From 47960a6d57e60561217e2fead36ad89ecd3b777c Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Mon, 16 Nov 2026 11:07:34 -0500 Subject: [PATCH] feat: host tls data service and route node and cluster connections --- docs/plans/evidence/grpc-data/README.md | 52 +- .../fixture-inventory-preparation.md | 139 ++ .../grpc-data/p07-contract-astra-review.md | 159 ++ .../grpc-data/p07-credential-astra-review.md | 146 ++ .../evidence/grpc-data/p07-preparation.md | 19 + .../grpc-data/p07-remote-astra-review.md | 133 ++ .../grpc-data/p07-wiring-preparation.md | 37 + scripts/validation/grpc-data/unit-phases.json | 68 +- .../DataConnections/DataProtoMapper.cs | 8 +- .../Protos/data_connection.proto | 10 +- .../Entities/DataConnectionScopeState.cs | 10 + ...35_AddDataConnectionScopeState.Designer.cs | 1979 +++++++++++++++++ ...61116135035_AddDataConnectionScopeState.cs | 41 + .../OtOpcUaConfigDbContextModelSnapshot.cs | 33 + .../OtOpcUaConfigDbContext.cs | 10 + .../Validation/DataConnectionScopeRevision.cs | 25 + .../Validation/DataConnectionValidator.cs | 2 +- .../Validation/DraftSnapshot.cs | 2 + .../Validation/DraftSnapshotFactory.cs | 1 + .../DataConnections/DataAddress.cs | 11 +- .../DataConnections/DataContracts.cs | 2 +- .../DataConnections/IDataConnection.cs | 6 + .../DataConnections/IDataServices.cs | 7 + .../AdminOperations/AdminOperationsActor.cs | 23 + .../AdminOperations/ConfigComposer.cs | 1 + .../DataConnectionAuthInterceptor.cs | 70 + .../DataConnectionBundleLoader.cs | 111 + .../DataConnectionCredentialResolver.cs | 47 + .../Configuration/DataConnectionEndpoints.cs | 111 + .../Configuration/DataConnectionOptions.cs | 28 + .../DataConnectionOptionsValidator.cs | 44 + .../DataConnectionRegistration.cs | 173 ++ .../DataConnectionSecretChangeHandler.cs | 27 + .../DataConnectionSecretProvisioner.cs | 218 ++ .../DataConnectionSecurityProvider.cs | 63 + .../DataConnectionServerCertificate.cs | 25 + .../DataConnectionTrustPolicy.cs | 175 ++ .../SecretChangeSignallingInvalidator.cs | 9 +- .../Configuration/SecretsRegistration.cs | 3 +- .../Grpc/DataConnectionGrpcBinding.cs | 91 + .../Grpc/DataConnectionGrpcService.cs | 287 +++ .../Grpc/DataConnectionUnaryLifetime.cs | 8 + .../Grpc/PreparedDataSubscription.cs | 40 + src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs | 23 +- .../ClusterEndpointSelector.cs | 20 + .../DataConnectionDeploymentRuntime.cs | 498 +++++ .../DataConnections/DataConnectionManager.cs | 138 ++ .../DataConnectionPublisherProps.cs | 28 + .../DataConnectionRoleAdapter.cs | 18 + .../DataConnectionWarmRoleView.cs | 66 + .../DataSubscriptionSession.cs | 2 + .../DataConnections/DataWriteDispatchGate.cs | 2 + .../DataConnections/DataWriteExecutor.cs | 2 +- .../DataConnections/GrpcDataConnection.cs | 774 +++++++ .../LocalCatalogCoordinator.cs | 8 +- .../DataConnections/LocalDataConnection.cs | 12 +- .../LocalDataRuntimeComposition.cs | 42 + .../DataConnections/LocalDataServices.cs | 51 +- .../DataConnections/WriteAdmissionTicket.cs | 2 +- .../DeploymentArtifact.DataConnections.cs | 13 + .../Drivers/DriverHostActor.cs | 45 +- .../OpcUa/OpcUaPublishActor.cs | 51 +- .../Redundancy/IRedundancyRoleView.cs | 62 +- .../ServiceCollectionExtensions.cs | 32 +- .../GrpcDataResponseServingTests.cs | 38 + .../GrpcDataConfigurationTests.cs | 10 + .../GrpcDataSchemaModelTests.cs | 33 +- .../GrpcDataScopeRevisionTests.cs | 36 + .../GrpcDataScopeArtifactTests.cs | 23 + .../GrpcDataScopeSealingTests.cs | 90 + .../GrpcDataBundleLifecycleTests.cs | 59 + .../GrpcDataCredentialRetirementTests.cs | 245 ++ .../GrpcDataIngressAuthTests.cs | 51 + .../DataConnections/GrpcDataListenerTests.cs | 157 ++ .../GrpcDataPublicationHandoffTests.cs | 147 ++ .../GrpcDataRuntimeRegistrationTests.cs | 184 ++ .../GrpcDataScopeActivationTests.cs | 26 + .../GrpcDataSecretProvisioningTests.cs | 205 ++ .../GrpcDataSecretRotationTests.cs | 29 + .../GrpcDataServiceDispatchTests.cs | 103 + .../GrpcDataTrustRotationTests.cs | 191 ++ .../GrpcDataCachedReadTests.cs | 23 + .../GrpcDataCatalogStagingTests.cs | 119 +- .../GrpcDataConnectionClientTests.cs | 824 +++++++ .../GrpcDataConsumerScopeTests.cs | 84 + .../GrpcDataDeploymentActivationTests.cs | 481 ++++ .../GrpcDataDriverOutcomeTests.cs | 13 +- .../GrpcDataEndpointSelectionTests.cs | 34 + .../GrpcDataLocalCompositionTests.cs | 42 + .../GrpcDataLocalConnectionTests.cs | 20 +- .../DataConnections/GrpcDataLocalRoleTests.cs | 53 + .../GrpcDataStreamOrderingTests.cs | 9 +- .../GrpcDataTransportPublicationTests.cs | 146 ++ .../DriverHostActorPrimaryRoleSourceTests.cs | 52 + .../OpcUa/OpcUaPublishActorWarmTests.cs | 95 + 95 files changed, 9878 insertions(+), 87 deletions(-) create mode 100644 docs/plans/evidence/grpc-data/fixture-inventory-preparation.md create mode 100644 docs/plans/evidence/grpc-data/p07-contract-astra-review.md create mode 100644 docs/plans/evidence/grpc-data/p07-credential-astra-review.md create mode 100644 docs/plans/evidence/grpc-data/p07-preparation.md create mode 100644 docs/plans/evidence/grpc-data/p07-remote-astra-review.md create mode 100644 docs/plans/evidence/grpc-data/p07-wiring-preparation.md create mode 100644 src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/DataConnectionScopeState.cs create mode 100644 src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261116135035_AddDataConnectionScopeState.Designer.cs create mode 100644 src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261116135035_AddDataConnectionScopeState.cs create mode 100644 src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionScopeRevision.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionAuthInterceptor.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionBundleLoader.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionCredentialResolver.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionEndpoints.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptionsValidator.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionSecretChangeHandler.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionSecretProvisioner.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionSecurityProvider.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionServerCertificate.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionTrustPolicy.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcBinding.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionUnaryLifetime.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/PreparedDataSubscription.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ClusterEndpointSelector.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionManager.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionPublisherProps.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionRoleAdapter.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionWarmRoleView.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs create mode 100644 tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataResponseServingTests.cs create mode 100644 tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataScopeRevisionTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/DataConnections/GrpcDataScopeArtifactTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/DataConnections/GrpcDataScopeSealingTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataBundleLifecycleTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataCredentialRetirementTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataIngressAuthTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataListenerTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataPublicationHandoffTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataRuntimeRegistrationTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataScopeActivationTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataSecretProvisioningTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataSecretRotationTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataServiceDispatchTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataTrustRotationTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConnectionClientTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConsumerScopeTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeploymentActivationTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataEndpointSelectionTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalCompositionTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalRoleTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataTransportPublicationTests.cs diff --git a/docs/plans/evidence/grpc-data/README.md b/docs/plans/evidence/grpc-data/README.md index 280a6116a..d7ae1ec7e 100644 --- a/docs/plans/evidence/grpc-data/README.md +++ b/docs/plans/evidence/grpc-data/README.md @@ -22,7 +22,7 @@ The [implementation plan](../../2026-11-15-grpc-data-connections-implementation- | 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 | Passed; Astra approved | Complete gate 910/910 passed `20261116T084759.594405Z-42a294fc7f4f` after three Astra regression corrections; source and candidate reconciliation approved | | P06 | Streams/sharing/fair delivery | Passed | 347/347 applicable tests; Astra approved frozen source and evidence | -| P07 | TLS/provisioning/node+cluster clients | Pending | | +| P07 | TLS/provisioning/node+cluster clients | Passed; Astra approved | 393/393 applicable tests, zero failures/skips; final frozen run `20261116T160335.804917Z-5a4994c32d15` | | P08 | Raw/UNS projection and adapter | Pending | | | P09 | Authoring/diagnostics/docs | Pending | | | P10 | Local Docker/CLI/probe integration | Pending | | @@ -166,3 +166,53 @@ The frozen facade is caller-bound through `IDataConnectionFactory` and `DataAuth ### P06 final gate and approval The frozen full P06 gate `20261116T121919.790393Z-0175b7fac86f` passed **347/347**, with zero failures or skips: Runtime 234, Abstractions 50, Commons 39, Modbus 24. Astra independently reconciled all four TRX files, HEAD, tracked diff and all 28 untracked production/test file hashes. [Final P06 review](p06-implementation-astra-review.md) approves the phase with no remaining actionable findings. This supersedes the earlier in-progress checkpoint notes; production network composition, Docker validation, benchmarks and final integrated review remain P07/P10/P11/P12 work. + +## P07 execution notes + +P06 was committed as `b710bf9f7` after approval. Credential missing-API RED is `20261116T123426.173714Z-b6d2bd79e693`; its predecessor `20261116T123338.015389Z-cb0d09ea2adb` caught a missing Xunit import. Remote client missing-API RED is `20261116T123443.452207Z-f447b54a2741`. Astra identified absent serving provenance in empty/error-only unary batches and Ack/Control frames. The additive negotiated response identity extension produced missing-field RED in `20261116T123631.004789Z-c4162d89dd31`, then passed the two new envelope cases and affected existing codec cases in `20261116T123708.013339Z-733e48c76e87`. This is a contract checkpoint, not the P07 phase gate or production network verification. + +### P07 component checkpoints and open work + +These are targeted component gates, not P07 approval. Dedicated listener policy passed three cases in `20261116T124514.748312Z-81f57a2816c5`. The first Runtime gate `20261116T124421.560971Z-3e0cb57452c4` ran 13 cases (ten passed, three actual role-policy REDs); those fixes plus affected local-read/P06 ordering/recovery passed **59/59** in `20261116T125221.449960Z-a59846699d1c`. Cluster/default Node require Primary, while explicit Node ReadyReplica permits only an actual ready Secondary. Caller authority epoch and target mode participate in final publication. + +Credential/trust behavioral RED `20261116T125329.808299Z-78cbe8de8f60` ran 23 cases (19 passed, four failed: overwritten active secret/version binding, durable deletion retry, SAN identity). Notification fan-out RED is `20261116T125519.025923Z-d690c1a866db` (four passed/one failed). Exact same-version notice replay RED is `20261116T130133.632281Z-29545a84cb26` (nine passed/two failed). Their repaired Host component plus listener/auth/binding tests passed **29/29** in `20261116T130336.930026Z-3b0156408b84`; this predates subsequent floor and lifecycle regressions. + +Additive serving envelopes are explicitly negotiated through `response_serving_identity`; all empty/error-only unary results and outer stream frames carry Serving. The registered contextual marshaller serializes into a bounded private buffer, then revalidates capture-bound publication before synchronous `Complete(byte[])`. Real service execution enforces NoCompress; this is transport-buffer acceptance, not socket flush or client receipt. Initial binder three-case gate passed `20261116T130009.001707Z-f4443cd19118`. Disposal during blocked final validation produced actual RED in `20261116T131308.089661Z-57464278e345` (31/32 passed), then post-guard state/cancellation checks were corrected. The same run passed scoped generation floors, >256 sequential-ID churn and stale high-version replay after restart. Trust removal/reintroduction subsequently produced actual RED in `20261116T132449.788119Z-5bbb43ed42fb` (13/14 passed); its fix passed the next checkpoint. Observation registration across scope removal produced actual RED in `20261116T133022.795892Z-850aefb609e5` (21/22 passed); repair awaits its next gate. + +Remote lifecycle tests first reproduced bounded-retirement, item-budget renewal and browse-lease mismatch in `20261116T130221.847789Z-21fac311a351` (11/15 passed). Corrected duplex harnesses reached real mutable-command, value-version and connection-disposal RED in `20261116T131620.409467Z-354683c116e5` (15/18 passed). Their subsequent component checkpoint `20261116T132916.652106Z-dca2192d7e9c` passed 22/25: two failures were the intentionally missing Runtime final-publication binding, while the proposed unary physical-work failure timed out before its intended assertion and was **not** evidence of a quota escape. Astra inspected pinned grpc-dotnet 2.76 and confirmed unary ResponseAsync retains admission through actual Send/body work; no blanket HTTP tracker was added. + +The latest Runtime checkpoint `20261116T134445.606174Z-21b953ccfa43` executed **42 cases: 36 passed/six actual REDs**. Passing cases include the public local composition, source invalidation at late stream serialization (snapshot value and SnapshotEnd), a valid handoff/receipt, ignored-cancellation physical write retention, and corrected ignored unary Send/body admission. Five remaining remote REDs are preheaders duplex disposal (with/without reader), stream setup admission before discovery, reconnect epoch reuse and no-primary backoff. The sixth reproduces source invalidation during unary publication authority validation; root changed the order to leave the fast source proof last, pending rerun. Preliminary compile blockers `20261116T134244.500978Z-eed6e685cbb4` and `20261116T130823.613210Z-d2b84c729d71` were nullable/assertion and test-cancellation errors, not behavioral proof. + +Safe credential history reclamation additionally requires a durable authoritative scope generation from central sealing. Missing API REDs are `20261116T134421.362584Z-5376bf1211c7` (Configuration) and `20261116T134423.343227Z-f43f8e65c786` (ControlPlane). The approved direction uses one bounded row locked before the validated draft read, unchanged-scope stable fingerprint/version, and one transaction through artifact save; empty/removal artifacts carry a positive version. Pure composition and drift probes do not mutate the revision. This implementation and its generated migration remain pending. Dedicated TLS listener binding, full production DI/role/actor wiring, deployed-scope application/bundle lifecycle, wire integration tests and complete phase approval also remain pending. No Docker or full solution tests have run. + +The first complete CURRENT P07 unit selector checkpoint `20261116T134802.525866Z-44c634f2fd5c` passed **192/192** with zero skips: Host 66, Runtime 82, Commons 41, Configuration 2, ControlPlane 1. It verifies the current remote receipt/setup/backoff/reconnect repairs, final source/publication guard, observed-ID/trust fixes and initial central pure revision/artifact cases. **This is not P07 completion:** Program/actor/DI wiring and deployed scope/bundle activation are not yet implemented; affected sealing regressions, generated migration checks and final phase Astra review are still required. The earlier Runtime behavioral RED `20261116T134445.606174Z-21b953ccfa43` executed 42 (36 passed/six expected new failures), including five remote lifecycle/backoff/epoch findings plus the root read-source recheck. Root nullable-assert compile blocker `20261116T134244.500978Z-eed6e685cbb4` was corrected before that behavioral run. The source guard fix and remote repairs are green in the 192-case checkpoint. + + +### P07 real composition and lifecycle follow-up + +Real Program/Kestrel/DI/actor wiring is now implemented in the working tree; it is not yet phase approved or committed. The old wiring-preparation document is a historical checklist. Actual observed-role owner regressions (missing local snapshot, stopped publisher and superseded publisher) were captured in `20261116T143717.808806Z-1f4e725b2aa4` and now pass. Independent Astra source review then found missing OPC UA publisher catalog injection, a Warm verdict bypass, role-generation ABA and outbound scope surviving failed local staging; these remain explicitly tracked until final reconciliation. + +`20261116T151314.060929Z-4848bb946446` passed Host 80/80 and Runtime 119/122, with three newly staged failures for credential rotation, identical artifact replay and bearer rendering. Those were repaired. Pending-command byte limits now follow the configured connection value across all of its streams; its missing-API RED was `20261116T151540.477969Z-f582458ed72d`. Secret invalidation composes the cache, Galaxy directory and data notification independently; public trust bundle APIs bound aggregate root count and DER bytes. Their API RED was `20261116T151548.692271Z-7ee23ed569f7` (an unrelated test import error was corrected before behavioral execution). + +`20261116T151707.477456Z-43f007c122a4` reproduced unary starvation when a long stream occupied the only common admission slot. Unary and stream admission now use separate finite lanes. A final monotonic unary budget check after publication validation supplements timer cancellation. Both pass in the later Host gate. + +The serving contract now includes additive `ServingGeneration`, with positive generation required by the negotiated remote response-identity contract. `20261116T152240.519810Z-7fe192135f72` executed Runtime 167 cases, 165 passing and two actual failures: a same-role ABA revived an old local publication permit, and a remote advertising generation zero was accepted. Coordinator generation comparison and remote negotiation were repaired. Actual Warm actor tests passed, covering accepted transitions, endpoint disagreement, blocked demotion callbacks, and stale owner fencing. + +`20261116T152849.971443Z-55329afdc892` passed Host **87/87**, including the real enabled deferred facade, durable scope barrier, composed invalidator, trust limits and local Warm-over-Hot artifact case. Runtime passed **207/210**: two new regressions proved that a Warm transition after policy capture still dispatched the device write; the internal write proof and final shared fence now retain full Serving identity. The third failure was a stream-ordering fixture attempting nonblocking ingress while its snapshot reader held the partition lock. That test now arranges successful ingress under the existing partition test seam, leaving contention/invalidation behavior covered separately; its affected gate is still pending. + +The production OPC UA publisher Props factory is shared with an actual DriverHost-to-publisher held-sink unit. Missing factory API was observed in `20261116T153139.282043Z-0a556b90b0c8`; a subsequent compile check identified the actual Akka resolver type rather than IServiceProvider, which is being corrected. New deployment-attempt barriers synchronously deny old routes before local parsing, and reject stale Apply completions. A transient local scope-store failure currently lacks a scheduled retry; a focused regression is staged before its correction. No Docker/SQL migration apply/live CLI or full-solution test gate has run. + + +`20261116T154135.539005Z-3185338d739f` passed Runtime 215/218 and Host 87/87. The two expected failures confirmed null/exception local-security resolution needed the same bounded retry timer; both were repaired. The third exposed an invalid actor-test fixture reference (`data/key` instead of required `secret:data/key`), not a production timing defect; parser preconditions now fail immediately. Correcting that fixture exposed the actual Host conversion bug: canonical references were being passed directly to SecretName, which rejects the colon. + +The separately continued component runs at `154508` / `154535` / `154631` / `154635` / `154639` passed Runtime 218, Commons 41, Configuration 9 and ControlPlane 21, while Host passed 88/91 with actual failures for canonical physical-store conversion, collateral invalidation, and uppercase physical aliases. Additional Host tests were staged during that sequential batch, so it is not treated as a frozen aggregate candidate. Direct pinned-library testing confirmed SecretName lowercases names. Host now strips only the exact `secret:` prefix when accessing physical rows, keeps canonical references in scope/history, rejects uppercase aliases, and records each successful connection observation's physical SecretName. Unrelated/Galaxy changes preserve data connections; shared-reference users retire together. Central lowercase-alias rejection was actual RED in `20261116T154756.981334Z-ba1d43a247b0` (five passed/two failed), followed by matching validator repair. + +The fresh frozen full P07 candidate `20261116T154916.700793Z-ba7f397be1ea` passed **391/391**, zero failures/skips: Host 91, Runtime 218, Commons 41, Configuration 20, ControlPlane 21. This is not final approval: Astra then identified a retained canceled B entry after A's security change raced a transient role read. `20261116T155211.129165Z-316e31f82ca8` reproduced it (22/23 deployment-activation cases passed). The agreed correction makes manager scope represent configured consumer authorization/lifetime, while worker creation, TryAcquire and every lease boundary enforce current role; actual role notifications still retire all entries/epochs and newer artifact attempts still empty manager scope immediately. The owning worker is implementing that final focused repair before a fresh full phase gate and Astra reconciliation. + +### P07 final phase gate and Astra approval + +After that final repair, frozen run `20261116T155343.945235Z-be0fbabc1a44` passed **392/392**, zero failures/skips: Host 91, Runtime 219, Commons 41, Configuration 20, ControlPlane 21. Astra independently reconciled all five TRXs, HEAD `b710bf9f74f04ede38b902fcffc7259e2e808aa1`, tracked diff SHA-256 `f2fad373d196e951f6f39ec799e36845ddb9dcbe48931958a0e17eab627362f4`, and all 50 recorded new production/test file hashes before review-document edits. [Final contract/composition review](p07-contract-astra-review.md), [credential/scope review](p07-credential-astra-review.md), and [remote/runtime review](p07-remote-astra-review.md) approve P07 with no remaining actionable findings at this phase boundary. Earlier in-progress statements above are historical. + +The accepted ordering variance moves creation of Task 15's `GrpcDataTlsWireTests` and `GrpcDataListenerIsolationWireTests` to P10 with their actual TLS fixtures; both remain required integration classes/scenarios alongside the existing mesh auth/boundary selectors. No wire-test requirement is waived. P10 still requires actual TLS/listener isolation, Docker/CLI/probes, deployed credential rotation/restart/failover, and SQL migration/concurrency/rollback evidence. P11 measurements and the P12 full-solution/final Astra gate remain pending. P07 approval permits its commit and dependent P08 work, without claiming those later results. + +Before commit, P08 preparation found that a Browse lease/continuation could outlive the original authenticated target credential. The commit was held. Actual RED `20261116T160304.904551Z-9a7e5ce79d56` passed 5/6 local-connection cases; the repair caps both durations by positive remaining original credential lifetime and denies expiry during completion. GetMetadata objects have no separate lease, so P08 must retain the Browse/request-start authority boundary. The superseding frozen full run `20261116T160335.804917Z-5a4994c32d15` passed **393/393**, zero failures/skips (H91/R220/C41/K20/P21). Astra independently reconciled all five TRXs, unchanged HEAD, tracked diff SHA-256 `55029f7b6c6323a87dd3d8b96a988928d1eaee5e3889e1f57c4b07e4bd5771ae`, and all 50 new source/test hashes before review-document edits, then reaffirmed P07 approval. This is the final approved P07 candidate; the later-phase obligations above remain unchanged. diff --git a/docs/plans/evidence/grpc-data/fixture-inventory-preparation.md b/docs/plans/evidence/grpc-data/fixture-inventory-preparation.md new file mode 100644 index 000000000..01cc818d9 --- /dev/null +++ b/docs/plans/evidence/grpc-data/fixture-inventory-preparation.md @@ -0,0 +1,139 @@ +# Draft fixture inventory preparation — final refresh required + +Prepared 2026-11-16 by independent Sol reviewer. **DRAFT: refresh against the final P12 HEAD and actual discovery/TRX.** This is source inspection only, not integration execution, fixture availability evidence, a final environment map, or an assertion that all tests pass. New GrpcData classes and their requirements are changing during P06–P10. + +Scope: reviewed the seven files committed in `136c8a38e` under `scripts/validation/grpc-data/` and scanned every repository `.csproj` for `IsTestProject`/`Microsoft.NET.Test.Sdk`, then test source for category traits, fixture constructors, environment access, conditional skips, platform checks, and shared endpoints. Found **64 test projects**, all under `tests/`; `SparkplugSimulator` is an executable fixture helper, not a test project. No build, test discovery/execution, Docker, SQL, network, or hardware command was run by this reviewer. The coordinator reported 10 pure fixture tests green; no actual Docker/SQL gate was reported. + +## Independent P10 scaffold review + +**Required P10 fix — Modbus refusal responses (P2).** `device/server.py:138-141` closes the socket on every `ValueError` from its protocol handler instead of sending a Modbus exception PDU. The sparse readable map at lines 28–29 has holes 1–9 and 13–19. Production `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Contracts/ModbusDriverOptions.cs:129-132` defaults `MaxReadGap=8`; tags at 10–12 and 20 can therefore form a read block across unmapped 13–19. Production `ModbusDriver.cs:1264-1315` distinguishes device refusal (permits prohibition/bisection and individual-read fallback) from transport failure. This fixture turns the former into the latter. Unsupported FC23 also closes instead of returning exception01; when FC23 is opted in, `ModbusDriver.cs:1813-1856` cannot take same-request FC16 fallback. This does not prove current unimplemented seed rows would trigger it, but it is a real protocol/setup gap to close before selecting those rows. Add wire framing/error tests first, then return exception01/02/03 as appropriate (or intentionally provide a dense readable map); preserve deliberate close-after-commit solely for the response-loss fault. Current pure tests exercise functions and expect `ValueError`, so cannot establish socket behavior. + +**Additional fixture evidence gap.** The read ledger increments only after a valid mapped read (`server.py:48-56`); write effects count only successful bounded mutations (`58-70`). There is no total request/rejected-write ledger. This suffices to count committed effects for the existing response-loss action, but it cannot independently prove every device-call-count assertion or distinguish a rejected write reaching the fixture from no request reaching it. Match the later D-scenario claims to the evidence actually captured, or extend the fixture ledger before claiming those cases. + +No independent LDAP/build-platform defect found: disabled LDAP exits `LdapOptionsValidator.cs:35`; the Dockerfile intentionally matches `docker-dev/Dockerfile`'s amd64 build/portable publish/native runtime pattern. SQL/Compose parsing, actual migration, host startup, and daemon/resource ownership remain unverified. Known P07 TLS/provisioning and P10 seeding/orchestration work is explicitly pending in README and is not reported as an additional surprise defect. This scaffold is **not integration ready**. + +## Assembly map + +Assembly names below omit only the common `ZB.MOM.WW.OtOpcUa.` prefix. Each corresponds to `tests/**//.csproj`. Categories are literal category traits observed in that assembly's own source; they do not mean every test has that category. Linked conformance and helper files must be included when P12 computes actual discovered names. `unclassified` is intentional and must not become an exclusion. `L` means no external software service prerequisite identified by this scan; many such tests create local actors, sockets, SDK servers, SQLite/temp files, fake servers, or subprocesses and still need normal filesystem/process resources. It does not certify execution or platform parity. + +| Assembly suffix | Observed categories | Fixture/gate groups | +|---|---|---| +| `Client.CLI.Tests` | unclassified | L | +| `Client.Shared.Tests` | Unit | L | +| `Client.UI.Tests` | unclassified | L | +| `Cluster.Tests` | unclassified | L | +| `Commons.Tests` | Unit | L | +| `Configuration.Tests` | Authorization, SchemaCompliance, Unit | SQL-CFG | +| `Core.Abstractions.Tests` | Unit | L | +| `Core.AlarmHistorian.Tests` | Unit | L | +| `Core.ScriptedAlarms.Tests` | Unit | L | +| `Core.Scripting.Tests` | Unit | L + child-process recursion gate | +| `Core.Tests` | Integration, Unit | L | +| `Core.VirtualTags.Tests` | Unit | L | +| `Driver.AbCip.Cli.Tests` | Unit | L | +| `Driver.AbLegacy.Cli.Tests` | Unit | L | +| `Driver.Cli.Common.Tests` | Unit | L | +| `Driver.FOCAS.Cli.Tests` | Unit | L | +| `Driver.Modbus.Cli.Tests` | Unit | L | +| `Driver.S7.Cli.Tests` | Unit | L | +| `Driver.TwinCAT.Cli.Tests` | Unit | L | +| `Driver.Ab.Transport.Tests` | unclassified | L | +| `Driver.AbCip.IntegrationTests` | Integration, LiveIntegration, Unit | AB-CIP | +| `Driver.AbCip.Tests` | Unit | L | +| `Driver.AbLegacy.IntegrationTests` | Integration | AB-LEGACY | +| `Driver.AbLegacy.Tests` | Unit | L | +| `Driver.Calculation.Tests` | Unit | L | +| `Driver.FOCAS.IntegrationTests` | unclassified | FOCAS | +| `Driver.FOCAS.Tests` | Unit | L | +| `Driver.Galaxy.Browser.Tests` | Unit | L | +| `Driver.Galaxy.Tests` | Integration, Unit | L + MXGW | +| `Driver.Heidenhain.Tests` | LiveIntegration, Unit | L + HEIDENHAIN | +| `Driver.Historian.Gateway.Tests` | LiveIntegration | L + HISTGW | +| `Driver.Historian.QuestDb.IntegrationTests` | SlowUnit | QUESTDB + LONG | +| `Driver.Historian.QuestDb.Tests` | unclassified | L | +| `Driver.Historian.Sql.Common.Tests` | unclassified | L | +| `Driver.Historian.SqlServer.IntegrationTests` | unclassified | SQL-HIST | +| `Driver.Historian.SqlServer.Tests` | unclassified | L | +| `Driver.MTConnect.IntegrationTests` | Integration | MTCONNECT | +| `Driver.MTConnect.Tests` | Unit | L | +| `Driver.Modbus.Addressing.Tests` | Unit | L | +| `Driver.Modbus.IntegrationTests` | Integration | MODBUS | +| `Driver.Modbus.Tests` | Unit | L | +| `Driver.Mqtt.IntegrationTests` | Integration, LiveIntegration | MQTT | +| `Driver.Mqtt.Tests` | SlowUnit, Unit | L | +| `Driver.OpcUaClient.Browser.IntegrationTests` | Integration | OPC + NAT | +| `Driver.OpcUaClient.Browser.Tests` | Unit | L | +| `Driver.OpcUaClient.IntegrationTests` | Integration | OPC | +| `Driver.OpcUaClient.Tests` | Unit | L | +| `Driver.S7.IntegrationTests` | Integration, Reconnect | S7 | +| `Driver.S7.Tests` | Unit | L | +| `Driver.Sql.Browser.Tests` | unclassified | L | +| `Driver.Sql.IntegrationTests` | Blackhole, Integration | SQL-POLL + PG + MYSQL + ORACLE + ODBC + BLACKHOLE | +| `Driver.Sql.Tests` | Unit | L | +| `Driver.TwinCAT.IntegrationTests` | Integration | TWINCAT | +| `Driver.TwinCAT.Tests` | Unit | L | +| `AdminUI.Tests` | Unit | SQL-CFG + discovery gate | +| `ControlPlane.Tests` | SchemaCompliance, Unit | SQL-CFG | +| `Host.IntegrationTests` | ArtifactBoundary, Failover, Integration, Unit | HOST + PROBES + MODBUS | +| `Host.Tests` | Unit | L | +| `OpcUaServer.IntegrationTests` | E2E, Integration, Perf | SDK + AVEVA + LONG | +| `OpcUaServer.Tests` | Benchmark, Unit | L + BENCH | +| `Runtime.Tests` | Unit | L | +| `ScriptWorker.Tests` | Perf, ScriptWorker | WORKER + LONG + WINDOWS | +| `Security.Tests` | unclassified | L | +| `Analyzers.Tests` | Unit | L | + +## Fixture/environment groups and source evidence + +Paths under `tests/Drivers/` below abbreviate the corresponding full assembly directory from the table; paths under `tests/Server/` and `tests/Core/` do likewise. All endpoint values must be generated from run-owned loopback resources. Do not reuse tracked examples, inherited credentials/endpoints, or defaults pointing to `10.100.0.35`, `10.100.0.48`, corporate/VPN hosts, or other shared hardware. + +| Group | Exact environment/settings and fixture behavior | Source evidence / preparation needed | +|---|---|---| +| SQL-CFG | `OTOPCUA_CONFIG_TEST_SERVER`, `OTOPCUA_CONFIG_TEST_SA_PASSWORD`; remove `OTOPCUA_UNIT_ONLY_DISCOVERY` from **discovery and execution** final children | `Configuration.Tests/SchemaComplianceFixture.cs:20-54` always migrates real SQL and reaps prefix databases; `ControlPlane.Tests/Harness/SqlServerTestDatabase.cs:17-34` also always migrates and defaults shared SQL; `AdminUI.Tests/AdminUiSqlServerFixture.cs:146-225` probes/skips/reaps and has unit-only bypass. Disposable SQL must be configured before discovery, including AdminUI attributes. | +| SQL-HIST | `HISTORIAN_SQL_TEST_CONNECTION` | `Historian.SqlServer.IntegrationTests/SqlHistorianFixture.cs`; local SQL with permission for generated databases; absent connection skips. Includes linked `tests/Drivers/Historian.Conformance/**/*.cs`. | +| QUESTDB | `HISTORIAN_QUESTDB_TEST_CONNECTION`; `HISTORIAN_QUESTDB_STRESS_SECONDS` opt-in | `Historian.QuestDb.IntegrationTests/QuestDbFixture.cs`, `LiveWriteReadRaceStressTests.cs:28-40`; QuestDB 10.0.1 PG-wire + HTTP fixture, isolated table prefixes; connection absence skips. Linked shared conformance tests must be counted. | +| SQL-POLL | `SQL_TEST_ENDPOINT`, `SQL_TEST_USER`, `SQL_TEST_PASSWORD`; alternative `Sql__ConnectionStrings__Fixture` | `Sql.IntegrationTests/SqlPollServerFixture.cs:45-60,218-254,315-334`; generated SQL driver schema and tables inside fixed `SqlPollFixture` database. Child env must reject a stale alternate connection string overriding the owned endpoint. | +| PG | `SQL_PG_ENDPOINT`, `SQL_PG_USER`, `SQL_PG_PASSWORD` | `Sql.IntegrationTests/PostgresReadTests.cs`; seed `Docker/postgres/seed-pg.sql`; postgres:17-alpine. | +| MYSQL | `SQL_MYSQL_ENDPOINT`, `SQL_MYSQL_USER`, `SQL_MYSQL_PASSWORD` | `Sql.IntegrationTests/MySqlReadTests.cs:433-439`; image mysql:8.4 + `Docker/mysql/seed-mysql.sql`. Not started by existing CI helper. | +| ORACLE | `SQL_ORACLE_ENDPOINT`, `SQL_ORACLE_USER`, `SQL_ORACLE_PASSWORD`, `SQL_ORACLE_SERVICE` | `Sql.IntegrationTests/OracleReadTests.cs:348-366`; gvenzl/oracle-free:23-slim + `Docker/oracle/seed-oracle.sql`, default service FREEPDB1. Local image/platform availability unknown, not inferred unavailable. | +| ODBC | `SQL_ODBC_CONNECTION_STRING` | `Sql.IntegrationTests/OdbcReadTests.cs:25-28,150-158`; requires local driver manager and installed vendor ODBC driver plus seeded backend. Software prerequisite, not hardware by default. Availability unknown. | +| BLACKHOLE | `SQL_BLACKHOLE_ENDPOINT`, `SQL_BLACKHOLE_USER`, `SQL_BLACKHOLE_PASSWORD`; clear `SQL_BLACKHOLE_DOCKER_SSH` | `Sql.IntegrationTests/SqlBlackholeTimeoutTests.cs:61-88,140-195,395-404`; requires separate disposable SQL because test pauses/unpauses it. **Current fixed name `otopcua-sql-blackhole` is not ownership-safe and ignores generated endpoint's resource ID. Must adapt before enabling.** Existing port14330 guard alone does not prove ownership. | +| OPC | `OPCUA_SIM_ENDPOINT` | `OpcUaClient.IntegrationTests/OpcPlcFixture.cs`, `OpcUaClient.Browser.IntegrationTests/OpcPlcProbe.cs`; opc-plc:2.14.10, anonymous/test options, local advertised port must match host port for ordinary fixture. Defaults shared host if unset. | +| NAT | `OPCUA_NAT_ENDPOINT`, `OPCUA_NAT_SERVER_CERT` | `OpcUaClient.Browser.IntegrationTests/NatPublishedEndpointBrowseTests.cs:48,132`; separate opc-plc:2.14.10 with unreachable advertised `.invalid` hostname/port and fresh copied public certificate. Missing cert silently leaves secure positive cases unexercised. Use per-run certificate/output directory. | +| MODBUS | `MODBUS_SIM_ENDPOINT`, `MODBUS_RTU_SIM_ENDPOINT`, `MODBUS_SIM_PROFILE` | `Modbus.IntegrationTests/{ModbusSimulatorFixture,ModbusRtuOverTcpFixture}.cs`, profile-gated `DL205/`, `Mitsubishi/`, `S7/`, `ExceptionInjectionTests.cs`; local pymodbus:3.13.0 profiles standard/dl205/mitsubishi/s7_1500/rtu_over_tcp/exception_injection. Needs separate profile runs; one standard simulator does not cover all profile-gated cases. P10's small custom simulator does not substitute for these existing fixtures. | +| S7 | `S7_SIM_ENDPOINT`, `S7_SIM_ALLOW_WRITES=1` only for local simulator; `S7_RECONNECT_BOUNCE_CMD`, `S7_TIMEOUT_OUTAGE_START_CMD`, `S7_TIMEOUT_OUTAGE_STOP_CMD`; `S7_TIMER_NUMBER_ADDRESSING` real-CPU gate | `S7.IntegrationTests/Snap7ServerFixture.cs` defaults shared; local python-snap7:1.0 s7_1500 image/profile. Command gates require generated commands targeting only owned container IDs, never inherited SSH commands. Timer/counter real-CPU assertions explicitly differ from simulator; record separately. | +| AB-CIP | `AB_SERVER_ENDPOINT`, `AB_SERVER_COMPOSE_PROFILE`, `AB_SERVER_PROFILE=abserver`, `AB_SERVER_ALLOW_WRITES=1` against local simulator only | `AbCip.IntegrationTests/{AbServerFixture,AbServerProfile,AbServerProfileGate,IntegrationWriteGate}.cs`, `TransportMatrix.cs`; patched libplctag ab_server controllogix/compactlogix/micro800/guardlogix profiles. Compose profiles share a fixed host port; run-owned remapping/sequential profile execution required. Emulate profile requires separate proprietary fixture and must be recorded unavailable unless supplied locally. | +| AB-LEGACY | `AB_LEGACY_ENDPOINT`, `AB_LEGACY_CIP_PATH`, `AB_LEGACY_COMPOSE_PROFILE`, `AB_SERVER_ALLOW_WRITES=1` only against local simulator | `AbLegacy.IntegrationTests/AbLegacyServerFixture.cs:39-159`, `TransportMatrix.cs`, `IntegrationWriteGate.cs`; ab_server slc500/micrologix/plc5 profiles. Explicit endpoint plus profile pin required; otherwise discovery attributes probe shared host/family ports. | +| AB excluded live evidence | Clear `AB_DIFF_ENDPOINT` plus related `AB_DIFF_PATH/FAMILY/TAGS/COUNT_OPENS/MAX_TAGS/MAX_TEMPLATES/PACE_MS`, `AB_LAT_TAGS/PASSES/PASS_GAP_MS`, `AB_LAT_ENFORCE`; do not enable `AB_HW_WRITE_APPROVED`, `AB_HW_WRITE_GATEWAY`, `AB_HW_WRITE_STRING_TAG`, `AB_HW_WRITE_DRYRUN`, `AB_HW_WRITE_GAP_SECONDS`, `AB_EVID_IDLE`, `AB_EVID_BROWSE`, `AB_EVID_MIX`/related tag controls against shared targets. `AB_LEASE_SOAK_CYCLES` tunes local soak. | `AbCip.IntegrationTests/Differential/`, `HardwareGate/`, `NativeLeaseReleaseSoakTests.cs`; exact unavailable/skipped names and reasons belong in final TRX inventory. Profile mismatch and differential/hardware opt-in skips are distinct from absent basic software fixtures. | +| FOCAS | `OTOPCUA_FOCAS_SIM_ENDPOINT`, `OTOPCUA_FOCAS_SIM_PROFILE` | `FOCAS.IntegrationTests/FocasSimFixture.cs:25-57`; existing Python focas-mock image built from `Docker/focas-mock`, seeded/reset via mock admin API and series profiles. Managed wire tests do not automatically require proprietary native FOCAS DLLs. Defaults shared host if unset. | +| MTCONNECT | `MTCONNECT_AGENT_ENDPOINT`, `MTCONNECT_WRITE_TARGET` | `MTConnect.IntegrationTests/MTConnectAgentFixture.cs:44-93`, `MTConnectAgentIntegrationTests.cs`; mtconnect/agent:2.7.0.12 **and adapter** with seeded device model and changing source; model-shape-dependent skips must be audited. Write target must be isolated supported writable item. | +| MQTT | `MQTT_FIXTURE_ENDPOINT`, `MQTT_FIXTURE_PLAIN_ENDPOINT`, `MQTT_FIXTURE_USERNAME`, `MQTT_FIXTURE_PASSWORD`, `MQTT_FIXTURE_CA_CERT`, `MQTT_FIXTURE_TOPIC_PREFIX` | `Mqtt.IntegrationTests/MqttFixture.cs:51-125`; Mosquitto2.0.22 TLS+plain listeners, generated credentials/CA and retained JSON publisher. Sparkplug live tests drive `SparkplugEdgeNode` in process; the standalone Sparkplug executable is for manual/live UI fixture use, not a required background service for those tests (`SparkplugSimulator/Program.cs:5-11`). If launched for other gates its controls are `MQTT_SIM_HOST/PORT/USE_TLS/GROUP/NODES/INTERVAL_SECONDS/CA_CERT/ALLOW_UNTRUSTED` and `MQTT_FIXTURE_USERNAME/PASSWORD`; do not confuse them with fixture client names. Include structured-metric and primary-host cases; broker alone is insufficient for retained JSON cases. | +| HOST | `OTOPCUA_HARNESS_USE_SQL`, `OTOPCUA_HARNESS_SQL_HOST`, `OTOPCUA_HARNESS_USE_LDAP`, `OTOPCUA_HARNESS_LDAP_HOST` | `Host.IntegrationTests/TwoNodeClusterHarness.cs:207-210,376-390,558-564`; default mode uses EF InMemory+stub LDAP; opt-in SQL hardcodes password `OtOpcUa!Harness123`, opt-in LDAP uses fixed port3894 and known fixture service identity. Generated SQL must match or harness must gain explicit credential input. Host real-mode fixture needs isolated GLAuth config from its compose. Decide whether/how real mode is exercised explicitly; default passing cases prove stub mode. | +| PROBES | **No endpoint env seam exists yet** | `Host.IntegrationTests/DriverProbeHandshakeE2eTests.cs:31-41` hardcodes shared DockerHost10.100.0.35, GalaxyHost10.100.0.48, local ports4840/14330; reachability probes occur before skip. Required P12 preparation: supply local owned endpoints for each protocol plus correct cross-protocol negative targets. Setting plan-table env variables cannot prevent forbidden network access here. `DriverTestConnectE2eTests.cs` does honor MODBUS_SIM_ENDPOINT but assumes wrong port9999 is unused. | +| SDK | Local `ServerEventRig`/SDK wire servers, transient PKI and ports; no external endpoint normally required | `OpcUaServer.IntegrationTests` SDK fixtures; additional GrpcData classes must be refreshed after P10. | +| TWINCAT | `TWINCAT_TARGET_HOST`, `TWINCAT_TARGET_NETID`, `TWINCAT_TARGET_PORT` | `TwinCAT.IntegrationTests/TwinCATXarFixture.cs:54-109`; Windows XAR runtime, valid trial/license, bilateral AMS routes, fixture PLC program and native ADS prerequisites. Not a Docker replacement. Unset NetId prevents probe; record exact skipped test names rather than enabling an arbitrary inherited target. | +| HEIDENHAIN | `HEIDENHAIN_LSV2_HOST`, `HEIDENHAIN_LSV2_PORT`, `OTOPCUA_HEIDENHAIN_INSPECT_PASSWORD` | `Heidenhain.Tests/HeidenhainLiveIntegrationTests.cs:20-31,64,96,166`; real-controller gate; in-process LSV2 simulator tests already exist separately and are not evidence of real-controller execution. | +| HISTGW | `HISTGW_GATEWAY_ENDPOINT`, `HISTGW_GATEWAY_APIKEY`, `HISTGW_TEST_TAG`, `HISTGW_WRITE_SANDBOX_TAG`, `HISTGW_BOOL_SANDBOX_TAG`, `HISTGW_ALARM_SOURCE`, `HISTGW_GATEWAY_ALLOW_UNTRUSTED` | `Historian.Gateway.Tests/Live/GatewayLiveFixture.cs:49-95`; local HistorianGateway with writable/history/event backend, correctly scoped key and dedicated sandbox tags. No local gateway hosting fixture found in this repo; available service/build/license not checked. Do not infer all gateway cases inherently require hardware, or route to documented VPN example. | +| MXGW | `MXGW_ENDPOINT`, `GALAXY_MXGW_API_KEY`, `MXGW_WRITE_WAIT_DISABLED`; alarm ack `GALAXY_904_ACK_USER`, `GALAXY_904_ACK_PASSWORD`, `GALAXY_904_ALARM_REF`; `D1_SMOKE_OUT` evidence output | `Galaxy.Tests/Runtime/GatewayGalaxy*LiveTests.cs`, `GalaxyPickerAckBeforeSnapshotLiveTests.cs`; actual Galaxy/MxAccessGateway backend with writable metering/alarm scenario. No matching local production backend fixture found; licensing/backend availability unknown. New gRPC rig is not a substitute for these product-specific cases. | +| AVEVA | `HISTGW_GATEWAY_ENDPOINT/APIKEY/ALLOW_UNTRUSTED`, `HISTGW_WRITE_SANDBOX_TAG`, `OTOPCUA_AVEVA_GATE_900`, `OTOPCUA_AVEVA_GATE_TAGS/WINDOWS/EVENT_SOURCES/EVENT_WINDOW/GALAXY_REFS/LABEL/OUT`, `OTOPCUA_AVEVA_GATE_STRICT_ENDPOINT/STRICT_CONTAINER/STRICT_SET_CEILING` | `OpcUaServer.IntegrationTests/AvevaGateway*LiveGateTests.cs`; real AVEVA history/alarm capabilities, data windows, optional strict gateway configuration. Strict-container control must not mutate inherited/shared containers. Availability unknown; absent required proprietary backend is explicit unavailable coverage. | +| WORKER | `OTOPCUA_SCRIPTWORKER_TEST_PATH` | `ScriptWorker.Tests/TestSupport.cs:42-46`, `WorkerEntryTests.cs:96`; some apphost gates require published self-contained worker path. Default build output does not prove this leg ran. Core scripting recursion child controls `OTOPCUA_RECURSION_CHILD_SCENARIO/RESULT` are parent-managed; normal parent run deliberately skips child-only test. | +| WINDOWS | `OTOPCUA_ISOLATION_INSTALLER_E2E=1` only in dedicated elevated Windows installer gate | `ScriptWorker.Tests/WorkerIsolationTests.cs:65-100`, `InstallerLayoutIsolationTests.cs:30-40`; Windows ACL/restricted-token/launch and installer service/firewall tests unavailable on macOS. Do not enable installer gate as part of local macOS final run. Some other tests return early by platform; a passing test can contain unexecuted platform branches. | +| LONG | `OTOPCUA_SDK2_SOAK`, `OTOPCUA_SDK2_SOAK_MODE/SECONDS/OUTPUT`, `OTOPCUA_SOAK_BUILD_SHA`, `OTOPCUA_SDK2_CLOSE_CONTROL`, `OTOPCUA_SDK2_SATURATION_CONTROL/OBSERVER/RUN_ID`, `OPCUA_CERTIFICATE_LEAK_TRACKING`; `OTOPCUA_EVENT_PERF`, `OTOPCUA_EVENT_PERF_OUT/REPORTS/ROUNDS`; `OTOPCUA_SCRIPT_PERF`, `OTOPCUA_SCRIPT_PERF_SECONDS/OUT`; QuestDB stress above | Explicit final-tier decision required for each. `Sdk2LifecycleSoakTests.cs:41-60` full/late-slope defaults2h and diagnostic is60–120s; `Sdk2LifecycleLateSlopeTests.cs:36-40` qualifies LinuxARM64/WindowsX64, exact .NET10.0.14 and leak tracking, so macOS diagnostic is not late-slope qualification. Folder/Script perf opt-ins skip by default. Record disabled cases as not executed, never silently call a no-filter run complete. | +| BENCH and knobs | `OTOPCUA_BENCH`; `OTOPCUA_PAGING_FUZZ_ITERATIONS`; **do not** set `OTOPCUA_SPARKPLUG_GOLDEN_REGEN` | OpcUaServer NodeManagerLockTimeBenchmark default executes assertions but enforces wall-clock budgets only with BENCH; paging knob controls fuzz iteration count. Golden regen mutates checked-in vectors, not a fixture requirement. | + +## Required owned local software fixture set + +1. SQL Server for configuration/AdminUI/control-plane/historian/poll tests, plus separate pausable SQL for blackhole; PostgreSQL17 seeded, QuestDB10.0.1, MySQL8.4 seeded, Oracle Free23 seeded, ODBC manager/vendor driver and suitable seeded backend. Isolate database/table prefixes. Optional Host real-SQL requires its hardcoded credential to be accommodated explicitly. +2. opc-plc2.14.10 ordinary fixture and separate NAT fixture with copied fresh public cert. Remap ordinary advertised/listen/published ports consistently. Isolated local Host gRPC rig supplies new-feature wire/CLI/node-probe cases only after seeding/TLS/provisioning/deploy/readiness work is complete. +3. Existing full Modbus simulator profiles and RTU-over-TCP, python-snap7 s7_1500 with owned lifecycle commands, patched AB CIP profiles, AB Legacy profiles, Python FOCAS mock, MTConnect Agent+adapter, Mosquitto TLS/plain+retained JSON publisher and generated CA/credentials; Sparkplug live tests start controlled simulator nodes in process. +4. Optional real-Host GLAuth fixture with its seeded service identity and fixed3894 constraint. A self-contained ScriptWorker apphost is a software build prerequisite for one gate. +5. Product backends for historian/Galaxy/AVEVA gates need separate availability determination; do not label absent endpoint variables a permanent software limitation without checking an allowed local option. TwinCAT XAR licensing/native runtime and real Heidenhain/controller-specific cases remain separate unavailable device/platform coverage where absent. + +No availability check was performed for images, Docker daemon/context, local ports, credentials, local gateway sources, ODBC drivers, self-contained worker output, native libraries, licensing, or device fixtures. Source presence is not running-fixture evidence. + +## Final-run orchestration work still required + +- `scripts/ci/integration-fixtures.sh:103` uses name-only `docker rm -f`; `up` calls it globally, failed starts remove by name again, published ports lack loopback binding, certificate output path is global, local suffix can be empty, and printed exports include passwords. **Do not invoke current helper for P12 local gate.** Implement explicit local-owned mode with local socket/context validation, mandatory unique owner/suffix, manifest/label validation, collision-safe loopback ports, restricted JSON child environment, per-run paths and owned cleanup; preserve CI mode separately. +- Existing helper provisions only SQL/PostgreSQL/QuestDB/opc-plc/NAT and emits exports without altering its parent environment. It does not provide config-test variables or the other required software fixtures. `run-final.py` must parse structured allowlisted output, explicitly inject real variables before discovery, remove unit-only discovery mode and replace unit-phase environment stripping. Do not `eval` logs or inherit unrelated endpoints/SSH commands. Discovery-time AdminUI/AB/TwinCAT attributes matter. +- Fix hardcoded Host probes and blackhole ownership seams before a no-category-filter run. They cannot be solved by an environment table alone. Audit all resolved targets fail-closed before processes start; no call to a forbidden shared host is permitted, including a reachability probe that would then skip. +- Refresh the 64-project/source map after new classes land; reconcile actual discovered project/test names with solution membership, source-linked test files and every GrpcData class. Capture nonzero discovered/executed expected classes, full per-assembly counts, every skipped name/reason, disabled long modes, platform early returns and required fixture readiness. No executed counts are asserted here. The plan's12,000 floor is a guard, not coverage proof. diff --git a/docs/plans/evidence/grpc-data/p07-contract-astra-review.md b/docs/plans/evidence/grpc-data/p07-contract-astra-review.md new file mode 100644 index 000000000..34e3f9ebb --- /dev/null +++ b/docs/plans/evidence/grpc-data/p07-contract-astra-review.md @@ -0,0 +1,159 @@ +# P07 serving-envelope and composition Astra review + +**Final disposition: P07 approved at its implementation/unit-gate boundary.** The final reconciliation below, including the subsequent credential-expiry lease repair, supersedes the historical checkpoint dispositions. Frozen run `20261116T160335.804917Z-5a4994c32d15` passed 393/393 applicable tests, with no failures or skips; source identity and all five TRXs were independently reconciled. This is not whole-implementation, real TLS/CLI/Docker, relational migration, or P12 approval. + +**Initial checkpoint disposition (historical): additive serving envelopes were approved as the contract direction, subject to the constraints below.** This preparation review inspected the committed P06 protocol, mapper, local authority/publication seams, configuration consistency policy, and Tasks 15/16 while implementation was active. No builds, tests, Docker commands, or commits were run by this reviewer. + +## Observed gap + +`CapabilitiesResponse` has cluster identity and Serving; Sample and CompactValues also have Serving. BrowseResponse, MetadataResponse, ReadResponse, WriteResponse, and the outer SubscriptionFrame do not. Consequently, an empty/error-only read, metadata batch, write outcome, acknowledgment, or heartbeat cannot independently prove the serving identity negotiated for its operation/stream. Existing value decoders compare nested provenance with expectedServing, but DecodeControlOrAck and the collection response helpers have no equivalent identity argument/check (`DataProtoMapper.cs:599-650`, `:1110-1165`, `:1209-1285`). + +Add an outer Serving field to all five missing response/frame messages, including every Ack/Control and both value encodings. At the reviewed baseline the available field numbers are BrowseResponse 7, MetadataResponse 2, ReadResponse 2, WriteResponse 2, and SubscriptionFrame 8. Preserve all existing numbers/oneofs and update the frozen contract tests. CapabilitiesResponse already has Serving at field 3 and needs no duplicate envelope. + +## Required contract constraints + +1. **Explicit negotiation.** Add a distinct capability flag or define a mandatory minor-version contract for serving envelopes; protocol major 1 or compact support alone is insufficient proof. An absent field from an older peer must not become the expected identity by default. The P07 strict client must fail closed when the required envelope contract is unavailable. A new capability flag may use the currently free CapabilitiesResponse field 12; if adopted, its domain default is false and advertisement is true only when all response paths honor the contract. Preserve additive old/new codec tests and pin the chosen version/fields. + +2. **Validate before accepting effects.** For every unary response and stream frame, validate the envelope against the authenticated operation/stream's expected node, boot incarnation, role, catalog epoch, and authority epoch before exposing content or updating handles, sequence, snapshot state, or cursors. Nested Sample/CompactValues provenance must also match that envelope and expected identity. Empty batches and control-only streams receive the same check. Validate browse lease/catalog provenance against its envelope; do not accept a lease from a different generation. A mismatch invalidates the route/stream and requires fresh authenticated discovery and, for subscriptions, a new epoch/snapshot. A control message cannot silently replace the stream's expected identity. The narrowly defined no-dispatch proof in item 6 is distinct from accepting successful data under changed role/epochs. + +3. **Keep authentication and identity binding intact.** Serving itself does not include cluster ID. The expected Serving must therefore remain bound to the validated cluster identity from capabilities, the selected endpoint, TLS trust/SAN policy, and the authenticated connection/credential generation. Do not treat a self-asserted NodeId, a caller-supplied expected identity, or a cached role hint as authentication. Node selection remains pinned even when unavailable. Endpoint/channel changes require a fresh capabilities proof; continuations and old handles cannot migrate with the URI alone. Capabilities discovery is the bootstrap exception to comparison with an already-negotiated Serving: authenticate it, validate configured cluster/node and structural fields, and then establish the candidate proof. It may honestly report Secondary, unknown role, or unready state; that does not establish an eligible Cluster route. + +4. **Capture provenance, then final-check it.** Capture the identity associated with the operation/session before materializing its response. Encode that identity, rather than attaching the latest Serving to older data or an earlier acknowledgment. After all potentially blocking preparation and immediately before publication, verify that the captured identity and original caller remain usable. Include original key/version/expiry, exact authenticated authority epoch, target policy, readiness, and operation/view authority. A generation change discards/closes the prepared response rather than relabeling it. The stream adapter must preserve P06's Prepare → final gate → actual WriteAsync → successful receipt boundary and retain ownership until actual completion even when cancellation is ignored. Unary publication likewise needs a final check after response construction/encoding work; a check only before invoking the local port is insufficient. + +5. **Role eligibility is separate from supported operations.** A Cluster route requires an authenticated, currently ready Primary for admission and data publication. Pinned Node cached reads/subscriptions on a nonprimary require the explicitly configured ReadyReplica consistency policy plus the existing Warm/Hot readiness verdict. Unknown/startup role is not a ready replica. A Write operation bit is only capability advertisement; the primary gate remains mandatory at admission and actual dispatch for both target modes. Demotion closes primary-only streams and invalidates routing hints. This preserves existing election semantics and makes no stronger split-brain fencing claim. + +6. **Do not turn publication rejection into mutation replay permission.** After dispatch, demotion, credential retirement, envelope mismatch, timeout, or loss of a response cannot change an item into RejectedBeforeDispatch. Keep the original bounded outcome observer and serving-incarnation precondition. If response validation prevents trusting a returned outcome, that item's result is ambiguous and must not be replayed. Only an authenticated, identity-valid, per-item RejectedBeforeDispatch result permits a new endpoint attempt; never retry a mixed batch wholesale. A definitive late outcome may be retained internally even when it cannot be published to the retired caller. If successful outcome reporting from an old primary is allowed later, it needs an explicit original-operation provenance contract; simply stamping the current primary identity is invalid. + + Preserve the planned stale-primary failover by distinguishing a trustworthy **negative dispatch proof** from current role eligibility. The same authenticated endpoint/node/boot can honestly reject an item before dispatch after demotion, and need not still be Primary merely to report that rejection. Define this exception explicitly: the response must be well formed, match the original endpoint/node/boot and request/item correlation, and the accepted item must be exactly RejectedBeforeDispatch. Changed role/catalog/authority fields do not permit accepting successful data or installing a new route identity. Fresh capabilities discovery is required before a new attempt. All other ambiguous items remain non-replayable. Treating every role mismatch as Unknown is conservative but forfeits this demotion-failover behavior; it must not be mistaken for the planned positive case. A different boot, malformed envelope, lost reply, or unauthenticated status is not this proof. + +## Existing local seams that P07 must complete + +- `DataCapabilitiesProvider.Get` samples live Serving/readiness and strips Write when role is not Primary (`DataCapabilitiesProvider.cs:21-34`). It does not itself enforce Cluster target eligibility, nor prove that an advertised operation remains authorized after preparation. +- `LocalDataServices.Ready`, `CanPublish`, and `CanUseSubscription` validate catalog/readiness and identity but do not require Cluster Primary (`LocalDataServices.cs:51-55`, `:78-79`, `:142-148`). `LocalDataConnection.CanPublish` does not pass Target to that gate. Thus P07 must supply a target/consistency-aware publication boundary rather than assuming the existing boolean covers role policy. +- `AuthorizeSubscription` currently derives ReadyReplica from any non-Primary Serving.Role (`LocalDataServices.cs:117-120`). The configuration entity already has an explicit Consistency defaulting to Primary, but DataTarget contains no consistency field. Preserve that configured policy through the connection/admission seam; do not infer permission to consume a replica from the server's reported role. A separate bound connection policy is sufficient; this does not require blindly adding client-controlled authorization fields to every request. +- `CanPublish` checks original caller usability but does not itself compare `context.AuthorityEpoch` to the captured catalog's authority epoch; subscription admission/lifetime checks do compare the authority epoch. Host ingress/final gates must bind the exact authenticated authority snapshot for all methods. A usable key alone must not upgrade an old admitted context to a newer authority generation. +- Browse/metadata/write domain return types have no batch Serving property. Their wire encoder must receive explicit captured provenance from a trustworthy facade/ingress context, including empty results. The current value-only mapper checks are not a substitute. Keep the strict remote path on helpers that require expected identity so an overload without that argument cannot accidentally bypass the contract. +- The capability provider, catalog coordinator, source publisher, write registry/dispatch gate, acquisition capacity, and actual DriverHost must use the same real process NodeId/incarnation and current role authority. Do not create a second boot GUID for the data listener, relabel cached samples from another boot, or wire disconnected process owners merely to satisfy DI. Ready capability publication must describe a coherent currently active catalog/authority/role state. + +## Required focused evidence before implementation approval + +- Round-trip the new fields on every response and all four stream variants; reject missing negotiated envelopes, another node/boot/role/epoch, nested/envelope disagreement, and empty or denied-only batches with wrong identity. Check that rejected Ack/Control frames leave handles and sequence untouched. +- Gate response preparation, then demote, change authority/catalog, revoke the original key, or expire it before publication. Require no old successful response/frame, including metadata and control-only traffic. Retain P06's blocked writer, ignored cancellation, and successful-write-only commitment regressions when the real sink is connected. +- Show Cluster refusing ready Secondary and unknown role despite read capabilities, pinned Node refusing replica use under Primary policy, and explicit ReadyReplica accepting only a genuinely ready permitted replica. Node failures must not substitute a partner. Restart on the same endpoint must invalidate the old boot proof and renew stream state. +- Show pre-dispatch rejection permitting only that item to retry, post-dispatch demotion and lost/malformed/mismatched write responses becoming non-replayable ambiguity, and credential/trust rotation retaining original in-flight outcome ownership. +- Exercise the actual Host composition with one boot/role/authority/acquisition owner, plus existing WarmRoleAuthority/PrimaryGatePolicy tests if the role adapter changes. Actual TLS certificate/listener behavior and Docker wire evidence remain P10; passing fake-client/codec tests cannot establish those transport claims. + +The normalized cache-ingress age contract and explicit unknown stream upper bound remain unchanged by this provenance addition. A serving envelope proves the validated source of a response; it does not turn cached value age into physical measurement age or prove exclusive device ownership. + +## Unary final-publication adapter direction + +**A narrow registered response-marshaller adapter is appropriate; a service-method/interceptor return check alone is not the final boundary.** In pinned grpc-dotnet 2.76.0, the unary call handler awaits the user method and subsequently passes its response to the framework writer. The writer can await response startup before invoking the contextual serializer. Thus a guard in the service can precede further asynchronous work. [Unary handler](https://github.com/grpc/grpc-dotnet/blob/v2.76.0/src/Grpc.AspNetCore.Server/Internal/CallHandlers/UnaryServerCallHandler.cs), [framework writer](https://github.com/grpc/grpc-dotnet/blob/v2.76.0/src/Grpc.AspNetCore.Server/Internal/PipeExtensions.cs). + +The generated protobuf serializer uses GetBufferWriter after declaring its size. That can write directly to the response pipe before Complete, so forwarding its buffer requests to the real context and checking only Complete is too late. Serialize into a private bounded owned buffer, then run the captured authority/publication-lease guard inside the actual registered response marshaller, then call the real Complete(byte[]) exactly once. Disable framework response compression for this path (NoCompress): otherwise Complete performs compression after the guard and before writing the pipe. This is synchronous transport-buffer handoff, not a flush acknowledgment or proof of remote receipt. Headers may already have started; rejection must prevent the response message body. [Serialization context implementation](https://github.com/grpc/grpc-dotnet/blob/v2.76.0/src/Grpc.AspNetCore.Server/Internal/HttpContextSerializationContext.cs). + +A custom BindServiceMethod/ServiceBinderBase wrapper can replace unary response marshallers while preserving generated request marshallers, names and service metadata. Keep the bind method's service parameter as the generated service base: the framework uses that type when checking handler base definitions. Discovery passes a null service instance, so registration must not capture a concrete call instance. [Bind discovery](https://github.com/grpc/grpc-dotnet/blob/v2.76.0/src/Grpc.AspNetCore.Server/Model/Internal/BinderServiceModelProvider.cs), [handler selection](https://github.com/grpc/grpc-dotnet/blob/v2.76.0/src/Grpc.AspNetCore.Server/Model/Internal/ProviderServiceBinder.cs). + +Associate each response with explicit bounded call-owned publication state; do not rely on an AsyncLocal assignment inside the completed user method being visible to its caller, or on an unbounded global response dictionary. Keep captured leases and byte reservations alive through marshalling/handoff. Supply idempotent call-completion cleanup when deadline/cancellation skips serialization, and retain a marshaller reference while physical preparation is running. Missing, retired, or already-consumed state rejects. A method-local finally must not release the state before the framework invokes the marshaller. + +Required evidence is through the registered binding: revoke after method return/before serialization, revoke while private serialization is gated, and verify no real-context completion/body write; verify a positive body is handed off once, compression is disabled, and cancellation/deadline before serializer invocation releases ownership. This is a contract-direction review only; no adapter implementation or transport test is claimed complete. + +## First registered-binding source checkpoint — open + +The coordinator subsequently implemented `DataConnectionGrpcBinding.cs` and GetCapabilities in the otherwise incomplete/unmapped service, and reports three registered-marshaller tests passing in `20261116T130009.001707Z-f4443cd19118`. Source review confirms the generated-base bind signature, response-marshaller replacement, private bounded protobuf serialization, response-associated ConditionalWeakTable state, one-use protection, and HTTP-completion disposal registration. These are implementation observations, not final transport approval. The following findings remain open: + +- **P1 — NoCompress is not enforced on the actual ASP.NET invocation path.** PublicationBinder sets the flag only in its replacement handler delegates (`DataConnectionGrpcBinding.cs:22-33`). ASP.NET discovery passes a null service instance, producing null handlers; ProviderServiceBinder creates invocation delegates through reflection rather than using the supplied handler. The actual Execute/GetCapabilities method does not set the flag. Therefore Complete can still perform framework compression after the final guard. Set the policy in the real service/interceptor/call-bound marshaller state and verify the actual discovery/invocation path. The three capture-binder tests prove marshaller replacement, but do not exercise runtime WriteOptions. [Pinned provider behavior](https://github.com/grpc/grpc-dotnet/blob/v2.76.0/src/Grpc.AspNetCore.Server/Model/Internal/ProviderServiceBinder.cs). +- **P2 — Registration disposal during the publication callback can still permit handoff.** Serialize reads `_state` before calling canPublish (`DataConnectionGrpcBinding.cs:70`). If that callback blocks, Dispose changes the state to 3, and the callback then returns true, execution still calls Complete. Recheck state after publication validation; put final cancellation/deadline checks after potentially blocking validation as well. Regress a gated callback, concurrent disposal, and zero Complete calls. This does not require a blocking global lock around transport handoff. +- **P2 — Configured unary timeout ownership ends before serialization.** Execute disposes its timeout/linked sources on method return (`DataConnectionGrpcService.cs:48-52`), while the later marshaller registration checks only the gRPC context cancellation token (`:66-68`). With a longer or absent client deadline, configured server UnaryTimeout can expire during subsequent preparation without denying handoff. Retain its deadline state through HTTP completion, or capture a monotonic expiry for the final guard; test expiration during private serialization and correct release when serialization is skipped. + +The new discovery gate is directionally consistent: it can report an honest unready/unknown-role snapshot while requiring exact current serving/authority and original caller usability. It does not use the stricter data-ready publication gate to suppress all unready discovery. This checkpoint found no additional discovery-gate defect. Remaining RPCs, middleware/Program composition, real binding wire tests, and the full P07 gate remain pending. + +## Stream publication-guard handoff direction + +**Approved as an additive direction, not yet an implementation approval:** add an optional transport-neutral prepared-delivery capability exposing one-time `SetPublicationGuard(Func)`. Runtime binds the existing PendingDelivery.Gate after successful Prepare and before Write. Host prepared deliveries require the binding, and invoke that exact Runtime predicate inside the registered marshaller after private byte preparation. This closes the interval in which the framework can await response startup after Runtime's earlier gate while only the source/producer proof changes, leaving the connection's Serving/catalog envelope unchanged. + +Binding is one-time and disposal-aware; unbound, duplicate/replaced, retired, or disposed registration fails closed. Host identity/auth validation runs before the Runtime predicate, which is the final potentially blocking validation; final state/cancellation/deadline reads follow immediately before synchronous handoff. The predicate is observational: do not run eligibility selection, snapshot rate consumption, receipt commitment, or cursor advancement from the marshaller. False/throwing/unbound guards must fault the actual write or provide a negative receipt, never report a successful no-op write. + +Runtime still commits baseline, sequence, cursor, and acknowledgment effects only after actual WriteAsync succeeds. Binding does not transfer or shorten ownership: pending delivery, frame/sample leases, byte reservation, session hold, prepared bytes, and registration stay owned until the physical write task settles, including when an outer wait is canceled and the transport ignores cancellation. A late callback after session retirement must observe invalid state without using prematurely released resources. Direct enumerable delivery retains its existing boundary. + +Required focused evidence holds the writer between entry/startup and the registered marshaller, then invalidates the source ticket or retires the producer without changing Serving/catalog or first letting the session's ordinary tick close it. Releasing the writer must produce zero body handoffs and zero receipt commits. Include a snapshot/control or Modify acknowledgment case, a valid one-handoff/one-successful-receipt positive, unbound/double-bound/disposed rejection, and ignored-cancellation physical-lifetime accounting. These are regression requirements; no result or implementation closure is claimed here. + +## Observed-role source checkpoint + +The reviewer independently read Runtime run `20261116T141626.988288Z-e977454116c3` (103/103 passed, zero skipped) and Host run `20261116T141558.244776Z-7bfca094cb86` (72/73 passed; the sole failure was the separately pending completed-credential-bundle replay regression). Existing role-policy cases and the new direct RedundancyRoleView provenance test passed. These results do not establish actual actor lifecycle behavior or completed P07 wiring. + +RedundancyRoleView now stores Allowed, Generation, and ServingRole in one immutable volatile verdict under the existing dispatch fence. ServingRole starts Unknown independently of the existing policy's permissive single-node boot fallback; explicit observed role changes advance the generation even when Allowed is unchanged. This is the correct distinction, and it does not alter the existing election algorithm. DriverHostActor now publishes its cached `_localRole` through this new method when the real shared view is present. + +### P1 — An accepted snapshot without the local node retains stale serving-role provenance + +`DriverHostActor.OnRedundancyStateChanged` intentionally leaves the legacy `_localRole` unchanged if a newly accepted snapshot omits this node (`DriverHostActor.cs:2709–2723`). The new `PublishPrimaryVerdict` forwards that cached value to `PublishDataServingRole`. Thus Primary followed by an accepted snapshot lacking the local entry still publishes Primary, and its generation need not change. A later P07 caller can treat stale provenance as current Primary even though the current snapshot supplies no local-role proof. The direct setter test cannot detect this actor adaptation error. + +Preserve the legacy bool/gate behavior where required, but track the data-service observed role separately from that legacy cache: every accepted snapshot must derive the current data-serving role from `local?.Role`, publishing Unknown on omission and advancing its authority generation. Regress the actual DriverHostActor with the real shared RedundancyRoleView: Primary → accepted missing-local snapshot → Unknown, unchanged legacy verdict if intended, invalidated old publication proof, and positive recovery on a new explicit local role. Rejected older snapshots must not disturb the current accepted proof. + +DriverHostActor.PostStop also currently leaves the last observed serving role in the shared view. The completed authority composition must define and test retirement/reset of that publisher so a stopped owner cannot leave a current serving proof indefinitely; actor restart starts Unknown again, but that alone does not prove the stopped interval. This lifecycle obligation is distinct from changing existing legacy write/historian policy. Source repair and actual actor regressions are pending; no whole-phase approval is granted. + +## Actual Host composition checkpoint — source review, gate pending + +The coordinator subsequently added real DataConnectionRegistration/Program wiring and three actual DriverHostActor regressions. Frozen source now keeps `_observedDataServingRole` separate from the legacy cached role, sets it to `local?.Role` on each accepted snapshot, registers a monotonic role-owner lease, and retires only that owner on PostStop. Replaced owners cannot publish or retire the replacement. Counter exhaustion poisons role availability. These source changes address the missing-local/stopped/old-owner findings; their new full-gate result was pending when this review began. The review did not run tests/builds or modify production code. + +Registration uses one process identity for the catalog, source publisher, and write registry; one shared dispatch fence/role view; one hub/clock; and one acquisition-capacity owner passed to the real DriverHostActor. A deferred facade resolves the actual ActorRegistry host rather than constructing another actor graph. The dedicated listener validates port conflicts, requires TLS except explicit development loopback, loads a current private-key certificate with SAN coverage for all allowed hosts, and uses the data middleware before mapped service dispatch. These observations are not wire/TLS evidence. The coordinator's separately tracked admission-class separation, final monotonic unary timeout, and existing secret-invalidator composition work are not duplicated here. + +### P1 — The actual OPC UA publisher is missing the shared catalog coordinator + +`Runtime/ServiceCollectionExtensions` passes SourcePublisher, LocalCatalogCoordinator, write runtime, and acquisition owner to DriverHostActor, but the real OpcUaPublishActor.Props call still omits its already-supported shared catalogCoordinator/dataCatalog arguments. DriverHost stages its shared attempt and deliberately completes it itself only when no OPC UA publisher exists. OpcUaPublishActor.FinishRebuild completes that attempt only when its own coordinator is nonnull. In the actual enabled graph neither completes the shared generation, leaving Current null and data readiness permanently unavailable despite a successful address-space apply. + +Inject the same coordinator/activation into the real publisher and add a positive real-composition apply/restore test. The registration test that expects facade creation to fail before an actor exists cannot establish successful activation. Source repair/evidence are pending. + +### P1 — Registration substitutes snapshot Primary for the existing Warm verdict + +The consumer activation callback accepts DataServingRole Primary regardless of mode and accepts Secondary for artifact-declared Hot. It never reads the actual WarmRoleAuthority verdict owned by OpcUaPublishActor. Warm can be Standby despite a Primary snapshot (membership disagreement, endpoint not listening, or no accepted revisioned snapshot), and can be Active during the approved unreachable-primary path while its snapshot role is still Secondary. The callback therefore both admits forbidden Standby work and suppresses legitimate Warm activation. Serving capability readiness likewise lacks the existing Warm readiness decision. + +Publish the existing accepted Warm verdict from OpcUaPublishActor through a shared owner-fenced view; do not duplicate election logic. Promotion publication follows the actual successful data-plane transition, while demotion denial precedes potentially blocking SDK/ServiceLevel work. Default/retired owners are Standby; stale owners cannot overwrite replacements. The same view and effective **local** WarmRedundancySettings must drive acquisition and serving readiness: artifact Hot cannot bypass a locally Warm Standby, since the existing actor explicitly retains local mode on artifact mismatch. + +The minimal existing seams are OpcUaPublishActor.ApplyWarmTransition, PostStop, both Props factories, and its real Runtime registration. Extend OpcUaPublishActorWarmTests (transition order, unrevisioned/older snapshot, failed ServiceLevel, disagreement), EndpointStateTests, and actual owner stop/replacement cases. Notify runtime after publishing the shared verdict and outside its publication fence. Source repair/evidence are pending. + +### P1 — Role/owner generation is discarded before publication, allowing ABA revival + +RedundancyRoleView advances PrimaryGeneration on role/owner changes, but the registration's Serving delegate emits only NodeId, Incarnation, Role and existing catalog/authority epochs. LocalCatalogCoordinator role wrappers preserve those epochs. A blocked old unary/frame can therefore survive Primary → Unknown/Secondary → Primary, or owner replacement followed by Primary, if its final gate sees only the final identical Serving tuple. The separate rich-write PrimaryGeneration proof does not protect ordinary metadata/read/control publication. + +The coordinator's proposed additive ServingGeneration (wire Serving field 6) is the appropriate minimal direction: capture role/readiness/owner validity and generation atomically from one immutable snapshot, propagate it through full serving comparisons, and refresh catalog wrappers even when the role string returns unchanged. Poison on overflow. Include Warm owner/verdict transitions in the same effective proof. Network negotiation must require a positive generation for the new serving contract; default zero may remain for legacy/local fixtures but must not silently disable ABA protection on a peer claiming the new contract. No separate backing-source epoch is needed, and original sample versions/cache-ingress timestamps must not be refreshed by role changes. Require actual late-marshaller away/back and owner-replacement regressions plus fresh-request recovery. This is an approved direction, not yet a verified repair. + +### P1 — Outbound revocation is conditional on successful local catalog staging + +StageCatalog calls `_dataConnections.Apply` only after authority installation and ParseLocalCatalogSnapshot. A newer desired artifact that removes consumers but fails unrelated local catalog/authority projection logs/returns first. BeginCatalogAttempt closes the origin catalog but does not deny the outbound runtime's old scope, so its previously acquired facades/streams can remain authorized indefinitely. + +Introduce an outbound desired-attempt denial barrier independent of local export staging; activate the replacement only from validated scope and durable floor. Regress an actual host apply with an active outbound scope, a newer removal artifact plus local catalog failure, old-handle/stream denial and drain, and honest recovery. Keeping legacy driver topology on failed apply does not authorize retaining the old external data scope. Registry internals are being reviewed separately; this finding concerns the actual actor integration order. Source repair/evidence are pending. + +This checkpoint remains open. No final P07, real TLS, Docker, or OPC UA integration approval is claimed. + +## Composition repair rereview — source verified, integrated gate pending + +The four preceding composition findings are addressed in the frozen source inspected at this checkpoint: + +- The actual ServiceCollectionExtensions graph now calls DataConnectionPublisherProps.Create, which selects the shared catalog coordinator/activation, authority, Warm view, and outbound runtime. The real Host-to-publisher held-sink regression calls that same production factory and requires the catalog to remain unavailable before successful topology completion, then activate on the matching acknowledgment. This guards the dependency omission rather than manually supplying a different test-only Props graph. +- Registration captures driver-role and Warm immutable state under the same shared dispatch fence, using TryEnter to keep acquisition callbacks nonblocking. Local Warm settings override artifact Hot; an unaccepted or retired Warm owner publishes an unavailable Standby serving identity. Actual accepted Warm transitions remain owned by OpcUaPublishActor, and its notifications run after the immutable publication leaves the fence. +- ServingGeneration propagates through catalog role wrappers even when the role string returns unchanged. The checked combined role/Warm generation rejects exhaustion. WriteRouteProof now retains full Serving identity; the actual dispatch gate captures live coordinator.Serving before checking IsPublished and requires both catalog and live identity to equal the proof under the shared fence, alongside the existing route/driver/PrimaryGeneration checks. It does not take a deployment-runtime lock inside that fence. +- DriverHost.BeginCatalogAttempt invokes the outbound BeginAttempt before empty/malformed input, authority installation, or local catalog parsing. The outbound runtime synchronously withdraws old routes and checks the latest attempt revision/generation before a delayed scope activation can install entries. The actual invalid-local-artifact regression holds an old import lease and verifies its cancellation and denied readiness after the failed newer apply. + +Evidence is deliberately limited: the reviewer independently read run `20261116T152849.971443Z-55329afdc892`: Host 87/87 passed; Runtime 207/210 passed, with both new Warm final-write fence regressions failing as expected before repair and one separate frozen-snapshot ordering failure. These results are not a green result for the repaired source. The reviewer also read `20261116T153431.302434Z-0add51a2b272`: deployment activation 15/16 passed, with the transient scope-store retry regression failing before its repair. Final repair results and the complete applicable P07 gate remain required. + +The new deployment-runtime availability findings are recorded in `p07-remote-astra-review.md`; the newly composed invalidator finding is recorded in `p07-credential-astra-review.md`. No whole-phase approval is granted. + +## Final P07 reconciliation and approval + +The reviewer independently read `artifacts/grpc-data/20261116T155343.945235Z-be0fbabc1a44/unit/P07/run.json` and all five TRXs: **392/392 passed, zero failures/skips** (Host 91, Runtime 219, Commons 41, Configuration 20, ControlPlane 21). Before these documentation edits, the current HEAD exactly matched `b710bf9f74f04ede38b902fcffc7259e2e808aa1`, `git diff HEAD --binary` SHA-256 matched `f2fad373d196e951f6f39ec799e36845ddb9dcbe48931958a0e17eab627362f4`, and all 50 recorded untracked production/test C#/proto/project hashes matched. The phase manifest includes the required new classes and affected existing auth, local service, stream, role, actor, write, codec, configuration, and sealing regressions. The reviewer ran no builds/tests, Docker commands, migrations, or commits. + +All actionable P07 findings in these three review notes are closed at this boundary. The serving envelope/generation is negotiated and compared for every response category. Actual method execution enforces NoCompress; the registered response marshaller prepares private bounded bytes, checks publication authority and final disposed/cancellation/monotonic timeout state, then synchronously hands off the buffer. Runtime's exact prepared-delivery guard crosses framework startup awaits into that marshaller; receipt effects still follow successful actual WriteAsync. These unit seams prove the selected handoff boundary, not network flush or remote receipt. + +The real production publisher factory, actual Host/publisher held-sink activation, observed-role owner lifecycle, accepted Warm publication, same-role ABA, final device-write Warm fences, and malformed-next-artifact outbound denial all pass. The final deployment-runtime fix keeps configured consumer scope independent of transient role observation, while role checks remain at worker creation, acquisition, and every borrowed-operation boundary. Actual role notifications still advance all route revisions and retire entries; BeginAttempt still immediately empties scope. Its last two-link regression was observed failing in `20261116T155211.129165Z-316e31f82ca8` and passes in the final run. Credential and remote lifecycle dispositions are recorded in their companion notes. + +**Approved phase-ordering variance:** Task 15 originally schedules creation of `GrpcDataTlsWireTests.cs` and `GrpcDataListenerIsolationWireTests.cs` in P07, with execution in P10. Their creation moves to P10 alongside the actual TLS fixtures, rather than adding unexecutable placeholders here. Both classes remain required under `Host.IntegrationTests/DataConnections`, tagged Feature=GrpcData/Category=Integration, alongside the existing mesh boundary/auth integration selectors. No wire-test requirement or scenario is waived. + +P10 still owns actual certificate/listener isolation, Docker/CLI/probe scenarios, deployed rotation/restart/failover, and relational migration/concurrency/rollback evidence. P11 owns workload/capacity measurements; P12 owns the full solution gate and separate final Astra review. This approval permits the P07 commit and dependent P08 work, without asserting those later outcomes. + +## Superseding final candidate — credential-expiry lease cap + +P08 preparation identified one additional P2 before the P07 commit: Browse issued MaxMetadataLease even when the original authenticated target credential expired sooner. A consumer cannot infer that target-key expiry from its opaque bearer. The coordinator held the commit and captured actual behavioral RED in `20261116T160304.904551Z-9a7e5ce79d56` (local connection 5/6 passed; Browse_lease_never_outlives_the_original_target_credential failed). The reviewer independently read that TRX. + +Frozen LocalDataServices now limits the branch lease to the smaller of MaxMetadataLease and the positive remaining original context.CredentialExpiresUtc measured with the same Clock. Expiry while finishing returns Denied with no lease. The continuation uses that exact capped duration and the existing request-start monotonic anchor, which is conservative rather than extending validity by response preparation time. The regression verifies a one-second original credential caps the lease and denies a later continuation after expiry. DataMetadata, including GetMetadata results, has no standalone authority lease; P08 caches must use the enclosing Browse lease/request-start boundary or obtain new authority, rather than inventing a duration for metadata objects. + +The reviewer independently reconciled the fresh full run `20261116T160335.804917Z-5a4994c32d15`: **393/393 passed, zero failures/skips** (Host 91, Runtime 220, Commons 41, Configuration 20, ControlPlane 21). Before these Markdown edits, HEAD still matched `b710bf9f74f04ede38b902fcffc7259e2e808aa1`; tracked diff SHA-256 matched `55029f7b6c6323a87dd3d8b96a988928d1eaee5e3889e1f57c4b07e4bd5771ae`; all 50 recorded new source/test hashes matched. This supersedes the earlier 392-case approval candidate. The additional finding is closed and **P07 approval is reaffirmed**, with the same explicit P10/P11/P12 obligations and TLS test-creation ordering variance. No builds/tests or commits were run by the reviewer. diff --git a/docs/plans/evidence/grpc-data/p07-credential-astra-review.md b/docs/plans/evidence/grpc-data/p07-credential-astra-review.md new file mode 100644 index 000000000..e6b515c94 --- /dev/null +++ b/docs/plans/evidence/grpc-data/p07-credential-astra-review.md @@ -0,0 +1,146 @@ +# P07 credential and scope Astra review + +**Final disposition: approved for P07.** The final reconciliation below supersedes the historical open dispositions. The superseding full P07 run `20261116T160335.804917Z-5a4994c32d15` passed 393/393 applicable tests with zero failures/skips, including Host 91, Configuration 20, and ControlPlane 21. Actual TLS, deployed rotation/restart, SQL migration/concurrency, and final implementation approval remain later gates. + +**Earlier checkpoint disposition (historical): five original findings and normal scope-history reclamation were repaired; failed trust retirement/reintroduction and observation-admission races remained open.** This initial read-only review covered the frozen `DataConnectionSecretProvisioner`, `DataConnectionCredentialResolver`, `DataConnectionSecretChangeHandler`, `DataConnectionTrustPolicy`/store, `DataConnectionSecurityProvider`, and their four Host test classes while startup/composition and the remote client were still being implemented. No builds, tests, Docker commands, or commits were run by the reviewer. The original findings below are retained chronologically; the final repair dispositions and evidence are recorded at the end. + +## Findings + +### P2 — A transient import failure permanently consumes the mounted bundle version + +`ApplyAsync` persists every entry as Version=V/Pending=true before encryption/payload writes and its final commit (`DataConnectionSecretProvisioner.cs:108-124`). Its validation then rejects every future bundle with a version less than or equal to V (`:103-106`). A transient payload store/encryption failure, cancellation after the first save, or crash before the final save leaves a Pending entry that cannot be completed by replaying the identical mounted bundle after recovery/restart. The existing failed-store test proves denial, but does not test recovery. + +Persist an immutable attempt identity and support safe resumption of that same attempt, or provide an equivalent durable transaction recovery protocol. A different payload under the same version must still reject. Regress failure after pending persistence, partial multi-entry writes, and failure of the final commit; restart and replay the identical bundle must eventually make its correctly committed entries usable without inventing a higher operator version. Recovery must never expose mixed/partially committed state. + +### P2 — Committed credential versions are not bound to their stored payloads + +The durable state records only Version, Deleted, and Pending (`DataConnectionSecretProvisioner.cs:22-27`). The resolver decrypts the current secret row and labels it with that independently stored version (`DataConnectionCredentialResolver.cs:19-24`). After a successful V2 import, an external editor or delayed store/replication update can replace the payload with an old V1 row; the resolver returns the old bearer labeled V2. The tombstoned-row test covers Deleted=true, but not replacement of an active committed payload. + +The packet owner confirmed the intended contract: external replacement must fail closed until explicitly reprovisioned at a higher version. Bind the committed version to an authenticated encrypted-state content hash or appropriate durable store revision and verify it on resolve. Regress active V2 followed by an old or different payload row; it must not return that replacement as V2. The same operation/content identity can support the safe pending retry above. Never include plaintext bearer values in diagnostics or unencrypted version metadata. + +### P2 — A failed scope-removal deletion is forgotten permanently + +`SetScopeAsync` saves the reduced scope and tombstones first, then deletes orphaned payload rows (`DataConnectionSecretProvisioner.cs:73-85`). If DeleteAsync fails, replay of the same scope/version returns before cleanup (`:69-70`). A later scope version computes orphaned references from the already-reduced scope, so the failed deletion is no longer discoverable. Logical resolution remains denied, which is correct, but the retired encrypted material has no durable cleanup obligation and may remain indefinitely. + +Retain resumable deletion work until actual store cleanup completes, with safe idempotent retry after restart or same-scope replay. Preserve deny-before-cleanup and shared-reference ownership: a reference still used by an allowed connection cannot be deleted. Regress a failed delete after state persistence, restart, and successful cleanup without resurrecting access; include a shared-reference positive. + +### P2 — Historical state has no lifetime bound or reclamation rule + +`DataCredentialState.Versions` retains every historical secret reference, including tombstones. The trust store likewise retains every historical connection entry/removal marker. `DataConnectionSecurityProvider._observed` retains every ResolveAsync ID forever, including failed and non-HTTPS lookups, and every secret invalidation scans all those IDs (`DataConnectionSecurityProvider.cs:14`, `:24`, `:34`). A one-MiB bundle-file limit bounds one import only; small sequential deployments with new IDs grow the persisted state and in-process invalidation work without bound. + +Define bounded live-state ownership and a safe generation/version barrier for retired history, or an explicit bounded persistence protocol with a recovery/reclamation path. Do not solve this solely by permanently exhausting a quota after enough historical IDs. The observed-ID set should reflect currently owned connections or use another bounded invalidation mechanism. Regress sequential distinct-ID/reference churn and failed lookups while retaining downgrade/stale-bundle protection and progress for a fresh active connection. + +### P2 — Trust policy does not enforce the required SAN identity + +`DataConnectionTrustPolicy.Validate` ignores the request URI and only rejects a supplied name-mismatch flag before custom-chain validation (`DataConnectionTrustPolicy.cs:23-33`). Its positive unit test creates a CN-only certificate with no SAN and expects it to pass when given SslPolicyErrors.None. That does not establish the plan's explicit DNS/IP SAN identity contract and depends on the platform's hostname policy. + +Check the requested endpoint's DNS/IP SAN explicitly, with common-name fallback disabled, while preserving custom-root chain and server-auth validation. The official [.NET 10 MatchesHostname API](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509certificate2.matcheshostname?view=net-10.0) exposes an `allowCommonName` choice; its default is true. Add actual CA-issued server-leaf positives, absent/wrong SAN, IP SAN, wrong root, removed root, and wrong usage/expired-leaf negatives as appropriate. The existing injected NameMismatch case alone is not SAN coverage. Real TLS/listener/certificate rotation remains P10 evidence. + +### P2 — One throwing notification subscriber can prevent required retirement fan-out + +`DataConnectionSecretChangeHandler` invokes multicast actions directly (`DataConnectionSecretChangeHandler.cs:8-11`), and the security provider similarly invokes its Changed event directly. The provisioner calls these notifications after persisting a pending import or reduced scope and before finishing all entries/connections. A throwing first subscriber prevents later subscribers and later connection notifications; a rotation can therefore leave required retirement listeners uninformed while durable state has already changed. Store denial on future resolution does not itself cancel an already active stream. + +Make required retirement notification fan-out resilient to individual callback failure and preserve/retry any operation-wide obligations. Errors may be reported, but cannot silently skip other affected connections. Test two listeners where the first throws and the second receives the retirement, plus a multi-connection shared-reference rotation/removal. Compose this with the existing invalidator and Galaxy notification path rather than replacing them. Do not run arbitrary blocking subscriber work under the global state semaphore if the integration can reenter credential resolution. + +## Reviewed properties and integration obligations + +- Scope is persisted before removed connections are notified/deleted, and the resolver rejects missing, Pending, or Deleted entries. Explicit tombstones prevent the already-tested retired-row resurrection. Shared references are retained while another allowed connection still names them. These are useful foundations; the recovery and active-payload-binding gaps above remain. +- Node/owner checks and the reference allowlist precede bundle payload mutation. Import writes encrypted payloads using the existing secret-store pattern, and credential/entry ToString methods redact values. The bounded reader supports atomic file replacement by opening with delete sharing; it does not by itself supply a production bundle watcher or restricted-file deployment policy. +- Trust is independently versioned, persists empty-root removal markers, uses custom-root trust and server-auth application policy, and rejects explicit name mismatch. Roots are copied from public certificate bytes. These observations do not establish real TLS behavior, and the SAN finding remains open. +- The four test classes include an actual SQLite/encryption restart test, but no execution result was supplied for this packet. They currently do not cover the new failure/recovery cases, changed-event composition, active streams/outcome observers, or packet lifecycle bounds. +- Host has not yet composed the bundle reader/provisioner, current allowlist, trust store, and change handler into startup/runtime lifecycle. The existing `SecretChangeSignallingInvalidator` still calls only its inner invalidator and Galaxy directory at this checkpoint; adding the data notification must preserve both. This is a known uncompleted composition boundary, not a claim that final Host wiring is defective. +- Credential/trust resolution is split across awaits. The actively implemented remote channel code currently captures a security-generation value before resolution and rejects changed generations before installing a channel. Keep that invariant and regress rotation/removal during resolution; a retired snapshot must not install a new channel after its retirement event. The active remote code was not reviewed as final. +- Scope/credential/trust retirement must deny new dispatch, retire channels and quiet streams, and retain only bounded observers for already dispatched mutations. A callback notification alone is not final evidence of those effects. No credential or trust rotation may replay a mutation or relabel its original outcome ownership. + +The coordinator and packet owner received each finding for test-first correction. Final packet closure requires frozen repaired source and actual focused evidence, followed by the complete P07 review/gate after Host and remote composition are finished. + +## First frozen repair rereview + +The coordinator supplied `20261116T130336.930026Z-3b0156408b84`. The reviewer independently read its run record and TRX: the selected Host component packet passed **29/29, zero failed/skipped**, including all 19 credential/trust cases in the four reviewed classes. This is not the full P07 gate. + +- **Interrupted-import recovery repaired:** pending entries now persist their intended content/deletion hash; an equal-version retry is accepted only while Pending and only for identical content. A changed payload under that version still rejects. The focused interrupted-version test proves denial after the initial failed write, changed-payload rejection, restart, and successful identical retry. +- **Committed payload/version binding repaired:** resolution hashes the decrypted payload and requires the committed encrypted-state hash. The active-row replacement regression returns unavailable rather than labeling replacement material with the stored version. +- **Deletion recovery repaired:** removed refs and affected connections become durable PendingDeletes/PendingNotices before work. Exact-scope replay completes those obligations rather than returning immediately; successful deletion is persisted per reference. Reintroduced/live refs are excluded from deletion. The restart-after-delete-failure regression passes. +- **SAN enforcement repaired:** validation explicitly matches RequestUri.IdnHost with common-name fallback disabled before custom-root chain validation. The focused tests now reject CN-only identity and validate a CA-issued SAN leaf against the correct/wrong issuer. Real wire trust rotation remains P10. +- **Notification fan-out repaired:** each subscriber and each affected connection is attempted despite individual exceptions, then failures are aggregated. Scope notices remain durable for same-version retry, and trust updates remain PendingNotice/unresolvable until successful notification. Tests cover a throwing first subscriber, same-scope notification retry, and same-version trust notification recovery. Final composition must still preserve the existing invalidator/Galaxy path and actual stream retirement. + +### Still open — a finite historical cap permanently exhausts availability + +The repair limits Versions and trust history to 256 entries, but does not reclaim absent historical entries (`DataConnectionSecretProvisioner.cs:134-135`; `DataConnectionTrustPolicy.cs:63`). After 256 sequential retired refs/connection IDs, a fresh active ID is permanently rejected even when the live scope is empty. SecurityProvider similarly caps `_observed` without removal; 256 failed HTTPS lookups can prevent a later valid connection from resolving. The new tests assert failure at the historical cap, not progress after churn. The memory growth is bounded, but the original availability/lifetime finding remains unresolved. + +The coordinator/worker proposed a durable scope-generation floor as the next repair direction. That is sound if every credential bundle and trust update must carry the exact current authoritative generation; floor and allowlist are atomically persisted before retirement/reclamation; and absent history is reclaimed only after cleanup and no remaining live reference. The floor must survive offline restart and come from a trusted monotonic deployed-scope revision. A process-local authority/catalog epoch, wall clock, or local increment that turns an old artifact into a fresh scope is insufficient. + +Include generation in immutable retry identity and reject an old generation even when its material Version is larger. Unchanged allowed references may retain already committed material; new updates must use the current generation. Regress removal/reintroduction of the same reference, old high-version bundle/trust replay after restart, failed cleanup, and more than 256 sequential IDs while a fresh active ID still progresses. Provider observation must track live ownership or another reclaimable bounded invalidation set. This direction has not yet been source-reviewed or tested as an implementation. + +## Scope-floor repair checkpoint — two paths still open + +The next frozen repair adds an exact persisted scope generation to credential bundles and trust updates, includes it in equal-version pending retry identity, and removes retired credential versions after successful physical deletion. Trust also persists an allowlist/floor before notifying removal and reclaiming absent entries. Source inspection verifies those normal-path barriers. The reviewer read the actual TRX for `20261116T131308.089661Z-57464278e345`: 32 executed, 31 passed, one failed. The failure is the separately identified Root publication-disposal race; the credential/trust scope-generation churn cases passed. This is not an all-green component or phase claim. + +Two remaining concrete paths prevent closing the lifetime/reclamation work: + +### P2 — Failed trust retirement can reactivate old trust on reintroduction + +ApplyScope persists removed IDs in PendingNotices but leaves their trust Entries intact until notification completes. If removal notification fails, then a newer scope reintroduces the same ID, CompleteScope clears the notice and retains the old Entry because it is once again in Scope (`DataConnectionTrustPolicy.cs:63-68`, `:79-85`). Resolve then returns the retired CA without a new current-generation SetAsync. + +Regress scope 1 containing A and an old CA; scope 2 empty with a throwing observer; scope 3 containing A after observer recovery. Trust must remain unavailable until explicitly provisioned under scope 3. Mark the entry retired durably when scope removal is persisted, or reclaim all pending-retired entries even when the ID has been reintroduced before cleanup. Preserve the successful notification/retry and unchanged-live-reference cases. + +### P2 — Observation admission can race past the removal notification + +SecurityProvider awaits IsEligibleAsync, then inserts the ID into `_observed`. Scope can be removed after eligibility completes but before that insertion: OnConnectionChanged removes nothing, the resolver then inserts the now-retired ID, later credential lookup returns null, and the stale observation remains. Repeating this window with distinct IDs exhausts the 256 cap despite empty live scope (`DataConnectionSecurityProvider.cs:24-32`). The client's separate security-generation check prevents installation of a stale channel, but does not reclaim this provider state. + +Fence observation admission against scope/change generation or use an equivalent owned conditional-cleanup protocol. Regress the eligibility-to-registration window deterministically and require eventual fresh-ID progress; do not remove another live observation merely because one concurrent resolve failed. + +## Authoritative central scope revision direction + +A bounded singleton central state row containing a positive checked scope revision, canonical current allowlist fingerprint, and concurrency token is an appropriate minimal durable source. It needs no historical-ID dictionary. This is a design decision only; migration/composer integration is not yet reviewed. + +- Increment only when effective scope changes. No-op scope reuses the revision, while A → B → A advances twice. Serialize the positive revision into every newly sealed artifact, including the empty/removal scope. +- Canonicalize the effective owner/consumer/connection-to-secret-and-trust allowlists using admission's identity semantics and scope-affecting enabled state. Exclude rowversions and timestamps from the semantic fingerprint. +- **Serialize revision assignment with the validated draft.** Current ComposeDeploymentAsync reads and commits the DraftSnapshotFactory transaction before later validation/composition. Allocating a new scope revision afterward can let delayed composer A seal an old allowlist with a revision newer than composer B's intervening removal. Lock the state row before reading the draft and hold an outer transaction through validation, compare/increment, composition and Deployment persistence, or use a snapshot-version CAS that retries the entire read/validate/compose. DraftSnapshotFactory already honors an existing transaction. +- Commit the state row and sealed deployment artifact together, and dispatch only after commit. A conflict retries the entire snapshot; do not reuse an old validated snapshot with a freshly allocated generation. Counter exhaustion must fail before changing authority. +- Keep ConfigComposer.Compose pure over its supplied snapshot, including the selected scope revision. SnapshotAndFlatten/drift probes must remain read-only and must not advance the counter. Extend no-op hash stability, concurrent sealing, rollback, and schema/model-compliance tests for the additive row/field. +- Consumers persist the floor across offline restarts. Missing/stale versions after a known floor cannot overwrite it or reactivate connections, including legacy/empty-artifact parsing. Intentional rollback requires a newly sealed higher scope generation rather than replay of an old artifact. Restoring central storage to an older counter cannot reset consumer floors. + +The proposed transaction boundary and consumer-floor rules were sent to the coordinator before migration work. The two local failure/race findings above remain open, and complete Host composition/full P07 review is still required. + +## Frozen repair and central source checkpoint + +The reviewer independently read run `20261116T134802.525866Z-44c634f2fd5c` and its TRX: 192 selected cases passed with zero failed/skipped, including Host 66 and all current credential/trust cases. **The two preceding local findings are repaired:** trust entries are marked Retired in the same saved removal state, and completion removes retired entries even if a later scope reintroduces the ID. Resolve denies Retired. The failed-retirement/reintroduction regression passed. SecurityProvider captures a change generation before eligibility and admits an observation only after credential/trust resolution, under the generation lock; all scope/secret events advance that generation. The eligibility-to-observation removal regression passed, and failed resolves no longer enter the observed set. Together with the earlier verified repairs and scope-churn/restart cases, this closes the prior local credential findings at the reviewed component boundary. Final activation/rotation wiring is still pending. + +`ComposeDeploymentAsync` now starts a Serializable transaction and takes the singleton scope-state write lock **before** DraftSnapshotFactory reads the draft. The factory reuses the outer transaction. The scope revision/fingerprint, Deployment artifact, and ConfigEdit are saved together; transaction commit precedes DispatchDeployment. This source ordering implements the approved stale-composer barrier. Pure ConfigComposer takes the scope version from its supplied snapshot, while read-only factory/drift paths do not advance it. The new singleton migration seeds ID 1/version 0, constrains singleton identity/nonnegative revision, and adds rowversion. Migration/model changes postdate the 192-case run and are not covered by that result; no SQL application was performed by this reviewer. + +### P2 — Central and consumer identifier semantics disagree + +DataConnectionScopeRevision uppercases owner, consumer, connection, and secret-owner identifiers, so a case-only ID change intentionally retains the same scope generation. Local credential/trust scopes instead use Ordinal dictionaries/sets; bundle owner/node checks and the hashed durable state namespaces use raw case. For example, the central Link → link no-op yields the same version, but SetScopeAsync rejects `{link: reference}` after `{Link: reference}` at that version. Changing owner/node case can also select a different durable floor namespace even though the central identity is unchanged. Secret references correctly remain case-sensitive and must not be folded. + +Use one canonical identifier representation or matching case-insensitive identity semantics across central fingerprint, credential/trust state names, scopes, bundle validation, and consumer activation. Regress the combined fingerprint-to-consumer path, mixed-case restart/state lookup, and stale-bundle rejection across case-only edits. Do not infer this agreement from the passing pure fingerprint case-insensitivity test. Repair/evidence are pending. + +### Central evidence still required + +The current Configuration two-case helper packet and one ControlPlane artifact test do not exercise ComposeDeploymentAsync. Required local coverage should use the real actor for no-op seals (same version/hash), A → B → A and final empty removal (state matches embedded artifact), invalid draft/no dispatch/no authority change, save failure/no dispatch, checked version exhaustion, and read-only SnapshotAndFlatten. InMemory failure-before-save is useful but must not be described as relational rollback/concurrent-lock proof. + +Applicable existing **local-only** selections are ControlPlane `ConfigComposerTests`, `AdminOperationsActorSingleSnapshotTests`, and the `AdminOperationsActorTests.StartDeployment_*` methods; Configuration `DraftSnapshotFactoryTests` and design-time `GrpcDataSchemaModelTests`. The latter currently assumes the latest migration is AddGrpcDataConnections; the new scope migration makes that assertion stale. Locate the intended prior migration by identity when checking its down script, and add new singleton model/seed/check/up/down-script assertions. Update schema documentation/table expectations for ScopeState. + +`SchemaComplianceTests`, `RawSchemaIntegrityTests`, `DraftSnapshotFactorySqlServerTests`, and `ConfigComposerSqlServerHashStabilityTests` require real SQL fixtures and are not local unit selections. Actual concurrent seal serialization, lock release on validation rejection, and rollback of state plus artifact on commit failure require explicit relational evidence; mock command ordering is not equivalent. Full P07 approval remains pending Host/DI/actor activation and the final integrated gate. + +## Composed invalidator checkpoint — P2 unrelated connections are retired + +The real SecretsRegistration now passes DataConnectionSecretChangeHandler to SecretChangeSignallingInvalidator. DataConnectionSecurityProvider.OnSecretChanged ignores the supplied SecretName and retires every observed connection. Consequently, rotating one data credential first sends the provisioner's precise per-reference notifications, then its ordinary invalidator call retires all other data links. Editing an unrelated Galaxy secret also drains the whole data connection set. The existing runtime test for a direct per-connection security event does not exercise this composed path. + +Resolve and retain bounded connection-to-reference provenance with each successful observation, or use an immutable current-scope reference map, so a secret notification retires exactly its current users. Preserve the first-resolution/in-flight generation barrier and removal cleanup; narrowing the fanout must not restore the previously fixed observation race. Do not synchronously reread the store from the callback: provisioning invokes the invalidator while holding DataConnectionSecretProvisioner.Gate, making that approach deadlock-prone. + +Required composed coverage uses the real invalidator, provider, and runtime: rotating A cancels A's old lease while distinct-reference B remains current; an unrelated secret cancels neither; a shared reference cancels all its users. The coordinator identified the composition concern and the reviewer independently confirmed the source path. Repair and actual regression evidence remain pending; this is not whole-phase approval. + +## Final credential, invalidation, and scope closure + +The final run and source identity were independently reconciled as recorded in `p07-contract-astra-review.md`. Host 91/91, Configuration 20/20, and ControlPlane 21/21 pass, with no failures or skips. This closes the earlier identifier-casing, completed-bundle replay, and composed-invalidator findings as well as the previously verified durable floor/tombstone/pending-cleanup/observation-race repairs. + +Canonical references remain `secret:data/...` in scope/history/artifacts; all physical store operations use the one StoreName conversion that strips the exact `secret:` prefix. Both central validation and Host scope admission reject uppercase suffix aliases, matching the pinned SecretName normalization. Owner/node/connection identities use consistent canonical casing. Completed identical bundles are replayable after restart, while changed payloads at the same version and externally overwritten committed payloads fail closed. The reviewer independently read the actual Host three-case RED in `20261116T154508.671279Z-4ce9d3d0e4b0` and central two-case uppercase RED in `20261116T154756.981334Z-ba1d43a247b0`; the repairs are green in the final frozen gate. + +Successful security observations now retain their resolved physical SecretName in the bounded observation map. Secret invalidation selects only matching users; an unrelated/Galaxy secret leaves data links current and a shared reference retires all its users. The existing global in-flight generation check remains, including when no successful observation exists yet. Callback processing performs no store read and therefore does not reenter the provisioner's held gate. The composed invalidator/provider/runtime regression passes, and the final Runtime two-link regression additionally verifies that a transient role read during A's change does not strand B. + +The central local gate now covers monotonic change/reversion/empty/no-op behavior at the revision helper, actual actor unchanged-scope sealing and failure-before-save/no-dispatch/retry, affected validation/single-snapshot/composer regressions, and design-time singleton migration/model/script assertions. This layered evidence is accepted for the P07 unit boundary; it is not an assertion that every state transition was separately exercised through a relational actor fixture. Serializable locking before the draft read and transaction-through-artifact-save remain source-verified. Actual SQL lock ordering/concurrency, rollback on commit failure, and migration application are explicit P10 obligations, not inferred from InMemory tests. + +No actionable credential/scope finding remains for P07. The final phase approval and explicit TLS test-creation timing variance are recorded in the contract review; no real network, SQL, Docker, or P12 approval is implied. + +The superseding 393-case run additionally closes the original target-credential expiry cap on Browse leases/continuations; the finding, narrow Runtime repair, actual RED, and new candidate identity are reconciled in `p07-contract-astra-review.md`. The credential/trust/central source reviewed here is unchanged by that repair and all its selected cases remain green. diff --git a/docs/plans/evidence/grpc-data/p07-preparation.md b/docs/plans/evidence/grpc-data/p07-preparation.md new file mode 100644 index 000000000..f6d72a46b --- /dev/null +++ b/docs/plans/evidence/grpc-data/p07-preparation.md @@ -0,0 +1,19 @@ +# P07 read-only preparation — NOT implementation + +P06 source and its final gate/review remain in progress. This note is a map, not approval or evidence of P07 implementation. Coordinator owns `Program.cs` and shared DI; settle packet interfaces before edits. + +## Existing boundaries + +- `src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs`: pre-host `AddZbSecrets` and SQLite migration at 118–129; role-gated `AddOtOpcUaLocalDb` at 273–279; `AddOtOpcUaSecrets` at 629; one `AddGrpc` interceptor chain at 658–675; explicit Kestrel h2c takeover and existing-binding reconstruction at 679–783; auth middleware only on admin at 803–809; mesh maps at 817–822. Any added listener must join the binding reconstruction, preserve UI bindings, and check actual local port/host on each RPC: endpoint routing alone does not isolate listeners. +- `Host/Configuration/MeshGrpcEndpoints.cs` maps LocalDb sync, artifact/central command, telemetry/node command with `AllowAnonymous`; the interceptors are the fail-closed authentication boundary, and the explicit metadata bypasses admin cookie fallback. Data ingress needs its own equally explicit fail-closed auth plus listener admission; mesh services must also be barred from the data port. Disabled means unmapped. TLS HTTP/2 is dedicated; cleartext only explicit loopback development. +- `Host/Configuration/SecretsRegistration.cs` selects local SQLite or opt-in pair replication and decorates `ISecretCacheInvalidator`. `SecretChangeSignallingInvalidator.Invalidate(SecretName)` calls the inner invalidator then optional Galaxy directory; compose any data change notification, do not replace either. Existing production write pattern in `AdminUI/ApiKeyAck/ApiKeyGalaxyAckIdentityService.cs` uses `_cipher.Encrypt(name, value, SecretContentType.Text) with { Description, CreatedBy, UpdatedBy }`, `_store.UpsertAsync(row, ct)`, then `_invalidator?.Invalidate(name)`. Mint target keys with `IApiKeyAdminService.CreateAsync(string name, string principal, DateTime? expiresUtc, string? notes, CancellationToken ct)`; only the returned string contains the plaintext. Grant scoped exports separately. +- Pinned `Directory.Packages.props`: Secrets 0.6.2, Secrets.Abstractions 0.6.6, Secrets.Replicator.AkkaDotNet 0.6.2, Grpc.AspNetCore/Grpc.Net.Client 2.76.0, Google.Protobuf 3.34.1. Installed 0.6.2 and 0.6.6 packages contain DLL and README but **no XML documentation**; do not infer unverified library methods from older XML. Check the pinned package README and existing call sites for any additional operation. +- `Runtime/DataConnections/LocalDataServices.cs` exposes `IDataConnectionFactory.Create(DataAuthenticatedContext, DataTarget)`; its constructor accepts the catalog provider, hub, policy, capabilities, clock and optional caller write/subscription factories. Without a factory it does not advertise the corresponding operation. `DataWriteRuntime.ForCaller(context, Func)` is public, but `LocalSubscriptionService`, `DriverHostSubscriptionDemandSource`, its `SubscriptionAcquisitionCapacity` dependency and session limits are internal. Add a narrow **public Runtime composition seam** that owns construction/lifetime; do not use `InternalsVisibleTo` for Host. `LocalCatalogCoordinator(activation, authority, Func)` and `SourceSamplePublisher(hub, Func, originClusterId)` require the same actual boot NodeId/incarnation and current role provenance as the facade. Share authority/dispatch fence, clock and process acquisition owner with write and driver-host paths. Verify Host actor construction actually receives those instances; creating disconnected singletons is insufficient. Feature remains false until fully wired. + +## Packet and test-first boundaries + +1. **Secret/trust lifecycle:** Host `Configuration/DataConnectionSecretProvisioner.cs`, `DataConnectionCredentialResolver.cs`, `DataConnectionSecretChangeHandler.cs`, `DataConnectionTrustPolicy.cs` and their four manifest Host tests. Define a narrow local bundle reader, current consumer scope/reference allowlist provider, durable monotonic version/tombstone store and credential/channel retirement notifications. On removal deny and drain before deleting an unshared reference; persist tombstones and current allowlist so an old mounted bundle cannot resurrect it after offline DB-less restart. Validate expected owner cluster and actual consumer NodeId per bundle, encrypt into local `ISecretStore`, never publish bearer in central deployment artifacts or offer an upload endpoint. Atomic replacement, encryption/store failure and partial updates must fail closed. Credential and independent trust versions retire matching channels/streams; retain dispatched write outcome observers without replay. Exercise existing Galaxy invalidation. Test two independently provisioned replicas and independent pairs, downgrade/wrong-scope/missing-secret, deletion and offline restart, and trust old/new/removal. +2. **Remote client:** Runtime `GrpcDataConnection.cs`, `DataConnectionManager.cs`, `ClusterEndpointSelector.cs`, `DataConnectionRoleAdapter.cs` and manifest `GrpcDataConnectionClientTests`, `GrpcDataEndpointSelectionTests`, `GrpcDataConsumerScopeTests`. Identity of a bounded cached channel includes endpoint, credential version and trust fingerprint. Node selection remains pinned; cluster selection authenticates capabilities and selects ready Primary, with unknown role/no primary unready and bounded backoff. Retry read/query within original causal budget; retry writes only individually typed `RejectedBeforeDispatch`, never unknown or a lost reply. Scope changes drain handles; stream epochs renew after channel/role changes. Construct realm roots from validated capability cluster identity. Confirm mapper and generated proto fields, version 1.1, age/readiness and decode/transport bounds before coding; no assumed field names. +3. **Coordinator-owned ingress and composition:** `Host/Grpc/DataConnectionGrpcService.cs`, `Configuration/DataConnectionOptions.cs`, `DataConnectionOptionsValidator.cs`, `DataConnectionAuthInterceptor.cs`, `DataConnectionEndpoints.cs`, plus Program/shared DI and Runtime public composition seam. Manifest `GrpcDataListenerTests`, `GrpcDataIngressAuthTests`, `GrpcDataServiceDispatchTests` should prove disabled mapping, listener and method admission, cookie behavior, key/pepper/authority failures, partial batches, final per-response publication gates and bounded parsing. Stream delivery must await real `WriteAsync` success before acknowledging baseline; expiry/revocation closes quiet streams. Separate unary and stream timeout policies, disable automatic write retries/hedges. Integration wire tests are P10, including real TLS/cert rotation and actual caller DI for the public NodeProbe fixture; no production network-control hook. + +Manifest H regressions: `DriverWriteBoundsBindingTests`, `ApiKeyStoreRegistrationTests`, `ApiKeyAuthenticationTests`, `SecretsPreHostContentRootSourceTests`; R role regressions `WarmRoleAuthorityTests` and `PrimaryGatePolicyTests` if role adapter changes. P10 also runs `MeshGrpcAnonymousMetadataTests`, `MeshGrpcAuthStackTests`, `MeshGrpcBoundaryTests` and the new TLS/listener wire tests. P06 focused tests and current review remain separate gates. diff --git a/docs/plans/evidence/grpc-data/p07-remote-astra-review.md b/docs/plans/evidence/grpc-data/p07-remote-astra-review.md new file mode 100644 index 000000000..d935736b6 --- /dev/null +++ b/docs/plans/evidence/grpc-data/p07-remote-astra-review.md @@ -0,0 +1,133 @@ +# P07 remote lifecycle Astra review + +**Final disposition: approved for P07.** The final reconciliation below closes the historical remote and deployment-runtime findings. The superseding full P07 run `20261116T160335.804917Z-5a4994c32d15` passed 393/393 applicable tests with zero failures/skips; Runtime passed 220/220. Later integration/scaling/full-implementation gates remain pending. + +**Initial checkpoint disposition (historical): the initial remote packet was not approved; the findings below required correction and focused evidence.** This source review covered the frozen `DataConnectionManager`, `GrpcDataConnection`, `ClusterEndpointSelector`, `DataConnectionRoleAdapter`, and their initial tests. New regression test preparation began while review continued; no new failing/passing result was inferred from test source. No builds, tests, Docker commands, or commits were run by this reviewer. The earlier coordinator run `20261116T125221.449960Z-a59846699d1c` recorded 59/59 passed, zero failed/skipped, for the initial focused packet and affected session/role tests; its run record was independently read. It did not close the new findings or establish final Host integration. + +## Findings + +### P1 — Retired channels are uncharged while physical cleanup can remain blocked + +`RetireAll` clears the entire active channel dictionary, discards each CancelAsync task, and queues a separate Channel.Dispose callback (`GrpcDataConnection.cs:70-78`). A subsequent acquisition can immediately create another channel under the same maxChannels allowance. Repeated security changes while a handler's Dispose is blocked accumulate old physical channels, callbacks, and queued disposal work without a bound tied to admission. + +Keep retired physical ownership charged until cleanup actually completes, with a bounded/coalesced retirement path and explicit admission behavior while saturated. Do not make a global lock wait for arbitrary transport disposal. Regress one allowed channel, gated handler disposal, repeated security rotations/new acquisitions, and eventual progress after releasing cleanup. A logical dictionary removal or cancellation request is not physical completion. + +### P1 — Scope revision churn admits unlimited unresolved cancellation generations + +`DataConnectionManager.ApplyScope` removes the old State, starts and discards CancelAsync, then immediately admits the replacement (`DataConnectionManager.cs:44-50`). Dispose similarly drops all states before cancellation callbacks complete; ScopeLease.Dispose has no ownership effect (`:63-76`). With maximumConnections=1, a blocked registered cancellation callback and repeated revisions create an unbounded sequence of retained old states/tasks while the active dictionary still contains only one entry. + +Give retired scope generations explicit bounded ownership through actual callback/lifetime cleanup and coalesce newer desired revisions. Retire outside the global lock while preserving immediate denial of the old generation. A replacement must not evade capacity merely by changing its revision or ID. Regress blocked cleanup, repeated same/different IDs, outstanding leases, and recovery to the latest desired revision after cleanup completes. Preserve stale-generation denial after scope removal/readdition. + +### P2 — Discovery and failover renew an item's original write budget + +The client records one batch start time but sends each item with `min(original item.RemainingBudget, remaining batch budget)` (`GrpcDataConnection.cs:249-251`). It never subtracts elapsed discovery, first-attempt, or retry-metadata time from the item's own original budget. An item with 500 ms remaining in a five-second batch can still be dispatched for another 500 ms after discovery already consumed 600 ms. + +Track each original item expiry against the same monotonic start and reduce it across all work/attempts. Do not dispatch an expired item; retain the proper no-dispatch result without preventing still-live items from progressing. Regress delayed capabilities and retry metadata with fake time, including mixed short/long item budgets and the original batch deadline. Never restart the item budget when changing endpoints or semantic preconditions for a proven rejection. + +### P2 — The receiver accepts retired-handle reuse and sample-version regressions + +Ack validation rejects collisions only with the currently active `_handles` dictionary (`GrpcDataConnection.cs:417-443`). Remove and Modify delete old entries, so a later acknowledgment can reuse a retired numeric handle/revision for another view. A late old value then passes the ordinary handle lookup. Separately, ReadAllAsync validates frame sequence and serving identity but does not track per-handle sample versions before yielding values (`:384-399`, `:454-457`). A new frame sequence with a lower sample version is therefore exposed. + +Enforce the contract's epoch-local no-reuse and monotonic value rules with bounded state and an explicit reset/admission policy when its bound is reached. Do not assume opaque handles are ordered unless that becomes an explicit negotiated contract. Regress remove/add and modify reuse, a late old value after the attempted reuse, and sample version 100 followed by 99 under the next valid frame sequence. A legitimate new stream epoch/new handle must still establish a fresh baseline. + +### P2 — Acknowledged commands retain timers and caller-owned payload graphs + +Every SendAsync stores the original caller command and starts an independent expiration task (`GrpcDataConnection.cs:350-368`). Successful acknowledgment removes only the pending dictionary entry (`:447-451`); the delay task still captures the complete command until the original timeout or stream cancellation. A healthy acknowledged burst can retain up to the lifetime command cap (100,000) worth of item lists/timers, with no pending-byte charge. The pending-count limit does not bound this already-acknowledged retention. + +The command's IReadOnlyList may also be backed by a mutable caller collection. Because pending state retains that same object, mutation after SendAsync can change later acknowledgment expectations even though different items were actually sent. + +Admit bounded owned command state before asynchronous work, copying the necessary semantic/ack identity and enforcing local count/byte limits. Release its deadline and retained state on acknowledgment or failure. A bounded shared deadline scheduler or correctly canceled per-command ownership can work; successful ACKs must not leave full payload graphs sleeping until timeout. Regress acknowledged churn with long timeouts and bounded outstanding work/bytes, plus caller collection mutation after send. Retain duplicate-command fencing without allowing unlimited historical IDs. + +## Source properties and remaining evidence + +- The selector now requires the expected cluster, explicit Node pin, ready state, and either Primary or an explicitly permitted Secondary replica read. Unknown roles deny. The role adapter delegates Warm/Hot decisions without performing an election. These helpers do not establish final Host role gating by themselves. +- Channel identity includes credential version and trust fingerprint. A generation captured before security resolution is checked before installation, which rejects a retired security snapshot. The initial test source includes rotation during resolution. Preserve this when introducing owned retirement accounting. +- Unary response envelopes and nested read samples are checked against selected provenance. Mutation retries are limited to explicit rejected items; initial lost replies become OutcomeUnknown. The implemented demotion exception accepts only an entirely rejected batch from the same node/boot. This is a conservative subset of the contract discussion, not permission to replay other items after a role mismatch. +- Original per-item budget handling above remains incorrect despite the correctly retained batch start. A passing lost-reply test does not establish all retry/deadline semantics. +- Stream count must have a receiver-owned local ceiling independent of a peer-advertised MaxStreams. A new test for this was being authored during review; its production/API repair and actual result are not claimed here. +- The initial tests mainly cover selector/scope helpers, unary fake-wire paths, and security-resolution generation. Add actual duplex fake-wire lifecycle cases for command ownership, acknowledgment timeout, handle reuse/version regression, retirement while reads/writes are blocked, and final release of stream/transport work. Cancellation that stops waiting must not release quota for still-owned physical work or allow unlimited replacements. +- Verify bounded no-ready-primary backoff, channel retirement under failure/churn, scope/revision removal, and fresh stream epochs/snapshots after role or endpoint changes at the completed connection-manager boundary. No ready-endpoint or reconnect behavior is established by an immediate one-pass selector loop alone. +- Credential/trust rotation may close the client route and produce an ambiguous result, but cannot replay or relabel an already dispatched mutation. The original origin-side bounded outcome observer must survive; final Host/remote tests must establish that composition rather than infer it from token cancellation. + +These are source findings and concrete regression requirements, not a final network/TLS/Docker review. Packet closure requires frozen repairs and actual focused results, followed by the full P07 gate and integrated source review. + +## Follow-up: physical HTTP ownership, 2026-11-16 + +The current source repairs the initial channel/scope accounting direction: retired channels remain included in channel admission until both cancellation callbacks and actual channel disposal finish; retired manager states retain their slots until cancellation completes and all scope leases release. `GrpcDataConnection.DisposeAsync` retains its scope lease until its active work, streams, and retired channels drain. These observations supersede the old implementation descriptions above; full packet evidence/disposition remains pending. + +The coordinator reported Runtime run `20261116T132916.652106Z-dca2192d7e9c` as 22 passed / 3 failed. Two failures were the deliberately unbound prepared-publication guard regressions. The ignored-HTTP-cancellation case timed out because it awaited the first unary result before releasing its intentionally blocked handler. That timeout is **not evidence that unary admission was released early**. The repaired handle/list/sample-version and original-item-budget cases passed in that reported run. This reviewer did not run the tests. + +### Unary Send/body reads: no demonstrated need for a raw HTTP tracker + +The exact pinned [grpc-dotnet v2.76.0 GrpcCall source](https://github.com/grpc/grpc-dotnet/blob/v2.76.0/src/Grpc.Net.Client/Internal/GrpcCall.cs) was independently inspected. `CancelCall` (lines 424–450) completes the overall `_callTcs` and requests cancellation but does not complete unary `_responseTcs`. `RunCall` directly awaits raw HTTP SendAsync (493–496) and, for a unary response, the body read (563–568). Its response task is completed only afterward (602/647). Current `QueryAsync` and `WriteAsync` retain `_unaryCapacity` and `_activeWork` through that actual ResponseAsync await. An ignored Send cancellation or body-read cancellation therefore keeps the current unary admission charged. Do not add a blanket HTTP wrapper on the basis of the timeout above. + +The correct regression holds the raw work, asserts the first unary task is still incomplete and another call is rejected by unary admission, then releases raw work before awaiting the first task and proves recovery. A handler's `Disposed` signal alone precedes completion of `FinishChannelRetirementAsync`; a generic capacity exception can otherwise accidentally assert the retiring-channel charge instead of the unary charge. + +### P1 — Duplex disposal can release its slot before preheaders HTTP work ends + +Current `SubscribeAsync` returns immediately after starting the duplex call (`GrpcDataConnection.cs:397–408`). `RemoteSubscription.ClosePhysicalAsync` marks `_physicalClosed` when `lifetime.Cancel` and `call.Dispose` return. With no active Send/MoveNext, this releases `_activeStreams`, although the pinned gRPC `RunCall` can still be awaiting a raw `/Subscribe` SendAsync that ignores cancellation. A MoveNext waiting for response headers does not fix this: cancellation eagerly cancels `ClientStreamReader.HttpResponseTcs`, allowing that operation to finish before raw Send ends. Repeated open/dispose on one unchanged channel can therefore exceed the configured physical stream bound. + +A narrow completion receipt is available without a raw handler/content wrapper: retain the owned stream through `call.ResponseHeadersAsync` as well as disposal and current operation counts. In the pinned source, `GetResponseHeadersCoreAsync:308` awaits the distinct `_httpResponseTcs`, which is set only after raw Send completes or throws (`RunCall:497/637`). Neither cancellation, deadline cancellation, nor Dispose eagerly completes that TCS. This proves preheaders Send completion, not body-read/write completion; keep the existing operation ownership for those phases. Require actual no-reader and preheaders-reader negative regressions, bounded replacement denial, and recovery after releasing the handler. Repair/evidence are pending. + +### P1 — Subscription discovery runs before bounded admission + +`SubscribeAsync:375–391` increments the unbounded `_activeWork` counter, then performs `SelectAsync`/GetCapabilities before reserving `_activeStreams`; it never takes `_unaryCapacity`. Concurrent subscription setup can thus launch arbitrarily many blocked capabilities HTTP operations despite both local limits being one. Reserve a bounded local stream/setup slot before discovery, validate the peer limit after discovery, and transfer that same reservation into the returned stream. Release it only after actual setup/owned transport work settles, including failure and cancellation. A deterministic regression must block capabilities discovery and prove a second setup is rejected without invoking another Send. Repair/evidence are pending. + +These two new findings are confined to duplex/setup ownership. They do not justify changing the already-held unary path, and neither the source direction nor the reported partial run constitutes full P07 approval. + +## Frozen repair checkpoint: 192 selected tests + +The reviewer independently read `20261116T134802.525866Z-44c634f2fd5c/unit/P07/run.json` and all five TRX files: **192 passed, zero failed/skipped** (Host 66, Runtime 82, Commons 41, Configuration 2, ControlPlane 1). This is a component checkpoint, not completed P07 integration. Host mapping, DI/actor composition, and deployed-scope/bundle activation remain unimplemented at this point. + +The frozen remote source now retains channel retirement through actual disposal/cancellation and manager scope retirement through callbacks plus outstanding leases. Per-item write time is reduced by elapsed discovery/attempt time. ACK expectations use an owned copy from the encoded command; retired numeric handles remain fenced with bounded history, and sample versions cannot regress. The focused cases for those changes passed. Query/discovery backoff has bounded exponential delay with jitter, security change clears it, and a bounded per-connection stream-ID/epoch fence denies reuse. The normal installed-stream path now awaits the exact pinned gRPC ResponseHeadersAsync receipt before physical-close completion; both no-reader/preheaders-reader regressions passed. Local stream reservation now precedes discovery, and its blocked-discovery regression passed. Ignored unary Send and body-read cases passed while keeping existing unary admission charged. No raw HTTP wrapper was added or is required by those cases. + +### P1 — Disposal between duplex creation and registration bypasses the new receipt + +In `SubscribeAsync`, the raw duplex call and RemoteSubscription (which captures `_headersReceipt`) are created before `_sync` is acquired to install the stream. If connection disposal wins that race, the `_disposed` branch calls `call.Dispose()` and throws. The catch disposes lifetime and the outer finally releases the setup reservation and `_activeWork`, without awaiting the constructed subscription's headers receipt. An ignored preheaders raw Send can therefore outlive all stream/scope ownership on this failure path. The passing installed-stream tests do not cover it. + +Require a deterministic after-call-creation/before-installation race with connection disposal and an ignored raw Send. Every path after raw call creation must transfer ownership to a closing subscription or retain/await its physical completion before releasing setup/scope charges. Do not wait for transport cleanup under `_sync`. Source repair and actual regression are pending. + +### P2 — Canceled command timers still capture uncharged acknowledged metadata + +`ExpireUnacknowledgedAsync(PendingCommand pending)` captures the record containing ClientIds/Removed arrays across Task.Delay. A successful ACK removes that record and releases `_pendingBytes`, then cancels/disposes the timer. Its queued cancellation continuation can still retain the record and arrays until it executes. A rapid ACK burst can therefore retain substantially more metadata than the current pending-byte allowance while only the much smaller historical command-ID charge remains. The mutable-list test establishes copying, but there is no acknowledged-churn/retained-byte regression in this checkpoint. + +Make the expiration task capture only a small command ID plus timer/identity token, using the pending dictionary to resolve live work at expiry, or retain the byte charge until the actual expiration task exits. Add deterministic delayed-cleanup/ACK-churn coverage. This is a command-state ownership issue; it does not call for a transport wrapper. Repair/evidence are pending. + +## Remote repair closure: Runtime 103/103 + +The reviewer independently read run `20261116T141626.988288Z-e977454116c3` and its TRX: **103 Runtime cases passed, zero failed/skipped**, including the two latest regressions and the earlier installed/preheaders/discovery/ignored-cancellation cases. The frozen `GrpcDataConnection` and manager repairs close the remote findings recorded above at this component boundary. + +- Failed stream installation now transfers the reservation to the created subscription even when connection disposal wins; asynchronous cleanup remains outside `_sync`, the captured headers receipt still owns preheaders raw Send, and the stream remains counted until that receipt and active operations complete. The deterministic disposal-before-install regression verifies connection disposal and scope replacement remain blocked until the raw handler is released. +- The expiry task now receives only command ID, timeout, and timer; it compares timer identity against the live dictionary entry. It does not capture PendingCommand or its item arrays across the delay. The regression delays the canceled timer continuation and uses a WeakReference to prove the acknowledged PendingCommand can be collected before that continuation resumes. + +No additional actionable defect was found in this frozen remote client/manager rereview. This is **not P07 approval**: the newly authored deployment registry/activation path was explicitly outside this review, and real Host DI, deployed scope/bundle application, final role authority, and integrated gates remain outstanding. The separately reviewed observed-role actor issue is recorded in `p07-contract-astra-review.md`. + +## Deployment-runtime source checkpoint — availability findings open + +The registry now owns one reconciliation worker, bounded desired definitions, the existing manager's active/retiring capacity, and connection retirement tasks through physical client cleanup. BeginAttempt denies routes before fallible local artifact processing, and matching attempt/generation checks prevent old asynchronous scope activation from reopening them. No additional physical-transport ownership defect was established in this inspection. The scope-store retry defect already under coordinator repair is not counted again here. + +### P2 — A transient role-read failure can permanently empty the connection manager + +Registration's coherent role capture uses TryEnter, returning Unknown on temporary dispatch-fence contention. ApplyManagerScopeLocked converts that one false eligibility observation into an empty manager scope (`DataConnectionDeploymentRuntime.cs:175–180`). ReconcileAsync can subsequently observe an active role and valid credentials but calls manager.Acquire against the still-empty scope; the denial is swallowed and no retry or scope reinstatement follows (`:277–314`). The same transient false during reconciliation can exit its only worker pass. No actual role transition need occur to wake it again. + +Keep acquisition fail-closed during contention, but reconcile the manager's desired scope after a current eligible observation and retain one bounded retry for temporary uncertainty. Regress false only on the initial eligibility read, as well as contention lasting through the first reconciliation pass; after release, the configured route must become acquirable without another artifact, credential, or role event. Source repair and observed regression results are pending. + +### Related unresolved boundary — transient credential/trust reads + +The scope retry alone does not cover ResolveAsync failures: reconciliation catches those exceptions or receives null and leaves that configured connection absent without another wake. The concrete Host credential resolver deliberately converts store exceptions into false/null, so retrying only thrown runtime exceptions is insufficient. Extend the existing owned backoff mechanism to a typed temporary resolution result or bounded retries for unresolved current entries, preserving immediate event wakeups and disarming on newer attempt/disposal. Regress a fail-once local credential/trust store read with no unrelated external event. This is part of the availability repair, not a request for per-entry tasks or extra device/network polls. + +No P07 approval is granted at this checkpoint; tests/builds were not run by the reviewer. + +## Final Runtime repair closure + +The reviewer independently verified the frozen final P07 run and all five TRXs: 392/392 passed, including Runtime 219/219. Candidate identity is reconciled in `p07-contract-astra-review.md`. Earlier Runtime 218/218 in `20261116T154535.379541Z-6ea9fe4e2f4b` established the original scope-store, transient-role, and null/exception security-resolution repairs, but did not close the subsequently discovered two-link case. + +That final case was observed failing in `20261116T155211.129165Z-316e31f82ca8` (deployment activation 22/23): rotating A during a transient false role read canceled B's manager token while retaining B as a Ready entry. The repaired ApplyManagerScopeLocked now always represents the validated configured consumer allowlist, independent of role observation. A's security change advances only A's route revision. B's lease remains current, while A retires and recovers. The same regression passes in the final gate. + +This separation does not open Standby access: reconciliation checks current role before creating a client, TryAcquire checks it before issuing a handle, and every borrowed-operation boundary checks it again. The raw manager/client entry remains private. Explicit NotifyConsumerRoleChanged still clears all entries and advances every route revision to drain prior physical work; BeginAttempt still applies an empty manager scope before parsing a newer artifact. Existing actual owner/role and Warm tests remain green. + +One owned timer and one coalesced worker now recover current unresolved local material and transient role/scope reads with bounded backoff. Null and thrown security results are both covered; newer attempts and disposal disarm the timer, and delayed results must match the latest generation. No per-entry retry task or device poll was added. Existing physical channel/stream/header-receipt/cancellation accounting and command metadata ownership remain verified by the full selected gate. + +No actionable remote/runtime finding remains for P07. This approval does not claim deployed network failover, TLS behavior, CLI interoperability, or capacity measurements; those remain P10/P11, with final integrated review in P12. + +The later pre-commit credential-expiry lease finding is closed in the superseding 393-case candidate. Browse branch leases and continuations now share a duration capped by the original target credential's remaining lifetime; GetMetadata objects carry no standalone lease. Source identity, actual RED, all five final TRXs, and the reaffirmed approval are recorded in `p07-contract-astra-review.md`. No remote transport/lifetime source changed for that narrow repair. diff --git a/docs/plans/evidence/grpc-data/p07-wiring-preparation.md b/docs/plans/evidence/grpc-data/p07-wiring-preparation.md new file mode 100644 index 000000000..c1f612d49 --- /dev/null +++ b/docs/plans/evidence/grpc-data/p07-wiring-preparation.md @@ -0,0 +1,37 @@ +# P07 wiring preparation — historical checklist + +This checklist predates the production wiring. Program/Kestrel, shared actor/DI dependencies, local bundle loading, observed-role owners and deployed-scope activation have since been implemented in the P07 working tree. The sections below preserve the original obligations; they do not describe current missing files. Current verification and unresolved review findings are recorded in [the execution ledger](README.md) and [Astra contract review](p07-contract-astra-review.md). P07 remains in progress and has no final approval. + +## Shared local composition + +Use actual `IClusterRoleInfo.LocalNode.Value` and `ClusterId`, plus one process boot incarnation. Register one DataWriteDispatchFence before DataPlaneAuthorityState and RedundancyRoleView resolve, so their optional constructor arguments use that same fence. Share TimeProvider.System registration, CatalogActivation, LocalCatalogCoordinator, hub, SourceSamplePublisher, DataOperationPolicy, DataCapabilitiesProvider, DataWriteRuntime, DriverWriteBounds and SubscriptionAcquisitionCapacity. + +RedundancyRoleView currently exposes only primary verdict/generation (generation zero at startup). Need the actual Primary/Secondary/Unknown role alongside its existing verdict, published from the SAME DriverHostActor handler/fence; do not infer Secondary from arbitrary false, or invent an election. Unknown startup cannot advertise ready. Existing WarmRoleAuthority/PrimaryGate tests become applicable if modified. + +Runtime ServiceCollectionExtensions currently passes NONE of SourceSamplePublisher, LocalCatalogCoordinator, DataWriteRuntime, SubscriptionAcquisitionCapacity or writeClock to DriverHostActor.Props. Add the actual shared instances, not disconnected singletons. Those optional Props parameters already exist. Root owns this file and Program. + +LocalDataRuntimeComposition is now public and worker-owned: it receives an ACTUAL local host IActorRef and the shared dependencies; it owns the one demand registry/bridge/transport capacity and exposes Services/AcquisitionCapacity. Construct after host registration. A stable Host IDataConnectionFactory wrapper should lazily resolve this composition inside Create, so the startup window returns an honest Unavailable instead of failing gRPC service activation. DataWriteRuntime itself must exist before Host actor construction and can resolve its host lazily through ActorRegistry. + +## Dedicated ingress + +Host options/auth/middleware, all six RPC implementations, private-buffer contextual binding and PreparedDataSubscription exist but are UNMAPPED. Extend the SAME Program Kestrel binding reconstruction block: adding a Listen call otherwise drops URLS/HTTP_PORTS UI bindings. Use dedicated HTTPS HTTP/2, configured certificate plus private key, explicit host and actual local port checks. Preserve mesh/UI binding behavior; reject conflicts. Current legacy block refuses to replay existing HTTPS bindings because certificate settings are not modeled. Do not silently disable an explicitly enabled data service or fall back to plaintext. + +Map only when enabled, with AllowAnonymous metadata so AdminUI cookies do not intercept authenticated RPCs; actual API-key middleware/interceptor remains fail-closed. Put admission before routing/auth parsing so unauthorized/oversized/concurrent work is bounded before protobuf allocation. Configure per-service MaxReceiveMessageSize and MaxSendMessageSize. Real service execution sets NoCompress, since ASP.NET discovery passes null service and discards generated binder handler wrappers. Registered marshaller serializes privately and checks capture-bound authority immediately before real Complete(byte[]); this is buffer handoff, not client receipt. + +Finish finite unary pre-parse lifetime in middleware (own linked RequestAborted/deadline through real HTTP completion). Execute currently retains its own timeout CTS until response cleanup and its marshaller guard rechecks that token after validation. Duplex initial capability timeout is separate; subscription uses actual context cancellation and P06 finite session/pre-Open lifetime. Prepared frame owns encoded bytes through actual Write completion; Runtime now binds PendingDelivery.Gate exactly once across the framework StartAsync window. Do not commit cursors/baselines/Ack effects inside the marshaller. + +## Deployed scope and local bundles + +Central worker owns authoritative DataConnectionScopeVersion (exact PascalCase artifact root + DraftSnapshot property), bounded singleton row and sealing transaction. Lock before reading the validated draft; commit row + artifact before dispatch. No-op scope stable; A-to-B-to-A increments; empty removals positive; drift/pure composition read-only. Root still needs generated EF migration and model checks; never apply against shared SQL. + +Runtime artifact parser and actual DriverHost/catalog path must publish validated deployed connection scope, including EMPTY/legacy cases, into a bounded latest-desired controller. Durable central version, never process epoch/time/hash ordering. Stale/missing version cannot overwrite an established floor or reactivate old imports. Desired scope must synchronously drain/deny prior manager epochs before asynchronous local store work; readiness only after floor/allowlist persisted. A newer desired scope must preempt old completion so it cannot enable old connections. Root must implement this seam; no callback currently exists. + +Suggested controller/worker split (not yet finalized): synchronous desired generation + immediate manager drain, bounded latest-item background worker to persist credential/trust scopes and load restricted mounted bundles, then atomically enable only the still-current scope. Local origin catalog should fail closed during the allowlist durability barrier; missing individual outbound secrets/trust should mark THOSE imports AuthFailed, not pretend they are ready. Keep unrelated committed material when scope advances. Bundle removal alone is not revocation. Root must decide exact activation seam in LocalCatalogCoordinator/DriverHostActor without blocking actor callbacks or holding dispatch fence across I/O. + +Credential worker APIs now require exact persisted ScopeVersion on each bundle/trust update. Scope generation allows safe retired-ID history reclamation. Security provider emits scoped retirement notifications and separately versioned trust fingerprints. Compose SecretChangeSignallingInvalidator with existing inner/Galaxy callbacks even if one consumer throws. Integrate actual local store/cipher/cache invalidator and a bounded atomic bundle reader/watch path. Check successful identical bundle replay/restart semantics: provisioner currently rejects complete same-version apply; mounted already-applied bundles must not break offline restart or silently accept changed same-version material. No secret upload endpoint or central bearer. + +Trust material also needs a restricted local provisioning source (versioned per-consumer CA bundle or equivalent operator-mounted inputs), independent of credentials and scoped to current generation. Root options currently include only CredentialBundlePath and server certificate paths; trust bundle consumption is not wired. Trust rotation must retire channels/streams without replaying in-flight writes; rolling restart for server certificate rotation, no unsupported hot reload. + +## Validation still required + +Add real Host service-dispatch/middleware regressions beyond the current capability fixture, finite deadline/cleanup and late serialized Read source proof, actual DI/role/actor composition tests, new scope parsing/stale/empty/durability tests, central transactional concurrency/fault/no-op tests, migration checks. Per-phase runner uses only applicable selectors; no full solution run yet. Real TLS/listener wire tests belong Host.IntegrationTests/P10. Docker/OPC UA CLI integration, scaling benchmarks and full solution/Astra final remain P10/P11/P12. diff --git a/scripts/validation/grpc-data/unit-phases.json b/scripts/validation/grpc-data/unit-phases.json index 916176f90..4aea49d0c 100644 --- a/scripts/validation/grpc-data/unit-phases.json +++ b/scripts/validation/grpc-data/unit-phases.json @@ -380,7 +380,11 @@ "GrpcDataTrustRotationTests", "GrpcDataListenerTests", "GrpcDataIngressAuthTests", - "GrpcDataServiceDispatchTests" + "GrpcDataServiceDispatchTests", + "GrpcDataPublicationHandoffTests", + "GrpcDataScopeActivationTests", + "GrpcDataBundleLifecycleTests", + "GrpcDataRuntimeRegistrationTests" ], "existing_classes": [ "DriverWriteBoundsBindingTests", @@ -391,13 +395,69 @@ }, { "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj", - "filter": "(Feature=GrpcData&Phase=P07)", + "filter": "(Feature=GrpcData&Phase=P07)|FullyQualifiedName~.GrpcDataLocalConnectionTests.|FullyQualifiedName~.GrpcDataCachedReadTests.|FullyQualifiedName~.GrpcDataStreamOrderingTests.|FullyQualifiedName~.GrpcDataRecoveryAdmissionTests.|FullyQualifiedName~.WarmRoleAuthorityTests.|FullyQualifiedName~.PrimaryGatePolicyTests.|FullyQualifiedName~.DriverHostActorPrimaryRoleSourceTests.|FullyQualifiedName~.GrpcDataCatalogStagingTests.|FullyQualifiedName~.OpcUaPublishActorWarmTests.|FullyQualifiedName~.OpcUaPublishActorEndpointStateTests.|FullyQualifiedName~.GrpcDataDriverOutcomeTests.|FullyQualifiedName~.GrpcDataWriteAdmissionTests.", "new_classes": [ "GrpcDataConnectionClientTests", "GrpcDataEndpointSelectionTests", - "GrpcDataConsumerScopeTests" + "GrpcDataConsumerScopeTests", + "GrpcDataLocalRoleTests", + "GrpcDataTransportPublicationTests", + "GrpcDataLocalCompositionTests", + "GrpcDataDeploymentActivationTests" ], - "existing_classes": [] + "existing_classes": [ + "GrpcDataLocalConnectionTests", + "GrpcDataCachedReadTests", + "GrpcDataStreamOrderingTests", + "GrpcDataRecoveryAdmissionTests", + "WarmRoleAuthorityTests", + "PrimaryGatePolicyTests", + "DriverHostActorPrimaryRoleSourceTests", + "GrpcDataCatalogStagingTests", + "OpcUaPublishActorWarmTests", + "OpcUaPublishActorEndpointStateTests", + "GrpcDataDriverOutcomeTests", + "GrpcDataWriteAdmissionTests" + ] + }, + { + "project": "tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/ZB.MOM.WW.OtOpcUa.Commons.Tests.csproj", + "filter": "FullyQualifiedName~.GrpcDataResponseServingTests.|FullyQualifiedName~.GrpcDataAgeReadinessCodecTests.|FullyQualifiedName~.GrpcDataCompactCodecTests.|FullyQualifiedName~.GrpcDataProtoContractTests.|FullyQualifiedName~.GrpcDataCodecTests.", + "new_classes": [ + "GrpcDataResponseServingTests" + ], + "existing_classes": [ + "GrpcDataAgeReadinessCodecTests", + "GrpcDataCompactCodecTests", + "GrpcDataProtoContractTests", + "GrpcDataCodecTests" + ] + }, + { + "project": "tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/ZB.MOM.WW.OtOpcUa.Configuration.Tests.csproj", + "filter": "FullyQualifiedName~.GrpcDataScopeRevisionTests.|FullyQualifiedName~.DraftSnapshotFactoryTests.|FullyQualifiedName~.GrpcDataSchemaModelTests.|FullyQualifiedName~.GrpcDataConfigurationTests.|FullyQualifiedName~.GrpcDataMappingValidationTests.", + "new_classes": [ + "GrpcDataScopeRevisionTests" + ], + "existing_classes": [ + "DraftSnapshotFactoryTests", + "GrpcDataSchemaModelTests", + "GrpcDataConfigurationTests", + "GrpcDataMappingValidationTests" + ] + }, + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=P07)|FullyQualifiedName~.ConfigComposerTests.|FullyQualifiedName~.AdminOperationsActorSingleSnapshotTests.|FullyQualifiedName~.AdminOperationsActorTests.StartDeployment_", + "new_classes": [ + "GrpcDataScopeArtifactTests", + "GrpcDataScopeSealingTests" + ], + "existing_classes": [ + "ConfigComposerTests", + "AdminOperationsActorSingleSnapshotTests", + "AdminOperationsActorTests" + ] } ], "P08": [ diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs index fea2ab05d..ed9326895 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs @@ -110,6 +110,7 @@ public static class DataProtoMapper Role = x.Role, CatalogEpoch = x.CatalogEpoch, AuthorityEpoch = x.AuthorityEpoch, + ServingGeneration = x.ServingGeneration, }; public static ServingIdentity DecodeServing(W.Serving x) @@ -120,7 +121,8 @@ public static class DataProtoMapper x.Incarnation, x.Role, x.CatalogEpoch, - x.AuthorityEpoch + x.AuthorityEpoch, + x.ServingGeneration ); identity.Validate(); return identity; @@ -985,6 +987,7 @@ public static class DataProtoMapper CompactBatches = x.CompactBatches, CompactCodecVersion = x.CompactCodecVersion, SubscriptionAgeReadiness = x.SubscriptionAgeReadiness, + ResponseServingIdentity = x.ResponseServingIdentity, Limits = new W.Limits { MaxPageItems = l.MaxPageItems, @@ -1049,7 +1052,8 @@ public static class DataProtoMapper x.CompactBatches, x.CompactCodecVersion, x.ClusterId, - x.SubscriptionAgeReadiness + x.SubscriptionAgeReadiness, + x.ResponseServingIdentity ); result.Validate(); return result; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto index 22aa9a9f8..2a8180c31 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto @@ -69,6 +69,7 @@ message Serving { string role = 3; int64 catalog_epoch = 4; int64 authority_epoch = 5; + int64 serving_generation = 6; } message Sample { TypedValue value = 1; @@ -111,6 +112,7 @@ message CapabilitiesResponse { int32 compact_codec_version = 9; string cluster_id = 10; bool subscription_age_readiness = 11; + bool response_serving_identity = 12; } message Metadata { View view = 1; @@ -145,6 +147,7 @@ message BrowseResponse { bool complete = 4; optional string continuation = 5; Lease lease = 6; + Serving serving = 7; } message MetadataRequest { repeated View views = 1; @@ -156,7 +159,7 @@ message MetadataResult { Metadata value = 3; optional string diagnostic = 4; } -message MetadataResponse { repeated MetadataResult items = 1; } +message MetadataResponse { repeated MetadataResult items = 1; Serving serving = 2; } message ReadItem { string correlation_id = 1; View view = 2; @@ -174,7 +177,7 @@ message ReadResult { Sample sample = 5; optional string diagnostic = 6; } -message ReadResponse { repeated ReadResult items = 1; } +message ReadResponse { repeated ReadResult items = 1; Serving serving = 2; } message WriteItem { string correlation_id = 1; string operation_id = 2; @@ -194,7 +197,7 @@ message WriteResult { uint32 status_code = 3; optional string diagnostic = 4; } -message WriteResponse { repeated WriteResult items = 1; } +message WriteResponse { repeated WriteResult items = 1; Serving serving = 2; } message Handle { string subscription_id = 1; int64 stream_epoch = 2; @@ -291,6 +294,7 @@ message SubscriptionFrame { string subscription_id = 1; int64 stream_epoch = 2; int64 sequence = 3; + Serving serving = 8; oneof frame { Ack ack = 4; Control control = 5; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/DataConnectionScopeState.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/DataConnectionScopeState.cs new file mode 100644 index 000000000..56eb8b8aa --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/DataConnectionScopeState.cs @@ -0,0 +1,10 @@ +namespace ZB.MOM.WW.OtOpcUa.Configuration.Entities; + +/// The singleton authoritative revision of the effective outbound data connection scope. +public sealed class DataConnectionScopeState +{ + public int Id { get; set; } = 1; + public long ScopeVersion { get; set; } + public string? Fingerprint { get; set; } + public byte[] RowVersion { get; set; } = []; +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261116135035_AddDataConnectionScopeState.Designer.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261116135035_AddDataConnectionScopeState.Designer.cs new file mode 100644 index 000000000..f2532bdf8 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261116135035_AddDataConnectionScopeState.Designer.cs @@ -0,0 +1,1979 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using ZB.MOM.WW.OtOpcUa.Configuration; + +#nullable disable + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations +{ + [DbContext(typeof(OtOpcUaConfigDbContext))] + [Migration("20261116135035_AddDataConnectionScopeState")] + partial class AddDataConnectionScopeState + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.7") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("FriendlyName") + .HasColumnType("nvarchar(max)"); + + b.Property("Xml") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("DataProtectionKeys", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ApiKey", b => + { + b.Property("ApiKeyRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ApiKeyId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CreatedUtc") + .HasColumnType("datetime2"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("ExpiresUtc") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Notes") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Principal") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SecretHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("ApiKeyRowId"); + + b.HasIndex("ApiKeyId") + .IsUnique() + .HasDatabaseName("UX_ApiKey_ApiKeyId"); + + b.HasIndex("Principal") + .HasDatabaseName("IX_ApiKey_Principal"); + + b.ToTable("ApiKey", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", b => + { + b.Property("NodeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("AkkaPort") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(4053); + + b.Property("ApplicationUri") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("DashboardPort") + .HasColumnType("int"); + + b.Property("DriverConfigOverridesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GrpcPort") + .HasColumnType("int"); + + b.Property("Host") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("LastSeenAt") + .HasColumnType("datetime2(3)"); + + b.Property("MaintenanceMode") + .HasColumnType("bit"); + + b.Property("OpcUaPort") + .HasColumnType("int"); + + b.Property("ServiceLevelBase") + .HasColumnType("tinyint"); + + b.HasKey("NodeId"); + + b.HasIndex("ApplicationUri") + .IsUnique() + .HasDatabaseName("UX_ClusterNode_ApplicationUri"); + + b.HasIndex("ClusterId") + .HasDatabaseName("IX_ClusterNode_ClusterId"); + + b.ToTable("ClusterNode", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNodeCredential", b => + { + b.Property("CredentialId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("NodeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RotatedAt") + .HasColumnType("datetime2(3)"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.HasKey("CredentialId"); + + b.HasIndex("Kind", "Value") + .IsUnique() + .HasDatabaseName("UX_ClusterNodeCredential_Value") + .HasFilter("[Enabled] = 1"); + + b.HasIndex("NodeId", "Enabled") + .HasDatabaseName("IX_ClusterNodeCredential_NodeId"); + + b.ToTable("ClusterNodeCredential", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ConfigAuditLog", b => + { + b.Property("AuditId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("AuditId")); + + b.Property("ClusterId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CorrelationId") + .HasColumnType("uniqueidentifier"); + + b.Property("DetailsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("EventId") + .HasColumnType("uniqueidentifier"); + + b.Property("EventType") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("GenerationId") + .HasColumnType("bigint"); + + b.Property("NodeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Outcome") + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("Principal") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Timestamp") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.HasKey("AuditId"); + + b.HasIndex("EventId") + .IsUnique() + .HasDatabaseName("UX_ConfigAuditLog_EventId") + .HasFilter("[EventId] IS NOT NULL"); + + b.HasIndex("GenerationId") + .HasDatabaseName("IX_ConfigAuditLog_Generation") + .HasFilter("[GenerationId] IS NOT NULL"); + + b.HasIndex("ClusterId", "Timestamp") + .IsDescending(false, true) + .HasDatabaseName("IX_ConfigAuditLog_Cluster_Time"); + + b.ToTable("ConfigAuditLog", null, t => + { + t.HasCheckConstraint("CK_ConfigAuditLog_DetailsJson_IsJson", "DetailsJson IS NULL OR ISJSON(DetailsJson) = 1"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ConfigEdit", b => + { + b.Property("EditId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("EditedAtUtc") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("EditedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("EntityId") + .HasColumnType("uniqueidentifier"); + + b.Property("EntityType") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ExecutionId") + .HasColumnType("uniqueidentifier"); + + b.Property("FieldsJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("SourceNode") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("EditId"); + + b.HasIndex("EditedAtUtc") + .HasDatabaseName("IX_ConfigEdit_EditedAt"); + + b.HasIndex("ExecutionId") + .HasDatabaseName("IX_ConfigEdit_Execution") + .HasFilter("[ExecutionId] IS NOT NULL"); + + b.HasIndex("EntityType", "EntityId") + .HasDatabaseName("IX_ConfigEdit_Entity"); + + b.ToTable("ConfigEdit", null, t => + { + t.HasCheckConstraint("CK_ConfigEdit_FieldsJson_IsJson", "ISJSON(FieldsJson) = 1"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnection", b => + { + b.Property("DataConnectionRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AllowedOperations") + .HasColumnType("int"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Consistency") + .HasColumnType("int"); + + b.PrimitiveCollection("ConsumerNodeIds") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DataConnectionId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.PrimitiveCollection("EligibleTargetNodeIds") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.PrimitiveCollection("Endpoints") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ExpectedClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ExpectedNodeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("MaxBatchItems") + .HasColumnType("int"); + + b.Property("MaxMessageBytes") + .HasColumnType("int"); + + b.Property("MaxMonitoredItems") + .HasColumnType("int"); + + b.Property("MaxPageItems") + .HasColumnType("int"); + + b.Property("MaxPendingBytes") + .HasColumnType("bigint"); + + b.Property("MaxStreams") + .HasColumnType("int"); + + b.Property("Revision") + .HasColumnType("bigint"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SecretReference") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("SecretScopeClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("TargetMode") + .HasColumnType("int"); + + b.Property("TimeoutMilliseconds") + .HasColumnType("int"); + + b.HasKey("DataConnectionRowId"); + + b.HasIndex("ClusterId"); + + b.HasIndex("DataConnectionId") + .IsUnique() + .HasFilter("[DataConnectionId] IS NOT NULL"); + + b.ToTable("DataConnection", null, t => + { + t.HasCheckConstraint("CK_DataConnection_Limits", "[Revision] > 0 AND [TimeoutMilliseconds] > 0 AND [MaxBatchItems] > 0 AND [MaxPageItems] > 0 AND [MaxMessageBytes] > 0 AND [MaxStreams] > 0 AND [MaxMonitoredItems] > 0 AND [MaxPendingBytes] > 0"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnectionScopeState", b => + { + b.Property("Id") + .HasColumnType("int"); + + b.Property("Fingerprint") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScopeVersion") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.ToTable("DataConnectionScopeState", null, t => + { + t.HasCheckConstraint("CK_DataConnectionScopeState_Singleton", "[Id] = 1 AND [ScopeVersion] >= 0"); + }); + + b.HasData( + new + { + Id = 1, + ScopeVersion = 0L + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataExport", b => + { + b.Property("DataExportRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AllowedOperations") + .HasColumnType("int"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DataExportId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("MaxBatchItems") + .HasColumnType("int"); + + b.Property("MaxMonitoredItems") + .HasColumnType("int"); + + b.Property("MaxPageItems") + .HasColumnType("int"); + + b.Property("MaxStreams") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Realm") + .HasColumnType("int"); + + b.Property("Revision") + .HasColumnType("bigint"); + + b.Property("RootEntityId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RootKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("DataExportRowId"); + + b.HasIndex("ClusterId"); + + b.HasIndex("DataExportId") + .IsUnique() + .HasFilter("[DataExportId] IS NOT NULL"); + + b.ToTable("DataExport", null, t => + { + t.HasCheckConstraint("CK_DataExport_Limits", "[Revision] > 0 AND [MaxBatchItems] > 0 AND [MaxPageItems] > 0 AND [MaxMonitoredItems] > 0 AND [MaxStreams] > 0"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Deployment", b => + { + b.Property("DeploymentId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ArtifactBlob") + .IsRequired() + .HasColumnType("varbinary(max)"); + + b.Property("CreatedAtUtc") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("FailureReason") + .HasMaxLength(2048) + .HasColumnType("nvarchar(2048)"); + + b.Property("RevisionHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SealedAtUtc") + .HasColumnType("datetime2(3)"); + + b.Property("Status") + .HasColumnType("int"); + + b.HasKey("DeploymentId"); + + b.HasIndex("CreatedAtUtc") + .HasDatabaseName("IX_Deployment_CreatedAt"); + + b.HasIndex("Status") + .HasDatabaseName("IX_Deployment_Status"); + + b.ToTable("Deployment", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Device", b => + { + b.Property("DeviceRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("DeviceConfig") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DeviceId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DriverInstanceId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("DeviceRowId"); + + b.HasIndex("DeviceId") + .IsUnique() + .HasDatabaseName("UX_Device_LogicalId") + .HasFilter("[DeviceId] IS NOT NULL"); + + b.HasIndex("DriverInstanceId") + .HasDatabaseName("IX_Device_Driver"); + + b.HasIndex("DriverInstanceId", "Name") + .IsUnique() + .HasDatabaseName("UX_Device_Driver_Name"); + + b.ToTable("Device", null, t => + { + t.HasCheckConstraint("CK_Device_DeviceConfig_IsJson", "ISJSON(DeviceConfig) = 1"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DriverInstance", b => + { + b.Property("DriverInstanceRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DriverConfig") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DriverInstanceId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DriverType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RawFolderId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ResilienceConfig") + .HasColumnType("nvarchar(max)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("DriverInstanceRowId"); + + b.HasIndex("ClusterId") + .HasDatabaseName("IX_DriverInstance_Cluster"); + + b.HasIndex("DriverInstanceId") + .IsUnique() + .HasDatabaseName("UX_DriverInstance_LogicalId") + .HasFilter("[DriverInstanceId] IS NOT NULL"); + + b.HasIndex("RawFolderId") + .HasDatabaseName("IX_DriverInstance_RawFolder"); + + b.HasIndex("ClusterId", "Name") + .IsUnique() + .HasDatabaseName("UX_DriverInstance_ClusterRoot_Name") + .HasFilter("[RawFolderId] IS NULL"); + + b.HasIndex("ClusterId", "RawFolderId", "Name") + .IsUnique() + .HasDatabaseName("UX_DriverInstance_Folder_Name") + .HasFilter("[RawFolderId] IS NOT NULL"); + + b.ToTable("DriverInstance", null, t => + { + t.HasCheckConstraint("CK_DriverInstance_DriverConfig_IsJson", "ISJSON(DriverConfig) = 1"); + + t.HasCheckConstraint("CK_DriverInstance_ResilienceConfig_IsJson", "ResilienceConfig IS NULL OR ISJSON(ResilienceConfig) = 1"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Equipment", b => + { + b.Property("EquipmentRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AssetLocation") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("DeviceManualUri") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("EquipmentClassRef") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("EquipmentId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("EquipmentUuid") + .HasColumnType("uniqueidentifier"); + + b.Property("HardwareRevision") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("MachineCode") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Manufacturer") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ManufacturerUri") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Model") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SAPID") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("SerialNumber") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("SoftwareRevision") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("UnsLineId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("YearOfConstruction") + .HasColumnType("smallint"); + + b.Property("ZTag") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("EquipmentRowId"); + + b.HasIndex("EquipmentId") + .IsUnique() + .HasDatabaseName("UX_Equipment_LogicalId") + .HasFilter("[EquipmentId] IS NOT NULL"); + + b.HasIndex("EquipmentUuid") + .IsUnique() + .HasDatabaseName("UX_Equipment_Uuid"); + + b.HasIndex("MachineCode") + .HasDatabaseName("IX_Equipment_MachineCode"); + + b.HasIndex("SAPID") + .HasDatabaseName("IX_Equipment_SAPID") + .HasFilter("[SAPID] IS NOT NULL"); + + b.HasIndex("UnsLineId") + .HasDatabaseName("IX_Equipment_Line"); + + b.HasIndex("ZTag") + .HasDatabaseName("IX_Equipment_ZTag") + .HasFilter("[ZTag] IS NOT NULL"); + + b.HasIndex("UnsLineId", "Name") + .IsUnique() + .HasDatabaseName("UX_Equipment_LinePath"); + + b.ToTable("Equipment", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ExternalIdReservation", b => + { + b.Property("ReservationId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("EquipmentUuid") + .HasColumnType("uniqueidentifier"); + + b.Property("FirstPublishedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("FirstPublishedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("LastPublishedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("ReleaseReason") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("ReleasedAt") + .HasColumnType("datetime2(3)"); + + b.Property("ReleasedBy") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("ReservationId"); + + b.HasIndex("EquipmentUuid") + .HasDatabaseName("IX_ExternalIdReservation_Equipment"); + + b.HasIndex("Kind", "Value") + .IsUnique() + .HasDatabaseName("UX_ExternalIdReservation_KindValue_Active") + .HasFilter("[ReleasedAt] IS NULL"); + + b.ToTable("ExternalIdReservation", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.LdapGroupRoleMapping", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClusterId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CreatedAtUtc") + .HasColumnType("datetime2(3)"); + + b.Property("IsSystemWide") + .HasColumnType("bit"); + + b.Property("LdapGroup") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Notes") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Id"); + + b.HasIndex("ClusterId"); + + b.HasIndex("LdapGroup") + .HasDatabaseName("IX_LdapGroupRoleMapping_Group"); + + b.HasIndex("LdapGroup", "ClusterId") + .IsUnique() + .HasDatabaseName("UX_LdapGroupRoleMapping_Group_Cluster") + .HasFilter("[ClusterId] IS NOT NULL"); + + b.ToTable("LdapGroupRoleMapping", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.NodeAcl", b => + { + b.Property("NodeAclRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("NodeAclId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Notes") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PermissionFlags") + .HasColumnType("int"); + + b.Property("Principal") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScopeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ScopeKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("NodeAclRowId"); + + b.HasIndex("ClusterId") + .HasDatabaseName("IX_NodeAcl_Cluster"); + + b.HasIndex("NodeAclId") + .IsUnique() + .HasDatabaseName("UX_NodeAcl_LogicalId") + .HasFilter("[NodeAclId] IS NOT NULL"); + + b.HasIndex("Principal") + .HasDatabaseName("IX_NodeAcl_Principal"); + + b.HasIndex("ScopeKind", "ScopeId") + .HasDatabaseName("IX_NodeAcl_Scope") + .HasFilter("[ScopeId] IS NOT NULL"); + + b.HasIndex("ClusterId", "Principal", "ScopeKind", "ScopeId") + .IsUnique() + .HasDatabaseName("UX_NodeAcl_PrincipalScope") + .HasFilter("[ScopeId] IS NOT NULL"); + + b.ToTable("NodeAcl", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.NodeDeploymentState", b => + { + b.Property("NodeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DeploymentId") + .HasColumnType("uniqueidentifier"); + + b.Property("AppliedAtUtc") + .HasColumnType("datetime2(3)"); + + b.Property("FailureReason") + .HasMaxLength(2048) + .HasColumnType("nvarchar(2048)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("StartedAtUtc") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("Status") + .HasColumnType("int"); + + b.HasKey("NodeId", "DeploymentId"); + + b.HasIndex("DeploymentId") + .HasDatabaseName("IX_NodeDeploymentState_Deployment"); + + b.HasIndex("Status") + .HasDatabaseName("IX_NodeDeploymentState_Status"); + + b.ToTable("NodeDeploymentState", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.PollGroup", b => + { + b.Property("PollGroupRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("DriverInstanceId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("IntervalMs") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PollGroupId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("PollGroupRowId"); + + b.HasIndex("DriverInstanceId") + .HasDatabaseName("IX_PollGroup_Driver"); + + b.HasIndex("PollGroupId") + .IsUnique() + .HasDatabaseName("UX_PollGroup_LogicalId") + .HasFilter("[PollGroupId] IS NOT NULL"); + + b.ToTable("PollGroup", null, t => + { + t.HasCheckConstraint("CK_PollGroup_IntervalMs_Min", "IntervalMs >= 50"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.RawFolder", b => + { + b.Property("RawFolderRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ParentRawFolderId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RawFolderId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.HasKey("RawFolderRowId"); + + b.HasIndex("ClusterId") + .HasDatabaseName("IX_RawFolder_Cluster"); + + b.HasIndex("RawFolderId") + .IsUnique() + .HasDatabaseName("UX_RawFolder_LogicalId") + .HasFilter("[RawFolderId] IS NOT NULL"); + + b.HasIndex("ClusterId", "Name") + .IsUnique() + .HasDatabaseName("UX_RawFolder_ClusterRoot_Name") + .HasFilter("[ParentRawFolderId] IS NULL"); + + b.HasIndex("ClusterId", "ParentRawFolderId", "Name") + .IsUnique() + .HasDatabaseName("UX_RawFolder_Parent_Name") + .HasFilter("[ParentRawFolderId] IS NOT NULL"); + + b.ToTable("RawFolder", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.RemoteNamespaceMapping", b => + { + b.Property("RemoteNamespaceMappingRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AllowedOperations") + .HasColumnType("int"); + + b.Property("BranchName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.PrimitiveCollection("ConsumerNodeIds") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DataConnectionId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("ExpectedArrayElementKind") + .HasColumnType("int"); + + b.Property("ExpectedValueKind") + .HasColumnType("int"); + + b.Property("LocalParentId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("LocalParentKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("MaxProjectionDepth") + .HasColumnType("int"); + + b.Property("MaxProjectionNodes") + .HasColumnType("int"); + + b.Property("MetadataLeaseMilliseconds") + .HasColumnType("int"); + + b.Property("PublishingIntervalMilliseconds") + .HasColumnType("int"); + + b.Property("Realm") + .HasColumnType("int"); + + b.Property("RemoteIdentifier") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RemoteIdentifierKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("RemoteNamespaceMappingId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RemoteNamespaceUri") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RemoteRealm") + .HasColumnType("int"); + + b.Property("RemoteRootEntityId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Revision") + .HasColumnType("bigint"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SamplingIntervalMilliseconds") + .HasColumnType("int"); + + b.Property("StaleTimeoutMilliseconds") + .HasColumnType("int"); + + b.Property("WriteThrough") + .HasColumnType("bit"); + + b.HasKey("RemoteNamespaceMappingRowId"); + + b.HasIndex("RemoteNamespaceMappingId") + .IsUnique() + .HasFilter("[RemoteNamespaceMappingId] IS NOT NULL"); + + b.HasIndex("ClusterId", "Realm", "LocalParentKind", "LocalParentId", "BranchName") + .IsUnique(); + + b.ToTable("RemoteNamespaceMapping", null, t => + { + t.HasCheckConstraint("CK_RemoteNamespaceMapping_Limits", "[Revision] > 0 AND [MaxProjectionNodes] > 0 AND [MaxProjectionDepth] > 0 AND [MetadataLeaseMilliseconds] > 0 AND [StaleTimeoutMilliseconds] > 0 AND [SamplingIntervalMilliseconds] > 0 AND [PublishingIntervalMilliseconds] > 0"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Script", b => + { + b.Property("ScriptRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("Language") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScriptId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("SourceCode") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("SourceHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("ScriptRowId"); + + b.HasIndex("ScriptId") + .IsUnique() + .HasDatabaseName("UX_Script_LogicalId") + .HasFilter("[ScriptId] IS NOT NULL"); + + b.HasIndex("SourceHash") + .HasDatabaseName("IX_Script_SourceHash"); + + b.ToTable("Script", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ScriptedAlarm", b => + { + b.Property("ScriptedAlarmRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AlarmType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("EquipmentId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("HistorizeToAveva") + .HasColumnType("bit"); + + b.Property("MessageTemplate") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PredicateScriptId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Retain") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScriptedAlarmId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Severity") + .HasColumnType("int"); + + b.HasKey("ScriptedAlarmRowId"); + + b.HasIndex("PredicateScriptId") + .HasDatabaseName("IX_ScriptedAlarm_Script"); + + b.HasIndex("ScriptedAlarmId") + .IsUnique() + .HasDatabaseName("UX_ScriptedAlarm_LogicalId") + .HasFilter("[ScriptedAlarmId] IS NOT NULL"); + + b.HasIndex("EquipmentId", "Name") + .IsUnique() + .HasDatabaseName("UX_ScriptedAlarm_EquipmentPath"); + + b.ToTable("ScriptedAlarm", null, t => + { + t.HasCheckConstraint("CK_ScriptedAlarm_AlarmType", "AlarmType IN ('AlarmCondition','LimitAlarm','OffNormalAlarm','DiscreteAlarm')"); + + t.HasCheckConstraint("CK_ScriptedAlarm_Severity_Range", "Severity BETWEEN 1 AND 1000"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", b => + { + b.Property("ClusterId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Enterprise") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("ModifiedAt") + .HasColumnType("datetime2(3)"); + + b.Property("ModifiedBy") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("NodeCount") + .HasColumnType("tinyint"); + + b.Property("Notes") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("RedundancyMode") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("Site") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("ClusterId"); + + b.HasIndex("Name") + .IsUnique() + .HasDatabaseName("UX_ServerCluster_Name"); + + b.HasIndex("Site") + .HasDatabaseName("IX_ServerCluster_Site"); + + b.ToTable("ServerCluster", null, t => + { + t.HasCheckConstraint("CK_ServerCluster_RedundancyMode_NodeCount", "((NodeCount = 1 AND RedundancyMode = 'None') OR (NodeCount = 2 AND RedundancyMode IN ('Warm', 'Hot')))"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Tag", b => + { + b.Property("TagRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AccessLevel") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("DataType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("DeviceId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PollGroupId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TagConfig") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TagGroupId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("TagId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("WriteIdempotent") + .HasColumnType("bit"); + + b.HasKey("TagRowId"); + + b.HasIndex("TagId") + .IsUnique() + .HasDatabaseName("UX_Tag_LogicalId") + .HasFilter("[TagId] IS NOT NULL"); + + b.HasIndex("DeviceId", "Name") + .IsUnique() + .HasDatabaseName("UX_Tag_Device_Name") + .HasFilter("[TagGroupId] IS NULL"); + + b.HasIndex("DeviceId", "TagGroupId") + .HasDatabaseName("IX_Tag_Device"); + + b.HasIndex("DeviceId", "TagGroupId", "Name") + .IsUnique() + .HasDatabaseName("UX_Tag_Group_Name") + .HasFilter("[TagGroupId] IS NOT NULL"); + + b.ToTable("Tag", null, t => + { + t.HasCheckConstraint("CK_Tag_TagConfig_IsJson", "ISJSON(TagConfig) = 1"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.TagGroup", b => + { + b.Property("TagGroupRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("DeviceId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ParentTagGroupId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.Property("TagGroupId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("TagGroupRowId"); + + b.HasIndex("DeviceId") + .HasDatabaseName("IX_TagGroup_Device"); + + b.HasIndex("TagGroupId") + .IsUnique() + .HasDatabaseName("UX_TagGroup_LogicalId") + .HasFilter("[TagGroupId] IS NOT NULL"); + + b.HasIndex("DeviceId", "Name") + .IsUnique() + .HasDatabaseName("UX_TagGroup_DeviceRoot_Name") + .HasFilter("[ParentTagGroupId] IS NULL"); + + b.HasIndex("DeviceId", "ParentTagGroupId", "Name") + .IsUnique() + .HasDatabaseName("UX_TagGroup_Parent_Name") + .HasFilter("[ParentTagGroupId] IS NOT NULL"); + + b.ToTable("TagGroup", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.UnsArea", b => + { + b.Property("UnsAreaRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Notes") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("UnsAreaId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("UnsAreaRowId"); + + b.HasIndex("ClusterId") + .HasDatabaseName("IX_UnsArea_Cluster"); + + b.HasIndex("UnsAreaId") + .IsUnique() + .HasDatabaseName("UX_UnsArea_LogicalId") + .HasFilter("[UnsAreaId] IS NOT NULL"); + + b.HasIndex("ClusterId", "Name") + .IsUnique() + .HasDatabaseName("UX_UnsArea_ClusterName"); + + b.ToTable("UnsArea", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.UnsLine", b => + { + b.Property("UnsLineRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Notes") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("UnsAreaId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("UnsLineId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("UnsLineRowId"); + + b.HasIndex("UnsAreaId") + .HasDatabaseName("IX_UnsLine_Area"); + + b.HasIndex("UnsLineId") + .IsUnique() + .HasDatabaseName("UX_UnsLine_LogicalId") + .HasFilter("[UnsLineId] IS NOT NULL"); + + b.HasIndex("UnsAreaId", "Name") + .IsUnique() + .HasDatabaseName("UX_UnsLine_AreaName"); + + b.ToTable("UnsLine", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.UnsTagReference", b => + { + b.Property("UnsTagReferenceRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("DisplayNameOverride") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("EquipmentId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.Property("TagId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("UnsTagReferenceId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("UnsTagReferenceRowId"); + + b.HasIndex("EquipmentId") + .HasDatabaseName("IX_UnsTagReference_Equipment"); + + b.HasIndex("TagId") + .HasDatabaseName("IX_UnsTagReference_Tag"); + + b.HasIndex("UnsTagReferenceId") + .IsUnique() + .HasDatabaseName("UX_UnsTagReference_LogicalId") + .HasFilter("[UnsTagReferenceId] IS NOT NULL"); + + b.HasIndex("EquipmentId", "TagId") + .IsUnique() + .HasDatabaseName("UX_UnsTagReference_Equip_Tag"); + + b.ToTable("UnsTagReference", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.VirtualTag", b => + { + b.Property("VirtualTagRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ChangeTriggered") + .HasColumnType("bit"); + + b.Property("DataType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("EquipmentId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Historize") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScriptId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("TimerIntervalMs") + .HasColumnType("int"); + + b.Property("VirtualTagId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("VirtualTagRowId"); + + b.HasIndex("ScriptId") + .HasDatabaseName("IX_VirtualTag_Script"); + + b.HasIndex("VirtualTagId") + .IsUnique() + .HasDatabaseName("UX_VirtualTag_LogicalId") + .HasFilter("[VirtualTagId] IS NOT NULL"); + + b.HasIndex("EquipmentId", "Name") + .IsUnique() + .HasDatabaseName("UX_VirtualTag_EquipmentPath"); + + b.ToTable("VirtualTag", null, t => + { + t.HasCheckConstraint("CK_VirtualTag_TimerInterval_Min", "TimerIntervalMs IS NULL OR TimerIntervalMs >= 50"); + + t.HasCheckConstraint("CK_VirtualTag_Trigger_AtLeastOne", "ChangeTriggered = 1 OR TimerIntervalMs IS NOT NULL"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", "Cluster") + .WithMany("Nodes") + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Cluster"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNodeCredential", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", "Node") + .WithMany("Credentials") + .HasForeignKey("NodeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Node"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnection", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", null) + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataExport", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", null) + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DriverInstance", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", "Cluster") + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Cluster"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.LdapGroupRoleMapping", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", "Cluster") + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Cascade); + + b.Navigation("Cluster"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.NodeDeploymentState", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Deployment", "Deployment") + .WithMany() + .HasForeignKey("DeploymentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", "Node") + .WithMany() + .HasForeignKey("NodeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Deployment"); + + b.Navigation("Node"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.RawFolder", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", null) + .WithMany("RawFolders") + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.RemoteNamespaceMapping", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", null) + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.UnsArea", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", "Cluster") + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Cluster"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", b => + { + b.Navigation("Credentials"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", b => + { + b.Navigation("Nodes"); + + b.Navigation("RawFolders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261116135035_AddDataConnectionScopeState.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261116135035_AddDataConnectionScopeState.cs new file mode 100644 index 000000000..c3fe75209 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261116135035_AddDataConnectionScopeState.cs @@ -0,0 +1,41 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations +{ + /// + public partial class AddDataConnectionScopeState : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "DataConnectionScopeState", + columns: table => new + { + Id = table.Column(type: "int", nullable: false), + ScopeVersion = table.Column(type: "bigint", nullable: false), + Fingerprint = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: true), + RowVersion = table.Column(type: "rowversion", rowVersion: true, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_DataConnectionScopeState", x => x.Id); + table.CheckConstraint("CK_DataConnectionScopeState_Singleton", "[Id] = 1 AND [ScopeVersion] >= 0"); + }); + + migrationBuilder.InsertData( + table: "DataConnectionScopeState", + columns: new[] { "Id", "Fingerprint", "ScopeVersion" }, + values: new object[] { 1, null, 0L }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "DataConnectionScopeState"); + } + } +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/OtOpcUaConfigDbContextModelSnapshot.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/OtOpcUaConfigDbContextModelSnapshot.cs index 250a90d66..add14d85a 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/OtOpcUaConfigDbContextModelSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/OtOpcUaConfigDbContextModelSnapshot.cs @@ -448,6 +448,39 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations }); }); + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnectionScopeState", b => + { + b.Property("Id") + .HasColumnType("int"); + + b.Property("Fingerprint") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScopeVersion") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.ToTable("DataConnectionScopeState", null, t => + { + t.HasCheckConstraint("CK_DataConnectionScopeState_Singleton", "[Id] = 1 AND [ScopeVersion] >= 0"); + }); + + b.HasData( + new + { + Id = 1, + ScopeVersion = 0L + }); + }); + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataExport", b => { b.Property("DataExportRowId") diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/OtOpcUaConfigDbContext.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/OtOpcUaConfigDbContext.cs index fb69502c0..919d39bb7 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/OtOpcUaConfigDbContext.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/OtOpcUaConfigDbContext.cs @@ -12,6 +12,7 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration; public sealed class OtOpcUaConfigDbContext(DbContextOptions options) : DbContext(options), IDataProtectionKeyContext { + public DbSet DataConnectionScopeStates => Set(); public DbSet DataConnections => Set(); public DbSet DataExports => Set(); public DbSet RemoteNamespaceMappings => Set(); @@ -77,6 +78,15 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions(e => + { + e.ToTable("DataConnectionScopeState", t => t.HasCheckConstraint("CK_DataConnectionScopeState_Singleton", "[Id] = 1 AND [ScopeVersion] >= 0")); + e.HasKey(x => x.Id); + e.Property(x => x.Id).ValueGeneratedNever(); + e.Property(x => x.Fingerprint).HasMaxLength(64); + e.Property(x => x.RowVersion).IsRowVersion(); + e.HasData(new { Id = 1, ScopeVersion = 0L }); + }); ConfigureDataConnectionEntities(modelBuilder); ConfigureServerCluster(modelBuilder); ConfigureClusterNode(modelBuilder); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionScopeRevision.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionScopeRevision.cs new file mode 100644 index 000000000..caab73cba --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionScopeRevision.cs @@ -0,0 +1,25 @@ +using System.Security.Cryptography; +using System.Text.Json; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Validation; + +/// Derives stable scope fingerprints and advances their authoritative monotonic revision. +public static class DataConnectionScopeRevision +{ + public sealed record Result(long Version, string Fingerprint); + public static Result Advance(long previousVersion, string? previousFingerprint, IEnumerable connections) + { + if (previousVersion < 0) throw new ArgumentOutOfRangeException(nameof(previousVersion)); + ArgumentNullException.ThrowIfNull(connections); + var entries = connections.Where(c => c.Enabled).SelectMany(c => c.ConsumerNodeIds.Select(node => new + { + Owner = c.ClusterId.ToUpperInvariant(), Consumer = node.ToUpperInvariant(), + Connection = c.DataConnectionId.ToUpperInvariant(), SecretOwner = c.SecretScopeClusterId.ToUpperInvariant(), Secret = c.SecretReference + })).OrderBy(x => x.Owner, StringComparer.Ordinal).ThenBy(x => x.Consumer, StringComparer.Ordinal) + .ThenBy(x => x.Connection, StringComparer.Ordinal).ThenBy(x => x.SecretOwner, StringComparer.Ordinal).ThenBy(x => x.Secret, StringComparer.Ordinal).ToArray(); + var fingerprint = Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(entries))); + return new Result(previousVersion > 0 && string.Equals(previousFingerprint, fingerprint, StringComparison.Ordinal) + ? previousVersion : checked(previousVersion + 1), fingerprint); + } +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs index 257955def..8d19117d9 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs @@ -34,7 +34,7 @@ public static class DataConnectionValidator uri.Scheme == Uri.UriSchemeHttps && string.IsNullOrEmpty(uri.UserInfo) && string.IsNullOrEmpty(uri.Query) && string.IsNullOrEmpty(uri.Fragment); bool ValidSecretReference(string? reference) => reference is not null && - Regex.IsMatch(reference, @"\Asecret:data/[A-Za-z0-9][A-Za-z0-9._/-]*\z", RegexOptions.CultureInvariant) && + Regex.IsMatch(reference, @"\Asecret:data/[a-z0-9][a-z0-9._/-]*\z", RegexOptions.CultureInvariant) && !reference.Contains("..", StringComparison.Ordinal); void DuplicateIds(IEnumerable ids, string kind) diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshot.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshot.cs index 8c105d157..184cc0900 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshot.cs @@ -8,6 +8,8 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Validation; /// public sealed class DraftSnapshot { + /// Authoritative deployed data-connection scope revision. + public long DataConnectionScopeVersion { get; set; } /// Gets the draft generation identifier. public required long GenerationId { get; init; } /// Gets the cluster identifier. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshotFactory.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshotFactory.cs index b864032df..2b8db0d19 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshotFactory.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftSnapshotFactory.cs @@ -72,6 +72,7 @@ public static class DraftSnapshotFactory ClusterId = string.Empty, // global snapshot; rules compare entity ClusterId fields, not this ServerClusters = await db.ServerClusters.AsNoTracking().OrderBy(x => x.ClusterId).ToListAsync(ct), ClusterNodes = await db.ClusterNodes.AsNoTracking().OrderBy(x => x.NodeId).ToListAsync(ct), + DataConnectionScopeVersion = await db.DataConnectionScopeStates.AsNoTracking().Where(x => x.Id == 1).Select(x => x.ScopeVersion).SingleOrDefaultAsync(ct), DataConnections = await db.DataConnections.AsNoTracking().OrderBy(x => x.DataConnectionId).ToListAsync(ct), DataExports = await db.DataExports.AsNoTracking().OrderBy(x => x.DataExportId).ToListAsync(ct), RemoteNamespaceMappings = await db.RemoteNamespaceMappings.AsNoTracking().OrderBy(x => x.RemoteNamespaceMappingId).ToListAsync(ct), diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataAddress.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataAddress.cs index 24ce1e2d4..2129f5234 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataAddress.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataAddress.cs @@ -16,11 +16,15 @@ public enum DataTargetMode { Unspecified = 0, Node = 1, Cluster = 2 } public enum DataConsistency { Unspecified = 0, Primary = 1, ReadyReplica = 2 } /// A request is bound to a cluster and, for node mode, an expected node. -public sealed record DataTarget(DataTargetMode Mode, string ExpectedClusterId, string? ExpectedNodeId) +public sealed record DataTarget(DataTargetMode Mode, string ExpectedClusterId, string? ExpectedNodeId, + DataConsistency Consistency = DataConsistency.Primary) { public void Validate() { DataContractValidation.Required(Mode); + DataContractValidation.Required(Consistency); + if (Mode == DataTargetMode.Cluster && Consistency != DataConsistency.Primary) + throw new ArgumentException("Cluster targets require Primary consistency.", nameof(Consistency)); ArgumentException.ThrowIfNullOrWhiteSpace(ExpectedClusterId); if (Mode == DataTargetMode.Node) ArgumentException.ThrowIfNullOrWhiteSpace(ExpectedNodeId); if (Mode == DataTargetMode.Cluster && ExpectedNodeId is not null) @@ -45,14 +49,15 @@ public sealed record DataView(DataAddress Address, DataRealm Realm, string? Mapp } } /// Actual serving replica provenance, distinct from origin ownership. -public sealed record ServingIdentity(string NodeId, string Incarnation, string Role, long CatalogEpoch, long AuthorityEpoch) +public sealed record ServingIdentity(string NodeId, string Incarnation, string Role, long CatalogEpoch, long AuthorityEpoch, + long ServingGeneration = 0) { public void Validate(bool requireEpochs = false) { ArgumentException.ThrowIfNullOrWhiteSpace(NodeId); ArgumentException.ThrowIfNullOrWhiteSpace(Incarnation); ArgumentException.ThrowIfNullOrWhiteSpace(Role); - if (CatalogEpoch < 0 || AuthorityEpoch < 0 || (requireEpochs && (CatalogEpoch == 0 || AuthorityEpoch == 0))) + if (ServingGeneration < 0 || CatalogEpoch < 0 || AuthorityEpoch < 0 || (requireEpochs && (CatalogEpoch == 0 || AuthorityEpoch == 0))) { throw new ArgumentOutOfRangeException(nameof(CatalogEpoch)); } 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 97423b294..068c8dc50 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs @@ -246,7 +246,7 @@ public sealed record DataLimits(int MaxPageItems, int MaxBatchItems, int MaxMess } public sealed record DataCapabilities(int ProtocolMajor, int ProtocolMinor, ServingIdentity Serving, DataReadiness Readiness, DataOperations Operations, IReadOnlySet ValueKinds, DataLimits Limits, bool CompactBatches, - int CompactCodecVersion, string ClusterId, bool SubscriptionAgeReadiness = false) + int CompactCodecVersion, string ClusterId, bool SubscriptionAgeReadiness = false, bool ResponseServingIdentity = false) { public void Validate() { 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 3ffa5e179..e7d19267b 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 @@ -49,3 +49,9 @@ public interface IDataConnectionPublicationGate { bool CanPublish(ServingIdentity expectedServing); } + +/// Discovery may report an unready role, while retaining that exact authenticated snapshot. +public interface IDataConnectionDiscoveryGate +{ + bool CanPublishCapabilities(DataCapabilities expected); +} 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 5c1d55faf..0e28e9d7c 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 @@ -152,6 +152,13 @@ public interface IDataPreparedSubscriptionDelivery : IDisposable long RetainedBytes { get; } } +/// Optional final source/authority proof carried across a transport's preparation awaits. +public interface IDataPreparedSubscriptionPublication : IDataPreparedSubscriptionDelivery +{ + /// Bind exactly once before writing. The callback observes publication eligibility without committing delivery. + void SetPublicationGuard(Func guard); +} + /// Operations use the authenticated caller bound to the containing connection facade. public interface IDataSubscriptionService { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs index 12e015bc6..984c10ad2 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs @@ -390,6 +390,24 @@ public sealed class AdminOperationsActor : ReceiveActor private async Task ComposeDeploymentAsync(StartDeployment msg, string sourceNode) { await using var db = await _dbFactory.CreateDbContextAsync(); + // The singleton update obtains a write lock BEFORE reading the draft. The revision and + // deployment row remain in this same transaction until the sealed artifact is committed. + await using var transaction = db.Database.IsRelational() + ? await db.Database.BeginTransactionAsync(System.Data.IsolationLevel.Serializable) + : null; + DataConnectionScopeState scopeState; + if (transaction is not null) + { + var locked = await db.Database.ExecuteSqlRawAsync("UPDATE DataConnectionScopeState SET ScopeVersion = ScopeVersion WHERE Id = 1"); + if (locked != 1) throw new InvalidOperationException("Authoritative data scope state is unavailable."); + scopeState = await db.DataConnectionScopeStates.SingleAsync(x => x.Id == 1); + } + else + { + // Nonrelational providers are used by isolated unit fixtures only. + scopeState = await db.DataConnectionScopeStates.SingleOrDefaultAsync(x => x.Id == 1) ?? new DataConnectionScopeState(); + if (db.Entry(scopeState).State == EntityState.Detached) db.DataConnectionScopeStates.Add(scopeState); + } // Full pre-seal gate: run the complete DraftValidator (one pass, all rules) and reject // on ANY validation error. The config is now canonical — the company overlay loader emits @@ -523,6 +541,10 @@ public sealed class AdminOperationsActor : ReceiveActor // Composed from the validated snapshot, never from a second read: an edit that lands between // validation and here is simply not in this artifact (R03:3.2). + var scope = DataConnectionScopeRevision.Advance(scopeState.ScopeVersion, scopeState.Fingerprint, draft.DataConnections); + scopeState.ScopeVersion = scope.Version; + scopeState.Fingerprint = scope.Fingerprint; + draft.DataConnectionScopeVersion = scope.Version; var artifact = ConfigComposer.Compose(draft); var deploymentId = DeploymentId.NewId(); var revHash = RevisionHash.Parse(artifact.RevisionHash); @@ -547,6 +569,7 @@ public sealed class AdminOperationsActor : ReceiveActor }); await db.SaveChangesAsync(); + if (transaction is not null) await transaction.CommitAsync(); // Accepted message = the compile-cost advisory (if any) + any Warn-mode TagConfig warnings, so // the operator sees the non-blocking strictness findings on a successful deploy. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/ConfigComposer.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/ConfigComposer.cs index 5bed779f3..a6da8ca2c 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/ConfigComposer.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/ConfigComposer.cs @@ -95,6 +95,7 @@ public static class ConfigComposer Scripts = snapshot.Scripts, VirtualTags = snapshot.VirtualTags, ScriptedAlarms = snapshot.ScriptedAlarms, + DataConnectionScopeVersion = snapshot.DataConnectionScopeVersion, DataConnections = snapshot.DataConnections.OrderBy(x => x.DataConnectionId, StringComparer.Ordinal).Select(connection => { var copy = JsonSerializer.Deserialize(JsonSerializer.SerializeToUtf8Bytes(connection, JsonOptions), JsonOptions)!; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionAuthInterceptor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionAuthInterceptor.cs new file mode 100644 index 000000000..f1bcf6462 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionAuthInterceptor.cs @@ -0,0 +1,70 @@ +using Grpc.Core; +using Grpc.Core.Interceptors; +using Microsoft.Extensions.Options; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Host.OpcUa; + +namespace ZB.MOM.WW.OtOpcUa.Host.Configuration; + +/// Authenticates against the same deployed, process-local authority as operation admission. +public sealed class DataConnectionAuthenticator(IDataPlaneAuthoritySource authority, IOptions options, + TimeProvider clock) +{ + public DataAuthenticatedContext Authenticate(string bearer) + { + var snapshot = authority.Current; + if (!snapshot.HasArtifact || string.IsNullOrWhiteSpace(options.Value.Pepper) + || !ApiKeySecret.TryParse(bearer, out var id, out var secret)) throw Denied(); + var key = snapshot.FindUsableKey(id, clock.GetUtcNow().UtcDateTime); + if (key is null || string.IsNullOrWhiteSpace(key.Principal) + || string.Equals(key.Principal, OpcUaPrincipals.Anonymous, StringComparison.OrdinalIgnoreCase)) throw Denied(); + try { if (!ApiKeySecret.Verify(secret, options.Value.Pepper, key.SecretHash)) throw Denied(); } + catch (ArgumentException) { throw Denied(); } + var context = new DataAuthenticatedContext(key.Principal, key.ApiKeyId, + DataCallerIdentity.CredentialVersionFor(key), key.ExpiresUtc is { } expiry + ? new DateTimeOffset(DateTime.SpecifyKind(expiry, DateTimeKind.Utc)) : null, snapshot.GenerationId); + if (!ReferenceEquals(snapshot, authority.Current) || !IsCurrent(context)) throw Denied(); + return context; + } + + public bool IsCurrent(DataAuthenticatedContext context) + { + var snapshot = authority.Current; + var now = clock.GetUtcNow(); + if (!snapshot.HasArtifact || snapshot.GenerationId != context.AuthorityEpoch + || context.CredentialExpiresUtc is { } originalExpiry && originalExpiry <= now) return false; + var key = snapshot.FindUsableKey(context.ApiKeyId, now.UtcDateTime); + return key is not null && string.Equals(key.Principal, context.PrincipalId, StringComparison.OrdinalIgnoreCase) + && DataCallerIdentity.CredentialVersionFor(key) == context.CredentialVersion + && ReferenceEquals(snapshot, authority.Current); + } + private static UnauthorizedAccessException Denied() => new("Data authentication failed."); +} + +/// Defense in depth after the pre-parse listener/authentication middleware. +public sealed class DataConnectionAuthInterceptor(IOptions options, + DataConnectionAuthenticator authenticator) : Interceptor +{ + public override Task UnaryServerHandler(TRequest request, + ServerCallContext context, UnaryServerMethod continuation) + { Validate(context); return continuation(request, context); } + + public override Task DuplexStreamingServerHandler(IAsyncStreamReader requests, + IServerStreamWriter responses, ServerCallContext context, + DuplexStreamingServerMethod continuation) + { Validate(context); return continuation(requests, responses, context); } + + private void Validate(ServerCallContext context) + { + var http = context.GetHttpContext(); + if (http.Connection.LocalPort == options.Value.ListenPort && options.Value.Enabled + && !DataConnectionEndpoints.IsDataRequest(http, options.Value)) + throw new RpcException(new Status(StatusCode.PermissionDenied, "Dedicated data listener.")); + if (!context.Method.StartsWith(DataConnectionEndpoints.ServicePrefix, StringComparison.Ordinal)) return; + if (!DataConnectionEndpoints.IsDataRequest(http, options.Value) + || http.Items[typeof(DataAuthenticatedContext)] is not DataAuthenticatedContext caller + || !authenticator.IsCurrent(caller)) + throw new RpcException(new Status(StatusCode.Unauthenticated, "Data authentication failed.")); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionBundleLoader.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionBundleLoader.cs new file mode 100644 index 000000000..ee2025848 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionBundleLoader.cs @@ -0,0 +1,111 @@ +using System.Security.Cryptography.X509Certificates; +using System.Text.Json; +using Microsoft.Extensions.Hosting; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Host.Configuration; + +/// Installs an applied scope in both independent local security stores. +public sealed class DataConnectionScopeActivator(DataConnectionSecretProvisioner credentials, DataConnectionTrustPolicyStore trust) : IDataConnectionScopeActivator +{ + public async Task SetScopeAsync(long version, IReadOnlyDictionary allowlist, CancellationToken cancellationToken) + { + await credentials.SetScopeAsync(version, allowlist, cancellationToken).ConfigureAwait(false); + await trust.ApplyScopeAsync(version, allowlist.Keys, cancellationToken).ConfigureAwait(false); + } +} + +/// Node-local trust bundle. Root certificates are public DER encoded in base64. +public sealed record DataConnectionTrustBundle(string OwnerCluster, string ConsumerNode, long ScopeVersion, IReadOnlyList Entries); +/// An independently versioned trust set; an empty root set is a removal tombstone. +public sealed record DataConnectionTrustBundleEntry(string ConnectionId, long Version, IReadOnlyList Roots); +/// Reports which local bundle files were successfully processed. +public sealed record DataConnectionBundleLoadResult(bool CredentialsLoaded, bool TrustLoaded); + +/// Reads a restricted, atomically replaced trust bundle under a fixed byte limit. +public sealed class DataConnectionTrustBundleReader(string path) +{ + public async Task ReadAsync(CancellationToken ct) + { + const int maximumBytes = 1024 * 1024; + await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, 4096, true); + if (stream.Length > maximumBytes) throw new InvalidDataException("Trust bundle exceeds the size limit."); + using var buffer = new MemoryStream(); var bytes = new byte[8192]; int count; + while ((count = await stream.ReadAsync(bytes, ct).ConfigureAwait(false)) != 0) + { + if (buffer.Length + count > maximumBytes) throw new InvalidDataException("Trust bundle exceeds the size limit."); + buffer.Write(bytes, 0, count); + } + return JsonSerializer.Deserialize(buffer.GetBuffer().AsSpan(0, checked((int)buffer.Length))) + ?? throw new InvalidDataException("Trust bundle is empty."); + } +} + +/// Imports local credential and trust mounts independently. No bundle content is logged. +public sealed class DataConnectionBundleLoader(DataConnectionSecretProvisioner credentials, DataConnectionTrustPolicyStore trust, + string ownerCluster, string consumerNode) +{ + private readonly string _owner = DataConnectionSecretProvisioner.NormalizeId(ownerCluster); + private readonly string _node = DataConnectionSecretProvisioner.NormalizeId(consumerNode); + + public async Task ApplyFilesAsync(string? credentialPath, string? trustPath, CancellationToken ct) + { + var credentialsLoaded = await TryCredentialsAsync(credentialPath, ct).ConfigureAwait(false); + var trustLoaded = await TryTrustAsync(trustPath, ct).ConfigureAwait(false); + return new(credentialsLoaded, trustLoaded); + } + private async Task TryCredentialsAsync(string? path, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(path)) return false; + try + { + var bundle = await new DataConnectionBundleReader(path).ReadAsync(ct).ConfigureAwait(false); + await credentials.ApplyAsync(bundle, ct).ConfigureAwait(false); + return true; + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } + catch (Exception) { return false; } + } + private async Task TryTrustAsync(string? path, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(path)) return false; + var certificates = new List(); + try + { + var bundle = await new DataConnectionTrustBundleReader(path).ReadAsync(ct).ConfigureAwait(false); + if (DataConnectionSecretProvisioner.NormalizeId(bundle.OwnerCluster) != _owner || DataConnectionSecretProvisioner.NormalizeId(bundle.ConsumerNode) != _node || bundle.Entries is null) + return false; + var entries = new List<(string ConnectionId, long Version, X509Certificate2[] Roots)>(); + foreach (var entry in bundle.Entries) + { + var roots = new List(); + foreach (var encoded in entry.Roots) + { + var cert = X509CertificateLoader.LoadCertificate(Convert.FromBase64String(encoded)); + certificates.Add(cert); roots.Add(cert); + } + entries.Add((entry.ConnectionId, entry.Version, roots.ToArray())); + } + await trust.SetBundleAsync(entries, bundle.ScopeVersion, ct).ConfigureAwait(false); + return true; + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } + catch (Exception) { return false; } + finally { foreach (var certificate in certificates) certificate.Dispose(); } + } +} + +/// Retries local mounts without treating a missing mount as a revocation. +public sealed class DataConnectionBundleBackgroundService(DataConnectionBundleLoader loader, string? credentialPath, + string? trustPath, TimeSpan interval) : BackgroundService +{ + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + if (interval <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(interval)); + while (!stoppingToken.IsCancellationRequested) + { + await loader.ApplyFilesAsync(credentialPath, trustPath, stoppingToken).ConfigureAwait(false); + await Task.Delay(interval, stoppingToken).ConfigureAwait(false); + } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionCredentialResolver.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionCredentialResolver.cs new file mode 100644 index 000000000..a477102f2 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionCredentialResolver.cs @@ -0,0 +1,47 @@ +using ZB.MOM.WW.Secrets.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.Host.Configuration; + +/// A credential and its durable local version. +public sealed record DataConnectionCredential(string Value, long Version, string SecretName) +{ + public override string ToString() => $"Credential version {Version} (redacted)"; +} + +/// Resolves only current, fully committed node-local credentials. +public sealed class DataConnectionCredentialResolver(ISecretStore store, ISecretCipher cipher, string ownerCluster, string consumerNode) +{ + public async Task IsEligibleAsync(string connectionId, CancellationToken ct) + { + connectionId = DataConnectionSecretProvisioner.NormalizeId(connectionId); + await DataConnectionSecretProvisioner.Gate.WaitAsync(ct).ConfigureAwait(false); + try + { + var state = await DataConnectionSecretProvisioner.ReadStateAsync(store, cipher, + DataConnectionSecretProvisioner.GetStateName(ownerCluster, consumerNode), ct).ConfigureAwait(false); + return !state.PendingNotices.Contains(connectionId) && state.Scope.ContainsKey(connectionId); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } + catch (Exception) { return false; } + finally { DataConnectionSecretProvisioner.Gate.Release(); } + } + public async Task ResolveAsync(string connectionId, CancellationToken ct) + { + connectionId = DataConnectionSecretProvisioner.NormalizeId(connectionId); + await DataConnectionSecretProvisioner.Gate.WaitAsync(ct).ConfigureAwait(false); + try + { + var state = await DataConnectionSecretProvisioner.ReadStateAsync(store, cipher, + DataConnectionSecretProvisioner.GetStateName(ownerCluster, consumerNode), ct).ConfigureAwait(false); + if (state.PendingNotices.Contains(connectionId) || !state.Scope.TryGetValue(connectionId, out var reference) || !state.Versions.TryGetValue(reference, out var version) || version.Deleted || version.Pending) + return null; + var row = await store.GetAsync(DataConnectionSecretProvisioner.StoreName(reference), ct).ConfigureAwait(false); + if (row is null) return null; + var value = cipher.Decrypt(row); + return DataConnectionSecretProvisioner.PayloadHash(value, false) != version.PayloadHash ? null : new DataConnectionCredential(value, version.Version, DataConnectionSecretProvisioner.StoreName(reference).Value); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } + catch (Exception) { return null; } + finally { DataConnectionSecretProvisioner.Gate.Release(); } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionEndpoints.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionEndpoints.cs new file mode 100644 index 000000000..adfd9fc29 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionEndpoints.cs @@ -0,0 +1,111 @@ +using Microsoft.Extensions.Options; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Host.Configuration; + +/// Actual listener isolation and bounded authentication before protobuf deserialization. +public static class DataConnectionEndpoints +{ + public const string ServicePrefix = "/data_connection.v1.DataConnectionService/"; + private static readonly HashSet Methods = ["GetCapabilities", "Browse", "GetMetadata", "Read", "Write", "Subscribe"]; + + public static bool IsDataRequest(HttpContext context, DataConnectionOptions options) => options.Enabled + && context.Connection.LocalPort == options.ListenPort + && (context.Request.IsHttps || options.AllowDevelopmentCleartext) + && context.Request.Protocol == "HTTP/2" && HttpMethods.IsPost(context.Request.Method) + && options.AllowedHosts.Contains(context.Request.Host.Host, StringComparer.OrdinalIgnoreCase) + && (context.Request.Host.Port is null || context.Request.Host.Port == options.ListenPort) + && context.Request.Path.Value is { } path && path.StartsWith(ServicePrefix, StringComparison.Ordinal) + && Methods.Contains(path[ServicePrefix.Length..]); + + public static DataTarget RequestedTarget(HttpContext context) + { + string Required(string name) + { + var values = context.Request.Headers[name]; + if (values.Count != 1 || string.IsNullOrWhiteSpace(values[0])) throw new ArgumentException("Missing data target policy."); + return values[0]!; + } + var modeText = Required("x-data-target-mode"); + var consistencyText = Required("x-data-consistency"); + // Parse names only: Enum.TryParse also accepts numeric enum values. + var mode = modeText switch { "Node" => DataTargetMode.Node, "Cluster" => DataTargetMode.Cluster, _ => throw new ArgumentException("Invalid target mode.") }; + var consistency = consistencyText switch { "Primary" => DataConsistency.Primary, "ReadyReplica" => DataConsistency.ReadyReplica, _ => throw new ArgumentException("Invalid consistency.") }; + var node = mode == DataTargetMode.Node ? Required("x-data-node-id") : null; + if (mode == DataTargetMode.Cluster && context.Request.Headers.ContainsKey("x-data-node-id")) + throw new ArgumentException("Cluster requests cannot pin a node."); + var target = new DataTarget(mode, Required("x-data-cluster-id"), node, consistency); + target.Validate(); + return target; + } + + public static IApplicationBuilder UseDataConnectionAdmission(this IApplicationBuilder app) => app.UseMiddleware(); +} + +/// Owns a finite admission slot until the real HTTP call ends. +public sealed class DataConnectionAdmissionMiddleware +{ + private readonly RequestDelegate _next; + private readonly DataConnectionOptions _options; + private readonly SemaphoreSlim _calls; + private readonly SemaphoreSlim _streams; + public DataConnectionAdmissionMiddleware(RequestDelegate next, IOptions options) + { + _next = next; _options = options.Value; + _calls = new(_options.MaxConcurrentCalls, _options.MaxConcurrentCalls); + _streams = new(_options.MaxStreams, _options.MaxStreams); + } + + public async Task InvokeAsync(HttpContext context, DataConnectionAuthenticator authenticator) + { + var path = context.Request.Path.Value ?? ""; + var dataPath = path.StartsWith(DataConnectionEndpoints.ServicePrefix, StringComparison.Ordinal); + var dataPort = _options.Enabled && context.Connection.LocalPort == _options.ListenPort; + if (!dataPath && !dataPort) { await _next(context).ConfigureAwait(false); return; } + if (!DataConnectionEndpoints.IsDataRequest(context, _options)) { Reject(context, 7); return; } + var isStream = path == DataConnectionEndpoints.ServicePrefix + "Subscribe"; + var admission = isStream ? _streams : _calls; + if (!await admission.WaitAsync(0, context.RequestAborted).ConfigureAwait(false)) { Reject(context, 8); return; } + try + { + var authorization = context.Request.Headers.Authorization; + if (authorization.Count != 1 || authorization[0] is not { } header + || !header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) + || header.Length > 4096 || header[7..].Any(char.IsWhiteSpace)) { Reject(context, 16); return; } + try + { + context.Items[typeof(DataAuthenticatedContext)] = authenticator.Authenticate(header[7..]); + context.Items[typeof(DataTarget)] = DataConnectionEndpoints.RequestedTarget(context); + } + catch (UnauthorizedAccessException) { Reject(context, 16); return; } + catch (ArgumentException) { Reject(context, 3); return; } + if (isStream) + { + // The stream engine owns finite pre-Open/session lifetime and command deadlines. + await _next(context).ConfigureAwait(false); + } + else + { + // Starts before protobuf parsing and stays alive through serialization/writing. + // A caller that omits grpc-timeout cannot pin a unary parse/admission slot forever. + var originalAbort = context.RequestAborted; + context.Items[typeof(Grpc.DataConnectionUnaryLifetime)] = new Grpc.DataConnectionUnaryLifetime(TimeProvider.System, _options.UnaryTimeout); + using var deadline = new CancellationTokenSource(_options.UnaryTimeout); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(originalAbort, deadline.Token); + using var abort = deadline.Token.Register(static state => ((HttpContext)state!).Abort(), context); + context.RequestAborted = linked.Token; + try { await _next(context).ConfigureAwait(false); } + finally { context.RequestAborted = originalAbort; } + } + } + finally { admission.Release(); } + } + + private static void Reject(HttpContext context, int grpcStatus) + { + context.Response.StatusCode = StatusCodes.Status200OK; + context.Response.ContentType = "application/grpc"; + context.Response.Headers["grpc-status"] = grpcStatus.ToString(System.Globalization.CultureInfo.InvariantCulture); + context.Response.Headers["grpc-message"] = "Data request refused."; + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs new file mode 100644 index 000000000..ecab2a4c6 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs @@ -0,0 +1,28 @@ +namespace ZB.MOM.WW.OtOpcUa.Host.Configuration; + +/// Dedicated data-plane listener and finite transport admission limits. +public sealed class DataConnectionOptions +{ + public const string SectionName = "DataConnections"; + public bool Enabled { get; set; } + public int ListenPort { get; set; } + public string ListenAddress { get; set; } = "0.0.0.0"; + public string[] AllowedHosts { get; set; } = []; + public string? CertificatePath { get; set; } + public string? CertificateKeyPath { get; set; } + public bool AllowDevelopmentCleartext { get; set; } + public int MaxMessageBytes { get; set; } = 1_048_576; + public int MaxConcurrentCalls { get; set; } = 64; + public int MaxStreams { get; set; } = 256; + public int MaxStreamsPerPrincipal { get; set; } = 8; + public int MaxMonitoredItems { get; set; } = 10_000; + public long MaxTransportBytes { get; set; } = 64 * 1024 * 1024; + public long MaxPendingBytes { get; set; } = 1024 * 1024; + public TimeSpan MaxSessionLifetime { get; set; } = TimeSpan.FromHours(1); + public ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.DataResourceLimits Hub { get; set; } = new(); + public TimeSpan UnaryTimeout { get; set; } = TimeSpan.FromSeconds(30); + public TimeSpan StreamCommandTimeout { get; set; } = TimeSpan.FromSeconds(5); + public string? CredentialBundlePath { get; set; } + public string? TrustBundlePath { get; set; } + public TimeSpan BundleRefreshInterval { get; set; } = TimeSpan.FromSeconds(1); +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptionsValidator.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptionsValidator.cs new file mode 100644 index 000000000..9683dc89a --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptionsValidator.cs @@ -0,0 +1,44 @@ +using System.Net; +using Microsoft.Extensions.Options; + +namespace ZB.MOM.WW.OtOpcUa.Host.Configuration; + +/// Rejects ambiguous listener identity and insecure production transport. +public sealed class DataConnectionOptionsValidator(IHostEnvironment environment) : IValidateOptions +{ + public ValidateOptionsResult Validate(string? name, DataConnectionOptions options) + { + var errors = Validate(options, environment.IsDevelopment()); + return errors.Count == 0 ? ValidateOptionsResult.Success : ValidateOptionsResult.Fail(errors); + } + + public static IReadOnlyList Validate(DataConnectionOptions options, bool development) + { + ArgumentNullException.ThrowIfNull(options); + if (!options.Enabled) return []; + var errors = new List(); + if (options.ListenPort is < 1 or > 65535) errors.Add("DataConnections:ListenPort must be a dedicated port."); + if (!IPAddress.TryParse(options.ListenAddress, out var address)) errors.Add("DataConnections:ListenAddress must be an IP literal."); + if (options.AllowedHosts is not { Length: > 0 } || options.AllowedHosts.Any(host => + string.IsNullOrWhiteSpace(host) || Uri.CheckHostName(host) == UriHostNameType.Unknown)) + errors.Add("DataConnections:AllowedHosts must name the dedicated endpoint hosts."); + if (options.AllowDevelopmentCleartext) + { + if (!development || address is null || !IPAddress.IsLoopback(address)) + errors.Add("Cleartext data transport requires Development and a literal loopback listener."); + } + else if (string.IsNullOrWhiteSpace(options.CertificatePath)) errors.Add("A data-plane TLS certificate is required."); + if (options.MaxMessageBytes is < 1024 or > 16_777_216 || options.MaxConcurrentCalls is < 1 or > 4096) + errors.Add("Data-plane parse and concurrency limits are outside supported bounds."); + if (options.MaxStreams is < 1 or > 4096 || options.MaxStreamsPerPrincipal <= 0 || options.MaxMonitoredItems <= 0 + || options.MaxPendingBytes <= 0 || options.MaxPendingBytes > options.MaxTransportBytes + || options.MaxSessionLifetime <= TimeSpan.Zero || options.MaxSessionLifetime > TimeSpan.FromDays(1) + || options.Hub is null || options.BundleRefreshInterval < TimeSpan.FromMilliseconds(100) + || options.BundleRefreshInterval > TimeSpan.FromMinutes(1)) + errors.Add("Data-plane retained work and refresh limits are invalid."); + if (options.UnaryTimeout <= TimeSpan.Zero || options.UnaryTimeout > TimeSpan.FromMinutes(5) + || options.StreamCommandTimeout <= TimeSpan.Zero || options.StreamCommandTimeout > TimeSpan.FromMinutes(1)) + errors.Add("Unary and stream-command timeouts must be finite and within supported limits."); + return errors; + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs new file mode 100644 index 000000000..7644c1146 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs @@ -0,0 +1,173 @@ +using Akka.Hosting; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; +using ZB.MOM.WW.OtOpcUa.Commons.Interfaces; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Host.Grpc; +using ZB.MOM.WW.OtOpcUa.Runtime; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy; +using ZB.MOM.WW.Secrets.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.Host.Configuration; + +internal sealed record DataConnectionProcessIdentity(string ClusterId, string NodeId, string Incarnation); + +/// Composes the actual node-local publishers and transport without constructing a second actor graph. +public static class DataConnectionRegistration +{ + public static DataConnectionOptions AddOtOpcUaDataConnections(this IServiceCollection services, + IConfiguration configuration, IHostEnvironment environment, bool hasDriver) + { + var options = configuration.GetSection(DataConnectionOptions.SectionName).Get() ?? new(); + var errors = DataConnectionOptionsValidator.Validate(options, environment.IsDevelopment()); + if (errors.Count != 0) throw new OptionsValidationException(string.Empty, typeof(DataConnectionOptions), errors); + services.AddOptions().Bind(configuration.GetSection(DataConnectionOptions.SectionName)).ValidateOnStart(); + services.AddSingleton>(new DataConnectionOptionsValidator(environment)); + if (!options.Enabled) return options; + if (!hasDriver) throw new InvalidOperationException("DataConnections requires this node's driver role."); + + services.TryAddSingleton(TimeProvider.System); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.AddSingleton(sp => + { + var role = sp.GetRequiredService(); + if (string.IsNullOrWhiteSpace(role.ClusterId)) throw new InvalidOperationException("DataConnections requires a configured owning cluster role."); + return new DataConnectionProcessIdentity(role.ClusterId, role.LocalNode.Value, Guid.NewGuid().ToString("N")); + }); + services.AddSingleton(sp => new CatalogActivation(sp.GetRequiredService())); + services.AddSingleton(sp => + { + var identity = sp.GetRequiredService(); + var role = sp.GetRequiredService(); + var warm = sp.GetRequiredService(); + var settings = sp.GetService() ?? WarmRedundancySettings.Unset; + return new LocalCatalogCoordinator(sp.GetRequiredService(), sp.GetRequiredService(), + () => + { + var state = CaptureRole(role, warm); + var servingRole = settings.IsWarm && state.WarmRole != WarmRole.Active ? "Standby" : state.Role; + return new(identity.NodeId, identity.Incarnation, servingRole, 0, 0, state.Generation); + }); + }); + services.AddSingleton(sp => new PartitionedSampleHub(options.Hub, sp.GetRequiredService())); + services.AddSingleton(sp => new SourceSamplePublisher(sp.GetRequiredService(), + () => sp.GetRequiredService().Serving, sp.GetRequiredService().ClusterId)); + services.AddSingleton(sp => new DataOperationPolicy(sp.GetRequiredService(), + sp.GetRequiredService(), sp.GetRequiredService())); + services.AddSingleton(sp => + { + var catalog = sp.GetRequiredService(); + return new DataCapabilitiesProvider(sp.GetRequiredService().ClusterId, + () => catalog.Serving, () => catalog.Current is not null && sp.GetRequiredService().CurrentScopeReady, + new(500, 1000, options.MaxMessageBytes, options.MaxMonitoredItems, Math.Min(options.MaxStreams, options.MaxStreamsPerPrincipal), + options.MaxPendingBytes, TimeSpan.FromSeconds(15), options.MaxSessionLifetime, TimeSpan.FromSeconds(30))); + }); + services.AddSingleton(sp => new SubscriptionAcquisitionCapacity(options.Hub.MaxTrackedSources)); + services.AddSingleton(sp => new DataWriteRuntime(sp.GetRequiredService(), + sp.GetRequiredService(), sp.GetRequiredService(), + sp.GetRequiredService(), sp.GetRequiredService(), + sp.GetRequiredService(), sp.GetRequiredService(), + sp.GetService() ?? DriverWriteBounds.Default, + sp.GetRequiredService().Incarnation, + 10_000, 16 * 1024 * 1024, 16 * 1024 * 1024, 128, TimeSpan.FromSeconds(30))); + services.AddSingleton(sp => + { + if (sp.GetService() is not { } registry || !registry.TryGet(out var host)) + throw new InvalidOperationException("The local driver host is not registered yet."); + return new LocalDataRuntimeComposition(sp.GetRequiredService(), sp.GetRequiredService(), + sp.GetRequiredService(), sp.GetRequiredService(), + sp.GetRequiredService(), sp.GetRequiredService(), host, + sp.GetRequiredService(), new(4096, options.Hub.MaxTrackedSources, + options.MaxStreams, Math.Min(options.MaxStreams, options.MaxStreamsPerPrincipal), options.MaxTransportBytes, + 128, 64, options.MaxPendingBytes, options.MaxSessionLifetime, TimeSpan.FromSeconds(5))); + }); + services.AddSingleton(sp => new DeferredFactory(() => sp.GetRequiredService().Services)); + services.AddSingleton(); + services.AddSingleton(sp => + { + var id = sp.GetRequiredService(); + return new DataConnectionSecretProvisioner(sp.GetRequiredService(), sp.GetRequiredService(), + sp.GetRequiredService(), sp.GetRequiredService(), id.ClusterId, id.NodeId); + }); + services.AddSingleton(sp => + { + var id = sp.GetRequiredService(); + return new DataConnectionCredentialResolver(sp.GetRequiredService(), sp.GetRequiredService(), id.ClusterId, id.NodeId); + }); + services.AddSingleton(sp => + { + var id = sp.GetRequiredService(); + return new DataConnectionTrustPolicyStore(sp.GetRequiredService(), sp.GetRequiredService(), + sp.GetRequiredService(), id.ClusterId, id.NodeId); + }); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(sp => + { + var id = sp.GetRequiredService(); + var role = sp.GetRequiredService(); + var warm = sp.GetRequiredService(); + var settings = sp.GetService() ?? WarmRedundancySettings.Unset; + DataConnectionDeploymentRuntime? runtime = null; + runtime = new DataConnectionDeploymentRuntime(id.NodeId, id.ClusterId, sp.GetRequiredService(), + sp.GetRequiredService(), 256, sp.GetRequiredService(), + () => + { + var state = CaptureRole(role, warm); + var mode = settings.Mode switch + { + OpcUaRedundancyMode.Warm => RedundancyMode.Warm, + OpcUaRedundancyMode.None => RedundancyMode.None, + _ => runtime?.CurrentConsumerMode ?? RedundancyMode.None + }; + return state.Generation > 0 && Enum.TryParse(state.Role, out var actual) + && DataConnectionRoleAdapter.MayAcquire(mode, state.WarmRole, actual); + }); + return runtime; + }); + services.AddSingleton(sp => + { + var id = sp.GetRequiredService(); + return new DataConnectionBundleLoader(sp.GetRequiredService(), + sp.GetRequiredService(), id.ClusterId, id.NodeId); + }); + services.AddHostedService(sp => new DataConnectionBundleBackgroundService(sp.GetRequiredService(), + options.CredentialBundlePath, options.TrustBundlePath, options.BundleRefreshInterval)); + services.AddSingleton(); + services.AddGrpc().AddServiceOptions(grpc => + { + grpc.MaxReceiveMessageSize = options.MaxMessageBytes; + grpc.MaxSendMessageSize = options.MaxMessageBytes; + grpc.EnableDetailedErrors = false; + }); + return options; + } + + private static (string Role, long Generation, WarmRole? WarmRole) CaptureRole(RedundancyRoleView role, DataConnectionWarmRoleView warm) + { + if (!ReferenceEquals(role.DispatchFence, warm.DispatchFence) || !role.DispatchFence.TryEnter(out var lease)) + return ("Unknown", 0, null); + using (lease) + { + var observed = role.DataServingRole; + var primaryGeneration = role.PrimaryGeneration; + var verdict = warm.Snapshot; + if (primaryGeneration == long.MaxValue || verdict.Generation == long.MaxValue + || primaryGeneration > long.MaxValue - verdict.Generation) return ("Unknown", long.MaxValue, null); + return (observed, primaryGeneration + verdict.Generation, verdict.Role); + } + } + + private sealed class DeferredFactory(Func resolve) : IDataConnectionFactory + { + public IDataConnection Create(DataAuthenticatedContext context, DataTarget target) => resolve().Create(context, target); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionSecretChangeHandler.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionSecretChangeHandler.cs new file mode 100644 index 000000000..f0ceb334e --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionSecretChangeHandler.cs @@ -0,0 +1,27 @@ +using ZB.MOM.WW.Secrets.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.Host.Configuration; + +/// Dependency-free broadcaster composed with the existing secret invalidation chain. +public sealed class DataConnectionSecretChangeHandler +{ + public event Action? SecretChanged; + public event Action? ConnectionChanged; + public void NotifySecretChanged(SecretName name) => Broadcast(SecretChanged, name); + public void NotifyConnectionChanged(string connectionId) => Broadcast(ConnectionChanged, connectionId); + internal static void Broadcast(Action? handlers, T value) + { + List? failures = null; + if (handlers is not null) + foreach (Action handler in handlers.GetInvocationList()) + try { handler(value); } catch (Exception ex) { (failures ??= []).Add(ex); } + if (failures is not null) throw new AggregateException(failures); + } + internal void NotifyConnectionsChanged(IEnumerable connections) + { + List? failures = null; + foreach (var connection in connections.Distinct(StringComparer.Ordinal)) + try { NotifyConnectionChanged(connection); } catch (Exception ex) { (failures ??= []).Add(ex); } + if (failures is not null) throw new AggregateException(failures); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionSecretProvisioner.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionSecretProvisioner.cs new file mode 100644 index 000000000..47dc3e706 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionSecretProvisioner.cs @@ -0,0 +1,218 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using ZB.MOM.WW.Secrets.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.Host.Configuration; + +/// A restricted, node-local credential bundle. Never serialize into deployment artifacts. +public sealed record DataConnectionCredentialBundle(string OwnerCluster, string ConsumerNode, long Version, IReadOnlyList Entries, long ScopeVersion = 0); +/// A bundle entry, including an explicit deletion marker. +public sealed record DataConnectionCredentialEntry(string ConnectionId, string SecretReference, string? Value, bool Deleted) +{ + public override string ToString() => $"Credential entry {ConnectionId} (redacted)"; +} + +internal sealed class DataCredentialState +{ + public long ScopeVersion { get; set; } + public Dictionary Scope { get; set; } = new(StringComparer.Ordinal); + public Dictionary Versions { get; set; } = new(StringComparer.Ordinal); + public HashSet PendingDeletes { get; set; } = new(StringComparer.Ordinal); + public HashSet PendingNotices { get; set; } = new(StringComparer.Ordinal); +} +internal sealed class DataCredentialVersion +{ + public long Version { get; set; } + public bool Deleted { get; set; } + public bool Pending { get; set; } + public string? PayloadHash { get; set; } + public long ScopeVersion { get; set; } +} + +/// Imports local bundles into the encrypted local secret store with durable revocation state. +public sealed class DataConnectionSecretProvisioner +{ + public const int MaximumReferences = 256; + internal static string PayloadHash(string? value, bool deleted) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(deleted ? "D" : "V" + value))); + internal static readonly SemaphoreSlim Gate = new(1, 1); + private readonly ISecretStore _store; + private readonly ISecretCipher _cipher; + private readonly ISecretCacheInvalidator _invalidator; + private readonly DataConnectionSecretChangeHandler _changes; + private readonly string _owner; + private readonly string _node; + internal readonly SecretName StateName; + + public DataConnectionSecretProvisioner(ISecretStore store, ISecretCipher cipher, ISecretCacheInvalidator invalidator, + DataConnectionSecretChangeHandler changes, string ownerCluster, string consumerNode) + { + _store = store; _cipher = cipher; _invalidator = invalidator; _changes = changes; + _owner = NormalizeId(ownerCluster); _node = NormalizeId(consumerNode); + StateName = GetStateName(ownerCluster, consumerNode); + } + internal static string NormalizeId(string value) => !string.IsNullOrWhiteSpace(value) + ? value.ToUpperInvariant() : throw new ArgumentException("Identity must be nonempty.", nameof(value)); + internal static SecretName StoreName(string reference) + { + if (reference is null || !System.Text.RegularExpressions.Regex.IsMatch(reference, @"\Asecret:data/[a-z0-9][a-z0-9._/-]*\z", System.Text.RegularExpressions.RegexOptions.CultureInvariant) + || reference.Contains("..", StringComparison.Ordinal)) + throw new InvalidOperationException("Invalid canonical data secret reference."); + return new SecretName(reference["secret:".Length..]); + } + internal static SecretName GetStateName(string owner, string node) => new("data-connection/state/" + + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(NormalizeId(owner) + "\0" + NormalizeId(node)))).ToLowerInvariant()); + internal static async Task ReadStateAsync(ISecretStore store, ISecretCipher cipher, SecretName name, CancellationToken ct) + { + var row = await store.GetAsync(name, ct).ConfigureAwait(false); + return row is null ? new DataCredentialState() : JsonSerializer.Deserialize(cipher.Decrypt(row)) + ?? throw new InvalidOperationException("Invalid data credential state."); + } + private Task SaveAsync(DataCredentialState state, CancellationToken ct) => + _store.UpsertAsync(_cipher.Encrypt(StateName, JsonSerializer.Serialize(state), SecretContentType.Text), ct); + + /// Persists current scope before retiring removed connections. + public async Task SetScopeAsync(long version, IReadOnlyDictionary scope, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(scope); + if (version <= 0 || scope.Any(x => string.IsNullOrWhiteSpace(x.Key) || string.IsNullOrWhiteSpace(x.Value) || x.Value.StartsWith("data-connection/", StringComparison.Ordinal))) + throw new ArgumentException("Invalid scope.", nameof(scope)); + var canonical = new Dictionary(StringComparer.Ordinal); + foreach (var pair in scope) + { + _ = StoreName(pair.Value); + if (!canonical.TryAdd(NormalizeId(pair.Key), pair.Value)) throw new InvalidOperationException("Duplicate connection identity."); + } + scope = canonical; + if (scope.Count > MaximumReferences || scope.Values.Distinct(StringComparer.Ordinal).Count() > MaximumReferences) + throw new InvalidOperationException("Scope capacity exceeded."); + await Gate.WaitAsync(ct).ConfigureAwait(false); + try + { + var state = await ReadStateAsync(_store, _cipher, StateName, ct).ConfigureAwait(false); + if (version == state.ScopeVersion && scope.Count == state.Scope.Count && + scope.All(pair => state.Scope.TryGetValue(pair.Key, out var existing) && existing == pair.Value)) + { + await CompleteNoticesAsync(state, ct).ConfigureAwait(false); + await CompleteDeletesAsync(state, ct).ConfigureAwait(false); + return; + } + if (version <= state.ScopeVersion) throw new InvalidOperationException("Scope version must increase."); + var old = state.Scope; + state.Scope = new Dictionary(scope, StringComparer.Ordinal); + state.ScopeVersion = version; + var orphaned = old.Values.Except(state.Scope.Values, StringComparer.Ordinal).ToArray(); + foreach (var reference in orphaned) + if (state.Versions.TryGetValue(reference, out var retired)) { retired.Deleted = true; retired.Pending = false; } + foreach (var pair in old.Where(p => !state.Scope.TryGetValue(p.Key, out var reference) || reference != p.Value)) + state.PendingNotices.Add(pair.Key); + foreach (var reference in orphaned) state.PendingDeletes.Add(reference); + if (state.PendingNotices.Count > MaximumReferences || state.PendingDeletes.Count > MaximumReferences) + throw new InvalidOperationException("Pending retirement capacity exceeded."); + // A reintroduced reference stays denied by its tombstone, but is no longer safe to delete. + state.PendingDeletes.ExceptWith(state.Scope.Values); + await SaveAsync(state, ct).ConfigureAwait(false); + await CompleteNoticesAsync(state, ct).ConfigureAwait(false); + await CompleteDeletesAsync(state, ct).ConfigureAwait(false); + } + finally { Gate.Release(); } + } + + private async Task CompleteNoticesAsync(DataCredentialState state, CancellationToken ct) + { + if (state.PendingNotices.Count == 0) return; + _changes.NotifyConnectionsChanged(state.PendingNotices); + state.PendingNotices.Clear(); + await SaveAsync(state, ct).ConfigureAwait(false); + } + + private async Task CompleteDeletesAsync(DataCredentialState state, CancellationToken ct) + { + foreach (var reference in state.PendingDeletes.ToArray()) + { + if (state.Scope.Values.Contains(reference, StringComparer.Ordinal)) continue; + await _store.DeleteAsync(StoreName(reference), "data-connection", ct).ConfigureAwait(false); + _invalidator.Invalidate(StoreName(reference)); + state.PendingDeletes.Remove(reference); + state.Versions.Remove(reference); + await SaveAsync(state, ct).ConfigureAwait(false); + } + } + + /// Validates node, scope and monotonic versions before importing a bundle. + public async Task ApplyAsync(DataConnectionCredentialBundle bundle, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(bundle); + if (NormalizeId(bundle.OwnerCluster) != _owner || NormalizeId(bundle.ConsumerNode) != _node || bundle.Version <= 0 || bundle.Entries is null) + throw new InvalidOperationException("Bundle scope is invalid."); + await Gate.WaitAsync(ct).ConfigureAwait(false); + try + { + var state = await ReadStateAsync(_store, _cipher, StateName, ct).ConfigureAwait(false); + if (bundle.ScopeVersion <= 0 || bundle.ScopeVersion != state.ScopeVersion) throw new InvalidOperationException("Bundle scope generation is stale."); + if (bundle.Entries.Count > MaximumReferences || state.Versions.Count + bundle.Entries.Count(e => !state.Versions.ContainsKey(e.SecretReference)) > MaximumReferences) + throw new InvalidOperationException("Credential history capacity exceeded."); + var seen = new HashSet(StringComparer.Ordinal); + var pending = new List(); + foreach (var entry in bundle.Entries) + { + if (!seen.Add(entry.SecretReference) || !state.Scope.TryGetValue(NormalizeId(entry.ConnectionId), out var reference) || reference != entry.SecretReference || + (!entry.Deleted && string.IsNullOrEmpty(entry.Value))) + throw new InvalidOperationException("Bundle entry is invalid or unauthorized."); + if (state.Versions.TryGetValue(reference, out var current) && bundle.Version <= current.Version) + { + if (bundle.Version != current.Version || current.ScopeVersion != bundle.ScopeVersion || + current.Deleted != entry.Deleted || current.PayloadHash != PayloadHash(entry.Value, entry.Deleted)) + throw new InvalidOperationException("Bundle entry is stale or differs from the committed version."); + if (!current.Pending) + { + var row = await _store.GetAsync(StoreName(reference), ct).ConfigureAwait(false); + if (entry.Deleted ? row is not null : row is null || PayloadHash(_cipher.Decrypt(row), false) != current.PayloadHash) + throw new InvalidOperationException("Committed credential no longer matches its version."); + continue; + } + } + pending.Add(entry); + } + if (pending.Count == 0) return; + // Persist denial first: interruption, encryption failure or partial writes cannot expose mixed state. + foreach (var entry in pending) + state.Versions[entry.SecretReference] = new DataCredentialVersion { Version = bundle.Version, Deleted = entry.Deleted, Pending = true, PayloadHash = PayloadHash(entry.Value, entry.Deleted), ScopeVersion = bundle.ScopeVersion }; + await SaveAsync(state, ct).ConfigureAwait(false); + var changedReferences = pending.Select(e => e.SecretReference).ToHashSet(StringComparer.Ordinal); + _changes.NotifyConnectionsChanged(state.Scope.Where(p => changedReferences.Contains(p.Value)).Select(p => p.Key)); + foreach (var entry in pending) + { + var name = StoreName(entry.SecretReference); + if (entry.Deleted) await _store.DeleteAsync(name, "data-connection", ct).ConfigureAwait(false); + else await _store.UpsertAsync(_cipher.Encrypt(name, entry.Value!, SecretContentType.Text) with + { Description = "Node-local data connection credential", CreatedBy = "data-connection", UpdatedBy = "data-connection" }, ct).ConfigureAwait(false); + _invalidator.Invalidate(name); + } + foreach (var entry in pending) state.Versions[entry.SecretReference].Pending = false; + await SaveAsync(state, ct).ConfigureAwait(false); + } + finally { Gate.Release(); } + } +} + +/// Reads one bounded, locally mounted JSON bundle; deployment artifacts do not contain its contents. +public sealed class DataConnectionBundleReader(string path) +{ + public async Task ReadAsync(CancellationToken ct) + { + const int maximumBytes = 1024 * 1024; + await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, 4096, true); + if (stream.Length > maximumBytes) throw new InvalidDataException("Credential bundle exceeds the size limit."); + using var buffer = new MemoryStream(); + var bytes = new byte[8192]; + int count; + while ((count = await stream.ReadAsync(bytes, ct).ConfigureAwait(false)) != 0) + { + if (buffer.Length + count > maximumBytes) throw new InvalidDataException("Credential bundle exceeds the size limit."); + buffer.Write(bytes, 0, count); + } + return JsonSerializer.Deserialize(buffer.GetBuffer().AsSpan(0, checked((int)buffer.Length))) + ?? throw new InvalidDataException("Credential bundle is empty."); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionSecurityProvider.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionSecurityProvider.cs new file mode 100644 index 000000000..350b68301 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionSecurityProvider.cs @@ -0,0 +1,63 @@ +using System.Collections.Concurrent; +using System.Globalization; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.Secrets.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.Host.Configuration; + +/// Adapts node-local credentials and trust to runtime channel security. +public sealed class DataConnectionSecurityProvider : IDataConnectionSecurityProvider, IDisposable +{ + private readonly DataConnectionCredentialResolver _credentials; + private readonly DataConnectionTrustPolicyStore _trust; + private readonly DataConnectionSecretChangeHandler _changes; + private readonly ConcurrentDictionary _observed = new(StringComparer.Ordinal); + private long _generation; + public DataConnectionSecurityProvider(DataConnectionCredentialResolver credentials, DataConnectionTrustPolicyStore trust, DataConnectionSecretChangeHandler changes) + { + _credentials = credentials; _trust = trust; _changes = changes; + changes.ConnectionChanged += OnConnectionChanged; + changes.SecretChanged += OnSecretChanged; + } + public event Action? Changed; + internal Func? AfterEligibilityForTest { get; set; } + internal int ObservedCountForTest => _observed.Count; + public async ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) + { + if (endpoint.Scheme != Uri.UriSchemeHttps) return null; + connectionId = DataConnectionSecretProvisioner.NormalizeId(connectionId); + long generation; + lock (_observed) generation = _generation; + if (!await _credentials.IsEligibleAsync(connectionId, cancellationToken).ConfigureAwait(false)) return null; + if (AfterEligibilityForTest is { } pause) await pause().ConfigureAwait(false); + var credential = await _credentials.ResolveAsync(connectionId, cancellationToken).ConfigureAwait(false); + var trust = await _trust.ResolveAsync(connectionId, cancellationToken).ConfigureAwait(false); + if (credential is null || trust is null) return null; + lock (_observed) + { + // Any scope, credential or trust signal during resolution invalidates the whole snapshot. + if (_generation != generation) return null; + if (!_observed.ContainsKey(connectionId) && _observed.Count >= DataConnectionSecretProvisioner.MaximumReferences) return null; + _observed[connectionId] = credential.SecretName; + } + return new DataConnectionSecurity(credential.Version.ToString(CultureInfo.InvariantCulture), + trust.Version.ToString(CultureInfo.InvariantCulture) + ":" + trust.Fingerprint, credential.Value, trust.CreateHandler); + } + private void OnConnectionChanged(string connectionId) + { + connectionId = DataConnectionSecretProvisioner.NormalizeId(connectionId); + lock (_observed) { checked { _generation++; } _observed.TryRemove(connectionId, out _); } + DataConnectionSecretChangeHandler.Broadcast(Changed, connectionId); + } + // Compare the physical name captured during resolution; never read the store in an invalidation callback. + private void OnSecretChanged(SecretName name) + { + string[] ids; + lock (_observed) { checked { _generation++; } ids = _observed.Where(pair => string.Equals(pair.Value, name.Value, StringComparison.Ordinal)).Select(pair => pair.Key).ToArray(); } + List? failures = null; + foreach (var id in ids) + try { OnConnectionChanged(id); } catch (Exception ex) { (failures ??= []).Add(ex); } + if (failures is not null) throw new AggregateException(failures); + } + public void Dispose() { _changes.ConnectionChanged -= OnConnectionChanged; _changes.SecretChanged -= OnSecretChanged; } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionServerCertificate.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionServerCertificate.cs new file mode 100644 index 000000000..81b9fd804 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionServerCertificate.cs @@ -0,0 +1,25 @@ +using System.Security.Cryptography.X509Certificates; + +namespace ZB.MOM.WW.OtOpcUa.Host.Configuration; + +/// Loads the dedicated listener certificate once; server rotation uses a rolling restart. +internal static class DataConnectionServerCertificate +{ + internal static X509Certificate2 Load(DataConnectionOptions options) + { + var path = options.CertificatePath ?? throw new InvalidOperationException("Missing data listener certificate."); + var certificate = Path.GetExtension(path).Equals(".pfx", StringComparison.OrdinalIgnoreCase) + || Path.GetExtension(path).Equals(".p12", StringComparison.OrdinalIgnoreCase) + ? X509CertificateLoader.LoadPkcs12FromFile(path, null) + : X509Certificate2.CreateFromPemFile(path, options.CertificateKeyPath ?? path); + try + { + if (!certificate.HasPrivateKey || certificate.NotBefore.ToUniversalTime() > DateTime.UtcNow + || certificate.NotAfter.ToUniversalTime() <= DateTime.UtcNow + || options.AllowedHosts.Any(host => !certificate.MatchesHostname(host.Trim('[', ']'), allowCommonName: false))) + throw new InvalidOperationException("Data listener certificate must have a current private key and SANs for every allowed host."); + return certificate; + } + catch { certificate.Dispose(); throw; } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionTrustPolicy.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionTrustPolicy.cs new file mode 100644 index 000000000..78b84a9b9 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionTrustPolicy.cs @@ -0,0 +1,175 @@ +using System.Net.Security; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; + +namespace ZB.MOM.WW.OtOpcUa.Host.Configuration; + +/// Immutable custom-root trust for an outbound channel; hostname validation remains mandatory. +public sealed class DataConnectionTrustPolicy +{ + private readonly X509Certificate2[] _roots; + public DataConnectionTrustPolicy(long version, IEnumerable roots) + { + if (version <= 0) throw new ArgumentOutOfRangeException(nameof(version)); + Version = version; + _roots = roots.Select(c => X509CertificateLoader.LoadCertificate(c.RawData)).ToArray(); + if (_roots.Length == 0) throw new ArgumentException("At least one trust root is required.", nameof(roots)); + var hashes = _roots.Select(c => Convert.ToHexString(SHA256.HashData(c.RawData))).Order(StringComparer.Ordinal); + Fingerprint = Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(string.Join(";", hashes)))); + } + public long Version { get; } + public string Fingerprint { get; } + public HttpMessageHandler CreateHandler() => new HttpClientHandler { ServerCertificateCustomValidationCallback = Validate }; + internal bool Validate(HttpRequestMessage request, X509Certificate2? certificate, X509Chain? suppliedChain, SslPolicyErrors errors) + { + if (certificate is null || (errors & (SslPolicyErrors.RemoteCertificateNameMismatch | SslPolicyErrors.RemoteCertificateNotAvailable)) != 0) return false; + if (request.RequestUri is null || !certificate.MatchesHostname(request.RequestUri.IdnHost, allowWildcards: true, allowCommonName: false)) return false; + using var chain = new X509Chain(); + chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; + chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; + chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.1")); + chain.ChainPolicy.CustomTrustStore.AddRange(_roots); + if (suppliedChain is not null) + foreach (var element in suppliedChain.ChainElements.Cast().Skip(1)) chain.ChainPolicy.ExtraStore.Add(element.Certificate); + return chain.Build(certificate); + } +} + +/// Persists independent per-connection trust versions and explicit removal markers. +public sealed class DataConnectionTrustPolicyStore( + ZB.MOM.WW.Secrets.Abstractions.ISecretStore store, + ZB.MOM.WW.Secrets.Abstractions.ISecretCipher cipher, + DataConnectionSecretChangeHandler changes, string ownerCluster, string consumerNode) +{ + public const int MaximumConnections = 256; + public const int MaximumRootCertificates = 256; + public const long MaximumTrustBytes = 1024 * 1024; + private readonly ZB.MOM.WW.Secrets.Abstractions.SecretName _name = new("data-connection/trust/" + + Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(DataConnectionSecretProvisioner.NormalizeId(ownerCluster) + "\0" + DataConnectionSecretProvisioner.NormalizeId(consumerNode)))).ToLowerInvariant()); + private sealed class Entry { public long Version { get; set; } public string[]? Roots { get; set; } public bool PendingNotice { get; set; } public bool Retired { get; set; } public long ScopeVersion { get; set; } } + private sealed class State + { + public long ScopeVersion { get; set; } + public HashSet Scope { get; set; } = new(StringComparer.Ordinal); + public Dictionary Entries { get; set; } = new(StringComparer.Ordinal); + public HashSet PendingNotices { get; set; } = new(StringComparer.Ordinal); + } + private async Task ReadAsync(CancellationToken ct) + { + var row = await store.GetAsync(_name, ct).ConfigureAwait(false); + return row is null ? new State() : System.Text.Json.JsonSerializer.Deserialize(cipher.Decrypt(row)) + ?? throw new InvalidOperationException("Invalid trust state."); + } + private Task SaveAsync(State state, CancellationToken ct) => store.UpsertAsync(cipher.Encrypt(_name, + System.Text.Json.JsonSerializer.Serialize(state), ZB.MOM.WW.Secrets.Abstractions.SecretContentType.Text), ct); + private async Task CompleteScopeAsync(State state, CancellationToken ct) + { + if (state.PendingNotices.Count > 0) changes.NotifyConnectionsChanged(state.PendingNotices); + state.PendingNotices.Clear(); + foreach (var id in state.Entries.Where(pair => pair.Value.Retired || !state.Scope.Contains(pair.Key)).Select(pair => pair.Key).ToArray()) state.Entries.Remove(id); + await SaveAsync(state, ct).ConfigureAwait(false); + } + /// Persist the authoritative applied scope revision before retiring old trust identities. + public async Task ApplyScopeAsync(long scopeVersion, IEnumerable connectionIds, CancellationToken ct) + { + var scope = new HashSet(StringComparer.Ordinal); + foreach (var id in connectionIds) + if (!scope.Add(DataConnectionSecretProvisioner.NormalizeId(id))) throw new InvalidOperationException("Duplicate connection identity."); + if (scopeVersion <= 0 || scope.Count > MaximumConnections || scope.Any(string.IsNullOrWhiteSpace)) throw new InvalidOperationException("Invalid trust scope."); + await DataConnectionSecretProvisioner.Gate.WaitAsync(ct).ConfigureAwait(false); + try + { + var state = await ReadAsync(ct).ConfigureAwait(false); + if (scopeVersion == state.ScopeVersion && scope.SetEquals(state.Scope)) { await CompleteScopeAsync(state, ct).ConfigureAwait(false); return; } + if (scopeVersion <= state.ScopeVersion) throw new InvalidOperationException("Trust scope version must increase."); + var removed = state.Scope.Except(scope).ToArray(); + state.PendingNotices.UnionWith(removed); + foreach (var id in removed) if (state.Entries.TryGetValue(id, out var retired)) retired.Retired = true; + if (state.PendingNotices.Count > MaximumConnections) throw new InvalidOperationException("Trust retirement capacity exceeded."); + state.Scope = scope; state.ScopeVersion = scopeVersion; + await SaveAsync(state, ct).ConfigureAwait(false); + await CompleteScopeAsync(state, ct).ConfigureAwait(false); + } + finally { DataConnectionSecretProvisioner.Gate.Release(); } + } + /// Atomically updates trust, or persists a tombstone when roots is empty. + public Task SetAsync(string connectionId, long version, IEnumerable roots, long scopeVersion, CancellationToken ct) => + SetBundleCoreAsync([(connectionId, version, roots.ToArray())], scopeVersion, false, ct); + + /// Atomically stages all trust changes before retiring channels and committing the batch. + public Task SetBundleAsync(IReadOnlyList<(string ConnectionId, long Version, X509Certificate2[] Roots)> entries, long scopeVersion, CancellationToken ct) => + SetBundleCoreAsync(entries, scopeVersion, true, ct); + + private async Task SetBundleCoreAsync(IReadOnlyList<(string ConnectionId, long Version, X509Certificate2[] Roots)> entries, long scopeVersion, bool allowCompletedReplay, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(entries); + if (entries.Count > MaximumConnections) throw new InvalidOperationException("Trust bundle capacity exceeded."); + var rootCount = 0; long totalBytes = 0; + foreach (var entry in entries) + { + ArgumentNullException.ThrowIfNull(entry.Roots); + foreach (var root in entry.Roots) + { + ArgumentNullException.ThrowIfNull(root); + rootCount = checked(rootCount + 1); + totalBytes = checked(totalBytes + root.RawData.Length); + if (rootCount > MaximumRootCertificates || totalBytes > MaximumTrustBytes) + throw new InvalidOperationException("Trust bundle capacity exceeded."); + } + } + var items = entries.Select(e => (ConnectionId: DataConnectionSecretProvisioner.NormalizeId(e.ConnectionId), e.Version, + Roots: e.Roots.Select(c => Convert.ToBase64String(c.RawData)).ToArray())).ToArray(); + if (items.Any(e => e.Version <= 0) || items.Select(e => e.ConnectionId).Distinct(StringComparer.Ordinal).Count() != items.Length) + throw new InvalidOperationException("Invalid or duplicate trust entry."); + await DataConnectionSecretProvisioner.Gate.WaitAsync(ct).ConfigureAwait(false); + try + { + var state = await ReadAsync(ct).ConfigureAwait(false); + if (scopeVersion <= 0 || state.ScopeVersion != scopeVersion) throw new InvalidOperationException("Trust scope is stale."); + var pending = new List<(string ConnectionId, long Version, string[] Roots)>(); + foreach (var item in items) + { + if (!state.Scope.Contains(item.ConnectionId) || state.PendingNotices.Contains(item.ConnectionId)) + throw new InvalidOperationException("Trust scope is unavailable."); + if (state.Entries.TryGetValue(item.ConnectionId, out var old) && item.Version <= old.Version) + { + if (item.Version != old.Version || old.ScopeVersion != scopeVersion || old.Retired || + old.Roots is null || !old.Roots.SequenceEqual(item.Roots, StringComparer.Ordinal)) + throw new InvalidOperationException("Trust version is stale or differs from the committed version."); + if (!old.PendingNotice) + { + if (!allowCompletedReplay) throw new InvalidOperationException("Trust version must increase."); + continue; + } + } + pending.Add(item); + } + if (state.Entries.Count + pending.Count(e => !state.Entries.ContainsKey(e.ConnectionId)) > MaximumConnections) + throw new InvalidOperationException("Trust history capacity exceeded."); + if (pending.Count == 0) return; + foreach (var item in pending) + state.Entries[item.ConnectionId] = new Entry { Version = item.Version, Roots = item.Roots, PendingNotice = true, ScopeVersion = scopeVersion }; + await SaveAsync(state, ct).ConfigureAwait(false); + changes.NotifyConnectionsChanged(pending.Select(x => x.ConnectionId)); + foreach (var item in pending) state.Entries[item.ConnectionId].PendingNotice = false; + await SaveAsync(state, ct).ConfigureAwait(false); + } + finally { DataConnectionSecretProvisioner.Gate.Release(); } + } + public async Task ResolveAsync(string connectionId, CancellationToken ct) + { + connectionId = DataConnectionSecretProvisioner.NormalizeId(connectionId); + await DataConnectionSecretProvisioner.Gate.WaitAsync(ct).ConfigureAwait(false); + try + { + var state = await ReadAsync(ct).ConfigureAwait(false); + if (!state.Scope.Contains(connectionId) || state.PendingNotices.Contains(connectionId) || !state.Entries.TryGetValue(connectionId, out var entry) || entry.PendingNotice || entry.Retired || entry.Roots is not { Length: > 0 }) return null; + var roots = entry.Roots.Select(s => X509CertificateLoader.LoadCertificate(Convert.FromBase64String(s))).ToArray(); + try { return new DataConnectionTrustPolicy(entry.Version, roots); } + finally { foreach (var root in roots) root.Dispose(); } + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } + catch (Exception) { return null; } + finally { DataConnectionSecretProvisioner.Gate.Release(); } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/SecretChangeSignallingInvalidator.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/SecretChangeSignallingInvalidator.cs index b1b8d28ee..0deea4334 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/SecretChangeSignallingInvalidator.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/SecretChangeSignallingInvalidator.cs @@ -12,7 +12,7 @@ namespace ZB.MOM.WW.OtOpcUa.Host.Configuration; /// The library's invalidator (the resolver cache). /// The node's directory, or null on a node that runs no drivers. internal sealed class SecretChangeSignallingInvalidator( - ISecretCacheInvalidator inner, GalaxyAckIdentityDirectory? directory) : ISecretCacheInvalidator + ISecretCacheInvalidator inner, GalaxyAckIdentityDirectory? directory, DataConnectionSecretChangeHandler? dataChanges = null) : ISecretCacheInvalidator { /// Gets the decorated invalidator (test seam). internal ISecretCacheInvalidator Inner => inner; @@ -20,7 +20,10 @@ internal sealed class SecretChangeSignallingInvalidator( /// public void Invalidate(SecretName name) { - inner.Invalidate(name); - directory?.NotifySecretChanged(name); + List? failures = null; + try { inner.Invalidate(name); } catch (Exception ex) { (failures ??= []).Add(ex); } + try { directory?.NotifySecretChanged(name); } catch (Exception ex) { (failures ??= []).Add(ex); } + try { dataChanges?.NotifySecretChanged(name); } catch (Exception ex) { (failures ??= []).Add(ex); } + if (failures is not null) throw new AggregateException(failures); } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/SecretsRegistration.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/SecretsRegistration.cs index 4065f43a6..d94d3aa51 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/SecretsRegistration.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/SecretsRegistration.cs @@ -101,6 +101,7 @@ public static class SecretsRegistration (ISecretCacheInvalidator)(existing.ImplementationInstance ?? existing.ImplementationFactory?.Invoke(sp) ?? ActivatorUtilities.CreateInstance(sp, existing.ImplementationType!)), - sp.GetService())); + sp.GetService(), + sp.GetService())); } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcBinding.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcBinding.cs new file mode 100644 index 000000000..c24307d3f --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcBinding.cs @@ -0,0 +1,91 @@ +using System.Runtime.CompilerServices; +using Google.Protobuf; +using Grpc.Core; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Host.Grpc; + +/// Installs the publication marshaller on the actual generated data-service binding. +public static class DataConnectionGrpcBinding +{ + // ASP.NET discovery passes null and resolves overrides against this generated base type. + public static void BindService(ServiceBinderBase binder, W.DataConnectionService.DataConnectionServiceBase service) => + W.DataConnectionService.BindService(new PublicationBinder(binder), service); + + private sealed class PublicationBinder(ServiceBinderBase inner) : ServiceBinderBase + { + private static Method Wrap(Method method) + where TRequest : class where TResponse : class => new(method.Type, method.ServiceName, method.Name, + method.RequestMarshaller, new Marshaller((response, context) => + DataConnectionPublication.Serialize((IMessage)response, context), method.ResponseMarshaller.ContextualDeserializer)); + + public override void AddMethod(Method method, + UnaryServerMethod? handler) => inner.AddMethod(Wrap(method), handler is null ? null : + (request, context) => { context.WriteOptions = new(WriteFlags.NoCompress); return handler(request, context); }); + + public override void AddMethod(Method method, + DuplexStreamingServerMethod? handler) => inner.AddMethod(Wrap(method), handler is null ? null : + (requests, responses, context) => + { + context.WriteOptions = new(WriteFlags.NoCompress); + responses.WriteOptions = new(WriteFlags.NoCompress); + return handler(requests, responses, context); + }); + } +} + +/// Call-owned bounded preparation with one final synchronous transport-buffer handoff. +public static class DataConnectionPublication +{ + private static readonly ConditionalWeakTable Pending = new(); + + /// The caller must retain and dispose this registration through HTTP completion or actual stream write. + public static IDisposable Register(IMessage response, Func canPublish, int maxBytes, byte[]? prepared = null) + => Register(response, canPublish, maxBytes, prepared, null); + + internal static IDisposable RegisterUnary(IMessage response, Func canPublish, int maxBytes, + DataConnectionUnaryLifetime deadline) => Register(response, canPublish, maxBytes, null, deadline); + + private static IDisposable Register(IMessage response, Func canPublish, int maxBytes, byte[]? prepared, + DataConnectionUnaryLifetime? deadline) + { + ArgumentNullException.ThrowIfNull(response); ArgumentNullException.ThrowIfNull(canPublish); + if (maxBytes <= 0 || prepared is { Length: var length } && length > maxBytes) throw new ArgumentOutOfRangeException(nameof(maxBytes)); + var publication = new Publication(response, canPublish, maxBytes, prepared, deadline); + Pending.Add(response, publication); + return publication; + } + + internal static void Serialize(IMessage response, SerializationContext context) + { + if (!Pending.TryGetValue(response, out var publication)) throw Refused(); + publication.Serialize(context); + } + + private sealed class Publication(IMessage response, Func canPublish, int maximum, byte[]? prepared, + DataConnectionUnaryLifetime? deadline) : IDisposable + { + private int _state; + public void Serialize(SerializationContext context) + { + if (Interlocked.CompareExchange(ref _state, 1, 0) != 0) throw Refused(); + try + { + // Never lend the protobuf serializer the real response pipe before authorization. + if (response.CalculateSize() > maximum) throw new RpcException(new Status(StatusCode.ResourceExhausted, "Data message exceeds transport limits.")); + var payload = prepared ?? response.ToByteArray(); + if (payload.Length > maximum) throw new RpcException(new Status(StatusCode.ResourceExhausted, "Data message exceeds transport limits.")); + var allowed = canPublish(); + if (!allowed || Volatile.Read(ref _state) != 1 || deadline is { IsActive: false }) throw Refused(); + // The actual service path enforces NoCompress. This synchronous Complete is + // buffer handoff, not evidence of a network flush or a remote client's receipt. + context.Complete(payload); + Interlocked.CompareExchange(ref _state, 2, 1); + } + finally { Pending.Remove(response); } + } + public void Dispose() { Interlocked.Exchange(ref _state, 3); Pending.Remove(response); } + } + + private static RpcException Refused() => new(new Status(StatusCode.Unavailable, "Data publication authority changed.")); +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs new file mode 100644 index 000000000..ce88e0bb2 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs @@ -0,0 +1,287 @@ +using Google.Protobuf; +using Grpc.Core; +using Microsoft.Extensions.Options; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Host.Grpc; + +/// Dedicated authenticated transport over the caller-bound origin-local ports. +[BindServiceMethod(typeof(DataConnectionGrpcBinding), nameof(DataConnectionGrpcBinding.BindService))] +public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IOptions options, + DataConnectionAuthenticator authenticator) : W.DataConnectionService.DataConnectionServiceBase +{ + private readonly DataConnectionOptions _options = options.Value; + + public override Task GetCapabilities(W.CapabilitiesRequest request, ServerCallContext context) => + Execute(context, async (connection, caller, token) => + { + if (request.ProtocolMajor != 1) throw new RpcException(new Status(StatusCode.Unimplemented, "Incompatible protocol major.")); + var budget = new DataBudget(_options.UnaryTimeout, 1, _options.MaxMessageBytes); + var capabilities = await connection.GetCapabilitiesAsync(budget, token).ConfigureAwait(false); + var response = DataProtoMapper.EncodeCapabilities(capabilities with + { ProtocolMinor = Math.Max(2, capabilities.ProtocolMinor), ResponseServingIdentity = true, SubscriptionAgeReadiness = true }); + CheckSize(response); + var current = await connection.GetCapabilitiesAsync(budget, token).ConfigureAwait(false); + if (!authenticator.IsCurrent(caller) || current.Serving != capabilities.Serving + || current.Readiness != capabilities.Readiness || current.Operations != capabilities.Operations) + throw Unavailable(); + Register(context, response, () => authenticator.IsCurrent(caller) + && !token.IsCancellationRequested + && connection is IDataConnectionDiscoveryGate gate && gate.CanPublishCapabilities(capabilities)); + return response; + }); + + public override Task Browse(W.BrowseRequest request, ServerCallContext context) => + Execute(context, async (connection, caller, token) => + { + var caps = await Ready(connection, DataOperations.Browse, token).ConfigureAwait(false); + var decoded = DataProtoMapper.DecodeBrowseRequest(request, DecodeLimits(caps)); + var result = await connection.BrowseAsync(decoded with { Budget = Clamp(decoded.Budget) }, token).ConfigureAwait(false); + var response = DataProtoMapper.EncodeBrowseResponse(result); + response.Serving = DataProtoMapper.EncodeServing(caps.Serving); + CheckSize(response); + Register(context, response, () => !token.IsCancellationRequested && CanPublish(connection, caller, caps.Serving)); + return response; + }); + + public override Task GetMetadata(W.MetadataRequest request, ServerCallContext context) => + Execute(context, async (connection, caller, token) => + { + var caps = await Ready(connection, DataOperations.Metadata, token).ConfigureAwait(false); + var decoded = DataProtoMapper.DecodeMetadataRequest(request, DecodeLimits(caps)); + var result = await connection.GetMetadataAsync(decoded with { Budget = Clamp(decoded.Budget) }, token).ConfigureAwait(false); + var response = DataProtoMapper.EncodeMetadataResponse(result); + response.Serving = DataProtoMapper.EncodeServing(caps.Serving); + CheckSize(response); + Register(context, response, () => !token.IsCancellationRequested && CanPublish(connection, caller, caps.Serving)); + return response; + }); + + public override Task Read(W.ReadRequest request, ServerCallContext context) => + Execute(context, async (connection, caller, token) => + { + var caps = await Ready(connection, DataOperations.Read, token).ConfigureAwait(false); + var decoded = DataProtoMapper.DecodeReadRequest(request, DecodeLimits(caps)); + var results = await connection.ReadAsync(decoded with { Budget = Clamp(decoded.Budget) }, token).ConfigureAwait(false); + foreach (var result in results) context.GetHttpContext().Response.RegisterForDispose(result); + var response = DataProtoMapper.EncodeReadResponse(results); + response.Serving = DataProtoMapper.EncodeServing(caps.Serving); + CheckSize(response); + Register(context, response, () => !token.IsCancellationRequested + && CanPublish(connection, caller, caps.Serving) + && results.All(result => result.Sample is null || result.ResourceLease is IDataPublicationLease { IsValid: true })); + return response; + }); + + public override Task Write(W.WriteRequest request, ServerCallContext context) => + Execute(context, async (connection, caller, token) => + { + var caps = await connection.GetCapabilitiesAsync(DiscoveryBudget, token).ConfigureAwait(false); + var limits = DecodeLimits(caps); + var decoded = DataProtoMapper.DecodeWriteRequest(request, limits.MaxItems, limits.MaxBytes, limits.MaxValueElements); + try + { + var results = caps.Readiness == DataReadiness.Ready && caps.Operations.HasFlag(DataOperations.Write) + ? await connection.WriteAsync(decoded with { Budget = Clamp(decoded.Budget) }, token).ConfigureAwait(false) + : decoded.Items.Select(item => new WriteItemResult(item.CorrelationId, + new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Write unavailable before dispatch."))).ToArray(); + var serving = caps.Serving; + DataCapabilities? rejectionCaps = null; + if (results.All(result => result.Outcome.State == DataWriteState.RejectedBeforeDispatch)) + { + var current = await connection.GetCapabilitiesAsync(DiscoveryBudget, token).ConfigureAwait(false); + if (current.Serving.NodeId != serving.NodeId || current.Serving.Incarnation != serving.Incarnation) throw Unavailable(); + rejectionCaps = current; serving = current.Serving; + } + var response = DataProtoMapper.EncodeWriteResponse(results); + response.Serving = DataProtoMapper.EncodeServing(serving); + CheckSize(response); + Register(context, response, () => !token.IsCancellationRequested && authenticator.IsCurrent(caller) + && (rejectionCaps is { } negative + ? connection is IDataConnectionDiscoveryGate discovery && discovery.CanPublishCapabilities(negative) + : CanPublish(connection, caller, serving))); + return response; + } + finally { foreach (var item in decoded.Items) item.Value.Dispose(); } + }); + + private DataBudget DiscoveryBudget => new(_options.UnaryTimeout, 1, _options.MaxMessageBytes); + private DataBudget Clamp(DataBudget budget) => budget with + { Timeout = budget.Timeout <= _options.UnaryTimeout ? budget.Timeout : _options.UnaryTimeout, + MaxBytes = Math.Min(budget.MaxBytes, _options.MaxMessageBytes) }; + private DataDecodeLimits DecodeLimits(DataCapabilities caps) => new(caps.Limits.MaxBatchItems, + Math.Min(caps.Limits.MaxMessageBytes, _options.MaxMessageBytes), caps.Limits.MaxValueElements); + private async Task Ready(IDataConnection connection, DataOperations operation, CancellationToken token) + { + var caps = await connection.GetCapabilitiesAsync(DiscoveryBudget, token).ConfigureAwait(false); + if (caps.Readiness != DataReadiness.Ready) throw Unavailable(); + if (!caps.Operations.HasFlag(operation)) throw new RpcException(new Status(StatusCode.PermissionDenied, "Data operation denied.")); + return caps; + } + private bool CanPublish(IDataConnection connection, DataAuthenticatedContext caller, ServingIdentity expected) => + authenticator.IsCurrent(caller) && connection is IDataConnectionPublicationGate gate && gate.CanPublish(expected); + + public override async Task Subscribe(IAsyncStreamReader requests, + IServerStreamWriter responses, ServerCallContext context) + { + try + { + context.WriteOptions = new(WriteFlags.NoCompress); + responses.WriteOptions = new(WriteFlags.NoCompress); + var (caller, target) = AuthenticateCall(context); + await using var connection = factory.Create(caller, target); + DataCapabilities caps; + IDataSubscription subscription; + using (var initial = CancellationTokenSource.CreateLinkedTokenSource(context.CancellationToken)) + { + initial.CancelAfter(_options.UnaryTimeout); + caps = await Ready(connection, DataOperations.Subscribe, initial.Token).ConfigureAwait(false); + } + subscription = await connection.SubscribeAsync(context.CancellationToken).ConfigureAwait(false); + await using (subscription) + { + if (subscription is not IDataSubscriptionTransport transport) + throw new RpcException(new Status(StatusCode.Unavailable, "Subscription transport is unavailable.")); + using var stop = CancellationTokenSource.CreateLinkedTokenSource(context.CancellationToken); + var sink = new GrpcDeliverySink(responses, context, caps, _options.MaxMessageBytes, + () => CanPublish(connection, caller, caps.Serving)); + var delivery = transport.RunDeliveryAsync(sink, stop.Token); + var commands = ReceiveCommands(); + try { await await Task.WhenAny(delivery, commands).ConfigureAwait(false); } + finally + { + await stop.CancelAsync().ConfigureAwait(false); + await subscription.DisposeAsync().ConfigureAwait(false); + try { await Task.WhenAll(delivery, commands).ConfigureAwait(false); } + catch (OperationCanceledException) when (stop.IsCancellationRequested) { } + } + + async Task ReceiveCommands() + { + var limits = DecodeLimits(caps) with { MaxItems = caps.Limits.MaxMonitoredItems }; + while (await requests.MoveNext(stop.Token).ConfigureAwait(false)) + { + if (!CanPublish(connection, caller, caps.Serving)) throw Unavailable(); + var command = DataProtoMapper.DecodeCommand(requests.Current, limits); + var ack = command.AcknowledgementTimeout <= _options.StreamCommandTimeout + ? command.AcknowledgementTimeout : _options.StreamCommandTimeout; + command = command switch + { + OpenSubscription open => open with { AcknowledgementTimeout = ack, SnapshotBudget = Clamp(open.SnapshotBudget) }, + AddSubscriptionItems add => add with { AcknowledgementTimeout = ack }, + ModifySubscriptionItems modify => modify with { AcknowledgementTimeout = ack }, + RemoveSubscriptionItems remove => remove with { AcknowledgementTimeout = ack }, + _ => throw new ArgumentException("Unsupported stream command.") + }; + using var commandDeadline = CancellationTokenSource.CreateLinkedTokenSource(stop.Token); + commandDeadline.CancelAfter(_options.StreamCommandTimeout); + await subscription.SendAsync(command, commandDeadline.Token).ConfigureAwait(false); + } + } + } + } + catch (RpcException) { throw; } + catch (UnauthorizedAccessException) { throw new RpcException(new Status(StatusCode.Unauthenticated, "Data authentication failed.")); } + catch (ArgumentException) { throw new RpcException(new Status(StatusCode.InvalidArgument, "Invalid stream command.")); } + catch (InvalidOperationException) { throw Unavailable(); } + catch (OperationCanceledException) { throw new RpcException(new Status(StatusCode.Cancelled, "Data stream canceled.")); } + } + + private sealed class GrpcDeliverySink(IServerStreamWriter writer, ServerCallContext context, + DataCapabilities caps, int maximumBytes, Func hostGuard) : IDataSubscriptionDeliverySink + { + public ValueTask PrepareAsync(DataSubscriptionFrame frame, long reservedBytes, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + // Reserve conservatively before allocating protobuf payload copies or serialized bytes. + long charge = checked(2048L + 4L * frame.SubscriptionId.Length); + charge = frame switch + { + DataSubscriptionValues values => values.Items.Aggregate(charge, (sum, item) => checked(sum + + 4 * item.Sample.Value.EstimatedRetainedBytes + 2048L)), + DataSubscriptionAck ack => ack.Items.Aggregate(charge, (sum, item) => checked(sum + 2048L + + 4L * (item.ClientItemId.Length + (item.Diagnostic?.Length ?? 0)))), + DataSubscriptionControl control => checked(charge + 128L * control.Watermarks.Count + 4L * (control.Diagnostic?.Length ?? 0)), + _ => throw new ArgumentException("Unsupported subscription frame.") + }; + if (charge > reservedBytes) throw new RpcException(new Status(StatusCode.ResourceExhausted, "Prepared frame exceeds its reservation.")); + var wire = frame is DataSubscriptionValues valuesFrame + ? DataProtoMapper.EncodeValues(valuesFrame, compactNegotiated: false, subscriptionAgeReadiness: true) + : DataProtoMapper.EncodeControlOrAck(frame); + wire.Serving = DataProtoMapper.EncodeServing(caps.Serving); + if (wire.CalculateSize() > maximumBytes) throw new RpcException(new Status(StatusCode.ResourceExhausted, "Stream message exceeds transport limits.")); + var payload = wire.ToByteArray(); + if (charge < payload.Length) throw new RpcException(new Status(StatusCode.ResourceExhausted, "Prepared frame exceeds its reservation.")); + return ValueTask.FromResult(new PreparedDataSubscription(wire, payload, charge, + maximumBytes, hostGuard, cancellationToken, () => !context.CancellationToken.IsCancellationRequested + && context.WriteOptions is { Flags: var flags } && (flags & WriteFlags.NoCompress) != 0)); + } + public async ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken) => + await writer.WriteAsync(((PreparedDataSubscription)prepared).Frame, cancellationToken).ConfigureAwait(false); + } + + private (DataAuthenticatedContext Caller, DataTarget Target) AuthenticateCall(ServerCallContext context) + { + var http = context.GetHttpContext(); + if (!DataConnectionEndpoints.IsDataRequest(http, _options) + || http.Items[typeof(DataAuthenticatedContext)] is not DataAuthenticatedContext caller + || !authenticator.IsCurrent(caller)) + throw new RpcException(new Status(StatusCode.Unauthenticated, "Data authentication failed.")); + if (http.Items[typeof(DataTarget)] is not DataTarget target) throw new ArgumentException("Missing target policy."); + target.Validate(); + return (caller, target); + } + + private async Task Execute(ServerCallContext context, + Func> operation) + { + try + { + // ASP.NET discovers generated bindings with a null service instance and creates its + // invoker by reflection. The real execution path must own this flag, not a binder delegate. + context.WriteOptions = new(WriteFlags.NoCompress); + var http = context.GetHttpContext(); + var (caller, target) = AuthenticateCall(context); + if (!http.Items.ContainsKey(typeof(DataConnectionUnaryLifetime))) + http.Items[typeof(DataConnectionUnaryLifetime)] = new DataConnectionUnaryLifetime(TimeProvider.System, _options.UnaryTimeout); + var timeout = new CancellationTokenSource(_options.UnaryTimeout); + http.Response.RegisterForDispose(timeout); + var linked = CancellationTokenSource.CreateLinkedTokenSource(context.CancellationToken, timeout.Token); + http.Response.RegisterForDispose(linked); + http.Items[typeof(DataConnectionGrpcService)] = linked.Token; + var connection = factory.Create(caller, target); + http.Response.RegisterForDisposeAsync(connection); + return await operation(connection, caller, linked.Token).ConfigureAwait(false); + } + catch (RpcException) { throw; } + catch (UnauthorizedAccessException) { throw new RpcException(new Status(StatusCode.Unauthenticated, "Data authentication failed.")); } + catch (ArgumentException) { throw new RpcException(new Status(StatusCode.InvalidArgument, "Invalid data request.")); } + catch (InvalidOperationException) { throw Unavailable(); } + catch (OperationCanceledException) { throw new RpcException(new Status(StatusCode.Cancelled, "Data request canceled.")); } + } + + private void CheckSize(IMessage response) + { + if (response.CalculateSize() > _options.MaxMessageBytes) + throw new RpcException(new Status(StatusCode.ResourceExhausted, "Data response exceeds transport limits.")); + } + private void Register(ServerCallContext context, IMessage response, Func guard) + { + var http = context.GetHttpContext(); + var operationToken = http.Items[typeof(DataConnectionGrpcService)] is CancellationToken token ? token : context.CancellationToken; + var deadline = (DataConnectionUnaryLifetime)http.Items[typeof(DataConnectionUnaryLifetime)]!; + http.Response.RegisterForDispose(DataConnectionPublication.RegisterUnary(response, () => + { + var allowed = guard(); + // Publication validation may block; cancellation/deadline and compression flags are + // observed again afterwards, immediately before the marshaller's final state read. + return allowed && !operationToken.IsCancellationRequested && !context.CancellationToken.IsCancellationRequested + && context.WriteOptions is { Flags: var flags } && (flags & WriteFlags.NoCompress) != 0; + }, _options.MaxMessageBytes, deadline)); + } + private static RpcException Unavailable() => new(new Status(StatusCode.Unavailable, "Data serving identity or authority is unavailable.")); +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionUnaryLifetime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionUnaryLifetime.cs new file mode 100644 index 000000000..779adb45d --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionUnaryLifetime.cs @@ -0,0 +1,8 @@ +namespace ZB.MOM.WW.OtOpcUa.Host.Grpc; + +/// Checks the server's own unary budget without relying on timer callback scheduling. +internal sealed class DataConnectionUnaryLifetime(TimeProvider clock, TimeSpan duration) +{ + private readonly long _started = clock.GetTimestamp(); + internal bool IsActive => clock.GetElapsedTime(_started) < duration; +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/PreparedDataSubscription.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/PreparedDataSubscription.cs new file mode 100644 index 000000000..f6591a174 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/PreparedDataSubscription.cs @@ -0,0 +1,40 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Host.Grpc; + +/// Owned encoded frame whose final runtime proof is evaluated in the actual response marshaller. +internal sealed class PreparedDataSubscription : IDataPreparedSubscriptionPublication +{ + private readonly IDisposable _registration; + private Func? _runtimeGuard; + private int _disposed; + internal PreparedDataSubscription(W.SubscriptionFrame frame, byte[] payload, long retainedBytes, int maximumBytes, + Func hostGuard, CancellationToken token, Func? finalTransportReady = null) + { + ArgumentNullException.ThrowIfNull(frame); ArgumentNullException.ThrowIfNull(payload); ArgumentNullException.ThrowIfNull(hostGuard); + if (retainedBytes < payload.Length) throw new ArgumentOutOfRangeException(nameof(retainedBytes)); + Frame = frame; RetainedBytes = retainedBytes; + _registration = DataConnectionPublication.Register(frame, () => + { + if (Volatile.Read(ref _disposed) != 0 || !hostGuard()) return false; + var runtime = Volatile.Read(ref _runtimeGuard); + if (runtime is null || !runtime()) return false; + return Volatile.Read(ref _disposed) == 0 && !token.IsCancellationRequested + && (finalTransportReady is null || finalTransportReady()); + }, maximumBytes, payload); + } + internal W.SubscriptionFrame Frame { get; } + public long RetainedBytes { get; } + public void SetPublicationGuard(Func guard) + { + ArgumentNullException.ThrowIfNull(guard); + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); + if (Interlocked.CompareExchange(ref _runtimeGuard, guard, null) is not null) + throw new InvalidOperationException("A publication guard can be bound only once."); + } + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) == 0) _registration.Dispose(); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs index f42d5920b..fc88a0671 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs @@ -627,6 +627,7 @@ if (hasAdmin) // Registered unconditionally: driver-role nodes resolve Layer-B DriverConfig secrets and have no auth/DP/AdminUI. // Cluster replication is opt-in behind Secrets:Replication:Enabled (default false) — see SecretsRegistration. builder.Services.AddOtOpcUaSecrets(builder.Configuration); +var dataConnectionOptions = builder.Services.AddOtOpcUaDataConnections(builder.Configuration, builder.Environment, hasDriver); // hasAdmin gates the configdb probe: a driver-only node registers no ConfigDb factory (see above), so // probing it would throw when the readiness endpoint resolves the factory. hasDriver adds the @@ -668,6 +669,7 @@ if (hasDriver || hasAdmin) o.Interceptors.Add(); o.Interceptors.Add(); } + if (dataConnectionOptions.Enabled) o.Interceptors.Add(); // Innermost (after every auth gate): ends open streaming calls — the peer's LocalDb sync stream // above all — on ApplicationStopping instead of letting Kestrel's drain wait out ShutdownTimeout // (lmxopcua#906), and refuses new streams once stopping has begun. @@ -698,7 +700,11 @@ if (hasDriver || hasAdmin) var syncListenPort = hasDriver ? LocalDbRegistration.SyncListenPort(builder.Configuration) : 0; var configServeGrpcPort = hasAdmin ? builder.Configuration.GetValue("ConfigServe:GrpcListenPort") : 0; var telemetryListenPort = hasDriver ? builder.Configuration.GetValue("Telemetry:GrpcListenPort") : 0; -if (syncListenPort > 0 || configServeGrpcPort > 0 || telemetryListenPort > 0) +var dataListenPort = dataConnectionOptions.Enabled ? dataConnectionOptions.ListenPort : 0; +System.Security.Cryptography.X509Certificates.X509Certificate2? dataServerCertificate = null; +if (dataListenPort > 0 && new[] { syncListenPort, configServeGrpcPort, telemetryListenPort }.Contains(dataListenPort)) + throw new InvalidOperationException("DataConnections:ListenPort must be separate from every mesh listener."); +if (syncListenPort > 0 || configServeGrpcPort > 0 || telemetryListenPort > 0 || dataListenPort > 0) { // Mirror Kestrel's own source precedence: URLS wins; else the HTTP_PORTS/HTTPS_PORTS bare-port // vars; else Kestrel's localhost:5000 default. Missing the HTTP_PORTS leg is not academic — the @@ -745,6 +751,8 @@ if (syncListenPort > 0 || configServeGrpcPort > 0 || telemetryListenPort > 0) // Kestrel takeover). if (existingBindings.Any(b => b.IsSecure)) { + if (dataListenPort > 0) + throw new InvalidOperationException("The dedicated data listener cannot safely replay existing HTTPS URL bindings. Configure an HTTP UI/health binding and the dedicated data TLS certificate separately."); Log.Error( "A dedicated h2c listener is requested (LocalDb:SyncListenPort={SyncPort}, " + "ConfigServe:GrpcListenPort={ConfigServePort}, Telemetry:GrpcListenPort={TelemetryPort}) but this " + @@ -763,6 +771,10 @@ if (syncListenPort > 0 || configServeGrpcPort > 0 || telemetryListenPort > 0) var syncPortToBind = syncListenPort; var configServePortToBind = configServeGrpcPort; var telemetryPortToBind = telemetryListenPort; + if (dataListenPort > 0 && existingBindings.Any(binding => binding.Port == dataListenPort)) + throw new InvalidOperationException("DataConnections:ListenPort conflicts with an existing UI/health binding."); + if (dataListenPort > 0 && !dataConnectionOptions.AllowDevelopmentCleartext) + dataServerCertificate = DataConnectionServerCertificate.Load(dataConnectionOptions); builder.WebHost.ConfigureKestrel(kestrel => { foreach (var binding in existingBindings) @@ -774,6 +786,12 @@ if (syncListenPort > 0 || configServeGrpcPort > 0 || telemetryListenPort > 0) kestrel.ListenAnyIP(configServePortToBind, o => o.Protocols = HttpProtocols.Http2); if (telemetryPortToBind > 0) kestrel.ListenAnyIP(telemetryPortToBind, o => o.Protocols = HttpProtocols.Http2); + if (dataListenPort > 0) + kestrel.Listen(System.Net.IPAddress.Parse(dataConnectionOptions.ListenAddress), dataListenPort, listener => + { + listener.Protocols = HttpProtocols.Http2; + if (dataServerCertificate is not null) listener.UseHttps(dataServerCertificate); + }); }); Log.Information( @@ -785,6 +803,8 @@ if (syncListenPort > 0 || configServeGrpcPort > 0 || telemetryListenPort > 0) } var app = builder.Build(); +if (dataServerCertificate is not null) app.Lifetime.ApplicationStopped.Register(dataServerCertificate.Dispose); +if (dataConnectionOptions.Enabled) app.UseDataConnectionAdmission(); // AddZbSerilog registers Serilog as the MEL logging provider but does NOT assign the static // Serilog.Log.Logger. Set it from the DI root logger so (1) static Log.* calls like the startup @@ -820,6 +840,7 @@ if (hasAdmin) // file's remarks — archreview 03/S14). app.MapOtOpcUaMeshGrpcServices( hasAdmin, hasDriver, syncListenPort, configServeGrpcPort, telemetryListenPort); +if (dataConnectionOptions.Enabled) app.MapGrpcService().AllowAnonymous(); app.MapOtOpcUaHealth(); app.MapOtOpcUaMetrics(); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ClusterEndpointSelector.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ClusterEndpointSelector.cs new file mode 100644 index 000000000..8eb07f0bb --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ClusterEndpointSelector.cs @@ -0,0 +1,20 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Admits only an authenticated capability response for the configured target. +public static class ClusterEndpointSelector +{ + public static bool IsEligible(DataTarget target, DataCapabilities capabilities, bool forWrite) + { + target.Validate(); + capabilities.Validate(); + if (capabilities.ProtocolMajor != 1 || capabilities.Readiness != DataReadiness.Ready || + !string.Equals(target.ExpectedClusterId, capabilities.ClusterId, StringComparison.OrdinalIgnoreCase)) return false; + if (target.Mode == DataTargetMode.Node && + !string.Equals(target.ExpectedNodeId, capabilities.Serving.NodeId, StringComparison.OrdinalIgnoreCase)) return false; + return string.Equals(capabilities.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase) || + target.Mode == DataTargetMode.Node && !forWrite && target.Consistency == DataConsistency.ReadyReplica && + string.Equals(capabilities.Serving.Role, "Secondary", StringComparison.OrdinalIgnoreCase); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs new file mode 100644 index 000000000..2c9d5253f --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs @@ -0,0 +1,498 @@ +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// A node-effective artifact and the durable credential-scope floor it requires. +public sealed record DataConnectionDeploymentSnapshot(long ScopeVersion, string ArtifactRevision, IReadOnlyList Connections, + RedundancyMode ConsumerMode = RedundancyMode.None); + +/// Persists the node's current connection-to-secret allowlist before any route is made ready. +public interface IDataConnectionScopeActivator +{ + Task SetScopeAsync(long version, IReadOnlyDictionary allowlist, CancellationToken cancellationToken); +} + +/// Owns configured connections and reconciles only the latest node-effective scope. +public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable +{ + private sealed record Spec(string Id, long Revision, DataTarget Target, Uri[] Endpoints, HashSet EligibleNodes, + string Secret, DataOperations Operations, TimeSpan Timeout, int Batch, int Page, int MessageBytes, + int Streams, int Monitored, long PendingBytes); + private sealed record Desired(long ScopeVersion, string ArtifactRevision, long Generation, RedundancyMode ConsumerMode, + IReadOnlyDictionary Specs, IReadOnlyDictionary Allowlist); + private sealed class Entry(Spec spec, long generation, GrpcDataConnection connection, CancellationToken token) + { + internal readonly Spec Spec = spec; + internal readonly long Generation = generation; + internal readonly GrpcDataConnection Connection = connection; + internal readonly CancellationToken Token = token; + internal bool Ready; + internal int Leases; + } + private readonly object _sync = new(); + private readonly string _node, _owner; + private readonly IDataConnectionSecurityProvider _security; + private readonly IDataConnectionScopeActivator _activator; + private readonly DataConnectionManager _manager; + private readonly int _maximum; + private readonly TimeProvider _clock; + private readonly Func _consumerMayAcquire; + private readonly CancellationTokenSource _stop = new(); + private readonly ITimer _retryTimer; + private readonly Dictionary _entries = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _routeRevisions = new(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _retirements = new(); + private Desired? _desired; + private Task? _worker, _disposeTask; + private bool _wake, _scopeReady, _disposed, _attemptPending; + private string? _attemptRevision; + private long _generation, _securityGeneration, _retryGeneration, _retryNotBefore; + private int _retryFailures; + + public DataConnectionDeploymentRuntime(string nodeId, string ownerCluster, IDataConnectionSecurityProvider security, + IDataConnectionScopeActivator scopeActivator, int maxConnections, TimeProvider? clock = null, + Func? consumerMayAcquire = null) + { + ArgumentException.ThrowIfNullOrWhiteSpace(nodeId); ArgumentException.ThrowIfNullOrWhiteSpace(ownerCluster); + if (maxConnections <= 0) throw new ArgumentOutOfRangeException(nameof(maxConnections)); + _node = nodeId; _owner = ownerCluster; _security = security ?? throw new ArgumentNullException(nameof(security)); + _activator = scopeActivator ?? throw new ArgumentNullException(nameof(scopeActivator)); _maximum = maxConnections; + _clock = clock ?? TimeProvider.System; _consumerMayAcquire = consumerMayAcquire ?? (() => true); + _retryTimer = _clock.CreateTimer(static state => ((DataConnectionDeploymentRuntime)state!).OnRetry(), this, + Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); + _manager = new DataConnectionManager(nodeId, maxConnections); + _manager.AvailabilityChanged += OnAvailability; + _security.Changed += OnSecurityChanged; + } + + /// True only after the current scope version and allowlist are durably accepted. + public bool CurrentScopeReady { get { lock (_sync) return !_disposed && _scopeReady; } } + /// Configured redundancy mode from the current validated artifact. + public RedundancyMode CurrentConsumerMode { get { lock (_sync) return _desired?.ConsumerMode ?? RedundancyMode.None; } } + + /// Withdraws current routes before parsing or staging a different artifact. + public void BeginAttempt(string artifactRevision) + { + ArgumentException.ThrowIfNullOrWhiteSpace(artifactRevision); + lock (_sync) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (!_attemptPending && _scopeReady && _desired is { } accepted && + string.Equals(accepted.ArtifactRevision, artifactRevision, StringComparison.Ordinal)) + { _attemptRevision = artifactRevision; return; } + if (_attemptPending && string.Equals(_attemptRevision, artifactRevision, StringComparison.Ordinal)) return; + _attemptRevision = artifactRevision; _attemptPending = true; _scopeReady = false; _wake = false; + DisarmRetryLocked(); + var generation = checked(++_generation); + if (_desired is not null) _desired = _desired with { Generation = generation }; + var old = _entries.Values.ToArray(); _entries.Clear(); + _manager.ApplyScope(new Dictionary(StringComparer.OrdinalIgnoreCase)); + foreach (var entry in old) Retire(entry); + } + } + + /// Copies and validates desired data, synchronously denies old routes, and schedules reconciliation. + public void Apply(DataConnectionDeploymentSnapshot snapshot) + { + ArgumentNullException.ThrowIfNull(snapshot); + if (snapshot.ScopeVersion <= 0 || !Enum.IsDefined(snapshot.ConsumerMode)) throw new ArgumentOutOfRangeException(nameof(snapshot)); + ArgumentException.ThrowIfNullOrWhiteSpace(snapshot.ArtifactRevision); + ArgumentNullException.ThrowIfNull(snapshot.Connections); + if (snapshot.Connections.Count > _maximum) throw new ArgumentException("Connection capacity exceeded.", nameof(snapshot)); + var specs = new Dictionary(StringComparer.OrdinalIgnoreCase); + var allow = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var item in snapshot.Connections) + { + ArgumentNullException.ThrowIfNull(item); + ArgumentException.ThrowIfNullOrWhiteSpace(item.DataConnectionId); + if (!item.Enabled) continue; + if (!string.Equals(item.ClusterId, _owner, StringComparison.OrdinalIgnoreCase) || + item.ConsumerNodeIds is null || !item.ConsumerNodeIds.Contains(_node, StringComparer.OrdinalIgnoreCase) || + !string.Equals(item.SecretScopeClusterId, _owner, StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException("Connection is not enabled for this consumer and owner.", nameof(snapshot)); + ArgumentException.ThrowIfNullOrWhiteSpace(item.SecretReference); + var target = new DataTarget(item.TargetMode, item.ExpectedClusterId, item.ExpectedNodeId, item.Consistency); target.Validate(); + if (item.Revision <= 0 || item.TimeoutMilliseconds <= 0 || item.MaxBatchItems <= 0 || item.MaxPageItems <= 0 || + item.MaxMessageBytes <= 0 || item.MaxStreams <= 0 || item.MaxMonitoredItems <= 0 || item.MaxPendingBytes <= 0 || + item.Endpoints is null || item.Endpoints.Count == 0 || item.Endpoints.Count > 32 || item.EligibleTargetNodeIds is null) + throw new ArgumentException("Connection limits or endpoints are invalid.", nameof(snapshot)); + const DataOperations known = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe; + if ((item.AllowedOperations & ~known) != 0) throw new ArgumentException("Unknown operation.", nameof(snapshot)); + var endpoints = item.Endpoints.Select(value => Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme == Uri.UriSchemeHttps + ? uri : throw new ArgumentException("Only HTTPS endpoints are accepted.", nameof(snapshot))).Distinct().ToArray(); + var eligible = new HashSet(item.EligibleTargetNodeIds, StringComparer.OrdinalIgnoreCase); + if (target.Mode == DataTargetMode.Cluster && (eligible.Count == 0 || eligible.Any(string.IsNullOrWhiteSpace))) + throw new ArgumentException("Cluster target has no eligible nodes.", nameof(snapshot)); + var spec = new Spec(item.DataConnectionId, item.Revision, target, endpoints, eligible, item.SecretReference, + item.AllowedOperations, TimeSpan.FromMilliseconds(item.TimeoutMilliseconds), item.MaxBatchItems, + item.MaxPageItems, item.MaxMessageBytes, item.MaxStreams, item.MaxMonitoredItems, item.MaxPendingBytes); + if (!specs.TryAdd(spec.Id, spec) || !allow.TryAdd(spec.Id, spec.Secret)) + throw new ArgumentException("Duplicate connection identity.", nameof(snapshot)); + } + Entry[] old; + lock (_sync) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_attemptRevision is not null && !string.Equals(_attemptRevision, snapshot.ArtifactRevision, StringComparison.Ordinal)) + throw new InvalidOperationException("Artifact does not match the latest deployment attempt."); + if (_desired is { } previous) + { + if (snapshot.ScopeVersion < previous.ScopeVersion) throw new InvalidOperationException("Scope version moved backwards."); + if (snapshot.ScopeVersion == previous.ScopeVersion && !SameAllowlist(previous.Allowlist, allow)) + throw new InvalidOperationException("A scope version cannot identify different allowlists."); + if (string.Equals(snapshot.ArtifactRevision, previous.ArtifactRevision, StringComparison.Ordinal)) + { + if (snapshot.ScopeVersion != previous.ScopeVersion || snapshot.ConsumerMode != previous.ConsumerMode || !SameSpecs(previous.Specs, specs)) + throw new InvalidOperationException("An artifact revision cannot identify different definitions."); + if (!_attemptPending) { if (!_scopeReady) DisarmRetryLocked(); WakeLocked(); return; } + } + } + _attemptPending = false; DisarmRetryLocked(); + var generation = checked(++_generation); + _routeRevisions.Clear(); + foreach (var id in specs.Keys) _routeRevisions.Add(id, generation); + _desired = new(snapshot.ScopeVersion, snapshot.ArtifactRevision, generation, snapshot.ConsumerMode, specs, allow); + _scopeReady = false; + old = _entries.Values.ToArray(); _entries.Clear(); + ApplyManagerScopeLocked(_desired); + foreach (var entry in old) Retire(entry); + WakeLocked(); + } + } + private static bool SameAllowlist(IReadOnlyDictionary left, IReadOnlyDictionary right) => + left.Count == right.Count && left.All(x => right.TryGetValue(x.Key, out var value) && string.Equals(value, x.Value, StringComparison.Ordinal)); + private static bool SameSpecs(IReadOnlyDictionary left, IReadOnlyDictionary right) => + left.Count == right.Count && left.All(pair => right.TryGetValue(pair.Key, out var b) && SameSpec(pair.Value, b)); + private static bool SameSpec(Spec a, Spec b) => + string.Equals(a.Id, b.Id, StringComparison.OrdinalIgnoreCase) && a.Revision == b.Revision && a.Target == b.Target && + a.Endpoints.SequenceEqual(b.Endpoints) && a.EligibleNodes.SetEquals(b.EligibleNodes) && + string.Equals(a.Secret, b.Secret, StringComparison.Ordinal) && a.Operations == b.Operations && a.Timeout == b.Timeout && + a.Batch == b.Batch && a.Page == b.Page && a.MessageBytes == b.MessageBytes && a.Streams == b.Streams && + a.Monitored == b.Monitored && a.PendingBytes == b.PendingBytes; + private bool MayAcquire() { try { return _consumerMayAcquire(); } catch (Exception) { return false; } } + private void ApplyManagerScopeLocked(Desired desired) + { + // The manager owns configured-node scope and physical lifetime only. Role checks + // independently guard activation, acquisition, and each borrowed operation. + var scope = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var spec in desired.Specs.Values) + scope.Add(spec.Id, new DataConnectionScope(_routeRevisions[spec.Id], new HashSet(StringComparer.OrdinalIgnoreCase) { _node })); + _manager.ApplyScope(scope); + } + /// Immediately drains routes on a local role change; called outside the role publication fence. + public void NotifyConsumerRoleChanged() + { + Entry[] old; + lock (_sync) + { + if (_disposed || _desired is null) return; + if (_attemptPending) return; + DisarmRetryLocked(); + var generation = checked(++_generation); + _desired = _desired with { Generation = generation }; + foreach (var id in _desired.Specs.Keys) _routeRevisions[id] = generation; + old = _entries.Values.ToArray(); _entries.Clear(); + ApplyManagerScopeLocked(_desired); + foreach (var entry in old) Retire(entry); + WakeLocked(); + } + } + private void OnAvailability() { lock (_sync) { if (!_disposed && !_attemptPending) WakeLocked(); } } + private void OnSecurityChanged(string id) + { + lock (_sync) + { + if (_disposed) return; + checked { _securityGeneration++; } + if (!_scopeReady) DisarmRetryLocked(); + if (_desired is not null && _entries.Remove(id, out var entry)) + { + var generation = checked(++_generation); + _desired = _desired with { Generation = generation }; + _routeRevisions[id] = generation; + ApplyManagerScopeLocked(_desired); + Retire(entry); + } + if (!_attemptPending) WakeLocked(); + } + } + private void DisarmRetryLocked() + { + _retryGeneration = 0; _retryNotBefore = 0; _retryFailures = 0; + _retryTimer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); + } + private void ScheduleRetryLocked(long generation) + { + var power = _retryFailures; + _retryFailures = Math.Min(_retryFailures + 1, 7); + var delay = TimeSpan.FromMilliseconds(Math.Min(30_000, 250 * (1 << power))); + _retryGeneration = generation; + _retryNotBefore = checked(_clock.GetTimestamp() + (long)(delay.TotalSeconds * _clock.TimestampFrequency)); + _retryTimer.Change(delay, Timeout.InfiniteTimeSpan); + } + private void OnRetry() + { + lock (_sync) + { + if (_disposed || _attemptPending || _retryGeneration == 0 || _desired?.Generation != _retryGeneration) return; + var now = _clock.GetTimestamp(); + if (now < _retryNotBefore) + { + _retryTimer.Change(_clock.GetElapsedTime(now, _retryNotBefore), Timeout.InfiniteTimeSpan); + return; + } + _retryGeneration = 0; + WakeLocked(); + } + } + private void WakeLocked() + { + _wake = true; + if (_worker is null) _worker = Task.Run(ReconcileAsync); + } + private async Task ReconcileAsync() + { + while (true) + { + Desired? desired; + bool floorAlreadyReady; + lock (_sync) + { + if (_disposed || !_wake) { _worker = null; return; } + _wake = false; desired = _attemptPending ? null : _desired; floorAlreadyReady = _scopeReady; + } + if (desired is null) continue; + if (!floorAlreadyReady) + { + try { await _activator.SetScopeAsync(desired.ScopeVersion, desired.Allowlist, _stop.Token).ConfigureAwait(false); } + catch (OperationCanceledException) when (_stop.IsCancellationRequested) { continue; } + catch (Exception) + { + lock (_sync) + if (!_disposed && !_attemptPending && !_scopeReady && _desired?.Generation == desired.Generation) + ScheduleRetryLocked(desired.Generation); + continue; + } + } + lock (_sync) + { + if (_disposed || _attemptPending || _desired?.Generation != desired.Generation) continue; + _scopeReady = true; + if (!MayAcquire()) + { + if (desired.Specs.Count > 0) ScheduleRetryLocked(desired.Generation); + else DisarmRetryLocked(); + continue; + } + // Reassert configured scope after a deferred physical retirement frees a slot. + ApplyManagerScopeLocked(desired); + } + var retryNeeded = false; + foreach (var spec in desired.Specs.Values) + { + Entry? existing; + long securityGeneration; + lock (_sync) + { + if (_disposed || _attemptPending || _desired?.Generation != desired.Generation) break; + if (!MayAcquire()) { retryNeeded = true; break; } + _entries.TryGetValue(spec.Id, out existing); + if (existing?.Ready == true) continue; + securityGeneration = _securityGeneration; + } + var available = false; + try + { + foreach (var endpoint in spec.Endpoints) + { + var security = await _security.ResolveAsync(spec.Id, endpoint, _stop.Token).ConfigureAwait(false); + if (security is not null && !string.IsNullOrWhiteSpace(security.Bearer) && + !string.IsNullOrWhiteSpace(security.CredentialVersion) && !string.IsNullOrWhiteSpace(security.TrustFingerprint)) + { available = true; break; } + } + } + catch (OperationCanceledException) when (_stop.IsCancellationRequested) { break; } + catch (Exception) { } + if (!available) { retryNeeded = true; continue; } + lock (_sync) + { + if (_disposed || _attemptPending || _desired?.Generation != desired.Generation || _securityGeneration != securityGeneration) continue; + if (!MayAcquire()) { retryNeeded = true; break; } + if (_entries.TryGetValue(spec.Id, out existing)) { existing.Ready = true; continue; } + DataConnectionScopeLease scope; + try { scope = _manager.Acquire(spec.Id); } + catch (UnauthorizedAccessException) { continue; } + try + { + var connection = new GrpcDataConnection(spec.Id, spec.Target, spec.Endpoints, _security, scope, + spec.MessageBytes, spec.Endpoints.Length, _clock, spec.EligibleNodes, + spec.Streams, spec.Monitored, maxPendingCommandBytes: spec.PendingBytes); + _entries.Add(spec.Id, new Entry(spec, desired.Generation, connection, scope.CancellationToken) { Ready = true }); + } + catch (Exception) { scope.Dispose(); retryNeeded = true; } + } + } + lock (_sync) + { + if (!_disposed && !_attemptPending && _desired?.Generation == desired.Generation) + { + if (retryNeeded) ScheduleRetryLocked(desired.Generation); + else DisarmRetryLocked(); + } + } + } + } + private void Retire(Entry entry) + { + var task = entry.Connection.DisposeAsync().AsTask(); + lock (_sync) _retirements.Add(task); + _ = ObserveRetirementAsync(task); + } + private async Task ObserveRetirementAsync(Task task) + { + try { await task.ConfigureAwait(false); } catch (Exception) { } + lock (_sync) { _retirements.Remove(task); if (!_disposed) WakeLocked(); } + } + /// Gets a non-owning, scope-bound connection lease when that individual credential is ready. + public bool TryAcquire(string id, out DataConnectionDeploymentLease? lease) + { + lock (_sync) + { + lease = null; + if (_disposed || !_scopeReady || !MayAcquire() || !_entries.TryGetValue(id, out var entry) || !entry.Ready || + entry.Token.IsCancellationRequested || entry.Leases >= 1024) return false; + entry.Leases++; + lease = new DataConnectionDeploymentLease(entry.Connection, entry.Token, entry.Spec.Operations, entry.Spec.Timeout, + entry.Spec.Batch, entry.Spec.Page, entry.Spec.MessageBytes, entry.Spec.Streams, entry.Spec.Monitored, entry.Spec.PendingBytes, + () => { lock (_sync) return !_disposed && _scopeReady && MayAcquire() && entry.Ready && + _entries.TryGetValue(id, out var current) && ReferenceEquals(entry, current); }, + () => { lock (_sync) entry.Leases--; }); + return true; + } + } + public ValueTask DisposeAsync() + { + lock (_sync) + { + if (_disposeTask is not null) return new(_disposeTask); + _disposed = true; _scopeReady = false; DisarmRetryLocked(); _security.Changed -= OnSecurityChanged; _manager.AvailabilityChanged -= OnAvailability; + _ = _stop.CancelAsync(); + _manager.Dispose(); + var old = _entries.Values.ToArray(); _entries.Clear(); + foreach (var entry in old) Retire(entry); + _disposeTask = FinishDisposeAsync(_worker, _retirements.ToArray()); + return new(_disposeTask); + } + } + private async Task FinishDisposeAsync(Task? worker, Task[] retirements) + { + if (worker is not null) try { await worker.ConfigureAwait(false); } catch (Exception) { } + try { await Task.WhenAll(retirements).ConfigureAwait(false); } catch (Exception) { } + _retryTimer.Dispose(); _stop.Dispose(); + } +} + +/// A non-owning handle with the deployed operation and resource policy. +public sealed class DataConnectionDeploymentLease : IDataConnection, IDisposable +{ + private readonly IDataConnection _inner; + private readonly CancellationToken _scope; + private readonly DataOperations _allowed; + private readonly TimeSpan _timeout; + private readonly int _batch, _page, _bytes, _streams, _monitored; + private readonly long _pendingBytes; + private readonly Func _current; + private readonly Action _release; + private int _disposed; + internal DataConnectionDeploymentLease(IDataConnection inner, CancellationToken scope, DataOperations allowed, TimeSpan timeout, + int batch, int page, int bytes, int streams, int monitored, long pendingBytes, Func current, Action release) + { + _inner = inner; _scope = scope; _allowed = allowed; _timeout = timeout; _batch = batch; _page = page; _bytes = bytes; + _streams = streams; _monitored = monitored; _pendingBytes = pendingBytes; _current = current; _release = release; + } + public IDataConnection Connection => this; + public CancellationToken CancellationToken => _scope; + public DataTarget Target => _inner.Target; + public TimeProvider Clock => _inner.Clock; + private void Check(DataOperations operation = DataOperations.None) + { + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); + _scope.ThrowIfCancellationRequested(); + if (!_current()) throw new InvalidOperationException("Connection is no longer ready in the current scope."); + if (operation != DataOperations.None && (_allowed & operation) != operation) throw new UnauthorizedAccessException("Operation is not enabled for this connection."); + } + private DataBudget Limit(DataBudget budget, int maxItems) + { + budget.Validate(); + return new(budget.Timeout < _timeout ? budget.Timeout : _timeout, Math.Min(budget.MaxItems, maxItems), + Math.Min(Math.Min(budget.MaxBytes, _bytes), _pendingBytes)); + } + public async Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) + { + Check(); var result = await _inner.GetCapabilitiesAsync(Limit(budget, _batch), cancellationToken).ConfigureAwait(false); Check(); + var l = result.Limits; + var limits = l with { MaxPageItems = Math.Min(l.MaxPageItems, _page), MaxBatchItems = Math.Min(l.MaxBatchItems, _batch), + MaxMessageBytes = Math.Min(l.MaxMessageBytes, _bytes), MaxStreams = Math.Min(l.MaxStreams, _streams), + MaxMonitoredItems = Math.Min(l.MaxMonitoredItems, _monitored), MaxPendingBytes = Math.Min(l.MaxPendingBytes, _pendingBytes) }; + return result with { Operations = result.Operations & _allowed, Limits = limits }; + } + public async Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) + { + Check(DataOperations.Browse); var value = await _inner.BrowseAsync(request with { Budget = Limit(request.Budget, _page) }, cancellationToken).ConfigureAwait(false); + Check(DataOperations.Browse); return value; + } + public async Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) + { + Check(DataOperations.Metadata); if (request.Views.Count > _batch) throw new ArgumentOutOfRangeException(nameof(request)); + var value = await _inner.GetMetadataAsync(request with { Budget = Limit(request.Budget, _batch) }, cancellationToken).ConfigureAwait(false); + Check(DataOperations.Metadata); return value; + } + public async Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) + { + Check(DataOperations.Read); if (request.Items.Count > _batch) throw new ArgumentOutOfRangeException(nameof(request)); + var value = await _inner.ReadAsync(request with { Budget = Limit(request.Budget, _batch) }, cancellationToken).ConfigureAwait(false); + try { Check(DataOperations.Read); return value; } + catch { foreach (var item in value) item.Dispose(); throw; } + } + public async Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) + { + Check(DataOperations.Write); if (request.Items.Count > _batch) throw new ArgumentOutOfRangeException(nameof(request)); + var value = await _inner.WriteAsync(request with { Budget = Limit(request.Budget, _batch) }, cancellationToken).ConfigureAwait(false); + try { Check(DataOperations.Write); return value; } + catch (Exception ex) when (ex is OperationCanceledException or InvalidOperationException or UnauthorizedAccessException) + { return request.Items.Select(x => new WriteItemResult(x.CorrelationId, new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Write outcome unknown after scope change."))).ToArray(); } + } + public async Task SubscribeAsync(CancellationToken cancellationToken) + { + Check(DataOperations.Subscribe); var stream = await _inner.SubscribeAsync(cancellationToken).ConfigureAwait(false); + try { Check(DataOperations.Subscribe); return new ScopedSubscription(this, stream); } + catch { await stream.DisposeAsync().ConfigureAwait(false); throw; } + } + private sealed class ScopedSubscription(DataConnectionDeploymentLease owner, IDataSubscription inner) : IDataSubscription + { + public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) + { + owner.Check(DataOperations.Subscribe); + var count = command switch { OpenSubscription o => o.Items.Count, AddSubscriptionItems a => a.Items.Count, + ModifySubscriptionItems m => m.Items.Count, RemoveSubscriptionItems r => r.Items.Count, _ => owner._monitored + 1 }; + if (count > owner._monitored) throw new ArgumentOutOfRangeException(nameof(command)); + if (command is OpenSubscription open) command = open with { SnapshotBudget = owner.Limit(open.SnapshotBudget, owner._monitored) }; + return inner.SendAsync(command, cancellationToken); + } + public async IAsyncEnumerable ReadAllAsync( + [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken) + { + await foreach (var frame in inner.ReadAllAsync(cancellationToken).ConfigureAwait(false)) + { + try { owner.Check(DataOperations.Subscribe); } + catch { if (frame is IDisposable owned) owned.Dispose(); throw; } + yield return frame; + } + } + public ValueTask DisposeAsync() => inner.DisposeAsync(); + } + public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) _release(); } + public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionManager.cs new file mode 100644 index 000000000..1ae44380d --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionManager.cs @@ -0,0 +1,138 @@ +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Deployed revision and permitted consumer nodes for a connection. +public sealed record DataConnectionScope(long Revision, IReadOnlySet ConsumerNodeIds); + +/// Node-scoped connection lifetimes. Removing scope cancels all handles from that epoch. +public sealed class DataConnectionManager : IDisposable +{ + private sealed class State(long epoch, long revision, CancellationTokenSource cancellation) + { + internal readonly long Epoch = epoch, Revision = revision; + internal readonly CancellationTokenSource Cancellation = cancellation; + internal int Leases; + internal bool Retired, CancellationCompleted; + } + private readonly object _sync = new(); + private readonly string _node; + private readonly int _maximum; + private readonly Dictionary _active = new(StringComparer.OrdinalIgnoreCase); + private long _epoch; + private int _retiring; + private readonly HashSet _retiringIds = new(StringComparer.OrdinalIgnoreCase); + private Dictionary _desired = new(StringComparer.OrdinalIgnoreCase); + private bool _disposed; + /// Signals that a retired slot finished cleanup and desired scope may be acquired. + public event Action? AvailabilityChanged; + public DataConnectionManager(string nodeId, int maximumConnections) + { + ArgumentException.ThrowIfNullOrWhiteSpace(nodeId); + if (maximumConnections <= 0) throw new ArgumentOutOfRangeException(nameof(maximumConnections)); + _node = nodeId; _maximum = maximumConnections; + } + public void ApplyScope(IReadOnlyDictionary> scope) => + ApplyScope(scope.ToDictionary(x => x.Key, x => new DataConnectionScope(1, x.Value), StringComparer.OrdinalIgnoreCase)); + public void ApplyScope(IReadOnlyDictionary scope) + { + ArgumentNullException.ThrowIfNull(scope); + var allowed = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var (id, entry) in scope) + { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + ArgumentNullException.ThrowIfNull(entry); + ArgumentNullException.ThrowIfNull(entry.ConsumerNodeIds); + if (entry.Revision <= 0) throw new ArgumentOutOfRangeException(nameof(scope)); + if (entry.ConsumerNodeIds.Contains(_node, StringComparer.OrdinalIgnoreCase) && !allowed.TryAdd(id, entry.Revision)) + throw new ArgumentException("Duplicate connection identity.", nameof(scope)); + } + if (allowed.Count > _maximum) throw new ArgumentException("Connection scope exceeds capacity.", nameof(scope)); + lock (_sync) + { + ObjectDisposedException.ThrowIf(_disposed, this); + foreach (var (id, revision) in allowed) + if (_desired.TryGetValue(id, out var prior) && revision < prior) + throw new InvalidOperationException("Connection revision cannot move backwards."); + _desired = allowed; + foreach (var id in _active.Keys.Where(id => !allowed.TryGetValue(id, out var revision) || revision != _active[id].Revision).ToArray()) + { + var state = _active[id]; _active.Remove(id); state.Retired = true; _retiring++; _retiringIds.Add(id); + // CancelAsync marks the token immediately; callbacks complete without holding the lock. + var cancellation = state.Cancellation.CancelAsync(); + _ = FinishRetirementAsync(id, state, cancellation); + } + FillLocked(); + } + } + private void FillLocked() + { + if (_disposed) return; + foreach (var (id, revision) in _desired) + { + if (_active.Count + _retiring >= _maximum) break; + if (!_active.ContainsKey(id) && !_retiringIds.Contains(id)) + _active.Add(id, new(checked(++_epoch), revision, new())); + } + } + private async Task FinishRetirementAsync(string id, State state, Task cancellation) + { + // Force asynchronous continuation even if there are no callbacks; callers must never run cleanup under the lock. + await Task.Yield(); + try { await cancellation.ConfigureAwait(false); } + catch (Exception) { /* callbacks cannot keep quota forever after completion */ } + finally + { + lock (_sync) + { + state.CancellationCompleted = true; + ReleaseRetiredLocked(id, state); + } + } + } + private void ReleaseRetiredLocked(string id, State state) + { + if (!state.Retired || !state.CancellationCompleted || state.Leases != 0) return; + state.Retired = false; state.Cancellation.Dispose(); _retiring--; _retiringIds.Remove(id); FillLocked(); + var handlers = AvailabilityChanged; + if (handlers is not null) ThreadPool.QueueUserWorkItem(static action => + { + foreach (var subscriber in action.GetInvocationList().Cast()) + try { subscriber(); } catch (Exception) { } + }, handlers, preferLocal: false); + } + public DataConnectionScopeLease Acquire(string connectionId) + { + lock (_sync) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (!_active.TryGetValue(connectionId, out var state)) throw new UnauthorizedAccessException("Connection is outside this node's scope."); + state.Leases++; + return new(state.Epoch, state.Cancellation.Token, () => + { + lock (_sync) { state.Leases--; ReleaseRetiredLocked(connectionId, state); } + }); + } + } + public void Dispose() + { + lock (_sync) + { + if (_disposed) return; + _disposed = true; _desired.Clear(); + foreach (var (id, state) in _active) + { + state.Retired = true; _retiring++; _retiringIds.Add(id); + _ = FinishRetirementAsync(id, state, state.Cancellation.CancelAsync()); + } + _active.Clear(); + } + } +} + +/// A snapshot of one authorized connection scope epoch. +public sealed class DataConnectionScopeLease(long epoch, CancellationToken cancellationToken, Action release) : IDisposable +{ + private int _disposed; + public long Epoch { get; } = epoch; + public CancellationToken CancellationToken { get; } = cancellationToken; + public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) release(); } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionPublisherProps.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionPublisherProps.cs new file mode 100644 index 000000000..cd56b190a --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionPublisherProps.cs @@ -0,0 +1,28 @@ +using Akka.Actor; +using Akka.DependencyInjection; +using Microsoft.EntityFrameworkCore; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Selects the node's registered publisher dependencies for the production actor. +internal static class DataConnectionPublisherProps +{ + internal static Props Create(IDependencyResolver services, IOpcUaAddressSpaceSink sink, IServiceLevelPublisher serviceLevel, + NodeId localNode, IDbContextFactory? dbFactory, AddressSpaceApplier applier, IActorRef? dbHealthProbe) + { + var redundancy = services.GetService() ?? WarmRedundancySettings.Unset; + return OpcUaPublishActor.Props(sink: sink, serviceLevel: serviceLevel, localNode: localNode, + dbFactory: dbFactory, applier: applier, dbHealthProbe: dbHealthProbe, dbLess: dbFactory is null, + dataPlaneAuthority: services.GetService(), + endpointState: services.GetService(), redundancy: redundancy, + standbyProjection: redundancy.IsWarm ? services.GetService() : null, + dataCatalog: services.GetService(), catalogCoordinator: services.GetService(), + dataWarmRole: services.GetService(), dataConnections: services.GetService()); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionRoleAdapter.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionRoleAdapter.cs new file mode 100644 index 000000000..32cffa634 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionRoleAdapter.cs @@ -0,0 +1,18 @@ +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Adapts existing local redundancy verdicts to import activation, without electing a role. +public static class DataConnectionRoleAdapter +{ + public static bool MayAcquire(RedundancyMode mode, WarmRole? warmRole, RedundancyRole? role) => mode switch + { + RedundancyMode.Warm => warmRole == WarmRole.Active, + RedundancyMode.Hot => role is RedundancyRole.Primary or RedundancyRole.Secondary, + RedundancyMode.None => role == RedundancyRole.Primary, + _ => false + }; + public static bool MayWrite(RedundancyRole? role) => role == RedundancyRole.Primary; +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionWarmRoleView.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionWarmRoleView.cs new file mode 100644 index 000000000..f47607754 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionWarmRoleView.cs @@ -0,0 +1,66 @@ +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// An immutable Warm verdict and its process-local change generation. +public sealed record DataConnectionWarmRoleSnapshot(WarmRole? Role, long Generation); + +/// Publishes the active OPC UA publisher's actual Warm verdict under the shared dispatch fence. +public sealed class DataConnectionWarmRoleView +{ + private sealed record State(long Owner, DataConnectionWarmRoleSnapshot Snapshot); + private State _state = new(0, new(null, 0)); + private long _nextOwner; + private bool _poisoned; + public DataConnectionWarmRoleView(DataWriteDispatchFence dispatchFence) => + DispatchFence = dispatchFence ?? throw new ArgumentNullException(nameof(dispatchFence)); + public DataWriteDispatchFence DispatchFence { get; } + public DataConnectionWarmRoleSnapshot Snapshot => Volatile.Read(ref _state).Snapshot; + public WarmRole? CurrentRole => Snapshot.Role; + public long Generation => Snapshot.Generation; + + /// Replaces the publisher owner and immediately withdraws the old verdict. + public long RegisterOwner() + { + using (DispatchFence.Enter()) + { + var current = _state; + if (_poisoned || _nextOwner == long.MaxValue || current.Snapshot.Generation == long.MaxValue) + { Poison(); throw new InvalidOperationException("Warm role generation exhausted."); } + var owner = ++_nextOwner; + Volatile.Write(ref _state, new State(owner, new(null, current.Snapshot.Generation + 1))); + return owner; + } + } + /// Publishes only for the current owner; returns true when the verdict changes. + public bool Publish(long owner, WarmRole role) + { + if (!Enum.IsDefined(role)) throw new ArgumentOutOfRangeException(nameof(role)); + using (DispatchFence.Enter()) + { + var current = _state; + if (_poisoned || owner == 0 || current.Owner != owner || current.Snapshot.Role == role) return false; + if (current.Snapshot.Generation == long.MaxValue) { Poison(); return true; } + Volatile.Write(ref _state, new State(owner, new(role, current.Snapshot.Generation + 1))); + return true; + } + } + /// Withdraws a current owner's verdict; a superseded owner cannot affect its successor. + public bool RetireOwner(long owner) + { + using (DispatchFence.Enter()) + { + var current = _state; + if (_poisoned || owner == 0 || current.Owner != owner) return false; + if (current.Snapshot.Generation == long.MaxValue) { Poison(); return true; } + Volatile.Write(ref _state, new State(0, new(null, current.Snapshot.Generation + 1))); + return true; + } + } + private void Poison() + { + _poisoned = true; + Volatile.Write(ref _state, new State(0, new(null, long.MaxValue))); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs index 28aaa4556..df5f8412f 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs @@ -1165,6 +1165,8 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport prepared = await sink.PrepareAsync(frame, _limits.MaxPendingBytes, cancellationToken).ConfigureAwait(false); if (prepared is null || prepared.RetainedBytes < 0 || prepared.RetainedBytes > _limits.MaxPendingBytes) { if (!pending.IsObsolete()) Stop(); return; } + if (prepared is IDataPreparedSubscriptionPublication publication) + publication.SetPublicationGuard(pending.Gate); if (!pending.IsEligible()) return; var rate = pending.ConsumeSnapshot(prepared.RetainedBytes); if (!rate.Accepted) { CloseWithReset($"Snapshot pacing; retry after {rate.Retry.TotalMilliseconds:F0} ms."); return; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteDispatchGate.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteDispatchGate.cs index 5e87e5162..18f485f23 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteDispatchGate.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteDispatchGate.cs @@ -47,8 +47,10 @@ internal sealed class DataWriteDispatchGate { // These are immutable reads only. Writers acquire their own state lock first, then this fence. var utcNow = clock.GetUtcNow(); + var liveServing = coordinator.Serving; if (!ReferenceEquals(snapshot, authority.Current) || !ReferenceEquals(activationSnapshot, activation.Current) || !coordinator.IsPublished(catalog) || !activationSnapshot.IsReady + || proof.Serving is null || catalog.Serving != proof.Serving || liveServing != proof.Serving || admission.AuthorityEpoch != snapshot.GenerationId || admission.CatalogRevision != activationSnapshot.CatalogEpoch || admission.ServingIncarnation != catalog.Serving.Incarnation || !role.ShouldActAsPrimary || role.PrimaryGeneration <= 0 || role.PrimaryGeneration != proof.PrimaryGeneration diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteExecutor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteExecutor.cs index 69f14afd2..ed17f743c 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteExecutor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteExecutor.cs @@ -119,7 +119,7 @@ internal sealed class DataWriteExecutor(DataAuthenticatedContext context, FuncVersioned security material supplied by the consuming host. +public sealed record DataConnectionSecurity(string CredentialVersion, string TrustFingerprint, string Bearer, + Func CreateHandler) +{ + public override string ToString() => $"DataConnectionSecurity {{ CredentialVersion = {CredentialVersion}, TrustFingerprint = {TrustFingerprint}, Bearer = [redacted] }}"; +} +public interface IDataConnectionSecurityProvider +{ + ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken); + event Action? Changed; +} +public sealed record DataConnectionChannelIdentity(string ConnectionId, Uri Endpoint, string CredentialVersion, string TrustFingerprint); + +/// Caller-bound remote facade. All channels and requests are bounded by configured local limits. +public sealed class GrpcDataConnection : IDataConnection +{ + private sealed class ChannelEntry(DataConnectionChannelIdentity identity, GrpcChannel channel, string bearer) + { + internal readonly DataConnectionChannelIdentity Identity = identity; + internal readonly GrpcChannel Channel = channel; + internal readonly W.DataConnectionService.DataConnectionServiceClient Client = new(channel); + internal readonly string Bearer = bearer; + internal readonly CancellationTokenSource Retired = new(); + } + private sealed record Selected(ChannelEntry Channel, DataCapabilities Capabilities); + private readonly object _sync = new(); + private readonly string _id; + private readonly Uri[] _endpoints; + private readonly HashSet? _eligibleNodeIds; + private readonly IDataConnectionSecurityProvider _security; + private readonly DataConnectionScopeLease _scope; + private readonly int _maxMessageBytes, _maxChannels, _maxStreams, _maxMonitoredItems, _maxPendingCommands; + private readonly TimeSpan _maxCommandTimeout; + private readonly SemaphoreSlim _unaryCapacity; + private readonly CommandStateBudget _commandBudget; + private readonly Dictionary _channels = new(); + private bool _disposed; + private long _securityGeneration; + private int _activeStreams, _retiringChannels, _activeWork; + private readonly HashSet _streams = new(); + private readonly CancellationTokenSource _shutdown = new(); + private readonly TaskCompletionSource _drained = new(TaskCreationOptions.RunContinuationsAsynchronously); + private Task? _disposeTask, _shutdownCancellation; + private long _nextProbeTimestamp; + private int _probeFailures; + private readonly Dictionary _streamEpochs = new(StringComparer.Ordinal); + private long _streamEpochBytes; + internal Func? BeforeStreamInstallForTests { get; set; } + internal Action? PendingIdentityObserverForTests { get; set; } + internal Func? AfterTimerCancelledForTests { get; set; } + public DataTarget Target { get; } + public TimeProvider Clock { get; } + + public GrpcDataConnection(string connectionId, DataTarget target, IEnumerable endpoints, + IDataConnectionSecurityProvider security, DataConnectionScopeLease scope, int maxMessageBytes, + int maxChannels, TimeProvider? clock = null, IReadOnlySet? eligibleNodeIds = null, + int maxStreams = 16, int maxMonitoredItems = 10_000, int maxPendingCommands = 256, + int maxConcurrentUnaryCalls = 64, TimeSpan? maxCommandTimeout = null, long maxPendingCommandBytes = 4 * 1024 * 1024) + { + ArgumentException.ThrowIfNullOrWhiteSpace(connectionId); + ArgumentNullException.ThrowIfNull(target); target.Validate(); + ArgumentNullException.ThrowIfNull(endpoints); + _endpoints = endpoints.Distinct().ToArray(); + if (_endpoints.Length == 0 || _endpoints.Any(x => !x.IsAbsoluteUri || x.Scheme != Uri.UriSchemeHttps)) + throw new ArgumentException("Only configured HTTPS endpoints are accepted.", nameof(endpoints)); + if (maxMessageBytes <= 0 || maxChannels <= 0 || _endpoints.Length > maxChannels || maxStreams <= 0 || + maxMonitoredItems <= 0 || maxPendingCommands <= 0 || maxConcurrentUnaryCalls <= 0 || maxPendingCommandBytes <= 0) + throw new ArgumentOutOfRangeException(nameof(maxChannels)); + _maxCommandTimeout = maxCommandTimeout ?? TimeSpan.FromSeconds(30); + if (_maxCommandTimeout <= TimeSpan.Zero || _maxCommandTimeout > TimeSpan.FromDays(1)) throw new ArgumentOutOfRangeException(nameof(maxCommandTimeout)); + _maxStreams = maxStreams; _maxMonitoredItems = maxMonitoredItems; _maxPendingCommands = maxPendingCommands; + _unaryCapacity = new(maxConcurrentUnaryCalls, maxConcurrentUnaryCalls); + _commandBudget = new CommandStateBudget(Math.Min(maxPendingCommandBytes, 4L * 1024 * 1024)); + if (target.Mode == DataTargetMode.Cluster && (eligibleNodeIds is null || eligibleNodeIds.Count == 0 || eligibleNodeIds.Any(string.IsNullOrWhiteSpace))) + throw new ArgumentException("Cluster targets require configured eligible node identities.", nameof(eligibleNodeIds)); + _eligibleNodeIds = eligibleNodeIds is null ? null : new(eligibleNodeIds, StringComparer.OrdinalIgnoreCase); + _id = connectionId; Target = target; _security = security ?? throw new ArgumentNullException(nameof(security)); + _scope = scope ?? throw new ArgumentNullException(nameof(scope)); _maxMessageBytes = maxMessageBytes; _maxChannels = maxChannels; + Clock = clock ?? TimeProvider.System; + _security.Changed += SecurityChanged; + } + public static int[] RetryableWriteIndexes(IReadOnlyList outcomes) => outcomes + .Select((item, index) => (item, index)).Where(x => x.item.Outcome.State == DataWriteState.RejectedBeforeDispatch) + .Select(x => x.index).ToArray(); + private sealed class CommandStateBudget(long maximum) + { + private readonly object _gate = new(); + private long _used; + internal bool TryReserve(long amount) + { + lock (_gate) { if (amount < 0 || amount > maximum - _used) return false; _used += amount; return true; } + } + internal void Release(long amount) { lock (_gate) { _used -= amount; } } + } + private void SecurityChanged(string connectionId) + { + if (!string.Equals(_id, connectionId, StringComparison.OrdinalIgnoreCase)) return; + lock (_sync) { _nextProbeTimestamp = 0; _probeFailures = 0; } + RetireAll(); + } + private bool ProbeAllowed() { lock (_sync) return _nextProbeTimestamp == 0 || Clock.GetTimestamp() >= _nextProbeTimestamp; } + private void ProbeSucceeded() { lock (_sync) { _probeFailures = 0; _nextProbeTimestamp = 0; } } + private void ProbeFailed() + { + lock (_sync) + { + var power = _probeFailures; + _probeFailures = Math.Min(_probeFailures + 1, 7); + var milliseconds = Math.Min(30_000d, 250d * (1 << power)) * (0.8 + Random.Shared.NextDouble() * 0.4); + _nextProbeTimestamp = checked(Clock.GetTimestamp() + (long)(milliseconds / 1000d * Clock.TimestampFrequency)); + } + } + private bool ClaimStreamEpoch(string id, long epoch) + { + lock (_sync) + { + if (_disposed || string.IsNullOrWhiteSpace(id) || epoch <= 0 || + _streamEpochs.TryGetValue(id, out var previous) && epoch <= previous) return false; + if (!_streamEpochs.ContainsKey(id)) + { + var charge = checked(64L + 2L * id.Length); + if (_streamEpochs.Count >= 100_000 || _streamEpochBytes + charge > 4 * 1024 * 1024) return false; + _streamEpochBytes += charge; + } + _streamEpochs[id] = epoch; return true; + } + } + private void RetireAll() + { + lock (_sync) + { + _securityGeneration++; + foreach (var item in _channels.Values) + { + _retiringChannels++; + var cancelled = item.Retired.CancelAsync(); + _ = FinishChannelRetirementAsync(item, cancelled); + } + _channels.Clear(); + } + } + private async Task FinishChannelRetirementAsync(ChannelEntry item, Task cancelled) + { + // Physical Dispose and arbitrary cancellation callbacks may block. Keep quota charged until both end. + await Task.Yield(); + try { await Task.WhenAll(cancelled, Task.Run(item.Channel.Dispose)).ConfigureAwait(false); } + catch (Exception) { } + finally + { + item.Retired.Dispose(); + lock (_sync) { _retiringChannels--; CheckDrainedLocked(); } + } + } + private void EnterWork() + { + lock (_sync) { Check(); _activeWork++; } + } + private void ExitWork() + { + lock (_sync) { _activeWork--; CheckDrainedLocked(); } + } + private void CheckDrainedLocked() + { + if (_disposed && _activeWork == 0 && _retiringChannels == 0 && _activeStreams == 0) _drained.TrySetResult(); + } + private void Check() { ObjectDisposedException.ThrowIf(_disposed, this); _scope.CancellationToken.ThrowIfCancellationRequested(); } + private async Task ChannelAsync(Uri endpoint, CancellationToken ct) + { + long generation; + lock (_sync) { Check(); generation = _securityGeneration; } + var security = await _security.ResolveAsync(_id, endpoint, ct).ConfigureAwait(false) + ?? throw new UnauthorizedAccessException("Connection credential or trust unavailable."); + ArgumentException.ThrowIfNullOrWhiteSpace(security.CredentialVersion); + ArgumentException.ThrowIfNullOrWhiteSpace(security.TrustFingerprint); + ArgumentException.ThrowIfNullOrWhiteSpace(security.Bearer); + var key = new DataConnectionChannelIdentity(_id, endpoint, security.CredentialVersion, security.TrustFingerprint); + lock (_sync) + { + Check(); + if (generation != _securityGeneration) throw new InvalidOperationException("Security changed while resolving."); + if (_channels.TryGetValue(key, out var existing)) return existing; + if (_channels.Count + _retiringChannels >= _maxChannels) throw new InvalidOperationException("Channel capacity exhausted."); + var handler = security.CreateHandler(); + try + { + var channel = GrpcChannel.ForAddress(endpoint, new GrpcChannelOptions { HttpHandler = handler, + DisposeHttpClient = true, DisableResolverServiceConfig = true, + MaxReceiveMessageSize = _maxMessageBytes, MaxSendMessageSize = _maxMessageBytes }); + var entry = new ChannelEntry(key, channel, security.Bearer); + _channels.Add(key, entry); return entry; + } + catch { handler.Dispose(); throw; } + } + } + private Metadata Headers(ChannelEntry channel) + { + var headers = new Metadata { { "authorization", "Bearer " + channel.Bearer }, + { "x-data-target-mode", Target.Mode.ToString() }, { "x-data-consistency", Target.Consistency.ToString() }, + { "x-data-cluster-id", Target.ExpectedClusterId } }; + if (Target.Mode == DataTargetMode.Node) headers.Add("x-data-node-id", Target.ExpectedNodeId!); + return headers; + } + private TimeSpan Remaining(long start, DataBudget budget) + { + var remaining = budget.Timeout - Clock.GetElapsedTime(start); + if (remaining <= TimeSpan.Zero) throw new TimeoutException("Original data request budget expired."); + return remaining; + } + private CallOptions Options(ChannelEntry channel, long start, DataBudget budget, CancellationToken ct) => + new(Headers(channel), DateTime.UtcNow + Remaining(start, budget), ct); + private DataDecodeLimits Limits(DataBudget budget, DataCapabilities caps) => new(Math.Min(budget.MaxItems, caps.Limits.MaxBatchItems), + (int)Math.Min(Math.Min(budget.MaxBytes, _maxMessageBytes), caps.Limits.MaxMessageBytes), caps.Limits.MaxValueElements); + private async Task SelectAsync(Uri endpoint, long start, DataBudget budget, bool write, CancellationToken ct) + { + var channel = await ChannelAsync(endpoint, ct).ConfigureAwait(false); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _scope.CancellationToken, channel.Retired.Token, _shutdown.Token); + var response = await channel.Client.GetCapabilitiesAsync(new W.CapabilitiesRequest { ProtocolMajor = 1, ProtocolMinor = 2 }, + Options(channel, start, budget, linked.Token)).ResponseAsync.ConfigureAwait(false); + var caps = DataProtoMapper.DecodeCapabilities(response, new DataDecodeLimits(budget.MaxItems, _maxMessageBytes)); + if (!caps.ResponseServingIdentity || caps.Serving.ServingGeneration <= 0 || !ClusterEndpointSelector.IsEligible(Target, caps, write) || + Target.Mode == DataTargetMode.Cluster && !_eligibleNodeIds!.Contains(caps.Serving.NodeId)) + throw new InvalidOperationException("Endpoint is not an authenticated ready target."); + linked.Token.ThrowIfCancellationRequested(); + return new(channel, caps); + } + private static void Verify(W.Serving? serving, Selected selected) + { + if (serving is null || DataProtoMapper.DecodeServing(serving) != selected.Capabilities.Serving) + throw new InvalidOperationException("Response serving identity changed."); + selected.Channel.Retired.Token.ThrowIfCancellationRequested(); + } + private async Task QueryAsync(DataBudget budget, Func> call, CancellationToken ct) + { + budget.Validate(); var start = Clock.GetTimestamp(); Exception? failure = null; + EnterWork(); + var admitted = false; + try + { + using var admission = CancellationTokenSource.CreateLinkedTokenSource(ct, _scope.CancellationToken, _shutdown.Token); + admitted = await _unaryCapacity.WaitAsync(0, admission.Token).ConfigureAwait(false); + if (!admitted) throw new InvalidOperationException("Unary capacity exhausted."); + if (!ProbeAllowed()) throw new InvalidOperationException("Data endpoint discovery is backing off."); + foreach (var endpoint in _endpoints) + { + Check(); + try + { + var selected = await SelectAsync(endpoint, start, budget, false, ct).ConfigureAwait(false); + ProbeSucceeded(); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _scope.CancellationToken, selected.Channel.Retired.Token, _shutdown.Token); + var remaining = budget with { Timeout = Remaining(start, budget) }; + var result = await call(selected, remaining, Options(selected.Channel, start, budget, linked.Token)).ConfigureAwait(false); + try { linked.Token.ThrowIfCancellationRequested(); return result; } + catch { if (result is IEnumerable reads) foreach (var item in reads) item.Dispose(); throw; } + } + catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException) + { failure = ex; } + } + ProbeFailed(); + throw new InvalidOperationException("No ready authenticated data endpoint.", failure); + } + finally { if (admitted) _unaryCapacity.Release(); ExitWork(); } + } + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => + QueryAsync(budget, (selected, _, _) => Task.FromResult(selected.Capabilities), cancellationToken); + public Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => + QueryAsync(request.Budget, async (selected, budget, options) => + { + var wire = await selected.Channel.Client.BrowseAsync(DataProtoMapper.EncodeBrowseRequest(request with { Budget = budget }), options).ResponseAsync.ConfigureAwait(false); + Verify(wire.Serving, selected); var result = DataProtoMapper.DecodeBrowseResponse(wire, Limits(budget, selected.Capabilities)); + if (result.Lease is { } lease && (lease.CatalogEpoch != selected.Capabilities.Serving.CatalogEpoch || + lease.AuthorityEpoch != selected.Capabilities.Serving.AuthorityEpoch || lease.Duration > selected.Capabilities.Limits.MaxMetadataLease)) + throw new InvalidOperationException("Browse lease has unexpected authority or duration."); + if (result.Parent != request.Parent || result.Items.Any(x => !string.Equals(x.View.Address.OriginClusterId, selected.Capabilities.ClusterId, StringComparison.OrdinalIgnoreCase))) + throw new InvalidOperationException("Browse response has unexpected provenance."); + Verify(wire.Serving, selected); return result; + }, cancellationToken); + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => + QueryAsync(request.Budget, async (selected, budget, options) => + { + var wire = await selected.Channel.Client.GetMetadataAsync(DataProtoMapper.EncodeMetadataRequest(request with { Budget = budget }), options).ResponseAsync.ConfigureAwait(false); + Verify(wire.Serving, selected); var result = DataProtoMapper.DecodeMetadataResponse(wire, Limits(budget, selected.Capabilities)); + if (result.Count != request.Views.Count || result.Where((x, i) => x.CorrelationId != i.ToString(System.Globalization.CultureInfo.InvariantCulture) || + x.Value is not null && x.Value.View.Address != request.Views[i].Address).Any()) + throw new InvalidOperationException("Metadata response has unexpected items."); + Verify(wire.Serving, selected); return result; + }, cancellationToken); + public Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) + { + var start = Clock.GetTimestamp(); + return QueryAsync(request.Budget, async (selected, budget, options) => + { + var wire = await selected.Channel.Client.ReadAsync(DataProtoMapper.EncodeReadRequest(request with { Budget = budget }), options).ResponseAsync.ConfigureAwait(false); + Verify(wire.Serving, selected); + var result = DataProtoMapper.DecodeReadResponse(wire, Limits(budget, selected.Capabilities), Clock.GetElapsedTime(start)); + try + { + if (result.Count != request.Items.Count || !result.Select(x => x.CorrelationId).SequenceEqual(request.Items.Select(x => x.CorrelationId)) || + result.Any(x => x.Sample is not null && x.Sample.Serving != selected.Capabilities.Serving)) + throw new InvalidOperationException("Read response has unexpected items or serving identity."); + Verify(wire.Serving, selected); return result; + } + catch { foreach (var item in result) item.Dispose(); throw; } + }, cancellationToken); + } + public async Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) + { + request.Budget.Validate(); + var admissionStart = Clock.GetTimestamp(); + EnterWork(); + var admitted = false; + try + { + using var admission = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, _shutdown.Token); + admitted = await _unaryCapacity.WaitAsync(0, admission.Token).ConfigureAwait(false); + if (!admitted) return request.Items.Select(x => new WriteItemResult(x.CorrelationId, + new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Unary capacity exhausted."))).ToArray(); + var elapsed = Clock.GetElapsedTime(admissionStart); + var remaining = Remaining(admissionStart, request.Budget); + var reduced = request with { Budget = request.Budget with { Timeout = remaining }, + Items = request.Items.Select(x => x with { RemainingBudget = x.RemainingBudget - elapsed }).ToArray() }; + return await WriteCoreAsync(reduced, cancellationToken).ConfigureAwait(false); + } + finally { if (admitted) _unaryCapacity.Release(); ExitWork(); } + } + private async Task> WriteCoreAsync(WriteBatch request, CancellationToken cancellationToken) + { + request.Budget.Validate(); + ArgumentNullException.ThrowIfNull(request.Items); + var start = Clock.GetTimestamp(); + var results = request.Items.Select(x => new WriteItemResult(x.CorrelationId, + new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "No ready endpoint."))).ToArray(); + if (!ProbeAllowed()) return results; + var eligible = Enumerable.Range(0, request.Items.Count).ToArray(); + var attempted = false; + foreach (var endpoint in _endpoints) + { + if (eligible.Length == 0) break; + cancellationToken.ThrowIfCancellationRequested(); + Selected selected; + try { selected = await SelectAsync(endpoint, start, request.Budget, true, cancellationToken).ConfigureAwait(false); ProbeSucceeded(); } + catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException or TimeoutException) + { continue; } + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, selected.Channel.Retired.Token, _shutdown.Token); + var items = eligible.Select(i => request.Items[i]).ToArray(); + if (attempted) + { + // A retry needs fresh, authenticated metadata from the new primary. Never infer a + // catalog revision from its serving epoch or reuse the old node incarnation. + try + { + var remaining = Remaining(start, request.Budget); + var budget = request.Budget with { Timeout = remaining }; + var metadataRequest = new MetadataRequest(items.Select(x => x.View).ToArray(), budget); + var wireMetadata = await selected.Channel.Client.GetMetadataAsync(DataProtoMapper.EncodeMetadataRequest(metadataRequest), + Options(selected.Channel, start, request.Budget, linked.Token)).ResponseAsync.ConfigureAwait(false); + Verify(wireMetadata.Serving, selected); + var metadata = DataProtoMapper.DecodeMetadataResponse(wireMetadata, Limits(budget, selected.Capabilities)); + if (metadata.Count != items.Length || metadata.Where((x, i) => x.CorrelationId != i.ToString(System.Globalization.CultureInfo.InvariantCulture) || + x.Status != DataItemStatus.Good || x.Value is null || x.Value.View.Address != items[i].View.Address || + !x.Value.Writable || (x.Value.AllowedOperations & DataOperations.Write) == 0).Any()) continue; + linked.Token.ThrowIfCancellationRequested(); Verify(wireMetadata.Serving, selected); + items = items.Select((x, i) => x with { ExpectedCatalogRevision = metadata[i].Value!.CatalogRevision, + ExpectedServingIncarnation = selected.Capabilities.Serving.Incarnation }).ToArray(); + } + catch (Exception ex) when (ex is RpcException or InvalidOperationException or ArgumentException or TimeoutException or OperationCanceledException) + { if (cancellationToken.IsCancellationRequested || _scope.CancellationToken.IsCancellationRequested) break; continue; } + } + var elapsed = Clock.GetElapsedTime(start); + var live = Enumerable.Range(0, items.Length).Where(i => items[i].RemainingBudget > elapsed).ToArray(); + foreach (var i in Enumerable.Range(0, items.Length).Except(live)) + results[eligible[i]] = new(request.Items[eligible[i]].CorrelationId, + new(DataWriteState.RejectedBeforeDispatch, 0x800A0000u, "Item budget expired before dispatch.")); + eligible = live.Select(i => eligible[i]).ToArray(); + items = live.Select(i => items[i] with { RemainingBudget = items[i].RemainingBudget - elapsed }).ToArray(); + if (eligible.Length == 0) break; + var dispatchStarted = false; + try + { + var remaining = Remaining(start, request.Budget); + var batch = new WriteBatch(items.Select(x => x with { RemainingBudget = x.RemainingBudget < remaining ? x.RemainingBudget : remaining }).ToArray(), + request.Budget with { Timeout = remaining }); + var options = Options(selected.Channel, start, request.Budget, linked.Token); + var encoded = DataProtoMapper.EncodeWriteRequest(batch); + linked.Token.ThrowIfCancellationRequested(); + dispatchStarted = true; + var wire = await selected.Channel.Client.WriteAsync(encoded, options).ResponseAsync.ConfigureAwait(false); + var decoded = DataProtoMapper.DecodeWriteResponse(wire, Limits(batch.Budget, selected.Capabilities)); + if (decoded.Count != items.Length || !decoded.Select(x => x.CorrelationId).SequenceEqual(items.Select(x => x.CorrelationId))) + throw new InvalidOperationException("Invalid write result sequence."); + VerifyWriteEnvelope(wire.Serving, selected, decoded); + linked.Token.ThrowIfCancellationRequested(); + for (var i = 0; i < eligible.Length; i++) results[eligible[i]] = decoded[i]; + eligible = eligible.Where((_, i) => decoded[i].Outcome.State == DataWriteState.RejectedBeforeDispatch).ToArray(); + attempted = true; + } + catch (Exception ex) when (ex is RpcException or HttpRequestException or OperationCanceledException or InvalidOperationException or ArgumentException or TimeoutException) + { + if (dispatchStarted) + foreach (var index in eligible) results[index] = new(request.Items[index].CorrelationId, + new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Write outcome unknown.")); + break; + } + } + if (!attempted && eligible.Length > 0) ProbeFailed(); + return results; + } + private static void VerifyWriteEnvelope(W.Serving? serving, Selected selected, IReadOnlyList results) + { + if (serving is null) throw new InvalidOperationException("Missing write serving identity."); + var actual = DataProtoMapper.DecodeServing(serving); + var expected = selected.Capabilities.Serving; + if (!AcceptWriteServing(expected, actual, results)) + throw new InvalidOperationException("Write serving identity changed."); + selected.Channel.Retired.Token.ThrowIfCancellationRequested(); + } + internal static bool AcceptWriteServing(ServingIdentity expected, ServingIdentity actual, IReadOnlyList results) => + actual == expected || actual.NodeId == expected.NodeId && actual.Incarnation == expected.Incarnation && + results.Count > 0 && results.All(x => x.Outcome.State == DataWriteState.RejectedBeforeDispatch); + + public async Task SubscribeAsync(CancellationToken cancellationToken) + { + EnterWork(); + var reserved = false; + try + { + if (!ProbeAllowed()) throw new InvalidOperationException("Data endpoint discovery is backing off."); + while (true) + { + var count = Volatile.Read(ref _activeStreams); + if (count >= _maxStreams) throw new InvalidOperationException("Stream capacity exhausted."); + if (Interlocked.CompareExchange(ref _activeStreams, count + 1, count) == count) { reserved = true; break; } + } + var budget = new DataBudget(TimeSpan.FromSeconds(5), 1000, _maxMessageBytes); + var start = Clock.GetTimestamp(); Exception? failure = null; + foreach (var endpoint in _endpoints) + { + try + { + var selected = await SelectAsync(endpoint, start, budget, false, cancellationToken).ConfigureAwait(false); + if ((selected.Capabilities.Operations & DataOperations.Subscribe) == 0 || + Volatile.Read(ref _activeStreams) > selected.Capabilities.Limits.MaxStreams) + throw new InvalidOperationException("Subscriptions unavailable or peer stream capacity exhausted."); + ProbeSucceeded(); + var lifetime = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, selected.Channel.Retired.Token, _shutdown.Token); + RemoteSubscription? subscription = null; + var transferred = false; + try + { + var call = selected.Channel.Client.Subscribe(Headers(selected.Channel), cancellationToken: lifetime.Token); + subscription = new RemoteSubscription(call, selected, lifetime, _maxMessageBytes, + Math.Min(_maxMonitoredItems, selected.Capabilities.Limits.MaxMonitoredItems), _maxPendingCommands, + _maxCommandTimeout, _commandBudget, ClaimStreamEpoch, PendingIdentityObserverForTests, AfterTimerCancelledForTests, () => { lock (_sync) { _streams.Remove(subscription!); Interlocked.Decrement(ref _activeStreams); CheckDrainedLocked(); } }); + if (BeforeStreamInstallForTests is { } pause) await pause().ConfigureAwait(false); + lock (_sync) + { + _streams.Add(subscription); reserved = false; transferred = true; + if (_disposed) throw new ObjectDisposedException(nameof(GrpcDataConnection)); + } + subscription.ObserveLifetime(); + return subscription; + } + catch + { + if (subscription is null) lifetime.Dispose(); + else + { + // Once a call exists, even a failed install owns a raw-send receipt. + // Transfer its slot first; cleanup and the receipt run outside this lock. + if (!transferred) + { + lock (_sync) { _streams.Add(subscription); reserved = false; } + } + _ = subscription.DisposeAsync(); + } + throw; + } + } + catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException) + { failure = ex; } + } + ProbeFailed(); + throw new InvalidOperationException("No ready subscription endpoint.", failure); + } + finally + { + if (reserved) { lock (_sync) { Interlocked.Decrement(ref _activeStreams); CheckDrainedLocked(); } } + ExitWork(); + } + } + + private sealed class RemoteSubscription( + AsyncDuplexStreamingCall call, Selected selected, + CancellationTokenSource lifetime, int maxBytes, int maxItems, int maxPendingCommands, + TimeSpan maxCommandTimeout, CommandStateBudget commandBudget, Func claimEpoch, Action? observePending, + Func? afterTimerCancelled, Action release) : IDataSubscription + { + private readonly SemaphoreSlim _send = new(1, 1); + private readonly Task _headersReceipt = call.ResponseHeadersAsync; + private Dictionary _handles = new(); + private Dictionary _clientHandles = new(StringComparer.Ordinal); + private HashSet _usedHandles = new(); + private Dictionary _versions = new(); + private sealed record PendingCommand(string Id, string[]? ClientIds, DataItemHandle[]? Removed, + bool IsModify, TimeSpan Timeout, long Bytes, CancellationTokenSource Timer); + private readonly Dictionary _pending = new(StringComparer.Ordinal); + private long _pendingBytes, _usedCommandBytes; + private readonly HashSet _usedCommands = new(StringComparer.Ordinal); + private string? _id; + private long _epoch, _sequence; + private int _disposed, _reading, _operations; + private bool _physicalClosed, _released; + private readonly object _lifecycle = new(); + private readonly TaskCompletionSource _closed = new(TaskCreationOptions.RunContinuationsAsynchronously); + private CancellationTokenRegistration _retirementRegistration; + internal void ObserveLifetime() => _retirementRegistration = lifetime.Token.Register(() => { _ = Task.Run(async () => await DisposeAsync()); }); + private void EnterOperation() + { + lock (_lifecycle) { ObjectDisposedException.ThrowIf(_disposed != 0, this); _operations++; } + } + private void ExitOperation() + { + bool finish; + lock (_lifecycle) { _operations--; finish = TryFinishLocked(); } + if (finish) Finish(); + } + private bool TryFinishLocked() + { + if (_disposed == 0 || !_physicalClosed || _operations != 0 || _released) return false; + _released = true; return true; + } + private void Finish() + { + _retirementRegistration.Dispose(); + lock (_pending) + { + foreach (var pending in _pending.Values) { pending.Timer.Cancel(); pending.Timer.Dispose(); } + _pending.Clear(); + commandBudget.Release(checked(_pendingBytes + _usedCommandBytes)); + _pendingBytes = 0; _usedCommandBytes = 0; + } + lifetime.Dispose(); release(); _closed.TrySetResult(); + } + public async Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) + { + EnterOperation(); + try + { + ArgumentNullException.ThrowIfNull(command); + if (command.AcknowledgementTimeout <= TimeSpan.Zero || command.AcknowledgementTimeout > maxCommandTimeout) + throw new ArgumentOutOfRangeException(nameof(command)); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, lifetime.Token); + linked.CancelAfter(command.AcknowledgementTimeout); + if (!await _send.WaitAsync(0, linked.Token).ConfigureAwait(false)) throw new InvalidOperationException("A command is already being sent."); + try + { + if (_id is null) + { + if (command is not OpenSubscription) throw new InvalidOperationException("First command must open the stream."); + if (!claimEpoch(command.SubscriptionId, command.StreamEpoch)) + throw new InvalidOperationException("Subscription epoch was already used or history capacity exhausted."); + _id = command.SubscriptionId; _epoch = command.StreamEpoch; + } + if (command.SubscriptionId != _id || command.StreamEpoch != _epoch || command.StreamEpoch <= 0) + throw new InvalidOperationException("Command belongs to another stream epoch."); + var count = command switch { OpenSubscription o => o.Items.Count, AddSubscriptionItems a => a.Items.Count, + ModifySubscriptionItems m => m.Items.Count, RemoveSubscriptionItems r => r.Items.Count, _ => maxItems + 1 }; + if (count > maxItems) throw new InvalidOperationException("Command item capacity exceeded."); + var encoded = DataProtoMapper.EncodeCommand(command); + if (encoded.CalculateSize() > Math.Min(maxBytes, selected.Capabilities.Limits.MaxMessageBytes)) + throw new InvalidOperationException("Command byte capacity exceeded."); + string[]? ids = command switch + { + OpenSubscription => encoded.Open.Items.Select(x => x.ClientItemId).ToArray(), + AddSubscriptionItems => encoded.Add.Items.Select(x => x.ClientItemId).ToArray(), + ModifySubscriptionItems => encoded.Modify.Items.Select(x => x.ClientItemId).ToArray(), + _ => null + }; + var removed = command is RemoveSubscriptionItems ? encoded.Remove.Items.Select(DataProtoMapper.DecodeHandle).ToArray() : null; + long charge = checked(256L + 2L * encoded.CommandId.Length + (ids?.Sum(x => 64L + 2L * x.Length) ?? 0L) + + (removed?.Sum(x => 96L + 2L * x.SubscriptionId.Length) ?? 0L)); + var pending = new PendingCommand(encoded.CommandId, ids, removed, command is ModifySubscriptionItems, + command.AcknowledgementTimeout, charge, CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token)); + lock (_pending) + { + var commandLimit = (int)Math.Min(100_000L, Math.Max(1024L, 4L * maxItems)); + long usedCharge = checked(64L + 2L * pending.Id.Length); + if (_pending.Count >= maxPendingCommands || _usedCommands.Count >= commandLimit || _usedCommands.Contains(pending.Id) || + !commandBudget.TryReserve(checked(charge + usedCharge))) + { pending.Timer.Dispose(); throw new InvalidOperationException("Command capacity or duplicate command."); } + _usedCommands.Add(pending.Id); _pending.Add(pending.Id, pending); + _pendingBytes += charge; _usedCommandBytes += usedCharge; + } + if (pending.ClientIds is not null) observePending?.Invoke(new WeakReference(pending.ClientIds)); + _ = ExpireUnacknowledgedAsync(pending.Id, pending.Timeout, pending.Timer); + try { await call.RequestStream.WriteAsync(encoded, linked.Token).ConfigureAwait(false); } + catch { await lifetime.CancelAsync().ConfigureAwait(false); throw; } + } + finally { _send.Release(); } + } + finally { ExitOperation(); } + } + private async Task ExpireUnacknowledgedAsync(string commandId, TimeSpan timeout, CancellationTokenSource timer) + { + try + { + await Task.Delay(timeout, timer.Token).ConfigureAwait(false); + Task? cancellation = null; + lock (_pending) + if (_pending.TryGetValue(commandId, out var current) && ReferenceEquals(current.Timer, timer)) + cancellation = lifetime.CancelAsync(); + if (cancellation is not null) await cancellation.ConfigureAwait(false); + } + catch (OperationCanceledException) { if (afterTimerCancelled is not null) await afterTimerCancelled().ConfigureAwait(false); } + catch (ObjectDisposedException) { } + } + public async IAsyncEnumerable ReadAllAsync([EnumeratorCancellation] CancellationToken cancellationToken) + { + if (Interlocked.Exchange(ref _reading, 1) != 0) throw new InvalidOperationException("A stream has one reader."); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, lifetime.Token); + try + { + while (true) + { + bool more; + EnterOperation(); + try { more = await call.ResponseStream.MoveNext(linked.Token).ConfigureAwait(false); } + finally { ExitOperation(); } + if (!more) break; + var wire = call.ResponseStream.Current; + Verify(wire.Serving, selected); + if (_id is null || wire.SubscriptionId != _id || wire.StreamEpoch != _epoch || wire.Sequence != _sequence + 1) + throw new InvalidOperationException("Unexpected stream epoch or sequence."); + DataSubscriptionFrame frame; + if (wire.Values is not null || wire.CompactValues is not null) + frame = DataProtoMapper.DecodeValues(wire, _handles, maxItems, + Math.Min(maxBytes, selected.Capabilities.Limits.MaxMessageBytes), selected.Capabilities.Serving, + selected.Capabilities.Limits.MaxValueElements, selected.Capabilities.SubscriptionAgeReadiness); + else frame = DataProtoMapper.DecodeControlOrAck(wire, new DataDecodeLimits(maxItems, + Math.Min(maxBytes, selected.Capabilities.Limits.MaxMessageBytes), selected.Capabilities.Limits.MaxValueElements)); + try + { + Verify(wire.Serving, selected); linked.Token.ThrowIfCancellationRequested(); + if (frame is DataSubscriptionAck ack) + { + PendingCommand pending; + lock (_pending) + { + if (!_pending.TryGetValue(ack.CommandId, out pending!)) throw new InvalidOperationException("Unknown acknowledgement."); + } + var requested = pending.ClientIds ?? pending.Removed!.Select(_ => (string?)null).ToArray(); + if (ack.Items.Count != requested.Length) throw new InvalidOperationException("Unexpected acknowledgement count."); + var next = new Dictionary(_handles); + var nextClients = new Dictionary(_clientHandles, StringComparer.Ordinal); + var nextUsed = new HashSet(_usedHandles); + var nextVersions = new Dictionary(_versions); + for (var i = 0; i < ack.Items.Count; i++) + { + var item = ack.Items[i]; + if (requested[i] is { } clientId && item.ClientItemId != clientId) + throw new InvalidOperationException("Unexpected acknowledgement item."); + if (item.Status != DataItemStatus.Good) continue; + var handle = item.Handle ?? throw new InvalidOperationException("Successful acknowledgement has no handle."); + if (pending.Removed is { } removedItems) + { + if (removedItems[i] != handle || !next.Remove(handle.Handle) || + !nextClients.Remove(item.ClientItemId, out var removed) || removed != handle.Handle) + throw new InvalidOperationException("Unexpected removed handle."); + nextVersions.Remove(handle.Handle); + } + else + { + DataItemHandle? prior = null; + if (pending.IsModify) + { + if (!nextClients.TryGetValue(item.ClientItemId, out var previous) || !next.Remove(previous, out prior)) + throw new InvalidOperationException("Unknown modified item."); + if (previous != handle.Handle) nextVersions.Remove(previous); + } + else if (nextClients.ContainsKey(item.ClientItemId)) throw new InvalidOperationException("Duplicate item."); + var unchanged = prior == handle; + if ((!unchanged && nextUsed.Contains(handle.Handle)) || next.Count >= maxItems || next.ContainsKey(handle.Handle)) + throw new InvalidOperationException("Handle capacity or identity conflict."); + if (!unchanged && nextUsed.Count >= Math.Min(100_000L, Math.Max(1024L, 4L * maxItems))) + throw new InvalidOperationException("Handle history capacity exhausted; reset the stream."); + nextUsed.Add(handle.Handle); next[handle.Handle] = handle; + nextClients[item.ClientItemId] = handle.Handle; + } + } + Verify(wire.Serving, selected); linked.Token.ThrowIfCancellationRequested(); + lock (_pending) + { + linked.Token.ThrowIfCancellationRequested(); + if (!_pending.Remove(ack.CommandId)) throw new InvalidOperationException("Acknowledgement expired."); + _pendingBytes -= pending.Bytes; commandBudget.Release(pending.Bytes); + pending.Timer.Cancel(); pending.Timer.Dispose(); + _handles = next; _clientHandles = nextClients; _usedHandles = nextUsed; _versions = nextVersions; + } + } + if (frame is DataSubscriptionValues values) + { + var nextVersions = new Dictionary(_versions); + var seen = new HashSet(); + foreach (var item in values.Items) + { + if (!seen.Add(item.Handle.Handle) || nextVersions.TryGetValue(item.Handle.Handle, out var previous) && item.Sample.Version < previous) + throw new InvalidOperationException("Duplicate handle or sample version regression."); + nextVersions[item.Handle.Handle] = item.Sample.Version; + } + Verify(wire.Serving, selected); linked.Token.ThrowIfCancellationRequested(); _versions = nextVersions; + } + _sequence = wire.Sequence; + } + catch { if (frame is IDisposable owned) owned.Dispose(); throw; } + yield return frame; + if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Reset }) + { await lifetime.CancelAsync().ConfigureAwait(false); yield break; } + } + } + finally { await DisposeAsync().ConfigureAwait(false); } + } + public ValueTask DisposeAsync() + { + lock (_lifecycle) + { + if (_disposed == 0) { _disposed = 1; _ = ClosePhysicalAsync(); } + return new(_closed.Task); + } + } + private async Task ClosePhysicalAsync() + { + await Task.Yield(); + try { await Task.Run(() => { lifetime.Cancel(); call.Dispose(); }).ConfigureAwait(false); } + catch (Exception) { } + // Unlike MoveNext's pre-header task, this receipt settles only after the raw HTTP send does. + try { await _headersReceipt.ConfigureAwait(false); } catch (Exception) { } + bool finish; + lock (_lifecycle) { _physicalClosed = true; finish = TryFinishLocked(); } + if (finish) Finish(); + } + } + public ValueTask DisposeAsync() + { + lock (_sync) + { + if (_disposeTask is not null) return new(_disposeTask); + _disposed = true; + _security.Changed -= SecurityChanged; + _shutdownCancellation = _shutdown.CancelAsync(); + RetireAll(); + foreach (var stream in _streams.ToArray()) _ = stream.DisposeAsync(); + CheckDrainedLocked(); + _disposeTask = FinishDisposeAsync(); + return new(_disposeTask); + } + } + private async Task FinishDisposeAsync() + { + await _drained.Task.ConfigureAwait(false); + try { if (_shutdownCancellation is not null) await _shutdownCancellation.ConfigureAwait(false); } + finally { _scope.Dispose(); _shutdown.Dispose(); } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs index ea4a6c375..56eaf097d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs @@ -51,14 +51,16 @@ public sealed class LocalCatalogCoordinator 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) + if (current.Role == catalog.Serving.Role && current.ServingGeneration == catalog.Serving.ServingGeneration) { 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; + if (verified.Role != catalog.Serving.Role || verified.ServingGeneration != catalog.Serving.ServingGeneration + || !ReferenceEquals(Volatile.Read(ref _published), catalog)) continue; return catalog.IsActive ? catalog : null; } - var adjusted = catalog.WithServingRole(catalog.Serving with { Role = current.Role }); + var adjusted = catalog.WithServingRole(catalog.Serving with + { Role = current.Role, ServingGeneration = current.ServingGeneration }); // Acquisition callers must not wait behind a write-commit or authority publisher. // Serving will return provisional zero epochs if the role wrapper cannot be refreshed. if (!DispatchFence.TryEnter(out var lease)) return null; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs index fc8599010..1dfe4e5c2 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs @@ -3,7 +3,7 @@ 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 +public sealed class LocalDataConnection : IDataConnection, IDataConnectionPublicationGate, IDataConnectionDiscoveryGate { private readonly LocalDataServices _services; private readonly DataAuthenticatedContext _context; @@ -12,16 +12,18 @@ public sealed class LocalDataConnection : IDataConnection, IDataConnectionPublic { _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); + public bool CanPublish(ServingIdentity expectedServing) => Volatile.Read(ref _disposed) == 0 && _services.CanPublish(_context, expectedServing, Target); + public bool CanPublishCapabilities(DataCapabilities expected) => Volatile.Read(ref _disposed) == 0 + && _services.CanPublishCapabilities(_context, Target, expected); private void Check() => ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) { Check(); return _services.GetCapabilitiesAsync(_context, Target, budget, cancellationToken); } public Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) - { Check(); return _services.BrowseAsync(_context, Target, request, cancellationToken); } + { Check(); _services.RequireTargetRole(Target); return _services.BrowseAsync(_context, Target, request, cancellationToken); } public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) - { Check(); return _services.GetMetadataAsync(_context, Target, request, cancellationToken); } + { Check(); _services.RequireTargetRole(Target); return _services.GetMetadataAsync(_context, Target, request, cancellationToken); } public Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) - { Check(); return _services.ReadAsync(_context, request, cancellationToken); } + { Check(); _services.RequireTargetRole(Target); return _services.ReadAsync(_context, Target, request, cancellationToken); } public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) { Check(); return _services.WriteAsync(_context, request, cancellationToken); } public Task SubscribeAsync(CancellationToken cancellationToken) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs new file mode 100644 index 000000000..de0ef2677 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs @@ -0,0 +1,42 @@ +using Akka.Actor; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Bounds shared physical demand and downstream subscription resources for one process. +public sealed record LocalDataRuntimeLimits(int MaxDrivers, int MaxInterests, int MaxOperations, + int MaxOperationsPerPrincipal, long MaxTransportBytes, int MaxCommands, int MaxPendingFrames, + long MaxPendingBytes, TimeSpan MaxSessionLifetime, TimeSpan DriverAskTimeout); + +/// Owns the local caller-bound services and the one shared physical-demand bridge. +public sealed class LocalDataRuntimeComposition : IDisposable +{ + private readonly DriverHostSubscriptionDemandSource _demand; + private int _disposed; + public LocalDataRuntimeComposition(LocalCatalogCoordinator catalog, PartitionedSampleHub hub, + DataOperationPolicy policy, DataCapabilitiesProvider capabilities, TimeProvider clock, DataWriteRuntime writes, + IActorRef host, SubscriptionAcquisitionCapacity acquisitionCapacity, LocalDataRuntimeLimits limits) + { + ArgumentNullException.ThrowIfNull(catalog); ArgumentNullException.ThrowIfNull(hub); + ArgumentNullException.ThrowIfNull(policy); ArgumentNullException.ThrowIfNull(capabilities); + ArgumentNullException.ThrowIfNull(clock); ArgumentNullException.ThrowIfNull(writes); + ArgumentNullException.ThrowIfNull(host); ArgumentNullException.ThrowIfNull(acquisitionCapacity); + ArgumentNullException.ThrowIfNull(limits); + if (!ReferenceEquals(hub.Clock, clock)) throw new ArgumentException("Local hub and services must share one clock.", nameof(clock)); + var sessionLimits = new SubscriptionSessionLimits(limits.MaxCommands, limits.MaxPendingFrames, limits.MaxPendingBytes, limits.MaxSessionLifetime); + sessionLimits.Validate(); + var registry = new UpstreamDemandRegistry(limits.MaxInterests, limits.MaxInterests); + var capacity = new SubscriptionTransportCapacity(limits.MaxOperations, limits.MaxOperationsPerPrincipal, limits.MaxTransportBytes, clock); + _demand = new DriverHostSubscriptionDemandSource(host, registry, limits.MaxDrivers, limits.MaxInterests, limits.DriverAskTimeout, acquisitionCapacity); + AcquisitionCapacity = acquisitionCapacity; + LocalDataServices? services = null; + services = new LocalDataServices(() => catalog.Current, hub, policy, capabilities, clock, + writes: context => writes.ForCaller(context, () => host), + targetSubscriptions: (context, target) => new LocalSubscriptionService(services!, context, target, _demand, sessionLimits, capacity)); + Services = services; + } + public LocalDataServices Services { get; } + public SubscriptionAcquisitionCapacity AcquisitionCapacity { get; } + public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) _demand.Dispose(); } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs index 4033df2e0..7d2ff9b85 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs @@ -48,17 +48,44 @@ public sealed class LocalDataServices : IDataConnectionFactory 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) + internal bool CanPublish(DataAuthenticatedContext context, ServingIdentity expectedServing, DataTarget? target = null) { var catalog = _catalog(); return catalog is not null && Ready(catalog) && catalog.Serving == expectedServing + && context.AuthorityEpoch == catalog.AuthorityEpoch + && (target is null || RoleAllows(target, catalog.Serving)) && _policy.IsCallerUsable(Caller(context)); } + private static bool RoleAllows(DataTarget target, ServingIdentity serving) => + string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase) + || target.Mode == DataTargetMode.Node && target.Consistency == DataConsistency.ReadyReplica + && string.Equals(serving.Role, "Secondary", StringComparison.OrdinalIgnoreCase); + + internal void RequireTargetRole(DataTarget target) + { + if (!RoleAllows(target, _capabilities.Serving)) + throw new InvalidOperationException("The requested target cannot serve the required consistency."); + } + + internal bool CanPublishCapabilities(DataAuthenticatedContext context, DataTarget target, DataCapabilities expected) + { + var catalog = _catalog(); + if (!_policy.IsCallerUsable(Caller(context)) || context.AuthorityEpoch != _policy.AuthorityEpoch + || _capabilities.Serving != expected.Serving) return false; + var ready = catalog is not null && Ready(catalog) && context.AuthorityEpoch == catalog.AuthorityEpoch + && RoleAllows(target, catalog.Serving); + var operations = ready ? catalog!.ExportOperations(context.PrincipalId) & Implemented(target) : DataOperations.None; + if (!string.Equals(expected.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)) operations &= ~DataOperations.Write; + return expected.Readiness == (ready ? DataReadiness.Ready : DataReadiness.Unavailable) + && expected.Operations == operations && _capabilities.Serving == expected.Serving + && _policy.IsCallerUsable(Caller(context)) && context.AuthorityEpoch == _policy.AuthorityEpoch; + } + private sealed class PublicationReadLease(CachedSourceRead read, Func gate) : IDataPublicationLease { private int _disposed; - public bool IsValid => Volatile.Read(ref _disposed) == 0 && read.IsValid && gate(); + public bool IsValid => gate() && Volatile.Read(ref _disposed) == 0 && read.IsValid; public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) read.Dispose(); } } @@ -104,6 +131,7 @@ public sealed class LocalDataServices : IDataConnectionFactory view.Validate(); target.Validate(); var catalog = _catalog(); if (catalog is null || !Ready(catalog)) return DataItemStatus.Unavailable; + if (!RoleAllows(target, catalog.Serving)) return DataItemStatus.Unavailable; if (context.AuthorityEpoch != catalog.AuthorityEpoch) return DataItemStatus.Denied; if (!string.Equals(target.ExpectedClusterId, catalog.ClusterId, StringComparison.OrdinalIgnoreCase) || target.Mode == DataTargetMode.Node && !string.Equals(target.ExpectedNodeId, catalog.Serving.NodeId, StringComparison.OrdinalIgnoreCase)) @@ -143,6 +171,7 @@ public sealed class LocalDataServices : IDataConnectionFactory { var catalog = _catalog(); return catalog is not null && Ready(catalog) && context.AuthorityEpoch == catalog.AuthorityEpoch && + RoleAllows(target, catalog.Serving) && (expected is null || catalog.Serving == expected) && _policy.IsCallerUsable(Caller(context)) && string.Equals(target.ExpectedClusterId, catalog.ClusterId, StringComparison.OrdinalIgnoreCase) && (target.Mode != DataTargetMode.Node || string.Equals(target.ExpectedNodeId, catalog.Serving.NodeId, StringComparison.OrdinalIgnoreCase)); @@ -183,7 +212,8 @@ public sealed class LocalDataServices : IDataConnectionFactory if (!_policy.IsCallerUsable(Caller(context))) throw new UnauthorizedAccessException(); var capabilities = _capabilities.Get(catalog is null ? DataOperations.None : catalog.ExportOperations(context.PrincipalId) & Implemented(target), catalog is null ? _capabilities.Limits : Limits(catalog, context)); - if (catalog is null || !Ready(catalog)) capabilities = capabilities with { Readiness = DataReadiness.Unavailable, Operations = DataOperations.None }; + if (catalog is null || !Ready(catalog) || context.AuthorityEpoch != catalog.AuthorityEpoch || !RoleAllows(target, catalog.Serving)) + capabilities = capabilities with { Readiness = DataReadiness.Unavailable, Operations = DataOperations.None }; return Task.FromResult(capabilities); } @@ -226,7 +256,7 @@ public sealed class LocalDataServices : IDataConnectionFactory return Task.FromResult>>(results); } - internal Task> ReadAsync(DataAuthenticatedContext context, ReadRequest request, CancellationToken cancellationToken) + internal Task> ReadAsync(DataAuthenticatedContext context, DataTarget target, ReadRequest request, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Items); var catalog = _catalog(); @@ -274,7 +304,7 @@ public sealed class LocalDataServices : IDataConnectionFactory 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) + var publication = new PublicationReadLease(read, () => CanPublish(context, exposed.Serving, target) && !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, new DataAgeBounds(age, age))); @@ -334,11 +364,18 @@ public sealed class LocalDataServices : IDataConnectionFactory bytes += size; page.Add(metadata); } if (!Allowed(catalog, context, parent, DataOperations.Browse)) return Task.FromResult(Empty(DataItemStatus.Denied)); + var leaseDuration = limits.MaxMetadataLease; + if (context.CredentialExpiresUtc is { } expiry) + { + var remaining = expiry - Clock.GetUtcNow(); + if (remaining <= TimeSpan.Zero) return Task.FromResult(Empty(DataItemStatus.Denied)); + if (remaining < leaseDuration) leaseDuration = remaining; + } 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)); + context.ApiKeyId, context.CredentialVersion, catalog.Serving, start, leaseDuration.Ticks)); return Task.FromResult(new DataBrowseBranch(request.Parent, DataItemStatus.Good, page, complete, token, - new MetadataLease(catalog.Serving.CatalogEpoch, catalog.Serving.AuthorityEpoch, limits.MaxMetadataLease))); + new MetadataLease(catalog.Serving.CatalogEpoch, catalog.Serving.AuthorityEpoch, leaseDuration))); } internal async Task> WriteAsync(DataAuthenticatedContext context, WriteBatch request, CancellationToken cancellationToken) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/WriteAdmissionTicket.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/WriteAdmissionTicket.cs index fcd7266e4..853c0e901 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/WriteAdmissionTicket.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/WriteAdmissionTicket.cs @@ -9,7 +9,7 @@ internal sealed record WriteRouteTarget(string DriverInstanceId, string DriverRe long RouteGeneration, long PrimaryGeneration); internal sealed record WriteRouteProof(DataWriteAdmission Admission, FrozenWriteScope Scope, string EntityKind, string EntityId, BackingSourceKey? Source, string DriverInstanceId, string DriverReference, - long RouteGeneration, long PrimaryGeneration); + long RouteGeneration, long PrimaryGeneration, ServingIdentity? Serving = null); /// Owns the value and its byte charge until rejection or actual driver completion. internal sealed class WriteAdmissionTicket : IDisposable 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 8a45295ad..c96e7c45f 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 @@ -6,6 +6,12 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers; public static partial class DeploymentArtifact { + /// Reads the durable central scope generation independently of whether this node still has imports. + public static long ParseDataConnectionScopeVersion(ReadOnlySpan blob) + { + using var parsed = Open(blob.ToArray()); + return parsed.ParseDataConnectionScopeVersion(); + } /// Read the node-effective data connections from an artifact. public static IReadOnlyList ParseDataConnections( ReadOnlySpan blob, @@ -36,6 +42,13 @@ public static partial class DeploymentArtifact internal sealed partial class ParsedDeploymentArtifact { + internal long ParseDataConnectionScopeVersion() + { + if (!Root.TryGetProperty("DataConnectionScopeVersion", out var value)) return 0; + if (!value.TryGetInt64(out var version) || version <= 0) + throw new InvalidOperationException("Data connection scope generation is invalid."); + return version; + } /// Materialize this node's eligible catalog inputs while the artifact document is alive. internal DraftSnapshot? ParseLocalCatalogSnapshot(string nodeId) => ReadDataProjection(nodeId)?.Snapshot; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs index d4b631a36..da03321d2 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -492,6 +492,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS /// snapshot proves this node is Primary (archreview 03/S4 — closes the dual-primary boot window). /// private RedundancyRole? _localRole; + private RedundancyRole? _observedDataServingRole; + private readonly long _dataServingOwner; + private readonly DataConnectionDeploymentRuntime? _dataConnections; /// Test seam (archreview 03/S4): overrides the count of Up driver-role cluster members /// the Primary gate reads while the role is unknown. Null ⇒ read the live cluster state (0 on a @@ -839,7 +842,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null, ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null, DataWriteRuntime? dataWriteRuntime = null, - SubscriptionAcquisitionCapacity? acquisitionCapacity = null) => + SubscriptionAcquisitionCapacity? acquisitionCapacity = null, + DataConnectionDeploymentRuntime? dataConnections = null) => // WARNING: this forwarding list is POSITIONAL, and Props.Create compiles it into an // expression tree. Six IActorRef? parameters and several interface-typed ones mean a // mis-ordered argument is usually type-compatible and therefore compiles clean, then binds @@ -854,7 +858,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS sharesHistorizationScopeWithLocal, applyWedgeTimeout, reprovisionBackoff, commsRecoveryAuditDelay, sharesAlarmQueueWithLocal, applyOutcomeTimeout, captureWhilePrimaryUnreachable, historyUpdateRoleView, scripting, ackPreflightView, writeBounds, writeClock, scriptedAlarmRunner, childShutdownTimeout, - enforceSnapshotOrdering, sourcePublisher, catalogCoordinator, dataWriteRuntime, acquisitionCapacity)); + enforceSnapshotOrdering, sourcePublisher, catalogCoordinator, dataWriteRuntime, acquisitionCapacity, dataConnections)); /// Initializes a new DriverHostActor with the specified dependencies. /// Database context factory for configuration database access. @@ -994,9 +998,11 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null, ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null, DataWriteRuntime? dataWriteRuntime = null, - SubscriptionAcquisitionCapacity? acquisitionCapacity = null) + SubscriptionAcquisitionCapacity? acquisitionCapacity = null, + DataConnectionDeploymentRuntime? dataConnections = null) { _dataWriteRuntime = dataWriteRuntime; + _dataConnections = dataConnections; _acquisitionCapacity = acquisitionCapacity; _acquisitionHostGeneration = acquisitionCapacity?.NextControlGeneration() ?? 0; _sourcePublisher = sourcePublisher; @@ -1023,6 +1029,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS _deploymentArtifactCache = deploymentArtifactCache; _redundancyRoleView = redundancyRoleView; _primaryRoleSource = primaryRoleSource; + _dataServingOwner = (primaryRoleSource as ZB.MOM.WW.OtOpcUa.Runtime.Redundancy.RedundancyRoleView)?.RegisterDataServingOwner() ?? 0; _replicationPeerHost = replicationPeerHost; _fetchAndCacheMode = fetchAndCacheMode; _artifactFetcher = artifactFetcher; @@ -1151,7 +1158,15 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS { var verdict = ShouldServiceAsPrimary(); _lastPublishedPrimaryVerdict = verdict; - _primaryRoleSource.PublishPrimaryRole(verdict); + if (_primaryRoleSource is ZB.MOM.WW.OtOpcUa.Runtime.Redundancy.RedundancyRoleView observed) + { + var generation = observed.PrimaryGeneration; + var role = observed.DataServingRole; + observed.PublishDataServingRole(_dataServingOwner, _observedDataServingRole, verdict); + if (generation != observed.PrimaryGeneration || role != observed.DataServingRole) + _dataConnections?.NotifyConsumerRoleChanged(); + } + else _primaryRoleSource.PublishPrimaryRole(verdict); } PublishHistoryUpdateVerdict(); } @@ -1228,6 +1243,14 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS /// protected override void PostStop() { + if (_primaryRoleSource is ZB.MOM.WW.OtOpcUa.Runtime.Redundancy.RedundancyRoleView observed) + { + var generation = observed.PrimaryGeneration; + var role = observed.DataServingRole; + observed.RetireDataServingOwner(_dataServingOwner); + if (generation != observed.PrimaryGeneration || role != observed.DataServingRole) + _dataConnections?.NotifyConsumerRoleChanged(); + } if (_subscribedToMemberEvents || _subscribedToReachabilityEvents) { try { Akka.Cluster.Cluster.Get(Context.System).Unsubscribe(Self); } @@ -2705,6 +2728,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS _redundancySnapshotReceived = true; var local = msg.Nodes.FirstOrDefault(n => n.NodeId == _localNode); + _observedDataServingRole = local?.Role; if (local is not null) { _localRole = local.Role; @@ -3574,9 +3598,10 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS private void BeginCatalogAttempt(byte[]? blob) { - if (_catalogCoordinator is null) return; var revision = blob is { Length: > 0 } ? Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(blob)) : "unavailable"; + _dataConnections?.BeginAttempt(revision); + if (_catalogCoordinator is null) return; _catalogAttempt = _catalogCoordinator.BeginAttempt(revision); } @@ -3602,6 +3627,16 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS return; } var snapshot = parsed.ParseLocalCatalogSnapshot(_localNode.Value); + if (_dataConnections is not null) + { + var owner = snapshot?.ClusterNodes.FirstOrDefault(node => + string.Equals(node.NodeId, _localNode.Value, StringComparison.OrdinalIgnoreCase))?.ClusterId; + var mode = snapshot?.ServerClusters.FirstOrDefault(cluster => + string.Equals(cluster.ClusterId, owner, StringComparison.OrdinalIgnoreCase))?.RedundancyMode + ?? ZB.MOM.WW.OtOpcUa.Configuration.Enums.RedundancyMode.None; + _dataConnections.Apply(new(parsed.ParseDataConnectionScopeVersion(), _catalogAttempt.Revision, + parsed.ParseDataConnections(_localNode.Value), mode)); + } if (snapshot is not null) _catalogCoordinator.Stage(_catalogAttempt, snapshot, _localNode.Value); } catch (Exception ex) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs index ae7dea8b2..65b5ecba3 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs @@ -338,7 +338,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers WarmRedundancySettings? redundancy = null, IStandbyProjection? standbyProjection = null, DataConnections.CatalogActivation? dataCatalog = null, - DataConnections.LocalCatalogCoordinator? catalogCoordinator = null) => + DataConnections.LocalCatalogCoordinator? catalogCoordinator = null, + DataConnections.DataConnectionWarmRoleView? dataWarmRole = null, + DataConnections.DataConnectionDeploymentRuntime? dataConnections = null) => Akka.Actor.Props.Create(() => new OpcUaPublishActor( sink ?? NullOpcUaAddressSpaceSink.Instance, serviceLevel ?? NullServiceLevelPublisher.Instance, @@ -355,7 +357,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers utcNow, endpointState, redundancy, - standbyProjection, dataCatalog, catalogCoordinator)).WithDispatcher(DispatcherId); + standbyProjection, dataCatalog, catalogCoordinator, dataWarmRole, dataConnections)).WithDispatcher(DispatcherId); /// Test-only Props that omits the pinned-dispatcher requirement and skips the /// DPS subscribe so unit tests can spin up the actor on a vanilla TestKit cluster. @@ -403,7 +405,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers WarmRedundancySettings? redundancy = null, IStandbyProjection? standbyProjection = null, DataConnections.CatalogActivation? dataCatalog = null, - DataConnections.LocalCatalogCoordinator? catalogCoordinator = null) => + DataConnections.LocalCatalogCoordinator? catalogCoordinator = null, + DataConnections.DataConnectionWarmRoleView? dataWarmRole = null, + DataConnections.DataConnectionDeploymentRuntime? dataConnections = null) => Akka.Actor.Props.Create(() => new OpcUaPublishActor( sink ?? NullOpcUaAddressSpaceSink.Instance, serviceLevel ?? NullServiceLevelPublisher.Instance, @@ -420,7 +424,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers utcNow, endpointState, redundancy, - standbyProjection, dataCatalog, catalogCoordinator)); + standbyProjection, dataCatalog, catalogCoordinator, dataWarmRole, dataConnections)); /// Test-only Props exposing the deferred-write bound and the plan-step seams. internal static Props PropsForTests( @@ -430,13 +434,15 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers int deferredWriteCapacity = DefaultDeferredWriteCapacity, NodeId? localNode = null, IDataPlaneAuthoritySink? dataPlaneAuthority = null, - DataConnections.LocalCatalogCoordinator? catalogCoordinator = null) => + DataConnections.LocalCatalogCoordinator? catalogCoordinator = null, + DataConnections.DataConnectionWarmRoleView? dataWarmRole = null, + DataConnections.DataConnectionDeploymentRuntime? dataConnections = null) => // CreateBy, not Create(expression): Akka's expression path activates through a PUBLIC constructor, and the // seam-carrying constructor is internal so the test seams stay off the public API (review M3). Akka.Actor.Props.CreateBy(new TestProducer(() => new OpcUaPublishActor( sink, NullServiceLevelPublisher.Instance, false, localNode, null, applier, null, null, null, null, false, dataPlaneAuthority, null, deferredWriteCapacity, hooks, endpointState: null, - catalogCoordinator: catalogCoordinator))); + catalogCoordinator: catalogCoordinator, dataWarmRole: dataWarmRole, dataConnections: dataConnections))); /// Produces the actor through its internal (seam-carrying) constructor, for . private sealed class TestProducer(Func create) : IIndirectActorProducer @@ -487,10 +493,12 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers WarmRedundancySettings? redundancy = null, IStandbyProjection? standbyProjection = null, DataConnections.CatalogActivation? dataCatalog = null, - DataConnections.LocalCatalogCoordinator? catalogCoordinator = null) + DataConnections.LocalCatalogCoordinator? catalogCoordinator = null, + DataConnections.DataConnectionWarmRoleView? dataWarmRole = null, + DataConnections.DataConnectionDeploymentRuntime? dataConnections = null) : this(sink, serviceLevel, subscribeRedundancyTopic, localNode, dbFactory, applier, dbHealthProbe, staleWindow, probeFreshnessWindow, healthTickInterval, dbLess, dataPlaneAuthority, utcNow, DefaultDeferredWriteCapacity, hooks: null, - endpointState, redundancy, standbyProjection, dataCatalog, catalogCoordinator) + endpointState, redundancy, standbyProjection, dataCatalog, catalogCoordinator, dataWarmRole, dataConnections) { } @@ -518,9 +526,12 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers WarmRedundancySettings? redundancy = null, IStandbyProjection? standbyProjection = null, DataConnections.CatalogActivation? dataCatalog = null, - DataConnections.LocalCatalogCoordinator? catalogCoordinator = null) + DataConnections.LocalCatalogCoordinator? catalogCoordinator = null, + DataConnections.DataConnectionWarmRoleView? dataWarmRole = null, + DataConnections.DataConnectionDeploymentRuntime? dataConnections = null) { _redundancy = redundancy ?? WarmRedundancySettings.Unset; + _dataWarmRole = dataWarmRole; _dataConnections = dataConnections; _standbyProjection = standbyProjection; _deferred = new DeferredWrites(Math.Max(1, deferredWriteCapacity)); _hooks = hooks; @@ -598,6 +609,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers /// protected override void PostStop() { + if (_dataWarmRole is not null && _dataWarmRole.RetireOwner(_dataWarmOwner)) + _dataConnections?.NotifyConsumerRoleChanged(); + _dataWarmOwner = 0; if (_redundancy.IsWarm) { try { _cluster.Unsubscribe(Self); } @@ -617,6 +631,11 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers if (_redundancy.IsWarm) { + if (_dataWarmRole is not null) + { + _dataWarmOwner = _dataWarmRole.RegisterOwner(); + _dataConnections?.NotifyConsumerRoleChanged(); + } OtOpcUaTelemetry.SetWarmRole(0); try { @@ -1834,6 +1853,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers private sealed class WarmRetry { public static readonly WarmRetry Instance = new(); private WarmRetry() { } } private readonly WarmRedundancySettings _redundancy; + private readonly DataConnections.DataConnectionWarmRoleView? _dataWarmRole; + private readonly DataConnections.DataConnectionDeploymentRuntime? _dataConnections; + private long _dataWarmOwner; private readonly IStandbyProjection? _standbyProjection; private readonly SnapshotRevisionGate _revisionGate = new(); /// The latest ACCEPTED revisioned snapshot — the only one the Warm verdict reads (spec §4.2). @@ -2008,10 +2030,13 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers /// private void ApplyWarmTransition(WarmRole target, byte level, string reason) { + // A real Standby verdict must close imports before any projection or publisher callback. + if (_acceptedSnapshot is not null && target == WarmRole.Standby) PublishDataWarmRole(target); if (target == _warmRole) { if (!TryPublishServiceLevel(level) && target == WarmRole.Active) ScheduleWarmRetry(); else if (target == WarmRole.Active) _promotionLevelPending = false; + if (_acceptedSnapshot is not null && target == WarmRole.Active) PublishDataWarmRole(target); return; } @@ -2024,6 +2049,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers projection?.SetAlarmSuppression(false); // 4. new alarm events delivered projection?.RefreshAllEventItems(); // 5. promotion refresh on every live event item _warmRole = WarmRole.Active; + if (_acceptedSnapshot is not null) PublishDataWarmRole(WarmRole.Active); if (TryPublishServiceLevel(level)) // 6. Active ServiceLevel, last { _promotionLevelPending = false; @@ -2054,6 +2080,13 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers target == WarmRole.Active ? "promotion" : "demotion", _warmRole, reason, _revisionGate.LastAccepted, level); } + private void PublishDataWarmRole(WarmRole role) + { + // Publish holds the dispatch fence only for the immutable state swap; notify after it exits. + if (_dataWarmRole is not null && _dataWarmRole.Publish(_dataWarmOwner, role)) + _dataConnections?.NotifyConsumerRoleChanged(); + } + /// /// Gitea #717 spec §3 deploy-time cross-check: under None or Warm, an artifact whose cluster /// RedundancyMode disagrees with the local mode (Hot included, owner answer Q5) logs an Error and diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Redundancy/IRedundancyRoleView.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Redundancy/IRedundancyRoleView.cs index a05251861..15134f990 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Redundancy/IRedundancyRoleView.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Redundancy/IRedundancyRoleView.cs @@ -1,6 +1,7 @@ using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Core.Authorization; using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy; namespace ZB.MOM.WW.OtOpcUa.Runtime.Redundancy; @@ -116,9 +117,13 @@ public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRole { public RedundancyRoleView(DataWriteDispatchFence? dispatchFence = null) => DispatchFence = dispatchFence ?? new(); public DataWriteDispatchFence DispatchFence { get; } - private sealed record PrimaryVerdict(bool Allowed, long Generation); - private PrimaryVerdict _primaryVerdict = new(PrimaryGatePolicy.ShouldServiceAsPrimary(null, 1), 0); + private sealed record PrimaryVerdict(bool Allowed, long Generation, string ServingRole); + private PrimaryVerdict _primaryVerdict = new(PrimaryGatePolicy.ShouldServiceAsPrimary(null, 1), 0, "Unknown"); + private long _nextDataOwner, _dataOwner; + private bool _rolePoisoned; public long PrimaryGeneration => Volatile.Read(ref _primaryVerdict).Generation; + /// The actual observed role, independent of the existing primary policy's boot fallback. + public string DataServingRole => Volatile.Read(ref _primaryVerdict).ServingRole; // seeded CLOSED, unlike the data-plane verdict. HistoryUpdate waits for a real redundancy verdict // (PrimaryGatePolicy.ShouldServeHistoryUpdate); a node that never publishes here is not a driver node with a // redundancy manager, and such a node does not register this view as its gate source. @@ -162,12 +167,61 @@ public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRole /// public void PublishPrimaryRole(bool shouldActAsPrimary) + => PublishPrimaryVerdict(shouldActAsPrimary, null); + + /// Publishes actual serving provenance with the existing primary verdict under their shared fence. + public void PublishDataServingRole(RedundancyRole? role, bool shouldActAsPrimary) + { + if (role is { } observed && !Enum.IsDefined(observed)) throw new ArgumentOutOfRangeException(nameof(role)); + PublishPrimaryVerdict(shouldActAsPrimary, role?.ToString() ?? "Unknown"); + } + + internal long RegisterDataServingOwner() { using (DispatchFence.Enter()) { var current = _primaryVerdict; - if (current.Generation == 0 || current.Allowed != shouldActAsPrimary) - Volatile.Write(ref _primaryVerdict, new(shouldActAsPrimary, checked(current.Generation + 1))); + if (_rolePoisoned || _nextDataOwner == long.MaxValue || current.Generation == long.MaxValue) + { PoisonRole(); throw new InvalidOperationException("Serving role generation exhausted."); } + _dataOwner = ++_nextDataOwner; + Volatile.Write(ref _primaryVerdict, new(current.Allowed, current.Generation + 1, "Unknown")); + return _dataOwner; + } + } + + internal void PublishDataServingRole(long owner, RedundancyRole? role, bool shouldActAsPrimary) => + PublishPrimaryVerdict(shouldActAsPrimary, role?.ToString() ?? "Unknown", owner); + + internal void RetireDataServingOwner(long owner) + { + using (DispatchFence.Enter()) + { + if (owner == 0 || _dataOwner != owner) return; + var current = _primaryVerdict; + _dataOwner = 0; + if (current.Generation == long.MaxValue) { PoisonRole(); return; } + Volatile.Write(ref _primaryVerdict, new(false, current.Generation + 1, "Unknown")); + } + } + + private void PoisonRole() + { + _rolePoisoned = true; _dataOwner = 0; + Volatile.Write(ref _primaryVerdict, new(false, long.MaxValue, "Unknown")); + } + + private void PublishPrimaryVerdict(bool shouldActAsPrimary, string? observedRole, long? owner = null) + { + using (DispatchFence.Enter()) + { + var current = _primaryVerdict; + if (_rolePoisoned || owner is { } expected && (expected == 0 || expected != _dataOwner)) return; + var role = observedRole ?? current.ServingRole; + if (current.Generation == 0 || current.Allowed != shouldActAsPrimary || current.ServingRole != role) + { + if (current.Generation == long.MaxValue) { PoisonRole(); return; } + Volatile.Write(ref _primaryVerdict, new(shouldActAsPrimary, current.Generation + 1, role)); + } } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs index 3f00c17a3..ed008a444 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs @@ -32,6 +32,8 @@ using ZB.MOM.WW.OtOpcUa.Runtime.Telemetry; using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags; using ZB.MOM.WW.LocalDb; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + namespace ZB.MOM.WW.OtOpcUa.Runtime; public static class ServiceCollectionExtensions @@ -559,31 +561,15 @@ public static class ServiceCollectionExtensions loggerFactory.CreateLogger(), provisioning: provisioning, historizedSubscriptions: historizedSubscriptions); - // the sink that receives each applied artifact's API keys + ACL grants, so OPC - // UA session activation can authenticate. Optional: GetService (not GetRequiredService), because - // a node with no driver role never registers it and test harnesses build this graph without it; - // the actor treats null as "nothing consumes authorization inputs" and skips the decode. - var dataPlaneAuthority = resolver.GetService(); // lmxopcua#762: the "did the OPC UA SDK start?" fact the Host's OtOpcUaServerHostedService maintains. // Optional: a harness that builds this graph without the hosted service registers none, and both // consumers then behave as if the endpoint were listening (the pre-#762 behaviour). var endpointState = resolver.GetService(); - // Gitea #717: OpcUa:Redundancy (registered by the Host from the validated OpcUa options). Absent in harnesses ⇒ - // Unset ⇒ today's behaviour. The standby projection is late-bound like the ServiceLevel publisher. var redundancy = resolver.GetService() ?? WarmRedundancySettings.Unset; + // The same production factory selects authority, catalog and Warm publications in tests. var publishActor = system.ActorOf( - OpcUaPublishActor.Props( - sink: addressSpaceSink, - serviceLevel: serviceLevel, - localNode: roleInfo.LocalNode, - dbFactory: dbFactory, - applier: applier, - dbHealthProbe: dbHealth, - dbLess: dbFactory is null, - dataPlaneAuthority: dataPlaneAuthority, - endpointState: endpointState, - redundancy: redundancy, - standbyProjection: redundancy.IsWarm ? resolver.GetService() : null), + DataConnectionPublisherProps.Create(resolver, addressSpaceSink, serviceLevel, + roleInfo.LocalNode, dbFactory, applier, dbHealth), OpcUaPublishActorName); registry.Register(publishActor); @@ -679,7 +665,13 @@ public static class ServiceCollectionExtensions scriptedAlarmRunner: resolver.GetService() ?.ForSeam(ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptSeam.ScriptedAlarm), // Gitea #717 spec §4.2: drop older redundancy snapshots under Warm only. - enforceSnapshotOrdering: redundancy.IsWarm), + enforceSnapshotOrdering: redundancy.IsWarm, + sourcePublisher: resolver.GetService(), + catalogCoordinator: resolver.GetService(), + dataWriteRuntime: resolver.GetService(), + acquisitionCapacity: resolver.GetService(), + writeClock: resolver.GetService(), + dataConnections: resolver.GetService()), DriverHostActorName); registry.Register(driverHost); diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataResponseServingTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataResponseServingTests.cs new file mode 100644 index 000000000..d971483d8 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataResponseServingTests.cs @@ -0,0 +1,38 @@ +using Google.Protobuf; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Commons.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")] +public sealed class GrpcDataResponseServingTests +{ + [Fact] + public void Empty_batches_and_control_frames_retain_their_explicit_serving_envelope() + { + var serving = new ServingIdentity("node", "boot", "Primary", 1, 2, ServingGeneration: 9); + foreach (var message in new IMessage[] { + new W.BrowseResponse { Serving = DataProtoMapper.EncodeServing(serving) }, + new W.MetadataResponse { Serving = DataProtoMapper.EncodeServing(serving) }, + new W.ReadResponse { Serving = DataProtoMapper.EncodeServing(serving) }, + new W.WriteResponse { Serving = DataProtoMapper.EncodeServing(serving) }, + new W.SubscriptionFrame { Serving = DataProtoMapper.EncodeServing(serving), Control = new W.Control() } }) + { + var roundtrip = message.Descriptor.Parser.ParseFrom(message.ToByteArray()); + var envelope = (W.Serving)roundtrip.Descriptor.FindFieldByName("serving").Accessor.GetValue(roundtrip); + DataProtoMapper.DecodeServing(envelope).ShouldBe(serving); + } + } + + [Fact] + public void Response_identity_support_is_explicit_and_defaults_to_false_for_older_peers() + { + var legacy = new W.CapabilitiesResponse(); + legacy.ResponseServingIdentity.ShouldBeFalse(); + var decoded = W.CapabilitiesResponse.Parser.ParseFrom(new W.CapabilitiesResponse { ResponseServingIdentity = true }.ToByteArray()); + decoded.ResponseServingIdentity.ShouldBeTrue(); + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataConfigurationTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataConfigurationTests.cs index e0474f0b7..05a74094c 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataConfigurationTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataConfigurationTests.cs @@ -11,6 +11,16 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests.DataConnections; [Trait("Phase", "P02")] public sealed class GrpcDataConfigurationTests { + [Theory] + [InlineData("secret:data/Key")] + [InlineData("secret:data/KEY")] + public void Secret_references_reject_distinct_spellings_that_alias_one_local_store_name(string reference) + { + var draft = GrpcDataMappingValidationTests.ValidDraft(); + draft.DataConnections[0].SecretReference = reference; + DataConnectionValidator.Validate(draft).ShouldContain(error => error.Code == "DataConnectionSecretReferenceInvalid"); + } + [Fact] public void Defaults_are_disabled_and_secrets_are_references() { diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataSchemaModelTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataSchemaModelTests.cs index 19fbcde88..b0b5ade44 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataSchemaModelTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataSchemaModelTests.cs @@ -1,6 +1,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Metadata; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; @@ -19,8 +20,9 @@ public sealed class GrpcDataSchemaModelTests using var db = new OtOpcUaConfigDbContext(new DbContextOptionsBuilder() .UseSqlServer("Server=127.0.0.1,1;Database=design;Integrated Security=true;TrustServerCertificate=true").Options); var migrations = db.Database.GetMigrations().ToArray(); - migrations[^1].ShouldEndWith("_AddGrpcDataConnections"); - var rollback = db.GetService().GenerateScript(migrations[^1], migrations[^2]); + var index = Array.FindIndex(migrations, x => x.EndsWith("_AddGrpcDataConnections", StringComparison.Ordinal)); + index.ShouldBeGreaterThan(0); + var rollback = db.GetService().GenerateScript(migrations[index], migrations[index - 1]); rollback.ShouldNotContain("ALTER COLUMN [ScopeKind]"); } @@ -41,4 +43,31 @@ public sealed class GrpcDataSchemaModelTests .GetMaxLength().GetValueOrDefault().ShouldBeGreaterThanOrEqualTo(nameof(NodeAclScopeKind.RemoteNamespaceMapping).Length); db.Database.HasPendingModelChanges().ShouldBeFalse(); } + [Fact] + public void Scope_state_has_singleton_seed_concurrency_and_reversible_migration() + { + using var db = new OtOpcUaConfigDbContext(new DbContextOptionsBuilder() + .UseSqlServer("Server=127.0.0.1,1;Database=design;Integrated Security=true;TrustServerCertificate=true").Options); + var entity = db.GetService().Model.FindEntityType(typeof(DataConnectionScopeState)).ShouldNotBeNull(); + entity.FindPrimaryKey().ShouldNotBeNull().Properties.Single().Name.ShouldBe(nameof(DataConnectionScopeState.Id)); + var rowVersion = entity.FindProperty(nameof(DataConnectionScopeState.RowVersion)).ShouldNotBeNull(); + rowVersion.IsConcurrencyToken.ShouldBeTrue(); + rowVersion.ValueGenerated.ShouldBe(Microsoft.EntityFrameworkCore.Metadata.ValueGenerated.OnAddOrUpdate); + var seed = entity.GetSeedData().ShouldHaveSingleItem(); + seed[nameof(DataConnectionScopeState.Id)].ShouldBe(1); + seed[nameof(DataConnectionScopeState.ScopeVersion)].ShouldBe(0L); + var migrations = db.Database.GetMigrations().ToArray(); + var index = Array.FindIndex(migrations, x => x.EndsWith("_AddDataConnectionScopeState", StringComparison.Ordinal)); + index.ShouldBeGreaterThan(0); + var migrator = db.GetService(); + var up = migrator.GenerateScript(migrations[index - 1], migrations[index]); + up.ShouldContain("CREATE TABLE [DataConnectionScopeState]"); + up.ShouldContain("[RowVersion] rowversion NOT NULL"); + up.ShouldContain("CHECK ([Id] = 1 AND [ScopeVersion] >= 0)"); + up.ShouldContain("INSERT INTO [DataConnectionScopeState]"); + up.ShouldContain("VALUES (1, NULL, CAST(0 AS bigint))"); + var down = migrator.GenerateScript(migrations[index], migrations[index - 1]); + down.ShouldContain("DROP TABLE [DataConnectionScopeState]"); + down.ShouldNotContain("DROP TABLE [DataConnection]"); + } } diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataScopeRevisionTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataScopeRevisionTests.cs new file mode 100644 index 000000000..d4305d01d --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataScopeRevisionTests.cs @@ -0,0 +1,36 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Validation; + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Phase", "P07")] +public sealed class GrpcDataScopeRevisionTests +{ + [Fact] + public void Revision_is_monotonic_for_change_reversion_and_empty_scope_but_stable_for_noop() + { + DataConnection Connection(string reference) => new() { Enabled = true, ClusterId = "Cluster", DataConnectionId = "conn", ConsumerNodeIds = ["NODE"], SecretReference = reference }; + var first = DataConnectionScopeRevision.Advance(0, null, [Connection("key-a")]); + first.Version.ShouldBe(1); + var same = DataConnectionScopeRevision.Advance(first.Version, first.Fingerprint, [Connection("key-a")]); + same.Version.ShouldBe(first.Version); + var second = DataConnectionScopeRevision.Advance(same.Version, same.Fingerprint, [Connection("key-b")]); + second.Version.ShouldBe(2); + var reverted = DataConnectionScopeRevision.Advance(second.Version, second.Fingerprint, [Connection("key-a")]); + reverted.Version.ShouldBe(3); + DataConnectionScopeRevision.Advance(reverted.Version, reverted.Fingerprint, []).Version.ShouldBe(4); + } + + [Fact] + public void Fingerprint_is_case_insensitive_for_identifiers_but_secret_names_are_case_sensitive() + { + var a = new DataConnection { Enabled = true, ClusterId = "Cluster", DataConnectionId = "Link", ConsumerNodeIds = ["NodeB", "NodeA"], SecretReference = "Key" }; + var b = new DataConnection { Enabled = true, ClusterId = "cluster", DataConnectionId = "link", ConsumerNodeIds = ["nodea", "nodeb"], SecretReference = "Key" }; + var first = DataConnectionScopeRevision.Advance(0, null, [a]); + DataConnectionScopeRevision.Advance(first.Version, first.Fingerprint, [b]).Version.ShouldBe(first.Version); + b.SecretReference = "key"; + DataConnectionScopeRevision.Advance(first.Version, first.Fingerprint, [b]).Version.ShouldBe(first.Version + 1); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/DataConnections/GrpcDataScopeArtifactTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/DataConnections/GrpcDataScopeArtifactTests.cs new file mode 100644 index 000000000..26f8a0ae0 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/DataConnections/GrpcDataScopeArtifactTests.cs @@ -0,0 +1,23 @@ +using System.IO.Compression; +using System.Text.Json; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Configuration.Validation; +using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations; + +namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Phase", "P07")] +public sealed class GrpcDataScopeArtifactTests +{ + [Fact] + public void Empty_scope_artifact_carries_its_authoritative_revision() + { + var artifact = ConfigComposer.Compose(new DraftSnapshot { GenerationId = 0, ClusterId = "", DataConnectionScopeVersion = 42 }); + using var input = new MemoryStream(artifact.Blob); + using var gzip = new GZipStream(input, CompressionMode.Decompress); + using var json = JsonDocument.Parse(gzip); + json.RootElement.GetProperty("DataConnectionScopeVersion").GetInt64().ShouldBe(42); + json.RootElement.GetProperty("DataConnections").GetArrayLength().ShouldBe(0); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/DataConnections/GrpcDataScopeSealingTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/DataConnections/GrpcDataScopeSealingTests.cs new file mode 100644 index 000000000..9b34fc378 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/DataConnections/GrpcDataScopeSealingTests.cs @@ -0,0 +1,90 @@ +using System.IO.Compression; +using System.Text.Json; +using Akka.Actor; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Microsoft.EntityFrameworkCore.Storage; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations; +using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")] +public sealed class GrpcDataScopeSealingTests : ControlPlaneActorTestBase +{ + [Fact] + public void Failed_save_does_not_dispatch_or_consume_version_and_retry_seals_matching_artifact() + { + var root = new InMemoryDatabaseRoot(); var name = Guid.NewGuid().ToString("N"); + var fault = new FailFirstSave(); var factory = new Factory(name, root, fault); + var coordinator = CreateTestProbe(); + var actor = Sys.ActorOf(AdminOperationsActor.Props(factory, coordinator.Ref, Array.Empty())); + actor.Tell(new StartDeployment("test", CorrelationId.NewId())); + var failed = ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + failed.Outcome.ShouldBe(StartDeploymentOutcome.Rejected); + coordinator.ExpectNoMsg(TimeSpan.FromMilliseconds(100), TestContext.Current.CancellationToken); + using (var db = factory.CreateDbContext()) + { + db.Deployments.Count().ShouldBe(0); + db.DataConnectionScopeStates.Count().ShouldBe(0); + } + actor.Tell(new StartDeployment("test", CorrelationId.NewId())); + var accepted = ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + accepted.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, accepted.Message); + coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + using var verify = factory.CreateDbContext(); + var state = verify.DataConnectionScopeStates.Single(); + state.ScopeVersion.ShouldBe(1); + var deployment = verify.Deployments.Single(); + using var stream = new GZipStream(new MemoryStream(deployment.ArtifactBlob), CompressionMode.Decompress); + using var json = JsonDocument.Parse(stream); + json.RootElement.GetProperty("DataConnectionScopeVersion").GetInt64().ShouldBe(state.ScopeVersion); + deployment.Status.ShouldBe(DeploymentStatus.Dispatching); + } + [Fact] + public void Unchanged_empty_scope_reseals_same_version_and_hash() + { + var factory = NewInMemoryDbFactory(); var coordinator = CreateTestProbe(); + var actor = Sys.ActorOf(AdminOperationsActor.Props(factory, coordinator.Ref, Array.Empty())); + actor.Tell(new StartDeployment("test", CorrelationId.NewId())); + var first = ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + first.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, first.Message); + coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + string firstHash; + using (var db = factory.CreateDbContext()) + { + db.DataConnectionScopeStates.Single().ScopeVersion.ShouldBe(1); + var deployment = db.Deployments.Single(); firstHash = deployment.RevisionHash; + deployment.Status = DeploymentStatus.Sealed; db.SaveChanges(); + } + actor.Tell(new StartDeployment("test", CorrelationId.NewId())); + var second = ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + second.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, second.Message); + coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + using var verify = factory.CreateDbContext(); + verify.DataConnectionScopeStates.Single().ScopeVersion.ShouldBe(1); + verify.Deployments.Select(x => x.RevisionHash).ToArray().ShouldAllBe(x => x == firstHash); + } + private sealed class FailFirstSave : SaveChangesInterceptor + { + private int _failed; + public override ValueTask> SavingChangesAsync(DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) + { + if (Interlocked.Exchange(ref _failed, 1) == 0) throw new InvalidOperationException("injected failure"); + return base.SavingChangesAsync(eventData, result, cancellationToken); + } + } + private sealed class Factory(string name, InMemoryDatabaseRoot root, IInterceptor interceptor) : IDbContextFactory + { + public OtOpcUaConfigDbContext CreateDbContext() => new(new DbContextOptionsBuilder() + .UseInMemoryDatabase(name, root).AddInterceptors(interceptor).Options); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataBundleLifecycleTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataBundleLifecycleTests.cs new file mode 100644 index 000000000..3b1d776ad --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataBundleLifecycleTests.cs @@ -0,0 +1,59 @@ +using System.Text.Json; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; +using static ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections.GrpcDataSecretProvisioningTests; + +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Phase", "P07")] +public sealed class GrpcDataBundleLifecycleTests +{ + [Fact] + public async Task Missing_file_is_not_revocation_and_restarted_loader_replays_completed_bundle() + { + var ct = TestContext.Current.CancellationToken; var directory = Directory.CreateTempSubdirectory("data-bundle-"); + try + { + var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); + var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); + var trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "pair", "node"); + await new DataConnectionScopeActivator(p, trust).SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); + var credentials = Path.Combine(directory.FullName, "credentials.json"); var trustFile = Path.Combine(directory.FullName, "trust.json"); + await File.WriteAllTextAsync(credentials, JsonSerializer.Serialize(new DataConnectionCredentialBundle("pair", "node", 1, [new("c", "secret:data/key", "bearer", false)], 1)), ct); + await File.WriteAllTextAsync(trustFile, JsonSerializer.Serialize(new DataConnectionTrustBundle("pair", "node", 1, [new("c", 1, [])])), ct); + var loader = new DataConnectionBundleLoader(p, trust, "pair", "node"); + var first = await loader.ApplyFilesAsync(credentials, trustFile, ct); + first.CredentialsLoaded.ShouldBeTrue(); first.TrustLoaded.ShouldBeTrue(); + var restarted = new DataConnectionBundleLoader(p, trust, "PAIR", "NODE"); + var replay = await restarted.ApplyFilesAsync(credentials, trustFile, ct); + replay.CredentialsLoaded.ShouldBeTrue(); replay.TrustLoaded.ShouldBeTrue(); + File.Delete(credentials); + var absent = await restarted.ApplyFilesAsync(credentials, trustFile, ct); + absent.CredentialsLoaded.ShouldBeFalse(); + (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct))!.Value.ShouldBe("bearer"); + } + finally { directory.Delete(true); } + } + [Fact] + public async Task Invalid_trust_batch_is_not_partially_applied_and_transient_failure_retries() + { + var ct = TestContext.Current.CancellationToken; var directory = Directory.CreateTempSubdirectory("data-bundle-"); + try + { + var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); + var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); + var trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "pair", "node"); + await new DataConnectionScopeActivator(p, trust).SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); + var path = Path.Combine(directory.FullName, "trust.json"); var loader = new DataConnectionBundleLoader(p, trust, "pair", "node"); + await File.WriteAllTextAsync(path, JsonSerializer.Serialize(new DataConnectionTrustBundle("pair", "node", 1, [new("c", 1, []), new("unauthorized", 1, [])])), ct); + (await loader.ApplyFilesAsync(null, path, ct)).TrustLoaded.ShouldBeFalse(); + await trust.SetAsync("c", 1, [], 1, ct); // failed batch did not commit its first entry + await File.WriteAllTextAsync(path, JsonSerializer.Serialize(new DataConnectionTrustBundle("wrong", "node", 1, [new("c", 2, [])])), ct); + (await loader.ApplyFilesAsync(null, path, ct)).TrustLoaded.ShouldBeFalse(); + await File.WriteAllTextAsync(path, JsonSerializer.Serialize(new DataConnectionTrustBundle("pair", "node", 1, [new("c", 2, [])])), ct); + (await loader.ApplyFilesAsync(null, path, ct)).TrustLoaded.ShouldBeTrue(); + } + finally { directory.Delete(true); } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataCredentialRetirementTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataCredentialRetirementTests.cs new file mode 100644 index 000000000..9b65366a7 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataCredentialRetirementTests.cs @@ -0,0 +1,245 @@ +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using Microsoft.Extensions.DependencyInjection; +using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime; +using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config; +using ZB.MOM.WW.Secrets.Abstractions; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; +using static ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections.GrpcDataSecretProvisioningTests; + +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; + +[Trait("Feature", "GrpcData")] +[Trait("Phase", "P07")] +public class GrpcDataCredentialRetirementTests +{ + [Fact] + public async Task Removal_persists_scope_and_stale_bundle_cannot_resurrect_after_restart() + { + var ct = TestContext.Current.CancellationToken; + var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); + var provisioner = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "cluster", "node"); + await provisioner.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); + var bundle = new DataConnectionCredentialBundle("cluster", "node", 1, [new("c", "secret:data/key", "value", false)], ScopeVersion: 1); + await provisioner.ApplyAsync(bundle, ct); + await provisioner.SetScopeAsync(2, new Dictionary(), ct); + var restarted = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "cluster", "node"); + await Should.ThrowAsync(() => restarted.ApplyAsync(bundle, ct)); + (await new DataConnectionCredentialResolver(store, cipher, "cluster", "node").ResolveAsync("c", ct)).ShouldBeNull(); + } + [Fact] + public async Task Shared_reference_is_retained_until_last_scope_is_removed() + { + var ct = TestContext.Current.CancellationToken; + var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); + var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); + await p.SetScopeAsync(1, new Dictionary { ["a"] = "secret:data/key", ["b"] = "secret:data/key" }, ct); + await p.ApplyAsync(new("pair", "node", 1, [new("a", "secret:data/key", "secret", false)], ScopeVersion: 1), ct); + await p.SetScopeAsync(2, new Dictionary { ["b"] = "secret:data/key" }, ct); + (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("b", ct))!.Value.ShouldBe("secret"); + await p.SetScopeAsync(3, new Dictionary(), ct); + store.Rows.ContainsKey("data/key").ShouldBeFalse(); + await Should.ThrowAsync(() => p.SetScopeAsync(2, new Dictionary(), ct)); + } + [Fact] + public async Task Reintroducing_scope_does_not_reactivate_a_previously_retired_reference() + { + var ct = TestContext.Current.CancellationToken; + var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); + var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); + var scope = new Dictionary { ["c"] = "secret:data/key" }; + await p.SetScopeAsync(1, scope, ct); + var old = new DataConnectionCredentialBundle("pair", "node", 1, [new("c", "secret:data/key", "old", false)], ScopeVersion: 1); + await p.ApplyAsync(old, ct); + var staleRow = store.Rows["data/key"]; + await p.SetScopeAsync(2, new Dictionary(), ct); + // A stale replicated row or failed external deletion must not bypass the tombstone. + store.Rows["data/key"] = staleRow; + await p.SetScopeAsync(3, scope, ct); + await p.SetScopeAsync(3, scope, ct); // unchanged applied artifact can be replayed on restart + await Should.ThrowAsync(() => p.SetScopeAsync(3, new Dictionary(), ct)); + (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct)).ShouldBeNull(); + await Should.ThrowAsync(() => p.ApplyAsync(old, ct)); + await p.ApplyAsync(new("pair", "node", 2, [new("c", "secret:data/key", "new", false)], ScopeVersion: 3), ct); + (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct))!.Value.ShouldBe("new"); + } + [Fact] + public async Task Failed_deletion_is_retried_after_restart_with_same_scope_version() + { + var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); + var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); + await p.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); + await p.ApplyAsync(new("pair", "node", 1, [new("c", "secret:data/key", "secret", false)], ScopeVersion: 1), ct); + store.FailDelete = true; + await Should.ThrowAsync(() => p.SetScopeAsync(2, new Dictionary(), ct)); + (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct)).ShouldBeNull(); + store.FailDelete = false; + var restarted = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); + await restarted.SetScopeAsync(2, new Dictionary(), ct); + store.Rows.ContainsKey("data/key").ShouldBeFalse(); + } + [Fact] + public void A_throwing_retirement_observer_does_not_prevent_other_observers_from_draining() + { + var changes = new DataConnectionSecretChangeHandler(); var observed = new List(); + changes.ConnectionChanged += _ => throw new InvalidOperationException("broken observer"); + changes.ConnectionChanged += observed.Add; + Should.Throw(() => changes.NotifyConnectionChanged("c")); + observed.ShouldBe(["c"]); + } + [Fact] + public async Task Failed_scope_notification_is_retried_on_same_version() + { + var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); + var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); + await p.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); + var calls = 0; Action observer = _ => { calls++; if (calls == 1) throw new InvalidOperationException(); }; + changes.ConnectionChanged += observer; + await Should.ThrowAsync(() => p.SetScopeAsync(2, new Dictionary(), ct)); + await p.SetScopeAsync(2, new Dictionary(), ct); + calls.ShouldBe(2); + } + [Fact] + public async Task Scope_generation_allows_reference_churn_without_stale_bundle_resurrection() + { + var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); + var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "pair", "node"); + var old = new DataConnectionCredentialBundle("pair", "node", 1, [new("c", "secret:data/key", "old", false)], ScopeVersion: 1); + await p.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); + await p.ApplyAsync(old, ct); + for (var i = 0; i < DataConnectionSecretProvisioner.MaximumReferences + 1; i++) + { + var generation = 2L + i; var reference = "secret:data/churn" + i; + await p.SetScopeAsync(generation, new Dictionary { ["c"] = reference }, ct); + await p.ApplyAsync(new("pair", "node", 1, [new("c", reference, "value", false)], ScopeVersion: generation), ct); + } + var latest = 3L + DataConnectionSecretProvisioner.MaximumReferences; + await p.SetScopeAsync(latest, new Dictionary { ["c"] = "secret:data/key" }, ct); + p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "pair", "node"); + await Should.ThrowAsync(() => p.ApplyAsync(old with { Version = 999 }, ct)); + await p.ApplyAsync(new("pair", "node", 1, [new("c", "secret:data/key", "new", false)], ScopeVersion: latest), ct); + (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct))!.Value.ShouldBe("new"); + } + [Fact] + public async Task Scope_removal_between_eligibility_and_observation_does_not_leak_id() + { + var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); + var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); + await p.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); + var trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "pair", "node"); + await trust.ApplyScopeAsync(1, ["c"], ct); + using var provider = new DataConnectionSecurityProvider(new DataConnectionCredentialResolver(store, cipher, "pair", "node"), trust, changes); + var eligible = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var resume = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + provider.AfterEligibilityForTest = async () => { eligible.SetResult(); await resume.Task; }; + var resolving = provider.ResolveAsync("c", new Uri("https://example.test"), ct).AsTask(); + await eligible.Task.WaitAsync(ct); + await p.SetScopeAsync(2, new Dictionary(), ct); + resume.SetResult(); + (await resolving).ShouldBeNull(); + provider.ObservedCountForTest.ShouldBe(0); + } + [Fact] + public async Task Mixed_case_scope_and_bundle_reuse_one_durable_generation_floor_after_restart() + { + var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); + var changes = new DataConnectionSecretChangeHandler(); + var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "Cluster", "Node"); + var central = ZB.MOM.WW.OtOpcUa.Configuration.Validation.DataConnectionScopeRevision.Advance(0, null, + [new ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnection { Enabled = true, ClusterId = "Cluster", DataConnectionId = "Link", ConsumerNodeIds = ["Node"], SecretReference = "secret:data/key" }]); + var same = ZB.MOM.WW.OtOpcUa.Configuration.Validation.DataConnectionScopeRevision.Advance(central.Version, central.Fingerprint, + [new ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnection { Enabled = true, ClusterId = "cluster", DataConnectionId = "link", ConsumerNodeIds = ["node"], SecretReference = "secret:data/key" }]); + same.Version.ShouldBe(central.Version); + await p.SetScopeAsync(central.Version, new Dictionary { ["Link"] = "secret:data/key" }, ct); + await p.ApplyAsync(new("cluster", "node", 1, [new("LINK", "secret:data/key", "token", false)], ScopeVersion: 1), ct); + var restarted = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "CLUSTER", "NODE"); + await restarted.SetScopeAsync(1, new Dictionary { ["link"] = "secret:data/key" }, ct); + (await new DataConnectionCredentialResolver(store, cipher, "cluster", "NODE").ResolveAsync("lInK", ct))!.Value.ShouldBe("token"); + await restarted.SetScopeAsync(2, new Dictionary(), ct); + await Should.ThrowAsync(() => p.SetScopeAsync(1, new Dictionary { ["Link"] = "secret:data/key" }, ct)); + await Should.ThrowAsync(() => restarted.ApplyAsync(new("cluster", "node", 999, [new("LINK", "secret:data/other", "token", false)], ScopeVersion: 1), ct)); + } + + [Fact] + public async Task Scope_rejects_duplicate_connection_ids_that_differ_only_by_case() + { + var ct = TestContext.Current.CancellationToken; var p = new DataConnectionSecretProvisioner(new MemoryStore(), new TestCipher(), new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "cluster", "node"); + await Should.ThrowAsync(() => p.SetScopeAsync(1, new Dictionary { ["Link"] = "secret:data/a", ["link"] = "secret:data/b" }, ct)); + } + [Fact] + public async Task Invalidator_attempts_galaxy_and_data_even_when_inner_throws() + { + var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); + var directory = new GalaxyAckIdentityDirectory(store, TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(2)); + (await directory.RefreshAsync(ct)).ShouldBeTrue(); + const string key = "0a1b2c3d4e5f6071"; + directory.GetPresence(key).ShouldBe(GalaxyAckIdentityPresence.Absent); + var changes = new DataConnectionSecretChangeHandler(); var called = 0; + changes.SecretChanged += _ => called++; + var invalidator = new SecretChangeSignallingInvalidator(new ThrowingInvalidator(), directory, changes); + Should.Throw(() => invalidator.Invalidate(new SecretName(GalaxyAckIdentitySecrets.UserSecretName(key)))); + called.ShouldBe(1); + directory.GetPresence(key).ShouldBe(GalaxyAckIdentityPresence.Unknown); + } + + [Fact] + public void Registration_composes_the_lightweight_handler_without_replacing_inner() + { + var services = new ServiceCollection(); var inner = new CountingInvalidator(); + services.AddSingleton(inner); + services.AddSingleton(); + SecretsRegistration.DecorateCacheInvalidator(services); + using var provider = services.BuildServiceProvider(); + var changed = 0; provider.GetRequiredService().SecretChanged += _ => changed++; + provider.GetRequiredService().Invalidate(new SecretName("data/key")); + inner.Count.ShouldBe(1); changed.ShouldBe(1); + } + [Fact] + public async Task Composed_invalidation_retires_only_connections_that_reference_the_changed_secret() + { + var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); + var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); + var trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "pair", "node"); + using var security = new DataConnectionSecurityProvider(new DataConnectionCredentialResolver(store, cipher, "pair", "node"), trust, changes); + await using var runtime = new DataConnectionDeploymentRuntime("node", "pair", security, new DataConnectionScopeActivator(p, trust), 4); + DataConnection Definition(string id, string reference) => new() { DataConnectionId = id, ClusterId = "pair", Revision = 1, Enabled = true, + ConsumerNodeIds = ["node"], TargetMode = DataTargetMode.Node, ExpectedClusterId = "target", ExpectedNodeId = "remote", + Endpoints = ["https://remote.example:8443"], SecretReference = reference, SecretScopeClusterId = "pair", AllowedOperations = DataOperations.Read }; + runtime.Apply(new DataConnectionDeploymentSnapshot(1, "rev", [Definition("a", "secret:data/a"), Definition("shared", "secret:data/a"), Definition("b", "secret:data/b")])); + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ct); deadline.CancelAfter(TimeSpan.FromSeconds(5)); + while (!runtime.CurrentScopeReady) await Task.Delay(10, deadline.Token); + await p.ApplyAsync(new("pair", "node", 1, [new("a", "secret:data/a", "first", false), new("b", "secret:data/b", "second", false)], 1), ct); + store.Rows.ContainsKey("data/a").ShouldBeTrue(); + store.Rows.ContainsKey("data/b").ShouldBeTrue(); + using var key = RSA.Create(2048); var request = new CertificateRequest("CN=ca", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); + using var ca = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); + await trust.SetBundleAsync([("a", 1, [ca]), ("shared", 1, [ca]), ("b", 1, [ca])], 1, ct); + DataConnectionDeploymentLease? a = null, shared = null, b = null; + while (!(runtime.TryAcquire("a", out a) && runtime.TryAcquire("shared", out shared) && runtime.TryAcquire("b", out b))) + { + a?.Dispose(); shared?.Dispose(); b?.Dispose(); a = null; shared = null; b = null; + await Task.Delay(10, deadline.Token); + } + using (a!) using (shared!) using (b!) + { + var invalidator = new SecretChangeSignallingInvalidator(new NoopInvalidator(), null, changes); + invalidator.Invalidate(new SecretName("otopcua/apikeys/unrelated")); + a!.CancellationToken.IsCancellationRequested.ShouldBeFalse(); + shared!.CancellationToken.IsCancellationRequested.ShouldBeFalse(); + b!.CancellationToken.IsCancellationRequested.ShouldBeFalse(); + invalidator.Invalidate(new SecretName("data/a")); + a.CancellationToken.IsCancellationRequested.ShouldBeTrue(); + shared.CancellationToken.IsCancellationRequested.ShouldBeTrue(); + b.CancellationToken.IsCancellationRequested.ShouldBeFalse(); + } + } + + private sealed class ThrowingInvalidator : ISecretCacheInvalidator { public void Invalidate(SecretName name) => throw new InvalidOperationException("failed"); } + private sealed class CountingInvalidator : ISecretCacheInvalidator { public int Count; public void Invalidate(SecretName name) => Count++; } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataIngressAuthTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataIngressAuthTests.cs new file mode 100644 index 000000000..5f686b94c --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataIngressAuthTests.cs @@ -0,0 +1,51 @@ +using Microsoft.Extensions.Options; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; +using ZB.MOM.WW.OtOpcUa.Host.OpcUa; + +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")] +public sealed class GrpcDataIngressAuthTests +{ + [Fact] + public void Authentication_uses_the_current_snapshot_and_original_key_material() + { + var (bearer, id, hash) = ApiKeySecret.Generate("pepper"); + var authority = new DataPlaneAuthorityState(); + var key = new ApiKey { ApiKeyId = id, Name = "test", Principal = "peer", SecretHash = hash, Enabled = true }; + authority.Apply("cluster", "v1", [key], [], new Dictionary>()); + var auth = new DataConnectionAuthenticator(authority, + Options.Create(new ApiKeyOptions { Pepper = "pepper" }), TimeProvider.System); + var context = auth.Authenticate(bearer); + context.PrincipalId.ShouldBe("peer"); + context.ApiKeyId.ShouldBe(id); + context.CredentialVersion.ShouldBe(DataCallerIdentity.CredentialVersionFor(key)); + auth.IsCurrent(context).ShouldBeTrue(); + authority.Apply("cluster", "v2", [], [], new Dictionary>()); + auth.IsCurrent(context).ShouldBeFalse(); + Should.Throw(() => auth.Authenticate(bearer)); + } + + [Fact] + public void Missing_pepper_missing_authority_and_forged_or_expired_keys_deny() + { + var (bearer, id, hash) = ApiKeySecret.Generate("pepper"); + var authority = new DataPlaneAuthorityState(); + var auth = new DataConnectionAuthenticator(authority, + Options.Create(new ApiKeyOptions { Pepper = "pepper" }), TimeProvider.System); + Should.Throw(() => auth.Authenticate(bearer)); + var expired = new ApiKey { ApiKeyId = id, Name = "test", Principal = "peer", SecretHash = hash, + Enabled = true, ExpiresUtc = DateTime.UtcNow.AddMinutes(-1) }; + authority.Apply("cluster", "v1", [expired], [], new Dictionary>()); + Should.Throw(() => auth.Authenticate(bearer)); + expired.ExpiresUtc = null; + authority.Apply("cluster", "v2", [expired], [], new Dictionary>()); + Should.Throw(() => auth.Authenticate("not-a-key")); + Should.Throw(() => new DataConnectionAuthenticator(authority, + Options.Create(new ApiKeyOptions()), TimeProvider.System).Authenticate(bearer)); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataListenerTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataListenerTests.cs new file mode 100644 index 000000000..86d26481d --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataListenerTests.cs @@ -0,0 +1,157 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Options; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; +using ZB.MOM.WW.OtOpcUa.Host.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; + +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")] +public sealed class GrpcDataListenerTests +{ + [Fact(Timeout = 15000)] + public async Task Long_lived_streams_have_a_separate_bounded_lane_from_unary_work() + { + var (bearer, id, hash) = ApiKeySecret.Generate("pepper"); + var authority = new DataPlaneAuthorityState(); + authority.Apply("cluster", "one", [new ApiKey { ApiKeyId = id, Name = "test", Principal = "peer", SecretHash = hash, Enabled = true }], + [], new Dictionary>()); + var auth = new DataConnectionAuthenticator(authority, Options.Create(new ApiKeyOptions { Pepper = "pepper" }), TimeProvider.System); + var options = new DataConnectionOptions { Enabled = true, ListenPort = 9443, CertificatePath = "server.pem", + AllowedHosts = ["source.local"], MaxConcurrentCalls = 1, MaxStreams = 1 }; + var streamEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var unaryEntered = false; + var middleware = new DataConnectionAdmissionMiddleware(async http => + { + if (http.Request.Path.Value!.EndsWith("/Subscribe", StringComparison.Ordinal)) + { streamEntered.TrySetResult(); await release.Task.WaitAsync(TestContext.Current.CancellationToken); } + else unaryEntered = true; + }, Options.Create(options)); + DefaultHttpContext Request(string method) + { + var http = At(9443, DataConnectionEndpoints.ServicePrefix + method); + http.Request.Headers.Authorization = "Bearer " + bearer; + http.Request.Headers["x-data-target-mode"] = "Node"; + http.Request.Headers["x-data-consistency"] = "Primary"; + http.Request.Headers["x-data-cluster-id"] = "cluster"; + http.Request.Headers["x-data-node-id"] = "node"; + return http; + } + var stream = middleware.InvokeAsync(Request("Subscribe"), auth); + try + { + await streamEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var extraStream = Request("Subscribe"); + await middleware.InvokeAsync(extraStream, auth); + extraStream.Response.Headers["grpc-status"].ToString().ShouldBe("8"); + await middleware.InvokeAsync(Request("Read"), auth); + unaryEntered.ShouldBeTrue("occupied stream capacity must preserve unary read/write/browse admission"); + } + finally { release.TrySetResult(); await stream; } + } + + [Fact] + public async Task Mesh_calls_on_data_port_and_unauthenticated_data_calls_never_enter_body_parsing() + { + var options = new DataConnectionOptions { Enabled = true, ListenPort = 9443, + CertificatePath = "server.pem", AllowedHosts = ["source.local"] }; + var parsed = 0; + var middleware = new DataConnectionAdmissionMiddleware(_ => { parsed++; return Task.CompletedTask; }, Options.Create(options)); + var auth = new DataConnectionAuthenticator(new DataPlaneAuthorityState(), Options.Create(new ApiKeyOptions()), TimeProvider.System); + var mesh = At(9443, "/mesh_transport.v1.NodeCommandService/Execute"); + await middleware.InvokeAsync(mesh, auth); + mesh.Response.Headers["grpc-status"].ToString().ShouldBe("7"); + var data = At(9443, DataConnectionEndpoints.ServicePrefix + "Read"); + await middleware.InvokeAsync(data, auth); + data.Response.Headers["grpc-status"].ToString().ShouldBe("16"); + parsed.ShouldBe(0); + } + + [Fact(Timeout = 15000)] + public async Task Unary_lifetime_also_bounds_preparse_work_when_client_supplies_no_deadline() + { + var (bearer, id, hash) = ApiKeySecret.Generate("pepper"); + var authority = new DataPlaneAuthorityState(); + authority.Apply("cluster", "one", [new ApiKey { ApiKeyId = id, Name = "test", Principal = "peer", SecretHash = hash, Enabled = true }], + [], new Dictionary>()); + var auth = new DataConnectionAuthenticator(authority, Options.Create(new ApiKeyOptions { Pepper = "pepper" }), TimeProvider.System); + var options = new DataConnectionOptions { Enabled = true, ListenPort = 9443, + CertificatePath = "server.pem", AllowedHosts = ["source.local"], UnaryTimeout = TimeSpan.FromMilliseconds(50) }; + using var cleanup = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var middleware = new DataConnectionAdmissionMiddleware(async http => + { entered.TrySetResult(); await Task.Delay(Timeout.InfiniteTimeSpan, http.RequestAborted); }, Options.Create(options)); + var context = At(9443, DataConnectionEndpoints.ServicePrefix + "Read"); + context.RequestAborted = cleanup.Token; + context.Request.Headers.Authorization = "Bearer " + bearer; + context.Request.Headers["x-data-target-mode"] = "Node"; + context.Request.Headers["x-data-consistency"] = "Primary"; + context.Request.Headers["x-data-cluster-id"] = "cluster"; + context.Request.Headers["x-data-node-id"] = "node"; + var processing = middleware.InvokeAsync(context, auth); + bool stopped; + try + { + await entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + stopped = await Task.WhenAny(processing, Task.Delay(TimeSpan.FromMilliseconds(500), TestContext.Current.CancellationToken)) == processing; + } + finally + { + await cleanup.CancelAsync(); + try { await processing; } catch (OperationCanceledException) { } + } + stopped.ShouldBeTrue("the server's own unary budget must cover pre-parse HTTP work"); + } + [Fact] + public void Disabled_surface_has_no_listener_or_method_admission() + { + var options = new DataConnectionOptions(); + DataConnectionOptionsValidator.Validate(options, development: false).ShouldBeEmpty(); + DataConnectionEndpoints.IsDataRequest(At(9443, "/data_connection.v1.DataConnectionService/Read"), options).ShouldBeFalse(); + } + + [Fact] + public void Cleartext_requires_explicit_development_and_literal_loopback() + { + var options = new DataConnectionOptions { Enabled = true, ListenPort = 9443, + ListenAddress = "127.0.0.1", AllowDevelopmentCleartext = true, AllowedHosts = ["localhost"] }; + DataConnectionOptionsValidator.Validate(options, development: true).ShouldBeEmpty(); + DataConnectionOptionsValidator.Validate(options, development: false).ShouldNotBeEmpty(); + options.ListenAddress = "0.0.0.0"; + DataConnectionOptionsValidator.Validate(options, development: true).ShouldNotBeEmpty(); + } + + [Fact] + public void Exact_rpc_host_and_actual_listener_are_required() + { + var options = new DataConnectionOptions { Enabled = true, ListenPort = 9443, + CertificatePath = "server.pem", AllowedHosts = ["source.local"] }; + var request = At(9443, "/data_connection.v1.DataConnectionService/Read"); + DataConnectionEndpoints.IsDataRequest(request, options).ShouldBeTrue(); + request.Connection.LocalPort = 8080; + request.Request.Headers["X-Forwarded-Port"] = "9443"; + DataConnectionEndpoints.IsDataRequest(request, options).ShouldBeFalse(); + request.Connection.LocalPort = 9443; + request.Request.Host = new HostString("other.local", 9443); + DataConnectionEndpoints.IsDataRequest(request, options).ShouldBeFalse(); + request.Request.Host = new HostString("source.local", 9443); + request.Request.Path += "Anything"; + DataConnectionEndpoints.IsDataRequest(request, options).ShouldBeFalse(); + } + + private static DefaultHttpContext At(int port, string path) + { + var context = new DefaultHttpContext(); + context.Connection.LocalPort = port; + context.Request.Host = new HostString("source.local", port); + context.Request.Scheme = "https"; + context.Request.Protocol = "HTTP/2"; + context.Request.Method = "POST"; + context.Request.Path = path; + return context; + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataPublicationHandoffTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataPublicationHandoffTests.cs new file mode 100644 index 000000000..4c0ef6118 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataPublicationHandoffTests.cs @@ -0,0 +1,147 @@ +using Google.Protobuf; +using Grpc.Core; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Host.Grpc; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")] +public sealed class GrpcDataPublicationHandoffTests +{ + [Fact] + public void Monotonic_unary_deadline_is_rechecked_after_validation_even_without_a_timer_callback() + { + var binder = new CaptureBinder(); + DataConnectionGrpcBinding.BindService(binder, null!); + var clock = new PublicationClock(); + var deadline = new DataConnectionUnaryLifetime(clock, TimeSpan.FromSeconds(1)); + var response = new W.CapabilitiesResponse { ProtocolMajor = 1 }; + using var registration = DataConnectionPublication.RegisterUnary(response, () => + { clock.Advance(TimeSpan.FromSeconds(2)); return true; }, 1024, deadline); + var context = new CaptureContext(); + Should.Throw(() => binder.Unary["GetCapabilities"](response, context)); + context.Handoffs.ShouldBe(0); + } + + private sealed class PublicationClock : TimeProvider + { + private long _ticks; + public override long TimestampFrequency => TimeSpan.TicksPerSecond; + public override long GetTimestamp() => _ticks; + internal void Advance(TimeSpan duration) => _ticks += duration.Ticks; + } + [Fact] + public void Registered_binding_checks_revocation_after_method_return_before_any_body_handoff() + { + var binder = new CaptureBinder(); + DataConnectionGrpcBinding.BindService(binder, null!); + var response = new W.CapabilitiesResponse { ProtocolMajor = 1 }; + var allowed = true; + using var registration = DataConnectionPublication.Register(response, () => allowed, 1024); + allowed = false; + var context = new CaptureContext(); + Should.Throw(() => binder.Unary["GetCapabilities"](response, context)); + context.Handoffs.ShouldBe(0); + } + + [Fact] + public void Registered_binding_performs_exactly_one_successful_private_buffer_handoff() + { + var binder = new CaptureBinder(); + DataConnectionGrpcBinding.BindService(binder, null!); + var response = new W.CapabilitiesResponse { ProtocolMajor = 1 }; + using var registration = DataConnectionPublication.Register(response, () => true, 1024); + var context = new CaptureContext(); + binder.Unary["GetCapabilities"](response, context); + context.Handoffs.ShouldBe(1); + W.CapabilitiesResponse.Parser.ParseFrom(context.Payload!).ProtocolMajor.ShouldBe(1); + Should.Throw(() => binder.Unary["GetCapabilities"](response, context)); + context.Handoffs.ShouldBe(1); + } + + [Fact] + public void Skipped_serializer_cleanup_and_unregistered_responses_fail_closed() + { + var binder = new CaptureBinder(); + DataConnectionGrpcBinding.BindService(binder, null!); + var response = new W.CapabilitiesResponse(); + var registration = DataConnectionPublication.Register(response, () => true, 1024); + registration.Dispose(); + var context = new CaptureContext(); + Should.Throw(() => binder.Unary["GetCapabilities"](response, context)); + Should.Throw(() => binder.Unary["GetCapabilities"](new W.CapabilitiesResponse(), context)); + context.Handoffs.ShouldBe(0); + } + + [Fact(Timeout = 15000)] + public async Task Disposal_during_a_blocked_final_guard_prevents_handoff() + { + var binder = new CaptureBinder(); + DataConnectionGrpcBinding.BindService(binder, null!); + var response = new W.CapabilitiesResponse { ProtocolMajor = 1 }; + using var entered = new ManualResetEventSlim(); + using var resume = new ManualResetEventSlim(); + using var registration = DataConnectionPublication.Register(response, () => + { + entered.Set(); + if (!resume.Wait(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)) throw new TimeoutException(); + return true; + }, 1024); + var context = new CaptureContext(); + var serialization = Task.Run(() => + { + try { binder.Unary["GetCapabilities"](response, context); return (Exception?)null; } + catch (Exception error) { return error; } + }, TestContext.Current.CancellationToken); + try + { + entered.Wait(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken).ShouldBeTrue(); + registration.Dispose(); + } + finally { resume.Set(); } + (await serialization.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeOfType(); + context.Handoffs.ShouldBe(0); + } + + [Fact] + public void Prepared_stream_delivery_requires_one_live_runtime_publication_guard() + { + var binder = new CaptureBinder(); + DataConnectionGrpcBinding.BindService(binder, null!); + W.SubscriptionFrame Frame() => new() { SubscriptionId = "s", StreamEpoch = 1, Sequence = 1, Control = new W.Control() }; + var unbound = Frame(); + using (var prepared = new PreparedDataSubscription(unbound, unbound.ToByteArray(), 1024, 1024, + () => true, TestContext.Current.CancellationToken)) + Should.Throw(() => binder.Duplex["Subscribe"](unbound, new CaptureContext())); + var valid = Frame(); + using var delivery = new PreparedDataSubscription(valid, valid.ToByteArray(), 1024, 1024, + () => true, TestContext.Current.CancellationToken); + ((IDataPreparedSubscriptionPublication)delivery).SetPublicationGuard(() => true); + Should.Throw(() => delivery.SetPublicationGuard(() => true)); + var context = new CaptureContext(); + binder.Duplex["Subscribe"](valid, context); + context.Handoffs.ShouldBe(1); + } + + private sealed class CaptureBinder : ServiceBinderBase + { + internal readonly Dictionary> Unary = []; + internal readonly Dictionary> Duplex = []; + public override void AddMethod(Method method, + UnaryServerMethod? handler) => + Unary.Add(method.Name, (response, context) => method.ResponseMarshaller.ContextualSerializer((TResponse)(object)response, context)); + public override void AddMethod(Method method, + DuplexStreamingServerMethod? handler) => + Duplex.Add(method.Name, (response, context) => method.ResponseMarshaller.ContextualSerializer((TResponse)(object)response, context)); + } + + private sealed class CaptureContext : SerializationContext + { + internal int Handoffs; + internal byte[]? Payload; + public override void Complete(byte[] payload) { Handoffs++; Payload = payload; } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataRuntimeRegistrationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataRuntimeRegistrationTests.cs new file mode 100644 index 000000000..bd2b80ed9 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataRuntimeRegistrationTests.cs @@ -0,0 +1,184 @@ +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using Akka.Actor; +using Akka.Hosting; +using ZB.MOM.WW.OtOpcUa.Commons.Interfaces; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Validation; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Runtime; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy; +using ZB.MOM.WW.Secrets.Abstractions; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.FileProviders; +using Microsoft.Extensions.Hosting; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; + +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")] +public sealed class GrpcDataRuntimeRegistrationTests +{ + [Fact] + public void Disabled_registration_requires_no_driver_or_secret_store_and_exposes_no_facade() + { + var services = new ServiceCollection(); + var options = services.AddOtOpcUaDataConnections(new ConfigurationBuilder().Build(), new Environment(), hasDriver: false); + options.Enabled.ShouldBeFalse(); + using var provider = services.BuildServiceProvider(); + provider.GetService().ShouldBeNull(); + } + + [Fact] + public void Enabled_surface_requires_the_actual_driver_role() + { + var services = new ServiceCollection(); + Should.Throw(() => services.AddOtOpcUaDataConnections(Configuration(), new Environment(), hasDriver: false)); + } + + [Fact] + public void Startup_facade_is_available_without_constructing_a_disconnected_actor_graph() + { + var services = new ServiceCollection(); + services.AddOtOpcUaDataConnections(Configuration(), new Environment(), hasDriver: true); + using var provider = services.BuildServiceProvider(); + var factory = provider.GetRequiredService(); + Should.Throw(() => factory.Create(new("peer", "key", "version", null, 1), + new(DataTargetMode.Node, "cluster", "node"))); + } + + [Fact] + public async Task Real_registered_graph_activates_scope_and_catalog_for_deferred_factory() + { + var ct = TestContext.Current.CancellationToken; + var system = ActorSystem.Create("grpc-di-" + Guid.NewGuid().ToString("N")); + try + { + var registry = new ActorRegistry(); + var services = new ServiceCollection(); + services.AddSingleton(registry); + services.AddSingleton(new LocalRole()); + services.AddSingleton(sp => new DataPlaneAuthorityState(sp.GetRequiredService())); + services.AddSingleton(sp => new RedundancyRoleView(sp.GetRequiredService())); + services.AddSingleton(sp => new TriePermissionEvaluator(sp.GetRequiredService().Tries)); + services.AddSingleton(new GrpcDataSecretProvisioningTests.MemoryStore()); + services.AddSingleton(new GrpcDataSecretProvisioningTests.TestCipher()); + services.AddSingleton(new GrpcDataSecretProvisioningTests.NoopInvalidator()); + services.AddOtOpcUaDataConnections(Configuration(), new Environment(), hasDriver: true); + await using var provider = services.BuildServiceProvider(); + var factory = provider.GetRequiredService(); + var target = new DataTarget(DataTargetMode.Node, "cluster", "node-a:4840"); + var key = new ApiKey { ApiKeyId = "key", Name = "key", Principal = "peer", SecretHash = "hash", Enabled = true }; + var catalog = provider.GetRequiredService(); + var role = provider.GetRequiredService(); + role.PublishDataServingRole(RedundancyRole.Primary, true); + var attempt = catalog.BeginAttempt("revision"); + catalog.InstallAuthority(attempt, new DataPlaneAuthorityProjection("cluster", [key], [], new Dictionary>())).ShouldBeTrue(); + var context = new DataAuthenticatedContext("peer", "key", DataCallerIdentity.CredentialVersionFor(key), null, + provider.GetRequiredService().Current.GenerationId); + Should.Throw(() => factory.Create(context, target)); // no registered host + var actor = system.ActorOf(Props.Create(() => new LocalActor())); + registry.Register(actor); + await using var connection = factory.Create(context, target); + var budget = new DataBudget(TimeSpan.FromSeconds(5), 100, 1_000_000); + (await connection.GetCapabilitiesAsync(budget, ct)).Readiness.ShouldBe(DataReadiness.Unavailable); + var snapshot = new DraftSnapshot { GenerationId = 0, ClusterId = "cluster", + ClusterNodes = [new ClusterNode { ClusterId = "cluster", NodeId = "node-a:4840", Host = "node-a", ApplicationUri = "urn:node-a", CreatedBy = "test" }] }; + catalog.Stage(attempt, snapshot, "node-a:4840").ShouldBeTrue(); + catalog.Complete(attempt, true).ShouldBeTrue(); + (await connection.GetCapabilitiesAsync(budget, ct)).Readiness.ShouldBe(DataReadiness.Unavailable); // scope not yet durable + var deployment = provider.GetRequiredService(); + deployment.Apply(new DataConnectionDeploymentSnapshot(1, "revision", [])); + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ct); + deadline.CancelAfter(TimeSpan.FromSeconds(5)); + while (!deployment.CurrentScopeReady) await Task.Delay(10, deadline.Token); + var ready = await connection.GetCapabilitiesAsync(budget, ct); + ready.Readiness.ShouldBe(DataReadiness.Ready); + ready.Serving.NodeId.ShouldBe("node-a:4840"); + ready.Serving.Incarnation.ShouldBe(catalog.Serving.Incarnation); + var composition = provider.GetRequiredService(); + composition.AcquisitionCapacity.ShouldBeSameAs(provider.GetRequiredService()); + composition.Services.Clock.ShouldBeSameAs(provider.GetRequiredService()); + } + finally { await system.Terminate().WaitAsync(ct); } + } + + [Fact] + public async Task Local_warm_standby_overrides_hot_artifact_and_withdraws_ready_import() + { + var ct = TestContext.Current.CancellationToken; var services = new ServiceCollection(); + services.AddSingleton(new LocalRole()); + services.AddSingleton(sp => new DataPlaneAuthorityState(sp.GetRequiredService())); + services.AddSingleton(sp => new RedundancyRoleView(sp.GetRequiredService())); + services.AddSingleton(new WarmRedundancySettings(OpcUaRedundancyMode.Warm)); + services.AddSingleton(new GrpcDataSecretProvisioningTests.MemoryStore()); + services.AddSingleton(new GrpcDataSecretProvisioningTests.TestCipher()); + services.AddSingleton(new GrpcDataSecretProvisioningTests.NoopInvalidator()); + services.AddOtOpcUaDataConnections(Configuration(), new Environment(), hasDriver: true); + await using var provider = services.BuildServiceProvider(); + var role = provider.GetRequiredService(); + var warm = provider.GetRequiredService(); + var owner = warm.RegisterOwner(); warm.Publish(owner, WarmRole.Active); + role.PublishDataServingRole(RedundancyRole.Primary, true); + var runtime = provider.GetRequiredService(); + var connection = new DataConnection { DataConnectionId = "link", ClusterId = "cluster", Revision = 1, Enabled = true, + ConsumerNodeIds = ["node-a:4840"], TargetMode = DataTargetMode.Node, ExpectedClusterId = "remote", ExpectedNodeId = "remote:4840", + Endpoints = ["https://remote.example:8443"], SecretReference = "secret:data/key", SecretScopeClusterId = "cluster", AllowedOperations = DataOperations.Read }; + runtime.Apply(new DataConnectionDeploymentSnapshot(1, "revision", [connection], RedundancyMode.Hot)); + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ct); deadline.CancelAfter(TimeSpan.FromSeconds(5)); + while (!runtime.CurrentScopeReady) await Task.Delay(10, deadline.Token); + await provider.GetRequiredService().ApplyAsync(new("cluster", "node-a:4840", 1, + [new("link", "secret:data/key", "bearer", false)], 1), ct); + using var key = RSA.Create(2048); + var request = new CertificateRequest("CN=ca", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); + using var ca = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); + await provider.GetRequiredService().SetAsync("link", 1, [ca], 1, ct); + DataConnectionDeploymentLease? lease = null; + while (!runtime.TryAcquire("link", out lease)) await Task.Delay(10, deadline.Token); + lease.ShouldNotBeNull(); + role.PublishDataServingRole(RedundancyRole.Secondary, false); + warm.Publish(owner, WarmRole.Standby); + runtime.TryAcquire("link", out _).ShouldBeFalse(); + Should.Throw(() => lease.GetCapabilitiesAsync(new DataBudget(TimeSpan.FromSeconds(1), 1, 1024), ct)); + lease.Dispose(); + } + + private sealed class LocalActor : ReceiveActor { } + private sealed class LocalRole : IClusterRoleInfo + { + public NodeId LocalNode => NodeId.Parse("node-a:4840"); + public IReadOnlySet LocalRoles => new HashSet { "driver", "cluster-cluster" }; + public string? ClusterRole => "cluster-cluster"; + public string? ClusterId => "cluster"; + public bool HasRole(string role) => LocalRoles.Contains(role); + public IReadOnlyList MembersWithRole(string role) => []; + public NodeId? RoleLeader(string role) => null; + public event EventHandler? RoleLeaderChanged { add { } remove { } } + } + + private static IConfiguration Configuration() => new ConfigurationBuilder().AddInMemoryCollection( + new Dictionary + { + ["DataConnections:Enabled"] = "true", ["DataConnections:ListenPort"] = "9443", + ["DataConnections:AllowedHosts:0"] = "source.local", ["DataConnections:CertificatePath"] = "server.pem" + }).Build(); + + private sealed class Environment : IHostEnvironment + { + public string EnvironmentName { get; set; } = Environments.Production; + public string ApplicationName { get; set; } = "GrpcDataTests"; + public string ContentRootPath { get; set; } = "/"; + public IFileProvider ContentRootFileProvider { get; set; } = new NullFileProvider(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataScopeActivationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataScopeActivationTests.cs new file mode 100644 index 000000000..0b3ec1b75 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataScopeActivationTests.cs @@ -0,0 +1,26 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; +using static ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections.GrpcDataSecretProvisioningTests; + +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Phase", "P07")] +public sealed class GrpcDataScopeActivationTests +{ + [Fact] + public async Task Activation_persists_identical_scope_to_credentials_and_trust() + { + var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); + var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); + var trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "pair", "node"); + var activator = new DataConnectionScopeActivator(p, trust); + await activator.SetScopeAsync(1, new Dictionary { ["link"] = "secret:data/key" }, ct); + await p.ApplyAsync(new("pair", "node", 1, [new("link", "secret:data/key", "bearer", false)], 1), ct); + await trust.SetAsync("LINK", 1, [], 1, ct); + await activator.SetScopeAsync(2, new Dictionary(), ct); + (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("link", ct)).ShouldBeNull(); + await Should.ThrowAsync(() => trust.SetAsync("link", 2, [], 1, ct)); + await Should.ThrowAsync(() => activator.SetScopeAsync(1, new Dictionary { ["link"] = "secret:data/key" }, ct)); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataSecretProvisioningTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataSecretProvisioningTests.cs new file mode 100644 index 000000000..bc362cbcc --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataSecretProvisioningTests.cs @@ -0,0 +1,205 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using ZB.MOM.WW.Secrets.DependencyInjection; +using ZB.MOM.WW.Secrets.Sqlite; +using Xunit; + +using System.Text; +using Shouldly; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; +using ZB.MOM.WW.Secrets.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; + +[Trait("Feature", "GrpcData")] +[Trait("Phase", "P07")] +public class GrpcDataSecretProvisioningTests +{ + [Fact] + public async Task Scoped_bundle_is_encrypted_and_survives_restart_without_bundle() + { + var store = new MemoryStore(); + var cipher = new TestCipher(); + var changed = new DataConnectionSecretChangeHandler(); + var provisioner = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changed, "consumer-cluster", "node-a"); + await provisioner.SetScopeAsync(1, new Dictionary { ["connection"] = "secret:data/key" }, TestContext.Current.CancellationToken); + await provisioner.ApplyAsync(new DataConnectionCredentialBundle("consumer-cluster", "node-a", 1, + [new DataConnectionCredentialEntry("connection", "secret:data/key", "bearer-value", false)], ScopeVersion: 1), TestContext.Current.CancellationToken); + var row = await store.GetAsync(new SecretName("data/key"), TestContext.Current.CancellationToken); + row.ShouldNotBeNull(); + Encoding.UTF8.GetString(row.Ciphertext).ShouldNotContain("bearer-value"); + var restarted = new DataConnectionCredentialResolver(store, cipher, "consumer-cluster", "node-a"); + var resolved = await restarted.ResolveAsync("connection", TestContext.Current.CancellationToken); + resolved.ShouldNotBeNull(); + resolved.Value.ShouldBe("bearer-value"); + resolved.Version.ShouldBe(1); + } + + [Fact] + public async Task Replica_and_pair_scopes_are_independent() + { + var ct = TestContext.Current.CancellationToken; + var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); + var a = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair-a", "a1"); + var b = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair-a", "a2"); + await a.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key-a" }, ct); + await b.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key-b" }, ct); + await a.ApplyAsync(new("pair-a", "a1", 1, [new("c", "secret:data/key-a", "a", false)], ScopeVersion: 1), ct); + (await new DataConnectionCredentialResolver(store, cipher, "pair-a", "a2").ResolveAsync("c", ct)).ShouldBeNull(); + (await new DataConnectionCredentialResolver(store, cipher, "pair-b", "a1").ResolveAsync("c", ct)).ShouldBeNull(); + await b.ApplyAsync(new("pair-a", "a2", 1, [new("c", "secret:data/key-b", "b", false)], ScopeVersion: 1), ct); + (await new DataConnectionCredentialResolver(store, cipher, "pair-a", "a2").ResolveAsync("c", ct))!.Value.ShouldBe("b"); + } + + [Fact] + public async Task Failed_store_write_leaves_pending_credential_unavailable() + { + var ct = TestContext.Current.CancellationToken; + var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); + var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); + await p.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); + await p.ApplyAsync(new("pair", "node", 1, [new("c", "secret:data/key", "old", false)], ScopeVersion: 1), ct); + store.FailUpsertName = "data/key"; + await Should.ThrowAsync(() => p.ApplyAsync(new("pair", "node", 2, [new("c", "secret:data/key", "new", false)], ScopeVersion: 1), ct)); + (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct)).ShouldBeNull(); + } + + [Fact] + public async Task Real_sqlite_store_keeps_ciphertext_and_recovers_after_provider_restart() + { + var ct = TestContext.Current.CancellationToken; + var directory = Directory.CreateTempSubdirectory("data-credentials-"); + try + { + var keyFile = Path.Combine(directory.FullName, "master-key"); + var db = Path.Combine(directory.FullName, "secrets.db"); + await File.WriteAllTextAsync(keyFile, Convert.ToBase64String(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32)), ct); + var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { + ["Secrets:SqlitePath"] = db, ["Secrets:MasterKey:Source"] = "File", + ["Secrets:MasterKey:FilePath"] = keyFile, ["Secrets:RunMigrationsOnStartup"] = "false", + }).Build(); + await using (var first = new ServiceCollection().AddLogging().AddZbSecrets(config, "Secrets").BuildServiceProvider()) + { + await first.GetRequiredService().MigrateAsync(ct); + var provisioner = new DataConnectionSecretProvisioner(first.GetRequiredService(), first.GetRequiredService(), + new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "cluster", "node"); + await provisioner.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); + await provisioner.ApplyAsync(new("cluster", "node", 1, [new("c", "secret:data/key", "private-bearer-value", false)], ScopeVersion: 1), ct); + } + var database = await File.ReadAllBytesAsync(db, ct); + Encoding.UTF8.GetString(database).ShouldNotContain("private-bearer-value"); + await using var second = new ServiceCollection().AddLogging().AddZbSecrets(config, "Secrets").BuildServiceProvider(); + var resolver = new DataConnectionCredentialResolver(second.GetRequiredService(), second.GetRequiredService(), "cluster", "node"); + (await resolver.ResolveAsync("c", ct))!.Value.ShouldBe("private-bearer-value"); + } + finally { directory.Delete(true); } + } + + [Fact] + public async Task Interrupted_version_can_resume_only_with_the_same_payload() + { + var ct = TestContext.Current.CancellationToken; + var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); + var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); + await p.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); + var bundle = new DataConnectionCredentialBundle("pair", "node", 1, [new("c", "secret:data/key", "intended", false)], ScopeVersion: 1); + store.FailUpsertName = "data/key"; + await Should.ThrowAsync(() => p.ApplyAsync(bundle, ct)); + store.FailUpsertName = null; + var restarted = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); + await Should.ThrowAsync(() => restarted.ApplyAsync(new("pair", "node", 1, [new("c", "secret:data/key", "different", false)], ScopeVersion: 1), ct)); + await restarted.ApplyAsync(bundle, ct); + (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct))!.Value.ShouldBe("intended"); + } + + [Fact] + public async Task Scope_and_historical_reference_capacity_fail_closed() + { + var ct = TestContext.Current.CancellationToken; + var store = new MemoryStore(); var cipher = new TestCipher(); + var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "pair", "node"); + var tooMany = Enumerable.Range(0, DataConnectionSecretProvisioner.MaximumReferences + 1).ToDictionary(i => "c" + i, i => "secret:data/key" + i); + await Should.ThrowAsync(() => p.SetScopeAsync(1, tooMany, ct)); + } + + [Fact] + public async Task Replaced_secret_cannot_be_resolved_under_a_committed_version() + { + var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); + var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "pair", "node"); + await p.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); + await p.ApplyAsync(new("pair", "node", 1, [new("c", "secret:data/key", "original", false)], ScopeVersion: 1), ct); + store.Rows["data/key"] = cipher.Encrypt(new SecretName("data/key"), "replacement", SecretContentType.Text); + (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct)).ShouldBeNull(); + await Should.ThrowAsync(() => p.ApplyAsync(new("pair", "node", 1, [new("c", "secret:data/key", "original", false)], ScopeVersion: 1), ct)); + } + + [Fact] + public async Task Completed_bundle_replay_after_restart_is_idempotent_but_changed_payload_is_rejected() + { + var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); + var changes = new DataConnectionSecretChangeHandler(); var notices = 0; changes.ConnectionChanged += _ => notices++; + var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); + await p.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); + var bundle = new DataConnectionCredentialBundle("pair", "node", 1, [new("c", "secret:data/key", "original", false)], ScopeVersion: 1); + await p.ApplyAsync(bundle, ct); + var restarted = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); + await restarted.ApplyAsync(bundle, ct); + notices.ShouldBe(1); + (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct))!.Value.ShouldBe("original"); + await Should.ThrowAsync(() => restarted.ApplyAsync(bundle with { Entries = [new("c", "secret:data/key", "different", false)] }, ct)); + } + + [Fact] + public async Task Canonical_reference_uses_physical_secret_name_for_store_and_resolution() + { + var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); + var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "pair", "node"); + await p.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); + await p.ApplyAsync(new("pair", "node", 1, [new("c", "secret:data/key", "bearer", false)], 1), ct); + (await store.GetAsync(new SecretName("data/key"), ct)).ShouldNotBeNull(); + (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct))!.Value.ShouldBe("bearer"); + } + + [Fact] + public void Pinned_secret_name_normalizes_case_so_wire_aliases_must_not_share_a_row() + { + new SecretName("data/Key").Value.ShouldBe(new SecretName("data/key").Value); + } + + [Fact] + public async Task Canonical_scope_rejects_uppercase_physical_secret_aliases() + { + var ct = TestContext.Current.CancellationToken; + var p = new DataConnectionSecretProvisioner(new MemoryStore(), new TestCipher(), new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "pair", "node"); + await Should.ThrowAsync(() => p.SetScopeAsync(1, new Dictionary { ["a"] = "secret:data/Key", ["b"] = "secret:data/key" }, ct)); + } + + internal sealed class NoopInvalidator : ISecretCacheInvalidator { public void Invalidate(SecretName name) { } } + internal sealed class TestCipher : ISecretCipher + { + public StoredSecret Encrypt(SecretName name, string plaintext, SecretContentType contentType) => new() + { + Name = name, ContentType = contentType, + Ciphertext = Encoding.UTF8.GetBytes(plaintext).Select(b => (byte)(b ^ 0x5a)).ToArray(), + Nonce = [], Tag = [], WrappedDek = [], WrapNonce = [], WrapTag = [], KekId = "test", Revision = 0, + CreatedUtc = DateTimeOffset.UtcNow, UpdatedUtc = DateTimeOffset.UtcNow, + }; + public string Decrypt(StoredSecret secret) => Encoding.UTF8.GetString(secret.Ciphertext.Select(b => (byte)(b ^ 0x5a)).ToArray()); + public StoredSecret Rewrap(StoredSecret secret, IMasterKeyProvider oldKek, IMasterKeyProvider newKek) => throw new NotSupportedException(); + } + internal sealed class MemoryStore : ISecretStore + { + public Dictionary Rows { get; } = new(); + public string? FailUpsertName { get; set; } + public bool FailDelete { get; set; } + public Task GetAsync(SecretName name, CancellationToken ct) => Task.FromResult(Rows.GetValueOrDefault(name.Value)); + public Task UpsertAsync(StoredSecret row, CancellationToken ct) { if (row.Name.Value == FailUpsertName) throw new InvalidOperationException("store unavailable"); Rows[row.Name.Value] = row; return Task.CompletedTask; } + public Task DeleteAsync(SecretName name, string? actor, CancellationToken ct) => FailDelete ? throw new InvalidOperationException("delete unavailable") : Task.FromResult(Rows.Remove(name.Value)); + public Task> ListAsync(bool includeDeleted, CancellationToken ct) => Task.FromResult>([]); + public Task> GetManifestAsync(CancellationToken ct) => throw new NotSupportedException(); + public Task ApplyReplicatedAsync(StoredSecret row, CancellationToken ct) => throw new NotSupportedException(); + public Task ApplyRewrapAsync(StoredSecret row, byte[] expectedCurrentWrappedDek, CancellationToken ct) => throw new NotSupportedException(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataSecretRotationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataSecretRotationTests.cs new file mode 100644 index 000000000..b98683935 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataSecretRotationTests.cs @@ -0,0 +1,29 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; +using static ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections.GrpcDataSecretProvisioningTests; + +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; + +[Trait("Feature", "GrpcData")] +[Trait("Phase", "P07")] +public class GrpcDataSecretRotationTests +{ + [Fact] + public async Task Rotation_retires_and_rejects_downgrade_and_wrong_node() + { + var ct = TestContext.Current.CancellationToken; + var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); + var changed = new List(); changes.ConnectionChanged += changed.Add; + var provisioner = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "cluster", "node"); + await provisioner.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); + DataConnectionCredentialBundle Bundle(long version, string node) => new("cluster", node, version, [new("c", "secret:data/key", "value" + version, false)], ScopeVersion: 1); + await provisioner.ApplyAsync(Bundle(1, "node"), ct); + await provisioner.ApplyAsync(Bundle(2, "node"), ct); + await Should.ThrowAsync(() => provisioner.ApplyAsync(Bundle(1, "node"), ct)); + await Should.ThrowAsync(() => provisioner.ApplyAsync(Bundle(3, "other"), ct)); + var credential = await new DataConnectionCredentialResolver(store, cipher, "cluster", "node").ResolveAsync("c", ct); + credential.ShouldNotBeNull(); credential.Value.ShouldBe("value2"); credential.Version.ShouldBe(2); + changed.Count.ShouldBe(2); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataServiceDispatchTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataServiceDispatchTests.cs new file mode 100644 index 000000000..016eed417 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataServiceDispatchTests.cs @@ -0,0 +1,103 @@ +using Grpc.Core; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Options; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; +using ZB.MOM.WW.OtOpcUa.Host.Grpc; +using ZB.MOM.WW.OtOpcUa.Host.OpcUa; +using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")] +public sealed class GrpcDataServiceDispatchTests +{ + [Fact] + public void Serving_provenance_uses_the_observed_role_instead_of_inventing_a_secondary_from_a_false_verdict() + { + var role = new RedundancyRoleView(); + role.DataServingRole.ShouldBe("Unknown"); + role.PublishPrimaryRole(false); + role.DataServingRole.ShouldBe("Unknown"); + role.PublishDataServingRole(RedundancyRole.Secondary, false); + role.DataServingRole.ShouldBe("Secondary"); + role.ShouldActAsPrimary.ShouldBeFalse(); + var generation = role.PrimaryGeneration; + role.PublishDataServingRole(null, false); + role.DataServingRole.ShouldBe("Unknown"); + role.PrimaryGeneration.ShouldBeGreaterThan(generation); + role.PublishDataServingRole(RedundancyRole.Primary, true); + role.DataServingRole.ShouldBe("Primary"); + role.ShouldActAsPrimary.ShouldBeTrue(); + } + [Fact] + public async Task Ingress_binds_the_trusted_caller_and_explicit_target_to_the_local_facade() + { + var fixture = Create(); + var failure = await Should.ThrowAsync(() => fixture.Service.GetCapabilities(new() { ProtocolMajor = 1 }, fixture.Context)); + failure.StatusCode.ShouldBe(StatusCode.Unavailable); + fixture.Context.WriteOptions!.Flags.ShouldBe(WriteFlags.NoCompress); + fixture.Factory.Caller!.PrincipalId.ShouldBe("peer"); + fixture.Factory.Target.ShouldBe(new(DataTargetMode.Node, "cluster", "node")); + } + + [Fact] + public async Task Revocation_after_preparse_authentication_prevents_facade_creation() + { + var fixture = Create(); + fixture.Authority.Apply("cluster", "revoked", [], [], new Dictionary>()); + var failure = await Should.ThrowAsync(() => fixture.Service.GetCapabilities(new() { ProtocolMajor = 1 }, fixture.Context)); + failure.StatusCode.ShouldBe(StatusCode.Unauthenticated); + fixture.Factory.Caller.ShouldBeNull(); + } + + private static (DataConnectionGrpcService Service, CallContext Context, RejectingFactory Factory, DataPlaneAuthorityState Authority) Create() + { + var (bearer, id, hash) = ApiKeySecret.Generate("pepper"); + var authority = new DataPlaneAuthorityState(); + authority.Apply("cluster", "v1", [new ApiKey { ApiKeyId = id, Name = "test", Principal = "peer", SecretHash = hash, Enabled = true }], + [], new Dictionary>()); + var authenticator = new DataConnectionAuthenticator(authority, Options.Create(new ApiKeyOptions { Pepper = "pepper" }), TimeProvider.System); + var options = new DataConnectionOptions { Enabled = true, ListenPort = 9443, AllowedHosts = ["source.local"], CertificatePath = "server.pem" }; + var context = new CallContext(); + var http = new DefaultHttpContext(); + http.Connection.LocalPort = 9443; + http.Request.Protocol = "HTTP/2"; http.Request.Scheme = "https"; http.Request.Method = "POST"; + http.Request.Host = new HostString("source.local", 9443); http.Request.Path = context.Method; + http.Items[typeof(DataAuthenticatedContext)] = authenticator.Authenticate(bearer); + http.Items[typeof(DataTarget)] = new DataTarget(DataTargetMode.Node, "cluster", "node"); + context.UserState["__HttpContext"] = http; + var factory = new RejectingFactory(); + return (new(factory, Options.Create(options), authenticator), context, factory, authority); + } + + private sealed class RejectingFactory : IDataConnectionFactory + { + public DataAuthenticatedContext? Caller; + public DataTarget? Target; + public IDataConnection Create(DataAuthenticatedContext context, DataTarget target) + { Caller = context; Target = target; throw new InvalidOperationException("Not ready."); } + } + + private sealed class CallContext : ServerCallContext + { + protected override string MethodCore => DataConnectionEndpoints.ServicePrefix + "GetCapabilities"; + protected override string HostCore => "source.local"; + protected override string PeerCore => "ipv4:127.0.0.1:0"; + protected override DateTime DeadlineCore => DateTime.MaxValue; + protected override Metadata RequestHeadersCore => []; + protected override CancellationToken CancellationTokenCore => TestContext.Current.CancellationToken; + protected override Metadata ResponseTrailersCore { get; } = []; + protected override Status StatusCore { get; set; } + protected override WriteOptions? WriteOptionsCore { get; set; } + protected override AuthContext AuthContextCore => new(null, new Dictionary>()); + protected override ContextPropagationToken CreatePropagationTokenCore(ContextPropagationOptions? options) => throw new NotSupportedException(); + protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders) => Task.CompletedTask; + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataTrustRotationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataTrustRotationTests.cs new file mode 100644 index 000000000..56aa26b77 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataTrustRotationTests.cs @@ -0,0 +1,191 @@ +using System.Net.Security; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; + +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; + +[Trait("Feature", "GrpcData")] +[Trait("Phase", "P07")] +public class GrpcDataTrustRotationTests +{ + [Fact] + public void Trust_changes_fingerprint_and_name_mismatch_never_falls_back() + { + using var key = RSA.Create(2048); + var request = new CertificateRequest("CN=localhost", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); + using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); + var policy = new DataConnectionTrustPolicy(1, [certificate]); + using var message = new HttpRequestMessage(HttpMethod.Get, "https://localhost"); + policy.Validate(message, certificate, null, SslPolicyErrors.RemoteCertificateNameMismatch).ShouldBeFalse(); + policy.Validate(message, certificate, null, SslPolicyErrors.None).ShouldBeFalse(); // CN alone is insufficient + Should.Throw(() => new DataConnectionTrustPolicy(2, [])); + } + [Fact] + public async Task Trust_version_rotation_and_removal_survive_restart() + { + var ct = TestContext.Current.CancellationToken; + var store = new GrpcDataSecretProvisioningTests.MemoryStore(); + var cipher = new GrpcDataSecretProvisioningTests.TestCipher(); + var changes = new DataConnectionSecretChangeHandler(); var retired = new List(); + changes.ConnectionChanged += retired.Add; + using var key = RSA.Create(2048); + var request = new CertificateRequest("CN=root", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); + using var oldRoot = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); + using var newKey = RSA.Create(2048); + var newRequest = new CertificateRequest("CN=new", newKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + newRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); + using var newRoot = newRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); + var policies = new DataConnectionTrustPolicyStore(store, cipher, changes, "pair", "node"); + await policies.ApplyScopeAsync(1, ["c"], ct); + await policies.SetAsync("c", 1, [oldRoot], 1, ct); + var old = await policies.ResolveAsync("c", ct); old.ShouldNotBeNull(); + await policies.SetAsync("c", 2, [oldRoot, newRoot], 1, ct); + var rotated = await policies.ResolveAsync("c", ct); rotated.ShouldNotBeNull(); + rotated.Fingerprint.ShouldNotBe(old.Fingerprint); + var restarted = new DataConnectionTrustPolicyStore(store, cipher, changes, "pair", "node"); + await restarted.SetAsync("c", 3, [newRoot], 1, ct); + using var message = new HttpRequestMessage(HttpMethod.Get, "https://localhost"); + var current = await restarted.ResolveAsync("c", ct); current.ShouldNotBeNull(); + current.Validate(message, oldRoot, null, SslPolicyErrors.RemoteCertificateChainErrors).ShouldBeFalse(); + await restarted.SetAsync("c", 4, [], 1, ct); + (await restarted.ResolveAsync("c", ct)).ShouldBeNull(); + await Should.ThrowAsync(() => restarted.SetAsync("c", 2, [oldRoot], 1, ct)); + retired.Count.ShouldBe(4); + } + [Fact] + public async Task Trust_tombstone_capacity_does_not_evict_prior_versions() + { + var ct = TestContext.Current.CancellationToken; + var store = new GrpcDataSecretProvisioningTests.MemoryStore(); + var policies = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), new DataConnectionSecretChangeHandler(), "pair", "node"); + await policies.ApplyScopeAsync(1, Enumerable.Range(0, DataConnectionTrustPolicyStore.MaximumConnections).Select(i => "c" + i), ct); + for (var i = 0; i < DataConnectionTrustPolicyStore.MaximumConnections; i++) await policies.SetAsync("c" + i, 1, [], 1, ct); + await Should.ThrowAsync(() => policies.SetAsync("overflow", 1, [], 1, ct)); + await Should.ThrowAsync(() => policies.SetAsync("c0", 1, [], 1, ct)); + } + [Fact] + public void Validation_requires_matching_san_and_trusted_issuer() + { + using var caKey = RSA.Create(2048); + var caRequest = new CertificateRequest("CN=ca", caKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + caRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); + caRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign, true)); + using var ca = caRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); + using var leafKey = RSA.Create(2048); + var leafRequest = new CertificateRequest("CN=ignored", leafKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + var san = new SubjectAlternativeNameBuilder(); san.AddDnsName("service.example"); + leafRequest.CertificateExtensions.Add(san.Build()); + using var leaf = leafRequest.Create(ca, DateTimeOffset.UtcNow.AddHours(-1), DateTimeOffset.UtcNow.AddHours(1), [1, 2, 3]); + var policy = new DataConnectionTrustPolicy(1, [ca]); + using var good = new HttpRequestMessage(HttpMethod.Get, "https://service.example"); + using var bad = new HttpRequestMessage(HttpMethod.Get, "https://wrong.example"); + policy.Validate(good, leaf, null, SslPolicyErrors.RemoteCertificateChainErrors).ShouldBeTrue(); + policy.Validate(bad, leaf, null, SslPolicyErrors.None).ShouldBeFalse(); + } + [Fact] + public async Task Failed_trust_notification_can_resume_same_version() + { + var ct = TestContext.Current.CancellationToken; var store = new GrpcDataSecretProvisioningTests.MemoryStore(); var changes = new DataConnectionSecretChangeHandler(); + var calls = 0; changes.ConnectionChanged += _ => { calls++; if (calls == 1) throw new InvalidOperationException(); }; + var trust = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), changes, "pair", "node"); + await trust.ApplyScopeAsync(1, ["c"], ct); + await Should.ThrowAsync(() => trust.SetAsync("c", 1, [], 1, ct)); + await trust.SetAsync("c", 1, [], 1, ct); + calls.ShouldBe(2); + } + [Fact] + public async Task Scoped_trust_churn_reclaims_retired_ids_and_rejects_stale_scope() + { + var ct = TestContext.Current.CancellationToken; var store = new GrpcDataSecretProvisioningTests.MemoryStore(); + var trust = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), new DataConnectionSecretChangeHandler(), "pair", "node"); + await trust.ApplyScopeAsync(1, ["first"], ct); + await trust.SetAsync("first", 1, [], 1, ct); + for (var i = 0; i < DataConnectionTrustPolicyStore.MaximumConnections + 1; i++) + { + var generation = 2L + i; var id = "c" + i; + await trust.ApplyScopeAsync(generation, [id], ct); + await trust.SetAsync(id, 1, [], generation, ct); + } + var latest = 3L + DataConnectionTrustPolicyStore.MaximumConnections; + await trust.ApplyScopeAsync(latest, ["first"], ct); + trust = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), new DataConnectionSecretChangeHandler(), "pair", "node"); + await Should.ThrowAsync(() => trust.SetAsync("first", 999, [], 1, ct)); + await trust.SetAsync("first", 1, [], latest, ct); + } + [Fact] + public async Task Failed_retirement_followed_by_reintroduction_cannot_restore_old_ca() + { + var ct = TestContext.Current.CancellationToken; var store = new GrpcDataSecretProvisioningTests.MemoryStore(); + var changes = new DataConnectionSecretChangeHandler(); var trust = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), changes, "pair", "node"); + using var key = RSA.Create(2048); + var request = new CertificateRequest("CN=ca", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); + using var ca = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); + await trust.ApplyScopeAsync(1, ["c"], ct); + await trust.SetAsync("c", 1, [ca], 1, ct); + Action broken = _ => throw new InvalidOperationException("retirement failed"); + changes.ConnectionChanged += broken; + await Should.ThrowAsync(() => trust.ApplyScopeAsync(2, [], ct)); + changes.ConnectionChanged -= broken; + trust = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), changes, "pair", "node"); + await trust.ApplyScopeAsync(3, ["c"], ct); + (await trust.ResolveAsync("c", ct)).ShouldBeNull(); + await Should.ThrowAsync(() => trust.SetAsync("c", 999, [ca], 1, ct)); + await trust.SetAsync("c", 1, [ca], 3, ct); + (await trust.ResolveAsync("c", ct)).ShouldNotBeNull(); + } + [Fact] + public async Task Trust_scope_identifiers_and_owner_node_are_case_insensitive_across_restart() + { + var ct = TestContext.Current.CancellationToken; var store = new GrpcDataSecretProvisioningTests.MemoryStore(); + var cipher = new GrpcDataSecretProvisioningTests.TestCipher(); var changes = new DataConnectionSecretChangeHandler(); + var trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "Cluster", "Node"); + await trust.ApplyScopeAsync(1, ["Link"], ct); + await trust.SetAsync("link", 1, [], 1, ct); + trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "cluster", "NODE"); + await trust.ApplyScopeAsync(1, ["LINK"], ct); + await Should.ThrowAsync(() => trust.SetAsync("LINK", 1, [], 1, ct)); + await trust.ApplyScopeAsync(2, [], ct); + await Should.ThrowAsync(() => trust.SetAsync("link", 999, [], 1, ct)); + await Should.ThrowAsync(() => trust.ApplyScopeAsync(3, ["Link", "link"], ct)); + } + [Fact] + public void A_trusted_server_name_with_client_auth_only_certificate_is_rejected() + { + using var caKey = RSA.Create(2048); + var caRequest = new CertificateRequest("CN=ca", caKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + caRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); + caRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign, true)); + using var ca = caRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); + using var leafKey = RSA.Create(2048); + var request = new CertificateRequest("CN=ignored", leafKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + var san = new SubjectAlternativeNameBuilder(); san.AddDnsName("service.example"); request.CertificateExtensions.Add(san.Build()); + var usages = new OidCollection { new Oid("1.3.6.1.5.5.7.3.2") }; + request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(usages, true)); + using var leaf = request.Create(ca, DateTimeOffset.UtcNow.AddHours(-1), DateTimeOffset.UtcNow.AddHours(1), [4, 5, 6]); + using var message = new HttpRequestMessage(HttpMethod.Get, "https://service.example"); + new DataConnectionTrustPolicy(1, [ca]).Validate(message, leaf, null, SslPolicyErrors.None).ShouldBeFalse(); + } + [Fact] + public async Task Public_trust_batch_rejects_excess_certificate_count_and_bytes_before_writing() + { + var ct = TestContext.Current.CancellationToken; var store = new GrpcDataSecretProvisioningTests.MemoryStore(); + var policy = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), new DataConnectionSecretChangeHandler(), "pair", "node"); + await policy.ApplyScopeAsync(1, ["c"], ct); + using var key = RSA.Create(2048); + var request = new CertificateRequest("CN=ca", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); + request.CertificateExtensions.Add(new X509Extension("1.2.3.4", new byte[16384], false)); + using var cert = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); + await Should.ThrowAsync(() => policy.SetBundleAsync([("c", 1, Enumerable.Repeat(cert, DataConnectionTrustPolicyStore.MaximumRootCertificates + 1).ToArray())], 1, ct)); + var byteLimitCount = checked((int)(DataConnectionTrustPolicyStore.MaximumTrustBytes / cert.RawData.Length) + 1); + byteLimitCount.ShouldBeLessThanOrEqualTo(DataConnectionTrustPolicyStore.MaximumRootCertificates); + await Should.ThrowAsync(() => policy.SetBundleAsync([("c", 1, Enumerable.Repeat(cert, byteLimitCount).ToArray())], 1, ct)); + await policy.SetAsync("c", 1, [], 1, ct); // rejected batches wrote nothing + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCachedReadTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCachedReadTests.cs index 944deac37..b13ad4305 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCachedReadTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCachedReadTests.cs @@ -1,12 +1,35 @@ using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; [Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P04")] public sealed class GrpcDataCachedReadTests { + [Fact] + public async Task Source_invalidation_during_publication_authority_validation_is_rechecked_afterwards() + { + using var fixture = new LocalDataFixture(); + var invalidate = false; + var capabilities = new DataCapabilitiesProvider("cluster", () => fixture.Serving, + () => fixture.Catalog.IsActive, fixture.Services.SubscriptionLimits); + var services = new LocalDataServices(() => + { + if (invalidate) fixture.Hub.Invalidate(fixture.Ticket, "During publication authority validation"); + return fixture.Catalog; + }, fixture.Hub, new DataOperationPolicy(fixture.Authority, + new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock), capabilities, fixture.Clock); + fixture.Publish(7); + await using var connection = services.Create(fixture.Context, new(DataTargetMode.Node, "cluster", "node-a")); + var results = await connection.ReadAsync(new([new("read", fixture.Raw, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken); + using var result = results.ShouldHaveSingleItem(); + var lease = result.ResourceLease.ShouldBeAssignableTo(); + invalidate = true; + lease!.IsValid.ShouldBeFalse(); + } [Fact] public async Task Prepared_response_is_fenced_before_send_after_ingress_invalidation_or_authority_change() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCatalogStagingTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCatalogStagingTests.cs index e22a9c55a..1b13f9505 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCatalogStagingTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCatalogStagingTests.cs @@ -1,8 +1,11 @@ using System.Security.Cryptography; using System.Text; using System.Text.Json.Nodes; +using System.Text.Json; using Akka.Actor; +using Akka.DependencyInjection; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Shouldly; using Xunit; @@ -33,6 +36,34 @@ public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase private static readonly ServingIdentity BootIdentity = new("node-a", "process-1", "Primary", 0, 0); private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 100, 1_000_000); + [Fact] + public async Task Returning_to_the_same_role_cannot_revive_a_previous_publication_permit() + { + var authority = new DataPlaneAuthorityState(); + var serving = BootIdentity with { ServingGeneration = 1 }; + var coordinator = new LocalCatalogCoordinator(new CatalogActivation(), authority, () => serving); + var attempt = Prepare(coordinator, Artifact()); + coordinator.Complete(attempt, true).ShouldBeTrue(); + using var hub = HubTest.Create(); + var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000, + TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1)); + var caps = new DataCapabilitiesProvider("cluster", () => coordinator.Serving, () => coordinator.Current is not null, limits); + var services = new LocalDataServices(() => coordinator.Current, hub, + new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, hub.Clock), hub.Clock), caps, hub.Clock); + var key = authority.Current.FindUsableKey("peer-key", DateTime.UtcNow).ShouldNotBeNull(); + await using var connection = services.Create(new("peer", key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(key), + DateTimeOffset.UtcNow.AddMinutes(10), authority.Current.GenerationId), new(DataTargetMode.Node, "cluster", Node.Value)); + var previous = await connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken); + var gate = (IDataConnectionPublicationGate)connection; + gate.CanPublish(previous.Serving).ShouldBeTrue(); + // The consumer need not observe the intervening demotion or actor replacement. + serving = serving with { ServingGeneration = 3 }; + gate.CanPublish(previous.Serving).ShouldBeFalse(); + var current = await connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken); + current.Serving.ServingGeneration.ShouldBe(3); + gate.CanPublish(current.Serving).ShouldBeTrue(); + } + [Fact] public void A_new_attempt_closes_a_completed_catalog_even_when_authority_revision_is_unchanged() { @@ -274,11 +305,13 @@ public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase var coordinator = NewCoordinator(authority, activation); using var entered = new ManualResetEventSlim(); using var release = new ManualResetEventSlim(); - var sink = NullOpcUaAddressSpaceSink.Instance; - var hooks = new OpcUaPublishActor.TestHooks { BeforeComposition = () => { entered.Set(); release.Wait(); } }; - var publish = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink, - new AddressSpaceApplier(sink, NullLogger.Instance), hooks, - dataPlaneAuthority: authority, catalogCoordinator: coordinator)); + var sink = new HeldFolderSink(entered, release); + using var services = new ServiceCollection() + .AddSingleton(authority) + .AddSingleton(activation).AddSingleton(coordinator).BuildServiceProvider(); + var props = DataConnectionPublisherProps.Create(new ServiceProviderDependencyResolver(services), sink, NullServiceLevelPublisher.Instance, Node, + dbFactory: null, new AddressSpaceApplier(sink, NullLogger.Instance), dbHealthProbe: null); + var publish = Sys.ActorOf(props.WithDispatcher("akka.actor.default-dispatcher")); var acks = CreateTestProbe(); var host = NewHost(bytes, coordinator, acks.Ref, publish: publish); try @@ -297,6 +330,52 @@ public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase finally { release.Set(); } } + [Fact] + public async Task Invalid_next_local_artifact_drains_active_import_before_fallible_staging() + { + var first = JsonNode.Parse(Artifact())!.AsObject(); + first["DataConnectionScopeVersion"] = 1; + first["DataConnections"] = JsonSerializer.SerializeToNode(new[] { new DataConnection + { + DataConnectionId = "link", ClusterId = "cluster", Revision = 1, Enabled = true, + ConsumerNodeIds = ["node-a"], TargetMode = DataTargetMode.Node, ExpectedClusterId = "remote-cluster", ExpectedNodeId = "remote", + Endpoints = ["https://remote.example:8443"], SecretReference = "secret:data/key", SecretScopeClusterId = "cluster", + AllowedOperations = DataOperations.Read + }}); + var valid = Encoding.UTF8.GetBytes(first.ToJsonString()); + DeploymentArtifact.ParseDataConnectionScopeVersion(valid).ShouldBe(1); + DeploymentArtifact.ParseDataConnections(valid, Node.Value).ShouldHaveSingleItem().DataConnectionId.ShouldBe("link"); + var fetcher = new MutableFetcher(valid); var authority = new DataPlaneAuthorityState(); + var coordinator = NewCoordinator(authority, new CatalogActivation()); + await using var outbound = new DataConnectionDeploymentRuntime("node-a", "cluster", new ReadySecurity(), new ImmediateScope(), 8); + var acks = CreateTestProbe(); + var host = Sys.ActorOf(DriverHostActor.Props(dbFactory: null, localNode: Node, ackRouter: acks.Ref, + localRoles: new HashSet { "driver" }, fetchAndCacheMode: true, artifactFetcher: fetcher, + catalogCoordinator: coordinator, dataConnections: outbound)); + host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(valid), CorrelationId.NewId())); + acks.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Applied); + AwaitCondition(() => outbound.CurrentScopeReady, TimeSpan.FromSeconds(2), "initial scope activation never completed", TestContext.Current.CancellationToken); + AwaitCondition(() => + { + if (!outbound.TryAcquire("link", out var candidate)) return false; + candidate!.Dispose(); return true; + }, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + outbound.TryAcquire("link", out var lease).ShouldBeTrue(); + using (lease!) + { + var invalid = first.DeepClone().AsObject(); + invalid["DataConnectionScopeVersion"] = 2; + invalid["DataConnections"] = new JsonArray(); + invalid["RawFolders"] = new JsonObject(); // malformed local topology, before scope apply + fetcher.Bytes = Encoding.UTF8.GetBytes(invalid.ToJsonString()); + host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(fetcher.Bytes), CorrelationId.NewId())); + acks.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + lease!.CancellationToken.IsCancellationRequested.ShouldBeTrue(); + outbound.CurrentScopeReady.ShouldBeFalse(); + outbound.TryAcquire("link", out _).ShouldBeFalse(); + } + } + [Fact] public void Role_transition_reuses_the_adjusted_catalog_and_does_not_freshen_the_cached_acquisition() { @@ -571,6 +650,36 @@ public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase return Encoding.UTF8.GetBytes(root.ToJsonString()); } + private sealed class ReadySecurity : IDataConnectionSecurityProvider + { + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => + ValueTask.FromResult(new("1", "trust", "key", () => new NoNetworkHandler())); + } + private sealed class NoNetworkHandler : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => + throw new InvalidOperationException("This test does not send network traffic."); + } + private sealed class ImmediateScope : IDataConnectionScopeActivator + { + public Task SetScopeAsync(long version, IReadOnlyDictionary allowlist, CancellationToken cancellationToken) => Task.CompletedTask; + } + + private sealed class HeldFolderSink(ManualResetEventSlim entered, ManualResetEventSlim release) : IOpcUaAddressSpaceSink + { + public void WriteValue(string nodeId, object? value, uint statusCode, DateTime sourceTimestampUtc, AddressSpaceRealm realm) { } + public void WriteAlarmQuality(string alarmNodeId, uint statusCode, DateTime sourceTimestampUtc, AddressSpaceRealm realm) { } + public void WriteAlarmCondition(string alarmNodeId, AlarmConditionSnapshot state, DateTime occurredUtc, AddressSpaceRealm realm) { } + public void MaterialiseAlarmCondition(string alarmNodeId, string equipmentNodeId, string displayName, string alarmType, int severity, AddressSpaceRealm realm, bool isNative = false) { } + public void EnsureFolder(string folderNodeId, string? parentNodeId, string displayName, AddressSpaceRealm realm) { entered.Set(); release.Wait(); } + public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, AddressSpaceRealm realm, string? historianTagname = null, bool isArray = false, uint? arrayLength = null, bool refuseArrayOnScalar = false) { } + public void RebuildAddressSpace() { } + public void RaiseNodesAddedModelChange(string affectedNodeId, AddressSpaceRealm realm) { } + public void WireAlarmNotifiers(string alarmNodeId, AddressSpaceRealm alarmRealm, IReadOnlyList notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm) { } + public void AddReference(string sourceNodeId, AddressSpaceRealm sourceRealm, string targetNodeId, AddressSpaceRealm targetRealm, string referenceType = "Organizes") { } + } + private sealed class MutableFetcher(byte[] bytes) : IDeploymentArtifactFetcher { private int _calls; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConnectionClientTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConnectionClientTests.cs new file mode 100644 index 000000000..d40517244 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConnectionClientTests.cs @@ -0,0 +1,824 @@ +using System.Buffers.Binary; +using System.Net; +using Google.Protobuf; +using Shouldly; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")] +public sealed class GrpcDataConnectionClientTests +{ + private static readonly DataLimits Limits = new(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)); + private static readonly ServingIdentity Serving = new("a", "boot", "Primary", 1, 1, 1); + private static readonly DataView View = new(new("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x"); + private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 16, 65536); + + [Fact] + public void Security_material_does_not_render_the_presented_bearer() + { + var security = new DataConnectionSecurity("credential-v1", "trust-fingerprint", "sensitive-bearer-value", () => new WireHandler()); + security.ToString().ShouldNotContain("sensitive-bearer-value"); + } + + [Fact] + public async Task Configured_pending_byte_cap_is_enforced_before_stream_command_send() + { + var handle = new DataItemHandle("s", 1, 1, 1); + var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); + var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, settings, null)])); + ack.Serving = DataProtoMapper.EncodeServing(Serving); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], new Security(new StreamWireHandler([ack])), manager.Acquire("link"), + 65536, 1, maxPendingCommandBytes: 128); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + await Should.ThrowAsync(() => subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), + [new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task Pending_command_bytes_are_shared_across_streams() + { + var handle = new DataItemHandle("s", 1, 1, 1); + var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); + var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, settings, null)])); + ack.Serving = DataProtoMapper.EncodeServing(Serving); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], new Security(new StreamWireHandler([ack])), manager.Acquire("link"), + 65536, 1, maxPendingCommandBytes: 500); + await using var first = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + await using var second = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + await first.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken); + await Should.ThrowAsync(() => second.SendAsync(new OpenSubscription("s2", 1, "open2", TimeSpan.FromSeconds(5), + [new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken)); + } + + [Fact] + public void Local_stream_capacity_must_be_positive_independently_of_peer_limits() + { + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + using var scope = manager.Acquire("link"); + Should.Throw(() => new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], new Security(new WireHandler()), scope, 65536, 1, maxStreams: 0)); + } + + [Fact] + public async Task Negotiated_envelope_peer_must_advertise_a_positive_serving_generation() + { + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], new Security(new WireHandler { ZeroServingGeneration = true }), manager.Acquire("link"), 65536, 1); + await Should.ThrowAsync(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task Lost_write_reply_is_unknown_and_is_not_resent() + { + var handler = new WireHandler { LoseWrite = true }; + var security = new Security(handler); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], security, manager.Acquire("link"), 65536, 1); + using var value = DataValue.FromScalar(DataValueKind.Int32, 42); + var result = await connection.WriteAsync(new([new("item", "op", View, value, 1, "boot", TimeSpan.FromSeconds(4))], Budget), TestContext.Current.CancellationToken); + result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown); + handler.WriteCalls.ShouldBe(1); + } + + [Fact] + public async Task Browse_rejects_a_lease_from_another_authority_generation() + { + var handler = new WireHandler { BadBrowseLease = true }; + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1); + await Should.ThrowAsync(() => connection.BrowseAsync(new(View, null, null, Budget), TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task Read_rejects_a_response_from_another_boot() + { + var handler = new WireHandler { WrongReadServing = true }; + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1); + await Should.ThrowAsync(() => connection.ReadAsync(new([new("item", View, null)], Budget), TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task No_ready_primary_backs_off_before_probing_again() + { + var clock = new ManualTimeProvider(); + var handler = new UnreadyHandler(); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), + [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1, clock, + new HashSet { "a" }); + await Should.ThrowAsync(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken)); + await Should.ThrowAsync(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken)); + handler.Calls.ShouldBe(1); + clock.Advance(TimeSpan.FromMinutes(1)); + await Should.ThrowAsync(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken)); + handler.Calls.ShouldBe(2); + } + private sealed class UnreadyHandler : HttpMessageHandler + { + public int Calls { get; private set; } + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Calls++; + return Task.FromResult(Frame(DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, + Serving with { Role = "Secondary" }, DataReadiness.Ready, DataOperations.Read, + new HashSet { DataValueKind.Int32 }, Limits, false, 0, "c", false, true)))); + } + } + + [Fact] + public async Task Discovery_consumes_each_write_items_original_budget_independently() + { + var clock = new ManualTimeProvider(); + var handler = new FailoverHandler("a", false, () => clock.Advance(TimeSpan.FromMilliseconds(600))); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://a.test")], new PairSecurity(handler, handler), manager.Acquire("link"), 65536, 1, clock); + using var first = DataValue.FromScalar(DataValueKind.Int32, 1); + using var second = DataValue.FromScalar(DataValueKind.Int32, 2); + var result = await connection.WriteAsync(new([new("expired", "one", View, first, 1, "boot", TimeSpan.FromMilliseconds(500)), + new("live", "two", View, second, 1, "boot", TimeSpan.FromSeconds(3))], Budget), TestContext.Current.CancellationToken); + result[0].Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); + result[1].Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess); + handler.WrittenIds.ShouldBe(new[] { "live" }); + } + + [Fact] + public async Task Failover_metadata_cannot_restart_a_rejected_items_budget() + { + var clock = new ManualTimeProvider(); + var first = new FailoverHandler("a", true); + var second = new FailoverHandler("b", false, onMetadata: () => clock.Advance(TimeSpan.FromMilliseconds(600))); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), + [new Uri("https://a.test"), new Uri("https://b.test")], new PairSecurity(first, second), manager.Acquire("link"), + 65536, 2, clock, new HashSet { "a", "b" }); + using var value = DataValue.FromScalar(DataValueKind.Int32, 1); + var result = await connection.WriteAsync(new([new("retry", "one", View, value, 1, "boot", TimeSpan.FromMilliseconds(500))], Budget), TestContext.Current.CancellationToken); + result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); + second.WrittenIds.ShouldBeEmpty(); + } + + [Fact] + public async Task Cluster_failover_retries_only_authenticated_pre_dispatch_rejection() + { + var first = new FailoverHandler("a", true); + var second = new FailoverHandler("b", false); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), + [new Uri("https://a.test"), new Uri("https://b.test")], new PairSecurity(first, second), manager.Acquire("link"), + 65536, 2, eligibleNodeIds: new HashSet { "a", "b" }); + using var firstValue = DataValue.FromScalar(DataValueKind.Int32, 1); + using var secondValue = DataValue.FromScalar(DataValueKind.Int32, 2); + var result = await connection.WriteAsync(new([new("retry", "one", View, firstValue, 1, "boot", TimeSpan.FromSeconds(4)), + new("unknown", "two", View, secondValue, 1, "boot", TimeSpan.FromSeconds(4))], Budget), TestContext.Current.CancellationToken); + result[0].Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess); + result[1].Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown); + second.WrittenIds.ShouldBe(new[] { "retry" }); + } + private sealed class PairSecurity(FailoverHandler first, FailoverHandler second) : IDataConnectionSecurityProvider + { + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => + ValueTask.FromResult(new("v1", "ca1", "key", () => endpoint.Host == "a.test" ? first : second)); + } + private sealed class FailoverHandler(string node, bool rejectFirst, Action? onCapabilities = null, Action? onMetadata = null) : HttpMessageHandler + { + public List WrittenIds { get; } = []; + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var serving = new ServingIdentity(node, "boot", "Primary", 1, 1, 1); + IMessage message; + if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal)) + { + onCapabilities?.Invoke(); + message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, serving, DataReadiness.Ready, + DataOperations.Read | DataOperations.Write | DataOperations.Metadata, new HashSet { DataValueKind.Int32 }, + Limits, false, 0, "c", false, true)); + } + else if (request.RequestUri.AbsolutePath.EndsWith("/GetMetadata", StringComparison.Ordinal)) + { + onMetadata?.Invoke(); + var metadata = new DataMetadata(View, "x", "tag", DataValueKind.Int32, -1, [], true, DataOperations.Write, + 2, null, null, false); + var wire = DataProtoMapper.EncodeMetadataResponse([new("0", DataItemStatus.Good, metadata, null)]); + wire.Serving = DataProtoMapper.EncodeServing(serving); message = wire; + } + else + { + var bytes = await request.Content!.ReadAsByteArrayAsync(cancellationToken); + var write = W.WriteRequest.Parser.ParseFrom(bytes.AsSpan(5).ToArray()); + WrittenIds.AddRange(write.Items.Select(x => x.CorrelationId)); + var result = new W.WriteResponse { Serving = DataProtoMapper.EncodeServing(serving) }; + foreach (var item in write.Items) + result.Items.Add(DataProtoMapper.EncodeWriteResult(new(item.CorrelationId, new(rejectFirst + ? item.CorrelationId == "retry" ? DataWriteState.RejectedBeforeDispatch : DataWriteState.OutcomeUnknown + : DataWriteState.DriverConfirmedSuccess, 1, null)))); + message = result; + } + return Frame(message); + } + } + private static HttpResponseMessage Frame(IMessage message) + { + var payload = message.ToByteArray(); var framed = new byte[payload.Length + 5]; + BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), payload.Length); payload.CopyTo(framed, 5); + var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent(framed) }; + response.Content.Headers.ContentType = new("application/grpc"); response.TrailingHeaders.Add("grpc-status", "0"); + return response; + } + + [Fact] + public async Task Reconnect_cannot_reuse_the_same_subscription_epoch() + { + var handle = new DataItemHandle("s", 1, 1, 1); + var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); + var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, settings, null)])); + ack.Serving = DataProtoMapper.EncodeServing(Serving); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], new Security(new StreamWireHandler([ack])), manager.Acquire("link"), 65536, 1); + var open = new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget); + await using (var first = await connection.SubscribeAsync(TestContext.Current.CancellationToken)) + { + await first.SendAsync(open, TestContext.Current.CancellationToken); + await using var reader = first.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken); + (await reader.MoveNextAsync()).ShouldBeTrue(); + } + await using var second = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + await Should.ThrowAsync(() => second.SendAsync(open, TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task Acknowledged_command_payload_is_not_retained_by_a_delayed_timer_continuation() + { + var handle = new DataItemHandle("s", 1, 1, 1); + var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); + var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, settings, null)])); + ack.Serving = DataProtoMapper.EncodeServing(Serving); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], new Security(new StreamWireHandler([ack])), manager.Acquire("link"), 65536, 1); + WeakReference? pendingIdentity = null; + var timerEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseTimer = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + connection.PendingIdentityObserverForTests = weak => pendingIdentity = weak; + connection.AfterTimerCancelledForTests = async () => { timerEntered.TrySetResult(); await releaseTimer.Task; }; + try + { + await SendOneAndDrainAsync(connection, settings); + await timerEntered.Task.WaitAsync(TestContext.Current.CancellationToken); + for (var i = 0; i < 3; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } + pendingIdentity.ShouldNotBeNull(); + pendingIdentity.IsAlive.ShouldBeFalse(); + } + finally { releaseTimer.TrySetResult(); } + } + private static async Task SendOneAndDrainAsync(GrpcDataConnection connection, DataSubscriptionSettings settings) + { + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(20), [new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken); + await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken); + (await reader.MoveNextAsync()).ShouldBeTrue(); + (await reader.MoveNextAsync()).ShouldBeFalse(); + } + + [Fact] + public async Task Stream_acknowledgement_is_bound_to_the_sent_copy_not_a_mutated_caller_list() + { + var handle = new DataItemHandle("s", 1, 1, 1); + var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", + [new("item", DataItemStatus.Good, handle, new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null), null)])); + ack.Serving = DataProtoMapper.EncodeServing(Serving); + var handler = new StreamWireHandler([ack]); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var items = new List { new("item", View, new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null)) }; + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), items, false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken); + items.Clear(); + await using var enumerator = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken); + (await enumerator.MoveNextAsync()).ShouldBeTrue(); + enumerator.Current.ShouldBeOfType(); + } + [Fact] + public async Task Stream_rejects_reuse_of_a_removed_handle_for_a_new_item() + { + var handle = new DataItemHandle("s", 1, 1, 1); + var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); + W.SubscriptionFrame Ack(long sequence, string id, string clientId, DataItemHandle item) + { + var wire = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, sequence, id, + [new(clientId, DataItemStatus.Good, item, settings, null)])); + wire.Serving = DataProtoMapper.EncodeServing(Serving); return wire; + } + var handler = new StreamWireHandler([Ack(1, "open", "item", handle), Ack(2, "remove", "item", handle), Ack(3, "add", "other", handle)]); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken); + await using var enumerator = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken); + (await enumerator.MoveNextAsync()).ShouldBeTrue(); + await subscription.SendAsync(new RemoveSubscriptionItems("s", 1, "remove", TimeSpan.FromSeconds(5), [handle]), TestContext.Current.CancellationToken); + (await enumerator.MoveNextAsync()).ShouldBeTrue(); + await subscription.SendAsync(new AddSubscriptionItems("s", 1, "add", TimeSpan.FromSeconds(5), [new("other", View, settings)]), TestContext.Current.CancellationToken); + await Should.ThrowAsync(async () => await enumerator.MoveNextAsync()); + } + + [Fact] + public async Task Stream_rejects_a_sample_version_regression_before_yield() + { + var handle = new DataItemHandle("s", 1, 1, 1); + var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); + var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, settings, null)])); + ack.Serving = DataProtoMapper.EncodeServing(Serving); + W.SubscriptionFrame ValueFrame(long seq, long version) + { + using var frame = new DataSubscriptionValues("s", 1, seq, false, + [new(handle, new DataSample(DataValue.FromScalar(DataValueKind.Int32, 42), 0, null, null, Serving, version))]); + var wire = DataProtoMapper.EncodeValues(frame, false); wire.Serving = DataProtoMapper.EncodeServing(Serving); return wire; + } + var handler = new StreamWireHandler([ack, ValueFrame(2, 100), ValueFrame(3, 99)]); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken); + await using var enumerator = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken); + (await enumerator.MoveNextAsync()).ShouldBeTrue(); + (await enumerator.MoveNextAsync()).ShouldBeTrue(); + ((IDisposable)enumerator.Current).Dispose(); + await Should.ThrowAsync(async () => await enumerator.MoveNextAsync()); + } + private sealed class StreamWireHandler(IReadOnlyList frames) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal)) + return Task.FromResult(Frame(DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, Serving, DataReadiness.Ready, + DataOperations.Subscribe, new HashSet { DataValueKind.Int32 }, Limits, false, 0, "c", false, true)))); + using var stream = new MemoryStream(); + foreach (var frame in frames) + { + var bytes = frame.ToByteArray(); var prefix = new byte[5]; BinaryPrimitives.WriteInt32BigEndian(prefix.AsSpan(1), bytes.Length); + stream.Write(prefix); stream.Write(bytes); + } + var sent = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _ = DrainRequestAsync(request.Content!, sent, cancellationToken); + var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, + Content = new StreamContent(new GatedResponseStream(stream.ToArray(), sent.Task)) }; + response.Content.Headers.ContentType = new("application/grpc"); response.TrailingHeaders.Add("grpc-status", "0"); + return Task.FromResult(response); + } + private static async Task DrainRequestAsync(HttpContent content, TaskCompletionSource sent, CancellationToken ct) + { + try { await content.CopyToAsync(new SignalSink(sent), ct); } + catch (Exception) { sent.TrySetCanceled(); } + } + } + private sealed class SignalSink(TaskCompletionSource sent) : Stream + { + public override bool CanRead => false; public override bool CanSeek => false; public override bool CanWrite => true; + public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + public override void Flush() { } + public override void Write(byte[] buffer, int offset, int count) { if (count > 0) sent.TrySetResult(); } + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { if (buffer.Length > 0) sent.TrySetResult(); return ValueTask.CompletedTask; } + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + } + private sealed class GatedResponseStream(byte[] bytes, Task sent) : MemoryStream(bytes) + { + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { await sent.WaitAsync(cancellationToken); return await base.ReadAsync(buffer, cancellationToken); } + public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { await sent.WaitAsync(cancellationToken); return await base.ReadAsync(buffer, offset, count, cancellationToken); } + } + + [Fact] + public async Task Disposal_winning_before_stream_install_keeps_raw_send_charged() + { + var handler = new BlockedDuplexHandler(); + var installReached = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var proceed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var manager = new DataConnectionManager("consumer", 1); + var consumers = new HashSet { "consumer" }; + manager.ApplyScope(new Dictionary { ["link"] = new(1, consumers) }); + var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1, maxStreams: 1); + connection.BeforeStreamInstallForTests = async () => + { + await handler.Started.Task.WaitAsync(TestContext.Current.CancellationToken); + installReached.TrySetResult(); + await proceed.Task.WaitAsync(TestContext.Current.CancellationToken); + }; + var opening = connection.SubscribeAsync(TestContext.Current.CancellationToken); + Task? closing = null; + try + { + await installReached.Task.WaitAsync(TestContext.Current.CancellationToken); + closing = connection.DisposeAsync().AsTask(); + proceed.TrySetResult(); + await Should.ThrowAsync(() => opening); + manager.ApplyScope(new Dictionary { ["link"] = new(2, consumers) }); + await Should.ThrowAsync(() => closing.WaitAsync(TimeSpan.FromMilliseconds(500), TestContext.Current.CancellationToken)); + Should.Throw(() => manager.Acquire("link")); + } + finally + { + proceed.TrySetResult(); handler.Release.TrySetResult(); + try { await opening; } catch (Exception) { } + if (closing is not null) await closing; + await connection.DisposeAsync(); + } + } + + [Fact] + public async Task Stream_capacity_is_reserved_before_blocked_capability_discovery() + { + var provider = new IgnoringSecurity(); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], provider, manager.Acquire("link"), 65536, 1, maxStreams: 1); + var first = connection.SubscribeAsync(TestContext.Current.CancellationToken); + try + { + await provider.Started.Task.WaitAsync(TestContext.Current.CancellationToken); + await Should.ThrowAsync(() => connection.SubscribeAsync(TestContext.Current.CancellationToken)); + provider.Sends.ShouldBe(1); + } + finally { provider.Release.TrySetResult(); try { await first; } catch (Exception) { } } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Duplex_disposal_waits_for_ignored_preheaders_http_send(bool startReader) + { + var handler = new BlockedDuplexHandler(); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1); + var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + IAsyncEnumerator? reader = null; + Task? moving = null; + try + { + await handler.Started.Task.WaitAsync(TestContext.Current.CancellationToken); + if (startReader) + { + reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken); + moving = reader.MoveNextAsync().AsTask(); + } + var closing = subscription.DisposeAsync().AsTask(); + await Should.ThrowAsync(() => closing.WaitAsync(TimeSpan.FromMilliseconds(500), TestContext.Current.CancellationToken)); + } + finally + { + handler.Release.TrySetResult(); + if (moving is not null) { try { await moving; } catch (Exception) { } } + if (reader is not null) await reader.DisposeAsync(); + await subscription.DisposeAsync(); + } + } + private sealed class BlockedDuplexHandler : HttpMessageHandler + { + public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal)) + return Frame(DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, Serving, DataReadiness.Ready, + DataOperations.Subscribe, new HashSet { DataValueKind.Int32 }, Limits, false, 0, "c", false, true))); + Started.TrySetResult(); await Release.Task; + var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent([]) }; + response.Content.Headers.ContentType = new("application/grpc"); response.TrailingHeaders.Add("grpc-status", "0"); + return response; + } + } + + [Fact] + public async Task Ignored_response_body_cancellation_remains_charged_after_rotation() + { + var provider = new IgnoringBodySecurity(); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], provider, manager.Acquire("link"), 65536, 1, maxConcurrentUnaryCalls: 1); + var first = connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken); + try + { + await provider.Started.Task.WaitAsync(TestContext.Current.CancellationToken); + provider.Rotate(); + await provider.Disposed.Task.WaitAsync(TestContext.Current.CancellationToken); + first.IsCompleted.ShouldBeFalse(); + var failure = await Should.ThrowAsync(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken)); + failure.Message.ShouldBe("Unary capacity exhausted."); + provider.Sends.ShouldBe(1); + } + finally { provider.Release.TrySetResult(); try { await first; } catch (Exception) { } } + await WaitForReady(connection); + provider.Sends.ShouldBe(2); + } + private sealed class IgnoringBodySecurity : IDataConnectionSecurityProvider + { + private int _version; + public event Action? Changed; + public int Sends; + public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource Disposed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => + ValueTask.FromResult(new(_version.ToString(), "ca", "key", () => new IgnoringBodyHandler(this))); + public void Rotate() { _version++; Changed?.Invoke("link"); } + } + private sealed class IgnoringBodyHandler(IgnoringBodySecurity owner) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + if (Interlocked.Increment(ref owner.Sends) > 1) + return Task.FromResult(Frame(DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, Serving, DataReadiness.Ready, + DataOperations.Read, new HashSet { DataValueKind.Int32 }, Limits, false, 0, "c", false, true)))); + var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, + Content = new StreamContent(new IgnoringBodyStream(owner)) }; + response.Content.Headers.ContentType = new("application/grpc"); response.TrailingHeaders.Add("grpc-status", "0"); + return Task.FromResult(response); + } + protected override void Dispose(bool disposing) { if (disposing) owner.Disposed.TrySetResult(); base.Dispose(disposing); } + } + private sealed class IgnoringBodyStream(IgnoringBodySecurity owner) : Stream + { + public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { owner.Started.TrySetResult(); await owner.Release.Task; return 0; } + public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { owner.Started.TrySetResult(); await owner.Release.Task; return 0; } + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + [Fact] + public async Task Ignored_http_cancellation_remains_charged_after_channel_dispose_and_rotation() + { + var provider = new IgnoringSecurity(); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], provider, manager.Acquire("link"), 65536, 1, maxConcurrentUnaryCalls: 1); + var first = connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken); + try + { + await provider.Started.Task.WaitAsync(TestContext.Current.CancellationToken); + provider.Rotate(); + await provider.Disposed.Task.WaitAsync(TestContext.Current.CancellationToken); + first.IsCompleted.ShouldBeFalse(); + var failure = await Should.ThrowAsync(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken)); + failure.Message.ShouldBe("Unary capacity exhausted."); + provider.Sends.ShouldBe(1); + } + finally + { + provider.Release.TrySetResult(); + try { await first; } catch (Exception) { } + } + await WaitForReady(connection); + provider.Sends.ShouldBe(2); + } + private static async Task WaitForReady(GrpcDataConnection connection) + { + for (var attempt = 0; attempt < 100; attempt++) + { + try { await connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken); return; } + catch (InvalidOperationException) { await Task.Delay(50, TestContext.Current.CancellationToken); } + } + throw new TimeoutException("Fresh channel did not recover."); + } + private sealed class IgnoringSecurity : IDataConnectionSecurityProvider + { + private int _version; + public event Action? Changed; + public int Sends; + public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource Disposed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => + ValueTask.FromResult(new(_version.ToString(), "ca", "key", () => new IgnoringHandler(this))); + public void Rotate() { _version++; Changed?.Invoke("link"); } + } + private sealed class IgnoringHandler(IgnoringSecurity owner) : HttpMessageHandler + { + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + if (Interlocked.Increment(ref owner.Sends) == 1) + { owner.Started.TrySetResult(); await owner.Release.Task; } + return Frame(DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, Serving, DataReadiness.Ready, + DataOperations.Read, new HashSet { DataValueKind.Int32 }, Limits, false, 0, "c", false, true))); + } + protected override void Dispose(bool disposing) { if (disposing) owner.Disposed.TrySetResult(); base.Dispose(disposing); } + } + + [Fact] + public async Task Connection_disposal_retains_scope_until_physical_channel_cleanup_finishes() + { + var provider = new BlockingSecurity(); + using var manager = new DataConnectionManager("consumer", 1); + var members = new HashSet { "consumer" }; + manager.ApplyScope(new Dictionary { ["link"] = new(1, members) }); + var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], provider, manager.Acquire("link"), 65536, 1); + try + { + await connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken); + var disposal = connection.DisposeAsync().AsTask(); + await provider.Entered.Task.WaitAsync(TestContext.Current.CancellationToken); + manager.ApplyScope(new Dictionary { ["link"] = new(2, members) }); + disposal.IsCompleted.ShouldBeFalse(); + Should.Throw(() => manager.Acquire("link")); + } + finally { provider.Release.Set(); await connection.DisposeAsync(); } + } + + [Fact] + public async Task Blocked_channel_disposal_remains_charged_during_rotation() + { + var provider = new BlockingSecurity(); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], provider, manager.Acquire("link"), 65536, 1); + try + { + await connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken); + provider.Rotate(); + await provider.Entered.Task.WaitAsync(TestContext.Current.CancellationToken); + await Should.ThrowAsync(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken)); + provider.Created.ShouldBe(1); + } + finally { provider.Release.Set(); } + } + private sealed class BlockingSecurity : IDataConnectionSecurityProvider + { + public event Action? Changed; + public int Created { get; private set; } + public ManualResetEventSlim Release { get; } = new(); + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => + ValueTask.FromResult(new("v1", "ca1", "key", () => { Created++; return new BlockingHandler(this); })); + public void Rotate() => Changed?.Invoke("link"); + } + private sealed class BlockingHandler(BlockingSecurity owner) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => + Task.FromResult(Frame(DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, Serving, DataReadiness.Ready, + DataOperations.Read, new HashSet { DataValueKind.Int32 }, Limits, false, 0, "c", false, true)))); + protected override void Dispose(bool disposing) + { + if (disposing) { owner.Entered.TrySetResult(); owner.Release.Wait(); } + base.Dispose(disposing); + } + } + + [Fact] + public async Task Rotation_during_resolution_cannot_install_stale_security() + { + var provider = new DelayedSecurity(); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], provider, manager.Acquire("link"), 65536, 1); + var pending = connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken); + await provider.Started.Task.WaitAsync(TestContext.Current.CancellationToken); + provider.Rotate(); + provider.Resolved.SetResult(new("old", "old-ca", "key", () => { provider.Installed = true; throw new InvalidOperationException("Stale handler installed."); })); + await Should.ThrowAsync(() => pending); + provider.Installed.ShouldBeFalse(); + } + private sealed class DelayedSecurity : IDataConnectionSecurityProvider + { + public event Action? Changed; + public bool Installed { get; set; } + public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource Resolved { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) + { Started.TrySetResult(); return new(Resolved.Task); } + public void Rotate() => Changed?.Invoke("link"); + } + private sealed class Security(HttpMessageHandler handler) : IDataConnectionSecurityProvider + { + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => + ValueTask.FromResult(new("v1", "ca1", "key", () => handler)); + } + private sealed class WireHandler : HttpMessageHandler + { + public bool LoseWrite { get; init; } + public bool WrongReadServing { get; init; } + public bool ZeroServingGeneration { get; init; } + public bool BadBrowseLease { get; init; } + public int WriteCalls { get; private set; } + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + IMessage message; + if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal)) + message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, ZeroServingGeneration ? Serving with { ServingGeneration = 0 } : Serving, DataReadiness.Ready, + DataOperations.Read | DataOperations.Write, new HashSet { DataValueKind.Int32 }, Limits, + false, 0, "c", false, true)); + else if (request.RequestUri.AbsolutePath.EndsWith("/Write", StringComparison.Ordinal)) + { + WriteCalls++; + if (LoseWrite) throw new HttpRequestException("Lost response after send."); + message = new W.WriteResponse { Serving = DataProtoMapper.EncodeServing(Serving) }; + } + else if (request.RequestUri.AbsolutePath.EndsWith("/Browse", StringComparison.Ordinal)) + { + var browse = DataProtoMapper.EncodeBrowseResponse(new DataBrowseBranch(View, DataItemStatus.Good, [], true, null, + new MetadataLease(Serving.CatalogEpoch, BadBrowseLease ? Serving.AuthorityEpoch + 1 : Serving.AuthorityEpoch, TimeSpan.FromSeconds(1)))); + browse.Serving = DataProtoMapper.EncodeServing(Serving); message = browse; + } + else if (request.RequestUri.AbsolutePath.EndsWith("/Read", StringComparison.Ordinal)) + message = new W.ReadResponse { Serving = DataProtoMapper.EncodeServing(WrongReadServing ? Serving with { Incarnation = "other" } : Serving) }; + else throw new InvalidOperationException("Unexpected call."); + var payload = message.ToByteArray(); + var framed = new byte[payload.Length + 5]; + BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), payload.Length); + payload.CopyTo(framed, 5); + var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent(framed) }; + response.Content.Headers.ContentType = new("application/grpc"); + response.TrailingHeaders.Add("grpc-status", "0"); + return Task.FromResult(response); + } + } + + [Fact] + public void Only_explicit_rejection_can_be_selected_for_mutation_retry() + { + var outcomes = new[] { + new WriteItemResult("rejected", new(DataWriteState.RejectedBeforeDispatch, 1, null)), + new WriteItemResult("unknown", new(DataWriteState.OutcomeUnknown, 1, null)), + new WriteItemResult("accepted", new(DataWriteState.AcceptedUnconfirmed, 1, null)), + new WriteItemResult("success", new(DataWriteState.DriverConfirmedSuccess, 0, null)) }; + GrpcDataConnection.RetryableWriteIndexes(outcomes).ShouldBe(new[] { 0 }); + } + + [Fact] + public void Demotion_is_negative_proof_only_for_an_entirely_rejected_batch_from_the_same_boot() + { + var expected = new ServingIdentity("a", "boot", "Primary", 4, 5); + var demoted = expected with { Role = "Secondary", AuthorityEpoch = 6 }; + var rejected = new WriteItemResult("a", new(DataWriteState.RejectedBeforeDispatch, 1, null)); + var unknown = new WriteItemResult("b", new(DataWriteState.OutcomeUnknown, 1, null)); + GrpcDataConnection.AcceptWriteServing(expected, demoted, [rejected]).ShouldBeTrue(); + GrpcDataConnection.AcceptWriteServing(expected, demoted, [rejected, unknown]).ShouldBeFalse(); + GrpcDataConnection.AcceptWriteServing(expected, demoted with { Incarnation = "new" }, [rejected]).ShouldBeFalse(); + GrpcDataConnection.AcceptWriteServing(expected, demoted with { NodeId = "b" }, [rejected]).ShouldBeFalse(); + GrpcDataConnection.AcceptWriteServing(expected, demoted, []).ShouldBeFalse(); + } + + [Fact] + public void Channel_identity_includes_both_security_versions() + { + var endpoint = new Uri("https://node.example:8443"); + var first = new DataConnectionChannelIdentity("link", endpoint, "credential-1", "trust-1"); + first.ShouldNotBe(first with { CredentialVersion = "credential-2" }); + first.ShouldNotBe(first with { TrustFingerprint = "trust-2" }); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConsumerScopeTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConsumerScopeTests.cs new file mode 100644 index 000000000..930fbf554 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConsumerScopeTests.cs @@ -0,0 +1,84 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")] +public sealed class GrpcDataConsumerScopeTests +{ + private static DataConnectionScopeLease WaitForLease(DataConnectionManager manager) + { + DataConnectionScopeLease? lease = null; + SpinWait.SpinUntil(() => { try { lease = manager.Acquire("link"); return true; } catch (UnauthorizedAccessException) { return false; } }, TimeSpan.FromSeconds(5)).ShouldBeTrue(); + return lease!; + } + + [Fact] + public void Warm_standby_cannot_acquire_and_hot_secondary_cannot_write() + { + DataConnectionRoleAdapter.MayAcquire(RedundancyMode.Warm, WarmRole.Standby, RedundancyRole.Secondary).ShouldBeFalse(); + DataConnectionRoleAdapter.MayAcquire(RedundancyMode.Warm, null, null).ShouldBeFalse(); + DataConnectionRoleAdapter.MayAcquire(RedundancyMode.Warm, WarmRole.Active, RedundancyRole.Primary).ShouldBeTrue(); + DataConnectionRoleAdapter.MayAcquire(RedundancyMode.Hot, null, RedundancyRole.Secondary).ShouldBeTrue(); + DataConnectionRoleAdapter.MayAcquire(RedundancyMode.Hot, null, null).ShouldBeFalse(); + DataConnectionRoleAdapter.MayWrite(RedundancyRole.Secondary).ShouldBeFalse(); + } + + [Fact] + public async Task Blocked_scope_cleanup_stays_charged_and_coalesces_revisions() + { + using var manager = new DataConnectionManager("node-a", 1); + var members = new HashSet { "node-a" }; + manager.ApplyScope(new Dictionary { ["link"] = new(1, members) }); + using var old = manager.Acquire("link"); + using var release = new ManualResetEventSlim(); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var registration = old.CancellationToken.Register(() => { entered.TrySetResult(); release.Wait(); }); + try + { + manager.ApplyScope(new Dictionary { ["link"] = new(2, members) }); + await entered.Task.WaitAsync(TestContext.Current.CancellationToken); + manager.ApplyScope(new Dictionary { ["link"] = new(3, members) }); + Should.Throw(() => manager.Acquire("link")); + } + finally { release.Set(); } + old.Dispose(); + using var replacement = WaitForLease(manager); + replacement.Epoch.ShouldBeGreaterThan(old.Epoch); + } + + [Fact] + public void A_new_connection_revision_retires_old_lifetimes_even_when_consumers_are_unchanged() + { + using var manager = new DataConnectionManager("node-a", 4); + var members = new HashSet { "node-a" }; + manager.ApplyScope(new Dictionary { ["link"] = new(1, members) }); + using var old = manager.Acquire("link"); + manager.ApplyScope(new Dictionary { ["link"] = new(2, members) }); + old.CancellationToken.IsCancellationRequested.ShouldBeTrue(); + old.Dispose(); + using var replacement = WaitForLease(manager); + replacement.Epoch.ShouldBeGreaterThan(old.Epoch); + } + + [Fact] + public void Scope_removal_cancels_existing_lifetime_and_readdition_uses_new_epoch() + { + using var manager = new DataConnectionManager("node-a", 4); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "node-a" } }); + using var first = manager.Acquire("link"); + first.CancellationToken.IsCancellationRequested.ShouldBeFalse(); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "node-b" } }); + first.CancellationToken.IsCancellationRequested.ShouldBeTrue(); + Should.Throw(() => manager.Acquire("link")); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "node-a" } }); + first.Dispose(); + using var next = WaitForLease(manager); + next.Epoch.ShouldBeGreaterThan(first.Epoch); + next.CancellationToken.IsCancellationRequested.ShouldBeFalse(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeploymentActivationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeploymentActivationTests.cs new file mode 100644 index 000000000..a76d91252 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeploymentActivationTests.cs @@ -0,0 +1,481 @@ +using System.Collections.Concurrent; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")] +public sealed class GrpcDataDeploymentActivationTests +{ + private static DataConnection Definition(string id, string secret) => new() + { + DataConnectionId = id, ClusterId = "owner", Revision = 1, Enabled = true, + ConsumerNodeIds = ["node-a"], TargetMode = DataTargetMode.Node, + ExpectedClusterId = "target", ExpectedNodeId = "remote", Endpoints = ["https://remote.example:8443"], + SecretReference = secret, SecretScopeClusterId = "owner", AllowedOperations = DataOperations.Read, + MaxMessageBytes = 65536, MaxBatchItems = 16, MaxPageItems = 16, MaxStreams = 2, + MaxMonitoredItems = 16, MaxPendingBytes = 65536, TimeoutMilliseconds = 5000 + }; + private static DataConnectionDeploymentSnapshot Snapshot(long version, params DataConnection[] connections) => + new(version, $"artifact-{version}", connections); + private static async Task EventuallyAsync(Func condition) + { + for (var i = 0; i < 100; i++) + { + if (condition()) return; + await Task.Delay(20, TestContext.Current.CancellationToken); + } + throw new TimeoutException("Expected deployment state did not arrive."); + } + + [Fact] + public async Task Transient_security_resolution_exception_retries_without_a_change_event() + { + var clock = new ManualTimeProvider(); var security = new FailOnceSecurity(); + var activator = new PausedActivator { PauseFirst = false }; + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", security, activator, 4, clock); + runtime.Apply(Snapshot(1, Definition("link", "secret"))); + await EventuallyAsync(() => runtime.CurrentScopeReady && security.Attempts == 1 && clock.ArmedTimers == 1); + runtime.TryAcquire("link", out _).ShouldBeFalse(); + clock.Advance(TimeSpan.FromMinutes(1)); + await EventuallyAsync(() => runtime.TryAcquire("link", out var lease) && DisposeAndTrue(lease!)); + security.Attempts.ShouldBe(2); + } + [Fact] + public async Task Temporarily_missing_security_material_retries_without_a_change_event() + { + var clock = new ManualTimeProvider(); var security = new NullOnceSecurity(); + var activator = new PausedActivator { PauseFirst = false }; + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", security, activator, 4, clock); + runtime.Apply(Snapshot(1, Definition("link", "secret"))); + await EventuallyAsync(() => runtime.CurrentScopeReady && security.Attempts == 1 && clock.ArmedTimers == 1); + runtime.TryAcquire("link", out _).ShouldBeFalse(); + clock.Advance(TimeSpan.FromMinutes(1)); + await EventuallyAsync(() => runtime.TryAcquire("link", out var lease) && DisposeAndTrue(lease!)); + security.Attempts.ShouldBe(2); + } + private sealed class NullOnceSecurity : IDataConnectionSecurityProvider + { + private int _attempts; + public int Attempts => Volatile.Read(ref _attempts); + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => + ValueTask.FromResult(Interlocked.Increment(ref _attempts) == 1 + ? null : new("1", "trust", "key", () => new EmptyHandler())); + } + + private sealed class FailOnceSecurity : IDataConnectionSecurityProvider + { + private int _attempts; + public int Attempts => Volatile.Read(ref _attempts); + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) + { + if (Interlocked.Increment(ref _attempts) == 1) throw new IOException("transient security store failure"); + return ValueTask.FromResult(new("1", "trust", "key", () => new EmptyHandler())); + } + } + + [Fact] + public async Task Transient_role_read_failure_during_apply_does_not_strand_the_current_scope() + { + var checks = 0; + var activator = new PausedActivator { PauseFirst = false }; + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4, + consumerMayAcquire: () => Interlocked.Increment(ref checks) > 1); + runtime.Apply(Snapshot(1, Definition("link", "secret"))); + await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var lease) && DisposeAndTrue(lease!)); + } + + [Fact] + public async Task Temporarily_unavailable_role_is_retried_on_the_owned_timer() + { + var clock = new ManualTimeProvider(); var role = new RoleFlag(); + var activator = new PausedActivator { PauseFirst = false }; + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4, clock, () => role.Allowed); + runtime.Apply(Snapshot(1, Definition("link", "secret"))); + await EventuallyAsync(() => runtime.CurrentScopeReady && clock.ArmedTimers == 1); + runtime.TryAcquire("link", out _).ShouldBeFalse(); + role.Allowed = true; + clock.Advance(TimeSpan.FromMinutes(1)); + await EventuallyAsync(() => runtime.TryAcquire("link", out var lease) && DisposeAndTrue(lease!)); + } + private sealed class RoleFlag { public volatile bool Allowed; } + + [Fact] + public async Task Transient_scope_store_failure_retries_on_one_clock_timer_without_external_signal() + { + var clock = new ManualTimeProvider(); + var activator = new FailOnceActivator(); + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4, clock); + runtime.Apply(Snapshot(1, Definition("link", "secret"))); + await EventuallyAsync(() => activator.Attempts == 1 && clock.ArmedTimers == 1); + runtime.CurrentScopeReady.ShouldBeFalse(); + clock.Advance(TimeSpan.FromMinutes(1)); + await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var lease) && DisposeAndTrue(lease!)); + activator.Attempts.ShouldBe(2); + } + [Fact] + public async Task Superseding_an_attempt_disarms_its_retry_and_activates_only_the_new_floor() + { + var clock = new ManualTimeProvider(); + var activator = new FailOnceActivator(); + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4, clock); + runtime.Apply(Snapshot(1, Definition("old", "old-ref"))); + await EventuallyAsync(() => activator.Attempts == 1 && clock.ArmedTimers == 1); + runtime.BeginAttempt("artifact-2"); + clock.ArmedTimers.ShouldBe(0); + runtime.Apply(Snapshot(2, Definition("new", "new-ref"))); + await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("new", out var lease) && DisposeAndTrue(lease!)); + clock.Advance(TimeSpan.FromMinutes(1)); + activator.Attempts.ShouldBe(2); + runtime.TryAcquire("old", out _).ShouldBeFalse(); + } + + [Fact] + public async Task Disposal_disarms_the_pending_scope_retry() + { + var clock = new ManualTimeProvider(); + var activator = new FailOnceActivator(); + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4, clock); + runtime.Apply(Snapshot(1, Definition("link", "secret"))); + await EventuallyAsync(() => activator.Attempts == 1 && clock.ArmedTimers == 1); + await runtime.DisposeAsync(); + clock.ArmedTimers.ShouldBe(0); + clock.Advance(TimeSpan.FromMinutes(1)); + activator.Attempts.ShouldBe(1); + } + + private sealed class FailOnceActivator : IDataConnectionScopeActivator + { + private int _attempts; + public int Attempts => Volatile.Read(ref _attempts); + public Task SetScopeAsync(long version, IReadOnlyDictionary allowlist, CancellationToken cancellationToken) + { + if (Interlocked.Increment(ref _attempts) == 1) throw new IOException("transient local store failure"); + return Task.CompletedTask; + } + } + + [Fact] + public async Task Beginning_a_new_artifact_attempt_immediately_denies_old_routes_and_rejects_stale_apply() + { + var activator = new PausedActivator { PauseFirst = false }; + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4); + runtime.Apply(Snapshot(1, Definition("link", "secret"))); + await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var candidate) && DisposeAndTrue(candidate!)); + runtime.TryAcquire("link", out var lease).ShouldBeTrue(); + using (lease!) + { + runtime.BeginAttempt("artifact-2"); + lease!.CancellationToken.IsCancellationRequested.ShouldBeTrue(); + runtime.CurrentScopeReady.ShouldBeFalse(); + runtime.TryAcquire("link", out _).ShouldBeFalse(); + Should.Throw(() => runtime.Apply(Snapshot(1, Definition("link", "secret")))); + } + runtime.Apply(Snapshot(2, Definition("link", "secret"))); + await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var next) && DisposeAndTrue(next!)); + } + + [Fact] + public async Task Replaying_the_accepted_artifact_attempt_keeps_live_routes() + { + var activator = new PausedActivator { PauseFirst = false }; + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4); + runtime.Apply(Snapshot(1, Definition("link", "secret"))); + await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var candidate) && DisposeAndTrue(candidate!)); + runtime.TryAcquire("link", out var lease).ShouldBeTrue(); + using (lease!) + { + runtime.BeginAttempt("artifact-1"); + lease!.CancellationToken.IsCancellationRequested.ShouldBeFalse(); + runtime.CurrentScopeReady.ShouldBeTrue(); + } + } + + [Fact] + public async Task Starting_a_new_attempt_before_first_activation_rejects_an_older_artifact() + { + var activator = new PausedActivator { PauseFirst = false }; + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4); + runtime.BeginAttempt("artifact-2"); + Should.Throw(() => runtime.Apply(Snapshot(1, Definition("old", "secret")))); + runtime.CurrentScopeReady.ShouldBeFalse(); + runtime.TryAcquire("old", out _).ShouldBeFalse(); + } + + [Fact] + public async Task Stale_scope_completion_cannot_publish_its_old_connection() + { + var activator = new PausedActivator(); + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4); + try + { + runtime.Apply(Snapshot(1, Definition("old", "old-ref"))); + await activator.Entered.Task.WaitAsync(TestContext.Current.CancellationToken); + runtime.Apply(Snapshot(2, Definition("new", "new-ref"))); + runtime.CurrentScopeReady.ShouldBeFalse(); + runtime.TryAcquire("old", out _).ShouldBeFalse(); + } + finally { activator.Release.TrySetResult(); } + await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("new", out var lease) && DisposeAndTrue(lease!)); + runtime.TryAcquire("old", out _).ShouldBeFalse(); + activator.AppliedVersions.ShouldBe(new long[] { 1, 2 }); + } + + [Fact] + public async Task Scope_removal_cancels_existing_lease_before_the_new_floor_finishes() + { + var activator = new PausedActivator { PauseFirst = false, PauseSecond = true }; + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4); + runtime.Apply(Snapshot(1, Definition("link", "secret"))); + await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var value) && DisposeAndTrue(value!)); + runtime.TryAcquire("link", out var lease).ShouldBeTrue(); + using (lease!) + { + try + { + runtime.Apply(Snapshot(2)); + lease!.CancellationToken.IsCancellationRequested.ShouldBeTrue(); + runtime.TryAcquire("link", out _).ShouldBeFalse(); + runtime.CurrentScopeReady.ShouldBeFalse(); + await activator.Entered.Task.WaitAsync(TestContext.Current.CancellationToken); + } + finally { activator.Release.TrySetResult(); } + } + await EventuallyAsync(() => runtime.CurrentScopeReady); + } + + [Fact] + public async Task Desired_definitions_are_copied_before_any_asynchronous_activation() + { + var activator = new PausedActivator(); + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4); + var definition = Definition("link", "secret"); + try + { + runtime.Apply(Snapshot(1, definition)); + await activator.Entered.Task.WaitAsync(TestContext.Current.CancellationToken); + definition.SecretReference = "changed"; + definition.ExpectedNodeId = "forged"; + definition.Endpoints.Clear(); + } + finally { activator.Release.TrySetResult(); } + await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var lease) && DisposeAndTrue(lease!)); + activator.Scopes[1]["link"].ShouldBe("secret"); + runtime.TryAcquire("link", out var current).ShouldBeTrue(); + using (current!) current!.Connection.Target.ExpectedNodeId.ShouldBe("remote"); + } + + [Fact] + public async Task Same_scope_version_with_different_contents_is_rejected() + { + var activator = new PausedActivator(); + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4); + try + { + runtime.Apply(Snapshot(1, Definition("link", "secret"))); + await activator.Entered.Task.WaitAsync(TestContext.Current.CancellationToken); + Should.Throw(() => runtime.Apply(Snapshot(1, Definition("link", "other-secret")))); + } + finally { activator.Release.TrySetResult(); } + } + + [Fact] + public async Task Consumer_redundancy_mode_is_preserved_from_the_validated_snapshot() + { + var activator = new PausedActivator { PauseFirst = false }; + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4); + runtime.Apply(new DataConnectionDeploymentSnapshot(1, "artifact-1", [Definition("link", "secret")], RedundancyMode.Hot)); + runtime.CurrentConsumerMode.ShouldBe(RedundancyMode.Hot); + await EventuallyAsync(() => runtime.CurrentScopeReady); + } + + [Fact] + public async Task Replaying_identical_artifact_does_not_retire_a_live_connection() + { + var activator = new PausedActivator { PauseFirst = false }; + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4); + runtime.Apply(Snapshot(1, Definition("link", "secret"))); + await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var candidate) && DisposeAndTrue(candidate!)); + runtime.TryAcquire("link", out var lease).ShouldBeTrue(); + using (lease!) + { + runtime.Apply(Snapshot(1, Definition("link", "secret"))); + lease!.CancellationToken.IsCancellationRequested.ShouldBeFalse(); + runtime.CurrentScopeReady.ShouldBeTrue(); + activator.AppliedVersions.ShouldBe(new long[] { 1 }); + } + } + + [Fact] + public async Task Same_artifact_revision_cannot_replace_connection_definitions() + { + var activator = new PausedActivator { PauseFirst = false }; + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4); + runtime.Apply(Snapshot(1, Definition("link", "secret"))); + await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var candidate) && DisposeAndTrue(candidate!)); + runtime.TryAcquire("link", out var lease).ShouldBeTrue(); + using (lease!) + { + var changed = Definition("link", "secret"); + changed.Endpoints = ["https://different.example:8443"]; + Should.Throw(() => runtime.Apply(Snapshot(1, changed))); + lease!.CancellationToken.IsCancellationRequested.ShouldBeFalse(); + runtime.CurrentScopeReady.ShouldBeTrue(); + } + } + + [Fact] + public async Task Transient_role_contention_during_one_credential_change_does_not_strand_other_connections() + { + var clock = new ManualTimeProvider(); var role = new RoleFlag { Allowed = true }; + var security = new MutableSecurity(); var activator = new PausedActivator { PauseFirst = false }; + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", security, activator, 4, clock, () => role.Allowed); + runtime.Apply(Snapshot(1, Definition("one", "secret-one"), Definition("two", "secret-two"))); + await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("one", out var a) && DisposeAndTrue(a!) && + runtime.TryAcquire("two", out var b) && DisposeAndTrue(b!)); + runtime.TryAcquire("one", out var first).ShouldBeTrue(); + runtime.TryAcquire("two", out var second).ShouldBeTrue(); + using (first!) using (second!) + { + role.Allowed = false; + security.Rotate("one"); + role.Allowed = true; + first!.CancellationToken.IsCancellationRequested.ShouldBeTrue(); + second!.CancellationToken.IsCancellationRequested.ShouldBeFalse(); + runtime.TryAcquire("two", out var unaffected).ShouldBeTrue(); + unaffected!.Dispose(); + } + await EventuallyAsync(() => clock.ArmedTimers > 0 || runtime.TryAcquire("one", out var value) && DisposeAndTrue(value!)); + if (clock.ArmedTimers > 0) clock.Advance(TimeSpan.FromMinutes(1)); + await EventuallyAsync(() => runtime.TryAcquire("one", out var recovered) && DisposeAndTrue(recovered!)); + } + + [Fact] + public async Task Credential_change_drains_only_affected_connection_before_reactivation() + { + var security = new MutableSecurity(); + var activator = new PausedActivator { PauseFirst = false }; + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", security, activator, 4); + runtime.Apply(Snapshot(1, Definition("one", "secret-one"), Definition("two", "secret-two"))); + await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("one", out var a) && DisposeAndTrue(a!) && + runtime.TryAcquire("two", out var b) && DisposeAndTrue(b!)); + runtime.TryAcquire("one", out var first).ShouldBeTrue(); + runtime.TryAcquire("two", out var second).ShouldBeTrue(); + using (first!) using (second!) + { + security.Rotate("one"); + first!.CancellationToken.IsCancellationRequested.ShouldBeTrue(); + second!.CancellationToken.IsCancellationRequested.ShouldBeFalse(); + runtime.CurrentScopeReady.ShouldBeTrue(); + } + } + private sealed class MutableSecurity : IDataConnectionSecurityProvider + { + public event Action? Changed; + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => + ValueTask.FromResult(new("1", "trust", "key", () => new EmptyHandler())); + public void Rotate(string id) => Changed?.Invoke(id); + } + + [Fact] + public async Task Deployed_operation_and_batch_limits_apply_before_any_network_call() + { + var definition = Definition("link", "secret"); + definition.MaxBatchItems = 1; + var activator = new PausedActivator { PauseFirst = false }; + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4); + runtime.Apply(Snapshot(1, definition)); + await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var candidate) && DisposeAndTrue(candidate!)); + runtime.TryAcquire("link", out var lease).ShouldBeTrue(); + using (lease!) + { + var view = new DataView(new("target", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x"); + using var value = DataValue.FromScalar(DataValueKind.Int32, 1); + var budget = new DataBudget(TimeSpan.FromSeconds(1), 4, 1024); + await Should.ThrowAsync(() => lease!.Connection.WriteAsync(new([new("a", "op", view, value, 1, "boot", TimeSpan.FromSeconds(1))], budget), TestContext.Current.CancellationToken)); + await Should.ThrowAsync(() => lease!.Connection.ReadAsync(new([new("a", view, null), new("b", view, null)], budget), TestContext.Current.CancellationToken)); + } + } + + [Fact] + public async Task Warm_standby_drains_existing_routes_and_keeps_durable_scope_ready() + { + var active = true; + var activator = new PausedActivator { PauseFirst = false }; + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4, consumerMayAcquire: () => active); + runtime.Apply(Snapshot(1, Definition("link", "secret"))); + await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var candidate) && DisposeAndTrue(candidate!)); + runtime.TryAcquire("link", out var lease).ShouldBeTrue(); + using (lease!) + { + active = false; + runtime.NotifyConsumerRoleChanged(); + lease!.CancellationToken.IsCancellationRequested.ShouldBeTrue(); + runtime.TryAcquire("link", out _).ShouldBeFalse(); + runtime.CurrentScopeReady.ShouldBeTrue(); + } + } + + [Fact] + public async Task Missing_one_credential_does_not_hold_other_connections_or_the_scope_unready() + { + var activator = new PausedActivator { PauseFirst = false }; + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security("missing"), activator, 4); + runtime.Apply(Snapshot(1, Definition("ready", "a"), Definition("missing", "b"))); + await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("ready", out var lease) && DisposeAndTrue(lease!)); + runtime.TryAcquire("missing", out _).ShouldBeFalse(); + } + + [Fact] + public async Task Invalid_scope_version_is_denied_before_any_activation() + { + var activator = new PausedActivator { PauseFirst = false }; + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4); + Should.Throw(() => runtime.Apply(Snapshot(0, Definition("link", "secret")))); + runtime.CurrentScopeReady.ShouldBeFalse(); + runtime.TryAcquire("link", out _).ShouldBeFalse(); + activator.AppliedVersions.ShouldBeEmpty(); + } + + private static bool DisposeAndTrue(IDisposable lease) { lease.Dispose(); return true; } + private sealed class Security(string? missing = null) : IDataConnectionSecurityProvider + { + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => + ValueTask.FromResult(string.Equals(connectionId, missing, StringComparison.OrdinalIgnoreCase) + ? null : new("1", "trust", "key", () => new EmptyHandler())); + } + private sealed class EmptyHandler : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => + throw new InvalidOperationException("This activation test must not use the network."); + } + private sealed class PausedActivator : IDataConnectionScopeActivator + { + public bool PauseFirst { get; init; } = true; + public bool PauseSecond { get; init; } + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly ConcurrentQueue _versions = new(); + public long[] AppliedVersions => _versions.ToArray(); + public ConcurrentDictionary> Scopes { get; } = new(); + public async Task SetScopeAsync(long version, IReadOnlyDictionary allowlist, CancellationToken cancellationToken) + { + _versions.Enqueue(version); + Scopes[version] = new Dictionary(allowlist, StringComparer.OrdinalIgnoreCase); + if (version == 1 && PauseFirst || version == 2 && PauseSecond) + { + Entered.TrySetResult(); + // Deliberately ignore cancellation to exercise stale-completion fencing. + await Release.Task; + } + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDriverOutcomeTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDriverOutcomeTests.cs index b02fe8fd9..7ff49ecbe 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDriverOutcomeTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDriverOutcomeTests.cs @@ -58,6 +58,8 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase [InlineData("host-membership-event")] [InlineData("incarnation")] [InlineData("current-key-expiry-fence")] + [InlineData("warm-standby-fence")] + [InlineData("warm-return-active-fence")] public async Task Real_catalog_policy_and_actor_revalidate_at_the_driver_invocation(string change) { var clock = new PolicyCompletionClock(); @@ -133,7 +135,7 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase var proof = new WriteRouteProof(admission, new(node.Scope.ClusterId, node.Scope.Kind, node.Scope.Segments.ToImmutableArray()), node.EntityKind, node.EntityId, node.Source, "driver", target.DriverReference, - target.RouteGeneration, role.PrimaryGeneration); + target.RouteGeneration, role.PrimaryGeneration, catalog.Serving); var ticket = new WriteAdmissionTicket(proof, DataValue.FromScalar(DataValueKind.Int32, 7), now); var registry = new WriteOperationRegistry("serving", 8, 8192, TimeSpan.FromMinutes(1), clock); var claim = registry.Claim("peer", "real-gate", "serving", SHA256.HashData([1, 2, 3])).Claim.ShouldNotBeNull(); @@ -157,6 +159,8 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase case "role": role.PublishPrimaryRole(false); role.PublishPrimaryRole(true); break; case "incarnation": routes.RetireDriver("driver", incarnation); routes.BeginDriverIncarnation("driver"); break; case "current-key-expiry-fence": + case "warm-standby-fence": + case "warm-return-active-fence": { using var releaseFence = new ManualResetEventSlim(); var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); @@ -171,7 +175,12 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase // The wrapped evaluator arms a signal for the *last* policy UTC read. It returns // the captured pre-expiry instant even if the test advances the clock immediately. await clock.AfterPolicyUtc.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken); - clock.Advance(TimeSpan.FromSeconds(2)); + if (change == "current-key-expiry-fence") clock.Advance(TimeSpan.FromSeconds(2)); + else + { + serving = serving with { Role = change == "warm-standby-fence" ? "Standby" : "Primary", ServingGeneration = 2 }; + role.PrimaryGeneration.ShouldBe(proof.PrimaryGeneration, "the driver's Primary verdict has not changed"); + } } finally { releaseFence.Set(); await holder.WaitAsync(Timeout, TestContext.Current.CancellationToken); } break; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataEndpointSelectionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataEndpointSelectionTests.cs new file mode 100644 index 000000000..8ad01cfb1 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataEndpointSelectionTests.cs @@ -0,0 +1,34 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")] +public sealed class GrpcDataEndpointSelectionTests +{ + private static readonly DataLimits Limits = new(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)); + private static DataCapabilities Cap(string node, string role, DataReadiness ready = DataReadiness.Ready, string cluster = "c") => + new(1, 1, new(node, "boot", role, 1, 1, 1), ready, DataOperations.Read, new HashSet(), Limits, false, 0, cluster); + + [Fact] + public void Cluster_requires_authenticated_ready_primary_and_expected_cluster() + { + var target = new DataTarget(DataTargetMode.Cluster, "c", null); + ClusterEndpointSelector.IsEligible(target, Cap("a", "Primary", DataReadiness.Unavailable), false).ShouldBeFalse(); + ClusterEndpointSelector.IsEligible(target, Cap("a", "Primary", cluster: "other"), false).ShouldBeFalse(); + ClusterEndpointSelector.IsEligible(target, Cap("a", "Secondary"), false).ShouldBeFalse(); + ClusterEndpointSelector.IsEligible(target, Cap("a", "Unknown"), false).ShouldBeFalse(); + ClusterEndpointSelector.IsEligible(target, Cap("a", "Primary"), false).ShouldBeTrue(); + } + + [Fact] + public void Pinned_node_cannot_substitute_partner_and_secondary_requires_explicit_read_consistency() + { + var target = new DataTarget(DataTargetMode.Node, "c", "a", DataConsistency.ReadyReplica); + ClusterEndpointSelector.IsEligible(target, Cap("b", "Primary"), true).ShouldBeFalse(); + ClusterEndpointSelector.IsEligible(target, Cap("a", "Secondary"), true).ShouldBeFalse(); + ClusterEndpointSelector.IsEligible(target, Cap("a", "Secondary"), false).ShouldBeTrue(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalCompositionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalCompositionTests.cs new file mode 100644 index 000000000..427e80d44 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalCompositionTests.cs @@ -0,0 +1,42 @@ +using Akka.Actor; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")] +public sealed class GrpcDataLocalCompositionTests : RuntimeActorTestBase +{ + private sealed class PassiveActor : ReceiveActor { } + + [Fact] + public void One_composition_shares_the_given_process_capacity_and_rejects_mismatched_clock() + { + var clock = TimeProvider.System; + var fence = new DataWriteDispatchFence(); var authority = new DataPlaneAuthorityState(fence); + var activation = new CatalogActivation(fence); var role = new RedundancyRoleView(fence); + var serving = new ServingIdentity("node", "boot", "Primary", 0, 0); + var catalog = new LocalCatalogCoordinator(activation, authority, () => serving); + var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1)); + var caps = new DataCapabilitiesProvider("cluster", () => serving, () => false, limits); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, clock), clock); + var bounds = new DriverWriteBounds(TimeSpan.FromMilliseconds(300)); + var writes = new DataWriteRuntime(catalog, activation, authority, policy, caps, role, clock, bounds, "boot", 16, 16_384, 16_384, 4, TimeSpan.FromMinutes(1)); + using var hub = HubTest.Create(clock: clock, bytes: 1_000_000); + var host = Sys.ActorOf(Props.Create(() => new PassiveActor())); + var shared = new SubscriptionAcquisitionCapacity(8); + var config = new LocalDataRuntimeLimits(8, 128, 8, 4, 1_000_000, 16, 16, 100_000, TimeSpan.FromMinutes(5), TimeSpan.FromSeconds(2)); + using var runtime = new LocalDataRuntimeComposition(catalog, hub, policy, caps, clock, writes, host, shared, config); + runtime.AcquisitionCapacity.ShouldBeSameAs(shared); + runtime.Services.ShouldNotBeNull(); + runtime.Services.Clock.ShouldBeSameAs(clock); + Should.Throw(() => new LocalDataRuntimeComposition(catalog, hub, policy, caps, + new ManualTimeProvider(), writes, host, shared, config)); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs index 9d7244876..529408bd2 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs @@ -12,6 +12,23 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; [Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P04")] public sealed class GrpcDataLocalConnectionTests { + [Fact] + public async Task Browse_lease_never_outlives_the_original_target_credential() + { + using var fixture = new LocalDataFixture(additionalRawNodes: 1); + var context = fixture.Context with { CredentialExpiresUtc = fixture.Clock.GetUtcNow().AddSeconds(1) }; + await using var connection = fixture.Services.Create(context, new(DataTargetMode.Node, "cluster", "node-a")); + var budget = LocalDataFixture.Budget with { MaxItems = 1 }; + var branch = await connection.BrowseAsync(new(fixture.Root, null, null, budget), TestContext.Current.CancellationToken); + branch.Status.ShouldBe(DataItemStatus.Good); + branch.Lease!.Duration.ShouldBeLessThanOrEqualTo(TimeSpan.FromSeconds(1)); + branch.Continuation.ShouldNotBeNull(); + fixture.Clock.Advance(TimeSpan.FromSeconds(2)); + var expired = await connection.BrowseAsync(new(fixture.Root, null, branch.Continuation, budget), TestContext.Current.CancellationToken); + expired.Status.ShouldBe(DataItemStatus.Denied); + expired.Items.ShouldBeEmpty(); + } + [Fact] public async Task Metadata_bootstrap_resolves_address_and_never_uses_the_claimed_subject_as_authority() { @@ -110,8 +127,9 @@ internal sealed class LocalDataFixture : IDisposable internal LocalDataFixture(int additionalRawNodes = 0, Func? subscriptions = null, Func? targetSubscriptions = null, - bool advanceAuthority = false) + bool advanceAuthority = false, string role = "Primary") { + Serving = Serving with { Role = role }; Hub = HubTest.Create(clock: Clock, bytes: 1_000_000); Hub.TryBind(Ticket).ShouldBeTrue(); var key = new ApiKey { ApiKeyId = "peer-key", Name = "peer-key", Principal = "peer", SecretHash = "hash", Enabled = true }; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalRoleTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalRoleTests.cs new file mode 100644 index 000000000..20b42d89b --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalRoleTests.cs @@ -0,0 +1,53 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")] +public sealed class GrpcDataLocalRoleTests +{ + [Fact] + public async Task Cluster_and_default_node_requests_cannot_read_a_secondary() + { + using var fixture = new LocalDataFixture(role: "Secondary"); + fixture.Publish(7); + foreach (var target in new[] { new DataTarget(DataTargetMode.Node, "cluster", "node-a"), + new DataTarget(DataTargetMode.Cluster, "cluster", null) }) + { + await using var connection = fixture.Services.Create(fixture.Context, target); + var caps = await connection.GetCapabilitiesAsync(LocalDataFixture.Budget, TestContext.Current.CancellationToken); + caps.Operations.ShouldBe(DataOperations.None); + caps.Readiness.ShouldBe(DataReadiness.Unavailable); + await Should.ThrowAsync(() => connection.ReadAsync( + new([new("read", fixture.Raw, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken)); + ((IDataConnectionPublicationGate)connection).CanPublish(fixture.Serving).ShouldBeFalse(); + } + } + + [Theory] + [InlineData("Unknown")] + [InlineData("Stopped")] + public async Task Ready_replica_never_treats_an_arbitrary_nonprimary_role_as_a_ready_secondary(string role) + { + using var fixture = new LocalDataFixture(role: role); + await using var connection = fixture.Services.Create(fixture.Context, + new(DataTargetMode.Node, "cluster", "node-a", DataConsistency.ReadyReplica)); + var caps = await connection.GetCapabilitiesAsync(LocalDataFixture.Budget, TestContext.Current.CancellationToken); + caps.Readiness.ShouldBe(DataReadiness.Unavailable); + ((IDataConnectionPublicationGate)connection).CanPublish(fixture.Serving).ShouldBeFalse(); + } + + [Fact] + public async Task Explicit_node_ready_replica_reads_its_own_cache() + { + using var fixture = new LocalDataFixture(role: "Secondary"); + fixture.Publish(7); + await using var connection = fixture.Services.Create(fixture.Context, + new(DataTargetMode.Node, "cluster", "node-a", DataConsistency.ReadyReplica)); + var results = await connection.ReadAsync(new([new("read", fixture.Raw, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken); + using var result = results.ShouldHaveSingleItem(); + result.Status.ShouldBe(DataItemStatus.Good); + result.Sample!.Value.GetScalar().ShouldBe(7); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataStreamOrderingTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataStreamOrderingTests.cs index caa60b108..cf552a5ca 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataStreamOrderingTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataStreamOrderingTests.cs @@ -513,8 +513,13 @@ public sealed class GrpcDataStreamOrderingTests using (var first = reader.Current.ShouldBeOfType()) first.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(1); fixture.Clock.Advance(TimeSpan.FromSeconds(2)); - HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); - fixture.Hub.ProcessPending(); + // Arrange successful ingress; nonblocking contention deliberately invalidates a + // source and is covered separately from frozen-snapshot/delta ordering. + fixture.Hub.WithPartitionLockForTest(fixture.Ticket.Key, () => + { + HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); + fixture.Hub.ProcessPending(); + }); var frozen = 1; while (true) { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataTransportPublicationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataTransportPublicationTests.cs new file mode 100644 index 000000000..ce98a52d8 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataTransportPublicationTests.cs @@ -0,0 +1,146 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P07")] +public sealed class GrpcDataTransportPublicationTests +{ + [Fact(Timeout = 30000)] + public async Task Valid_late_publication_has_one_handoff_and_allows_snapshot_end() + { + using var fixture = CreateFixture(out _); + fixture.Publish(1); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var sink = new DelayedMarshallerSink(false); + var writer = ((IDataSubscriptionTransport)subscription).RunDeliveryAsync(sink, TestContext.Current.CancellationToken); + await Open(subscription, fixture); + try { await sink.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); } + finally { sink.Release.TrySetResult(); } + await sink.SnapshotEnd.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + sink.Bound.ShouldBeTrue(); + sink.BlockedHandoffs.ShouldBe(1); + await subscription.DisposeAsync(); + await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + } + + [Fact(Timeout = 30000)] + public async Task Ignored_cancellation_keeps_the_prepared_frame_and_work_charged_until_physical_write_finishes() + { + using var fixture = CreateFixture(out var capacity); + fixture.Publish(1); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var sink = new DelayedMarshallerSink(false); + var writer = ((IDataSubscriptionTransport)subscription).RunDeliveryAsync(sink, TestContext.Current.CancellationToken); + await Open(subscription, fixture); + try + { + await sink.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + await subscription.DisposeAsync(); + capacity.ActiveOperations.ShouldBe(1); + sink.BlockedPreparedDisposed.Task.IsCompleted.ShouldBeFalse(); + } + finally { sink.Release.TrySetResult(); } + await sink.BlockedPreparedDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + capacity.ActiveOperations.ShouldBe(0); + sink.BlockedHandoffs.ShouldBe(0); + await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + } + + private static LocalDataFixture CreateFixture(out SubscriptionTransportCapacity capacity) + { + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var shared = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + fixture = new LocalDataFixture(targetSubscriptions: (caller, target) => + new LocalSubscriptionService(fixture!.Services, caller, target, demand, limits, shared)); + capacity = shared; + return fixture; + } + private static Task Open(IDataSubscription subscription, LocalDataFixture fixture) => subscription.SendAsync( + new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10), + [new("one", fixture.Raw, new(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null))], + false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken); + + [Theory(Timeout = 30000)] + [InlineData(false)] + [InlineData(true)] + public async Task Late_transport_serialization_revalidates_source_without_a_catalog_change(bool blockEnd) + { + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(targetSubscriptions: (caller, target) => + new LocalSubscriptionService(fixture!.Services, caller, target, demand, limits, capacity))) + { + fixture.Publish(1); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + var sink = new DelayedMarshallerSink(blockEnd); + var writer = ((IDataSubscriptionTransport)subscription).RunDeliveryAsync(sink, TestContext.Current.CancellationToken); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10), + [new("one", fixture.Raw, new(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null))], + false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken); + try + { + await sink.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.Hub.Invalidate(fixture.Ticket, "Late transport invalidation"); + } + finally { sink.Release.TrySetResult(); } + await sink.Settled.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + sink.Bound.ShouldBeTrue(); + sink.BlockedHandoffs.ShouldBe(0); + await subscription.DisposeAsync(); + await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + } + } + + private sealed class DelayedMarshallerSink(bool blockEnd) : IDataSubscriptionDeliverySink + { + internal readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource Release = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource Settled = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource SnapshotEnd = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource BlockedPreparedDisposed = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal bool Bound; + internal int BlockedHandoffs; + public ValueTask PrepareAsync(DataSubscriptionFrame frame, long reservedBytes, + CancellationToken cancellationToken) => ValueTask.FromResult(new Prepared(frame, + () => { if (Blocked(frame)) BlockedPreparedDisposed.TrySetResult(); })); + private bool Blocked(DataSubscriptionFrame frame) => blockEnd + ? frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd } + : frame is DataSubscriptionValues; + public async ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken) + { + var item = (Prepared)prepared; + if (!Blocked(item.Frame)) + { + if (item.Frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) SnapshotEnd.TrySetResult(); + return; + } + Bound = item.Guard is not null; + Entered.TrySetResult(); + try + { + await Release.Task; // Models ASP.NET starting the response before invoking its marshaller. + if (item.Guard is null || !item.Guard()) throw new InvalidOperationException("Publication refused."); + BlockedHandoffs++; + } + finally { Settled.TrySetResult(); } + } + private sealed class Prepared(DataSubscriptionFrame frame, Action disposed) : IDataPreparedSubscriptionPublication + { + internal DataSubscriptionFrame Frame { get; } = frame; + internal Func? Guard; + public long RetainedBytes => 1; + public void SetPublicationGuard(Func guard) => Guard = guard; + public void Dispose() => disposed(); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorPrimaryRoleSourceTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorPrimaryRoleSourceTests.cs index 6cc379d15..f4b541331 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorPrimaryRoleSourceTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorPrimaryRoleSourceTests.cs @@ -6,6 +6,7 @@ using ZB.MOM.WW.OtOpcUa.Commons.Types; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; +using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; @@ -23,6 +24,57 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; /// public sealed class DriverHostActorPrimaryRoleSourceTests : RuntimeActorTestBase { + [Fact] + public void An_accepted_snapshot_missing_local_node_retires_observed_primary_provenance() + { + var view = new RedundancyRoleView(); + var host = SpawnHost(view, () => 2); + host.Tell(Snapshot(RedundancyRole.Primary)); + AwaitAssert(() => view.DataServingRole.ShouldBe("Primary"), duration: Timeout, cancellationToken: TestContext.Current.CancellationToken); + var generation = view.PrimaryGeneration; + host.Tell(new RedundancyStateChanged([], CorrelationId.NewId())); + AwaitAssert(() => + { + view.DataServingRole.ShouldBe("Unknown"); + view.PrimaryGeneration.ShouldBeGreaterThan(generation); + }, duration: Timeout, cancellationToken: TestContext.Current.CancellationToken); + } + + [Fact] + public void Stopping_the_actual_role_publisher_retires_its_serving_proof() + { + var view = new RedundancyRoleView(); + var host = SpawnHost(view, () => 2); + host.Tell(Snapshot(RedundancyRole.Primary)); + AwaitAssert(() => view.DataServingRole.ShouldBe("Primary"), duration: Timeout, cancellationToken: TestContext.Current.CancellationToken); + var watcher = CreateTestProbe(); watcher.Watch(host); Sys.Stop(host); + watcher.ExpectTerminated(host, Timeout, cancellationToken: TestContext.Current.CancellationToken); + view.DataServingRole.ShouldBe("Unknown"); + } + + [Fact] + public async Task An_old_publisher_cannot_overwrite_or_retire_its_replacement() + { + var view = new RedundancyRoleView(); + var old = SpawnHost(view, () => 2); + old.Tell(Snapshot(RedundancyRole.Primary)); + AwaitAssert(() => view.DataServingRole.ShouldBe("Primary"), duration: Timeout, cancellationToken: TestContext.Current.CancellationToken); + var generation = view.PrimaryGeneration; + var current = SpawnHost(view, () => 2); + current.Tell(Snapshot(RedundancyRole.Primary)); + AwaitAssert(() => + { + view.PrimaryGeneration.ShouldBeGreaterThan(generation); + view.DataServingRole.ShouldBe("Primary"); + }, duration: Timeout, cancellationToken: TestContext.Current.CancellationToken); + old.Tell(Snapshot(RedundancyRole.Secondary)); + await old.Ask(new DriverHostActor.GetOpenAcquisitionCountForTest(), + Timeout, TestContext.Current.CancellationToken); + view.DataServingRole.ShouldBe("Primary"); + var watcher = CreateTestProbe(); watcher.Watch(old); Sys.Stop(old); + watcher.ExpectTerminated(old, Timeout, cancellationToken: TestContext.Current.CancellationToken); + view.DataServingRole.ShouldBe("Primary"); + } private static readonly NodeId TestNode = NodeId.Parse("driver-primary-source-test"); private static readonly TimeSpan Timeout = PresenceBudget; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorWarmTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorWarmTests.cs index 1c83c8f81..3f3201218 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorWarmTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorWarmTests.cs @@ -8,7 +8,10 @@ using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Commons.Types; using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa; +using ZB.MOM.WW.OtOpcUa.Runtime.Health; using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy; using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Redundancy; @@ -64,6 +67,98 @@ public sealed class OpcUaPublishActorWarmTests : RuntimeActorTestBase private static readonly string[] Promotion = ["proj:False", "queue:False", "delivery:False", "alarms:False", "refresh", "SL:250"]; private static readonly string[] Demotion = ["SL:90", "delivery:True", "alarms:True", "proj:True", "queue:True"]; + [Fact, Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")] + public void Data_warm_verdict_stays_unknown_until_revisioned_snapshot_and_tracks_actual_transitions() + { + var view = new DataConnectionWarmRoleView(new DataWriteDispatchFence()); + var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests( + serviceLevel: new LoggingPublisher(_log), localNode: Self, dbLess: true, + healthTickInterval: TimeSpan.FromMinutes(5), redundancy: new WarmRedundancySettings(OpcUaRedundancyMode.Warm), + standbyProjection: new RecordingProjection(_log), dataWarmRole: view)); + view.CurrentRole.ShouldBeNull(); + actor.Tell(Snapshot(Self, revisioned: false)); + AwaitLogEndsWith("SL:90"); + view.CurrentRole.ShouldBeNull(); + actor.Tell(Snapshot(Self)); + AwaitAssert(() => view.CurrentRole.ShouldBe(WarmRole.Active), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + actor.Tell(Snapshot(Other)); + AwaitAssert(() => view.CurrentRole.ShouldBe(WarmRole.Standby), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + Watch(actor); Sys.Stop(actor); ExpectTerminated(actor, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + AwaitAssert(() => view.CurrentRole.ShouldBeNull(), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + } + + [Fact, Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")] + public void A_primary_snapshot_is_not_a_warm_active_verdict_after_endpoint_failure() + { + var view = new DataConnectionWarmRoleView(new DataWriteDispatchFence()); + var endpoint = new OpcUaEndpointState(); endpoint.MarkStarted(); + var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests( + serviceLevel: new LoggingPublisher(_log), localNode: Self, dbLess: true, + healthTickInterval: TimeSpan.FromMilliseconds(25), endpointState: endpoint, + redundancy: new WarmRedundancySettings(OpcUaRedundancyMode.Warm), + standbyProjection: new RecordingProjection(_log), dataWarmRole: view)); + actor.Tell(Snapshot(Self)); + AwaitAssert(() => view.CurrentRole.ShouldBe(WarmRole.Active), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + endpoint.MarkFailed("test failure"); + AwaitAssert(() => view.CurrentRole.ShouldBe(WarmRole.Standby), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + } + + [Fact, Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")] + public async Task Warm_demotion_invalidates_import_role_before_a_blocked_projection_callback() + { + var view = new DataConnectionWarmRoleView(new DataWriteDispatchFence()); + using var publisher = new BlockingStandbyPublisher(); + var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests( + serviceLevel: publisher, localNode: Self, dbLess: true, healthTickInterval: TimeSpan.FromMinutes(5), + redundancy: new WarmRedundancySettings(OpcUaRedundancyMode.Warm), + standbyProjection: new RecordingProjection(_log), dataWarmRole: view)); + try + { + actor.Tell(Snapshot(Self)); + AwaitAssert(() => view.CurrentRole.ShouldBe(WarmRole.Active), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + publisher.Block = true; + actor.Tell(Snapshot(Other)); + await publisher.Entered.Task.WaitAsync(TestContext.Current.CancellationToken); + view.CurrentRole.ShouldBe(WarmRole.Standby); + } + finally { publisher.Release.Set(); Watch(actor); Sys.Stop(actor); ExpectTerminated(actor, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); } + } + private sealed class BlockingStandbyPublisher : IServiceLevelPublisher, IDisposable + { + public volatile bool Block; + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public ManualResetEventSlim Release { get; } = new(); + public void Publish(byte level) + { + if (Block && level < 100) { Entered.TrySetResult(); Release.Wait(); } + } + public void Dispose() => Release.Dispose(); + } + + [Fact, Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")] + public void Superseded_warm_actor_cannot_publish_or_retire_the_new_owner() + { + var view = new DataConnectionWarmRoleView(new DataWriteDispatchFence()); + IActorRef NewActor() => Sys.ActorOf(OpcUaPublishActor.PropsForTests( + serviceLevel: new LoggingPublisher(_log), localNode: Self, dbLess: true, + healthTickInterval: TimeSpan.FromMinutes(5), redundancy: new WarmRedundancySettings(OpcUaRedundancyMode.Warm), + standbyProjection: new RecordingProjection(_log), dataWarmRole: view)); + var first = NewActor(); first.Tell(Snapshot(Self)); + AwaitAssert(() => view.CurrentRole.ShouldBe(WarmRole.Active), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var oldGeneration = view.Generation; + var second = NewActor(); + AwaitAssert(() => { view.Generation.ShouldBeGreaterThan(oldGeneration); view.CurrentRole.ShouldBeNull(); }, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + first.Tell(Snapshot(Other)); + AwaitLogEndsWith(Demotion); + view.CurrentRole.ShouldBeNull(); + second.Tell(Snapshot(Self)); + AwaitAssert(() => view.CurrentRole.ShouldBe(WarmRole.Active), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + Watch(first); Sys.Stop(first); ExpectTerminated(first, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + view.CurrentRole.ShouldBe(WarmRole.Active); + Watch(second); Sys.Stop(second); ExpectTerminated(second, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + AwaitAssert(() => view.CurrentRole.ShouldBeNull(), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + } + [Fact] public void Promotion_and_demotion_run_in_the_spec_order() {