From 29fec57fac6fa21b9b51c92ada49abb93a7f3d8a Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 17 Nov 2026 22:01:26 -0500 Subject: [PATCH] test: validate grpc data connections with local docker and opcua cli --- docs/DataConnections.md | 33 + docs/ReadWriteOperations.md | 60 + scripts/validation/grpc-data/Dockerfile | 30 +- scripts/validation/grpc-data/README.md | 219 +- scripts/validation/grpc-data/cli_gate.py | 131 +- scripts/validation/grpc-data/compose.yml | 68 +- scripts/validation/grpc-data/credentials.py | 111 + .../validation/grpc-data/device/Dockerfile | 2 + scripts/validation/grpc-data/device/server.py | 3 + .../node-probe/GrpcDataNodeProbe.csproj | 10 + .../grpc-data/node-probe/NodeProbeStartup.cs | 272 +++ .../node-probe/ProjectionDiagnostics.cs | 81 + .../node-probe/RuntimeCohortDiagnostics.cs | 138 ++ .../node-probe/SdkItemDiagnostics.cs | 103 + .../grpc-data/probe/GrpcDataProbe.csproj | 7 + .../validation/grpc-data/probe/ProbeEngine.cs | 316 +++ .../grpc-data/probe/ProbeFailureClassifier.cs | 82 + scripts/validation/grpc-data/probe/Program.cs | 249 +++ .../grpc-data/probe/WorkloadEngine.cs | 364 +++ scripts/validation/grpc-data/processes.py | 126 +- scripts/validation/grpc-data/rig.py | 958 +++++++- scripts/validation/grpc-data/scenarios.json | 1535 +++++++++++++ scripts/validation/grpc-data/scenarios.py | 1953 +++++++++++++++++ .../seed/FixtureMutationRevisions.cs | 52 + .../grpc-data/seed/GrpcDataSeed.csproj | 7 + scripts/validation/grpc-data/seed/Program.cs | 432 ++++ .../tests/test_bundle_commit_orchestration.py | 105 + .../grpc-data/tests/test_cli_gate.py | 87 + .../grpc-data/tests/test_compose_fixture.py | 19 +- .../test_consumer_failover_preparation.py | 63 + .../tests/test_control_outage_preparation.py | 69 + .../grpc-data/tests/test_credentials.py | 118 + .../tests/test_d06_pinned_export_denial.py | 73 + .../tests/test_d07_projected_read_order.py | 93 + .../grpc-data/tests/test_endpoint_refresh.py | 131 ++ .../tests/test_export_withdrawal_fixtures.py | 79 + .../tests/test_extended_source_outage.py | 284 +++ .../tests/test_key_only_revision_evidence.py | 72 + .../tests/test_live_fault_failure_evidence.py | 107 + .../tests/test_live_read_timestamps.py | 118 + .../tests/test_live_stream_redaction.py | 95 + .../test_positive_projection_readiness.py | 85 + .../tests/test_process_cancellation.py | 81 + .../tests/test_raw_continuation_replay.py | 67 + .../validation/grpc-data/tests/test_rig.py | 292 ++- .../grpc-data/tests/test_scenarios.py | 391 ++++ .../tests/test_warm_secondary_fixture.py | 59 + .../tests/test_warm_startup_fixture.py | 117 + scripts/validation/grpc-data/unit-phases.json | 37 + .../Commands/ReadCommand.cs | 15 +- .../Commands/SubscribeCommand.cs | 2 +- .../Commands/WriteCommand.cs | 49 +- .../Adapters/DefaultSessionAdapter.cs | 23 + .../Adapters/DefaultSubscriptionAdapter.cs | 24 +- .../Adapters/ISessionAdapter.cs | 3 + .../IOpcUaClientService.cs | 14 + .../OpcUaClientService.cs | 56 +- .../DataConnections/DataProtoMapper.cs | 40 +- .../DataConnectionDiagnosticsSnapshot.cs | 6 +- .../Protos/DataConnectionProtoContract.cs | 2 + .../Protos/data_connection.proto | 15 + .../Entities/DataConnection.cs | 2 +- .../DataConnections/DataContracts.cs | 10 +- .../DataConnections/IDataServices.cs | 23 +- .../ProjectedValuePublication.cs | 2 +- .../IAcknowledgedAcquisitionSource.cs | 10 + .../ModbusDriver.cs | 2 +- .../Clusters/ClusterDataConnections.razor | 4 +- .../Clusters/ClusterDataConnections.razor.css | 5 + .../DataConnectionBundleCommitObserver.cs | 22 + .../Configuration/DataConnectionOptions.cs | 2 + .../DataConnectionRegistration.cs | 66 +- .../DataConnectionSecretProvisioner.cs | 16 + .../DataConnectionTrustPolicy.cs | 16 + .../Grpc/DataConnectionGrpcService.cs | 14 +- .../DeferredProjectedNamespacePageSink.cs | 3 + .../IProjectedNamespacePageSink.cs | 2 + .../OtOpcUaNodeManager.cs | 307 ++- .../OtOpcUaSdkServer.cs | 2 +- .../ProjectedDeliveryDiagnostics.cs | 13 + .../SdkAddressSpaceSink.cs | 4 + .../Security/DataPlaneAuthorizer.cs | 9 + .../WarmStandby.cs | 332 ++- .../ActorProjectedValuePublisher.cs | 24 +- .../DataConnectionDeploymentRuntime.cs | 97 +- .../DataSubscriptionSession.cs | 153 +- .../DataConnections/DataWriteExecutor.cs | 44 +- .../DeployedGrpcDataConnectionSource.cs | 2 + .../DriverHostSubscriptionDemandSource.cs | 13 + .../DataConnections/FederatedBrowseService.cs | 20 +- .../GrpcDataConnection.Diagnostics.cs | 6 +- .../DataConnections/GrpcDataConnection.cs | 152 +- .../DataConnections/GrpcDataDriverAdapter.cs | 9 +- .../GrpcDataWorkloadAccounting.cs | 16 + .../IDataConnectionBundleCommitObserver.cs | 11 + .../LocalDataRuntimeComposition.cs | 9 +- .../DataConnections/LocalDataServices.cs | 39 +- .../DataConnections/MetadataAuthorityLease.cs | 12 + .../DataConnections/PartitionedSampleHub.cs | 9 +- .../DataConnections/ProjectedBrowseAccess.cs | 51 +- .../DataConnections/ProjectedCatalogCache.cs | 179 +- .../DataConnections/ProjectedDataAccess.cs | 1299 +++++++++-- .../ProjectedMappingDeploymentRuntime.cs | 13 + .../ProjectedStreamDiagnostics.cs | 13 + .../RemoteNamespaceResolver.cs | 132 +- .../DataConnections/SamplePartition.cs | 299 ++- .../SourceIngressDiagnostics.cs | 12 + .../DataConnections/SourceInterestLease.cs | 6 +- .../DataConnections/UpstreamDemandRegistry.cs | 4 + .../Drivers/DriverInstanceActor.cs | 75 +- .../Redundancy/IRedundancyRoleView.cs | 32 +- .../VirtualTags/DependencyMuxActor.cs | 10 +- .../Fakes/FakeOpcUaClientService.cs | 8 + .../ReadCommandTests.cs | 38 +- .../SubscribeCommandSummaryTests.cs | 4 +- .../WriteCommandTests.cs | 129 +- .../Fakes/FakeEndpointDiscovery.cs | 4 +- .../Fakes/FakeSessionAdapter.cs | 22 +- .../Fakes/FakeSubscriptionAdapter.cs | 8 + .../OpcUaClientServiceTests.cs | 123 ++ .../ReadResultValidationTests.cs | 25 + .../GrpcDataFreshnessChallengeCodecTests.cs | 213 ++ .../GrpcDataMetadataLeaseCodecTests.cs | 178 ++ .../ProjectedInputBudgetTests.cs | 7 +- .../GrpcDataCalculationOwnershipTests.cs | 11 +- .../GrpcDataFreshnessCommandTlsWireTests.cs | 163 ++ .../GrpcDataListenerIsolationWireTests.cs | 54 + .../GrpcDataSampleFidelityTlsWireTests.cs | 81 + .../DataConnections/GrpcDataTlsWireTests.cs | 190 ++ .../GrpcDataFixtureIsolationTests.cs | 22 + .../GrpcDataBundleCommitObserverTests.cs | 173 ++ .../GrpcDataProjectionRoutingTests.cs | 16 +- .../GrpcDataRuntimeRegistrationTests.cs | 132 +- ...pcDataClientSubscriptionStatusWireTests.cs | 40 + .../GrpcDataSdkBrowseWireTests.cs | 120 +- .../GrpcDataSdkDeliveryWireTests.cs | 178 +- .../GrpcDataSdkMappedAccessTests.cs | 26 +- .../GrpcDataSdkProjectionLifetimeTests.cs | 68 + .../GrpcDataSdkProjectionTests.cs | 4 + .../GrpcDataCatalogStagingTests.cs | 8 +- .../GrpcDataComposedBrowseWireTests.cs | 305 ++- .../GrpcDataConfiguredDiscoveryWireTests.cs | 67 +- .../GrpcDataConnectionClientTests.cs | 225 +- .../GrpcDataCrossCadenceProofWireTests.cs | 72 + .../GrpcDataDeployedFreshnessWireTests.cs | 143 ++ .../GrpcDataDeployedWriteDeadlineTests.cs | 132 ++ ...GrpcDataExpiredOverlapFailoverWireTests.cs | 431 ++++ .../GrpcDataFederatedBrowseTests.cs | 34 + .../GrpcDataFixtureMutationRevisionTests.cs | 129 ++ .../GrpcDataFramedLifecycleWireTests.cs | 301 +++ .../GrpcDataFreshnessBatchWireTests.cs | 100 + .../GrpcDataFreshnessChallengeTests.cs | 101 + .../GrpcDataFreshnessHistoryTests.cs | 127 ++ .../GrpcDataHotRouteContinuityTests.cs | 217 ++ .../GrpcDataIngressMailboxAdmissionTests.cs | 202 ++ .../GrpcDataIngressMailboxRaceTests.cs | 134 ++ .../GrpcDataIngressOverflowTests.cs | 3 +- .../GrpcDataLocalConnectionTests.cs | 17 +- .../GrpcDataMetadataLeaseClientTests.cs | 120 + .../GrpcDataMetadataLeaseIssuanceTests.cs | 47 + ...pcDataMetadataRenewalCacheCapacityTests.cs | 217 ++ .../GrpcDataMetadataRenewalCacheTests.cs | 111 + ...cDataMetadataRenewalContinuityWireTests.cs | 593 +++++ ...MetadataRenewalDeliveryDiagnosticsTests.cs | 65 + ...DataMetadataRenewalPredecessorWireTests.cs | 140 ++ .../GrpcDataMetadataRenewalPublisherTests.cs | 68 + .../GrpcDataMetadataRenewalRetryTests.cs | 35 + .../GrpcDataProbeFailureClassifierTests.cs | 162 ++ .../GrpcDataProjectedAccessTests.cs | 591 ++++- ...rpcDataProjectedPageGenerationWireTests.cs | 153 ++ .../GrpcDataProjectedReadFreshnessTests.cs | 49 + ...GrpcDataProjectedReconnectLifetimeTests.cs | 151 ++ .../GrpcDataProjectedRetryJitterTests.cs | 40 + ...pcDataProjectedStreamReconnectWireTests.cs | 324 +++ .../GrpcDataProjectedWriteAdmissionTests.cs | 76 + .../GrpcDataProjectedWriteDeadlineTests.cs | 75 + ...cDataProjectionValidityDiagnosticsTests.cs | 115 + .../GrpcDataRootMountWireTests.cs | 30 + .../GrpcDataSdkBadQualityEvidenceTests.cs | 220 ++ .../GrpcDataSdkItemDiagnosticsTests.cs | 96 + .../GrpcDataSdkRenewalEvidenceTests.cs | 95 + .../GrpcDataSdkSampleFidelityWireTests.cs | 60 + .../GrpcDataSdkSourceLossTests.cs | 643 ++++++ .../GrpcDataSdkTimestampEvidenceTests.cs | 216 ++ .../GrpcDataSecondaryWriteBackoffTests.cs | 90 + .../GrpcDataStreamFreshnessWireTests.cs | 233 ++ .../GrpcDataStreamOrderingTests.cs | 169 ++ ...GrpcDataSuppressedItemRecoveryWireTests.cs | 84 + .../GrpcDataSuppressedTombstoneWireTests.cs | 66 + .../GrpcDataWriteAdmissionTests.cs | 53 + .../Drivers/GrpcDataDriverDemandActorTests.cs | 80 +- .../GrpcDataModbusBaselineFreshnessTests.cs | 84 + .../GrpcDataProjectedMuxLifetimeTests.cs | 86 + .../ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj | 5 + 194 files changed, 23327 insertions(+), 740 deletions(-) create mode 100644 scripts/validation/grpc-data/credentials.py create mode 100644 scripts/validation/grpc-data/node-probe/GrpcDataNodeProbe.csproj create mode 100644 scripts/validation/grpc-data/node-probe/NodeProbeStartup.cs create mode 100644 scripts/validation/grpc-data/node-probe/ProjectionDiagnostics.cs create mode 100644 scripts/validation/grpc-data/node-probe/RuntimeCohortDiagnostics.cs create mode 100644 scripts/validation/grpc-data/node-probe/SdkItemDiagnostics.cs create mode 100644 scripts/validation/grpc-data/probe/GrpcDataProbe.csproj create mode 100644 scripts/validation/grpc-data/probe/ProbeEngine.cs create mode 100644 scripts/validation/grpc-data/probe/ProbeFailureClassifier.cs create mode 100644 scripts/validation/grpc-data/probe/Program.cs create mode 100644 scripts/validation/grpc-data/probe/WorkloadEngine.cs create mode 100644 scripts/validation/grpc-data/scenarios.json create mode 100644 scripts/validation/grpc-data/scenarios.py create mode 100644 scripts/validation/grpc-data/seed/FixtureMutationRevisions.cs create mode 100644 scripts/validation/grpc-data/seed/GrpcDataSeed.csproj create mode 100644 scripts/validation/grpc-data/seed/Program.cs create mode 100644 scripts/validation/grpc-data/tests/test_bundle_commit_orchestration.py create mode 100644 scripts/validation/grpc-data/tests/test_consumer_failover_preparation.py create mode 100644 scripts/validation/grpc-data/tests/test_control_outage_preparation.py create mode 100644 scripts/validation/grpc-data/tests/test_credentials.py create mode 100644 scripts/validation/grpc-data/tests/test_d06_pinned_export_denial.py create mode 100644 scripts/validation/grpc-data/tests/test_d07_projected_read_order.py create mode 100644 scripts/validation/grpc-data/tests/test_endpoint_refresh.py create mode 100644 scripts/validation/grpc-data/tests/test_export_withdrawal_fixtures.py create mode 100644 scripts/validation/grpc-data/tests/test_extended_source_outage.py create mode 100644 scripts/validation/grpc-data/tests/test_key_only_revision_evidence.py create mode 100644 scripts/validation/grpc-data/tests/test_live_fault_failure_evidence.py create mode 100644 scripts/validation/grpc-data/tests/test_live_read_timestamps.py create mode 100644 scripts/validation/grpc-data/tests/test_live_stream_redaction.py create mode 100644 scripts/validation/grpc-data/tests/test_positive_projection_readiness.py create mode 100644 scripts/validation/grpc-data/tests/test_process_cancellation.py create mode 100644 scripts/validation/grpc-data/tests/test_raw_continuation_replay.py create mode 100644 scripts/validation/grpc-data/tests/test_scenarios.py create mode 100644 scripts/validation/grpc-data/tests/test_warm_secondary_fixture.py create mode 100644 scripts/validation/grpc-data/tests/test_warm_startup_fixture.py create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor.css create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionBundleCommitObserver.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedDeliveryDiagnostics.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataWorkloadAccounting.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/IDataConnectionBundleCommitObserver.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedStreamDiagnostics.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceIngressDiagnostics.cs create mode 100644 tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/ReadResultValidationTests.cs create mode 100644 tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataFreshnessChallengeCodecTests.cs create mode 100644 tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataMetadataLeaseCodecTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataFreshnessCommandTlsWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataListenerIsolationWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataSampleFidelityTlsWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataTlsWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Configuration/GrpcDataFixtureIsolationTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataBundleCommitObserverTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataClientSubscriptionStatusWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCrossCadenceProofWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeployedFreshnessWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeployedWriteDeadlineTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataExpiredOverlapFailoverWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFixtureMutationRevisionTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFramedLifecycleWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFreshnessBatchWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFreshnessChallengeTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFreshnessHistoryTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHotRouteContinuityTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataIngressMailboxAdmissionTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataIngressMailboxRaceTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataLeaseClientTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataLeaseIssuanceTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalCacheCapacityTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalCacheTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalContinuityWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalDeliveryDiagnosticsTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalPredecessorWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalPublisherTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalRetryTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProbeFailureClassifierTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedPageGenerationWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedReadFreshnessTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedReconnectLifetimeTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedRetryJitterTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedStreamReconnectWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedWriteAdmissionTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedWriteDeadlineTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectionValidityDiagnosticsTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataRootMountWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkBadQualityEvidenceTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkItemDiagnosticsTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkRenewalEvidenceTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSampleFidelityWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSourceLossTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkTimestampEvidenceTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSecondaryWriteBackoffTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataStreamFreshnessWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSuppressedItemRecoveryWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSuppressedTombstoneWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataModbusBaselineFreshnessTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/GrpcDataProjectedMuxLifetimeTests.cs diff --git a/docs/DataConnections.md b/docs/DataConnections.md index d003a81bb..769c98549 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -24,6 +24,10 @@ validator remains authoritative: consumers must belong to the owning cluster, ma must be a subset of the connection's consumers, local parents must be valid containers, and branch collisions, invalid self-routes and unsupported type expectations are rejected. +New connections default to a 30-second call timeout. Existing explicitly configured shorter +timeouts remain in force. This limit never extends a caller's original deadline; a write without +enough remaining time for the driver budget is rejected before dispatch. + Raw maps to Raw and UNS maps to UNS. A remote root is a branch, so descendants can be discovered without authoring one import row per leaf. The local mapping owns a distinct view with remote origin provenance. Remote projected branches cannot be re-exported as locally owned data. Stable addresses @@ -64,6 +68,35 @@ unavailable/pending remote data rather than a successfully browsed empty branch. continues independently. [Read/write operations](ReadWriteOperations.md) describes asynchronous projected cache refresh, freshness checks and mutation outcomes. +### Subscription freshness and exact-item renewal + +Peers negotiate stream freshness challenges and per-item metadata leases as separate capabilities. +A Subscribe-authorized active item can receive a bounded, same-stream freshness challenge. The +origin captures its age after accepting that challenge and keeps the challenge identifier coupled +to the sample through delivery. The consumer bounds age by combining that origin age with elapsed +time since its challenge started, then advances the bound through local queueing and publication. +An unknown, expired, evicted or unnegotiated challenge cannot establish a finite age bound. +Periodic challenge snapshots can renew a quiet item's age evidence without a device poll or an +additional Read grant. A newer sample version alone cannot inherit an older challenge's proof. + +An existing SDK monitored item can renew only its **exact projected node** through a successful +`GetMetadata` response with an explicit item lease from a peer advertising that capability. +`MaxMetadataLease` is a ceiling, not an implicit grant. The origin still authorizes the service +principal for Metadata; the consumer rechecks the original local caller and key for Subscribe. +Renewal checks the full prior origin view and subject, serving identity, catalog/authority epochs, +mapping scope, node lifetime and compatible metadata shape. Its lease begins at the consumer's +monotonic request start and is capped by the mapping and original credential lifetime. A delayed +reply cannot lengthen it. Renewal grants no parent or sibling visibility, Browse page, cursor or +local Browse privilege. Missing capability, denied Metadata or an invalid lease leaves the item +unavailable until valid authority can be established. + +An authorized logical monitored-item request can survive a physical stream expiry and seek a new +pinned binding with bounded retries. The old binding and any queued sample evidence remain tied to +their original authority and serving generation. The same item needs a fresh, complete baseline +under the new stream epoch before it can publish again; old queued or Republish data cannot borrow +the new proof. Withdrawal or expiry of the original local Subscribe authority stops renewal. +Consumers can miss intermediate changes during an interruption. + ## Rollout and diagnosis 1. Provision TLS trust and connection-scoped target credentials on each consumer; configure the diff --git a/docs/ReadWriteOperations.md b/docs/ReadWriteOperations.md index 965e44534..5950237da 100644 --- a/docs/ReadWriteOperations.md +++ b/docs/ReadWriteOperations.md @@ -40,6 +40,11 @@ read and returns `BadWaitingForInitialData`; it does not block the SDK callback The response refreshes the local cache for a later Read. The origin's own local Read remains a cached read rather than a device poll. +For explicit cached reads, the CLI accepts `read --max-age 5000` (milliseconds). +Its default remains zero. A cold projection can still return pending; retry after +the bounded refresh completes. This matches the [OPC UA Read age parameter](https://reference.opcfoundation.org/specs/OPC-10000-4/5.11.2); +it does not extend a mapping's authority lease or allowed origin-sample age. + Projected data-change monitored items acquire live demands and share compatible upstream acquisition. Delivery checks current authority and freshness through the publish path, including queued delivery; admission alone is insufficient. Reconnect/reset uses a fresh snapshot and new @@ -47,6 +52,61 @@ stream epoch. There is no durable event replay or seamless subscription transfer Browsing metadata alone does not acquire value subscriptions. Configured imported dependencies can acquire values for local derived engines under their deployed authority. +For an active projected SDK monitored item, a negotiated same-stream freshness challenge can +establish a finite upper bound on sample age. The origin captures age after accepting the +challenge; the consumer adds elapsed time from its own pre-send start and keeps advancing the +bound through queued delivery. A missing or unrecognized challenge leaves that upper bound +unknown, even if the sample version increased. A periodic complete challenge snapshot can +refresh a quiet source under Subscribe authority without a device poll or an extra Read grant. +The item's maximum-age rule still applies at final publication. + +A preserved source timestamp can distinguish equal-valued acquisitions retained by the SDK +queue. It identifies the original evidence; freshness still uses monotonic age bounds. When +missing, omitted or equal timestamps leave multiple acquisitions indistinguishable, delivery +fails closed and requests a fresh baseline. Republish retains the selected sample's original +age and authority proof. + +After stream or metadata-lease expiry, recovery retains the original monitored item's local +Subscribe caller and exact logical target while obtaining a new pinned binding. The origin must +return an explicit, valid per-item `GetMetadata` lease from a peer that advertises that +capability; a capability limit alone is not a lease. Renewal does not grant local Browse access, +materialize a parent or sibling, or make a new continuation. If the peer lacks the capability, +Metadata is denied, the prior subject or shape changed, or the original caller is no longer +authorized, delivery remains unavailable. The same item needs a fresh complete baseline before +publication resumes. Old queued notifications and Republish evidence stay fenced to the old +binding and cannot inherit the new age or authority proof. See +[Data connections](DataConnections.md#subscription-freshness-and-exact-item-renewal). + +### Operating a mapped branch + +Create the origin `DataExport`, consumer `DataConnection` and `RemoteNamespaceMapping` as +drafts, then deploy them through the normal deployment flow. A mapping applies only to its +listed consumer nodes, which must be a subset of the connection's consumers. Moving a branch, +changing its remote root or changing consumer membership needs a new deployment; verify the +applied catalog and rediscover the branch before treating an old NodeId or continuation as +current. The projected view has its own namespace URI and retains origin and serving identity; +resolve that URI from `NamespaceArray` after reconnect. Only locally owned Raw/UNS roots can be +exported, so a projected branch cannot be relayed onward as an origin. + +Provision each consumer's connection-scoped API key under its `secret:data/...` reference and +its trust roots in separate restricted bundles. The gRPC data listener uses a dedicated port; +production transport requires TLS with a certificate valid for the configured endpoint hosts. +Stage trust before rotating the server certificate, verify the new identity, then retire the +old trust. A missing bundle is retried; an explicit scoped key retirement or deployed scope +removal revokes authority. The mesh key does not authorize this data plane. See +[Data connections](DataConnections.md#listener-credentials-and-trust) and +[Configuration](Configuration.md#dataconnections) for options and defaults. + +If a branch is pending or unavailable, compare the applied connection/mapping/export state, +consumer membership, authenticated endpoint role, key scope and version, trust roots, metadata +lease and sample age. Inspect the connection's per-node diagnostics for last verified handshake, +selected endpoint, stream resets, overflow and retained import views. Listener and hub admission +limits can reject calls or reset a stream under overload; recovery starts a fresh snapshot and +does not replay missed changes. `DataConnections:UseCompactBatches` defaults to `true` for +outbound subscriptions when the peer supports compact batches. To roll back an import, disable +the mapping or connection in a draft and deploy it; retired authority makes the projected data +unavailable. Check dependent calculations and subscriptions after that deployment. + ## Local Value writes Writable local variables attach `OnEquipmentTagWrite`; non-writable variables are rejected by diff --git a/scripts/validation/grpc-data/Dockerfile b/scripts/validation/grpc-data/Dockerfile index 257f40f27..92536b6c6 100644 --- a/scripts/validation/grpc-data/Dockerfile +++ b/scripts/validation/grpc-data/Dockerfile @@ -1,17 +1,31 @@ # Standalone P10 host image. The run coordinator supplies SOURCE_REVISION from # the current checkout and uses a run-scoped image name in compose.yml. +# Grpc.Tools linux_arm64 protoc exits139 under Apple Silicon Docker. +# Build portable IL on amd64; the Host runtime remains native, as in docker-dev. FROM --platform=linux/amd64 mcr.microsoft.com/dotnet/sdk:10.0 AS build WORKDIR /src COPY . . -RUN dotnet restore ZB.MOM.WW.OtOpcUa.slnx +RUN dotnet restore src/Server/ZB.MOM.WW.OtOpcUa.Host/ZB.MOM.WW.OtOpcUa.Host.csproj --disable-parallel -m:1 ARG SOURCE_REVISION -RUN test -n "$SOURCE_REVISION" && dotnet publish \ +ARG SOURCE_TREE_HASH +RUN test -n "$SOURCE_REVISION" && test -n "$SOURCE_TREE_HASH" && dotnet publish \ src/Server/ZB.MOM.WW.OtOpcUa.Host/ZB.MOM.WW.OtOpcUa.Host.csproj \ - -c Release -o /app --no-restore -p:SourceRevisionId="$SOURCE_REVISION" + -c Release -o /app --no-restore -m:1 -p:SourceRevisionId="$SOURCE_REVISION" +RUN printf '{"revision":"%s","tree_hash":"%s"}\n' "$SOURCE_REVISION" "$SOURCE_TREE_HASH" > /app/grpc-data-source.json + +# These fixture projects are intentionally outside the solution. Restore their +# already-cached dependency graph explicitly and serialize emulated MSBuild. +# Vulnerability auditing belongs to the normal solution restore, not a second +# network audit of identical dependencies during fixture packaging. +RUN dotnet restore scripts/validation/grpc-data/node-probe/GrpcDataNodeProbe.csproj --disable-parallel -m:1 -p:NuGetAudit=false +RUN dotnet publish scripts/validation/grpc-data/node-probe/GrpcDataNodeProbe.csproj -c Release -o /node-probe --no-restore -m:1 FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS runtime WORKDIR /app COPY --from=build /app ./ +# Preserve Host-resolved dependency versions; this fixture assembly has no extra packages. +COPY --from=build /node-probe/GrpcDataNodeProbe.dll ./ +COPY --from=build /node-probe/GrpcDataNodeProbe.deps.json ./ EXPOSE 9000 4053 4055 4056 4057 4840 9001 ENTRYPOINT ["dotnet", "OtOpcUa.Host.dll"] @@ -20,5 +34,15 @@ RUN dotnet tool install --global dotnet-ef --version 10.0.7 ENV PATH="${PATH}:/root/.dotnet/tools" WORKDIR /src ENTRYPOINT ["dotnet", "ef", "database", "update", \ + "--no-build", "--configuration", "Release", \ "--project", "src/Core/ZB.MOM.WW.OtOpcUa.Configuration", \ "--startup-project", "src/Core/ZB.MOM.WW.OtOpcUa.Configuration"] + +FROM build AS seed-build +RUN dotnet restore scripts/validation/grpc-data/seed/GrpcDataSeed.csproj --disable-parallel -m:1 -p:NuGetAudit=false +RUN dotnet publish scripts/validation/grpc-data/seed/GrpcDataSeed.csproj -c Release -o /seed --no-restore -m:1 + +FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS seeder +WORKDIR /seed +COPY --from=seed-build /seed ./ +ENTRYPOINT ["dotnet", "GrpcDataSeed.dll"] diff --git a/scripts/validation/grpc-data/README.md b/scripts/validation/grpc-data/README.md index 735b7d0cc..90761718a 100644 --- a/scripts/validation/grpc-data/README.md +++ b/scripts/validation/grpc-data/README.md @@ -1,71 +1,166 @@ -# gRPC data local fixture scaffold +# Standalone gRPC data integration rig -This directory contains the **preparation** for the P10 gate. The standalone -Compose file describes six Host processes in three independent two-node pairs: -CONTROL (admin and deployment), SOURCE, and CONSUMER. Each process has its own -LocalDb/secrets volume. SOURCE and CONSUMER have pair-local LocalDb replication. -The SQL Server and Modbus simulator are run-local services; exposed host ports -use Docker's dynamic allocation on `127.0.0.1`. +This fixture builds the current checkout and runs six Host processes in three +independent Akka pairs: CONTROL, SOURCE and CONSUMER. Its SQL Server, writable +Modbus device, private CA, images, network, volumes and secrets belong to one +explicit run. It never inherits `docker-dev` configuration. Run it against a +local Unix Docker socket or Windows named pipe; SSH and TCP contexts are rejected. +Docker and .NET 10 must be installed. SQL Server uses Docker's amd64 emulation on +ARM hosts. `openssl` is required for the ephemeral CA and service SAN certificates. -The fixture is **not ready for integration execution**. P07's dedicated TLS -listener, client trust options, target-issued credential provisioner, and -production seeding/deployment path are still in progress. The certificate -mounts reserve `/run/grpc-data/tls` on the four data nodes, but no guessed P07 -option names or TLS activation are included. The existing `rig.py` currently -provides pure safety/polling boundaries, not `up`, `seed`, or `deploy` behavior. -The presence of this Compose file does not establish a healthy cluster, a -deployed catalog, or passing D01–D14 scenarios. +From the repository root: -## Run-owned inputs for later rig integration +```bash +python3 scripts/validation/grpc-data/rig.py preflight +python3 scripts/validation/grpc-data/rig.py up --run-id grpc-data-local +python3 scripts/validation/grpc-data/rig.py seed --run-id grpc-data-local +python3 scripts/validation/grpc-data/rig.py deploy --run-id grpc-data-local +python3 scripts/validation/grpc-data/rig.py status --run-id grpc-data-local +python3 scripts/validation/grpc-data/rig.py down --run-id grpc-data-local +``` -The future `rig.py up` must generate a restricted run directory and inject all -required Compose variables. `GRPC_DATA_PROJECT`, `GRPC_DATA_RUN_ID`, -`GRPC_DATA_IMAGE`, `GRPC_DATA_MIGRATOR_IMAGE`, and `GRPC_DATA_DEVICE_IMAGE` must -identify the run uniquely. `SOURCE_REVISION` must be the current source SHA, -including a dirty marker when applicable. `GRPC_DATA_CERT_DIR` must contain -per-node SAN certificates and private keys under `source-1`, `source-2`, -`consumer-1`, and `consumer-2`; their common trust material belongs in the same -restricted run directory. The rig must generate `GRPC_DATA_SQL_PASSWORD`, -`GRPC_DATA_APIKEY_PEPPER`, `GRPC_DATA_JWT_KEY`, `GRPC_DATA_DEPLOY_KEY`, -`GRPC_DATA_SECRETS_KEK`, `GRPC_DATA_CONFIG_KEY`, `GRPC_DATA_TELEMETRY_KEY`, -three `GRPC_DATA_MESH_PSK_*` values, and both `GRPC_DATA_SYNC_KEY_*` values. -None has a tracked default. The rig should pass them from a `0600` environment -file without writing values to logs or a public manifest. +`up` generates restricted run files, validates resolved Compose endpoints, builds +run-specific images, applies EF migrations to the owned SQL container, starts the +pairs and waits for ready health plus exactly one active role per pair. Docker +allocates every published port on `127.0.0.1`; the manifest records the actual +bindings. Each node has a separate persistent LocalDb/secrets volume. SOURCE and +CONSUMER use pair-local LocalDb sync. LDAP is disabled through its actual startup +option and the local machine deploy API requires a generated key. -The current Compose image build follows the repository's Host publish graph and -requires a nonempty `SourceRevisionId`. The future coordinator must build the -runtime and migrator images for the current checkout before starting nodes, -inspect Docker's allocated loopback ports, and record the exact run-owned -resource IDs and labels. A separate production-path seeder must create the -CONTROL/SOURCE/CONSUMER cluster rows, author source and mapping configuration, -provision every eligible consumer, and deploy through `/api/deployments` before -any readiness or CLI assertion is meaningful. No node should use a shared-host -endpoint or another node's OPC UA endpoint as its source driver. +`seed` uses the production EF model, `ApiKeyAdminService`, `DraftValidator` and +cluster topology validator. SOURCE gets a local Modbus driver, Raw tags and UNS +references to those same tags, export grants and a target-issued data key. +CONSUMER gets a scoped outbound connection and both realm mappings. No source +uses another Host's OPC UA endpoint as a driver. Data keys and the CLI key are +written directly to restricted files, never printed or put in the manifest. + +`deploy` sends only `{"createdBy":"grpc-data-local-gate"}` to the normal machine +API. Its acceptance callback reads the **exact GZip deployment artifact** and +scope version, then atomically provisions each node's actual credential/trust +bundle. The Host's P07 loader imports those files into its encrypted local store. +The gate follows the returned Location and requires the same revision and a +successful apply outcome on every intended node. It rejects degraded outcomes, +unexpected nodes, duplicate nodes, remote redirects and in-flight triggers. +It also waits for each required data node to acknowledge the exact committed credential and +trust scope/entry versions. Pending durable retirement or notification work cannot satisfy this +barrier; its observations contain numeric versions and state flags, without secret payloads. +After an owned restart, the harness re-inspects the affected nodes' actual loopback ports and +updates the manifest before reconnecting. +Finally, real Client.Shared OPC UA sessions read NamespaceArray, verify expected +application identities, browse the deployed trees and resolve/read fixture leaves. +This avoids assuming namespace indexes. A run becomes `ready` only after these +checks. Readiness does not stand in for the D01–D14 scenario evidence. + +Mapped positive CLI reads use `--max-age 5000` and retry only an explicit +`BadWaitingForInitialData` response within the scenario deadline. The CLI default +remains zero, which schedules asynchronous refresh rather than waiting under the +SDK lock. Read and subscription timestamps retain the SDK timestamp's full UTC +precision. Every running Host build stamp is checked against the recorded +compiled-input hash before scenario mutations; published tools record their +own binary hash and the same source identity. +The Modbus device image has a separate hash over its protocol/ledger source and +Dockerfile, checked against the running container before scenarios or workloads. + +The restricted manifest is +`artifacts/grpc-data/runs//manifest.json` (schema version 1). It contains: + +- `endpoints`: keys such as `source-1.data`, `consumer-1.opcua`, + `control-1.admin`, `device.modbus` and `device.control`. Every row records scheme, + host/container host, host/container port and the allocated loopback URL. +- `nodes`: service names mapped to cluster, `node_id` (`source-1:4053`) and unique + application URI. `deployment` records the exact ID, hash, scope and node outcomes. +- `tls.ca_file`, `credentials.cli_key_file`, `credentials.data_key_files.source` + and `node_probe_dirs`: paths only. Presented secrets remain in `0600` files. +- `fixture.namespace_uris`, `fixture.origin_paths` and `resolved_nodes`: canonical + URI identities, source Raw/UNS aliases and per-node resolved NodeIds. +- `resources`: exact Docker object IDs and exact run/project labels. Both the Git + revision and a SHA256 of actual checkout file contents are recorded; the image + also contains `/app/grpc-data-source.json`, so pending source changes are covered. + +`down` refreshes the exact run-label inventory, verifies labels again, and removes +only those exact container/network/volume/image IDs. It never calls Compose down, +prune or prefix-based deletion. Interrupted setup leaves a restricted ownership +journal that enables the same cleanup. Run files are retained for evidence; +use a new run ID for another run. + +## Scenario authoring and node probes + +The seeder is available through `LocalRig.seed_helper(action, *arguments)`. Its +`snapshot` action writes a restricted `seed/baseline.json` and baseline presented +key; `restore` restores mutable fixture rows transactionally through EF and +production validation, then restores key enabled state through ApiKeyAdminService. +Call normal `deploy` after authoring changes. `scope ` +reads the exact artifact; `resolve` writes `seed/resolved.json` from real sessions. + +For `mutate`, atomically write `seed/mutation.json` and invoke `seed_helper("mutate")`. +Supported snake_case fields are `connection_id` (default `consumer-source`), +`target_mode` (`Node`/`Cluster`), `target_node_id`, `consistency`, +`consumer_node_ids`, `connection_enabled`, `connection_allowed_operations`, +`mapping_enabled`, `write_through`, `allowed_operations` (mapping operations), +`export_enabled`, `export_allowed_operations`, `source_redundancy_mode`, +`consumer_redundancy_mode`, `rename_tag: {tag_id,name}`, `disable_feature`, +`key_action` (`rotate`, `rotate_staged`, `retire_old`, `revoke`, `expire`) and `key_expiry_seconds`. +`upsert_connection`, `upsert_mapping`, `upsert_export` and `upsert_tag` accept the corresponding +production entity's PascalCase JSON fields, with numeric enum values; +`remove_mapping_id` deletes an authored mapping; `remove_tag_id` removes a tag +and its UNS references. Unknown mutation fields are rejected. Validator refusals +write stable codes to restricted `seed/rejection.json` and roll back the EF transaction. All authored gRPC endpoints must +name a run-owned service over HTTPS. Mutations use an EF transaction and the +production validator. A scope/key change still requires deployment and local +bundle publication; neither a SQL row nor a mutation return code makes it active. + +For negative scenarios call `deploy(require_catalog=False)` after normal authoring +and deployment, then assert the expected closed capability/read behavior through +the real probe. `credential_action(action, node=None)` accepts +`remove_consumer_secret`, `provision_consumer_secret` and `reload_stale_bundle`. +It publishes actual P07 tombstones or active bundles; omitting the node targets +both consumers. Bundle generation high-watermarks survive stale-file replay. +`trust_action("stage_new")`, `trust_action("rotate_server")` and +`trust_action("retire_old")` implement a second local CA, overlapping trust, +actual service certificate replacement/restarts and retirement. `restore_security()` +restores original certificates/CA after baseline authoring restore; the next normal +deployment provisions its authoritative scope. These controls publish changes; +scenario assertions still wait for and inspect actual runtime behavior. + +D07 restores the maintenance flag in SQL before allowing 65 seconds for CONTROL +to refresh its dispatch targets. It then issues one normal baseline deployment +and verifies all six acknowledgements and the baseline catalog. The wait is part +of teardown and does not extend D07's live failover observation. + +Only this Dockerfile packages the rig-only `GrpcDataNodeProbe` hosting-startup +assembly, and only this Compose file enables it. Per-node restricted mounted +command directories allow the scenario runner to call the actual Host caller DI +graph. The ordinary Host image/configuration does not enable this fixture. ## Device fixture -`device/server.py` uses the Python standard library. Modbus TCP unit 1 listens -on container port 5020. Holding register 0 is a counter changed only by the -fixture control action `{"action":"advance","steps":N}` (1–1000). Registers -10–12 start at `[7, 11, 13]`; registers 20–63 are writable uint16 values. -FC03/FC04 reads and FC06/FC16 writes are supported. Unmapped spans return -exception 02, malformed values/counts return 03, and unsupported functions -(including FC23) return 01 so callers can retry using FC16. The fixture's -unknown-unit policy returns target-unavailable exception 0B with the unit echoed. -Validly framed refusals keep the stream open; invalid MBAP framing closes it. -Total requests, read attempts (including refusals), rejected writes, and committed -effects have separate bounded ledgers with monotonic totals. Records contain -structural numeric metadata and bounded fixture write values, never raw payloads. -Invalid/truncated frames count as requests; clean stream EOF does not. Read and -rejected-write records share the total-request sequence. The HTTP control -listener on container port 8080 offers `GET /state` and `POST /control`, with -`advance`, bounded `set`, and `drop_next_write_response` actions. The last -action closes one Modbus write connection after applying and recording the -effect, so D08 can distinguish an ambiguous response from a second effect. -The control listener is fixture-only and its allocated host port is loopback -bound; it must never be wired into the production Host. +The standard-library Python fixture listens on Modbus TCP unit 1, container port +5020. Holding register 0 is a deterministic counter; 10–12 start at `[7,11,13]`; +20–63 are writable uint16 registers. Raw/UNS `scalar` both reach register 20; +`counter` reaches 0 and `array0`–`array2` expose the fixed samples as individual +scalar registers. No unsupported array representation is invented by the seeder. +FC03/FC04 reads and FC06/FC16 writes are supported. Unmapped spans return exception +02, malformed values/counts 03, unsupported functions 01 and unknown units 0B. -Unit tests in `tests/test_device.py`, `tests/test_device_wire.py`, and -`tests/test_compose_fixture.py` are pure. The wire tests drive the actual handler -through memory streams. They do not start a socket, container, migration, or -network client. +The fixture-only HTTP API on container port 8080 has `GET /state` and +`POST /control`. Actions are `{"action":"advance","steps":1}`, +`{"action":"set","address":20,"value":42}`, and +`{"action":"drop_next_write_response"}`. The last commits and records one write +before closing its response connection. Bounded ledgers distinguish total requests, +read attempts, rejected writes and committed effects. The control API is never +registered in production Host. + +## Focused verification + +The coordinator runs these commands; they do not bring up Docker: + +```bash +python3 -m unittest discover -s scripts/validation/grpc-data/tests -p 'test_rig.py' +python3 -m unittest discover -s scripts/validation/grpc-data/tests -p 'test_credentials.py' +python3 -m unittest discover -s scripts/validation/grpc-data/tests -p 'test_compose_fixture.py' +python3 -m unittest discover -s scripts/validation/grpc-data/tests -p 'test_device.py' +python3 -m unittest discover -s scripts/validation/grpc-data/tests -p 'test_device_wire.py' +``` + +C# seed/probe compilation and actual migrations, deploys, TLS and scenario runs are +integration checks. A checked-in fixture implementation is not passing evidence. diff --git a/scripts/validation/grpc-data/cli_gate.py b/scripts/validation/grpc-data/cli_gate.py index 77b8dd098..8d5510514 100644 --- a/scripts/validation/grpc-data/cli_gate.py +++ b/scripts/validation/grpc-data/cli_gate.py @@ -1,11 +1,4 @@ -"""Evidence validators for the repository CLI's current human-readable output. - -These functions validate individual healthy operations, not the complete P10 -scenario matrix. A process exit of zero alone is never success. Subscription -summary text must come from a fresh run-owned --summary-file; stdout alone is -insufficient. Integration orchestration and explicit denial/fault expectations -will be connected once the production fixture graph exists. -""" +"""Run the isolated production CLI/probe gate and validate actual operation evidence.""" import argparse from datetime import datetime import ipaddress @@ -22,8 +15,8 @@ class CliGateError(RuntimeError): def _process_ok(result): - if not isinstance(result, ProcessResult) or result.timed_out or result.returncode != 0 or result.truncated: - raise CliGateError("CLI failed, timed out, or produced truncated evidence") + if not isinstance(result, ProcessResult) or result.cancelled or result.timed_out or result.returncode != 0 or result.truncated: + raise CliGateError("CLI failed, was cancelled, timed out, or produced truncated evidence") if not isinstance(result.stdout, str) or not result.stdout.strip(): raise CliGateError("CLI stdout evidence is missing") @@ -45,17 +38,30 @@ def _timestamp(value): return value +def is_good_status(status): + return re.fullmatch(r"Good(?: \[0x00000000\])?", status) is not None + + +def parse_notification(line): + match = re.fullmatch(r"\[([^\]]+)\] (.+?) = (.*) \(([^()]*)\)\r?", line) + if match is None: + return None + timestamp, node, value, status = match.groups() + _timestamp(timestamp) + return {"timestamp": timestamp, "node": node, "value": value, "status": status} + + def validate_read(result, *, expected_node): _process_ok(result) if _field(result.stdout, "Node") != expected_node: raise CliGateError("CLI read returned a different node") status = _field(result.stdout, "Status") - if status != "Good": + if not is_good_status(status): raise CliGateError("CLI read status is not Good") value = _field(result.stdout, "Value") if not value: raise CliGateError("CLI read value is missing") - return {"node": expected_node, "status": status, "value": value, + return {"node": expected_node, "status": "Good", "value": value, "source_time": _timestamp(_field(result.stdout, "Source Time")), "server_time": _timestamp(_field(result.stdout, "Server Time"))} @@ -68,6 +74,44 @@ def validate_write(result, *, expected_node): return {"node": expected_node, "accepted_value": successes[0][1].strip()} +def validate_connect(result, *, expected_endpoint): + _process_ok(result) + if _field(result.stdout, "Connected to") != expected_endpoint or result.stdout.count("Connection successful.") != 1: + raise CliGateError("CLI connection did not confirm the selected endpoint") + return {"endpoint": expected_endpoint, "server": _field(result.stdout, "Server")} + + +def validate_browse(result, *, expected_nodes): + _process_ok(result) + found = re.findall(r"^\s*\[(?:Object|Variable|Method)\] .+? \(NodeId: (.+)\)$", result.stdout, re.M) + if not expected_nodes or not set(expected_nodes).issubset(found): + raise CliGateError("CLI browse did not expose every expected child") + return {"nodes": found, "count": len(found)} + + +def validate_denial(result, *, command, expected_statuses): + if not isinstance(result, ProcessResult) or result.cancelled or result.timed_out or result.truncated: + raise CliGateError("denial evidence was cancelled, timed out, or was truncated") + combined = result.stdout + "\n" + result.stderr + if not expected_statuses or not any(status in combined for status in expected_statuses): + raise CliGateError("CLI did not explicitly report the expected denial") + if command == "write" and "Write successful:" in combined: + raise CliGateError("denied CLI write reported success") + if command == "read" and re.search(r"^Status:[ \t]*Good$", combined, re.M): + raise CliGateError("denied CLI read reported Good") + return {"denied": True, "command": command} + + +def resolve_node_id(namespace_array, namespace_uri, identifier): + """Resolve only by an observed NamespaceArray; ambiguous/absent URIs fail.""" + if not isinstance(namespace_array, list) or namespace_array.count(namespace_uri) != 1: + raise CliGateError("namespace URI is absent or ambiguous") + index = namespace_array.index(namespace_uri) + if not 0 < index <= 65535 or not isinstance(identifier, str) or not identifier: + raise CliGateError("invalid namespace or string identifier") + return f"ns={index};s={identifier}" + + _COUNTERS = { "total": "Total subscribed", "ever_bad": " Ever went BAD during window", @@ -128,7 +172,7 @@ def validate_subscription(result, *, summary_text, expected_nodes, require_chang if node not in expected: raise CliGateError("CLI notification refers to an unexpected node") _timestamp(timestamp) - if status != "Good": + if not is_good_status(status): raise CliGateError("CLI notification status is not Good") notifications[node].append(value) for values in notifications.values(): @@ -140,6 +184,39 @@ def validate_subscription(result, *, summary_text, expected_nodes, require_chang "summary": file_counts} +def validate_recovery_subscription(result, *, summary_text, expected_node, require_gap, require_held_session=False): + _process_ok(result) + attached = re.findall(r"^Subscribed to (\d+)/(\d+) nodes \(interval: (\d+)ms\)\.", result.stdout, re.M) + if len(attached) != 1 or attached[0][:2] != ("1", "1") or int(attached[0][2]) <= 0 or "FAILED to subscribe" in result.stdout: + raise CliGateError("recovery subscription did not attach its item") + counts = _summary(summary_text) + if counts != _summary(result.stdout) or counts["total"] != 1 or counts["good"] != 1 or counts["bad"] or counts["never"]: + raise CliGateError("CLI subscription did not finish with a recovered Good item") + if require_gap and counts["ever_bad"] != 1: + raise CliGateError("CLI subscription did not observe the remote quality gap") + if require_held_session and re.search(r"Session lost on .+?\. Attempting failover\.\.\.", + result.stdout.split(_SUMMARY_HEADING, 1)[0]): + raise CliGateError("CLI started transport failover before the held subscription finished") + notifications = re.findall(r"^\[([^\]]+)\] (.+?) = (.*) \(([^()]*)\)$", result.stdout, re.M) + good = [] + for timestamp, node, value, status in notifications: + if node != expected_node: + raise CliGateError("recovery notification has unexpected node") + _timestamp(timestamp) + if is_good_status(status): + good.append(value) + if len(good) < 2 or len(set(good)) < 2: + raise CliGateError("recovery lacks changing Good values") + if not notifications or not is_good_status(notifications[-1][3]): + raise CliGateError("recovery final notification is not Good") + if require_gap: + bad_indexes = [index for index, entry in enumerate(notifications) if entry[3].startswith("Bad")] + if not bad_indexes or not any(is_good_status(entry[3]) for entry in notifications[:bad_indexes[0]]) or not any( + is_good_status(entry[3]) for entry in notifications[bad_indexes[-1] + 1:]): + raise CliGateError("recovery must have Good notifications before and after a Bad gap") + return {"summary": counts, "good_notifications": len(good)} + + def _local_endpoint(url): try: parsed = urlsplit(url) @@ -154,7 +231,7 @@ def _local_endpoint(url): def build_cli_argv(dll, command, endpoint, credential, *, node=None, value=None, summary_file=None, duration=30, interval=200, recursive=False, depth=6, - partner_endpoint=None): + partner_endpoint=None, max_age_ms=0): """Build portable argv from a published DLL and current supported CLI flags. Returned argv contains the key solely to pass it to the CLI, which currently @@ -177,10 +254,16 @@ def build_cli_argv(dll, command, endpoint, credential, *, node=None, value=None, if not isinstance(node, str) or not node: raise CliGateError("an explicit resolved NodeId is required") argv.extend(["-n", node]) + if command == "read": + if type(max_age_ms) is not int or not 0 <= max_age_ms <= 30000: + raise CliGateError("read maximum age must be a bounded millisecond value") + if max_age_ms: + argv.extend(["--max-age", str(max_age_ms)]) if command == "write": if value is None: raise CliGateError("an explicit write value is required") - argv.extend(["-v", str(value)]) + # The physical fixture scalars are UInt16; writing must not require read access. + argv.extend(["-v", str(value), "--type", "UInt16"]) if command == "browse" and recursive: if type(depth) is not int or depth <= 0: raise CliGateError("browse depth must be positive") @@ -200,10 +283,20 @@ def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--run-id", required=True) parser.add_argument("--scenario", required=True) - parser.parse_args(argv) - print("grpc-data CLI gate: scenario prerequisites not configured; production rig, published CLI, " - "restricted manifest, and concrete scenario assertions are required", file=sys.stderr) - return 2 + parser.add_argument("--manifest", type=Path) + parser.add_argument("--cli-dll", type=Path) + parser.add_argument("--probe-dll", type=Path) + arguments = parser.parse_args(argv) + try: + from scenarios import ScenarioRunner + runner = ScenarioRunner(arguments.run_id, manifest_path=arguments.manifest, + cli_dll=arguments.cli_dll, probe_dll=arguments.probe_dll) + report = runner.run(arguments.scenario) + print(__import__("json").dumps(report, sort_keys=True)) + return 0 if report["passed"] else 1 + except Exception as error: + print("grpc-data CLI gate: " + type(error).__name__ + "; restricted diagnostics retained", file=sys.stderr) + return 2 if __name__ == "__main__": diff --git a/scripts/validation/grpc-data/compose.yml b/scripts/validation/grpc-data/compose.yml index 98f932fd8..6d205f88f 100644 --- a/scripts/validation/grpc-data/compose.yml +++ b/scripts/validation/grpc-data/compose.yml @@ -1,4 +1,4 @@ -# P10 standalone infrastructure scaffold. Secrets and TLS files are generated in +# P10 standalone owned local integration rig. Secrets and TLS files are generated in # a run-owned restricted directory. See README.md before using this file. name: ${GRPC_DATA_PROJECT:?run-scoped project required} @@ -7,6 +7,9 @@ x-labels: &labels otopcua.grpc-data.fixture: "v1" x-common-env: &common-env + ASPNETCORE_HOSTINGSTARTUPASSEMBLIES: GrpcDataNodeProbe + DOTNET_ADDITIONAL_DEPS: /app/GrpcDataNodeProbe.deps.json + GRPC_DATA_NODE_PROBE_DIR: /grpc-data-probe Security__Ldap__Enabled: "false" Security__Auth__DisableLogin: "true" Security__Acl__Enabled: "true" @@ -30,8 +33,6 @@ x-common-env: &common-env LocalDb__Path: /app/data/otopcua-localdb.db Serilog__MinimumLevel__Override__Microsoft.EntityFrameworkCore: Warning Serilog__MinimumLevel__Override__Microsoft.AspNetCore: Warning - # P07_TLS_BINDING_PENDING: match the actual P07 listener/client option names - # before enabling data gRPC. Certificate mounts are already isolated below. x-control-env: &control-env <<: *common-env @@ -57,6 +58,15 @@ x-data-env: &data-env ConfigSource__ApiKey: ${GRPC_DATA_CONFIG_KEY:?generated config key required} LocalDb__SyncListenPort: "9001" LocalDb__Replication__MaxBatchSize: "16" + ASPNETCORE_HOSTINGSTARTUPASSEMBLIES: GrpcDataNodeProbe + DOTNET_ADDITIONAL_DEPS: /app/GrpcDataNodeProbe.deps.json + GRPC_DATA_NODE_PROBE_DIR: /grpc-data-probe + DataConnections__Enabled: "true" + DataConnections__ListenPort: "4057" + DataConnections__CertificatePath: /run/grpc-data/tls/server.pem + DataConnections__CertificateKeyPath: /run/grpc-data/tls/server.key + DataConnections__CredentialBundlePath: /run/grpc-data/credentials/bundle.json + DataConnections__TrustBundlePath: /run/grpc-data/credentials/trust.json x-host: &host image: ${GRPC_DATA_IMAGE:?run-scoped current-SHA image required} @@ -68,7 +78,7 @@ x-host: &host migrator: {condition: service_completed_successfully} x-founder-health: &founder-health - test: ["CMD-SHELL", "bash -c ' 256: + raise ValueError("invalid credential scope") + seen = set() + for entry in entries: + if not isinstance(entry, dict) or not isinstance(entry.get("ConnectionId"), str) or not entry["ConnectionId"].strip(): + raise ValueError("invalid connection identity") + identity = entry["ConnectionId"].upper() + reference = entry.get("SecretReference", "") + if identity in seen or not re.fullmatch(r"secret:data/[a-z0-9][a-z0-9._/-]*", reference) or ".." in reference: + raise ValueError("invalid secret scope") + if type(entry.get("Deleted")) is not bool or (not entry["Deleted"] and (not isinstance(entry.get("Value"), str) or not entry["Value"])): + raise ValueError("fixture requires an explicit active credential or deletion marker") + seen.add(identity) + + +def provision_tls(destination, nodes): + """Create CA and SAN server certificates before any deployment exists.""" + destination = Path(destination) + if destination.exists(): + raise FileExistsError("credential directory already exists") + if not nodes or any(not re.fullmatch(r"[a-z][a-z0-9-]{0,62}", node) for node in nodes): + raise ValueError("invalid local node identity") + destination.mkdir(mode=0o700) + try: + ca_key, ca = destination / "ca.key", destination / "ca.pem" + _openssl("req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes", + "-keyout", ca_key, "-out", ca, "-days", "2", "-subj", "/CN=grpc-data-local-run", + "-addext", "basicConstraints=critical,CA:TRUE", "-addext", "keyUsage=critical,keyCertSign,cRLSign") + for node in nodes: + tls = destination / "tls" / node + tls.mkdir(parents=True, mode=0o700) + extension = tls / "extensions.cnf" + atomic_write_secret(extension, f"subjectAltName=DNS:{node}\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=serverAuth\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid,issuer\n") + _openssl("req", "-new", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes", + "-keyout", tls / "server.key", "-out", tls / "request.pem", "-subj", f"/CN={node}") + _openssl("x509", "-req", "-in", tls / "request.pem", "-CA", ca, "-CAkey", ca_key, + "-set_serial", str(int.from_bytes(os.urandom(16), "big")), "-out", tls / "server.pem", + "-days", "2", "-extfile", extension) + (tls / "request.pem").unlink() + extension.unlink() + for path in destination.rglob("*"): + path.chmod(0o700 if path.is_dir() else 0o600) + except BaseException: + shutil.rmtree(destination) + raise + + +def write_bundles(destination, nodes): + """Atomically publish bundles only for an authoritative deployed scope.""" + _validate_nodes(nodes) + destination = Path(destination) + root_der = base64.b64encode(_openssl("x509", "-in", destination / "ca.pem", "-outform", "DER")).decode("ascii") + (destination / "credentials").mkdir(exist_ok=True, mode=0o700) + for node, scope in nodes.items(): + bundle_path = destination / "credentials" / node + bundle_path.mkdir(parents=True, exist_ok=True, mode=0o700) + common = {"OwnerCluster": scope["owner"], "ConsumerNode": node + ":4053", "ScopeVersion": scope["scope_version"]} + atomic_write_secret(bundle_path / "bundle.json", json.dumps({**common, "Version": scope.get("bundle_version", 1), "Entries": scope["entries"]})) + atomic_write_secret(bundle_path / "trust.json", json.dumps({**common, "Entries": [ + {"ConnectionId": entry["ConnectionId"], "Version": scope.get("trust_version", 1), "Roots": scope.get("trust_roots", [root_der])} for entry in scope["entries"]]})) + + +def provision(destination, nodes): + """Compatibility helper for callers that already hold a deployed scope.""" + destination = Path(destination) + if destination.exists(): + raise FileExistsError("credential directory already exists") + _validate_nodes(nodes) + provision_tls(destination, nodes) + try: + write_bundles(destination, nodes) + except BaseException: + shutil.rmtree(destination) + raise diff --git a/scripts/validation/grpc-data/device/Dockerfile b/scripts/validation/grpc-data/device/Dockerfile index 6f3d2218a..457aea6d5 100644 --- a/scripts/validation/grpc-data/device/Dockerfile +++ b/scripts/validation/grpc-data/device/Dockerfile @@ -1,6 +1,8 @@ FROM python:3.13-slim WORKDIR /fixture COPY scripts/validation/grpc-data/device/server.py /fixture/server.py +ARG DEVICE_TREE_HASH +RUN test -n "$DEVICE_TREE_HASH" && printf '%s\n' "$DEVICE_TREE_HASH" > /fixture/source-hash EXPOSE 5020 8080 USER 65534:65534 ENTRYPOINT ["python", "-u", "/fixture/server.py"] diff --git a/scripts/validation/grpc-data/device/server.py b/scripts/validation/grpc-data/device/server.py index 31c71e5ec..d95ac5dfe 100644 --- a/scripts/validation/grpc-data/device/server.py +++ b/scripts/validation/grpc-data/device/server.py @@ -27,6 +27,9 @@ class DeviceState: self._lock = threading.RLock() self._registers = {0: 0, 10: 7, 11: 11, 12: 13} self._registers.update({address: 0 for address in range(20, 64)}) + self._registers.update({24: 7, 25: 11, 26: 13}) + text = b"grpc data source" + self._registers.update({40 + offset // 2: int.from_bytes(text[offset:offset + 2], "big") for offset in range(0, len(text), 2)}) self._effect_total = 0 self._read_total = 0 self._request_total = 0 diff --git a/scripts/validation/grpc-data/node-probe/GrpcDataNodeProbe.csproj b/scripts/validation/grpc-data/node-probe/GrpcDataNodeProbe.csproj new file mode 100644 index 000000000..995b675e1 --- /dev/null +++ b/scripts/validation/grpc-data/node-probe/GrpcDataNodeProbe.csproj @@ -0,0 +1,10 @@ + + GrpcDataNodeProbefalse + + + + + + + + diff --git a/scripts/validation/grpc-data/node-probe/NodeProbeStartup.cs b/scripts/validation/grpc-data/node-probe/NodeProbeStartup.cs new file mode 100644 index 000000000..0b9fbb0ea --- /dev/null +++ b/scripts/validation/grpc-data/node-probe/NodeProbeStartup.cs @@ -0,0 +1,272 @@ +using System.Text.Json; +using System.Text.RegularExpressions; +using Grpc.Core; +using Grpc.Net.Client; +using GrpcDataProbe; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using T = ZB.MOM.WW.OtOpcUa.Commons.Protos.Telemetry.V1; + +[assembly: HostingStartup(typeof(GrpcDataNodeProbe.NodeProbeStartup))] + +namespace GrpcDataNodeProbe; + +/// Loaded only by the isolated Docker fixture's explicit hosting-startup assembly. +public sealed class NodeProbeStartup : IHostingStartup +{ + public void Configure(IWebHostBuilder builder) => builder.ConfigureServices(services => + { + services.AddSingleton(); + services.AddSingleton(); + services.AddHostedService(); + }); +} + +/// Fixture-only process counter; retains no request identity or payload. +public sealed class InboundDataRequestCounter +{ + private long _requests; + public string InstanceId { get; } = Guid.NewGuid().ToString("N"); + public long Requests => Interlocked.Read(ref _requests); + public void Record() => Interlocked.Increment(ref _requests); +} + +/// Observes HTTP arrivals before the fixture Host's authentication and gRPC pipeline. +public sealed class FixtureDataRequestStartupFilter(InboundDataRequestCounter counter) : IStartupFilter +{ + public Action Configure(Action next) => app => + { + app.Use(nextMiddleware => async context => + { + if (context.Connection.LocalPort == 4057) counter.Record(); + await nextMiddleware(context); + }); + next(app); + }; +} + +/// Bounded, one-shot file requests through the caller's deployed DI registry; no listener. +public sealed partial class NodeProbeWorker(IServiceProvider services) : BackgroundService +{ + [GeneratedRegex("^[a-zA-Z0-9][a-zA-Z0-9-]{0,95}$")] + private static partial Regex SafeId(); + private object CaptureOriginAccounting() + { + var hub = services.GetService(); + var acquisition = services.GetService(); + var composition = services.GetService(); + return new + { + retainedBytes = hub?.Resources.RetainedBytes, maximumRetainedBytes = hub?.Resources.MaximumBytes, + reservedDrivers = acquisition?.ReservedDriverCount, maximumReservedDrivers = acquisition?.MaxReservations, + acquisitionOwnerSerial = acquisition?.CurrentOwnerSerial, acquisitionControlGeneration = acquisition?.ControlGeneration, + workload = composition?.CaptureWorkloadAccounting(), + sourceIngressCounters = SourceIngressDiagnostics.Capture(), + definition = "actual origin hub resource charges and physical driver reservation owners; driver count is not source count" + }; + } + + private static async Task LegacyTelemetryAsync(ProbeCommand command, CancellationToken cancellationToken) + { + var observations = new Dictionary(); + var assertions = 0; + void Check(bool condition) + { + if (!condition) throw new InvalidOperationException(); + assertions++; + } + try + { + // These are the two run-owned SOURCE nodes, never a caller-supplied URL. + var address = command.ExpectedNodeId switch + { + "source-1:4053" => "http://source-1:4056", + "source-2:4053" => "http://source-2:4056", + _ => throw new InvalidOperationException() + }; + Check(command.TimeoutSeconds is >= 1 and <= 20); + var key = Environment.GetEnvironmentVariable("Telemetry__ApiKey"); + Check(!string.IsNullOrWhiteSpace(key)); + observations["protocol"] = "authenticated gRPC over HTTP/2"; + observations["service"] = "telemetry.v1.TelemetryStreamService/Subscribe"; + observations["eventClass"] = "DriverHealth"; + observations["target"] = new { mode = "Node", expectedClusterId = "SOURCE", expectedNodeId = command.ExpectedNodeId }; + using var handler = new SocketsHttpHandler + { + AllowAutoRedirect = false, + UseProxy = false, + ConnectTimeout = TimeSpan.FromSeconds(Math.Min(command.TimeoutSeconds, 5)) + }; + using var channel = GrpcChannel.ForAddress(address, new GrpcChannelOptions + { + HttpHandler = handler, + MaxReceiveMessageSize = 64 * 1024 + }); + var client = new T.TelemetryStreamService.TelemetryStreamServiceClient(channel); + var headers = new Metadata { { "authorization", "Bearer " + key } }; + using var call = client.Subscribe(new T.TelemetryStreamRequest { CorrelationId = command.Id }, headers, + deadline: DateTime.UtcNow.AddSeconds(command.TimeoutSeconds), cancellationToken: cancellationToken); + while (await call.ResponseStream.MoveNext(cancellationToken)) + { + var envelope = call.ResponseStream.Current; + // The production local telemetry hub primes new subscribers with its + // actual driver-health snapshot. Other telemetry is not a substitute. + if (envelope.DriverHealth is not { DriverInstanceId: "source-modbus" } health) continue; + Check(envelope.CorrelationId == command.Id); + Check(health.DriverInstanceId == "source-modbus"); + Check(health.HasReportingNodeId); + Check(health.ReportingNodeId == command.ExpectedNodeId); + Check(health.ClusterId == "SOURCE"); + observations["driverInstanceId"] = health.DriverInstanceId; + observations["servingNodeId"] = health.ReportingNodeId; + observations["reportingNodeId"] = health.ReportingNodeId; + observations["clusterId"] = health.ClusterId; + observations["authenticatedSnapshotReceived"] = true; + return new(command.Id, command.Operation, true, assertions, observations); + } + return new(command.Id, command.Operation, false, assertions, observations, "SnapshotUnavailable"); + } + catch (Exception error) when (error is not OutOfMemoryException) + { + // Headers, credentials and remote exception detail stay out of evidence. + return new(command.Id, command.Operation, false, assertions, observations, error.GetType().Name); + } + } + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + var configured = Environment.GetEnvironmentVariable("GRPC_DATA_NODE_PROBE_DIR"); + if (string.IsNullOrWhiteSpace(configured) || !Path.IsPathFullyQualified(configured)) + throw new InvalidOperationException("Fixture command directory required."); + var folder = new DirectoryInfo(configured); + folder.Create(); + if (folder.LinkTarget is not null) throw new InvalidOperationException("Fixture command directory cannot be linked."); + while (!stoppingToken.IsCancellationRequested) + { + foreach (var input in folder.EnumerateFiles("*.request.json").OrderBy(file => file.Name).Take(16)) + { + if (input.LinkTarget is not null || input.Length is <= 0 or > 16384) continue; + var id = input.Name[..^".request.json".Length]; + if (!SafeId().IsMatch(id)) continue; + var resultPath = Path.Combine(folder.FullName, id + ".result.json"); + if (File.Exists(resultPath)) { input.Delete(); continue; } + var claimed = input.FullName + ".running"; + try { File.Move(input.FullName, claimed, overwrite: false); } + catch (IOException) { continue; } + ProbeResult result; + try + { + var command = JsonSerializer.Deserialize(await File.ReadAllTextAsync(claimed, stoppingToken), ProbeEngine.Json) + ?? throw new InvalidOperationException(); + if (command.Id != id || command.TimeoutSeconds is < 1 or > 120) throw new InvalidOperationException(); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); + timeout.CancelAfter(TimeSpan.FromSeconds(command.TimeoutSeconds)); + if (command.Operation == "topology") + { + var cluster = Akka.Cluster.Cluster.Get(services.GetRequiredService()); + var members = cluster.State.Members.Select(member => new + { + host = member.Address.Host, port = member.Address.Port, + status = member.Status.ToString(), roles = member.Roles.ToArray() + }).ToArray(); + result = new(id, "topology", members.Length == 2 && members.All(member => member.status == "Up"), 2, + new() { ["members"] = members, ["self"] = cluster.SelfAddress.ToString(), ["processId"] = Environment.ProcessId }); + var cache = services.GetService(); + var artifact = cache is null ? null : await cache.GetCurrentUnkeyedAsync(timeout.Token); + result.Observations["artifactRevision"] = artifact?.RevisionHash; + result.Observations["deploymentId"] = artifact?.DeploymentId; + result.Observations["connections"] = services.GetService()?.CaptureDiagnostics(); + result.Observations["originAccounting"] = CaptureOriginAccounting(); + result.Observations["process"] = WorkloadEngine.CaptureProcess(); + result.Observations["inboundDataRequests"] = services.GetRequiredService().Requests; + result.Observations["inboundDataRequestObserverId"] = services.GetRequiredService().InstanceId; + } + else if (command.Operation == "warm-state") + { + var settings = services.GetService() ?? WarmRedundancySettings.Unset; + var warm = services.GetRequiredService().Snapshot; + var serving = services.GetRequiredService().Serving; + using var process = System.Diagnostics.Process.GetCurrentProcess(); + result = new(id, command.Operation, true, 1, new() + { + ["nodeId"] = serving.NodeId, ["mode"] = settings.Mode.ToString(), ["isWarm"] = settings.IsWarm, + ["warmRole"] = new { role = warm.Role?.ToString(), generation = warm.Generation }, + ["serving"] = serving, + ["process"] = new { id = Environment.ProcessId, startedUtc = process.StartTime.ToUniversalTime().ToString("O") } + }); + } + else if (command.Operation == "bundle-commit") + { + var observer = services.GetRequiredService(); + var state = await observer.ObserveAsync(command.ConnectionId, timeout.Token); + result = new(id, command.Operation, true, 1, new() + { + ["credentialScopeVersion"] = state.CredentialScopeVersion, + ["credentialVersion"] = state.CredentialVersion, + ["credentialDeleted"] = state.CredentialDeleted, + ["trustScopeVersion"] = state.TrustScopeVersion, + ["trustVersion"] = state.TrustVersion, + ["trustRetired"] = state.TrustRetired + }); + } + else if (command.Operation == "projection-diagnostics") + { + result = CaptureProjectionDiagnostics(command); + } + else if (command.Operation == "legacy-telemetry") + { + // Feature-disable validation must bypass DataConnection acquisition. + result = await LegacyTelemetryAsync(command, timeout.Token); + var callerCluster = Akka.Cluster.Cluster.Get(services.GetRequiredService()); + result.Observations["caller"] = Environment.GetEnvironmentVariable("HOSTNAME"); + result.Observations["callerNodeId"] = $"{callerCluster.SelfAddress.Host}:{callerCluster.SelfAddress.Port}"; + result.Observations["callerClusterId"] = callerCluster.SelfRoles.Single(role => role.StartsWith("cluster-", StringComparison.Ordinal))["cluster-".Length..]; + } + else + { + var runtime = services.GetRequiredService(); + var callerCluster = Akka.Cluster.Cluster.Get(services.GetRequiredService()); + if (!runtime.TryAcquire(command.ConnectionId, out var lease) || lease is null) + result = new(id, command.Operation, command.ExpectedState == "Unavailable", 1, + new() { ["readiness"] = "Unavailable", ["caller"] = Environment.GetEnvironmentVariable("HOSTNAME") }); + else + { + await using (lease) + { + using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, lease.CancellationToken); + result = command.Operation == "workload" + ? await WorkloadEngine.RunAsync(lease.Connection, command, linked.Token, + () => new { connections = runtime.CaptureDiagnostics(), originAccounting = CaptureOriginAccounting() }) + : await ProbeEngine.RunAsync(lease.Connection, command, linked.Token); + result.Observations["caller"] = Environment.GetEnvironmentVariable("HOSTNAME"); + var target = lease.Connection.Target; + result.Observations["target"] = new { mode = target.Mode.ToString(), target.ExpectedClusterId, + target.ExpectedNodeId, consistency = target.Consistency.ToString() }; + result.Observations["realm"] = command.Realm; + result.Observations["namespaceUri"] = command.NamespaceUri; + result.Observations["path"] = command.Path; + } + } + result.Observations["callerNodeId"] = $"{callerCluster.SelfAddress.Host}:{callerCluster.SelfAddress.Port}"; + result.Observations["callerClusterId"] = callerCluster.SelfRoles.Single(role => role.StartsWith("cluster-", StringComparison.Ordinal))["cluster-".Length..]; + } + } + catch (Exception error) when (error is not OutOfMemoryException) + { + var failure = ProbeFailureClassifier.Capture(error, ProbeFailurePhase.NodeProbe); + result = new(id, "invalid", false, 0, + new() { ["failurePhase"] = failure.Phase, ["failureEvidence"] = failure }, failure.Category); + } + var temporary = resultPath + ".tmp"; + await File.WriteAllTextAsync(temporary, JsonSerializer.Serialize(result, ProbeEngine.Json), stoppingToken); + if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(temporary, UnixFileMode.UserRead | UnixFileMode.UserWrite); + File.Move(temporary, resultPath, overwrite: false); + File.Delete(claimed); + } + await Task.Delay(100, stoppingToken); + } + } +} diff --git a/scripts/validation/grpc-data/node-probe/ProjectionDiagnostics.cs b/scripts/validation/grpc-data/node-probe/ProjectionDiagnostics.cs new file mode 100644 index 000000000..b250ed658 --- /dev/null +++ b/scripts/validation/grpc-data/node-probe/ProjectionDiagnostics.cs @@ -0,0 +1,81 @@ +using GrpcDataProbe; +using Microsoft.Extensions.DependencyInjection; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace GrpcDataNodeProbe; + +public sealed partial class NodeProbeWorker +{ + // Fixture-only, read-only inspection. Retained validity and item observations + // are bounded diagnostics, not an atomic authorization decision. + private ProbeResult CaptureProjectionDiagnostics(ProbeCommand command) + { + if (!Enum.TryParse(command.Realm, true, out var realm) || + realm is not (DataRealm.Raw or DataRealm.Uns) || + string.IsNullOrWhiteSpace(command.OriginCluster) || command.OriginCluster.Length > 128 || + string.IsNullOrWhiteSpace(command.NamespaceUri) || command.NamespaceUri.Length > 1024 || + string.IsNullOrWhiteSpace(command.Path) || command.Path.Length > 4096) + throw new ArgumentException("Invalid fixture projection target."); + + var mapping = command.OperationId ?? (realm == DataRealm.Raw ? "map-raw" : "map-uns"); + if (string.IsNullOrWhiteSpace(mapping) || mapping.Length > 128) + throw new ArgumentException("Invalid fixture mapping."); + var identifier = ProjectedDataIds.Identifier(mapping, + new DataAddress(command.OriginCluster, command.NamespaceUri, "string", command.Path)); + var nodes = services.GetRequiredService(); + var catalog = services.GetRequiredService(); + var mappings = services.GetRequiredService(); + var access = services.GetService(); + var accessPresent = access is not null; + var nodeIdResolvable = nodes.TryGetNodeId(ProjectedDataIds.NamespaceUri(realm), identifier, out var nodeId); + ProjectedVariableDefinition? definition = null; + var definitionResolvable = nodeIdResolvable && nodeId is { } actual && nodes.TryResolve(actual, out definition); + var proofResolvable = catalog.TryResolveProjected(realm, identifier, out var proof); + var connectionPresent = mappings.TryGetConnectionId(mapping, out var connectionId); + var cache = services.GetRequiredService(); + var capture = typeof(ProjectedCatalogCache).GetMethod("CaptureRetainedDiagnostics", + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + var retained = capture?.Invoke(cache, [realm, identifier]); + var retainedFlags = new Dictionary(); + foreach (var name in new[] { "Retained", "Retired", "Generation", "RouteAlive", "LocalAuthorityActive", + "RemoteLeaseValid", "MappingBindingCurrent", "CacheGenerationCurrent" }) + retainedFlags[name] = retained?.GetType().GetProperty(name)?.GetValue(retained); + var metadataMatches = definition is not null && proof is not null && + proof.Metadata.Dimensions.SequenceEqual(definition.Metadata.Dimensions) && + (proof.Metadata with { Dimensions = definition.Metadata.Dimensions }) == definition.Metadata; + var deferred = services.GetService(); + var sdk = deferred?.GetCapability(); + var manager = sdk?.GetType().GetField("_nodeManager", + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)?.GetValue(sdk); + var sdkItems = SdkItemDiagnostics.Capture(manager, nodeId); + var observations = new Dictionary + { + ["nodeIdResolvable"] = nodeIdResolvable, + ["definitionResolvable"] = definitionResolvable, + ["definitionAuthorityCurrent"] = definition?.AuthorityIsCurrent(), + ["definitionLifetimeActive"] = definition?.Lifetime.IsActive, + ["definitionGeneration"] = definition?.ProjectionGeneration, + ["proofResolvable"] = proofResolvable, + ["proofGeneration"] = proof?.Generation, + ["generationMatches"] = definition is not null && proof is not null && definition.ProjectionGeneration == proof.Generation, + ["metadataMatches"] = metadataMatches, + ["leaseValid"] = proof?.Lease.IsValid, + ["leaseRemainingMilliseconds"] = null, // IDataAuthorizationLease does not expose a remaining duration. + ["retainedValidity"] = retainedFlags, + ["maximumSampleAgeMilliseconds"] = proof?.MaximumSampleAge.TotalMilliseconds, + ["servingGeneration"] = proof?.Lease.Serving.ServingGeneration, + ["allowedOperations"] = proof?.Subject.AllowedOperations.ToString(), + ["connectionMappingPresent"] = connectionPresent && !string.IsNullOrWhiteSpace(connectionId), + ["projectedAccessPresent"] = accessPresent, + ["streamCounters"] = ProjectedStreamDiagnostics.Capture(), + ["deliveryCounters"] = ProjectedDeliveryDiagnostics.Capture(), + ["sdkItems"] = sdkItems, + ["runtimeCohorts"] = RuntimeCohortDiagnostics.Capture(access, catalog, realm, identifier, proof), + ["callerAuthorization"] = "unknown: no caller identity is supplied to this fixture diagnostic" + }; + return new(command.Id, command.Operation, true, 1, observations); + } +} diff --git a/scripts/validation/grpc-data/node-probe/RuntimeCohortDiagnostics.cs b/scripts/validation/grpc-data/node-probe/RuntimeCohortDiagnostics.cs new file mode 100644 index 000000000..8a31b913d --- /dev/null +++ b/scripts/validation/grpc-data/node-probe/RuntimeCohortDiagnostics.cs @@ -0,0 +1,138 @@ +using System.Collections; +using System.Reflection; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace GrpcDataNodeProbe; + +// Fixture-only read-only snapshots. References are copied under their owning +// locks; validity callbacks run after releasing those locks. Results are not an +// atomic authorization decision and never include values, callers or secrets. +internal static class RuntimeCohortDiagnostics +{ + private const BindingFlags Members = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + private const int ScanLimit = 16384; + private const int ItemLimit = 16; + internal sealed record Serving(string NodeId, string Incarnation, string Role, long CatalogEpoch, + long AuthorityEpoch, long ServingGeneration); + internal sealed record Proof(bool? LeaseValid, bool? LocalAuthorityActive, bool? CacheUsable, bool? IsCurrentCacheProof, + long? Generation, long? MappingRevision, double? RemainingMilliseconds, Serving? Serving); + internal sealed record Cohort(Serving? Serving, double? IntervalMilliseconds, int? Started, int? Closing, + int? HealthyBaseline, int? ServingMismatch, long? AttemptEpoch); + internal sealed record Demand(bool? Disposed, bool? Valid, string? Operation, bool? NodePinValid, + bool? DefinitionLifetimeActive, bool? DefinitionAuthorityCurrent, long? DefinitionGeneration, + Proof? Proof, Cohort? Cohort); + internal sealed record Source(bool? ReadOwned, bool? NodePinValid, bool? DefinitionLifetimeActive, + bool? DefinitionAuthorityCurrent, int? ActiveAttempts, long? AttemptEra, long? AuthorityGeneration, + long? LastVersion, bool? CachedSamplePresent, Proof? Current, Proof? Previous); + internal sealed record Snapshot(bool Available, bool Truncated, int DemandsScanned, int SourcesScanned, + int? UnaryCount, long? UnaryBytes, IReadOnlyList Demands, IReadOnlyList Sources); + + private sealed record DemandRefs(IProjectedDemandLease Demand, object? Binding, object? Cohort, object? CohortKey); + private sealed record SourceRefs(object Source, object? Key); + + internal static Snapshot Capture(ProjectedDataAccess? access, IFederatedProjectionCatalog catalog, + DataRealm realm, string identifier, ProjectedNodeProof? currentCacheProof) + { + if (access is null) return new(false, false, 0, 0, null, null, [], []); + try + { + var sync = Field(access, "_sync"); + var demands = Field(access, "_demands") as IEnumerable; + var memberships = Field(access, "_demandCohorts") as IDictionary; + var sources = Field(access, "_sources") as IDictionary; + if (sync is null || demands is null || memberships is null || sources is null) + return new(false, false, 0, 0, null, null, [], []); + var selectedDemands = new List(); var selectedSources = new List(); + var demandsScanned = 0; var sourcesScanned = 0; var truncated = false; + int? unaryCount; long? unaryBytes; + lock (sync) + { + unaryCount = Field(access, "_unaryCount") as int?; + unaryBytes = Field(access, "_unaryBytes") as long?; + foreach (var item in demands) + { + if (++demandsScanned > ScanLimit) { truncated = true; break; } + if (item is not IProjectedDemandLease demand || demand.Realm != realm || demand.LocalIdentifier != identifier) continue; + if (selectedDemands.Count == ItemLimit) { truncated = true; break; } + var cohort = memberships.Contains(item) ? memberships[item] : null; + selectedDemands.Add(new(demand, Property(item, "CurrentBinding"), cohort, Field(cohort, "_key"))); + } + foreach (DictionaryEntry entry in sources) + { + if (++sourcesScanned > ScanLimit) { truncated = true; break; } + var key = entry.Key; + if (Property(key, "Realm") is not DataRealm sourceRealm || sourceRealm != realm || + Property(key, "LocalIdentifier") as string != identifier) continue; + if (selectedSources.Count == ItemLimit) { truncated = true; break; } + if (entry.Value is { } source) selectedSources.Add(new(source, key)); + } + } + var describedDemands = selectedDemands.Select(item => DescribeDemand(item, catalog, currentCacheProof)).ToArray(); + var describedSources = selectedSources.Select(item => DescribeSource(item, catalog, currentCacheProof)).ToArray(); + return new(true, truncated, Math.Min(demandsScanned, ScanLimit), Math.Min(sourcesScanned, ScanLimit), + unaryCount, unaryBytes, describedDemands, describedSources); + } + catch (Exception error) when (error is not OutOfMemoryException) + { return new(false, false, 0, 0, null, null, [], []); } + } + + private static Demand DescribeDemand(DemandRefs item, IFederatedProjectionCatalog catalog, ProjectedNodeProof? currentCacheProof) + { + var definition = Property(item.Binding, "Definition") as ProjectedVariableDefinition; + var proof = Property(item.Binding, "Proof") as ProjectedNodeProof; + var nodePin = Property(item.Binding, "NodePin") as IProjectedNodePin; + var operation = Property(item.Demand, "RequestedOperation") is DataOperations value ? value.ToString() : null; + var cohort = item.Cohort is null ? null : new Cohort( + DescribeServing(Property(item.CohortKey, "Serving") as ServingIdentity), + (Property(item.CohortKey, "Interval") as TimeSpan?)?.TotalMilliseconds, + Field(item.Cohort, "_started") as int?, Field(item.Cohort, "_closing") as int?, + Field(item.Cohort, "_healthyBaseline") as int?, Field(item.Cohort, "_servingMismatch") as int?, + Field(item.Cohort, "_epoch") as long?); + return new(SafeBool(() => Property(item.Demand, "Disposed") as bool?), SafeBool(() => item.Demand.IsValid), operation, + SafeBool(() => nodePin?.IsValid), SafeBool(() => definition?.Lifetime.IsActive), + SafeBool(() => definition?.AuthorityIsCurrent()), definition?.ProjectionGeneration, + DescribeProof(proof, catalog, currentCacheProof), cohort); + } + + private static Source DescribeSource(SourceRefs item, IFederatedProjectionCatalog catalog, ProjectedNodeProof? currentCacheProof) + { + var gate = Field(item.Source, "Gate") ?? throw new InvalidOperationException("Source gate missing."); + ProjectedNodeProof? current, previous; ProjectedVariableDefinition? definition; IProjectedNodePin? pin; + int? active; long? era, generation, version; bool? readOwned, cached; + lock (gate) + { + current = Field(item.Source, "_proof") as ProjectedNodeProof; + previous = Field(item.Source, "_previousProof") as ProjectedNodeProof; + definition = Field(item.Source, "_definition") as ProjectedVariableDefinition; + pin = Field(item.Source, "_nodePin") as IProjectedNodePin; + active = Field(item.Source, "_activeAttempts") as int?; era = Field(item.Source, "_attemptEra") as long?; + generation = Field(item.Source, "_authorityGeneration") as long?; version = Field(item.Source, "LastVersion") as long?; + readOwned = Field(item.Source, "ReadOwned") as bool?; cached = Field(item.Source, "_cachedSample") is not null; + } + return new(readOwned, SafeBool(() => pin?.IsValid), SafeBool(() => definition?.Lifetime.IsActive), + SafeBool(() => definition?.AuthorityIsCurrent()), active, era, generation, version, cached, + DescribeProof(current, catalog, currentCacheProof), DescribeProof(previous, catalog, currentCacheProof)); + } + + private static Proof? DescribeProof(ProjectedNodeProof? proof, IFederatedProjectionCatalog catalog, ProjectedNodeProof? currentCacheProof) + { + if (proof is null) return null; + return new(SafeBool(() => proof.Lease.IsValid), SafeBool(() => proof.Resolver.LocalAuthority.IsActive), + SafeBool(() => catalog.IsUsableProof(proof)), ReferenceEquals(proof, currentCacheProof), proof.Generation, + proof.Metadata.View.MappingRevision, SafeDouble(() => (Property(proof.Lease, "Remaining") as TimeSpan?)?.TotalMilliseconds), + DescribeServing(proof.Lease.Serving)); + } + + private static Serving? DescribeServing(ServingIdentity? serving) => serving is null ? null : + new(Bounded(serving.NodeId, 512), Bounded(serving.Incarnation, 256), Bounded(serving.Role, 32), + serving.CatalogEpoch, serving.AuthorityEpoch, serving.ServingGeneration); + private static string Bounded(string value, int length) => value.Length <= length ? value : value[..length]; + private static object? Field(object? target, string name) => target?.GetType().GetField(name, Members)?.GetValue(target); + private static object? Property(object? target, string name) => target?.GetType().GetProperty(name, Members)?.GetValue(target); + private static bool? SafeBool(Func read) + { try { return read(); } catch (Exception error) when (error is not OutOfMemoryException) { return null; } } + private static double? SafeDouble(Func read) + { try { return read(); } catch (Exception error) when (error is not OutOfMemoryException) { return null; } } +} diff --git a/scripts/validation/grpc-data/node-probe/SdkItemDiagnostics.cs b/scripts/validation/grpc-data/node-probe/SdkItemDiagnostics.cs new file mode 100644 index 000000000..64a20a230 --- /dev/null +++ b/scripts/validation/grpc-data/node-probe/SdkItemDiagnostics.cs @@ -0,0 +1,103 @@ +using System.Collections; +using System.Diagnostics; +using System.Reflection; +using Opc.Ua; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; + +namespace GrpcDataNodeProbe; + +// Fixture-only inspection. All returned fields are bounded, fixed-shape state; +// no item, proof, principal, identifier, payload or exception text escapes. +internal static class SdkItemDiagnostics +{ + private const BindingFlags Fields = BindingFlags.Instance | BindingFlags.NonPublic; + private const BindingFlags Properties = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + private const int ScanLimit = 16384; + private const int ItemLimit = 16; + internal sealed record Item(bool? Retired, bool? Suppressed, bool? HealthTracked, bool? DemandPresent, + bool? DemandValid, long? DefinitionGeneration, bool? DefinitionLifetimeActive, bool? DefinitionAuthorityCurrent, + bool? SourceBindingValid, bool? LatestProofValid, int? CandidateCount, int? MonitoringMode); + internal sealed record Snapshot(long ProcessTimestamp, long ProcessFrequency, bool Available, bool Truncated, + int LiveScanned, int HealthScanned, IReadOnlyList Items); + + internal static Snapshot Capture(object? manager, NodeId? target) + { + var timestamp = Stopwatch.GetTimestamp(); + if (manager is null || target is not { } actualTarget) return new(timestamp, Stopwatch.Frequency, false, false, 0, 0, []); + try + { + var type = manager.GetType(); + var live = type.GetField("_liveItems", Fields)?.GetValue(manager) as IEnumerable; + var health = type.GetField("_projectedHealthIndex", Fields)?.GetValue(manager) as IDictionary; + var healthGate = type.GetField("_projectedHealthGate", Fields)?.GetValue(manager); + if (live is null || health is null || healthGate is null) + return new(timestamp, Stopwatch.Frequency, false, false, 0, 0, []); + var found = new Dictionary(System.Collections.Generic.ReferenceEqualityComparer.Instance); + var liveScanned = 0; var healthScanned = 0; var truncated = false; + foreach (var pair in live) + { + if (++liveScanned > ScanLimit) { truncated = true; break; } + var item = pair?.GetType().GetProperty("Key")?.GetValue(pair); + if (!Matches(item, actualTarget)) continue; + if (found.Count == ItemLimit) { truncated = true; break; } + var tracked = pair!.GetType().GetProperty("Value")?.GetValue(pair); + found[item!] = (ReadBool(tracked, "Suppressed"), false); + } + // Copy only references under the index lock. Authority and proof checks + // happen after releasing it, avoiding health-index/manager lock inversion. + var healthItems = new List(); + lock (healthGate) + { + foreach (var key in health.Keys) + { + if (++healthScanned > ScanLimit) { truncated = true; break; } + if (key is not null) healthItems.Add(key); + } + } + foreach (var item in healthItems) + { + if (!Matches(item, actualTarget)) continue; + if (found.TryGetValue(item, out var current)) found[item] = (current.Suppressed, true); + else if (found.Count < ItemLimit) found[item] = (null, true); + else truncated = true; + } + var items = found.Select(pair => Describe(pair.Key, pair.Value.Suppressed, + pair.Value.Health ? true : truncated ? null : false)).ToArray(); + return new(timestamp, Stopwatch.Frequency, true, truncated, Math.Min(liveScanned, ScanLimit), + Math.Min(healthScanned, ScanLimit), items); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { return new(timestamp, Stopwatch.Frequency, false, false, 0, 0, []); } + } + + private static bool Matches(object? item, NodeId target) => + item?.GetType().GetProperty("ProjectedNodeId", Properties)?.GetValue(item) is NodeId id && id == target; + + private static Item Describe(object item, bool? suppressed, bool? healthTracked) + { + var type = item.GetType(); + object? demand, binding, evidence; ProjectedVariableDefinition? definition; int? candidateCount; + var sync = type.GetField("_bindingSync", Fields)!.GetValue(item)!; + lock (sync) + { + demand = type.GetField("_demand", Fields)?.GetValue(item); + binding = type.GetField("_binding", Fields)?.GetValue(item); + evidence = type.GetField("_latestEvidence", Fields)?.GetValue(item); + definition = type.GetField("_definition", Fields)?.GetValue(item) as ProjectedVariableDefinition; + candidateCount = (type.GetField("_candidates", Fields)?.GetValue(item) as ICollection)?.Count; + } + var proof = evidence?.GetType().GetProperty("Proof", Properties)?.GetValue(evidence); + return new(ReadBool(item, "HealthRetired"), suppressed, healthTracked, demand is not null, + Safe(() => (demand as IProjectedDemandLease)?.IsValid), definition?.ProjectionGeneration, Safe(() => definition?.Lifetime.IsActive), + Safe(() => definition?.AuthorityIsCurrent()), ReadBool(binding, "IsValid"), ReadBool(proof, "IsValid"), + candidateCount, SafeInt(() => type.GetProperty("MonitoringMode", Properties)?.GetValue(item) is { } mode + ? Convert.ToInt32(mode) : null)); + } + private static bool? ReadBool(object? target, string property) => + Safe(() => target?.GetType().GetProperty(property, Properties)?.GetValue(target) as bool?); + private static bool? Safe(Func read) + { try { return read(); } catch (Exception ex) when (ex is not OutOfMemoryException) { return null; } } + private static int? SafeInt(Func read) + { try { return read(); } catch (Exception ex) when (ex is not OutOfMemoryException) { return null; } } +} diff --git a/scripts/validation/grpc-data/probe/GrpcDataProbe.csproj b/scripts/validation/grpc-data/probe/GrpcDataProbe.csproj new file mode 100644 index 000000000..60b9adaba --- /dev/null +++ b/scripts/validation/grpc-data/probe/GrpcDataProbe.csproj @@ -0,0 +1,7 @@ + + Exefalse + + + + + diff --git a/scripts/validation/grpc-data/probe/ProbeEngine.cs b/scripts/validation/grpc-data/probe/ProbeEngine.cs new file mode 100644 index 000000000..a2a1e34a8 --- /dev/null +++ b/scripts/validation/grpc-data/probe/ProbeEngine.cs @@ -0,0 +1,316 @@ +using System.Text.Json; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace GrpcDataProbe; + +// Shared by the external wire client and the fixture-only in-process caller. +public sealed record ProbeCommand(string Id, string ConnectionId, string Operation, string Realm = "Raw", + string OriginCluster = "SOURCE", string NamespaceUri = "", string Path = "", string? Subject = null, + int TimeoutSeconds = 30, int Value = 42, string? OperationId = null, string? ExpectedNodeId = null, + string? ExpectedRole = null, string? ExpectedState = null, string? Continuation = null, + long? ExpectedCatalogRevision = null, string? ExpectedIncarnation = null, long? ExpectedGeneration = null, + WorkloadOptions? Workload = null, string? WorkloadUnsNamespaceUri = null, + IReadOnlyDictionary? WorkloadBrowseRoots = null, int? MaximumAgeMilliseconds = 5000); + +public sealed record ProbeResult(string Id, string Operation, bool Passed, int Assertions, + Dictionary Observations, string? Failure = null); + +public static class ProbeEngine +{ + private sealed class ProbeAssertionException(string name) : Exception(name) { } + public static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web) { WriteIndented = true }; + public static async Task RunAsync(IDataConnection connection, ProbeCommand command, CancellationToken stop) + { + if (command.Operation == "workload") return await WorkloadEngine.RunAsync(connection, command, stop); + var observations = new Dictionary(); + var assertions = 0; + var phase = ProbeFailurePhase.ValidateCommand; + DataCapabilities? validatedCapabilities = null; + void Check(bool condition, string name) + { + if (!condition) throw new ProbeAssertionException(name); + assertions++; + } + try + { + if (command.TimeoutSeconds is < 1 or > 120) throw new InvalidOperationException("invalid deadline"); + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(stop); + deadline.CancelAfter(TimeSpan.FromSeconds(command.TimeoutSeconds)); + var ct = deadline.Token; + var budgetSeconds = command.Operation is "write" or "dedup" or "mixed-write" ? 30 : 10; + var budget = new DataBudget(TimeSpan.FromSeconds(Math.Min(command.TimeoutSeconds, budgetSeconds)), 32, 1024 * 1024); + phase = ProbeFailurePhase.GetCapabilities; + var caps = await connection.GetCapabilitiesAsync(budget, ct); + caps.Validate(); + Check(caps.ProtocolMajor == 1, "protocol major"); + Check(caps.ProtocolMinor >= 3 && caps.ResponseServingIdentity && caps.SubscriptionAgeReadiness, "negotiated serving and age protocol"); + Check(!caps.CompactBatches || caps.CompactCodecVersion == 1, "compact negotiation"); + observations["serving"] = caps.Serving; + observations["readiness"] = caps.Readiness.ToString(); + observations["operations"] = caps.Operations.ToString(); + observations["compact"] = caps.CompactBatches; + observations["limits"] = caps.Limits; + if (command.ExpectedNodeId is { } expectedNode) Check(caps.Serving.NodeId == expectedNode, "serving node"); + if (command.ExpectedRole is { } expectedRole) Check(caps.Serving.Role == expectedRole, "serving role"); + if (command.Operation == "capabilities") + { + if (command.ExpectedState is { } state) Check(caps.Readiness.ToString() == state, "expected readiness"); + return new(command.Id, command.Operation, true, assertions, observations); + } + Check(caps.Readiness == DataReadiness.Ready + || command.Operation == "read" && command.ExpectedState == "UnavailableData", "connection ready"); + validatedCapabilities = caps; + var realm = Enum.Parse(command.Realm, ignoreCase: true); + var view = new DataView(new(command.OriginCluster, command.NamespaceUri, "string", command.Path), + realm, null, 0, command.Subject ?? command.Path); + view.Validate(); + if (command.Operation is "browse" or "continuation") + { + phase = ProbeFailurePhase.Metadata; + view = await CanonicalBrowseViewAsync(connection, view, budget, ct); + observations["browseView"] = view; + Check(view.Address.Identifier == command.Path, "canonical browse container identity"); + phase = ProbeFailurePhase.Browse; + var branch = await connection.BrowseAsync(new(view, null, command.Continuation, budget with { MaxItems = 1 }), ct); + observations["status"] = branch.Status.ToString(); + observations["complete"] = branch.Complete; + observations["continuation"] = branch.Continuation; + observations["items"] = branch.Items; + observations["lease"] = branch.Lease; + Check(branch.Status.ToString() == (command.ExpectedState ?? "Good"), "browse status"); + Check(branch.Items.Count <= 1, "page bound"); + var bytes = ZB.MOM.WW.OtOpcUa.Commons.DataConnections.DataProtoMapper.EncodeBrowseResponse(branch).CalculateSize(); + Check(bytes <= budget.MaxBytes, "browse byte budget"); + observations["serializedBytes"] = bytes; + if (branch.Lease is { } lease) Check(lease.Duration > TimeSpan.Zero && lease.Duration <= caps.Limits.MaxMetadataLease, "bounded metadata lease"); + if (!branch.Complete && branch.Status == DataItemStatus.Good) Check(!string.IsNullOrEmpty(branch.Continuation), "cursor present"); + } + else if (command.Operation == "metadata") + { + phase = ProbeFailurePhase.Metadata; + var metadata = await connection.GetMetadataAsync(new([view], budget), ct); + Check(metadata.Count == 1, "metadata cardinality"); + Check(metadata[0].Status.ToString() == (command.ExpectedState ?? "Good"), "metadata status"); + observations["metadata"] = metadata[0].Value; + } + else if (command.Operation == "read") + { + phase = ProbeFailurePhase.Read; + Check(command.MaximumAgeMilliseconds is null or >= 0 and <= 30000, "bounded requested read freshness"); + var maximumAge = command.MaximumAgeMilliseconds is { } milliseconds ? TimeSpan.FromMilliseconds(milliseconds) : (TimeSpan?)null; + var items = await connection.ReadAsync(new([new("one", view, maximumAge)], budget), ct); + try + { + Check(items.Count == 1 && items[0].CorrelationId == "one", "ordered read cardinality"); + observations["status"] = items[0].Status.ToString(); + observations["resultReadiness"] = items[0].Readiness.ToString(); + observations["maximumAgeMilliseconds"] = command.MaximumAgeMilliseconds; + observations["ageBounds"] = new { lowerMilliseconds = items[0].AgeBounds.Lower?.TotalMilliseconds, + upperMilliseconds = items[0].AgeBounds.Upper?.TotalMilliseconds }; + observations["sample"] = items[0].Sample is { } observedSample + ? new { observedSample.StatusCode, observedSample.SourceTimestampUtc, observedSample.ServerTimestampUtc, + observedSample.Serving, observedSample.Version, + value = ZB.MOM.WW.OtOpcUa.Commons.DataConnections.TypedValueCodec.Encode(observedSample.Value).ToString() } + : null; + if (command.ExpectedState == "UnavailableData") + { + Check(items[0].Status is DataItemStatus.WaitingForInitialData or DataItemStatus.Unavailable, + "unavailable data status"); + Check(items[0].Readiness != DataReadiness.Ready, "unavailable data must not be ready"); + Check(items[0].Sample is null, "unavailable data must not carry a sample"); + } + else + Check(items[0].Status.ToString() == (command.ExpectedState ?? "Good"), "read status"); + if (command.ExpectedState is null or "Good") + { + Check(items[0].Readiness == DataReadiness.Ready, "read result readiness"); + if (maximumAge is { } boundedAge) + Check(items[0].AgeBounds.Lower is { } lower && items[0].AgeBounds.Upper is { } upper + && lower >= TimeSpan.Zero && upper >= lower && upper <= boundedAge, "finite read age within requested bound"); + Check(items[0].Sample is not null, "read sample"); + var sample = items[0].Sample!; + Check(sample.StatusCode == 0, "sample quality"); + Check(sample.SourceTimestampUtc != default && sample.ServerTimestampUtc != default, "sample timestamps"); + } + } + finally { foreach (var item in items) item.Dispose(); } + } + else if (command.Operation is "write" or "dedup" or "mixed-write") + { + phase = ProbeFailurePhase.Metadata; + var metadata = await connection.GetMetadataAsync(new([view], budget), ct); + Check(metadata.Count == 1 && metadata[0].Value is not null, "write metadata"); + var meta = metadata[0].Value!; + using var value = Scalar(meta.ValueKind, command.Value); + var item = new WriteItem("one", command.OperationId ?? Guid.NewGuid().ToString("N"), view, value, + command.ExpectedCatalogRevision ?? meta.CatalogRevision, command.ExpectedIncarnation ?? caps.Serving.Incarnation, + budget.Timeout, command.ExpectedGeneration ?? caps.Serving.ServingGeneration); + var batch = command.Operation == "mixed-write" + ? new WriteBatch([item, item with { CorrelationId = "two", OperationId = Guid.NewGuid().ToString("N"), + View = view with { Address = view.Address with { Identifier = command.Path + "/absent" }, Subject = command.Path + "/absent" } }], budget) + : new WriteBatch([item], budget); + phase = ProbeFailurePhase.Write; + var outcomes = await connection.WriteAsync(batch, ct); + // Preserve bounded, non-secret outcome evidence even if an assertion below fails. + observations["outcomes"] = outcomes.Select(result => new + { + result.CorrelationId, + Outcome = new { result.Outcome.State, result.Outcome.StatusCode }, + }).ToArray(); + Check(outcomes.Count == batch.Items.Count, "write cardinality"); + Check(outcomes[0].CorrelationId == "one", "write order"); + Check(outcomes[0].Outcome.State.ToString() == (command.ExpectedState ?? "DriverConfirmedSuccess"), "write outcome"); + if (command.Operation == "mixed-write") Check(outcomes[1].Outcome.State == DataWriteState.RejectedBeforeDispatch, "undispatched item"); + if (command.Operation == "dedup") + { + var duplicate = await connection.WriteAsync(batch, ct); + Check(duplicate.Count == 1 && duplicate[0].Outcome.State == outcomes[0].Outcome.State, "duplicate stable outcome"); + } + observations["outcomes"] = outcomes; + observations["operationId"] = item.OperationId; + } + else if (command.Operation == "subscribe") + { + phase = ProbeFailurePhase.Subscribe; + await using var subscription = await connection.SubscribeAsync(ct); + var id = Guid.NewGuid().ToString("N"); + await subscription.SendAsync(new OpenSubscription(id, 1, "open", TimeSpan.FromSeconds(5), + [new("one", view, new(TimeSpan.FromMilliseconds(200), TimeSpan.FromMilliseconds(200), DataChangeTrigger.StatusValue, null))], + false, TimeSpan.FromSeconds(command.TimeoutSeconds), budget), ct); + var acknowledged = false; + var snapshot = false; + long lastSequence = 0; + var values = new HashSet(StringComparer.Ordinal); + DataItemHandle? handle = null; + var controls = new List(); + var controlCounts = new Dictionary(StringComparer.Ordinal); + var streamEvidence = new Dictionary + { + ["frames"] = 0, ["acknowledged"] = false, ["snapshotValue"] = false, + ["distinctValues"] = 0, ["lastSequence"] = 0L, + ["controlCounts"] = controlCounts, ["controls"] = controls, + }; + observations["stream"] = streamEvidence; + await foreach (var frame in subscription.ReadAllAsync(ct)) + { + streamEvidence["frames"] = (int)streamEvidence["frames"]! + 1; + streamEvidence["lastFrame"] = frame.GetType().Name; + streamEvidence["lastSequence"] = frame.Sequence; + if (frame is DataSubscriptionControl control) + { + var kind = control.Kind.ToString(); + controlCounts[kind] = controlCounts.GetValueOrDefault(kind) + 1; + if (controls.Count < 32) + controls.Add(new { Kind = kind, Reason = SafeControlReason(control.Diagnostic) }); + } + Check(frame.SubscriptionId == id && frame.StreamEpoch == 1 && frame.Sequence > lastSequence, "stream ordering"); + lastSequence = frame.Sequence; + if (frame is DataSubscriptionAck ack) + { + streamEvidence["ackStatuses"] = ack.Items.Take(32).Select(item => item.Status.ToString()).ToArray(); + Check(ack.CommandId == "open" && ack.Items.Count == 1 && ack.Items[0].Status == DataItemStatus.Good && ack.Items[0].Handle is not null, "open acknowledgement"); + handle = ack.Items[0].Handle; + acknowledged = true; + streamEvidence["acknowledged"] = true; + } + if (frame is DataSubscriptionValues update) + { + using (update) + { + snapshot |= update.IsSnapshot; + streamEvidence["snapshotValue"] = snapshot; + foreach (var entry in update.Items) + { + Check(acknowledged && entry.Handle == handle, "acknowledged handle revision"); + Check(entry.Sample.StatusCode == 0 && entry.Readiness == DataReadiness.Ready, "stream quality and readiness"); + values.Add(ZB.MOM.WW.OtOpcUa.Commons.DataConnections.TypedValueCodec.Encode(entry.Sample.Value).ToString()); + streamEvidence["distinctValues"] = values.Count; + } + } + } + if (acknowledged && snapshot && values.Count >= 2) break; + } + Check(acknowledged && snapshot && values.Count >= 2, "changing snapshot and updates"); + observations["distinctValues"] = values.Count; + observations["lastSequence"] = lastSequence; + } + else throw new InvalidOperationException("unsupported operation"); + return new(command.Id, command.Operation, true, assertions, observations); + } + catch (Exception error) when (error is not OutOfMemoryException) + { + var failure = ProbeFailureClassifier.Capture(error, phase); + observations["failurePhase"] = failure.Phase; + observations["failureEvidence"] = failure; + if (command.Operation == "read" && command.ExpectedState == "Denied" && phase == ProbeFailurePhase.Read + && ProbeFailureClassifier.IsPinnedReadPermissionDenied(connection.Target, validatedCapabilities, failure)) + { + observations["status"] = "Denied"; + observations["reason"] = "pinned origin Read RPC explicitly denied the unadvertised operation"; + observations["denialBoundary"] = "origin Read RPC"; + return new(command.Id, command.Operation, true, assertions + 1, observations); + } + if (command.ExpectedState == "TargetIneligible" && phase == ProbeFailurePhase.GetCapabilities + && failure.Category == "TargetIneligible" && !failure.Truncated) + { + observations["readiness"] = "Unavailable"; + observations["selectionRejection"] = "TargetIneligible"; + return new(command.Id, command.Operation, true, assertions + 1, observations); + } + if (command.Operation == "capabilities" && command.ExpectedState == "Unavailable" + && error is InvalidOperationException { Message: "No ready authenticated data endpoint." or "Data endpoint discovery is backing off." }) + { + observations["readiness"] = "Unavailable"; + observations["reason"] = "authenticated endpoint selection failed"; + return new(command.Id, command.Operation, true, assertions + 1, observations); + } + if (command.ExpectedState == "Denied" && (error is UnauthorizedAccessException + || error is Grpc.Core.RpcException { StatusCode: Grpc.Core.StatusCode.PermissionDenied })) + { + observations["status"] = "Denied"; + observations["reason"] = "explicit permission rejection"; + return new(command.Id, command.Operation, true, assertions + 1, observations); + } + // Only fixed local assertion names and classifier codes cross the evidence boundary. + return new(command.Id, command.Operation, false, assertions, observations, + error is ProbeAssertionException ? error.Message : failure.Category); + } + } + + private static string? SafeControlReason(string? diagnostic) => diagnostic switch + { + null => null, + "Source change history expired." or "Source became unavailable." or + "Snapshot catch-up expired; retry later." or "Snapshot lifetime expired; retry later." or + "Snapshot admission exhausted; retry later." or "Freshness snapshot admission exhausted; retry later." or + "Pending snapshot memory exhausted." or "Pending value memory exhausted." or + "Pending value capacity exhausted." or "Pending control capacity exhausted." or + "Transport capacity exhausted." => diagnostic, + _ when diagnostic.StartsWith("Snapshot pacing; retry after ", StringComparison.Ordinal) => "Snapshot pacing", + _ => "Other server control reason", + }; + + internal static async Task CanonicalBrowseViewAsync(IDataConnection connection, DataView requested, + DataBudget budget, CancellationToken stop) + { + // Container IDs and physical authorization subjects are separate in UNS. + // Metadata resolves the authoritative subject without altering Read's + // deliberate forged-subject negative scenario. + var metadata = await connection.GetMetadataAsync(new([requested], budget), stop); + if (metadata.Count != 1 || metadata[0].Status != DataItemStatus.Good || metadata[0].Value is not { } parent + || parent.View.Address != requested.Address || parent.View.Realm != requested.Realm || parent.View.MappingId is not null) + throw new InvalidOperationException("Canonical browse parent metadata unavailable."); + parent.View.Validate(); + return parent.View; + } + + private static DataValue Scalar(DataValueKind kind, int value) => DataValue.FromScalar(kind, kind switch + { + DataValueKind.Int8 => (object)checked((sbyte)value), DataValueKind.UInt8 => checked((byte)value), + DataValueKind.Int16 => checked((short)value), DataValueKind.UInt16 => checked((ushort)value), + DataValueKind.Int32 => value, DataValueKind.UInt32 => checked((uint)value), + DataValueKind.Int64 => (long)value, DataValueKind.UInt64 => checked((ulong)value), + DataValueKind.Float => (float)value, DataValueKind.Double => (double)value, + _ => throw new InvalidOperationException("fixture writable scalar type") + }); +} diff --git a/scripts/validation/grpc-data/probe/ProbeFailureClassifier.cs b/scripts/validation/grpc-data/probe/ProbeFailureClassifier.cs new file mode 100644 index 000000000..a88410d96 --- /dev/null +++ b/scripts/validation/grpc-data/probe/ProbeFailureClassifier.cs @@ -0,0 +1,82 @@ +using System.Security.Authentication; +using Grpc.Core; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace GrpcDataProbe; + +/// Fixed fixture stages; no caller-controlled text is emitted as a stage. +public enum ProbeFailurePhase +{ + ValidateCommand, GetCapabilities, Metadata, Browse, Read, Write, Subscribe, NodeProbe, + WireSetup, WirePositiveCapabilities, WireProtocolMajor, WirePreviousKey, WireBadKey, WireWrongCa, + WireWrongSan, WireWrongListener, WireH2c, WireRetiredCa, WireOperation, Other +} + +/// Fixed local rejection code and an optional gRPC status enum name. +public sealed record ProbeFailureFrame(string Code, string? RpcStatus = null); + +/// Bounded nonsecret exception-chain evidence for fixture assertions. +public sealed record ProbeFailureEvidence(string Phase, string Category, bool Truncated, IReadOnlyList Chain); + +/// Classifies only known local messages and typed transport failure categories. +public static class ProbeFailureClassifier +{ + /// Recognizes only an explicit missing-Read denial from the exact pinned SOURCE primary. + public static bool IsPinnedReadPermissionDenied(DataTarget target, DataCapabilities? capabilities, ProbeFailureEvidence evidence) => + target.Mode == DataTargetMode.Node && target.Consistency == DataConsistency.Primary + && target.ExpectedClusterId == "SOURCE" && target.ExpectedNodeId is "source-1:4053" or "source-2:4053" + && capabilities is { ProtocolMajor: 1, ProtocolMinor: >= 3, Readiness: DataReadiness.Ready, + ResponseServingIdentity: true, SubscriptionAgeReadiness: true, ClusterId: "SOURCE" } + && capabilities.Serving.NodeId == target.ExpectedNodeId && capabilities.Serving.Role == "Primary" + && !string.IsNullOrWhiteSpace(capabilities.Serving.Incarnation) && capabilities.Serving.CatalogEpoch > 0 + && capabilities.Serving.AuthorityEpoch > 0 && capabilities.Serving.ServingGeneration > 0 + && (capabilities.Operations & DataOperations.Read) == 0 + && (capabilities.Operations & ~(DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe)) == 0 + && evidence is { Phase: "Read", Category: "RpcFailure", Truncated: false } + && evidence.Chain.Count == 2 + && evidence.Chain[0] is { Code: "NoReadyEndpoint", RpcStatus: null } + && evidence.Chain[1] is { Code: "RpcFailure", RpcStatus: "PermissionDenied" }; + + /// Recognizes a typed TLS authentication rejection at the retired-CA fixture phase. + public static bool IsRetiredCaTlsRejection(ProbeFailureEvidence evidence) => + evidence is { Phase: "WireRetiredCa", Category: "TlsFailure", Truncated: false } + && evidence.Chain.Count == 3 + && evidence.Chain[0] is { Code: "RpcFailure", RpcStatus: "Internal" or "Unavailable" } + && evidence.Chain[1] is { Code: "TransportFailure", RpcStatus: null } + && evidence.Chain[2] is { Code: "TlsFailure", RpcStatus: null }; + + /// Captures bounded fixed-code evidence without exception text, URIs or stacks. + public static ProbeFailureEvidence Capture(Exception error, ProbeFailurePhase phase) + { + var frames = new List(8); + Exception? current = error; + while (current is not null && frames.Count < 8) + { + frames.Add(current switch + { + InvalidOperationException { Message: "No ready authenticated data endpoint." } => new("NoReadyEndpoint"), + InvalidOperationException { Message: "Endpoint is not an authenticated ready target." } => new("TargetIneligible"), + InvalidOperationException { Message: "Data endpoint discovery is backing off." } => new("DiscoveryBackoff"), + InvalidOperationException { Message: "No ready subscription endpoint." } => new("NoReadySubscriptionEndpoint"), + InvalidOperationException { Message: "Subscriptions unavailable or peer stream capacity exhausted." } => new("SubscriptionUnavailable"), + InvalidOperationException { Message: "Unary capacity exhausted." } => new("UnaryCapacity"), + UnauthorizedAccessException { Message: "Connection credential or trust unavailable." } => new("SecurityMaterialUnavailable"), + TimeoutException { Message: "Original data request budget expired." } => new("RequestBudgetExpired"), + RpcException rpc => new("RpcFailure", Enum.IsDefined(rpc.StatusCode) ? rpc.StatusCode.ToString() : "Unknown"), + AuthenticationException => new("TlsFailure"), + HttpRequestException => new("TransportFailure"), + OperationCanceledException => new("Cancelled"), + _ => new("Other") + }); + current = current.InnerException; + } + var truncated = current is not null; + var ineligible = !truncated && frames.Any(frame => frame.Code == "TargetIneligible") + && frames.All(frame => frame.Code is "NoReadyEndpoint" or "TargetIneligible"); + var category = ineligible ? "TargetIneligible" : frames.Any(frame => frame.Code == "SecurityMaterialUnavailable") + ? "SecurityMaterialUnavailable" : frames.Any(frame => frame.Code == "TlsFailure") ? "TlsFailure" + : frames.Any(frame => frame.Code == "TransportFailure") ? "TransportFailure" + : frames.Any(frame => frame.Code == "RpcFailure") ? "RpcFailure" : "Other"; + return new(Enum.IsDefined(phase) ? phase.ToString() : "Other", category, truncated, frames); + } +} diff --git a/scripts/validation/grpc-data/probe/Program.cs b/scripts/validation/grpc-data/probe/Program.cs new file mode 100644 index 000000000..31399efeb --- /dev/null +++ b/scripts/validation/grpc-data/probe/Program.cs @@ -0,0 +1,249 @@ +using System.Net; +using System.Net.Security; +using System.Net.Sockets; +using System.Security.Authentication; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text.Json; +using Grpc.Core; +using Grpc.Net.Client; +using GrpcDataProbe; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +var failurePhase = ProbeFailurePhase.WireSetup; +string? failureTarget = null; +string? failureOutput = null; +var results = new List(); +try +{ + var arguments = args.Chunk(2).ToDictionary(pair => pair[0], pair => pair.Length == 2 ? pair[1] : throw new ArgumentException()); + failureOutput = arguments.GetValueOrDefault("--output"); + var manifestPath = Path.GetFullPath(arguments["--manifest"]); + Restricted(manifestPath); + using var manifest = JsonDocument.Parse(await File.ReadAllTextAsync(manifestPath)); + var root = manifest.RootElement; + var scenario = arguments.GetValueOrDefault("--scenario", "all"); + if (scenario is not ("all" or "D13" or "wire")) throw new ArgumentException("Unsupported wire scenario."); + var nodes = root.GetProperty("nodes"); + var endpoints = root.GetProperty("endpoints"); + var keyPath = root.GetProperty("credentials").GetProperty("data_key_files").GetProperty("source").GetString()!; + Restricted(keyPath); + var key = (await File.ReadAllTextAsync(keyPath)).Trim(); + var caPath = root.GetProperty("tls").GetProperty("ca_file").GetString()!; + using var ca = X509Certificate2.CreateFromPem(File.ReadAllText(caPath)); + var sourceNodes = nodes.EnumerateObject().Where(item => item.Value.GetProperty("cluster_id").GetString() == "SOURCE").ToArray(); + if (sourceNodes.Length != 2) throw new InvalidOperationException(); + var routes = sourceNodes.ToDictionary(item => item.Name, item => endpoints.GetProperty(item.Name + ".data").GetProperty("host_port").GetInt32()); + foreach (var port in routes.Values) if (port is < 1 or > 65535) throw new InvalidOperationException(); + using var security = new ProbeSecurity(routes, ca, key); + if (scenario is "all" or "D13") + { + foreach (var node in sourceNodes) + { + var name = node.Name; + failureTarget = name is "source-1" or "source-2" ? name : null; + var nodeId = node.Value.GetProperty("node_id").GetString()!; + async Task Reject(string id, string credential, bool correctCa, bool correctName, bool useUi = false, bool plainData = false) + { + failurePhase = id switch + { + "bad-key" => ProbeFailurePhase.WireBadKey, "wrong-ca" => ProbeFailurePhase.WireWrongCa, + "wrong-san" => ProbeFailurePhase.WireWrongSan, "wrong-listener" => ProbeFailurePhase.WireWrongListener, + "h2c-data-listener" => ProbeFailurePhase.WireH2c, _ => ProbeFailurePhase.Other + }; + using var handler = security.Handler(name, correctCa, correctName, useUi + ? endpoints.GetProperty(name + ".admin").GetProperty("host_port").GetInt32() : null); + using var channel = GrpcChannel.ForAddress($"{(useUi || plainData ? "http" : "https")}://{name}:{(useUi ? 9000 : 4057)}", new() { HttpHandler = handler }); + var client = new W.DataConnectionService.DataConnectionServiceClient(channel); + var headers = Headers(credential, "Node", nodeId); + var denied = false; + try { await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, headers, DateTime.UtcNow.AddSeconds(5)); } + catch (RpcException error) when (error.StatusCode is StatusCode.Unauthenticated or StatusCode.PermissionDenied or StatusCode.Unavailable or StatusCode.Unimplemented or StatusCode.Internal) { denied = true; } + results.Add(new(id + "-" + name, "wire-rejection", denied, 1, new() { ["target"] = nodeId, ["rejected"] = denied })); + } + // Each negative changes only one admission input after a positive TLS call. + using (var handler = security.Handler(name)) + using (var channel = GrpcChannel.ForAddress($"https://{name}:4057", new() { HttpHandler = handler })) + { + failurePhase = ProbeFailurePhase.WirePositiveCapabilities; + var client = new W.DataConnectionService.DataConnectionServiceClient(channel); + var caps = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, Headers(key, "Node", nodeId), DateTime.UtcNow.AddSeconds(5)); + var valid = caps.ProtocolMajor == 1 && caps.ClusterId == "SOURCE" && caps.Serving.NodeId == nodeId; + results.Add(new("positive-" + name, "wire-capabilities", valid, 3, new() { ["serving"] = caps.Serving.ToString() })); + var incompatible = false; + failurePhase = ProbeFailurePhase.WireProtocolMajor; + try { await client.GetCapabilitiesAsync(new() { ProtocolMajor = 99 }, Headers(key, "Node", nodeId), DateTime.UtcNow.AddSeconds(5)); } + catch (RpcException error) when (error.StatusCode == StatusCode.Unimplemented) { incompatible = true; } + results.Add(new("protocol-major-" + name, "wire-negotiation", incompatible, 1, new() { ["rejectedIncompatibleMajor"] = incompatible })); + if (arguments.TryGetValue("--previous-key-state", out var previousState)) + { + failurePhase = ProbeFailurePhase.WirePreviousKey; + if (previousState is not ("enabled" or "revoked")) throw new ArgumentException(); + var previousPath = Path.Combine(Path.GetDirectoryName(keyPath)!, "source-previous.key"); + Restricted(previousPath); + var previousKey = (await File.ReadAllTextAsync(previousPath)).Trim(); + var accepted = false; + var explicitlyDenied = false; + try + { + var oldCaps = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, Headers(previousKey, "Node", nodeId), DateTime.UtcNow.AddSeconds(5)); + accepted = oldCaps.Serving.NodeId == nodeId; + } + catch (RpcException error) when (error.StatusCode is StatusCode.Unauthenticated or StatusCode.PermissionDenied) { explicitlyDenied = true; } + results.Add(new("previous-key-" + name, "wire-credential-rotation", previousState == "enabled" ? accepted : explicitlyDenied, 1, + new() { ["expectedState"] = previousState, ["accepted"] = accepted, ["explicitlyDenied"] = explicitlyDenied })); + } + } + await Reject("bad-key", "invalid-presented-key", true, true); + await Reject("wrong-ca", key, false, true); + await Reject("wrong-san", key, true, false); + await Reject("wrong-listener", key, true, true, useUi: true); + await Reject("h2c-data-listener", key, true, true, plainData: true); + if (root.GetProperty("tls").TryGetProperty("rotation", out var rotation) && rotation.GetString() == "retired") + { + failurePhase = ProbeFailurePhase.WireRetiredCa; + using var oldCa = X509Certificate2.CreateFromPem(File.ReadAllText(Path.Combine(Path.GetDirectoryName(caPath)!, "ca-original.pem"))); + using var oldSecurity = new ProbeSecurity(routes, oldCa, key); + using var handler = oldSecurity.Handler(name); + using var channel = GrpcChannel.ForAddress($"https://{name}:4057", new() { HttpHandler = handler }); + var rejected = false; + ProbeFailureEvidence? tlsRejection = null; + try { await new W.DataConnectionService.DataConnectionServiceClient(channel).GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, Headers(key, "Node", nodeId), DateTime.UtcNow.AddSeconds(5)); } + catch (RpcException error) when (ProbeFailureClassifier.IsRetiredCaTlsRejection( + ProbeFailureClassifier.Capture(error, ProbeFailurePhase.WireRetiredCa))) + { + rejected = true; + tlsRejection = ProbeFailureClassifier.Capture(error, ProbeFailurePhase.WireRetiredCa); + } + results.Add(new("retired-ca-" + name, "wire-trust-retirement", rejected, 1, + new() { ["oldCaRejected"] = rejected, ["failureEvidence"] = tlsRejection })); + } + } + } + if (scenario != "D13") + { + var fixture = root.GetProperty("fixture"); + var rawUri = fixture.GetProperty("namespace_uris").GetProperty("raw").GetString()!; + var unsUri = fixture.GetProperty("namespace_uris").GetProperty("uns").GetString()!; + foreach (var mode in new[] { DataTargetMode.Node, DataTargetMode.Cluster }) + { + foreach (var source in mode == DataTargetMode.Node ? sourceNodes : sourceNodes.Take(1)) + { + failurePhase = ProbeFailurePhase.WireOperation; + failureTarget = source.Name is "source-1" or "source-2" ? source.Name : null; + var target = new DataTarget(mode, "SOURCE", mode == DataTargetMode.Node ? source.Value.GetProperty("node_id").GetString() : null, + mode == DataTargetMode.Node ? DataConsistency.ReadyReplica : DataConsistency.Primary); + using var scope = new DataConnectionScopeLease(1, CancellationToken.None, () => { }); + await using var connection = new GrpcDataConnection("wire-probe", target, + (mode == DataTargetMode.Node ? [source] : sourceNodes).Select(item => new Uri($"https://{item.Name}:4057")), + security, scope, 1024 * 1024, 2, eligibleNodeIds: sourceNodes.Select(item => item.Value.GetProperty("node_id").GetString()!).ToHashSet()); + foreach (var realm in new[] { "raw", "uns" }) + { + var path = fixture.GetProperty("origin_paths").GetProperty(realm).GetString()!; + foreach (var operation in new[] { "capabilities", "metadata", "read", "browse" }) + { + var command = new ProbeCommand($"{mode}-{source.Name}-{realm}-{operation}", "wire-probe", operation, + realm, "SOURCE", realm == "raw" ? rawUri : unsUri, + operation == "browse" ? fixture.GetProperty("browse_roots").GetProperty(realm).GetString()! : path, + ExpectedNodeId: mode == DataTargetMode.Node ? source.Value.GetProperty("node_id").GetString() : null); + results.Add(await ProbeEngine.RunAsync(connection, command, CancellationToken.None)); + } + } + } + } + } + var output = JsonSerializer.Serialize(new { schemaVersion = 1, scenario, passed = results.Count > 0 && results.All(result => result.Passed && result.Assertions > 0), results }, ProbeEngine.Json); + if (arguments.TryGetValue("--output", out var outputPath)) + { + await File.WriteAllTextAsync(outputPath, output); + if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(outputPath, UnixFileMode.UserRead | UnixFileMode.UserWrite); + } + Console.WriteLine(output); + return results.Count > 0 && results.All(result => result.Passed && result.Assertions > 0) ? 0 : 1; +} +catch (Exception error) when (error is not OutOfMemoryException) +{ + var failure = ProbeFailureClassifier.Capture(error, failurePhase); + var output = JsonSerializer.Serialize(new { passed = false, failure = failure.Category, + failurePhase = failure.Phase, targetNode = failureTarget, failureEvidence = failure, + results = results.Take(128).ToArray(), partialResultsTruncated = results.Count > 128 }, ProbeEngine.Json); + if (failureOutput is not null && Path.IsPathFullyQualified(failureOutput)) + { + try + { + if (new FileInfo(failureOutput).LinkTarget is null) + { + await File.WriteAllTextAsync(failureOutput, output); + if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(failureOutput, UnixFileMode.UserRead | UnixFileMode.UserWrite); + } + } + catch (Exception) { /* Preserve the original wire failure and exit status. */ } + } + Console.Error.WriteLine(output); + return 2; +} + +static void Restricted(string path) +{ + var file = new FileInfo(path); + if (!file.Exists || file.LinkTarget is not null || !Path.IsPathFullyQualified(path) || file.Length > 1024 * 1024) throw new InvalidOperationException(); + if (!OperatingSystem.IsWindows() && (File.GetUnixFileMode(path) & (UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute)) != 0) + throw new InvalidOperationException(); +} + +static Metadata Headers(string key, string mode, string nodeId) => new() +{ + { "authorization", "Bearer " + key }, { "x-data-target-mode", mode }, { "x-data-cluster-id", "SOURCE" }, + { "x-data-node-id", nodeId }, { "x-data-consistency", "ReadyReplica" } +}; + +sealed class ProbeSecurity(Dictionary routes, X509Certificate2 root, string key) : IDataConnectionSecurityProvider, IDisposable +{ + private readonly X509Certificate2 _untrustedRoot = UntrustedRoot(); + private static X509Certificate2 UntrustedRoot() + { + using var signingKey = ECDsa.Create(ECCurve.NamedCurves.nistP256); + var request = new CertificateRequest("CN=unrelated-grpc-data-probe-ca", signingKey, HashAlgorithmName.SHA256); + request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); + return request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-1), DateTimeOffset.UtcNow.AddHours(1)); + } + public void Dispose() => _untrustedRoot.Dispose(); + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => + ValueTask.FromResult(new("fixture-key-v1", Convert.ToHexString(SHA256.HashData(root.RawData)), key, + () => Handler(endpoint.Host))); + + public HttpMessageHandler Handler(string host, bool correctCa = true, bool correctName = true, int? overridePort = null) + { + if (!routes.TryGetValue(host, out var port)) throw new InvalidOperationException(); + return new SocketsHttpHandler + { + UseProxy = false, + ConnectTimeout = TimeSpan.FromSeconds(5), + ConnectCallback = async (_, token) => + { + var socket = new Socket(SocketType.Stream, ProtocolType.Tcp); + try { await socket.ConnectAsync(IPAddress.Loopback, overridePort ?? port, token); return new NetworkStream(socket, ownsSocket: true); } + catch { socket.Dispose(); throw; } + }, + SslOptions = new SslClientAuthenticationOptions + { + EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13, + RemoteCertificateValidationCallback = (_, certificate, _, _) => + { + if (certificate is null) return false; + using var leaf = X509CertificateLoader.LoadCertificate(certificate.GetRawCertData()); + if (!leaf.MatchesHostname(correctName ? host : "wrong-san.grpc-data.invalid", allowWildcards: false, allowCommonName: false)) return false; + using var chain = new X509Chain(); + chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; + chain.ChainPolicy.CustomTrustStore.Add(correctCa ? root : _untrustedRoot); + chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; + chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.1")); + return chain.Build(leaf); + } + } + }; + } +} diff --git a/scripts/validation/grpc-data/probe/WorkloadEngine.cs b/scripts/validation/grpc-data/probe/WorkloadEngine.cs new file mode 100644 index 000000000..17a6a40af --- /dev/null +++ b/scripts/validation/grpc-data/probe/WorkloadEngine.cs @@ -0,0 +1,364 @@ +using System.Diagnostics; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace GrpcDataProbe; + +// Limits apply to the experiment itself, independently of production admission. +public sealed record WorkloadSource(string Id, string RawPath, string UnsPath, string ExpectedKind = "UInt16", int ExpectedRank = -1, bool RequireChanges = false); +public sealed record WorkloadOptions(string ProfileId, IReadOnlyList Sources, + int Clients = 1, int RegistrationsPerClient = 1, int ViewsPerSource = 1, int DurationSeconds = 8, + int SamplingMilliseconds = 100, int PublishingMilliseconds = 100, double? Deadband = null, + int SlowClientCount = 0, int SlowClientMilliseconds = 0, int BrowseBurst = 0, int BrowseWorkers = 1, + bool Overlap = true, bool RequireAllAdmitted = true, int HubPartitions = 4, bool CompactBatches = true); + +/// Measures real facade streams; it never synthesizes sources or values. +public static class WorkloadEngine +{ + public static async Task RunAsync(IDataConnection connection, ProbeCommand command, CancellationToken stop, Func? captureDiagnostics = null) + { + var observations = new Dictionary(); + var assertions = 0; + var phase = "configuration"; + void Check(bool condition, string name) + { + if (!condition) + { + observations["failedCheck"] = name; + throw new InvalidOperationException(name); + } + assertions++; + } + try + { + var options = command.Workload ?? throw new InvalidOperationException("missing workload"); + Check(options.ProfileId.Length is > 0 and <= 64 && options.Sources.Count is > 0 and <= 64 + && options.Sources.Select(source => source.Id).Distinct().Count() == options.Sources.Count, "bounded sources"); + Check(options.Clients is > 0 and <= 64 && options.RegistrationsPerClient is > 0 and <= 256 + && options.Clients * options.RegistrationsPerClient <= 4096 && options.ViewsPerSource is 1 or 2 + && options.DurationSeconds is >= 2 and <= 90 && command.TimeoutSeconds >= options.DurationSeconds + 10 + && options.SamplingMilliseconds is >= 0 and <= 10000 && options.PublishingMilliseconds is >= 0 and <= 10000 + && options.SlowClientCount >= 0 && options.SlowClientCount <= options.Clients + && options.SlowClientMilliseconds is >= 0 and <= 5000 && options.BrowseBurst is >= 0 and <= 1024 + && options.BrowseWorkers is > 0 and <= 32 && options.HubPartitions is > 0 and <= 16 + && options.RegistrationsPerClient * (options.Overlap ? 1 : options.Clients) >= options.Sources.Count * options.ViewsPerSource + && (options.Overlap || options.Clients * options.RegistrationsPerClient <= options.Sources.Count * options.ViewsPerSource), "bounded experiment"); + var budget = new DataBudget(TimeSpan.FromSeconds(5), 256, 1024 * 1024); + phase = "capabilities"; + var capabilities = await connection.GetCapabilitiesAsync(budget, stop); + Check(capabilities.Readiness == DataReadiness.Ready, "ready workload target"); + Check(!options.CompactBatches || capabilities.CompactBatches, "requested compact codec is supported"); + var views = new List<(WorkloadSource Source, DataView View)>(); + foreach (var source in options.Sources) + { + views.Add((source, new(new(command.OriginCluster, command.NamespaceUri, "string", source.RawPath), DataRealm.Raw, null, 0, source.RawPath))); + if (options.ViewsPerSource == 2) + { + // UNS URI is a public fixture value passed explicitly, never inferred from an index. + var unsUri = command.WorkloadUnsNamespaceUri ?? throw new InvalidOperationException("UNS namespace required"); + views.Add((source, new(new(command.OriginCluster, unsUri, "string", source.UnsPath), DataRealm.Uns, null, 0, source.UnsPath))); + } + } + phase = "metadata"; + foreach (var chunk in views.Chunk(256)) + { + var metadata = await connection.GetMetadataAsync(new(chunk.Select(item => item.View).ToArray(), budget), stop); + Check(metadata.Count == chunk.Length, "metadata cardinality"); + for (var i = 0; i < chunk.Length; i++) + Check(metadata[i].Status == DataItemStatus.Good && metadata[i].Value is { } value + && value.ValueKind.ToString() == chunk[i].Source.ExpectedKind && value.ValueRank == chunk[i].Source.ExpectedRank, + "observed payload kind and rank"); + } + phase = "browse-parent"; + var browseViews = new List(); + if (options.BrowseBurst > 0) + foreach (var leaf in views.Select(item => item.View).DistinctBy(view => view.Realm)) + { + var realm = leaf.Realm.ToString().ToLowerInvariant(); + if (command.WorkloadBrowseRoots is null || !command.WorkloadBrowseRoots.TryGetValue(realm, out var root) + || string.IsNullOrWhiteSpace(root)) throw new InvalidOperationException("Explicit workload browse container required."); + var requested = leaf with { Address = leaf.Address with { Identifier = root }, Subject = root }; + browseViews.Add(await ProbeEngine.CanonicalBrowseViewAsync(connection, requested, budget, stop)); + } + phase = "measurement"; + observations["profile"] = options; + observations["serving"] = capabilities.Serving; + observations["capabilities"] = new { capabilities.CompactBatches, capabilities.Limits }; + observations["processBefore"] = CaptureProcess(); + observations["diagnosticsBefore"] = captureDiagnostics?.Invoke(); + var watch = Stopwatch.StartNew(); + using var measurement = new CancellationTokenSource(TimeSpan.FromSeconds(options.DurationSeconds)); + using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(stop, measurement.Token); + bool MeasurementEnded() => measurement.IsCancellationRequested && !stop.IsCancellationRequested; + var clients = Enumerable.Range(0, options.Clients).Select(index => RunClient(index)).ToArray(); + var browse = RunBrowse(); + var samples = new List(); + while (!lifetime.IsCancellationRequested) + { + samples.Add(new { process = CaptureProcess(), diagnostics = captureDiagnostics?.Invoke() }); + try { await Task.Delay(500, lifetime.Token); } catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { } + } + var results = await Task.WhenAll(clients); + observations["clients"] = results; + phase = "browse-completion"; + var browseResult = await browse; + phase = "reconciliation"; + watch.Stop(); + observations["elapsedSeconds"] = watch.Elapsed.TotalSeconds; + observations["browse"] = browseResult; + observations["processSamples"] = samples; + observations["processAfter"] = CaptureProcess(); + observations["diagnosticsAfter"] = captureDiagnostics?.Invoke(); + observations["bytesDefinition"] = "serialized typed-value protobuf bytes only; excludes frame, HTTP/2 and TLS overhead"; + observations["schedulingDefinition"] = "monotonic client inter-delivery gaps and first-snapshot latency; source age is reported separately"; + Check(results.All(result => result.Failure is null), "all workload tasks completed"); + Check(results.All(result => result.UnreadySamples == 0), "steady workload retains source readiness"); + if (options.RequireAllAdmitted) + { + Check(results.Sum(result => result.Acknowledged) == options.Clients * options.RegistrationsPerClient, "actual acknowledged registrations"); + Check(results.All(result => result.Snapshots == result.Acknowledged && result.Acknowledged > 0 + && result.Controls.GetValueOrDefault("SnapshotEnd") > 0), "every registration initialized in a completed snapshot"); + Check(results.All(result => result.RequiredChangingItems.All(item => item.Changes > 0)), "hot registrations progress"); + Check(results.Where(result => result.Client >= options.SlowClientCount).All(result => result.RequiredChangingItems.All(item => + item.ChangesAfterMidpoint > 0 && item.HotTailMilliseconds <= budget.Timeout.TotalMilliseconds)), "healthy registrations progress through final half within snapshot budget"); + } + else + { + Check(results.Any(result => result.RejectedBeforeStream), "independent bounded stream admission rejection observed"); + Check(results.Any(result => result.Acknowledged > 0 && result.Snapshots == result.Acknowledged), "admitted peers retain initialized service"); + } + Check(browseResult.Completed == options.BrowseBurst, "concurrent browse completion"); + return new(command.Id, command.Operation, true, assertions, observations); + + async Task RunClient(int client) + { + var result = new ClientResult(client); + var items = new Dictionary(StringComparer.Ordinal); + var handles = new Dictionary(); + var id = command.Id + "-c" + client; + var timer = Stopwatch.StartNew(); + long sequence = 0; + var snapshotOpen = false; + var clientPhase = "subscribe"; + try + { + await using var stream = await connection.SubscribeAsync(lifetime.Token); + var definitions = Enumerable.Range(0, options.RegistrationsPerClient).Select(index => + { + var selected = views[(options.Overlap ? index : client * options.RegistrationsPerClient + index) % views.Count]; + var key = "r" + index; + items.Add(key, new(key, selected.Source.Id, selected.View.Realm.ToString(), selected.Source.RequireChanges)); + return new DataSubscriptionItem(key, selected.View, new(TimeSpan.FromMilliseconds(options.SamplingMilliseconds), + TimeSpan.FromMilliseconds(options.PublishingMilliseconds), DataChangeTrigger.StatusValue, options.Deadband)); + }).ToArray(); + clientPhase = "open"; + await stream.SendAsync(new OpenSubscription(id, 1, "open", TimeSpan.FromSeconds(5), definitions, false, + TimeSpan.FromSeconds(options.DurationSeconds + 5), budget), lifetime.Token); + clientPhase = "receive"; + await foreach (var frame in stream.ReadAllAsync(lifetime.Token)) + { + clientPhase = "frame"; + result.LastFrame = new(frame.Sequence, frame.StreamEpoch, frame.GetType().Name, + frame is DataSubscriptionControl marker ? marker.Kind.ToString() : null, + frame is DataSubscriptionValues batch ? batch.Items.Count : null); + if (frame.SubscriptionId != id || frame.StreamEpoch != 1 || frame.Sequence <= sequence) + throw new InvalidOperationException("stream order"); + sequence = frame.Sequence; + if (frame is DataSubscriptionAck ack) + { + if (ack.CommandId != "open" || ack.Items.Count != definitions.Length) throw new InvalidOperationException("ack cardinality"); + foreach (var entry in ack.Items) + { + if (!items.TryGetValue(entry.ClientItemId, out var item)) throw new InvalidOperationException("unknown ack item"); + if (entry.Status == DataItemStatus.Good && entry.Handle is { } handle) + { handles.Add(handle.Handle, item); item.HandleRevision = handle.ItemRevision; result.Acknowledged++; } + else { result.Rejected++; result.RejectionStatuses.Add(entry.Status.ToString()); } + } + } + else if (frame is DataSubscriptionControl control) + { + result.Controls[control.Kind.ToString()] = result.Controls.GetValueOrDefault(control.Kind.ToString()) + 1; + if (control.Kind == DataStreamControlKind.Reset) foreach (var item in items.Values) item.Initialized = false; + if (control.Kind == DataStreamControlKind.SnapshotBegin) + { if (snapshotOpen) throw new InvalidOperationException("nested snapshot"); snapshotOpen = true; } + if (control.Kind == DataStreamControlKind.SnapshotEnd) + { if (!snapshotOpen || handles.Values.Any(item => !item.Initialized)) throw new InvalidOperationException("incomplete snapshot"); snapshotOpen = false; } + } + else if (frame is DataSubscriptionValues update) + { + using (update) + { + foreach (var entry in update.Items) + { + if (!handles.TryGetValue(entry.Handle.Handle, out var item) || entry.Handle.ItemRevision != item.HandleRevision) + throw new InvalidOperationException("unacknowledged revision"); + if (entry.Readiness != DataReadiness.Ready || entry.Sample.StatusCode != 0) + { result.UnreadySamples++; continue; } + if (!item.Initialized && !update.IsSnapshot) throw new InvalidOperationException("delta before snapshot"); + if (update.IsSnapshot && !snapshotOpen) throw new InvalidOperationException("unbracketed snapshot"); + var elapsed = timer.Elapsed.TotalMilliseconds; + if (update.IsSnapshot && !item.Initialized) + { item.Initialized = true; if (item.FirstSnapshotMilliseconds is null) { item.FirstSnapshotMilliseconds = elapsed; result.Snapshots++; } } + var encoded = TypedValueCodec.Encode(entry.Sample.Value); + var fingerprint = encoded.ToString(); + if (item.LastFingerprint is { } previous && previous != fingerprint) + { item.Changes++; if (elapsed >= options.DurationSeconds * 500) item.ChangesAfterMidpoint++; } + item.LastFingerprint = fingerprint; + if (item.LastDeliveryMilliseconds is { } last) item.DeliveryGaps.Observe(elapsed - last); + item.LastDeliveryMilliseconds = elapsed; + if (entry.AgeBounds.Upper is { } age) item.SourceAge.Observe(age.TotalMilliseconds); + item.Samples++; item.TypedValueBytes += encoded.CalculateSize(); + } + } + if (client < options.SlowClientCount && options.SlowClientMilliseconds > 0) + await Task.Delay(options.SlowClientMilliseconds, lifetime.Token); + } + clientPhase = "receive"; + } + clientPhase = "end"; + if (!MeasurementEnded()) throw new InvalidOperationException("Stream ended before the scheduled measurement deadline."); + } + catch (OperationCanceledException) when (MeasurementEnded()) { } + catch (Grpc.Core.RpcException error) when (error.StatusCode == Grpc.Core.StatusCode.Cancelled && MeasurementEnded()) { } + catch (InvalidOperationException error) when (!options.RequireAllAdmitted && error.Message == "Stream capacity exhausted.") + { result.RejectedBeforeStream = true; } + catch (Exception error) when (error is not OutOfMemoryException) + { + result.Failure = FailureCode(error); + result.FailurePhase = clientPhase; + result.FailureMilliseconds = timer.Elapsed.TotalMilliseconds; + } + foreach (var item in items.Values) + item.HotTailMilliseconds = item.LastDeliveryMilliseconds is { } last ? timer.Elapsed.TotalMilliseconds - last : timer.Elapsed.TotalMilliseconds; + result.Items = items.Values.ToArray(); + return result; + } + async Task RunBrowse() + { + var completed = 0; + var latency = new BoundedHistogram(); + using var slots = new SemaphoreSlim(options.BrowseWorkers); + await Task.WhenAll(Enumerable.Range(0, options.BrowseBurst).Select(async index => + { + await slots.WaitAsync(stop); + try + { + var timer = Stopwatch.StartNew(); + var view = browseViews[index % browseViews.Count]; + var branch = await connection.BrowseAsync(new(view, null, null, budget), stop); + if (branch.Status != DataItemStatus.Good) throw new BrowseResponseFailure(branch.Status, view.Realm); + lock (latency) { latency.Observe(timer.Elapsed.TotalMilliseconds); completed++; } + } + finally { slots.Release(); } + })); + return new(completed, latency); + } + } + catch (Exception error) when (error is not OutOfMemoryException) + { + observations["failurePhase"] = phase; + if (error is BrowseResponseFailure browse) + observations["browseFailure"] = new { status = browse.Status.ToString(), realm = browse.Realm.ToString() }; + return new(command.Id, command.Operation, false, assertions, observations, FailureCode(error)); + } + } + + // Emit only fixed local reasons and the enum transport status. + private static string FailureCode(Exception error) => error switch + { + Grpc.Core.RpcException rpc => "rpc:" + rpc.StatusCode, + BrowseResponseFailure => "workload-browse-status", + InvalidOperationException invalid => invalid.Message switch + { + "Stream ended before the scheduled measurement deadline." => "early-stream-end", + "Unexpected stream epoch or sequence." => "remote-order", + "Response serving identity changed." => "serving-identity", + "Duplicate handle or sample version regression." => "remote-version-or-handle", + "Canonical browse parent metadata unavailable." => "browse-parent-metadata", + "No ready authenticated data endpoint." => "no-ready-endpoint", + "No ready subscription endpoint." => "no-ready-subscription-endpoint", + "Data endpoint discovery is backing off." => "endpoint-backoff", + "Unknown acknowledgement." => "remote-ack", + "Acknowledgement expired." => "remote-ack-expired", + "stream order" => "workload-order", + "ack cardinality" => "workload-ack-cardinality", + "unknown ack item" => "workload-ack-item", + "nested snapshot" => "workload-nested-snapshot", + "incomplete snapshot" => "workload-incomplete-snapshot", + "unacknowledged revision" => "workload-handle", + "delta before snapshot" => "workload-delta-before-snapshot", + "unbracketed snapshot" => "workload-unbracketed-snapshot", + _ => nameof(InvalidOperationException) + }, + _ => error.GetType().Name + }; + + private sealed class BrowseResponseFailure(DataItemStatus status, DataRealm realm) : Exception + { + internal DataItemStatus Status { get; } = status; + internal DataRealm Realm { get; } = realm; + } + + public static object CaptureProcess() + { + using var process = Process.GetCurrentProcess(); + var gc = GC.GetGCMemoryInfo(); + return new { atUtc = DateTimeOffset.UtcNow, processId = Environment.ProcessId, process.WorkingSet64, process.PrivateMemorySize64, + totalProcessorMilliseconds = process.TotalProcessorTime.TotalMilliseconds, managedBytes = GC.GetTotalMemory(false), + gc.HeapSizeBytes, gc.FragmentedBytes, gc.TotalCommittedBytes, gc.MemoryLoadBytes, + collections = new[] { GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2) }, threadCount = process.Threads.Count }; + } + public sealed class ClientResult(int client) + { + public int Client { get; } = client; + public int Acknowledged { get; set; } + public int Rejected { get; set; } + public bool RejectedBeforeStream { get; set; } + public int Snapshots { get; set; } + public long UnreadySamples { get; set; } + public HashSet RejectionStatuses { get; } = new(); + public Dictionary Controls { get; } = new(); + public IReadOnlyList Items { get; set; } = []; + public IEnumerable RequiredChangingItems => Items.Where(item => item.RequireChanges); + public string? Failure { get; set; } + public string? FailurePhase { get; set; } + public double? FailureMilliseconds { get; set; } + public FrameReceipt? LastFrame { get; set; } + } + + public sealed record FrameReceipt(long Sequence, long Epoch, string Kind, string? Control, int? Items); + + public sealed class ItemResult(string id, string sourceId, string realm, bool requireChanges) + { + public string Id { get; } = id; + public string SourceId { get; } = sourceId; + public string Realm { get; } = realm; + public bool RequireChanges { get; } = requireChanges; + public long HandleRevision { get; set; } + public bool Initialized { get; set; } + public long Samples { get; set; } + public long Changes { get; set; } + public long ChangesAfterMidpoint { get; set; } + public double HotTailMilliseconds { get; set; } + public long TypedValueBytes { get; set; } + public double? FirstSnapshotMilliseconds { get; set; } + public BoundedHistogram DeliveryGaps { get; } = new(); + public BoundedHistogram SourceAge { get; } = new(); + [System.Text.Json.Serialization.JsonIgnore] public string? LastFingerprint { get; set; } + [System.Text.Json.Serialization.JsonIgnore] public double? LastDeliveryMilliseconds { get; set; } + } + public sealed record BrowseResult(int Completed, BoundedHistogram Latency); + // Fixed logarithmic buckets bound memory regardless of delivery rate. + public sealed class BoundedHistogram + { + private readonly long[] _buckets = new long[256]; + public long Count { get; private set; } + public double Maximum { get; private set; } + public double? P95 => Quantile(.95); + public double? P99 => Quantile(.99); + public void Observe(double value) + { if (!double.IsFinite(value) || value < 0) throw new ArgumentOutOfRangeException(nameof(value)); _buckets[Math.Min(255, (int)(Math.Log2(value + 1) * 16))]++; Count++; Maximum = Math.Max(Maximum, value); } + private double? Quantile(double fraction) + { if (Count == 0) return null; var target = (long)Math.Ceiling(Count * fraction); long seen = 0; for (var i = 0; i < _buckets.Length; i++) { seen += _buckets[i]; if (seen >= target) return Math.Min(Maximum, Math.Pow(2, (i + 1) / 16d) - 1); } return Maximum; } + } +} diff --git a/scripts/validation/grpc-data/processes.py b/scripts/validation/grpc-data/processes.py index 404c458f2..3e1c2b5e5 100644 --- a/scripts/validation/grpc-data/processes.py +++ b/scripts/validation/grpc-data/processes.py @@ -1,13 +1,14 @@ """Bounded subprocess execution for the local validation gate. -Only the immediate child is owned here. Real subprocesses start in a fresh process -group; callers must not use shell wrappers that detach grandchildren. There is no -process-name scan, global kill, Docker reaper, or inherited fixture configuration. +Real subprocesses start in a fresh owned process group; POSIX cancellation and +timeouts signal only that group. Callers must not use wrappers that detach +descendants. There is no process-name scan, global kill, or Docker reaper. """ from dataclasses import dataclass import codecs import math import os +import signal import subprocess import threading import time @@ -26,6 +27,7 @@ class ProcessResult: timed_out: bool truncated: bool duration_seconds: float + cancelled: bool = False _SECRET_FLAGS = {"-P", "--password", "--api-key", "--apikey", "--token", "--secret"} @@ -75,7 +77,7 @@ def _positive_finite(value, name): class _Capture: - def __init__(self, limit, secrets): + def __init__(self, limit, secrets, observer=None): self.limit = limit self.secrets = secrets self.used = 0 @@ -83,6 +85,7 @@ class _Capture: self.lock = threading.Lock() self.parts = {"stdout": [], "stderr": []} self.failures = [] + self.observer = observer def append(self, stream, text): encoded = redact_text(text, self.secrets).encode("utf-8") @@ -94,39 +97,60 @@ class _Capture: if retained: self.parts[stream].append(retained) self.used += len(retained.encode("utf-8")) + if retained and self.observer is not None: + self.observer(stream, retained) def drain(self, name, pipe): - # Keep enough uncommitted text to redact a credential spanning reads. - keep = max((len(secret) for secret in self.secrets), default=1) - 1 + # Only an actual secret prefix can delay live output. Complete matches + # are consumed before carrying a suffix, bounding even self-overlap. pending = "" decoder = codecs.getincrementaldecoder("utf-8")(errors="replace") try: while True: - chunk = pipe.read(4096) + chunk = getattr(pipe, "read1", pipe.read)(4096) if not chunk: pending += decoder.decode(b"", final=True) - self.append(name, pending) + safe, _ = _redact_stream_prefix(pending, self.secrets, final=True) + self.append(name, safe) break pending += decoder.decode(chunk) if isinstance(chunk, bytes) else chunk - safe_length = max(0, len(pending) - keep) - for secret in self.secrets: - start = pending.find(secret, max(0, safe_length - len(secret) + 1)) - if start >= 0 and start < safe_length < start + len(secret): - safe_length = start - self.append(name, pending[:safe_length]) - pending = pending[safe_length:] + safe, pending = _redact_stream_prefix(pending, self.secrets) + self.append(name, safe) except Exception: # Do not include raw exception text: pipes/factories may mention argv. with self.lock: self.failures.append(name) +def _redact_stream_prefix(pending, secrets, *, final=False): + """Consume complete matches and retain only a genuine unresolved secret-prefix suffix.""" + secrets = tuple(secret for secret in secrets if secret) + safe = [] + while pending: + keep = 0 if final else max((length for secret in secrets + for length in range(1, min(len(secret), len(pending) + 1)) + if pending.endswith(secret[:length])), default=0) + frontier = len(pending) - keep + matches = [(start, -len(secret), secret) for secret in secrets + if (start := pending.find(secret)) >= 0 and start < frontier] + if not matches: + safe.append(pending[:frontier]) + return "".join(safe), pending[frontier:] + start, _, secret = min(matches) + safe.extend((pending[:start], "[REDACTED]")) + # A match crossing the frontier is consumed in full. Any overlapping + # candidate already contains redacted characters and cannot leak intact. + pending = pending[start + len(secret):] + return "".join(safe), "" + + def run_process(argv, *, timeout, secrets=(), max_output_bytes=1024 * 1024, - popen=None, clock=time.monotonic, cleanup_timeout=2.0, cwd=None, environment=None): + popen=None, clock=time.monotonic, cleanup_timeout=2.0, cwd=None, environment=None, observer=None, + cancellation_event=None): """Execute argv once, draining both streams while bounding retained evidence. - A timed-out command is never retried. Timeout is recorded even if termination - returns exit zero. An injected Popen factory is intended for pure unit tests. + A timed-out or cancelled command is never retried. Either state is recorded + even if termination returns exit zero. An injected Popen factory is intended for pure unit tests. The caller supplies an explicit environment when fixture isolation is needed. """ if not isinstance(argv, (list, tuple)) or not argv or any( @@ -134,6 +158,10 @@ def run_process(argv, *, timeout, secrets=(), max_output_bytes=1024 * 1024, raise ProcessError("a nonempty argv sequence is required") _positive_finite(timeout, "timeout") _positive_finite(cleanup_timeout, "cleanup timeout") + if observer is not None and not callable(observer): + raise ProcessError("output observer must be callable") + if cancellation_event is not None and not callable(getattr(cancellation_event, "is_set", None)): + raise ProcessError("cancellation signal must expose is_set") if type(max_output_bytes) is not int or not 0 < max_output_bytes <= 64 * 1024 * 1024: raise ProcessError("capture limit must be between 1 and 67108864 bytes") secret_values = tuple(sorted({str(value) for value in (*secrets, *_argv_secrets(argv)) if value}, @@ -154,41 +182,79 @@ def run_process(argv, *, timeout, secrets=(), max_output_bytes=1024 * 1024, except Exception: raise ProcessError("failed to start validation child") from None - capture = _Capture(max_output_bytes, secret_values) + capture = _Capture(max_output_bytes, secret_values, observer) readers = [threading.Thread(target=capture.drain, args=(name, getattr(process, name)), daemon=True) for name in ("stdout", "stderr")] timed_out = False + cancelled = False failed = False returncode = None for reader in readers: reader.start() + def stop_owned(force=False): + if popen is None and os.name != "nt": + try: + os.killpg(process.pid, signal.SIGKILL if force else signal.SIGTERM) + except ProcessLookupError: + pass + else: + (process.kill if force else process.terminate)() try: - try: - returncode = process.wait(timeout=timeout) - except subprocess.TimeoutExpired: - timed_out = True - process.terminate() + if cancellation_event is None: + try: + returncode = process.wait(timeout=timeout) + except subprocess.TimeoutExpired: + timed_out = True + else: + deadline = started + timeout + while True: + if cancellation_event.is_set(): + cancelled = True + break + remaining = deadline - clock() + if remaining <= 0: + timed_out = True + break + try: + returncode = process.wait(timeout=min(.1, remaining)) + break + except subprocess.TimeoutExpired: + continue + if timed_out or cancelled: + stop_owned() try: returncode = process.wait(timeout=cleanup_timeout) except subprocess.TimeoutExpired: - process.kill() + stop_owned(force=True) returncode = process.wait(timeout=cleanup_timeout) + if popen is None and os.name != "nt": + # The leader can exit on TERM while a silent same-group child + # survives. Escalate the exact owned group independently of EOF. + stop_owned(force=True) except BaseException: failed = True try: - process.kill() + stop_owned(force=True) returncode = process.wait(timeout=cleanup_timeout) except BaseException: pass finally: + drain_deadline = clock() + cleanup_timeout for reader in readers: - reader.join(timeout=cleanup_timeout) + reader.join(timeout=max(0, drain_deadline - clock())) # A detached descendant holding a pipe is an error, never a successful # capture. Do not block indefinitely trying to close a buffered pipe while # another thread is inside read(); daemon readers allow bounded return. if any(reader.is_alive() for reader in readers): - failed = True - else: + try: + stop_owned(force=True) + drain_deadline = clock() + cleanup_timeout + for reader in readers: + reader.join(timeout=max(0, drain_deadline - clock())) + except BaseException: + failed = True + failed = failed or any(reader.is_alive() for reader in readers) or not (timed_out or cancelled) + if not any(reader.is_alive() for reader in readers): for name in ("stdout", "stderr"): try: getattr(process, name).close() @@ -198,4 +264,4 @@ def run_process(argv, *, timeout, secrets=(), max_output_bytes=1024 * 1024, raise ProcessError("failed to collect validation child within cleanup deadline") from None return ProcessResult(safe_argv, returncode, "".join(capture.parts["stdout"]), "".join(capture.parts["stderr"]), timed_out, capture.truncated, - max(0.0, clock() - started)) + max(0.0, clock() - started), cancelled) diff --git a/scripts/validation/grpc-data/rig.py b/scripts/validation/grpc-data/rig.py index a09b1621f..cd025e8f9 100644 --- a/scripts/validation/grpc-data/rig.py +++ b/scripts/validation/grpc-data/rig.py @@ -1,12 +1,7 @@ -"""Pure safety and polling boundaries for the future standalone local rig. - -This module does not implement bring-up, migration, authoring, secret provisioning, -or scenario execution. Those actions need the real P04–P09 composition. In -particular, a validated safety manifest is not evidence that a rig is ready. -HTTP and resource deletion are explicit callbacks so unit tests never use Docker -or a network. The coordinator owns connecting these boundaries to real tools. -""" +"""Standalone local Docker fixture, with pure safety and polling boundaries.""" import argparse +import copy +from contextlib import contextmanager import ipaddress import json import math @@ -23,6 +18,59 @@ class RigError(RuntimeError): """The local gate cannot safely proceed.""" +def bundle_commit_matches(expected, observed): + """Require both production stores to acknowledge the exact published scope/version.""" + if not isinstance(expected, dict) or not isinstance(observed, dict): + return False + if type(expected.get("scopeVersion")) is not int or expected["scopeVersion"] <= 0: + return False + if not all(type(observed.get(key)) is int and observed[key] == expected["scopeVersion"] + for key in ("credentialScopeVersion", "trustScopeVersion")): + return False + if expected.get("kind") == "scope-only": + return all(observed.get(key) is None + for key in ("credentialVersion", "trustVersion", "credentialDeleted", "trustRetired")) + if expected.get("kind", "entry") != "entry" or any(type(expected.get(key)) is not int or expected[key] <= 0 + for key in ("credentialVersion", "trustVersion")): + return False + pairs = (("credentialScopeVersion", "scopeVersion"), ("trustScopeVersion", "scopeVersion"), + ("credentialVersion", "credentialVersion"), ("trustVersion", "trustVersion")) + return (all(type(observed.get(actual)) is int and observed[actual] == expected[wanted] + for actual, wanted in pairs) + and all(type(expected.get(flag, False)) is bool and observed.get(flag) is expected.get(flag, False) + for flag in ("credentialDeleted", "trustRetired"))) + + +def deployment_bundle_expectations(scope, published, *, selected=None): + """Wait only for enabled scope entries actually published to required consumers.""" + required = scope.get("required_node_ids") + connections = scope.get("connections") + if not isinstance(required, list) or not isinstance(connections, list) or not isinstance(published, list): + raise RigError("published deployment bundle inventory is missing") + consumers = NODES[2:] if selected is None else selected + wanted = {(node, item["connection_id"]) for item in connections for node in consumers + if node + ":4053" in required and node + ":4053" in item["consumer_node_ids"]} + scope_only_nodes = {node for node in consumers if node + ":4053" in required and not any(pair[0] == node for pair in wanted)} + wanted.update((node, "fixture-scope-only") for node in scope_only_nodes) + selected = [] + seen = set() + for entry in published: + pair = (entry.get("node"), entry.get("connectionId")) + if pair not in wanted: + continue + if (pair in seen or (entry.get("kind") == "scope-only") != (pair[0] in scope_only_nodes) + or entry.get("scopeVersion") != scope.get("scope_version") or not bundle_commit_matches(entry, { + "credentialScopeVersion": entry.get("scopeVersion"), "trustScopeVersion": entry.get("scopeVersion"), + "credentialVersion": entry.get("credentialVersion"), "trustVersion": entry.get("trustVersion"), + "credentialDeleted": entry.get("credentialDeleted", False), "trustRetired": entry.get("trustRetired", False)})): + raise RigError("published deployment bundle inventory is invalid") + seen.add(pair) + selected.append(dict(entry)) + if seen != wanted: + raise RigError("required deployment bundle entry was not published") + return selected + + RUN_LABEL = "otopcua.grpc-data.run" PROJECT_LABEL = "com.docker.compose.project" _RUN_PATTERN = re.compile(r"[a-z0-9][a-z0-9-]{0,47}\Z") @@ -134,7 +182,10 @@ def validate_fixture_endpoints(document, *, local_services): except ValueError: raise RigError("fixture endpoint URL is invalid") from None check_host(host) - if parsed.username is not None or parsed.password is not None: + akka_seed = (parsed.scheme == "akka.tcp" and parsed.username == "otopcua" and parsed.password is None + and parsed.path == "" and not parsed.query and not parsed.fragment + and re.fullmatch(r"(?:Cluster__SeedNodes__|Cluster:SeedNodes:)\d+|SeedNodes", key) is not None) + if (parsed.username is not None or parsed.password is not None) and not akka_seed: raise RigError("fixture endpoint URLs cannot contain credentials") db_hosts = _DB_HOST_PATTERN.findall(value) for host in db_hosts: @@ -314,7 +365,7 @@ def _status_complete(body, deployment_id, revision, expected_nodes): def deploy_and_wait(base_url, api_key, expected_nodes, *, request, timeout=120, poll_interval=1, - clock=time.monotonic, sleep=time.sleep, created_by="grpc-data-local-gate"): + clock=time.monotonic, sleep=time.sleep, created_by="grpc-data-local-gate", on_accepted=None): """Trigger one deployment and verify its revision and every node's apply row. request(method, url, headers=..., json_body=..., timeout=...) returns a @@ -379,6 +430,13 @@ def deploy_and_wait(base_url, api_key, expected_nodes, *, request, timeout=120, if location is not None: if not isinstance(location, str) or urljoin(origin + "/", location) != poll_url: raise RigError("deployment Location does not match the same local origin and deployment") + if on_accepted is not None: + required = on_accepted(deployment_id, revision) + if required is not None: + if (not isinstance(required, (set, frozenset, list, tuple)) or not required + or any(not isinstance(node, str) for node in required) or not set(required) <= expected_nodes): + raise RigError("deployment required-node inventory is outside the owned topology") + expected_nodes = set(required) while True: status, _, body = call("GET", poll_url) if status != 200: @@ -410,19 +468,883 @@ def require_production_prerequisites(action, available): raise RigError(f"{action} prerequisites not configured: {', '.join(missing)}") +# Runtime composition. Every subprocess is argv-only, bounded and captures output; +# failed child diagnostics are deliberately withheld because Docker can echo env. +ROOT = Path(__file__).resolve().parents[3] +HERE = Path(__file__).resolve().parent +NODES = tuple(f"{pair}-{n}" for pair in ("control", "source", "consumer") for n in (1, 2)) +SERVICES = ("sql", "migrator", "device", "seeder", *NODES) + + +def run_command(argv, *, timeout=120, environment=None): + from processes import ProcessError, run_process + import threading + if not isinstance(argv, list) or not argv or any(not isinstance(arg, str) or "\0" in arg for arg in argv): + raise RigError("invalid subprocess argv") + progress = None + observer = None + run_id = (environment or {}).get("GRPC_DATA_RUN_ID") + if run_id and _RUN_PATTERN.fullmatch(run_id): + log_dir = ROOT / "artifacts" / "grpc-data" / "runs" / run_id / "diagnostics" + log_dir.mkdir(parents=True, exist_ok=True, mode=0o700) + if log_dir.is_symlink(): raise RigError("diagnostics directory cannot be linked") + fd = os.open(log_dir / (uuid.uuid4().hex + ".progress.log"), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + progress = os.fdopen(fd, "w") + lock = threading.Lock() + def observer(stream, chunk): + with lock: + progress.write(chunk); progress.flush() + try: + result = run_process(argv, cwd=ROOT, environment=environment, timeout=timeout, + max_output_bytes=16 * 1024 * 1024, observer=observer) + except (OSError, ProcessError): + raise RigError("local tool failed or exceeded its deadline; credentials withheld") from None + finally: + if progress is not None: progress.close() + if result.returncode or result.cancelled or result.timed_out or result.truncated: + run_id = (environment or {}).get("GRPC_DATA_RUN_ID") + if run_id and _RUN_PATTERN.fullmatch(run_id): + log_dir = ROOT / "artifacts" / "grpc-data" / "runs" / run_id / "diagnostics" + log_dir.mkdir(parents=True, exist_ok=True, mode=0o700) + if log_dir.is_symlink(): raise RigError("diagnostics directory cannot be linked") + name = uuid.uuid4().hex + atomic_write_secret(log_dir / (name + ".stdout.log"), result.stdout or "(empty)\n") + atomic_write_secret(log_dir / (name + ".stderr.log"), result.stderr or "(empty)\n") + raise RigError("local tool returned failure; inspect restricted run diagnostics locally") + return result.stdout + + +def source_tree_hash(): + """Hash image build inputs, including pending/new code, excluding review evidence. + + Harness Python and test sources have their own evidence and do not enter the + Host/seeder/probe binaries. Notes can change without invalidating an image. + """ + import hashlib + paths = run_command(["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"]).split("\0") + digest = hashlib.sha256() + for name in sorted(set(filter(None, paths))): + path = ROOT / name + if (name.startswith(("docs/", "tests/", ".playwright-mcp/")) or + not (path.suffix in {".cs", ".csproj", ".props", ".targets", ".slnx", ".resx", ".razor", ".css", ".js", ".proto"} + or name in {"global.json", "NuGet.Config", "nuget.config", "Directory.Build.rsp", ".dockerignore", "scripts/validation/grpc-data/Dockerfile"} + or name.startswith("src/") and path.suffix == ".json")): + continue + if path.is_file() and not path.is_symlink(): + digest.update(name.encode() + b"\0") + digest.update(hashlib.sha256(path.read_bytes()).digest()) + return digest.hexdigest() + + +def device_tree_hash(): + """Identify the fixture protocol/ledger implementation independently of Hosts.""" + import hashlib + digest = hashlib.sha256() + for name in ("Dockerfile", "server.py"): + path = HERE / "device" / name + if path.is_symlink() or not path.is_file(): raise RigError("device fixture input is unavailable") + digest.update(name.encode() + b"\0" + path.read_bytes()) + return digest.hexdigest() + + +def docker_context(): + name = run_command(["docker", "context", "show"]).strip() + rows = json.loads(run_command(["docker", "context", "inspect", name])) + if not isinstance(rows, list) or len(rows) != 1: + raise RigError("Docker context inspection was ambiguous") + validate_docker_context(rows[0], environment=dict(os.environ)) + return rows[0] + + +def http_request(method, url, *, headers, json_body=None, timeout=10): + import urllib.request + import urllib.error + class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, hdrs, newurl): + return None + data = None if json_body is None else json.dumps(json_body).encode() + request = urllib.request.Request(url, data=data, headers={**headers, **({"Content-Type": "application/json"} if data else {})}, method=method) + opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()) + try: + response = opener.open(request, timeout=min(timeout, 15)) + except urllib.error.HTTPError as error: + response = error + with response: + raw = response.read(1024 * 1024 + 1) + if len(raw) > 1024 * 1024: + raise RigError("HTTP response exceeded limit") + try: + body = json.loads(raw) if raw else None + except (ValueError, UnicodeError): + body = None + return response.status, dict(response.headers), body + + +def wait_until(predicate, *, timeout, description, interval=1): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + if predicate(): + return + except (OSError, ValueError, RigError): + pass + time.sleep(min(interval, max(0, deadline - time.monotonic()))) + raise RigError(f"deadline waiting for {description}") + + +def observe_active_endpoint(node_urls, *, request, timeout, require_ready=False, clock=None): + """Observe the whole pair; one failed endpoint cannot hide its partner.""" + _duration(timeout, "active endpoint observation timeout") + if not isinstance(node_urls, dict) or len(node_urls) != 2: + raise RigError("an explicit two-node active endpoint inventory is required") + clock = clock or time.monotonic + deadline = clock() + timeout + active = [] + for node, origin in node_urls.items(): + remaining = deadline - clock() + if remaining <= 0: + return None # An incomplete pair observation cannot select a node. + try: + status, _, _ = request("GET", origin.rstrip("/") + "/health/active", headers={}, timeout=min(5, remaining)) + except OSError: + continue + if status == 200: + active.append(node) + if len(active) > 1: + raise RigError("pair has more than one observed active node") + if not active or clock() >= deadline: + return None + selected = active[0] + if require_ready: + remaining = deadline - clock() + if remaining <= 0: + return None + try: + status, _, _ = request("GET", node_urls[selected].rstrip("/") + "/health/ready", headers={}, timeout=min(5, remaining)) + except OSError: + return None + if status != 200 or clock() >= deadline: + return None + return selected + + +def wait_active_endpoint(node_urls, *, request, timeout, require_ready=False, clock=None, sleep=None): + """Bound startup/election polling without retrying any deployment mutation.""" + _duration(timeout, "active endpoint selection timeout") + clock, sleep = clock or time.monotonic, sleep or time.sleep + deadline = clock() + timeout + while True: + remaining = deadline - clock() + if remaining <= 0: + raise RigError("deadline waiting for one ready active endpoint") + selected = observe_active_endpoint(node_urls, request=request, timeout=min(15, remaining), + require_ready=require_ready, clock=clock) + if selected is not None: + return selected + remaining = deadline - clock() + if remaining <= 0: + raise RigError("deadline waiting for one ready active endpoint") + sleep(min(1, remaining)) + + +class LocalRig: + def __init__(self, run_id, *, base=None): + if not _RUN_PATTERN.fullmatch(run_id or ""): + raise RigError("a safe explicit --run-id is required") + self.run_id = run_id + self.folder = (Path(base) if base else ROOT / "artifacts" / "grpc-data" / "runs") / run_id + self.path = self.folder / "manifest.json" + self.project = "grpc-data-" + run_id + self.environment = dict(os.environ) + self.environment["COMPOSE_PROJECT_NAME"] = self.project + self.context = docker_context() + self.docker = ["docker", "--context", self.context["Name"]] + if self.folder.exists(): + if self.folder.is_symlink() or self.folder.stat().st_mode & 0o077: + raise RigError("run directory must be restricted and cannot be a symlink") + env_path = self.folder / "environment.json" + if env_path.exists(): + self.environment.update(json.loads(env_path.read_text())) + + def compose(self, *args, timeout=120): + return run_command([*self.docker, "compose", "--project-name", self.project, "--file", str(HERE / "compose.yml"), *args], timeout=timeout, environment=self.environment) + + @contextmanager + def hub_partitions(self, count): + """Restart only the owned SOURCE pair with an explicit hub partition count. + + Port allocation changes when Compose recreates a container, so every + transition refreshes the canonical manifest before readiness polling. + """ + if type(count) is not int or not 1 <= count <= 256: + raise RigError("hub partition count must be between 1 and 256") + with self._configuration_experiment("hub-partitions", ("source-1", "source-2"), + {"DataConnections__Hub__PartitionCount": str(count)}): + yield + + @contextmanager + def compact_batches(self, enabled): + """Exercise the production caller's negotiated encoding preference.""" + if type(enabled) is not bool: + raise RigError("compact encoding preference must be boolean") + with self._configuration_experiment("compact-batches", ("consumer-1", "consumer-2"), + {"DataConnections__UseCompactBatches": str(enabled).lower()}): + yield + + @contextmanager + def _configuration_experiment(self, name, nodes, environment, *, before_restore=None): + override = self.folder / (name + ".json") + if override.exists(): + raise RigError("a configuration experiment is already present") + def transition(extra): + # Inspect exact project resources before changing its owned services. + self.inspect_resources() + run_command([*self.docker, "compose", "--project-name", self.project, + "--file", str(HERE / "compose.yml"), *extra, "up", "--detach", "--no-deps", *nodes], + timeout=300, environment=self.environment) + manifest = self.refresh_endpoints(nodes) + self.capture(manifest) + wait_until(lambda: self.health(manifest), timeout=180, description="configuration experiment pair readiness") + atomic_write_secret(override, json.dumps({"services": {node: {"environment": environment} for node in nodes}})) + try: + transition(["--file", str(override)]) + yield + finally: + try: + if before_restore is not None: + before_restore() + transition([]) + finally: + override.unlink(missing_ok=True) + + def save(self, manifest): + atomic_write_secret(self.path, json.dumps(manifest, indent=2, sort_keys=True) + "\n") + + def load(self): + if not self.path.is_file() or self.path.is_symlink(): + raise RigError("restricted run manifest is missing") + manifest = json.loads(self.path.read_text()) + validate_manifest(manifest, expected_run_id=self.run_id) + if manifest.get("docker_context") != self.context["Name"]: + raise RigError("selected Docker context differs from the recorded run") + return manifest + + def verify_candidate(self): + """Match every running Host binary stamp to the actual compiled inputs.""" + manifest = self.load() + expected = source_tree_hash() + if manifest.get("source_tree_hash") != expected: + raise RigError("running manifest does not match current image build inputs") + for node in NODES: + raw = self.compose("exec", "--no-TTY", node, "cat", "/app/grpc-data-source.json", timeout=15) + stamp = json.loads(raw) + if stamp.get("tree_hash") != expected or stamp.get("revision") != manifest.get("source_revision"): + raise RigError("running Host build stamp does not match the candidate") + device_hash = device_tree_hash() + if manifest.get("device_source_hash") != device_hash: + raise RigError("device manifest does not match current fixture inputs") + observed = self.compose("exec", "--no-TTY", "device", "cat", "/fixture/source-hash", timeout=15).strip() + if observed != device_hash: + raise RigError("running device fixture does not match current protocol/ledger inputs") + return expected + + def inspect_resources(self): + resources = [] + for kind, listing in (("container", ["container", "ls", "-a", "-q"]), ("network", ["network", "ls", "-q"]), ("volume", ["volume", "ls", "-q"]), ("image", ["image", "ls", "-q"])): + ids = run_command([*self.docker, *listing, "--filter", f"label={RUN_LABEL}={self.run_id}", "--filter", f"label={PROJECT_LABEL}={self.project}"]).split() + for identity in dict.fromkeys(ids): + row = json.loads(run_command([*self.docker, kind, "inspect", identity]))[0] + labels = row.get("Config", {}).get("Labels") if kind in {"container", "image"} else row.get("Labels") + if not isinstance(labels, dict) or labels.get(RUN_LABEL) != self.run_id or labels.get(PROJECT_LABEL) != self.project: + raise RigError("observed Docker object ownership mismatch") + resources.append({"kind": kind, "id": row.get("Id", row.get("Name")), "labels": labels}) + return resources + + def capture(self, manifest): + manifest["resources"] = self.inspect_resources() + self.save(manifest) + + def allocate_manifest(self): + endpoints = {} + for node in (*NODES, "sql", "device"): + ids = self.compose("ps", "--all", "--quiet", node).split() + if len(ids) != 1: + raise RigError("fixture must contain exactly one container per service") + row = json.loads(run_command([*self.docker, "container", "inspect", ids[0]]))[0] + for container_port, bindings in row["NetworkSettings"]["Ports"].items(): + if not bindings: + continue + port = int(container_port.split("/")[0]) + if len(bindings) != 1 or bindings[0]["HostIp"] != "127.0.0.1": + raise RigError("Docker published a fixture port outside loopback") + suffix = {9000: "admin", 4840: "opcua", 4057: "data", 1433: "sql", 5020: "modbus", 8080: "control"}[port] + scheme = {4840: "opc.tcp", 4057: "https", 1433: "tcp", 5020: "tcp"}.get(port, "http") + host_port = int(bindings[0]["HostPort"]) + path = "/OtOpcUa" if port == 4840 else "" + endpoints[f"{node}.{suffix}"] = {"scheme": scheme, "host": "127.0.0.1", "host_port": host_port, + "container_host": node, "container_port": port, "url": f"{scheme}://127.0.0.1:{host_port}{path}"} + return {"schema_version": 1, "run_id": self.run_id, "project": self.project, + "labels": {RUN_LABEL: self.run_id, PROJECT_LABEL: self.project}, "services": list(SERVICES), + "docker_context": self.context["Name"], "endpoints": endpoints, "resources": [], + "nodes": {node: {"cluster_id": node.split("-")[0].upper(), "node_id": node + ":4053", "application_uri": "urn:OtOpcUa:grpc-data:" + node} for node in NODES}, + "tls": {"ca_file": str(self.folder / "security" / "ca.pem")}, "state": "started"} + + def refresh_endpoints(self, nodes): + """Refresh only restarted owned services, preserving intentionally stopped peers.""" + if (not isinstance(nodes, (tuple, list)) or not nodes or any(not isinstance(node, str) or node not in NODES for node in nodes) + or len(nodes) != len(set(nodes))): + raise RigError("endpoint refresh requires unique owned node services") + manifest = copy.deepcopy(self.load()) + for node in nodes: + ids = self.compose("ps", "--all", "--quiet", node).split() + if len(ids) != 1: + raise RigError("endpoint refresh requires exactly one owned service container") + try: + rows = json.loads(run_command([*self.docker, "container", "inspect", ids[0]])) + if not isinstance(rows, list) or len(rows) != 1: + raise ValueError() + row = rows[0] + labels = row.get("Config", {}).get("Labels", {}) + if (not isinstance(labels, dict) or labels.get(RUN_LABEL) != self.run_id + or labels.get(PROJECT_LABEL) != self.project or labels.get("com.docker.compose.service") != node + or row.get("State", {}).get("Running") is not True): + raise ValueError() + ports = row["NetworkSettings"]["Ports"] + expected = {"4840/tcp": ("opcua", "opc.tcp"), "9000/tcp": ("admin", "http")} + if not node.startswith("control-"): + expected["4057/tcp"] = ("data", "https") + if not isinstance(ports, dict) or any(bindings and port not in expected for port, bindings in ports.items()): + raise ValueError() + for port, (suffix, scheme) in expected.items(): + bindings = ports.get(port) + if (not isinstance(bindings, list) or len(bindings) != 1 + or bindings[0].get("HostIp") != "127.0.0.1"): + raise ValueError() + allocated = int(bindings[0]["HostPort"]) + if not _port(allocated): + raise ValueError() + container_port = int(port.split("/")[0]) + path = "/OtOpcUa" if suffix == "opcua" else "" + manifest["endpoints"][node + "." + suffix] = {"scheme": scheme, "host": "127.0.0.1", + "host_port": allocated, "container_host": node, "container_port": container_port, + "url": f"{scheme}://127.0.0.1:{allocated}{path}"} + except (ValueError, TypeError, KeyError, AttributeError): + raise RigError("endpoint refresh requires an owned running container with complete loopback bindings") from None + validate_manifest(manifest, expected_run_id=self.run_id) + self.save(manifest) + return manifest + + def up(self, timeout=600): + import secrets + import credentials + if self.folder.exists(): + raise RigError("run already exists; use status or owned down before reusing its id") + self.folder.mkdir(parents=True, mode=0o700) + os.chmod(self.folder, 0o700) + atomic_write_secret(self.folder / "setup.json", json.dumps({"run_id": self.run_id, "docker_context": self.context["Name"], "project": self.project})) + revision = run_command(["git", "rev-parse", "HEAD"]).strip() + tree_hash = source_tree_hash() + settings = {"GRPC_DATA_UID": str(os.getuid()) if hasattr(os, "getuid") else "0", "GRPC_DATA_GID": str(os.getgid()) if hasattr(os, "getgid") else "0", "GRPC_DATA_RUN_ID": self.run_id, "GRPC_DATA_PROJECT": self.project, "SOURCE_REVISION": revision, "SOURCE_TREE_HASH": tree_hash, "DEVICE_TREE_HASH": device_tree_hash(), + "GRPC_DATA_IMAGE": f"otopcua-grpc-data:{self.run_id}", "GRPC_DATA_MIGRATOR_IMAGE": f"otopcua-grpc-migrator:{self.run_id}", + "GRPC_DATA_DEVICE_IMAGE": f"otopcua-grpc-device:{self.run_id}", "GRPC_DATA_SEED_IMAGE": f"otopcua-grpc-seed:{self.run_id}", + "GRPC_DATA_CERT_DIR": str(self.folder / "security" / "tls"), "GRPC_DATA_CREDENTIAL_DIR": str(self.folder / "security" / "credentials"), + "GRPC_DATA_OUTPUT_DIR": str(self.folder / "seed"), "GRPC_DATA_PROBE_DIR": str(self.folder / "probe")} + for name in ("APIKEY_PEPPER", "JWT_KEY", "DEPLOY_KEY", "CONFIG_KEY", "TELEMETRY_KEY", "MESH_PSK_CONTROL", "MESH_PSK_SOURCE", "MESH_PSK_CONSUMER", "SYNC_KEY_SOURCE", "SYNC_KEY_CONSUMER"): + settings["GRPC_DATA_" + name] = secrets.token_hex(32) + settings["GRPC_DATA_SQL_PASSWORD"] = "Gd!" + secrets.token_hex(24) + import base64 + settings["GRPC_DATA_SECRETS_KEK"] = base64.b64encode(secrets.token_bytes(32)).decode() + atomic_write_secret(self.folder / "environment.json", json.dumps(settings)) + self.environment.update(settings) + credentials.provision_tls(self.folder / "security", NODES[2:]) + (self.folder / "security" / "credentials").mkdir(mode=0o700) + for node in NODES[2:]: + (self.folder / "security" / "credentials" / node).mkdir(parents=True, mode=0o700) + (self.folder / "seed").mkdir(mode=0o700) + (self.folder / "probe").mkdir(mode=0o700) + for node in NODES: + (self.folder / "probe" / node).mkdir(parents=True, mode=0o700) + # Save a restricted setup journal before the first mutation, so interrupted + # builds can still be collected by exact observed object IDs on `down`. + atomic_write_secret(self.folder / "setup.json", json.dumps({"run_id": self.run_id, "docker_context": self.context["Name"], "project": self.project})) + resolved = json.loads(self.compose("config", "--format", "json")) + validate_fixture_endpoints(resolved, local_services=SERVICES) + try: + self.compose("build", "--pull", "migrator", "device", "control-1", "seeder", timeout=1800) + self.compose("up", "--detach", "sql", "device", "migrator", *NODES, timeout=timeout) + manifest = self.allocate_manifest() + manifest["source_revision"] = revision + manifest["source_tree_hash"] = tree_hash + manifest["device_source_hash"] = settings["DEVICE_TREE_HASH"] + self.capture(manifest) + wait_until(lambda: self.health(manifest, require_catalog=False), timeout=timeout, description="six node health and independent pair roles") + manifest["state"] = "up" + self.capture(manifest) + return manifest + except BaseException: + # Capture whatever exists; no broad compose down/prune is permitted. + atomic_write_secret(self.folder / "interrupted-resources.json", json.dumps(self.inspect_resources())) + raise + + def health(self, manifest, *, require_catalog=False, timeout=None): + deadline = None if timeout is None else time.monotonic() + timeout + def request_timeout(): + remaining = 5 if deadline is None else deadline - time.monotonic() + if remaining <= 0: + raise RigError("fixture readiness deadline timeout") + return min(5, remaining) + active = {} + for node in NODES: + origin = manifest["endpoints"][node + ".admin"]["url"] + status, _, _ = http_request("GET", origin + "/health/ready", headers={}, timeout=request_timeout()) + if status != 200: + return False + status, _, _ = http_request("GET", origin + "/health/active", headers={}, timeout=request_timeout()) + active[node] = status == 200 + if any(sum(active[node] for node in NODES if node.startswith(pair + "-")) != 1 for pair in ("control", "source", "consumer")): + return False + if require_catalog: + # Namespace resolution reads through real OPC UA sessions on all six + # hosts, validates each URI, and requires Good fixture leaf values. + remaining = 120 if deadline is None else deadline - time.monotonic() + if remaining <= 0: + raise RigError("fixture catalog readiness deadline timeout") + self.seed_helper("resolve", timeout=min(120, remaining)) + if deadline is not None and time.monotonic() >= deadline: + raise RigError("fixture readiness exceeded its deadline") + return True + + def seed_helper(self, action, *arguments, timeout=120): + self.compose("run", "--rm", "--no-deps", "seeder", action, *arguments, timeout=timeout) + + def seed(self): + manifest = self.load() + self.seed_helper("seed") + fixture = json.loads((self.folder / "seed" / "fixture.json").read_text()) + validate_fixture_endpoints(fixture.get("endpoints", {}), local_services=SERVICES) + manifest["fixture"] = fixture + manifest["node_probe_dirs"] = {node: str(self.folder / "probe" / node) for node in NODES} + manifest["credentials"] = {"cli_key_file": str(self.folder / "seed" / "cli.key"), + "data_key_files": {"source": str(self.folder / "seed" / "source.key")}} + manifest["state"] = "seeded" + self.capture(manifest) + return manifest + + def provision_deployment(self, deployment_id, revision, *, timeout=120): + import credentials + self.seed_helper("scope", deployment_id, revision, timeout=timeout) + scope = json.loads((self.folder / "seed" / "scope.json").read_text()) + published = self.publish_scope(scope) + scope["bundle_expectations"] = deployment_bundle_expectations(scope, published) + return scope + + def bundle_version(self, node): + directory = self.folder / "security" / "credentials" / node + bundle = directory / "bundle.json" + generation = directory / "generation.txt" + return max(json.loads(bundle.read_text())["Version"] if bundle.exists() else 0, + int(generation.read_text()) if generation.exists() else 0) + 1 + + def publish_scope(self, scope, *, selected=None, deleted=False): + import base64 + import credentials + key = (self.folder / "seed" / "source.key").read_text().strip() + state_path = self.folder / "trust-state.json" + ca_files = json.loads(state_path.read_text())["roots"] if state_path.exists() else [str(self.folder / "security" / "ca.pem")] + roots = [base64.b64encode(credentials._openssl("x509", "-in", path, "-outform", "DER")).decode("ascii") for path in ca_files] + nodes = {} + for node in selected if selected is not None else NODES[2:]: + entries = [{"ConnectionId": item["connection_id"], "SecretReference": item["secret_reference"], "Value": None if deleted else key, "Deleted": deleted} + for item in scope["connections"] if node + ":4053" in item["consumer_node_ids"]] + version = self.bundle_version(node) + nodes[node] = {"owner": node.split("-")[0].upper(), "scope_version": scope["scope_version"], "entries": entries, + "bundle_version": version, "trust_version": version, "trust_roots": roots} + directory = self.folder / "security" / "credentials" / node + for name in ("bundle", "trust"): + current = directory / (name + ".json") + if current.exists(): + atomic_write_secret(directory / (name + "-previous.json"), current.read_text()) + credentials.write_bundles(self.folder / "security", nodes) + for node, spec in nodes.items(): + atomic_write_secret(self.folder / "security" / "credentials" / node / "generation.txt", str(spec["bundle_version"])) + entries = [{"node": node, "connectionId": entry["ConnectionId"], "scopeVersion": spec["scope_version"], + "kind": "entry", + "credentialVersion": spec["bundle_version"], "trustVersion": spec["trust_version"], + "credentialDeleted": entry["Deleted"], "trustRetired": False} + for node, spec in nodes.items() for entry in spec["entries"]] + return entries + [{"node": node, "connectionId": "fixture-scope-only", "kind": "scope-only", + "scopeVersion": spec["scope_version"], "credentialVersion": None, "trustVersion": None, + "credentialDeleted": None, "trustRetired": None} for node, spec in nodes.items() if not spec["entries"]] + + def wait_bundle_commits(self, expectations, *, timeout): + """Observe exact numeric acknowledgements through each caller's production DI stores.""" + _duration(timeout, "bundle commit readiness timeout") + if not isinstance(expectations, list): + raise RigError("published bundle expectations are missing") + deadline = time.monotonic() + timeout + records = [] + safe_fields = ("credentialScopeVersion", "credentialVersion", "trustScopeVersion", "trustVersion", + "credentialDeleted", "trustRetired") + diagnostics = self.folder / "seed" / "bundle-commit-readiness.json" + atomic_write_secret(diagnostics, json.dumps({"required_entries": len(expectations), "entries": records})) + for expected in expectations: + node = expected["node"] + folder = self.folder / "probe" / node + if node not in NODES[2:] or folder.is_symlink() or not folder.is_dir(): + raise RigError("bundle acknowledgement requires an owned data-node probe directory") + record = {"node": node, "connectionId": expected["connectionId"], + "expected": {key: expected[key] for key in ("scopeVersion", "credentialVersion", "trustVersion", + "credentialDeleted", "trustRetired")}, + "observed": None, "matched": False} + record["expected"]["kind"] = expected.get("kind", "entry") + records.append(record) + atomic_write_secret(diagnostics, json.dumps({"required_entries": len(expectations), "entries": records})) + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise RigError("deadline waiting for exact credential and trust bundle acknowledgements") + identity = "bundle-" + uuid.uuid4().hex + request = folder / (identity + ".request.json") + response = folder / (identity + ".result.json") + atomic_write_secret(request, json.dumps({"id": identity, "operation": "bundle-commit", + "connectionId": expected["connectionId"], "timeoutSeconds": max(1, min(5, int(remaining)))})) + try: + while not response.exists(): + remaining = deadline - time.monotonic() + if remaining <= 0: + raise RigError("deadline waiting for bundle acknowledgement probe") + time.sleep(min(.1, remaining)) + if time.monotonic() > deadline: + raise RigError("deadline waiting for bundle acknowledgement probe") + if response.is_symlink() or not response.is_file() or response.stat().st_size > 16384: + raise RigError("bundle acknowledgement probe output is invalid") + result = json.loads(response.read_text()) + if (result.get("id") != identity or result.get("operation") != "bundle-commit" + or result.get("passed") is not True or type(result.get("assertions")) is not int + or result["assertions"] <= 0 or not isinstance(result.get("observations"), dict)): + raise RigError("bundle acknowledgement probe identity or result is invalid") + observed = {key: result["observations"].get(key) for key in safe_fields} + if any(value is not None and type(value) is not (bool if key in {"credentialDeleted", "trustRetired"} else int) + for key, value in observed.items()): + raise RigError("bundle acknowledgement fields must be nullable numeric versions or state flags") + record["observed"] = observed + record["matched"] = bundle_commit_matches(record["expected"], record["observed"]) + atomic_write_secret(diagnostics, json.dumps({"required_entries": len(expectations), "entries": records})) + if record["matched"]: + break + finally: + request.unlink(missing_ok=True) + time.sleep(min(.1, max(0, deadline - time.monotonic()))) + return records + + def credential_action(self, action, node=None): + """Publish through the actual node bundle loader, never fake an auth result.""" + if node is not None and node not in NODES[2:]: + raise RigError("credential action requires an owned data node") + selected = [node] if node is not None else [name for name in NODES if name.startswith("consumer-")] + if action == "reload_stale_bundle": + for name in selected: + directory = self.folder / "security" / "credentials" / name + for kind in ("bundle", "trust"): + previous = directory / (kind + "-previous.json") + if not previous.is_file(): + raise RigError("no previous bundle is available for stale replay") + atomic_write_secret(directory / (kind + ".json"), previous.read_text()) + elif action in {"remove_consumer_secret", "provision_consumer_secret"}: + scope = json.loads((self.folder / "seed" / "scope.json").read_text()) + published = self.publish_scope(scope, selected=selected, deleted=action == "remove_consumer_secret") + self.wait_bundle_commits(deployment_bundle_expectations(scope, published, selected=selected), timeout=120) + else: + raise RigError("unknown credential fixture action") + return {"action": action, "nodes": selected} + + def trust_action(self, action): + """Stage trust, replace owned server certs, then retire the original CA.""" + import credentials + security = self.folder / "security" + next_security = self.folder / "security-next" + state_path = self.folder / "trust-state.json" + if action == "stage_new": + if next_security.exists(): + raise RigError("a CA rotation is already staged") + credentials.provision_tls(next_security, NODES[2:]) + for node in NODES[2:]: + for kind in ("pem", "key"): + directory = security / "tls" / node + atomic_write_secret(directory / ("server-original." + kind), (directory / ("server." + kind)).read_text()) + original = security / "ca-original.pem" + atomic_write_secret(original, (security / "ca.pem").read_text()) + atomic_write_secret(state_path, json.dumps({"phase": "staged", "roots": [str(original), str(next_security / "ca.pem")]})) + atomic_write_secret(security / "ca.pem", original.read_text() + (next_security / "ca.pem").read_text()) + else: + if not state_path.exists(): + raise RigError("CA rotation has not been staged") + state = json.loads(state_path.read_text()) + if action == "rotate_server": + if state["phase"] != "staged": + raise RigError("server certificates can rotate only after trust staging") + for node in NODES[2:]: + for name in ("server.pem", "server.key"): + atomic_write_secret(security / "tls" / node / name, (next_security / "tls" / node / name).read_text()) + self.compose("restart", *NODES[2:], timeout=120) + self.refresh_endpoints(NODES[2:]) + state["phase"] = "rotated" + elif action == "retire_old": + if state["phase"] != "rotated": + raise RigError("old CA can retire only after server certificate rotation") + state = {"phase": "retired", "roots": [str(next_security / "ca.pem")]} + atomic_write_secret(security / "ca.pem", (next_security / "ca.pem").read_text()) + else: + raise RigError("unknown trust fixture action") + atomic_write_secret(state_path, json.dumps(state)) + scope = json.loads((self.folder / "seed" / "scope.json").read_text()) + published = self.publish_scope(scope) + self.wait_bundle_commits(deployment_bundle_expectations(scope, published), timeout=120) + manifest = self.load() + manifest["tls"]["rotation"] = json.loads(state_path.read_text())["phase"] + manifest["tls"]["ca_file"] = str(security / "ca.pem") + self.save(manifest) + return {"action": action, "phase": manifest["tls"]["rotation"]} + + def restore_security(self): + """Restore the original local CA/certificates while keeping bundle generations monotonic.""" + import shutil + security = self.folder / "security" + state_path = self.folder / "trust-state.json" + if not state_path.exists(): + return {"restored": False} + original = security / "ca-original.pem" + if not original.is_file(): + raise RigError("original local CA material is unavailable") + for node in NODES[2:]: + for kind in ("pem", "key"): + directory = security / "tls" / node + atomic_write_secret(directory / ("server." + kind), (directory / ("server-original." + kind)).read_text()) + atomic_write_secret(security / "ca.pem", original.read_text()) + atomic_write_secret(state_path, json.dumps({"phase": "restored", "roots": [str(original)]})) + self.compose("restart", *NODES[2:], timeout=120) + self.refresh_endpoints(NODES[2:]) + scope = json.loads((self.folder / "seed" / "scope.json").read_text()) + published = self.publish_scope(scope) + self.wait_bundle_commits(deployment_bundle_expectations(scope, published), timeout=120) + next_security = self.folder / "security-next" + if next_security.is_symlink(): + raise RigError("staged security directory cannot be a symlink") + if next_security.exists(): + shutil.rmtree(next_security) + state_path.unlink() + manifest = self.load() + manifest["tls"]["rotation"] = "restored" + manifest["tls"]["ca_file"] = str(security / "ca.pem") + self.save(manifest) + return {"restored": True} + + @contextmanager + def retired_server_identity(self, node): + """Present an old-CA server identity after actual consumers retired it.""" + if node not in ("source-1", "source-2"): + raise RigError("retired identity experiment requires an owned SOURCE node") + state_path = self.folder / "trust-state.json" + if not state_path.is_file() or json.loads(state_path.read_text()).get("phase") != "retired": + raise RigError("old CA must be retired before the identity experiment") + directory = self.folder / "security" / "tls" / node + original = {} + for kind in ("pem", "key"): + old = directory / ("server-original." + kind) + if old.is_symlink() or not old.is_file(): + raise RigError("restricted server identities are unavailable") + original[kind] = old.read_text() + with self._server_identity_material(node, original): + yield + + @contextmanager + def rejected_server_identity(self, node, reason): + """Serve a real invalid identity to the production caller trust policy.""" + if node not in ("source-1", "source-2") or reason not in ("wrong-ca", "wrong-san"): + raise RigError("invalid owned TLS rejection experiment") + if reason == "wrong-ca": + import credentials + isolated = self.folder / "security-rejected" + if isolated.is_symlink(): raise RigError("rejected identity directory cannot be linked") + if not isolated.exists(): credentials.provision_tls(isolated, ("source-1", "source-2")) + directory = isolated / "tls" / node + else: + partner = "source-2" if node == "source-1" else "source-1" + directory = self.folder / "security" / "tls" / partner + material = {} + for kind in ("pem", "key"): + path = directory / ("server." + kind) + if path.is_symlink() or not path.is_file(): raise RigError("owned TLS test identity is unavailable") + material[kind] = path.read_text() + if reason == "wrong-san": + # The Host correctly checks its own certificate against AllowedHosts + # at startup. Admit the partner identity on that server only, while + # the actual caller remains pinned to this node's original URI. + live = self.folder / "security" / "tls" / node + saved = {kind: (live / ("server." + kind)).read_text() for kind in ("pem", "key")} + def restore(): + for kind, content in saved.items(): + atomic_write_secret(live / ("server." + kind), content) + try: + for kind, content in material.items(): + atomic_write_secret(live / ("server." + kind), content) + with self._configuration_experiment("wrong-san-" + node, (node,), + {"DataConnections__AllowedHosts__0": partner}, before_restore=restore): + yield + finally: + restore() + return + with self._server_identity_material(node, material): + yield + + def verify_test_tls_listener(self, node, reason): + """Validate the presented test certificate independently of consumer trust. + + This control proves that the same owned TLS listener is reachable while + the production consumer must reject its configured identity. It sends no + HTTP request and grants no trust material to that consumer. + """ + import hashlib + import socket + import ssl + if node not in ("source-1", "source-2") or reason not in ("wrong-ca", "wrong-san", "retired-ca"): + raise RigError("invalid owned TLS listener control") + security = self.folder / "security" + ca = (self.folder / "security-rejected" / "ca.pem") if reason == "wrong-ca" else ( + security / "ca-original.pem" if reason == "retired-ca" else security / "ca.pem") + server_name = ("source-2" if node == "source-1" else "source-1") if reason == "wrong-san" else node + endpoint = self.load()["endpoints"][node + ".data"] + context = ssl.create_default_context(cafile=str(ca)) + context.minimum_version = ssl.TLSVersion.TLSv1_2 + with socket.create_connection((endpoint["host"], endpoint["host_port"]), timeout=5) as transport: + with context.wrap_socket(transport, server_hostname=server_name) as channel: + actual = channel.getpeercert(binary_form=True) + expected = ssl.PEM_cert_to_DER_cert((security / "tls" / node / "server.pem").read_text()) + if actual != expected: raise RigError("TLS control observed another server identity") + return {"server_name": server_name, "certificate_sha256": hashlib.sha256(actual).hexdigest(), + "tls_version": channel.version(), "listener_reachable": True} + + @contextmanager + def _server_identity_material(self, node, material): + directory = self.folder / "security" / "tls" / node + current = {} + for kind in ("pem", "key"): + path = directory / ("server." + kind) + if path.is_symlink() or not path.is_file(): raise RigError("restricted server identity is unavailable") + current[kind] = path.read_text() + def apply(material): + self.inspect_resources() + for kind, content in material.items(): + atomic_write_secret(directory / ("server." + kind), content) + self.compose("restart", node, timeout=90) + manifest = self.refresh_endpoints((node,)) + wait_until(lambda: self.health(manifest), timeout=180, description="server identity experiment readiness") + try: + apply(material) + yield + finally: + apply(current) + + def deploy(self, timeout=180, *, require_catalog=True): + _duration(timeout, "deployment operation timeout") + deadline = time.monotonic() + timeout + def remaining(): + value = deadline - time.monotonic() + if value <= 0: + raise RigError("deployment operation deadline timeout") + return value + manifest = self.load() + if "fixture" not in manifest: + raise RigError("seed must complete before deploy") + primary = wait_active_endpoint({node: manifest["endpoints"][node + ".admin"]["url"] for node in NODES[:2]}, + request=http_request, timeout=remaining(), require_ready=True) + scope = {} + def accepted(identity, revision): + scope.update(self.provision_deployment(identity, revision, timeout=remaining())) + # This inventory comes from the sealer's immutable artifact, not the + # status rows we are about to validate. Maintenance deliberately + # removes a node from expected apply acknowledgements. + required = scope.get("required_node_ids") + if not isinstance(required, list) or not required: + raise RigError("sealed artifact has no required-node inventory") + return required + outcome = deploy_and_wait(manifest["endpoints"][primary + ".admin"]["url"], self.environment["GRPC_DATA_DEPLOY_KEY"], + {node + ":4053" for node in NODES}, request=http_request, timeout=remaining(), on_accepted=accepted) + manifest["deployment"] = {"id": outcome["deploymentId"], "revision_hash": outcome["revisionHash"], "scope_version": scope["scope_version"], "nodes": outcome["nodes"], "required_node_ids": scope["required_node_ids"]} + manifest["deployment"]["bundle_commits"] = self.wait_bundle_commits(scope["bundle_expectations"], timeout=remaining()) + if require_catalog: + wait_until(lambda: self.health(manifest, require_catalog=True, timeout=remaining()), timeout=remaining(), description="deployed catalog and OPC UA namespace identity") + manifest["resolved_nodes"] = json.loads((self.folder / "seed" / "resolved.json").read_text()) + remaining() + manifest["state"] = "ready" + self.capture(manifest) + return manifest + + def status(self): + manifest = self.load() + try: + manifest["healthy"] = self.health(manifest, require_catalog=manifest.get("state") == "ready") + except (OSError, ValueError, RigError): + manifest["healthy"] = False + self.capture(manifest) + return manifest + + def down(self): + if self.path.exists(): + manifest = self.load() + # Refresh exact-ID inventory of the same run; labels are checked twice. + manifest["resources"] = self.inspect_resources() + else: + setup = json.loads((self.folder / "setup.json").read_text()) + if setup != {"run_id": self.run_id, "docker_context": self.context["Name"], "project": self.project}: + raise RigError("interrupted setup journal ownership mismatch") + # cleanup_owned also validates endpoint/node schema; this placeholder + # is safety-only and cannot be reported as running or ready. + manifest = {"schema_version": 1, "run_id": self.run_id, "project": self.project, "labels": {RUN_LABEL: self.run_id, PROJECT_LABEL: self.project}, + "services": list(SERVICES), "endpoints": {"journal": {"scheme": "tcp", "host": "127.0.0.1", "host_port": 1, "container_host": "sql", "container_port": 1433}}, + "nodes": {"source-1": {"cluster_id": "SOURCE", "application_uri": "urn:OtOpcUa:grpc-data:source-1"}}, "resources": self.inspect_resources()} + order = {"container": 0, "network": 1, "volume": 2, "image": 3} + manifest["resources"].sort(key=lambda row: order[row["kind"]]) + def remove(kind, identity): + run_command([*self.docker, kind, "rm", *(["--force"] if kind == "container" else []), identity]) + cleanup_owned(manifest, self.inspect_resources(), remove=remove) + manifest["state"] = "down" + manifest["resources"] = [] + self.save(manifest) + return manifest + + def main(argv=None): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("action", choices=tuple(_PREREQUISITES)) + parser = argparse.ArgumentParser(description="Standalone owned local gRPC data integration rig") + parser.add_argument("action", choices=("preflight", "up", "seed", "deploy", "status", "down")) parser.add_argument("--run-id") + parser.add_argument("--timeout", type=float, default=None) arguments = parser.parse_args(argv) try: - if arguments.action != "preflight" and (not arguments.run_id or not _RUN_PATTERN.fullmatch(arguments.run_id)): - raise RigError("a safe explicit --run-id is required") - require_production_prerequisites(arguments.action, {}) - except RigError as error: - print(f"grpc-data rig: {error}", file=__import__("sys").stderr) + if arguments.action == "preflight": + context = docker_context() + environment = dict(os.environ) + for name in re.findall(r"\$\{([A-Z][A-Z0-9_]*)", (HERE / "compose.yml").read_text()): + environment[name] = "preflight" + environment.update({"GRPC_DATA_PROJECT": "grpc-data-preflight", "GRPC_DATA_RUN_ID": "preflight", + "GRPC_DATA_UID": "0", "GRPC_DATA_GID": "0", "GRPC_DATA_CERT_DIR": "/tmp/grpc-data-preflight/tls", + "GRPC_DATA_CREDENTIAL_DIR": "/tmp/grpc-data-preflight/credentials", "GRPC_DATA_OUTPUT_DIR": "/tmp/grpc-data-preflight/output", + "GRPC_DATA_PROBE_DIR": "/tmp/grpc-data-preflight/probe"}) + resolved = json.loads(run_command(["docker", "--context", context["Name"], "compose", "--file", str(HERE / "compose.yml"), "config", "--format", "json"], environment=environment)) + validate_fixture_endpoints(resolved, local_services=SERVICES) + print(json.dumps({"local_docker": True, "resolved_fixture_local": True, "context": context["Name"]})) + return 0 + rig = LocalRig(arguments.run_id) + action = getattr(rig, arguments.action) + result = action(**({"timeout": arguments.timeout} if arguments.timeout is not None and arguments.action in {"up", "deploy"} else {})) + print(json.dumps({"run_id": result["run_id"], "state": result.get("state"), "manifest": str(rig.path), "healthy": result.get("healthy")})) + return 0 + except (RigError, ValueError, OSError, KeyError) as error: + # Only our own fixed RigError messages are public. Parser/system errors + # can include paths or env supplied secrets, so withhold their contents. + message = str(error) if isinstance(error, RigError) else "fixture operation failed; inspect restricted run files" + print("grpc-data rig: " + message, file=__import__("sys").stderr) return 2 - return 0 if __name__ == "__main__": diff --git a/scripts/validation/grpc-data/scenarios.json b/scripts/validation/grpc-data/scenarios.json new file mode 100644 index 000000000..aeed6fac9 --- /dev/null +++ b/scripts/validation/grpc-data/scenarios.json @@ -0,0 +1,1535 @@ +{ + "schema_version": 1, + "required_order": [ + "D01", + "D01a", + "D02", + "D03", + "D04", + "D05", + "D06", + "D07", + "D08", + "D09", + "D10", + "D11", + "D12", + "D13", + "D14" + ], + "default_timeout_seconds": 480, + "timeouts": { + "D01a": 900, + "D03": 900, + "D14": 900, + "D02": 900, + "D07": 900, + "D10": 900, + "D13": 900 + }, + "prerequisites": [ + "run-owned Docker project", + "six applied nodes", + "dynamic loopback endpoints", + "restricted credentials", + "NamespaceArray resolutions", + "production CLI DLL", + "wire probe DLL", + "caller file runner", + "fixture effect ledger" + ], + "restoration": [ + "transactional baseline authoring restore", + "original TLS identity and trust", + "monotonic scoped credential bundles", + "production deployment and apply polling" + ], + "coverage": { + "D01": [ + "three isolated two-member clusters", + "OPC UA application identity", + "applied artifact revision", + "roles and capabilities" + ], + "D01a": [ + "no namespace mappings", + "Node and Cluster targets", + "actual consumer DI facade", + "same-cluster direct Node", + "Raw and UNS", + "browse metadata read write subscribe" + ], + "D02": [ + "same-cluster Node target", + "A-only scope", + "actual target provenance", + "standby local UA write rejection", + "direct runtime write to primary" + ], + "D03": [ + "cross-cluster Node and Cluster", + "Raw and UNS", + "recursive CLI browse", + "origin value and timestamp", + "new child rename removal", + "genuinely new Raw tag and UNS reference, preserving existing sibling" + ], + "D04": [ + "changing Good CLI notifications", + "write acceptance", + "origin and simulator readback", + "one device effect" + ], + "D05": [ + "page bound", + "continuation use and reuse rejection", + "revision invalidation" + ], + "D06": [ + "local write denial", + "narrow export denial", + "expired key", + "revoked key", + "replacement credential" + ], + "D07": [ + "fixed consumer OPC UA URL", + "source primary failover", + "observed quality gap", + "new serving identity", + "pinned target unavailable", + "Raw and UNS pinned outage", + "operational maintenance primary excluded before failover" + ], + "D08": [ + "mixed per-item results", + "response loss after effect", + "same operation deduplication", + "caller restart", + "stale incarnation rejection" + ], + "D09": [ + "pinned secondary", + "explicit ReadyReplica reads", + "write denial", + "Warm standby and activation", + "Raw and UNS secondary read/write boundaries" + ], + "D10": [ + "OPC UA partner endpoint", + "actual client reconnection", + "new consumer demand", + "A-only scope absent on partner", + "post-stop changing CLI Good notifications while old consumer remains stopped" + ], + "D11": [ + "CONTROL outage only", + "SOURCE local data", + "CONSUMER cross-cluster data", + "no write replay after restart" + ], + "D12": [ + "consumer scope removal", + "export removal", + "mapping removal", + "connection disable", + "local Raw and UNS remain usable" + ], + "D13": [ + "positive TLS identity baseline", + "wrong CA", + "wrong SAN", + "bad key", + "wrong listener", + "untrusted subject", + "authoring rejects peer re-export", + "actual deployed consumer rejects wrong CA and SAN server identities" + ], + "D14": [ + "secret tombstone and provisioning", + "both replicas", + "staged key rotation", + "new CA trust staging", + "server certificate rotation", + "old CA retirement", + "offline restart", + "unknown write tracking", + "stale bundle downgrade rejection", + "actual deployed consumer rejects old-CA server after retirement" + ] + }, + "required_cells": [ + { + "id": "D01a.cross-cluster.Cluster.direct.primary.raw.capabilities", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "capabilities", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Cluster.direct.primary.raw.browse", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "browse", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Cluster.direct.primary.raw.metadata", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "metadata", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Cluster.direct.primary.raw.read", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "read", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Cluster.direct.primary.raw.write", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "write", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Cluster.direct.primary.raw.subscribe", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "subscribe", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Cluster.direct.primary.uns.capabilities", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "capabilities", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Cluster.direct.primary.uns.browse", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "browse", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Cluster.direct.primary.uns.metadata", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "metadata", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Cluster.direct.primary.uns.read", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "read", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Cluster.direct.primary.uns.write", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "write", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Cluster.direct.primary.uns.subscribe", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "subscribe", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Node.direct.primary.raw.capabilities", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "capabilities", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Node.direct.primary.raw.browse", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "browse", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Node.direct.primary.raw.metadata", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "metadata", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Node.direct.primary.raw.read", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "read", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Node.direct.primary.raw.write", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "write", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Node.direct.primary.raw.subscribe", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "subscribe", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Node.direct.primary.uns.capabilities", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "capabilities", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Node.direct.primary.uns.browse", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "browse", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Node.direct.primary.uns.metadata", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "metadata", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Node.direct.primary.uns.read", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "read", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Node.direct.primary.uns.write", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "write", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.cross-cluster.Node.direct.primary.uns.subscribe", + "scenario": "D01a", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "subscribe", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.same-cluster.Node.direct.primary.raw.capabilities", + "scenario": "D01a", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "capabilities", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.same-cluster.Node.direct.primary.raw.browse", + "scenario": "D01a", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "browse", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.same-cluster.Node.direct.primary.raw.metadata", + "scenario": "D01a", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "metadata", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.same-cluster.Node.direct.primary.raw.read", + "scenario": "D01a", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "read", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.same-cluster.Node.direct.primary.raw.write", + "scenario": "D01a", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "write", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.same-cluster.Node.direct.primary.raw.subscribe", + "scenario": "D01a", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "subscribe", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.same-cluster.Node.direct.primary.uns.capabilities", + "scenario": "D01a", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "capabilities", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.same-cluster.Node.direct.primary.uns.browse", + "scenario": "D01a", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "browse", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.same-cluster.Node.direct.primary.uns.metadata", + "scenario": "D01a", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "metadata", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.same-cluster.Node.direct.primary.uns.read", + "scenario": "D01a", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "read", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.same-cluster.Node.direct.primary.uns.write", + "scenario": "D01a", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "write", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D01a.same-cluster.Node.direct.primary.uns.subscribe", + "scenario": "D01a", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "subscribe", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D02.same-cluster.Node.direct.primary.raw.capabilities", + "scenario": "D02", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "capabilities", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D02.same-cluster.Node.direct.primary.raw.browse", + "scenario": "D02", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "browse", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D02.same-cluster.Node.direct.primary.raw.metadata", + "scenario": "D02", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "metadata", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D02.same-cluster.Node.direct.primary.raw.read", + "scenario": "D02", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "read", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D02.same-cluster.Node.direct.primary.raw.write", + "scenario": "D02", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "write", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D02.same-cluster.Node.direct.primary.raw.subscribe", + "scenario": "D02", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "subscribe", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D02.same-cluster.Node.direct.primary.uns.capabilities", + "scenario": "D02", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "capabilities", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D02.same-cluster.Node.direct.primary.uns.browse", + "scenario": "D02", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "browse", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D02.same-cluster.Node.direct.primary.uns.metadata", + "scenario": "D02", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "metadata", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D02.same-cluster.Node.direct.primary.uns.read", + "scenario": "D02", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "read", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D02.same-cluster.Node.direct.primary.uns.write", + "scenario": "D02", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "write", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D02.same-cluster.Node.direct.primary.uns.subscribe", + "scenario": "D02", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "subscribe", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D02.same-cluster.Node.mounted.primary.raw.read", + "scenario": "D02", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "mounted", + "boundary": "primary", + "realm": "raw", + "operation": "read", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D02.same-cluster.Node.mounted.primary.uns.read", + "scenario": "D02", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "mounted", + "boundary": "primary", + "realm": "uns", + "operation": "read", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D02.same-cluster.Node.mounted.local-standby.raw.write", + "scenario": "D02", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "mounted", + "boundary": "local-standby", + "realm": "raw", + "operation": "write", + "outcome": "Denied", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D02.same-cluster.Node.mounted.local-standby.uns.write", + "scenario": "D02", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "mounted", + "boundary": "local-standby", + "realm": "uns", + "operation": "write", + "outcome": "Denied", + "target_consistency": "Primary", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D02.same-cluster.Node.direct.secondary.raw.read", + "scenario": "D02", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "secondary", + "realm": "raw", + "operation": "read", + "outcome": "Good", + "target_consistency": "ReadyReplica", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D02.same-cluster.Node.direct.secondary.uns.read", + "scenario": "D02", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "secondary", + "realm": "uns", + "operation": "read", + "outcome": "Good", + "target_consistency": "ReadyReplica", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D02.same-cluster.Node.direct.secondary.raw.write", + "scenario": "D02", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "secondary", + "realm": "raw", + "operation": "write", + "outcome": "RejectedBeforeDispatch", + "target_consistency": "ReadyReplica", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D02.same-cluster.Node.direct.secondary.uns.write", + "scenario": "D02", + "topology": "same-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "secondary", + "realm": "uns", + "operation": "write", + "outcome": "RejectedBeforeDispatch", + "target_consistency": "ReadyReplica", + "caller_cluster": "SOURCE", + "target_cluster": "SOURCE" + }, + { + "id": "D03.cross-cluster.Node.mounted.primary.raw.browse", + "scenario": "D03", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "mounted", + "boundary": "primary", + "realm": "raw", + "operation": "browse", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D03.cross-cluster.Node.mounted.primary.raw.read", + "scenario": "D03", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "mounted", + "boundary": "primary", + "realm": "raw", + "operation": "read", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D03.cross-cluster.Node.mounted.primary.uns.browse", + "scenario": "D03", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "mounted", + "boundary": "primary", + "realm": "uns", + "operation": "browse", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D03.cross-cluster.Node.mounted.primary.uns.read", + "scenario": "D03", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "mounted", + "boundary": "primary", + "realm": "uns", + "operation": "read", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D03.cross-cluster.Node.direct.primary.raw.metadata", + "scenario": "D03", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "metadata", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D03.cross-cluster.Node.direct.primary.uns.metadata", + "scenario": "D03", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "metadata", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D04.cross-cluster.Node.mounted.primary.raw.write", + "scenario": "D04", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "mounted", + "boundary": "primary", + "realm": "raw", + "operation": "write", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D04.cross-cluster.Node.mounted.primary.raw.subscribe", + "scenario": "D04", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "mounted", + "boundary": "primary", + "realm": "raw", + "operation": "subscribe", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D04.cross-cluster.Node.mounted.primary.uns.write", + "scenario": "D04", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "mounted", + "boundary": "primary", + "realm": "uns", + "operation": "write", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D04.cross-cluster.Node.mounted.primary.uns.subscribe", + "scenario": "D04", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "mounted", + "boundary": "primary", + "realm": "uns", + "operation": "subscribe", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D03.cross-cluster.Cluster.mounted.primary.raw.browse", + "scenario": "D03", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "mounted", + "boundary": "primary", + "realm": "raw", + "operation": "browse", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D03.cross-cluster.Cluster.mounted.primary.raw.read", + "scenario": "D03", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "mounted", + "boundary": "primary", + "realm": "raw", + "operation": "read", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D03.cross-cluster.Cluster.mounted.primary.uns.browse", + "scenario": "D03", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "mounted", + "boundary": "primary", + "realm": "uns", + "operation": "browse", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D03.cross-cluster.Cluster.mounted.primary.uns.read", + "scenario": "D03", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "mounted", + "boundary": "primary", + "realm": "uns", + "operation": "read", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D03.cross-cluster.Cluster.direct.primary.raw.metadata", + "scenario": "D03", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "direct", + "boundary": "primary", + "realm": "raw", + "operation": "metadata", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D03.cross-cluster.Cluster.direct.primary.uns.metadata", + "scenario": "D03", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "direct", + "boundary": "primary", + "realm": "uns", + "operation": "metadata", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D04.cross-cluster.Cluster.mounted.primary.raw.write", + "scenario": "D04", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "mounted", + "boundary": "primary", + "realm": "raw", + "operation": "write", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D04.cross-cluster.Cluster.mounted.primary.raw.subscribe", + "scenario": "D04", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "mounted", + "boundary": "primary", + "realm": "raw", + "operation": "subscribe", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D04.cross-cluster.Cluster.mounted.primary.uns.write", + "scenario": "D04", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "mounted", + "boundary": "primary", + "realm": "uns", + "operation": "write", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D04.cross-cluster.Cluster.mounted.primary.uns.subscribe", + "scenario": "D04", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "mounted", + "boundary": "primary", + "realm": "uns", + "operation": "subscribe", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D07.cross-cluster.Node.direct.pinned-loss.raw.capabilities", + "scenario": "D07", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "pinned-loss", + "realm": "raw", + "operation": "capabilities", + "outcome": "Unavailable", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D07.cross-cluster.Node.direct.pinned-loss.uns.capabilities", + "scenario": "D07", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "pinned-loss", + "realm": "uns", + "operation": "capabilities", + "outcome": "Unavailable", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D07.cross-cluster.Node.mounted.pinned-loss.raw.read", + "scenario": "D07", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "mounted", + "boundary": "pinned-loss", + "realm": "raw", + "operation": "read", + "outcome": "Denied", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D07.cross-cluster.Node.mounted.pinned-loss.uns.read", + "scenario": "D07", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "mounted", + "boundary": "pinned-loss", + "realm": "uns", + "operation": "read", + "outcome": "Denied", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D07.cross-cluster.Cluster.direct.maintenance-primary.raw.capabilities", + "scenario": "D07", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "direct", + "boundary": "maintenance-primary", + "realm": "raw", + "operation": "capabilities", + "outcome": "Unavailable", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D07.cross-cluster.Cluster.direct.maintenance-primary.uns.capabilities", + "scenario": "D07", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "direct", + "boundary": "maintenance-primary", + "realm": "uns", + "operation": "capabilities", + "outcome": "Unavailable", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D07.cross-cluster.Cluster.direct.maintenance-exclusion.raw.read", + "scenario": "D07", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "direct", + "boundary": "maintenance-exclusion", + "realm": "raw", + "operation": "read", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D07.cross-cluster.Cluster.direct.maintenance-exclusion.uns.read", + "scenario": "D07", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "direct", + "boundary": "maintenance-exclusion", + "realm": "uns", + "operation": "read", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D07.cross-cluster.Cluster.mounted.source-failover.raw.subscribe", + "scenario": "D07", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "mounted", + "boundary": "source-failover", + "realm": "raw", + "operation": "subscribe", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D07.cross-cluster.Cluster.mounted.source-failover.uns.subscribe", + "scenario": "D07", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "mounted", + "boundary": "source-failover", + "realm": "uns", + "operation": "subscribe", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D09.cross-cluster.Node.direct.secondary.raw.read", + "scenario": "D09", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "secondary", + "realm": "raw", + "operation": "read", + "outcome": "Good", + "target_consistency": "ReadyReplica", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D09.cross-cluster.Node.direct.secondary.uns.read", + "scenario": "D09", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "secondary", + "realm": "uns", + "operation": "read", + "outcome": "Good", + "target_consistency": "ReadyReplica", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D09.cross-cluster.Node.direct.secondary.raw.write", + "scenario": "D09", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "secondary", + "realm": "raw", + "operation": "write", + "outcome": "RejectedBeforeDispatch", + "target_consistency": "ReadyReplica", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D09.cross-cluster.Node.direct.secondary.uns.write", + "scenario": "D09", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "secondary", + "realm": "uns", + "operation": "write", + "outcome": "RejectedBeforeDispatch", + "target_consistency": "ReadyReplica", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D10.cross-cluster.Cluster.mounted.consumer-failover.raw.subscribe", + "scenario": "D10", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "mounted", + "boundary": "consumer-failover", + "realm": "raw", + "operation": "subscribe", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D10.cross-cluster.Cluster.mounted.consumer-failover.uns.subscribe", + "scenario": "D10", + "topology": "cross-cluster", + "target_mode": "Cluster", + "surface": "mounted", + "boundary": "consumer-failover", + "realm": "uns", + "operation": "subscribe", + "outcome": "Good", + "target_consistency": "Primary", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D13.cross-cluster.Node.direct.wrong-ca.raw.capabilities", + "scenario": "D13", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "wrong-ca", + "realm": "raw", + "operation": "capabilities", + "outcome": "Unavailable", + "target_consistency": "ReadyReplica", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D13.cross-cluster.Node.direct.wrong-ca.uns.capabilities", + "scenario": "D13", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "wrong-ca", + "realm": "uns", + "operation": "capabilities", + "outcome": "Unavailable", + "target_consistency": "ReadyReplica", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D13.cross-cluster.Node.direct.wrong-san.raw.capabilities", + "scenario": "D13", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "wrong-san", + "realm": "raw", + "operation": "capabilities", + "outcome": "Unavailable", + "target_consistency": "ReadyReplica", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D13.cross-cluster.Node.direct.wrong-san.uns.capabilities", + "scenario": "D13", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "wrong-san", + "realm": "uns", + "operation": "capabilities", + "outcome": "Unavailable", + "target_consistency": "ReadyReplica", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D14.cross-cluster.Node.direct.retired-ca.raw.capabilities", + "scenario": "D14", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "retired-ca", + "realm": "raw", + "operation": "capabilities", + "outcome": "Unavailable", + "target_consistency": "ReadyReplica", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + }, + { + "id": "D14.cross-cluster.Node.direct.retired-ca.uns.capabilities", + "scenario": "D14", + "topology": "cross-cluster", + "target_mode": "Node", + "surface": "direct", + "boundary": "retired-ca", + "realm": "uns", + "operation": "capabilities", + "outcome": "Unavailable", + "target_consistency": "ReadyReplica", + "caller_cluster": "CONSUMER", + "target_cluster": "SOURCE" + } + ] +} diff --git a/scripts/validation/grpc-data/scenarios.py b/scripts/validation/grpc-data/scenarios.py new file mode 100644 index 000000000..a3c8f8743 --- /dev/null +++ b/scripts/validation/grpc-data/scenarios.py @@ -0,0 +1,1953 @@ +"""Executable, fail-closed D01-D14 production-rig orchestration. + +Every result is derived from a production operation, a deployed artifact, or the +run-owned device ledger. Missing instrumentation is a failed assertion. Nothing +is skipped by ``all``. The only remote control surface is the software device; +host-side controls use exact owned Compose services and the fixture file runner. +""" +from contextlib import contextmanager, nullcontext +import base64 +import copy +from dataclasses import asdict +from datetime import datetime, timedelta, timezone +import hashlib +import json +import math +import os +from pathlib import Path +import re +import sys +import threading +import time +import uuid + +import cli_gate +from processes import run_process, redact_text +import rig + + +SCENARIOS = ("D01", "D01a", *(f"D{number:02}" for number in range(2, 15))) +OPERATIONS = 1 | 2 | 4 | 8 | 16 +FIXTURE_CLOCK_ALLOWANCE_SECONDS = 1 +# The CONTROL fixture uses MeshTransportOptions.ContactRefreshSeconds (60) +# plus five seconds for the asynchronous SQL read and actor adoption. +MAINTENANCE_CONTACT_SETTLE_SECONDS = 65 +D03_TIMESTAMP_BOUNDARY_COMPANIONS = { + "kind": "external_phase_gate_source_references", + "scope": "Two separate controlled boundary proofs; execution receipts belong to the phase evidence ledger.", + "tests": [ + {"boundary": "production TLS gRPC read", + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests.csproj", + "selector": "FullyQualifiedName=ZB.MOM.WW.OtOpcUa.Host.IntegrationTests.DataConnections.GrpcDataSampleFidelityTlsWireTests.Production_tls_read_preserves_one_controlled_samples_independent_timestamps_status_value_and_version", + "source": "tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataSampleFidelityTlsWireTests.cs"}, + {"boundary": "mapped OPC UA SDK read", + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj", + "selector": "FullyQualifiedName=ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections.GrpcDataConfiguredDiscoveryWireTests.Sdk_mapped_read_preserves_one_controlled_samples_independent_timestamps_quality_value_and_version", + "source": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSampleFidelityWireTests.cs"} + ] +} + + +class ScenarioError(RuntimeError): + pass + + +def _fixture_utc_timestamp(value): + if not isinstance(value, str): + raise ScenarioError("fixture read timestamp is missing") + try: + parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) + except (ValueError, TypeError): + raise ScenarioError("fixture read timestamp is invalid") from None + if parsed.tzinfo is None or parsed.utcoffset() != timedelta(0): + raise ScenarioError("fixture read timestamp must be aware UTC") + if parsed.year <= 1601 or parsed.year == 9999: + raise ScenarioError("fixture read timestamp is a sentinel") + return parsed + + +def validate_fixture_read_timestamps(observed, *, modbus_fixture=False): + """Validate each cached sample against its own observed CLI completion.""" + if not isinstance(observed, dict) or observed.get("status") != "Good": + raise ScenarioError("fixture CLI read must be Good") + source = _fixture_utc_timestamp(observed.get("source_time")) + server = _fixture_utc_timestamp(observed.get("server_time")) + completed = _fixture_utc_timestamp(observed.get("completed_at_utc")) + latest = completed + timedelta(seconds=FIXTURE_CLOCK_ALLOWANCE_SECONDS) + if source > latest or server > latest: + raise ScenarioError("fixture read timestamp exceeds its CLI completion clock allowance") + # This fixture's Modbus acquisition sets source time before server time. + # Other sources can carry independent clocks and have no ordering contract. + if modbus_fixture and source > server: + raise ScenarioError("Modbus fixture source timestamp exceeds server timestamp") + return observed + + +def validate_fixture_read_pair(origin, mapped, *, modbus_fixture=False): + """Compare stable fixture values while retaining independent cached sample times.""" + validate_fixture_read_timestamps(origin, modbus_fixture=modbus_fixture) + validate_fixture_read_timestamps(mapped, modbus_fixture=modbus_fixture) + if not origin.get("value") or origin.get("value") != mapped.get("value"): + raise ScenarioError("origin and mapped fixture values differ") + return {"origin": origin, "mapped": mapped, "clock_allowance_seconds": FIXTURE_CLOCK_ALLOWANCE_SECONDS, + "modbus_source_not_after_server": modbus_fixture, + "comparison": "independent cached samples with matching fixture values"} + + +def fixture_browse_root(fixture, realm): + """UNS container identity is an EquipmentId, separate from leaf paths.""" + roots = fixture.get("browse_roots") if isinstance(fixture, dict) else None + root = roots.get(realm) if isinstance(roots, dict) else None + if realm not in {"raw", "uns"} or not isinstance(root, str) or not root or len(root) > 1024: + raise ScenarioError("explicit fixture browse container identity missing") + return root + + +def relative_origin_identifier(fixture, realm, identifier, name): + return identifier.rsplit("/", 1)[0] + "/" + name if name else fixture_browse_root(fixture, realm) + + +def validate_read_freshness(observed, maximum_age_ms=5000): + if (not isinstance(observed, dict) or observed.get("status") != "Good" + or observed.get("resultReadiness") != "Ready" or observed.get("maximumAgeMilliseconds") != maximum_age_ms): + raise ScenarioError("actual read readiness or requested freshness differs") + if maximum_age_ms is not None: + bounds = observed.get("ageBounds") + lower = bounds.get("lowerMilliseconds") if isinstance(bounds, dict) else None + upper = bounds.get("upperMilliseconds") if isinstance(bounds, dict) else None + if (type(lower) not in (int, float) or type(upper) not in (int, float) + or not math.isfinite(lower) or not math.isfinite(upper) or not 0 <= lower <= upper <= maximum_age_ms): + raise ScenarioError("actual read has no finite age within requested bound") + return observed + + +def validate_warm_secondary_read(observed, *, expected_node_id): + """Validate payloadless API-eligible Secondary data; startup Warm Standby uses selection rejection.""" + if (not isinstance(observed, dict) or observed.get("status") not in {"WaitingForInitialData", "Unavailable"} + or observed.get("resultReadiness") not in {"WaitingForInitialData", "Unavailable", "Invalidated"} + or "sample" not in observed or observed["sample"] is not None): + raise ScenarioError("Warm secondary must expose only unavailable or waiting data without a sample") + serving, target = observed.get("serving"), observed.get("target") + if (not isinstance(serving, dict) or serving.get("nodeId") != expected_node_id or serving.get("role") != "Secondary" + or not isinstance(target, dict) or target.get("mode") != "Node" or target.get("consistency") != "ReadyReplica" + or target.get("expectedClusterId") != "SOURCE" or target.get("expectedNodeId") != expected_node_id): + raise ScenarioError("Warm secondary read moved outside its exact pinned secondary") + return observed + + +def validate_startup_warm_state(observed, *, expected_node_id, expected_role=None): + if (not isinstance(observed, dict) or observed.get("nodeId") != expected_node_id + or observed.get("mode") != "Warm" or observed.get("isWarm") is not True): + raise ScenarioError("SOURCE node has not proven startup Warm mode") + role, serving, process = observed.get("warmRole"), observed.get("serving"), observed.get("process") + if (not isinstance(role, dict) or role.get("role") not in {"Active", "Standby"} + or type(role.get("generation")) is not int or role["generation"] <= 0 + or expected_role is not None and role["role"] != expected_role + or not isinstance(serving, dict) or serving.get("nodeId") != expected_node_id + or serving.get("role") != ("Primary" if role["role"] == "Active" else "Standby") + or not isinstance(serving.get("incarnation"), str) or not serving["incarnation"] + or any(type(serving.get(key)) is not int or serving[key] <= 0 + for key in ("catalogEpoch", "authorityEpoch", "servingGeneration")) + or not isinstance(process, dict) or type(process.get("id")) is not int or process["id"] <= 0): + raise ScenarioError("SOURCE Warm verdict, serving identity or process proof is incomplete") + _fixture_utc_timestamp(process.get("startedUtc")) + return observed + + +def select_warm_pair(states): + if not isinstance(states, dict) or set(states) != {"source-1", "source-2"}: + raise ScenarioError("the exact owned SOURCE Warm pair is required") + for node, observed in states.items(): + validate_startup_warm_state(observed, expected_node_id=node + ":4053") + active = [node for node, observed in states.items() if observed["warmRole"]["role"] == "Active"] + standby = [node for node, observed in states.items() if observed["warmRole"]["role"] == "Standby"] + if len(active) != 1 or len(standby) != 1: + raise ScenarioError("SOURCE Warm pair must prove one actual Active and one Standby") + return active[0], standby[0] + + +def validate_warm_target_rejection(observed, source_state, *, expected_node_id): + validate_startup_warm_state(source_state, expected_node_id=expected_node_id, expected_role="Standby") + if not isinstance(observed, dict): + raise ScenarioError("Warm Standby target rejection evidence is missing") + target, failure = observed.get("target"), observed.get("failureEvidence") + chain = failure.get("chain") if isinstance(failure, dict) else None + if (observed.get("selectionRejection") != "TargetIneligible" or observed.get("failurePhase") != "GetCapabilities" + or observed.get("readiness") != "Unavailable" or observed.get("sample") is not None + or not isinstance(target, dict) or target.get("mode") != "Node" or target.get("consistency") != "ReadyReplica" + or target.get("expectedClusterId") != "SOURCE" or target.get("expectedNodeId") != expected_node_id + or not isinstance(failure, dict) or failure.get("category") != "TargetIneligible" or failure.get("truncated") is not False + or not isinstance(chain, list) or not 1 <= len(chain) <= 8 + or not all(isinstance(frame, dict) and frame.get("code") in {"NoReadyEndpoint", "TargetIneligible"} + and frame.get("rpcStatus") is None for frame in chain) + or not any(frame.get("code") == "TargetIneligible" for frame in chain)): + raise ScenarioError("Warm Standby requires exact authenticated target-ineligible proof, not transport or TLS failure") + return observed + + +def is_key_only_mutation(mutation): + return (isinstance(mutation, dict) and isinstance(mutation.get("key_action"), str) + and mutation["key_action"] in {"rotate", "rotate_staged", "expire", "retire_old", "revoke"} + and set(mutation) <= {"key_action", "key_expiry_seconds"}) + + +def validate_key_only_revision_receipt(receipt, *, action): + if (not isinstance(receipt, dict) or set(receipt) != {"keyAction", "revisions"} + or receipt.get("keyAction") != action or not is_key_only_mutation({"key_action": action})): + raise ScenarioError("credential mutation revision receipt does not match the requested action") + revisions = receipt["revisions"] + if (not isinstance(revisions, dict) or set(revisions) != {"CredentialOnly", "Before", "After"} + or revisions.get("CredentialOnly") is not True): + raise ScenarioError("credential mutation was not isolated from configuration revisions") + for snapshot in (revisions["Before"], revisions["After"]): + if not isinstance(snapshot, dict) or set(snapshot) != {"Connection", "Mappings", "Exports"}: + raise ScenarioError("credential revision snapshot is incomplete") + values = [snapshot["Connection"]] + for kind in ("Mappings", "Exports"): + rows = snapshot[kind] + if (not isinstance(rows, dict) or len(rows) > 256 + or any(not isinstance(identity, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", identity) for identity in rows)): + raise ScenarioError("credential revision snapshot has invalid entity identities") + values.extend(rows.values()) + if any(type(value) is not int or not 0 < value <= 2**63 - 1 for value in values): + raise ScenarioError("credential revision snapshot must contain positive numeric revisions") + if revisions["Before"] != revisions["After"]: + raise ScenarioError("credential-only mutation changed connection, mapping or export revisions") + return receipt + + +def metadata_lease_seconds(lease): + duration = lease.get("duration") if isinstance(lease, dict) else None + if not isinstance(duration, str) or not re.fullmatch(r"\d{2}:\d{2}:\d{2}(?:\.\d{1,7})?", duration): + raise ScenarioError("observed metadata lease duration is missing") + hours, minutes, seconds = duration.split(":") + value = int(hours) * 3600 + int(minutes) * 60 + float(seconds) + if not 0 < value <= 60 or int(minutes) >= 60 or float(seconds) >= 60: + raise ScenarioError("observed metadata lease exceeds the bounded fixture wait") + return value + + +def validate_tls_rejection_counters(before, after): + identity = before.get("inboundDataRequestObserverId") + if (not isinstance(identity, str) or not identity or after.get("inboundDataRequestObserverId") != identity + or type(before.get("inboundDataRequests")) is not int or before["inboundDataRequests"] != 0 + or type(after.get("inboundDataRequests")) is not int or after["inboundDataRequests"] != 0): + raise ScenarioError("TLS-negative requests reached HTTP or the listener observer changed") + return {"observer_id": identity, "http_requests_before": 0, "http_requests_after": 0} + + +class NotificationLines: + """Incrementally parse complete CLI notification lines without duplicate arrivals.""" + def __init__(self): + self.pending = "" + + def feed(self, chunk): + self.pending += chunk + if len(self.pending) > 65536: + raise ScenarioError("oversized CLI notification line") + lines = self.pending.split("\n") + self.pending = lines.pop() + return [parsed for line in lines if (parsed := cli_gate.parse_notification(line)) is not None] + + +def required_matrix_cells(): + """Executable cells from the plan's topology/realm/operation matrix.""" + cells = [] + def add(scenario, topology, mode, surface, operations, outcome="Good", boundary="primary"): + for realm in ("raw", "uns"): + for operation in operations: + cells.append({"id": ".".join((scenario, topology, mode, surface, boundary, realm, operation)), + "scenario": scenario, "topology": topology, "target_mode": mode, "surface": surface, + "boundary": boundary, "realm": realm, "operation": operation, "outcome": outcome, + "target_consistency": "ReadyReplica" if boundary in {"secondary", "wrong-ca", "wrong-san", "retired-ca"} else "Primary", + "caller_cluster": "SOURCE" if topology == "same-cluster" else "CONSUMER", "target_cluster": "SOURCE"}) + for topology, mode in (("cross-cluster", "Cluster"), ("cross-cluster", "Node"), ("same-cluster", "Node")): + add("D01a", topology, mode, "direct", ("capabilities", "browse", "metadata", "read", "write", "subscribe")) + add("D02", "same-cluster", "Node", "direct", ("capabilities", "browse", "metadata", "read", "write", "subscribe")) + add("D02", "same-cluster", "Node", "mounted", ("read",)) + add("D02", "same-cluster", "Node", "mounted", ("write",), "Denied", "local-standby") + add("D02", "same-cluster", "Node", "direct", ("read",), boundary="secondary") + add("D02", "same-cluster", "Node", "direct", ("write",), "RejectedBeforeDispatch", "secondary") + for mode in ("Node", "Cluster"): + add("D03", "cross-cluster", mode, "mounted", ("browse", "read")) + add("D03", "cross-cluster", mode, "direct", ("metadata",)) + add("D04", "cross-cluster", mode, "mounted", ("write", "subscribe")) + add("D07", "cross-cluster", "Node", "direct", ("capabilities",), "Unavailable", "pinned-loss") + add("D07", "cross-cluster", "Node", "mounted", ("read",), "Denied", "pinned-loss") + add("D07", "cross-cluster", "Cluster", "direct", ("capabilities",), "Unavailable", "maintenance-primary") + add("D07", "cross-cluster", "Cluster", "direct", ("read",), boundary="maintenance-exclusion") + add("D07", "cross-cluster", "Cluster", "mounted", ("subscribe",), boundary="source-failover") + add("D09", "cross-cluster", "Node", "direct", ("read",), boundary="secondary") + add("D09", "cross-cluster", "Node", "direct", ("write",), "RejectedBeforeDispatch", "secondary") + add("D10", "cross-cluster", "Cluster", "mounted", ("subscribe",), boundary="consumer-failover") + for boundary in ("wrong-ca", "wrong-san"): + add("D13", "cross-cluster", "Node", "direct", ("capabilities",), "Unavailable", boundary) + add("D14", "cross-cluster", "Node", "direct", ("capabilities",), "Unavailable", "retired-ca") + return cells + + +MATRIX_CELLS = required_matrix_cells() + + +def matrix_cell_id(scenario, topology, mode, surface, realm, operation, boundary="primary"): + return ".".join((scenario, topology, mode, surface, boundary, realm, operation)) + + +def validate_matrix_cells(observed, selected=SCENARIOS): + required = {cell["id"]: cell for cell in MATRIX_CELLS if cell["scenario"] in selected} + if not isinstance(observed, list): + raise ScenarioError("observed matrix cells missing") + ids = [cell.get("id") for cell in observed if isinstance(cell, dict)] + if len(ids) != len(observed) or len(ids) != len(set(ids)) or set(ids) != set(required): + raise ScenarioError("required topology/realm/operation cells missing or duplicated") + for cell in observed: + expected = required[cell["id"]] + if any(cell.get(key) != value for key, value in expected.items()) or cell.get("validated") is not True: + raise ScenarioError("observed matrix cell differs from required routing") + if not cell.get("caller_node_id") or not isinstance(cell.get("evidence"), dict): + raise ScenarioError("matrix cell lacks actual caller and operation evidence") + probe = cell["evidence"].get("probe") + target = probe.get("target") if isinstance(probe, dict) else None + if (not isinstance(target, dict) or probe.get("callerNodeId") != cell["caller_node_id"] + or probe.get("callerClusterId") != expected["caller_cluster"] or probe.get("realm", "").lower() != expected["realm"] + or target.get("mode") != expected["target_mode"] or target.get("expectedClusterId") != expected["target_cluster"] + or target.get("consistency") != expected["target_consistency"] + or not probe.get("namespaceUri") or not probe.get("path")): + raise ScenarioError("matrix observed caller/target/realm routing evidence invalid") + serving = probe.get("serving") + if expected["outcome"] == "Unavailable" or expected["boundary"] == "pinned-loss": + if probe.get("readiness") != "Unavailable" or serving: + raise ScenarioError("matrix unavailable endpoint unexpectedly served") + elif not isinstance(serving, dict) or serving.get("nodeId") != cell.get("serving_node_id"): + raise ScenarioError("matrix actual serving identity missing") + elif serving.get("role") != ("Secondary" if expected["boundary"] == "secondary" else "Primary"): + raise ScenarioError("matrix serving role differs from required boundary") + if expected["target_mode"] == "Node" and (not target.get("expectedNodeId") + or isinstance(serving, dict) and serving["nodeId"] != target["expectedNodeId"]): + raise ScenarioError("matrix pinned node substituted another endpoint") + if expected["surface"] == "mounted" and not cell["evidence"].get("cli"): + raise ScenarioError("matrix mounted operation has no CLI evidence") + return True + + +class ControlledFixtureSource: + """Keep ordinary changes disjoint from a reserved, one-shot recovery value.""" + def __init__(self, device, initial, used_values): + self.device = device + self.current = initial + self.initial_value = initial + self.ordinary_wrap_count = 0 + self.used_values = used_values + self.used_values.add(initial) + self.lock = threading.Lock() + self.paused = threading.Event() + self.sentinel_value = next((value for value in range(65535, 32767, -1) if value not in used_values), None) + if self.sentinel_value is None: + raise ScenarioError("bounded recovery sentinel space exhausted") + self.used_values.add(self.sentinel_value) + self.reserved_at = time.monotonic() + self.published = False + + def tick(self): + with self.lock: + if self.paused.is_set(): + return False + # Regular production never visits the reserved high UInt16 band. + next_value = (self.current + 1) % 32768 + if self.current < 32768 and next_value <= self.current: + self.ordinary_wrap_count += 1 + self.current = next_value + self.used_values.add(self.current) + self.device("advance", steps=1) + self.device("set", address=20, value=self.current) + return True + + @contextmanager + def sentinel(self): + with self.lock: + if self.published or self.paused.is_set(): + raise ScenarioError("recovery sentinel may be produced once per controlled source") + self.paused.set() + self.published = True + produced_at = time.monotonic() + try: + state = self.device("set", address=20, value=self.sentinel_value) + except BaseException: + self.paused.clear() + raise + confirmed_at = time.monotonic() + if state.get("writable", {}).get("20") != self.sentinel_value: + self.paused.clear() + raise ScenarioError("fixture did not confirm the recovery sentinel") + try: + yield {"value": str(self.sentinel_value), "reserved_at": self.reserved_at, + "produced_at": produced_at, "confirmed_at": confirmed_at} + finally: + self.paused.clear() + + +def validate_fault_notifications(notifications, *, fault_at, require_gap, required_sentinel, effective_at=None, + withdrawal_at=None, reauthorization_at=None, reauthorization_completed_at=None): + """Use arrival times captured once per complete CLI line, not whole-log matches.""" + before = [row for row in notifications if row["at"] < fault_at and cli_gate.is_good_status(row["status"])] + after = [row for row in notifications if row["at"] >= (effective_at if effective_at is not None else fault_at) and cli_gate.is_good_status(row["status"])] + if not before or not after or not any(row["value"] != before[-1]["value"] for row in after): + raise ScenarioError("CLI has no fresh changing Good notification after the actual fault") + if (not isinstance(required_sentinel, dict) or not isinstance(required_sentinel.get("value"), str) + or not required_sentinel["value"].isdigit() or not 32768 <= int(required_sentinel["value"]) <= 65535 + or not isinstance(required_sentinel.get("reserved_at"), (int, float)) + or not isinstance(required_sentinel.get("produced_at"), (int, float)) + or not isinstance(required_sentinel.get("confirmed_at"), (int, float)) + or not required_sentinel["reserved_at"] < fault_at + or not (effective_at if effective_at is not None else fault_at) <= required_sentinel["produced_at"] <= required_sentinel["confirmed_at"]): + raise ScenarioError("unique post-fault source sentinel evidence missing") + sentinel_rows = [row for row in notifications if cli_gate.is_good_status(row["status"]) + and row["value"] == required_sentinel["value"]] + if (not sentinel_rows or any(row["at"] < required_sentinel["produced_at"] for row in sentinel_rows) + or not any(row["at"] >= required_sentinel["produced_at"] for row in after if row["value"] == required_sentinel["value"])): + raise ScenarioError("CLI did not observe the newly produced recovery sentinel") + if require_gap: + gaps = [row for row in notifications if row["at"] >= fault_at and row["status"].startswith("Bad")] + if not gaps or not any(row["at"] > gaps[0]["at"] for row in after): + raise ScenarioError("CLI lacks a fault-time quality gap followed by Good recovery") + if withdrawal_at is not None: + if reauthorization_at is None or reauthorization_at - withdrawal_at < 1: + raise ScenarioError("authorization withdrawal observation interval missing") + if any(cli_gate.is_good_status(row["status"]) and withdrawal_at <= row["at"] < reauthorization_at for row in notifications): + raise ScenarioError("CLI emitted Good during withdrawn authorization") + if not any(row["at"] >= reauthorization_at for row in after): + raise ScenarioError("CLI lacks Good after reauthorization") + if (reauthorization_completed_at is None or reauthorization_completed_at < reauthorization_at + or required_sentinel["produced_at"] < reauthorization_completed_at): + raise ScenarioError("recovery sentinel preceded completed reauthorization") + return {"fault_at": fault_at, "fault_effective_at": effective_at, "post_fault_good": len(after), "notifications": notifications, + "withdrawal_at": withdrawal_at, "reauthorization_at": reauthorization_at, + "reauthorization_completed_at": reauthorization_completed_at, "sentinel": required_sentinel, + "sentinel_notifications": len(sentinel_rows)} + + +def validate_source_outage_notification(notifications, *, stop_requested_at, stop_completed_at): + """Require the latest actual quality to show the current shutdown outage. + + Graceful shutdown may emit its only Bad before Docker stop completes. That + observation remains useful after completion only until a later Good arrives. + Callers inspect the notification list while holding its append lock. + """ + if (any(type(value) not in (int, float) or not math.isfinite(value) + for value in (stop_requested_at, stop_completed_at)) + or stop_requested_at > stop_completed_at or not notifications): + raise ScenarioError("SOURCE outage boundaries or actual notification are missing") + latest = notifications[-1] + arrival = latest.get("at") if isinstance(latest, dict) else None + status = latest.get("status") if isinstance(latest, dict) else None + if (type(arrival) not in (int, float) or not math.isfinite(arrival) + or not stop_requested_at <= arrival <= stop_requested_at + 45 + or not isinstance(status, str) or not status or cli_gate.is_good_status(status)): + raise ScenarioError("latest CLI quality does not prove the requested SOURCE outage") + return arrival + + +def validate_post_lease_progress(notifications, *, boundary_at, ordinary_floor, ordinary_wrap_count): + """Exclude queued pre-boundary data and high-band sentinels from ordinary progress.""" + if (type(ordinary_floor) is not int or not 0 <= ordinary_floor < 32768 + or type(ordinary_wrap_count) is not int or ordinary_wrap_count != 0): + raise ScenarioError("post-lease ordinary source floor is invalid") + values, arrivals = [], [] + for row in notifications: + value = row.get("value") + if (row["at"] >= boundary_at and cli_gate.is_good_status(row["status"]) + and isinstance(value, str) and value.isdigit() and ordinary_floor < int(value) < 32768 + and int(value) not in values): + values.append(int(value)); arrivals.append(row["at"]) + if len(values) == 2: + return {"boundary_at": boundary_at, "ordinary_floor": ordinary_floor, "ordinary_wrap_count": ordinary_wrap_count, + "ordinary_values": values, "observed_at": arrivals} + raise ScenarioError("live CLI lacks two fresh ordinary changes after the metadata-lease boundary") + + +def validate_probe_result(result, *, expected_id, expected_operation=None): + if not isinstance(result, dict) or result.get("id") != expected_id or result.get("passed") is not True: + raise ScenarioError("production probe did not pass the requested command") + if type(result.get("assertions")) is not int or result["assertions"] <= 0: + raise ScenarioError("probe supplied no assertions") + if expected_operation is not None and result.get("operation") != expected_operation: + raise ScenarioError("probe operation mismatch") + if not isinstance(result.get("observations"), dict): + raise ScenarioError("probe observations missing") + return result + + +def validate_scenario_rows(rows, expected): + if len(rows) != len(expected) or [row.get("id") for row in rows] != list(expected): + raise ScenarioError("scenario result coverage is incomplete or reordered") + if not all(row.get("passed") is True and type(row.get("assertions")) is int and row["assertions"] > 0 + and row.get("restored") is True for row in rows): + return False + try: + return all(validate_matrix_cells(row.get("cells"), (row["id"],)) for row in rows) + except ScenarioError: + return False + + +def restricted_json(path): + path = Path(path) + if not path.is_absolute() or path.is_symlink() or not path.is_file() or path.stat().st_size > 8 * 1024 * 1024: + raise ScenarioError("restricted run file missing or invalid") + if os.name != "nt" and path.stat().st_mode & 0o077: + raise ScenarioError("run file must not be accessible by group or others") + return json.loads(path.read_text()) + + +def probe_timeout_seconds(operation, timeout): + """Bound each operation while leaving the default origin write enough dispatch time.""" + if timeout is not None: + return timeout + if operation == "dedup": + return 70 + if operation in {"write", "mixed-write"}: + return 40 + return 20 + + +def cli_timeout_seconds(operation, duration): + return 60 if operation == "write" else duration + 20 + + +class ScenarioRunner: + def __init__(self, run_id, *, manifest_path=None, cli_dll=None, probe_dll=None): + self.rig = rig.LocalRig(run_id) + self.manifest_path = Path(manifest_path or self.rig.path).resolve() + if self.manifest_path != self.rig.path.resolve(): + raise ScenarioError("scenario mutations require this run's canonical manifest") + self.manifest = restricted_json(self.manifest_path) + self.initial_resolved = copy.deepcopy(self.manifest.get("resolved_nodes", {})) + rig.validate_manifest(self.manifest, expected_run_id=run_id) + if self.manifest.get("state") != "ready": + raise ScenarioError("the deployed production fixture must be ready") + self.rig.verify_candidate() + self.folder = self.rig.folder / "evidence" + self.folder.mkdir(mode=0o700, exist_ok=True) + self.cli_dll = Path(cli_dll or self.rig.folder / "tools" / "cli" / "ZB.MOM.WW.OtOpcUa.Client.CLI.dll").resolve() + self.probe_dll = Path(probe_dll or self.rig.folder / "tools" / "probe" / "GrpcDataProbe.dll").resolve() + self.secrets = [] + for path in [self.manifest["credentials"]["cli_key_file"], *self.manifest["credentials"]["data_key_files"].values()]: + file = Path(path) + if not file.is_absolute() or not file.resolve().is_relative_to(self.rig.folder.resolve()) or file.is_symlink() or not file.is_file() or (os.name != "nt" and file.stat().st_mode & 0o077): + raise ScenarioError("credential file must be restricted") + self.secrets.append(file.read_text().strip()) + self.key = self.secrets[0] + self.count = 0 + self.records = [] + self.deadline = 0 + self.active = "" + self.timeline = [] + self.catalog = json.loads((rig.HERE / "scenarios.json").read_text()) + if tuple(self.catalog["required_order"]) != SCENARIOS: + raise ScenarioError("required scenario catalog is incomplete") + if self.catalog.get("required_cells") != MATRIX_CELLS: + raise ScenarioError("required topology/realm/operation catalog is incomplete") + self.matrix_cells = [] + + def record_matrix_cell(self, topology, mode, surface, realm, operation, caller, observed, *, + boundary="primary", expected_node=None, cli_evidence=None): + identity = matrix_cell_id(self.active, topology, mode, surface, realm, operation, boundary) + required = next((cell for cell in MATRIX_CELLS if cell["id"] == identity), None) + self.check(required is not None, "declared matrix cell") + self.check(not any(cell["id"] == identity for cell in self.matrix_cells), "matrix cell recorded exactly once") + self.check(observed.get("callerNodeId") == self.node_id(caller) + and observed.get("callerClusterId") == self.manifest["nodes"][caller]["cluster_id"] == required["caller_cluster"], "actual caller identity and topology") + target = observed.get("target") + self.check(isinstance(target, dict) and target.get("mode") == mode + and target.get("expectedClusterId") == required["target_cluster"] + and target.get("consistency") == required["target_consistency"], "actual configured target mode, cluster and consistency") + self.check(observed.get("realm", "").lower() == realm + and observed.get("namespaceUri") == self.manifest["fixture"]["namespace_uris"][realm], "executed origin realm and namespace") + serving = observed.get("serving") + if required["outcome"] != "Unavailable" and boundary != "pinned-loss": + self.check(isinstance(serving, dict) and serving.get("nodeId") in { + row["node_id"] for row in self.manifest["nodes"].values() if row["cluster_id"] == "SOURCE"}, "observed serving node belongs to origin") + if expected_node is not None: + self.check(serving["nodeId"] == self.node_id(expected_node), "actual serving node matches selected boundary") + self.check(serving.get("role") == ("Secondary" if boundary == "secondary" else "Primary"), "actual target role matches boundary") + if mode == "Node": + self.check(expected_node is not None and target.get("expectedNodeId") == self.node_id(expected_node), "actual pinned identity") + if isinstance(serving, dict): + self.check(serving["nodeId"] == target["expectedNodeId"], "pinned target never substitutes partner") + if surface == "mounted": + self.check(isinstance(cli_evidence, dict) and bool(cli_evidence), "validated actual CLI operation evidence") + elif operation == "read": + self.check(observed.get("status") == required["outcome"], "observed read outcome") + elif operation == "write": + self.check(isinstance(observed.get("outcomes"), list) and bool(observed["outcomes"]), "observed write outcome evidence") + state = observed["outcomes"][0].get("outcome", {}).get("state") + self.check(state in ((1, "RejectedBeforeDispatch") if required["outcome"] == "RejectedBeforeDispatch" else (2, "DriverConfirmedSuccess")), + "observed exact write outcome") + elif required["outcome"] == "Unavailable": + self.check(observed.get("readiness") == "Unavailable" and not serving, "actual pinned endpoint unavailable") + evidence = {"probe": observed, **({"cli": cli_evidence} if cli_evidence is not None else {})} + self.matrix_cells.append({**required, "validated": True, "caller_node_id": observed["callerNodeId"], + "serving_node_id": serving.get("nodeId") if isinstance(serving, dict) else None, "evidence": evidence}) + + def matrix_probe(self, topology, mode, realm, operation, caller, *, boundary="primary", expected_node=None, connection="consumer-source", **fields): + observed = self.probe(caller, operation, realm, connection=connection, + **({"expectedNodeId": self.node_id(expected_node)} if expected_node else {}), **fields) + self.record_matrix_cell(topology, mode, "direct", realm, "write" if operation == "dedup" else operation, + caller, observed, boundary=boundary, expected_node=expected_node) + return observed + + def matrix_cli(self, topology, mode, realm, operation, caller, *, boundary="primary", expected_node=None, + connection="consumer-source", observed=None, **fields): + evidence = self.cli(operation, caller, realm, **fields) + if observed is None: + observed = self.probe(caller, "capabilities", realm, connection=connection, + **({"expectedNodeId": self.node_id(expected_node)} if expected_node else {})) + self.record_matrix_cell(topology, mode, "mounted", realm, operation, caller, observed, + boundary=boundary, expected_node=expected_node, cli_evidence=evidence) + return evidence + + def prepare_positive_projection(self, node, realm): + """Materialize the exact positive target through the caller's authenticated Browse.""" + self.wait_connection_ready(node, realm) + return self.cli("browse", node, realm, recursive=True) + + def wait_connection_ready(self, caller, realm="raw", *, expected_node=None, require_fresh_sample=False): + end = time.monotonic() + self.remaining(30) + while True: + try: + timeout = max(1, min(10, int(end - time.monotonic()))) + observed = self.probe(caller, "capabilities", realm, expected_state="Ready", timeout=timeout, + **({"expectedNodeId": self.node_id(expected_node)} if expected_node else {})) + if require_fresh_sample: + observed = self.probe(caller, "read", realm, timeout=max(1, min(10, int(end - time.monotonic()))), + **({"expectedNodeId": self.node_id(expected_node)} if expected_node else {})) + return observed + except ScenarioError: + if time.monotonic() >= end: + raise ScenarioError("actual caller connection did not regain authenticated readiness") + time.sleep(min(.5, max(0, end - time.monotonic()))) + + def remaining(self, maximum=30): + remaining = self.deadline - time.monotonic() + if remaining <= 0: + raise ScenarioError("scenario deadline exceeded") + return min(remaining, maximum) + + def check(self, condition, name): + if not condition: + raise ScenarioError(name) + self.count += 1 + + def save(self, name, body): + text = json.dumps(body, indent=2, sort_keys=True) + rig.atomic_write_secret(self.folder / name, redact_text(text, self.secrets) + "\n") + + def process(self, argv, name, *, timeout=30): + result = run_process(argv, timeout=self.remaining(timeout), secrets=self.secrets, cwd=rig.ROOT, + environment=self.rig.environment) + self.save(name + ".process.json", asdict(result)) + return result + + def publish(self): + tools = {} + source_hash = rig.source_tree_hash() + for project, dll in ((rig.ROOT / "src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/ZB.MOM.WW.OtOpcUa.Client.CLI.csproj", self.cli_dll), + (rig.HERE / "probe/GrpcDataProbe.csproj", self.probe_dll)): + stamp_path = dll.parent / "published.json" + stamp = restricted_json(stamp_path) if stamp_path.exists() else {} + digest = hashlib.sha256(dll.read_bytes()).hexdigest() if dll.is_file() else None + if (digest and stamp.get("source_revision") == self.manifest.get("source_revision") + and stamp.get("source_tree_hash") == source_hash and stamp.get("sha256") == digest): + tools[dll.stem] = stamp + continue + dll.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + result = run_process(["dotnet", "publish", str(project), "-c", "Release", "-o", str(dll.parent)], + timeout=600, secrets=self.secrets, cwd=rig.ROOT, environment=self.rig.environment) + self.save("publish-" + dll.stem + ".json", asdict(result)) + if result.returncode != 0 or result.cancelled or result.timed_out or result.truncated or not dll.is_file(): + raise ScenarioError("publish did not produce the expected portable DLL") + stamp = {"dll": str(dll), "source_revision": self.manifest.get("source_revision"), + "source_tree_hash": source_hash, "sha256": hashlib.sha256(dll.read_bytes()).hexdigest()} + rig.atomic_write_secret(stamp_path, json.dumps(stamp)) + tools[dll.stem] = stamp + self.manifest["tools"] = tools + self.rig.save(self.manifest) + + def endpoint(self, node, kind="opcua"): + return self.manifest["endpoints"][node + "." + kind]["url"] + + def primary(self, pair): + nodes = [node for node in self.manifest["nodes"] if node.startswith(pair + "-")] + try: + active = rig.observe_active_endpoint({node: self.endpoint(node, "admin") for node in nodes}, + request=rig.http_request, timeout=self.remaining(10)) + except rig.RigError as error: + raise ScenarioError(str(error)) from None + self.check(active is not None, "pair must have one observed active node") + return active + + def wait_primary(self, pair, *, exclude=None): + while True: + try: + node = self.primary(pair) + if node != exclude: + return node + except (OSError, ScenarioError): + pass + time.sleep(self.remaining(0.5)) + + def wait_pair_topology(self, pair): + nodes = sorted(node for node in self.manifest["nodes"] if node.startswith(pair + "-")) + self.check(len(nodes) == 2, "exact fixture pair inventory") + expected = {self.node_id(node) for node in nodes} + deadline = time.monotonic() + self.remaining(45) + while time.monotonic() < deadline: + try: + observed = [self.probe(node, "topology", timeout=3) for node in nodes] + if all(state["self"].endswith("@" + self.node_id(node)) and + len(state["members"]) == 2 and + {f"{member['host']}:{member['port']}" for member in state["members"] + if member["status"] == "Up"} == expected + for node, state in zip(nodes, observed, strict=True)): + return + except (ScenarioError, OSError): + pass + time.sleep(min(.5, max(0, deadline - time.monotonic()))) + raise ScenarioError(f"{pair} pair did not rejoin with both expected Up members") + + def wait_warm_pair(self): + end = time.monotonic() + self.remaining(60) + while True: + states = {node: self.probe(node, "warm-state") for node in ("source-1", "source-2")} + try: + select_warm_pair(states) + return states + except ScenarioError: + if time.monotonic() >= end: + raise + time.sleep(min(.2, max(0, end - time.monotonic()))) + + def wait_warm_state(self, node, expected_role): + end = time.monotonic() + self.remaining(60) + while True: + observed = self.probe(node, "warm-state") + try: + return validate_startup_warm_state(observed, expected_node_id=self.node_id(node), expected_role=expected_role) + except ScenarioError: + if time.monotonic() >= end: + raise + time.sleep(min(.2, max(0, end - time.monotonic()))) + + def node_id(self, node): + return self.manifest["nodes"][node]["node_id"] + + def leaf(self, node, realm, *, counter=False): + resolved = self.manifest.get("resolved_nodes", self.initial_resolved).get(node, self.initial_resolved[node]) + if realm not in resolved.get("aliases", {}): + resolved = self.initial_resolved[node] + leaf = resolved["aliases"][realm] + uri = self.manifest["fixture"]["namespace_uris"][("mapped_" if node.startswith("consumer-") else "") + realm] + match = re.fullmatch(r"ns=(\d+);s=(.+)", leaf) + self.check(match is not None, "resolved string NodeId required") + identifier = match[2] + self.check(cli_gate.resolve_node_id(resolved["namespace_uris"], uri, identifier) == leaf, "NamespaceArray identity") + if counter: + return self.relative_node(node, realm, "counter") + return leaf + + def relative_node(self, node, realm, name, *, mapping_id=None): + leaf = self.leaf(node, realm) + ns, identifier = leaf.split(";s=", 1) + if identifier.startswith("p1."): + payload = identifier[3:] + decoded = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))) + origin = decoded["Origin"] + origin["Identifier"] = relative_origin_identifier(self.manifest["fixture"], realm, origin["Identifier"], name) + if mapping_id is not None: + decoded["MappingId"] = mapping_id + identifier = "p1." + base64.urlsafe_b64encode(json.dumps(decoded, separators=(",", ":")).encode()).decode().rstrip("=") + else: + identifier = relative_origin_identifier(self.manifest["fixture"], realm, identifier, name) + return ns + ";s=" + identifier + + def cli(self, command, node, realm="raw", *, value=42, denial=False, partner=None, duration=8, counter=False, recursive=False, target_override=None, + expected_nodes=None, absent_nodes=(), denial_statuses=None): + identity = self.active + "-" + command + "-" + uuid.uuid4().hex[:8] + summary = self.folder / (identity + ".summary.txt") + target = self.leaf(node, realm, counter=counter) if command in {"browse", "read", "write", "subscribe"} else None + if command == "browse": + target = self.relative_node(node, realm, "") + if target_override is not None: + target = target_override + argv = cli_gate.build_cli_argv(self.cli_dll, command, self.endpoint(node), self.key, node=target, value=value, + summary_file=summary, duration=duration, recursive=recursive, partner_endpoint=self.endpoint(partner) if partner else None, + max_age_ms=5000 if command == "read" else 0) + result = self.process(argv, identity, timeout=cli_timeout_seconds(command, duration)) + completed_at_utc = datetime.now(timezone.utc).isoformat() if command == "read" else None + # Cold mapped reads schedule bounded background work. Retry only the + # explicit pending status, preserving each attempt as separate evidence. + if command == "read" and not denial: + for attempt in range(3): + if (result.returncode != 0 or result.cancelled or result.timed_out or result.truncated + or "BadWaitingForInitialData" not in result.stdout): + break + time.sleep(self.remaining(.1)) + result = self.process(argv, identity + "-pending-" + str(attempt), timeout=15) + completed_at_utc = datetime.now(timezone.utc).isoformat() + if denial: + evidence = cli_gate.validate_denial(result, command=command, + expected_statuses=denial_statuses or ("BadUserAccessDenied", "BadNotWritable", "BadNodeIdUnknown", "BadNotConnected", "BadNoCommunication", "BadServerNotConnected", "BadOutOfService", "BadWaitingForInitialData", "BadInvalidState")) + elif command == "read": + evidence = cli_gate.validate_read(result, expected_node=target) + elif command == "write": + evidence = cli_gate.validate_write(result, expected_node=target) + elif command == "browse": + evidence = cli_gate.validate_browse(result, expected_nodes=expected_nodes or {self.leaf(node, realm)}) + self.check(not set(absent_nodes).intersection(evidence["nodes"]), "removed/denied children absent from browse") + elif command == "connect": + evidence = cli_gate.validate_connect(result, expected_endpoint=self.endpoint(node)) + elif command == "subscribe": + if not summary.is_file() or summary.is_symlink(): + raise ScenarioError("fresh CLI subscription summary missing") + evidence = cli_gate.validate_subscription(result, summary_text=summary.read_text(), expected_nodes={target}) + else: + cli_gate._process_ok(result) + self.check(cli_gate._field(result.stdout, "Application URI") == self.manifest["nodes"][node]["application_uri"], "UA application identity") + evidence = {"application_uri": cli_gate._field(result.stdout, "Application URI")} + if command == "read": + evidence["completed_at_utc"] = completed_at_utc + if not denial: + validate_fixture_read_timestamps(evidence, modbus_fixture=True) + self.count += 1 + self.save(identity + ".validated.json", evidence) + return evidence + + def probe(self, node, operation, realm="raw", *, connection="consumer-source", path=None, expected_state=None, timeout=None, **fields): + timeout = probe_timeout_seconds(operation, timeout) + identity = self.active + "-" + uuid.uuid4().hex + paths = self.manifest["fixture"]["origin_paths"] + command = {"id": identity, "connectionId": connection, "operation": operation, "realm": realm, + "originCluster": "SOURCE", "namespaceUri": self.manifest["fixture"]["namespace_uris"][realm], + "path": paths[realm] if path is None else path, "timeoutSeconds": min(timeout, int(self.remaining(120))), **fields} + if expected_state is not None: + command["expectedState"] = expected_state + folder = Path(self.manifest["node_probe_dirs"][node]) + if not folder.is_absolute() or folder.is_symlink() or not folder.is_dir() or folder.resolve() != (self.rig.folder / "probe" / node).resolve(): + raise ScenarioError("run-owned caller probe directory missing") + input_file, output_file = folder / (identity + ".request.json"), folder / (identity + ".result.json") + rig.atomic_write_secret(input_file, json.dumps(command)) + end = time.monotonic() + self.remaining(timeout + 5) + try: + while not output_file.exists(): + if time.monotonic() >= end: + raise ScenarioError("caller node file probe deadline") + time.sleep(min(0.1, end - time.monotonic())) + raw = restricted_json(output_file) + self.save(identity + ".probe.json", raw) + result = validate_probe_result(raw, expected_id=identity, expected_operation=operation) + if operation == "read" and expected_state in (None, "Good"): + validate_read_freshness(result["observations"], fields.get("maximumAgeMilliseconds", 5000)) + self.count += result["assertions"] + self.save(identity + ".probe.json", result) + return result["observations"] + finally: + input_file.unlink(missing_ok=True) + + def wire(self, scenario="D13", *, previous_key_state=None): + identity = self.active + "-wire" + output = self.folder / (identity + ".json") + arguments = ["dotnet", str(self.probe_dll), "--manifest", str(self.manifest_path), "--scenario", scenario, "--output", str(output)] + if previous_key_state is not None: + arguments.extend(["--previous-key-state", previous_key_state]) + result = self.process(arguments, identity, timeout=90) + self.check(result.returncode == 0 and not result.cancelled and not result.timed_out and not result.truncated, "wire process") + report = restricted_json(output) + self.check(report.get("passed") is True and bool(report.get("results")), "wire report") + for item in report["results"]: + validate_probe_result(item, expected_id=item["id"]) + self.count += item["assertions"] + + def live_cli_fault(self, consumer, fault_node=None, *, partner=None, require_gap=True, on_fault=None, recovery=None, duration=60, realm="raw", + outage_partner=None, post_lease_seconds=None, after_validated_recovery=None): + """Fault only after the real subscriber has attached and emitted Good.""" + identity = self.active + "-live-" + uuid.uuid4().hex[:8] + summary = self.folder / (identity + ".summary.txt") + target = self.leaf(consumer, realm) + producer = getattr(self, "_controlled_source", None) + self.check(isinstance(producer, ControlledFixtureSource), "fault subscriber has an exclusive controlled source") + if outage_partner is not None and (fault_node is None or outage_partner == fault_node or partner is not None): + raise ScenarioError("extended SOURCE outage requires distinct owned sources and one unchanged CLI endpoint") + if post_lease_seconds is not None and (type(post_lease_seconds) not in (int, float) + or not math.isfinite(post_lease_seconds) or not 0 < post_lease_seconds <= 65): + raise ScenarioError("post-lease progress wait must be finite and fixture bounded") + ready = threading.Event() + bad = threading.Event() + cancellation = threading.Event() + line_parser = NotificationLines() + notifications = [] + notification_lock = threading.Lock() + holder = [] + failures = [] + def observe(stream, chunk): + if stream == "stdout": + try: + parsed = line_parser.feed(chunk) + except (ScenarioError, cli_gate.CliGateError): + failures.append("invalid CLI notification line") + return + for notification in parsed: + if notification["node"] == target: + with notification_lock: + if len(notifications) >= 4096: + failures.append("CLI notification observation bound exceeded") + continue + notifications.append({"at": time.monotonic(), "value": notification["value"], "status": notification["status"]}) + if cli_gate.is_good_status(notification["status"]): + ready.set() + else: + bad.set() + def run(): + try: + holder.append(run_process(cli_gate.build_cli_argv(self.cli_dll, "subscribe", self.endpoint(consumer), self.key, + node=target, summary_file=summary, duration=duration, partner_endpoint=self.endpoint(partner) if partner else None), + timeout=self.remaining(duration + 20), secrets=self.secrets, cwd=rig.ROOT, environment=self.rig.environment, + observer=observe, cancellation_event=cancellation, cleanup_timeout=1.0)) + except BaseException as error: + failures.append(type(error).__name__) + worker = threading.Thread(target=run, daemon=True) + started_at_utc = datetime.now(timezone.utc).isoformat() + started_at_monotonic = time.monotonic() + worker.start() + fault_at = effective_at = withdrawal_at = reauthorization_at = reauthorization_completed_at = None + sentinel = None + source_outage = post_lease = None + try: + self.check(ready.wait(self.remaining(15)), "real CLI attachment and Good update before fault") + bad.clear() + action_started = time.monotonic() + def wait_for_non_good(*, stop_requested_at, stop_completed_at): + end = stop_requested_at + self.remaining(45) + while True: + with notification_lock: + try: + return validate_source_outage_notification(notifications, + stop_requested_at=stop_requested_at, stop_completed_at=stop_completed_at) + except ScenarioError: + pass + remaining = end - time.monotonic() + if remaining <= 0 or not worker.is_alive() or failures: + raise ScenarioError("extended SOURCE outage did not produce an actual CLI non-Good update within 45 seconds") + bad.wait(min(.1, remaining)); bad.clear() + fault_scope = (self.extended_source_outage(fault_node, outage_partner, wait_for_non_good=wait_for_non_good) + if outage_partner is not None else self.stopped(fault_node) if fault_node else nullcontext()) + with fault_scope as source_outage: + fault_at = action_started + effective_at = time.monotonic() + if source_outage is not None: + with notification_lock: + non_good = next(row for row in notifications if row["at"] == source_outage["actual_non_good_at"]) + source_outage["actual_non_good_status"] = non_good["status"] + source_outage["actual_bad_at"] = non_good["at"] if non_good["status"].startswith("Bad") else None + if on_fault is not None: + on_fault() + if recovery is not None: + self.check(bad.wait(self.remaining(25)), "live stream authorization/expiry gate withdrew values") + with notification_lock: + withdrawal_at = next((row["at"] for row in notifications if row["at"] >= action_started and row["status"].startswith("Bad")), None) + self.check(withdrawal_at is not None, "observed authorization withdrawal boundary") + time.sleep(self.remaining(2)) + reauthorization_at = time.monotonic() + recovery() + reauthorization_completed_at = time.monotonic() + # The old consumer/source remains stopped throughout this + # challenge. No queued pre-fault output can contain this value. + with producer.sentinel() as sentinel: + end = time.monotonic() + self.remaining(20) + while True: + with notification_lock: + observed_at = next((row["at"] for row in notifications + if row["at"] >= sentinel["produced_at"] and row["value"] == sentinel["value"] + and cli_gate.is_good_status(row["status"])), None) + if observed_at is not None: + sentinel["observed_at"] = observed_at + break + if time.monotonic() >= end or not worker.is_alive() or failures: + raise ScenarioError("live CLI did not observe the held post-fault recovery sentinel") + time.sleep(min(.1, max(0, end - time.monotonic()))) + if post_lease_seconds is not None: + resumed_at = time.monotonic() + time.sleep(self.remaining(post_lease_seconds)) + waited = time.monotonic() - resumed_at + self.check(waited >= post_lease_seconds, "advertised metadata lease plus margin actually elapsed") + with producer.lock: + floor = producer.current + wraps = producer.ordinary_wrap_count + boundary = time.monotonic() + post_lease = {"resumed_after_sentinel_at": resumed_at, "wait_seconds": post_lease_seconds, + "actual_wait_seconds": waited, "boundary_at": boundary, "ordinary_floor": floor, + "ordinary_source_initial_value": producer.initial_value, "ordinary_wrap_count": wraps} + self.check(wraps == 0, "post-lease numeric floor requires a nonwrapping ordinary producer sequence") + end = boundary + self.remaining(10) + while True: + with notification_lock: + snapshot = list(notifications) + with producer.lock: + observed_wraps = producer.ordinary_wrap_count + post_lease["ordinary_wrap_count_at_observation"] = observed_wraps + self.check(observed_wraps == 0, "ordinary producer did not wrap during the post-lease progress observation") + try: + post_lease.update(validate_post_lease_progress(snapshot, boundary_at=boundary, + ordinary_floor=floor, ordinary_wrap_count=observed_wraps)) + break + except ScenarioError: + if time.monotonic() >= end or not worker.is_alive() or failures: + raise + time.sleep(min(.1, max(0, end - time.monotonic()))) + self.save(identity + ".post-lease-progress.json", post_lease) + worker.join(timeout=self.remaining(duration + 10)) + self.check(not worker.is_alive() and not failures and len(holder) == 1, "bounded fault subscription completion") + self.save(identity + ".process.json", asdict(holder[0])) + self.check(summary.is_file() and not summary.is_symlink(), "fresh recovery summary") + evidence = cli_gate.validate_recovery_subscription(holder[0], summary_text=summary.read_text(), + expected_node=target, require_gap=require_gap, require_held_session=outage_partner is not None) + evidence["temporal"] = validate_fault_notifications(notifications, fault_at=fault_at, + effective_at=effective_at, require_gap=require_gap, required_sentinel=sentinel, + withdrawal_at=withdrawal_at, reauthorization_at=reauthorization_at, + reauthorization_completed_at=reauthorization_completed_at) + evidence["consumer_endpoint"] = self.endpoint(consumer) + evidence["partner_endpoint"] = self.endpoint(partner) if partner else None + evidence["fault_node"] = fault_node + if source_outage is not None: + evidence["extended_source_outage"] = source_outage + if post_lease is not None: + evidence["post_lease_progress"] = post_lease + self.save(identity + ".validated.json", evidence) + if after_validated_recovery is not None: + after_validated_recovery() + self.count += 1 + return evidence + finally: + original_failure = sys.exc_info()[1] + cancellation_requested = worker.is_alive() + if cancellation_requested: + cancellation.set() + cleanup_started = time.monotonic() + cleanup_deadline = cleanup_started + 8 + cleanup_errors = [] + try: + while worker.is_alive() and time.monotonic() < cleanup_deadline: + worker.join(timeout=min(.25, max(0, cleanup_deadline - time.monotonic()))) + except BaseException as error: + cleanup_errors.append(type(error).__name__) + worker_collected = not worker.is_alive() + if holder: + self.save(identity + ".process.json", asdict(holder[0])) + with notification_lock: + selected = notifications if len(notifications) <= 512 else notifications[:256] + notifications[-256:] + bounded_notifications = [{"at": row["at"], + "value": redact_text(str(row["value"]), self.secrets)[:256], + "status": redact_text(str(row["status"]), self.secrets)[:128]} for row in selected] + notification_count = len(notifications) + self.save(identity + ".fault-observation.json", { + "started_at_utc": started_at_utc, "completed_at_utc": datetime.now(timezone.utc).isoformat(), + "started_at_monotonic": started_at_monotonic, "completed_at_monotonic": time.monotonic(), + "fault_at": fault_at, "fault_effective_at": effective_at, "withdrawal_at": withdrawal_at, + "reauthorization_at": reauthorization_at, "reauthorization_completed_at": reauthorization_completed_at, + "sentinel": sentinel, "notifications": bounded_notifications, "notification_count": notification_count, + "notifications_truncated": notification_count > len(bounded_notifications), "failures": failures[:32], + "worker_collected": worker_collected, "process_collected": len(holder) == 1, + "cancellation_requested": cancellation_requested, "cleanup_budget_seconds": 8, + "cleanup_duration_seconds": time.monotonic() - cleanup_started, "cleanup_errors": cleanup_errors, + "original_failure_type": type(original_failure).__name__ if original_failure is not None else None, + "consumer_endpoint": self.endpoint(consumer), "partner_endpoint": self.endpoint(partner) if partner else None, + "fault_node": fault_node, "extended_source_outage": source_outage, "post_lease_progress": post_lease}) + if original_failure is None and (not worker_collected or cleanup_errors): + raise ScenarioError("owned subscriber could not be collected after cancellation") + + def device(self, action=None, **fields): + base = self.manifest["endpoints"]["device.control"]["url"] + status, _, body = rig.http_request("POST" if action else "GET", base + ("/control" if action else "/state"), + headers={}, json_body={"action": action, **fields} if action else None, timeout=self.remaining(5)) + self.check(status == 200 and isinstance(body, dict) and type(body.get("effect_total")) is int, "device ledger response") + return body + + def wait_readback(self, node, realm, expected): + end = time.monotonic() + self.remaining(20) + while True: + result = self.cli("read", node, realm) + if result["value"] == expected: + self.check(True, "eventual origin cached readback") + return result + if time.monotonic() >= end: + raise ScenarioError("origin did not converge to the accepted fixture write") + time.sleep(min(0.2, end - time.monotonic())) + + @contextmanager + def changing(self): + done = threading.Event() + failures = [] + initial = self.device()["writable"]["20"] + self.check(getattr(self, "_controlled_source", None) is None, "one controlled fixture producer at a time") + if not hasattr(self, "_fixture_used_values"): + self._fixture_used_values = set() + producer = ControlledFixtureSource(self.device, initial, self._fixture_used_values) + self._controlled_source = producer + def worker(): + try: + while not done.wait(0.5): + producer.tick() + except BaseException as error: + failures.append(type(error).__name__) + thread = threading.Thread(target=worker, daemon=True) + thread.start() + try: + yield + self.check(not failures, "controlled source changes") + finally: + done.set() + thread.join(timeout=6) + self._controlled_source = None + self.check(not thread.is_alive(), "controlled fixture producer retired") + self.device("set", address=20, value=initial) + + def mutate(self, **mutation): + key_only = is_key_only_mutation(mutation) + revision_receipt = self.rig.folder / "seed" / "mutation-revisions.json" + if key_only: + if revision_receipt.is_symlink(): + raise ScenarioError("credential revision receipt must be an owned regular file") + revision_receipt.unlink(missing_ok=True) + rig.atomic_write_secret(self.rig.folder / "seed" / "mutation.json", json.dumps(mutation)) + self.rig.seed_helper("mutate") + if key_only: + receipt = validate_key_only_revision_receipt(restricted_json(revision_receipt), action=mutation["key_action"]) + self.save(self.active + "-credential-revisions-" + uuid.uuid4().hex[:8] + ".json", receipt) + self.manifest = self.rig.deploy(timeout=self.remaining(180), require_catalog=False) + for path in self.manifest["credentials"]["data_key_files"].values(): + secret = Path(path).read_text().strip() + if secret and secret not in self.secrets: + self.secrets.append(secret) + self.timeline.append({"event": "deploy", "revision": self.manifest["deployment"]["revision_hash"], "at": time.monotonic()}) + + def _owned_source_process(self, node): + """Read only the recorded owned container's process identity; retain no environment payload.""" + if not isinstance(node, str) or not node.startswith("source-") or node not in self.manifest["nodes"]: + raise ScenarioError("SOURCE pause target is outside the owned fixture") + required = {rig.RUN_LABEL: self.manifest["run_id"], rig.PROJECT_LABEL: self.manifest["project"], + "com.docker.compose.service": node} + def selected(rows): + return [row for row in rows if row.get("kind") == "container" + and row.get("labels", {}).get("com.docker.compose.service") == node] + recorded = selected(self.manifest.get("resources", [])) + observed = selected(self.rig.inspect_resources()) + if (len(recorded) != 1 or len(observed) != 1 or recorded[0]["id"] != observed[0]["id"] + or any(row.get("labels", {}).get(key) != value for row in (*recorded, *observed) + for key, value in required.items())): + raise ScenarioError("SOURCE pause ownership or recorded container identity changed") + identity = recorded[0]["id"] + try: + rows = json.loads(rig.run_command([*self.rig.docker, "container", "inspect", identity], timeout=10)) + if not isinstance(rows, list) or len(rows) != 1: + raise ValueError() + row = rows[0] + state, labels = row["State"], row["Config"]["Labels"] + if (row["Id"] != identity or any(labels.get(key) != value for key, value in required.items()) + or state.get("Running") is not True or type(state.get("Pid")) is not int or state["Pid"] <= 0 + or not isinstance(state.get("StartedAt"), str) or not state["StartedAt"] + or type(state.get("Paused")) is not bool): + raise ValueError() + return {"node": node, "container_id": identity, "process_id": state["Pid"], + "started_at": state["StartedAt"], "paused": state["Paused"]} + except (ValueError, KeyError, TypeError, AttributeError): + raise ScenarioError("SOURCE pause process inspection is invalid") from None + + @contextmanager + def paused(self, node): + before = self._owned_source_process(node) + if before["paused"]: + raise ScenarioError("SOURCE partner was already paused before this fault") + receipt = {"node": node, "container_id": before["container_id"], "process_id_before": before["process_id"], + "process_start_before": before["started_at"], "process_identity_kind": "owned Host container init PID and StartedAt", + "paused_at": None, "resumed_at": None, "cleanup_succeeded": False} + def same_process(state): + if (state["container_id"] != before["container_id"] or state["process_id"] != before["process_id"] + or state["started_at"] != before["started_at"]): + raise ScenarioError("paused SOURCE partner process identity changed") + def resume(): + current = self._owned_source_process(node) + same_process(current) + if current["paused"]: + self.rig.compose("unpause", node, timeout=30) + receipt["resumed_at"] = time.monotonic() + self.timeline.append({"event": "unpause", "nodes": [node], "at": receipt["resumed_at"]}) + after = self._owned_source_process(node) + receipt.update(process_id_after=after["process_id"], process_start_after=after["started_at"]) + same_process(after) + if after["paused"]: + raise ScenarioError("owned SOURCE partner remained paused") + receipt["cleanup_succeeded"] = True + return dict(receipt) + resume.receipt = receipt + try: + self.rig.compose("pause", node, timeout=self.remaining(20)) + paused = self._owned_source_process(node) + same_process(paused) + if not paused["paused"]: + raise ScenarioError("owned SOURCE partner did not pause") + receipt["paused_at"] = time.monotonic() + self.timeline.append({"event": "pause", "nodes": [node], "at": receipt["paused_at"]}) + yield resume + finally: + original = sys.exc_info()[1] + cleanup_error = None + try: + resume() + except BaseException as error: + cleanup_error = type(error).__name__ + receipt["cleanup_succeeded"] = False + receipt["cleanup_error"] = cleanup_error + try: + self.save(self.active + "-" + node + "-pause-" + uuid.uuid4().hex[:8] + ".json", receipt) + except BaseException as error: + cleanup_error = cleanup_error or type(error).__name__ + if cleanup_error is not None and original is None: + raise ScenarioError("owned SOURCE partner pause cleanup failed") + + @contextmanager + def extended_source_outage(self, primary, partner, *, wait_for_non_good): + """Hold both sources unavailable until the actual CLI observes the outage.""" + with self.paused(partner) as resume: + stop_requested_at = time.monotonic() + self.timeline.append({"event": "source-outage-stop-request", "nodes": [primary], "at": stop_requested_at}) + with self.stopped(primary): + stop_completed_at = time.monotonic() + self.timeline.append({"event": "source-outage-stop-complete", "nodes": [primary], "at": stop_completed_at}) + non_good_at = wait_for_non_good(stop_requested_at=stop_requested_at, stop_completed_at=stop_completed_at) + if (any(type(value) not in (int, float) or not math.isfinite(value) + for value in (stop_requested_at, stop_completed_at, non_good_at)) + or not stop_requested_at <= stop_completed_at + or not stop_requested_at <= non_good_at <= stop_requested_at + 45): + raise ScenarioError("SOURCE outage observation is outside its actual shutdown boundaries") + resumed = resume() + yield {"setup": "partner paused and old primary stopped before recovery", + "primary": primary, "partner": partner, "primary_stop_requested_at": stop_requested_at, + "both_sources_unavailable_at": stop_completed_at, "actual_non_good_at": non_good_at, + "partner_pause": resumed} + + @contextmanager + def stopped(self, *nodes): + if not nodes or any(node not in self.manifest["nodes"] for node in nodes): + raise ScenarioError("stop target is outside recorded nodes") + # Re-inspect both ownership labels before every fault mutation. + resources = self.rig.inspect_resources() + self.check(all(row["labels"].get(rig.RUN_LABEL) == self.manifest["run_id"] for row in resources), "fault resource ownership") + try: + self.rig.compose("stop", "--timeout", "5", *nodes, timeout=self.remaining(20)) + self.timeline.append({"event": "stop", "nodes": nodes, "at": time.monotonic()}) + yield + finally: + original = sys.exc_info()[1] + def failure_type(error): + return {RuntimeError: "RuntimeError", ValueError: "ValueError", OSError: "OSError", + TimeoutError: "TimeoutError", ScenarioError: "ScenarioError", rig.RigError: "RigError"}.get(type(error), "OtherError") + cleanup_errors = [] + try: + self.rig.compose("start", *nodes, timeout=30) + self.timeline.append({"event": "start", "nodes": nodes, "at": time.monotonic()}) + except BaseException as error: + cleanup_errors.append({"operation": "start", "type": failure_type(error)}) + # Refresh remains an independent cleanup attempt even if start fails. + try: + self.manifest = self.rig.refresh_endpoints(nodes) + except BaseException as error: + cleanup_errors.append({"operation": "refresh", "type": failure_type(error)}) + receipt = {"event": "stop-cleanup", "nodes": nodes, "at": time.monotonic(), + "original_error": failure_type(original) if original is not None else None, + "cleanup_errors": cleanup_errors} + self.timeline.append(receipt) + try: + self.save(self.active + "-stop-cleanup-" + uuid.uuid4().hex[:8] + ".json", receipt) + except BaseException as error: + cleanup_errors.append({"operation": "record", "type": failure_type(error)}) + if cleanup_errors and original is None: + raise ScenarioError("owned stopped-node cleanup failed") + + def baseline(self, *, maintenance_changed=False): + # Restoration deliberately uses the rig's independent bounded startup, + # deployment and catalog deadlines, even after this scenario expires. + self.rig.seed_helper("restore") + self.rig.restore_security() + if maintenance_changed: + # The coordinator reads fresh eligible rows while mesh dispatch uses + # cached contacts. Let CONTROL refresh after the restore commits, + # then require every real acknowledgement in a single deployment. + time.sleep(MAINTENANCE_CONTACT_SETTLE_SECONDS) + self.timeline.append({"event": "maintenance-contact-settle", "at": time.monotonic(), + "seconds": MAINTENANCE_CONTACT_SETTLE_SECONDS}) + self.manifest = self.rig.deploy(timeout=180) + + def run(self, selection): + chosen = SCENARIOS if selection == "all" else (selection,) + if any(item not in SCENARIOS for item in chosen): + raise ScenarioError("unknown required scenario") + self.publish() + self.rig.seed_helper("snapshot") + self.matrix_cells = [] + rows = [] + for name in chosen: + self.active, self.count = name, 0 + catalog = getattr(self, "catalog", {"default_timeout_seconds": 480, "timeouts": {}}) + self.deadline = time.monotonic() + catalog["timeouts"].get(name, catalog["default_timeout_seconds"]) + started = time.monotonic() + error = None + restored = False + try: + getattr(self, "scenario_" + name)() + self.check(self.count > 0, "nonempty scenario") + validate_matrix_cells([cell for cell in self.matrix_cells if cell["scenario"] == name], (name,)) + except Exception as failure: + error = type(failure).__name__ + (": " + str(failure) if isinstance(failure, (ScenarioError, cli_gate.CliGateError)) else "") + finally: + try: + self.baseline(maintenance_changed=name == "D07") + restored = True + except Exception as failure: + error = (error + "; " if error else "") + "restoration " + type(failure).__name__ + row = {"id": name, "passed": error is None, "assertions": self.count, "restored": restored, + "duration_seconds": time.monotonic() - started, "failure": error, + "cells": [cell for cell in self.matrix_cells if cell["scenario"] == name]} + rows.append(row) + self.save("scenario-results.json", {"rows": rows, "complete": len(rows) == len(chosen)}) + report = {"schema_version": 1, "run_id": self.manifest["run_id"], "passed": validate_scenario_rows(rows, chosen), "rows": rows} + self.deadline = time.monotonic() + 30 + self.save("scenario-results.json", report) + self.save("fault-timeline.json", self.timeline) + self.save("device-ledger.json", self.device()) + files = sorted(path for path in self.folder.iterdir() if path.is_file() and path.name != "index.json") + self.save("index.json", {"source_revision": self.manifest.get("source_revision"), "files": [ + {"path": path.name, "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), "bytes": path.stat().st_size} for path in files]}) + return report + + def scenario_D01(self): + all_members = set() + containers = [row for row in self.rig.inspect_resources() if row["kind"] == "container" + and row["labels"].get("com.docker.compose.service") in self.manifest["nodes"]] + self.check(len(containers) == 6 and len({row["id"] for row in containers}) == 6, "six distinct host processes") + for node in self.manifest["nodes"]: + result = self.probe(node, "topology") + self.check(result.get("artifactRevision") == self.manifest["deployment"]["revision_hash"], "node cached applied revision") + expected = {peer for peer in self.manifest["nodes"] if peer.split("-")[0] == node.split("-")[0]} + observed = {member["host"] for member in result["members"]} + self.check(observed == expected and observed.isdisjoint(all_members - expected), "independent pair members") + all_members.update(observed) + self.cli("redundancy", node) + deployment = self.manifest["deployment"] + self.check(len(deployment["nodes"]) == 6, "six applied revisions") + self.check(bool(deployment["revision_hash"]), "artifact revision present") + for pair in ("control", "source", "consumer"): + self.primary(pair) + self.probe(self.primary("consumer"), "capabilities", expected_state="Ready") + + def direct_suite(self, caller, connection, *, write=True, expected_node=None, topology="cross-cluster", mode="Cluster"): + for realm in ("raw", "uns"): + parent = fixture_browse_root(self.manifest["fixture"], realm) + for operation in ("capabilities", "browse", "metadata", "read"): + self.matrix_probe(topology, mode, realm, operation, caller, connection=connection, + path=parent if operation == "browse" else None, expected_node=expected_node) + with self.changing(): + self.matrix_probe(topology, mode, realm, "subscribe", caller, connection=connection, expected_node=expected_node) + if write: + before = self.device()["effect_total"] + self.matrix_probe(topology, mode, realm, "dedup", caller, connection=connection, value=42, expected_node=expected_node) + after = self.device() + self.check(after["effect_total"] == before + 1 and after["writable"]["20"] == 42, "one remote effect for same operation ID") + + def scenario_D01a(self): + # Removing projection is essential: success cannot be caused by an anchor. + self.mutate(mapping_enabled=False) + caller = self.primary("consumer") + for realm in ("raw", "uns"): + self.cli("read", caller, realm, denial=True) + self.direct_suite(caller, "consumer-source") + primary = self.primary("source") + self.mutate(target_mode="Node", target_node_id=self.node_id(primary), consistency="Primary") + self.direct_suite(caller, "consumer-source", expected_node=primary, mode="Node") + self.same_cluster(direct_only=True) + + def same_cluster(self, *, direct_only=False): + target = self.primary("source") + caller = next(node for node in self.manifest["nodes"] if node.startswith("source-") and node != target) + spec = {"DataConnectionId": "source-source", "ClusterId": "SOURCE", "Enabled": True, + "ConsumerNodeIds": [self.node_id(caller)], "TargetMode": 1, "ExpectedClusterId": "SOURCE", "ExpectedNodeId": self.node_id(target), + "Consistency": 1, "EligibleTargetNodeIds": [], "Endpoints": ["https://" + target + ":4057"], + "SecretReference": "secret:data/source-source", "SecretScopeClusterId": "SOURCE", "AllowedOperations": OPERATIONS, "Revision": 1} + self.mutate(upsert_connection=spec, connection_id="source-source") + self.direct_suite(caller, "source-source", expected_node=target, topology="same-cluster", mode="Node") + self.probe(target, "capabilities", connection="source-source", expected_state="Unavailable") + if not direct_only: + baseline = restricted_json(self.rig.folder / "seed" / "baseline.json") + for mapping in baseline["Mappings"]: + mapping = dict(mapping) + realm = "raw" if mapping["Realm"] == 1 else "uns" + mapping.update(RemoteNamespaceMappingId="same-" + realm, ClusterId="SOURCE", DataConnectionId="source-source", + ConsumerNodeIds=[self.node_id(caller)], LocalParentId="SOURCE") + self.mutate(upsert_mapping=mapping, connection_id="source-source") + # NamespaceArray was observed for every node at setup; scoped + # mappings do not change those registered namespace URIs. Materialize + # the exact caller branch instead of globally traversing unrelated + # cold projections through the seeder. + # A is standby while B is the target primary: runtime positive above, + # UA local-primary enforcement remains a negative on the mounted view. + for realm in ("raw", "uns"): + template_node = next(node for node in self.initial_resolved if node.startswith("consumer-")) + projected = self.relative_node(template_node, realm, "scalar", mapping_id="same-" + realm) + identifier = projected.split(";s=", 1)[1] + resolved = self.manifest["resolved_nodes"][caller] + uri = self.manifest["fixture"]["namespace_uris"]["mapped_" + realm] + mapped = cli_gate.resolve_node_id(resolved["namespace_uris"], uri, identifier) + root = self.relative_node(template_node, realm, "", mapping_id="same-" + realm) + root = cli_gate.resolve_node_id(resolved["namespace_uris"], uri, root.split(";s=", 1)[1]) + self.cli("browse", caller, realm, recursive=True, target_override=root, expected_nodes={mapped}) + self.matrix_cli("same-cluster", "Node", realm, "read", caller, target_override=mapped, + expected_node=target, connection="source-source") + before = self.device()["effect_total"] + self.matrix_cli("same-cluster", "Node", realm, "write", caller, denial=True, target_override=mapped, + denial_statuses={"BadInvalidState"}, boundary="local-standby", expected_node=target, connection="source-source") + self.check(self.device()["effect_total"] == before, "local standby gate rejected before device dispatch") + # Reverse the pinned route: the previous target remains primary, + # while the previous caller is the explicit ReadyReplica target. + reverse = dict(spec, ConsumerNodeIds=[self.node_id(target)], ExpectedNodeId=self.node_id(caller), + Endpoints=["https://" + caller + ":4057"], Consistency=2) + self.mutate(upsert_connection=reverse, connection_id="source-source") + for realm in ("raw", "uns"): + self.matrix_probe("same-cluster", "Node", realm, "read", target, connection="source-source", + boundary="secondary", expected_node=caller) + before = self.device()["effect_total"] + self.matrix_probe("same-cluster", "Node", realm, "write", target, connection="source-source", + boundary="secondary", expected_node=caller, expected_state="RejectedBeforeDispatch") + self.check(self.device()["effect_total"] == before, "pinned same-cluster secondary write has no effect") + + def scenario_D02(self): + self.same_cluster() + + def scenario_D03(self): + for mode in ("Cluster", "Node"): + target = self.primary("source") + self.mutate(target_mode=mode, target_node_id=self.node_id(target), consistency="Primary") + consumer = self.primary("consumer") + for realm in ("raw", "uns"): + self.wait_connection_ready(consumer, realm, expected_node=target if mode == "Node" else None) + self.matrix_cli("cross-cluster", mode, realm, "browse", consumer, recursive=True, + expected_node=target if mode == "Node" else None) + origin = self.cli("read", target, realm) + mapped = self.matrix_cli("cross-cluster", mode, realm, "read", consumer, + expected_node=target if mode == "Node" else None) + comparison = validate_fixture_read_pair(origin, mapped, modbus_fixture=True) + comparison["controlled_boundary_companions"] = D03_TIMESTAMP_BOUNDARY_COMPANIONS + self.check(origin["value"] == mapped["value"], "origin and mapped fixture values agree") + self.save(f"D03-{mode}-{realm}-read-timestamps.json", comparison) + self.matrix_probe("cross-cluster", mode, realm, "metadata", consumer, + expected_node=target if mode == "Node" else None) + self.check(self.leaf(consumer, "raw") != self.leaf(consumer, "uns"), "realm aliases remain distinct") + baseline = restricted_json(self.rig.folder / "seed" / "baseline.json") + tag = dict(next(row for row in baseline["Tags"] if row["TagId"] == "source-array2")) + tag.update(TagId="source-new-child", Name="new-child") + reference = dict(next(row for row in baseline["References"] if row["TagId"] == "source-array2")) + reference.update(UnsTagReferenceId="ref-source-new-child", TagId="source-new-child") + self.mutate(upsert_tag=tag, upsert_reference=reference) + for realm in ("raw", "uns"): + self.cli("browse", consumer, realm, recursive=True, + expected_nodes={self.relative_node(consumer, realm, "new-child"), self.relative_node(consumer, realm, "array2")}) + self.mutate(rename_tag={"tag_id": "source-new-child", "name": "renamed-child"}) + for realm in ("raw", "uns"): + self.cli("browse", consumer, realm, recursive=True, + expected_nodes={self.relative_node(consumer, realm, "renamed-child")}, absent_nodes={self.relative_node(consumer, realm, "new-child")}) + self.mutate(remove_tag_id="source-new-child") + for realm in ("raw", "uns"): + self.cli("browse", consumer, realm, recursive=True, absent_nodes={self.relative_node(consumer, realm, "renamed-child")}) + self.baseline() + + def scenario_D04(self): + for mode in ("Cluster", "Node"): + target = self.primary("source") + self.mutate(target_mode=mode, target_node_id=self.node_id(target), consistency="Primary") + consumer = self.primary("consumer") + for realm in ("raw", "uns"): + self.prepare_positive_projection(consumer, realm) + with self.changing(): + self.matrix_cli("cross-cluster", mode, realm, "subscribe", consumer, + expected_node=target if mode == "Node" else None) + self.prepare_positive_projection(consumer, realm) + before = self.device()["effect_total"] + self.matrix_cli("cross-cluster", mode, realm, "write", consumer, value=42, + expected_node=target if mode == "Node" else None) + self.check(self.device()["effect_total"] == before + 1, "CLI write exactly one device effect") + self.wait_readback(self.primary("source"), realm, "42") + self.check(self.device()["writable"]["20"] == 42, "simulator readback") + + def scenario_D05(self): + for mode in ("Node", "Cluster"): + self.mutate(target_mode=mode, target_node_id=self.node_id(self.primary("source")), consistency="Primary") + node = self.primary("consumer") + for realm in ("raw", "uns"): + parent = fixture_browse_root(self.manifest["fixture"], realm) + branch = self.probe(node, "browse", realm, path=parent) + self.check(branch["complete"] is False and bool(branch["continuation"]), "bounded nonempty continuation page") + cursor = branch["continuation"] + first = self.probe(node, "continuation", realm, path=parent, continuation=cursor, expected_state="Good") + repeated = self.probe(node, "continuation", realm, path=parent, continuation=cursor, expected_state="Good") + # Origin HMAC cursors are stateless. The mounted SDK's separate + # continuation store consumes its cursor only on a committed page. + self.check(isinstance(first.get("items"), list) and isinstance(repeated.get("items"), list) + and len(first["items"]) <= 1 and repeated["items"] == first["items"], + "origin cursor replay preserves the same ordered bounded metadata page") + self.check(type(first.get("complete")) is bool and repeated.get("complete") is first["complete"] + and isinstance(first.get("serving"), dict) + and all(repeated.get(field) == first.get(field) + for field in ("serving", "limits", "operations", "compact", "readiness")), + "origin cursor replay preserves completion and full serving capability era") + fresh = self.probe(node, "browse", realm, path=parent) + self.check(bool(fresh["continuation"]), "unconsumed cursor before revision change") + origin_before = fresh["serving"] + self.mutate(allowed_operations=OPERATIONS) + origin_after = self.probe(node, "capabilities", realm, expected_state="Ready")["serving"] + self.check(origin_before != origin_after, "origin serving catalog or authority actually changed before token invalidation") + invalid = self.probe(node, "continuation", realm, path=parent, continuation=fresh["continuation"], expected_state="InvalidContinuation") + self.check(invalid.get("items") == [], "invalid origin continuation leaks no metadata rows") + self.save(f"D05-{mode}-{realm}-origin-continuation.json", { + "origin_before": origin_before, "origin_after": origin_after, + "first_page": {"items": first["items"], "complete": first["complete"]}, + "replay_page": {"items": repeated["items"], "complete": repeated["complete"]}, + "invalidated_items": invalid["items"], "origin_same_owner_replay": "Good"}) + + def scenario_D06(self): + node = self.primary("consumer") + self.mutate(write_through=False, allowed_operations=OPERATIONS & ~8) + for realm in ("raw", "uns"): + self.prepare_positive_projection(node, realm) + self.cli("read", node, realm) + self.cli("write", node, realm, denial=True) + quiet_leases = [] + for realm in ("raw", "uns"): + parent = fixture_browse_root(self.manifest["fixture"], realm) + observed = self.probe(node, "browse", realm, path=parent) + quiet_leases.append(metadata_lease_seconds(observed.get("lease"))) + self.cli("browse", node, realm, recursive=True) + quiet_started = time.monotonic() + quiet_bound = max(quiet_leases) + # No browse/read/metadata traffic renews the quiet projected lease here. + time.sleep(self.remaining(quiet_bound + .5)) + self.check(time.monotonic() - quiet_started >= quiet_bound, "quiet metadata lease elapsed") + for realm in ("raw", "uns"): + self.cli("read", node, realm, denial=True, + denial_statuses={"BadUserAccessDenied", "BadNodeIdUnknown", "BadNoCommunication"}) + self.cli("browse", node, realm, recursive=True) + self.cli("read", node, realm) + self.save("D06-quiet-lease.json", {"lease_seconds": quiet_leases, + "elapsed_seconds": time.monotonic() - quiet_started, "expired_both_realms": True}) + baseline = restricted_json(self.rig.folder / "seed" / "baseline.json") + export_scopes = [] + for export in baseline["Exports"]: + # Projection admission needs parent Metadata. This inherited grant + # includes descendant Metadata, while scalar-only Browse filters siblings. + parent_metadata = dict(export, AllowedOperations=2) + self.mutate(upsert_export=parent_metadata) + raw = export["Realm"] == 1 + scalar = dict(export, DataExportId=export["DataExportId"] + "-scalar", AllowedOperations=OPERATIONS, + RootKind="RawTag" if raw else "UnsTagReference", RootEntityId="source-scalar" if raw else "ref-scalar") + self.mutate(upsert_export=scalar) + export_scopes.append({"realm": "raw" if raw else "uns", "metadata_root": parent_metadata, + "scalar_root": scalar}) + for realm in ("raw", "uns"): + self.prepare_positive_projection(node, realm) + self.cli("browse", node, realm, recursive=True, absent_nodes={self.relative_node(node, realm, "counter")}) + self.cli("read", node, realm) + counter = self.manifest["fixture"]["origin_paths"][realm].rsplit("/", 1)[0] + "/counter" + self.probe(node, "read", realm, path=counter, expected_state="Denied") + effects = self.device()["effect_total"] + self.probe(node, "write", realm, path=counter, expected_state="RejectedBeforeDispatch") + self.check(self.device()["effect_total"] == effects, "out-of-scope counter write has zero physical effects") + self.save("D06-export-scopes.json", {"grants": export_scopes, + "metadata_scope": "Parent Metadata permission is inherited by descendants; it is not an exact-parent-only grant.", + "browse_scope": "Full scalar-leaf operations grant allows ancestor discovery and excludes counter from complete browse."}) + self.baseline() + target = self.primary("source") + # Pin the authenticated Primary so a secondary selection failure cannot + # replace the explicit origin permission denial in the exception chain. + self.mutate(export_allowed_operations=1 | 2, target_mode="Node", target_node_id=self.node_id(target), + consistency="Primary", connection_allowed_operations=OPERATIONS) + for realm in ("raw", "uns"): + self.wait_connection_ready(node, realm, expected_node=target) + self.probe(node, "read", realm, expected_state="Denied", expectedNodeId=self.node_id(target), expectedRole="Primary") + # The failed Read sets discovery backoff; authenticate readiness + # again before the independent actual Write rejection assertion. + self.wait_connection_ready(node, realm, expected_node=target) + effects = self.device()["effect_total"] + self.probe(node, "write", realm, expected_state="RejectedBeforeDispatch", + expectedNodeId=self.node_id(target), expectedRole="Primary") + self.check(self.device()["effect_total"] == effects, "origin operation-mask write denial has zero physical effects") + self.mutate(export_allowed_operations=OPERATIONS, write_through=True, target_mode="Cluster", consistency="Primary") + self.prepare_positive_projection(node, "raw") + with self.changing(): + self.live_cli_fault(node, on_fault=lambda: self.mutate(key_action="revoke"), + recovery=lambda: self.mutate(key_action="rotate"), require_gap=True, duration=90) + self.mutate(key_action="expire", key_expiry_seconds=20) + self.prepare_positive_projection(node, "raw") + with self.changing(): + self.live_cli_fault(node, recovery=lambda: self.mutate(key_action="rotate"), require_gap=True, duration=90) + self.probe(node, "capabilities", expected_state="Ready") + + def scenario_D07(self): + consumer = self.primary("consumer") + for realm in ("raw", "uns"): + source = self.primary("source") + self.wait_connection_ready(consumer, realm, require_fresh_sample=True) + capabilities = self.probe(consumer, "capabilities", realm) + before = capabilities["serving"] + lease_seconds = metadata_lease_seconds({"duration": capabilities["limits"]["maxMetadataLease"]}) + source_partner = next(node for node in self.manifest["nodes"] if node.startswith("source-") and node != source) + self.prepare_positive_projection(consumer, realm) + recovered_observation = [] + def recovered(): + selected = self.wait_primary("source", exclude=source) + self.check(selected == source_partner, "extended outage recovered the unpaused SOURCE partner") + self.wait_connection_ready(consumer, realm, expected_node=selected, require_fresh_sample=True) + observed = self.probe(consumer, "read", realm, expectedNodeId=self.node_id(selected)) + self.check(observed["serving"] != before, "source serving epoch changed") + recovered_observation.append(observed) + # Prove the unchanged item recovered first, then read through the + # same consumer while the old SOURCE is still stopped. + with self.changing(): + evidence = self.live_cli_fault(consumer, source, require_gap=True, on_fault=recovered, realm=realm, + outage_partner=source_partner, duration=120, post_lease_seconds=lease_seconds + 5, + after_validated_recovery=lambda: self.cli("read", consumer, realm)) + self.record_matrix_cell("cross-cluster", "Cluster", "mounted", realm, "subscribe", consumer, + recovered_observation[0], boundary="source-failover", cli_evidence=evidence) + self.wait_primary("source") + self.wait_primary("source") + source = self.primary("source") + self.mutate(target_mode="Node", target_node_id=self.node_id(source), consistency="Primary") + with self.stopped(source): + self.wait_primary("source", exclude=source) + for realm in ("raw", "uns"): + unavailable = self.matrix_probe("cross-cluster", "Node", realm, "capabilities", consumer, + boundary="pinned-loss", expected_node=source, expected_state="Unavailable") + self.matrix_cli("cross-cluster", "Node", realm, "read", consumer, + boundary="pinned-loss", expected_node=source, observed=unavailable, denial=True) + self.wait_pair_topology("source") + selected = self.wait_primary("source") + self.mutate(target_mode="Cluster", consistency="Primary", + maintenance_mode={"node_id": self.node_id(selected), "enabled": True}) + # The excluded endpoint remains reachable and active. Unavailability here + # proves maintenance policy, rather than merely TCP failure, excludes it. + self.check(self.primary("source") == selected, "maintenance endpoint remains operational primary") + self.probe(selected, "topology") + for realm in ("raw", "uns"): + self.matrix_probe("cross-cluster", "Cluster", realm, "capabilities", consumer, + boundary="maintenance-primary", expected_state="Unavailable") + with self.stopped(selected): + partner = self.wait_primary("source", exclude=selected) + for realm in ("raw", "uns"): + self.wait_connection_ready(consumer, realm, expected_node=partner, require_fresh_sample=True) + self.matrix_probe("cross-cluster", "Cluster", realm, "read", consumer, + boundary="maintenance-exclusion", expected_node=partner) + self.wait_pair_topology("source") + + def scenario_D08(self): + node = self.primary("consumer") + self.probe(node, "mixed-write") + before = self.device()["effect_total"] + self.device("drop_next_write_response") + operation = "loss-" + uuid.uuid4().hex + self.probe(node, "dedup", expected_state="OutcomeUnknown", operationId=operation) + self.check(self.device()["effect_total"] == before + 1, "ambiguous duplicate has one effect") + self.rig.compose("restart", node, timeout=self.remaining(40)) + self.manifest = self.rig.refresh_endpoints((node,)) + self.wait_primary("consumer") + self.wait_connection_ready(node, require_fresh_sample=True) + self.probe(node, "dedup", expected_state="OutcomeUnknown", operationId=operation) + self.check(self.device()["effect_total"] == before + 1, "caller restart same operation has no replay") + observed = self.probe(node, "capabilities")["serving"] + source = next(name for name in self.manifest["nodes"] if self.node_id(name) == observed["nodeId"]) + before_stale = self.device()["effect_total"] + with self.stopped(source): + selected = self.wait_primary("source", exclude=source) + self.wait_connection_ready(node, expected_node=selected, require_fresh_sample=True) + current = self.probe(node, "capabilities", expectedNodeId=self.node_id(selected))["serving"] + self.check(current != observed, "observed source incarnation changed before stale request") + self.probe(node, "write", expectedIncarnation=observed["incarnation"], expectedGeneration=observed["servingGeneration"], expected_state="RejectedBeforeDispatch") + self.check(self.device()["effect_total"] == before_stale, "stale incarnation had no device effect") + + def scenario_D09(self): + primary = self.primary("source") + secondary = next(node for node in self.manifest["nodes"] if node.startswith("source-") and node != primary) + self.mutate(target_mode="Node", target_node_id=self.node_id(secondary), consistency="ReadyReplica") + consumer = self.primary("consumer") + before = {} + for realm in ("raw", "uns"): + before[realm] = self.matrix_probe("cross-cluster", "Node", realm, "read", consumer, + boundary="secondary", expected_node=secondary)["serving"] + effects = self.device()["effect_total"] + self.matrix_probe("cross-cluster", "Node", realm, "write", consumer, + boundary="secondary", expected_node=secondary, expected_state="RejectedBeforeDispatch") + self.check(self.device()["effect_total"] == effects, "pinned secondary write produces no effect") + try: + with self.rig._configuration_experiment("warm-source", ("source-1", "source-2"), + {"OpcUa__Redundancy__Mode": "Warm"}): + self.manifest = self.rig.load() + # Startup Warm and artifact redundancy policy are separate inputs. + # mutate deploys with require_catalog=False while Standby is unservable. + self.mutate(source_redundancy_mode="Warm") + states = self.wait_warm_pair() + active, standby = select_warm_pair(states) + self.mutate(target_mode="Node", target_node_id=self.node_id(standby), consistency="ReadyReplica") + warm = {"pair": states, "target_node": standby, "realms": {}} + for realm in ("raw", "uns"): + if realm == "uns": + # A rejected selection sets the first discovery backoff + # to at most 300 ms. Prove the second realm by a new + # eligible attempt, never by accepting that backoff. + time.sleep(self.remaining(.35)) + source_state = self.wait_warm_state(standby, "Standby") + # The actual read command first authenticates capabilities; + # a strict GetCapabilities rejection proves no Read dispatch. + rejected = self.probe(consumer, "read", realm, expected_state="TargetIneligible", + expectedNodeId=self.node_id(standby)) + validate_warm_target_rejection(rejected, source_state, expected_node_id=self.node_id(standby)) + warm["realms"][realm] = {"source_state": source_state, "read": rejected} + self.save("D09-Warm-standby.json", warm) + previous = warm["realms"]["raw"]["source_state"] + with self.stopped(active): + reads_before = self.device()["read_total"] + current = self.wait_warm_state(standby, "Active") + self.check(current["process"] == previous["process"] + and current["serving"]["incarnation"] == previous["serving"]["incarnation"] + and current["serving"] != previous["serving"] + and current["warmRole"]["generation"] > previous["warmRole"]["generation"], + "same pinned Warm process activates with a new actual verdict and serving identity") + activated = {} + for realm in ("raw", "uns"): + self.wait_connection_ready(consumer, realm, expected_node=standby, require_fresh_sample=True) + actual = self.probe(consumer, "read", realm, expected_state="Good", + expectedNodeId=self.node_id(standby), expectedRole="Primary") + validate_read_freshness(actual) + self.check(actual.get("sample") is not None and actual["serving"] == current["serving"], + "Warm activated primary returns a fresh sample from the unchanged pinned target") + activated[realm] = actual + reads_after = self.device()["read_total"] + self.check(type(reads_before) is int and type(reads_after) is int and reads_after > reads_before, + "activated Warm target produces physical reads while former Active remains stopped") + self.save("D09-Warm-primary.json", {"state": current, "realms": activated, + "physical_reads_before": reads_before, "physical_reads_after": reads_after}) + finally: + # The startup override restores before run() performs its outer artifact baseline. + self.manifest = self.rig.load() + + def scenario_D10(self): + for realm in ("raw", "uns"): + consumer = self.primary("consumer") + partner = next(node for node in self.manifest["nodes"] if node.startswith("consumer-") and node != consumer) + source_before = self.probe(consumer, "capabilities", realm)["serving"]["nodeId"] + self.cli("connect", consumer, partner=partner) + preparation = {"realm": realm, "nodes": [], + "scope": "Both eligible SDK projections are explicitly prepared; this setup does not prove cold or expired partner recovery."} + for prepared_node in (consumer, partner): + started = time.monotonic() + self.prepare_positive_projection(prepared_node, realm) + preparation["nodes"].append({"node": prepared_node, "started_at_monotonic": started, + "completed_at_monotonic": time.monotonic(), "completed_at_utc": datetime.now(timezone.utc).isoformat()}) + # The automatic CLI partner is prepared last. A successful browse + # records an observed projection, without claiming a new cache lease. + preparation["prepared_before_automatic_failover_at"] = time.monotonic() + self.timeline.append({"event": "consumer-failover-projections-prepared", "realm": realm, + "nodes": preparation["nodes"], "at": preparation["prepared_before_automatic_failover_at"]}) + self.save(f"D10-{realm}-projection-preparation.json", preparation) + recovered_observation = [] + def recovered(): + self.wait_primary("consumer", exclude=consumer) + self.wait_connection_ready(partner, realm, require_fresh_sample=True) + observed = self.probe(partner, "read", realm) + self.check(observed["serving"]["nodeId"] == source_before, "UA client moved while SOURCE serving node stayed fixed") + recovered_observation.append(observed) + with self.changing(): + evidence = self.live_cli_fault(consumer, consumer, partner=partner, require_gap=False, on_fault=recovered, realm=realm) + temporal = evidence["temporal"] + preparation["attachment_and_fault"] = { + "first_good_at": next((row["at"] for row in temporal["notifications"] if cli_gate.is_good_status(row["status"])), None), + "fault_at": temporal["fault_at"]} + evidence["projection_preparation"] = preparation + self.save(f"D10-{realm}-projection-preparation.json", preparation) + self.record_matrix_cell("cross-cluster", "Cluster", "mounted", realm, "subscribe", partner, + recovered_observation[0], boundary="consumer-failover", cli_evidence=evidence) + self.wait_primary("consumer") + consumer = self.primary("consumer") + partner = next(node for node in self.manifest["nodes"] if node.startswith("consumer-") and node != consumer) + self.mutate(consumer_node_ids=[self.node_id(consumer)]) + self.probe(partner, "capabilities", expected_state="Unavailable") + for realm in ("raw", "uns"): + self.cli("read", partner, realm, denial=True) + + def scenario_D11(self): + before = self.device()["effect_total"] + with self.stopped("control-1", "control-2"): + for realm in ("raw", "uns"): + self.cli("read", self.primary("source"), realm) + consumer = self.primary("consumer") + for operation in ("read", "subscribe"): + started = time.monotonic() + self.prepare_positive_projection(consumer, realm) + self.timeline.append({"event": "control-outage-projection-prepared", "node": consumer, + "realm": realm, "operation": operation, "started_at": started, "at": time.monotonic(), + "setup": "authenticated Browse while both CONTROL nodes are stopped; no automatic lease-renewal claim"}) + if operation == "subscribe": + with self.changing(): + self.cli(operation, consumer, realm) + else: + self.cli(operation, consumer, realm) + self.wait_primary("control") + self.check(self.device()["effect_total"] == before, "controller reconciliation did not replay writes") + + def scenario_D12(self): + consumer = self.primary("consumer") + partner = next(node for node in self.manifest["nodes"] if node.startswith("consumer-") and node != consumer) + for mutation in ({"consumer_node_ids": [self.node_id(partner)]}, {"export_enabled": False}, {"mapping_enabled": False}, {"connection_enabled": False, "mapping_enabled": False}, {"disable_feature": True}): + self.mutate(**mutation) + for realm in ("raw", "uns"): + self.cli("read", consumer, realm, denial=True) + self.cli("write", consumer, realm, denial=True) + self.cli("read", self.primary("source"), realm) + deployment = self.manifest["deployment"] + self.check({row["nodeId"] for row in deployment["nodes"] if row["status"] == "Applied"} + == set(deployment["required_node_ids"]), "existing deployment command path applied after withdrawal") + telemetry = self.probe(self.primary("control"), "legacy-telemetry", + expectedNodeId=self.node_id(self.primary("source")), timeout=20) + self.check(telemetry.get("authenticatedSnapshotReceived") is True, + "existing authenticated telemetry plane remains usable after withdrawal") + if any(key in mutation for key in ("consumer_node_ids", "mapping_enabled", "connection_enabled", "disable_feature")): + end = time.monotonic() + self.remaining(30) + while True: + connections = self.probe(consumer, "topology").get("connections") + self.check(isinstance(connections, list), "withdrawal diagnostics available") + if all(connection["activeStreams"] == 0 and connection["activeCalls"] == 0 for connection in connections): + self.check(True, "projected streams and operations withdrawn") + break + if time.monotonic() >= end: + raise ScenarioError("removed projection retained remote demand") + time.sleep(min(0.25, end - time.monotonic())) + self.baseline() + + def scenario_D13(self): + self.wire() + consumer = self.primary("consumer") + certificate_target = self.primary("source") + self.mutate(target_mode="Node", target_node_id=self.node_id(certificate_target), consistency="ReadyReplica") + for reason in ("wrong-ca", "wrong-san"): + for realm in ("raw", "uns"): + self.probe(consumer, "read", realm, expectedNodeId=self.node_id(certificate_target)) + with self.rig.rejected_server_identity(certificate_target, reason): + self.manifest = self.rig.load() + self.wait_primary("source") + control = self.rig.verify_test_tls_listener(certificate_target, reason) + before_tls = self.probe(certificate_target, "topology") + for realm in ("raw", "uns"): + self.matrix_probe("cross-cluster", "Node", realm, "capabilities", consumer, + boundary=reason, expected_node=certificate_target, expected_state="Unavailable") + self.cli("read", consumer, realm, denial=True) + after_tls = self.probe(certificate_target, "topology") + self.save("D13-" + reason + "-tls-boundary.json", {"listener_control": control, + **validate_tls_rejection_counters(before_tls, after_tls)}) + self.manifest = self.rig.load() + self.wait_primary("source") + for realm in ("raw", "uns"): + self.wait_connection_ready(consumer, realm, expected_node=certificate_target) + self.probe(consumer, "read", realm, expectedNodeId=self.node_id(certificate_target)) + self.check(self.probe(certificate_target, "topology").get("inboundDataRequests", 0) > 0, + "restored actual consumer traffic proves the listener observer") + self.mutate(target_mode="Cluster", consistency="Primary") + self.probe(consumer, "read", subject="unrelated/claimed/principal", expected_state="Denied") + request = {"upsert_export": {"DataExportId": "illegal-peer-reexport", "ClusterId": "CONSUMER", "Enabled": True, + "Realm": 1, "RootKind": "RemoteNamespaceMapping", "RootEntityId": "map-raw", "PrincipalId": "fixture-consumer", "AllowedOperations": OPERATIONS}} + rig.atomic_write_secret(self.rig.folder / "seed" / "mutation.json", json.dumps(request)) + rejected = False + try: + self.rig.seed_helper("mutate") + except rig.RigError: + rejection = restricted_json(self.rig.folder / "seed" / "rejection.json") + rejected = rejection.get("validator") == "DraftValidator" and bool(rejection.get("codes")) + self.save("D13-peer-reexport-rejection.json", rejection) + self.check(rejected, "production authoring rejects mounted peer re-export") + + def scenario_D14(self): + consumer = self.primary("consumer") + # Missing/retired material exercises the durable P07 store by restarting + # the actual caller; changing only this Python process would prove nothing. + self.rig.credential_action("remove_consumer_secret") + self.rig.compose("restart", consumer, timeout=self.remaining(40)) + self.manifest = self.rig.refresh_endpoints((consumer,)) + self.wait_primary("consumer") + self.probe(consumer, "capabilities", expected_state="Unavailable") + self.rig.credential_action("provision_consumer_secret") + self.wait_connection_ready(consumer, require_fresh_sample=True) + self.probe(consumer, "read") + for node in ("consumer-1", "consumer-2"): + self.wait_connection_ready(node) + self.probe(node, "capabilities", expected_state="Ready") + self.mutate(key_action="rotate_staged") + self.wait_connection_ready(consumer, require_fresh_sample=True) + self.probe(consumer, "read") + self.wire(previous_key_state="enabled") + self.mutate(key_action="retire_old") + self.wait_connection_ready(consumer, require_fresh_sample=True) + self.probe(consumer, "read") + self.wire(previous_key_state="revoked") + self.rig.trust_action("stage_new") + self.wait_connection_ready(consumer, require_fresh_sample=True) + self.probe(consumer, "read") + self.rig.trust_action("rotate_server") + self.manifest = self.rig.load() + self.wait_primary("source") + self.wait_connection_ready(consumer, require_fresh_sample=True) + self.probe(consumer, "read") + self.rig.trust_action("retire_old") + self.manifest = self.rig.load() + self.wire() + certificate_target = self.primary("source") + self.mutate(target_mode="Node", target_node_id=self.node_id(certificate_target), consistency="ReadyReplica") + for realm in ("raw", "uns"): + self.probe(consumer, "read", realm, expectedNodeId=self.node_id(certificate_target)) + with self.rig.retired_server_identity(certificate_target): + self.manifest = self.rig.load() + self.wait_primary("source") + control = self.rig.verify_test_tls_listener(certificate_target, "retired-ca") + before_tls = self.probe(certificate_target, "topology") + for realm in ("raw", "uns"): + self.matrix_probe("cross-cluster", "Node", realm, "capabilities", consumer, + boundary="retired-ca", expected_node=certificate_target, expected_state="Unavailable") + self.cli("read", consumer, realm, denial=True) + after_tls = self.probe(certificate_target, "topology") + self.save("D14-retired-ca-tls-boundary.json", {"listener_control": control, + **validate_tls_rejection_counters(before_tls, after_tls)}) + self.manifest = self.rig.load() + self.wait_primary("source") + for realm in ("raw", "uns"): + self.wait_connection_ready(consumer, realm, expected_node=certificate_target) + self.probe(consumer, "read", realm, expectedNodeId=self.node_id(certificate_target)) + self.check(self.probe(certificate_target, "topology").get("inboundDataRequests", 0) > 0, + "restored current trust produces actual HTTP requests") + self.mutate(target_mode="Cluster", consistency="Primary") + before = self.device()["effect_total"] + operation = "offline-loss-" + uuid.uuid4().hex + self.device("drop_next_write_response") + self.probe(consumer, "dedup", expected_state="OutcomeUnknown", operationId=operation) + self.check(self.device()["effect_total"] == before + 1, "tracked ambiguous effect before offline restart") + with self.stopped("control-1", "control-2"): + self.rig.compose("restart", consumer, timeout=self.remaining(40)) + self.manifest = self.rig.refresh_endpoints((consumer,)) + self.wait_primary("consumer") + self.wait_connection_ready(consumer, require_fresh_sample=True) + self.probe(consumer, "read") + self.probe(consumer, "dedup", expected_state="OutcomeUnknown", operationId=operation) + self.check(self.device()["effect_total"] == before + 1, "offline restart did not replay in-flight writes") + partner = next(node for node in self.manifest["nodes"] if node.startswith("consumer-") and node != consumer) + self.mutate(consumer_node_ids=[self.node_id(partner)]) + self.rig.credential_action("reload_stale_bundle", node=consumer) + self.probe(consumer, "capabilities", expected_state="Unavailable") diff --git a/scripts/validation/grpc-data/seed/FixtureMutationRevisions.cs b/scripts/validation/grpc-data/seed/FixtureMutationRevisions.cs new file mode 100644 index 000000000..cff19f28a --- /dev/null +++ b/scripts/validation/grpc-data/seed/FixtureMutationRevisions.cs @@ -0,0 +1,52 @@ +using System.Text.Json; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; + +namespace GrpcDataSeed; + +/// Nonsecret selected entity revisions before or after a fixture mutation. +public sealed record FixtureEntityRevisions(long Connection, IReadOnlyDictionary Mappings, + IReadOnlyDictionary Exports); + +/// Audits whether a fixture mutation preserved the selected placement identities. +public sealed record FixtureMutationRevisionReceipt(bool CredentialOnly, FixtureEntityRevisions Before, FixtureEntityRevisions After); + +/// Keeps credential faults distinct from deliberately fenced configuration mutations. +public static class FixtureMutationRevisions +{ + /// Applies the fixture connection's inherited mapping consumer placement. + public static void InheritConsumerPlacement(JsonElement mutation, DataConnection connection, RemoteNamespaceMapping mapping) + { + if (!IsCredentialOnly(mutation)) + mapping.ConsumerNodeIds = connection.ConsumerNodeIds.ToList(); + } + + private static bool IsCredentialOnly(JsonElement mutation) + { + if (mutation.ValueKind != JsonValueKind.Object || !mutation.TryGetProperty("key_action", out var action) + || action.ValueKind != JsonValueKind.String + || action.GetString() is not ("rotate" or "rotate_staged" or "expire" or "retire_old" or "revoke")) return false; + var fields = mutation.EnumerateObject().Select(property => property.Name).ToArray(); + return fields.Length is 1 or 2 && fields.Distinct(StringComparer.Ordinal).Count() == fields.Length + && fields.All(field => field is "key_action" or "key_expiry_seconds"); + } + + /// Applies the fixture's revision policy to the actual selected tracked entities. + public static FixtureMutationRevisionReceipt Advance(JsonElement mutation, DataConnection connection, + IEnumerable mappings, IEnumerable exports) + { + var selectedMappings = mappings.ToArray(); + var selectedExports = exports.ToArray(); + FixtureEntityRevisions Capture() => new(connection.Revision, + selectedMappings.ToDictionary(item => item.RemoteNamespaceMappingId, item => item.Revision, StringComparer.Ordinal), + selectedExports.ToDictionary(item => item.DataExportId, item => item.Revision, StringComparer.Ordinal)); + var before = Capture(); + var credentialOnly = IsCredentialOnly(mutation); + if (!credentialOnly) + { + connection.Revision++; + foreach (var mapping in selectedMappings) mapping.Revision++; + foreach (var export in selectedExports) export.Revision++; + } + return new(credentialOnly, before, Capture()); + } +} diff --git a/scripts/validation/grpc-data/seed/GrpcDataSeed.csproj b/scripts/validation/grpc-data/seed/GrpcDataSeed.csproj new file mode 100644 index 000000000..7e986ba8b --- /dev/null +++ b/scripts/validation/grpc-data/seed/GrpcDataSeed.csproj @@ -0,0 +1,7 @@ + + Exefalse + + + + + diff --git a/scripts/validation/grpc-data/seed/Program.cs b/scripts/validation/grpc-data/seed/Program.cs new file mode 100644 index 000000000..fdc5fdeb6 --- /dev/null +++ b/scripts/validation/grpc-data/seed/Program.cs @@ -0,0 +1,432 @@ +// Disposable local fixture only. No plaintext key or SQL diagnostic is printed. +using System.Text.Json; +using System.IO.Compression; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Opc.Ua; +using ZB.MOM.WW.OtOpcUa.Client.Shared; +using ZB.MOM.WW.OtOpcUa.Client.Shared.Models; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Configuration.Validation; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using GrpcDataSeed; + +var output = Environment.GetEnvironmentVariable("GRPC_DATA_OUTPUT") ?? "/output"; +var connection = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_CONNECTION") ?? throw new InvalidOperationException("local SQL configuration required"); +var pepper = Environment.GetEnvironmentVariable("GRPC_DATA_PEPPER") ?? throw new InvalidOperationException("local API pepper required"); +// Never accept an arbitrary DB host. The helper runs only on this run's network. +var sql = new Microsoft.Data.SqlClient.SqlConnectionStringBuilder(connection); +if (sql.DataSource != "sql,1433") throw new InvalidOperationException("fixture SQL must use owned service DNS"); +var options = new DbContextOptionsBuilder().UseSqlServer(connection).Options; +IDbContextFactory factory = new PooledDbContextFactory(options); +string[] nodes = ["control-1", "control-2", "source-1", "source-2", "consumer-1", "consumer-2"]; +const DataOperations operations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe; +try +{ + if (args.Length == 0) return 2; + if (args[0] == "scope") + { + var id = Guid.Parse(args[1]); + await using var db = await factory.CreateDbContextAsync(); + var deployment = await db.Deployments.AsNoTracking().SingleAsync(x => x.DeploymentId == id); + if (deployment.RevisionHash != args[2] || deployment.ArtifactBlob.Length == 0) throw new InvalidOperationException(); + using var compressed = new MemoryStream(deployment.ArtifactBlob); + using var stream = new GZipStream(compressed, CompressionMode.Decompress); + using var artifact = await JsonDocument.ParseAsync(stream); + var version = artifact.RootElement.GetProperty("DataConnectionScopeVersion").GetInt64(); + if (version <= 0) throw new InvalidOperationException(); + await Save("scope.json", new { deployment_id = id, revision_hash = deployment.RevisionHash, scope_version = version, + required_node_ids = artifact.RootElement.GetProperty("Nodes").EnumerateArray() + .Where(x => x.GetProperty("Enabled").GetBoolean() && !x.GetProperty("MaintenanceMode").GetBoolean()) + .Select(x => x.GetProperty("NodeId").GetString()).ToArray(), + connections = artifact.RootElement.GetProperty("DataConnections").EnumerateArray() + .Where(x => x.GetProperty("Enabled").GetBoolean()).Select(x => new { + connection_id = x.GetProperty("DataConnectionId").GetString(), + owner = x.GetProperty("ClusterId").GetString(), + secret_reference = x.GetProperty("SecretReference").GetString(), + consumer_node_ids = x.GetProperty("ConsumerNodeIds").EnumerateArray().Select(y => y.GetString()).ToArray() }).ToArray() }); + return 0; + } + if (args[0] == "resolve") + { + var resolved = new Dictionary(); + await using var config = await factory.CreateDbContextAsync(); + var activeConnections = await config.DataConnections.Where(x => x.Enabled).Select(x => x.DataConnectionId).ToListAsync(); + var activeMappings = await config.RemoteNamespaceMappings.Where(x => x.Enabled && activeConnections.Contains(x.DataConnectionId)).ToListAsync(); + foreach (var node in nodes) + { + var client = new OpcUaClientServiceFactory().Create(); + try + { + await client.ConnectAsync(new ConnectionSettings { EndpointUrl = $"opc.tcp://{node}:4840", SecurityMode = SecurityMode.None, + Username = "apikey", Password = (await File.ReadAllTextAsync(Path.Combine(output, "cli.key"))).Trim(), + AutoAcceptCertificates = true, CertificateStorePath = "/output/pki", SessionTimeoutSeconds = 30 }); + var ns = await client.ReadValueAsync(VariableIds.Server_NamespaceArray); + if (StatusCode.IsBad(ns.StatusCode) || ns.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy) is not string[] uris) throw new InvalidOperationException(); + var servers = await client.ReadValueAsync(VariableIds.Server_ServerArray); + if (servers.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy) is not string[] applications || !applications.Contains("urn:OtOpcUa:grpc-data:" + node, StringComparer.Ordinal)) throw new InvalidOperationException("unexpected application identity"); + var rawIndex = Array.IndexOf(uris, V3NodeIds.RawNamespaceUri); + if (rawIndex > 0) + { + var pending = new Queue<(NodeId Node, int Depth)>(); + var seen = new HashSet(StringComparer.Ordinal); + pending.Enqueue((new NodeId(V3NodeIds.SharedRootFolderId, checked((ushort)rawIndex)), 0)); + while (pending.TryDequeue(out var parent)) + { + if (!seen.Add(parent.Node.ToString()) || parent.Depth > 8 || seen.Count > 256) continue; + foreach (var child in await client.BrowseAsync(parent.Node)) + if (child.HasChildren) pending.Enqueue((NodeId.Parse(child.NodeId), parent.Depth + 1)); + } + } + var aliases = new Dictionary(); + var expected = new List<(string Name, string Uri, string Identifier)>(); + if (node.StartsWith("source-", StringComparison.Ordinal)) + { + expected.Add(("raw", V3NodeIds.RawNamespaceUri, "modbus/plc/scalar")); + expected.Add(("uns", V3NodeIds.UnsNamespaceUri, "area/line/plc/scalar")); + } + if (node.StartsWith("consumer-", StringComparison.Ordinal)) + { + foreach (var realm in new[] { DataRealm.Raw, DataRealm.Uns }) + { + if (!activeMappings.Any(x => x.RemoteNamespaceMappingId == "map-" + realm.ToString().ToLowerInvariant() && x.ConsumerNodeIds.Contains(node + ":4053"))) continue; + var uri = realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri; + var path = realm == DataRealm.Raw ? "modbus/plc/scalar" : "area/line/plc/scalar"; + expected.Add((realm.ToString().ToLowerInvariant(), ProjectedDataIds.NamespaceUri(realm), + ProjectedDataIds.Identifier("map-" + realm.ToString().ToLowerInvariant(), new("SOURCE", uri, "string", path)))); + } + } + foreach (var item in expected) + { + var index = Array.IndexOf(uris, item.Uri); + if (index < 1) throw new InvalidOperationException("namespace absent"); + var id = new NodeId(item.Identifier, checked((ushort)index)); + Opc.Ua.DataValue value; + var readDeadline = DateTime.UtcNow.AddSeconds(5); + while (true) + { + try { value = await client.ReadValueAsync(id, TimeSpan.FromSeconds(5)); break; } + catch (ServiceResultException error) when (error.StatusCode == StatusCodes.BadWaitingForInitialData && DateTime.UtcNow < readDeadline) + { await Task.Delay(100); } + } + if (StatusCode.IsBad(value.StatusCode)) throw new InvalidOperationException("fixture leaf not ready"); + aliases[item.Name] = id.ToString(); + } + resolved[node] = new { namespace_uris = uris, aliases }; + } + finally { await client.DisconnectAsync(); } + } + await Save("resolved.json", resolved); + return 0; + } + if (args[0] == "snapshot") + { + await using var db = await factory.CreateDbContextAsync(); + await Save("baseline.json", new { + Connections = await db.DataConnections.AsNoTracking().ToListAsync(), Mappings = await db.RemoteNamespaceMappings.AsNoTracking().ToListAsync(), + Exports = await db.DataExports.AsNoTracking().ToListAsync(), Tags = await db.Tags.AsNoTracking().ToListAsync(), + References = await db.UnsTagReferences.AsNoTracking().ToListAsync(), + Clusters = await db.ServerClusters.AsNoTracking().ToListAsync(), Nodes = await db.ClusterNodes.AsNoTracking().ToListAsync(), + Acls = await db.NodeAcls.AsNoTracking().ToListAsync(), + Keys = await db.ApiKeys.AsNoTracking().Select(x => new { x.ApiKeyId, x.Enabled }).ToListAsync() }); + await SaveText("baseline-source.key", await File.ReadAllTextAsync(Path.Combine(output, "source.key"))); + return 0; + } + if (args[0] == "restore") + { + using var baseline = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine(output, "baseline.json"))); + var root = baseline.RootElement; + await using var db = await factory.CreateDbContextAsync(); + await using var transaction = await db.Database.BeginTransactionAsync(); + await RestoreRows(db, db.DataConnections, root.GetProperty("Connections").Deserialize>()!, x => x.DataConnectionId); + await RestoreRows(db, db.RemoteNamespaceMappings, root.GetProperty("Mappings").Deserialize>()!, x => x.RemoteNamespaceMappingId); + await RestoreRows(db, db.DataExports, root.GetProperty("Exports").Deserialize>()!, x => x.DataExportId); + await RestoreRows(db, db.Tags, root.GetProperty("Tags").Deserialize>()!, x => x.TagId); + await RestoreRows(db, db.UnsTagReferences, root.GetProperty("References").Deserialize>()!, x => x.UnsTagReferenceId); + await RestoreRows(db, db.ServerClusters, root.GetProperty("Clusters").Deserialize>()!, x => x.ClusterId); + await RestoreRows(db, db.ClusterNodes, root.GetProperty("Nodes").Deserialize>()!, x => x.NodeId); + await RestoreRows(db, db.NodeAcls, root.GetProperty("Acls").Deserialize>()!, x => x.NodeAclId); + await db.SaveChangesAsync(); + if (DraftValidator.Validate(await DraftSnapshotFactory.FromConfigDbAsync(db)).Count != 0) throw new InvalidOperationException(); + await transaction.CommitAsync(); + var admin = new ApiKeyAdminService(factory, pepper); + var baselineKeys = root.GetProperty("Keys").EnumerateArray().Select(x => x.GetProperty("ApiKeyId").GetString()).ToHashSet(StringComparer.Ordinal); + foreach (var extra in (await admin.ListAsync(default)).Where(x => !baselineKeys.Contains(x.ApiKeyId))) + await admin.SetEnabledAsync(extra.ApiKeyId, false, default); + foreach (var key in root.GetProperty("Keys").EnumerateArray()) + await admin.SetEnabledAsync(key.GetProperty("ApiKeyId").GetString()!, key.GetProperty("Enabled").GetBoolean(), default); + await SaveText("source.key", await File.ReadAllTextAsync(Path.Combine(output, "baseline-source.key"))); + return 0; + } + if (args[0] == "mutate") + { + using var mutation = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine(output, "mutation.json"))); + var root = mutation.RootElement; + string[] allowedFields = ["connection_id", "target_mode", "target_node_id", "consistency", "consumer_node_ids", "connection_enabled", "connection_allowed_operations", + "mapping_enabled", "write_through", "allowed_operations", "export_id", "export_enabled", "export_allowed_operations", "source_redundancy_mode", "consumer_redundancy_mode", + "control_redundancy_mode", "rename_tag", "upsert_tag", "upsert_reference", "remove_tag_id", "disable_feature", "key_action", "key_expiry_seconds", "upsert_connection", "upsert_mapping", "upsert_export", "remove_mapping_id", "maintenance_mode"]; + if (root.ValueKind != JsonValueKind.Object || root.EnumerateObject().Any(property => !allowedFields.Contains(property.Name, StringComparer.Ordinal))) + throw new InvalidOperationException("unknown fixture mutation field"); + await using var db = await factory.CreateDbContextAsync(); + await using var transaction = await db.Database.BeginTransactionAsync(); + var rejectionPath = Path.Combine(output, "rejection.json"); + if (File.Exists(rejectionPath)) File.Delete(rejectionPath); + var revisionReceiptPath = Path.Combine(output, "mutation-revisions.json"); + if (File.Exists(revisionReceiptPath)) File.Delete(revisionReceiptPath); + if (root.TryGetProperty("key_action", out var keyAction) && keyAction.GetString() is not ("rotate" or "rotate_staged" or "expire" or "retire_old" or "revoke")) + throw new InvalidOperationException("unknown key mutation"); + if (root.TryGetProperty("maintenance_mode", out var maintenance)) + { + if (maintenance.ValueKind != JsonValueKind.Object + || maintenance.EnumerateObject().Select(x => x.Name).Order().SequenceEqual(new[] { "enabled", "node_id" }) is false + || maintenance.GetProperty("node_id").GetString() is not { } maintenanceNodeId + || !nodes.Select(node => node + ":4053").Contains(maintenanceNodeId, StringComparer.Ordinal) + || maintenance.GetProperty("enabled").ValueKind is not (JsonValueKind.True or JsonValueKind.False)) + throw new InvalidOperationException("owned maintenance node and boolean required"); + var maintenanceNode = await db.ClusterNodes.SingleAsync(x => x.NodeId == maintenanceNodeId); + maintenanceNode.MaintenanceMode = maintenance.GetProperty("enabled").GetBoolean(); + } + if (root.TryGetProperty("upsert_connection", out var newConnection)) + { + var candidate = JsonSerializer.Deserialize(newConnection.GetRawText()) ?? throw new InvalidOperationException(); + if (candidate.Endpoints.Any(endpoint => !Uri.TryCreate(endpoint, UriKind.Absolute, out var url) || url.Scheme != "https" || !nodes.Contains(url.Host, StringComparer.Ordinal) || url.Port != 4057)) throw new InvalidOperationException("owned endpoint required"); + candidate.DataConnectionRowId = Guid.NewGuid(); + var existing = await db.DataConnections.SingleOrDefaultAsync(x => x.DataConnectionId == candidate.DataConnectionId); + if (existing is null) db.DataConnections.Add(candidate); + else { candidate.DataConnectionRowId = existing.DataConnectionRowId; db.Entry(existing).CurrentValues.SetValues(candidate); } + await db.SaveChangesAsync(); + } + if (root.TryGetProperty("upsert_mapping", out var newMapping)) + { + var candidate = JsonSerializer.Deserialize(newMapping.GetRawText()) ?? throw new InvalidOperationException(); + candidate.RemoteNamespaceMappingRowId = Guid.NewGuid(); + var existing = await db.RemoteNamespaceMappings.SingleOrDefaultAsync(x => x.RemoteNamespaceMappingId == candidate.RemoteNamespaceMappingId); + if (existing is null) db.RemoteNamespaceMappings.Add(candidate); + else { candidate.RemoteNamespaceMappingRowId = existing.RemoteNamespaceMappingRowId; db.Entry(existing).CurrentValues.SetValues(candidate); } + } + if (root.TryGetProperty("upsert_export", out var newExport)) + { + var candidate = newExport.Deserialize() ?? throw new InvalidOperationException(); + candidate.DataExportRowId = Guid.NewGuid(); + var existing = await db.DataExports.SingleOrDefaultAsync(x => x.DataExportId == candidate.DataExportId); + if (existing is null) db.DataExports.Add(candidate); + else { candidate.DataExportRowId = existing.DataExportRowId; db.Entry(existing).CurrentValues.SetValues(candidate); } + } + if (root.TryGetProperty("remove_mapping_id", out var removeMapping)) + await db.RemoteNamespaceMappings.Where(x => x.RemoteNamespaceMappingId == removeMapping.GetString()).ExecuteDeleteAsync(); + var connectionId = root.TryGetProperty("connection_id", out var selected) ? selected.GetString() : "consumer-source"; + var item = await db.DataConnections.SingleAsync(x => x.DataConnectionId == connectionId); + if (root.TryGetProperty("target_mode", out var mode)) + { + item.TargetMode = Enum.Parse(mode.GetString()!); + item.ExpectedNodeId = item.TargetMode == DataTargetMode.Node ? (root.TryGetProperty("target_node_id", out var target) ? target.GetString() : "source-1:4053") : null; + item.EligibleTargetNodeIds = item.TargetMode == DataTargetMode.Node ? [] : ["source-1:4053", "source-2:4053"]; + item.Endpoints = item.TargetMode == DataTargetMode.Node ? ["https://" + item.ExpectedNodeId!.Split(':')[0] + ":4057"] : ["https://source-1:4057", "https://source-2:4057"]; + } + if (root.TryGetProperty("consistency", out var consistency)) item.Consistency = Enum.Parse(consistency.GetString()!); + if (root.TryGetProperty("connection_allowed_operations", out var connectionOps)) item.AllowedOperations = (DataOperations)connectionOps.GetInt32(); + if (root.TryGetProperty("connection_enabled", out var enabled)) item.Enabled = enabled.GetBoolean(); + if (root.TryGetProperty("consumer_node_ids", out var consumers)) item.ConsumerNodeIds = consumers.EnumerateArray().Select(x => x.GetString()!).ToList(); + var mutationMappings = await db.RemoteNamespaceMappings.Where(x => x.DataConnectionId == connectionId).ToListAsync(); + foreach (var mapping in mutationMappings) + { + FixtureMutationRevisions.InheritConsumerPlacement(root, item, mapping); + if (root.TryGetProperty("mapping_enabled", out var mappingEnabled)) mapping.Enabled = mappingEnabled.GetBoolean(); + if (root.TryGetProperty("write_through", out var write)) mapping.WriteThrough = write.GetBoolean(); + if (root.TryGetProperty("allowed_operations", out var ops)) mapping.AllowedOperations = (DataOperations)ops.GetInt32(); + } + var selectedExport = root.TryGetProperty("export_id", out var exportId) ? exportId.GetString() : null; + var mutationExports = await db.DataExports.Where(x => selectedExport == null || x.DataExportId == selectedExport).ToListAsync(); + foreach (var export in mutationExports) + { + if (root.TryGetProperty("export_enabled", out var exportEnabled)) export.Enabled = exportEnabled.GetBoolean(); + if (root.TryGetProperty("export_allowed_operations", out var ops)) export.AllowedOperations = (DataOperations)ops.GetInt32(); + } + var revisionReceipt = FixtureMutationRevisions.Advance(root, item, mutationMappings, mutationExports); + foreach (var cluster in await db.ServerClusters.ToListAsync()) + { + var field = cluster.ClusterId.ToLowerInvariant() + "_redundancy_mode"; + if (root.TryGetProperty(field, out var redundancy)) cluster.RedundancyMode = Enum.Parse(redundancy.GetString()!); + } + if (root.TryGetProperty("rename_tag", out var rename)) + { + var tag = await db.Tags.SingleAsync(x => x.TagId == rename.GetProperty("tag_id").GetString()); + tag.Name = rename.GetProperty("name").GetString()!; + } + if (root.TryGetProperty("upsert_tag", out var newTag)) + { + var candidate = newTag.Deserialize() ?? throw new InvalidOperationException(); + candidate.TagRowId = Guid.NewGuid(); + db.Tags.Add(candidate); + } + if (root.TryGetProperty("upsert_reference", out var newReference)) + { + var candidate = newReference.Deserialize() ?? throw new InvalidOperationException(); + if (!root.TryGetProperty("upsert_tag", out var pairedTag) + || candidate.TagId != pairedTag.GetProperty("TagId").GetString() + || candidate.UnsTagReferenceId != "ref-" + candidate.TagId + || !await db.Equipment.AnyAsync(x => x.EquipmentId == candidate.EquipmentId)) + throw new InvalidOperationException("new fixture reference must accompany its local tag"); + candidate.UnsTagReferenceRowId = Guid.NewGuid(); + db.UnsTagReferences.Add(candidate); + } + if (root.TryGetProperty("remove_tag_id", out var removeTag)) + { + await db.UnsTagReferences.Where(x => x.TagId == removeTag.GetString()).ExecuteDeleteAsync(); + await db.Tags.Where(x => x.TagId == removeTag.GetString()).ExecuteDeleteAsync(); + } + if (root.TryGetProperty("disable_feature", out var disable) && disable.GetBoolean()) + { + foreach (var row in await db.DataConnections.ToListAsync()) { row.Enabled = false; row.Revision++; } + foreach (var row in await db.RemoteNamespaceMappings.ToListAsync()) { row.Enabled = false; row.Revision++; } + foreach (var row in await db.DataExports.ToListAsync()) { row.Enabled = false; row.Revision++; } + } + await db.SaveChangesAsync(); + var errors = DraftValidator.Validate(await DraftSnapshotFactory.FromConfigDbAsync(db)); + if (errors.Count != 0) + { + await Save("rejection.json", new { validator = "DraftValidator", codes = errors.Select(error => error.Code).Distinct().ToArray() }); + throw new InvalidOperationException("production mutation validation failed"); + } + await transaction.CommitAsync(); + if (revisionReceipt.CredentialOnly) + await Save("mutation-revisions.json", new { keyAction = root.GetProperty("key_action").GetString(), revisions = revisionReceipt }); + if (root.TryGetProperty("key_action", out var action)) + { + var admin = new ApiKeyAdminService(factory, pepper); + var old = (await File.ReadAllTextAsync(Path.Combine(output, "source.key"))).Trim(); + if (action.GetString() is "rotate" or "rotate_staged" or "expire") + { + await SaveText("source-previous.key", old); + await SaveText("source.key", await admin.CreateAsync("source-issued-rotated", "fixture-consumer", + action.GetString() == "expire" ? DateTime.UtcNow.AddSeconds(root.TryGetProperty("key_expiry_seconds", out var seconds) ? seconds.GetInt32() : 10) : null, "local rotation", default)); + if (action.GetString() != "rotate_staged") await admin.SetEnabledAsync(old.Split('_')[1], false, default); + } + else if (action.GetString() == "retire_old") + await admin.SetEnabledAsync((await File.ReadAllTextAsync(Path.Combine(output, "source-previous.key"))).Trim().Split('_')[1], false, default); + else if (action.GetString() == "revoke") await admin.SetEnabledAsync(old.Split('_')[1], false, default); + else throw new InvalidOperationException("unknown key mutation"); + } + return 0; + } + if (args[0] != "seed") return 2; + await using (var db = await factory.CreateDbContextAsync()) + { + if (await db.ServerClusters.AnyAsync()) throw new InvalidOperationException("fixture seed requires empty owned database"); + foreach (var cluster in new[] { "CONTROL", "SOURCE", "CONSUMER" }) + { + db.ServerClusters.Add(new() { ClusterId = cluster, Name = cluster, Enterprise = "zb", Site = "local", NodeCount = 2, + RedundancyMode = RedundancyMode.Hot, CreatedBy = "grpc-data-local-gate" }); + foreach (var node in nodes.Where(x => x.StartsWith(cluster.ToLowerInvariant() + "-", StringComparison.Ordinal))) + db.ClusterNodes.Add(new() { NodeId = node + ":4053", ClusterId = cluster, Host = node, OpcUaPort = 4840, DashboardPort = 9000, + GrpcPort = 4056, ApplicationUri = "urn:OtOpcUa:grpc-data:" + node, CreatedBy = "grpc-data-local-gate" }); + db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "cli-" + cluster, ClusterId = cluster, + Principal = "fixture-cli", ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Admin }); + } + db.DriverInstances.Add(new() { DriverInstanceRowId = Guid.NewGuid(), DriverInstanceId = "source-modbus", ClusterId = "SOURCE", Name = "modbus", DriverType = "Modbus", + DriverConfig = """{"TimeoutMs":2000,"AutoReconnect":true,"Probe":{"Enabled":true,"ProbeAddress":0}}""" }); + db.Devices.Add(new() { DeviceRowId = Guid.NewGuid(), DeviceId = "source-device", DriverInstanceId = "source-modbus", Name = "plc", + DeviceConfig = """{"Host":"device","Port":5020,"UnitId":1}""" }); + db.PollGroups.Add(new() { PollGroupRowId = Guid.NewGuid(), PollGroupId = "source-fast", DriverInstanceId = "source-modbus", Name = "fast", IntervalMs = 200 }); + foreach (var (name, address, writable) in new[] { ("counter", 0, false), ("scalar", 20, true), ("array0", 10, false), ("array1", 11, false), ("array2", 12, false) }) + db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-" + name, DeviceId = "source-device", Name = name, DataType = "UInt16", + AccessLevel = writable ? TagAccessLevel.ReadWrite : TagAccessLevel.Read, WriteIdempotent = false, PollGroupId = "source-fast", + TagConfig = JsonSerializer.Serialize(new { region = "HoldingRegisters", address, dataType = "UInt16", writable }) }); + db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-vector", DeviceId = "source-device", Name = "vector", DataType = "UInt16", + AccessLevel = TagAccessLevel.ReadWrite, WriteIdempotent = false, PollGroupId = "source-fast", + TagConfig = """{"region":"HoldingRegisters","address":24,"dataType":"UInt16","isArray":true,"arrayLength":3,"writable":true}""" }); + db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-text", DeviceId = "source-device", Name = "text", DataType = "String", + AccessLevel = TagAccessLevel.ReadWrite, WriteIdempotent = false, PollGroupId = "source-fast", + TagConfig = """{"region":"HoldingRegisters","address":40,"dataType":"String","stringLength":16,"writable":true}""" }); + db.UnsAreas.Add(new() { UnsAreaRowId = Guid.NewGuid(), UnsAreaId = "source-area", ClusterId = "SOURCE", Name = "area" }); + db.UnsLines.Add(new() { UnsLineRowId = Guid.NewGuid(), UnsLineId = "source-line", UnsAreaId = "source-area", Name = "line" }); + var uuid = Guid.NewGuid(); + var equipment = DraftValidator.DeriveEquipmentId(uuid); + db.Equipment.Add(new() { EquipmentRowId = Guid.NewGuid(), EquipmentId = equipment, EquipmentUuid = uuid, UnsLineId = "source-line", Name = "plc", MachineCode = "fixture-plc" }); + foreach (var name in new[] { "counter", "scalar", "array0", "array1", "array2", "vector", "text" }) + db.UnsTagReferences.Add(new() { UnsTagReferenceRowId = Guid.NewGuid(), UnsTagReferenceId = "ref-" + name, EquipmentId = equipment, TagId = "source-" + name }); + db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "source-peer", ClusterId = "SOURCE", Principal = "fixture-consumer", + ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Admin }); + db.DataConnections.Add(new() { DataConnectionRowId = Guid.NewGuid(), DataConnectionId = "consumer-source", ClusterId = "CONSUMER", Enabled = true, + ConsumerNodeIds = ["consumer-1:4053", "consumer-2:4053"], TargetMode = DataTargetMode.Cluster, ExpectedClusterId = "SOURCE", + EligibleTargetNodeIds = ["source-1:4053", "source-2:4053"], Endpoints = ["https://source-1:4057", "https://source-2:4057"], + SecretReference = "secret:data/source", SecretScopeClusterId = "CONSUMER", AllowedOperations = operations, + TimeoutMilliseconds = 30000 }); + foreach (var realm in new[] { DataRealm.Raw, DataRealm.Uns }) + { + var name = realm.ToString().ToLowerInvariant(); + var rootKind = realm == DataRealm.Raw ? "RawDevice" : "Equipment"; + var entity = realm == DataRealm.Raw ? "source-device" : equipment; + db.DataExports.Add(new() { DataExportRowId = Guid.NewGuid(), DataExportId = "export-" + name, ClusterId = "SOURCE", Enabled = true, + Realm = realm, RootKind = rootKind, RootEntityId = entity, PrincipalId = "fixture-consumer", AllowedOperations = operations }); + db.RemoteNamespaceMappings.Add(new() { RemoteNamespaceMappingRowId = Guid.NewGuid(), RemoteNamespaceMappingId = "map-" + name, + ClusterId = "CONSUMER", DataConnectionId = "consumer-source", Enabled = true, ConsumerNodeIds = ["consumer-1:4053", "consumer-2:4053"], + Realm = realm, RemoteRealm = realm, LocalParentKind = "Cluster", LocalParentId = "CONSUMER", BranchName = "remote-source", + RemoteRootEntityId = entity, RemoteNamespaceUri = realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri, + RemoteIdentifierKind = "string", RemoteIdentifier = realm == DataRealm.Raw ? "modbus/plc" : equipment, AllowedOperations = operations, WriteThrough = true }); + } + await db.SaveChangesAsync(); + } + var seedAdmin = new ApiKeyAdminService(factory, pepper); + await SaveText("cli.key", await seedAdmin.CreateAsync("fixture-cli", "fixture-cli", null, "owned local fixture", default)); + await SaveText("source.key", await seedAdmin.CreateAsync("source-issued-consumer", "fixture-consumer", null, "SOURCE grants for CONSUMER", default)); + string unsBrowseRoot; + await using (var db = await factory.CreateDbContextAsync()) + { + var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(db); + var errors = DraftValidator.Validate(snapshot).Concat(snapshot.ServerClusters.SelectMany(cluster => DraftValidator.ValidateClusterTopology(cluster, snapshot.ClusterNodes.Where(node => node.ClusterId == cluster.ClusterId).ToList()))).ToList(); + if (errors.Count != 0) throw new InvalidOperationException("production validator rejected fixture"); + unsBrowseRoot = await db.Equipment.Select(item => item.EquipmentId).SingleAsync(); + } + await Save("fixture.json", new { connection_id = "consumer-source", mapping_ids = new[] { "map-raw", "map-uns" }, + namespace_uris = new { raw = V3NodeIds.RawNamespaceUri, uns = V3NodeIds.UnsNamespaceUri, mapped_raw = ProjectedDataIds.RawNamespaceUri, mapped_uns = ProjectedDataIds.UnsNamespaceUri }, + browse_roots = new { raw = "modbus/plc", uns = unsBrowseRoot }, + browse_subjects = new { raw = "modbus/plc", uns = "area/line/plc" }, + origin_paths = new { raw = "modbus/plc/scalar", uns = "area/line/plc/scalar", raw_array = "modbus/plc/vector", uns_array = "area/line/plc/vector", raw_string = "modbus/plc/text", uns_string = "area/line/plc/text" }, aliases = new[] { "raw", "uns" } }); + return 0; +} +catch (Exception error) +{ + // Only the restricted run-owned output receives diagnostics. Console output + // remains safe for Docker orchestration, which can contain credential args. + try { await SaveText("last-error.txt", error.ToString()[..Math.Min(error.ToString().Length, 16384)]); } + catch (Exception) { /* Preserve the original failure and redacted console. */ } + Console.Error.WriteLine("grpc-data fixture helper failed; secret-bearing diagnostics withheld"); + return 1; +} + +async Task Save(string name, object body) => await SaveText(name, JsonSerializer.Serialize(body)); +async Task SaveText(string name, string text) +{ + Directory.CreateDirectory(output); + var path = Path.Combine(output, name); + var temporary = Path.Combine(output, "." + name + "." + Guid.NewGuid().ToString("N")); + var fileOptions = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write }; + if (!OperatingSystem.IsWindows()) fileOptions.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; + await using (var file = new FileStream(temporary, fileOptions)) + await using (var writer = new StreamWriter(file)) { await writer.WriteAsync(text); } + File.Move(temporary, path, true); +} + +async Task RestoreRows(OtOpcUaConfigDbContext db, DbSet set, List baseline, Func identity) where T : class +{ + var rows = await set.ToListAsync(); + foreach (var row in rows.Where(row => !baseline.Any(candidate => identity(candidate) == identity(row)))) set.Remove(row); + foreach (var candidate in baseline) + { + var current = rows.SingleOrDefault(row => identity(row) == identity(candidate)); + if (current is null) { set.Add(candidate); continue; } + var entry = db.Entry(current); + var previousRevision = entry.Metadata.FindProperty("Revision") is not null ? (long)entry.Property("Revision").CurrentValue! : 0; + var preserved = entry.Metadata.FindPrimaryKey()!.Properties.Select(property => property.Name).Append("RowVersion") + .Where(name => entry.Metadata.FindProperty(name) is not null).ToDictionary(name => name, name => entry.Property(name).CurrentValue); + entry.CurrentValues.SetValues(candidate); + if (entry.Metadata.FindProperty("Revision") is not null) + entry.Property("Revision").CurrentValue = checked(Math.Max(previousRevision, (long)entry.Property("Revision").CurrentValue!) + 1); + foreach (var property in preserved) entry.Property(property.Key).CurrentValue = property.Value; + } +} diff --git a/scripts/validation/grpc-data/tests/test_bundle_commit_orchestration.py b/scripts/validation/grpc-data/tests/test_bundle_commit_orchestration.py new file mode 100644 index 000000000..34d4713c5 --- /dev/null +++ b/scripts/validation/grpc-data/tests/test_bundle_commit_orchestration.py @@ -0,0 +1,105 @@ +"""Exact deployed bundle acknowledgements use pure file-probe fakes, never a live host.""" +import json +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import rig + + +def expectation(node="consumer-1", deleted=False): + return {"node": node, "connectionId": "consumer-source", "scopeVersion": 9, + "credentialVersion": 12, "trustVersion": 12, "credentialDeleted": deleted, "trustRetired": False} + + +def observed(deleted=False): + return {"credentialScopeVersion": 9, "trustScopeVersion": 9, "credentialVersion": 12, + "trustVersion": 12, "credentialDeleted": deleted, "trustRetired": False} + + +def scope_only(): + return {"node": "consumer-1", "connectionId": "fixture-scope-only", "kind": "scope-only", "scopeVersion": 9, + "credentialVersion": None, "trustVersion": None, "credentialDeleted": None, "trustRetired": None} + + +class BundleCommitOrchestrationTests(unittest.TestCase): + def scope(self): + return {"scope_version": 9, "required_node_ids": ["consumer-1:4053"], + "connections": [{"connection_id": "consumer-source", "consumer_node_ids": ["consumer-1:4053", "consumer-2:4053"]}]} + + def test_requires_only_actual_enabled_scope_entries_on_required_consumers(self): + wanted = expectation() + self.assertEqual(rig.deployment_bundle_expectations(self.scope(), [wanted, expectation("consumer-2")]), [wanted]) + with self.assertRaises(rig.RigError): + rig.deployment_bundle_expectations(self.scope(), []) + scope = self.scope() + scope["connections"] = [] + self.assertEqual(rig.deployment_bundle_expectations(scope, [scope_only()]), [scope_only()]) + with self.assertRaises(rig.RigError): + rig.deployment_bundle_expectations(scope, []) + + def test_scope_only_requires_both_exact_scope_commits_without_claiming_a_key(self): + ready = {"credentialScopeVersion": 9, "trustScopeVersion": 9, + "credentialVersion": None, "trustVersion": None, "credentialDeleted": None, "trustRetired": None} + self.assertTrue(rig.bundle_commit_matches(scope_only(), ready)) + for fields in ({"credentialScopeVersion": 8}, {"trustScopeVersion": 10}, {"trustScopeVersion": None}, + {"credentialScopeVersion": None}, {"credentialVersion": 12}, {"credentialDeleted": False}): + with self.subTest(fields=fields): + self.assertFalse(rig.bundle_commit_matches(scope_only(), {**ready, **fields})) + + def test_deletion_requires_exact_committed_tombstone_and_live_trust(self): + expected = expectation(deleted=True) + self.assertTrue(rig.bundle_commit_matches(expected, observed(deleted=True))) + for fields in ({"credentialVersion": None}, {"credentialDeleted": None}, {"credentialDeleted": False}, + {"credentialVersion": 11}, {"trustVersion": 11}, {"trustRetired": True}): + with self.subTest(fields=fields): + self.assertFalse(rig.bundle_commit_matches(expected, {**observed(deleted=True), **fields})) + + def test_pending_ack_retries_and_persists_only_exact_numeric_versions_and_flags(self): + with tempfile.TemporaryDirectory() as directory: + instance = object.__new__(rig.LocalRig) + instance.folder = Path(directory) + (instance.folder / "probe" / "consumer-1").mkdir(parents=True) + (instance.folder / "seed").mkdir() + writes = [] + original_write = rig.atomic_write_secret + def write(path, text): + original_write(path, text) + if str(path).endswith(".request.json"): + request = json.loads(text) + writes.append(request) + observation = {key: None for key in observed()} if len(writes) == 1 else {**observed(), "secret": "must-not-copy"} + output = {"id": request["id"], "operation": "bundle-commit", "passed": True, + "assertions": 1, "observations": observation} + original_write(Path(str(path).replace(".request.json", ".result.json")), json.dumps(output)) + with patch.object(rig, "atomic_write_secret", side_effect=write), patch.object(rig.time, "sleep"): + records = instance.wait_bundle_commits([expectation()], timeout=2) + self.assertEqual(len(writes), 2) + self.assertEqual(records[0]["observed"], observed()) + self.assertTrue(records[0]["matched"]) + self.assertNotIn("must-not-copy", (instance.folder / "seed" / "bundle-commit-readiness.json").read_text()) + + def test_empty_inventory_records_zero_entries_without_claiming_any_key_commit(self): + with tempfile.TemporaryDirectory() as directory: + instance = object.__new__(rig.LocalRig) + instance.folder = Path(directory) + (instance.folder / "seed").mkdir() + self.assertEqual(instance.wait_bundle_commits([], timeout=1), []) + self.assertEqual(json.loads((instance.folder / "seed" / "bundle-commit-readiness.json").read_text()), + {"required_entries": 0, "entries": []}) + + def test_pending_ack_cannot_outlive_the_shared_deadline(self): + with tempfile.TemporaryDirectory() as directory: + instance = object.__new__(rig.LocalRig) + instance.folder = Path(directory) + (instance.folder / "probe" / "consumer-1").mkdir(parents=True) + (instance.folder / "seed").mkdir() + with patch.object(rig.time, "monotonic", side_effect=[0, 0, 2]), self.assertRaises(rig.RigError): + instance.wait_bundle_commits([expectation()], timeout=1) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/validation/grpc-data/tests/test_cli_gate.py b/scripts/validation/grpc-data/tests/test_cli_gate.py index feca19247..e66ddaff7 100644 --- a/scripts/validation/grpc-data/tests/test_cli_gate.py +++ b/scripts/validation/grpc-data/tests/test_cli_gate.py @@ -110,14 +110,85 @@ class ProcessSafetyTests(unittest.TestCase): self.assertTrue(process.terminate.called or process.kill.called) self.assertNotIn(KEY, str(raised.exception)) + def test_live_output_observer_receives_only_redacted_text(self): + observed = [] + output, _ = self.run_process(self.fake_process(stdout=(KEY + " ready\n").encode()), + observer=lambda stream, chunk: observed.append((stream, chunk))) + self.assertTrue(observed) + self.assertNotIn(KEY, repr(observed)) + self.assertIn("[REDACTED]", output.stdout) + + def test_invalid_observer_cannot_start_a_child(self): + factory = Mock() + with self.assertRaises(processes.ProcessError): + processes.run_process(["dotnet", "unit.dll"], timeout=1, observer="invalid", popen=factory) + factory.assert_not_called() + class CliContentGateTests(unittest.TestCase): + def test_cancelled_exit_zero_cannot_satisfy_success_or_denial_validators(self): + cancelled = processes.ProcessResult(argv=("unit",), returncode=0, stdout="Write failed: BadUserAccessDenied", + stderr="", timed_out=False, truncated=False, duration_seconds=.1, cancelled=True) + checks = (lambda: cli_gate._process_ok(cancelled), + lambda: cli_gate.validate_read(cancelled, expected_node=NODE), + lambda: cli_gate.validate_write(cancelled, expected_node=NODE), + lambda: cli_gate.validate_browse(cancelled, expected_nodes={NODE}), + lambda: cli_gate.validate_connect(cancelled, expected_endpoint="opc.tcp://127.0.0.1:52113"), + lambda: cli_gate.validate_subscription(cancelled, summary_text="", expected_nodes={NODE}), + lambda: cli_gate.validate_recovery_subscription(cancelled, summary_text="", expected_node=NODE, require_gap=True), + lambda: cli_gate.validate_denial(cancelled, command="write", expected_statuses={"BadUserAccessDenied"})) + for check in checks: + with self.subTest(check=check), self.assertRaisesRegex(cli_gate.CliGateError, "cancel"): + check() + + def test_recovery_requires_quality_gap_and_changing_final_good_updates(self): + text = summary().replace("Ever went BAD during window: 0", "Ever went BAD during window: 1") + output = subscription_output().replace(summary(), text) + second = f"[2026-11-16T00:00:01.0000000Z] {NODE} = 2 (Good)" + output = output.replace(second, f"[2026-11-16T00:00:00.5000000Z] {NODE} = 0 (BadNoCommunication)\n" + second) + self.assertEqual(cli_gate.validate_recovery_subscription(result(output), summary_text=text, + expected_node=NODE, require_gap=True)["summary"]["ever_bad"], 1) + warning = "[00:00:02 WRN] Session lost on opc.tcp://127.0.0.1:40001/OtOpcUa. Attempting failover...\n" + with self.assertRaisesRegex(cli_gate.CliGateError, "started transport failover"): + cli_gate.validate_recovery_subscription(result(output.replace(second, warning + second)), summary_text=text, + expected_node=NODE, require_gap=True, require_held_session=True) + self.assertEqual(cli_gate.validate_recovery_subscription(result(output + warning), summary_text=text, + expected_node=NODE, require_gap=True, require_held_session=True)["summary"]["ever_bad"], 1) + for output, summary_text in ((subscription_output(), summary()), + (subscription_output(values=(1, 1)).replace(summary(), text), text), + (subscription_output(attached=0).replace(summary(), text), text)): + with self.assertRaises(cli_gate.CliGateError): + cli_gate.validate_recovery_subscription(result(output), summary_text=summary_text, expected_node=NODE, require_gap=True) + def test_namespace_resolution_uses_uri_instead_of_fixed_index(self): + self.assertEqual(cli_gate.resolve_node_id(["standard", "other", "urn:raw"], "urn:raw", "device/scalar"), "ns=2;s=device/scalar") + self.assertEqual(cli_gate.resolve_node_id(["standard", "urn:raw", "other"], "urn:raw", "device/scalar"), "ns=1;s=device/scalar") + for uris in (["standard"], ["standard", "urn:raw", "urn:raw"]): + with self.assertRaises(cli_gate.CliGateError): + cli_gate.resolve_node_id(uris, "urn:raw", "device/scalar") + + def test_browse_requires_actual_expected_children(self): + text = f"[Object] plc (NodeId: ns=7;s=unit/device)\n [Variable] scalar (NodeId: {NODE})\n" + self.assertEqual(cli_gate.validate_browse(result(text), expected_nodes={NODE})["count"], 2) + for output in (result(""), result("No nodes"), result(text.replace(NODE, "ns=2;s=other"))): + with self.assertRaises(cli_gate.CliGateError): + cli_gate.validate_browse(output, expected_nodes={NODE}) + + def test_explicit_denial_is_not_an_arbitrary_process_failure(self): + cli_gate.validate_denial(result("Write failed: BadUserAccessDenied"), command="write", expected_statuses={"BadUserAccessDenied"}) + for output in (result("", stderr="connection failed", returncode=1), + result("Write failed: BadUserAccessDenied", timed_out=True), + result(f"Write successful: {NODE} = 42\nBadUserAccessDenied")): + with self.assertRaises(cli_gate.CliGateError): + cli_gate.validate_denial(output, command="write", expected_statuses={"BadUserAccessDenied"}) + def test_good_read_requires_matching_node_value_status_and_timestamps(self): text = (f"Node: {NODE}\nValue: 42\nStatus: Good\n" "Source Time: 2026-11-16T00:00:00.0000000Z\nServer Time: 2026-11-16T00:00:00.0000000Z\n") evidence = cli_gate.validate_read(result(text), expected_node=NODE) self.assertEqual(evidence["value"], "42") self.assertEqual(evidence["status"], "Good") + self.assertEqual(cli_gate.validate_read(result(text.replace("Status: Good", "Status: Good [0x00000000]")), expected_node=NODE)["status"], "Good") + self.assertFalse(cli_gate.is_good_status("Good [0x80000000]")) def test_exit_zero_bad_uncertain_or_missing_read_fields_fail(self): for text in (f"Node: {NODE}\nValue: \nStatus: BadUserAccessDenied (BadUserAccessDenied)\n", @@ -183,9 +254,25 @@ class CliContentGateTests(unittest.TestCase): self.assertEqual(argv[argv.index("-n") + 1], NODE) self.assertNotIn("--json", argv) self.assertNotIn(KEY, repr(processes.redact_argv(argv))) + argv = cli_gate.build_cli_argv(Path("/unit/tools/cli.dll"), "read", "opc.tcp://127.0.0.1:52113", KEY, + node=NODE, max_age_ms=5000) + self.assertEqual(argv[argv.index("--max-age") + 1], "5000") def test_cli_builder_rejects_exe_rebuilds_and_remote_endpoint(self): for dll, url in ((Path("/unit/tools/tool.exe"), "opc.tcp://127.0.0.1:52113"), (Path("/unit/tools/tool.dll"), "opc.tcp://10.100.0.35:4840")): with self.subTest(dll=dll, url=url), self.assertRaises(cli_gate.CliGateError): cli_gate.build_cli_argv(dll, "read", url, KEY, node=NODE) + + def test_cli_write_builder_uses_known_fixture_uint16_without_read_inference(self): + argv = cli_gate.build_cli_argv(Path("/unit/tools/cli.dll"), "write", + "opc.tcp://127.0.0.1:52113", KEY, node=NODE, value=65535) + self.assertEqual(argv[argv.index("--type") + 1], "UInt16") + self.assertEqual(argv[argv.index("-v") + 1], "65535") + self.assertEqual(argv[argv.index("-n") + 1], NODE) + self.assertEqual(argv.count("--type"), 1) + + def test_cli_read_builder_does_not_add_write_type(self): + argv = cli_gate.build_cli_argv(Path("/unit/tools/cli.dll"), "read", + "opc.tcp://127.0.0.1:52113", KEY, node=NODE) + self.assertNotIn("--type", argv) diff --git a/scripts/validation/grpc-data/tests/test_compose_fixture.py b/scripts/validation/grpc-data/tests/test_compose_fixture.py index 65c4a4a27..362032231 100644 --- a/scripts/validation/grpc-data/tests/test_compose_fixture.py +++ b/scripts/validation/grpc-data/tests/test_compose_fixture.py @@ -65,15 +65,32 @@ class StandaloneComposeContractTests(unittest.TestCase): def test_local_sql_device_and_generated_tls_mounts(self): self.assertIn(" sql:", self.compose) self.assertIn(" device:", self.compose) + data = extension_block(self.compose, "x-data-env") + self.assertIn('DataConnections__Enabled: "true"', data) + self.assertIn('DataConnections__ListenPort: "4057"', data) + self.assertIn('DataConnections__CertificatePath: /run/grpc-data/tls/server.pem', data) + self.assertIn('DataConnections__CertificateKeyPath: /run/grpc-data/tls/server.key', data) + self.assertIn('DataConnections__CredentialBundlePath: /run/grpc-data/credentials/bundle.json', data) + self.assertIn('DataConnections__TrustBundlePath: /run/grpc-data/credentials/trust.json', data) for node in ("source-1", "source-2", "consumer-1", "consumer-2"): block = service_block(self.compose, node) self.assertIn("GRPC_DATA_CERT_DIR", block) self.assertIn("/run/grpc-data/tls", block) - self.assertIn("P07_TLS_BINDING_PENDING", self.compose) + self.assertIn(f"DataConnections__AllowedHosts__0: {node}", block) + self.assertRegex(block, rf"GRPC_DATA_CREDENTIAL_DIR[^\n]+/{node}:/run/grpc-data/credentials:ro") + self.assertNotIn("P07_TLS_BINDING_PENDING", self.compose) self.assertIn("device:5020", self.compose) self.assertRegex(self.compose, r"127\.0\.0\.1::(?:4840|9000)") self.assertNotRegex(self.compose, r"(?m)^\s+- ['\"]?0\.0\.0\.0:") + def test_seeder_and_probe_are_fixture_only_and_source_contents_are_identified(self): + self.assertIn("SOURCE_TREE_HASH", self.dockerfile) + self.assertIn("grpc-data-source.json", self.dockerfile) + self.assertIn("target: seeder", self.compose) + self.assertIn("ASPNETCORE_HOSTINGSTARTUPASSEMBLIES: GrpcDataNodeProbe", self.compose) + for node in ("control-1", "control-2", "source-1", "source-2", "consumer-1", "consumer-2"): + self.assertIn("/grpc-data-probe", service_block(self.compose, node)) + def test_no_tracked_secrets_or_private_keys(self): for line in self.compose.splitlines(): match = re.match(r"^\s*(?:SA_PASSWORD|ZB_SECRETS_MASTER_KEY|Security__ApiKeys__Pepper):\s*(.*)$", line) diff --git a/scripts/validation/grpc-data/tests/test_consumer_failover_preparation.py b/scripts/validation/grpc-data/tests/test_consumer_failover_preparation.py new file mode 100644 index 000000000..439d33017 --- /dev/null +++ b/scripts/validation/grpc-data/tests/test_consumer_failover_preparation.py @@ -0,0 +1,63 @@ +"""The automatic CLI partner is prepared last before each measured consumer failover.""" +from contextlib import nullcontext +from pathlib import Path +import sys +import unittest +from unittest.mock import Mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import scenarios + + +class ConsumerFailoverPreparationTests(unittest.TestCase): + def runner(self, *, source_changed=False): + runner = object.__new__(scenarios.ScenarioRunner) + runner.manifest = {"nodes": {"consumer-1": {}, "consumer-2": {}}} + runner.primary = Mock(return_value="consumer-1") + runner.node_id = Mock(side_effect=lambda node: node + ":4053") + runner.cli, runner.mutate, runner.record_matrix_cell, runner.save = Mock(), Mock(), Mock(), Mock() + runner.timeline = [] + calls = [] + runner.prepare_positive_projection = Mock(side_effect=lambda node, realm: calls.append(("prepare", node, realm))) + runner.changing = Mock(side_effect=lambda: nullcontext()) + runner.wait_primary = Mock(return_value="consumer-2") + runner.wait_connection_ready = Mock() + def probe(node, operation, realm="raw", **fields): + return {"serving": {"nodeId": "source-2:4053" if source_changed and operation == "read" else "source-1:4053"}} + runner.probe = Mock(side_effect=probe) + def check(valid, message): + if not valid: + raise scenarios.ScenarioError(message) + runner.check = Mock(side_effect=check) + def fault(node, fault_node, *, realm, on_fault, **fields): + calls.append(("automatic-failover", node, realm)) + on_fault() + return {"temporal": {"fault_at": 10, "notifications": []}} + runner.live_cli_fault = Mock(side_effect=fault) + return runner, calls + + def test_both_eligible_nodes_are_prepared_partner_last_before_each_realm_fault(self): + runner, calls = self.runner() + runner.scenario_D10() + self.assertEqual(calls, [(operation, node, realm) for realm in ("raw", "uns") + for operation, node in (("prepare", "consumer-1"), ("prepare", "consumer-2"), ("automatic-failover", "consumer-1"))]) + for realm in ("raw", "uns"): + runner.live_cli_fault.assert_any_call("consumer-1", "consumer-1", partner="consumer-2", + require_gap=False, on_fault=next(call.kwargs["on_fault"] for call in runner.live_cli_fault.call_args_list + if call.kwargs["realm"] == realm), realm=realm) + self.assertEqual(runner.record_matrix_cell.call_count, 2) + + def test_same_source_and_unmounted_partner_negative_checks_remain_required(self): + runner, _ = self.runner() + runner.scenario_D10() + runner.mutate.assert_called_once_with(consumer_node_ids=["consumer-1:4053"]) + runner.probe.assert_any_call("consumer-2", "capabilities", expected_state="Unavailable") + for realm in ("raw", "uns"): + runner.cli.assert_any_call("read", "consumer-2", realm, denial=True) + changed, _ = self.runner(source_changed=True) + with self.assertRaisesRegex(scenarios.ScenarioError, "SOURCE serving node stayed fixed"): + changed.scenario_D10() + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/validation/grpc-data/tests/test_control_outage_preparation.py b/scripts/validation/grpc-data/tests/test_control_outage_preparation.py new file mode 100644 index 000000000..c05a32917 --- /dev/null +++ b/scripts/validation/grpc-data/tests/test_control_outage_preparation.py @@ -0,0 +1,69 @@ +"""D11 prepares each positive mapped operation through authenticated offline discovery.""" +from contextlib import contextmanager, nullcontext +from pathlib import Path +import sys +import unittest +from unittest.mock import Mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import scenarios + + +class ControlOutagePreparationTests(unittest.TestCase): + def runner(self): + runner = object.__new__(scenarios.ScenarioRunner) + runner.timeline = [] + runner.primary = Mock(side_effect=lambda pair: pair + "-1") + runner.device = Mock(return_value={"effect_total": 12}) + runner.wait_primary = Mock() + runner.check = Mock(side_effect=lambda valid, message: self.assertTrue(valid, message)) + runner.changing = Mock(side_effect=lambda: nullcontext()) + state = {"controls_offline": False} + @contextmanager + def stopped(*nodes): + self.assertEqual(nodes, ("control-1", "control-2")) + state["controls_offline"] = True + try: + yield + finally: + state["controls_offline"] = False + runner.stopped = stopped + return runner, state + + def test_both_realms_browse_while_controls_offline_immediately_before_each_mapped_positive(self): + runner, state = self.runner() + events = [] + def prepare(node, realm): + self.assertTrue(state["controls_offline"]) + events.append(("authenticated browse", node, realm)) + runner.prepare_positive_projection = Mock(side_effect=prepare) + def cli(operation, node, realm): + self.assertTrue(state["controls_offline"]) + if node == "consumer-1": + self.assertEqual(events[-1:], [("authenticated browse", node, realm)]) + events.append((operation, node, realm)) + runner.cli = Mock(side_effect=cli) + runner.scenario_D11() + self.assertEqual(runner.prepare_positive_projection.call_count, 4) + for realm in ("raw", "uns"): + for operation in ("read", "subscribe"): + index = events.index((operation, "consumer-1", realm)) + self.assertEqual(events[index - 1], ("authenticated browse", "consumer-1", realm)) + records = [row for row in runner.timeline if row["event"] == "control-outage-projection-prepared"] + self.assertEqual([(row["realm"], row["operation"]) for row in records], + [("raw", "read"), ("raw", "subscribe"), ("uns", "read"), ("uns", "subscribe")]) + self.assertFalse(state["controls_offline"]) + runner.wait_primary.assert_called_once_with("control") + + def test_failed_authenticated_browse_prevents_mapped_positive_and_restores_controls(self): + runner, state = self.runner() + runner.prepare_positive_projection = Mock(side_effect=scenarios.ScenarioError("authenticated browse rejected")) + runner.cli = Mock() + with self.assertRaisesRegex(scenarios.ScenarioError, "authenticated browse rejected"): + runner.scenario_D11() + self.assertFalse(state["controls_offline"]) + self.assertTrue(all(call.args[1] != "consumer-1" for call in runner.cli.call_args_list)) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/validation/grpc-data/tests/test_credentials.py b/scripts/validation/grpc-data/tests/test_credentials.py new file mode 100644 index 000000000..77280a3c2 --- /dev/null +++ b/scripts/validation/grpc-data/tests/test_credentials.py @@ -0,0 +1,118 @@ +"""Run-local certificate and restricted bundle provisioning checks.""" +import importlib.util +import json +import socket +import ssl +from pathlib import Path +import subprocess +import sys +import tempfile +import threading +import unittest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import credentials + + +class CredentialFixtureTests(unittest.TestCase): + def test_generated_leaf_has_subject_and_authority_key_identifiers(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) / "run" + credentials.provision_tls(root, ["source-1"]) + certificate = root / "tls" / "source-1" / "server.pem" + result = subprocess.run(["openssl", "x509", "-in", str(certificate), "-noout", "-text"], + capture_output=True, timeout=10) + self.assertEqual(result.returncode, 0) + self.assertIn(b"X509v3 Subject Key Identifier", result.stdout) + self.assertIn(b"X509v3 Authority Key Identifier", result.stdout) + + def test_generated_leaf_passes_real_strict_python_tls_with_hostname_validation(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) / "run" + credentials.provision_tls(root, ["source-1"]) + server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + server_context.load_cert_chain(root / "tls/source-1/server.pem", root / "tls/source-1/server.key") + client_context = ssl.create_default_context(cafile=str(root / "ca.pem")) + client_context.verify_flags |= ssl.VERIFY_X509_STRICT + self.assertTrue(client_context.check_hostname) + self.assertEqual(client_context.verify_mode, ssl.CERT_REQUIRED) + errors = [] + with socket.socket() as listener: + listener.bind(("127.0.0.1", 0)) + listener.listen(1) + listener.settimeout(3) + def serve(): + try: + connection, _ = listener.accept() + with connection, server_context.wrap_socket(connection, server_side=True) as channel: + channel.settimeout(3) + channel.recv(1) + channel.sendall(b"x") + except (OSError, ssl.SSLError) as error: + errors.append(type(error).__name__) + worker = threading.Thread(target=serve, daemon=True) + worker.start() + try: + with socket.create_connection(listener.getsockname(), timeout=3) as connection: + with client_context.wrap_socket(connection, server_hostname="source-1") as channel: + channel.sendall(b"x") + self.assertEqual(channel.recv(1), b"x") + finally: + worker.join(timeout=4) + self.assertFalse(worker.is_alive()) + self.assertEqual(errors, []) + + def test_generated_certificate_has_only_requested_node_identity_and_trusted_chain(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) / "run" + credentials.provision(root, {"consumer-1": {"owner": "CONSUMER", "scope_version": 7, + "entries": [{"ConnectionId": "source", "SecretReference": "secret:data/source", "Value": "fixture-only", "Deleted": False}]}}) + certificate = root / "tls" / "consumer-1" / "server.pem" + result = subprocess.run(["openssl", "verify", "-CAfile", str(root / "ca.pem"), + "-verify_hostname", "consumer-1", str(certificate)], capture_output=True, timeout=10) + self.assertEqual(result.returncode, 0) + wrong = subprocess.run(["openssl", "verify", "-CAfile", str(root / "ca.pem"), + "-verify_hostname", "source-1", str(certificate)], capture_output=True, timeout=10) + self.assertNotEqual(wrong.returncode, 0) + for path in root.rglob("*"): + self.assertEqual(path.stat().st_mode & 0o777, 0o700 if path.is_dir() else 0o600) + bundle = json.loads((root / "credentials" / "consumer-1" / "bundle.json").read_text()) + trust = json.loads((root / "credentials" / "consumer-1" / "trust.json").read_text()) + self.assertEqual(bundle["ConsumerNode"], "consumer-1:4053") + self.assertEqual(bundle["ScopeVersion"], 7) + self.assertEqual(trust["Entries"][0]["ConnectionId"], "source") + self.assertNotIn("fixture-only", (root / "credentials" / "consumer-1" / "trust.json").read_text()) + with self.assertRaises(FileExistsError): + credentials.provision(root, {}) + + def test_invalid_node_or_secret_scope_is_rejected_before_creating_files(self): + for node, entry in [("../escape", {}), ("consumer-1", {"owner": "CONSUMER", "scope_version": 0, "entries": []}), + ("consumer-1", {"owner": "CONSUMER", "scope_version": 1, "entries": [{"ConnectionId": "x", "SecretReference": "secret:../x", "Value": "x", "Deleted": False}]})]: + with self.subTest(node=node, entry=entry), tempfile.TemporaryDirectory() as folder: + root = Path(folder) / "run" + with self.assertRaises(ValueError): credentials.provision(root, {node: entry}) + self.assertFalse(root.exists()) + + def test_tls_can_precede_deployment_but_bundles_require_authoritative_scope(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) / "run" + credentials.provision_tls(root, ["consumer-1"]) + self.assertTrue((root / "tls" / "consumer-1" / "server.pem").is_file()) + self.assertFalse((root / "credentials").exists()) + with self.assertRaises(ValueError): + credentials.write_bundles(root, {"consumer-1": {"owner": "CONSUMER", "scope_version": 0, "entries": []}}) + credentials.write_bundles(root, {"consumer-1": {"owner": "CONSUMER", "scope_version": 9, "entries": []}}) + bundle = json.loads((root / "credentials" / "consumer-1" / "bundle.json").read_text()) + self.assertEqual(bundle["ScopeVersion"], 9) + self.assertEqual((root / "credentials").stat().st_mode & 0o777, 0o700) + + def test_explicit_deletion_bundle_is_supported_for_real_provisioner_negative_case(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) / "run" + credentials.provision(root, {"consumer-1": {"owner": "CONSUMER", "scope_version": 7, + "bundle_version": 4, "entries": [{"ConnectionId": "source", "SecretReference": "secret:data/source", "Value": None, "Deleted": True}]}}) + bundle = json.loads((root / "credentials" / "consumer-1" / "bundle.json").read_text()) + self.assertEqual(bundle["Version"], 4) + self.assertIsNone(bundle["Entries"][0]["Value"]) + self.assertTrue(bundle["Entries"][0]["Deleted"]) diff --git a/scripts/validation/grpc-data/tests/test_d06_pinned_export_denial.py b/scripts/validation/grpc-data/tests/test_d06_pinned_export_denial.py new file mode 100644 index 000000000..b05624113 --- /dev/null +++ b/scripts/validation/grpc-data/tests/test_d06_pinned_export_denial.py @@ -0,0 +1,73 @@ +"""D06 isolates a real origin denial from cluster partner-selection fallbacks.""" +from pathlib import Path +import sys +import unittest +from unittest.mock import Mock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import scenarios + + +class PinnedExportDenialTests(unittest.TestCase): + def runner(self, *, fail_read=False): + runner = object.__new__(scenarios.ScenarioRunner) + runner.primary = Mock(side_effect=lambda pair: pair + "-1") + runner.node_id = Mock(side_effect=lambda node: node + ":4053") + runner.prepare_positive_projection, runner.cli, runner.save, runner.baseline = Mock(), Mock(), Mock(), Mock() + runner.remaining = Mock(side_effect=lambda maximum: maximum) + runner.check = Mock() + runner.device = Mock(return_value={"effect_total": 10}) + runner.relative_node = Mock(side_effect=lambda node, realm, name: realm + "/" + name) + runner.manifest = {"fixture": {"browse_roots": {"raw": "modbus/plc", "uns": "equipment"}, + "origin_paths": {"raw": "modbus/plc/scalar", "uns": "area/line/plc/scalar"}}} + runner.rig = Mock(folder=Path("/owned")) + events, active = [], [False] + def mutate(**fields): + if fields.get("export_allowed_operations") == 3: + active[0] = True + self.assertEqual(fields, {"export_allowed_operations": 3, "target_mode": "Node", + "target_node_id": "source-1:4053", "consistency": "Primary", "connection_allowed_operations": scenarios.OPERATIONS}) + events.append("pinned denial setup") + elif active[0] and fields.get("export_allowed_operations") == scenarios.OPERATIONS: + self.assertEqual(fields.get("target_mode"), "Cluster") + self.assertEqual(fields.get("consistency"), "Primary") + raise RuntimeError("pinned denial phase complete") + runner.mutate = Mock(side_effect=mutate) + def ready(node, realm="raw", **fields): + self.assertEqual(fields, {"expected_node": "source-1"}) + events.append(("ready", realm)) + runner.wait_connection_ready = Mock(side_effect=ready) + def probe(node, operation, realm="raw", **fields): + if active[0]: + self.assertEqual(node, "consumer-1") + self.assertEqual(events[-1:], [("ready", realm)]) + self.assertEqual(fields.get("expectedNodeId"), "source-1:4053") + self.assertEqual(fields.get("expectedRole"), "Primary") + self.assertEqual(fields.get("expected_state"), "Denied" if operation == "read" else "RejectedBeforeDispatch") + events.append((operation, realm)) + if fail_read: + raise scenarios.ScenarioError("actual denial proof failed") + return {"lease": {"duration": "00:00:15"}} + runner.probe = Mock(side_effect=probe) + return runner, events + + def test_both_realms_pin_actual_primary_and_confirm_ready_before_real_denied_operations(self): + runner, events = self.runner() + with patch.object(scenarios, "restricted_json", return_value={"Exports": []}), \ + patch.object(scenarios.time, "sleep"), self.assertRaisesRegex(RuntimeError, "pinned denial phase complete"): + runner.scenario_D06() + self.assertEqual(events, ["pinned denial setup", ("ready", "raw"), ("read", "raw"), + ("ready", "raw"), ("write", "raw"), ("ready", "uns"), ("read", "uns"), ("ready", "uns"), ("write", "uns")]) + runner.check.assert_any_call(True, "origin operation-mask write denial has zero physical effects") + + def test_failed_actual_denial_does_not_continue_to_key_rotation(self): + runner, events = self.runner(fail_read=True) + with patch.object(scenarios, "restricted_json", return_value={"Exports": []}), \ + patch.object(scenarios.time, "sleep"), self.assertRaisesRegex(scenarios.ScenarioError, "actual denial proof failed"): + runner.scenario_D06() + self.assertFalse(any("key_action" in call.kwargs for call in runner.mutate.call_args_list)) + self.assertNotIn(("write", "raw"), events) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/validation/grpc-data/tests/test_d07_projected_read_order.py b/scripts/validation/grpc-data/tests/test_d07_projected_read_order.py new file mode 100644 index 000000000..da10bf9ba --- /dev/null +++ b/scripts/validation/grpc-data/tests/test_d07_projected_read_order.py @@ -0,0 +1,93 @@ +"""D07 waits for unchanged monitored-item recovery before its required mapped Read.""" +from contextlib import contextmanager +from pathlib import Path +import sys +import unittest +from unittest.mock import Mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import scenarios + + +class ProjectedReadRecoveryOrderTests(unittest.TestCase): + def runner(self, *, fail_live=False, fail_read=False): + runner = object.__new__(scenarios.ScenarioRunner) + runner.manifest = {"nodes": {"source-1": {}, "source-2": {}, "consumer-1": {}}} + runner.primary = Mock(side_effect=lambda pair: pair + "-1") + runner.node_id = Mock(side_effect=lambda node: node + ":4053") + runner.wait_connection_ready, runner.prepare_positive_projection = Mock(), Mock() + runner.wait_primary = Mock(return_value="source-2") + runner.check = Mock(side_effect=lambda valid, message: self.assertTrue(valid, message)) + runner.mutate = Mock(side_effect=RuntimeError("D07 positive phase complete")) + events, state = [], {"in_live": False, "live_complete": set()} + @contextmanager + def changing(): + yield + runner.changing = Mock(side_effect=changing) + def probe(node, operation, realm, **fields): + if operation == "read": + self.assertTrue(state["in_live"]) + events.append(("direct fresh Read", realm)) + return {"limits": {"maxMetadataLease": "00:00:15"}, "serving": { + "nodeId": "source-2:4053" if operation == "read" else "source-1:4053", + "servingGeneration": 2 if operation == "read" else 1}} + runner.probe = Mock(side_effect=probe) + def live(*args, **fields): + realm = fields["realm"] + state["in_live"] = True + try: + fields["on_fault"]() + if fail_live: + raise scenarios.ScenarioError("unchanged monitored-item recovery failed") + events.append(("held sentinel and post-lease progress verified", realm)) + state["live_complete"].add(realm) + fields["after_validated_recovery"]() + return {"sentinel": {"verified": True}, "post_lease_progress": {"verified": True}} + finally: + state["in_live"] = False + events.append(("old SOURCE restored", realm)) + runner.live_cli_fault = Mock(side_effect=live) + def cli(operation, node, realm, **fields): + self.assertTrue(state["in_live"], "mapped Read must run while the old SOURCE is still stopped") + self.assertIn(realm, state["live_complete"]) + self.assertEqual((operation, node), ("read", "consumer-1")) + events.append(("required mapped Read", realm)) + if fail_read: + raise scenarios.ScenarioError("mapped Read failed") + return {"status": "Good"} + runner.cli = Mock(side_effect=cli) + def record(*args, **fields): + realm = args[3] + self.assertEqual(events[-2:], [("required mapped Read", realm), ("old SOURCE restored", realm)]) + events.append(("record successful recovery", realm)) + runner.record_matrix_cell = Mock(side_effect=record) + return runner, events + + def test_both_realms_require_mapped_read_only_after_complete_live_recovery_proof(self): + runner, events = self.runner() + with self.assertRaisesRegex(RuntimeError, "D07 positive phase complete"): + runner.scenario_D07() + self.assertEqual(events, [(label, realm) for realm in ("raw", "uns") for label in + ("direct fresh Read", "held sentinel and post-lease progress verified", "required mapped Read", + "old SOURCE restored", "record successful recovery")]) + self.assertEqual(runner.prepare_positive_projection.call_count, 2) + self.assertEqual(runner.cli.call_count, 2) + + def test_partial_direct_read_success_never_records_mapped_or_live_recovery_success(self): + runner, events = self.runner(fail_live=True) + with self.assertRaisesRegex(scenarios.ScenarioError, "unchanged monitored-item recovery failed"): + runner.scenario_D07() + runner.cli.assert_not_called() + runner.record_matrix_cell.assert_not_called() + self.assertEqual(events, [("direct fresh Read", "raw"), ("old SOURCE restored", "raw")]) + + def test_failed_mapped_read_restores_source_without_recording_success(self): + runner, events = self.runner(fail_read=True) + with self.assertRaisesRegex(scenarios.ScenarioError, "mapped Read failed"): + runner.scenario_D07() + runner.record_matrix_cell.assert_not_called() + self.assertEqual(events[-2:], [("required mapped Read", "raw"), ("old SOURCE restored", "raw")]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/validation/grpc-data/tests/test_endpoint_refresh.py b/scripts/validation/grpc-data/tests/test_endpoint_refresh.py new file mode 100644 index 000000000..eeb45dde8 --- /dev/null +++ b/scripts/validation/grpc-data/tests/test_endpoint_refresh.py @@ -0,0 +1,131 @@ +"""Partial endpoint refresh inspects only exact owned services; no Docker is started.""" +from copy import deepcopy +import json +from pathlib import Path +import sys +import unittest +from unittest.mock import Mock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import rig + + +RUN = "unit-refresh" + + +def manifest(): + endpoints = {} + for index, node in enumerate(rig.NODES): + ports = [(4840, "opcua", "opc.tcp"), (9000, "admin", "http")] + if not node.startswith("control-"): + ports.append((4057, "data", "https")) + for offset, (port, suffix, scheme) in enumerate(ports): + allocated = 51000 + index * 10 + offset + endpoints[node + "." + suffix] = {"scheme": scheme, "host": "127.0.0.1", "host_port": allocated, + "container_host": node, "container_port": port, + "url": f"{scheme}://127.0.0.1:{allocated}" + ("/OtOpcUa" if port == 4840 else "")} + return {"schema_version": 1, "run_id": RUN, "project": "grpc-data-" + RUN, + "labels": {rig.RUN_LABEL: RUN, rig.PROJECT_LABEL: "grpc-data-" + RUN}, "services": list(rig.SERVICES), + "endpoints": endpoints, "resources": [], "state": "ready", + "nodes": {node: {"cluster_id": node.split("-")[0].upper(), "application_uri": "urn:unit:" + node} + for node in rig.NODES}, "deployment": {"revision_hash": "unchanged"}, + "credentials": {"marker": "unchanged"}, "resolved_nodes": {"marker": "unchanged"}} + + +def inspected(node): + ports = (4840, 9000) if node.startswith("control-") else (4840, 9000, 4057) + offset = rig.NODES.index(node) * 10 + return {"Config": {"Labels": {rig.RUN_LABEL: RUN, rig.PROJECT_LABEL: "grpc-data-" + RUN, + "com.docker.compose.service": node}}, "State": {"Running": True}, + "NetworkSettings": {"Ports": {str(port) + "/tcp": [{"HostIp": "127.0.0.1", "HostPort": str(52000 + offset + i)}] + for i, port in enumerate(ports)}}} + + +class EndpointRefreshTests(unittest.TestCase): + def instance(self): + instance = object.__new__(rig.LocalRig) + instance.run_id, instance.project = RUN, "grpc-data-" + RUN + instance.docker = ["docker", "--context", "unit-local"] + instance.load = Mock(return_value=manifest()) + instance.save = Mock() + instance.compose = Mock(side_effect=lambda *args: "container-" + args[-1]) + return instance + + def inspect(self, argv): + return json.dumps([inspected(argv[-1].removeprefix("container-"))]) + + def test_refreshes_selected_ports_and_preserves_stopped_control_and_manifest_fields(self): + instance = self.instance() + original = deepcopy(instance.load.return_value) + with patch.object(rig, "run_command", side_effect=self.inspect): + updated = instance.refresh_endpoints(("source-1",)) + self.assertNotEqual(updated["endpoints"]["source-1.admin"], original["endpoints"]["source-1.admin"]) + self.assertEqual(updated["endpoints"]["source-1.opcua"]["url"], "opc.tcp://127.0.0.1:52020/OtOpcUa") + for key, value in original["endpoints"].items(): + if not key.startswith("source-1."): + self.assertEqual(updated["endpoints"][key], value) + for field in ("deployment", "credentials", "resolved_nodes", "state"): + self.assertEqual(updated[field], original[field]) + instance.compose.assert_called_once_with("ps", "--all", "--quiet", "source-1") + self.assertEqual(instance.load.return_value, original) + instance.save.assert_called_once_with(updated) + + def test_control_refresh_requires_only_its_two_published_ports(self): + instance = self.instance() + with patch.object(rig, "run_command", side_effect=self.inspect): + updated = instance.refresh_endpoints(("control-1",)) + self.assertEqual(updated["endpoints"]["control-1.admin"]["host_port"], 52001) + self.assertNotIn("control-1.data", updated["endpoints"]) + + def test_invalid_node_selection_fails_before_inspecting_or_saving(self): + for nodes in ((), ("unknown",), ("source-1", "source-1"), "source-1"): + instance = self.instance() + with self.subTest(nodes=nodes), self.assertRaises(rig.RigError): + instance.refresh_endpoints(nodes) + instance.compose.assert_not_called() + instance.save.assert_not_called() + + def test_ownership_running_state_and_complete_loopback_bindings_are_required(self): + def label(key, value): + return lambda row: row["Config"]["Labels"].update({key: value}) + changes = [label(rig.RUN_LABEL, "other"), label(rig.PROJECT_LABEL, "other"), + label("com.docker.compose.service", "source-2"), + lambda row: row["State"].update(Running=False), + lambda row: row["NetworkSettings"]["Ports"].pop("4057/tcp"), + lambda row: row["NetworkSettings"]["Ports"].update({"4057/tcp": None}), + lambda row: row["NetworkSettings"]["Ports"]["4057/tcp"][0].update(HostIp="0.0.0.0"), + lambda row: row["NetworkSettings"]["Ports"]["4057/tcp"][0].update(HostPort="0"), + lambda row: row["NetworkSettings"]["Ports"]["4057/tcp"].append({"HostIp": "127.0.0.1", "HostPort": "53000"})] + for change in changes: + instance = self.instance() + row = inspected("source-1") + change(row) + with self.subTest(change=change), patch.object(rig, "run_command", return_value=json.dumps([row])), self.assertRaises(rig.RigError): + instance.refresh_endpoints(("source-1",)) + instance.save.assert_not_called() + + def test_missing_or_duplicate_service_container_fails_without_save(self): + for ids in ("", "first second"): + instance = self.instance() + instance.compose.return_value, instance.compose.side_effect = ids, None + with self.subTest(ids=ids), self.assertRaises(rig.RigError): + instance.refresh_endpoints(("source-1",)) + instance.save.assert_not_called() + + def test_second_invalid_node_cannot_partially_mutate_or_save_manifest(self): + instance = self.instance() + original = deepcopy(instance.load.return_value) + def inspect(argv): + node = argv[-1].removeprefix("container-") + row = inspected(node) + if node == "source-2": + row["State"]["Running"] = False + return json.dumps([row]) + with patch.object(rig, "run_command", side_effect=inspect), self.assertRaises(rig.RigError): + instance.refresh_endpoints(("source-1", "source-2")) + self.assertEqual(instance.load.return_value, original) + instance.save.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/validation/grpc-data/tests/test_export_withdrawal_fixtures.py b/scripts/validation/grpc-data/tests/test_export_withdrawal_fixtures.py new file mode 100644 index 000000000..2cddbb551 --- /dev/null +++ b/scripts/validation/grpc-data/tests/test_export_withdrawal_fixtures.py @@ -0,0 +1,79 @@ +"""Narrowed exports and disabled connections remain legal, measured fixture configurations.""" +from pathlib import Path +import sys +import unittest +from unittest.mock import Mock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import scenarios + + +class ExportWithdrawalFixtureTests(unittest.TestCase): + def d06_runner(self): + runner = object.__new__(scenarios.ScenarioRunner) + runner.primary = Mock(return_value="consumer-1") + runner.mutate, runner.prepare_positive_projection, runner.cli, runner.save = Mock(), Mock(), Mock(), Mock() + runner.probe = Mock(return_value={"lease": {"duration": "00:00:15"}}) + runner.remaining = Mock(side_effect=lambda value: value) + runner.check = Mock() + runner.device = Mock(return_value={"effect_total": 0}) + runner.relative_node = Mock(side_effect=lambda node, realm, name: realm + "/" + name) + runner.manifest = {"fixture": {"browse_roots": {"raw": "modbus/plc", "uns": "equipment"}, + "origin_paths": {"raw": "modbus/plc/scalar", "uns": "area/line/plc/scalar"}}} + runner.rig = Mock(folder=Path("/owned")) + runner.baseline = Mock(side_effect=RuntimeError("narrowed export phase complete")) + return runner + + def run_d06_narrowing(self): + runner = self.d06_runner() + exports = [{"DataExportId": "export-raw", "Realm": 1, "RootKind": "RawDevice", "RootEntityId": "source-device", "AllowedOperations": 31}, + {"DataExportId": "export-uns", "Realm": 2, "RootKind": "Equipment", "RootEntityId": "equipment", "AllowedOperations": 31}] + with patch.object(scenarios, "restricted_json", return_value={"Exports": exports}), \ + patch.object(scenarios.time, "sleep"), self.assertRaisesRegex(RuntimeError, "narrowed export phase complete"): + runner.scenario_D06() + return runner, exports + + def test_d06_keeps_parent_metadata_only_and_adds_distinct_scalar_grants(self): + runner, baseline = self.run_d06_narrowing() + authored = [call.kwargs["upsert_export"] for call in runner.mutate.call_args_list if "upsert_export" in call.kwargs] + self.assertEqual(len(authored), 4) + for parent in baseline: + actual = next(item for item in authored if item["DataExportId"] == parent["DataExportId"]) + self.assertEqual(actual["RootKind"], parent["RootKind"]) + self.assertEqual(actual["RootEntityId"], parent["RootEntityId"]) + self.assertEqual(actual["AllowedOperations"], 2) + leaf = next(item for item in authored if item["Realm"] == parent["Realm"] and item["DataExportId"] != parent["DataExportId"]) + self.assertEqual(leaf["RootKind"], "RawTag" if parent["Realm"] == 1 else "UnsTagReference") + self.assertEqual(leaf["RootEntityId"], "source-scalar" if parent["Realm"] == 1 else "ref-scalar") + self.assertEqual(leaf["AllowedOperations"], scenarios.OPERATIONS) + + def test_d06_checks_counter_reads_and_writes_are_denied_without_device_effects(self): + runner, _ = self.run_d06_narrowing() + for realm, counter in (("raw", "modbus/plc/counter"), ("uns", "area/line/plc/counter")): + runner.probe.assert_any_call("consumer-1", "read", realm, path=counter, expected_state="Denied") + runner.probe.assert_any_call("consumer-1", "write", realm, path=counter, expected_state="RejectedBeforeDispatch") + self.assertGreaterEqual(runner.device.call_count, 4) + self.assertTrue(any("effect" in call.args[1] for call in runner.check.call_args_list)) + + def test_d12_disables_dependent_mappings_with_the_connection(self): + runner = object.__new__(scenarios.ScenarioRunner) + runner.primary = Mock(side_effect=lambda pair: pair + "-1") + runner.node_id = Mock(side_effect=lambda node: node + ":4053") + runner.manifest = {"nodes": {"consumer-1": {}, "consumer-2": {}}, "deployment": { + "nodes": [{"nodeId": "source-1:4053", "status": "Applied"}], "required_node_ids": ["source-1:4053"]}} + def mutate(**fields): + if "connection_enabled" in fields: + raise RuntimeError("disabled connection mutation observed") + runner.mutate = Mock(side_effect=mutate) + runner.cli, runner.check, runner.baseline = Mock(), Mock(), Mock() + runner.probe = Mock(side_effect=lambda node, operation, **fields: + {"authenticatedSnapshotReceived": True} if operation == "legacy-telemetry" else {"connections": []}) + runner.remaining = Mock(return_value=1) + with self.assertRaisesRegex(RuntimeError, "disabled connection mutation observed"): + runner.scenario_D12() + self.assertEqual(runner.mutate.call_args.kwargs, {"connection_enabled": False, "mapping_enabled": False}) + self.assertEqual(runner.baseline.call_count, 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/validation/grpc-data/tests/test_extended_source_outage.py b/scripts/validation/grpc-data/tests/test_extended_source_outage.py new file mode 100644 index 000000000..6c861ce3c --- /dev/null +++ b/scripts/validation/grpc-data/tests/test_extended_source_outage.py @@ -0,0 +1,284 @@ +"""D07 holds both sources unavailable before recovery and proves progress beyond a lease.""" +from contextlib import contextmanager, nullcontext +import json +from pathlib import Path +import sys +import unittest +from unittest.mock import Mock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import scenarios + + +class PostLeaseProgressTests(unittest.TestCase): + def test_ordinary_wrap_is_recorded_but_high_initial_sentinel_is_not_an_ordinary_wrap(self): + producer = scenarios.ControlledFixtureSource(Mock(), 32766, set()) + producer.tick() + producer.tick() + self.assertEqual(producer.current, 0) + self.assertEqual(producer.ordinary_wrap_count, 1) + high_initial = scenarios.ControlledFixtureSource(Mock(), 65535, set()) + high_initial.tick() + self.assertEqual(high_initial.current, 0) + self.assertEqual(high_initial.ordinary_wrap_count, 0) + + def test_wrapped_ordinary_sequence_cannot_prove_unqueued_post_lease_values(self): + rows = [{"at": 11, "value": "32766", "status": "Good"}, + {"at": 12, "value": "32767", "status": "Good"}] + for wraps in (1, True, -1, None): + with self.subTest(wraps=wraps), self.assertRaises(scenarios.ScenarioError): + scenarios.validate_post_lease_progress(rows, boundary_at=10, ordinary_floor=0, ordinary_wrap_count=wraps) + + def test_only_two_fresh_distinct_ordinary_values_above_boundary_floor_count(self): + rows = [{"at": 9, "value": "999", "status": "Good"}, + {"at": 11, "value": "65535", "status": "Good"}, + {"at": 12, "value": "51", "status": "Good"}, + {"at": 13, "value": "52", "status": "Good"}] + receipt = scenarios.validate_post_lease_progress(rows, boundary_at=10, ordinary_floor=50, ordinary_wrap_count=0) + self.assertEqual(receipt["ordinary_values"], [51, 52]) + self.assertEqual(receipt["boundary_at"], 10) + + def test_queued_sentinel_duplicate_old_or_bad_values_cannot_prove_post_lease_progress(self): + cases = ([{"at": 9, "value": "51", "status": "Good"}, {"at": 9.5, "value": "52", "status": "Good"}], + [{"at": 11, "value": "65534", "status": "Good"}, {"at": 12, "value": "65535", "status": "Good"}], + [{"at": 11, "value": "51", "status": "Good"}, {"at": 12, "value": "51", "status": "Good"}], + [{"at": 11, "value": "49", "status": "Good"}, {"at": 12, "value": "50", "status": "Good"}], + [{"at": 11, "value": "51", "status": "BadNoCommunication"}, {"at": 12, "value": "52", "status": "Good"}]) + for rows in cases: + with self.subTest(rows=rows), self.assertRaises(scenarios.ScenarioError): + scenarios.validate_post_lease_progress(rows, boundary_at=10, ordinary_floor=50, ordinary_wrap_count=0) + + +class OwnedSourcePauseTests(unittest.TestCase): + def runner(self): + runner = object.__new__(scenarios.ScenarioRunner) + runner.active = "D07" + labels = {scenarios.rig.RUN_LABEL: "unit", scenarios.rig.PROJECT_LABEL: "grpc-data-unit", + "com.docker.compose.service": "source-2"} + identity = "2" * 64 + resource = {"kind": "container", "id": identity, "labels": labels} + runner.manifest = {"run_id": "unit", "project": "grpc-data-unit", "nodes": {"source-1": {}, "source-2": {}}, + "resources": [resource]} + runner.timeline, runner.save = [], Mock() + runner.remaining = Mock(return_value=1) + runner.rig = Mock(docker=["docker", "--context", "unit"]) + runner.rig.inspect_resources.return_value = [resource] + state = {"Running": True, "Paused": False, "Pid": 77, "StartedAt": "2026-11-17T00:00:00Z"} + def compose(verb, node, **kwargs): + self.assertEqual(node, "source-2") + if verb in {"pause", "unpause"}: + state["Paused"] = verb == "pause" + return "" + runner.rig.compose.side_effect = compose + def inspect(argv, **kwargs): + self.assertEqual(argv[-3:], ["container", "inspect", identity]) + return json.dumps([{"Id": identity, "Config": {"Labels": labels}, "State": state}]) + return runner, state, inspect + + def test_pause_resumes_same_owned_process_and_finally_rechecks_identity(self): + runner, state, inspect = self.runner() + with patch.object(scenarios.rig, "run_command", side_effect=inspect): + with runner.paused("source-2") as resume: + self.assertTrue(state["Paused"]) + receipt = resume() + self.assertFalse(state["Paused"]) + self.assertEqual(receipt["process_id_before"], 77) + self.assertEqual(receipt["process_id_after"], 77) + self.assertGreaterEqual(runner.rig.inspect_resources.call_count, 3) + self.assertEqual([call.args[0] for call in runner.rig.compose.call_args_list], ["pause", "unpause"]) + + def test_cleanup_attempts_unpause_and_preserves_original_body_failure(self): + runner, state, inspect = self.runner() + original = runner.rig.compose.side_effect + def compose(verb, node, **kwargs): + if verb == "unpause": + raise RuntimeError("cleanup failure") + return original(verb, node, **kwargs) + runner.rig.compose.side_effect = compose + with patch.object(scenarios.rig, "run_command", side_effect=inspect), self.assertRaisesRegex(RuntimeError, "original body"): + with runner.paused("source-2"): + raise RuntimeError("original body") + self.assertTrue(any(call.args[0] == "unpause" for call in runner.rig.compose.call_args_list)) + + def test_foreign_or_replaced_container_cannot_be_paused_or_unpaused(self): + runner, state, inspect = self.runner() + runner.rig.inspect_resources.return_value = [{"kind": "container", "id": "f" * 64, + "labels": {"com.docker.compose.service": "source-2"}}] + with patch.object(scenarios.rig, "run_command", side_effect=inspect), self.assertRaises(scenarios.ScenarioError): + with runner.paused("source-2"): + self.fail("foreign pause entered") + runner.rig.compose.assert_not_called() + + def test_cleanup_rejects_foreign_replacement_and_preserves_original_failure(self): + runner, state, inspect = self.runner() + with patch.object(scenarios.rig, "run_command", side_effect=inspect), self.assertRaisesRegex(RuntimeError, "original body"): + with runner.paused("source-2"): + runner.rig.inspect_resources.return_value = [{"kind": "container", "id": "f" * 64, + "labels": {"com.docker.compose.service": "source-2"}}] + raise RuntimeError("original body") + self.assertEqual([call.args[0] for call in runner.rig.compose.call_args_list], ["pause"]) + self.assertGreaterEqual(runner.rig.inspect_resources.call_count, 2) + + def test_resume_rejects_a_changed_process_identity(self): + runner, state, inspect = self.runner() + original = runner.rig.compose.side_effect + def compose(verb, node, **kwargs): + result = original(verb, node, **kwargs) + if verb == "unpause": + state["Pid"] = 78 + return result + runner.rig.compose.side_effect = compose + with patch.object(scenarios.rig, "run_command", side_effect=inspect), self.assertRaises(scenarios.ScenarioError): + with runner.paused("source-2") as resume: + resume() + + +class ExtendedSourceOutageTests(unittest.TestCase): + def test_outage_gate_accepts_early_shutdown_bad_only_while_it_remains_latest(self): + rows = [{"at": 8, "status": "Good"}, {"at": 9.5, "status": "BadNoCommunication"}] + self.assertEqual(scenarios.validate_source_outage_notification(rows, stop_requested_at=9, stop_completed_at=10), 9.5) + for invalid in ([{"at": 8, "status": "BadNoCommunication"}], + rows + [{"at": 10.5, "status": "Good"}], + [{"at": float("nan"), "status": "BadNoCommunication"}]): + with self.subTest(invalid=invalid), self.assertRaises(scenarios.ScenarioError): + scenarios.validate_source_outage_notification(invalid, stop_requested_at=9, stop_completed_at=10) + for requested, completed in ((11, 10), (float("nan"), 10), (9, float("inf"))): + with self.subTest(requested=requested, completed=completed), self.assertRaises(scenarios.ScenarioError): + scenarios.validate_source_outage_notification(rows, stop_requested_at=requested, stop_completed_at=completed) + + def test_outage_wait_records_request_and_completed_primary_stop_boundaries(self): + runner = object.__new__(scenarios.ScenarioRunner) + runner.timeline = [] + runner.paused = Mock(return_value=nullcontext(Mock(return_value={}))) + runner.stopped = Mock(return_value=nullcontext()) + waiter = Mock(return_value=12) + with patch.object(scenarios.time, "monotonic", side_effect=[9, 10]): + with runner.extended_source_outage("source-1", "source-2", wait_for_non_good=waiter) as receipt: + self.assertEqual(receipt["primary_stop_requested_at"], 9) + self.assertEqual(receipt["both_sources_unavailable_at"], 10) + waiter.assert_called_once_with(stop_requested_at=9, stop_completed_at=10) + + def test_pre_outage_or_nonfinite_notification_cannot_satisfy_outage_gate(self): + for arrival in (9, float("nan"), float("inf")): + runner = object.__new__(scenarios.ScenarioRunner) + runner.timeline = [] + runner.paused = Mock(return_value=nullcontext(Mock(return_value={}))) + runner.stopped = Mock(return_value=nullcontext()) + with self.subTest(arrival=arrival), patch.object(scenarios.time, "monotonic", side_effect=[10, 11]), self.assertRaises(scenarios.ScenarioError): + with runner.extended_source_outage("source-1", "source-2", wait_for_non_good=Mock(return_value=arrival)): + pass + + def test_nested_stop_cleanup_preserves_original_and_still_unpauses_partner(self): + for failed_operation in ("start", "refresh"): + with self.subTest(failed_operation=failed_operation): + runner = object.__new__(scenarios.ScenarioRunner) + runner.active, runner.timeline, runner.save = "D07", [], Mock() + runner.manifest = {"run_id": "unit", "nodes": {"source-1": {}, "source-2": {}}} + runner.remaining = Mock(return_value=1) + runner.check = Mock(side_effect=lambda valid, message: self.assertTrue(valid, message)) + runner.rig = Mock() + runner.rig.inspect_resources.return_value = [{"labels": {scenarios.rig.RUN_LABEL: "unit"}}] + def compose(verb, *args, **kwargs): + if verb == "start" and failed_operation == "start": + raise ValueError("cleanup private text must not be recorded") + runner.rig.compose.side_effect = compose + runner.rig.refresh_endpoints.side_effect = ValueError("cleanup private text") if failed_operation == "refresh" else None + runner.rig.refresh_endpoints.return_value = runner.manifest + events = [] + @contextmanager + def paused(node): + try: + yield Mock(return_value={}) + finally: + events.append("partner unpause attempted") + runner.paused = paused + def bad(*args, **kwargs): + raise RuntimeError("original outage assertion") + with self.assertRaisesRegex(RuntimeError, "original outage assertion"): + with runner.extended_source_outage("source-1", "source-2", wait_for_non_good=bad): + self.fail("outage body must not run") + self.assertEqual(events, ["partner unpause attempted"]) + runner.rig.refresh_endpoints.assert_called_once_with(("source-1",)) + cleanup = next(row for row in runner.timeline if row["event"] == "stop-cleanup") + self.assertEqual(cleanup["original_error"], "RuntimeError") + self.assertEqual(cleanup["cleanup_errors"], [{"operation": failed_operation, "type": "ValueError"}]) + self.assertNotIn("private", json.dumps(cleanup)) + + def test_successful_body_cannot_hide_stop_cleanup_failure(self): + runner = object.__new__(scenarios.ScenarioRunner) + runner.active, runner.timeline, runner.save = "D07", [], Mock() + runner.manifest = {"run_id": "unit", "nodes": {"source-1": {}}} + runner.remaining, runner.check, runner.rig = Mock(return_value=1), Mock(), Mock() + runner.rig.inspect_resources.return_value = [{"labels": {scenarios.rig.RUN_LABEL: "unit"}}] + runner.rig.compose.side_effect = lambda verb, *args, **kwargs: (_ for _ in ()).throw(ValueError()) if verb == "start" else None + runner.rig.refresh_endpoints.return_value = runner.manifest + with self.assertRaises(scenarios.ScenarioError): + with runner.stopped("source-1"): + pass + runner.rig.refresh_endpoints.assert_called_once_with(("source-1",)) + + def test_partner_stays_paused_until_actual_non_good_then_recovers_while_primary_stopped(self): + runner = object.__new__(scenarios.ScenarioRunner) + runner.timeline = [] + calls = [] + resume = Mock(side_effect=lambda: calls.append("resume partner") or {"process_id_before": 77, "process_id_after": 77}) + resume.receipt = {"process_id_before": 77} + @contextmanager + def paused(node): + self.assertEqual(node, "source-2") + calls.append("pause partner") + try: + yield resume + finally: + calls.append("verify resumed") + @contextmanager + def stopped(node): + self.assertEqual(node, "source-1") + calls.append("stop primary") + try: + yield + finally: + calls.append("start primary") + runner.paused, runner.stopped = paused, stopped + def bad(*args, **kwargs): + calls.append("actual nonGood") + return 12.5 + with patch.object(scenarios.time, "monotonic", side_effect=[10, 11]): + with runner.extended_source_outage("source-1", "source-2", wait_for_non_good=bad): + calls.append("recovery and held sentinel") + self.assertEqual(calls, ["pause partner", "stop primary", "actual nonGood", "resume partner", + "recovery and held sentinel", "start primary", "verify resumed"]) + + def test_d07_opts_into_extended_outage_and_post_lease_progress_for_both_realms(self): + runner = object.__new__(scenarios.ScenarioRunner) + runner.manifest = {"nodes": {"source-1": {}, "source-2": {}, "consumer-1": {}}} + runner.primary = Mock(side_effect=lambda pair: pair + "-1") + runner.node_id = Mock(side_effect=lambda node: node + ":4053") + runner.wait_connection_ready, runner.prepare_positive_projection, runner.cli = Mock(), Mock(), Mock() + runner.wait_primary = Mock(return_value="source-2") + runner.check = Mock(side_effect=lambda valid, message: self.assertTrue(valid, message)) + runner.record_matrix_cell = Mock() + runner.mutate = Mock(side_effect=RuntimeError("source-failover loops complete")) + runner.changing = Mock(side_effect=lambda: nullcontext()) + def probe(node, operation, realm, **kwargs): + return {"limits": {"maxMetadataLease": "00:00:15"}, "serving": { + "nodeId": "source-2:4053" if operation == "read" else "source-1:4053", "servingGeneration": 2 if operation == "read" else 1}} + runner.probe = Mock(side_effect=probe) + def fault(*args, **kwargs): + kwargs["on_fault"]() + kwargs["after_validated_recovery"]() + return {"temporal": {}} + runner.live_cli_fault = Mock(side_effect=fault) + with self.assertRaisesRegex(RuntimeError, "source-failover loops complete"): + runner.scenario_D07() + self.assertEqual(runner.live_cli_fault.call_count, 2) + for call in runner.live_cli_fault.call_args_list: + self.assertEqual(call.kwargs["outage_partner"], "source-2") + self.assertEqual(call.kwargs["duration"], 120) + self.assertEqual(call.kwargs["post_lease_seconds"], 20) + self.assertTrue(call.kwargs["require_gap"]) + self.assertNotIn("partner", call.kwargs) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/validation/grpc-data/tests/test_key_only_revision_evidence.py b/scripts/validation/grpc-data/tests/test_key_only_revision_evidence.py new file mode 100644 index 000000000..5ae8acb48 --- /dev/null +++ b/scripts/validation/grpc-data/tests/test_key_only_revision_evidence.py @@ -0,0 +1,72 @@ +"""Credential-only mutations require fresh numeric evidence from the actual seeder path.""" +from copy import deepcopy +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import Mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import scenarios + + +def receipt(): + revisions = {"Connection": 7, "Mappings": {"map-raw": 11, "map-uns": 12}, + "Exports": {"export-raw": 13, "export-uns": 14}} + return {"keyAction": "rotate", "revisions": {"CredentialOnly": True, "Before": revisions, "After": deepcopy(revisions)}} + + +class KeyOnlyRevisionEvidenceTests(unittest.TestCase): + def test_only_matching_credential_action_and_unchanged_numeric_revisions_pass(self): + valid = receipt() + self.assertIs(scenarios.validate_key_only_revision_receipt(valid, action="rotate"), valid) + invalid = [] + for field, value in (("Connection", 8), ("Mappings", {"map-raw": 12, "map-uns": 12}), + ("Exports", {"export-raw": 14, "export-uns": 14}), ("Connection", True)): + actual = deepcopy(valid) + actual["revisions"]["After"][field] = value + invalid.append(actual) + invalid += [dict(valid, keyAction="revoke"), {"keyAction": "rotate", "revisions": {}}, + {"keyAction": "rotate", "revisions": dict(valid["revisions"], CredentialOnly=False)}] + for actual in invalid: + with self.subTest(actual=actual), self.assertRaises(scenarios.ScenarioError): + scenarios.validate_key_only_revision_receipt(actual, action="rotate") + + def runner(self, folder): + runner = object.__new__(scenarios.ScenarioRunner) + runner.active, runner.timeline, runner.secrets = "D06", [], [] + runner.rig = Mock(folder=folder) + runner.rig.deploy.return_value = {"credentials": {"data_key_files": {}}, "deployment": {"revision_hash": "current"}} + runner.remaining = Mock(side_effect=lambda maximum: maximum) + runner.save = Mock() + (folder / "seed").mkdir() + return runner + + def test_key_only_requires_fresh_actual_seeder_receipt_before_deploy_and_copies_evidence(self): + with tempfile.TemporaryDirectory() as temporary: + runner = self.runner(Path(temporary)) + path = Path(temporary) / "seed/mutation-revisions.json" + scenarios.rig.atomic_write_secret(path, scenarios.json.dumps(receipt())) + def seed(action): + self.assertEqual(action, "mutate") + self.assertFalse(path.exists(), "a prior mutation receipt cannot satisfy the current mutation") + scenarios.rig.atomic_write_secret(path, scenarios.json.dumps(receipt())) + runner.rig.seed_helper.side_effect = seed + runner.mutate(key_action="rotate") + runner.rig.deploy.assert_called_once() + self.assertEqual(runner.save.call_count, 1) + self.assertEqual(runner.save.call_args.args[1], receipt()) + + def test_missing_key_only_receipt_prevents_deploy_but_mixed_configuration_uses_normal_path(self): + with tempfile.TemporaryDirectory() as temporary: + runner = self.runner(Path(temporary)) + with self.assertRaises(scenarios.ScenarioError): + runner.mutate(key_action="rotate") + runner.rig.deploy.assert_not_called() + runner.mutate(key_action="rotate", mapping_enabled=False) + runner.rig.deploy.assert_called_once() + runner.save.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/validation/grpc-data/tests/test_live_fault_failure_evidence.py b/scripts/validation/grpc-data/tests/test_live_fault_failure_evidence.py new file mode 100644 index 000000000..9cfb9a77e --- /dev/null +++ b/scripts/validation/grpc-data/tests/test_live_fault_failure_evidence.py @@ -0,0 +1,107 @@ +"""A failed live subscriber gate still leaves bounded, sanitized local evidence.""" +import json +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import Mock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import processes +import scenarios + + +class LiveFaultFailureEvidenceTests(unittest.TestCase): + def test_attachment_failure_cancels_active_worker_and_preserves_original_failure(self): + with tempfile.TemporaryDirectory() as folder: + runner = object.__new__(scenarios.ScenarioRunner) + runner.active, runner.count = "D06", 0 + runner.folder, runner.cli_dll = Path(folder), Path("/unit/cli.dll") + runner.key, runner.secrets = "unit-secret", ["unit-secret"] + runner._controlled_source = object.__new__(scenarios.ControlledFixtureSource) + runner.leaf = Mock(return_value="ns=2;s=fixture") + runner.endpoint = Mock(return_value="opc.tcp://127.0.0.1:52113") + runner.remaining = Mock(return_value=.1) + runner.rig = Mock(environment={}) + output = processes.ProcessResult(argv=("dotnet",), returncode=-15, + stdout="subscriber cancelled", stderr="", timed_out=False, + truncated=False, duration_seconds=.1, cancelled=True) + workers, calls = [], [] + def run_process(*args, **kwargs): + calls.append(kwargs) + return output + def thread(target, **kwargs): + worker = Mock() + alive = [True] + # Defer the process fake until join so cancellation must precede collection. + worker.start.return_value = None + def join(timeout): + self.assertLessEqual(timeout, .25) + if not calls: + target() + self.assertIn("cancellation_event", calls[0]) + self.assertTrue(calls[0]["cancellation_event"].is_set()) + alive[0] = False + worker.join.side_effect = join + worker.is_alive.side_effect = lambda: alive[0] + workers.append(worker) + return worker + def make_event(): + result = Mock() + result.wait.return_value = False + state = [False] + result.set.side_effect = lambda: state.__setitem__(0, True) + result.is_set.side_effect = lambda: state[0] + return result + with patch.object(scenarios.threading, "Thread", side_effect=thread), \ + patch.object(scenarios.threading, "Event", side_effect=make_event), \ + patch.object(scenarios, "run_process", side_effect=run_process), \ + self.assertRaisesRegex(scenarios.ScenarioError, "real CLI attachment"): + runner.live_cli_fault("consumer-1", duration=90) + self.assertFalse(workers[0].is_alive()) + observed = json.loads(next(Path(folder).glob("*.fault-observation.json")).read_text()) + self.assertTrue(observed["worker_collected"]) + self.assertTrue(observed["process_collected"]) + self.assertTrue(observed["cancellation_requested"]) + self.assertEqual(len(list(Path(folder).glob("*.process.json"))), 1) + + def test_initial_attachment_failure_persists_process_and_temporal_observation_in_finally(self): + with tempfile.TemporaryDirectory() as folder: + runner = object.__new__(scenarios.ScenarioRunner) + runner.active, runner.count = "D07", 0 + runner.folder, runner.cli_dll = Path(folder), Path("/unit/cli.dll") + runner.key, runner.secrets = "unit-secret", ["unit-secret"] + runner._controlled_source = object.__new__(scenarios.ControlledFixtureSource) + runner.leaf = Mock(return_value="ns=2;s=fixture") + runner.endpoint = Mock(return_value="opc.tcp://127.0.0.1:52113") + runner.remaining = Mock(return_value=.1) + runner.rig = Mock(environment={}) + output = processes.ProcessResult(argv=("dotnet", "-P", "unit-secret"), returncode=1, + stdout="unit-secret attachment failed", stderr="unit-secret error", timed_out=False, + truncated=False, duration_seconds=.1) + def thread(target, **kwargs): + worker = Mock() + worker.start.side_effect = target + worker.is_alive.return_value = False + return worker + event = Mock() + event.wait.return_value = False + with patch.object(scenarios.threading, "Thread", side_effect=thread), \ + patch.object(scenarios.threading, "Event", return_value=event), \ + patch.object(scenarios, "run_process", return_value=output), \ + self.assertRaisesRegex(scenarios.ScenarioError, "real CLI attachment"): + runner.live_cli_fault("consumer-1", duration=1) + process_files = list(Path(folder).glob("*.process.json")) + observations = list(Path(folder).glob("*.fault-observation.json")) + self.assertEqual(len(process_files), 1) + self.assertEqual(len(observations), 1) + observed = json.loads(observations[0].read_text()) + self.assertTrue(observed["worker_collected"]) + self.assertTrue(observed["started_at_utc"]) + self.assertTrue(observed["completed_at_utc"]) + self.assertIn("notifications", observed) + self.assertNotIn("unit-secret", process_files[0].read_text() + observations[0].read_text()) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/validation/grpc-data/tests/test_live_read_timestamps.py b/scripts/validation/grpc-data/tests/test_live_read_timestamps.py new file mode 100644 index 000000000..abbb662b6 --- /dev/null +++ b/scripts/validation/grpc-data/tests/test_live_read_timestamps.py @@ -0,0 +1,118 @@ +"""Live fixture reads retain independent cached timestamps and completion evidence.""" +from copy import deepcopy +from datetime import datetime, timezone +from pathlib import Path +import sys +import unittest +from unittest.mock import Mock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import processes +import scenarios + + +def read(source="2026-11-17T09:00:00.1234567Z", server="2026-11-17T09:00:00.7654321Z", + completed="2026-11-17T10:00:00+00:00", value="42"): + return {"status": "Good", "value": value, "source_time": source, + "server_time": server, "completed_at_utc": completed} + + +class LiveReadTimestampTests(unittest.TestCase): + def test_distinct_legitimate_cached_timestamps_pass_without_rewriting_strings(self): + origin = read() + mapped = read(source="2026-11-17T09:01:00.1111111Z", server="2026-11-17T09:01:00.2222222Z", + completed="2026-11-17T10:01:00+00:00") + original = deepcopy((origin, mapped)) + scenarios.validate_fixture_read_pair(origin, mapped, modbus_fixture=True) + self.assertEqual((origin, mapped), original) + + def test_each_read_uses_its_own_completion_and_one_second_clock_allowance(self): + origin = read(source="2026-11-17T10:00:00.5Z", server="2026-11-17T10:00:01Z") + mapped = read(source="2026-11-17T10:01:00Z", server="2026-11-17T10:01:00.5Z", + completed="2026-11-17T10:01:00+00:00") + scenarios.validate_fixture_read_pair(origin, mapped, modbus_fixture=True) + origin["server_time"] = "2026-11-17T10:00:01.000001Z" + with self.assertRaises(scenarios.ScenarioError): + scenarios.validate_fixture_read_pair(origin, mapped, modbus_fixture=True) + + def test_missing_naive_non_utc_sentinel_or_future_timestamps_fail(self): + for field in ("source_time", "server_time", "completed_at_utc"): + for invalid in (None, "", "not-a-time", "2026-11-17T09:00:00", + "2026-11-17T09:00:00+01:00", "0001-01-01T00:00:00Z", + "1601-01-01T00:00:00Z", "9999-12-31T23:59:59.9999999Z"): + observed = read() + if invalid is None: + del observed[field] + else: + observed[field] = invalid + with self.subTest(field=field, invalid=invalid), self.assertRaises(scenarios.ScenarioError): + scenarios.validate_fixture_read_pair(observed, read(), modbus_fixture=True) + for field in ("source_time", "server_time"): + observed = read() + observed[field] = "2026-11-17T10:00:02Z" + with self.subTest(field=field), self.assertRaises(scenarios.ScenarioError): + scenarios.validate_fixture_read_pair(read(), observed, modbus_fixture=True) + + def test_swapped_modbus_times_fail_but_other_source_clocks_are_not_ordered(self): + observed = read(source="2026-11-17T09:00:01Z", server="2026-11-17T09:00:00Z") + with self.assertRaises(scenarios.ScenarioError): + scenarios.validate_fixture_read_pair(read(), observed, modbus_fixture=True) + scenarios.validate_fixture_read_pair(read(), observed, modbus_fixture=False) + + def test_value_mismatch_and_non_good_reads_still_fail(self): + for origin, mapped in ((read(value="41"), read()), (read(), dict(read(), status="BadNoCommunication"))): + with self.subTest(origin=origin, mapped=mapped), self.assertRaises(scenarios.ScenarioError): + scenarios.validate_fixture_read_pair(origin, mapped, modbus_fixture=True) + + def d03_runner(self, mapped): + runner = object.__new__(scenarios.ScenarioRunner) + runner.primary = Mock(side_effect=lambda pair: pair + "-1") + runner.node_id = Mock(side_effect=lambda node: node + ":4053") + runner.mutate, runner.wait_connection_ready, runner.save = Mock(), Mock(), Mock() + runner.cli = Mock(return_value=read()) + runner.matrix_cli = Mock(return_value=mapped) + runner.matrix_probe = Mock(side_effect=RuntimeError("reached metadata alias checks")) + def check(valid, message): + if not valid: + raise scenarios.ScenarioError(message) + runner.check = Mock(side_effect=check) + return runner + + def test_d03_accepts_independent_cached_times_and_continues_metadata_alias_checks(self): + mapped = read(source="2026-11-17T09:01:00Z", server="2026-11-17T09:01:01Z") + runner = self.d03_runner(mapped) + with self.assertRaisesRegex(RuntimeError, "reached metadata alias checks"): + runner.scenario_D03() + runner.matrix_probe.assert_called_once() + + def test_d03_keeps_same_fixture_value_comparison(self): + runner = self.d03_runner(read(value="41")) + with self.assertRaises(scenarios.ScenarioError): + runner.scenario_D03() + runner.matrix_probe.assert_not_called() + + def test_cli_read_records_final_pending_retry_completion(self): + runner = object.__new__(scenarios.ScenarioRunner) + runner.active, runner.count = "D03", 0 + runner.folder, runner.cli_dll, runner.key = Path("/unit/evidence"), Path("/unit/cli.dll"), "unit-key" + runner.leaf = Mock(return_value="ns=2;s=scalar") + runner.endpoint = Mock(return_value="opc.tcp://127.0.0.1:52113") + runner.remaining = Mock(return_value=.1) + runner.save = Mock() + def output(status): + return processes.ProcessResult(argv=("dotnet",), returncode=0, stderr="", timed_out=False, + truncated=False, duration_seconds=.1, stdout=("Node: ns=2;s=scalar\nValue: 42\n" + f"Status: {status}\nSource Time: 2026-11-17T09:00:00Z\nServer Time: 2026-11-17T09:00:01Z\n")) + runner.process = Mock(side_effect=[output("BadWaitingForInitialData"), output("Good")]) + first = datetime(2026, 11, 17, 9, 1, tzinfo=timezone.utc) + final = datetime(2026, 11, 17, 9, 2, tzinfo=timezone.utc) + with patch.object(scenarios, "datetime", wraps=datetime) as clock, patch.object(scenarios.time, "sleep"): + clock.now.side_effect = [first, final] + observed = runner.cli("read", "consumer-1") + self.assertEqual(observed["completed_at_utc"], final.isoformat()) + self.assertEqual(runner.process.call_count, 2) + self.assertEqual(observed["source_time"], "2026-11-17T09:00:00Z") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/validation/grpc-data/tests/test_live_stream_redaction.py b/scripts/validation/grpc-data/tests/test_live_stream_redaction.py new file mode 100644 index 000000000..875e5ff77 --- /dev/null +++ b/scripts/validation/grpc-data/tests/test_live_stream_redaction.py @@ -0,0 +1,95 @@ +"""Live output must flush complete nonsecret lines without waiting for another read or EOF.""" +from pathlib import Path +import sys +import threading +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import processes + + +class LiveStreamRedactionTests(unittest.TestCase): + def test_complete_nonsecret_notification_is_observed_before_stream_eof(self): + complete_line = "[2026-11-17T10:00:00Z] ns=4;s=fixture = 65535 (Good)\n" + observed, release, blocked, full_line = [], threading.Event(), threading.Event(), threading.Event() + class LivePipe: + reads = 0 + def read(self, size): + self.reads += 1 + if self.reads == 1: + return complete_line.encode() + blocked.set() + release.wait(timeout=2) + return b"" + def observe(stream, chunk): + observed.append(chunk) + if "\n" in "".join(observed): + full_line.set() + capture = processes._Capture(4096, ("K" * 43,), observe) + worker = threading.Thread(target=capture.drain, args=("stdout", LivePipe()), daemon=True) + worker.start() + try: + self.assertTrue(blocked.wait(timeout=1), "reader must be blocked before EOF") + self.assertTrue(full_line.wait(timeout=.3), "complete notification must be visible while the pipe remains open and quiet") + self.assertEqual("".join(observed), complete_line) + finally: + release.set() + worker.join(timeout=1) + self.assertFalse(worker.is_alive()) + + def test_split_and_overlapping_secret_matches_never_cross_the_observer_boundary(self): + chunks = iter((b"abcd", b"ef\n", b"")) + class ChunkPipe: + def read(self, size): + return next(chunks) + observed = [] + capture = processes._Capture(4096, ("abc", "bcd", "de"), lambda stream, chunk: observed.append(chunk)) + capture.drain("stdout", ChunkPipe()) + self.assertFalse(capture.failures) + for secret in ("abc", "bcd", "de"): + self.assertNotIn(secret, "".join(observed)) + self.assertIn("[REDACTED]", "".join(observed)) + + def test_self_overlapping_secret_is_consumed_while_pipe_remains_open(self): + release, blocked, emitted = threading.Event(), threading.Event(), threading.Event() + observed = [] + class LivePipe: + reads = 0 + def read(self, size): + self.reads += 1 + if self.reads == 1: + return b"a" * 8193 + blocked.set() + release.wait(timeout=2) + return b"" + def observe(stream, chunk): + observed.append(chunk) + emitted.set() + capture = processes._Capture(65536, ("aa",), observe) + worker = threading.Thread(target=capture.drain, args=("stdout", LivePipe()), daemon=True) + worker.start() + try: + self.assertTrue(blocked.wait(timeout=1)) + self.assertTrue(emitted.wait(timeout=.3), "complete repeated matches must be consumed before EOF") + self.assertNotIn("aa", "".join(observed)) + self.assertIn("[REDACTED]", "".join(observed)) + finally: + release.set() + worker.join(timeout=1) + self.assertFalse(worker.is_alive()) + + def test_prefix_related_secrets_and_split_utf8_are_redacted_without_holding_a_safe_newline(self): + encoded = "safe 密钥🔒 abcd\n".encode() + chunks = iter((encoded[:7], encoded[7:10], encoded[10:14], encoded[14:], b"")) + class ChunkPipe: + def read(self, size): + return next(chunks) + observed = [] + capture = processes._Capture(4096, ("密钥🔒", "abc", "abcd"), lambda stream, chunk: observed.append(chunk)) + capture.drain("stdout", ChunkPipe()) + self.assertFalse(capture.failures) + self.assertEqual("".join(observed), "safe [REDACTED] [REDACTED]\n") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/validation/grpc-data/tests/test_positive_projection_readiness.py b/scripts/validation/grpc-data/tests/test_positive_projection_readiness.py new file mode 100644 index 000000000..2fbf9ee40 --- /dev/null +++ b/scripts/validation/grpc-data/tests/test_positive_projection_readiness.py @@ -0,0 +1,85 @@ +"""Positive mounted operations explicitly establish their caller's projected node.""" +from contextlib import nullcontext +from pathlib import Path +import sys +import unittest +from unittest.mock import Mock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import scenarios + + +class PositiveProjectionReadinessTests(unittest.TestCase): + def test_d06_read_only_mapping_removes_write_operation_before_disabling_write_through(self): + runner = object.__new__(scenarios.ScenarioRunner) + runner.primary = Mock(return_value="consumer-1") + stop = RuntimeError("stop after observing the initial mutation") + runner.mutate = Mock(side_effect=stop) + with self.assertRaisesRegex(RuntimeError, "stop after observing"): + runner.scenario_D06() + runner.mutate.assert_called_once_with(write_through=False, allowed_operations=scenarios.OPERATIONS & ~8) + operations = runner.mutate.call_args.kwargs["allowed_operations"] + self.assertEqual(operations & 8, 0) + self.assertEqual(operations, 1 | 2 | 4 | 16) + + def test_same_cluster_materializes_exact_caller_branch_without_global_resolver(self): + runner = object.__new__(scenarios.ScenarioRunner) + runner.manifest = {"nodes": {"source-1": {}, "source-2": {}}, + "fixture": {"namespace_uris": {"mapped_raw": "mapped/raw", "mapped_uns": "mapped/uns"}}, + "resolved_nodes": {"source-2": {"namespace_uris": ["standard", "mapped/raw", "mapped/uns"]}}} + runner.initial_resolved = {"consumer-1": {}, "source-2": runner.manifest["resolved_nodes"]["source-2"]} + runner.primary = Mock(return_value="source-1") + runner.node_id = Mock(side_effect=lambda node: node + ":4053") + runner.mutate = Mock() + runner.direct_suite = Mock() + runner.probe = Mock() + runner.rig = Mock() + runner.rig.folder = Path("/owned") + runner.rig.seed_helper.side_effect = AssertionError("unrelated global resolver invoked") + runner.relative_node = Mock(side_effect=lambda node, realm, name, **kw: "ns=4;s=same-" + realm + "/" + name) + runner.cli = Mock() + runner.device = Mock(return_value={"effect_total": 0}) + runner.matrix_cli = Mock(side_effect=RuntimeError("first mounted read")) + with patch.object(scenarios, "restricted_json", return_value={"Mappings": [{"Realm": 1}, {"Realm": 2}]}): + with self.assertRaisesRegex(RuntimeError, "first mounted read"): + runner.same_cluster() + runner.rig.seed_helper.assert_not_called() + runner.cli.assert_called_once_with("browse", "source-2", "raw", recursive=True, + target_override="ns=1;s=same-raw/", expected_nodes={"ns=1;s=same-raw/scalar"}) + runner.matrix_cli.assert_called_once() + + def test_d04_browses_each_positive_target_before_subscribe_and_write(self): + runner = object.__new__(scenarios.ScenarioRunner) + calls = [] + effects = [0] + runner.primary = Mock(side_effect=lambda pair: pair + "-1") + runner.node_id = Mock(side_effect=lambda node: node + ":4053") + runner.mutate = Mock(side_effect=lambda **_: calls.append(("deploy", None))) + runner.cli = Mock(side_effect=lambda command, node, realm, **kwargs: + calls.append((command, realm, node, kwargs))) + runner.wait_connection_ready = Mock(side_effect=lambda node, realm: calls.append(("ready", realm, node))) + runner.changing = Mock(side_effect=lambda: nullcontext()) + def matrix(*args, **kwargs): + operation = args[3] + calls.append((operation, args[2])) + if operation == "write": + effects[0] += 1 + runner.matrix_cli = Mock(side_effect=matrix) + runner.device = Mock(side_effect=lambda: {"effect_total": effects[0], "writable": {"20": 42}}) + runner.check = Mock(side_effect=lambda valid, message: self.assertTrue(valid, message)) + runner.wait_readback = Mock() + runner.scenario_D04() + relevant = [call for call in calls if call[0] in {"ready", "browse", "subscribe", "write"}] + self.assertEqual(24, len(relevant)) + for index in range(0, len(relevant), 6): + ready1, browse1, subscribe, ready2, browse2, write = relevant[index:index + 6] + realm = subscribe[1] + self.assertEqual(("ready", realm, "consumer-1"), ready1) + self.assertEqual(("browse", realm, "consumer-1", {"recursive": True}), browse1) + self.assertEqual(("ready", realm, "consumer-1"), ready2) + self.assertEqual(("browse", realm, "consumer-1", {"recursive": True}), browse2) + self.assertEqual(("write", realm), write) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/validation/grpc-data/tests/test_process_cancellation.py b/scripts/validation/grpc-data/tests/test_process_cancellation.py new file mode 100644 index 000000000..407747744 --- /dev/null +++ b/scripts/validation/grpc-data/tests/test_process_cancellation.py @@ -0,0 +1,81 @@ +"""Owned Python children can be cancelled and collected without waiting for run timeout.""" +import os +from pathlib import Path +import signal +import sys +import tempfile +import threading +import time +import unittest +from unittest.mock import Mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import processes + + +class ProcessCancellationTests(unittest.TestCase): + @unittest.skipIf(os.name == "nt", "POSIX process-group signal contract") + def test_cancellation_kills_silent_term_ignoring_descendant_after_parent_exits(self): + with tempfile.TemporaryDirectory() as directory: + heartbeat = Path(directory) / "heartbeat.txt" + descendant = ("import os,signal,time\nfrom pathlib import Path\n" + "signal.signal(signal.SIGTERM, signal.SIG_IGN)\nos.close(1)\nos.close(2)\n" + f"path=Path({str(heartbeat)!r})\n" + "while True:\n path.write_text(str(time.monotonic()))\n time.sleep(.02)\n") + child = ("import os,subprocess,sys,time\nfrom pathlib import Path\n" + f"subprocess.Popen([sys.executable, '-c', {descendant!r}])\n" + f"path=Path({str(heartbeat)!r})\n" + "while not path.exists(): time.sleep(.01)\n" + "print('parent-ready:'+str(os.getpid()), flush=True)\ntime.sleep(60)\n") + cancellation, group, observed = threading.Event(), [], [] + def observe(stream, chunk): + if stream == "stdout": + observed.append(chunk) + if "\n" in "".join(observed): + group.append(int("".join(observed).split("parent-ready:", 1)[1].split()[0])) + cancellation.set() + try: + result = processes.run_process([sys.executable, "-u", "-c", child], timeout=10, + cleanup_timeout=.25, cancellation_event=cancellation, observer=observe) + self.assertTrue(result.cancelled) + self.assertEqual(result.returncode, -signal.SIGTERM) + first = heartbeat.read_text() + time.sleep(.2) + self.assertEqual(heartbeat.read_text(), first, "silent same-group descendant must stop after parent collection") + finally: + if group: + try: + os.killpg(group[0], signal.SIGKILL) + except ProcessLookupError: + pass + + @unittest.skipIf(os.name == "nt", "POSIX process-group signal contract") + def test_cancellation_kills_and_collects_owned_python_group_and_retains_result(self): + cancellation = threading.Event() + child = ("import signal,subprocess,sys,time\n" + "signal.signal(signal.SIGTERM, signal.SIG_IGN)\n" + "subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'])\n" + "print('parent-ready', flush=True)\n" + "time.sleep(60)\n") + def observe(stream, chunk): + if stream == "stdout" and "parent-ready" in chunk: + cancellation.set() + started = time.monotonic() + result = processes.run_process([sys.executable, "-u", "-c", child], timeout=20, + cleanup_timeout=.25, cancellation_event=cancellation, observer=observe) + self.assertTrue(result.cancelled) + self.assertFalse(result.timed_out) + self.assertEqual(result.returncode, -signal.SIGKILL) + self.assertIn("parent-ready", result.stdout) + self.assertLess(time.monotonic() - started, 4) + + def test_invalid_cancellation_signal_is_rejected_before_start(self): + factory = Mock() + with self.assertRaises(processes.ProcessError): + processes.run_process([sys.executable, "-c", "pass"], timeout=1, + cancellation_event=object(), popen=factory) + factory.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/validation/grpc-data/tests/test_raw_continuation_replay.py b/scripts/validation/grpc-data/tests/test_raw_continuation_replay.py new file mode 100644 index 000000000..07b0b9b4c --- /dev/null +++ b/scripts/validation/grpc-data/tests/test_raw_continuation_replay.py @@ -0,0 +1,67 @@ +"""Origin HMAC continuation tokens allow bounded same-owner replay until revision changes.""" +from pathlib import Path +import sys +import unittest +from unittest.mock import Mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import scenarios + + +class RawContinuationReplayTests(unittest.TestCase): + def runner(self, *, changed_repeat=False, error_rows=False, unchanged_origin=False): + runner = object.__new__(scenarios.ScenarioRunner) + runner.primary = Mock(side_effect=lambda pair: pair + "-1") + runner.node_id = Mock(side_effect=lambda node: node + ":4053") + runner.manifest = {"fixture": {"browse_roots": {"raw": "modbus/plc", "uns": "equipment"}}} + revision = [0] + runner.mutate = Mock(side_effect=lambda **_: revision.__setitem__(0, revision[0] + 1)) + runner.save = Mock() + def check(valid, message): + if not valid: + raise scenarios.ScenarioError(message) + runner.check = Mock(side_effect=check) + uses, issued = {}, {} + def serving(): + return {"nodeId": "source-1:4053", "incarnation": "unit", "authorityEpoch": 1, + "catalogEpoch": 1 if unchanged_origin else revision[0], "servingGeneration": 1} + def probe(node, operation, realm, **fields): + if operation == "capabilities": + return {"serving": serving()} + if operation == "browse": + cursor = "cursor-" + str(len(issued)) + issued[cursor] = revision[0] + return {"complete": False, "continuation": cursor, "items": [{"id": "first"}], "serving": serving()} + cursor = fields["continuation"] + uses[cursor] = uses.get(cursor, 0) + 1 + if issued[cursor] == revision[0]: + self.assertEqual(fields.get("expected_state", "Good"), "Good") + return {"status": "Good", "items": [{"id": "changed" if changed_repeat and uses[cursor] == 2 else "second"}], + "serving": serving(), "limits": {"maxPageItems": 1}, "complete": True, + "operations": "Browse, Metadata, Read", "compact": True, "readiness": "Ready"} + self.assertEqual(fields["expected_state"], "InvalidContinuation") + return {"status": "InvalidContinuation", "items": [{"id": "leaked"}] if error_rows else []} + runner.probe = Mock(side_effect=probe) + return runner + + def test_d05_accepts_same_ordered_origin_page_replay_then_requires_invalid_after_revision(self): + runner = self.runner() + runner.scenario_D05() + continuations = [call for call in runner.probe.call_args_list if call.args[1] == "continuation"] + self.assertEqual(len(continuations), 12) + + def test_d05_rejects_different_replayed_items(self): + with self.assertRaises(scenarios.ScenarioError): + self.runner(changed_repeat=True).scenario_D05() + + def test_d05_rejects_items_on_invalid_continuation(self): + with self.assertRaises(scenarios.ScenarioError): + self.runner(error_rows=True).scenario_D05() + + def test_d05_requires_an_actual_origin_serving_revision_change(self): + with self.assertRaises(scenarios.ScenarioError): + self.runner(unchanged_origin=True).scenario_D05() + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/validation/grpc-data/tests/test_rig.py b/scripts/validation/grpc-data/tests/test_rig.py index 60099347f..fe00cf21a 100644 --- a/scripts/validation/grpc-data/tests/test_rig.py +++ b/scripts/validation/grpc-data/tests/test_rig.py @@ -1,12 +1,14 @@ """Safety units only: no Docker, HTTP, DNS, socket, or production fixture calls.""" from copy import deepcopy +import json import os from pathlib import Path import stat import sys import tempfile import unittest -from unittest.mock import patch +from unittest.mock import Mock, patch +from urllib.error import URLError sys.path.insert(0, str(Path(__file__).resolve().parents[1])) import rig @@ -17,6 +19,135 @@ LABELS = {"otopcua.grpc-data.run": RUN, "com.docker.compose.project": f"grpc-data-{RUN}"} +class BundleCommitReadinessTests(unittest.TestCase): + def test_exact_scope_and_both_committed_versions_are_required(self): + expected = {"scopeVersion": 9, "credentialVersion": 12, "trustVersion": 12} + ready = {"credentialScopeVersion": 9, "credentialVersion": 12, + "trustScopeVersion": 9, "trustVersion": 12, "credentialDeleted": False, "trustRetired": False} + self.assertTrue(rig.bundle_commit_matches(expected, ready)) + for change in ({"credentialVersion": 11}, {"trustVersion": 11}, {"trustVersion": None}, + {"credentialScopeVersion": 8}, {"trustScopeVersion": 8}, {"trustVersion": 13}, + {"credentialDeleted": None}, {"credentialDeleted": True}, {"trustRetired": None}, {"trustRetired": True}): + with self.subTest(change=change): + self.assertFalse(rig.bundle_commit_matches(expected, {**ready, **change})) + self.assertFalse(rig.bundle_commit_matches(expected, None)) + + +class ActiveEndpointSelectionTests(unittest.TestCase): + def setUp(self): + self.urls = {'control-1': 'http://127.0.0.1:51000', 'control-2': 'http://127.0.0.1:51001'} + self.now = 0 + self.sleeps = [] + + def sleep(self, duration): + self.sleeps.append(duration) + self.now += duration + + def test_unreachable_first_control_does_not_hide_ready_active_partner(self): + request = Mock(side_effect=[URLError('refused'), (200, {}, None), (200, {}, None)]) + selected = rig.observe_active_endpoint(self.urls, request=request, timeout=10, require_ready=True, clock=lambda: self.now) + self.assertEqual('control-2', selected) + self.assertEqual([self.urls['control-1'] + '/health/active', self.urls['control-2'] + '/health/active', + self.urls['control-2'] + '/health/ready'], [call.args[1] for call in request.call_args_list]) + self.assertTrue(all(call.args[0] == 'GET' for call in request.call_args_list)) + + def test_startup_requires_active_and_ready_then_returns_within_one_deadline(self): + request = Mock(side_effect=[(503, {}, None), (503, {}, None), + (200, {}, None), (503, {}, None), (503, {}, None), + (200, {}, None), (503, {}, None), (200, {}, None)]) + self.assertEqual('control-1', rig.wait_active_endpoint(self.urls, request=request, timeout=5, + require_ready=True, clock=lambda: self.now, sleep=self.sleep)) + self.assertEqual([1, 1], self.sleeps) + self.assertEqual(2, self.now) + + def test_duplicate_active_endpoints_are_rejected_without_ready_or_privileged_requests(self): + request = Mock(return_value=(200, {}, None)) + with self.assertRaisesRegex(rig.RigError, 'more than one'): + rig.wait_active_endpoint(self.urls, request=request, timeout=5, require_ready=True, + clock=lambda: self.now, sleep=self.sleep) + self.assertEqual(2, request.call_count) + self.assertEqual([], self.sleeps) + self.assertTrue(all(call.args[0] == 'GET' and call.args[1].endswith('/health/active') for call in request.call_args_list)) + + def test_never_ready_or_http_500_stops_at_bounded_deadline(self): + request = Mock(return_value=(500, {}, None)) + with self.assertRaisesRegex(rig.RigError, 'deadline'): + rig.wait_active_endpoint(self.urls, request=request, timeout=3, + require_ready=True, clock=lambda: self.now, sleep=self.sleep) + self.assertEqual(3, self.now) + self.assertEqual(6, request.call_count) + self.assertTrue(all(call.args[0] == 'GET' for call in request.call_args_list)) + + def test_incomplete_pair_observation_never_selects_the_first_active(self): + def request(*args, **kwargs): + self.now = 10 + return 200, {}, None + self.assertIsNone(rig.observe_active_endpoint(self.urls, request=request, timeout=5, clock=lambda: self.now)) + + def test_deploy_selection_apply_and_catalog_share_the_original_timeout(self): + with tempfile.TemporaryDirectory() as directory: + instance = object.__new__(rig.LocalRig) + instance.folder = Path(directory) + (instance.folder / 'seed').mkdir() + (instance.folder / 'seed' / 'resolved.json').write_text('{}') + instance.environment = {'GRPC_DATA_DEPLOY_KEY': 'unit-deploy-key'} + instance.load = Mock(return_value={'fixture': {}, 'endpoints': {node + '.admin': {'url': url} for node, url in self.urls.items()}}) + instance.capture = Mock() + instance.health = Mock(return_value=True) + instance.wait_bundle_commits = Mock(return_value=[]) + instance.provision_deployment = Mock(return_value={'scope_version': 1, 'required_node_ids': [node + ':4053' for node in rig.NODES], 'bundle_expectations': []}) + def select(*args, **kwargs): + self.assertEqual(10, kwargs['timeout']) + self.assertTrue(kwargs['require_ready']) + self.now += 2 + return 'control-2' + def deploy(url, key, expected, **kwargs): + self.assertEqual(self.urls['control-2'], url) + self.assertEqual(8, kwargs['timeout']) + self.now += 3 + kwargs['on_accepted']('unit-deployment', 'unit-revision') + return {'deploymentId': 'unit-deployment', 'revisionHash': 'unit-revision', 'nodes': []} + def catalog(predicate, **kwargs): + self.assertEqual(5, kwargs['timeout']) + self.assertTrue(predicate()) + with patch.object(rig.time, 'monotonic', side_effect=lambda: self.now), \ + patch.object(rig, 'wait_active_endpoint', side_effect=select), \ + patch.object(rig, 'deploy_and_wait', side_effect=deploy), \ + patch.object(rig, 'wait_until', side_effect=catalog): + self.assertEqual('ready', instance.deploy(timeout=10)['state']) + instance.provision_deployment.assert_called_once_with('unit-deployment', 'unit-revision', timeout=5) + self.assertEqual(5, instance.health.call_args.kwargs['timeout']) + instance.wait_bundle_commits.assert_called_once_with([], timeout=5) + + +class ManifestEndpointAllocationTests(unittest.TestCase): + def test_allocated_opcua_endpoint_retains_exact_host_port_and_configured_application_path(self): + instance = object.__new__(rig.LocalRig) + instance.run_id = RUN + instance.project = 'grpc-data-' + RUN + instance.folder = Path('/unused-owned-fixture') + instance.context = {'Name': 'unit-local'} + instance.docker = ['docker', '--context', 'unit-local'] + instance.compose = Mock(side_effect=lambda *args: 'container-' + args[-1]) + def inspect(argv): + node = argv[-1].removeprefix('container-') + ports = (4840, 9000, 4057) if node in rig.NODES else (1433,) if node == 'sql' else (5020, 8080) + offset = (*rig.NODES, 'sql', 'device').index(node) * 10 + return json.dumps([{'NetworkSettings': {'Ports': { + str(port) + '/tcp': [{'HostIp': '127.0.0.1', 'HostPort': str(51000 + offset + index)}] + for index, port in enumerate(ports)}}}]) + with patch.object(rig, 'run_command', side_effect=inspect): + endpoints = instance.allocate_manifest()['endpoints'] + for node in rig.NODES: + ua = endpoints[node + '.opcua'] + self.assertEqual('opc.tcp://127.0.0.1:' + str(ua['host_port']) + '/OtOpcUa', ua['url']) + self.assertEqual(node, ua['container_host']) + self.assertEqual(4840, ua['container_port']) + for suffix, scheme in (('admin', 'http'), ('data', 'https')): + endpoint = endpoints[node + '.' + suffix] + self.assertEqual(scheme + '://127.0.0.1:' + str(endpoint['host_port']), endpoint['url']) + + def manifest(): return { "schema_version": 1, "run_id": RUN, "project": f"grpc-data-{RUN}", @@ -230,6 +361,15 @@ class DeploymentPollingTests(unittest.TestCase): self.invoke() self.assertEqual([call[0] for call in self.calls], ["POST", "GET"]) + def test_sealed_inventory_can_explicitly_exclude_maintenance_but_not_add_foreign_nodes(self): + outcomes = self.status()["nodes"][:1] + self.responses = [self.accepted(), (200, {}, self.status(nodes=outcomes))] + self.assertEqual(self.invoke(on_accepted=lambda *_: {"source-1"})["nodes"], outcomes) + for nodes in ([], {"foreign"}, [True]): + self.responses = [self.accepted()] + with self.subTest(nodes=nodes), self.assertRaises(rig.RigError): + self.invoke(on_accepted=lambda *_: nodes) + def test_no_changes_without_deployment_and_inflight_are_explicit_failures(self): for response in ((200, {}, {"outcome": "NoChanges", "deploymentId": None, "revisionHash": "unit-revision"}), (409, {}, {"outcome": "AnotherDeploymentInFlight"})): @@ -279,3 +419,153 @@ class DeploymentPollingTests(unittest.TestCase): with self.assertRaisesRegex(rig.RigError, "prerequisite|not configured|not wired"): rig.require_production_prerequisites(action, {}) popen.assert_not_called() + + +class RuntimeCompositionTests(unittest.TestCase): + def test_server_identity_context_installs_test_material_and_restores_after_failure(self): + from unittest.mock import Mock + with tempfile.TemporaryDirectory() as folder: + instance = object.__new__(rig.LocalRig); instance.folder = Path(folder) + directory = instance.folder / "security" / "tls" / "source-1" + directory.mkdir(parents=True) + for kind in ("pem", "key"): (directory / ("server." + kind)).write_text("current-" + kind) + instance.inspect_resources = Mock(return_value=[]) + instance.compose = Mock(return_value="") + instance.load = Mock(return_value={}) + instance.refresh_endpoints = Mock(return_value={}) + instance.health = Mock(return_value=True) + with self.assertRaisesRegex(ValueError, "test failure"): + with instance._server_identity_material("source-1", {"pem": "test-pem", "key": "test-key"}): + self.assertEqual((directory / "server.pem").read_text(), "test-pem") + self.assertEqual((directory / "server.key").read_text(), "test-key") + raise ValueError("test failure") + self.assertEqual((directory / "server.pem").read_text(), "current-pem") + self.assertEqual((directory / "server.key").read_text(), "current-key") + self.assertEqual(instance.compose.call_count, 2) + + def test_candidate_checks_every_running_host_and_rejects_stale_binary_stamp(self): + from unittest.mock import Mock + import json + instance = object.__new__(rig.LocalRig) + instance.load = Mock(return_value={"source_tree_hash": "code", "source_revision": "revision", "device_source_hash": "device"}) + def stamp(*args, **kwargs): + return "device\n" if "device" in args else json.dumps({"tree_hash": "code", "revision": "revision"}) + instance.compose = Mock(side_effect=stamp) + with patch.object(rig, "source_tree_hash", return_value="code"), patch.object(rig, "device_tree_hash", return_value="device"): + self.assertEqual(instance.verify_candidate(), "code") + self.assertEqual(instance.compose.call_count, 7) + instance.compose.side_effect = None + instance.compose.return_value = json.dumps({"tree_hash": "old", "revision": "revision"}) + with self.assertRaises(rig.RigError): instance.verify_candidate() + + def test_partition_experiment_rejects_invalid_counts_before_docker(self): + instance = object.__new__(rig.LocalRig) + for count in (True, 0, 257, "4"): + with self.subTest(count=count), self.assertRaises(rig.RigError): + with instance.hub_partitions(count): + self.fail("invalid experiment entered") + + def test_encoding_experiment_uses_only_consumer_pair_and_boolean_preference(self): + from contextlib import nullcontext + from unittest.mock import Mock + instance = object.__new__(rig.LocalRig) + instance._configuration_experiment = Mock(return_value=nullcontext()) + with instance.compact_batches(False): + pass + instance._configuration_experiment.assert_called_once_with("compact-batches", ("consumer-1", "consumer-2"), + {"DataConnections__UseCompactBatches": "false"}) + for value in (0, 1, "false", None): + with self.subTest(value=value), self.assertRaises(rig.RigError): + with instance.compact_batches(value): + self.fail("invalid experiment entered") + + def test_partition_experiment_restores_pair_and_refreshes_ports_on_failure(self): + from unittest.mock import Mock + with tempfile.TemporaryDirectory() as folder: + instance = object.__new__(rig.LocalRig) + instance.folder = Path(folder) + instance.project = "grpc-data-unit" + instance.docker = ["docker", "--context", "unit"] + instance.environment = {} + instance.inspect_resources = Mock(return_value=[]) + instance.load = Mock(return_value={}) + instance.refresh_endpoints = Mock(return_value={"endpoints": {"refreshed": True}}) + instance.capture = Mock() + instance.health = Mock(return_value=True) + with patch.object(rig, "run_command", return_value="") as execute: + with self.assertRaisesRegex(ValueError, "experiment failure"): + with instance.hub_partitions(1): + document = __import__("json").loads((Path(folder) / "hub-partitions.json").read_text()) + self.assertEqual(set(document["services"]), {"source-1", "source-2"}) + raise ValueError("experiment failure") + self.assertEqual(execute.call_count, 2) + self.assertEqual(instance.refresh_endpoints.call_count, 2) + instance.refresh_endpoints.assert_called_with(("source-1", "source-2")) + self.assertEqual(instance.capture.call_args.args[0]["endpoints"], {"refreshed": True}) + self.assertFalse((Path(folder) / "hub-partitions.json").exists()) + + def test_subprocess_is_argv_only_bounded_and_does_not_echo_failure(self): + from processes import ProcessError, ProcessResult + completed = ProcessResult(("unit",), 0, "safe", "", False, False, .1) + with patch("processes.run_process", return_value=completed) as execute: + self.assertEqual(rig.run_command(["unit", "literal;value"], timeout=7), "safe") + self.assertEqual(execute.call_args.args[0], ["unit", "literal;value"]) + self.assertEqual(execute.call_args.kwargs["timeout"], 7) + self.assertEqual(execute.call_args.kwargs["max_output_bytes"], 16 * 1024 * 1024) + for code, timeout, truncated in ((1, False, False), (0, True, False), (0, False, True)): + result = ProcessResult(("unit",), code, "secret", "secret", timeout, truncated, .1) + with patch("processes.run_process", return_value=result): + with self.assertRaises(rig.RigError) as caught: + rig.run_command(["unit"]) + self.assertNotIn("secret", str(caught.exception)) + with patch("processes.run_process", side_effect=ProcessError("secret")): + with self.assertRaises(rig.RigError): rig.run_command(["unit"], timeout=7) + + def test_http_transport_disables_redirects_and_proxy_inheritance(self): + # The actual network adapter is covered through its opener configuration; + # no HTTP/Docker action is allowed in the unit phase. + import inspect + source = inspect.getsource(rig.http_request) + self.assertIn("ProxyHandler({})", source) + self.assertIn("NoRedirect()", source) + self.assertIn("1024 * 1024 + 1", source) + + def test_source_digest_covers_uncommitted_file_contents(self): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "source.cs" + path.write_text("before") + with patch.object(rig, "ROOT", Path(folder)), patch.object(rig, "run_command", return_value="source.cs\0"): + first = rig.source_tree_hash() + path.write_text("after") + self.assertNotEqual(first, rig.source_tree_hash()) + + def test_role_readiness_requires_exactly_one_active_per_independent_pair(self): + instance = object.__new__(rig.LocalRig) + row = {"endpoints": {node + ".admin": {"url": "http://127.0.0.1:" + str(51000 + i)} for i, node in enumerate(rig.NODES)}} + responses = [] + for index, _node in enumerate(rig.NODES): + responses += [(200, {}, None), (200 if index % 2 == 0 else 503, {}, None)] + with patch.object(rig, "http_request", side_effect=responses): + self.assertTrue(instance.health(row)) + with patch.object(rig, "http_request", return_value=(200, {}, None)): + self.assertFalse(instance.health(row)) + + +class AkkaSeedEndpointTests(unittest.TestCase): + def test_named_akka_system_in_owned_seed_context_is_not_a_password(self): + rig.validate_fixture_endpoints({"Cluster__SeedNodes__0": "akka.tcp://otopcua@source-1:4053"}, local_services={"source-1"}) + rig.validate_fixture_endpoints({"SeedNodes": ["akka.tcp://otopcua@source-1:4053"]}, local_services={"source-1"}) + + def test_akka_exception_rejects_other_keys_passwords_systems_paths_and_remote_hosts(self): + variants = [ + {"Endpoint": "akka.tcp://otopcua@source-1:4053"}, + {"Cluster__SeedNodes__0": "akka.tcp://other@source-1:4053"}, + {"Cluster__SeedNodes__0": "akka.tcp://otopcua:password@source-1:4053"}, + {"Cluster__SeedNodes__0": "akka.tcp://otopcua@source-1:4053/escape"}, + {"Cluster__SeedNodes__0": "akka.tcp://otopcua@source-1:4053?key=secret"}, + {"Cluster__SeedNodes__0": "akka.tcp://otopcua@10.100.0.35:4053"}, + {"Cluster__SeedNodes__0": "https://otopcua@source-1:4057"}, + ] + for row in variants: + with self.subTest(row=row), self.assertRaises(rig.RigError): + rig.validate_fixture_endpoints(row, local_services={"source-1"}) diff --git a/scripts/validation/grpc-data/tests/test_scenarios.py b/scripts/validation/grpc-data/tests/test_scenarios.py new file mode 100644 index 000000000..5989d9098 --- /dev/null +++ b/scripts/validation/grpc-data/tests/test_scenarios.py @@ -0,0 +1,391 @@ +"""Pure result, file and orchestration boundaries; no Docker or network calls.""" +import json +import base64 +import copy +import os +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import Mock, call, patch +from urllib.error import URLError + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import scenarios + + +class ProbeResultTests(unittest.TestCase): + def pair_runner(self): + runner = object.__new__(scenarios.ScenarioRunner) + runner.manifest = {'nodes': {'source-1': {}, 'source-2': {}}, + 'endpoints': {'source-1.admin': {'url': 'http://127.0.0.1:51000'}, + 'source-2.admin': {'url': 'http://127.0.0.1:51001'}}} + runner.remaining = Mock(return_value=10) + runner.count = 0 + return runner + + def test_operation_deadlines_leave_room_for_default_write_bounds(self): + self.assertEqual(20, scenarios.probe_timeout_seconds('read', None)) + self.assertEqual(40, scenarios.probe_timeout_seconds('write', None)) + self.assertEqual(40, scenarios.probe_timeout_seconds('mixed-write', None)) + self.assertEqual(70, scenarios.probe_timeout_seconds('dedup', None)) + self.assertEqual(7, scenarios.probe_timeout_seconds('write', 7)) + self.assertEqual(60, scenarios.cli_timeout_seconds('write', 8)) + self.assertEqual(28, scenarios.cli_timeout_seconds('read', 8)) + + def test_primary_observes_partner_after_dead_first_endpoint(self): + runner = self.pair_runner() + with patch.object(scenarios.rig, 'http_request', side_effect=[URLError('refused'), (200, {}, None)]) as request: + self.assertEqual('source-2', runner.primary('source')) + self.assertEqual(2, request.call_count) + + def test_primary_rejects_duplicate_active_pair(self): + runner = self.pair_runner() + with patch.object(scenarios.rig, 'http_request', return_value=(200, {}, None)), self.assertRaises(scenarios.ScenarioError): + runner.primary('source') + + def test_wait_primary_can_observe_startup_then_partner_without_assuming_health(self): + runner = self.pair_runner() + with patch.object(scenarios.rig, 'http_request', side_effect=[(503, {}, None), (500, {}, None), + URLError('still starting'), (200, {}, None)]), patch.object(scenarios.time, 'sleep') as sleep: + self.assertEqual('source-2', runner.wait_primary('source', exclude='source-1')) + sleep.assert_called_once() + + def test_pair_topology_waits_for_both_expected_up_views(self): + runner = self.pair_runner() + runner.node_id = Mock(side_effect=lambda node: node + ":4053") + members = [{"host": node, "port": 4053, "status": "Up"} for node in runner.manifest["nodes"]] + states = [{"self": f"akka.tcp://otopcua@{node}:4053", "members": members} + for node in runner.manifest["nodes"]] + wrong_peer = {**states[1], "members": [members[1], {**members[0], "host": "consumer-1"}]} + runner.probe = Mock(side_effect=[scenarios.ScenarioError("peer still joining"), + states[0], wrong_peer, *states]) + with patch.object(scenarios.time, "sleep"): + runner.wait_pair_topology("source") + self.assertEqual([("source-1", "topology"), ("source-1", "topology"), ("source-2", "topology"), + ("source-1", "topology"), ("source-2", "topology")], + [call.args for call in runner.probe.call_args_list]) + + def test_pair_topology_rejects_persistent_singleton(self): + runner = self.pair_runner() + runner.node_id = Mock(side_effect=lambda node: node + ":4053") + runner.probe = Mock(side_effect=scenarios.ScenarioError("singleton")) + with patch.object(scenarios.time, "monotonic", side_effect=[0, 0, 11, 11]), patch.object(scenarios.time, "sleep"), \ + self.assertRaisesRegex(scenarios.ScenarioError, "both expected Up members"): + runner.wait_pair_topology("source") + self.assertEqual(1, runner.probe.call_count) + + def test_baseline_restoration_uses_its_own_deploy_readiness_budget_after_scenario_expiry(self): + runner = object.__new__(scenarios.ScenarioRunner) + runner.deadline = -1 + runner.remaining = Mock(side_effect=scenarios.ScenarioError('scenario already expired')) + runner.rig = Mock() + runner.rig.deploy.return_value = {'state': 'ready'} + runner.baseline() + runner.rig.seed_helper.assert_called_once_with('restore') + runner.rig.restore_security.assert_called_once_with() + runner.rig.deploy.assert_called_once_with(timeout=180) + runner.remaining.assert_not_called() + self.assertEqual({'state': 'ready'}, runner.manifest) + + def test_maintenance_restoration_waits_after_seed_and_posts_once(self): + runner = object.__new__(scenarios.ScenarioRunner) + runner.rig = Mock() + runner.timeline = [] + operations = Mock() + operations.attach_mock(runner.rig, 'rig') + with patch.object(scenarios.time, 'sleep') as sleep: + operations.attach_mock(sleep, 'sleep') + runner.baseline(maintenance_changed=True) + self.assertEqual([ + call.rig.seed_helper('restore'), call.rig.restore_security(), + call.sleep(scenarios.MAINTENANCE_CONTACT_SETTLE_SECONDS), + call.rig.deploy(timeout=180) + ], operations.mock_calls) + self.assertEqual('maintenance-contact-settle', runner.timeline[0]['event']) + + def test_positive_read_requires_observed_ready_and_finite_requested_age(self): + observed = {'status': 'Good', 'resultReadiness': 'Ready', 'maximumAgeMilliseconds': 5000, + 'ageBounds': {'lowerMilliseconds': 100, 'upperMilliseconds': 120}} + self.assertIs(observed, scenarios.validate_read_freshness(observed)) + for field, value in (('resultReadiness', 'Unavailable'), ('maximumAgeMilliseconds', None), ('ageBounds', None)): + with self.subTest(field=field), self.assertRaises(scenarios.ScenarioError): + scenarios.validate_read_freshness({**observed, field: value}) + for lower, upper in ((None, 120), (100, None), (-1, 120), (121, 120), (100, 5001), (100, float('inf')), (False, 120)): + with self.subTest(lower=lower, upper=upper), self.assertRaises(scenarios.ScenarioError): + scenarios.validate_read_freshness({**observed, 'ageBounds': {'lowerMilliseconds': lower, 'upperMilliseconds': upper}}) + scenarios.validate_read_freshness({**observed, 'maximumAgeMilliseconds': None, 'ageBounds': None}, None) + + def test_positive_transition_poll_requires_actual_ready_and_fresh_sample_on_pinned_route(self): + runner = object.__new__(scenarios.ScenarioRunner) + runner.remaining = Mock(return_value=30) + runner.node_id = Mock(return_value='source-2:4053') + expected = {'status': 'Good', 'resultReadiness': 'Ready'} + runner.probe = Mock(side_effect=[scenarios.ScenarioError('catalog activating'), {'readiness': 'Ready'}, expected]) + with patch.object(scenarios.time, 'sleep'): + self.assertIs(expected, runner.wait_connection_ready('consumer-1', 'uns', expected_node='source-2', require_fresh_sample=True)) + self.assertEqual(['capabilities', 'capabilities', 'read'], [call.args[1] for call in runner.probe.call_args_list]) + self.assertTrue(all(call.kwargs['expectedNodeId'] == 'source-2:4053' for call in runner.probe.call_args_list)) + + def test_permanent_unreadiness_still_fails_at_bounded_deadline(self): + runner = object.__new__(scenarios.ScenarioRunner) + runner.remaining = Mock(return_value=30) + runner.probe = Mock(side_effect=scenarios.ScenarioError('permanently unavailable')) + with patch.object(scenarios.time, 'monotonic', side_effect=[0, 0, 31]), self.assertRaises(scenarios.ScenarioError): + runner.wait_connection_ready('consumer-1', require_fresh_sample=True) + self.assertEqual(1, runner.probe.call_count) + + def test_uns_browse_container_is_explicit_equipment_id_and_leaf_paths_stay_physical(self): + fixture = {'browse_roots': {'raw': 'modbus/plc', 'uns': 'EQ-fixture'}, + 'origin_paths': {'raw': 'modbus/plc/scalar', 'uns': 'area/line/plc/scalar'}} + self.assertEqual('EQ-fixture', scenarios.fixture_browse_root(fixture, 'uns')) + self.assertEqual('EQ-fixture', scenarios.relative_origin_identifier(fixture, 'uns', 'area/line/plc/scalar', '')) + self.assertEqual('area/line/plc/counter', scenarios.relative_origin_identifier(fixture, 'uns', 'area/line/plc/scalar', 'counter')) + self.assertEqual('modbus/plc', scenarios.relative_origin_identifier(fixture, 'raw', 'modbus/plc/scalar', '')) + with self.assertRaises(scenarios.ScenarioError): + scenarios.fixture_browse_root({'origin_paths': fixture['origin_paths']}, 'uns') + + def test_native_and_projected_uns_parent_nodeids_use_same_stable_container(self): + runner = object.__new__(scenarios.ScenarioRunner) + runner.manifest = {'fixture': {'browse_roots': {'raw': 'modbus/plc', 'uns': 'EQ-fixture'}}} + runner.leaf = Mock(return_value='ns=3;s=area/line/plc/scalar') + self.assertEqual('ns=3;s=EQ-fixture', runner.relative_node('source-1', 'uns', '')) + self.assertEqual('ns=3;s=area/line/plc/new-child', runner.relative_node('source-1', 'uns', 'new-child')) + payload = {'MappingId': 'map-uns', 'Origin': {'OriginClusterId': 'SOURCE', 'NamespaceUri': 'urn:fixture:uns', + 'IdentifierKind': 'string', 'Identifier': 'area/line/plc/scalar'}} + token = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip('=') + runner.leaf = Mock(return_value='ns=5;s=p1.' + token) + parent = runner.relative_node('consumer-1', 'uns', '', mapping_id='same-uns') + encoded = parent.split(';s=p1.', 1)[1] + decoded = json.loads(base64.urlsafe_b64decode(encoded + '=' * (-len(encoded) % 4))) + self.assertEqual('EQ-fixture', decoded['Origin']['Identifier']) + self.assertEqual('same-uns', decoded['MappingId']) + self.assertEqual('urn:fixture:uns', decoded['Origin']['NamespaceUri']) + + def test_tls_negative_requires_same_process_observer_and_no_http_arrival(self): + before = {'inboundDataRequestObserverId': 'one', 'inboundDataRequests': 0} + self.assertEqual(scenarios.validate_tls_rejection_counters(before, dict(before))['http_requests_after'], 0) + for change in ({'inboundDataRequestObserverId': 'two'}, {'inboundDataRequests': 1}, {'inboundDataRequests': None}): + with self.subTest(change=change), self.assertRaises(scenarios.ScenarioError): + scenarios.validate_tls_rejection_counters(before, {**before, **change}) + + def test_quiet_lease_wait_uses_observed_finite_bounded_duration(self): + self.assertEqual(scenarios.metadata_lease_seconds({'duration': '00:00:15.0000000'}), 15) + for lease in (None, {}, {'duration': '01:00:00'}, {'duration': '00:00:00'}, {'duration': True}, {'duration': '00:60:01'}): + with self.subTest(lease=lease), self.assertRaises(scenarios.ScenarioError): + scenarios.metadata_lease_seconds(lease) + + def test_chunked_live_notifications_accept_actual_good_numeric_status_once(self): + parser = scenarios.NotificationLines() + line = "[2026-11-17T03:00:00.1234567Z] ns=4;s=fixture = 42 (Good [0x00000000])\r\n" + self.assertEqual(parser.feed(line[:50]), []) + rows = parser.feed(line[50:]) + self.assertEqual(len(rows), 1) + self.assertTrue(scenarios.cli_gate.is_good_status(rows[0]['status'])) + self.assertEqual(rows[0]['value'], '42') + self.assertEqual(parser.feed('summary line\n'), []) + rows = parser.feed(line.replace('Good [0x00000000]', 'BadNoCommunication [0x80310000]')) + self.assertTrue(rows[0]['status'].startswith('Bad')) + + def cells(self, selected=scenarios.SCENARIOS): + rows = [] + for cell in scenarios.MATRIX_CELLS: + if cell['scenario'] not in selected: + continue + caller = 'source-1:4053' if cell['caller_cluster'] == 'SOURCE' else 'consumer-1:4053' + unavailable = cell['outcome'] == 'Unavailable' or cell['boundary'] == 'pinned-loss' + probe = {'callerNodeId': caller, 'callerClusterId': cell['caller_cluster'], 'realm': cell['realm'], + 'namespaceUri': 'urn:fixture:' + cell['realm'], 'path': 'fixture/' + cell['realm'] + '/scalar', + 'target': {'mode': cell['target_mode'], 'expectedClusterId': 'SOURCE', + 'consistency': cell['target_consistency'], + 'expectedNodeId': 'source-2:4053' if cell['target_mode'] == 'Node' else None}, + 'readiness': 'Unavailable' if unavailable else 'Ready'} + if not unavailable: + probe['serving'] = {'nodeId': 'source-2:4053', 'role': 'Secondary' if cell['boundary'] == 'secondary' else 'Primary'} + rows.append({**cell, 'validated': True, 'caller_node_id': caller, + 'serving_node_id': None if unavailable else 'source-2:4053', + 'evidence': {'probe': probe, **({'cli': {'validated': 'actual process'}} if cell['surface'] == 'mounted' else {})}}) + return rows + + def result(self, **changes): + result = {"id": "D01a-unit", "operation": "read", "passed": True, + "assertions": 3, "observations": {"serving": {"nodeId": "source-2:4053"}}} + result.update(changes) + return result + + def test_nonempty_exact_requested_probe_result(self): + self.assertEqual(scenarios.validate_probe_result(self.result(), expected_id="D01a-unit", expected_operation="read")["assertions"], 3) + + def test_false_zero_boolean_wrong_id_operation_and_absent_evidence_fail(self): + for changes in ({"passed": False}, {"assertions": 0}, {"assertions": True}, {"id": "another"}, + {"operation": "write"}, {"observations": None}): + with self.subTest(changes=changes), self.assertRaises(scenarios.ScenarioError): + scenarios.validate_probe_result(self.result(**changes), expected_id="D01a-unit", expected_operation="read") + + def test_all_required_ids_include_direct_case_and_have_concrete_methods(self): + self.assertEqual(set(scenarios.SCENARIOS), {"D01", "D01a", *(f"D{n:02}" for n in range(2, 15))}) + for name in scenarios.SCENARIOS: + self.assertTrue(callable(getattr(scenarios.ScenarioRunner, "scenario_" + name))) + + def test_rows_require_exact_coverage_nonzero_assertions_and_successful_restoration(self): + rows = [{"id": name, "passed": True, "assertions": 1, "restored": True, 'cells': self.cells((name,))} for name in scenarios.SCENARIOS] + self.assertTrue(scenarios.validate_scenario_rows(rows, scenarios.SCENARIOS)) + with self.assertRaises(scenarios.ScenarioError): + scenarios.validate_scenario_rows(rows[:-1], scenarios.SCENARIOS) + with self.assertRaises(scenarios.ScenarioError): + scenarios.validate_scenario_rows(list(reversed(rows)), scenarios.SCENARIOS) + for field, value in (("assertions", 0), ("assertions", True), ("restored", False), ("passed", False)): + changed = [dict(row) for row in rows] + changed[0][field] = value + self.assertFalse(scenarios.validate_scenario_rows(changed, scenarios.SCENARIOS)) + + def test_catalog_contains_exact_required_observed_matrix(self): + catalog = json.loads((Path(scenarios.__file__).parent / 'scenarios.json').read_text()) + self.assertEqual(scenarios.MATRIX_CELLS, catalog['required_cells']) + self.assertTrue(scenarios.validate_matrix_cells(self.cells())) + + def test_named_passing_scenarios_without_actual_cells_cannot_pass(self): + rows = [{'id': name, 'passed': True, 'assertions': 100, 'restored': True, 'cells': []} for name in scenarios.SCENARIOS] + self.assertFalse(scenarios.validate_scenario_rows(rows, scenarios.SCENARIOS)) + for changed in (self.cells()[:-1], self.cells() + [self.cells()[0]]): + with self.assertRaises(scenarios.ScenarioError): + scenarios.validate_matrix_cells(changed) + + def test_matrix_rejects_echoed_labels_with_wrong_actual_caller_target_or_realm(self): + for field, value in (('callerNodeId', 'another:4053'), ('callerClusterId', 'SOURCE'), ('realm', 'other')): + cells = self.cells() + cells[0]['evidence']['probe'][field] = value + with self.subTest(field=field), self.assertRaises(scenarios.ScenarioError): + scenarios.validate_matrix_cells(cells) + cells = self.cells() + cells[0]['evidence']['probe']['target']['mode'] = 'Node' + with self.assertRaises(scenarios.ScenarioError): + scenarios.validate_matrix_cells(cells) + cells = self.cells() + pinned = next(cell for cell in cells if cell['target_mode'] == 'Node' and cell['outcome'] == 'Good') + pinned['evidence']['probe']['target']['expectedNodeId'] = 'source-1:4053' + with self.assertRaises(scenarios.ScenarioError): + scenarios.validate_matrix_cells(cells) + + def test_live_recovery_requires_changing_good_after_actual_stop(self): + notifications = [{'at': 1, 'value': '41', 'status': 'Good'}, {'at': 2.5, 'value': '', 'status': 'BadNotConnected'}, + {'at': 4, 'value': '65535', 'status': 'Good'}] + sentinel = {'value': '65535', 'reserved_at': 0, 'produced_at': 3.5, 'confirmed_at': 3.6} + self.assertEqual(1, scenarios.validate_fault_notifications(notifications, fault_at=2, effective_at=3, + require_gap=True, required_sentinel=sentinel)['post_fault_good']) + for rows in (notifications[:1], notifications[:2], [{**row, 'value': '41'} for row in notifications], + [notifications[0], {**notifications[-1], 'at': 2.7}]): + with self.subTest(rows=rows), self.assertRaises(scenarios.ScenarioError): + scenarios.validate_fault_notifications(rows, fault_at=2, effective_at=3, require_gap=False, required_sentinel=sentinel) + + def test_revocation_requires_quiet_unauthorized_interval_and_later_good(self): + notifications = [{'at': 1, 'value': '41', 'status': 'Good'}, {'at': 2.5, 'value': '', 'status': 'BadUserAccessDenied'}, + {'at': 6, 'value': '65535', 'status': 'Good'}] + sentinel = {'value': '65535', 'reserved_at': 0, 'produced_at': 5.5, 'confirmed_at': 5.6} + scenarios.validate_fault_notifications(notifications, fault_at=2, require_gap=True, required_sentinel=sentinel, + withdrawal_at=2.5, reauthorization_at=5, reauthorization_completed_at=5.4) + with self.assertRaises(scenarios.ScenarioError): + scenarios.validate_fault_notifications(notifications + [{'at': 3.5, 'value': '99', 'status': 'Good'}], + fault_at=2, require_gap=True, required_sentinel=sentinel, + withdrawal_at=2.5, reauthorization_at=5, reauthorization_completed_at=5.4) + with self.assertRaises(scenarios.ScenarioError): + scenarios.validate_fault_notifications(notifications, fault_at=2, require_gap=True, required_sentinel=sentinel, + withdrawal_at=2.5, reauthorization_at=2.6, reauthorization_completed_at=5.4) + with self.assertRaises(scenarios.ScenarioError): + scenarios.validate_fault_notifications(notifications, fault_at=2, require_gap=True, required_sentinel=sentinel, + withdrawal_at=2.5, reauthorization_at=5, reauthorization_completed_at=5.7) + + def test_delayed_prefault_output_cannot_substitute_for_postfault_source_sentinel(self): + sentinel = {'value': '65535', 'reserved_at': 0, 'produced_at': 3.5, 'confirmed_at': 3.6} + buffered = [{'at': 1, 'value': '41', 'status': 'Good'}, {'at': 4, 'value': '42', 'status': 'Good [0x00000000]'}] + with self.assertRaisesRegex(scenarios.ScenarioError, 'newly produced recovery sentinel'): + scenarios.validate_fault_notifications(buffered, fault_at=2, effective_at=3, require_gap=False, required_sentinel=sentinel) + observed = buffered + [{'at': 5, 'value': '65535', 'status': 'Good [0x00000000]'}] + result = scenarios.validate_fault_notifications(observed, fault_at=2, effective_at=3, require_gap=False, required_sentinel=sentinel) + self.assertEqual(1, result['sentinel_notifications']) + with self.assertRaises(scenarios.ScenarioError): + scenarios.validate_fault_notifications(observed + [{'at': 1.5, 'value': '65535', 'status': 'Good'}], + fault_at=2, effective_at=3, require_gap=False, required_sentinel=sentinel) + + def test_sentinel_production_must_follow_actual_fault_and_be_reserved_before_it(self): + notifications = [{'at': 1, 'value': '41', 'status': 'Good'}, {'at': 4, 'value': '65535', 'status': 'Good'}] + sentinel = {'value': '65535', 'reserved_at': 0, 'produced_at': 3.5, 'confirmed_at': 3.6} + for field, value in (('reserved_at', 2.1), ('produced_at', 2.8), ('confirmed_at', 3.4), ('value', '42')): + with self.subTest(field=field), self.assertRaises(scenarios.ScenarioError): + scenarios.validate_fault_notifications(notifications, fault_at=2, effective_at=3, + require_gap=False, required_sentinel={**sentinel, field: value}) + + def test_controlled_source_reserves_unique_high_sentinel_and_pauses_until_observed(self): + state = {'writable': {'20': 65535}} + calls = [] + def device(action, **fields): + calls.append((action, fields)) + if action == 'set': + state['writable']['20'] = fields['value'] + return copy.deepcopy(state) + used = {65534} + producer = scenarios.ControlledFixtureSource(device, 65535, used) + self.assertEqual(65533, producer.sentinel_value) + self.assertTrue(producer.tick()) + self.assertEqual(0, state['writable']['20']) + with producer.sentinel() as challenge: + self.assertEqual('65533', challenge['value']) + self.assertEqual(65533, state['writable']['20']) + prior_calls = len(calls) + self.assertFalse(producer.tick()) + self.assertEqual(prior_calls, len(calls)) + self.assertTrue(producer.paused.is_set()) + self.assertFalse(producer.paused.is_set()) + self.assertTrue(producer.tick()) + self.assertEqual(1, state['writable']['20']) + next_producer = scenarios.ControlledFixtureSource(device, 1, used) + self.assertEqual(65532, next_producer.sentinel_value) + with self.assertRaises(scenarios.ScenarioError): + with producer.sentinel(): + pass + + def test_failed_sentinel_write_always_releases_the_paused_producer(self): + producer = scenarios.ControlledFixtureSource(Mock(side_effect=scenarios.ScenarioError('fixture write failed')), 42, set()) + with self.assertRaises(scenarios.ScenarioError): + with producer.sentinel(): + pass + self.assertFalse(producer.paused.is_set()) + + def test_restricted_file_rejects_world_readable_and_links(self): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "result.json" + path.write_text(json.dumps(self.result())) + path.chmod(0o600) + self.assertTrue(scenarios.restricted_json(path)["passed"]) + link = Path(folder) / "linked.json" + link.symlink_to(path) + with self.assertRaises(scenarios.ScenarioError): + scenarios.restricted_json(link) + if os.name != "nt": + path.chmod(0o644) + with self.assertRaises(scenarios.ScenarioError): + scenarios.restricted_json(path) + + def test_scenario_failure_still_restores_and_never_becomes_a_skip(self): + runner = object.__new__(scenarios.ScenarioRunner) + runner.manifest = {"run_id": "unit-run"} + runner.rig = Mock() + runner.folder = Path("/unused") + runner.timeline = [] + runner.secrets = [] + runner.publish = Mock() + runner.baseline = Mock() + runner.save = Mock() + runner.device = Mock(return_value={"effect_total": 0}) + runner.scenario_D01 = Mock(side_effect=scenarios.ScenarioError("wire observation missing")) + with patch.object(Path, "iterdir", return_value=iter(())): + report = runner.run("D01") + runner.baseline.assert_called_once_with(maintenance_changed=False) + self.assertFalse(report["passed"]) + self.assertEqual(report["rows"][0]["assertions"], 0) + self.assertTrue(report["rows"][0]["restored"]) + self.assertIn("wire observation missing", report["rows"][0]["failure"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/validation/grpc-data/tests/test_warm_secondary_fixture.py b/scripts/validation/grpc-data/tests/test_warm_secondary_fixture.py new file mode 100644 index 000000000..d021852d7 --- /dev/null +++ b/scripts/validation/grpc-data/tests/test_warm_secondary_fixture.py @@ -0,0 +1,59 @@ +"""Warm standby data readiness is measured separately from catalog/API availability.""" +from contextlib import nullcontext +from copy import deepcopy +from pathlib import Path +import sys +import unittest +from unittest.mock import Mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import scenarios + + +def observation(status="WaitingForInitialData", readiness="WaitingForInitialData", *, primary=False): + return {"readiness": "Ready", "status": status, "resultReadiness": readiness, "sample": None, + "maximumAgeMilliseconds": 5000, "ageBounds": {"lowerMilliseconds": 0, "upperMilliseconds": 1}, + "serving": {"nodeId": "source-2:4053", "role": "Primary" if primary else "Secondary", + "incarnation": "unit", "catalogEpoch": 4, "authorityEpoch": 4, "servingGeneration": 4 if primary else 3}, + "target": {"mode": "Node", "expectedNodeId": "source-2:4053", "expectedClusterId": "SOURCE", "consistency": "ReadyReplica"}} + + +class WarmSecondaryFixtureTests(unittest.TestCase): + def test_catalog_ready_with_waiting_or_unavailable_payloadless_read_is_allowed(self): + for state in ("WaitingForInitialData", "Unavailable"): + actual = observation(state, state) + self.assertIs(scenarios.validate_warm_secondary_read(actual, expected_node_id="source-2:4053"), actual) + + def test_good_stale_ready_payload_or_wrong_serving_cannot_pass_warm_negative(self): + changes = [{"status": "Good"}, {"status": "Stale"}, {"resultReadiness": "Ready"}, + {"sample": {"value": 42}}, {"sample": "missing"}, + {"serving": dict(observation()["serving"], nodeId="source-1:4053")}, + {"serving": dict(observation()["serving"], role="Primary")}, + {"target": dict(observation()["target"], mode="Cluster")}] + for change in changes: + actual = deepcopy(observation()) + actual.update(change) + if change.get("sample") == "missing": + del actual["sample"] + with self.subTest(change=change), self.assertRaises(scenarios.ScenarioError): + scenarios.validate_warm_secondary_read(actual, expected_node_id="source-2:4053") + + def test_d09_retains_hot_matrix_before_entering_real_warm_startup(self): + runner = object.__new__(scenarios.ScenarioRunner) + runner.manifest = {"nodes": {"source-1": {}, "source-2": {}, "consumer-1": {}}} + runner.primary = Mock(side_effect=lambda pair: pair + "-1") + runner.node_id = Mock(side_effect=lambda node: node + ":4053") + runner.mutate = Mock() + runner.matrix_probe = Mock(return_value={"serving": dict(observation()["serving"], catalogEpoch=3, authorityEpoch=3)}) + runner.device = Mock(return_value={"effect_total": 0}) + runner.check = Mock(side_effect=lambda valid, message: self.assertTrue(valid, message)) + runner.rig = Mock() + runner.rig._configuration_experiment.side_effect = RuntimeError("Warm startup entered") + runner.probe = Mock(side_effect=AssertionError("artifact-only Warm must not be mistaken for real startup Warm")) + with self.assertRaisesRegex(RuntimeError, "Warm startup entered"): + runner.scenario_D09() + self.assertEqual(runner.matrix_probe.call_count, 4) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/validation/grpc-data/tests/test_warm_startup_fixture.py b/scripts/validation/grpc-data/tests/test_warm_startup_fixture.py new file mode 100644 index 000000000..4d728e905 --- /dev/null +++ b/scripts/validation/grpc-data/tests/test_warm_startup_fixture.py @@ -0,0 +1,117 @@ +"""Actual startup Warm state and exact authenticated target rejection are independent proofs.""" +from contextlib import contextmanager +from copy import deepcopy +from pathlib import Path +import sys +import unittest +from unittest.mock import Mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import scenarios + + +def warm_state(node, role, generation=3): + return {"nodeId": node + ":4053", "mode": "Warm", "isWarm": True, + "warmRole": {"role": role, "generation": generation}, + "serving": {"nodeId": node + ":4053", "role": "Primary" if role == "Active" else "Standby", + "incarnation": "warm-" + node, "catalogEpoch": 4, "authorityEpoch": 4, "servingGeneration": generation}, + "process": {"id": 11 if node == "source-1" else 12, "startedUtc": "2026-11-17T00:00:00Z"}} + + +def rejection(node="source-1"): + return {"readiness": "Unavailable", "selectionRejection": "TargetIneligible", "failurePhase": "GetCapabilities", + "failureEvidence": {"category": "TargetIneligible", "truncated": False, + "chain": [{"code": "NoReadyEndpoint"}, {"code": "TargetIneligible"}]}, + "target": {"mode": "Node", "expectedClusterId": "SOURCE", "expectedNodeId": node + ":4053", "consistency": "ReadyReplica"}} + + +class WarmStartupFixtureTests(unittest.TestCase): + def test_actual_roles_select_warm_standby_instead_of_old_hot_secondary(self): + states = {"source-1": warm_state("source-1", "Standby"), "source-2": warm_state("source-2", "Active")} + self.assertEqual(scenarios.select_warm_pair(states), ("source-2", "source-1")) + for change in ({"mode": "Unset"}, {"isWarm": False}, {"warmRole": {"role": "Standby", "generation": 0}}, + {"nodeId": "other:4053"}): + bad = deepcopy(states) + bad["source-1"].update(change) + with self.subTest(change=change), self.assertRaises(scenarios.ScenarioError): + scenarios.select_warm_pair(bad) + + def test_only_known_target_ineligible_chain_and_exact_source_standby_proof_pass(self): + actual, source = rejection(), warm_state("source-1", "Standby") + self.assertIs(scenarios.validate_warm_target_rejection(actual, source, expected_node_id="source-1:4053"), actual) + + def test_tls_transport_rpc_backoff_truncation_and_wrong_target_cannot_pass(self): + cases = [dict(rejection(), failurePhase="Read"), dict(rejection(), sample={"value": 42}), + dict(rejection(), target=dict(rejection()["target"], expectedNodeId="source-2:4053")), + dict(rejection(), failureEvidence={"category": "TargetIneligible", "truncated": True, "chain": []}), + dict(rejection(), failureEvidence={"category": "TargetIneligible", "truncated": False, + "chain": [{"code": "NoReadyEndpoint"}, {"code": "TransportFailure"}]}), + dict(rejection(), failureEvidence={"category": "TargetIneligible", "truncated": False, + "chain": [{"code": "NoReadyEndpoint"}, {"code": "RpcFailure", "rpcStatus": "Unavailable"}]}), + dict(rejection(), failureEvidence={"category": "TargetIneligible", "truncated": False, + "chain": [{"code": "DiscoveryBackoff"}]}), + dict(rejection(), failureEvidence={"category": "TargetIneligible", "truncated": False, + "chain": [{"code": "NoReadyEndpoint"}, {"code": "TlsFailure"}]}), + dict(rejection(), failureEvidence={"category": "TargetIneligible", "truncated": False, + "chain": [{"code": "TargetIneligible"}] * 9})] + for actual in cases: + with self.subTest(actual=actual), self.assertRaises(scenarios.ScenarioError): + scenarios.validate_warm_target_rejection(actual, warm_state("source-1", "Standby"), expected_node_id="source-1:4053") + + def test_d09_uses_real_startup_override_actual_standby_and_restores_before_outer_baseline(self): + runner = object.__new__(scenarios.ScenarioRunner) + runner.manifest = {"nodes": {"source-1": {}, "source-2": {}, "consumer-1": {}}} + runner.primary = Mock(side_effect=lambda pair: pair + "-1") + runner.node_id = Mock(side_effect=lambda node: node + ":4053") + hot = {"nodeId": "source-2:4053", "role": "Secondary", "incarnation": "hot", "servingGeneration": 1} + runner.matrix_probe = Mock(return_value={"serving": hot}) + events, reads = [], [10] + runner.device = Mock(side_effect=lambda: {"effect_total": 0, "read_total": reads[0]}) + runner.check = Mock(side_effect=lambda valid, message: self.assertTrue(valid, message)) + runner.rig = Mock() + runner.rig.load.return_value = runner.manifest + runner.rig.seed_helper.side_effect = AssertionError("no global resolver inside Warm startup context") + @contextmanager + def configuration(name, nodes, environment): + self.assertEqual(nodes, ("source-1", "source-2")) + self.assertEqual(environment, {"OpcUa__Redundancy__Mode": "Warm"}) + events.append("startup Warm") + try: + yield + finally: + events.append("startup restored") + runner.rig._configuration_experiment.side_effect = configuration + runner.mutate = Mock(side_effect=lambda **fields: events.append(fields)) + states = {"source-1": warm_state("source-1", "Standby"), "source-2": warm_state("source-2", "Active")} + runner.wait_warm_pair = Mock(return_value=states) + runner.wait_warm_state = Mock(side_effect=lambda node, role: warm_state(node, role, 4 if role == "Active" else 3)) + runner.wait_connection_ready, runner.save = Mock(), Mock() + runner.remaining = Mock(side_effect=lambda maximum: maximum) + runner.baseline = Mock(side_effect=AssertionError("outer baseline must follow startup restoration")) + @contextmanager + def stopped(node): + self.assertEqual(node, "source-2") + events.append("stop Warm Active") + yield + runner.stopped = stopped + def probe(node, operation, realm="raw", **fields): + if fields.get("expected_state") == "TargetIneligible": + return rejection() + active = warm_state("source-1", "Active", 4) + reads[0] += 1 + return {"serving": active["serving"], "status": "Good", "resultReadiness": "Ready", "maximumAgeMilliseconds": 5000, + "ageBounds": {"lowerMilliseconds": 0, "upperMilliseconds": 1}, "sample": {"value": 42, "serving": active["serving"]}} + runner.probe = Mock(side_effect=probe) + runner.scenario_D09() + self.assertEqual(runner.matrix_probe.call_count, 4) + self.assertLess(events.index("startup Warm"), events.index({"source_redundancy_mode": "Warm"})) + self.assertIn({"target_mode": "Node", "target_node_id": "source-1:4053", "consistency": "ReadyReplica"}, events) + self.assertEqual(events[-1], "startup restored") + runner.baseline.assert_not_called() + for realm in ("raw", "uns"): + runner.probe.assert_any_call("consumer-1", "read", realm, expected_state="TargetIneligible", expectedNodeId="source-1:4053") + runner.probe.assert_any_call("consumer-1", "read", realm, expected_state="Good", expectedNodeId="source-1:4053", expectedRole="Primary") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/validation/grpc-data/unit-phases.json b/scripts/validation/grpc-data/unit-phases.json index 7cd9627f1..fb8a38ec0 100644 --- a/scripts/validation/grpc-data/unit-phases.json +++ b/scripts/validation/grpc-data/unit-phases.json @@ -610,5 +610,42 @@ "DriverHostActorDiagnosticsTests" ] } + ], + "P10": [ + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/ZB.MOM.WW.OtOpcUa.Host.Tests.csproj", + "filter": "FullyQualifiedName~.GrpcDataFixtureIsolationTests.", + "new_classes": [ + "GrpcDataFixtureIsolationTests" + ], + "existing_classes": [] + }, + { + "project": "tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests.csproj", + "filter": "FullyQualifiedName~.ReadResultValidationTests.|FullyQualifiedName~.OpcUaClientServiceTests.ReadValueAsync_MaximumAge", + "new_classes": [ + "ReadResultValidationTests" + ], + "existing_classes": [ + "OpcUaClientServiceTests" + ] + }, + { + "project": "tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests.csproj", + "filter": "FullyQualifiedName~.ReadCommandTests.|FullyQualifiedName~.SubscribeCommandSummaryTests.", + "new_classes": [], + "existing_classes": [ + "ReadCommandTests", + "SubscribeCommandSummaryTests" + ] + }, + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj", + "filter": "FullyQualifiedName~.GrpcDataProjectedAccessTests.", + "new_classes": [], + "existing_classes": [ + "GrpcDataProjectedAccessTests" + ] + } ] } diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/ReadCommand.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/ReadCommand.cs index db1ab1fd6..aac885270 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/ReadCommand.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/ReadCommand.cs @@ -25,9 +25,16 @@ public class ReadCommand : CommandBase [CommandOption("node", 'n', Description = "Node ID (e.g. ns=2;s=MyNode)", IsRequired = true)] public string NodeId { get; init; } = default!; + /// Gets the maximum acceptable cache age in milliseconds. + [CommandOption("max-age", Description = "Maximum cached value age in milliseconds (0 to 2147483647; default 0)")] + public double MaxAgeMilliseconds { get; init; } + /// public override async ValueTask ExecuteAsync(IConsole console) { + if (!double.IsFinite(MaxAgeMilliseconds) || MaxAgeMilliseconds < 0 || MaxAgeMilliseconds > int.MaxValue) + throw new CommandException("Invalid --max-age value: expected a finite number from 0 to 2147483647 milliseconds."); + ConfigureLogging(); NodeId nodeId; @@ -49,7 +56,9 @@ public class ReadCommand : CommandBase DataValue value; try { - value = await service.ReadValueAsync(nodeId, ct); + value = MaxAgeMilliseconds == 0 + ? await service.ReadValueAsync(nodeId, ct) + : await service.ReadValueAsync(nodeId, TimeSpan.FromMilliseconds(MaxAgeMilliseconds), ct); } catch (ServiceResultException ex) when (ex.StatusCode != StatusCodes.BadSessionIdInvalid && ex.StatusCode != StatusCodes.BadConnectionClosed @@ -67,8 +76,8 @@ public class ReadCommand : CommandBase await console.Output.WriteLineAsync($"Node: {NodeId}"); await console.Output.WriteLineAsync($"Value: {ValueFormatter.Format(ValueConverter.ToClrObject(value.WrappedValue))}"); await console.Output.WriteLineAsync($"Status: {value.StatusCode}"); - await console.Output.WriteLineAsync($"Source Time: {value.SourceTimestamp:O}"); - await console.Output.WriteLineAsync($"Server Time: {value.ServerTimestamp:O}"); + await console.Output.WriteLineAsync($"Source Time: {value.SourceTimestamp.ToString("O")}"); + await console.Output.WriteLineAsync($"Server Time: {value.ServerTimestamp.ToString("O")}"); } finally { diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/SubscribeCommand.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/SubscribeCommand.cs index a205ce313..05bed3b86 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/SubscribeCommand.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/SubscribeCommand.cs @@ -131,7 +131,7 @@ public class SubscribeCommand : CommandBase if (!Quiet) { var line = - $"[{e.Value.SourceTimestamp:O}] {displayNameByNodeId.GetValueOrDefault(key, key)} = {ValueFormatter.Format(ValueConverter.ToClrObject(e.Value.WrappedValue))} ({e.Value.StatusCode})"; + $"[{e.Value.SourceTimestamp.ToString("O")}] {displayNameByNodeId.GetValueOrDefault(key, key)} = {ValueFormatter.Format(ValueConverter.ToClrObject(e.Value.WrappedValue))} ({e.Value.StatusCode})"; outputChannel.Writer.TryWrite(line); } } diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/WriteCommand.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/WriteCommand.cs index 1810d2867..6107662cb 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/WriteCommand.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/WriteCommand.cs @@ -1,3 +1,4 @@ +using System.Globalization; using CliFx.Attributes; using CliFx.Exceptions; using CliFx.Infrastructure; @@ -31,6 +32,12 @@ public class WriteCommand : CommandBase [CommandOption("value", 'v', Description = "Value to write", IsRequired = true)] public string Value { get; init; } = default!; + /// + /// Gets an optional built-in scalar type, allowing a write without reading the current value. + /// + [CommandOption("type", Description = "Scalar type: Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Float, Double, String; omit to infer from a read")] + public string? Type { get; init; } + /// public override async ValueTask ExecuteAsync(IConsole console) { @@ -46,15 +53,20 @@ public class WriteCommand : CommandBase throw new CommandException($"Invalid --node value: {ex.Message}"); } + object typedValue = Type is null ? Value : ConvertExplicitValue(Value, Type); + IOpcUaClientService? service = null; try { var ct = console.RegisterCancellationHandler(); (service, _) = await CreateServiceAndConnectAsync(ct); - // Read current value to determine type for conversion - var currentValue = await service.ReadValueAsync(nodeId, ct); - var typedValue = ValueConverter.ConvertValue(Value, ValueConverter.ToClrObject(currentValue.WrappedValue)); + if (Type is null) + { + // Preserve runtime type inference for callers that omit --type. + var currentValue = await service.ReadValueAsync(nodeId, ct); + typedValue = ValueConverter.ConvertValue(Value, ValueConverter.ToClrObject(currentValue.WrappedValue)); + } var statusCode = await service.WriteValueAsync(nodeId, typedValue, ct); @@ -72,4 +84,35 @@ public class WriteCommand : CommandBase } } } + + /// Converts an explicitly typed scalar before opening a client connection. + /// The raw operator-entered value. + /// The supported OPC UA built-in scalar type name. + /// The exact CLR scalar required by the selected type. + private static object ConvertExplicitValue(string value, string type) + { + try + { + return type.ToUpperInvariant() switch + { + "BOOLEAN" => ValueConverter.ConvertValue(value, false), + "BYTE" => byte.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture), + "SBYTE" => sbyte.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture), + "INT16" => short.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture), + "UINT16" => ushort.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture), + "INT32" => int.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture), + "UINT32" => uint.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture), + "INT64" => long.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture), + "UINT64" => ulong.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture), + "FLOAT" => float.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture), + "DOUBLE" => double.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture), + "STRING" => value, + _ => throw new CommandException($"Unsupported --type value '{type}'. Use Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Float, Double, or String.") + }; + } + catch (Exception ex) when (ex is FormatException or OverflowException) + { + throw new CommandException($"Invalid --value for --type {type}: {ex.Message}"); + } + } } diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSessionAdapter.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSessionAdapter.cs index 70025bdd4..8c3710d39 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSessionAdapter.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSessionAdapter.cs @@ -66,6 +66,29 @@ internal sealed class DefaultSessionAdapter : ISessionAdapter return await _session.ReadValueAsync(nodeId, ct); } + /// + public async Task ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct) + { + if (maximumAge < TimeSpan.Zero || maximumAge.TotalMilliseconds > int.MaxValue) + throw new ArgumentOutOfRangeException(nameof(maximumAge)); + ArrayOf nodes = [new ReadValueId { NodeId = nodeId, AttributeId = Attributes.Value }]; + var response = await _session.ReadAsync(null, maximumAge.TotalMilliseconds, TimestampsToReturn.Both, nodes, ct); + return ValidateReadResult(response.ResponseHeader, response.Results, nodeId); + } + + internal static DataValue ValidateReadResult(ResponseHeader? header, ArrayOf results, NodeId nodeId) + { + var serviceStatus = header?.ServiceResult.Code ?? StatusCodes.BadUnexpectedError; + if (StatusCode.IsBad(serviceStatus)) + throw new ServiceResultException(serviceStatus); + if (results.Count != 1) + throw new ServiceResultException(StatusCodes.BadUnexpectedError, $"Read response contained {results.Count} results for node {nodeId}."); + var value = results[0]; + if (StatusCode.IsBad(value.StatusCode)) + throw new ServiceResultException(value.StatusCode); + return value; + } + /// public async Task WriteValueAsync(NodeId nodeId, DataValue value, CancellationToken ct) { diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSubscriptionAdapter.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSubscriptionAdapter.cs index 6a49f91c1..e44c3dc1f 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSubscriptionAdapter.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSubscriptionAdapter.cs @@ -53,8 +53,7 @@ internal sealed class DefaultSubscriptionAdapter : ISubscriptionAdapter onDataChange(nodeId.ToString(), notification.Value); }; - _subscription.AddItem(item); - await _subscription.ApplyChangesAsync(ct); + await AddItemAsync(item, ct); var handle = item.ClientHandle; _monitoredItems[handle] = item; @@ -95,8 +94,7 @@ internal sealed class DefaultSubscriptionAdapter : ISubscriptionAdapter if (Volatile.Read(ref _finishing) == 0 && e.NotificationValue is EventFieldList eventFields) onEvent(eventFields); }; - _subscription.AddItem(item); - await _subscription.ApplyChangesAsync(ct); + await AddItemAsync(item, ct); var handle = item.ClientHandle; _monitoredItems[handle] = item; @@ -105,6 +103,24 @@ internal sealed class DefaultSubscriptionAdapter : ISubscriptionAdapter return handle; } + private async Task AddItemAsync(MonitoredItem item, CancellationToken ct) + { + _subscription.AddItem(item); + try + { + await _subscription.ApplyChangesAsync(ct); + if (item.Status.Error is { } error && StatusCode.IsBad(error.StatusCode)) + throw new ServiceResultException(error.StatusCode); + } + catch + { + // Keep a rejected or interrupted add out of the tracked subscription; the + // SDK will carry any required deletion on its next ApplyChanges call. + _subscription.RemoveItem(item); + throw; + } + } + /// public async Task ConditionRefreshAsync(CancellationToken ct) { diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs index 8b18e17d7..cb1c6c87b 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs @@ -61,6 +61,9 @@ internal interface ISessionAdapter : IDisposable /// The current data value read from the server. Task ReadValueAsync(NodeId nodeId, CancellationToken ct = default); + /// Reads a value using the supplied maximum cache age. + Task ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct = default); + /// /// Writes a typed value to a node on the connected OPC UA server. /// diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs index 54012c432..b7933f880 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs @@ -42,6 +42,20 @@ public interface IOpcUaClientService : IDisposable /// The current data value of the node. Task ReadValueAsync(NodeId nodeId, CancellationToken ct = default); + /// Reads a value allowing a cached value up to the specified age. + /// The node whose value should be retrieved. + /// Maximum cache age, from zero to Int32.MaxValue milliseconds. + /// The cancellation token that aborts the read request. + /// The data value returned by the server. + Task ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct = default) + { + if (maximumAge < TimeSpan.Zero || maximumAge.TotalMilliseconds > int.MaxValue) + throw new ArgumentOutOfRangeException(nameof(maximumAge)); + if (maximumAge != TimeSpan.Zero) + throw new NotSupportedException("This client does not support reads with a maximum age."); + return ReadValueAsync(nodeId, ct); + } + /// /// Writes an operator-supplied value to an OPC UA node after applying client-side type conversion when needed. /// diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs index 0951babe9..d14de8060 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs @@ -155,7 +155,8 @@ public sealed class OpcUaClientService : IOpcUaClientService // A new epoch first: a failover still connecting abandons itself instead of resurrecting the connection. lock (_subscriptionLock) _connectionEpoch++; - var endpointUrl = _session?.EndpointUrl ?? _settings?.EndpointUrl ?? string.Empty; + // The SDK transport may already be disposed when teardown begins. + var endpointUrl = CurrentConnectionInfo?.EndpointUrl ?? _settings?.EndpointUrl ?? string.Empty; // Snapshot the subscription adapter references under the lock so a concurrent // RunFailoverAsync that nulls _dataSubscription / _alarmSubscription @@ -210,6 +211,18 @@ public sealed class OpcUaClientService : IOpcUaClientService return await _session!.ReadValueAsync(nodeId, ct); } + /// + public async Task ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct = default) + { + if (maximumAge < TimeSpan.Zero || maximumAge.TotalMilliseconds > int.MaxValue) + throw new ArgumentOutOfRangeException(nameof(maximumAge)); + if (maximumAge == TimeSpan.Zero) + return await ReadValueAsync(nodeId, ct); + ThrowIfDisposed(); + ThrowIfNotConnected(); + return await _session!.ReadValueAsync(nodeId, maximumAge, ct); + } + /// public async Task WriteValueAsync(NodeId nodeId, object value, CancellationToken ct = default) { @@ -391,10 +404,17 @@ public sealed class OpcUaClientService : IOpcUaClientService var monitorNode = sourceNodeId ?? ObjectIds.Server; var subscription = await session.CreateSubscriptionAsync(intervalMs, ct); lock (_subscriptionLock) _alarmSubscription = subscription; - - var filter = CreateAlarmEventFilter(); - await subscription.AddEventMonitoredItemAsync( - monitorNode, intervalMs, filter, AlarmCallback(session, subscription), ct); + try + { + var filter = CreateAlarmEventFilter(); + await subscription.AddEventMonitoredItemAsync( + monitorNode, intervalMs, filter, AlarmCallback(session, subscription), ct); + } + catch + { + await CleanupFailedAlarmSubscriptionAsync(subscription); + throw; + } lock (_subscriptionLock) { @@ -871,7 +891,7 @@ public sealed class OpcUaClientService : IOpcUaClientService return; var oldSession = _session; - var oldEndpoint = oldSession?.EndpointUrl ?? string.Empty; + var oldEndpoint = CurrentConnectionInfo?.EndpointUrl ?? _settings?.EndpointUrl ?? string.Empty; if (!TransitionStateIfCurrent(epoch, ConnectionState.Reconnecting, oldEndpoint)) return; Logger.Warning("Session lost on {EndpointUrl}. Attempting failover...", oldEndpoint); @@ -1012,10 +1032,11 @@ public sealed class OpcUaClientService : IOpcUaClientService if (alarmSubscription.HasValue) { var (sourceNodeId, intervalMs) = alarmSubscription.Value; + ISubscriptionAdapter? replayedAlarms = null; try { var monitorNode = sourceNodeId ?? ObjectIds.Server; - var replayedAlarms = await session.CreateSubscriptionAsync(intervalMs, CancellationToken.None); + replayedAlarms = await session.CreateSubscriptionAsync(intervalMs, CancellationToken.None); lock (_subscriptionLock) _alarmSubscription = replayedAlarms; var filter = CreateAlarmEventFilter(); await replayedAlarms.AddEventMonitoredItemAsync( @@ -1028,11 +1049,32 @@ public sealed class OpcUaClientService : IOpcUaClientService } catch (Exception ex) { + if (replayedAlarms is not null) await CleanupFailedAlarmSubscriptionAsync(replayedAlarms); Logger.Warning(ex, "Failed to replay alarm subscription"); } } } + private async Task CleanupFailedAlarmSubscriptionAsync(ISubscriptionAdapter subscription) + { + lock (_subscriptionLock) + { + if (ReferenceEquals(_alarmSubscription, subscription)) + { + _alarmSubscription = null; + _activeAlarmSubscription = null; + } + } + using var cleanup = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + try { await subscription.DeleteAsync(cleanup.Token); } + catch (Exception ex) { Logger.Warning(ex, "Failed to delete rejected alarm subscription"); } + finally + { + try { subscription.Dispose(); } + catch (Exception ex) { Logger.Warning(ex, "Failed to dispose rejected alarm subscription"); } + } + } + private bool IsCurrentNotification(ISessionAdapter session, ISubscriptionAdapter subscription, bool alarm) { lock (_subscriptionLock) 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 192ad1a9a..766ded7dd 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs @@ -335,6 +335,10 @@ public static class DataProtoMapper v.Remove = new W.HandleChanges(); v.Remove.Items.AddRange(r.Items.Select(EncodeHandle)); break; + case ChallengeSubscriptionFreshness c: + v.FreshnessChallenge = new W.HandleChanges(); + v.FreshnessChallenge.Items.AddRange(c.Items.Select(EncodeHandle)); + break; default: throw new ArgumentException("Unsupported command."); } @@ -353,6 +357,7 @@ public static class DataProtoMapper W.SubscriptionCommand.CommandOneofCase.Add => x.Add.Items.Count, W.SubscriptionCommand.CommandOneofCase.Modify => x.Modify.Items.Count, W.SubscriptionCommand.CommandOneofCase.Remove => x.Remove.Items.Count, + W.SubscriptionCommand.CommandOneofCase.FreshnessChallenge => x.FreshnessChallenge.Items.Count, _ => 0, }; Preflight(x, count, limits); @@ -372,6 +377,10 @@ public static class DataProtoMapper || handle.StreamEpoch != x.StreamEpoch ) throw new ArgumentException("Removal handle belongs to another stream."); + if (x.FreshnessChallenge is { } challenge) + foreach (var handle in challenge.Items) + if (handle.SubscriptionId != x.SubscriptionId || handle.StreamEpoch != x.StreamEpoch) + throw new ArgumentException("Challenge handle belongs to another stream."); var t = TimeSpan.FromTicks(x.AcknowledgementTimeoutTicks); return x.CommandCase switch { @@ -406,6 +415,9 @@ public static class DataProtoMapper t, x.Remove.Items.Select(DecodeHandle).ToArray() ), + W.SubscriptionCommand.CommandOneofCase.FreshnessChallenge => new ChallengeSubscriptionFreshness( + x.SubscriptionId, x.StreamEpoch, x.CommandId, t, + x.FreshnessChallenge.Items.Select(DecodeHandle).ToArray()), _ => throw new ArgumentException("Missing command."), }; } @@ -488,7 +500,8 @@ public static class DataProtoMapper serving, update.Version ); - items.Add(new DataSubscriptionValue(handle, sample, ageBounds, readiness)); + items.Add(new DataSubscriptionValue(handle, sample, ageBounds, readiness, + subscriptionAgeReadiness && update.HasFreshnessChallengeId && update.FreshnessChallengeId.Length <= 32 ? update.FreshnessChallengeId : null)); } return new DataSubscriptionValues( frame.SubscriptionId, @@ -533,6 +546,7 @@ public static class DataProtoMapper ValidateSubscriptionAgeReadiness(item); if (item.AgeBounds.Lower is { } lower) update.OriginAgeTicks = lower.Ticks; update.Readiness = (int)item.Readiness; + if (item.FreshnessChallengeId is { } challenge) update.FreshnessChallengeId = challenge; } result.Values.Items.Add(update); } @@ -573,6 +587,7 @@ public static class DataProtoMapper ValidateSubscriptionAgeReadiness(item); if (item.AgeBounds.Lower is { } lower) update.OriginAgeTicks = lower.Ticks; update.Readiness = (int)item.Readiness; + if (item.FreshnessChallengeId is { } challenge) update.FreshnessChallengeId = challenge; } if (item.Sample.StatusCode != first.StatusCode) update.StatusCode = item.Sample.StatusCode; @@ -649,7 +664,8 @@ public static class DataProtoMapper throw new ArgumentException("Unexpected serving identity."); var (ageBounds, readiness) = DecodeSubscriptionAgeReadiness(subscriptionAgeReadiness, item.HasOriginAgeTicks, item.OriginAgeTicks, item.HasReadiness, item.Readiness); - items.Add(new(handle, DecodeSample(item.Sample, maxElements, maxBytes), ageBounds, readiness)); + items.Add(new(handle, DecodeSample(item.Sample, maxElements, maxBytes), ageBounds, readiness, + subscriptionAgeReadiness && item.HasFreshnessChallengeId && item.FreshnessChallengeId.Length <= 32 ? item.FreshnessChallengeId : null)); } return new( frame.SubscriptionId, @@ -995,6 +1011,8 @@ public static class DataProtoMapper SubscriptionAgeReadiness = x.SubscriptionAgeReadiness, ResponseServingIdentity = x.ResponseServingIdentity, WriteServingGenerationEnforced = x.WriteServingGenerationEnforced, + SubscriptionFreshnessChallenges = x.SubscriptionFreshnessChallenges, + MetadataItemLeases = x.MetadataItemLeases, Limits = new W.Limits { MaxPageItems = l.MaxPageItems, @@ -1061,7 +1079,9 @@ public static class DataProtoMapper x.ClusterId, x.SubscriptionAgeReadiness, x.ResponseServingIdentity, - x.WriteServingGenerationEnforced + x.WriteServingGenerationEnforced, + x.SubscriptionFreshnessChallenges, + x.MetadataItemLeases ); result.Validate(); return result; @@ -1190,6 +1210,9 @@ public static class DataProtoMapper public static W.MetadataResult EncodeMetadataResult(DataItemResult item) { DataContractValidation.Required(item.Status); + if (item.Lease is { } lease && (item.Status != DataItemStatus.Good || item.Value is null || + lease.CatalogEpoch <= 0 || lease.AuthorityEpoch <= 0 || lease.Duration <= TimeSpan.Zero)) + throw new ArgumentException("A metadata lease requires a successful item and valid authority."); var result = new W.MetadataResult { CorrelationId = item.CorrelationId, @@ -1199,6 +1222,9 @@ public static class DataProtoMapper result.Value = EncodeMetadata(item.Value); if (item.Diagnostic is not null) result.Diagnostic = item.Diagnostic; + if (item.Lease is { } itemLease) + result.Lease = new W.Lease { CatalogEpoch = itemLease.CatalogEpoch, AuthorityEpoch = itemLease.AuthorityEpoch, + DurationTicks = itemLease.Duration.Ticks }; return result; } @@ -1210,11 +1236,17 @@ public static class DataProtoMapper Preflight(item, 1, limits); var status = (DataItemStatus)item.Status; DataContractValidation.Required(status); + MetadataLease? lease = item.Lease is { } itemLease + ? new(itemLease.CatalogEpoch, itemLease.AuthorityEpoch, TimeSpan.FromTicks(itemLease.DurationTicks)) : null; + if (lease is not null && (status != DataItemStatus.Good || item.Value is null || + lease.CatalogEpoch <= 0 || lease.AuthorityEpoch <= 0 || lease.Duration <= TimeSpan.Zero)) + throw new ArgumentException("A metadata lease requires a successful item and valid authority."); return new( item.CorrelationId, status, item.Value is null ? null : DecodeMetadata(item.Value), - item.HasDiagnostic ? item.Diagnostic : null + item.HasDiagnostic ? item.Diagnostic : null, + lease ); } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs index c35a033f4..eab2c01a8 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs @@ -30,4 +30,8 @@ public sealed record DataConnectionDiagnosticsSnapshot( long? WriteFailedCount = null, long? WriteUnconfirmedCount = null, TimeSpan? SampleAgeUpperBound = null, - long? CoalescedCount = null); + long? CoalescedCount = null, + long? CompactFrameCount = null, + long? FallbackFrameCount = null, + long? SerializedValueFrameBytes = null, + string? AccountingInstanceId = null); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/DataConnectionProtoContract.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/DataConnectionProtoContract.cs index 29bc1c877..aebbfb775 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/DataConnectionProtoContract.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/DataConnectionProtoContract.cs @@ -8,6 +8,8 @@ public static class DataConnectionProtoContract public const int ProtocolMajor = 1; public const int ProtocolMinor = 1; public const int CompactCodecVersion = 1; + /// Optional, per-subscription client opt-in to a supported compact codec. + public const string CompactCodecHeader = "x-data-compact-codec"; public static void Validate() { 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 3d1629a2c..ec061e12a 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 @@ -114,6 +114,11 @@ message CapabilitiesResponse { bool subscription_age_readiness = 11; bool response_serving_identity = 12; bool write_serving_generation_enforced = 13; + // The server accepts freshness_challenge and captures each stamped age after + // admitting the identified challenge. Absence or false leaves stream age unbounded. + bool subscription_freshness_challenges = 14; + // Good GetMetadata results may include an exact-item authority lease. + bool metadata_item_leases = 15; } message Metadata { View view = 1; @@ -159,6 +164,8 @@ message MetadataResult { int32 status = 2; Metadata value = 3; optional string diagnostic = 4; + // Valid only for this authorized item and this response's serving identity. + Lease lease = 5; } message MetadataResponse { repeated MetadataResult items = 1; Serving serving = 2; } message ReadItem { @@ -227,6 +234,9 @@ message SubscriptionCommand { ItemChanges add = 6; ItemChanges modify = 7; HandleChanges remove = 8; + // Subscribe-authorized bounded current snapshot of these active item revisions. + // command_id is a per-stream strictly increasing freshness sequence. + HandleChanges freshness_challenge = 9; } } message Open { @@ -265,6 +275,9 @@ message ValueUpdate { // Age since normalized origin-cache ingress, not sensor measurement age. optional int64 origin_age_ticks = 3; optional int32 readiness = 4; + // The admitted challenge observed before origin_age_ticks was computed. + // The value and this identifier must remain coupled through queued encoding. + optional string freshness_challenge_id = 5; } message Values { bool is_snapshot = 1; @@ -283,6 +296,8 @@ message CompactUpdate { // Age since normalized origin-cache ingress, not sensor measurement age. optional int64 origin_age_ticks = 8; optional int32 readiness = 9; + // Same causal witness semantics as ValueUpdate.freshness_challenge_id. + optional string freshness_challenge_id = 10; } message CompactValues { bool is_snapshot = 1; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/DataConnection.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/DataConnection.cs index 496b757e4..64285caf4 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/DataConnection.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/DataConnection.cs @@ -21,7 +21,7 @@ public sealed class DataConnection public string SecretReference { get; set; } = ""; public string SecretScopeClusterId { get; set; } = ""; public DataOperations AllowedOperations { get; set; } - public int TimeoutMilliseconds { get; set; } = 5000; + public int TimeoutMilliseconds { get; set; } = 30000; public int MaxBatchItems { get; set; } = 1000; public int MaxPageItems { get; set; } = 500; public int MaxMessageBytes { get; set; } = 4 * 1024 * 1024; 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 e3b06f61f..e166e0551 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 @@ -247,7 +247,8 @@ public sealed record DataLimits(int MaxPageItems, int MaxBatchItems, int MaxMess public sealed record DataCapabilities(int ProtocolMajor, int ProtocolMinor, ServingIdentity Serving, DataReadiness Readiness, DataOperations Operations, IReadOnlySet ValueKinds, DataLimits Limits, bool CompactBatches, int CompactCodecVersion, string ClusterId, bool SubscriptionAgeReadiness = false, bool ResponseServingIdentity = false, - bool WriteServingGenerationEnforced = false) + bool WriteServingGenerationEnforced = false, bool SubscriptionFreshnessChallenges = false, + bool MetadataItemLeases = false) { public void Validate() { @@ -310,6 +311,11 @@ public sealed record DataMetadata(DataView View, string BrowseName, string NodeK } } } -public sealed record DataItemResult(string CorrelationId, DataItemStatus Status, T? Value, string? Diagnostic); +/// +/// A per-item result. A metadata lease certifies only this returned item; its local +/// request-start timestamp uses the connection's clock and is never serialized. +/// +public sealed record DataItemResult(string CorrelationId, DataItemStatus Status, T? Value, string? Diagnostic, + MetadataLease? Lease = null, long? LeaseRequestStartedTimestamp = null); public sealed record DataBrowseBranch(DataView Parent, DataItemStatus Status, IReadOnlyList Items, bool Complete, string? Continuation, MetadataLease? Lease, ServingIdentity? Serving = null); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs index b6e71faa3..8bef99472 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 @@ -10,10 +10,11 @@ public sealed record BrowseRequest(DataView Parent, string? Filter, string? Cont public sealed record MetadataRequest(IReadOnlyList Views, DataBudget Budget); public sealed record ReadItem(string CorrelationId, DataView View, TimeSpan? MaximumAge); public sealed record ReadRequest(IReadOnlyList Items, DataBudget Budget); -/// Sample is owned by the recipient. Status/age/readiness are distinct from original sample quality. +/// Sample is owned by the recipient. Status/age/readiness are distinct from original sample quality. +/// FreshnessObservedTimestamp, when present, is local to the connection clock and is never serialized. public sealed record ReadResult(string CorrelationId, DataItemStatus Status, DataReadiness Readiness, TimeSpan? Age, DataSample? Sample, string? Diagnostic, IDisposable? ResourceLease = null, - DataAgeBounds AgeBounds = default) : IDisposable + DataAgeBounds AgeBounds = default, long? FreshnessObservedTimestamp = null) : IDisposable { public void Dispose() { @@ -95,6 +96,9 @@ public sealed record ModifySubscriptionItems(string SubscriptionId, long StreamE IReadOnlyList Items) : DataSubscriptionCommand(SubscriptionId, StreamEpoch, CommandId, AcknowledgementTimeout); public sealed record RemoveSubscriptionItems(string SubscriptionId, long StreamEpoch, string CommandId, TimeSpan AcknowledgementTimeout, IReadOnlyList Items) : DataSubscriptionCommand(SubscriptionId, StreamEpoch, CommandId, AcknowledgementTimeout); +/// Requests a bounded, Subscribe-authorized current-value refresh and starts a freshness witness. +public sealed record ChallengeSubscriptionFreshness(string SubscriptionId, long StreamEpoch, string CommandId, TimeSpan AcknowledgementTimeout, + IReadOnlyList Items) : DataSubscriptionCommand(SubscriptionId, StreamEpoch, CommandId, AcknowledgementTimeout); public sealed record DataSubscriptionItemAck(string ClientItemId, DataItemStatus Status, DataItemHandle? Handle, DataSubscriptionSettings? RevisedSettings, string? Diagnostic); public abstract record DataSubscriptionFrame(string SubscriptionId, long StreamEpoch, long Sequence); @@ -121,9 +125,14 @@ public sealed record DataSubscriptionValues(string SubscriptionId, long StreamEp finally { ResourceLease?.Dispose(); } } } -/// Age bounds describe normalized origin-cache ingress age, independent of wall timestamps. +/// +/// Age bounds describe normalized origin-cache ingress age, independent of wall timestamps. +/// A finite bound calculated by a remote adapter is anchored to its own monotonic clock at +/// FreshnessObservedTimestamp; the local observation timestamp is never sent on the wire. +/// public sealed record DataSubscriptionValue(DataItemHandle Handle, DataSample Sample, - DataAgeBounds AgeBounds = default, DataReadiness Readiness = DataReadiness.Unspecified); + DataAgeBounds AgeBounds = default, DataReadiness Readiness = DataReadiness.Unspecified, string? FreshnessChallengeId = null, + long? FreshnessObservedTimestamp = null); /// Commands and frames are ordered per stream. Dispose cancels the stream and releases demand. public interface IDataSubscription : IAsyncDisposable @@ -131,6 +140,12 @@ public interface IDataSubscription : IAsyncDisposable Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken); IAsyncEnumerable ReadAllAsync(CancellationToken cancellationToken); } +/// True only when this stream negotiated causal freshness challenges. +public interface IDataSubscriptionFreshnessSupport +{ + bool SupportsFreshnessChallenges { get; } + int FreshnessMaxItems { get; } +} /// Immutable serving identity captured when the subscription was established. public interface IDataSubscriptionProvenance { diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/ProjectedValuePublication.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/ProjectedValuePublication.cs index 40ec96f50..cb30530f3 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/ProjectedValuePublication.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/ProjectedValuePublication.cs @@ -17,7 +17,7 @@ public interface IProjectedSamplePublicationProof /// An imported sample retaining original ingress age through local actor and SDK queues. public sealed record ProjectedValueWrite(DataRealm Realm, string LocalIdentifier, long ProjectionGeneration, ServingIdentity Serving, DataValueSnapshot Snapshot, DataAgeBounds OriginAgeBounds, long ReceivedTimestamp, - IProjectedSamplePublicationProof Proof, bool IsCompleteSnapshot = false); + IProjectedSamplePublicationProof Proof, bool IsCompleteSnapshot = false, long? SourceVersion = null); /// Applies imported values only after checking their captured proof at the actual SDK boundary. public interface IProjectedValueSink diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAcknowledgedAcquisitionSource.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAcknowledgedAcquisitionSource.cs index 61c508c79..f23493315 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAcknowledgedAcquisitionSource.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAcknowledgedAcquisitionSource.cs @@ -18,6 +18,16 @@ public interface IAcknowledgedAcquisitionSource Action onAcquired, CancellationToken cancellationToken); } +/// +/// An acknowledged acquisition that can replace the ordinary baseline subscription. +/// The returned handle produces the same initial and subsequent native value and status +/// change events as , while the acquisition +/// callback reports every physical acquisition, including unchanged successful reads. +/// A driver must explicitly implement this capability only when both feeds describe the +/// same physical subscription and preserve their ordinary handle and ownership semantics. +/// +public interface IAcknowledgedBaselineAcquisitionSource : IAcknowledgedAcquisitionSource { } + /// Complete physical interest and revision fence for one producer incarnation. public sealed record AcquisitionSubscriptionRequest(IReadOnlyList FullReferences, TimeSpan RequestedSamplingInterval, long DesiredRevision, long ProducerIncarnation); diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriver.cs index 1c6d4d868..31ebc349e 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriver.cs @@ -21,7 +21,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus; /// since Modbus has no native push model. /// public sealed class ModbusDriver - : IDriver, ITagDiscovery, IReadable, IWritable, IWriteOutcomeCapability, IBatchSubscribable, IAcknowledgedAcquisitionSource, IHostConnectivityProbe, IPerCallHostResolver, ISkippedTagReporter, IDisposable, IAsyncDisposable + : IDriver, ITagDiscovery, IReadable, IWritable, IWriteOutcomeCapability, IBatchSubscribable, IAcknowledgedBaselineAcquisitionSource, IHostConnectivityProbe, IPerCallHostResolver, ISkippedTagReporter, IDisposable, IAsyncDisposable { /// Authored tags this driver could not build into its poll table. private readonly SkippedTagLedger _skippedTags = new(); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor index 5cd0cd588..c44e28d8e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor @@ -31,11 +31,11 @@ else
@row.Id@if (row.Draft is { } draft) { Draft: @(draft.Enabled ? "enabled" : "disabled") } else { Removed from draft }@if (!_live.Any(x => Same(x.Row.ConnectionId, row.Id))) { Runtime: unavailable } @foreach (var live in _live.Where(x => Same(x.Row.ConnectionId, row.Id))) { -
@live.NodeId: @DataConnectionDiagnostics.State(live.Row.State) · revision @live.Row.Revision · endpoint @DataConnectionDiagnostics.Endpoint(live.Row.SelectedEndpoint) +
@live.NodeId: @DataConnectionDiagnostics.State(live.Row.State) · revision @live.Row.Revision · endpoint @DataConnectionDiagnostics.Endpoint(live.Row.SelectedEndpoint) @if (live.Row.Serving is { } serving) { · serving @serving.NodeId · role @serving.Role · incarnation @serving.Incarnation }
Streams @live.Row.ActiveStreams · calls @live.Row.ActiveCalls · retained import views @Measure(live.Row.SourceCount) · registrations @Measure(live.Row.RegistrationCount) · resets @Measure(live.Row.ResetCount) · coalesced notices @Measure(live.Row.CoalescedCount) · overflows @Measure(live.Row.OverflowCount)
Writes succeeded @Measure(live.Row.WriteSucceededCount) · rejected @Measure(live.Row.WriteRejectedCount) · failed @Measure(live.Row.WriteFailedCount) · unconfirmed @Measure(live.Row.WriteUnconfirmedCount) · unknown @Measure(live.Row.WriteUnknownCount)
-
Last observed sample bound @Time(live.Row.LastSampleAtUtc) (age upper bound @DataConnectionDiagnostics.SampleAge(live.Row)) · metadata lease expires @Time(live.Row.MetadataLeaseExpiresAtUtc) · last handshake @Time(live.Row.LastVerifiedAtUtc) · observed @live.Row.AsOfUtc.ToString("u") · artifact @live.Row.ArtifactRevision · protocol @Measure(live.Row.ProtocolMajor).@Measure(live.Row.ProtocolMinor)
+
Last observed sample bound @Time(live.Row.LastSampleAtUtc) (age upper bound @DataConnectionDiagnostics.SampleAge(live.Row)) · metadata lease expires @Time(live.Row.MetadataLeaseExpiresAtUtc) · last handshake @Time(live.Row.LastVerifiedAtUtc) · observed @live.Row.AsOfUtc.ToString("u") · artifact @live.Row.ArtifactRevision · protocol @(live.Row.ProtocolMajor is { } major && live.Row.ProtocolMinor is { } minor ? $"{major}.{minor}" : "unavailable")
} @foreach (var applied in _applied.Where(x => Same(x.ConnectionId, row.Id))) { @applied.NodeId: last applied revision @applied.Revision (@(applied.Enabled ? "enabled" : "disabled")) } @if (row.Draft is { } editable) { }
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor.css b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor.css new file mode 100644 index 000000000..7a7fc2ade --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor.css @@ -0,0 +1,5 @@ +.data-connection-diagnostics { + min-width: 0; + max-width: 100%; + overflow-wrap: anywhere; +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionBundleCommitObserver.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionBundleCommitObserver.cs new file mode 100644 index 000000000..e02f4e236 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionBundleCommitObserver.cs @@ -0,0 +1,22 @@ +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Host.Configuration; + +/// Observes the committed provisioning state without exposing secret or trust material. +public sealed class DataConnectionBundleCommitObserver(DataConnectionSecretProvisioner credentials, DataConnectionTrustPolicyStore trust) + : IDataConnectionBundleCommitObserver +{ + /// + public async Task ObserveAsync(string connectionId, CancellationToken cancellationToken) + { + ArgumentException.ThrowIfNullOrWhiteSpace(connectionId); + await DataConnectionSecretProvisioner.Gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + var credential = await credentials.ObserveCommittedLockedAsync(connectionId, cancellationToken).ConfigureAwait(false); + var trustState = await trust.ObserveCommittedLockedAsync(connectionId, cancellationToken).ConfigureAwait(false); + return new(credential.Scope, credential.Version, credential.Deleted, trustState.Scope, trustState.Version, trustState.Retired); + } + finally { DataConnectionSecretProvisioner.Gate.Release(); } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs index ecab2a4c6..ea8dd1a99 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs @@ -5,6 +5,8 @@ public sealed class DataConnectionOptions { public const string SectionName = "DataConnections"; public bool Enabled { get; set; } + /// Requests supported compact batches on outbound data subscriptions. + public bool UseCompactBatches { get; set; } = true; public int ListenPort { get; set; } public string ListenAddress { get; set; } = "0.0.0.0"; public string[] AllowedHosts { get; set; } = []; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs index 3a9c33fa6..9f58fccd8 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs @@ -53,7 +53,7 @@ public static class DataConnectionRegistration return new LocalCatalogCoordinator(sp.GetRequiredService(), sp.GetRequiredService(), () => { - var state = CaptureRole(role, warm); + var state = CaptureReadRole(role, warm); var servingRole = settings.IsWarm && state.WarmRole != WarmRole.Active ? "Standby" : state.Role; return new(identity.NodeId, identity.Incarnation, servingRole, 0, 0, state.Generation); }); @@ -108,12 +108,12 @@ public static class DataConnectionRegistration localWriteRole: () => { var role = sp.GetRequiredService(); - var state = CaptureRole(role, sp.GetRequiredService()); + var state = CaptureWriteRole(role, sp.GetRequiredService()); var settings = sp.GetService() ?? WarmRedundancySettings.Unset; var active = sp.GetRequiredService().Current is { IsActive: true }; return (active && role.ShouldActAsPrimary && state.Role == "Primary" && (!settings.IsWarm || state.WarmRole == WarmRole.Active), state.Generation); - })); + }, renewalSink: sp.GetRequiredService())); services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(sp => new ConfiguredProjectionDiscovery( sp.GetRequiredService(), sp.GetRequiredService(), @@ -171,6 +171,7 @@ public static class DataConnectionRegistration sp.GetRequiredService(), id.ClusterId, id.NodeId); }); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(sp => { @@ -183,7 +184,7 @@ public static class DataConnectionRegistration sp.GetRequiredService(), 256, sp.GetRequiredService(), () => { - var state = CaptureRole(role, warm); + var state = CaptureReadRole(role, warm); var mode = settings.Mode switch { OpcUaRedundancyMode.Warm => RedundancyMode.Warm, @@ -192,6 +193,25 @@ public static class DataConnectionRegistration }; return state.Generation > 0 && Enum.TryParse(state.Role, out var actual) && DataConnectionRoleAdapter.MayAcquire(mode, state.WarmRole, actual); + }, useCompactBatches: options.UseCompactBatches, consumerRoleSnapshot: artifactMode => + { + var mode = settings.Mode switch + { + OpcUaRedundancyMode.Warm => RedundancyMode.Warm, + OpcUaRedundancyMode.None => RedundancyMode.None, + _ => artifactMode + }; + if (mode == RedundancyMode.Hot) + { + var hot = role.CaptureDataServingRole(); + var hotEligible = hot.Generation > 0 && Enum.TryParse(hot.Role, out var hotRole) + && DataConnectionRoleAdapter.MayAcquire(mode, null, hotRole); + return new DataConnectionConsumerRoleSnapshot(mode, hotEligible, hot.ReadEligibilityEpoch); + } + var state = CaptureReadRole(role, warm); + var eligible = state.Generation > 0 && Enum.TryParse(state.Role, out var actual) + && DataConnectionRoleAdapter.MayAcquire(mode, state.WarmRole, actual); + return new DataConnectionConsumerRoleSnapshot(mode, eligible, state.Generation); }); return runtime; }); @@ -213,19 +233,37 @@ public static class DataConnectionRegistration return options; } - private static (string Role, long Generation, WarmRole? WarmRole) CaptureRole(RedundancyRoleView role, DataConnectionWarmRoleView warm) + private static (string Role, long Generation, WarmRole? WarmRole, long ReadEpoch) CaptureReadRole( + RedundancyRoleView role, DataConnectionWarmRoleView warm) + { + if (!ReferenceEquals(role.DispatchFence, warm.DispatchFence)) return ("Unknown", 0, null, 0); + + // Both verdicts are immutable. The monotone primary generation brackets + // the Warm read, so a stable generation gives a pair that coexisted. + // A competing read or dispatch does not withdraw an unchanged role. + var primary = role.CaptureDataServingRole(); + var warmVerdict = warm.Snapshot; + return primary.Generation == role.PrimaryGeneration + ? CombineRole(primary, warmVerdict) + : ("Unknown", 0, null, 0); + } + + private static (string Role, long Generation, WarmRole? WarmRole, long ReadEpoch) CaptureWriteRole( + RedundancyRoleView role, DataConnectionWarmRoleView warm) { if (!ReferenceEquals(role.DispatchFence, warm.DispatchFence) || !role.DispatchFence.TryEnter(out var lease)) - return ("Unknown", 0, null); + return ("Unknown", 0, null, 0); 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); - } + return CombineRole(role.CaptureDataServingRole(), warm.Snapshot); + } + + private static (string Role, long Generation, WarmRole? WarmRole, long ReadEpoch) CombineRole( + DataServingRoleSnapshot primary, DataConnectionWarmRoleSnapshot warm) + { + if (primary.Generation == long.MaxValue || warm.Generation == long.MaxValue + || primary.Generation > long.MaxValue - warm.Generation) + return ("Unknown", long.MaxValue, null, long.MaxValue); + return (primary.Role, primary.Generation + warm.Generation, warm.Role, primary.ReadEligibilityEpoch); } private sealed class DeferredFactory(Func resolve) : IDataConnectionFactory diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionSecretProvisioner.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionSecretProvisioner.cs index 47dc3e706..f9b913587 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionSecretProvisioner.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionSecretProvisioner.cs @@ -71,6 +71,22 @@ public sealed class DataConnectionSecretProvisioner private Task SaveAsync(DataCredentialState state, CancellationToken ct) => _store.UpsertAsync(_cipher.Encrypt(StateName, JsonSerializer.Serialize(state), SecretContentType.Text), ct); + // Caller holds Gate so a combined credential/trust observation cannot straddle a commit. + internal async Task<(long? Scope, long? Version, bool? Deleted)> ObserveCommittedLockedAsync(string connectionId, CancellationToken ct) + { + var id = NormalizeId(connectionId); + var state = await ReadStateAsync(_store, _cipher, StateName, ct).ConfigureAwait(false); + // The durable scope is not committed while any retirement or bundle transition + // can still publish a connection-change notice or remove a retained credential. + if (state.PendingNotices.Count != 0 || state.PendingDeletes.Count != 0 || state.Versions.Values.Any(version => version.Pending)) + return (null, null, null); + var scope = state.ScopeVersion > 0 ? state.ScopeVersion : (long?)null; + if (state.PendingNotices.Contains(id) || !state.Scope.TryGetValue(id, out var reference) || + !state.Versions.TryGetValue(reference, out var version) || version.Pending || + version.ScopeVersion != state.ScopeVersion || version.Version <= 0) return (scope, null, null); + return (scope, version.Version, version.Deleted); + } + /// Persists current scope before retiring removed connections. public async Task SetScopeAsync(long version, IReadOnlyDictionary scope, CancellationToken ct) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionTrustPolicy.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionTrustPolicy.cs index 78b84a9b9..e8b8249cc 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionTrustPolicy.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionTrustPolicy.cs @@ -60,6 +60,22 @@ public sealed class DataConnectionTrustPolicyStore( return row is null ? new State() : System.Text.Json.JsonSerializer.Deserialize(cipher.Decrypt(row)) ?? throw new InvalidOperationException("Invalid trust state."); } + // Caller holds the shared provisioning Gate; no trust certificates are materialized. + internal async Task<(long? Scope, long? Version, bool? Retired)> ObserveCommittedLockedAsync(string connectionId, CancellationToken ct) + { + var id = DataConnectionSecretProvisioner.NormalizeId(connectionId); + var state = await ReadAsync(ct).ConfigureAwait(false); + // Pending retirement or bundle notices can still revoke a route after the + // scope was persisted; do not report that scope as committed yet. + if (state.PendingNotices.Count != 0 || state.Entries.Values.Any(entry => entry.PendingNotice)) + return (null, null, null); + var scope = state.ScopeVersion > 0 ? state.ScopeVersion : (long?)null; + if (!state.Scope.Contains(id) || state.PendingNotices.Contains(id) || !state.Entries.TryGetValue(id, out var entry) || + entry.PendingNotice || entry.Roots is null || entry.ScopeVersion != state.ScopeVersion || entry.Version <= 0) + return (scope, null, null); + return (scope, entry.Version, entry.Retired || entry.Roots.Length == 0); + } + 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) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs index 333881835..aac25b963 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs @@ -2,6 +2,7 @@ using Google.Protobuf; using Grpc.Core; using Microsoft.Extensions.Options; using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Commons.Protos; 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; @@ -140,13 +141,18 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO initial.CancelAfter(_options.UnaryTimeout); caps = await Ready(connection, DataOperations.Subscribe, initial.Token).ConfigureAwait(false); } + var codecHeaders = context.RequestHeaders.Where(entry => string.Equals(entry.Key, DataConnectionProtoContract.CompactCodecHeader, StringComparison.OrdinalIgnoreCase)).ToArray(); + if (codecHeaders.Length > 1 || codecHeaders.Length == 1 && + (codecHeaders[0].IsBinary || codecHeaders[0].Value != "1")) + throw new RpcException(new Status(StatusCode.InvalidArgument, "Invalid compact codec negotiation.")); + var compact = codecHeaders.Length == 1 && DataProtoMapper.NegotiateCompact(caps); 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, + var sink = new GrpcDeliverySink(responses, context, caps, _options.MaxMessageBytes, compact, () => CanPublish(connection, caller, caps.Serving)); var delivery = transport.RunDeliveryAsync(sink, stop.Token); var commands = ReceiveCommands(); @@ -174,6 +180,8 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO AddSubscriptionItems add => add with { AcknowledgementTimeout = ack }, ModifySubscriptionItems modify => modify with { AcknowledgementTimeout = ack }, RemoveSubscriptionItems remove => remove with { AcknowledgementTimeout = ack }, + ChallengeSubscriptionFreshness challenge when caps.SubscriptionFreshnessChallenges && caps.SubscriptionAgeReadiness => + challenge with { AcknowledgementTimeout = ack }, _ => throw new ArgumentException("Unsupported stream command.") }; using var commandDeadline = CancellationTokenSource.CreateLinkedTokenSource(stop.Token); @@ -191,7 +199,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO } private sealed class GrpcDeliverySink(IServerStreamWriter writer, ServerCallContext context, - DataCapabilities caps, int maximumBytes, Func hostGuard) : IDataSubscriptionDeliverySink + DataCapabilities caps, int maximumBytes, bool compact, Func hostGuard) : IDataSubscriptionDeliverySink { public ValueTask PrepareAsync(DataSubscriptionFrame frame, long reservedBytes, CancellationToken cancellationToken) @@ -210,7 +218,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO }; 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.EncodeValues(valuesFrame, compactNegotiated: compact && valuesFrame.Items.Count > 0, 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.")); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/DeferredProjectedNamespacePageSink.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/DeferredProjectedNamespacePageSink.cs index b326e5dbe..da99453ad 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/DeferredProjectedNamespacePageSink.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/DeferredProjectedNamespacePageSink.cs @@ -14,4 +14,7 @@ public sealed class DeferredProjectedNamespacePageSink(DeferredAddressSpaceSink public bool TryRemove(NodeId nodeId, ProjectedVariableDefinition expected) => deferred.GetCapability()?.TryRemove(nodeId, expected) ?? false; + + public bool TryRenewExact(NodeId nodeId, ProjectedVariableDefinition expected, ProjectedVariableDefinition replacement, Func commit) => + deferred.GetCapability()?.TryRenewExact(nodeId, expected, replacement, commit) ?? false; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedNamespacePageSink.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedNamespacePageSink.cs index c5a2c6e0b..b2d11e9bc 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedNamespacePageSink.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedNamespacePageSink.cs @@ -7,6 +7,8 @@ public interface IProjectedNamespacePageSink { bool TryApply(NodeId parent, IReadOnlyList nodes, Func commit); bool TryRemove(NodeId nodeId, ProjectedVariableDefinition expected); + /// Renews one existing compatible node without asserting a parent page or sibling authority. + bool TryRenewExact(NodeId nodeId, ProjectedVariableDefinition expected, ProjectedVariableDefinition replacement, Func commit) => false; /// Atomically promotes an owned mapping anchor to its verified leaf value. bool TryApplyRootLeaf(NodeId anchorId, ProjectedVariableDefinition rootDefinition, Func commit) => false; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index 669bfe85b..a7afb38b5 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -1,4 +1,5 @@ using System.Collections.Concurrent; +using System.Collections.Immutable; using System.Globalization; using System.Runtime.CompilerServices; using Microsoft.Extensions.Logging; @@ -44,6 +45,14 @@ public sealed record ProjectedVariableDefinition(DataRealm Realm, string LocalId public sealed record ProjectedAnchorDefinition(DataRealm Realm, string LocalIdentifier, NodeId Parent, string BrowseName, string LocalSubject, string MappingId, long MappingRevision, Func AuthorityIsCurrent) { + private NodeScope? _localScope; + /// The exact, locally deployed ACL placement of this mapping anchor. + public NodeScope? LocalScope + { + get => _localScope; + init => _localScope = value?.Segments is null ? null : + value with { Segments = Array.AsReadOnly(value.Segments.ToArray()) }; + } /// Stable for one installed mapping anchor incarnation. public ProjectedNodeLifetime Lifetime { get; init; } = new(); } @@ -748,14 +757,26 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro { if (disposing) { + lock (_projectedHealthGate) + { + _projectedHealthStopped = true; + _projectedHealthTimer?.Dispose(); + _projectedHealthTimer = null; + _projectedHealthItems.Clear(); _projectedHealthIndex.Clear(); _projectedHealthCursor = null; + } // #854 review: refuse new Server-object refreshes and let the ones in flight finish (the base's private // NodeManagerOperation guard does this for its own paths). - lock (Lock) _disposing = true; + lock (Lock) + { + _disposing = true; + Volatile.Write(ref _committedProjectedDefinitions, _committedProjectedDefinitions.Clear()); + } Interlocked.MemoryBarrier(); // the flag write must not be reordered after the in-flight read (#854 re-review) if (!SpinWait.SpinUntil(() => Volatile.Read(ref _refreshesInFlight) == 0, TimeSpan.FromSeconds(10))) _logger.LogWarning("Node manager disposed with {Count} Server-object ConditionRefresh call(s) still in flight after 10 s", Volatile.Read(ref _refreshesInFlight)); Volatile.Read(ref _dataPlaneAuthority).Changed -= OnAuthorityChanged; + foreach (var item in _liveItems.Keys.OfType()) item.Retire(); _liveItems.Clear(); _eventItems.Clear(); _allEventsItems.Clear(); @@ -4194,7 +4215,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro string.IsNullOrWhiteSpace(definition.LocalIdentifier) || string.IsNullOrWhiteSpace(definition.BrowseName) || string.IsNullOrWhiteSpace(definition.MappingId) || string.IsNullOrWhiteSpace(definition.LocalSubject) || !ProjectedDataIds.TryDecodeIdentifier(definition.LocalIdentifier, out var mappingId, out _) || mappingId != definition.MappingId || - definition.MappingRevision <= 0 || !definition.Lifetime.IsActive || definition.AuthorityIsCurrent is null) + definition.MappingRevision <= 0 || !definition.Lifetime.IsActive || definition.AuthorityIsCurrent is null || + definition.LocalScope is { } scope && (string.IsNullOrWhiteSpace(scope.ClusterId) || scope.Segments.Any(string.IsNullOrEmpty))) return false; lock (Lock) { @@ -4206,7 +4228,12 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro { if (old.Definition.Parent != definition.Parent || old.Definition.MappingId != definition.MappingId || old.Definition.MappingRevision != definition.MappingRevision || old.Definition.LocalSubject != definition.LocalSubject || - !old.Definition.AuthorityIsCurrent()) return false; + old.Definition.BrowseName != definition.BrowseName || !SameAnchorScope(old.Definition.LocalScope, definition.LocalScope)) return false; + if (!old.Definition.AuthorityIsCurrent()) + { + if (!ReferenceEquals(old.Definition.Lifetime, definition.Lifetime) || !definition.Lifetime.IsActive) return false; + _projectedAnchors[id] = (definition, old.Node); + } nodeId = id; return true; } if (GetManagerHandle(id) is not null) return false; @@ -4226,8 +4253,14 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro } } + private static bool SameAnchorScope(NodeScope? left, NodeScope? right) => + left is null ? right is null : right is not null && left.ClusterId == right.ClusterId && + left.Kind == right.Kind && left.Segments.SequenceEqual(right.Segments, StringComparer.Ordinal); + private static long ProjectedAnchorCharge(ProjectedAnchorDefinition definition) => - checked(1024L + 2L * (definition.LocalIdentifier.Length + definition.BrowseName.Length + definition.LocalSubject.Length + definition.MappingId.Length)); + checked(1024L + 2L * (definition.LocalIdentifier.Length + definition.BrowseName.Length + definition.LocalSubject.Length + definition.MappingId.Length) + + (definition.LocalScope is { } scope ? 64L + 2L * scope.ClusterId.Length + + scope.Segments.Sum(segment => 24L + 2L * segment.Length) : 0)); /// public bool TryRemoveProjectedAnchor(NodeId nodeId, ProjectedAnchorDefinition expected) @@ -4237,8 +4270,10 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro if (_disposing || !_projectedAnchors.TryGetValue(nodeId, out var anchor) || !ReferenceEquals(anchor.Definition, expected)) return false; var mappingId = anchor.Definition.MappingId; - foreach (var id in _projectedVariables.Keys.Where(id => - ProjectedDataIds.TryDecodeIdentifier(id.IdentifierAsString, out var mapping, out _) && mapping == mappingId).ToArray()) + var descendants = _projectedVariables.Keys.Where(id => + ProjectedDataIds.TryDecodeIdentifier(id.IdentifierAsString, out var mapping, out _) && mapping == mappingId).ToArray(); + Volatile.Write(ref _committedProjectedDefinitions, _committedProjectedDefinitions.RemoveRange(descendants).Remove(nodeId)); + foreach (var id in descendants) { if (_projectedVariables.Remove(id, out var child)) { @@ -4274,11 +4309,19 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro /// public bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition) { - lock (Lock) + // Runtime demand checks can hold a source gate that SDK publication also needs. + // Resolve committed metadata without acquiring the SDK address-space lock. + var committed = Volatile.Read(ref _committedProjectedDefinitions); + if (!_disposing && committed.TryGetValue(nodeId, out var current) && current.Lifetime.IsActive && + current.AuthorityIsCurrent() && !_disposing && current.Lifetime.IsActive && + Volatile.Read(ref _committedProjectedDefinitions).TryGetValue(nodeId, out var latest) && + ReferenceEquals(current, latest)) { - if (!_disposing && _projectedDefinitions.TryGetValue(nodeId, out definition) && definition.Lifetime.IsActive && definition.AuthorityIsCurrent()) return true; - definition = null; return false; + definition = current; + return true; } + definition = null; + return false; } private int _maxProjectedNodes = 4096; @@ -4310,6 +4353,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro private long _retiredProjectedBytes; private void RetireProjectedCharge(NodeId id, ProjectedNodeLifetime lifetime) { + RemoveCommittedProjectedDefinition(id); if (!_projectedNodeCharges.Remove(id, out var charge)) { lifetime.ForceRetire(); return; } _projectedNodeBytes -= charge; Interlocked.Add(ref _retiredProjectedBytes, charge); @@ -4330,6 +4374,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro _projectedVariables.Values.Any(child => child.Parent == pair.Key) || !pair.Value.Lifetime.TryRetire()) continue; if (!_projectedVariables.Remove(pair.Key, out var entry)) continue; _projectedDefinitions.Remove(pair.Key); RemoveProjectedSample(pair.Key); + RemoveCommittedProjectedDefinition(pair.Key); if (_projectedNodeCharges.Remove(pair.Key, out var oldBytes)) _projectedNodeBytes -= oldBytes; entry.Node.Parent?.RemoveChild(entry.Node); PredefinedNodes?.Remove(pair.Key); if (_projectedVariables.Count + _projectedAnchors.Count - _projectedRootLeaves.Count + Volatile.Read(ref _retiredProjectedNodes) < _maxProjectedNodes && bytes <= _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes) return true; @@ -4340,7 +4385,10 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro _projectedVariables.Values.Any(node => node.Parent == pair.Key) || !pair.Value.Definition.Lifetime.TryRetire()) continue; if (!_projectedAnchors.TryRemove(pair.Key, out var anchor)) continue; if (_projectedRootLeaves.TryRemove(pair.Key, out _)) - { _projectedVariables.Remove(pair.Key); _projectedDefinitions.Remove(pair.Key); RemoveProjectedSample(pair.Key); } + { + _projectedVariables.Remove(pair.Key); _projectedDefinitions.Remove(pair.Key); RemoveProjectedSample(pair.Key); + RemoveCommittedProjectedDefinition(pair.Key); + } if (_projectedNodeCharges.Remove(pair.Key, out var oldBytes)) _projectedNodeBytes -= oldBytes; anchor.Node.Parent?.RemoveChild(anchor.Node); PredefinedNodes?.Remove(pair.Key); if (_projectedVariables.Count + _projectedAnchors.Count - _projectedRootLeaves.Count + Volatile.Read(ref _retiredProjectedNodes) < _maxProjectedNodes && bytes <= _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes) return true; @@ -4348,6 +4396,17 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro return false; } private readonly Dictionary _projectedDefinitions = new(); + // Writers hold Lock. Staged entries stay private until the catalog commit and SDK checks succeed. + private ImmutableDictionary _committedProjectedDefinitions = + ImmutableDictionary.Empty.WithComparers( + EqualityComparer.Default, System.Collections.Generic.ReferenceEqualityComparer.Instance); + + private void CommitProjectedDefinition(NodeId id, ProjectedVariableDefinition definition) => + Volatile.Write(ref _committedProjectedDefinitions, _committedProjectedDefinitions.SetItem(id, definition)); + + private void RemoveCommittedProjectedDefinition(NodeId id) => + Volatile.Write(ref _committedProjectedDefinitions, _committedProjectedDefinitions.Remove(id)); + private readonly ProjectedCandidateBudget _projectedCandidateBudget = new(65_536, 16 * 1024 * 1024); internal ProjectedCandidateBudget ProjectedCandidateBudget => _projectedCandidateBudget; internal bool IsProjectedItem(NodeId nodeId) => IsProjectedDescendant(nodeId); @@ -4495,7 +4554,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro if (value is null || value.Proof is null || value.Realm is not (DataRealm.Raw or DataRealm.Uns)) { valid = false; continue; } var id = new NodeId(value.LocalIdentifier, value.Realm == DataRealm.Raw ? NamespaceIndexes[2] : NamespaceIndexes[3]); if (!seen.Add(id) || !_projectedVariables.TryGetValue(id, out var target) || target.Generation != value.ProjectionGeneration || - !value.Proof.IsValid || !target.Guard() || target.Node is not BaseDataVariableState || value.Serving.ServingGeneration <= 0 || + !value.Proof.IsValid || value.SourceVersion is <= 0 || !target.Guard() || target.Node is not BaseDataVariableState || value.Serving.ServingGeneration <= 0 || (target.Metadata.Serving is { } expected && expected != value.Serving) || !ProjectedValueMatches(target.Metadata, value.Snapshot.Value)) { valid = false; continue; } try @@ -4515,6 +4574,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro if (valid && targets.Any(target => !target.Value.Proof.IsValid)) valid = false; if (!valid || targets.Count != values.Count) { + ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.SinkRejected); // Retire only matching generations: a late old owner cannot invalidate a new projection. foreach (var value in values) { @@ -4531,6 +4591,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro } else { + ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.SinkAccepted); foreach (var target in targets) { var source = target.Value.Snapshot.Value; @@ -4543,6 +4604,10 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro target.Node.Timestamp = detached.Snapshot.SourceTimestampUtc ?? DateTime.MinValue; RemoveProjectedSample(target.Id); _projectedSamples[target.Id] = detached; _projectedSampleCharges[target.Id] = target.Charge; _projectedSampleBytes += target.Charge; + // A completed baseline may equal the value already installed by another + // cadence. Recovered monitored items have cleared their SDK queues and + // still need the value callback even when no node field changed. + if (detached.IsCompleteSnapshot) target.Node.UpdateChangeMasks(NodeStateChangeMasks.Value); target.Node.ClearChangeMasks(SystemContext, false); } } @@ -4587,6 +4652,37 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro private readonly Dictionary Guard)> _projectedVariables = new(); + bool IProjectedNamespacePageSink.TryRenewExact(NodeId nodeId, ProjectedVariableDefinition expected, + ProjectedVariableDefinition replacement, Func commit) + { + ArgumentNullException.ThrowIfNull(expected); + ArgumentNullException.ThrowIfNull(replacement); + ArgumentNullException.ThrowIfNull(commit); + lock (Lock) + { + if (_disposing || !_projectedDefinitions.TryGetValue(nodeId, out var old) || + !_projectedVariables.TryGetValue(nodeId, out var existing) || + !ReferenceEquals(old.Lifetime, expected.Lifetime) || !old.Lifetime.IsActive || + old.Realm != replacement.Realm || old.LocalIdentifier != replacement.LocalIdentifier || + old.Parent != replacement.Parent || old.Metadata.View != replacement.Metadata.View || + old.Metadata.BrowseName != replacement.Metadata.BrowseName || old.Metadata.NodeKind != replacement.Metadata.NodeKind || + old.Metadata.ValueKind != replacement.Metadata.ValueKind || old.Metadata.ValueRank != replacement.Metadata.ValueRank || + old.Metadata.ArrayElementKind != replacement.Metadata.ArrayElementKind || + !old.Metadata.Dimensions.SequenceEqual(replacement.Metadata.Dimensions) || !replacement.AuthorityIsCurrent()) return false; + var renewed = replacement with { Lifetime = old.Lifetime }; + var charge = checked(ProjectedNodeCharge(renewed) + + (_projectedRootLeaves.ContainsKey(nodeId) ? ProjectedAnchorCharge(_projectedAnchors[nodeId].Definition) : 0)); + var delta = charge - _projectedNodeCharges[nodeId]; + if (delta > _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes || + !commit() || !renewed.AuthorityIsCurrent() || !old.Lifetime.IsActive) return false; + _projectedVariables[nodeId] = (existing.Parent, renewed.ProjectionGeneration, renewed.Metadata, existing.Node, renewed.AuthorityIsCurrent); + _projectedDefinitions[nodeId] = renewed; + _projectedNodeBytes += delta; _projectedNodeCharges[nodeId] = charge; + CommitProjectedDefinition(nodeId, renewed); + return true; + } + } + bool IProjectedNamespacePageSink.TryApply(NodeId parent, IReadOnlyList nodes, Func commit) { ArgumentNullException.ThrowIfNull(nodes); @@ -4596,7 +4692,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro { if (_disposing) return false; var added = new List(); - var renewals = new List<(NodeId Id, ProjectedVariableDefinition Definition, long Charge)>(); + var renewals = new List<(NodeId Id, ProjectedVariableDefinition Definition, long Charge, + ProjectedVariableDefinition Old, BaseInstanceState Node, long OldGeneration)>(); var seen = new HashSet(); var applied = false; try @@ -4609,32 +4706,46 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro if (_projectedVariables.TryGetValue(id, out var existing)) { if (!_projectedDefinitions.TryGetValue(id, out var old) || existing.Parent != parent || - existing.Generation != definition.ProjectionGeneration || !definition.AuthorityIsCurrent() || + old.Parent != parent || old.Realm != definition.Realm || old.LocalIdentifier != definition.LocalIdentifier || + !old.Lifetime.IsActive || !definition.AuthorityIsCurrent() || + (existing.Generation != definition.ProjectionGeneration && + (definition.ProjectionGeneration <= existing.Generation || old.AuthorityIsCurrent())) || old.Metadata.View != definition.Metadata.View || old.Metadata.BrowseName != definition.Metadata.BrowseName || old.Metadata.NodeKind != definition.Metadata.NodeKind || old.Metadata.ValueKind != definition.Metadata.ValueKind || old.Metadata.ValueRank != definition.Metadata.ValueRank || old.Metadata.ArrayElementKind != definition.Metadata.ArrayElementKind || !old.Metadata.Dimensions.SequenceEqual(definition.Metadata.Dimensions)) return false; var renewed = ReferenceEquals(definition.Lifetime, old.Lifetime) ? definition : definition with { Lifetime = old.Lifetime }; renewals.Add((id, renewed, checked(ProjectedNodeCharge(renewed) + - (_projectedRootLeaves.ContainsKey(id) ? ProjectedAnchorCharge(_projectedAnchors[id].Definition) : 0)))); + (_projectedRootLeaves.ContainsKey(id) ? ProjectedAnchorCharge(_projectedAnchors[id].Definition) : 0)), + old, existing.Node, existing.Generation)); continue; } - if (!TryEnsureProjectedVariable(definition, out var created) || created != id) return false; + if (!TryEnsureProjectedVariable(definition, out var created, stage: true) || created != id) return false; added.Add(id); } long renewalDelta = 0; foreach (var renewal in renewals) renewalDelta = checked(renewalDelta + renewal.Charge - _projectedNodeCharges[renewal.Id]); + bool RenewalsCurrent() => renewals.All(renewal => renewal.Old.Lifetime.IsActive && + _projectedDefinitions.TryGetValue(renewal.Id, out var current) && ReferenceEquals(current, renewal.Old) && + _projectedVariables.TryGetValue(renewal.Id, out var variable) && variable.Parent == parent && + variable.Generation == renewal.OldGeneration && ReferenceEquals(variable.Node, renewal.Node) && + (renewal.OldGeneration == renewal.Definition.ProjectionGeneration || !renewal.Old.AuthorityIsCurrent())); if (renewalDelta > _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes || - nodes.Any(node => !node.AuthorityIsCurrent()) || !commit() || nodes.Any(node => !node.AuthorityIsCurrent())) return false; + !RenewalsCurrent() || !added.All(_projectedDefinitions.ContainsKey) || nodes.Any(node => !node.AuthorityIsCurrent()) || + !commit() || !RenewalsCurrent() || !added.All(_projectedDefinitions.ContainsKey) || + nodes.Any(node => !node.AuthorityIsCurrent())) return false; foreach (var renewal in renewals) { var previous = _projectedVariables[renewal.Id]; - _projectedVariables[renewal.Id] = (previous.Parent, previous.Generation, renewal.Definition.Metadata, + _projectedVariables[renewal.Id] = (previous.Parent, renewal.Definition.ProjectionGeneration, renewal.Definition.Metadata, previous.Node, renewal.Definition.AuthorityIsCurrent); _projectedDefinitions[renewal.Id] = renewal.Definition; _projectedNodeBytes += renewal.Charge - _projectedNodeCharges[renewal.Id]; _projectedNodeCharges[renewal.Id] = renewal.Charge; } + var committed = _committedProjectedDefinitions.SetItems(seen.Select(id => + new KeyValuePair(id, _projectedDefinitions[id]))); + Volatile.Write(ref _committedProjectedDefinitions, committed); applied = true; return true; } @@ -4687,6 +4798,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro _projectedDefinitions[anchorId] = installed; _projectedNodeCharges[anchorId] = renewedCharge; _projectedNodeBytes += delta; + CommitProjectedDefinition(anchorId, installed); return true; } if (anchor.Node is not FolderState folder) return false; @@ -4729,6 +4841,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro _projectedDefinitions.Add(anchorId, installed); _projectedNodeCharges[anchorId] = anchorCharge + charge; _projectedNodeBytes += charge; charged = true; if (!installed.AuthorityIsCurrent() || !commit() || !installed.AuthorityIsCurrent()) return false; + CommitProjectedDefinition(anchorId, installed); accepted = true; return true; } finally @@ -4759,7 +4872,10 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro } /// Materializes one checked scalar under its exact existing parent. Access stays denied until its live proof is wired. - internal bool TryEnsureProjectedVariable(ProjectedVariableDefinition definition, out NodeId? nodeId) + internal bool TryEnsureProjectedVariable(ProjectedVariableDefinition definition, out NodeId? nodeId) => + TryEnsureProjectedVariable(definition, out nodeId, stage: false); + + private bool TryEnsureProjectedVariable(ProjectedVariableDefinition definition, out NodeId? nodeId, bool stage) { nodeId = null; if (definition is null || definition.Metadata is null || definition.AuthorityIsCurrent is null || @@ -4813,6 +4929,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro _projectedVariables.Add(candidate, (definition.Parent, definition.ProjectionGeneration, definition.Metadata, node, definition.AuthorityIsCurrent)); _projectedDefinitions.Add(candidate, definition); _projectedNodeCharges.Add(candidate, charge); _projectedNodeBytes += charge; + if (!stage) CommitProjectedDefinition(candidate, definition); nodeId = candidate; return true; } } @@ -5424,6 +5541,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro lock (Lock) { retiredProofs = _projectedSamples.Values.Select(sample => sample.Proof).Distinct().ToArray(); + Volatile.Write(ref _committedProjectedDefinitions, _committedProjectedDefinitions.Clear()); foreach (var item in _liveItems.Keys.OfType()) item.Retire(); foreach (var id in _projectedVariables.Keys) PredefinedNodes?.Remove(id); foreach (var id in _projectedAnchors.Keys) PredefinedNodes?.Remove(id); @@ -5841,9 +5959,13 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro if (_projectedAnchors.TryGetValue(nodeId, out var anchor) && operation == OpcUaOperation.Browse) { if (!anchor.Definition.AuthorityIsCurrent()) return false; - var localId = new NodeId(anchor.Definition.LocalSubject, NamespaceIndexForRealm(realm)); - return _authorizer?.AuthorizeIfRequired(identity, operation, localId, realm) is null && - (_authorizer is not null || _mappedSubjectResolver is null); + var scope = anchor.Definition.LocalScope; + return scope is not null && scope.Kind == (realm == AddressSpaceRealm.Raw ? NodeHierarchyKind.Raw : NodeHierarchyKind.Uns) && + scope.Segments.Count > 0 && scope.Segments.All(segment => !string.IsNullOrWhiteSpace(segment) && !segment.Contains('/')) && + string.Join('/', scope.Segments) == anchor.Definition.LocalSubject && + scope.Segments[^1] == anchor.Definition.BrowseName && + _authorizer is { } authorizer && authorizer.AuthorizeProjectedAnchor(identity, scope) && + anchor.Definition.AuthorityIsCurrent(); } if (nodeId.NamespaceIndex == NamespaceIndexes[2] || nodeId.NamespaceIndex == NamespaceIndexes[3]) return _authorizer is { } mappedAuthorizer && mappedAuthorizer.TryAuthorizeMapped(identity, operation, nodeId, realm, out var veto) && veto is null; @@ -6395,7 +6517,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro NodeHandle handle) { if (SecurityFilteringActive && monitoringMode != MonitoringMode.Disabled - && !(monitoredItem is ProjectedMonitoredItem projected && projected.IsCurrent) + && !(monitoredItem is ProjectedMonitoredItem projected && projected.HasCurrentDemand) && !Permits(IdentityOf(context), OpcUaOperation.CreateMonitoredItems, handle.NodeId)) { return StatusCodes.BadUserAccessDenied; @@ -6412,6 +6534,13 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro TrackLiveMonitoredItem(handle, monitoredItem); } + protected override void OnMonitoringModeChanged(ServerSystemContext context, NodeHandle handle, + ISampledDataChangeMonitoredItem monitoredItem, MonitoringMode previousMode, MonitoringMode monitoringMode) + { + base.OnMonitoringModeChanged(context, handle, monitoredItem, previousMode, monitoringMode); + if (monitoredItem is ProjectedMonitoredItem projected) projected.ResetHealthMonitoringMode(); + } + /// Starts tracking for revalidation, if we own its node. /// The handle the item was created against. /// The item. @@ -6422,13 +6551,14 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro internal void TrackLiveMonitoredItem(NodeHandle handle, ISampledDataChangeMonitoredItem monitoredItem) { if (OwnsNamespace(handle.NodeId)) _liveItems[monitoredItem] = new LiveItem(handle); + if (monitoredItem is ProjectedMonitoredItem projected) TrackProjectedHealth(projected); } /// protected override void OnMonitoredItemDeleted( ServerSystemContext context, NodeHandle handle, ISampledDataChangeMonitoredItem monitoredItem) { - if (monitoredItem is ProjectedMonitoredItem projected) projected.Retire(); + if (monitoredItem is ProjectedMonitoredItem projected) { ForgetProjectedHealth(projected); projected.Retire(); } if (_liveItems.TryRemove(monitoredItem, out var tracked) && tracked.Suppressed) Interlocked.Decrement(ref _suppressedItems); base.OnMonitoredItemDeleted(context, handle, monitoredItem); } @@ -6574,6 +6704,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro if (!tracked.Suppressed || (nodeId is not null && tracked.Handle.NodeId != nodeId.Value)) continue; if (!_liveItems.TryRemove(item, out _)) continue; Interlocked.Decrement(ref _suppressedItems); + if (item is ProjectedMonitoredItem projected) projected.Retire(); TellNodeRemoved(item, now); ReleaseComponentCacheReference(item); } @@ -6614,6 +6745,11 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro _cacheReferenceReleased.AddOrUpdate(item, ReleasedMarker); } + // The SDK's classic item-manager factory has no rollback callback. A failed + // item is never returned to the SDK, so return its exact cache reference here. + internal void ReleaseFailedComponentCache(ISystemContext context, NodeHandle handle) => + RemoveNodeFromComponentCache(context, handle); + /// Data items whose component-cache reference a removal already gave back (review fix I3). Weak, so an /// item the SDK drops without a delete (it always deletes, but a leak here would be silent) is not kept alive. private readonly System.Runtime.CompilerServices.ConditionalWeakTable _cacheReferenceReleased = new(); @@ -6729,6 +6865,69 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro /// for every create and delete including subscription teardown, so the map cannot outlive the items. /// private readonly ConcurrentDictionary _liveItems = new(); + private readonly object _projectedHealthGate = new(); + private readonly LinkedList _projectedHealthItems = new(); + private readonly Dictionary> _projectedHealthIndex = new(); + private LinkedListNode? _projectedHealthCursor; + private ITimer? _projectedHealthTimer; + private bool _projectedHealthStopped; + private int _projectedHealthRunning; + private void TrackProjectedHealth(ProjectedMonitoredItem item) + { + lock (_projectedHealthGate) + { + if (_projectedHealthStopped || item.HealthRetired || _projectedHealthIndex.ContainsKey(item)) return; + _projectedHealthIndex.Add(item, _projectedHealthItems.AddLast(item)); + _projectedHealthTimer ??= ProjectedBrowseClock.CreateTimer(_ => SweepProjectedHealth(), null, + TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(100)); + } + } + internal void ForgetProjectedHealth(ProjectedMonitoredItem item) + { + lock (_projectedHealthGate) + { + if (!_projectedHealthIndex.Remove(item, out var node)) return; + if (ReferenceEquals(_projectedHealthCursor, node)) _projectedHealthCursor = node.Next ?? _projectedHealthItems.First; + _projectedHealthItems.Remove(node); + if (_projectedHealthItems.Count == 0) _projectedHealthCursor = null; + } + } + private void SweepProjectedHealth() + { + if (Interlocked.Exchange(ref _projectedHealthRunning, 1) != 0) return; + try + { + var items = new List(256); + lock (_projectedHealthGate) + { + if (_projectedHealthStopped || _projectedHealthItems.Count == 0) return; + var count = Math.Min(256, _projectedHealthItems.Count); + var cursor = _projectedHealthCursor ?? _projectedHealthItems.First!; + for (var i = 0; i < count; i++) + { + items.Add(cursor.Value); + cursor = cursor.Next ?? _projectedHealthItems.First!; + } + _projectedHealthCursor = cursor; + } + foreach (var item in items) + { + try + { + if (item.HealthRetired) { ForgetProjectedHealth(item); continue; } + if (_liveItems.TryGetValue(item, out var tracked) && tracked.Suppressed) + RevalidateProjectedItem(item, tracked, UtcNow); + var loss = item.CaptureLoss(); + if (loss is null) continue; + // Sample application uses this same order (manager lock, then item lock). + lock (Lock) if (!_disposing) item.QueueLossIfCurrent(loss); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { _logger.LogDebug(ex, "Projected health observation will be retried"); } + } + } + finally { Volatile.Write(ref _projectedHealthRunning, 0); } + } /// A tracked monitored item: the handle it was created against, and whether we have silenced it. /// The node handle, which carries the fan-out list. @@ -8219,6 +8418,54 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro /// QueueValue calls between them, and the attach/detach is what actually needs the lock. /// /// + // The bounded health sweep and authority-change pass share this exact-item + // transition so renewal can reattach without a second global ACL pass. + private int RevalidateProjectedItem(ProjectedMonitoredItem item, LiveItem expected, DateTime now) + { + var restored = false; + var removed = false; + var changed = 0; + lock (Lock) + { + if (_disposing || !_liveItems.TryGetValue(item, out var current) || !ReferenceEquals(current, expected)) return 0; + bool permitted; + try { permitted = item.HasCurrentDemand; } + catch (Exception ex) when (ex is not OutOfMemoryException) { permitted = false; } + if (permitted && current.Suppressed) + { + var liveNode = (GetManagerHandle(current.Handle.NodeId) as NodeHandle)?.Node; + if (liveNode is not null && ReferenceEquals(liveNode, current.Handle.Node) && current.Handle.MonitoredNode is { } fanout) + { + fanout.Add((IDataChangeMonitoredItem2)item); current.Suppressed = false; + Interlocked.Decrement(ref _suppressedItems); restored = true; changed = 1; + } + else + { + _liveItems.TryRemove(item, out _); current.Suppressed = false; + Interlocked.Decrement(ref _suppressedItems); removed = true; + } + } + else if (!permitted && !current.Suppressed) + { + try + { + item.QueueValue(new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied, DateTimeUtc.MinValue, now), + new ServiceResult(StatusCodes.BadUserAccessDenied), ignoreFilters: true); + } + catch (Exception ex) when (ex is not OutOfMemoryException) { } + current.Handle.MonitoredNode?.Remove((IDataChangeMonitoredItem2)item); + current.Suppressed = true; Interlocked.Increment(ref _suppressedItems); changed = -1; + } + } + if (removed) { item.Retire(); TellNodeRemoved(item, now); } + else if (restored) + { + try { item.RequestBaseline(); } + catch (Exception ex) when (ex is not OutOfMemoryException) { } + } + return changed; + } + public void RevalidateMonitoredItems() { if (!SecurityFilteringActive) return; @@ -8239,10 +8486,16 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro // re-checked — the deploy thread running this has no session of its own. if (item is not IMonitoredItem live) continue; + if (item is ProjectedMonitoredItem projected) + { + var changed = RevalidateProjectedItem(projected, tracked, now); + if (changed < 0) stoodDown++; + else if (changed > 0) restored++; + continue; + } + var nodeId = tracked.Handle.NodeId; - var permitted = item is ProjectedMonitoredItem projectedItem - ? projectedItem.HasCurrentDemand - : IsSubscriptionStillPermitted(live.EffectiveIdentity as RoleCarryingUserIdentity, nodeId, verdicts); + var permitted = IsSubscriptionStillPermitted(live.EffectiveIdentity as RoleCarryingUserIdentity, nodeId, verdicts); if (permitted) { @@ -8266,7 +8519,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro Interlocked.Decrement(ref _suppressedItems); if (!reattached) { - if (item is ProjectedMonitoredItem projected) projected.Retire(); + if (item is ProjectedMonitoredItem removedProjected) removedProjected.Retire(); TellNodeRemoved(item, now); continue; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs index 4bdd72be5..d8bf1cd39 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs @@ -413,7 +413,7 @@ public sealed class OtOpcUaSdkServer : StandardServer demand is null || !demand.IsValid) { result[i] = StatusCodes.BadUserAccessDenied; continue; } if (!manager.CanDispatchProjectedWrite()) { result[i] = StatusCodes.BadInvalidState; continue; } - var milliseconds = requestHeader is { TimeoutHint: > 0 } ? Math.Min(requestHeader.TimeoutHint, 5000u) : 5000u; + var milliseconds = requestHeader is { TimeoutHint: > 0 } ? Math.Min(requestHeader.TimeoutHint, 30000u) : 30000u; var budget = new DataBudget(TimeSpan.FromMilliseconds(milliseconds), 1, 4 * 1024 * 1024); var outcome = await access.WriteAsync(demand, SdkValueBoundary.ToClr(item.Value.WrappedValue), budget, started, requestLifetime.CancellationToken).ConfigureAwait(false); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedDeliveryDiagnostics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedDeliveryDiagnostics.cs new file mode 100644 index 000000000..79a00171d --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedDeliveryDiagnostics.cs @@ -0,0 +1,13 @@ +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// Bounded aggregate observations of projected SDK notification admission. +public static class ProjectedDeliveryDiagnostics +{ + internal enum Event { SinkRejected, SinkAccepted, CandidateUnique, CandidateMissing, CandidateAmbiguous, + CurrentBindingRejected, CurrentProofRejected, CurrentAgeRejected, CurrentAccepted, + MarkerHandleRejected, MarkerFingerprintRejected, MarkerAuthorizationRejected, MarkerAccepted, MarkerException } + private static readonly long[] Counts = new long[Enum.GetValues().Length]; + internal static void Count(Event value) => Interlocked.Increment(ref Counts[(int)value]); + /// Captures process-wide counters without source identifiers or payloads. + public static IReadOnlyDictionary Capture() => Enum.GetValues().ToDictionary(x => x.ToString(), x => Interlocked.Read(ref Counts[(int)x])); +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs index 63eaf4af5..f09f23333 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs @@ -41,6 +41,10 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre /// public bool TryRemove(NodeId nodeId, ProjectedVariableDefinition expected) => ((IProjectedNamespacePageSink)_nodeManager).TryRemove(nodeId, expected); + /// + public bool TryRenewExact(NodeId nodeId, ProjectedVariableDefinition expected, ProjectedVariableDefinition replacement, Func commit) => + ((IProjectedNamespacePageSink)_nodeManager).TryRenewExact(nodeId, expected, replacement, commit); + /// public bool TryApply(NodeId parent, IReadOnlyList nodes, Func commit) => ((IProjectedNamespacePageSink)_nodeManager).TryApply(parent, nodes, commit); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs index df1f203c1..5c0d5ec6d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs @@ -149,6 +149,15 @@ public sealed class DataPlaneAuthorizer NodeId nodeId, AddressSpaceRealm realm, bool cached = true) => Evaluate(identity, operation, nodeId, realm, cached, localBypass: !Enabled); + /// Checks a deployed mapping's local anchor scope regardless of the legacy ACL switch. + public bool AuthorizeProjectedAnchor(RoleCarryingUserIdentity? identity, NodeScope scope) + { + if (identity is null) return false; + var caller = new DataCallerIdentity(identity.Principal, identity.ApiKeyId, + identity.CredentialVersion, identity.CredentialExpiresUtc); + return _policy.AuthorizeLocal(caller, OpcUaOperation.Browse, scope); + } + /// Checks a mapping without changing the legacy local role gate. public bool TryAuthorizeMapped(RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId, AddressSpaceRealm realm, out ServiceResult? veto) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs index 9a1f01627..38fcb2eb2 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs @@ -351,18 +351,25 @@ internal sealed class OrdinaryTagItemManager(IAsyncNodeManager nodeManager, ISer throw new ServiceResultException(StatusCodes.BadUserAccessDenied); uint? reservedId = null; + ISampledDataChangeMonitoredItem? constructed = null; + MonitoredNode2? registeredNode = null; + var cacheAdded = false; + var createdNode = false; try { // Mirrors MonitoredNodeMonitoredItemManager.CreateMonitoredItem in exact tagged 2.0.1, swapping only the item type. var cachedNode = addNodeToComponentCache(context, handle, handle.Node); + cacheAdded = true; if (!MonitoredNodes.TryGetValue(handle.Node.NodeId, out var monitoredNode)) { MonitoredNodes[handle.Node.NodeId] = monitoredNode = new MonitoredNode2(nodeManager, server, cachedNode, nodeManager.IsMultipleEventConsumerNode(cachedNode.NodeId)); + createdNode = true; } handle.Node = monitoredNode.Node; handle.MonitoredNode = monitoredNode; + registeredNode = monitoredNode; uint id; do { @@ -371,7 +378,7 @@ internal sealed class OrdinaryTagItemManager(IAsyncNodeManager nodeManager, ISer while (!MonitoredItems.TryAdd(id, null!)); reservedId = id; - ISampledDataChangeMonitoredItem item = projected + ISampledDataChangeMonitoredItem item = constructed = projected ? new ProjectedMonitoredItem(server, nodeManager, handle, subscriptionId, id, itemToCreate, diagnosticsMasks, timestampsToReturn, filterToUse, euRange, samplingInterval, revisedQueueSize, createDurable, owner, demand!, initialSample, definition!) @@ -386,6 +393,24 @@ internal sealed class OrdinaryTagItemManager(IAsyncNodeManager nodeManager, ISer catch { if (reservedId is { } id) MonitoredItems.TryRemove(id, out _); + if (constructed is IDataChangeMonitoredItem2 data && registeredNode is not null) + { + try { registeredNode.Remove(data); } catch (Exception) { } + } + if (createdNode && registeredNode is not null && !registeredNode.HasMonitoredItems && + MonitoredNodes.TryGetValue(registeredNode.Node.NodeId, out var currentNode) && ReferenceEquals(currentNode, registeredNode) && + MonitoredNodes.TryRemove(registeredNode.Node.NodeId, out _)) + { + try { registeredNode.Dispose(); } catch (Exception) { } + } + if (cacheAdded) + { + try { owner.ReleaseFailedComponentCache(context, handle); } catch (Exception) { } + } + if (constructed is IDisposable disposable) + { + try { disposable.Dispose(); } catch (Exception) { } + } demand?.Dispose(); throw; } @@ -399,7 +424,7 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem private IProjectedDemandLease? _demand; private ProjectedVariableDefinition? _definition; private readonly NodeId _nodeId; - private sealed class SourceBinding(IProjectedSamplePublicationProof proof) + internal sealed class SourceBinding(IProjectedSamplePublicationProof proof) { private readonly object _sync = new(); private IProjectedSamplePublicationProof? _proof = proof; @@ -429,7 +454,7 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem } } private sealed record Candidate(ProjectedValueWrite Sample, Variant Value, SourceBinding Binding, long Bytes, IDisposable Charge); - private sealed class SampleEvidence(SourceBinding binding, IProjectedSamplePublicationProof proof, DataAgeBounds age, long receivedTimestamp) + internal sealed class SampleEvidence(SourceBinding binding, IProjectedSamplePublicationProof proof, DataAgeBounds age, long receivedTimestamp) { private IProjectedSamplePublicationProof? _proof = proof; public SourceBinding Binding => binding; @@ -442,6 +467,10 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem private const long MaxCandidateBytes = 1024 * 1024; private readonly object _bindingSync = new(); private readonly List _candidates = []; + private SampleEvidence? _latestEvidence; + private SampleEvidence? _reportedLoss; + private LossControl? _queuedLoss; + internal Action? AfterLossDequeueForTests; private long _candidateBytes; private bool _needsSnapshot; private int _snapshotRequested; @@ -462,6 +491,7 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem { _binding = new(initialSample.Proof); AddCandidate(initialSample, _binding); + _latestEvidence = new SampleEvidence(_binding, initialSample.Proof, initialSample.OriginAgeBounds, initialSample.ReceivedTimestamp); } } @@ -471,11 +501,38 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem lock (_bindingSync) { var original = _binding; - var sameSource = original is not null && ReferenceEquals(original.Proof?.SourceIdentity, sample.Proof.SourceIdentity); + // A new physical attempt may use the same logical source identity, but an + // ended attempt's captured evidence must not keep the SDK queue bound to it. + var sameSource = original is { IsValid: true } && ReferenceEquals(original.Proof?.SourceIdentity, sample.Proof.SourceIdentity); + if (sample.IsCompleteSnapshot && sameSource && !_needsSnapshot) + { + var matching = _candidates.FirstOrDefault(candidate => ReferenceEquals(candidate.Binding, original) && + SameAcquisition(candidate.Sample, sample)); + if (matching is not null) + { + // A queued notification keeps its original evidence. If it has expired, + // a separately fresh observation must start a new binding and queue. + if (FreshForDemand(matching.Sample)) + { + // A separately proven observation may renew health without + // changing the queued candidate's original sample witness. + if (FreshForDemand(sample)) + { + var successor = new SampleEvidence(original!, sample.Proof, sample.OriginAgeBounds, sample.ReceivedTimestamp); + _latestEvidence?.Clear(); + _latestEvidence = successor; _reportedLoss = null; + } + return false; + } + if (!FreshForDemand(sample)) return true; + _needsSnapshot = true; + } + } if (!sameSource || (_needsSnapshot && sample.IsCompleteSnapshot)) { original?.Retire(); _binding = null; + _latestEvidence?.Clear(); _latestEvidence = null; _queuedLoss = null; _reportedLoss = null; if (Volatile.Read(ref _retired) != 0 || !sample.IsCompleteSnapshot || !sample.Proof.IsSourceValid || _demand?.IsValid != true) { _needsSnapshot = true; return true; } // Pinned SDK resets the entire data queue and last value across this transition. @@ -491,9 +548,101 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem } if (_binding is null) { _needsSnapshot = true; return true; } if (_candidates.Any(candidate => ReferenceEquals(candidate.Sample, sample))) return false; - return !AddCandidate(sample, _binding); + if (_queuedLoss is not null) + { + // A newly admitted value supersedes an unconsumed outage status. + // Reset the SDK queue before its normal value callback is delivered. + var mode = MonitoringMode; + if (mode != MonitoringMode.Disabled) { SetMonitoringMode(MonitoringMode.Disabled); SetMonitoringMode(mode); } + ClearCandidates(); _queuedLoss = null; + } + if (!AddCandidate(sample, _binding)) return true; + _latestEvidence?.Clear(); _reportedLoss = null; + _latestEvidence = new SampleEvidence(_binding, sample.Proof, sample.OriginAgeBounds, sample.ReceivedTimestamp); + return false; } } + internal bool HealthRetired => Volatile.Read(ref _retired) != 0; + internal sealed class LossControl(ProjectedMonitoredItem owner, SampleEvidence evidence) + { + internal bool IsCurrent => owner.IsLossCurrent(evidence); + internal bool IsAuthorized + { + get + { + try { return owner.HasCurrentDemand; } + catch (Exception ex) when (ex is not OutOfMemoryException) { return false; } + } + } + internal SampleEvidence Evidence => evidence; + } + private bool IsLossCurrent(SampleEvidence evidence) + { + if (Volatile.Read(ref _retired) != 0 || !ReferenceEquals(Volatile.Read(ref _latestEvidence), evidence) || + !ReferenceEquals(Volatile.Read(ref _binding), evidence.Binding)) return false; + var proof = evidence.Proof; + var demand = _demand; + if (proof is null || demand is null) return true; + try + { + if (!proof.IsValid || demand.MaximumSampleAge <= TimeSpan.Zero) return true; + var elapsed = proof.Clock.GetElapsedTime(evidence.ReceivedTimestamp, proof.Clock.GetTimestamp()); + return elapsed < TimeSpan.Zero || !evidence.Age.Advance(elapsed).IsFresh(demand.MaximumSampleAge); + } + catch (Exception ex) when (ex is not OutOfMemoryException) { return true; } + } + internal LossControl? CaptureLoss() + { + if (Volatile.Read(ref _queuedLoss) is not null) return null; + var latest = Volatile.Read(ref _latestEvidence); + if (ReferenceEquals(Volatile.Read(ref _reportedLoss), latest)) return null; + return latest is not null && IsLossCurrent(latest) ? new LossControl(this, latest) : null; + } + // Called under the manager lock, matching the order used by ObserveSample. + // No source/caller callback is evaluated while that lock is held. + internal void QueueLossIfCurrent(LossControl loss) + { + lock (_bindingSync) + { + if (MonitoringMode == MonitoringMode.Disabled || _queuedLoss is not null || ReferenceEquals(_reportedLoss, loss.Evidence) || _retired != 0 || !ReferenceEquals(_latestEvidence, loss.Evidence) || + !ReferenceEquals(_binding, loss.Evidence.Binding)) return; + _queuedLoss = loss; + try { QueueValue(new DataValue(Variant.Null, StatusCodes.BadNoCommunication, DateTimeUtc.MinValue, DateTimeUtc.MinValue), + new ServiceResult(StatusCodes.BadNoCommunication), ignoreFilters: true); } + catch (Exception) { _queuedLoss = null; } + } + } + private bool FreshForDemand(ProjectedValueWrite sample) + { + if (_demand is not { IsValid: true } demand || demand.MaximumSampleAge <= TimeSpan.Zero || !sample.Proof.IsValid) return false; + try + { + return sample.OriginAgeBounds.Advance(sample.Proof.Clock.GetElapsedTime(sample.ReceivedTimestamp, + sample.Proof.Clock.GetTimestamp())).IsFresh(demand.MaximumSampleAge); + } + catch (Exception ex) when (ex is ArgumentException or OverflowException) { return false; } + } + internal static bool SameAcquisition(ProjectedValueWrite left, ProjectedValueWrite right) + { + if (left.SourceVersion is not > 0 || left.SourceVersion != right.SourceVersion || + !ReferenceEquals(left.Proof.SourceIdentity, right.Proof.SourceIdentity) || !ReferenceEquals(left.Proof.Clock, right.Proof.Clock) || + left.Realm != right.Realm || left.LocalIdentifier != right.LocalIdentifier || left.ProjectionGeneration != right.ProjectionGeneration || + left.Serving != right.Serving || + left.Snapshot.StatusCode != right.Snapshot.StatusCode || left.Snapshot.SourceTimestampUtc != right.Snapshot.SourceTimestampUtc || + left.Snapshot.ServerTimestampUtc != right.Snapshot.ServerTimestampUtc) return false; + var first = left.Snapshot.Value; var second = right.Snapshot.Value; + if (first is Array || second is Array) + return first is Array firstArray && second is Array secondArray && firstArray.GetType() == secondArray.GetType() && + System.Collections.StructuralComparisons.StructuralEqualityComparer.Equals(firstArray, secondArray); + return Equals(first, second); + } + // The SDK removes the DataValue info-type marker when it carries no info bits. + // Keep every actual information, structure, semantics, severity and subcode bit. + internal static bool SameObservedStatus(uint source, uint observed) + { + static uint Normalize(uint value) => (value & 0x00000FFFu) == 0x00000400u ? value & ~0x00000400u : value; + return Normalize(source) == Normalize(observed); + } private bool AddCandidate(ProjectedValueWrite sample, SourceBinding binding) { long bytes = 256; @@ -531,14 +680,20 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem private bool IsCurrentCandidate(SourceBinding? binding, SampleEvidence? candidate) { if (candidate is null || !ReferenceEquals(candidate.Binding, binding) || !IsCurrentBinding(binding) || - _demand is not { } demand || demand.MaximumSampleAge <= TimeSpan.Zero) return false; - if (candidate.Proof is not { IsValid: true } proof) { RequestBaseline(); return false; } + _demand is not { } demand || demand.MaximumSampleAge <= TimeSpan.Zero) { ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.CurrentBindingRejected); return false; } + if (candidate.Proof is not { IsValid: true } proof) { ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.CurrentProofRejected); RequestBaseline(); return false; } try { var age = candidate.Age.Advance(proof.Clock.GetElapsedTime(candidate.ReceivedTimestamp, proof.Clock.GetTimestamp())); - if (age.IsFresh(demand.MaximumSampleAge)) return proof.IsValid && IsCurrentBinding(binding); + if (age.IsFresh(demand.MaximumSampleAge)) + { + var current = proof.IsValid && IsCurrentBinding(binding); + ProjectedDeliveryDiagnostics.Count(current ? ProjectedDeliveryDiagnostics.Event.CurrentAccepted : ProjectedDeliveryDiagnostics.Event.CurrentBindingRejected); + return current; + } } catch (Exception ex) when (ex is ArgumentException or OverflowException) { } + ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.CurrentAgeRejected); RequestBaseline(); return false; } @@ -547,42 +702,107 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem internal bool IsCurrent => IsCurrentBinding(Volatile.Read(ref _binding)); internal bool HasCurrentDemand => Volatile.Read(ref _retired) == 0 && _demand is { IsValid: true } && _definition is { } definition && _owner.IsProjectedDefinitionCurrent(_nodeId, definition); + internal void ResetHealthMonitoringMode() + { + lock (_bindingSync) { _queuedLoss = null; _reportedLoss = null; } + } internal void Retire() { - Interlocked.Exchange(ref _retired, 1); - lock (_bindingSync) { _binding?.Retire(); _binding = null; ClearCandidates(); } + if (Interlocked.Exchange(ref _retired, 1) != 0) return; + _owner.ForgetProjectedHealth(this); + lock (_bindingSync) { _binding?.Retire(); _binding = null; _latestEvidence?.Clear(); _latestEvidence = null; _queuedLoss = null; _reportedLoss = null; ClearCandidates(); } _definition = null; if (Interlocked.Exchange(ref _released, 1) == 0) Interlocked.Exchange(ref _demand, null)?.Dispose(); } + protected override void Dispose(bool disposing) + { + try { if (disposing) Retire(); } + finally { base.Dispose(disposing); } + } public override bool Publish(OperationContext context, Queue notifications, Queue diagnostics, uint maximum, ILogger logger) { - var captured = Volatile.Read(ref _binding); var local = new Queue(); var localDiagnostics = new Queue(); - var more = base.Publish(context, local, localDiagnostics, maximum, logger); + SourceBinding? captured; + LossControl? capturedLoss; + bool more; + lock (_bindingSync) + { + captured = _binding; + capturedLoss = _queuedLoss; + more = base.Publish(context, local, localDiagnostics, maximum, logger); + } + var hadLocal = local.Count > 0; + if (capturedLoss is not null && local.Any(x => x.Value.WrappedValue.IsNull && x.Value.StatusCode.Code == StatusCodes.BadNoCommunication)) + AfterLossDequeueForTests?.Invoke(); + var sawLoss = false; while (local.Count > 0) { var notification = local.Dequeue(); SampleEvidence? evidence = null; lock (_bindingSync) { + if (capturedLoss is { } loss && notification.Value.WrappedValue.IsNull && + notification.Value.StatusCode.Code == StatusCodes.BadNoCommunication) + { + sawLoss = true; + if (ReferenceEquals(_queuedLoss, loss)) _queuedLoss = null; + if (ReferenceEquals(_latestEvidence, loss.Evidence)) _reportedLoss = loss.Evidence; + notifications.Enqueue(new ProjectedSdkNotification(notification, + new ProjectedLossMarker(notification.ClientHandle, loss))); + if (localDiagnostics.Count > 0) diagnostics.Enqueue(localDiagnostics.Dequeue()); + continue; + } + // The SDK can replace a Bad source sample's value with null. Every + // Bad candidate of the same status could have produced that null; + // consider all of them before using a source timestamp to disambiguate. + var badNull = notification.Value.WrappedValue.IsNull && StatusCode.IsBad(notification.Value.StatusCode); var matching = _candidates.Where(candidate => ReferenceEquals(candidate.Binding, captured) && - candidate.Value.Equals(notification.Value.WrappedValue) && candidate.Sample.Snapshot.StatusCode == notification.Value.StatusCode.Code).Take(2).ToArray(); + (badNull || candidate.Value.Equals(notification.Value.WrappedValue)) && + SameObservedStatus(candidate.Sample.Snapshot.StatusCode, notification.Value.StatusCode.Code)).Take(2).ToArray(); + if (matching.Length > 1 && notification.Value.SourceTimestamp != DateTimeUtc.MinValue) + { + // The SDK carries the source timestamp from the projected node. It can + // distinguish equal values from different acquisitions, but only when + // exactly one retained acquisition has that original timestamp. + matching = _candidates.Where(candidate => ReferenceEquals(candidate.Binding, captured) && + (badNull || candidate.Value.Equals(notification.Value.WrappedValue)) && + SameObservedStatus(candidate.Sample.Snapshot.StatusCode, notification.Value.StatusCode.Code) && + candidate.Sample.Snapshot.SourceTimestampUtc is { } sourceTimestamp && + (DateTimeUtc)sourceTimestamp == notification.Value.SourceTimestamp).Take(2).ToArray(); + } + if (matching.Length == 1 && notification.Value.SourceTimestamp != DateTimeUtc.MinValue && + matching[0].Sample.Snapshot.SourceTimestampUtc is { } originalTimestamp && + (DateTimeUtc)originalTimestamp != DateTimeUtc.MinValue && + (DateTimeUtc)originalTimestamp != notification.Value.SourceTimestamp) + { + // A contradictory timestamp cannot consume the sole remaining + // candidate's proof, even when value and status happen to match. + matching = []; + } if (matching.Length == 1) { + ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.CandidateUnique); var matched = matching[0]; _candidates.Remove(matched); _candidateBytes -= matched.Bytes; evidence = matched.Binding.Capture(matched.Sample.Proof, matched.Sample.OriginAgeBounds, matched.Sample.ReceivedTimestamp); matched.Charge.Dispose(); } - else _needsSnapshot = true; + else { ProjectedDeliveryDiagnostics.Count(matching.Length == 0 ? ProjectedDeliveryDiagnostics.Event.CandidateMissing : ProjectedDeliveryDiagnostics.Event.CandidateAmbiguous); _needsSnapshot = true; } } if (evidence is null) RequestBaseline(); var originalSample = evidence; - notification.Message = new ProjectedNotificationMarker(notification.ClientHandle, notification.Value, () => IsCurrentCandidate(captured, originalSample)); - notifications.Enqueue(notification); + notifications.Enqueue(new ProjectedSdkNotification(notification, + new ProjectedNotificationMarker(notification.ClientHandle, notification.Value, + () => IsCurrentCandidate(captured, originalSample)))); if (localDiagnostics.Count > 0) diagnostics.Enqueue(localDiagnostics.Dequeue()); } + if (!sawLoss && capturedLoss is not null && !more) + { + lock (_bindingSync) + if (ReferenceEquals(_queuedLoss, capturedLoss) && hadLocal) + _queuedLoss = null; + } while (localDiagnostics.Count > 0) diagnostics.Enqueue(localDiagnostics.Dequeue()); return more; } @@ -608,7 +828,37 @@ internal sealed class SdkStandbyProjection(OtOpcUaNodeManager nodeManager, WarmS public int RefreshAllEventItems() => nodeManager.RefreshAllEventItems(); } -/// Captured per-notification proof. A stale pooled helper is treated as denied. +/// Owns a projected payload and keeps its proof through the SDK's server-side clone. +internal sealed class ProjectedSdkNotification : MonitoredItemNotification +{ + public ProjectedSdkNotification(MonitoredItemNotification rented, NotificationMessage marker) + { + ClientHandle = rented.ClientHandle; + Value = rented.Value; + DiagnosticInfo = rented.DiagnosticInfo; + Marker = marker; + + // The SDK resets its encoded fields on return. Clear its manual fields + // before returning this stock object for ordinary or built-in items. + rented.Message = null!; + rented.DiagnosticInfo = null!; + rented.Reuse(); + } + + internal NotificationMessage? Marker { get; private set; } + + protected override void ReuseCore() + { + // ACK, eviction and message disposal use this hook through IPooledEncodeable. + // This subclass stays out of the shared stock pool. + Marker = null; + Message = null!; + DiagnosticInfo = null!; + ResetForReuse(); + } +} + +/// Captured authority and value identity for a projected notification. internal sealed class ProjectedNotificationMarker : NotificationMessage { private readonly uint _clientHandle; @@ -618,13 +868,16 @@ internal sealed class ProjectedNotificationMarker : NotificationMessage { _clientHandle = clientHandle; _fingerprint = Fingerprint(value); _authorize = authorize; } public bool Permits(MonitoredItemNotification notification) { - if (notification.ClientHandle != _clientHandle || _fingerprint is null) return false; + if (notification.ClientHandle != _clientHandle || _fingerprint is null) { ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.MarkerHandleRejected); return false; } try { var current = Fingerprint(notification.Value); - return current is not null && System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(_fingerprint, current) && _authorize(); + if (current is null || !System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(_fingerprint, current)) { ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.MarkerFingerprintRejected); return false; } + var allowed = _authorize(); + ProjectedDeliveryDiagnostics.Count(allowed ? ProjectedDeliveryDiagnostics.Event.MarkerAccepted : ProjectedDeliveryDiagnostics.Event.MarkerAuthorizationRejected); + return allowed; } - catch { return false; } + catch { ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.MarkerException); return false; } } private static byte[]? Fingerprint(DataValue value) { @@ -652,6 +905,14 @@ internal sealed class ProjectedNotificationMarker : NotificationMessage } } +internal sealed class ProjectedLossMarker(uint clientHandle, ProjectedMonitoredItem.LossControl loss) : NotificationMessage +{ + internal bool IsObsolete => !loss.IsCurrent; + internal bool Permits(MonitoredItemNotification notification) => notification.ClientHandle == clientHandle && + notification.Value.WrappedValue.IsNull && notification.Value.StatusCode.Code == StatusCodes.BadNoCommunication && + notification.Value.SourceTimestamp == DateTimeUtc.MinValue && loss.IsAuthorized; +} + /// Rechecks captured projected notification authority for every delivery and retransmission. internal static class ProjectedNotificationRewriter { @@ -664,21 +925,48 @@ internal static class ProjectedNotificationRewriter if (!payload.TryGetValue(out var change) || change is null) { payloads.Add(payload); continue; } var items = new List(change.MonitoredItems.Count); + var originalDiagnostics = change.DiagnosticInfos.ToArray() ?? []; + var alignedDiagnostics = originalDiagnostics.Length == change.MonitoredItems.Count; + var keptDiagnostics = new List(originalDiagnostics.Length); var changedPayload = false; + var index = 0; foreach (var item in change.MonitoredItems) { - if (item.Message is ProjectedNotificationMarker marker && !marker.Permits(item)) + var diagnostic = alignedDiagnostics ? originalDiagnostics[index] : null; + index++; + var projected = item as ProjectedSdkNotification; + var marker = projected?.Marker; + if (marker is ProjectedLossMarker loss && loss.IsObsolete) + { + changedPayload = true; + continue; + } + if (marker is ProjectedLossMarker deniedLoss && !deniedLoss.Permits(item)) + { + if (deniedLoss.IsObsolete) { changedPayload = true; continue; } + items.Add(new MonitoredItemNotification { ClientHandle = item.ClientHandle, + Value = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied, DateTimeUtc.MinValue, item.Value.ServerTimestamp) }); + changedPayload = true; + if (alignedDiagnostics) keptDiagnostics.Add(diagnostic!); + continue; + } + if (marker is ProjectedLossMarker currentLoss && currentLoss.IsObsolete) + { changedPayload = true; continue; } + if (projected is not null && marker is not ProjectedLossMarker && + (marker is not ProjectedNotificationMarker proof || !proof.Permits(item))) { items.Add(new MonitoredItemNotification { ClientHandle = item.ClientHandle, Value = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied, DateTimeUtc.MinValue, item.Value.ServerTimestamp) }); changedPayload = true; } else items.Add(item); + if (alignedDiagnostics) keptDiagnostics.Add(diagnostic!); } if (changedPayload) { changed = true; - payloads.Add(new ExtensionObject(new DataChangeNotification { MonitoredItems = items, DiagnosticInfos = change.DiagnosticInfos })); + payloads.Add(new ExtensionObject(new DataChangeNotification { MonitoredItems = items, + DiagnosticInfos = alignedDiagnostics ? keptDiagnostics.ToArray() : change.DiagnosticInfos })); } else payloads.Add(payload); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ActorProjectedValuePublisher.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ActorProjectedValuePublisher.cs index db739be58..3f193be75 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ActorProjectedValuePublisher.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ActorProjectedValuePublisher.cs @@ -4,6 +4,16 @@ using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +internal interface IObsoleteProjectedSample { bool CanDropExpiredPredecessor { get; } } +internal static class ProjectedEvidenceRetirement +{ + internal static bool CanDrop(IProjectedSamplePublicationProof proof) + { + try { return !proof.IsValid && proof.IsSourceValid && proof is IObsoleteProjectedSample { CanDropExpiredPredecessor: true }; } + catch (Exception) { return false; } + } +} + /// Owns bounded imported-value messages through the actual SDK apply, with captured route ownership. public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDisposable { @@ -128,7 +138,14 @@ public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDi } } public TimeProvider Clock => source.Clock; - public void Invalidate() { try { source.Invalidate(); } finally { owner.RetireWitness(binding, identity); } } + public void Invalidate() + { + // An expired sample can remain queued across a compatible authority + // handoff. Discard that evidence without retiring the independently live + // logical source which may already own a fresh successor baseline. + if (ProjectedEvidenceRetirement.CanDrop(source) && IsSourceValid) return; + try { source.Invalidate(); } finally { owner.RetireWitness(binding, identity); } + } } private bool OwnsIdentity(Binding binding, object identity) { @@ -159,6 +176,7 @@ public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDi { foreach (var update in updates) { + if (ProjectedEvidenceRetirement.CanDrop(update.SourceProof) && IsCurrent(update.Route)) continue; try { update.SourceProof.Invalidate(); } catch (Exception) { } Retire(update.Route); } @@ -187,7 +205,7 @@ public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDi var update = captured[i]; update.OriginAgeBounds.Validate(); if (!ReferenceEquals(update.SourceProof.Clock, _clock) || !update.SourceProof.IsValid - || _clock.GetElapsedTime(update.ReceivedTimestamp) < TimeSpan.Zero || !Authorized(update.Route)) return Refused(); + || update.SourceVersion is <= 0 || _clock.GetElapsedTime(update.ReceivedTimestamp) < TimeSpan.Zero || !Authorized(update.Route)) return Refused(); charge = checked(charge + 512 + OwnedDataSample.Estimate(update.Snapshot.Value)); } var admitted = false; @@ -212,7 +230,7 @@ public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDi var writes = captured.Select((update, i) => new ProjectedValueWrite(update.Route.Realm, update.Route.LocalIdentifier, update.Route.ProjectionGeneration, update.Route.Serving, update.Snapshot with { Value = OwnedDataSample.CopyLegacy(update.Snapshot.Value) }, update.OriginAgeBounds, - update.ReceivedTimestamp, WitnessFor(bindings[i], update), update.IsCompleteSnapshot)).ToArray(); + update.ReceivedTimestamp, WitnessFor(bindings[i], update), update.IsCompleteSnapshot, update.SourceVersion)).ToArray(); batch = new(writes, captured.Select(update => update.Route).ToArray(), Complete, ForwardToMux); lock (_sync) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs index bcb219035..786232a8e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs @@ -8,6 +8,9 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; public sealed record DataConnectionDeploymentSnapshot(long ScopeVersion, string ArtifactRevision, IReadOnlyList Connections, RedundancyMode ConsumerMode = RedundancyMode.None); +/// Host-effective role eligibility and the continuity epoch observed under its role fence. +public sealed record DataConnectionConsumerRoleSnapshot(RedundancyMode Mode, bool Eligible, long Epoch); + /// Persists the node's current connection-to-secret allowlist before any route is made ready. public interface IDataConnectionScopeActivator { @@ -22,12 +25,17 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable 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) + private sealed class Entry(Spec spec, long generation, GrpcDataConnection connection, CancellationToken token, + RedundancyMode artifactMode, DataConnectionConsumerRoleSnapshot? role) { internal readonly Spec Spec = spec; internal readonly long Generation = generation; internal readonly GrpcDataConnection Connection = connection; internal readonly CancellationToken Token = token; + internal readonly object RouteIdentity = new(); + internal readonly RedundancyMode ArtifactMode = artifactMode; + internal readonly DataConnectionConsumerRoleSnapshot? Role = role; + internal volatile bool Live = true; internal bool Ready; internal int Leases; } @@ -39,6 +47,8 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable private readonly int _maximum; private readonly TimeProvider _clock; private readonly Func _consumerMayAcquire; + private readonly Func? _consumerRoleSnapshot; + private readonly bool _useCompactBatches; private readonly CancellationTokenSource _stop = new(); private readonly ITimer _retryTimer; private readonly Dictionary _entries = new(StringComparer.OrdinalIgnoreCase); @@ -53,13 +63,15 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable public DataConnectionDeploymentRuntime(string nodeId, string ownerCluster, IDataConnectionSecurityProvider security, IDataConnectionScopeActivator scopeActivator, int maxConnections, TimeProvider? clock = null, - Func? consumerMayAcquire = null) + Func? consumerMayAcquire = null, bool useCompactBatches = true, + Func? consumerRoleSnapshot = 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); + _clock = clock ?? TimeProvider.System; _consumerMayAcquire = consumerMayAcquire ?? (() => true); _useCompactBatches = useCompactBatches; + _consumerRoleSnapshot = consumerRoleSnapshot; _retryTimer = _clock.CreateTimer(static state => ((DataConnectionDeploymentRuntime)state!).OnRetry(), this, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); _manager = new DataConnectionManager(nodeId, maxConnections); @@ -190,6 +202,16 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable 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 DataConnectionConsumerRoleSnapshot? CaptureRole(RedundancyMode mode) + { try { return _consumerRoleSnapshot?.Invoke(mode); } catch (Exception) { return null; } } + private bool RouteCurrent(Entry entry) + { + if (!entry.Live || entry.Token.IsCancellationRequested) return false; + if (entry.Role is not { Eligible: true, Epoch: > 0 and < long.MaxValue } captured) + return true; + var current = CaptureRole(entry.ArtifactMode); + return current is { Eligible: true, Epoch: > 0 and < long.MaxValue } && current.Mode == captured.Mode && current.Epoch == captured.Epoch; + } private void ApplyManagerScopeLocked(Desired desired) { // The manager owns configured-node scope and physical lifetime only. Role checks @@ -207,6 +229,15 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable { if (_disposed || _desired is null) return; if (_attemptPending) return; + if (_consumerRoleSnapshot is not null && _entries.Count > 0) + { + var snapshots = _entries.Values.Select(entry => (Entry: entry, Current: CaptureRole(entry.ArtifactMode))).ToArray(); + if (snapshots.All(x => x.Entry.Role is { Mode: RedundancyMode.Hot, Eligible: true, Epoch: > 0 and < long.MaxValue }) && + snapshots.Any(x => x.Current is not { Epoch: > 0 })) return; + if (snapshots.All(x => x.Entry.Role is { Mode: RedundancyMode.Hot, Eligible: true, Epoch: > 0 and < long.MaxValue } captured && + x.Current is { Mode: RedundancyMode.Hot, Eligible: true, Epoch: > 0 and < long.MaxValue } current && captured.Epoch == current.Epoch)) + { WakeLocked(); return; } + } DisarmRetryLocked(); var generation = checked(++_generation); _desired = _desired with { Generation = generation }; @@ -312,6 +343,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable { Entry? existing; long securityGeneration; + DataConnectionConsumerRoleSnapshot? beforeRole; lock (_sync) { if (_disposed || _attemptPending || _desired?.Generation != desired.Generation) break; @@ -319,6 +351,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable _entries.TryGetValue(spec.Id, out existing); if (existing?.Ready == true) continue; securityGeneration = _securityGeneration; + beforeRole = CaptureRole(desired.ConsumerMode); } var available = false; try @@ -339,6 +372,12 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable 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; } + var role = CaptureRole(desired.ConsumerMode); + if (_consumerRoleSnapshot is not null && (role is null || !role.Eligible || role.Epoch <= 0 || role.Epoch == long.MaxValue)) + { retryNeeded = true; continue; } + if (_consumerRoleSnapshot is not null && (beforeRole is null || !beforeRole.Eligible || beforeRole.Epoch <= 0 || + beforeRole.Epoch == long.MaxValue || beforeRole.Mode != role!.Mode || beforeRole.Epoch != role.Epoch)) + { retryNeeded = true; continue; } DataConnectionScopeLease scope; try { scope = _manager.Acquire(spec.Id); } catch (UnauthorizedAccessException) { continue; } @@ -346,8 +385,8 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable { 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 }); + spec.Streams, spec.Monitored, maxPendingCommandBytes: spec.PendingBytes, enableCompactBatches: _useCompactBatches); + _entries.Add(spec.Id, new Entry(spec, desired.Generation, connection, scope.CancellationToken, desired.ConsumerMode, role) { Ready = true }); } catch (Exception) { scope.Dispose(); retryNeeded = true; } } @@ -364,6 +403,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable } private void Retire(Entry entry) { + entry.Live = false; var task = entry.Connection.DisposeAsync().AsTask(); lock (_sync) _retirements.Add(task); _ = ObserveRetirementAsync(task); @@ -379,14 +419,27 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable lock (_sync) { lease = null; - if (_disposed || !_scopeReady || !MayAcquire() || !_entries.TryGetValue(id, out var entry) || !entry.Ready || + if (!_disposed && _desired is { } desired && _entries.TryGetValue(id, out var stale) && + stale.Role is { Eligible: true, Epoch: > 0 and < long.MaxValue } captured && + CaptureRole(stale.ArtifactMode) is { Epoch: > 0 and < long.MaxValue } observed && + (observed.Mode != captured.Mode || !observed.Eligible || observed.Epoch != captured.Epoch)) + { + _entries.Remove(id); + var generation = checked(++_generation); + _desired = desired with { Generation = generation }; + _routeRevisions[id] = generation; + ApplyManagerScopeLocked(_desired); + Retire(stale); + if (!_attemptPending) WakeLocked(); + } + if (_disposed || !_scopeReady || !MayAcquire() || !_entries.TryGetValue(id, out var entry) || !entry.Ready || !RouteCurrent(entry) || 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 && + () => { lock (_sync) return !_disposed && _scopeReady && MayAcquire() && entry.Ready && RouteCurrent(entry) && _entries.TryGetValue(id, out var current) && ReferenceEquals(entry, current); }, - () => { lock (_sync) entry.Leases--; }); + () => { lock (_sync) entry.Leases--; }, () => RouteCurrent(entry), entry.RouteIdentity); return true; } } @@ -423,13 +476,18 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDisposable private readonly long _pendingBytes; private readonly Func _current; private readonly Action _release; + private readonly Func _routeCurrent; + internal object? RouteIdentity { get; } 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) + int batch, int page, int bytes, int streams, int monitored, long pendingBytes, Func current, Action release, Func? routeCurrent = null, object? routeIdentity = null) { _inner = inner; _scope = scope; _allowed = allowed; _timeout = timeout; _batch = batch; _page = page; _bytes = bytes; _streams = streams; _monitored = monitored; _pendingBytes = pendingBytes; _current = current; _release = release; + _routeCurrent = routeCurrent ?? (() => !scope.IsCancellationRequested); + RouteIdentity = routeIdentity; } + internal Func RouteCurrent => _routeCurrent; public IDataConnection Connection => this; public CancellationToken CancellationToken => _scope; public DataTarget Target => _inner.Target; @@ -495,14 +553,31 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDisposable { public ServingIdentity Serving { get; } = serving; } - private class ScopedSubscription(DataConnectionDeploymentLease owner, IDataSubscription inner) : IDataSubscription + private class ScopedSubscription(DataConnectionDeploymentLease owner, IDataSubscription inner) : IDataSubscription, IDataSubscriptionFreshnessSupport { + public bool SupportsFreshnessChallenges => inner is IDataSubscriptionFreshnessSupport { SupportsFreshnessChallenges: true }; + public int FreshnessMaxItems => inner is IDataSubscriptionFreshnessSupport support && support.SupportsFreshnessChallenges + ? Math.Min(support.FreshnessMaxItems, Math.Min(owner._batch, owner._monitored)) : 0; 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 }; + ModifySubscriptionItems m => m.Items.Count, RemoveSubscriptionItems r => r.Items.Count, + ChallengeSubscriptionFreshness c => c.Items.Count, _ => owner._monitored + 1 }; if (count > owner._monitored) throw new ArgumentOutOfRangeException(nameof(command)); + if (command is ChallengeSubscriptionFreshness challenge) + { + if (!SupportsFreshnessChallenges) throw new InvalidOperationException("Peer did not negotiate freshness challenges."); + if (count <= 0 || count > FreshnessMaxItems) throw new ArgumentOutOfRangeException(nameof(command)); + // Conservative preflight before any wire encoding, including UTF-8 expansion and per-handle overhead. + var bytes = 128L + 4L * (challenge.SubscriptionId?.Length ?? 0) + 4L * (challenge.CommandId?.Length ?? 0); + foreach (var handle in challenge.Items) + { + if (handle is null) throw new ArgumentException("Invalid challenge handle.", nameof(command)); + bytes = checked(bytes + 128L + 4L * (handle.SubscriptionId?.Length ?? 0)); + } + if (bytes > Math.Min(owner._bytes, owner._pendingBytes)) 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); } 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 df5f8412f..bd764b3fe 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs @@ -22,6 +22,8 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport private readonly Dictionary _items = new(); private readonly Dictionary _itemsByClient = new(StringComparer.Ordinal); private readonly LinkedList _interests = new(); + private readonly HashSet _temporaryInterests = []; + private readonly Dictionary _challengedHandles = new(); private LinkedListNode? _interestCursor; private readonly List _snapshots = []; private readonly List _snapshotAdmissions = []; @@ -36,12 +38,17 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport private SubscriptionItemHandleTable? _handles; private ITimer? _expiry, _tick, _ackTimer, _preOpen; private string? _subscriptionId; + private string? _freshnessChallengeId; private ServingIdentity? _serving; private long _epoch, _sequence, _dirtySequence, _ackId, _lastHeartbeat; + private long _lastFreshnessSequence; private int _mode, _closed, _closing, _tickQueued, _queuedValues, _barrier, _admissionCursor, _coalesced; private readonly Task _worker; internal Task Completion => _worker; internal Action? BeforeDirectCommitForTests { get; set; } + internal Action? SnapshotEndCommittedForTests { get; set; } + internal Action? BeforeDirtyTickForTests { get; set; } + internal Action? AfterTickForTests { get; set; } internal Action? OnCandidateQueuedForTests { get; set; } private sealed class SharedSessionLease(IDisposable lease) : IDisposable @@ -97,7 +104,7 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport internal bool SnapshotComplete; } private sealed class SnapshotJob(SnapshotLease snapshot, IDisposable admission, InterestGroup group, - IReadOnlyList items, IReadOnlyList watermarks) + IReadOnlyList items, IReadOnlyList watermarks, bool temporaryInterest = false) { internal readonly SnapshotLease Snapshot = snapshot; internal readonly IDisposable Admission = admission; @@ -105,6 +112,8 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport internal readonly IReadOnlyList Items = items; internal readonly IReadOnlyList Watermarks = watermarks; internal int Index; + internal bool Started; + internal readonly bool TemporaryInterest = temporaryInterest; } private sealed class StagedChange(Item previous, SubscriptionAuthorizedView view, DataSubscriptionSettings settings, IDisposable demand, SnapshotLease snapshot, SourceInterestLease interest, IDisposable admission, @@ -278,6 +287,7 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport AddSubscriptionItems add => add with { Items = CopyItems(add.Items) }, ModifySubscriptionItems modify => modify with { Items = CopyItems(modify.Items) }, RemoveSubscriptionItems remove => remove with { Items = CopyHandles(remove.Items) }, + ChallengeSubscriptionFreshness challenge => challenge with { Items = CopyHandles(challenge.Items) }, _ => throw new ArgumentException("Unknown subscription command.", nameof(command)) }; if (bytes > _limits.MaxPendingBytes) throw new ArgumentOutOfRangeException(nameof(command)); @@ -329,13 +339,15 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport else { if (_handles is null || command.SubscriptionId != _subscriptionId || command.StreamEpoch != _epoch) { Stop(); break; } - if (command is ModifySubscriptionItems && HasIncompleteSnapshot()) + if (command is ModifySubscriptionItems && HasIncompleteSnapshot() || + command is ChallengeSubscriptionFreshness && HasOutstandingSnapshots()) { _deferred.Enqueue(work); retained = true; Interlocked.CompareExchange(ref _barrier, 1, 0); continue; } switch (command) { case AddSubscriptionItems add: await AddAsync(add.Items, add.CommandId, work.Started, add.AcknowledgementTimeout).ConfigureAwait(false); break; case ModifySubscriptionItems modify: await ModifyAsync(modify, work.Started).ConfigureAwait(false); break; case RemoveSubscriptionItems remove: await RemoveAsync(remove).ConfigureAwait(false); break; + case ChallengeSubscriptionFreshness challenge: await ChallengeFreshnessAsync(challenge).ConfigureAwait(false); break; default: Stop(); break; } } @@ -358,6 +370,8 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport _itemsByClient.Clear(); foreach (var interest in _interests) interest.Lease.Dispose(); _interests.Clear(); + foreach (var interest in _temporaryInterests) interest.Lease.Dispose(); + _temporaryInterests.Clear(); foreach (var snapshot in _snapshots) snapshot.Dispose(); _snapshots.Clear(); foreach (var admission in _snapshotAdmissions) admission.Dispose(); @@ -375,6 +389,11 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport lock (_gate) return _interests.Any(group => !group.SnapshotComplete); } + private bool HasOutstandingSnapshots() + { + lock (_gate) return _snapshots.Count != 0; + } + private void ReleaseBarrier(int expected) { if (Interlocked.CompareExchange(ref _barrier, 0, expected) != expected) return; @@ -508,7 +527,6 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport await EnqueueAsync(ControlAck(commandId, acks, () => !snapshot!.IsReset && admission.Permit.IsValid && admitted.All(item => item.View.CanPublish()))).ConfigureAwait(false); var marks = snapshot!.Watermarks.Select(x => new PartitionWatermark(x.Key, x.Value)).ToArray(); - await EnqueueAsync(Control(DataStreamControlKind.SnapshotBegin, marks, snapshot, admission.Permit)).ConfigureAwait(false); foreach (var item in admitted) { if (item.Ticket is not { } ticket || !snapshot.Items.TryGetValue(ticket, out var captured)) continue; @@ -519,6 +537,54 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport await PumpSnapshotsAsync().ConfigureAwait(false); } + private async Task ChallengeFreshnessAsync(ChallengeSubscriptionFreshness challenge) + { + // Limit both capture work and retained memory through the same snapshot admission as Open/Add. + if (challenge.CommandId.Length > 32 || !challenge.CommandId.StartsWith("freshness-", StringComparison.Ordinal) || + !long.TryParse(challenge.CommandId.AsSpan("freshness-".Length), System.Globalization.NumberStyles.None, + System.Globalization.CultureInfo.InvariantCulture, out var sequence) || sequence <= _lastFreshnessSequence || + challenge.Items.Count == 0 || challenge.Items.Count > _services.SubscriptionLimits.MaxBatchItems || + challenge.Items.Distinct().Count() != challenge.Items.Count) { Stop(); return; } + var items = new List(challenge.Items.Count); + lock (_gate) + { + foreach (var handle in challenge.Items) + { + if (!_handles!.IsCurrent(handle) || !_items.TryGetValue(handle.Handle, out var item) || + item.Handle != handle || item.Ticket is null || !item.View.CanPublish()) { Stop(); return; } + items.Add(item); + } + } + var tickets = items.Select(x => x.Ticket!.Value).Distinct().ToArray(); + if (!_capacity.Snapshots.TryAcquire(_context.PrincipalId, 1, out var rawAdmission)) + { CloseWithReset("Freshness snapshot admission exhausted; retry later."); return; } + var permit = (SnapshotAdmissionScheduler.Permit)rawAdmission!; + if (!permit.TryRetain(out var hold)) { permit.Dispose(); Stop(); return; } + var admission = new SnapshotOwnership(permit, hold!); + var budget = new DataBudget(challenge.AcknowledgementTimeout, tickets.Length, _limits.MaxPendingBytes); + if (!_services.SubscriptionHub.TryCaptureInterestSnapshot(tickets, budget, _stop.Token, out var snapshot, out var interest, permit)) + { admission.Dispose(); Stop(); return; } + var group = new InterestGroup(interest!); + _lastFreshnessSequence = sequence; + lock (_gate) + { + _snapshots.Add(snapshot!); _snapshotAdmissions.Add(admission); _temporaryInterests.Add(group); + foreach (var item in items) + { + _challengedHandles.TryGetValue(item.Handle.Handle, out var count); + _challengedHandles[item.Handle.Handle] = checked(count + 1); + } + } + // Values created after this store compute their age after the causal challenge. + Volatile.Write(ref _freshnessChallengeId, challenge.CommandId); + var acks = items.Select(item => new DataSubscriptionItemAck(item.ClientItemId, DataItemStatus.Good, item.Handle, item.Settings, null)).ToArray(); + await EnqueueAsync(ControlAck(challenge.CommandId, acks, + () => !snapshot!.IsReset && permit.IsValid && items.All(item => item.View.CanPublish()))).ConfigureAwait(false); + var marks = snapshot!.Watermarks.Select(x => new PartitionWatermark(x.Key, x.Value)).ToArray(); + _snapshotJobs.AddLast(new SnapshotJob(snapshot, admission, group, items, marks, temporaryInterest: true)); + await PumpSnapshotsAsync().ConfigureAwait(false); + } + private async Task RemoveAsync(RemoveSubscriptionItems remove) { var acks = new List(); @@ -738,6 +804,8 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport private async Task TickAsync() { + try + { lock (_gate) { for (var count = 0; count < Math.Min(32, _snapshotAdmissions.Count); count++) @@ -749,8 +817,6 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport } for (var count = 0; count < 32 && _committedSnapshots.TryDequeue(out var committed); count++) { - await EnqueueAsync(Control(DataStreamControlKind.SnapshotBegin, committed.Watermarks, committed.Snapshot, - ((SnapshotOwnership)committed.Admission).Permit)).ConfigureAwait(false); _snapshotJobs.AddLast(committed); } if (_services.Clock.GetElapsedTime(_lastHeartbeat) >= TimeSpan.FromSeconds(5)) @@ -797,12 +863,13 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport } } await PumpSnapshotsAsync().ConfigureAwait(false); + BeforeDirtyTickForTests?.Invoke(_outbound.Reader.Count, Volatile.Read(ref _queuedValues), interests.Count); foreach (var interest in interests) { if (!interest.TryReadChanges(32, out var changes)) { CloseWithReset("Source change history expired."); return; } foreach (var change in changes) MarkDirty(change.Ticket.Key); } - var availableValues = Math.Max(0, Math.Max(1, _limits.MaxPendingFrames - 2) - Volatile.Read(ref _queuedValues)); + var availableValues = AvailableValueSlots(); if (availableValues > 0) foreach (var scheduled in _scheduler.TakeSlice(Math.Min(32, availableValues))) { @@ -814,7 +881,7 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport var dueItems = new List(); lock (_gate) { - availableValues = Math.Max(0, Math.Max(1, _limits.MaxPendingFrames - 2) - Volatile.Read(ref _queuedValues)); + availableValues = AvailableValueSlots(); for (var count = 0; count < Math.Min(32, availableValues) && _due.Count > 0 && _due.Min.Due <= now; count++) { var entry = _due.Min; _due.Remove(entry); @@ -823,6 +890,8 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport } } foreach (var item in dueItems) await ConsiderAsync(item).ConfigureAwait(false); + } + finally { AfterTickForTests?.Invoke(); } } private async Task RecoverWaitingAsync(Item item, SourceTicket ticket) @@ -848,7 +917,6 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport group.Node = _interests.AddLast(group); item.Interest = group; } var marks = snapshot!.Watermarks.Select(x => new PartitionWatermark(x.Key, x.Value)).ToArray(); - await EnqueueAsync(Control(DataStreamControlKind.SnapshotBegin, marks, snapshot, admission.Permit)).ConfigureAwait(false); var captured = snapshot.Items[ticket]; if (captured.Sample is not null) item.LastConsidered = captured.Sample.Version; _snapshotJobs.AddLast(new SnapshotJob(snapshot, admission!, group, [item], marks)); @@ -861,13 +929,21 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport var budget = Math.Min(32, _snapshotJobs.Count * 2); while (budget-- > 0 && _snapshotJobs.First is { } node && Volatile.Read(ref _closing) == 0) { - var job = node.Value; _snapshotJobs.RemoveFirst(); + var job = node.Value; if (job.Snapshot.IsReset || !((SnapshotOwnership)job.Admission).Permit.IsValid) { CloseWithReset("Snapshot catch-up expired; retry later."); return; } + if (!job.Started) + { + // Leave a control slot available for command acknowledgements. A dequeued + // frame queues another tick, so a blocked boundary remains resumable. + if (_outbound.Reader.Count >= Math.Max(1, _limits.MaxPendingFrames - 1)) return; + await EnqueueAsync(Control(DataStreamControlKind.SnapshotBegin, job.Watermarks, job.Snapshot, + ((SnapshotOwnership)job.Admission).Permit)).ConfigureAwait(false); + job.Started = true; + } if (job.Index < job.Items.Count) { - if (Volatile.Read(ref _queuedValues) >= Math.Max(1, _limits.MaxPendingFrames - 2)) - { _snapshotJobs.AddFirst(job); return; } + if (AvailableValueSlots() == 0) return; var item = job.Items[job.Index++]; if (_handles!.IsCurrent(item.Handle) && item.Ticket is { } ticket && job.Snapshot.Items.TryGetValue(ticket, out var captured) && captured.Sample is not null && @@ -877,34 +953,66 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport ((SnapshotOwnership)job.Admission).Permit); if (delivery is null) { - if (!_handles.IsCurrent(item.Handle)) { _snapshotJobs.AddLast(job); continue; } + if (!_handles.IsCurrent(item.Handle)) continue; CloseWithReset("Pending snapshot memory exhausted."); return; } await EnqueueAsync(delivery).ConfigureAwait(false); } - _snapshotJobs.AddLast(job); continue; } + if (_outbound.Reader.Count >= Math.Max(1, _limits.MaxPendingFrames - 1)) return; + _snapshotJobs.RemoveFirst(); await EnqueueAsync(Control(DataStreamControlKind.SnapshotEnd, job.Watermarks, job.Snapshot, ((SnapshotOwnership)job.Admission).Permit, () => { var allComplete = false; lock (_gate) { + SnapshotEndCommittedForTests?.Invoke(); job.Group.SnapshotComplete = true; + if (job.TemporaryInterest) _temporaryInterests.Remove(job.Group); _snapshots.Remove(job.Snapshot); _snapshotAdmissions.Remove(job.Admission); - allComplete = _interests.All(group => group.SnapshotComplete); + allComplete = _snapshots.Count == 0 && _interests.All(group => group.SnapshotComplete); } - job.Snapshot.Dispose(); job.Admission.Dispose(); QueueTick(); + job.Snapshot.Dispose(); job.Admission.Dispose(); + if (job.TemporaryInterest) FinishChallengeSnapshot(job); + QueueTick(); if (allComplete) ReleaseBarrier(1); - }, () => { job.Snapshot.Dispose(); job.Admission.Dispose(); })).ConfigureAwait(false); + }, () => + { + job.Snapshot.Dispose(); job.Admission.Dispose(); + if (job.TemporaryInterest) + { + FinishChallengeSnapshot(job); + } + })).ConfigureAwait(false); } } private void MarkDirty(BackingSourceKey source) => _scheduler.TryMarkDirty(source, Interlocked.Increment(ref _dirtySequence)); + private void FinishChallengeSnapshot(SnapshotJob job) + { + lock (_gate) + { + _temporaryInterests.Remove(job.Group); + foreach (var item in job.Items) + { + if (!_challengedHandles.TryGetValue(item.Handle.Handle, out var count)) continue; + if (count > 1) _challengedHandles[item.Handle.Handle] = count - 1; + else + { + _challengedHandles.Remove(item.Handle.Handle); + if (_handles?.IsCurrent(item.Handle) == true) MarkDirty(item.View.Source); + } + } + } + job.Group.Lease.Dispose(); + } + private async Task ConsiderAsync(Item item) { + lock (_gate) if (_challengedHandles.ContainsKey(item.Handle.Handle)) return; if (item.Ticket is not { } ticket) return; using var read = _services.SubscriptionHub.Read(ticket); if (read.Readiness != DataReadiness.Ready || read.Sample is null) { CloseWithReset("Source became unavailable."); return; } @@ -986,10 +1094,12 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport } return new PendingDelivery(sequence => { + // Capture the admitted challenge before computing the age; queued/prepared frames retain this witness. + var freshnessChallengeId = Volatile.Read(ref _freshnessChallengeId); var age = _services.Clock.GetElapsedTime(received); if (age < TimeSpan.Zero) throw new InvalidOperationException("Invalid monotonic age."); return new DataSubscriptionValues(_subscriptionId!, _epoch, sequence, snapshot, - [new(item.Handle, owned, new DataAgeBounds(age, null), DataReadiness.Ready)], lease); + [new(item.Handle, owned, new DataAgeBounds(age, null), DataReadiness.Ready, freshnessChallengeId)], lease); }, Gate, Commit, () => { owned.Dispose(); lease.Dispose(); }, true, () => Volatile.Read(ref _closing) != 0 || !_handles!.IsCurrent(item.Handle), Eligible, snapshot ? bytes => @@ -1034,6 +1144,15 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport _services.CanUseSubscription(_context, _target, _serving), () => { delivered?.Invoke(); return true; }, dropped, obsolete: () => Volatile.Read(ref _closing) != 0); } + // Snapshot controls and ACKs share the same bounded channel as values. Check + // both limits before removing scheduler work or advancing a snapshot item. + private int AvailableValueSlots() + { + var valueSlots = Math.Max(0, Math.Max(1, _limits.MaxPendingFrames - 2) - Volatile.Read(ref _queuedValues)); + var channelSlots = Math.Max(0, _limits.MaxPendingFrames - _outbound.Reader.Count); + return Math.Min(valueSlots, channelSlots); + } + private Task EnqueueAsync(PendingDelivery delivery) { if (Volatile.Read(ref _closed) != 0 || Volatile.Read(ref _closing) != 0) { delivery.Dispose(); return Task.CompletedTask; } 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 2abff3a48..b31a8958d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteExecutor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteExecutor.cs @@ -38,6 +38,8 @@ internal sealed class DataWriteExecutor(DataAuthenticatedContext context, Func> WriteAsync(WriteBatch request, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(request); + // The caller's budget covers validation and all batch preflight work. + var started = clock.GetTimestamp(); ArgumentNullException.ThrowIfNull(request.Items); request.Budget.Validate(); cancellationToken.ThrowIfCancellationRequested(); @@ -51,7 +53,6 @@ internal sealed class DataWriteExecutor(DataAuthenticatedContext context, Func request.Budget.MaxBytes) throw new ArgumentOutOfRangeException(nameof(request), "Write batch exceeds its byte limit."); - var started = clock.GetTimestamp(); var pending = request.Items.Select(item => ExecuteItem(item, request.Budget, started, cancellationToken)).ToArray(); return await Task.WhenAll(pending).ConfigureAwait(false); } @@ -94,12 +95,37 @@ internal sealed class DataWriteExecutor(DataAuthenticatedContext context, Func= TimeSpan.Zero && elapsed < allowance && now < expiration && + allowance - elapsed >= bounds.GatewayAsk; + } + catch (Exception ex) when (ex is ArgumentException or OverflowException) { return false; } + } WriteRouteTarget? target; - try { target = remaining >= bounds.GatewayAsk && route.TryResolve(node.Metadata.View, out var resolved) ? resolved : null; } + try { target = !cancellationToken.IsCancellationRequested && HasDispatchBudget(clock.GetTimestamp()) && + route.TryResolve(node.Metadata.View, out var resolved) ? resolved : null; } catch { target = null; } - if (target is null) + if (target is null || cancellationToken.IsCancellationRequested || !HasDispatchBudget(clock.GetTimestamp())) { var rejected = Rejected("Insufficient budget or no active driver route."); claim.Complete(rejected); @@ -116,7 +142,6 @@ internal sealed class DataWriteExecutor(DataAuthenticatedContext context, Func lease.Connection; public CancellationToken CancellationToken => lease.CancellationToken; + public object? RouteIdentity => lease.RouteIdentity; + public Func RouteCurrent => lease.RouteCurrent; public ValueTask DisposeAsync() => lease.DisposeAsync(); } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DriverHostSubscriptionDemandSource.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DriverHostSubscriptionDemandSource.cs index e0698032a..8b6fb4917 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DriverHostSubscriptionDemandSource.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DriverHostSubscriptionDemandSource.cs @@ -64,6 +64,19 @@ internal sealed class DriverHostSubscriptionDemandSource : ISubscriptionDemandSo // Counts actual reference keys visited to materialize physical desired sets. internal long ReferenceVisitCount => Interlocked.Read(ref _referenceVisits); + internal SubscriptionDemandAccounting CaptureAccounting() + { + int interests, drivers, desired, applied, retiring; + lock (_gate) + { + interests = _interests.Count; drivers = _drivers.Count; + desired = _drivers.Values.Sum(state => state.References.Count); + applied = _drivers.Values.Sum(state => Volatile.Read(ref state.Applied)?.References.Length ?? 0); + retiring = _drivers.Values.Count(state => state.Interests == 0); + } + var registry = _registry.CaptureAccounting(); + return new(interests, registry.Groups, registry.Interests, drivers, desired, applied, retiring); + } internal Task WaitForDriverIdleForTest(string driver) { lock (_gate) return _drivers.TryGetValue(driver, out var state) ? state.IdleForTest.Task : Task.CompletedTask; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/FederatedBrowseService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/FederatedBrowseService.cs index fcc7cef97..7906b5d7a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/FederatedBrowseService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/FederatedBrowseService.cs @@ -5,12 +5,28 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// Combines the remote metadata lease with local catalog and connection retirement fences. internal sealed class BoundProjectionLease(MetadataAuthorityLease remote, CancellationToken route, - IDataMappedCatalogAuthority local, ProjectedCatalogCache cache, string mapping, long generation, Func bindingCurrent) : IDataAuthorizationLease + IDataMappedCatalogAuthority local, ProjectedCatalogCache cache, string mapping, long generation, Func bindingCurrent, + Func? routeCurrent = null, object? routeIdentity = null, DataTarget? target = null, object? bindingIdentity = null) : IDataAuthorizationLease { public ServingIdentity Serving => remote.Serving; - public bool IsValid => !route.IsCancellationRequested && local.IsActive && remote.IsValid && bindingCurrent() && cache.IsCurrentGeneration(mapping, generation); + internal object? RouteIdentity => routeIdentity; + internal DataTarget? Target => target; + internal object? BindingIdentity => bindingIdentity; + internal TimeSpan Remaining => remote.Remaining; + internal TimeSpan UsableDuration => remote.UsableDuration; + private bool RouteAlive => !route.IsCancellationRequested && (routeCurrent?.Invoke() ?? true); + internal bool LiveContext => RouteAlive && local.IsActive && bindingCurrent() && cache.IsCurrentGeneration(mapping, generation); + internal bool ExpiredNaturally => remote.ExpiredNaturally && LiveContext; + public bool IsValid => LiveContext && remote.IsValid; + internal ProjectionLeaseDiagnostics CaptureDiagnostics() => new(RouteAlive, local.IsActive, + remote.IsValid, bindingCurrent(), cache.IsCurrentGeneration(mapping, generation)); } +// Read-only observations, not an authorization decision. The five fences can change +// between reads, and callers must continue to use IsValid for authority. +internal sealed record ProjectionLeaseDiagnostics(bool RouteAlive, bool LocalAuthorityActive, bool RemoteLeaseValid, + bool MappingBindingCurrent, bool CacheGenerationCurrent); + /// A page holds its physical connection lease until the caller commits or aborts it. internal sealed class PreparedPage : IProjectedPreparedPage { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.Diagnostics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.Diagnostics.cs index be0f371b8..794beae6c 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.Diagnostics.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.Diagnostics.cs @@ -13,6 +13,8 @@ public sealed partial class GrpcDataConnection private DateTime? _lastSampleAtUtc, _metadataLeaseExpiresAtUtc, _lastVerifiedAtUtc; private TimeSpan? _sampleAgeUpper; private long _sampleReceivedTimestamp; + private long _compactFrameCount, _fallbackFrameCount, _serializedValueFrameBytes; + private readonly string _accountingInstanceId = Guid.NewGuid().ToString("N"); private long _resetCount, _coalescedCount, _writeSucceededCount, _writeRejectedCount, _writeUnknownCount, _writeFailedCount, _writeUnconfirmedCount; internal DataConnectionDiagnosticsSnapshot CaptureDiagnostics(long revision, long scopeVersion, string artifactRevision) @@ -28,7 +30,9 @@ public sealed partial class GrpcDataConnection WriteUnknownCount: Interlocked.Read(ref _writeUnknownCount), ProtocolMajor: _diagnosticMajor, ProtocolMinor: _diagnosticMinor, LastVerifiedAtUtc: _lastVerifiedAtUtc, WriteFailedCount: Interlocked.Read(ref _writeFailedCount), WriteUnconfirmedCount: Interlocked.Read(ref _writeUnconfirmedCount), SampleAgeUpperBound: ObservedUpperAge(), - CoalescedCount: Interlocked.Read(ref _coalescedCount)); + CoalescedCount: Interlocked.Read(ref _coalescedCount), + CompactFrameCount: Interlocked.Read(ref _compactFrameCount), FallbackFrameCount: Interlocked.Read(ref _fallbackFrameCount), + SerializedValueFrameBytes: Interlocked.Read(ref _serializedValueFrameBytes), AccountingInstanceId: _accountingInstanceId); } private TimeSpan? ObservedUpperAge() diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs index f7270582f..2ffb7044f 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs @@ -34,6 +34,9 @@ public sealed partial class GrpcDataConnection : IDataConnection internal readonly CancellationTokenSource Retired = new(); } private sealed record Selected(ChannelEntry Channel, DataCapabilities Capabilities); + // Capability discovery is a protocol envelope, not an operation result page. + // Bound its advertised kinds by the locally understood finite enum. + private static readonly int MaxCapabilityKinds = Enum.GetValues().Length - 1; private readonly object _sync = new(); private readonly string _id; private readonly Uri[] _endpoints; @@ -42,6 +45,7 @@ public sealed partial class GrpcDataConnection : IDataConnection private readonly DataConnectionScopeLease _scope; private readonly int _maxMessageBytes, _maxChannels, _maxStreams, _maxMonitoredItems, _maxPendingCommands; private readonly TimeSpan _maxCommandTimeout; + private readonly bool _enableCompactBatches; private readonly SemaphoreSlim _unaryCapacity; private readonly CommandStateBudget _commandBudget; private readonly Dictionary _channels = new(); @@ -66,7 +70,8 @@ public sealed partial class GrpcDataConnection : IDataConnection 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) + int maxConcurrentUnaryCalls = 64, TimeSpan? maxCommandTimeout = null, long maxPendingCommandBytes = 4 * 1024 * 1024, + bool enableCompactBatches = true) { ArgumentException.ThrowIfNullOrWhiteSpace(connectionId); ArgumentNullException.ThrowIfNull(target); target.Validate(); @@ -80,6 +85,7 @@ public sealed partial class GrpcDataConnection : IDataConnection _maxCommandTimeout = maxCommandTimeout ?? TimeSpan.FromSeconds(30); if (_maxCommandTimeout <= TimeSpan.Zero || _maxCommandTimeout > TimeSpan.FromDays(1)) throw new ArgumentOutOfRangeException(nameof(maxCommandTimeout)); _maxStreams = maxStreams; _maxMonitoredItems = maxMonitoredItems; _maxPendingCommands = maxPendingCommands; + _enableCompactBatches = enableCompactBatches; _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))) @@ -227,9 +233,11 @@ public sealed partial class GrpcDataConnection : IDataConnection { var channel = await ChannelAsync(endpoint, ct).ConfigureAwait(false); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _scope.CancellationToken, channel.Retired.Token, _shutdown.Token); - var response = await channel.Client.GetCapabilitiesAsync(new W.CapabilitiesRequest { ProtocolMajor = 1, ProtocolMinor = 3 }, + var response = await channel.Client.GetCapabilitiesAsync(new W.CapabilitiesRequest { ProtocolMajor = 1, ProtocolMinor = 5 }, Options(channel, start, budget, linked.Token)).ResponseAsync.ConfigureAwait(false); - var caps = DataProtoMapper.DecodeCapabilities(response, new DataDecodeLimits(budget.MaxItems, _maxMessageBytes)); + if (response.ValueKinds.Count > MaxCapabilityKinds || response.ValueKinds.Distinct().Count() != response.ValueKinds.Count) + throw new ArgumentException("Invalid capability value kinds."); + var caps = DataProtoMapper.DecodeCapabilities(response, new DataDecodeLimits(MaxCapabilityKinds, _maxMessageBytes)); if (!caps.ResponseServingIdentity || (write && (caps.ProtocolMinor < 3 || !caps.WriteServingGenerationEnforced)) || caps.Serving.ServingGeneration <= 0 || !ClusterEndpointSelector.IsEligible(Target, caps, write) || Target.Mode == DataTargetMode.Cluster && !_eligibleNodeIds!.Contains(caps.Serving.NodeId)) throw new InvalidOperationException("Endpoint is not an authenticated ready target."); @@ -299,18 +307,31 @@ public sealed partial class GrpcDataConnection : IDataConnection var serving = DataProtoMapper.DecodeServing(wire.Serving); return result with { Serving = serving, Items = result.Items.Select(x => ExposeMetadata(x, serving, selected.Capabilities)).ToArray() }; }, cancellationToken); - public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => - QueryAsync(request.Budget, async (selected, budget, options) => + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) + { + // Covers endpoint selection, dispatch, transport and decoding, never a peer-supplied clock. + var started = Clock.GetTimestamp(); + return 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 || x.Value.CatalogRevision != selected.Capabilities.Serving.CatalogEpoch)).Any()) + x.Value is not null && (x.Value.View.Address != request.Views[i].Address || x.Value.CatalogRevision != selected.Capabilities.Serving.CatalogEpoch) || + selected.Capabilities.MetadataItemLeases && x.Lease is { } lease && + (lease.CatalogEpoch != selected.Capabilities.Serving.CatalogEpoch || lease.AuthorityEpoch != selected.Capabilities.Serving.AuthorityEpoch || + lease.Duration > selected.Capabilities.Limits.MaxMetadataLease)).Any()) throw new InvalidOperationException("Metadata response has unexpected items."); Verify(wire.Serving, selected); var serving = DataProtoMapper.DecodeServing(wire.Serving); - return (IReadOnlyList>)result.Select(x => x.Value is null ? x : x with { Value = ExposeMetadata(x.Value, serving, selected.Capabilities) }).ToArray(); + return (IReadOnlyList>)result.Select((x, i) => x with + { + Value = x.Value is null ? null : ExposeMetadata(x.Value, serving, selected.Capabilities), + Lease = selected.Capabilities.MetadataItemLeases && x.Value?.View == request.Views[i] ? x.Lease : null, + LeaseRequestStartedTimestamp = selected.Capabilities.MetadataItemLeases && x.Value?.View == request.Views[i] && x.Lease is not null + ? started : null, + }).ToArray(); }, cancellationToken); + } public Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) { var start = Clock.GetTimestamp(); @@ -318,7 +339,8 @@ public sealed partial class GrpcDataConnection : IDataConnection { 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)); + var observedAt = Clock.GetTimestamp(); + var result = DataProtoMapper.DecodeReadResponse(wire, Limits(budget, selected.Capabilities), Clock.GetElapsedTime(start, observedAt)); try { if (result.Count != request.Items.Count || !result.Select(x => x.CorrelationId).SequenceEqual(request.Items.Select(x => x.CorrelationId)) || @@ -326,7 +348,8 @@ public sealed partial class GrpcDataConnection : IDataConnection throw new InvalidOperationException("Read response has unexpected items or serving identity."); Verify(wire.Serving, selected); if (result.LastOrDefault(x => x.Sample is not null) is { } observed) RecordSampleAge(observed.AgeBounds); - return result; + // The decoded results transfer their owned leases to these stamped copies. + return (IReadOnlyList)result.Select(item => item with { FreshnessObservedTimestamp = observedAt }).ToArray(); } catch { foreach (var item in result) item.Dispose(); throw; } }, cancellationToken); @@ -366,14 +389,22 @@ public sealed partial class GrpcDataConnection : IDataConnection if (!ProbeAllowed()) return results; var eligible = Enumerable.Range(0, request.Items.Count).ToArray(); var attempted = false; + var readReadyButWriteIneligible = 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(); } + try { selected = await SelectAsync(endpoint, start, request.Budget, false, cancellationToken).ConfigureAwait(false); ProbeSucceeded(); } catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException or TimeoutException) { continue; } + if (!SupportsWrites(selected.Capabilities) || !ClusterEndpointSelector.IsEligible(Target, selected.Capabilities, true)) + { + // A read-ready endpoint can be intentionally ineligible for writes. Do not + // turn that policy decision into discovery backoff for subsequent reads. + readReadyButWriteIneligible = true; + continue; + } using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, selected.Channel.Retired.Token, _shutdown.Token); // Caller-bound generations are strict: never replace any supplied precondition or rebind. var strictMismatch = eligible.Where(i => request.Items[i].ExpectedServingGeneration is { } generation && @@ -467,7 +498,7 @@ public sealed partial class GrpcDataConnection : IDataConnection eligible = dispatchStarted ? deferred.ToArray() : deferred.Concat(eligible).ToArray(); } } - if (!attempted && eligible.Length > 0) ProbeFailed(); + if (!attempted && eligible.Length > 0 && !readReadyButWriteIneligible) ProbeFailed(); return results; } private static void VerifyWriteEnvelope(W.Serving? serving, Selected selected, IReadOnlyList results) @@ -512,8 +543,11 @@ public sealed partial class GrpcDataConnection : IDataConnection var transferred = false; try { - var call = selected.Channel.Client.Subscribe(Headers(selected.Channel), cancellationToken: lifetime.Token); - subscription = new RemoteSubscription(this, call, selected, lifetime, _maxMessageBytes, + var compact = _enableCompactBatches && DataProtoMapper.NegotiateCompact(selected.Capabilities); + var headers = Headers(selected.Channel); + if (compact) headers.Add(DataConnectionProtoContract.CompactCodecHeader, DataConnectionProtoContract.CompactCodecVersion.ToString(System.Globalization.CultureInfo.InvariantCulture)); + var call = selected.Channel.Client.Subscribe(headers, cancellationToken: lifetime.Token); + subscription = new RemoteSubscription(this, call, selected, lifetime, compact, _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); @@ -556,11 +590,16 @@ public sealed partial class GrpcDataConnection : IDataConnection private sealed class RemoteSubscription(GrpcDataConnection owner, AsyncDuplexStreamingCall call, Selected selected, - CancellationTokenSource lifetime, int maxBytes, int maxItems, int maxPendingCommands, + CancellationTokenSource lifetime, bool compactNegotiated, int maxBytes, int maxItems, int maxPendingCommands, TimeSpan maxCommandTimeout, CommandStateBudget commandBudget, Func claimEpoch, Action? observePending, - Func? afterTimerCancelled, Action release) : IDataSubscription, IDataSubscriptionProvenance + Func? afterTimerCancelled, Action release) : IDataSubscription, IDataSubscriptionProvenance, IDataSubscriptionFreshnessSupport { public ServingIdentity Serving { get; } = selected.Capabilities.Serving; + public bool SupportsFreshnessChallenges => selected.Capabilities.SubscriptionFreshnessChallenges && selected.Capabilities.SubscriptionAgeReadiness; + public int FreshnessMaxItems => selected.Capabilities.Limits.MaxBatchItems; + private readonly Dictionary _freshnessStarts = new(StringComparer.Ordinal); + private readonly Queue _freshnessOrder = new(); + private long _lastFreshnessSequence; private readonly SemaphoreSlim _send = new(1, 1); private readonly Task _headersReceipt = call.ResponseHeadersAsync; private Dictionary _handles = new(); @@ -568,7 +607,7 @@ public sealed partial class GrpcDataConnection : IDataConnection 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); + bool IsModify, bool IsChallenge, TimeSpan Timeout, long Bytes, CancellationTokenSource Timer); private readonly Dictionary _pending = new(StringComparer.Ordinal); private long _pendingBytes, _usedCommandBytes; private readonly HashSet _usedCommands = new(StringComparer.Ordinal); @@ -630,8 +669,9 @@ public sealed partial class GrpcDataConnection : IDataConnection 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 }; + ModifySubscriptionItems m => m.Items.Count, RemoveSubscriptionItems r => r.Items.Count, ChallengeSubscriptionFreshness c => c.Items.Count, _ => maxItems + 1 }; if (count > maxItems) throw new InvalidOperationException("Command item capacity exceeded."); + if (command is ChallengeSubscriptionFreshness && !SupportsFreshnessChallenges) throw new InvalidOperationException("Peer did not negotiate freshness challenges."); var encoded = DataProtoMapper.EncodeCommand(command); if (encoded.CalculateSize() > Math.Min(maxBytes, selected.Capabilities.Limits.MaxMessageBytes)) throw new InvalidOperationException("Command byte capacity exceeded."); @@ -642,23 +682,41 @@ public sealed partial class GrpcDataConnection : IDataConnection ModifySubscriptionItems => encoded.Modify.Items.Select(x => x.ClientItemId).ToArray(), _ => null }; - var removed = command is RemoveSubscriptionItems ? encoded.Remove.Items.Select(DataProtoMapper.DecodeHandle).ToArray() : null; + var removed = command switch { RemoveSubscriptionItems => encoded.Remove.Items.Select(DataProtoMapper.DecodeHandle).ToArray(), + ChallengeSubscriptionFreshness => encoded.FreshnessChallenge.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)); + command is ChallengeSubscriptionFreshness, 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) || + long sequence = 0; + if (pending.IsChallenge && (pending.Id.Length > 32 || !pending.Id.StartsWith("freshness-", StringComparison.Ordinal) || + !long.TryParse(pending.Id.AsSpan("freshness-".Length), System.Globalization.NumberStyles.None, + System.Globalization.CultureInfo.InvariantCulture, out sequence) || sequence <= _lastFreshnessSequence)) + { pending.Timer.Dispose(); throw new InvalidOperationException("Freshness challenge sequence is invalid."); } + if (!pending.IsChallenge && pending.Id.StartsWith("freshness-", StringComparison.Ordinal)) + { pending.Timer.Dispose(); throw new InvalidOperationException("Reserved command identifier."); } + long usedCharge = pending.IsChallenge ? 0 : checked(64L + 2L * pending.Id.Length); + if (_pending.Count >= maxPendingCommands || (!pending.IsChallenge && (_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); + if (pending.IsChallenge) _lastFreshnessSequence = sequence; + else _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); + if (pending.IsChallenge) + { + lock (_pending) + { + _freshnessStarts.Add(pending.Id, owner.Clock.GetTimestamp()); _freshnessOrder.Enqueue(pending.Id); + while (_freshnessOrder.Count > 16) _freshnessStarts.Remove(_freshnessOrder.Dequeue()); + } + } try { await call.RequestStream.WriteAsync(encoded, linked.Token).ConfigureAwait(false); } catch { await lifetime.CancelAsync().ConfigureAwait(false); throw; } } @@ -699,6 +757,8 @@ public sealed partial class GrpcDataConnection : IDataConnection 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.CompactValues is not null && !compactNegotiated) + throw new InvalidOperationException("Unnegotiated compact subscription 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, @@ -730,10 +790,19 @@ public sealed partial class GrpcDataConnection : IDataConnection 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); + if (removedItems[i] != handle) throw new InvalidOperationException("Unexpected acknowledged handle."); + if (pending.IsChallenge) + { + if (!next.TryGetValue(handle.Handle, out var currentHandle) || currentHandle != handle || + !nextClients.TryGetValue(item.ClientItemId, out var currentClient) || currentClient != handle.Handle) + throw new InvalidOperationException("Unexpected challenged handle."); + } + else + { + if (!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 { @@ -776,11 +845,40 @@ public sealed partial class GrpcDataConnection : IDataConnection nextVersions[item.Handle.Handle] = item.Sample.Version; } Verify(wire.Serving, selected); linked.Token.ThrowIfCancellationRequested(); _versions = nextVersions; + if (SupportsFreshnessChallenges) + { + var bounded = new List(values.Items.Count); + try + { + foreach (var item in values.Items) + { + long start; + lock (_pending) start = item.FreshnessChallengeId is { } nonce && _freshnessStarts.TryGetValue(nonce, out var known) ? known : -1; + var bounds = item.AgeBounds; + long? observed = null; + if (start >= 0 && bounds.Lower is { } lower) + { + observed = owner.Clock.GetTimestamp(); + bounds = new(bounds.Lower, lower + owner.Clock.GetElapsedTime(start, observed.Value)); + } + bounded.Add(item with { Sample = item.Sample with { Value = item.Sample.Value.Retain() }, AgeBounds = bounds, + FreshnessObservedTimestamp = observed }); + } + frame = new DataSubscriptionValues(values.SubscriptionId, values.StreamEpoch, values.Sequence, values.IsSnapshot, bounded, values); + } + catch { foreach (var item in bounded) item.Sample.Dispose(); throw; } + } } _sequence = wire.Sequence; } catch { if (frame is IDisposable owned) owned.Dispose(); throw; } - if (frame is DataSubscriptionValues { Items.Count: > 0 } observedValues) owner.RecordSampleAge(observedValues.Items[^1].AgeBounds); + if (frame is DataSubscriptionValues observedValues) + { + if (wire.CompactValues is not null) Interlocked.Increment(ref owner._compactFrameCount); + else Interlocked.Increment(ref owner._fallbackFrameCount); + Interlocked.Add(ref owner._serializedValueFrameBytes, wire.CalculateSize()); + if (observedValues.Items.Count > 0) owner.RecordSampleAge(observedValues.Items[^1].AgeBounds); + } if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Reset }) Interlocked.Increment(ref owner._resetCount); if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Coalesced }) Interlocked.Increment(ref owner._coalescedCount); yield return frame; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataDriverAdapter.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataDriverAdapter.cs index a18407679..7107aea54 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataDriverAdapter.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataDriverAdapter.cs @@ -9,6 +9,13 @@ public interface IGrpcDataAdapterConnectionLease : IAsyncDisposable { IDataConnection Connection { get; } CancellationToken CancellationToken { get; } + /// Opaque stable identity for one route and credential lifetime; null disables overlap. + object? RouteIdentity => null; + /// A detached route guard that remains meaningful after this borrower is released. + Func RouteCurrent + { + get { var token = CancellationToken; return () => !token.IsCancellationRequested; } + } } public interface IGrpcDataAdapterConnectionSource @@ -31,7 +38,7 @@ public sealed record ProjectedValueRoute(string DriverInstanceId, string Depende public sealed record ProjectedValueUpdate(ProjectedValueRoute Route, DataValueSnapshot Snapshot, DataAgeBounds OriginAgeBounds, long ReceivedTimestamp, IProjectedSamplePublicationProof SourceProof, bool IsCompleteSnapshot = false, - TimeSpan? MaximumSampleAge = null); + TimeSpan? MaximumSampleAge = null, long? SourceVersion = null); public interface IProjectedValuePublisher { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataWorkloadAccounting.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataWorkloadAccounting.cs new file mode 100644 index 000000000..fa569a299 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataWorkloadAccounting.cs @@ -0,0 +1,16 @@ +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Actual logical demand and acknowledged physical driver references, without identity labels. +/// Physical references count unique references within each driver; logical interests include Raw/UNS and principal boundaries. +public sealed record SubscriptionDemandAccounting(int LogicalInterests, int SharingGroups, int RegistryInterests, + int TrackedDrivers, int DesiredPhysicalReferences, int AppliedPhysicalReferences, int RetiringDrivers); + +/// Actual source-cache resource charges and in-flight snapshot/interest item counts. +/// Counts are individually synchronized observations, not an atomic transaction across partitions. +public sealed record SampleHubAccounting(int TrackedSources, int SnapshotItems, int InterestItems, + long RetainedBytes, long MaximumRetainedBytes, int PartitionCount); + +/// Bounded origin accounting sampled from the owners of physical demand and cache resources. +/// Components are captured sequentially and may advance between observations. ReservedDrivers includes late physical cleanup. +public sealed record GrpcDataWorkloadAccounting(DateTimeOffset CapturedAtUtc, SubscriptionDemandAccounting Demand, + SampleHubAccounting Hub, int ReservedDrivers, int MaximumReservedDrivers); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/IDataConnectionBundleCommitObserver.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/IDataConnectionBundleCommitObserver.cs new file mode 100644 index 000000000..285a6e547 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/IDataConnectionBundleCommitObserver.cs @@ -0,0 +1,11 @@ +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Numeric committed bundle observations, without credential or trust material. +public sealed record DataConnectionBundleCommitObservation(long? CredentialScopeVersion, long? CredentialVersion, bool? CredentialDeleted, + long? TrustScopeVersion, long? TrustVersion, bool? TrustRetired); + +/// Observes committed node-local credential and trust versions for a connection. +public interface IDataConnectionBundleCommitObserver +{ + Task ObserveAsync(string connectionId, 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 index de0ef2677..4276f279d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs @@ -13,6 +13,7 @@ public sealed record LocalDataRuntimeLimits(int MaxDrivers, int MaxInterests, in public sealed class LocalDataRuntimeComposition : IDisposable { private readonly DriverHostSubscriptionDemandSource _demand; + private readonly PartitionedSampleHub _hub; private int _disposed; public LocalDataRuntimeComposition(LocalCatalogCoordinator catalog, PartitionedSampleHub hub, DataOperationPolicy policy, DataCapabilitiesProvider capabilities, TimeProvider clock, DataWriteRuntime writes, @@ -23,6 +24,7 @@ public sealed class LocalDataRuntimeComposition : IDisposable ArgumentNullException.ThrowIfNull(clock); ArgumentNullException.ThrowIfNull(writes); ArgumentNullException.ThrowIfNull(host); ArgumentNullException.ThrowIfNull(acquisitionCapacity); ArgumentNullException.ThrowIfNull(limits); + _hub = hub; 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(); @@ -33,10 +35,15 @@ public sealed class LocalDataRuntimeComposition : IDisposable 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)); + targetSubscriptions: (context, target) => new LocalSubscriptionService(services!, context, target, _demand, sessionLimits, capacity), + subscriptionFreshnessChallenges: true); Services = services; } public LocalDataServices Services { get; } public SubscriptionAcquisitionCapacity AcquisitionCapacity { get; } + /// Samples actual demand and cache owners; component reads are not cross-component atomic. + public GrpcDataWorkloadAccounting CaptureWorkloadAccounting() => new(_hub.Clock.GetUtcNow(), + _demand.CaptureAccounting(), _hub.CaptureAccounting(), AcquisitionCapacity.ReservedDriverCount, + AcquisitionCapacity.MaxReservations); 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 b045d32b5..806e999a5 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs @@ -18,6 +18,7 @@ public sealed class LocalDataServices : IDataConnectionFactory private readonly Func? _writes; private readonly Func? _subscriptions; private readonly Func? _targetSubscriptions; + private readonly bool _subscriptionFreshnessChallenges; private readonly byte[] _continuationKey = RandomNumberGenerator.GetBytes(32); private readonly ConditionalWeakTable _callers = new(); private sealed record Continuation(DataView Parent, string? Filter, int Offset, string Principal, @@ -27,7 +28,8 @@ public sealed class LocalDataServices : IDataConnectionFactory DataOperationPolicy policy, DataCapabilitiesProvider capabilities, TimeProvider clock, Func? writes = null, Func? subscriptions = null, - Func? targetSubscriptions = null) + Func? targetSubscriptions = null, + bool subscriptionFreshnessChallenges = false) { _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); _hub = hub ?? throw new ArgumentNullException(nameof(hub)); @@ -38,6 +40,7 @@ public sealed class LocalDataServices : IDataConnectionFactory _writes = writes; _subscriptions = subscriptions; _targetSubscriptions = targetSubscriptions; + _subscriptionFreshnessChallenges = subscriptionFreshnessChallenges; } public TimeProvider Clock { get; } @@ -214,7 +217,9 @@ public sealed class LocalDataServices : IDataConnectionFactory catalog is null ? _capabilities.Limits : Limits(catalog, context)); if (catalog is null || !Ready(catalog) || context.AuthorityEpoch != catalog.AuthorityEpoch || !RoleAllows(target, catalog.Serving)) capabilities = capabilities with { Readiness = DataReadiness.Unavailable, Operations = DataOperations.None }; - return Task.FromResult(capabilities with { WriteServingGenerationEnforced = true, ProtocolMinor = Math.Max(3, capabilities.ProtocolMinor) }); + return Task.FromResult(capabilities with { WriteServingGenerationEnforced = true, SubscriptionAgeReadiness = true, + ResponseServingIdentity = true, SubscriptionFreshnessChallenges = _subscriptionFreshnessChallenges, + MetadataItemLeases = true, ProtocolMinor = Math.Max(5, capabilities.ProtocolMinor) }); } internal Task>> GetMetadataAsync(DataAuthenticatedContext context, DataTarget target, MetadataRequest request, CancellationToken cancellationToken) @@ -236,6 +241,7 @@ public sealed class LocalDataServices : IDataConnectionFactory : !catalog.TryResolveAddress(view, out _) ? catalog.ContainsAddress(view) ? DataItemStatus.Denied : DataItemStatus.NotFound : DataItemStatus.Good; DataMetadata? metadata = null; + MetadataLease? itemLease = null; if (status == DataItemStatus.Good && catalog.TryResolveAddress(view, out var node)) { if (!Allowed(catalog, context, node, DataOperations.Metadata)) status = DataItemStatus.Denied; @@ -243,16 +249,32 @@ public sealed class LocalDataServices : IDataConnectionFactory else { metadata = Metadata(catalog, context, target, node); - bytes = checked(bytes + MetadataBytes(metadata)); + bytes = checked(bytes + MetadataBytes(metadata) + 64); if (bytes > Math.Min(request.Budget.MaxBytes, _capabilities.Limits.MaxMessageBytes)) { status = DataItemStatus.LimitExceeded; metadata = null; } + else if (context.AuthorityEpoch == catalog.AuthorityEpoch && RoleAllows(target, catalog.Serving) && + ReferenceEquals(_catalog(), catalog) && Allowed(catalog, context, node, DataOperations.Metadata)) + { + var duration = Limits(catalog, context).MaxMetadataLease; + if (context.CredentialExpiresUtc is { } expiry) + { + var remaining = expiry - Clock.GetUtcNow(); + if (remaining < duration) duration = remaining; + } + if (duration > TimeSpan.Zero && Ready(catalog) && ReferenceEquals(_catalog(), catalog) && + context.AuthorityEpoch == catalog.AuthorityEpoch && _policy.IsCallerUsable(Caller(context))) + itemLease = new MetadataLease(catalog.Serving.CatalogEpoch, catalog.Serving.AuthorityEpoch, duration); + } } } - results.Add(new(i.ToString(System.Globalization.CultureInfo.InvariantCulture), status, metadata, null)); + results.Add(new(i.ToString(System.Globalization.CultureInfo.InvariantCulture), status, metadata, null, + itemLease, itemLease is null ? null : start)); } - if (!Ready(catalog) || !_policy.IsCallerUsable(Caller(context))) + if (!Ready(catalog) || !ReferenceEquals(_catalog(), catalog) || context.AuthorityEpoch != catalog.AuthorityEpoch || + !RoleAllows(target, catalog.Serving) || !_policy.IsCallerUsable(Caller(context))) return Task.FromResult>>(results.Select(x => x with - { Status = !Ready(catalog) ? DataItemStatus.Unavailable : DataItemStatus.Denied, Value = null }).ToArray()); + { Status = !Ready(catalog) || !RoleAllows(target, catalog.Serving) ? DataItemStatus.Unavailable : DataItemStatus.Denied, + Value = null, Lease = null, LeaseRequestStartedTimestamp = null }).ToArray()); return Task.FromResult>>(results); } @@ -295,7 +317,8 @@ public sealed class LocalDataServices : IDataConnectionFactory bytes = checked(bytes + sample.Value.EstimatedRetainedBytes + 256); if (bytes > Math.Min(request.Budget.MaxBytes, _capabilities.Limits.MaxMessageBytes)) { read.Dispose(); results.Add(Empty(DataItemStatus.LimitExceeded)); continue; } - var age = Clock.GetElapsedTime(read.ReceivedTimestamp); + var observedAt = Clock.GetTimestamp(); + var age = Clock.GetElapsedTime(read.ReceivedTimestamp, observedAt); if (age < TimeSpan.Zero) { read.Dispose(); results.Add(Empty(DataItemStatus.Unavailable)); continue; } // Catalog/authority headers describe current serving. Cache ingress age, value version // and original timestamps remain unchanged, including provisional boot acquisitions. @@ -307,7 +330,7 @@ public sealed class LocalDataServices : IDataConnectionFactory 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))); + DataReadiness.Ready, age, exposed, null, publication, new DataAgeBounds(age, age), observedAt)); } if (!Ready(catalog) || !_policy.IsCallerUsable(Caller(context))) for (var i = 0; i < results.Count; i++) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/MetadataAuthorityLease.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/MetadataAuthorityLease.cs index 82aa89f42..ff91f8678 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/MetadataAuthorityLease.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/MetadataAuthorityLease.cs @@ -37,6 +37,18 @@ public sealed class MetadataAuthorityLease : IDataAuthorizationLease public long CatalogEpoch { get; } public long AuthorityEpoch { get; } public ServingIdentity Serving { get; } + internal TimeSpan Remaining + { + get + { + if (Volatile.Read(ref _invalidated) != 0) return TimeSpan.Zero; + var elapsed = _clock.GetElapsedTime(_requestStart, _clock.GetTimestamp()); + return elapsed < TimeSpan.Zero || elapsed >= _usableDuration ? TimeSpan.Zero : _usableDuration - elapsed; + } + } + internal TimeSpan UsableDuration => _usableDuration; + internal bool ExpiredNaturally => Volatile.Read(ref _invalidated) == 0 && + _clock.GetElapsedTime(_requestStart, _clock.GetTimestamp()) >= _usableDuration; public bool IsValid { get diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs index c0e80d4d3..8318b3564 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs @@ -153,6 +153,8 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable private int _interestItems; private long _snapshotValidationWork; internal Action? BeforeReadForTests { get; set; } + internal Action? BeforePendingValueCurrentForTests { get; set; } + internal Action? AfterValueSequenceForTests { get; set; } internal Action? BeforeSnapshotValidationForTests { get; set; } internal long SnapshotValidationWorkForTests => Interlocked.Read(ref _snapshotValidationWork); internal void CountSnapshotValidationForTests() => Interlocked.Increment(ref _snapshotValidationWork); @@ -168,6 +170,10 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable } public TimeProvider Clock { get; } public DataResourceBudget Resources { get; } + /// Captures actual bounded resource counters without enumerating source identities. + public SampleHubAccounting CaptureAccounting() => new(Volatile.Read(ref _trackedSources), + Volatile.Read(ref _snapshotItems), Volatile.Read(ref _interestItems), Resources.RetainedBytes, + Resources.MaximumBytes, Volatile.Read(ref _partitions).Length); internal DataResourceLimits Limits => _limits; internal long RoutingEpoch => Interlocked.Read(ref _routingEpoch); internal bool IsDisposed => Volatile.Read(ref _disposed) != 0; @@ -223,7 +229,8 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable return IsDisposed || !ValidKey(ticket.Key) ? EmptyRead(DataItemStatus.Unavailable, DataReadiness.Unavailable, 0) : Partition(ticket.Key).Read(ticket); } internal CachedSourceRead EmptyRead(DataItemStatus status, DataReadiness readiness, long epoch) => new(Resources, status, readiness, null, 0, epoch, 0, 0); - internal void ProcessPending() { foreach (var partition in Volatile.Read(ref _partitions)) partition.Drain(); } + internal void ProcessPending() { foreach (var partition in Volatile.Read(ref _partitions)) partition.DrainForTests(); } + internal void DrainOneSliceForTests(BackingSourceKey key) => Partition(key).Drain(); internal void WithPartitionLockForTest(BackingSourceKey key, Action action) => Partition(key).WithLockForTest(action); internal PartitionControlSignal ControlSignalForTests(BackingSourceKey key) => Partition(key).Control; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedBrowseAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedBrowseAccess.cs index cae7f41e7..d9ac279aa 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedBrowseAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedBrowseAccess.cs @@ -1,5 +1,6 @@ using System.Collections.Concurrent; using Opc.Ua; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Authorization; using ZB.MOM.WW.OtOpcUa.OpcUaServer; @@ -49,26 +50,57 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable /// Reconciles against the live SDK binding; safe to call after the deferred sink binds. public void RefreshAnchors() { + lock (_lifecycle.TransitionGate) lock (_anchorGate) { if (Volatile.Read(ref _disposed) != 0) return; + // During an unresolved deployment the old guard is already invalid. Retain its + // bounded SDK lifetime so an identical placement can be reauthorized later. + if (_lifecycle.Suspended) return; var placements = _lifecycle.Active; foreach (var entry in _installed.ToArray()) { var old = entry.Value; if (Current(old.Placement)) continue; + var next = placements.FirstOrDefault(candidate => CompatiblePlacement(old.Placement, candidate)); + if (next is not null && Current(next)) + { + var renewed = new ProjectedAnchorDefinition(next.Mapping.Realm, old.Definition.LocalIdentifier, + old.Definition.Parent, next.Mapping.BranchName, next.Anchor.Subject, + next.Mapping.RemoteNamespaceMappingId, next.Mapping.Revision, () => Current(next)) + { LocalScope = next.Scope, Lifetime = old.Definition.Lifetime }; + if (_anchors.TryEnsureProjectedAnchor(renewed, out var node) && node == old.Node) + { + if (Current(next)) + { + _installed[entry.Key] = new(old.Node, renewed, next); + continue; + } + _installed.TryRemove(entry.Key, out _); + _anchors.TryRemoveProjectedAnchor(old.Node, renewed); + continue; + } + } _installed.TryRemove(entry.Key, out _); _anchors.TryRemoveProjectedAnchor(old.Node, old.Definition); } foreach (var placement in placements) { var mappingId = placement.Mapping.RemoteNamespaceMappingId; - if (_installed.ContainsKey(mappingId) || !Current(placement) || placement.Parent.Address.IdentifierKind != "string") continue; - var parent = _resolveNode(placement.Parent.Address.NamespaceUri, placement.Parent.Address.Identifier); + if (_installed.ContainsKey(mappingId) || !Current(placement)) continue; + // Transport realm roots deliberately use a disjoint identifier kind. Resolve only + // the exact trusted local root to the native SDK root, never a remote claimed ID. + var localRoot = LocalExportCatalog.RealmRoot(placement.Parent.Address.OriginClusterId, placement.Mapping.Realm); + var isRoot = placement.Parent == localRoot && string.Equals(placement.Parent.Address.OriginClusterId, + placement.Mapping.ClusterId, StringComparison.OrdinalIgnoreCase); + if (!isRoot && placement.Parent.Address.IdentifierKind != "string") continue; + var parent = _resolveNode(isRoot ? V3NodeIds.RawNamespaceUri : placement.Parent.Address.NamespaceUri, + isRoot ? V3NodeIds.SharedRootFolderId : placement.Parent.Address.Identifier); if (parent is not { } parentNode) continue; var id = ProjectedDataIds.Identifier(mappingId, placement.Anchor.Address); var definition = new ProjectedAnchorDefinition(placement.Mapping.Realm, id, parentNode, placement.Mapping.BranchName, - placement.Anchor.Subject, mappingId, placement.Mapping.Revision, () => Current(placement)); + placement.Anchor.Subject, mappingId, placement.Mapping.Revision, () => Current(placement)) + { LocalScope = placement.Scope }; if (_anchors.TryEnsureProjectedAnchor(definition, out var node) && node is { } anchorNode) { if (Current(placement)) _installed[mappingId] = new(anchorNode, definition, placement); @@ -78,6 +110,19 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable } } + private static bool CompatiblePlacement(ProjectedMappingPlacement previous, ProjectedMappingPlacement next) => + previous.Parent == next.Parent && previous.Anchor == next.Anchor && previous.Mapping.Realm == next.Mapping.Realm && + string.Equals(previous.Mapping.RemoteNamespaceMappingId, next.Mapping.RemoteNamespaceMappingId, StringComparison.OrdinalIgnoreCase) && + previous.Mapping.Revision == next.Mapping.Revision && + string.Equals(previous.Mapping.DataConnectionId, next.Mapping.DataConnectionId, StringComparison.OrdinalIgnoreCase) && + previous.Mapping.LocalParentKind == next.Mapping.LocalParentKind && + string.Equals(previous.Mapping.LocalParentId, next.Mapping.LocalParentId, StringComparison.OrdinalIgnoreCase) && + previous.Mapping.RemoteRootEntityId == next.Mapping.RemoteRootEntityId && + previous.Mapping.BranchName == next.Mapping.BranchName && previous.Scope.Kind == next.Scope.Kind && + string.Equals(previous.Scope.ClusterId, next.Scope.ClusterId, StringComparison.OrdinalIgnoreCase) && + previous.Scope.Segments.SequenceEqual(next.Scope.Segments, StringComparer.Ordinal) && + previous.LocalAncestry.SequenceEqual(next.LocalAncestry, StringComparer.OrdinalIgnoreCase); + private sealed class PageGuard(ProjectedBrowseAccess owner, IProjectedPageGuard source) { public bool IsCurrent() => Volatile.Read(ref owner._disposed) == 0 && source.IsCurrent; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs index afb9c3fbe..920516760 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs @@ -13,6 +13,8 @@ public sealed record ProjectedNodeProof(string LocalIdentifier, DataMetadata Met public sealed record ProjectedParentSnapshot(ProjectionPageStatus Status, IReadOnlyList Items, bool Complete, string? Continuation, long Generation, IDataAuthorizationLease? Lease = null, IDataMappedCatalogAuthority? LocalAuthority = null, ProjectedNodeProof? ParentProof = null); +internal sealed record RetainedProjectionDiagnostics(bool Retained, bool Retired, long? Generation, + bool? RouteAlive, bool? LocalAuthorityActive, bool? RemoteLeaseValid, bool? MappingBindingCurrent, bool? CacheGenerationCurrent); /// One bounded parent query, with the original monotonic request-start timestamp. public sealed record ProjectedBrowseRequest(string MappingId, DataView Parent, string? Filter, string? Continuation, DataCallerIdentity Caller, DataBudget Budget, long RequestStartedTimestamp) @@ -39,6 +41,9 @@ public interface IFederatedProjectionCatalog IProjectedPageGuard? CaptureParentGuard(ProjectedBrowseRequest request, ProjectedParentSnapshot expected) => null; Task PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken); bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof); + /// Checks authority for evidence already acquired under an exact proof. + bool IsUsableProof(ProjectedNodeProof proof) => proof.Lease.IsValid && + TryResolveProjected(proof.Metadata.View.Realm, proof.LocalIdentifier, out var current) && ReferenceEquals(current, proof); bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin); event Action? Invalidated; } @@ -48,11 +53,13 @@ public sealed class ProjectedCatalogCache { private readonly record struct ParentKey(string Mapping, DataView Parent, string? Filter, string? Cursor, DataCallerIdentity? Caller, ConfiguredProjectionCapability? Capability); private sealed class ParentEntry(ProjectedParentSnapshot snapshot) { internal readonly object Version = new(); internal ProjectedParentSnapshot Snapshot = snapshot; internal LinkedListNode? Sweep; } - private sealed class NodeEntry(ProjectedNodeProof proof) { internal ProjectedNodeProof Proof = proof; internal int Pins; internal bool Retired; internal LinkedListNode<(DataRealm Realm, string Id)>? Sweep; } + private sealed class NodeEntry(ProjectedNodeProof proof) { internal ProjectedNodeProof Proof = proof; internal NodeEntry? Predecessor; internal int Pins; internal bool Retired; internal LinkedListNode<(DataRealm Realm, string Id)>? Sweep; } private readonly object _sync = new(); private readonly Dictionary _parents = new(); private readonly Dictionary<(DataRealm Realm, string Id), NodeEntry> _nodes = new(); private readonly HashSet _retiredPinned = new(); + private readonly Dictionary _retiredByProof = new(ReferenceEqualityComparer.Instance); + private readonly Dictionary<(DataRealm Realm, string Id), int> _retiredPerNode = new(); private readonly LinkedList _parentSweep = new(); private readonly LinkedList<(DataRealm Realm, string Id)> _nodeSweep = new(); private readonly Dictionary _mappingNodeCounts = new(StringComparer.OrdinalIgnoreCase); @@ -72,6 +79,30 @@ public sealed class ProjectedCatalogCache } public TimeProvider Clock { get; } public event Action? Invalidated; + // Diagnostic lookup only: copy the retained reference while holding the cache lock, + // then release it before evaluating any lease fence or resolver callback. + internal RetainedProjectionDiagnostics CaptureRetainedDiagnostics(DataRealm realm, string localIdentifier) + { + if (realm is not (DataRealm.Raw or DataRealm.Uns) || string.IsNullOrWhiteSpace(localIdentifier) || localIdentifier.Length > 16384) + throw new ArgumentException("Invalid projected diagnostic target."); + ProjectedNodeProof? proof; + bool retired; + lock (_sync) + { + if (_nodes.TryGetValue((realm, localIdentifier), out var current)) + { proof = current.Proof; retired = current.Retired; } + else + { + var entry = _retiredPinned.FirstOrDefault(candidate => candidate.Proof.Metadata.View.Realm == realm && + candidate.Proof.LocalIdentifier == localIdentifier); + proof = entry?.Proof; retired = entry is not null; + } + } + if (proof is null) return new(false, false, null, null, null, null, null, null); + var flags = (proof.Lease as BoundProjectionLease)?.CaptureDiagnostics(); + return new(true, retired, proof.Generation, flags?.RouteAlive, flags?.LocalAuthorityActive, flags?.RemoteLeaseValid, + flags?.MappingBindingCurrent, flags?.CacheGenerationCurrent); + } private static ParentKey Key(ProjectedBrowseRequest request) => new(request.MappingId.ToUpperInvariant(), request.Parent, request.Filter, request.Continuation, request.Caller, request.ConfiguredCapability); private static (string Mapping, DataView Parent) Parent(string mapping, DataView parent) => (mapping.ToUpperInvariant(), parent); @@ -141,8 +172,13 @@ public sealed class ProjectedCatalogCache private void RemoveNode((DataRealm Realm, string Id) key) { if (!_nodes.Remove(key, out var node)) return; + node.Predecessor = null; _nodeSweep.Remove(node.Sweep!); node.Sweep = null; - if (node.Pins > 0) { node.Retired = true; _retiredPinned.Add(node); } + if (node.Pins > 0) + { + node.Retired = true; _retiredPinned.Add(node); _retiredByProof.Add(node.Proof, node); + _retiredPerNode.TryGetValue(key, out var count); _retiredPerNode[key] = checked(count + 1); + } else { _retainedBytes -= Bytes(node.Proof); ChangeMappingCount(node, -1); } } private void AddNode((DataRealm Realm, string Id) key, ProjectedNodeProof proof) @@ -191,6 +227,11 @@ public sealed class ProjectedCatalogCache string.Equals(left.Scope.ClusterId, right.Scope.ClusterId, StringComparison.OrdinalIgnoreCase) && left.Scope.Segments.SequenceEqual(right.Scope.Segments, StringComparer.Ordinal) && left.LocalAncestry.SequenceEqual(right.LocalAncestry, StringComparer.OrdinalIgnoreCase); + private static bool SamePlacementAcrossServing(ProjectedNodeProof previous, ProjectedNodeProof incoming) => + previous.Subject.Serving != incoming.Subject.Serving && + previous.OriginMetadata.View == incoming.OriginMetadata.View && + SamePlacement(previous.Subject with { Serving = incoming.Subject.Serving }, incoming.Subject); + private bool Usable(ProjectedBrowseRequest request) => request.ConfiguredCapability is { } capability ? capability.Matches(request.MappingId, request.Parent, null) : request.Caller is not null && _policy is not null && _policy.IsCallerUsable(request.Caller); private bool Allowed(ProjectedBrowseRequest request, ProjectedNodeProof proof) => Valid(proof) && @@ -275,6 +316,16 @@ public sealed class ProjectedCatalogCache items.Any(item => item.Generation != page.Generation || item.Lease.Serving != page.Lease.Serving || !ReferenceEquals(item.Resolver.LocalAuthority, local) || !Allowed(request, item)) || indexedItems.Select(item => (item.Metadata.View.Realm, item.LocalIdentifier)).Distinct().Count() != indexedItems.Length) return false; + // A new serving node may refresh the exact expired placement. Count + // all outstanding owners before the capacity sweep can unindex it. + foreach (var item in indexedItems) + { + var nodeKey = (item.Metadata.View.Realm, item.LocalIdentifier); + if (!_nodes.TryGetValue(nodeKey, out var old) || old.Proof.Subject.Serving == item.Subject.Serving) continue; + _retiredPerNode.TryGetValue(nodeKey, out var retired); + if (!SamePlacementAcrossServing(old.Proof, item) || Valid(old.Proof) || + (long)retired + (old.Pins > 0 ? 1 : 0) + 1 > 2) return false; + } var key = Key(request); var estimatedPage = KeyBytes(key) + Bytes(parent) + items.Sum(Bytes); _mappingNodeCounts.TryGetValue(request.MappingId, out var initialMappingCount); @@ -295,7 +346,8 @@ public sealed class ProjectedCatalogCache if (siblingNames.TryGetValue(item.Metadata.BrowseName, out var old) && old.Address != item.OriginMetadata.View.Address) return false; foreach (var item in indexedItems) if (_nodes.TryGetValue((item.Metadata.View.Realm, item.LocalIdentifier), out var existing) && - (existing.Retired || !SamePlacement(existing.Proof.Subject, item.Subject))) return false; + (existing.Retired || !SamePlacement(existing.Proof.Subject, item.Subject) && + (Valid(existing.Proof) || !SamePlacementAcrossServing(existing.Proof, item)))) return false; var cursor = commitCursor is null ? (true, page.Continuation) : commitCursor(); if (!cursor.Item1) return false; foreach (var item in indexedItems) @@ -342,6 +394,92 @@ public sealed class ProjectedCatalogCache lock (_sync) return _nodes.TryGetValue((proof.Metadata.View.Realm, proof.LocalIdentifier), out var entry) && !entry.Retired && ReferenceEquals(entry.Proof, proof) && Valid(proof); } + internal bool IsUsableProof(ProjectedNodeProof proof) + { + lock (_sync) + { + if (!_nodes.TryGetValue((proof.Metadata.View.Realm, proof.LocalIdentifier), out var current) || current.Retired || !Valid(current.Proof)) return false; + if (ReferenceEquals(current.Proof, proof)) return true; + var old = current.Predecessor; + return old is { Retired: true, Pins: > 0 } && ReferenceEquals(old.Proof, proof) && Valid(proof) && SameOverlap(proof, current.Proof); + } + } + // Renew only an already-owned node; this does not create a parent page, cursor or sibling grant. + internal bool TryRenewExact(ProjectedNodeProof previous, ProjectedNodeProof replacement, + int maximumMappingNodes, out ProjectedNodeProof? committed) => + TryRenewCore(previous, replacement, maximumMappingNodes, false, out committed); + internal bool TryRenewOverlap(ProjectedNodeProof previous, ProjectedNodeProof replacement, + int maximumMappingNodes, out ProjectedNodeProof? committed) => + TryRenewCore(previous, replacement, maximumMappingNodes, true, out committed); + private bool TryRenewCore(ProjectedNodeProof previous, ProjectedNodeProof replacement, + int maximumMappingNodes, bool overlap, out ProjectedNodeProof? committed) + { + committed = null; + ProjectedNodeProof frozen; + try { frozen = Freeze(replacement); } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or NullReferenceException) { return false; } + lock (_sync) + { + var key = (previous.Metadata.View.Realm, previous.LocalIdentifier); + _nodes.TryGetValue(key, out var current); + var retainedPrevious = current is not null && ReferenceEquals(current.Proof, previous) && !current.Retired || + _retiredByProof.ContainsKey(previous); + var mapping = previous.Metadata.View.MappingId; + if (!retainedPrevious || mapping is null || _saturated || + !_mappingGenerations.TryGetValue(mapping, out var generation) || frozen.Generation != generation || + !SameRenewalLineage(previous, frozen) || overlap && (!Valid(previous) || !SameOverlap(previous, frozen)) || + !Valid(frozen)) return false; + if (current is not null && !ReferenceEquals(current.Proof, previous)) + { + // A previous SDK transaction can lose its final guard after the cache + // committed. Only an exact descendant of the still-pinned old proof may + // be adopted/replaced; never overwrite an unrelated current binding. + if (!SameRenewalLineage(previous, current.Proof)) return false; + if (Valid(current.Proof)) + { + if (overlap && (current.Predecessor is not { Pins: > 0 } predecessor || + !ReferenceEquals(predecessor.Proof, previous) || !SameOverlap(previous, current.Proof))) return false; + if (current.Proof.Lease.Serving != frozen.Lease.Serving || + !SameMetadata(current.Proof.Metadata, frozen.Metadata) || + !SameMetadata(current.Proof.OriginMetadata, frozen.OriginMetadata)) return false; + committed = current.Proof; + return true; + } + } + var addsEntry = current is null || current.Pins > 0; + if (overlap && (current is null || current.Pins <= 0 || !ReferenceEquals(current.Proof, previous))) return false; + if (_nodes.Count + _retiredPinned.Count + (addsEntry ? 1 : 0) > _maxNodes) return false; + // A replacement and one still-pinned predecessor are distinct physical owners, + // but only one logical projected node. Never admit a chain of predecessors. + _retiredPerNode.TryGetValue(key, out var oldCount); + if ((long)oldCount + (current is { Pins: > 0 } ? 1 : 0) + 1 > 2) return false; + _mappingNodeCounts.TryGetValue(mapping, out var count); + var physicalMappingLimit = (long)maximumMappingNodes + Math.Min((long)maximumMappingNodes, _maxNodes); + if ((long)count + (addsEntry ? 1 : 0) > physicalMappingLimit) return false; + var delta = Bytes(frozen) - (current is { Pins: 0 } ? Bytes(current.Proof) : 0); + if (delta > _maxBytes - _retainedBytes) return false; + AddNode(key, frozen); + if (overlap) _nodes[key].Predecessor = current; + committed = frozen; + return true; + } + } + private static bool SameMetadata(DataMetadata left, DataMetadata right) => + left.Dimensions.SequenceEqual(right.Dimensions) && (left with { Dimensions = right.Dimensions }) == right; + private static bool SameRenewalLineage(ProjectedNodeProof left, ProjectedNodeProof right) => + left.LocalIdentifier == right.LocalIdentifier && left.Metadata.View == right.Metadata.View && + left.OriginMetadata.View == right.OriginMetadata.View && left.Subject.Scope.Kind == right.Subject.Scope.Kind && + string.Equals(left.Subject.Scope.ClusterId, right.Subject.Scope.ClusterId, StringComparison.OrdinalIgnoreCase) && + left.Subject.Scope.Segments.SequenceEqual(right.Subject.Scope.Segments, StringComparer.Ordinal) && + left.Subject.LocalAncestry.SequenceEqual(right.Subject.LocalAncestry, StringComparer.OrdinalIgnoreCase); + private static bool SameOverlap(ProjectedNodeProof left, ProjectedNodeProof right) => + SameRenewalLineage(left, right) && left.Generation == right.Generation && left.MaximumSampleAge == right.MaximumSampleAge && + left.Lease.Serving == right.Lease.Serving && SameMetadata(left.Metadata, right.Metadata) && SameMetadata(left.OriginMetadata, right.OriginMetadata) && + left.Subject.Serving == right.Subject.Serving && left.Subject.AllowedOperations == right.Subject.AllowedOperations && + left.Subject.WriteThrough == right.Subject.WriteThrough && ReferenceEquals(left.Resolver.LocalAuthority, right.Resolver.LocalAuthority) && + left.Lease is BoundProjectionLease a && right.Lease is BoundProjectionLease b && a.RouteIdentity is not null && + ReferenceEquals(a.RouteIdentity, b.RouteIdentity) && a.BindingIdentity is not null && ReferenceEquals(a.BindingIdentity, b.BindingIdentity) && + a.Target is not null && a.Target == b.Target; public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) { lock (_sync) @@ -358,6 +496,32 @@ public sealed class ProjectedCatalogCache entry.Pins++; pin = new Pin(this, entry); return true; } } + // Pins an already charged, expired successor solely for an invalid recovery + // binding. The caller must separately prove the source's exact predecessor. + internal bool TryPinExpiredRecoveryPair(ProjectedNodeProof previous, ProjectedNodeProof successor, out IDisposable? pin) + { + pin = null; + lock (_sync) + { + var key = (previous.Metadata.View.Realm, previous.LocalIdentifier); + if (!_retiredByProof.TryGetValue(previous, out var predecessor) || predecessor.Pins <= 0 || + previous.Lease is not BoundProjectionLease oldLease || successor.Lease is not BoundProjectionLease nextLease || + !oldLease.ExpiredNaturally || !nextLease.ExpiredNaturally || !SameOverlap(previous, successor)) return false; + _retiredPerNode.TryGetValue(key, out var retiredCount); + NodeEntry? current; + if (_nodes.TryGetValue(key, out var active)) + { + if (!ReferenceEquals(active.Proof, successor) || retiredCount != 1 || + !ReferenceEquals(active.Predecessor, predecessor)) return false; + current = active; + } + else if (retiredCount != 2 || !_retiredByProof.TryGetValue(successor, out current)) return false; + if (current.Pins <= 0) return false; + checked { current.Pins++; } + pin = new Pin(this, current); + return true; + } + } private sealed class Pin(ProjectedCatalogCache owner, NodeEntry entry) : IDisposable { private int _disposed; @@ -370,8 +534,15 @@ public sealed class ProjectedCatalogCache if (entry.Pins == 0 && entry.Retired) { var key = (entry.Proof.Metadata.View.Realm, entry.Proof.LocalIdentifier); + if (owner._nodes.TryGetValue(key, out var successor) && ReferenceEquals(successor.Predecessor, entry)) successor.Predecessor = null; if (owner._nodes.TryGetValue(key, out var current) && ReferenceEquals(current, entry)) owner.RemoveNode(key); - if (owner._retiredPinned.Remove(entry)) { owner._retainedBytes -= Bytes(entry.Proof); owner.ChangeMappingCount(entry, -1); } + if (owner._retiredPinned.Remove(entry)) + { + owner._retiredByProof.Remove(entry.Proof); + var retiredCount = owner._retiredPerNode[key] - 1; + if (retiredCount == 0) owner._retiredPerNode.Remove(key); else owner._retiredPerNode[key] = retiredCount; + owner._retainedBytes -= Bytes(entry.Proof); owner.ChangeMappingCount(entry, -1); + } } } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs index 2aba47db4..0a19a2b48 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs @@ -17,6 +17,8 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable { private readonly object _sync = new(); public TimeProvider Clock { get; } + internal Func? RetryJitterForTests { get; set; } + internal Action? BeforeSuccessorAdoptionForTests { get; set; } private readonly IFederatedProjectionCatalog _catalog; private readonly IProjectedNodeLookup _nodes; private readonly Func _connectionForMapping; @@ -24,8 +26,11 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable private readonly ProjectedDataAccessLimits _limits; private readonly IGrpcDataAdapterConnectionSource _connections; private readonly IProjectedValuePublisher _publisher; + private readonly IProjectedNamespacePageSink? _renewalSink; private readonly Func<(bool Allowed, long Generation)> _localWriteRole; private readonly Dictionary _sources = new(); + private readonly Dictionary<(string Connection, DataRealm Realm, string LocalIdentifier), HashSet> _sourcesByProjection = new(); + private readonly Dictionary _sourceSubscriptionOwners = new(); private readonly System.Collections.Concurrent.ConcurrentDictionary> _sourcesByMapping = new(StringComparer.OrdinalIgnoreCase); private readonly object _sourceRetirementGate = new(); private readonly LinkedList _sourceSweep = new(); @@ -36,27 +41,67 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable internal int PendingSourceRetirementsForTests { get { lock (_sourceRetirementGate) return _pendingSourceRetirement.Count; } } private int _unaryCount; private long _unaryBytes; + private long _cachedSampleBytes; + internal long CachedSampleBytesForTests => Interlocked.Read(ref _cachedSampleBytes); private readonly Dictionary _cohorts = new(); private readonly Dictionary _demandCohorts = new(); + private readonly Dictionary _demandSourceKeys = new(); private readonly HashSet _demands = []; private readonly Dictionary<(DataRealm Realm, string Identifier), int> _demandCounts = new(); private bool _disposed; public ProjectedDataAccess(IFederatedProjectionCatalog catalog, IProjectedNodeLookup nodes, IGrpcDataAdapterConnectionSource connections, Func connectionForMapping, DataOperationPolicy policy, IProjectedValuePublisher publisher, TimeProvider clock, ProjectedDataAccessLimits limits, - Func<(bool Allowed, long Generation)>? localWriteRole = null) + Func<(bool Allowed, long Generation)>? localWriteRole = null, IProjectedNamespacePageSink? renewalSink = null) { _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); _nodes = nodes ?? throw new ArgumentNullException(nameof(nodes)); _connections = connections ?? throw new ArgumentNullException(nameof(connections)); _connectionForMapping = connectionForMapping ?? throw new ArgumentNullException(nameof(connectionForMapping)); _policy = policy ?? throw new ArgumentNullException(nameof(policy)); _publisher = publisher ?? throw new ArgumentNullException(nameof(publisher)); Clock = clock ?? throw new ArgumentNullException(nameof(clock)); _limits = limits ?? throw new ArgumentNullException(nameof(limits)); _localWriteRole = localWriteRole ?? (() => (true, 1)); + _renewalSink = renewalSink; if (limits.MaxDemands <= 0 || limits.MaxUnaryOperations <= 0 || limits.MaxUnaryBytes <= 0 || limits.MaxStreams <= 0) throw new ArgumentOutOfRangeException(nameof(limits)); _catalog.Invalidated += OnCatalogInvalidated; } private static bool MetadataMatches(DataMetadata left, DataMetadata right) => left.Dimensions.SequenceEqual(right.Dimensions) && (left with { Dimensions = right.Dimensions }) == right; - private static ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue EncodeValue(DataMetadata metadata, object? value) + // Check the borrowed input without boxing or copying it. Array encoding temporarily owns + // two reference arrays, boxed elements and scalar wrappers as well as the eventual value; + // charge a conservative per-element bound before any of those allocations occur. + private static bool FitsWriteBudget(DataMetadata metadata, object? value, long maximumBytes) + { + const long scalarOverhead = 288; + if (maximumBytes < scalarOverhead) return false; + if (value is null) return true; + if (metadata.ValueKind == DataValueKind.Array) + { + if (metadata.ValueRank != 1 || metadata.Dimensions.Count != 1 || metadata.ArrayElementKind is not { } kind || + !ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.IsSupportedArrayElementKind(kind) || + value is not Array array || array.Rank != 1 || array.GetLowerBound(0) != 0 || + (metadata.Dimensions[0] != 0 && metadata.Dimensions[0] != array.Length)) return false; + const long overhead = 512, perElement = 128; + if (maximumBytes < overhead || array.LongLength > (maximumBytes - overhead) / perElement) return false; + var used = overhead + perElement * array.LongLength; + if (kind == DataValueKind.String) + { + // Both typed string arrays and the object arrays accepted by EncodeValue are + // indexable without creating an iterator or boxing individual elements. + if (array is not object[] strings) return false; + for (var i = 0; i < strings.Length; i++) + { + if (strings[i] is not string text || text.Length > (maximumBytes - used) / 2) return false; + used += 2L * text.Length; + } + } + return true; + } + if (metadata.ValueKind == DataValueKind.Bytes && value is byte[] bytes) + return bytes.LongLength <= maximumBytes - scalarOverhead; + if (metadata.ValueKind == DataValueKind.String && value is string textValue) + return textValue.Length <= (maximumBytes - scalarOverhead) / 2; + return true; // Exact scalar type checks remain in EncodeValue after admission. + } + private static ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue EncodeValue(DataMetadata metadata, object? value, long maximumBytes) { if (value is null) return ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.Null(); if (metadata.ValueKind == DataValueKind.Array) @@ -64,9 +109,18 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable if (metadata.ValueRank != 1 || metadata.Dimensions.Count != 1 || metadata.ArrayElementKind is not { } kind || value is not Array array || array.Rank != 1 || (metadata.Dimensions[0] != 0 && metadata.Dimensions[0] != array.Length)) throw new ArgumentException("Incompatible array shape."); var values = new object[array.Length]; + var used = 512L + 128L * array.LongLength; for (var i = 0; i < values.Length; i++) { var item = array.GetValue(i) ?? throw new ArgumentException("Null array element."); + // The caller owns the array and can replace its elements after preflight. + // Recheck each captured string against the already-reserved allowance. + if (kind == DataValueKind.String) + { + if (item is not string text || text.Length > (maximumBytes - used) / 2) + throw new ArgumentException("Array exceeds write budget."); + used += 2L * text.Length; + } values[i] = kind == DataValueKind.Timestamp && item is DateTime time ? new DateTimeOffset(time.ToUniversalTime()) : item; } return ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromArray(kind, values, [array.Length]); @@ -100,7 +154,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable public bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand) { demand = null; - if (caller is null || operation is not (DataOperations.Browse or DataOperations.Read or DataOperations.Write or DataOperations.Subscribe)) return false; + if (caller is null || operation is not (DataOperations.Browse or DataOperations.Read or DataOperations.Write or DataOperations.Subscribe)) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireInvalid); return false; } try { if (!_nodes.TryResolve(nodeId, out var definition) || definition is null || !definition.AuthorityIsCurrent() || @@ -108,26 +162,26 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable proof.Generation != definition.ProjectionGeneration || !MetadataMatches(proof.Metadata, definition.Metadata) || ((operation is DataOperations.Read or DataOperations.Subscribe) && proof.MaximumSampleAge <= TimeSpan.Zero) || proof.Metadata.View.MappingId is not { } mapping || proof.Lease.Serving.ServingGeneration <= 0 || - _connectionForMapping(mapping) is not { Length: > 0 } connectionId) return false; + _connectionForMapping(mapping) is not { Length: > 0 } connectionId) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireDefinition); return false; } var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc); var localRole = operation == DataOperations.Write ? _localWriteRole() : (Allowed: true, Generation: 1L); if (!localRole.Allowed || localRole.Generation <= 0) return false; var op = Operation(operation); if (!_policy.AuthorizeMapped(identity, op, proof.Metadata.View, proof.Lease.Serving, proof.Subject, proof.Resolver, proof.Lease) || - !definition.Lifetime.TryPin(out var nodePin) || nodePin is null) return false; - if (!_catalog.TryPinProjected(definition.Realm, definition.LocalIdentifier, out var pin) || pin is null) { nodePin.Dispose(); return false; } + !definition.Lifetime.TryPin(out var nodePin) || nodePin is null) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireAuthorization); return false; } + if (!_catalog.TryPinProjected(definition.Realm, definition.LocalIdentifier, out var pin) || pin is null) { nodePin.Dispose(); ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquirePin); return false; } var candidate = new Demand(this, nodeId, definition, proof, identity, operation, pin, nodePin, connectionId, localRole.Generation, null); lock (_sync) { - if (_disposed || _demands.Count >= _limits.MaxDemands) { pin.Dispose(); nodePin.Dispose(); return false; } + if (_disposed || _demands.Count >= _limits.MaxDemands) { pin.Dispose(); nodePin.Dispose(); ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireCapacity); return false; } _demands.Add(candidate); var key = (candidate.Realm, candidate.LocalIdentifier); _demandCounts.TryGetValue(key, out var count); _demandCounts[key] = checked(count + 1); } - if (!candidate.IsValid) { candidate.Dispose(); return false; } - demand = candidate; return true; + if (!candidate.IsValid) { candidate.Dispose(); ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireStale); return false; } + demand = candidate; ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireAccepted); return true; } - catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireException); return false; } } internal bool TryAcquireConfigured(NodeId nodeId, ConfiguredProjectionCapability capability, out IProjectedDemandLease? demand) { @@ -170,13 +224,20 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable private sealed class Demand(ProjectedDataAccess owner, NodeId nodeId, ProjectedVariableDefinition definition, ProjectedNodeProof proof, DataCallerIdentity? caller, DataOperations operation, IDisposable pin, IProjectedNodePin nodePin, string connectionId, long writeRoleGeneration, ConfiguredProjectionCapability? configured) : IProjectedDemandLease { + internal sealed record Binding(ProjectedVariableDefinition Definition, ProjectedNodeProof Proof, + IDisposable Pin, IProjectedNodePin NodePin, string ConnectionId, bool RecoveryOnly = false); + private Binding _binding = new(definition, proof, pin, nodePin, connectionId); private int _disposed; private int _holds; private bool _cleaned; private readonly TaskCompletionSource _completed = new(TaskCreationOptions.RunContinuationsAsynchronously); private readonly CancellationTokenSource _stop = new(); - internal ProjectedNodeProof Proof => proof; - internal ProjectedVariableDefinition Definition => definition; + internal Binding CurrentBinding => Volatile.Read(ref _binding); + internal ProjectedNodeProof Proof => CurrentBinding.Proof; + internal ProjectedVariableDefinition Definition => CurrentBinding.Definition; + internal NodeId NodeId => nodeId; + internal DataCallerIdentity? Caller => caller; + internal ConfiguredProjectionCapability? Configured => configured; internal DataOperations RequestedOperation => operation; internal bool Disposed => Volatile.Read(ref _disposed) != 0; internal bool TryHold() { lock (owner._sync) { if (_disposed != 0) return false; _holds++; return true; } } @@ -185,18 +246,19 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable { if (_cleaned) return; _cleaned = true; - pin.Dispose(); nodePin.Dispose(); owner._demands.Remove(this); + var binding = CurrentBinding; + binding.Pin.Dispose(); binding.NodePin.Dispose(); owner._demands.Remove(this); var key = (Realm, LocalIdentifier); var count = owner._demandCounts[key]; if (count == 1) owner._demandCounts.Remove(key); else owner._demandCounts[key] = count - 1; _completed.TrySetResult(); } internal Task Completion => _completed.Task; - public TimeSpan MaximumSampleAge => proof.MaximumSampleAge; - public DataView OriginView => proof.OriginMetadata.View; - public DataRealm Realm => definition.Realm; - public string LocalIdentifier => definition.LocalIdentifier; - public long ProjectionGeneration => proof.Generation; - public ServingIdentity Serving => proof.Lease.Serving; + public TimeSpan MaximumSampleAge => CurrentBinding.Proof.MaximumSampleAge; + public DataView OriginView => CurrentBinding.Proof.OriginMetadata.View; + public DataRealm Realm => CurrentBinding.Definition.Realm; + public string LocalIdentifier => CurrentBinding.Definition.LocalIdentifier; + public long ProjectionGeneration => CurrentBinding.Proof.Generation; + public ServingIdentity Serving => CurrentBinding.Proof.Lease.Serving; public CancellationToken CancellationToken => _stop.Token; public bool IsValid { @@ -205,17 +267,65 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable if (Volatile.Read(ref _disposed) != 0) return false; try { + var binding = CurrentBinding; + if (binding.RecoveryOnly) return false; + var currentDefinition = binding.Definition; var currentProof = binding.Proof; var role = operation == DataOperations.Write ? owner._localWriteRole() : (Allowed: true, Generation: 1L); - return role.Allowed && role.Generation == writeRoleGeneration && role.Generation > 0 && nodePin.IsValid && definition.AuthorityIsCurrent() && owner._nodes.TryResolve(nodeId, out var now) && now is not null && ReferenceEquals(now.Lifetime, definition.Lifetime) && now.ProjectionGeneration == definition.ProjectionGeneration && now.Metadata.View == definition.Metadata.View && - owner._catalog.TryResolveProjected(Realm, LocalIdentifier, out var current) && ReferenceEquals(current, proof) && - string.Equals(owner._connectionForMapping(proof.Metadata.View.MappingId!), connectionId, StringComparison.OrdinalIgnoreCase) && - (configured is not null ? configured.Matches(proof.Metadata.View.MappingId!, proof.Metadata.View, proof.Resolver.LocalAuthority) && (proof.Subject.AllowedOperations & DataOperations.Subscribe) != 0 : - caller is not null && owner._policy.AuthorizeMapped(caller, Operation(operation), proof.Metadata.View, Serving, proof.Subject, proof.Resolver, proof.Lease)) && - Volatile.Read(ref _disposed) == 0; + return role.Allowed && role.Generation == writeRoleGeneration && role.Generation > 0 && binding.NodePin.IsValid && currentDefinition.AuthorityIsCurrent() && owner._nodes.TryResolve(nodeId, out var now) && now is not null && ReferenceEquals(now.Lifetime, currentDefinition.Lifetime) && now.ProjectionGeneration == currentDefinition.ProjectionGeneration && now.Metadata.View == currentDefinition.Metadata.View && + owner._catalog.IsUsableProof(currentProof) && + string.Equals(owner._connectionForMapping(currentProof.Metadata.View.MappingId!), binding.ConnectionId, StringComparison.OrdinalIgnoreCase) && + (configured is not null ? configured.Matches(currentProof.Metadata.View.MappingId!, currentProof.Metadata.View, currentProof.Resolver.LocalAuthority) && (currentProof.Subject.AllowedOperations & DataOperations.Subscribe) != 0 : + caller is not null && owner._policy.AuthorizeMapped(caller, Operation(operation), currentProof.Metadata.View, currentProof.Lease.Serving, currentProof.Subject, currentProof.Resolver, currentProof.Lease)) && + ReferenceEquals(CurrentBinding, binding) && Volatile.Read(ref _disposed) == 0; } catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; } } } + internal bool TryPrepareBinding(Binding expected, out Binding? replacement) + { + replacement = null; + IProjectedNodePin? nextNodePin = null; + IDisposable? nextPin = null; + try + { + if (operation != DataOperations.Subscribe || Disposed || !ReferenceEquals(CurrentBinding, expected) || + !owner._nodes.TryResolve(nodeId, out var nextDefinition) || nextDefinition is null || !nextDefinition.AuthorityIsCurrent() || + !ReferenceEquals(nextDefinition.Lifetime, expected.Definition.Lifetime) || + nextDefinition.Metadata.View != expected.Definition.Metadata.View || + nextDefinition.Metadata.BrowseName != expected.Definition.Metadata.BrowseName || + nextDefinition.Metadata.NodeKind != expected.Definition.Metadata.NodeKind || + nextDefinition.Metadata.ValueKind != expected.Definition.Metadata.ValueKind || + nextDefinition.Metadata.ValueRank != expected.Definition.Metadata.ValueRank || + nextDefinition.Metadata.ArrayElementKind != expected.Definition.Metadata.ArrayElementKind || + !nextDefinition.Metadata.Dimensions.SequenceEqual(expected.Definition.Metadata.Dimensions) || + !owner._catalog.TryResolveProjected(nextDefinition.Realm, nextDefinition.LocalIdentifier, out var nextProof) || nextProof is null || + nextProof.OriginMetadata.View != expected.Proof.OriginMetadata.View || nextProof.Generation != nextDefinition.ProjectionGeneration || + !MetadataMatches(nextProof.Metadata, nextDefinition.Metadata) || nextProof.MaximumSampleAge <= TimeSpan.Zero || + nextProof.Metadata.View.MappingId is not { } mapping || + owner._connectionForMapping(mapping) is not { Length: > 0 } nextConnection || + !string.Equals(nextConnection, expected.ConnectionId, StringComparison.OrdinalIgnoreCase) || + (configured is not null ? !configured.Matches(mapping, nextProof.Metadata.View, nextProof.Resolver.LocalAuthority) || + (nextProof.Subject.AllowedOperations & DataOperations.Subscribe) == 0 : + caller is null || !owner._policy.AuthorizeMapped(caller, OpcUaOperation.CreateMonitoredItems, + nextProof.Metadata.View, nextProof.Lease.Serving, nextProof.Subject, nextProof.Resolver, nextProof.Lease)) || + !nextDefinition.Lifetime.TryPin(out nextNodePin) || nextNodePin is null) return false; + if (!owner._catalog.TryPinProjected(nextDefinition.Realm, nextDefinition.LocalIdentifier, out nextPin) || nextPin is null) return false; + if (!nextDefinition.AuthorityIsCurrent() || !owner._catalog.TryResolveProjected(nextDefinition.Realm, nextDefinition.LocalIdentifier, out var pinnedProof) || + !ReferenceEquals(pinnedProof, nextProof)) return false; + replacement = new(nextDefinition, nextProof, nextPin, nextNodePin, nextConnection); + nextPin = null; nextNodePin = null; + return true; + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; } + finally { try { nextPin?.Dispose(); } finally { nextNodePin?.Dispose(); } } + } + // Called under the owner's lock after all external authorization/pinning work. + internal bool TryInstallBinding(Binding expected, Binding replacement) + { + if (Disposed || !ReferenceEquals(_binding, expected)) return false; + Volatile.Write(ref _binding, replacement); + return true; + } public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) != 0) return; @@ -227,17 +337,40 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable } } } - private sealed record SourceKey(string Connection, DataView View, ServingIdentity Serving, long Generation); + private sealed record SourceKey(string Connection, DataView View, ServingIdentity Serving, long Generation, DataRealm Realm, string LocalIdentifier) + { + internal (string Connection, DataRealm Realm, string LocalIdentifier) Projection => (Connection, Realm, LocalIdentifier); + } + private interface ILeaseSampleProof { bool Matches(ProjectedNodeProof proof); } private sealed class SourceState : IProjectedSamplePublicationProof { private readonly ProjectedDataAccess _owner; private readonly SourceKey _key; private readonly ProjectedValueRoute _route; private ProjectedNodeProof? _proof; private ProjectedVariableDefinition? _definition; private IDisposable? _pin; private IProjectedNodePin? _nodePin; + private ProjectedNodeProof? _previousProof; private IDisposable? _previousPin; private IProjectedNodePin? _previousNodePin; + private WeakReference? _acceptedPredecessor; internal readonly object Gate = new(); internal long LastVersion; + private ProjectedValueUpdate? _cachedSample; + private long _cachedVersion, _cachedBytes; + private long _attemptEra; + private long _authorityGeneration; + private int _activeAttempts; + // Read publications retain their route until authority invalidation or access disposal. + internal bool ReadOwned; internal string MappingId { get; } internal SourceState(ProjectedDataAccess owner, SourceKey key, ProjectedNodeProof proof, ProjectedVariableDefinition definition, IDisposable pin, IProjectedNodePin nodePin, ProjectedValueRoute route) { _owner = owner; _key = key; _proof = proof; _definition = definition; _pin = pin; _nodePin = nodePin; _route = route; MappingId = proof.Metadata.View.MappingId!; } internal ProjectedValueRoute Route => _route; + internal long BeginAttempt() { lock (Gate) { _activeAttempts = checked(_activeAttempts + 1); return _attemptEra; } } + internal void EndAttempt(long era) + { + lock (Gate) + { + if (era != _attemptEra || _activeAttempts <= 0) return; + if (--_activeAttempts == 0) _attemptEra = checked(_attemptEra + 1); + } + } + internal bool IsAttemptValid(long era) { lock (Gate) return _activeAttempts > 0 && _attemptEra == era && IsValid; } public TimeProvider Clock => _owner.Clock; public bool IsValid { @@ -245,30 +378,194 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable { lock (Gate) { + ReleaseExpiredPredecessorLocked(); var proof = _proof; var definition = _definition; try { return proof is not null && definition is not null && _nodePin is { IsValid: true } && definition.AuthorityIsCurrent() && proof.Lease.IsValid && - _owner._catalog.TryResolveProjected(definition.Realm, definition.LocalIdentifier, out var now) && ReferenceEquals(now, proof) && + _owner._catalog.IsUsableProof(proof) && string.Equals(_owner._connectionForMapping(proof.Metadata.View.MappingId!), _key.Connection, StringComparison.OrdinalIgnoreCase); } catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; } } } } + private void ReleaseExpiredPredecessorLocked() + { + if (_previousProof is null || _previousProof.Lease.IsValid) return; + _previousProof = null; + _previousNodePin?.Dispose(); _previousNodePin = null; + _previousPin?.Dispose(); _previousPin = null; + } + internal void ReleaseExpiredPredecessor() + { + lock (Gate) ReleaseExpiredPredecessorLocked(); + } + internal bool IsProofValid(ProjectedNodeProof captured) + { + try { return IsValid && captured.Lease.IsValid && _owner._catalog.IsUsableProof(captured); } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; } + } + internal long AuthorityGenerationFor(ProjectedNodeProof captured) + { + lock (Gate) + { + if (ReferenceEquals(_proof, captured)) return _authorityGeneration; + if (ReferenceEquals(_previousProof, captured)) return _authorityGeneration - 1; + if (_proof is not null && _owner._catalog.IsUsableProof(_proof) && + _owner._catalog.TryResolveProjected(captured.Metadata.View.Realm, captured.LocalIdentifier, out var current) && + ReferenceEquals(current, captured) && _owner._catalog.IsUsableProof(captured)) return checked(_authorityGeneration + 1); + throw new InvalidOperationException("Sample proof does not belong to the current renewal handoff."); + } + } + internal bool CanDropExpiredPredecessor(IDataAuthorizationLease captured, long generation, long? era) + { + lock (Gate) + { + if (generation >= _authorityGeneration || era is { } value && (_activeAttempts <= 0 || value != _attemptEra) || + !IsValid || captured is not BoundProjectionLease old || !old.ExpiredNaturally || + _proof?.Lease is not BoundProjectionLease current || old.RouteIdentity is null || + !ReferenceEquals(old.RouteIdentity, current.RouteIdentity) || old.BindingIdentity is null || + !ReferenceEquals(old.BindingIdentity, current.BindingIdentity) || old.Target is null || old.Target != current.Target) return false; + return true; + } + } + internal bool TryPrepareSuccessor(Demand demand, out Demand.Binding? binding) + { + binding = null; + lock (Gate) + { + var captured = demand.Proof; + if (ReferenceEquals(_proof, captured)) return true; + // Another cadence can already own the successor while this one + // still has an independently live predecessor. Keep its original + // witness; a predecessor is never a request to adopt backwards. + if (ReferenceEquals(_previousProof, captured)) return IsProofValid(captured); + } + return demand.TryPrepareBinding(demand.CurrentBinding, out binding); + } + internal bool TryAdoptSuccessor(Demand.Binding binding, out bool consumed) + { + consumed = false; + lock (Gate) + { + if (_proof is null || _definition is null || !IsValid || !_owner._catalog.IsUsableProof(binding.Proof) || + !binding.NodePin.IsValid || !binding.Definition.AuthorityIsCurrent()) return false; + if (ReferenceEquals(_proof, binding.Proof)) return true; + if (_previousProof is not null) return false; + _previousProof = _proof; _previousPin = _pin; _previousNodePin = _nodePin; + _acceptedPredecessor = new WeakReference(_proof); + _proof = binding.Proof; _definition = binding.Definition; _pin = binding.Pin; _nodePin = binding.NodePin; + _authorityGeneration = checked(_authorityGeneration + 1); + consumed = true; + return true; + } + } + internal bool TryPrepareRecoveryParking(Demand.Binding expected, out Demand.Binding? parked) + { + parked = null; + lock (Gate) + { + var proof = _proof; var definition = _definition; + if (proof is null || definition is null || _nodePin is not { IsValid: true } || + _acceptedPredecessor is null || !_acceptedPredecessor.TryGetTarget(out var previous) || + !ReferenceEquals(previous, expected.Proof) || ReferenceEquals(proof, previous) || + !ReferenceEquals(definition.Lifetime, expected.Definition.Lifetime) || + definition.Realm != expected.Definition.Realm || definition.LocalIdentifier != expected.Definition.LocalIdentifier || + definition.Parent != expected.Definition.Parent || definition.Metadata.View != expected.Definition.Metadata.View || + _owner._catalog is not RemoteNamespaceResolver resolver || + !resolver.TryPinExpiredRecoveryPair(previous, proof, out var pin) || pin is null) return false; + if (!definition.Lifetime.TryPin(out var nodePin) || nodePin is null) { pin.Dispose(); return false; } + parked = new(definition, proof, pin, nodePin, expected.ConnectionId, RecoveryOnly: true); + return true; + } + } + private sealed class ReadProof(SourceState source, ProjectedNodeProof captured) : IProjectedSamplePublicationProof, ILeaseSampleProof, IObsoleteProjectedSample + { + private readonly WeakReference _proof = new(captured); + private readonly IDataAuthorizationLease _lease = captured.Lease; + private readonly long _generation = source.AuthorityGenerationFor(captured); + public TimeProvider Clock => source.Clock; + public object SourceIdentity => source; + public bool IsSourceValid => source.IsValid; + public bool IsValid => _lease.IsValid && _proof.TryGetTarget(out var proof) && source.IsProofValid(proof); + public bool Matches(ProjectedNodeProof proof) => _proof.TryGetTarget(out var target) && ReferenceEquals(target, proof); + public bool CanDropExpiredPredecessor => source.CanDropExpiredPredecessor(_lease, _generation, null); + public void Invalidate() => source.Invalidate(); + } + internal IProjectedSamplePublicationProof CaptureReadProof(ProjectedNodeProof proof) => new ReadProof(this, proof); + private void ClearCachedLocked() + { + _cachedSample = null; _cachedVersion = 0; + if (_cachedBytes != 0) { Interlocked.Add(ref _owner._cachedSampleBytes, -_cachedBytes); _cachedBytes = 0; } + } + // Called under Gate only after the publication has been admitted. The cache owns a + // copy, and all SourceStates share one finite budget independent of transport frames. + internal void CacheLocked(ProjectedValueUpdate update, long version) + { + ClearCachedLocked(); + if (!IsValid) return; + long bytes; + try { bytes = checked(512 + OwnedDataSample.Estimate(update.Snapshot.Value)); } + catch (Exception ex) when (ex is ArgumentException or OverflowException) { return; } + while (true) + { + var used = Interlocked.Read(ref _owner._cachedSampleBytes); + if (bytes > _owner._limits.MaxUnaryBytes - used) return; + if (Interlocked.CompareExchange(ref _owner._cachedSampleBytes, used + bytes, used) == used) break; + } + try + { + var owned = OwnedDataSample.CopyLegacy(update.Snapshot.Value); + _cachedSample = update with { Snapshot = update.Snapshot with { Value = owned } }; + _cachedVersion = version; _cachedBytes = bytes; + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or OverflowException) { } + finally { if (_cachedBytes != bytes) Interlocked.Add(ref _owner._cachedSampleBytes, -bytes); } + } + internal bool TryRecoveryLocked(Demand demand, bool successorOnly = false) + { + var sample = _cachedSample; + if (sample is null || _cachedVersion != LastVersion || !sample.SourceProof.IsValid || !demand.IsValid || !IsValid || + successorOnly && (sample.SourceProof is not ILeaseSampleProof witness || !witness.Matches(demand.Proof))) return false; + try + { + var elapsed = _owner.Clock.GetElapsedTime(sample.ReceivedTimestamp, _owner.Clock.GetTimestamp()); + if (!sample.OriginAgeBounds.Advance(elapsed).IsFresh(demand.MaximumSampleAge)) return false; + // Preserve the original receipt and bounds; downstream advances the same + // evidence again at observation, rather than resetting source age. + return _owner._publisher.TryPublish([sample with { IsCompleteSnapshot = true, MaximumSampleAge = demand.MaximumSampleAge }]); + } + catch (Exception ex) when (ex is ArgumentException or OverflowException) { return false; } + } + internal bool HasFreshCachedLocked(Demand demand) + { + var sample = _cachedSample; + if (sample is null || _cachedVersion != LastVersion || !sample.SourceProof.IsValid || !demand.IsValid || !IsValid) return false; + try + { + return sample.OriginAgeBounds.Advance(_owner.Clock.GetElapsedTime(sample.ReceivedTimestamp, + _owner.Clock.GetTimestamp())).IsFresh(demand.MaximumSampleAge); + } + catch (Exception ex) when (ex is ArgumentException or OverflowException) { return false; } + } public void Invalidate() { - IDisposable? pin; IProjectedNodePin? nodePin; + IDisposable? pin; IProjectedNodePin? nodePin; IDisposable? previousPin; IProjectedNodePin? previousNodePin; lock (Gate) { if (_proof is null) return; _proof = null; _definition = null; pin = _pin; _pin = null; nodePin = _nodePin; _nodePin = null; + previousPin = _previousPin; _previousPin = null; previousNodePin = _previousNodePin; _previousNodePin = null; _previousProof = null; _acceptedPredecessor = null; ClearCachedLocked(); } try { _owner._publisher.Retire(_route); } catch (Exception) { } - finally { nodePin?.Dispose(); pin?.Dispose(); } + finally { nodePin?.Dispose(); pin?.Dispose(); previousNodePin?.Dispose(); previousPin?.Dispose(); } } } private bool RemoveSourceLocked(SourceKey key, out SourceState? source) { if (!_sources.Remove(key, out source)) return false; + var projectionKeys = _sourcesByProjection[key.Projection]; + projectionKeys.Remove(key); + if (projectionKeys.Count == 0) _sourcesByProjection.Remove(key.Projection); if (_sourceSweepNodes.Remove(key, out var sweep)) _sourceSweep.Remove(sweep); if (_sourcesByMapping.TryGetValue(source.MappingId, out var keys)) { @@ -281,6 +578,19 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable } return true; } + private void AddSourceOwnerLocked(SourceKey key) + { + _sourceSubscriptionOwners.TryGetValue(key, out var count); + _sourceSubscriptionOwners[key] = checked(count + 1); + } + private SourceState? ReleaseSourceOwnerLocked(SourceKey key) + { + var count = _sourceSubscriptionOwners[key]; + if (count > 1) { _sourceSubscriptionOwners[key] = count - 1; return null; } + _sourceSubscriptionOwners.Remove(key); + if (_sources.TryGetValue(key, out var source) && !source.ReadOwned && RemoveSourceLocked(key, out var retired)) return retired; + return null; + } private void OnCatalogInvalidated(string mapping, long generation) { // Mapping activation may hold its own lock. Never acquire the data-access @@ -318,38 +628,82 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable } private SourceState? GetSource(Demand demand, string connection) { - var proof = demand.Proof; var key = new SourceKey(connection.ToUpperInvariant(), demand.OriginView, demand.Serving, demand.ProjectionGeneration); - lock (_sync) + var proof = demand.Proof; var key = new SourceKey(connection.ToUpperInvariant(), demand.OriginView, demand.Serving, demand.ProjectionGeneration, demand.Realm, demand.LocalIdentifier); + List? retired = null; + try { - if (_sources.TryGetValue(key, out var existing)) + lock (_sync) { - if (existing.IsValid) return existing; - RemoveSourceLocked(key, out _); existing.Invalidate(); + if (_disposed || !ReferenceEquals(demand.Proof, proof) || !demand.IsValid) return null; + retired = RemoveInvalidReadSourcesLocked(key); + return GetSourceLocked(demand, connection, proof, key); } - if (_sources.Count >= _limits.MaxDemands) - { - var count = Math.Min(16, _sourceSweep.Count); - for (var i = 0; i < count && _sourceSweep.First is { } first; i++) - { - var sourceKey = first.Value; var state = _sources[sourceKey]; - if (!state.IsValid) { RemoveSourceLocked(sourceKey, out _); state.Invalidate(); } - else { _sourceSweep.RemoveFirst(); _sourceSweep.AddLast(first); } - } - } - if (_sources.Count >= _limits.MaxDemands || !demand.Definition.Lifetime.TryPin(out var nodePin) || nodePin is null) return null; - if (!_catalog.TryPinProjected(demand.Realm, demand.LocalIdentifier, out var pin) || pin is null) { nodePin.Dispose(); return null; } - var route = new ProjectedValueRoute("grpc-data:" + connection, ProjectedDataIds.DependencyReference(demand.Realm, demand.LocalIdentifier), - demand.Realm, demand.LocalIdentifier, demand.ProjectionGeneration, demand.Serving, Guid.NewGuid()); - var source = new SourceState(this, key, proof, demand.Definition, pin, nodePin, route); - if (!source.IsValid || !_publisher.TryBind(route)) { source.Invalidate(); return null; } - _sources.Add(key, source); _sourceSweepNodes.Add(key, _sourceSweep.AddLast(key)); - if (!_sourcesByMapping.TryGetValue(source.MappingId, out var keys)) _sourcesByMapping[source.MappingId] = keys = new(); - keys.Add(key); - // Attach before the final authority check: invalidation either observes this - // bucket or is detected here, so no source can strand its physical pins. - if (!source.IsValid) { RemoveSourceLocked(key, out _); source.Invalidate(); return null; } - return source; } + finally + { + if (retired is not null) + foreach (var previous in retired) previous.Invalidate(); + } + } + + private List? RemoveInvalidReadSourcesLocked(SourceKey key) + { + if (!_sourcesByProjection.TryGetValue(key.Projection, out var keys) || + (keys.Count == 1 && keys.Contains(key))) return null; + + // A read-owned source may outlive its last subscription. An invalid route + // at this exact projection must release its own pin before the new route + // tries to renew, including when this attachment reuses the new source. + List? retired = null; + foreach (var previous in keys.ToArray()) + { + if (previous == key || _sourceSubscriptionOwners.ContainsKey(previous)) continue; + var source = _sources[previous]; + if (!source.ReadOwned || source.IsValid) continue; + RemoveSourceLocked(previous, out _); + (retired ??= []).Add(source); + } + return retired; + } + + private SourceState? GetSourceLocked(Demand demand, string connection, ProjectedNodeProof proof, SourceKey key) + { + if (_sources.TryGetValue(key, out var existing)) + { + if (existing.IsValid) + { + if (demand.RequestedOperation == DataOperations.Read) existing.ReadOwned = true; + return existing; + } + RemoveSourceLocked(key, out _); existing.Invalidate(); + } + if (_sources.Count >= _limits.MaxDemands) + { + var count = Math.Min(16, _sourceSweep.Count); + for (var i = 0; i < count && _sourceSweep.First is { } first; i++) + { + var sourceKey = first.Value; var state = _sources[sourceKey]; + if (!state.IsValid) { RemoveSourceLocked(sourceKey, out _); state.Invalidate(); } + else { _sourceSweep.RemoveFirst(); _sourceSweep.AddLast(first); } + } + } + if (_sources.Count >= _limits.MaxDemands || !demand.Definition.Lifetime.TryPin(out var nodePin) || nodePin is null) return null; + if (!_catalog.TryPinProjected(demand.Realm, demand.LocalIdentifier, out var pin) || pin is null) { nodePin.Dispose(); return null; } + var route = new ProjectedValueRoute("grpc-data:" + connection, ProjectedDataIds.DependencyReference(demand.Realm, demand.LocalIdentifier), + demand.Realm, demand.LocalIdentifier, demand.ProjectionGeneration, demand.Serving, Guid.NewGuid()); + var source = new SourceState(this, key, proof, demand.Definition, pin, nodePin, route) + { ReadOwned = demand.RequestedOperation == DataOperations.Read }; + if (!source.IsValid || !_publisher.TryBind(route)) { source.Invalidate(); return null; } + _sources.Add(key, source); _sourceSweepNodes.Add(key, _sourceSweep.AddLast(key)); + if (!_sourcesByProjection.TryGetValue(key.Projection, out var projectionKeys)) + _sourcesByProjection.Add(key.Projection, projectionKeys = []); + projectionKeys.Add(key); + if (!_sourcesByMapping.TryGetValue(source.MappingId, out var keys)) _sourcesByMapping[source.MappingId] = keys = new(); + keys.Add(key); + // Attach before the final authority check: invalidation either observes this + // bucket or is detected here, so no source can strand its physical pins. + if (!source.IsValid) { RemoveSourceLocked(key, out _); source.Invalidate(); return null; } + return source; } public bool ScheduleRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp) { @@ -357,44 +711,56 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable try { budget.Validate(); } catch (ArgumentException) { return false; } var elapsed = Clock.GetElapsedTime(requestStartedTimestamp, Clock.GetTimestamp()); if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) return false; + // The request's byte budget is an upper bound. Narrow it to this adapter's + // configured physical limit before admission and before remote dispatch. + var boundedBudget = budget with { MaxBytes = Math.Min(budget.MaxBytes, _limits.MaxUnaryBytes) }; lock (_sync) { - if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || budget.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !item.TryHold()) return false; - _unaryCount++; _unaryBytes += budget.MaxBytes; + if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || boundedBudget.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !item.TryHold()) return false; + _unaryCount++; _unaryBytes += boundedBudget.MaxBytes; } - _ = Task.Run(() => ReadCoreAsync(item, budget, requestStartedTimestamp)); return true; + _ = Task.Run(() => ReadCoreAsync(item, boundedBudget, requestStartedTimestamp)); return true; } private async Task ReadCoreAsync(Demand demand, DataBudget budget, long started) { IGrpcDataAdapterConnectionLease? connection = null; try { + var original = demand.CurrentBinding; + var originalProof = original.Proof; var remaining = budget.Timeout - Clock.GetElapsedTime(started, Clock.GetTimestamp()); - if (remaining <= TimeSpan.Zero || !demand.IsValid) return; - var connectionId = _connectionForMapping(demand.Proof.Metadata.View.MappingId!); + if (remaining <= TimeSpan.Zero || !demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original)) return; + var connectionId = _connectionForMapping(originalProof.Metadata.View.MappingId!); if (string.IsNullOrWhiteSpace(connectionId)) return; using var timeout = new CancellationTokenSource(remaining, Clock); using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, demand.CancellationToken); connection = await _connections.AcquireAsync(connectionId, linked.Token).ConfigureAwait(false); - if (connection is null || !ReferenceEquals(connection.Connection.Clock, Clock) || connection.CancellationToken.IsCancellationRequested || !demand.IsValid) return; + if (connection is null || !ReferenceEquals(connection.Connection.Clock, Clock) || connection.CancellationToken.IsCancellationRequested || + !demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original)) return; using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken); - var result = await connection.Connection.ReadAsync(new DataReadRequest([new ReadItem("0", demand.OriginView, null)], budget with { Timeout = remaining }), route.Token).ConfigureAwait(false); + var readStarted = Clock.GetTimestamp(); + var result = await connection.Connection.ReadAsync(new DataReadRequest([new ReadItem("0", originalProof.OriginMetadata.View, null)], budget with { Timeout = remaining }), route.Token).ConfigureAwait(false); try { if (result.Count != 1 || result[0].CorrelationId != "0" || result[0].Status != DataItemStatus.Good || result[0].Readiness != DataReadiness.Ready || - result[0].Sample is not { } sample || sample.Serving != demand.Serving || sample.Version <= 0 || !demand.IsValid || route.IsCancellationRequested) return; + result[0].Sample is not { } sample || sample.Serving != originalProof.Lease.Serving || sample.Version <= 0 || !demand.IsValid || + !ReferenceEquals(demand.CurrentBinding, original) || route.IsCancellationRequested) return; result[0].AgeBounds.Validate(); - if (!result[0].AgeBounds.IsFresh(demand.MaximumSampleAge)) return; + // An unstamped implementation is conservatively anchored before the read call. + var received = result[0].FreshnessObservedTimestamp ?? readStarted; + if (!result[0].AgeBounds.Advance(Clock.GetElapsedTime(received, Clock.GetTimestamp())).IsFresh(originalProof.MaximumSampleAge)) return; if (sample.Value.EstimatedRetainedBytes > budget.MaxBytes) return; - var payload = DecodeValue(sample.Value, demand.Proof.OriginMetadata); + var payload = DecodeValue(sample.Value, originalProof.OriginMetadata); var snapshot = new DataValueSnapshot(payload, sample.StatusCode, sample.SourceTimestampUtc?.UtcDateTime, sample.ServerTimestampUtc?.UtcDateTime); - var received = Clock.GetTimestamp(); var source = GetSource(demand, connectionId); + var source = GetSource(demand, connectionId); if (source is null) return; lock (source.Gate) { - if (!demand.IsValid || !source.IsValid || sample.Version <= source.LastVersion) return; - if (_publisher.TryPublish([new(source.Route, snapshot, result[0].AgeBounds, received, source, true, demand.MaximumSampleAge)])) source.LastVersion = sample.Version; - else source.Invalidate(); + if (!demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original) || !source.IsValid || sample.Version <= source.LastVersion || route.IsCancellationRequested || + !result[0].AgeBounds.Advance(Clock.GetElapsedTime(received, Clock.GetTimestamp())).IsFresh(originalProof.MaximumSampleAge)) return; + var update = new ProjectedValueUpdate(source.Route, snapshot, result[0].AgeBounds, received, source.CaptureReadProof(originalProof), true, originalProof.MaximumSampleAge, sample.Version); + if (_publisher.TryPublish([update])) { source.LastVersion = sample.Version; source.CacheLocked(update, sample.Version); } + else if (!ProjectedEvidenceRetirement.CanDrop(update.SourceProof)) source.Invalidate(); } } finally { foreach (var item in result) item.Dispose(); } @@ -412,21 +778,50 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable var rejected = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, StatusCodes.BadNotConnected.Code, null); var unknown = new DataWriteOutcome(DataWriteState.OutcomeUnknown, StatusCodes.BadTimeout.Code, null); if (demand is not Demand item || item.RequestedOperation != DataOperations.Write || !item.IsValid || budget is null || cancellationToken.IsCancellationRequested) return rejected; - ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue owned; try { budget.Validate(); - owned = EncodeValue(item.Proof.OriginMetadata, value); + // The SDK's request cap is an upper bound, not a minimum required reservation. + // Use the adapter's configured ceiling for payload checks and physical work. + budget = budget with { MaxBytes = Math.Min(budget.MaxBytes, _limits.MaxUnaryBytes) }; + if (!FitsWriteBudget(item.Proof.OriginMetadata, value, budget.MaxBytes)) return rejected; } - catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return rejected; } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or OverflowException) { return rejected; } var elapsed = Clock.GetElapsedTime(requestStartedTimestamp, Clock.GetTimestamp()); - if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout || owned.EstimatedRetainedBytes > budget.MaxBytes) { owned.Dispose(); return rejected; } + if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) return rejected; lock (_sync) { - if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || budget.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !item.TryHold()) { owned.Dispose(); return rejected; } + if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || budget.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !item.TryHold()) return rejected; _unaryCount++; _unaryBytes += budget.MaxBytes; } - var task = Task.Run(() => WriteCoreAsync(item, owned, budget, requestStartedTimestamp, cancellationToken)); + ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue? owned = null; + Task task; + var transferred = false; + try + { + if (cancellationToken.IsCancellationRequested || !item.IsValid) return rejected; + owned = EncodeValue(item.Proof.OriginMetadata, value, budget.MaxBytes); + elapsed = Clock.GetElapsedTime(requestStartedTimestamp, Clock.GetTimestamp()); + if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout || owned.EstimatedRetainedBytes > budget.MaxBytes || + cancellationToken.IsCancellationRequested || !item.IsValid) return rejected; + var reservedValue = owned; + task = Task.Run(() => WriteCoreAsync(item, reservedValue, budget, requestStartedTimestamp, cancellationToken)); + transferred = true; + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or OverflowException or TaskSchedulerException) + { return rejected; } + finally + { + if (!transferred) + { + try { owned?.Dispose(); } + finally + { + try { item.ReleaseHold(); } + finally { lock (_sync) { _unaryCount--; _unaryBytes -= budget.MaxBytes; } } + } + } + } try { return await task.WaitAsync(budget.Timeout - elapsed, Clock, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { return unknown; } catch (TimeoutException) { return unknown; } @@ -461,7 +856,15 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable finally { try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); } - finally { value.Dispose(); demand.ReleaseHold(); lock (_sync) { _unaryCount--; _unaryBytes -= budget.MaxBytes; } } + finally + { + try { value.Dispose(); } + finally + { + try { demand.ReleaseHold(); } + finally { lock (_sync) { _unaryCount--; _unaryBytes -= budget.MaxBytes; } } + } + } } } private sealed record CohortKey(string Connection, ServingIdentity Serving, TimeSpan Interval); @@ -483,20 +886,63 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable if (cohort.Closing || !item.TryHold()) { if (created) _cohorts.Remove(key); return false; } _demandCohorts.Add(item, cohort); if (!cohort.Add(item)) { _demandCohorts.Remove(item); item.ReleaseHold(); if (created) _cohorts.Remove(key); return false; } + var sourceKey = new SourceKey(key.Connection, item.OriginView, key.Serving, item.ProjectionGeneration, item.Realm, item.LocalIdentifier); + AddSourceOwnerLocked(sourceKey); _demandSourceKeys.Add(item, sourceKey); cohort.Start(); return true; } } private sealed class Cohort { + private sealed class AttemptProof(SourceState source, ProjectedNodeProof captured) : IProjectedSamplePublicationProof, ILeaseSampleProof, IObsoleteProjectedSample + { + private readonly WeakReference _proof = new(captured); + private readonly IDataAuthorizationLease _lease = captured.Lease; + private readonly long _generation = source.AuthorityGenerationFor(captured); + private int _active = 1; + private int _counted; + private long _era = -1; + internal SourceState Source => source; + public bool Matches(ProjectedNodeProof proof) => _proof.TryGetTarget(out var target) && ReferenceEquals(target, proof); + internal bool LeaseValid => _lease.IsValid; + public bool IsValid { get { var era = Interlocked.Read(ref _era); return era >= 0 && _lease.IsValid && _proof.TryGetTarget(out var proof) && source.IsAttemptValid(era) && source.IsProofValid(proof); } } + public bool IsSourceValid { get { var era = Interlocked.Read(ref _era); return era >= 0 && source.IsAttemptValid(era); } } + public bool CanDropExpiredPredecessor { get { var era = Interlocked.Read(ref _era); return era >= 0 && source.CanDropExpiredPredecessor(_lease, _generation, era); } } + public object SourceIdentity => source; + public TimeProvider Clock => source.Clock; + public void Invalidate() { Close(); source.Invalidate(); } + internal bool Promote() + { + if (IsValid) return true; + if (Volatile.Read(ref _active) == 0 || Interlocked.Read(ref _era) >= 0) return false; + var era = source.BeginAttempt(); + Interlocked.Exchange(ref _era, era); + Interlocked.Exchange(ref _counted, 1); + if (Volatile.Read(ref _active) == 0) { ReleaseCoverage(); return false; } + return IsValid; + } + private void ReleaseCoverage() + { + if (Interlocked.Exchange(ref _counted, 0) != 0) source.EndAttempt(Interlocked.Read(ref _era)); + } + internal void Close() { if (Interlocked.Exchange(ref _active, 0) != 0) ReleaseCoverage(); } + } private abstract record Event; private sealed record AddEvent(Demand Demand) : Event; private sealed record RemoveEvent(Demand Demand) : Event; - private sealed record FrameEvent(DataSubscriptionFrame Frame, long Bytes) : Event; + private sealed record RefreshEvent(Demand Demand) : Event; + private sealed record FrameEvent(DataSubscriptionFrame Frame, long Bytes, long ReceivedTimestamp) : Event; + private sealed record FreshnessEvent : Event; + private sealed record RenewalEvent : Event; + private sealed record RenewedEvent(Demand Demand, Demand.Binding Expected, bool Success) : Event; private sealed record EndEvent : Event; private sealed class Registration(Demand demand, string id) - { internal readonly Demand Demand = demand; internal readonly string Id = id; internal DataItemHandle? Handle; internal bool Removed; } + { + internal readonly Demand Demand = demand; internal readonly string Id = id; + internal DataItemHandle? Handle; internal bool Removed, Rebinding, Recovery, AwaitingCurrent, NeedsChallenge, HasBaseline, Renewal; + internal IDataAuthorizationLease? RenewalPredecessor; + } private readonly ProjectedDataAccess _owner; - private readonly CohortKey _key; + private CohortKey _key; private readonly string _connectionId; private readonly Channel _events; private readonly CancellationTokenSource _stop = new(); @@ -504,11 +950,15 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable private readonly Dictionary _byId = new(StringComparer.Ordinal); private readonly Dictionary _byHandle = new(); private readonly Dictionary _removing = new(StringComparer.Ordinal); - private readonly string _id = Guid.NewGuid().ToString("N"); - private const long Epoch = 1; - private int _started, _closing, _restart; + // Guarded by the owner's lock; at most one queued or active refresh per demand. + private readonly HashSet _refreshRequests = []; + private string _id = string.Empty; + private long _epoch; + private int _started, _closing, _healthyBaseline; private long _sequence; private long _frameBytes; + private int _freshnessQueued; + private int _servingMismatch; internal bool Closing => Volatile.Read(ref _closing) != 0; internal Cohort(ProjectedDataAccess owner, CohortKey key, string connectionId) { @@ -520,138 +970,622 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable internal void Remove(Demand demand) { if (!_events.Writer.TryWrite(new RemoveEvent(demand))) Stop(); } internal void Start() { if (Interlocked.Exchange(ref _started, 1) == 0) _ = Task.Run(RunAsync); } internal void Stop() { if (Interlocked.Exchange(ref _closing, 1) == 0) _ = _stop.CancelAsync(); } - internal bool Restart() + internal bool Refresh(Demand demand) { - if (Volatile.Read(ref _restart) != 0) return true; if (Closing) return false; - Interlocked.Exchange(ref _restart, 1); Stop(); return true; + if (!_refreshRequests.Add(demand)) return true; + if (_events.Writer.TryWrite(new RefreshEvent(demand))) return true; + _refreshRequests.Remove(demand); return false; } - private async Task PumpAsync(IDataSubscription stream) + private void FinishRefresh(Demand demand) + { + lock (_owner._sync) _refreshRequests.Remove(demand); + } + private async Task PumpAsync(IDataSubscription stream, CancellationToken attemptStop) { try { - await foreach (var frame in stream.ReadAllAsync(_stop.Token).ConfigureAwait(false)) + await foreach (var frame in stream.ReadAllAsync(attemptStop).ConfigureAwait(false)) { - var bytes = frame is DataSubscriptionValues values ? checked(512L + values.Items.Sum(x => x.Sample.Value.EstimatedRetainedBytes)) : 512L; + var receivedTimestamp = _owner.Clock.GetTimestamp(); + var bytes = frame is DataSubscriptionValues values ? checked(512L + values.Items.Sum(x => + checked(x.Sample.Value.EstimatedRetainedBytes + 2L * (x.FreshnessChallengeId?.Length ?? 0)))) : 512L; if (bytes > _owner._limits.MaxUnaryBytes || Interlocked.Add(ref _frameBytes, bytes) > _owner._limits.MaxUnaryBytes) { Interlocked.Add(ref _frameBytes, -bytes); (frame as IDisposable)?.Dispose(); break; } - try { await _events.Writer.WriteAsync(new FrameEvent(frame, bytes), _stop.Token).ConfigureAwait(false); } + try { await _events.Writer.WriteAsync(new FrameEvent(frame, bytes, receivedTimestamp), attemptStop).ConfigureAwait(false); } catch { Interlocked.Add(ref _frameBytes, -bytes); (frame as IDisposable)?.Dispose(); throw; } } } catch (Exception) { } - finally { _events.Writer.TryWrite(new EndEvent()); } + finally { try { await _events.Writer.WriteAsync(new EndEvent(), attemptStop).ConfigureAwait(false); } catch (OperationCanceledException) { } } } private DataSubscriptionItem Item(Registration registration) => new(registration.Id, registration.Demand.OriginView, new DataSubscriptionSettings(_key.Interval, _key.Interval, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataChangeTrigger.StatusValueTimestamp, null)); private async Task RunAsync() { - IGrpcDataAdapterConnectionLease? connection = null; IDataSubscription? stream = null; Task? pump = null; - var opened = false; var inSnapshot = false; long snapshotBytes = 0; - var pending = new List<(Registration Registration, ProjectedValueUpdate Update, long Version)>(); try { - connection = await _owner._connections.AcquireAsync(_connectionId, _stop.Token).ConfigureAwait(false); + var delay = TimeSpan.FromMilliseconds(100); + while (!_stop.IsCancellationRequested) + { + ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.Attempt); + Interlocked.Exchange(ref _healthyBaseline, 0); + await RunAttemptAsync().ConfigureAwait(false); + if (_stop.IsCancellationRequested) break; + if (Volatile.Read(ref _healthyBaseline) != 0) delay = TimeSpan.FromMilliseconds(100); + try { await RenewInvalidDemandsAsync().ConfigureAwait(false); } + catch (Exception ex) when (ex is not OutOfMemoryException && !_stop.IsCancellationRequested) + { /* A failed renewal is retried under the same bounded cohort. */ } + bool any; + lock (_owner._sync) + { + any = _owner._demandCohorts.Any(x => ReferenceEquals(x.Value, this)); + if (!any) Stop(); // Close under admission lock before a new item can join. + } + if (!any) break; + // Each physical retry samples independently; keep the delay bounded + // even at the exponential-backoff ceiling. + var minimum = delay.TotalMilliseconds * 0.8; + var maximum = Math.Min(5000, delay.TotalMilliseconds * 1.2); + var randomized = _owner.RetryJitterForTests?.Invoke(delay) ?? + TimeSpan.FromMilliseconds(minimum + Random.Shared.NextDouble() * (maximum - minimum)); + var retryDelay = TimeSpan.FromMilliseconds(Math.Clamp(randomized.TotalMilliseconds, 1, 5000)); + await Task.Delay(retryDelay, _stop.Token).ConfigureAwait(false); + delay = TimeSpan.FromMilliseconds(Math.Min(5000, delay.TotalMilliseconds * 2)); + } + } + catch (OperationCanceledException) when (_stop.IsCancellationRequested) { } + finally + { + Stop(); + Demand[] owned; var retired = new List(); + lock (_owner._sync) + { + owned = _owner._demandCohorts.Where(x => ReferenceEquals(x.Value, this)).Select(x => x.Key).ToArray(); + if (_owner._cohorts.TryGetValue(_key, out var current) && ReferenceEquals(current, this)) _owner._cohorts.Remove(_key); + foreach (var item in owned) + { + _owner._demandCohorts.Remove(item); + if (_owner._demandSourceKeys.Remove(item, out var sourceKey) && + _owner.ReleaseSourceOwnerLocked(sourceKey) is { } state) retired.Add(state); + } + } + foreach (var source in retired) source.Invalidate(); + foreach (var item in owned) { item.Dispose(); item.ReleaseHold(); } + _stop.Dispose(); + } + } + private async Task RenewInvalidDemandsAsync() + { + Demand[] owned; + (Demand Demand, SourceState Source)[] sources; + lock (_owner._sync) + { + owned = _owner._demandCohorts.Where(x => ReferenceEquals(x.Value, this)).Select(x => x.Key).ToArray(); + sources = owned.Select(demand => (Demand: demand, Source: _owner._demandSourceKeys.TryGetValue(demand, out var key) && + _owner._sources.TryGetValue(key, out var source) ? source : null)) + .Where(item => item.Source is not null).Select(item => (item.Demand, item.Source!)).ToArray(); + } + // A stopped stream need not evaluate source validity again. Drop only the + // source-owned expired predecessor before trying to reserve its successor. + foreach (var source in sources.Select(item => item.Source).Distinct()) source.ReleaseExpiredPredecessor(); + // A different cadence may still own the predecessor's pin. Park only that + // expired demand on the already charged successor; this grants no authority. + foreach (var item in sources) + { + var expected = item.Demand.CurrentBinding; + if (expected.RecoveryOnly || !item.Source.TryPrepareRecoveryParking(expected, out var parked) || parked is null) continue; + bool installed; + lock (_owner._sync) + installed = !_owner._disposed && _owner._demandCohorts.TryGetValue(item.Demand, out var current) && + ReferenceEquals(current, this) && _owner._demandSourceKeys.TryGetValue(item.Demand, out var key) && + _owner._sources.TryGetValue(key, out var currentSource) && ReferenceEquals(currentSource, item.Source) && + item.Demand.TryInstallBinding(expected, parked); + var release = installed ? expected : parked; + release.NodePin.Dispose(); release.Pin.Dispose(); + } + var requireNewServing = Interlocked.Exchange(ref _servingMismatch, 0) != 0; + var prepared = new List<(Demand Demand, Demand.Binding Old, Demand.Binding Next)>(); + try + { + foreach (var demand in owned) + { + if (_stop.IsCancellationRequested) return; + if (demand.Disposed) { ReleaseDemand(demand); continue; } + if (demand.IsValid && !requireNewServing) continue; + var old = demand.CurrentBinding; + using var demandStop = CancellationTokenSource.CreateLinkedTokenSource(_stop.Token, demand.CancellationToken); + var attempted = false; + if (requireNewServing && _owner._catalog is RemoteNamespaceResolver refresh && _owner._renewalSink is { } refreshSink) + { + attempted = true; + await RenewOwnedAsync(demand, old, refresh, refreshSink, demandStop.Token).ConfigureAwait(false); + } + if (!demand.TryPrepareBinding(old, out var replacement) || replacement is null) + { + if (attempted || _owner._catalog is not RemoteNamespaceResolver resolver || _owner._renewalSink is null) continue; + if (!await RenewOwnedAsync(demand, old, resolver, _owner._renewalSink, demandStop.Token).ConfigureAwait(false) || + !demand.TryPrepareBinding(old, out replacement) || replacement is null) continue; + } + if (requireNewServing && replacement.Proof.Lease.Serving == _key.Serving) + { replacement.NodePin.Dispose(); replacement.Pin.Dispose(); continue; } + prepared.Add((demand, old, replacement)); + } + var installed = new HashSet(); + var retired = new List(); + var groups = prepared.GroupBy(item => new CohortKey(_key.Connection, item.Next.Proof.Lease.Serving, _key.Interval)) + .Select(group => (Key: group.Key, Items: group.ToArray(), + Members: group.Select(item => item.Demand).ToHashSet(System.Collections.Generic.ReferenceEqualityComparer.Instance))).ToArray(); + lock (_owner._sync) + { + var survivors = _owner._demandCohorts.Where(x => ReferenceEquals(x.Value, this) && !x.Key.Disposed).Select(x => x.Key).ToArray(); + foreach (var group in groups) + { + if (_owner._disposed) break; + var targetKey = group.Key; + Cohort? target; + var created = false; + if (targetKey == _key) target = this; + else if (!_owner._cohorts.TryGetValue(targetKey, out target)) + { + if (_owner._cohorts.Count < _owner._limits.MaxStreams) + { + target = new Cohort(_owner, targetKey, _connectionId); + _owner._cohorts.Add(targetKey, target); created = true; + } + else + { + // A drained cohort can change serving in-place when every one + // of its surviving demands has the same verified new target. + if (survivors.Length == 0 || survivors.Any(d => !group.Members.Contains(d))) continue; + _owner._cohorts.Remove(_key); _key = targetKey; _owner._cohorts.Add(_key, this); target = this; + } + } + if (target is null || target.Closing) continue; + var moved = 0; + foreach (var item in group.Items) + { + if (!_owner._demandCohorts.TryGetValue(item.Demand, out var current) || !ReferenceEquals(current, this) || + item.Demand.Disposed || target != this && !target.Add(item.Demand) || !item.Demand.TryInstallBinding(item.Old, item.Next)) continue; + var oldKey = _owner._demandSourceKeys[item.Demand]; + var nextKey = new SourceKey(targetKey.Connection, item.Next.Proof.OriginMetadata.View, targetKey.Serving, + item.Next.Proof.Generation, item.Next.Definition.Realm, item.Next.Definition.LocalIdentifier); + if (oldKey != nextKey) + { + _owner.AddSourceOwnerLocked(nextKey); + if (_owner.ReleaseSourceOwnerLocked(oldKey) is { } source) retired.Add(source); + _owner._demandSourceKeys[item.Demand] = nextKey; + } + _owner._demandCohorts[item.Demand] = target; + installed.Add(item.Demand); moved++; + } + if (created && moved == 0) _owner._cohorts.Remove(targetKey); + else if (target != this && moved != 0) target.Start(); + } + } + foreach (var source in retired) source.Invalidate(); + foreach (var item in prepared) + { + var dispose = installed.Contains(item.Demand) ? item.Old : item.Next; + dispose.NodePin.Dispose(); dispose.Pin.Dispose(); + } + prepared.Clear(); + } + finally { foreach (var item in prepared) { item.Next.NodePin.Dispose(); item.Next.Pin.Dispose(); } } + } + private async Task RenewOwnedAsync(Demand demand, Demand.Binding old, RemoteNamespaceResolver resolver, + IProjectedNamespacePageSink sink, CancellationToken cancellationToken, bool overlap = false) + { + var timeout = TimeSpan.FromSeconds(5); + if (overlap && old.Proof.Lease is BoundProjectionLease authority) + { + var remaining = authority.Remaining; + if (remaining <= TimeSpan.FromMilliseconds(1)) return false; + timeout = TimeSpan.FromTicks(Math.Min(timeout.Ticks, remaining.Ticks - remaining.Ticks / 4)); + } + var budget = new DataBudget(timeout, 1, _owner._limits.MaxUnaryBytes); + lock (_owner._sync) + { + if (_owner._disposed || demand.Disposed || _owner._unaryCount >= _owner._limits.MaxUnaryOperations || + budget.MaxBytes > _owner._limits.MaxUnaryBytes - _owner._unaryBytes) return false; + _owner._unaryCount++; _owner._unaryBytes += budget.MaxBytes; + } + try + { + return await resolver.RenewExactAsync(old.Proof, old.Definition, demand.NodeId, demand.Caller, + demand.Configured, sink, budget, () => !demand.Disposed && (!overlap || + ReferenceEquals(demand.CurrentBinding, old) && demand.IsValid), cancellationToken, overlap).ConfigureAwait(false); + } + finally { lock (_owner._sync) { _owner._unaryCount--; _owner._unaryBytes -= budget.MaxBytes; } } + } + private async Task RunAttemptAsync() + { + IGrpcDataAdapterConnectionLease? connection = null; IDataSubscription? stream = null; Task? pump = null; + CancellationTokenSource? route = null; + ITimer? freshnessTimer = null, renewalTimer = null; + using var attemptStop = CancellationTokenSource.CreateLinkedTokenSource(_stop.Token); + var evidence = new Dictionary>(); + var demandSources = new Dictionary(); + var renewals = new Dictionary(); + var renewalQueued = 0; + var pendingCommands = new Dictionary(); + var snapshotQueue = new Queue>(); + HashSet? snapshotOwners = null; + void EnqueueSnapshot(HashSet owners) + { + if ((long)snapshotQueue.Count >= (long)_owner._limits.MaxDemands + 1) + throw new InvalidDataException("Too many pending snapshot boundaries."); + snapshotQueue.Enqueue(owners); + } + _id = Guid.NewGuid().ToString("N"); _epoch = checked(_epoch + 1); _sequence = 0; + _registrations.Clear(); _byId.Clear(); _byHandle.Clear(); _removing.Clear(); + Interlocked.Exchange(ref _freshnessQueued, 0); + string? challengeId = null; + long challengeSequence = 0; + var opened = false; var inSnapshot = false; long snapshotBytes = 0; + var pending = new List<(Registration Registration, ProjectedValueUpdate Update, long Version)>(); + AttemptProof EvidenceFor(SourceState source, ProjectedNodeProof proof) + { + if (!evidence.TryGetValue(source, out var witnesses)) evidence[source] = witnesses = []; + foreach (var expired in witnesses.Where(witness => !witness.LeaseValid).ToArray()) { expired.Close(); witnesses.Remove(expired); } + var existing = witnesses.Find(witness => witness.Matches(proof)); + if (existing is not null) return existing; + if (witnesses.Count >= 2) throw new InvalidDataException("Too many overlapping authority witnesses."); + var created = new AttemptProof(source, proof); witnesses.Add(created); return created; + } + void TrackSource(Demand demand) + { + var source = _owner.GetSource(demand, _connectionId) ?? throw new InvalidDataException("Source unavailable."); + EvidenceFor(source, demand.Proof); + demandSources[demand] = source; + } + void UntrackSource(Demand demand, bool preserve = false) + { + if (!demandSources.Remove(demand, out var source)) return; + if (_registrations.Values.Any(other => other.HasBaseline && demandSources.TryGetValue(other.Demand, out var retained) && ReferenceEquals(retained, source))) return; + if (preserve) return; + if (evidence.Remove(source, out var witnesses)) foreach (var proof in witnesses) proof.Close(); + } + async Task ChallengeAsync(CancellationToken token) + { + if (challengeId is not null || stream is not IDataSubscriptionFreshnessSupport { SupportsFreshnessChallenges: true } support) return; + var chosen = _registrations.Values.Where(x => x.NeedsChallenge && !x.Removed && x.Demand.IsValid && x.Handle is not null) + .Take(Math.Min(128, support.FreshnessMaxItems)).ToArray(); + if (chosen.Length == 0) return; + foreach (var item in chosen) item.NeedsChallenge = false; + challengeId = "freshness-" + checked(++challengeSequence).ToString(System.Globalization.CultureInfo.InvariantCulture); + await stream.SendAsync(new ChallengeSubscriptionFreshness(_id, _epoch, challengeId, TimeSpan.FromSeconds(5), + chosen.Select(x => x.Handle!).ToArray()), token).ConfigureAwait(false); + } + async Task RenewAsync(Demand demand, Demand.Binding expected, CancellationToken token) + { + var success = false; + try + { + if (_owner._catalog.TryResolveProjected(expected.Definition.Realm, expected.Definition.LocalIdentifier, out var current) && + current is not null && !ReferenceEquals(current, expected.Proof) && _owner._catalog.IsUsableProof(expected.Proof) && + _owner._nodes.TryResolve(demand.NodeId, out var definition) && definition is not null && + RemoteNamespaceResolver.DefinitionOwnsProof(definition, current)) success = true; + else if (_owner._catalog is RemoteNamespaceResolver resolver && _owner._renewalSink is { } sink) + { + using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, demand.CancellationToken); + success = await RenewOwnedAsync(demand, expected, resolver, sink, linked.Token, overlap: true).ConfigureAwait(false); + } + await _events.Writer.WriteAsync(new RenewedEvent(demand, expected, success), token).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OutOfMemoryException) { } + } + try + { + Demand[] initial; + lock (_owner._sync) initial = _owner._demandCohorts.Where(x => ReferenceEquals(x.Value, this)).Select(x => x.Key).ToArray(); + foreach (var demand in initial) if (demand.Disposed) ReleaseDemand(demand); + initial = initial.Where(demand => !demand.Disposed && demand.IsValid && demand.Serving == _key.Serving).ToArray(); + if (initial.Length == 0) return; + connection = await _owner._connections.AcquireAsync(_connectionId, attemptStop.Token).ConfigureAwait(false); if (connection is null || !ReferenceEquals(connection.Connection.Clock, _owner.Clock) || connection.CancellationToken.IsCancellationRequested) return; - using var route = CancellationTokenSource.CreateLinkedTokenSource(_stop.Token, connection.CancellationToken); + route = CancellationTokenSource.CreateLinkedTokenSource(attemptStop.Token, connection.CancellationToken); stream = await connection.Connection.SubscribeAsync(route.Token).ConfigureAwait(false); - if (stream is not IDataSubscriptionProvenance provenance || provenance.Serving != _key.Serving) return; - pump = PumpAsync(stream); + if (stream is not IDataSubscriptionProvenance provenance || provenance.Serving != _key.Serving) + { Interlocked.Exchange(ref _servingMismatch, 1); return; } + freshnessTimer = _owner.Clock.CreateTimer(_ => + { + if (Interlocked.Exchange(ref _freshnessQueued, 1) == 0 && !_events.Writer.TryWrite(new FreshnessEvent())) + Interlocked.Exchange(ref _freshnessQueued, 0); + }, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5)); + var minimumLease = initial.Select(d => (d.Proof.Lease as BoundProjectionLease)?.UsableDuration ?? TimeSpan.FromSeconds(1)).Min(); + var renewalInterval = TimeSpan.FromTicks(Math.Max(TimeSpan.TicksPerMillisecond, + Math.Min(TimeSpan.FromMilliseconds(250).Ticks, minimumLease.Ticks / 4))); + renewalTimer = _owner.Clock.CreateTimer(_ => + { + if (Interlocked.Exchange(ref renewalQueued, 1) == 0 && !_events.Writer.TryWrite(new RenewalEvent())) + Interlocked.Exchange(ref renewalQueued, 0); + }, null, renewalInterval, renewalInterval); + pump = PumpAsync(stream, route.Token); + foreach (var demand in initial) + { + if (demand.Disposed) { ReleaseDemand(demand); continue; } + if (!demand.IsValid) continue; + TrackSource(demand); + var registration = new Registration(demand, Guid.NewGuid().ToString("N")) { Recovery = _epoch > 1 }; + _registrations[demand] = registration; _byId[registration.Id] = registration; + var commandId = Guid.NewGuid().ToString("N"); pendingCommands.Add(commandId, registration); + DataSubscriptionCommand command = !opened + ? new OpenSubscription(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [Item(registration)], false, TimeSpan.FromMinutes(1), new(TimeSpan.FromSeconds(5), 1, _owner._limits.MaxUnaryBytes)) + : new AddSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [Item(registration)]); + await stream.SendAsync(command, route.Token).ConfigureAwait(false); opened = true; + } + // A temporarily unavailable proof must not leave an unopened stream parked + // forever. Retry the bounded attempt after backoff so renewal can make it usable. + if (!opened) return; await foreach (var message in _events.Reader.ReadAllAsync(route.Token).ConfigureAwait(false)) { if (message is AddEvent add) { + lock (_owner._sync) + if (!_owner._demandCohorts.TryGetValue(add.Demand, out var owner) || !ReferenceEquals(owner, this)) continue; + if (_registrations.ContainsKey(add.Demand)) continue; + if (add.Demand.Disposed) { ReleaseDemand(add.Demand); continue; } if (!add.Demand.IsValid) continue; + TrackSource(add.Demand); var registration = new Registration(add.Demand, Guid.NewGuid().ToString("N")); _registrations[add.Demand] = registration; _byId[registration.Id] = registration; + if (renewalTimer is not null && add.Demand.Proof.Lease is BoundProjectionLease addedLease) + { + var nextInterval = TimeSpan.FromTicks(Math.Max(TimeSpan.TicksPerMillisecond, + Math.Min(TimeSpan.FromMilliseconds(250).Ticks, addedLease.UsableDuration.Ticks / 4))); + if (nextInterval < renewalInterval) { renewalInterval = nextInterval; renewalTimer.Change(nextInterval, nextInterval); } + } + var commandId = Guid.NewGuid().ToString("N"); pendingCommands.Add(commandId, registration); DataSubscriptionCommand command = !opened - ? new OpenSubscription(_id, Epoch, Guid.NewGuid().ToString("N"), TimeSpan.FromSeconds(5), [Item(registration)], false, TimeSpan.FromMinutes(1), new(TimeSpan.FromSeconds(5), 1, _owner._limits.MaxUnaryBytes)) - : new AddSubscriptionItems(_id, Epoch, Guid.NewGuid().ToString("N"), TimeSpan.FromSeconds(5), [Item(registration)]); + ? new OpenSubscription(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [Item(registration)], false, TimeSpan.FromMinutes(1), new(TimeSpan.FromSeconds(5), 1, _owner._limits.MaxUnaryBytes)) + : new AddSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [Item(registration)]); await stream.SendAsync(command, route.Token).ConfigureAwait(false); opened = true; } + else if (message is RefreshEvent refresh) + { + if (!_registrations.TryGetValue(refresh.Demand, out var registration) || !refresh.Demand.IsValid) + { FinishRefresh(refresh.Demand); continue; } + if (registration.Removed) + { + // A renewal (or an earlier refresh) already owns the remove/add + // barrier and its complete baseline satisfies this request. + if (!registration.Rebinding) FinishRefresh(refresh.Demand); + continue; + } + registration.Removed = true; registration.Rebinding = true; + if (registration.Handle is { } handle) + { + var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration; + await stream.SendAsync(new RemoveSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [handle]), route.Token).ConfigureAwait(false); + } + } else if (message is RemoveEvent remove) { + FinishRefresh(remove.Demand); if (_registrations.TryGetValue(remove.Demand, out var registration)) { - registration.Removed = true; - if (registration.Handle is { } handle) + registration.Rebinding = false; + if (!registration.Removed) { - var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration; - await stream.SendAsync(new RemoveSubscriptionItems(_id, Epoch, commandId, TimeSpan.FromSeconds(5), [handle]), route.Token).ConfigureAwait(false); + registration.Removed = true; + if (registration.Handle is { } handle) + { + var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration; + await stream.SendAsync(new RemoveSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [handle]), route.Token).ConfigureAwait(false); + } } } - if (_registrations.Values.All(x => x.Removed)) break; + else ReleaseDemand(remove.Demand); + if (_registrations.Values.All(x => x.Removed && !x.Rebinding)) break; + } + else if (message is FreshnessEvent) + { + Interlocked.Exchange(ref _freshnessQueued, 0); + if (_registrations.Values.Any(x => !x.Removed && !x.Demand.IsValid)) break; + foreach (var registration in _registrations.Values) registration.NeedsChallenge = true; + await ChallengeAsync(route.Token).ConfigureAwait(false); + } + else if (message is RenewalEvent) + { + Interlocked.Exchange(ref renewalQueued, 0); + if (_registrations.Values.Any(registration => registration.Renewal && + registration.RenewalPredecessor is not { IsValid: true })) + throw new InvalidDataException("The predecessor expired before its successor baseline completed."); + foreach (var witnesses in evidence.Values) + foreach (var expired in witnesses.Where(proof => !proof.LeaseValid).ToArray()) { expired.Close(); witnesses.Remove(expired); } + foreach (var registration in _registrations.Values.ToArray()) + { + var demand = registration.Demand; + if (registration.Removed || renewals.ContainsKey(demand) || !demand.IsValid || + demand.Proof.Lease is not BoundProjectionLease lease || lease.RouteIdentity is null || + lease.Remaining <= TimeSpan.Zero || lease.Remaining > lease.UsableDuration / 2) continue; + var expected = demand.CurrentBinding; + renewals[demand] = RenewAsync(demand, expected, route.Token); + } + } + else if (message is RenewedEvent renewed) + { + renewals.Remove(renewed.Demand); + if (!renewed.Success || !_registrations.TryGetValue(renewed.Demand, out var registration) || registration.Removed || + !ReferenceEquals(renewed.Demand.CurrentBinding, renewed.Expected) || !renewed.Demand.IsValid || + !renewed.Demand.TryPrepareBinding(renewed.Expected, out var replacement) || replacement is null) continue; + if (!RemoteNamespaceResolver.DefinitionOwnsProof(replacement.Definition, replacement.Proof)) + { replacement.NodePin.Dispose(); replacement.Pin.Dispose(); continue; } + var installed = false; + lock (_owner._sync) + { + if (!_owner._disposed && _owner._demandCohorts.TryGetValue(renewed.Demand, out var owner) && ReferenceEquals(owner, this)) + installed = renewed.Demand.TryInstallBinding(renewed.Expected, replacement); + } + if (!installed) { replacement.NodePin.Dispose(); replacement.Pin.Dispose(); continue; } + renewed.Expected.NodePin.Dispose(); renewed.Expected.Pin.Dispose(); + registration.Removed = true; registration.Rebinding = true; registration.Renewal = true; + registration.RenewalPredecessor = renewed.Expected.Proof.Lease; + if (registration.Handle is { } handle) + { + var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration; + await stream.SendAsync(new RemoveSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [handle]), route.Token).ConfigureAwait(false); + } } else if (message is EndEvent) break; else if (message is FrameEvent delivered) { var frame = delivered.Frame; + ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.Frame); try { - if (frame.SubscriptionId != _id || frame.StreamEpoch != Epoch || frame.Sequence <= _sequence) break; + if (frame.SubscriptionId != _id || frame.StreamEpoch != _epoch || frame.Sequence <= _sequence) break; _sequence = frame.Sequence; if (frame is DataSubscriptionAck ack) { - if (_removing.Remove(ack.CommandId, out var removed)) + if (ack.CommandId == challengeId) { - if (ack.Items.Count != 1 || ack.Items[0].Status != DataItemStatus.Good || ack.Items[0].Handle != removed.Handle || ack.Items[0].ClientItemId != removed.Id) { Stop(); continue; } + challengeId = null; + if (ack.Items.Any(x => x.Status != DataItemStatus.Good || x.Handle is null || + !_byHandle.TryGetValue(x.Handle, out var current) || current.Id != x.ClientItemId)) throw new InvalidDataException("Invalid freshness acknowledgement."); + EnqueueSnapshot(ack.Items.Select(x => _byHandle[x.Handle!]).ToHashSet()); + await ChallengeAsync(route.Token).ConfigureAwait(false); + } + else if (_removing.Remove(ack.CommandId, out var removed)) + { + if (ack.Items.Count != 1 || ack.Items[0].Status != DataItemStatus.Good || ack.Items[0].Handle != removed.Handle || ack.Items[0].ClientItemId != removed.Id) throw new InvalidDataException("Invalid removal acknowledgement."); _registrations.Remove(removed.Demand); _byId.Remove(removed.Id); if (removed.Handle is { } removedHandle) _byHandle.Remove(removedHandle); - SourceState? retiredSource = null; - lock (_owner._sync) + UntrackSource(removed.Demand, removed.Renewal); + if (removed.Rebinding && removed.Demand.IsValid) { - _owner._demandCohorts.Remove(removed.Demand); - if (!_registrations.Values.Any(x => !x.Removed && x.Demand.OriginView == removed.Demand.OriginView && x.Demand.ProjectionGeneration == removed.Demand.ProjectionGeneration)) - { - var sourceKey = new SourceKey(_key.Connection, removed.Demand.OriginView, _key.Serving, removed.Demand.ProjectionGeneration); - _owner.RemoveSourceLocked(sourceKey, out retiredSource); - } + var replacement = new Registration(removed.Demand, Guid.NewGuid().ToString("N")) + { Recovery = true, Renewal = removed.Renewal, RenewalPredecessor = removed.RenewalPredecessor }; + _registrations[removed.Demand] = replacement; _byId[replacement.Id] = replacement; + TrackSource(removed.Demand); + var commandId = Guid.NewGuid().ToString("N"); pendingCommands.Add(commandId, replacement); + await stream.SendAsync(new AddSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [Item(replacement)]), route.Token).ConfigureAwait(false); + continue; } - retiredSource?.Invalidate(); - removed.Demand.ReleaseHold(); + FinishRefresh(removed.Demand); + ReleaseDemand(removed.Demand); } - else foreach (var response in ack.Items) + else { - if (!_byId.TryGetValue(response.ClientItemId, out var registration) || response.Status != DataItemStatus.Good || response.Handle is null) { Stop(); break; } + if (!pendingCommands.Remove(ack.CommandId, out var expected) || ack.Items.Count != 1 || + ack.Items[0].ClientItemId != expected.Id) throw new InvalidDataException("Unexpected snapshot acknowledgement."); + var response = ack.Items[0]; + if (!_byId.TryGetValue(response.ClientItemId, out var registration) || response.Status != DataItemStatus.Good || response.Handle is null) throw new InvalidDataException("Invalid item acknowledgement."); registration.Handle = response.Handle; _byHandle[response.Handle] = registration; + EnqueueSnapshot([registration]); + registration.NeedsChallenge = true; + if (freshnessTimer is not null) + { + var milliseconds = Math.Clamp(_registrations.Values.Min(x => x.Demand.MaximumSampleAge.TotalMilliseconds) / 2, 50, 5000); + var interval = TimeSpan.FromMilliseconds(milliseconds); + freshnessTimer.Change(interval, interval); + } if (registration.Removed) { var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration; - await stream.SendAsync(new RemoveSubscriptionItems(_id, Epoch, commandId, TimeSpan.FromSeconds(5), [response.Handle]), route.Token).ConfigureAwait(false); + await stream.SendAsync(new RemoveSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [response.Handle]), route.Token).ConfigureAwait(false); } } + await ChallengeAsync(route.Token).ConfigureAwait(false); } else if (frame is DataSubscriptionControl control) { if (control.CatalogEpoch != _key.Serving.CatalogEpoch || control.AuthorityEpoch != _key.Serving.AuthorityEpoch) break; - if (control.Kind == DataStreamControlKind.SnapshotBegin) { inSnapshot = true; pending.Clear(); snapshotBytes = 0; } - else if (control.Kind == DataStreamControlKind.SnapshotEnd && inSnapshot) + if (control.Kind == DataStreamControlKind.SnapshotBegin) { - foreach (var item in pending) Publish(item.Registration, item.Update with { IsCompleteSnapshot = true }, item.Version); + if (inSnapshot) throw new InvalidDataException("Overlapping snapshots."); + if (!snapshotQueue.TryDequeue(out snapshotOwners)) throw new InvalidDataException("Snapshot has no acknowledged owner."); + inSnapshot = true; pending.Clear(); snapshotBytes = 0; + } + else if (control.Kind == DataStreamControlKind.SnapshotEnd) + { + ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.SnapshotEnd); + if (!inSnapshot) throw new InvalidDataException("Snapshot end without begin."); + foreach (var item in pending) + { + var accepted = Publish(item.Registration, item.Update with { IsCompleteSnapshot = true }, item.Version, out var validated); + if (!accepted && item.Registration.Recovery && item.Update.SourceProof is AttemptProof recoveryProof) + { + var recoverySource = recoveryProof.Source; + lock (recoverySource.Gate) + if (!item.Registration.Removed && recoverySource.TryRecoveryLocked(item.Registration.Demand, item.Registration.Renewal)) + validated = accepted = recoveryProof.Promote(); + } + if (item.Registration.Renewal && !accepted) + throw new InvalidDataException("Renewal requires an accepted fresh complete baseline."); + if (validated) item.Registration.HasBaseline = true; + if (item.Registration.Recovery) + { + if (accepted || validated) { item.Registration.Recovery = false; item.Registration.Renewal = false; item.Registration.RenewalPredecessor = null; FinishRefresh(item.Registration.Demand); } + else item.Registration.AwaitingCurrent = true; + } + } + foreach (var awaiting in snapshotOwners!) + if (!awaiting.Removed && !awaiting.HasBaseline) + { + if (awaiting.Renewal) throw new InvalidDataException("Renewal snapshot did not establish a complete baseline."); + awaiting.Recovery = true; awaiting.AwaitingCurrent = true; + } + snapshotOwners = null; pending.Clear(); snapshotBytes = 0; inSnapshot = false; } - else if (control.Kind is DataStreamControlKind.Reset or DataStreamControlKind.CatalogInvalidated or DataStreamControlKind.AuthorityInvalidated) break; + else if (control.Kind is DataStreamControlKind.Reset or DataStreamControlKind.CatalogInvalidated or DataStreamControlKind.AuthorityInvalidated) + { + ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.Reset); + ProjectedStreamDiagnostics.Count(control.Diagnostic switch + { + "Source change history expired." => ProjectedStreamDiagnostics.Event.ResetHistory, + "Source became unavailable." => ProjectedStreamDiagnostics.Event.ResetUnavailable, + "Snapshot catch-up expired; retry later." or "Snapshot lifetime expired; retry later." => ProjectedStreamDiagnostics.Event.ResetSnapshot, + _ => ProjectedStreamDiagnostics.Event.ResetOther + }); + break; + } } else if (frame is DataSubscriptionValues values) { foreach (var item in values.Items) { - if (!_byHandle.TryGetValue(item.Handle, out var registration) || registration.Removed || !registration.Demand.IsValid || - item.Sample.Serving != _key.Serving || item.Sample.Version <= 0 || item.Readiness != DataReadiness.Ready || - !item.AgeBounds.IsFresh(registration.Demand.MaximumSampleAge) || item.Sample.Value.EstimatedRetainedBytes > _owner._limits.MaxUnaryBytes) - { Stop(); break; } - var source = _owner.GetSource(registration.Demand, _connectionId); if (source is null) { Stop(); break; } + ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.Value); + if (!_byHandle.TryGetValue(item.Handle, out var registration)) throw new InvalidDataException("Unknown item handle."); + // Frames queued before a remove barrier may arrive while withdrawal is pending. + if (registration.Removed || !registration.Demand.IsValid) continue; + if (!values.IsSnapshot && registration.Renewal && !registration.HasBaseline) continue; + if (item.Sample.Serving != _key.Serving || item.Sample.Version <= 0 || item.Readiness != DataReadiness.Ready || + item.Sample.Value.EstimatedRetainedBytes > _owner._limits.MaxUnaryBytes) + throw new InvalidDataException("Invalid source sample."); + var ageTimestamp = item.FreshnessObservedTimestamp ?? delivered.ReceivedTimestamp; + if (!item.AgeBounds.Advance(_owner.Clock.GetElapsedTime(ageTimestamp, _owner.Clock.GetTimestamp())).IsFresh(registration.Demand.MaximumSampleAge)) + { ProjectedStreamDiagnostics.Count(item.AgeBounds.Upper is null ? ProjectedStreamDiagnostics.Event.UnknownAge : ProjectedStreamDiagnostics.Event.StaleAge); continue; } + ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.FreshAge); + var source = _owner.GetSource(registration.Demand, _connectionId); if (source is null) throw new InvalidDataException("Source unavailable."); + if (demandSources.TryGetValue(registration.Demand, out var priorSource) && !ReferenceEquals(priorSource, source)) + UntrackSource(registration.Demand); + demandSources[registration.Demand] = source; + var attemptProof = EvidenceFor(source, registration.Demand.Proof); var sample = item.Sample; var payload = DecodeValue(sample.Value, registration.Demand.Proof.OriginMetadata); var update = new ProjectedValueUpdate(source.Route, new DataValueSnapshot(payload, sample.StatusCode, sample.SourceTimestampUtc?.UtcDateTime, sample.ServerTimestampUtc?.UtcDateTime), - item.AgeBounds, _owner.Clock.GetTimestamp(), source, false, registration.Demand.MaximumSampleAge); - if (inSnapshot) + item.AgeBounds, ageTimestamp, attemptProof, false, registration.Demand.MaximumSampleAge, sample.Version); + if (values.IsSnapshot) { + if (!inSnapshot) throw new InvalidDataException("Snapshot value outside snapshot."); + if (snapshotOwners is null || !snapshotOwners.Contains(registration)) throw new InvalidDataException("Snapshot value belongs to another command."); snapshotBytes = checked(snapshotBytes + sample.Value.EstimatedRetainedBytes + 512); - if (pending.Count >= _owner._limits.MaxDemands || snapshotBytes > _owner._limits.MaxUnaryBytes) { Stop(); break; } + if (pending.Count >= _owner._limits.MaxDemands || snapshotBytes > _owner._limits.MaxUnaryBytes) throw new InvalidDataException("Snapshot capacity exceeded."); pending.Add((registration, update, sample.Version)); } - else Publish(registration, update, sample.Version); + else + { + // A sibling registration's coverage cannot make this + // handle ready before its own snapshot barrier ends. + if (!registration.HasBaseline && !registration.AwaitingCurrent) continue; + var recovery = registration.Recovery && registration.AwaitingCurrent; + var accepted = Publish(registration, recovery ? update with { IsCompleteSnapshot = true } : update, sample.Version, out var validated); + if (recovery && (accepted || validated)) + { registration.HasBaseline = true; registration.Recovery = false; registration.AwaitingCurrent = false; FinishRefresh(registration.Demand); } + } } } } @@ -659,62 +1593,81 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable } } } - catch (Exception) { } + catch (Exception ex) { ProjectedStreamDiagnostics.Count(ex is OperationCanceledException ? ProjectedStreamDiagnostics.Event.AttemptCanceled : ex is InvalidDataException ? ProjectedStreamDiagnostics.Event.AttemptInvalidData : ProjectedStreamDiagnostics.Event.AttemptOther); } finally { - Stop(); + foreach (var proof in evidence.Values.SelectMany(witnesses => witnesses)) proof.Close(); + try { if (route is not null) await route.CancelAsync().ConfigureAwait(false); } catch (Exception) { } + try { await attemptStop.CancelAsync().ConfigureAwait(false); } catch (Exception) { } + freshnessTimer?.Dispose(); + renewalTimer?.Dispose(); + try { await Task.WhenAll(renewals.Values).ConfigureAwait(false); } catch (Exception) { } try { if (stream is not null) await stream.DisposeAsync().ConfigureAwait(false); } catch (Exception) { } try { if (pump is not null) await pump.ConfigureAwait(false); } catch (Exception) { } try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); } catch (Exception) { } + route?.Dispose(); while (_events.Reader.TryRead(out var remaining)) if (remaining is FrameEvent f) { Interlocked.Add(ref _frameBytes, -f.Bytes); (f.Frame as IDisposable)?.Dispose(); } - Demand[] owned; var transferred = new HashSet(); var retired = new List(); - lock (_owner._sync) - { - owned = _owner._demandCohorts.Where(x => ReferenceEquals(x.Value, this)).Select(x => x.Key).ToArray(); - foreach (var item in owned) _owner._demandCohorts.Remove(item); - if (_owner._cohorts.TryGetValue(_key, out var current) && ReferenceEquals(current, this)) _owner._cohorts.Remove(_key); - foreach (var item in owned) - { - var sourceKey = new SourceKey(_key.Connection, item.OriginView, _key.Serving, item.ProjectionGeneration); - if (_owner.RemoveSourceLocked(sourceKey, out var state) && state is not null) retired.Add(state); - } - } - foreach (var source in retired) source.Invalidate(); - lock (_owner._sync) - { - if (Volatile.Read(ref _restart) != 0 && !_owner._disposed) - { - var eligible = owned.Where(d => !d.Disposed).ToArray(); - if (eligible.Length > 0 && !_owner._cohorts.ContainsKey(_key) && _owner._cohorts.Count < _owner._limits.MaxStreams) - { - var replacement = new Cohort(_owner, _key, _connectionId); _owner._cohorts.Add(_key, replacement); - foreach (var demand in eligible) - if (replacement.Add(demand)) { _owner._demandCohorts[demand] = replacement; transferred.Add(demand); } - if (transferred.Count > 0) replacement.Start(); else _owner._cohorts.Remove(_key); - } - } - } - foreach (var item in owned) if (!transferred.Contains(item)) { item.Dispose(); item.ReleaseHold(); } - _stop.Dispose(); + lock (_owner._sync) _refreshRequests.Clear(); } } - private void Publish(Registration registration, ProjectedValueUpdate update, long version) + private void ReleaseDemand(Demand demand) { - if (!registration.Demand.IsValid || update.SourceProof is not SourceState source) return; - lock (source.Gate) + SourceState? retired = null; + lock (_owner._sync) { - if (!source.IsValid || version <= source.LastVersion) return; - if (_owner._publisher.TryPublish([update])) source.LastVersion = version; else source.Invalidate(); + if (!_owner._demandCohorts.Remove(demand)) return; + if (_owner._demandSourceKeys.Remove(demand, out var key)) retired = _owner.ReleaseSourceOwnerLocked(key); } + retired?.Invalidate(); + demand.ReleaseHold(); + } + private bool Publish(Registration registration, ProjectedValueUpdate update, long version, out bool validated) + { + validated = false; + if (registration.Removed || !registration.Demand.IsValid || update.SourceProof is not AttemptProof proof) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishDemand); return false; } + var source = proof.Source; + if (!source.TryPrepareSuccessor(registration.Demand, out var successor)) return false; + try + { + if (successor is not null) _owner.BeforeSuccessorAdoptionForTests?.Invoke(); + lock (source.Gate) + { + if (successor is not null && !update.IsCompleteSnapshot) return false; + if (!update.OriginAgeBounds.Advance(_owner.Clock.GetElapsedTime(update.ReceivedTimestamp, _owner.Clock.GetTimestamp())) + .IsFresh(registration.Demand.MaximumSampleAge)) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishStale); return false; } + if (!source.IsValid || version < source.LastVersion || version == source.LastVersion && !update.IsCompleteSnapshot) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishVersion); return false; } + // A command or ACK only owns transport resources. Source coverage begins at + // the first validated complete baseline, never at an unacknowledged Open. + if (!proof.IsValid && (!update.IsCompleteSnapshot || !proof.Promote())) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishProof); return false; } + validated = update.IsCompleteSnapshot; + if (version == source.LastVersion && update.IsCompleteSnapshot && !registration.Recovery && + source.HasFreshCachedLocked(registration.Demand)) return false; + if (_owner._publisher.TryPublish([update])) + { + if (successor is not null) + { + if (!update.IsCompleteSnapshot || !source.TryAdoptSuccessor(successor, out var consumed)) { source.Invalidate(); return false; } + if (consumed) successor = null; + } + if (update.IsCompleteSnapshot && (update.Snapshot.StatusCode & 0xC0000000u) == 0) + Interlocked.Exchange(ref _healthyBaseline, 1); + source.LastVersion = version; source.CacheLocked(update, version); ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishAccepted); return true; + } + if (!ProjectedEvidenceRetirement.CanDrop(update.SourceProof)) source.Invalidate(); + else validated = false; + ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishSink); return false; + } + } + finally { if (successor is not null) { successor.NodePin.Dispose(); successor.Pin.Dispose(); } } } } public bool RequestFreshSnapshot(IProjectedDemandLease demand) { if (demand is not Demand item || item.RequestedOperation != DataOperations.Subscribe || !item.IsValid) return false; - lock (_sync) return !_disposed && _demandCohorts.TryGetValue(item, out var cohort) && cohort.Restart(); + lock (_sync) return !_disposed && _demandCohorts.TryGetValue(item, out var cohort) && cohort.Refresh(item); } public void Dispose() { @@ -726,7 +1679,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable lock (_sync) cohorts = _cohorts.Values.ToArray(); foreach (var cohort in cohorts) cohort.Stop(); SourceState[] sources; - lock (_sync) { sources = _sources.Values.ToArray(); _sources.Clear(); _sourcesByMapping.Clear(); _sourceSweep.Clear(); _sourceSweepNodes.Clear(); lock (_sourceRetirementGate) _pendingSourceRetirement.Clear(); } + lock (_sync) { sources = _sources.Values.ToArray(); _sources.Clear(); _sourcesByProjection.Clear(); _sourcesByMapping.Clear(); _sourceSweep.Clear(); _sourceSweepNodes.Clear(); lock (_sourceRetirementGate) _pendingSourceRetirement.Clear(); } foreach (var source in sources) source.Invalidate(); } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedMappingDeploymentRuntime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedMappingDeploymentRuntime.cs index bd20a8635..57867d25c 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedMappingDeploymentRuntime.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedMappingDeploymentRuntime.cs @@ -13,6 +13,11 @@ public sealed record ProjectedMappingPlacement(RemoteNamespaceMapping Mapping, D public sealed class ProjectedMappingDeploymentRuntime : IDisposable { private readonly object _gate = new(); + // Serializes placement transitions with the SDK anchor reconciler without holding + // the catalog gate across SDK calls or introducing SDK -> transition lock ordering. + internal object TransitionGate { get; } = new(); + private bool _suspended; + internal bool Suspended => Volatile.Read(ref _suspended); private readonly LocalCatalogCoordinator _coordinator; private readonly RemoteNamespaceResolver _resolver; private CatalogAttempt? _attempt; @@ -130,10 +135,12 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable internal void AttemptBegan(CatalogAttempt attempt) { bool changed; + lock (TransitionGate) lock (_gate) { if (_disposed || _attempt is not null && attempt.Epoch <= _attempt.Epoch) return; _attempt = attempt; + Volatile.Write(ref _suspended, true); Volatile.Write(ref _configuredStamp, new object()); _configuredCapabilities.Clear(); _staged = []; _connections = []; @@ -148,12 +155,14 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable internal void AttemptCompleted(CatalogAttempt attempt, bool completed) { IReadOnlyList published; + lock (TransitionGate) lock (_gate) { if (_disposed || !ReferenceEquals(_attempt, attempt)) return; Volatile.Write(ref _configuredStamp, new object()); _configuredCapabilities.Clear(); var catalog = completed ? _coordinator.MappingCatalog(attempt) : null; + var success = false; if (catalog is null || !catalog.IsActive) { _resolver.ApplyMappings([]); @@ -171,6 +180,7 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable if (current is null || !ReferenceEquals(current.MappingAuthority, catalog.MappingAuthority) || !catalog.IsActive) throw new InvalidOperationException("Catalog attempt changed during projection activation."); Volatile.Write(ref _active, Array.AsReadOnly(placements)); + success = true; } catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or OverflowException) { @@ -178,6 +188,7 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable Volatile.Write(ref _active, Array.Empty()); } } + Volatile.Write(ref _suspended, !success); _byMapping = _active.ToDictionary(x => x.Mapping.RemoteNamespaceMappingId, StringComparer.OrdinalIgnoreCase); published = CopyPlacements(_active); } @@ -233,10 +244,12 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable public void Dispose() { + lock (TransitionGate) lock (_gate) { if (_disposed) return; _disposed = true; + Volatile.Write(ref _suspended, false); Volatile.Write(ref _configuredStamp, new object()); _configuredCapabilities.Clear(); Volatile.Write(ref _active, Array.Empty()); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedStreamDiagnostics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedStreamDiagnostics.cs new file mode 100644 index 000000000..7a6418557 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedStreamDiagnostics.cs @@ -0,0 +1,13 @@ +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Bounded aggregate observations of projected stream admission and delivery. +public static class ProjectedStreamDiagnostics +{ + internal enum Event { AcquireInvalid, AcquireDefinition, AcquireAuthorization, AcquirePin, AcquireCapacity, AcquireStale, AcquireAccepted, AcquireException, + Attempt, Frame, Reset, SnapshotEnd, Value, UnknownAge, StaleAge, FreshAge, PublishDemand, PublishStale, PublishVersion, PublishProof, PublishSink, PublishAccepted, + AttemptCanceled, AttemptInvalidData, AttemptOther, ResetHistory, ResetUnavailable, ResetSnapshot, ResetOther } + private static readonly long[] Counts = new long[Enum.GetValues().Length]; + internal static void Count(Event value) => Interlocked.Increment(ref Counts[(int)value]); + /// Captures process-wide counters without source identifiers or payloads. + public static IReadOnlyDictionary Capture() => Enum.GetValues().ToDictionary(x => x.ToString(), x => Interlocked.Read(ref Counts[(int)x])); +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs index e1331ce4e..d52ccf107 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs @@ -1,8 +1,10 @@ using System.Collections.ObjectModel; +using NodeId = Opc.Ua.NodeId; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; @@ -94,7 +96,10 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => _cache.TryGetParent(request); public IProjectedPageGuard? CaptureParentGuard(ProjectedBrowseRequest request, ProjectedParentSnapshot expected) => _cache.CaptureParentGuard(request, expected); public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) => _cache.TryResolveProjected(realm, localId, out proof); + public bool IsUsableProof(ProjectedNodeProof proof) => _cache.IsUsableProof(proof); public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) => _cache.TryPinProjected(realm, localId, out pin); + internal bool TryPinExpiredRecoveryPair(ProjectedNodeProof previous, ProjectedNodeProof successor, out IDisposable? pin) => + _cache.TryPinExpiredRecoveryPair(previous, successor, out pin); public async Task PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(request); request.Budget.Validate(); request.Parent.Validate(); @@ -228,7 +233,8 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp return PreparedPage.Failed(ProjectionPageStatus.Unavailable); var maxLease = TimeSpan.FromMilliseconds(binding.Mapping.MetadataLeaseMilliseconds); var lease = new BoundProjectionLease(new MetadataAuthorityLease(serving, branch.Lease, request.RequestStartedTimestamp, maxLease, TimeSpan.Zero, Clock), - connection.CancellationToken, binding.LocalAuthority, _cache, request.MappingId, generation, () => IsCurrent(binding)); + connection.CancellationToken, binding.LocalAuthority, _cache, request.MappingId, generation, () => IsCurrent(binding), connection.RouteCurrent, + connection.RouteIdentity, connection.Connection.Target, binding); if (!lease.IsValid) return PreparedPage.Failed(ProjectionPageStatus.Unavailable); var parentScope = previousParent?.Subject.Scope ?? binding.LocalScope; var ancestry = previousParent?.Subject.LocalAncestry ?? binding.LocalAncestry; @@ -273,6 +279,130 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp { lock (_sync) return !_disposed && _mappings.TryGetValue(binding.Mapping.RemoteNamespaceMappingId, out var current) && ReferenceEquals(current, binding); } + + private sealed class ExactAuthority(ProjectedNodeProof proof) : IProjectedRetainedAuthority + { + private ProjectedNodeProof _proof = proof; + public long RetainedBytes { get; } = checked(2048L + ProjectedProofSize.Estimate(proof)); + internal void Adopt(ProjectedNodeProof committed) => Volatile.Write(ref _proof, committed); + internal bool IsFor(ProjectedNodeProof committed) => ReferenceEquals(Volatile.Read(ref _proof), committed); + public bool IsCurrent() + { + var proof = Volatile.Read(ref _proof); + try { return proof.Lease.IsValid && proof.Resolver.LocalAuthority.IsActive && + proof.Resolver.Resolve(proof.Metadata.View, proof.Subject).Kind == MappedSubjectResolutionKind.Mapped; } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; } + } + } + internal static bool DefinitionOwnsProof(ProjectedVariableDefinition definition, ProjectedNodeProof proof) => + definition.AuthorityIsCurrent.Target is ExactAuthority authority && authority.IsFor(proof) && authority.IsCurrent(); + + // Refresh exactly one already-owned projected item. This deliberately creates no Browse + // page, cursor or sibling visibility and does not create a physical subscription. + internal async Task RenewExactAsync(ProjectedNodeProof previous, ProjectedVariableDefinition definition, + NodeId nodeId, DataCallerIdentity? caller, ConfiguredProjectionCapability? configured, + IProjectedNamespacePageSink sink, DataBudget budget, Func demandActive, CancellationToken cancellationToken, bool overlap = false) + { + var mapping = previous.Metadata.View.MappingId; + if (mapping is null || previous.Subject.Scope.Segments.Count == 0) return false; + ProjectedMappingBinding binding; + lock (_sync) + { + if (_disposed || !_mappings.TryGetValue(mapping, out binding!)) return false; + } + bool CallerAllowed() => demandActive() && (configured is not null + ? configured.Matches(mapping, previous.Metadata.View, binding.LocalAuthority) + : caller is not null && _policy.IsCallerUsable(caller) && + _policy.AuthorizeLocal(caller, OpcUaOperation.CreateMonitoredItems, previous.Subject.Scope)); + if (!IsCurrent(binding) || !binding.LocalAuthority.IsActive || !CallerAllowed() || + previous.Metadata.View.MappingRevision != binding.Mapping.Revision || previous.Metadata.View.Realm != binding.Mapping.Realm || + previous.OriginMetadata.View.MappingId is not null || + previous.Subject.Scope.Kind != binding.LocalScope.Kind || + !string.Equals(previous.Subject.Scope.ClusterId, binding.LocalScope.ClusterId, StringComparison.OrdinalIgnoreCase) || + previous.Subject.Scope.Segments.Count < binding.LocalScope.Segments.Count || + !previous.Subject.Scope.Segments.Take(binding.LocalScope.Segments.Count).SequenceEqual(binding.LocalScope.Segments, StringComparer.Ordinal) || + !previous.Subject.LocalAncestry.SequenceEqual(binding.LocalAncestry, StringComparer.OrdinalIgnoreCase)) return false; + if (!await _fetchSlots.WaitAsync(0, cancellationToken).ConfigureAwait(false)) return false; + IGrpcDataAdapterConnectionLease? connection = null; + try + { + var started = Clock.GetTimestamp(); + using var timeout = new CancellationTokenSource(budget.Timeout, Clock); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token); + connection = await _source.AcquireAsync(binding.Mapping.DataConnectionId, linked.Token).ConfigureAwait(false); + if (connection is null || !ReferenceEquals(connection.Connection.Clock, Clock) || + !string.Equals(connection.Connection.Target.ExpectedClusterId, previous.OriginMetadata.View.Address.OriginClusterId, StringComparison.OrdinalIgnoreCase)) return false; + using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken); + var capabilities = await connection.Connection.GetCapabilitiesAsync(budget, route.Token).ConfigureAwait(false); + capabilities.Validate(); + var serving = capabilities.Serving; + var target = connection.Connection.Target; + if (!capabilities.MetadataItemLeases || capabilities.Readiness != DataReadiness.Ready || + (capabilities.Operations & DataOperations.Metadata) == 0 || serving.ServingGeneration <= 0 || + !(string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase) || + target.Mode == DataTargetMode.Node && target.Consistency == DataConsistency.ReadyReplica && string.Equals(serving.Role, "Secondary", StringComparison.OrdinalIgnoreCase))) return false; + var elapsed = Clock.GetElapsedTime(started, Clock.GetTimestamp()); + if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) return false; + var results = await connection.Connection.GetMetadataAsync(new([previous.OriginMetadata.View], + budget with { MaxItems = 1, Timeout = budget.Timeout - elapsed }), route.Token).ConfigureAwait(false); + elapsed = Clock.GetElapsedTime(started, Clock.GetTimestamp()); + if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout || linked.IsCancellationRequested) return false; + if (results.Count != 1 || results[0].CorrelationId != "0" || results[0].Status != DataItemStatus.Good || + results[0].Value is not { } metadata || results[0].Lease is not { } remoteLease || + metadata.View != previous.OriginMetadata.View || metadata.Serving != serving || metadata.CatalogRevision != serving.CatalogEpoch || + remoteLease.CatalogEpoch != serving.CatalogEpoch || remoteLease.AuthorityEpoch != serving.AuthorityEpoch || + remoteLease.Duration <= TimeSpan.Zero || remoteLease.Duration > capabilities.Limits.MaxMetadataLease || + metadata.BrowseName != previous.OriginMetadata.BrowseName || metadata.NodeKind != previous.OriginMetadata.NodeKind || + metadata.ValueKind != previous.OriginMetadata.ValueKind || metadata.ValueRank != previous.OriginMetadata.ValueRank || + metadata.ArrayElementKind != previous.OriginMetadata.ArrayElementKind || + !metadata.Dimensions.SequenceEqual(previous.OriginMetadata.Dimensions) || + (metadata.AllowedOperations & binding.Mapping.AllowedOperations & DataOperations.Subscribe) == 0 || + !IsCurrent(binding) || !CallerAllowed() || connection.CancellationToken.IsCancellationRequested) return false; + metadata.Validate(); remoteLease.Validate(); + var generation = _cache.CaptureGeneration(mapping); + var maximumLease = TimeSpan.FromMilliseconds(binding.Mapping.MetadataLeaseMilliseconds); + if (caller?.CredentialExpiresUtc is { } expiry) + { + var remaining = expiry - Clock.GetUtcNow(); + if (remaining <= TimeSpan.Zero) return false; + if (remaining < maximumLease) maximumLease = remaining; + } + var lease = new BoundProjectionLease(new MetadataAuthorityLease(serving, remoteLease, started, maximumLease, TimeSpan.Zero, Clock), + connection.CancellationToken, binding.LocalAuthority, _cache, mapping, generation, () => IsCurrent(binding), connection.RouteCurrent, + connection.RouteIdentity, connection.Connection.Target, binding); + var subject = previous.Subject with { Serving = serving, AllowedOperations = binding.Mapping.AllowedOperations & metadata.AllowedOperations, + WriteThrough = binding.Mapping.WriteThrough && metadata.Writable }; + var mapped = metadata with { View = previous.Metadata.View }; + var resolver = new MappedSubjectResolver([subject], serving.CatalogEpoch, binding.LocalAuthority); + var renewed = new ProjectedNodeProof(previous.LocalIdentifier, mapped, subject, resolver, lease, generation, metadata, + TimeSpan.FromMilliseconds(binding.Mapping.StaleTimeoutMilliseconds)); + var guard = new ExactAuthority(renewed); + if (!guard.IsCurrent() || caller is not null && !_policy.AuthorizeMapped(caller, OpcUaOperation.CreateMonitoredItems, + mapped.View, serving, subject, resolver, lease)) return false; + var newDefinition = new ProjectedVariableDefinition(definition.Realm, definition.LocalIdentifier, definition.Parent, + mapped, generation, guard.IsCurrent) { Lifetime = definition.Lifetime }; + return sink.TryRenewExact(nodeId, definition, newDefinition, () => + { + var duration = Clock.GetElapsedTime(started, Clock.GetTimestamp()); + if (linked.IsCancellationRequested || cancellationToken.IsCancellationRequested || connection.CancellationToken.IsCancellationRequested || + duration < TimeSpan.Zero || duration >= budget.Timeout || + !IsCurrent(binding) || !CallerAllowed() || !guard.IsCurrent()) return false; + ProjectedNodeProof? actual; + var committed = overlap ? _cache.TryRenewOverlap(previous, renewed, binding.Mapping.MaxProjectionNodes, out actual) : + _cache.TryRenewExact(previous, renewed, binding.Mapping.MaxProjectionNodes, out actual); + if (!committed || actual is null) return false; + guard.Adopt(actual); + return guard.IsCurrent(); + }); + } + catch (Exception ex) when (ex is not OutOfMemoryException) { return false; } + finally + { + try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); } + catch (Exception) { } + finally { _fetchSlots.Release(); } + } + } public void Dispose() { ProjectedMappingBinding[] old; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SamplePartition.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SamplePartition.cs index d86545d48..b7a6695ba 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SamplePartition.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SamplePartition.cs @@ -13,7 +13,10 @@ internal sealed class SamplePartition : IDisposable private readonly object _gate = new(); private readonly ConcurrentDictionary _sources = new(); private readonly Queue _queue = new(); - private readonly Dictionary _dirty = new(); + private readonly ConcurrentQueue _mailbox = new(); + private readonly ConcurrentQueue _dirty = new(); + private int _dirtyCount; + private int _producerState; // sign bit closes admission; remaining bits count active writers. private readonly LinkedList<(long Version, BackingSourceKey Key)> _changes = new(); private readonly Dictionary> _changeIndex = new(); private long _epoch = 1; @@ -82,7 +85,7 @@ internal sealed class SamplePartition : IDisposable state.Fence = fence; state.PartitionEpoch = _epoch; Volatile.Write(ref state.Gate, new SourceGate(ticket.Generation, ticket.Binding)); state.AppliedInvalidations = 0; - state.LastSubmitted = 0; state.LastApplied = 0; state.Barrier = 0; ReleaseCache(state); + state.LastApplied = 0; state.Barrier = 0; ReleaseCache(state); RecordChange(ticket.Key); return true; } var charge = SourceCharge(ticket.Key); @@ -147,63 +150,151 @@ internal sealed class SamplePartition : IDisposable _hub.Schedule(this); } Interlocked.Increment(ref gate.Invalidated); + Interlocked.Increment(ref gate.ProducerStamp); } finally { Control.EndQuiet(); } } + private static bool TryPin(SourceState state) + { + while (true) + { + if (Volatile.Read(ref state.RegistryRetired) != 0) return false; + var count = Volatile.Read(ref state.MetadataOwners); + if (count <= 0 || count == int.MaxValue) return false; + if (Interlocked.CompareExchange(ref state.MetadataOwners, count + 1, count) == count) return true; + } + } + private static bool TryIncrementBounded(ref int count, int maximum) + { + while (true) + { + var current = Volatile.Read(ref count); + if (current >= maximum) return false; + if (Interlocked.CompareExchange(ref count, current + 1, current) == current) return true; + } + } + private static bool TryAdvance(SourceGate gate, long sequence) + { + while (true) + { + var current = Interlocked.Read(ref gate.LastSubmitted); + if (sequence <= current) return false; + if (Interlocked.CompareExchange(ref gate.LastSubmitted, sequence, current) == current) return true; + } + } internal bool TryReserve(SourceTicket ticket, long estimated, out IIngressReservation? reservation) { reservation = null; - if (!Monitor.TryEnter(_gate)) { Signal(ticket); return false; } - try - { - if (_disposed || !Current(ticket, out var state)) return false; - if (estimated <= 0 || estimated > long.MaxValue - PartitionedSampleHub.SampleOverhead || - Volatile.Read(ref _reservations) >= _hub.Limits.MaxIngressItemsPerPartition + _hub.Limits.MaxDirtySourcesPerPartition || - !_hub.Resources.TryReserve(estimated + PartitionedSampleHub.SampleOverhead)) - { InvalidateSource(state); return false; } - Interlocked.Increment(ref _reservations); - Interlocked.Increment(ref state.Reservations); - Interlocked.Increment(ref state.MetadataOwners); - reservation = new Reservation(this, state, ticket, estimated, estimated + PartitionedSampleHub.SampleOverhead, - state.InvalidationVersion, _epoch, _hub.Clock.GetTimestamp()); - return true; - } - finally { Monitor.Exit(_gate); } + if (_hub.IsDisposed || Volatile.Read(ref _disposed) || _hub.RoutingEpoch != _routingEpoch || + !_sources.TryGetValue(ticket.Key, out var state) || !TryPin(state)) return false; + var gate = Volatile.Read(ref state.Gate); + var epoch = Interlocked.Read(ref _epoch); + var stamp = Interlocked.Read(ref gate.ProducerStamp); + var signal = Interlocked.Read(ref gate.Invalidated); + if (Volatile.Read(ref state.RegistryRetired) != 0 || !_sources.TryGetValue(ticket.Key, out var current) || + !ReferenceEquals(current, state) || !IsTicketCurrentNonBlocking(ticket) || + !ReferenceEquals(gate, Volatile.Read(ref state.Gate))) + { ReleaseMetadataOwner(state); return false; } + if (estimated <= 0 || estimated > long.MaxValue - PartitionedSampleHub.SampleOverhead || + !TryIncrementBounded(ref _reservations, (int)Math.Min(int.MaxValue, (long)_hub.Limits.MaxIngressItemsPerPartition + _hub.Limits.MaxDirtySourcesPerPartition))) + { ReleaseMetadataOwner(state); SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ReserveCapacity); Signal(ticket); return false; } + var charge = estimated + PartitionedSampleHub.SampleOverhead; + if (!_hub.Resources.TryReserve(charge)) + { Interlocked.Decrement(ref _reservations); ReleaseMetadataOwner(state); SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ReserveCapacity); Signal(ticket); return false; } + Interlocked.Increment(ref state.Reservations); + if (!IsTicketCurrentNonBlocking(ticket) || !ReferenceEquals(gate, Volatile.Read(ref state.Gate)) || + Interlocked.Read(ref _epoch) != epoch || Interlocked.Read(ref gate.ProducerStamp) != stamp || Interlocked.Read(ref gate.Invalidated) != signal) + { ReleaseReservation(state); _hub.Resources.Release(charge); return false; } + reservation = new Reservation(this, state, gate, ticket, estimated, charge, stamp, signal, epoch, _hub.Clock.GetTimestamp()); + return true; } - private bool Commit(SourceState reservedState, SourceTicket ticket, long estimate, long charge, long invalidationVersion, - long partitionEpoch, long receivedTimestamp, DataSample sample, long sequence) + private bool Commit(SourceState state, SourceGate gate, SourceTicket ticket, long estimate, long charge, long stamp, + long signal, long partitionEpoch, long receivedTimestamp, DataSample sample, long sequence) + { + if (!TryEnterProducer()) { ReleaseReservation(state); _hub.Resources.Release(charge); return false; } + if (Interlocked.CompareExchange(ref gate.Committing, 1, 0) != 0) + { + ReleaseReservation(state); _hub.Resources.Release(charge); Signal(ticket); ExitProducer(); return false; + } + try { return CommitEntered(state, gate, ticket, estimate, charge, stamp, signal, partitionEpoch, receivedTimestamp, sample, sequence); } + finally { Volatile.Write(ref gate.Committing, 0); ExitProducer(); } + } + private bool CommitEntered(SourceState state, SourceGate gate, SourceTicket ticket, long estimate, long charge, long stamp, + long signal, long partitionEpoch, long receivedTimestamp, DataSample sample, long sequence) { - if (!Monitor.TryEnter(_gate)) - { ReleaseReservation(reservedState); _hub.Resources.Release(charge); Signal(ticket); return false; } try { - ReleaseReservation(reservedState); - if (_disposed || !Current(ticket, out var state)) { _hub.Resources.Release(charge); return false; } - if (state.InvalidationVersion != invalidationVersion || _epoch != partitionEpoch) { _hub.Resources.Release(charge); return false; } - try - { - ArgumentNullException.ThrowIfNull(sample.Value); - ArgumentNullException.ThrowIfNull(sample.Serving); - sample.Serving.Validate(requireEpochs: false); - if (sequence <= state.LastSubmitted || sample.Version != sequence || sample.Value.EstimatedRetainedBytes > estimate || - sample.Serving.NodeId != ticket.Key.ServingNodeId || sample.Serving.Incarnation != ticket.Key.ServingIncarnation) - { _hub.Resources.Release(charge); InvalidateSource(state); return false; } - } - catch (Exception e) when (e is ArgumentException or ObjectDisposedException or OverflowException) - { _hub.Resources.Release(charge); InvalidateSource(state); return false; } - var pending = new Pending(ticket, sequence, ++_ordinal, sample, charge, receivedTimestamp) { AdmissionEpoch = state.InvalidationVersion, PartitionEpoch = partitionEpoch }; - if (_queuedValues < _hub.Limits.MaxIngressItemsPerPartition) - { _queue.Enqueue(pending); _queuedValues++; } - else if (_dirty.TryGetValue(ticket.Key, out var previous)) - { ReleasePending(previous); _dirty[ticket.Key] = pending; } - else if (_dirty.Count < _hub.Limits.MaxDirtySourcesPerPartition) _dirty.Add(ticket.Key, pending); - else { _hub.Resources.Release(charge); InvalidatePartition(); return false; } - state.LastSubmitted = sequence; - _hub.Schedule(this); - return true; + ArgumentNullException.ThrowIfNull(sample.Value); + ArgumentNullException.ThrowIfNull(sample.Serving); + sample.Serving.Validate(requireEpochs: false); + if (sample.Version != sequence || sample.Value.EstimatedRetainedBytes > estimate || + sample.Serving.NodeId != ticket.Key.ServingNodeId || sample.Serving.Incarnation != ticket.Key.ServingIncarnation) + throw new ArgumentException("Invalid ingress sample."); + } + catch (Exception e) when (e is ArgumentException or ObjectDisposedException or OverflowException) + { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.CommitInvalid); ReleaseReservation(state); _hub.Resources.Release(charge); Signal(ticket); return false; } + if (!IsTicketCurrentNonBlocking(ticket) || !ReferenceEquals(gate, Volatile.Read(ref state.Gate)) || + partitionEpoch != Interlocked.Read(ref _epoch) || stamp != Interlocked.Read(ref gate.ProducerStamp) || signal != Interlocked.Read(ref gate.Invalidated)) + { ReleaseReservation(state); _hub.Resources.Release(charge); return false; } + if (!TryAdvance(gate, sequence)) + { ReleaseReservation(state); _hub.Resources.Release(charge); Signal(ticket); return false; } + _hub.AfterValueSequenceForTests?.Invoke(); + var pending = new Pending(ticket, sequence, Interlocked.Increment(ref _ordinal), sample, charge, receivedTimestamp) + { PartitionEpoch = partitionEpoch, Owner = state, Gate = gate, ProducerStamp = stamp, SignalStamp = signal }; + var admitted = EnqueueValue(state, pending); + if (admitted != EnqueueResult.Accepted) + { + ReleaseReservation(state); _hub.Resources.Release(charge); + if (admitted == EnqueueResult.Capacity) InvalidatePartition(); + else Signal(ticket); + return false; + } + // The mailbox owns the metadata pin; the in-flight copy permit ends at transfer. + Interlocked.Decrement(ref _reservations); + var lastReservation = Interlocked.Decrement(ref state.Reservations) == 0; + if (lastReservation && Volatile.Read(ref state.Gate.Retired) != 0 && !Volatile.Read(ref _disposed)) RequestReclaim(); + _hub.Schedule(this); + return true; + } + private bool TryEnterProducer() + { + while (true) + { + var current = Volatile.Read(ref _producerState); + if (current < 0 || current == int.MaxValue) return false; + if (Interlocked.CompareExchange(ref _producerState, current + 1, current) == current) return true; + } + } + private void ExitProducer() + { + if (Interlocked.Decrement(ref _producerState) < 0) Schedule(); + } + private enum EnqueueResult { Accepted, Stale, Capacity } + private EnqueueResult EnqueueValue(SourceState state, Pending pending) + { + while (true) + { + var existing = Volatile.Read(ref state.Dirty); + if (existing is not null) + { + if (ReferenceEquals(existing.Gate, pending.Gate) && existing.Sequence >= pending.Sequence || + !ReferenceEquals(existing.Gate, pending.Gate) && existing.Gate is not null && pending.Gate is not null && + Compare(existing.Gate.Generation, pending.Gate.Generation) >= 0) return EnqueueResult.Stale; + if (Interlocked.CompareExchange(ref state.Dirty, pending, existing) != existing) continue; + ReleasePending(existing); return EnqueueResult.Accepted; + } + if (TryIncrementBounded(ref _queuedValues, _hub.Limits.MaxIngressItemsPerPartition)) + { + if (Volatile.Read(ref state.Dirty) is not null) { Interlocked.Decrement(ref _queuedValues); continue; } + _mailbox.Enqueue(pending); return EnqueueResult.Accepted; + } + if (!TryIncrementBounded(ref _dirtyCount, _hub.Limits.MaxDirtySourcesPerPartition)) + { if (Volatile.Read(ref state.Dirty) is not null) continue; return EnqueueResult.Capacity; } + if (Interlocked.CompareExchange(ref state.Dirty, pending, null) is null) + { _dirty.Enqueue(state); return EnqueueResult.Accepted; } + Interlocked.Decrement(ref _dirtyCount); } - finally { Monitor.Exit(_gate); } } private void ReleaseReservation(SourceState state) { @@ -213,7 +304,7 @@ internal sealed class SamplePartition : IDisposable if (lastReservation && Volatile.Read(ref state.Gate.Retired) != 0 && !Volatile.Read(ref _disposed)) RequestReclaim(); } private void Abandon(SourceState state, long charge) { ReleaseReservation(state); _hub.Resources.Release(charge); } - internal void Invalidate(SourceTicket ticket) => Signal(ticket); + internal void Invalidate(SourceTicket ticket) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ExternalInvalidate); Signal(ticket); } private void InvalidateSource(SourceState state) { Control.BeginQuiet(); @@ -227,13 +318,13 @@ internal sealed class SamplePartition : IDisposable try { var partitionEpoch = Interlocked.Read(ref _epoch); - if (_disposed || !Current(ticket, out var state) || sequence <= state.LastSubmitted) return false; + if (_disposed || !Current(ticket, out var state) || !TryAdvance(Volatile.Read(ref state.Gate), sequence)) return false; if (_queuedControls >= _hub.Limits.MaxControlItemsPerPartition || !_hub.Resources.TryReserve(ControlOverhead)) { InvalidatePartition(); return false; } var wasReady = state.Readiness == DataReadiness.Ready; Control.Begin(); - try { state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); state.Barrier = sequence; state.LastSubmitted = sequence; } + try { state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); Interlocked.Increment(ref state.Gate.ProducerStamp); state.Barrier = sequence; } finally { Control.End(); } - _queue.Enqueue(new Pending(ticket, sequence, ++_ordinal, status, source, server, wasReady, ControlOverhead) { AdmissionEpoch = state.InvalidationVersion, PartitionEpoch = partitionEpoch }); _queuedControls++; + _queue.Enqueue(new Pending(ticket, sequence, Interlocked.Increment(ref _ordinal), status, source, server, wasReady, ControlOverhead) { AdmissionEpoch = state.InvalidationVersion, PartitionEpoch = partitionEpoch }); _queuedControls++; _hub.Schedule(this); return true; } finally { Monitor.Exit(_gate); } @@ -246,17 +337,17 @@ internal sealed class SamplePartition : IDisposable // Retirement must still be able to release a source after its shared fence closed. if (_disposed || !_sources.TryGetValue(ticket.Key, out var state)) return false; ApplyGate(state); ApplyPartitionEpoch(state); - if (state.Removed || state.Ticket != ticket || Volatile.Read(ref state.Gate.Retired) != 0 || sequence <= state.LastSubmitted) return false; + if (state.Removed || state.Ticket != ticket || Volatile.Read(ref state.Gate.Retired) != 0 || !TryAdvance(Volatile.Read(ref state.Gate), sequence)) return false; Control.BeginQuiet(); try { if (_queuedControls >= _hub.Limits.MaxControlItemsPerPartition || !_hub.Resources.TryReserve(ControlOverhead)) { state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); RequestReclaim(); InvalidatePartition(); return false; } - state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); state.LastSubmitted = sequence; ReleaseCache(state); + state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); Interlocked.Increment(ref state.Gate.ProducerStamp); ReleaseCache(state); } finally { Control.EndQuiet(); } RequestReclaim(); - _queue.Enqueue(new Pending(ticket, sequence, ++_ordinal, ControlOverhead) { PartitionEpoch = _epoch }); _queuedControls++; + _queue.Enqueue(new Pending(ticket, sequence, Interlocked.Increment(ref _ordinal), ControlOverhead) { PartitionEpoch = _epoch }); _queuedControls++; _hub.Schedule(this); return true; } finally { Monitor.Exit(_gate); } @@ -273,38 +364,63 @@ internal sealed class SamplePartition : IDisposable finally { Volatile.Write(ref _scheduled, 0); - lock (_gate) if (!_disposed && (_cleanedEpoch != _epoch || Volatile.Read(ref _retiredSweepRequested) != 0 || Volatile.Read(ref _reclaimRequested) != 0 || _queue.Count != 0 || _dirty.Count != 0)) Schedule(); + lock (_gate) if ((!_disposed && (_cleanedEpoch != _epoch || Volatile.Read(ref _retiredSweepRequested) != 0 || Volatile.Read(ref _reclaimRequested) != 0 || _queue.Count != 0)) || !_mailbox.IsEmpty || !_dirty.IsEmpty) Schedule(); } } internal void Drain() { lock (_gate) { - CleanupInvalidatedEpoch(); - CleanupRetiredSources(); - while (!_disposed && (_queue.Count != 0 || _dirty.Count != 0)) + if (!_disposed) { CleanupInvalidatedEpoch(); CleanupRetiredSources(); } + // Controls present at entry cannot be replenished while this gate is held. Drain + // that finite bounded set first, then give values their own bounded work slice. + var controlsRemaining = _queue.Count; + var valueWork = 0; + while (controlsRemaining > 0 || valueWork < 128) { - Pending? dirty = null; - foreach (var value in _dirty.Values) if (dirty is null || value.Ordinal < dirty.Ordinal) dirty = value; - Pending p; - if (dirty is not null && (_queue.Count == 0 || dirty.Ordinal < _queue.Peek().Ordinal)) - { p = dirty; _dirty.Remove(p.Ticket.Key); } - else - { p = _queue.Dequeue(); if (p.IsControl) _queuedControls--; else _queuedValues--; } - if (p.PartitionEpoch != _epoch || !Current(p.Ticket, out var state) || p.AdmissionEpoch != state.InvalidationVersion || p.Sequence <= state.LastApplied) + Pending? p = null; + if (controlsRemaining > 0 && _queue.TryDequeue(out var control)) { controlsRemaining--; p = control; _queuedControls--; } + else if (++valueWork > 128) break; + else if (_mailbox.TryPeek(out var first)) + { + var dirtyFirst = _dirty.TryPeek(out var dirtyState) ? Volatile.Read(ref dirtyState.Dirty) : null; + if (dirtyFirst is not null && dirtyFirst.Ordinal < first.Ordinal) + { + if (!_dirty.TryDequeue(out dirtyState)) continue; + Interlocked.Decrement(ref _dirtyCount); + p = Interlocked.Exchange(ref dirtyState.Dirty, null); + } + else if (_mailbox.TryDequeue(out p)) Interlocked.Decrement(ref _queuedValues); + } + else if (_dirty.TryDequeue(out var dirtyState)) + { + Interlocked.Decrement(ref _dirtyCount); + p = Interlocked.Exchange(ref dirtyState.Dirty, null); + } + else break; + if (p is null) continue; + if (_disposed || p.PartitionEpoch != _epoch || + p.Owner is not null && (!ReferenceEquals(p.Gate, Volatile.Read(ref p.Owner.Gate)) || + p.Gate is null || p.ProducerStamp != Interlocked.Read(ref p.Gate.ProducerStamp) || p.SignalStamp != Interlocked.Read(ref p.Gate.Invalidated))) + { ReleasePending(p); continue; } + if (p.Owner is not null) _hub.BeforePendingValueCurrentForTests?.Invoke(); + if (!Current(p.Ticket, out var state) || p.IsControl && p.AdmissionEpoch != state.InvalidationVersion || p.Sequence <= state.LastApplied || + p.Owner is not null && (!ReferenceEquals(p.Owner, state) || p.PartitionEpoch != Interlocked.Read(ref _epoch) || + !ReferenceEquals(p.Gate, Volatile.Read(ref state.Gate)) || p.Gate is null || + p.ProducerStamp != Interlocked.Read(ref p.Gate.ProducerStamp) || p.SignalStamp != Interlocked.Read(ref p.Gate.Invalidated))) { ReleasePending(p); continue; } state.LastApplied = p.Sequence; if (p.Sample is not null) { ReleaseCache(state); state.Sample = p.Sample; state.SampleCharge = p.Charge; state.Received = p.Received; state.Readiness = p.Sequence < state.Barrier ? DataReadiness.Invalidated : DataReadiness.Ready; + if (p.Owner is not null) ReleaseMetadataOwner(p.Owner); } else { if (p.IsStatus && state.Sample is not null) { var old = state.Sample; - // Missing timestamps on a status-only event mean no new acquisition timestamp. state.Sample = old with { StatusCode = p.Status, SourceTimestampUtc = p.SourceTimestamp ?? old.SourceTimestampUtc, ServerTimestampUtc = p.ServerTimestamp ?? old.ServerTimestampUtc, Version = p.Sequence }; @@ -315,7 +431,17 @@ internal sealed class SamplePartition : IDisposable } RecordChange(p.Ticket.Key); } - ReclaimTombstones(); + if (!_disposed) ReclaimTombstones(); + } + } + // Deterministic fixture helper: production workers always use the fixed Drain slice. + internal void DrainForTests() + { + var maximum = (long)_hub.Limits.MaxIngressItemsPerPartition + _hub.Limits.MaxDirtySourcesPerPartition + _hub.Limits.MaxControlItemsPerPartition; + for (long work = 0; work <= maximum / 128 + 1; work++) + { + Drain(); + lock (_gate) if (_queue.Count == 0 && _mailbox.IsEmpty && _dirty.IsEmpty) return; } } private void RecordChange(BackingSourceKey key) @@ -328,6 +454,7 @@ internal sealed class SamplePartition : IDisposable } internal void InvalidatePartition() { + SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.PartitionInvalidated); Control.BeginQuiet(); try { Interlocked.Increment(ref _epoch); } finally { Control.EndQuiet(); } @@ -386,7 +513,7 @@ internal sealed class SamplePartition : IDisposable _hub.UntrackSource(); } private void ReleaseCache(SourceState state) { if (state.Sample is not null) { state.Sample.Dispose(); state.Sample = null; _hub.Resources.Release(state.SampleCharge); state.SampleCharge = 0; } } - private void ReleasePending(Pending p) { p.Sample?.Dispose(); _hub.Resources.Release(p.Charge); } + private void ReleasePending(Pending p) { p.Sample?.Dispose(); _hub.Resources.Release(p.Charge); if (p.Owner is not null) ReleaseMetadataOwner(p.Owner); } internal CachedSourceRead Read(SourceTicket ticket) => Read(ticket, out _); internal CachedSourceRead Read(SourceTicket ticket, out long watermark) @@ -396,12 +523,12 @@ internal sealed class SamplePartition : IDisposable watermark = _watermark; if (_disposed || !Current(ticket, out var state)) return _hub.EmptyRead(DataItemStatus.NotFound, DataReadiness.Unavailable, _epoch); if (state.Readiness != DataReadiness.Ready || state.Sample is null) - return _hub.EmptyRead(state.Readiness == DataReadiness.WaitingForInitialData ? DataItemStatus.WaitingForInitialData : DataItemStatus.Unavailable, state.Readiness, _epoch); + { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ReadNotReady); return _hub.EmptyRead(state.Readiness == DataReadiness.WaitingForInitialData ? DataItemStatus.WaitingForInitialData : DataItemStatus.Unavailable, state.Readiness, _epoch); } var gate = Volatile.Read(ref state.Gate); var signal = Volatile.Read(ref gate.Invalidated); - if (signal != state.AppliedInvalidations) return _hub.EmptyRead(DataItemStatus.Unavailable, DataReadiness.Invalidated, _epoch); + if (signal != state.AppliedInvalidations) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ReadInvalidated); return _hub.EmptyRead(DataItemStatus.Unavailable, DataReadiness.Invalidated, _epoch); } var charge = checked(state.Sample.Value.EstimatedRetainedBytes + PartitionedSampleHub.ReferenceOverhead); - if (!_hub.Resources.TryReserve(charge)) return _hub.EmptyRead(DataItemStatus.ResourceExhausted, DataReadiness.Unavailable, _epoch); + if (!_hub.Resources.TryReserve(charge)) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ReadExhausted); return _hub.EmptyRead(DataItemStatus.ResourceExhausted, DataReadiness.Unavailable, _epoch); } Interlocked.Increment(ref state.Readers); Interlocked.Increment(ref state.MetadataOwners); return new CachedSourceRead(_hub.Resources, DataItemStatus.Good, state.Readiness, @@ -477,15 +604,15 @@ internal sealed class SamplePartition : IDisposable scanned = 0; lock (_gate) { - if (_disposed || epoch != _epoch) return false; + if (_disposed || epoch != _epoch) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestEpoch); return false; } if (position == _watermark) return true; - if (!_changeIndex.TryGetValue(position + 1, out var node)) return false; + if (!_changeIndex.TryGetValue(position + 1, out var node)) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestHistoryGap); return false; } while (node is not null && scanned < maximum) { var change = node.Value; position = change.Version; scanned++; if (tickets.TryGetValue(change.Key, out var ticket)) { - if (!Current(ticket, out _)) return false; + if (!Current(ticket, out _)) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestTicket); return false; } changes.Add(new(ticket, change.Version)); } node = node.Next; @@ -519,19 +646,26 @@ internal sealed class SamplePartition : IDisposable public void Dispose() { + Interlocked.Or(ref _producerState, int.MinValue); lock (_gate) { if (_disposed) return; _disposed = true; InvalidatePartition(); CleanupInvalidatedEpoch(); while (_queue.TryDequeue(out var p)) ReleasePending(p); - foreach (var p in _dirty.Values) ReleasePending(p); - _dirty.Clear(); _queuedValues = 0; _queuedControls = 0; + while (_mailbox.TryDequeue(out var value)) { Interlocked.Decrement(ref _queuedValues); ReleasePending(value); } + while (_dirty.TryDequeue(out var dirtyState)) + { + Interlocked.Decrement(ref _dirtyCount); + var dirty = Interlocked.Exchange(ref dirtyState.Dirty, null); + if (dirty is not null) ReleasePending(dirty); + } + _queuedControls = 0; foreach (var pair in _sources) { pair.Value.Removed = true; RetireSourceState(pair.Value); } _sources.Clear(); } } private sealed class SourceGate(SourceGeneration generation, SourceBindingFence binding) - { public readonly SourceGeneration Generation = generation; public readonly SourceBindingFence Binding = binding; public long Invalidated; public int Retired; } + { public readonly SourceGeneration Generation = generation; public readonly SourceBindingFence Binding = binding; public long Invalidated, ProducerStamp, LastSubmitted; public int Retired, Committing; } private sealed class SourceState(SourceTicket ticket, long sourceCharge, ProducerFence? fence, long partitionEpoch) { public SourceTicket Ticket = ticket; public SourceGeneration Generation = ticket.Generation; public readonly long SourceCharge = sourceCharge; @@ -543,7 +677,7 @@ internal sealed class SamplePartition : IDisposable public int Readers; public int Reservations; public int Snapshots; public bool Removed; public DataReadiness Readiness = DataReadiness.WaitingForInitialData; public DataSample? Sample; public long SampleCharge; public long Received; - public long LastSubmitted; public long LastApplied; public long Barrier; public long InvalidationVersion; + public long LastApplied; public long Barrier; public long InvalidationVersion; public Pending? Dirty; } private sealed class Pending { @@ -553,14 +687,15 @@ internal sealed class SamplePartition : IDisposable { Ticket = ticket; Sequence = sequence; Ordinal = ordinal; Status = status; SourceTimestamp = source; ServerTimestamp = server; WasReady = wasReady; Charge = charge; IsControl = true; IsStatus = true; } public Pending(SourceTicket ticket, long sequence, long ordinal, long charge) { Ticket = ticket; Sequence = sequence; Ordinal = ordinal; Charge = charge; IsControl = true; } public SourceTicket Ticket; public long Sequence; public long Ordinal; public DataSample? Sample; public long Charge; public long Received; public long AdmissionEpoch; public long PartitionEpoch; + public SourceState? Owner; public SourceGate? Gate; public long ProducerStamp, SignalStamp; public bool IsControl; public bool IsStatus; public uint Status; public DateTimeOffset? SourceTimestamp; public DateTimeOffset? ServerTimestamp; public bool WasReady; } - private sealed class Reservation(SamplePartition partition, SourceState state, SourceTicket ticket, long estimate, long charge, - long invalidationVersion, long partitionEpoch, long receivedTimestamp) : IIngressReservation + private sealed class Reservation(SamplePartition partition, SourceState state, SourceGate gate, SourceTicket ticket, long estimate, long charge, + long producerStamp, long signal, long partitionEpoch, long receivedTimestamp) : IIngressReservation { private int _completed; public bool TryCommit(DataSample owned, long sequence) - { ArgumentNullException.ThrowIfNull(owned); return Interlocked.Exchange(ref _completed, 1) == 0 && partition.Commit(state, ticket, estimate, charge, invalidationVersion, partitionEpoch, receivedTimestamp, owned, sequence); } + { ArgumentNullException.ThrowIfNull(owned); return Interlocked.Exchange(ref _completed, 1) == 0 && partition.Commit(state, gate, ticket, estimate, charge, producerStamp, signal, partitionEpoch, receivedTimestamp, owned, sequence); } public void Dispose() { if (Interlocked.Exchange(ref _completed, 1) == 0) partition.Abandon(state, charge); } } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceIngressDiagnostics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceIngressDiagnostics.cs new file mode 100644 index 000000000..ae5ec0630 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceIngressDiagnostics.cs @@ -0,0 +1,12 @@ +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Bounded aggregate observations of origin source admission and retained history. +public static class SourceIngressDiagnostics +{ + internal enum Event { ReserveLock, CommitLock, ReserveCapacity, CommitInvalid, PartitionInvalidated, ExternalInvalidate, + ReadNotReady, ReadInvalidated, ReadExhausted, InterestReset, InterestQuiet, InterestEpoch, InterestHistoryGap, InterestTicket } + private static readonly long[] Counts = new long[Enum.GetValues().Length]; + internal static void Count(Event value) => Interlocked.Increment(ref Counts[(int)value]); + /// Captures process-wide counters without source identifiers or payloads. + public static IReadOnlyDictionary Capture() => Enum.GetValues().ToDictionary(x => x.ToString(), x => Interlocked.Read(ref Counts[(int)x])); +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceInterestLease.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceInterestLease.cs index ce1e46caf..308db6171 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceInterestLease.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceInterestLease.cs @@ -56,7 +56,7 @@ public sealed class SourceInterestLease : IDisposable { if (Volatile.Read(ref _released) != 0 || _hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch) return true; foreach (var cursor in Volatile.Read(ref _cursors)) - if (!cursor.Partition.Control.Quiet.Matches(cursor.QuietControl)) return true; + if (!cursor.Partition.Control.Quiet.Matches(cursor.QuietControl)) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestQuiet); return true; } return Volatile.Read(ref _released) != 0 || _hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch; } } @@ -69,7 +69,7 @@ public sealed class SourceInterestLease : IDisposable { var result = new List(); changes = result; - if (IsReset) { Release(); return false; } + if (IsReset) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestReset); Release(); return false; } var scanned = 0; for (var visited = 0; visited < _cursors.Length && scanned < maximum; visited++) { @@ -78,7 +78,7 @@ public sealed class SourceInterestLease : IDisposable maximum - scanned, result, out var used)) { Release(); result.Clear(); return false; } scanned += used; } - if (IsReset) { Release(); result.Clear(); return false; } + if (IsReset) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestReset); Release(); result.Clear(); return false; } return true; } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/UpstreamDemandRegistry.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/UpstreamDemandRegistry.cs index 92ce6a4fb..acb27555f 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/UpstreamDemandRegistry.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/UpstreamDemandRegistry.cs @@ -80,6 +80,10 @@ internal sealed class UpstreamDemandRegistry if (maxKeys <= 0 || maxInterests <= 0) throw new ArgumentOutOfRangeException(nameof(maxKeys)); _maxKeys = maxKeys; _maxInterests = maxInterests; } + internal (int Groups, int Interests) CaptureAccounting() + { + lock (_gate) return (_entries.Count, _interestCount); + } internal bool TryAdd(DemandSharingKey key, DataSubscriptionSettings settings, out IDisposable? lease) { ArgumentNullException.ThrowIfNull(key); ArgumentNullException.ThrowIfNull(settings); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs index f7d10f4b0..393262cb7 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs @@ -916,7 +916,12 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers Receive(RetrySourceBindingBatch); ReceiveAsync(async msg => { - if (msg.RequireAcquisition) { await ApplyAcquisitionDemandAsync(msg, Sender); return; } + if (msg.RequireAcquisition) + { + var replyTo = Sender; + await ApplyAcquisitionDemandAsync(msg, result => replyTo.Tell(result)); + return; + } if (_abandonedAcquisition is { } abandoned && !abandoned.Finished.IsCompleted) { var schedule = _deferredLegacyDemand is null; @@ -1880,6 +1885,34 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers try { + // With a source hub, use the driver's acknowledged physical acquisition feed even + // for the ordinary baseline. A change-only event cannot prove that an unchanged + // device value has been read again. This replaces the baseline poller; it does not + // add a second subscription or change the driver's native change notifications. + if (_sourcePublisher is not null && _sourceIncarnation is > 0 && _acquisitionCapacity is not null && + _driver is IAcknowledgedBaselineAcquisitionSource && msg.FullReferences.Count > 0) + { + if (_previousAcquisitionCleanup is { IsCompleted: false } cleanup) + await cleanup.WaitAsync(_acquisitionTimeout); + var admission = new LegacyAdmission(this, self, stageSources: false); + Volatile.Write(ref _legacyAdmission, admission); + AttachDataChangeHandler(subscribable, self); + AcquisitionDemandApplied? applied = null; + await ApplyAcquisitionDemandAsync(new SetDesiredSubscriptions(msg.FullReferences, msg.PublishingInterval, + DesiredRevision: 1, ProducerIncarnation: _sourceIncarnation.Value, RequireAcquisition: true), + result => applied = result, baseline: true); + if (applied is not { Succeeded: true } || _subscriptionHandle is null) + throw new InvalidOperationException("Baseline acquisition was not acknowledged."); + if (!admission.Finish(_subscriptionHandle)) + { + await UnsubscribeAsync(); + throw new InvalidOperationException("Legacy initial callback staging capacity exceeded."); + } + replyTo.Tell(new SubscriptionEstablished(_subscriptionHandle.DiagnosticId, msg.FullReferences.Count)); + _log.Info("DriverInstance {Id}: subscribed to {Count} refs ({Diag})", + _driverInstanceId, msg.FullReferences.Count, _subscriptionHandle.DiagnosticId); + return; + } var sourceBindingNeedsRetry = false; if (_sourcePublisher is not null && _sourceIncarnation is { } incarnation) { @@ -1985,7 +2018,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers // callbacks under a bounded generation gate, then accept only the returned handle. Source // reservations capture their own monotonic ingress time at callback time; SDK delivery does // not depend on source-hub admission. - private sealed class LegacyAdmission(DriverInstanceActor owner, IActorRef self) : IDisposable + private sealed class LegacyAdmission(DriverInstanceActor owner, IActorRef self, bool stageSources = true) : IDisposable { private const int MaxItems = 4096; private const long MaxBytes = 16 * 1024 * 1024; @@ -2027,7 +2060,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers bytes = checked(bytes + OwnedDataSample.Estimate(item.Snapshot.Value) + 2L * item.FullReference.Length); if (bytes > MaxBytes - _bytes) throw new ArgumentException("Legacy initial callback budget exceeded."); copied[i] = new DataChangeItem(item.FullReference, CopyLegacySnapshot(item.Snapshot)); - sources[i] = owner.StageLegacySource(item); + if (stageSources) sources[i] = owner.StageLegacySource(item); } _items += items.Count; _bytes += bytes; _events.Add(new StagedEvent(handle, copied, sources)); @@ -2213,36 +2246,37 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers } } - private async Task ApplyAcquisitionDemandAsync(SetDesiredSubscriptions desired, IActorRef replyTo) + private async Task ApplyAcquisitionDemandAsync(SetDesiredSubscriptions desired, + Action reply, bool baseline = false) { var failed = new AcquisitionDemandApplied(desired.DesiredRevision, desired.ProducerIncarnation, TimeSpan.Zero, false); if (_abandonedAcquisition is { } abandoned) { if (!abandoned.Finished.IsCompleted) { - replyTo.Tell(failed with { Busy = true, RetryWhenReady = abandoned.Finished }); + reply(failed with { Busy = true, RetryWhenReady = abandoned.Finished }); return; } if (!abandoned.Finished.IsCompletedSuccessfully || !abandoned.Finished.Result) { - replyTo.Tell(failed); + reply(failed); return; } _abandonedAcquisition = null; } - if (_desiredAcquisition is { } current && _subscriptionHandle is not null && + if (!baseline && _desiredAcquisition is { } current && _subscriptionHandle is not null && Volatile.Read(ref _activeAcquisition) is not null && current.DesiredRevision == desired.DesiredRevision && current.ProducerIncarnation == desired.ProducerIncarnation && current.PublishingInterval == desired.PublishingInterval && current.FullReferences.SequenceEqual(desired.FullReferences, StringComparer.Ordinal)) { StoreDesiredSubscriptions(desired); SubscribeDesiredAlarms(); - replyTo.Tell(new AcquisitionDemandApplied(desired.DesiredRevision, desired.ProducerIncarnation, _acquisitionNominal, true)); + reply(new AcquisitionDemandApplied(desired.DesiredRevision, desired.ProducerIncarnation, _acquisitionNominal, true)); return; } if (_previousAcquisitionCleanup is { IsCompleted: false } cleanup) { - replyTo.Tell(failed with { Busy = true, RetryWhenReady = cleanup }); + reply(failed with { Busy = true, RetryWhenReady = cleanup }); return; } if (_driver is not IAcknowledgedAcquisitionSource source || _driver is not ISubscribable subscribable || @@ -2251,7 +2285,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers _acquisitionCapacity is null || _activeCapacity?.IsUncertain == true || _previousAcquisitionCleanup is { IsCompleted: false } || _previousAcquisitionCleanup is { IsCompletedSuccessfully: true, Result: false }) { - replyTo.Tell(failed); + reply(failed); return; } var shared = _activeCapacity; @@ -2261,7 +2295,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers var reservation = _acquisitionCapacity.TryAcquire(_clusterId, _driverInstanceId, out var ready); if (reservation is null) { - replyTo.Tell(ready is null ? failed : failed with { Busy = true, RetryWhenReady = ready }); + reply(ready is null ? failed : failed with { Busy = true, RetryWhenReady = ready }); return; } shared = new SharedAcquisitionReservation(reservation); @@ -2316,32 +2350,35 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers operation.Abandon(); _abandonedAcquisition = operation; if (!hadHandler) DetachDataSubscription(); - replyTo.Tell(failed); + reply(failed); return; } var activeReference = _activeCapacityReference is null ? shared.Retain() : null; if (!operation.TryAdopt(installed)) { activeReference?.Dispose(); - replyTo.Tell(failed); + reply(failed); return; } if (activeReference is not null) { _activeCapacity = shared; _activeCapacityReference = activeReference; } _subscriptionHandle = installed.Handle; Volatile.Write(ref _fenceLegacyHandles, true); - Interlocked.Exchange(ref _legacyAdmission, null)?.Dispose(); + if (!baseline) Interlocked.Exchange(ref _legacyAdmission, null)?.Dispose(); Volatile.Write(ref _activeAcquisition, fence); Volatile.Write(ref _acquisitionPending, 0); - StoreDesiredSubscriptions(desired); - _desiredAcquisition = desired; + if (!baseline) + { + StoreDesiredSubscriptions(desired); + _desiredAcquisition = desired; + } _acquisitionNominal = installed.NominalSamplingInterval; if (sourceBindingNeedsRetry) Timers.StartSingleTimer("source-binding-retry", new RetrySourceBindings(desired.FullReferences, 0, false, 0, sourceBindingVersion, fence.Producer), TimeSpan.FromMilliseconds(250)); - SubscribeDesiredAlarms(); + if (!baseline) SubscribeDesiredAlarms(); if (previousHandle is not null && !ReferenceEquals(previousHandle, installed.Handle)) _previousAcquisitionCleanup = CleanupAcquiredHandleAsync(subscribable, previousHandle, shared.Retain(), shared); - replyTo.Tell(new AcquisitionDemandApplied(fence.Revision, fence.Producer, installed.NominalSamplingInterval, true)); + reply(new AcquisitionDemandApplied(fence.Revision, fence.Producer, installed.NominalSamplingInterval, true)); } catch (Exception ex) when (ex is not OutOfMemoryException) { @@ -2349,7 +2386,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers else operation.CancelBeforeStart(); if (!hadHandler) DetachDataSubscription(); _log.Warning(ex, "DriverInstance {Id}: acquisition demand failed", _driverInstanceId); - replyTo.Tell(failed); + reply(failed); } finally { _pendingAcquisition = null; Volatile.Write(ref _acquisitionPending, 0); } } 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 15134f990..92bd10945 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Redundancy/IRedundancyRoleView.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Redundancy/IRedundancyRoleView.cs @@ -97,6 +97,9 @@ public interface IHistoryUpdateRoleView void PublishHistoryUpdateRole(bool shouldServeHistoryUpdate); } +/// An atomic observation of the data-plane role and its independent continuity epoch. +public sealed record DataServingRoleSnapshot(string Role, long Generation, long ReadEligibilityEpoch); + /// /// Thread-safe + + /// + , each backed by its own volatile field. @@ -117,11 +120,19 @@ 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, string ServingRole); - private PrimaryVerdict _primaryVerdict = new(PrimaryGatePolicy.ShouldServiceAsPrimary(null, 1), 0, "Unknown"); + private sealed record PrimaryVerdict(bool Allowed, long Generation, string ServingRole, long ReadEligibilityEpoch); + private PrimaryVerdict _primaryVerdict = new(PrimaryGatePolicy.ShouldServiceAsPrimary(null, 1), 0, "Unknown", 1); private long _nextDataOwner, _dataOwner; private bool _rolePoisoned; public long PrimaryGeneration => Volatile.Read(ref _primaryVerdict).Generation; + /// Changes on owner replacement or loss of a known readable role. + public long ReadEligibilityEpoch => Volatile.Read(ref _primaryVerdict).ReadEligibilityEpoch; + /// Captures the immutable role verdict without acquiring the dispatch fence. + public DataServingRoleSnapshot CaptureDataServingRole() + { + var verdict = Volatile.Read(ref _primaryVerdict); + return new(verdict.ServingRole, verdict.Generation, verdict.ReadEligibilityEpoch); + } /// 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 @@ -181,10 +192,10 @@ public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRole using (DispatchFence.Enter()) { var current = _primaryVerdict; - if (_rolePoisoned || _nextDataOwner == long.MaxValue || current.Generation == long.MaxValue) + if (_rolePoisoned || _nextDataOwner == long.MaxValue || current.Generation == long.MaxValue || current.ReadEligibilityEpoch == long.MaxValue) { PoisonRole(); throw new InvalidOperationException("Serving role generation exhausted."); } _dataOwner = ++_nextDataOwner; - Volatile.Write(ref _primaryVerdict, new(current.Allowed, current.Generation + 1, "Unknown")); + Volatile.Write(ref _primaryVerdict, new(current.Allowed, current.Generation + 1, "Unknown", current.ReadEligibilityEpoch + 1)); return _dataOwner; } } @@ -199,15 +210,15 @@ public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRole 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")); + if (current.Generation == long.MaxValue || current.ReadEligibilityEpoch == long.MaxValue) { PoisonRole(); return; } + Volatile.Write(ref _primaryVerdict, new(false, current.Generation + 1, "Unknown", current.ReadEligibilityEpoch + 1)); } } private void PoisonRole() { _rolePoisoned = true; _dataOwner = 0; - Volatile.Write(ref _primaryVerdict, new(false, long.MaxValue, "Unknown")); + Volatile.Write(ref _primaryVerdict, new(false, long.MaxValue, "Unknown", long.MaxValue)); } private void PublishPrimaryVerdict(bool shouldActAsPrimary, string? observedRole, long? owner = null) @@ -219,11 +230,14 @@ public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRole 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)); + var losesReadRole = IsReadRole(current.ServingRole) && !IsReadRole(role); + if (current.Generation == long.MaxValue || losesReadRole && current.ReadEligibilityEpoch == long.MaxValue) { PoisonRole(); return; } + Volatile.Write(ref _primaryVerdict, new(shouldActAsPrimary, current.Generation + 1, role, + current.ReadEligibilityEpoch + (losesReadRole ? 1 : 0))); } } } + private static bool IsReadRole(string role) => role is "Primary" or "Secondary"; /// public void PublishHistorizationRole(bool shouldRecordHistorizedValues) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs index b47086f4b..28497bad1 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs @@ -274,8 +274,14 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers private void RemoveSubscriber(IActorRef subscriber) { if (!Detach(subscriber)) return; - if (_projectedSubscribers.TryGetValue(subscriber, out var projectedMailbox)) projectedMailbox.Clear(); - Context.Unwatch(subscriber); + if (_projectedSubscribers.TryGetValue(subscriber, out var projectedMailbox)) + { + // The subscriber can still hold values taken from this mailbox. Clear queued work, + // but keep watching until its termination disposes the retained delivered values + // and releases their shared quota. A later registration reuses the same mailbox. + projectedMailbox.Clear(); + } + else Context.Unwatch(subscriber); _log.Debug("DependencyMux: subscriber {Sub} removed", subscriber); } diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/Fakes/FakeOpcUaClientService.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/Fakes/FakeOpcUaClientService.cs index cd36a88e7..1a9538134 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/Fakes/FakeOpcUaClientService.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/Fakes/FakeOpcUaClientService.cs @@ -182,6 +182,14 @@ public sealed class FakeOpcUaClientService : IOpcUaClientService return Task.FromResult(ReadValueResult); } + public TimeSpan? LastMaximumAge { get; private set; } + + public Task ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct = default) + { + LastMaximumAge = maximumAge; + return ReadValueAsync(nodeId, ct); + } + /// public Task WriteValueAsync(NodeId nodeId, object value, CancellationToken ct = default) { diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/ReadCommandTests.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/ReadCommandTests.cs index 248933864..321c17a5e 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/ReadCommandTests.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/ReadCommandTests.cs @@ -8,11 +8,45 @@ namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Tests; public class ReadCommandTests { + [Theory] + [InlineData(0)] + [InlineData(5000)] + [InlineData(2147483647)] + public async Task Execute_ForwardsMaximumAge(double milliseconds) + { + var service = new FakeOpcUaClientService(); + var command = new ReadCommand(new FakeOpcUaClientServiceFactory(service)) + { + Url = "opc.tcp://localhost:4840", NodeId = "ns=2;s=Test", MaxAgeMilliseconds = milliseconds + }; + using var console = TestConsoleHelper.CreateConsole(); + await command.ExecuteAsync(console); + if (milliseconds == 0) service.LastMaximumAge.ShouldBeNull(); + else service.LastMaximumAge.ShouldBe(TimeSpan.FromMilliseconds(milliseconds)); + } + + [Theory] + [InlineData(-1)] + [InlineData(2147483648d)] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + public async Task Execute_RejectsInvalidMaximumAge(double milliseconds) + { + var service = new FakeOpcUaClientService(); + var command = new ReadCommand(new FakeOpcUaClientServiceFactory(service)) + { + Url = "opc.tcp://localhost:4840", NodeId = "ns=2;s=Test", MaxAgeMilliseconds = milliseconds + }; + using var console = TestConsoleHelper.CreateConsole(); + await Should.ThrowAsync(async () => await command.ExecuteAsync(console)); + service.ReadNodeIds.ShouldBeEmpty(); + } + /// Verifies that execute prints the read value. [Fact] public async Task Execute_PrintsReadValue() { - var sourceTime = new DateTime(2025, 6, 15, 10, 30, 0, DateTimeKind.Utc); + var sourceTime = new DateTime(2025, 6, 15, 10, 30, 0, DateTimeKind.Utc).AddTicks(1234567); var serverTime = new DateTime(2025, 6, 15, 10, 30, 1, DateTimeKind.Utc); var fakeService = new FakeOpcUaClientService { @@ -38,6 +72,8 @@ public class ReadCommandTests output.ShouldContain("Status:"); output.ShouldContain("Source Time:"); output.ShouldContain("Server Time:"); + output.ShouldContain("Source Time: " + sourceTime.ToString("O", System.Globalization.CultureInfo.InvariantCulture)); + output.ShouldContain("Server Time: " + serverTime.ToString("O", System.Globalization.CultureInfo.InvariantCulture)); } /// Verifies that execute calls read value with correct node ID. diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/SubscribeCommandSummaryTests.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/SubscribeCommandSummaryTests.cs index b4c68d578..36c7aa72c 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/SubscribeCommandSummaryTests.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/SubscribeCommandSummaryTests.cs @@ -60,9 +60,10 @@ public class SubscribeCommandSummaryTests // Wait until the subscription is registered by the fake. await WaitForAsync(() => fakeService.SubscribeCalls.Count == 1); + var acquisitionTime = new DateTime(2026, 11, 17, 3, 0, 0, DateTimeKind.Utc).AddTicks(7654321); fakeService.RaiseDataChanged( "ns=2;s=GoodNode", - new DataValue(new Variant(42), StatusCodes.Good, DateTime.UtcNow, DateTime.UtcNow)); + new DataValue(new Variant(42), StatusCodes.Good, acquisitionTime, DateTime.UtcNow)); await runTask; @@ -70,6 +71,7 @@ public class SubscribeCommandSummaryTests output.ShouldContain("NEVER went bad (suspect): 1"); output.ShouldContain("Last status GOOD: 1"); output.ShouldContain("No update received at all: 0"); + output.ShouldContain("[" + acquisitionTime.ToString("O") + "]"); } /// Verifies that nodes with bad values are counted as ever went bad. diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/WriteCommandTests.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/WriteCommandTests.cs index 9e1236d8e..2e9407ec2 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/WriteCommandTests.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/WriteCommandTests.cs @@ -1,3 +1,5 @@ +using System.Globalization; +using CliFx.Exceptions; using Opc.Ua; using Shouldly; using Xunit; @@ -8,6 +10,131 @@ namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Tests; public class WriteCommandTests { + /// Verifies that an explicit UInt16 write does not require read access. + [Fact] + public async Task Execute_ExplicitUInt16BypassesReadAndWritesUShort() + { + var fakeService = new FakeOpcUaClientService + { + ReadException = new InvalidOperationException("Value read is not authorized.") + }; + var command = new WriteCommand(new FakeOpcUaClientServiceFactory(fakeService)) + { + Url = "opc.tcp://localhost:4840", + NodeId = "ns=2;s=WriteOnly", + Value = "65535", + Type = "UInt16" + }; + + using var console = TestConsoleHelper.CreateConsole(); + await command.ExecuteAsync(console); + + fakeService.ReadNodeIds.ShouldBeEmpty(); + fakeService.WriteValues.Count.ShouldBe(1); + fakeService.WriteValues[0].Value.ShouldBeOfType().ShouldBe(ushort.MaxValue); + fakeService.DisconnectCalled.ShouldBeTrue(); + fakeService.DisposeCalled.ShouldBeTrue(); + } + + /// Verifies the explicit scalar set and invariant numeric conversion. + [Theory] + [InlineData("Boolean", "yes", typeof(bool))] + [InlineData("Byte", "255", typeof(byte))] + [InlineData("SByte", "-128", typeof(sbyte))] + [InlineData("Int16", "-32768", typeof(short))] + [InlineData("UInt16", "65535", typeof(ushort))] + [InlineData("Int32", "-2147483648", typeof(int))] + [InlineData("UInt32", "4294967295", typeof(uint))] + [InlineData("Int64", "-9223372036854775808", typeof(long))] + [InlineData("UInt64", "18446744073709551615", typeof(ulong))] + [InlineData("Float", "1.25", typeof(float))] + [InlineData("Double", "1.25", typeof(double))] + [InlineData("String", "operator text", typeof(string))] + [InlineData("uint16", "123", typeof(ushort))] + public async Task Execute_ExplicitScalarUsesRequestedClrType(string type, string value, Type expectedType) + { + var fakeService = new FakeOpcUaClientService + { + ReadException = new InvalidOperationException("Explicit types must not read.") + }; + var command = new WriteCommand(new FakeOpcUaClientServiceFactory(fakeService)) + { + Url = "opc.tcp://localhost:4840", NodeId = "ns=2;s=Scalar", Value = value, Type = type + }; + var originalCulture = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR"); + using var console = TestConsoleHelper.CreateConsole(); + await command.ExecuteAsync(console); + } + finally + { + CultureInfo.CurrentCulture = originalCulture; + } + + fakeService.ReadNodeIds.ShouldBeEmpty(); + fakeService.WriteValues.Count.ShouldBe(1); + var writtenValue = fakeService.WriteValues[0].Value; + writtenValue.GetType().ShouldBe(expectedType); + if (expectedType == typeof(bool)) + writtenValue.ShouldBe(true); + else + Convert.ToString(writtenValue, CultureInfo.InvariantCulture).ShouldBe(value); + } + + /// Verifies unsupported type names fail locally before connecting or writing. + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("DateTime")] + [InlineData("ByteString")] + [InlineData("UInt16[]")] + [InlineData("System.UInt16")] + [InlineData("Unknown")] + public async Task Execute_UnsupportedExplicitTypeRejectsBeforeConnect(string type) + { + var fakeService = new FakeOpcUaClientService(); + var command = new WriteCommand(new FakeOpcUaClientServiceFactory(fakeService)) + { + Url = "opc.tcp://localhost:4840", NodeId = "ns=2;s=Scalar", Value = "1", Type = type + }; + + using var console = TestConsoleHelper.CreateConsole(); + var error = await Should.ThrowAsync(async () => await command.ExecuteAsync(console)); + + error.Message.ShouldContain("--type"); + fakeService.ConnectCalled.ShouldBeFalse(); + fakeService.ReadNodeIds.ShouldBeEmpty(); + fakeService.WriteValues.ShouldBeEmpty(); + } + + /// Verifies invalid explicit values fail locally before connecting or writing. + [Theory] + [InlineData("UInt16", "65536")] + [InlineData("UInt16", "-1")] + [InlineData("UInt16", "not-a-number")] + [InlineData("UInt16", "1.5")] + [InlineData("SByte", "128")] + [InlineData("Boolean", "maybe")] + [InlineData("Double", "1,25")] + public async Task Execute_InvalidExplicitValueRejectsBeforeConnect(string type, string value) + { + var fakeService = new FakeOpcUaClientService(); + var command = new WriteCommand(new FakeOpcUaClientServiceFactory(fakeService)) + { + Url = "opc.tcp://localhost:4840", NodeId = "ns=2;s=Scalar", Value = value, Type = type + }; + + using var console = TestConsoleHelper.CreateConsole(); + var error = await Should.ThrowAsync(async () => await command.ExecuteAsync(console)); + + error.Message.ShouldContain("--value"); + fakeService.ConnectCalled.ShouldBeFalse(); + fakeService.ReadNodeIds.ShouldBeEmpty(); + fakeService.WriteValues.ShouldBeEmpty(); + } + /// Verifies that write command executes successfully. [Fact] public async Task Execute_WritesSuccessfully() @@ -104,4 +231,4 @@ public class WriteCommandTests fakeService.DisconnectCalled.ShouldBeTrue(); fakeService.DisposeCalled.ShouldBeTrue(); } -} \ No newline at end of file +} diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeEndpointDiscovery.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeEndpointDiscovery.cs index 373cec651..565bc4785 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeEndpointDiscovery.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeEndpointDiscovery.cs @@ -11,6 +11,8 @@ internal sealed class FakeEndpointDiscovery : IEndpointDiscovery public int SelectCallCount { get; private set; } /// Gets the last endpoint URL passed to SelectEndpoint. public string? LastEndpointUrl { get; private set; } + /// Gets or sets the discovered endpoint URL when it differs from the input URL. + public string? SelectedEndpointUrl { get; set; } /// Selects an endpoint for the given configuration and URL, optionally throwing an exception. /// The application configuration. @@ -28,7 +30,7 @@ internal sealed class FakeEndpointDiscovery : IEndpointDiscovery return Task.FromResult(new EndpointDescription { - EndpointUrl = endpointUrl, + EndpointUrl = SelectedEndpointUrl ?? endpointUrl, SecurityMode = requestedMode, SecurityPolicyUri = requestedMode == MessageSecurityMode.None ? SecurityPolicies.None diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeSessionAdapter.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeSessionAdapter.cs index 120d6e27f..ea9f28985 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeSessionAdapter.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeSessionAdapter.cs @@ -89,8 +89,17 @@ internal sealed class FakeSessionAdapter : ISessionAdapter /// public string SessionName { get; set; } = "FakeSession"; + private string _endpointUrl = "opc.tcp://localhost:4840"; + + /// Simulates SDK endpoint metadata becoming unavailable after a transport failure. + public bool ThrowOnEndpointUrlRead { get; set; } + /// - public string EndpointUrl { get; set; } = "opc.tcp://localhost:4840"; + public string EndpointUrl + { + get => ThrowOnEndpointUrlRead ? throw new NullReferenceException("The SDK transport is gone.") : _endpointUrl; + set => _endpointUrl = value; + } /// public string ServerName { get; set; } = "FakeServer"; @@ -123,6 +132,17 @@ internal sealed class FakeSessionAdapter : ISessionAdapter return Task.FromResult(ReadResponse ?? new DataValue(new Variant(0), StatusCodes.Good)); } + public TimeSpan? LastMaximumAge { get; private set; } + public CancellationToken LastReadCancellationToken { get; private set; } + + public Task ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct) + { + LastMaximumAge = maximumAge; + LastReadCancellationToken = ct; + ct.ThrowIfCancellationRequested(); + return ReadValueAsync(nodeId, ct); + } + /// public Task WriteValueAsync(NodeId nodeId, DataValue value, CancellationToken ct) { diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeSubscriptionAdapter.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeSubscriptionAdapter.cs index b567b15cf..120d9cef0 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeSubscriptionAdapter.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeSubscriptionAdapter.cs @@ -37,6 +37,12 @@ internal sealed class FakeSubscriptionAdapter : ISubscriptionAdapter /// Gets the number of times AddEventMonitoredItemAsync was called. public int AddEventCount { get; private set; } + /// Optional per-item rejection for an event add. + public Exception? EventAddException { get; set; } + + /// Whether this instance was disposed. + public bool Disposed { get; private set; } + /// Gets or sets a value indicating whether RemoveMonitoredItemAsync throws (a session that died). public bool ThrowOnRemove { get; set; } @@ -91,6 +97,7 @@ internal sealed class FakeSubscriptionAdapter : ISubscriptionAdapter lock (_itemsLock) { AddEventCount++; + if (EventAddException is { } error) throw error; var handle = _nextHandle++; _items[handle] = (nodeId, null, onEvent); return Task.FromResult(handle); @@ -126,6 +133,7 @@ internal sealed class FakeSubscriptionAdapter : ISubscriptionAdapter /// public void Dispose() { + Disposed = true; lock (_itemsLock) _items.Clear(); } diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/OpcUaClientServiceTests.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/OpcUaClientServiceTests.cs index 0d54bd1af..c6ac10a70 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/OpcUaClientServiceTests.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/OpcUaClientServiceTests.cs @@ -216,6 +216,30 @@ public class OpcUaClientServiceTests : IDisposable _service.CurrentConnectionInfo.ShouldBeNull(); } + [Fact] + public async Task DisconnectAsync_AfterTransportLoss_UsesPublishedEndpointAndClosesSession() + { + var ct = TestContext.Current.CancellationToken; + const string endpoint = "opc.tcp://negotiated:4840"; + _endpointDiscovery.SelectedEndpointUrl = endpoint; + var session = new FakeSessionAdapter(); + _sessionFactory.EnqueueSession(session); + await _service.ConnectAsync(ValidSettings(), ct); + _service.CurrentConnectionInfo!.EndpointUrl.ShouldBe(endpoint); + session.ThrowOnEndpointUrlRead = true; + + var events = new List(); + _service.ConnectionStateChanged += (_, state) => events.Add(state); + await _service.DisconnectAsync(ct); + + session.Closed.ShouldBeTrue(); + session.Disposed.ShouldBeTrue(); + _service.CurrentConnectionInfo.ShouldBeNull(); + var disconnected = events.ShouldHaveSingleItem(); + disconnected.NewState.ShouldBe(ConnectionState.Disconnected); + disconnected.EndpointUrl.ShouldBe(endpoint); + } + /// /// Verifies that disconnect is safe to call when no server session is active. /// @@ -239,6 +263,36 @@ public class OpcUaClientServiceTests : IDisposable // --- Read tests --- + [Fact] + public async Task ReadValueAsync_MaximumAge_ForwardsAgeAndCancellation() + { + var session = new FakeSessionAdapter(); + _sessionFactory.EnqueueSession(session); + await _service.ConnectAsync(ValidSettings(), TestContext.Current.CancellationToken); + using var source = new CancellationTokenSource(); + await _service.ReadValueAsync(new NodeId("tag", 2), TimeSpan.FromSeconds(5), source.Token); + session.LastMaximumAge.ShouldBe(TimeSpan.FromSeconds(5)); + session.LastReadCancellationToken.ShouldBe(source.Token); + source.Cancel(); + await Should.ThrowAsync(() => + _service.ReadValueAsync(new NodeId("tag", 2), TimeSpan.FromSeconds(5), source.Token)); + } + + [Fact] + public async Task ReadValueAsync_MaximumAge_ZeroPreservesOriginalPathAndInvalidAgesFail() + { + var session = new FakeSessionAdapter(); + _sessionFactory.EnqueueSession(session); + await _service.ConnectAsync(ValidSettings(), TestContext.Current.CancellationToken); + await _service.ReadValueAsync(new NodeId("tag", 2), TimeSpan.Zero, TestContext.Current.CancellationToken); + session.LastMaximumAge.ShouldBeNull(); + session.ReadCount.ShouldBe(1); + await Should.ThrowAsync(() => _service.ReadValueAsync(new NodeId("tag", 2), TimeSpan.FromMilliseconds(-1), TestContext.Current.CancellationToken)); + await Should.ThrowAsync(() => _service.ReadValueAsync(new NodeId("tag", 2), TimeSpan.FromMilliseconds((double)int.MaxValue + 1), TestContext.Current.CancellationToken)); + } + + + /// /// Verifies that a connected client can read the current value of a node through the session adapter. /// @@ -718,6 +772,50 @@ public class OpcUaClientServiceTests : IDisposable session.CreatedSubscriptions[0].AddEventCount.ShouldBe(1); } + [Fact] + public async Task Rejected_alarm_item_cleans_up_and_a_later_subscribe_succeeds() + { + var rejected = new ServiceResultException(StatusCodes.BadUserAccessDenied); + var failed = new FakeSubscriptionAdapter { EventAddException = rejected }; + var session = new FakeSessionAdapter { NextSubscription = failed }; + _sessionFactory.EnqueueSession(session); + await _service.ConnectAsync(ValidSettings(), TestContext.Current.CancellationToken); + + var error = await Should.ThrowAsync(() => + _service.SubscribeAlarmsAsync(ct: TestContext.Current.CancellationToken)); + error.ShouldBeSameAs(rejected); + failed.Deleted.ShouldBeTrue(); + failed.Disposed.ShouldBeTrue(); + + await _service.SubscribeAlarmsAsync(ct: TestContext.Current.CancellationToken); + session.CreatedSubscriptions.Count.ShouldBe(2); + session.CreatedSubscriptions[1].AddEventCount.ShouldBe(1); + session.CreatedSubscriptions[1].ActiveHandles.Count.ShouldBe(1); + } + + [Fact] + public async Task Rejected_alarm_replay_cleans_up_and_a_later_subscribe_succeeds() + { + var failed = new FakeSubscriptionAdapter { EventAddException = new ServiceResultException(StatusCodes.BadUserAccessDenied) }; + var original = new FakeSessionAdapter { EndpointUrl = "opc.tcp://primary:4840" }; + var replacement = new FakeSessionAdapter { EndpointUrl = "opc.tcp://backup:4840", NextSubscription = failed }; + _sessionFactory.EnqueueSession(original); + _sessionFactory.EnqueueSession(replacement); + var settings = ValidSettings("opc.tcp://primary:4840"); + settings.FailoverUrls = ["opc.tcp://backup:4840"]; + await _service.ConnectAsync(settings, TestContext.Current.CancellationToken); + await _service.SubscribeAlarmsAsync(ct: TestContext.Current.CancellationToken); + original.SimulateKeepAlive(false); + await _service.LastFailover.ShouldNotBeNull().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + failed.Deleted.ShouldBeTrue(); + failed.Disposed.ShouldBeTrue(); + + await _service.SubscribeAlarmsAsync(ct: TestContext.Current.CancellationToken); + replacement.CreatedSubscriptions.Count.ShouldBe(2); + replacement.CreatedSubscriptions[1].AddEventCount.ShouldBe(1); + replacement.CreatedSubscriptions[1].ActiveHandles.Count.ShouldBe(1); + } + /// /// Verifies that duplicate alarm-subscription requests do not create duplicate event subscriptions. /// @@ -1486,6 +1584,31 @@ public class OpcUaClientServiceTests : IDisposable e.EndpointUrl == "opc.tcp://backup:4840"); } + [Fact] + public async Task KeepAliveFailure_AfterTransportLoss_UsesPublishedEndpointAndReconnects() + { + var ct = TestContext.Current.CancellationToken; + const string primary = "opc.tcp://primary:4840"; + const string backup = "opc.tcp://backup:4840"; + var original = new FakeSessionAdapter { EndpointUrl = primary }; + _sessionFactory.EnqueueSession(original); + _sessionFactory.EnqueueSession(new FakeSessionAdapter { EndpointUrl = backup }); + var settings = ValidSettings(primary); + settings.FailoverUrls = [backup]; + await _service.ConnectAsync(settings, ct); + original.ThrowOnEndpointUrlRead = true; + + var events = new List(); + _service.ConnectionStateChanged += (_, state) => events.Add(state); + original.SimulateKeepAlive(false); + await _service.LastFailover!.WaitAsync(TimeSpan.FromSeconds(5), ct); + + original.Disposed.ShouldBeTrue(); + events.Select(state => (state.NewState, state.EndpointUrl)).ShouldBe([ + (ConnectionState.Reconnecting, primary), (ConnectionState.Connected, backup)]); + _service.CurrentConnectionInfo!.EndpointUrl.ShouldBe(backup); + } + /// /// Verifies that connection metadata is refreshed to reflect the newly active failover endpoint. /// diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/ReadResultValidationTests.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/ReadResultValidationTests.cs new file mode 100644 index 000000000..0e7a3a582 --- /dev/null +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/ReadResultValidationTests.cs @@ -0,0 +1,25 @@ +using Opc.Ua; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters; + +namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Tests; + +[Trait("Feature", "GrpcData"), Trait("Phase", "P10")] +public class ReadResultValidationTests +{ + [Fact] + public void ValidateReadResult_RejectsMissingOrExtraResultsAndBadStatus() + { + var header = new ResponseHeader { ServiceResult = StatusCodes.Good }; + var node = new NodeId("tag", 2); + Should.Throw(() => DefaultSessionAdapter.ValidateReadResult(header, [], node)); + Should.Throw(() => DefaultSessionAdapter.ValidateReadResult(header, + [new DataValue(), new DataValue()], node)); + var error = Should.Throw(() => DefaultSessionAdapter.ValidateReadResult(header, + [new DataValue(new Variant(0), StatusCodes.BadNodeIdUnknown)], node)); + error.StatusCode.ShouldBe(StatusCodes.BadNodeIdUnknown); + Should.Throw(() => DefaultSessionAdapter.ValidateReadResult( + new ResponseHeader { ServiceResult = StatusCodes.BadUnexpectedError }, [new DataValue()], node)); + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataFreshnessChallengeCodecTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataFreshnessChallengeCodecTests.cs new file mode 100644 index 000000000..6b893a925 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataFreshnessChallengeCodecTests.cs @@ -0,0 +1,213 @@ +using Google.Protobuf; +using Google.Protobuf.Reflection; +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("Feature", "GrpcData"), Trait("Phase", "P07"), Trait("Category", "Unit")] +public sealed class GrpcDataFreshnessChallengeCodecTests +{ + private static readonly ServingIdentity Serving = new("node", "incarnation", "Primary", 11, 12, 13); + private static readonly DataItemHandle First = new("subscription", 3, 41, 2); + private static readonly DataItemHandle Second = new("subscription", 3, 42, 5); + private static readonly IReadOnlyDictionary Handles = + new Dictionary { [41] = First, [42] = Second }; + + private static W.SubscriptionFrame Values(bool compact, bool negotiatedAge = true) + { + using var frame = new DataSubscriptionValues("subscription", 3, 17, false, + [ + new(First, new(DataValue.FromBytes(new byte[] { 1, 2, 3 }), 0, DateTimeOffset.UnixEpoch, null, Serving, 21), + new(TimeSpan.FromMilliseconds(7), null), DataReadiness.Ready, "challenge-previously-sent", 123456), + new(Second, new(DataValue.FromScalar(DataValueKind.Int32, 42), 0, null, null, Serving, 22), + new(TimeSpan.FromMilliseconds(9), null), DataReadiness.Ready) + ]); + return DataProtoMapper.EncodeValues(frame, compact, subscriptionAgeReadiness: negotiatedAge); + } + + private static DataSubscriptionValues Decode(W.SubscriptionFrame frame, bool negotiatedAge = true, int maxBytes = 65536) => + DataProtoMapper.DecodeValues(frame, Handles, 2, maxBytes, Serving, subscriptionAgeReadiness: negotiatedAge); + + private static void SetNonce(W.SubscriptionFrame frame, bool compact, string nonce) + { + if (compact) frame.CompactValues.Items[0].FreshnessChallengeId = nonce; + else frame.Values.Items[0].FreshnessChallengeId = nonce; + } + + private static W.SubscriptionCommand Challenge() => DataProtoMapper.EncodeCommand( + new ChallengeSubscriptionFreshness("subscription", 3, "challenge-previously-sent", TimeSpan.FromSeconds(2), [First, Second])); + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Serialized_nonce_survives_source_disposal_and_is_independent_of_wire_mutation(bool compact) + { + // Values() disposes the source frame before returning the encoded bytes. + var wire = Values(compact); + var bytes = wire.ToByteArray(); + SetNonce(wire, compact, "changed-after-serialization"); + var received = W.SubscriptionFrame.Parser.ParseFrom(bytes); + using var decoded = Decode(received); + SetNonce(received, compact, "changed-after-decode"); + + decoded.Items[0].FreshnessChallengeId.ShouldBe("challenge-previously-sent"); + decoded.Items[0].Handle.ShouldBe(First); + decoded.Items[0].Sample.Value.GetBytes().ToArray().ShouldBe(new byte[] { 1, 2, 3 }); + decoded.Items[0].Sample.Version.ShouldBe(21); + decoded.Items[1].FreshnessChallengeId.ShouldBeNull(); + decoded.Items[1].Handle.ShouldBe(Second); + decoded.Items[1].Sample.Value.GetScalar().ShouldBe(42); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Wire_nonce_does_not_manufacture_receiver_observation_time_or_finite_upper_age(bool compact) + { + using var decoded = Decode(W.SubscriptionFrame.Parser.ParseFrom(Values(compact).ToByteArray())); + decoded.Items[0].FreshnessChallengeId.ShouldNotBeNull(); + decoded.Items[0].FreshnessObservedTimestamp.ShouldBeNull(); + decoded.Items[0].AgeBounds.Lower.ShouldBe(TimeSpan.FromMilliseconds(7)); + decoded.Items[0].AgeBounds.Upper.ShouldBeNull(); + decoded.Items[1].FreshnessChallengeId.ShouldBeNull(); + decoded.Items[1].FreshnessObservedTimestamp.ShouldBeNull(); + decoded.Items[1].AgeBounds.Upper.ShouldBeNull(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Unnegotiated_age_extension_cannot_confer_a_freshness_witness(bool compact) + { + using var oldPeer = Decode(Values(compact), negotiatedAge: false); + oldPeer.Items[0].FreshnessChallengeId.ShouldBeNull(); + oldPeer.Items[0].FreshnessObservedTimestamp.ShouldBeNull(); + oldPeer.Items[0].AgeBounds.ShouldBe(default(DataAgeBounds)); + oldPeer.Items[0].Readiness.ShouldBe(DataReadiness.Unspecified); + + var omitted = Values(compact, negotiatedAge: false); + if (compact) omitted.CompactValues.Items[0].HasFreshnessChallengeId.ShouldBeFalse(); + else omitted.Values.Items[0].HasFreshnessChallengeId.ShouldBeFalse(); + } + + [Fact] + public void Capability_requires_explicit_peer_bit_even_with_a_newer_protocol_minor() + { + var limits = new DataLimits(10, 10, 65536, 20, 2, 65536, + TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); + var capabilities = new DataCapabilities(1, 99, Serving, DataReadiness.Ready, DataOperations.Subscribe, + new HashSet { DataValueKind.Int32 }, limits, true, 1, "cluster", SubscriptionAgeReadiness: true); + var wire = DataProtoMapper.EncodeCapabilities(capabilities); + var oldPeer = W.CapabilitiesResponse.Parser.ParseFrom(wire.ToByteArray()); + DataProtoMapper.DecodeCapabilities(oldPeer).SubscriptionFreshnessChallenges.ShouldBeFalse(); + + var enabled = DataProtoMapper.EncodeCapabilities(capabilities with { SubscriptionFreshnessChallenges = true }); + DataProtoMapper.DecodeCapabilities(W.CapabilitiesResponse.Parser.ParseFrom(enabled.ToByteArray())) + .SubscriptionFreshnessChallenges.ShouldBeTrue(); + } + + [Fact] + public void Additive_wire_fields_preserve_numbers_types_and_nonce_presence() + { + var capability = W.CapabilitiesResponse.Descriptor.FindFieldByName("subscription_freshness_challenges"); + capability.FieldNumber.ShouldBe(14); + capability.FieldType.ShouldBe(FieldType.Bool); + var command = W.SubscriptionCommand.Descriptor.FindFieldByName("freshness_challenge"); + command.FieldNumber.ShouldBe(9); + command.FieldType.ShouldBe(FieldType.Message); + command.ContainingOneof.ShouldNotBeNull(); + foreach (var (descriptor, number) in new[] { (W.ValueUpdate.Descriptor, 5), (W.CompactUpdate.Descriptor, 10) }) + { + var nonce = descriptor.FindFieldByName("freshness_challenge_id"); + nonce.FieldNumber.ShouldBe(number); + nonce.FieldType.ShouldBe(FieldType.String); + nonce.ToProto().Proto3Optional.ShouldBeTrue(); + } + } + + [Fact] + public void Challenge_round_trip_preserves_handle_revisions_and_copies_the_requested_set() + { + var requested = new List { First, Second }; + var command = new ChallengeSubscriptionFreshness("subscription", 3, "challenge-id", TimeSpan.FromSeconds(2), requested); + var wire = DataProtoMapper.EncodeCommand(command); + requested.Clear(); + var received = W.SubscriptionCommand.Parser.ParseFrom(wire.ToByteArray()); + var decoded = DataProtoMapper.DecodeCommand(received).ShouldBeOfType(); + received.FreshnessChallenge.Items.Clear(); + + decoded.SubscriptionId.ShouldBe("subscription"); + decoded.StreamEpoch.ShouldBe(3); + decoded.CommandId.ShouldBe("challenge-id"); + decoded.AcknowledgementTimeout.ShouldBe(TimeSpan.FromSeconds(2)); + decoded.Items.ShouldBe(new[] { First, Second }); + } + + [Theory] + [InlineData("subscription")] + [InlineData("epoch")] + [InlineData("zero-handle")] + [InlineData("zero-revision")] + [InlineData("blank-nonce")] + [InlineData("zero-timeout")] + public void Malformed_challenge_identity_and_handle_generations_are_rejected(string malformed) + { + var wire = Challenge(); + switch (malformed) + { + case "subscription": wire.FreshnessChallenge.Items[0].SubscriptionId = "another-stream"; break; + case "epoch": wire.FreshnessChallenge.Items[0].StreamEpoch = 4; break; + case "zero-handle": wire.FreshnessChallenge.Items[0].Handle_ = 0; break; + case "zero-revision": wire.FreshnessChallenge.Items[0].ItemRevision = 0; break; + case "blank-nonce": wire.CommandId = " "; break; + case "zero-timeout": wire.AcknowledgementTimeoutTicks = 0; break; + } + Should.Throw(() => DataProtoMapper.DecodeCommand(wire)); + } + + [Fact] + public void Repeated_challenge_handles_cannot_evade_receiver_item_or_byte_limits() + { + var wire = Challenge(); + wire.FreshnessChallenge.Items[1] = wire.FreshnessChallenge.Items[0].Clone(); + Should.Throw(() => DataProtoMapper.DecodeCommand(wire, new DataDecodeLimits(1, 65536, 100))); + wire.CommandId = new string('n', 4096); + Should.Throw(() => DataProtoMapper.DecodeCommand(wire, new DataDecodeLimits(2, 1024, 100))); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Value_nonce_is_charged_to_receiver_bytes_before_owned_payload_decode(bool compact) + { + var wire = Values(compact); + SetNonce(wire, compact, new string('n', 4096)); + Should.Throw(() => Decode(wire, maxBytes: 1024)); + // A parsed protobuf that fits the wire ceiling must also fit the + // conservative receiver ownership charge, including nonce strings. + Should.Throw(() => Decode(wire, maxBytes: wire.CalculateSize() + 1)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Oversized_nonce_within_frame_budget_cannot_become_a_freshness_witness(bool compact) + { + var wire = Values(compact); + SetNonce(wire, compact, new string('n', 32)); + using (var accepted = Decode(wire)) + accepted.Items[0].FreshnessChallengeId.ShouldBe(new string('n', 32)); + + SetNonce(wire, compact, new string('n', 33)); + using var unknown = Decode(W.SubscriptionFrame.Parser.ParseFrom(wire.ToByteArray())); + unknown.Items[0].FreshnessChallengeId.ShouldBeNull(); + unknown.Items[0].FreshnessObservedTimestamp.ShouldBeNull(); + unknown.Items[0].AgeBounds.Lower.ShouldBe(TimeSpan.FromMilliseconds(7)); + unknown.Items[0].AgeBounds.Upper.ShouldBeNull(); + unknown.Items[0].Sample.Value.GetBytes().ToArray().ShouldBe(new byte[] { 1, 2, 3 }); + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataMetadataLeaseCodecTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataMetadataLeaseCodecTests.cs new file mode 100644 index 000000000..e4b1b64b6 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataMetadataLeaseCodecTests.cs @@ -0,0 +1,178 @@ +using Google.Protobuf; +using Google.Protobuf.Reflection; +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("Feature", "GrpcData"), Trait("Phase", "P11"), Trait("Category", "Unit")] +public sealed class GrpcDataMetadataLeaseCodecTests +{ + private static readonly ServingIdentity Serving = new("node", "incarnation", "Primary", 11, 12, 13); + private static readonly MetadataLease Lease = new(11, 12, TimeSpan.FromTicks(1234567)); + + private static DataMetadata Metadata(string identifier = "driver/device/tag", DataRealm realm = DataRealm.Raw) => + new(new(new("cluster", "urn:fixture:" + realm, "string", identifier), realm, null, 0, + realm == DataRealm.Uns ? "area/line/equipment" : identifier), + "tag", "Variable", DataValueKind.Int32, -1, Array.Empty(), false, + DataOperations.Browse | DataOperations.Metadata | DataOperations.Read, 11, "source-id", "unit", false); + + private static DataItemResult Good(string correlation = "request-slot-0") => + new(correlation, DataItemStatus.Good, Metadata(), null, Lease); + + private static DataCapabilities Capabilities() => new(1, 99, Serving, DataReadiness.Ready, + DataOperations.Metadata, new HashSet { DataValueKind.Int32 }, + new(10, 10, 65536, 10, 1, 65536, TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)), + true, 1, "cluster", SubscriptionAgeReadiness: true, ResponseServingIdentity: true, + SubscriptionFreshnessChallenges: true); + + [Fact] + public void Exact_metadata_result_can_negotiate_a_per_item_authority_lease() + { + W.CapabilitiesResponse.Descriptor.FindFieldByName("metadata_item_leases").ShouldNotBeNull().FieldNumber.ShouldBe(15); + W.MetadataResult.Descriptor.FindFieldByName("lease").ShouldNotBeNull().FieldNumber.ShouldBe(5); + typeof(DataCapabilities).GetProperty("MetadataItemLeases").ShouldNotBeNull(); + typeof(DataItemResult).GetProperty("Lease").ShouldNotBeNull(); + } + + [Fact] + public void Serialized_response_preserves_each_items_lease_view_revision_correlation_and_serving_envelope() + { + var first = Good(); + var second = new DataItemResult("request-slot-1", DataItemStatus.Good, + Metadata("EQ-container", DataRealm.Uns), null, Lease with { Duration = TimeSpan.FromTicks(9876543) }); + var wire = DataProtoMapper.EncodeMetadataResponse([first, second, + new("request-slot-2", DataItemStatus.Denied, null, "denied"), + Good("legacy-peer") with { Lease = null }]); + wire.Serving = DataProtoMapper.EncodeServing(Serving); + var received = W.MetadataResponse.Parser.ParseFrom(wire.ToByteArray()); + var decoded = DataProtoMapper.DecodeMetadataResponse(received); + received.Items[0].Lease.CatalogEpoch = 999; + received.Items[1].Lease.DurationTicks = 1; + + DataProtoMapper.DecodeServing(received.Serving).ShouldBe(Serving); + decoded.Select(item => item.CorrelationId).ShouldBe(new[] { "request-slot-0", "request-slot-1", "request-slot-2", "legacy-peer" }); + decoded[0].Lease.ShouldBe(Lease); + decoded[1].Lease.ShouldBe(second.Lease); + decoded[0].Value.ShouldNotBeNull().View.ShouldBe(first.Value!.View); + decoded[1].Value.ShouldNotBeNull().View.ShouldBe(second.Value!.View); + decoded[0].Value!.CatalogRevision.ShouldBe(11); + decoded[1].Value!.CatalogRevision.ShouldBe(11); + decoded[1].Value!.View.Address.Identifier.ShouldBe("EQ-container"); + decoded[1].Value!.View.Subject.ShouldBe("area/line/equipment"); + decoded[2].Status.ShouldBe(DataItemStatus.Denied); + decoded[2].Value.ShouldBeNull(); + decoded[2].Lease.ShouldBeNull(); + decoded[3].Status.ShouldBe(DataItemStatus.Good); + decoded[3].Lease.ShouldBeNull(); + } + + [Fact] + public void Missing_per_item_lease_stays_unknown_and_is_not_borrowed_from_another_result() + { + var wire = DataProtoMapper.EncodeMetadataResponse([Good(), Good("other") with { Lease = null }]); + wire.Items[0].Lease.ShouldNotBeNull(); + wire.Items[1].Lease.ShouldBeNull(); + var decoded = DataProtoMapper.DecodeMetadataResponse(W.MetadataResponse.Parser.ParseFrom(wire.ToByteArray())); + decoded[0].Lease.ShouldBe(Lease); + decoded[1].Lease.ShouldBeNull(); + typeof(DataItemResult).GetProperty("Lease")!.GetValue( + new DataItemResult("old-constructor", DataItemStatus.Good, Metadata(), null)).ShouldBeNull(); + } + + [Fact] + public void Older_peer_defaults_to_no_metadata_lease_capability_despite_newer_minor_or_other_extensions() + { + var capabilities = Capabilities(); + var oldPeer = DataProtoMapper.EncodeCapabilities(capabilities); + DataProtoMapper.DecodeCapabilities(W.CapabilitiesResponse.Parser.ParseFrom(oldPeer.ToByteArray())) + .MetadataItemLeases.ShouldBeFalse(); + + var advertised = DataProtoMapper.EncodeCapabilities(capabilities with { MetadataItemLeases = true }); + var decoded = DataProtoMapper.DecodeCapabilities(W.CapabilitiesResponse.Parser.ParseFrom(advertised.ToByteArray())); + decoded.MetadataItemLeases.ShouldBeTrue(); + decoded.ProtocolMinor.ShouldBe(99); + decoded.Serving.ShouldBe(Serving); + } + + [Fact] + public void Additive_lease_fields_have_explicit_types_and_capability_does_not_imply_readiness() + { + var capability = W.CapabilitiesResponse.Descriptor.FindFieldByName("metadata_item_leases"); + capability.FieldNumber.ShouldBe(15); + capability.FieldType.ShouldBe(FieldType.Bool); + var lease = W.MetadataResult.Descriptor.FindFieldByName("lease"); + lease.FieldNumber.ShouldBe(5); + lease.FieldType.ShouldBe(FieldType.Message); + lease.MessageType.FullName.ShouldBe(W.Lease.Descriptor.FullName); + + var wire = DataProtoMapper.EncodeCapabilities(Capabilities() with { MetadataItemLeases = true, Readiness = DataReadiness.Unavailable }); + DataProtoMapper.DecodeCapabilities(wire).Readiness.ShouldBe(DataReadiness.Unavailable); + wire.Readiness = (int)DataReadiness.Unspecified; + Should.Throw(() => DataProtoMapper.DecodeCapabilities(wire)); + } + + [Theory] + [InlineData(0L, 12L, 1L)] + [InlineData(-1L, 12L, 1L)] + [InlineData(11L, 0L, 1L)] + [InlineData(11L, -1L, 1L)] + [InlineData(11L, 12L, 0L)] + [InlineData(11L, 12L, -1L)] + public void Invalid_authority_epochs_and_duration_are_rejected_on_encode_and_decode(long catalog, long authority, long ticks) + { + var invalid = new MetadataLease(catalog, authority, TimeSpan.FromTicks(ticks)); + Should.Throw(() => DataProtoMapper.EncodeMetadataResult(Good() with { Lease = invalid })); + var wire = DataProtoMapper.EncodeMetadataResult(Good()); + wire.Lease = new W.Lease { CatalogEpoch = catalog, AuthorityEpoch = authority, DurationTicks = ticks }; + Should.Throw(() => DataProtoMapper.DecodeMetadataResult(wire)); + } + + [Theory] + [InlineData(DataItemStatus.Good, false)] + [InlineData(DataItemStatus.Denied, false)] + [InlineData(DataItemStatus.Denied, true)] + [InlineData(DataItemStatus.Unavailable, true)] + [InlineData(DataItemStatus.NotFound, false)] + public void Only_a_successful_metadata_value_can_carry_a_lease(DataItemStatus status, bool hasValue) + { + var invalid = Good() with { Status = status, Value = hasValue ? Metadata() : null }; + Should.Throw(() => DataProtoMapper.EncodeMetadataResult(invalid)); + var wire = DataProtoMapper.EncodeMetadataResult(Good()); + wire.Status = (int)status; + if (!hasValue) wire.Value = null; + Should.Throw(() => DataProtoMapper.DecodeMetadataResult(wire)); + } + + [Theory] + [InlineData("revision")] + [InlineData("view-address")] + [InlineData("view-mapping")] + public void A_lease_cannot_make_malformed_metadata_decodable(string malformed) + { + var wire = DataProtoMapper.EncodeMetadataResult(Good()); + switch (malformed) + { + case "revision": wire.Value.CatalogRevision = 0; break; + case "view-address": wire.Value.View.Address.NamespaceUri = ""; break; + case "view-mapping": wire.Value.View.MappingId = "mapping-without-revision"; break; + } + Should.Throw(() => DataProtoMapper.DecodeMetadataResult(wire)); + } + + [Fact] + public void Leased_metadata_still_obeys_receiver_item_byte_and_owned_decode_budgets() + { + var wire = DataProtoMapper.EncodeMetadataResponse([Good(), Good("second")]); + Should.Throw(() => DataProtoMapper.DecodeMetadataResponse(wire, new DataDecodeLimits(1, 65536, 100))); + Should.Throw(() => DataProtoMapper.DecodeMetadataResponse(wire, new DataDecodeLimits(2, 1, 100))); + Should.Throw(() => DataProtoMapper.DecodeMetadataResponse(wire, + new DataDecodeLimits(2, wire.CalculateSize() + 1, 100))); + + var large = DataProtoMapper.EncodeMetadataResult(Good() with { Value = Metadata() with { BrowseName = new string('x', 4096) } }); + Should.Throw(() => DataProtoMapper.DecodeMetadataResult(large, new DataDecodeLimits(1, 1024, 100))); + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/ProjectedInputBudgetTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/ProjectedInputBudgetTests.cs index 2e943d24a..7e1b9789b 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/ProjectedInputBudgetTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/ProjectedInputBudgetTests.cs @@ -5,9 +5,10 @@ using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.DataConnections; +[Trait("Feature", "GrpcData"), Trait("Phase", "P08")] public sealed class ProjectedInputBudgetTests { - [Fact, Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + [Fact] public void Leases_bound_retained_bytes_across_owners_and_release_once() { var now = DateTime.UtcNow; @@ -36,7 +37,7 @@ public sealed class ProjectedInputBudgetTests afterRetirement.ShouldNotBeNull().Dispose(); } - [Fact, Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + [Fact] public void Unsupported_mutable_values_fail_closed() { var now = DateTime.UtcNow; @@ -45,7 +46,7 @@ public sealed class ProjectedInputBudgetTests lease.ShouldBeNull(); } - [Fact, Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + [Fact] public void Snapshot_enumeration_stops_at_the_entry_limit() { var seen = 0; diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation.Tests/GrpcDataCalculationOwnershipTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation.Tests/GrpcDataCalculationOwnershipTests.cs index 471e8ce2f..7af3f5e80 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation.Tests/GrpcDataCalculationOwnershipTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation.Tests/GrpcDataCalculationOwnershipTests.cs @@ -8,6 +8,7 @@ using ZB.MOM.WW.OtOpcUa.Core.Scripting; namespace ZB.MOM.WW.OtOpcUa.Driver.Calculation.Tests; +[Trait("Feature", "GrpcData"), Trait("Phase", "P08")] public sealed class GrpcDataCalculationOwnershipTests { private sealed class Proof : IProjectedSamplePublicationProof @@ -33,7 +34,7 @@ public sealed class GrpcDataCalculationOwnershipTests public IReadOnlyCollection QuarantinedKeys(ScriptContextKind kind) => []; } - [Fact(Timeout = 30000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + [Fact(Timeout = 30000)] public async Task Large_projected_fanout_replaces_pending_entries_with_linear_queue_work() { const int tagCount = 200; @@ -63,7 +64,7 @@ public sealed class GrpcDataCalculationOwnershipTests finally { runner.Release(); } } - [Fact(Timeout = 30000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + [Fact(Timeout = 30000)] public async Task Pending_input_remains_charged_after_the_runner_finishes_while_output_is_blocked() { const string source = "return ctx.GetTag(\"src/a\").Value ?? 0;"; @@ -94,7 +95,7 @@ public sealed class GrpcDataCalculationOwnershipTests finally { unblock.Set(); runner.Release(); } } - [Fact(Timeout = 30000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + [Fact(Timeout = 30000)] public async Task Revocation_during_an_output_callback_is_checked_before_the_next_acceptance() { const string source = "return (int)ctx.GetTag(\"src/a\").Value + 1;"; @@ -131,7 +132,7 @@ public sealed class GrpcDataCalculationOwnershipTests finally { unblock.Set(); runner.Release(); } } - [Fact(Timeout = 30000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + [Fact(Timeout = 30000)] public async Task Rejected_projected_values_coalesce_while_the_pump_is_blocked() { const string source = "return (int)ctx.GetTag(\"src/a\").Value + 1;"; @@ -171,7 +172,7 @@ public sealed class GrpcDataCalculationOwnershipTests } } - [Theory(Timeout = 30000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + [Theory(Timeout = 30000)] [InlineData(true)] [InlineData(false)] public async Task Blocked_pump_coalesces_projected_triggers_and_rechecks_captured_source(bool revokeOldProof) diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataFreshnessCommandTlsWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataFreshnessCommandTlsWireTests.cs new file mode 100644 index 000000000..f8f5724a9 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataFreshnessCommandTlsWireTests.cs @@ -0,0 +1,163 @@ +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Grpc.Core; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests.DataConnections; + +[Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P11Wire")] +public sealed class GrpcDataFreshnessCommandTlsWireTests +{ + private static readonly ServingIdentity Serving = new("node", "boot", "Primary", 1, 1, 1); + private static readonly DataView View = new(new("cluster", "urn:test", "string", "source"), DataRealm.Raw, null, 0, "source"); + private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 1, 65536); + private static readonly DataSubscriptionSettings Settings = new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); + + [Fact(Timeout = 30000)] + public async Task Production_tls_service_forwards_challenge_and_remote_client_receives_causal_freshness_bound() + { + var ct = TestContext.Current.CancellationToken; + var origin = new Origin(); + await using var fixture = await GrpcDataWireFixture.StartAsync(HttpProtocols.Http2, new(origin.Create)); + var trust = new DataConnectionTrustPolicy(1, [fixture.Ca]); + 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, "cluster", "node"), + [new UriBuilder("https", "localhost", fixture.TlsAddress.Port).Uri], new Security(fixture, trust), + manager.Acquire("link"), 65536, 1); + await using var stream = await connection.SubscribeAsync(ct); + (stream as IDataSubscriptionFreshnessSupport).ShouldNotBeNull().SupportsFreshnessChallenges.ShouldBeTrue(); + await stream.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), + [new("item", View, Settings)], false, TimeSpan.FromSeconds(30), Budget), ct); + await using var reader = stream.ReadAllAsync(ct).GetAsyncEnumerator(ct); + (await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeTrue(); + var handle = reader.Current.ShouldBeOfType().Items.Single().Handle.ShouldNotBeNull(); + (await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin); + (await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeTrue(); + using (var initial = reader.Current.ShouldBeOfType()) + initial.Items.Single().AgeBounds.Upper.ShouldBeNull(); + (await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Kind.ShouldBe(DataStreamControlKind.SnapshotEnd); + await stream.SendAsync(new ChallengeSubscriptionFreshness("s", 1, "freshness-1", TimeSpan.FromSeconds(5), [handle]), ct); + (await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeTrue(); + reader.Current.ShouldBeOfType().CommandId.ShouldBe("freshness-1"); + origin.ChallengeReceived.ShouldBeTrue(); + (await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin); + (await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeTrue(); + using (var value = reader.Current.ShouldBeOfType()) + { + var item = value.Items.ShouldHaveSingleItem(); + item.Sample.Value.GetScalar().ShouldBe(42); item.Sample.Serving.ShouldBe(Serving); + item.AgeBounds.Upper.ShouldNotBeNull(); + item.FreshnessObservedTimestamp.ShouldNotBeNull(); + item.AgeBounds.IsFresh(TimeSpan.FromSeconds(5)).ShouldBeTrue(); + } + } + + [Fact(Timeout = 30000)] + public async Task Production_tls_service_rejects_raw_challenge_when_origin_does_not_advertise_support() + { + var ct = TestContext.Current.CancellationToken; + var origin = new Origin(negotiated: false); + await using var fixture = await GrpcDataWireFixture.StartAsync(HttpProtocols.Http2, new(origin.Create)); + using var channel = fixture.TlsChannel(fixture.Ca, "localhost"); + var client = new W.DataConnectionService.DataConnectionServiceClient(channel); + var caps = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 5 }, fixture.Headers(), cancellationToken: ct); + caps.SubscriptionFreshnessChallenges.ShouldBeFalse(); + using var call = client.Subscribe(fixture.Headers(), cancellationToken: ct); + await call.RequestStream.WriteAsync(DataProtoMapper.EncodeCommand(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), + [new("item", View, Settings)], false, TimeSpan.FromSeconds(30), Budget)), ct); + for (var i = 0; i < 4; i++) + (await call.ResponseStream.MoveNext(ct).WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeTrue(); + await call.RequestStream.WriteAsync(DataProtoMapper.EncodeCommand(new ChallengeSubscriptionFreshness("s", 1, + "freshness-1", TimeSpan.FromSeconds(5), [new DataItemHandle("s", 1, 1, 1)])), ct); + var error = await Should.ThrowAsync(async () => + await call.ResponseStream.MoveNext(ct).WaitAsync(TimeSpan.FromSeconds(5), ct)); + error.StatusCode.ShouldBe(StatusCode.InvalidArgument); + origin.ChallengeReceived.ShouldBeFalse(); + } + + private sealed class Security(GrpcDataWireFixture fixture, DataConnectionTrustPolicy trust) : IDataConnectionSecurityProvider + { + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string id, Uri endpoint, CancellationToken ct) => + ValueTask.FromResult(new("credential", trust.Fingerprint, fixture.Bearer, trust.CreateHandler)); + } + private sealed class Origin(bool negotiated = true) + { + private readonly bool _negotiated = negotiated; + private int _challengeReceived; + internal bool ChallengeReceived => Volatile.Read(ref _challengeReceived) != 0; + internal IDataConnection Create(DataTarget target) => new Connection(this, target); + private sealed class Connection(Origin owner, DataTarget target) : IDataConnection, IDataConnectionPublicationGate, IDataConnectionDiscoveryGate + { + public DataTarget Target => target; + public TimeProvider Clock => TimeProvider.System; + public bool CanPublish(ServingIdentity expected) => expected == Serving; + public bool CanPublishCapabilities(DataCapabilities expected) => expected.Serving == Serving && expected.Readiness == DataReadiness.Ready; + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken ct) => Task.FromResult(new DataCapabilities(1, 5, Serving, + DataReadiness.Ready, DataOperations.Subscribe, new HashSet { DataValueKind.Int32 }, + new(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)), + false, 0, "cluster", true, true, false, owner._negotiated)); + public Task SubscribeAsync(CancellationToken ct) => Task.FromResult(new Stream(owner)); + public Task BrowseAsync(BrowseRequest request, CancellationToken ct) => throw new NotSupportedException(); + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken ct) => throw new NotSupportedException(); + public Task> ReadAsync(ReadRequest request, CancellationToken ct) => throw new NotSupportedException(); + public Task> WriteAsync(WriteBatch request, CancellationToken ct) => throw new NotSupportedException(); + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + private sealed class Stream(Origin owner) : IDataSubscriptionTransport + { + private readonly TaskCompletionSource _open = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _challenge = new(TaskCreationOptions.RunContinuationsAsynchronously); + public Task SendAsync(DataSubscriptionCommand command, CancellationToken ct) + { + if (command is OpenSubscription open) _open.TrySetResult(open); + else if (command is ChallengeSubscriptionFreshness challenge) + { Interlocked.Exchange(ref owner._challengeReceived, 1); _challenge.TrySetResult(challenge); } + else throw new ArgumentException("Unexpected command."); + return Task.CompletedTask; + } + public IAsyncEnumerable ReadAllAsync(CancellationToken ct) => throw new NotSupportedException(); + public async Task RunDeliveryAsync(IDataSubscriptionDeliverySink sink, CancellationToken ct) + { + var open = await _open.Task.WaitAsync(ct); + var handle = new DataItemHandle(open.SubscriptionId, open.StreamEpoch, 1, 1); + async Task Send(DataSubscriptionFrame frame) + { + try + { + using var prepared = await sink.PrepareAsync(frame, 16384, ct); + ((IDataPreparedSubscriptionPublication)prepared).SetPublicationGuard(() => !ct.IsCancellationRequested); + await sink.WriteAsync(prepared, ct); + } + finally { (frame as IDisposable)?.Dispose(); } + } + async Task Snapshot(long start, string? challenge) + { + await Send(new DataSubscriptionControl(open.SubscriptionId, open.StreamEpoch, start, DataStreamControlKind.SnapshotBegin, [], 1, 1, null)); + await Send(new DataSubscriptionValues(open.SubscriptionId, open.StreamEpoch, start + 1, true, + [new(handle, new(DataValue.FromScalar(DataValueKind.Int32, 42), 0, null, null, Serving, 1), + new(TimeSpan.Zero, null), DataReadiness.Ready, challenge)])); + await Send(new DataSubscriptionControl(open.SubscriptionId, open.StreamEpoch, start + 2, DataStreamControlKind.SnapshotEnd, [], 1, 1, null)); + } + await Send(new DataSubscriptionAck(open.SubscriptionId, open.StreamEpoch, 1, open.CommandId, + [new(open.Items[0].ClientItemId, DataItemStatus.Good, handle, open.Items[0].Settings, null)])); + await Snapshot(2, null); + var challenge = await _challenge.Task.WaitAsync(ct); + await Send(new DataSubscriptionAck(open.SubscriptionId, open.StreamEpoch, 5, challenge.CommandId, + [new(open.Items[0].ClientItemId, DataItemStatus.Good, handle, open.Items[0].Settings, null)])); + await Snapshot(6, challenge.CommandId); + await Task.Delay(Timeout.InfiniteTimeSpan, ct); + } + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataListenerIsolationWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataListenerIsolationWireTests.cs new file mode 100644 index 000000000..6834f4efd --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataListenerIsolationWireTests.cs @@ -0,0 +1,54 @@ +using System.Net; +using Grpc.Core; +using Grpc.Net.Client; +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests.DataConnections; + +[Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P07Wire"), Trait("Phase", "P10")] +public sealed class GrpcDataListenerIsolationWireTests +{ + [Fact(Timeout = 30000)] + public async Task Data_rpc_is_denied_on_h2c_listener_while_tls_listener_serves_it() + { + await using var fixture = await GrpcDataWireFixture.StartAsync(HttpProtocols.Http2); + using (var channel = fixture.TlsChannel(fixture.Ca, "localhost")) + { + var response = await new W.DataConnectionService.DataConnectionServiceClient(channel) + .GetCapabilitiesAsync(new() { ProtocolMajor = 1 }, fixture.Headers(), cancellationToken: TestContext.Current.CancellationToken); + response.Serving.NodeId.ShouldBe("node"); + } + var accepted = fixture.Factory.Created; + using var h2c = GrpcChannel.ForAddress(new UriBuilder("http", "localhost", fixture.OtherAddress.Port).Uri); + var denied = await Should.ThrowAsync(async () => await new W.DataConnectionService.DataConnectionServiceClient(h2c) + .GetCapabilitiesAsync(new() { ProtocolMajor = 1 }, fixture.Headers(), cancellationToken: TestContext.Current.CancellationToken)); + denied.StatusCode.ShouldBe(StatusCode.PermissionDenied); + fixture.Factory.Created.ShouldBe(accepted); + + using var http = new HttpClient(new DataConnectionTrustPolicy(1, [fixture.Ca]).CreateHandler()); + using var request = new HttpRequestMessage(HttpMethod.Get, new UriBuilder("https", "localhost", fixture.TlsAddress.Port, "healthz").Uri) + { Version = HttpVersion.Version20, VersionPolicy = HttpVersionPolicy.RequestVersionExact }; + using var responseOnDataPort = await http.SendAsync(request, TestContext.Current.CancellationToken); + responseOnDataPort.Headers.GetValues("grpc-status").ShouldHaveSingleItem().ShouldBe("7"); + } + + [Fact(Timeout = 30000)] + public async Task Data_path_is_denied_on_http_ui_listener_without_disrupting_ui_health() + { + await using var fixture = await GrpcDataWireFixture.StartAsync(HttpProtocols.Http1); + var address = new UriBuilder("http", "localhost", fixture.OtherAddress.Port).Uri; + using var http = new HttpClient(); + (await http.GetStringAsync(new Uri(address, "/healthz"), TestContext.Current.CancellationToken)).ShouldBe("ok"); + using var request = new HttpRequestMessage(HttpMethod.Post, new Uri(address, "/data_connection.v1.DataConnectionService/GetCapabilities")) + { Content = new ByteArrayContent([0, 0, 0, 0, 0]), Version = HttpVersion.Version11, VersionPolicy = HttpVersionPolicy.RequestVersionExact }; + request.Content.Headers.ContentType = new("application/grpc"); + using var response = await http.SendAsync(request, TestContext.Current.CancellationToken); + response.StatusCode.ShouldBe(HttpStatusCode.OK); + response.Headers.GetValues("grpc-status").ShouldHaveSingleItem().ShouldBe("7"); + fixture.Factory.Created.ShouldBe(0); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataSampleFidelityTlsWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataSampleFidelityTlsWireTests.cs new file mode 100644 index 000000000..40cda38ed --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataSampleFidelityTlsWireTests.cs @@ -0,0 +1,81 @@ +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests.DataConnections; + +[Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P10Wire")] +public sealed class GrpcDataSampleFidelityTlsWireTests +{ + private static readonly ServingIdentity Serving = new("node", "boot", "Primary", 1, 1, 1); + private static readonly DataView View = new(new("cluster", "urn:test", "string", "source"), DataRealm.Raw, null, 0, "source"); + private static readonly DateTimeOffset SourceTime = new DateTimeOffset(2026, 1, 2, 3, 4, 5, TimeSpan.Zero).AddTicks(1234); + private static readonly DateTimeOffset ServerTime = new DateTimeOffset(2026, 1, 2, 3, 4, 7, TimeSpan.Zero).AddTicks(5678); + private const uint Quality = 0x40A40480u; + private const long Version = 73; + + [Fact(Timeout = 30000)] + public async Task Production_tls_read_preserves_one_controlled_samples_independent_timestamps_status_value_and_version() + { + var ct = TestContext.Current.CancellationToken; + await using var fixture = await GrpcDataWireFixture.StartAsync(HttpProtocols.Http2, new(target => new Origin(target))); + var trust = new DataConnectionTrustPolicy(1, [fixture.Ca]); + 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, "cluster", "node"), + [new UriBuilder("https", "localhost", fixture.TlsAddress.Port).Uri], new Security(fixture, trust), + manager.Acquire("link"), 65536, 1); + var results = await connection.ReadAsync(new ReadRequest([new ReadItem("one", View, TimeSpan.FromSeconds(5))], + new DataBudget(TimeSpan.FromSeconds(5), 1, 65536)), ct); + try + { + var result = results.ShouldHaveSingleItem(); + result.Status.ShouldBe(DataItemStatus.Good); + result.Readiness.ShouldBe(DataReadiness.Ready); + var sample = result.Sample.ShouldNotBeNull(); + sample.Value.GetScalar().ShouldBe(42); + sample.StatusCode.ShouldBe(Quality); + sample.SourceTimestampUtc.ShouldBe(SourceTime); + sample.ServerTimestampUtc.ShouldBe(ServerTime); + sample.Version.ShouldBe(Version); + sample.Serving.ShouldBe(Serving); + } + finally { foreach (var result in results) result.Dispose(); } + } + + private sealed class Security(GrpcDataWireFixture fixture, DataConnectionTrustPolicy trust) : IDataConnectionSecurityProvider + { + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string id, Uri endpoint, CancellationToken ct) => + ValueTask.FromResult(new("credential", trust.Fingerprint, fixture.Bearer, trust.CreateHandler)); + } + private sealed class Lease : IDataPublicationLease + { + public bool IsValid => true; + public void Dispose() { } + } + private sealed class Origin(DataTarget target) : IDataConnection, IDataConnectionPublicationGate, IDataConnectionDiscoveryGate + { + public DataTarget Target => target; + public TimeProvider Clock => TimeProvider.System; + public bool CanPublish(ServingIdentity expected) => expected == Serving; + public bool CanPublishCapabilities(DataCapabilities expected) => expected.Serving == Serving && expected.Readiness == DataReadiness.Ready; + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken ct) => Task.FromResult(new DataCapabilities(1, 5, Serving, + DataReadiness.Ready, DataOperations.Read, new HashSet { DataValueKind.Int32 }, + new(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)), + false, 0, "cluster", true, true)); + public Task> ReadAsync(ReadRequest request, CancellationToken ct) => + Task.FromResult>([new(request.Items.Single().CorrelationId, DataItemStatus.Good, DataReadiness.Ready, + TimeSpan.Zero, new(DataValue.FromScalar(DataValueKind.Int32, 42), Quality, SourceTime, ServerTime, Serving, Version), + null, new Lease(), new(TimeSpan.Zero, TimeSpan.Zero))]); + public Task SubscribeAsync(CancellationToken ct) => throw new NotSupportedException(); + public Task BrowseAsync(BrowseRequest request, CancellationToken ct) => throw new NotSupportedException(); + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken ct) => throw new NotSupportedException(); + public Task> WriteAsync(WriteBatch request, CancellationToken ct) => throw new NotSupportedException(); + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataTlsWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataTlsWireTests.cs new file mode 100644 index 000000000..b310c9f1d --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataTlsWireTests.cs @@ -0,0 +1,190 @@ +using System.Net; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using Grpc.Core; +using Grpc.Net.Client; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; +using ZB.MOM.WW.OtOpcUa.Host.Grpc; +using ZB.MOM.WW.OtOpcUa.Host.OpcUa; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests.DataConnections; + +[Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P07Wire"), Trait("Phase", "P10")] +public sealed class GrpcDataTlsWireTests +{ + [Fact(Timeout = 30000)] + public async Task Trusted_ca_and_san_reach_the_authenticated_service_wrong_ca_and_name_fail_tls() + { + await using var fixture = await GrpcDataWireFixture.StartAsync(HttpProtocols.Http2); + using (var channel = fixture.TlsChannel(fixture.Ca, "localhost")) + { + var response = await new W.DataConnectionService.DataConnectionServiceClient(channel) + .GetCapabilitiesAsync(new() { ProtocolMajor = 1 }, fixture.Headers(), cancellationToken: TestContext.Current.CancellationToken); + response.Serving.NodeId.ShouldBe("node"); + fixture.Factory.Created.ShouldBeGreaterThan(0); + } + var accepted = fixture.Factory.Created; + using var other = GrpcDataWireFixture.CreateCa(); + using (var channel = fixture.TlsChannel(other, "localhost")) + { + var error = await Should.ThrowAsync(async () => await new W.DataConnectionService.DataConnectionServiceClient(channel) + .GetCapabilitiesAsync(new() { ProtocolMajor = 1 }, fixture.Headers(), cancellationToken: TestContext.Current.CancellationToken)); + AssertTlsValidationFailure(error); + } + using (var channel = fixture.TlsChannel(fixture.Ca, "127.0.0.1")) + { + var error = await Should.ThrowAsync(async () => await new W.DataConnectionService.DataConnectionServiceClient(channel) + .GetCapabilitiesAsync(new() { ProtocolMajor = 1 }, fixture.Headers(), cancellationToken: TestContext.Current.CancellationToken)); + AssertTlsValidationFailure(error); + } + fixture.Factory.Created.ShouldBe(accepted, "TLS failures must not reach the authenticated data facade"); + } + + private static void AssertTlsValidationFailure(RpcException error) + { + (error.StatusCode is StatusCode.Unavailable or StatusCode.Internal).ShouldBeTrue(); + var cause = error.Status.DebugException; + var sawAuthenticationFailure = false; + while (cause is not null) + { + if (cause is System.Security.Authentication.AuthenticationException) sawAuthenticationFailure = true; + cause = cause.InnerException; + } + sawAuthenticationFailure.ShouldBeTrue("the connection must fail during TLS certificate validation"); + } + + [Theory(Timeout = 30000)] + [InlineData(null)] + [InlineData("invalid")] + public async Task Missing_or_bad_key_is_rejected_on_the_real_tls_listener(string? bearer) + { + await using var fixture = await GrpcDataWireFixture.StartAsync(HttpProtocols.Http2); + using var channel = fixture.TlsChannel(fixture.Ca, "localhost"); + var failure = await Should.ThrowAsync(async () => await new W.DataConnectionService.DataConnectionServiceClient(channel) + .GetCapabilitiesAsync(new() { ProtocolMajor = 1 }, fixture.Headers(bearer, useDefaultBearer: false), cancellationToken: TestContext.Current.CancellationToken)); + failure.StatusCode.ShouldBe(StatusCode.Unauthenticated); + fixture.Factory.Created.ShouldBe(0); + } +} + +/// Ephemeral loopback Kestrel plus in-memory CA and production data admission/service wiring. +internal sealed class GrpcDataWireFixture : IAsyncDisposable +{ + private readonly WebApplication _app; + private readonly X509Certificate2 _server; + private readonly RSA _caKey, _serverKey; + private readonly string _bearer; + internal X509Certificate2 Ca { get; } + internal string Bearer => _bearer; + internal Uri TlsAddress { get; } + internal Uri OtherAddress { get; } + internal WireFactory Factory { get; } + private GrpcDataWireFixture(WebApplication app, X509Certificate2 ca, X509Certificate2 server, RSA caKey, RSA serverKey, + string bearer, Uri tlsAddress, Uri otherAddress, WireFactory factory) + { _app = app; Ca = ca; _server = server; _caKey = caKey; _serverKey = serverKey; _bearer = bearer; TlsAddress = tlsAddress; OtherAddress = otherAddress; Factory = factory; } + + internal static X509Certificate2 CreateCa() + { + using var key = RSA.Create(2048); + var request = new CertificateRequest("CN=grpc-data-unrelated-ca", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); + request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign, true)); + return request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddHours(1)); + } + internal static async Task StartAsync(HttpProtocols otherProtocol, WireFactory? suppliedFactory = null) + { + var caKey = RSA.Create(2048); var serverKey = RSA.Create(2048); + var caRequest = new CertificateRequest("CN=grpc-data-test-ca", caKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + caRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); + caRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign, true)); + var ca = caRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddHours(1)); + var leafRequest = new CertificateRequest("CN=unused", serverKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + leafRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true)); + leafRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true)); + leafRequest.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new("1.3.6.1.5.5.7.3.1") }, true)); + var san = new SubjectAlternativeNameBuilder(); san.AddDnsName("localhost"); leafRequest.CertificateExtensions.Add(san.Build()); + using var unsigned = leafRequest.Create(ca, DateTimeOffset.UtcNow.AddMinutes(-1), DateTimeOffset.UtcNow.AddMinutes(30), [1, 2, 3, 4]); + var server = unsigned.CopyWithPrivateKey(serverKey); + var (bearer, id, hash) = ApiKeySecret.Generate("pepper"); + var authority = new DataPlaneAuthorityState(); + authority.Apply("cluster", "v1", [new ApiKey { ApiKeyId = id, Name = "wire", Principal = "peer", SecretHash = hash, Enabled = true }], + [], new Dictionary>()); + var options = new DataConnectionOptions { Enabled = true, AllowedHosts = ["localhost"], MaxMessageBytes = 65536 }; + var factory = suppliedFactory ?? new WireFactory(); + var builder = WebApplication.CreateBuilder(); + builder.Environment.ApplicationName = typeof(GrpcDataWireFixture).Assembly.GetName().Name!; + builder.WebHost.ConfigureKestrel(k => + { + k.Listen(IPAddress.Loopback, 0, endpoint => { endpoint.Protocols = HttpProtocols.Http2; endpoint.UseHttps(server); }); + k.Listen(IPAddress.Loopback, 0, endpoint => endpoint.Protocols = otherProtocol); + }); + builder.Services.AddSingleton>(Options.Create(options)); + builder.Services.AddSingleton>(Options.Create(new ApiKeyOptions { Pepper = "pepper" })); + builder.Services.AddSingleton(authority); + builder.Services.AddSingleton(TimeProvider.System); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(factory); + builder.Services.AddGrpc(grpc => grpc.Interceptors.Add()); + var app = builder.Build(); + app.UseDataConnectionAdmission(); + app.MapGet("/healthz", () => "ok"); + app.MapGrpcService().AllowAnonymous(); + await app.StartAsync(TestContext.Current.CancellationToken); + var addresses = app.Services.GetRequiredService().Features.Get()!.Addresses.Select(x => new Uri(x)).ToArray(); + var tls = addresses.Single(x => x.Scheme == "https"); var other = addresses.Single(x => x.Scheme == "http"); + options.ListenPort = tls.Port; + return new(app, ca, server, caKey, serverKey, bearer, tls, other, factory); + } + internal Metadata Headers(string? bearer = null, bool useDefaultBearer = true) + { + var headers = new Metadata { { "x-data-target-mode", "Node" }, { "x-data-consistency", "Primary" }, + { "x-data-cluster-id", "cluster" }, { "x-data-node-id", "node" } }; + var credential = useDefaultBearer ? _bearer : bearer; + if (credential is not null) headers.Add("authorization", "Bearer " + credential); + return headers; + } + internal GrpcChannel TlsChannel(X509Certificate2 ca, string host) => GrpcChannel.ForAddress( + new UriBuilder("https", host, TlsAddress.Port).Uri, new GrpcChannelOptions { HttpHandler = new DataConnectionTrustPolicy(1, [ca]).CreateHandler() }); + internal Task StopAsync() => _app.StopAsync(TestContext.Current.CancellationToken); + public async ValueTask DisposeAsync() + { + await _app.DisposeAsync(); _server.Dispose(); Ca.Dispose(); _serverKey.Dispose(); _caKey.Dispose(); + } + internal sealed class WireFactory(Func? create = null) : IDataConnectionFactory + { + private int _created; + internal int Created => Volatile.Read(ref _created); + public IDataConnection Create(DataAuthenticatedContext context, DataTarget target) + { Interlocked.Increment(ref _created); return create?.Invoke(target) ?? new WireConnection(target); } + } + private sealed class WireConnection(DataTarget target) : IDataConnection, IDataConnectionDiscoveryGate + { + private static readonly ServingIdentity Serving = new("node", "boot", "Primary", 1, 1, 1); + public DataTarget Target => target; + public TimeProvider Clock => TimeProvider.System; + public bool CanPublishCapabilities(DataCapabilities expected) => expected.Serving == Serving; + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken token) => Task.FromResult(new DataCapabilities(1, 3, Serving, + DataReadiness.Ready, DataOperations.Browse | DataOperations.Read | DataOperations.Subscribe, + new HashSet { DataValueKind.Int32 }, new(16, 16, 65536, 16, 4, 65536, + TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)), true, 1, "cluster", true, true)); + public Task SubscribeAsync(CancellationToken token) => throw new NotSupportedException(); + public Task BrowseAsync(BrowseRequest request, CancellationToken token) => throw new NotSupportedException(); + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken token) => throw new NotSupportedException(); + public Task> ReadAsync(ReadRequest request, CancellationToken token) => throw new NotSupportedException(); + public Task> WriteAsync(WriteBatch request, CancellationToken token) => throw new NotSupportedException(); + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Configuration/GrpcDataFixtureIsolationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Configuration/GrpcDataFixtureIsolationTests.cs new file mode 100644 index 000000000..0a885d8b8 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Configuration/GrpcDataFixtureIsolationTests.cs @@ -0,0 +1,22 @@ +using Microsoft.AspNetCore.Hosting; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; + +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.Configuration; + +/// The production Host never references or auto-loads the file-command fixture. +[Trait("Feature", "GrpcData")] +[Trait("Category", "Unit")] +[Trait("Phase", "P10")] +public sealed class GrpcDataFixtureIsolationTests +{ + [Fact] + public void NormalHostHasNoFixtureAssemblyReferenceOrStartupAttribute() + { + var host = typeof(DataConnectionRegistration).Assembly; + Assert.DoesNotContain(host.GetReferencedAssemblies(), assembly => assembly.Name == "GrpcDataNodeProbe"); + Assert.DoesNotContain(host.GetCustomAttributes(typeof(HostingStartupAttribute), inherit: false), + attribute => ((HostingStartupAttribute)attribute).HostingStartupType.FullName?.StartsWith("GrpcDataNodeProbe.", StringComparison.Ordinal) == true); + Assert.DoesNotContain(host.GetTypes(), type => type.FullName?.StartsWith("GrpcDataNodeProbe.", StringComparison.Ordinal) == true); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataBundleCommitObserverTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataBundleCommitObserverTests.cs new file mode 100644 index 000000000..07c6bff26 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataBundleCommitObserverTests.cs @@ -0,0 +1,173 @@ +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text.Json; +using Shouldly; +using ZB.MOM.WW.Secrets.Abstractions; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; + +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Phase", "P11")] +public sealed class GrpcDataBundleCommitObserverTests +{ + [Theory] + [InlineData("credential-notice")] + [InlineData("credential-delete")] + [InlineData("trust-notice")] + public async Task Scope_only_observation_waits_for_pending_retirement_completion(string failure) + { + var ct = TestContext.Current.CancellationToken; + var store = new GrpcDataSecretProvisioningTests.MemoryStore(); + var cipher = new GrpcDataSecretProvisioningTests.TestCipher(); + var changes = new DataConnectionSecretChangeHandler(); + var credentials = new DataConnectionSecretProvisioner(store, cipher, + new GrpcDataSecretProvisioningTests.NoopInvalidator(), changes, "cluster", "node"); + var trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "cluster", "node"); + var observer = new DataConnectionBundleCommitObserver(credentials, trust); + await credentials.SetScopeAsync(9, new Dictionary { ["link"] = "secret:data/key" }, ct); + await trust.ApplyScopeAsync(9, ["link"], ct); + await credentials.ApplyAsync(new("cluster", "node", 12, [new("link", "secret:data/key", "test-value", false)], 9), ct); + Action failNotice = _ => throw new InvalidOperationException("controlled notification failure"); + if (failure == "trust-notice") + { + await credentials.SetScopeAsync(10, new Dictionary(), ct); + changes.ConnectionChanged += failNotice; + await Should.ThrowAsync(() => trust.ApplyScopeAsync(10, [], ct)); + changes.ConnectionChanged -= failNotice; + } + else + { + await trust.ApplyScopeAsync(10, [], ct); + if (failure == "credential-notice") changes.ConnectionChanged += failNotice; + else store.FailDelete = true; + if (failure == "credential-notice") + await Should.ThrowAsync(() => credentials.SetScopeAsync(10, new Dictionary(), ct)); + else + await Should.ThrowAsync(() => credentials.SetScopeAsync(10, new Dictionary(), ct)); + changes.ConnectionChanged -= failNotice; + store.FailDelete = false; + } + var pending = await observer.ObserveAsync("fixture-scope-only", ct); + if (failure == "trust-notice") + { pending.TrustScopeVersion.ShouldBeNull(); pending.CredentialScopeVersion.ShouldBe(10); } + else + { pending.CredentialScopeVersion.ShouldBeNull(); pending.TrustScopeVersion.ShouldBe(10); } + await credentials.SetScopeAsync(10, new Dictionary(), ct); + await trust.ApplyScopeAsync(10, [], ct); + var committed = await observer.ObserveAsync("fixture-scope-only", ct); + committed.CredentialScopeVersion.ShouldBe(10); committed.TrustScopeVersion.ShouldBe(10); + committed.CredentialVersion.ShouldBeNull(); committed.TrustVersion.ShouldBeNull(); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Scope_observation_waits_for_interrupted_bundle_notice_and_import_retry(bool credential) + { + var ct = TestContext.Current.CancellationToken; + var store = new GrpcDataSecretProvisioningTests.MemoryStore(); + var cipher = new GrpcDataSecretProvisioningTests.TestCipher(); + var changes = new DataConnectionSecretChangeHandler(); + var credentials = new DataConnectionSecretProvisioner(store, cipher, + new GrpcDataSecretProvisioningTests.NoopInvalidator(), changes, "cluster", "node"); + var trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "cluster", "node"); + var observer = new DataConnectionBundleCommitObserver(credentials, trust); + await credentials.SetScopeAsync(9, new Dictionary { ["link"] = "secret:data/key" }, ct); + await trust.ApplyScopeAsync(9, ["link"], ct); + await credentials.ApplyAsync(new("cluster", "node", 12, [new("link", "secret:data/key", "first", false)], 9), ct); + using var rsa = RSA.Create(2048); + var request = new CertificateRequest("CN=fixture", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-1), DateTimeOffset.UtcNow.AddHours(1)); + await trust.SetAsync("link", 12, [certificate], 9, ct); + Action failNotice = _ => throw new InvalidOperationException("controlled notification failure"); + changes.ConnectionChanged += failNotice; + if (credential) + await Should.ThrowAsync(() => credentials.ApplyAsync(new("cluster", "node", 13, [new("link", "secret:data/key", "second", false)], 9), ct)); + else + await Should.ThrowAsync(() => trust.SetAsync("link", 13, [certificate], 9, ct)); + changes.ConnectionChanged -= failNotice; + var pending = await observer.ObserveAsync("fixture-scope-only", ct); + if (credential) { pending.CredentialScopeVersion.ShouldBeNull(); pending.TrustScopeVersion.ShouldBe(9); } + else { pending.TrustScopeVersion.ShouldBeNull(); pending.CredentialScopeVersion.ShouldBe(9); } + if (credential) + await credentials.ApplyAsync(new("cluster", "node", 13, [new("link", "secret:data/key", "second", false)], 9), ct); + else + await trust.SetAsync("link", 13, [certificate], 9, ct); + var committed = await observer.ObserveAsync("fixture-scope-only", ct); + committed.CredentialScopeVersion.ShouldBe(9); committed.TrustScopeVersion.ShouldBe(9); + } + + [Fact] + public async Task Observer_requires_both_committed_versions_and_never_reads_the_secret_payload() + { + var ct = TestContext.Current.CancellationToken; + var store = new GrpcDataSecretProvisioningTests.MemoryStore(); + var cipher = new PayloadGuardCipher(); + var changes = new DataConnectionSecretChangeHandler(); + var credentials = new DataConnectionSecretProvisioner(store, cipher, + new GrpcDataSecretProvisioningTests.NoopInvalidator(), changes, "cluster", "node"); + var trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "cluster", "node"); + var observer = new DataConnectionBundleCommitObserver(credentials, trust); + await credentials.SetScopeAsync(9, new Dictionary { ["link"] = "secret:data/key" }, ct); + await trust.ApplyScopeAsync(9, ["link"], ct); + var empty = await observer.ObserveAsync("link", ct); + empty.CredentialScopeVersion.ShouldBe(9); empty.TrustScopeVersion.ShouldBe(9); + empty.CredentialVersion.ShouldBeNull(); empty.CredentialDeleted.ShouldBeNull(); + empty.TrustVersion.ShouldBeNull(); empty.TrustRetired.ShouldBeNull(); + await credentials.ApplyAsync(new("cluster", "node", 12, [new("link", "secret:data/key", "unit-bearer-marker", false)], 9), ct); + cipher.DenyPayloadReads = true; + var pendingTrust = await observer.ObserveAsync("link", ct); + pendingTrust.CredentialVersion.ShouldBe(12); pendingTrust.CredentialDeleted.ShouldBe(false); + pendingTrust.TrustVersion.ShouldBeNull(); pendingTrust.TrustRetired.ShouldBeNull(); + using var rsa = RSA.Create(2048); + var request = new CertificateRequest("CN=fixture", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-1), DateTimeOffset.UtcNow.AddHours(1)); + await trust.SetAsync("link", 12, [certificate], 9, ct); + var committed = await observer.ObserveAsync("link", ct); + committed.CredentialScopeVersion.ShouldBe(9); committed.CredentialVersion.ShouldBe(12); + committed.TrustScopeVersion.ShouldBe(9); committed.TrustVersion.ShouldBe(12); + committed.CredentialDeleted.ShouldBe(false); committed.TrustRetired.ShouldBe(false); + JsonSerializer.Serialize(committed).ShouldNotContain("unit-bearer-marker"); + cipher.DenyPayloadReads = false; + await credentials.ApplyAsync(new("cluster", "node", 13, [new("link", "secret:data/key", "new-bearer-marker", false)], 9), ct); + cipher.DenyPayloadReads = true; + var staggered = await observer.ObserveAsync("link", ct); + staggered.CredentialVersion.ShouldBe(13); staggered.TrustVersion.ShouldBe(12); + cipher.DenyPayloadReads = false; + await credentials.ApplyAsync(new("cluster", "node", 14, [new("link", "secret:data/key", null, true)], 9), ct); + await trust.SetAsync("link", 14, [], 9, ct); + cipher.DenyPayloadReads = true; + var tombstones = await observer.ObserveAsync("link", ct); + tombstones.CredentialVersion.ShouldBe(14); tombstones.CredentialDeleted.ShouldBe(true); + tombstones.TrustVersion.ShouldBe(14); tombstones.TrustRetired.ShouldBe(true); + await credentials.SetScopeAsync(10, new Dictionary(), ct); + await trust.ApplyScopeAsync(10, [], ct); + var retired = await observer.ObserveAsync("link", ct); + retired.CredentialScopeVersion.ShouldBe(10); retired.TrustScopeVersion.ShouldBe(10); + retired.CredentialVersion.ShouldBeNull(); retired.CredentialDeleted.ShouldBeNull(); + retired.TrustVersion.ShouldBeNull(); retired.TrustRetired.ShouldBeNull(); + } + + private sealed class PayloadGuardCipher : ISecretCipher + { + private readonly GrpcDataSecretProvisioningTests.TestCipher _inner = new(); + public bool DenyPayloadReads { get; set; } + public StoredSecret Encrypt(SecretName name, string plaintext, SecretContentType contentType) => _inner.Encrypt(name, plaintext, contentType); + public string Decrypt(StoredSecret secret) + { + if (DenyPayloadReads && secret.Name.Value == "data/key") throw new InvalidOperationException("Observer read secret payload"); + return _inner.Decrypt(secret); + } + public StoredSecret Rewrap(StoredSecret secret, IMasterKeyProvider oldKek, IMasterKeyProvider newKek) => _inner.Rewrap(secret, oldKek, newKek); + } + + [Fact] + public void Host_exposes_a_typed_bounded_committed_bundle_observer() + { + var type = typeof(DataConnectionSecretProvisioner).Assembly.GetType( + "ZB.MOM.WW.OtOpcUa.Host.Configuration.DataConnectionBundleCommitObserver"); + type.ShouldNotBeNull("the fixture needs committed credential and trust versions before declaring the deployed scope ready"); + type.GetMethod("ObserveAsync").ShouldNotBeNull(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataProjectionRoutingTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataProjectionRoutingTests.cs index cea6e5221..8b693aa5d 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataProjectionRoutingTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataProjectionRoutingTests.cs @@ -69,13 +69,14 @@ public sealed class GrpcDataProjectionRoutingTests : TestKit var proof = new Gate(); var bytes = new byte[] { 1, 2 }; broker.TryBind(route).ShouldBeTrue(); - broker.TryPublish([Update(route, proof, bytes) with { IsCompleteSnapshot = true }]).ShouldBeTrue(); + broker.TryPublish([Update(route, proof, bytes) with { IsCompleteSnapshot = true, SourceVersion = 17 }]).ShouldBeTrue(); bytes[0] = 99; await sink.Completed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); var stored = sink.Writes.ShouldHaveSingleItem(); stored.Snapshot.Value.ShouldBeOfType().ShouldBe(new byte[] { 1, 2 }); stored.OriginAgeBounds.Lower.ShouldBe(TimeSpan.FromSeconds(3)); stored.IsCompleteSnapshot.ShouldBeTrue(); + stored.SourceVersion.ShouldBe(17); stored.Proof.IsValid.ShouldBeTrue(); VirtualTagActor.DependencyValueChanged? dependency = null; subscriber.ExpectMsg(TimeSpan.FromSeconds(5), @@ -86,6 +87,19 @@ public sealed class GrpcDataProjectionRoutingTests : TestKit AwaitAssert(() => broker.PendingBytes.ShouldBe(0), TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); } + [Theory(Timeout = 20000), Trait("Phase", "P11")] + [InlineData(0L)] + [InlineData(-1L)] + public void Nonpositive_supplied_source_version_is_rejected_and_invalidated(long sourceVersion) + { + var host = CreateTestProbe(); + using var broker = new ActorProjectedValuePublisher(() => host.Ref, _ => true, 8, 1_000_000, TimeProvider.System); + var route = Route(); var proof = new Gate(); + broker.TryBind(route).ShouldBeTrue(); + broker.TryPublish([Update(route, proof, 42) with { SourceVersion = sourceVersion }]).ShouldBeFalse(); + proof.IsValid.ShouldBeFalse(); + } + [Fact(Timeout = 20000)] public async Task Replacing_a_live_source_fences_old_witnesses_without_retiring_the_new_source() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataRuntimeRegistrationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataRuntimeRegistrationTests.cs index 04bceeea2..b32a87230 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataRuntimeRegistrationTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataRuntimeRegistrationTests.cs @@ -92,17 +92,7 @@ public sealed class GrpcDataRuntimeRegistrationTests 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(); + await using var provider = RegisteredOriginServices(registry).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 }; @@ -140,6 +130,102 @@ public sealed class GrpcDataRuntimeRegistrationTests finally { await system.Terminate().WaitAsync(ct); } } + [Theory(Timeout = 30000), Trait("Phase", "P11")] + [InlineData(false)] + [InlineData(true)] + public async Task Healthy_origin_catalog_stays_ready_while_another_thread_holds_the_dispatch_fence(bool warm) + { + var ct = TestContext.Current.CancellationToken; + var system = ActorSystem.Create("grpc-role-snapshot-" + Guid.NewGuid().ToString("N")); + try + { + var registry = new ActorRegistry(); + registry.Register(system.ActorOf(Props.Create(() => new LocalActor()))); + await using var provider = RegisteredOriginServices(registry, warm).BuildServiceProvider(); + var catalog = provider.GetRequiredService(); + var role = provider.GetRequiredService(); + var warmRole = provider.GetRequiredService(); + var warmOwner = warm ? warmRole.RegisterOwner() : 0; + if (warm) warmRole.Publish(warmOwner, WarmRole.Active).ShouldBeTrue(); + role.PublishDataServingRole(RedundancyRole.Primary, true); + + var key = new ApiKey { ApiKeyId = "key", Name = "key", Principal = "peer", SecretHash = "hash", Enabled = true }; + var attempt = catalog.BeginAttempt("revision"); + catalog.InstallAuthority(attempt, new DataPlaneAuthorityProjection("cluster", [key], [], + new Dictionary>())).ShouldBeTrue(); + const string nodeId = "node-a:4840"; + var draft = new DraftSnapshot { GenerationId = 0, ClusterId = "cluster", + ClusterNodes = [new ClusterNode { ClusterId = "cluster", NodeId = nodeId, Host = "node-a", + ApplicationUri = "urn:node-a", CreatedBy = "test" }] }; + catalog.Stage(attempt, draft, nodeId).ShouldBeTrue(); + catalog.Complete(attempt, true).ShouldBeTrue(); + var deployment = provider.GetRequiredService(); + deployment.Apply(new DataConnectionDeploymentSnapshot(1, "revision", [])); + using var scopeDeadline = CancellationTokenSource.CreateLinkedTokenSource(ct); + scopeDeadline.CancelAfter(TimeSpan.FromSeconds(5)); + while (!deployment.CurrentScopeReady) await Task.Delay(10, scopeDeadline.Token); + + var activeCatalog = catalog.Current.ShouldNotBeNull(); + var serving = activeCatalog.Serving; + serving.Role.ShouldBe("Primary"); + serving.ServingGeneration.ShouldBeGreaterThan(0); + var context = new DataAuthenticatedContext("peer", "key", DataCallerIdentity.CredentialVersionFor(key), + null, serving.AuthorityEpoch); + var factory = provider.GetRequiredService(); + await using var connection = factory.Create(context, new(DataTargetMode.Node, "cluster", nodeId)); + var budget = new DataBudget(TimeSpan.FromSeconds(5), 100, 1_000_000); + (await connection.GetCapabilitiesAsync(budget, ct)).Readiness.ShouldBe(DataReadiness.Ready); + + using var withdraw = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + var fenceHeld = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var verdictWithdrawn = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var fence = provider.GetRequiredService(); + var owner = Task.Run(() => + { + using var lease = fence.Enter(); + fenceHeld.SetResult(); + if (!withdraw.Wait(TimeSpan.FromSeconds(8), ct) || release.IsSet) return; + if (warm) warmRole.Publish(warmOwner, WarmRole.Standby).ShouldBeTrue(); + else role.PublishDataServingRole(null, false); + verdictWithdrawn.SetResult(); + release.Wait(TimeSpan.FromSeconds(8), ct).ShouldBeTrue(); + }, ct); + try + { + await fenceHeld.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + // Establish real contention without relying on a sleep or changing the + // underlying verdict. The fence remains exclusive for dispatch. + var exclusiveEntry = fence.TryEnter(out var unexpectedLease); + unexpectedLease?.Dispose(); + exclusiveEntry.ShouldBeFalse(); + catalog.Current.ShouldBeSameAs(activeCatalog); + catalog.Serving.ShouldBe(serving); + var contended = await connection.GetCapabilitiesAsync(budget, ct); + contended.Readiness.ShouldBe(DataReadiness.Ready); + contended.Serving.ShouldBe(serving); + + withdraw.Set(); + await verdictWithdrawn.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + var withdrawn = await connection.GetCapabilitiesAsync(budget, ct); + withdrawn.Readiness.ShouldBe(DataReadiness.Unavailable); + withdrawn.Operations.ShouldBe(DataOperations.None); + withdrawn.Serving.ShouldNotBe(serving); + } + finally + { + release.Set(); + withdraw.Set(); + await owner.WaitAsync(TimeSpan.FromSeconds(5), ct); + } + + var afterRelease = await connection.GetCapabilitiesAsync(budget, ct); + afterRelease.Readiness.ShouldBe(DataReadiness.Unavailable); + afterRelease.Serving.ServingGeneration.ShouldBeGreaterThan(serving.ServingGeneration); + } + finally { await system.Terminate().WaitAsync(ct); } + } + [Fact] public async Task Local_warm_standby_overrides_hot_artifact_and_withdraws_ready_import() { @@ -177,10 +263,32 @@ public sealed class GrpcDataRuntimeRegistrationTests 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)); + try + { + await lease.GetCapabilitiesAsync(new DataBudget(TimeSpan.FromSeconds(1), 1, 1024), ct); + throw new Xunit.Sdk.XunitException("A withdrawn route must not reach the network."); + } + catch (OperationCanceledException) when (lease.CancellationToken.IsCancellationRequested) { } + catch (InvalidOperationException ex) when (ex.Message == "Connection is no longer ready in the current scope.") { } lease.Dispose(); } + private static ServiceCollection RegisteredOriginServices(ActorRegistry registry, bool warm = false) + { + 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()); + if (warm) services.AddSingleton(new WarmRedundancySettings(OpcUaRedundancyMode.Warm)); + services.AddOtOpcUaDataConnections(Configuration(), new Environment(), hasDriver: true); + return services; + } + private sealed class LocalActor : ReceiveActor { } private sealed class LocalRole : IClusterRoleInfo { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataClientSubscriptionStatusWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataClientSubscriptionStatusWireTests.cs new file mode 100644 index 000000000..d10ca2118 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataClientSubscriptionStatusWireTests.cs @@ -0,0 +1,40 @@ +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Client.Shared; +using ZB.MOM.WW.OtOpcUa.Client.Shared.Models; +using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.WarmRedundancyWireTests; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests; + +[Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P10Wire")] +public sealed class GrpcDataClientSubscriptionStatusWireTests +{ + [Fact(Timeout = 90000)] + public async Task Rejected_monitored_item_is_not_reported_as_an_active_subscription() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await StartModeAsync("GrpcClientItemStatus", "None", ct); + var missing = new NodeId(uint.MaxValue, 0); + using (var reference = await rig.ConnectAsync(anonymous: true, ct)) + { + var client = (SessionClient)reference; + var id = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 10, 0, true, 0, ct)).SubscriptionId; + var response = await client.CreateMonitoredItemsAsync(new RequestHeader(), id, TimestampsToReturn.Both, + [new MonitoredItemCreateRequest + { + ItemToMonitor = new ReadValueId { NodeId = missing, AttributeId = Attributes.Value }, + MonitoringMode = MonitoringMode.Reporting, + RequestedParameters = new MonitoringParameters { ClientHandle = 1, SamplingInterval = 100, QueueSize = 1, DiscardOldest = true } + }], ct); + response.Results[0].StatusCode.ShouldBe(StatusCodes.BadNodeIdUnknown); + } + + using var service = new OpcUaClientService(); + await service.ConnectAsync(new ConnectionSettings { EndpointUrl = rig.EndpointUrl }, ct); + var error = await Should.ThrowAsync(() => service.SubscribeAsync(missing, 100, ct)); + error.StatusCode.ShouldBe(StatusCodes.BadNodeIdUnknown); + await service.SubscribeAsync(VariableIds.Server_ServerStatus_CurrentTime, 100, ct); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataSdkBrowseWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataSdkBrowseWireTests.cs index 88275739c..6fb97c708 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataSdkBrowseWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataSdkBrowseWireTests.cs @@ -4,8 +4,13 @@ using Opc.Ua.Server; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; +using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.ServerEventRig; using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.WarmRedundancyWireTests; namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests; @@ -13,17 +18,91 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests; [Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] public sealed class GrpcDataSdkBrowseWireTests { + [Theory(Timeout = 90000), Trait("Phase", "P10Wire")] + [InlineData(AddressSpaceRealm.Raw, DataRealm.Raw, "raw")] + [InlineData(AddressSpaceRealm.Uns, DataRealm.Uns, "uns")] + public async Task Parent_browse_and_translate_enforce_each_anchor_grant_with_legacy_acl_disabled( + AddressSpaceRealm realm, DataRealm dataRealm, string aclRealm) + { + var ct = Deadline(); + await using var rig = await StartModeAsync("ProjectedAnchorAcl", "None", ct); + rig.Nm.EnsureFolder("Plant", null, "Plant", realm); + var parent = rig.Nm.TryGetFolder("Plant", realm)!.NodeId; + rig.Nm.EnsureFolder("Ordinary", "Plant", "Ordinary", realm); + var ordinary = rig.Nm.TryGetFolder("Ordinary", realm)!.NodeId; + var scopePaths = new Dictionary> + { + [new(NodeAclScopeKind.RawFolder, "allowed")] = [new([aclRealm, "Plant", "Allowed"])], + }; + var grant = new NodeAcl { NodeAclId = "allowed", ClusterId = ServerEventRig.Cluster, Principal = OpcUaPrincipals.Anonymous, + ScopeKind = NodeAclScopeKind.RawFolder, ScopeId = "allowed", PermissionFlags = NodePermissions.Browse }; + rig.Enforce(false, [Key()], scopePaths, grant); + var address = new DataAddress("origin", "urn:source", "string", "root"); + var allowedDef = new ProjectedAnchorDefinition(dataRealm, ProjectedDataIds.Identifier("allowed", address), + parent, "Allowed", "Plant/Allowed", "allowed", 1, () => true) + { LocalScope = new NodeScope { ClusterId = ServerEventRig.Cluster, Kind = realm == AddressSpaceRealm.Raw ? NodeHierarchyKind.Raw : NodeHierarchyKind.Uns, Segments = ["Plant", "Allowed"] } }; + var deniedDef = new ProjectedAnchorDefinition(dataRealm, ProjectedDataIds.Identifier("denied", address), + parent, "Denied", "Plant/Denied", "denied", 1, () => true) + { LocalScope = new NodeScope { ClusterId = ServerEventRig.Cluster, Kind = realm == AddressSpaceRealm.Raw ? NodeHierarchyKind.Raw : NodeHierarchyKind.Uns, Segments = ["Plant", "Denied"] } }; + rig.Nm.TryEnsureProjectedAnchor(allowedDef, out var allowed).ShouldBeTrue(); + rig.Nm.TryEnsureProjectedAnchor(deniedDef, out var denied).ShouldBeTrue(); + using var session = await rig.ConnectAsync(anonymous: true, ct); + var client = (SessionClient)session; + var browse = await client.BrowseAsync(H(), null, 100, [new BrowseDescription + { + NodeId = parent, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences, + IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All, + }], ct); + StatusCode.IsGood(browse.Results[0].StatusCode).ShouldBeTrue(); + var targets = browse.Results[0].References.ToArray()!.Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray(); + targets.ShouldContain(allowed!.Value); + targets.ShouldNotContain(denied!.Value); + targets.ShouldContain(ordinary, "legacy local ACL off still permits ordinary local browse"); + + var translated = await client.TranslateBrowsePathsToNodeIdsAsync(H(), new[] + { + Path(allowed.Value), Path(denied.Value) + }, ct); + translated.Results[0].StatusCode.ShouldBe(StatusCodes.Good); + translated.Results[0].Targets.ToArray()!.ShouldContain(t => + ExpandedNodeId.ToNodeId(t.TargetId, session.NamespaceUris) == allowed.Value); + StatusCode.IsBad(translated.Results[1].StatusCode).ShouldBeTrue(); + translated.Results[1].Targets.Count.ShouldBe(0); + rig.Nm.Authorizer = null; + var withoutAuthority = await client.BrowseAsync(H(), null, 100, [new BrowseDescription + { + NodeId = parent, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences, + IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All, + }], ct); + var withoutAuthorityTargets = withoutAuthority.Results[0].References.ToArray()! + .Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray(); + withoutAuthorityTargets.ShouldNotContain(allowed.Value, "an anchor requires an installed local authority"); + withoutAuthorityTargets.ShouldContain(ordinary); + return; + + BrowsePath Path(NodeId target) => new() + { + StartingNode = parent, + RelativePath = new RelativePath { Elements = [new RelativePathElement + { + ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences, IncludeSubtypes = true, + TargetName = new QualifiedName(target.IdentifierAsString, target.NamespaceIndex) + }] } + }; + } + [Fact(Timeout = 90000)] public async Task BrowseNext_is_session_bound_and_rechecks_page_authority_before_each_child() { var ct = Deadline(); await using var rig = await StartModeAsync("ProjectedBrowseCursor", "None", ct); + AllowAnonymousAnchor(rig); rig.Server.SetProjectedBrowseLimits(maxCursors: 1, maxBytes: 8 * 1024 * 1024); rig.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); var parent = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; var root = new DataAddress("origin", "urn:raw", "string", "root"); - var anchorDefinition = new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", root), - parent, "Remote", "Plant/Remote", "mapping", 1, () => true); + var anchorDefinition = WithRawAnchorScope(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", root), + parent, "Remote", "Plant/Remote", "mapping", 1, () => true)); rig.Nm.TryEnsureProjectedAnchor(anchorDefinition, out var anchor).ShouldBeTrue(); var children = new List(); foreach (var name in new[] { "First", "Second", "Third" }) @@ -40,8 +119,8 @@ public sealed class GrpcDataSdkBrowseWireTests rig.Nm.ProjectedBrowseAccess = pages; var access = new BrowseOnlyAccess(); rig.Nm.ProjectedDataAccess = access; - using var first = await rig.ConnectAsync(anonymous: false, ct); - using var second = await rig.ConnectAsync(anonymous: false, ct); + using var first = await rig.ConnectAsync(anonymous: true, ct); + using var second = await rig.ConnectAsync(anonymous: true, ct); var firstClient = (SessionClient)first; var secondClient = (SessionClient)second; var result = await firstClient.BrowseAsync(H(), null, 1, [new BrowseDescription @@ -60,6 +139,9 @@ public sealed class GrpcDataSdkBrowseWireTests next.Results[0].References.Count.ShouldBe(1); var replacement = next.Results[0].ContinuationPoint; replacement.IsEmpty.ShouldBeFalse("the claimed cursor must reuse its reservation at the configured count limit"); + var replay = await firstClient.BrowseNextAsync(H(), false, [cursor], ct); + replay.Results[0].StatusCode.ShouldBe(StatusCodes.BadContinuationPointInvalid); + replay.Results[0].References.Count.ShouldBe(0); access.OnAcquire = () => pages.Valid = false; var resumed = await firstClient.BrowseNextAsync(H(), false, [replacement], ct); StatusCode.IsBad(resumed.Results[0].StatusCode).ShouldBeTrue(); @@ -71,11 +153,12 @@ public sealed class GrpcDataSdkBrowseWireTests { var ct = Deadline(); await using var rig = await StartModeAsync("ProjectedBrowseFilters", "None", ct); + AllowAnonymousAnchor(rig); rig.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); var parent = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; var origin = new DataAddress("origin", "urn:raw", "string", "root"); - var definition = new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", origin), parent, - "Remote", "Plant/Remote", "mapping", 1, () => true); + var definition = WithRawAnchorScope(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", origin), parent, + "Remote", "Plant/Remote", "mapping", 1, () => true)); rig.Nm.TryEnsureProjectedAnchor(definition, out var anchor).ShouldBeTrue(); var childOrigin = origin with { Identifier = "child" }; var childView = new DataView(childOrigin, DataRealm.Raw, "mapping", 1, "Plant/Remote/Child"); @@ -84,7 +167,7 @@ public sealed class GrpcDataSdkBrowseWireTests metadata, 1, () => true), out var child).ShouldBeTrue(); rig.Nm.ProjectedBrowseAccess = new BrowsePages([child!.Value]); rig.Nm.ProjectedDataAccess = new BrowseOnlyAccess(); - using var session = await rig.ConnectAsync(anonymous: false, ct); + using var session = await rig.ConnectAsync(anonymous: true, ct); var client = (SessionClient)session; async Task Browse(BrowseDirection direction, NodeId referenceType, uint classMask, uint resultMask) { @@ -114,11 +197,12 @@ public sealed class GrpcDataSdkBrowseWireTests { var ct = Deadline(); await using var rig = await StartModeAsync("ProjectedCursorExpiry", "None", ct); + AllowAnonymousAnchor(rig); rig.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); var parent = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; var root = new DataAddress("origin", "urn:raw", "string", "root"); - var anchorDefinition = new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", root), parent, - "Remote", "Plant/Remote", "mapping", 1, () => true); + var anchorDefinition = WithRawAnchorScope(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", root), parent, + "Remote", "Plant/Remote", "mapping", 1, () => true)); rig.Nm.TryEnsureProjectedAnchor(anchorDefinition, out var anchor).ShouldBeTrue(); var children = new List(); foreach (var name in new[] { "First", "Second" }) @@ -135,7 +219,7 @@ public sealed class GrpcDataSdkBrowseWireTests rig.Nm.ProjectedBrowseClock = clock; rig.Nm.ProjectedBrowseAccess = pages; rig.Nm.ProjectedDataAccess = new BrowseOnlyAccess(); - using var session = await rig.ConnectAsync(anonymous: false, ct); + using var session = await rig.ConnectAsync(anonymous: true, ct); var client = (SessionClient)session; var first = await client.BrowseAsync(H(), null, 1, [new BrowseDescription { NodeId = anchor!.Value, BrowseDirection = BrowseDirection.Forward, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All }], ct); @@ -145,6 +229,15 @@ public sealed class GrpcDataSdkBrowseWireTests try { await pages.FetchEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + // The simulated remote page remains outstanding while another + // thread acquires the real SDK lock. A network wait cannot hold it. + var lockAvailable = await Task.Run(() => + { + if (!Monitor.TryEnter(rig.Nm.Lock, TimeSpan.FromSeconds(1))) return false; + try { return true; } + finally { Monitor.Exit(rig.Nm.Lock); } + }, ct); + lockAvailable.ShouldBeTrue(); clock.Advance(TimeSpan.FromSeconds(61)); } finally { pages.Release.TrySetResult(); } @@ -156,6 +249,13 @@ public sealed class GrpcDataSdkBrowseWireTests retry.Results[0].StatusCode.ShouldBe(StatusCodes.BadContinuationPointInvalid); } + private static void AllowAnonymousAnchor(ServerEventRig rig) => rig.Enforce(false, [Key()], + ClusterGrant(OpcUaPrincipals.Anonymous, "anchor-browse", NodePermissions.Browse)); + + private static ProjectedAnchorDefinition WithRawAnchorScope(ProjectedAnchorDefinition definition) => + definition with { LocalScope = new NodeScope { ClusterId = ServerEventRig.Cluster, Kind = NodeHierarchyKind.Raw, + Segments = definition.LocalSubject.Split('/') } }; + private sealed class TestMonotonicClock : TimeProvider { private long _ticks; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataSdkDeliveryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataSdkDeliveryWireTests.cs index 927273da3..94aaaa742 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataSdkDeliveryWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataSdkDeliveryWireTests.cs @@ -12,9 +12,82 @@ using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.WarmRedundancyWireTe namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests; +[Collection(WarmRedundancyProcessWideCollection.Name)] [Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] public sealed class GrpcDataSdkDeliveryWireTests { + [Theory(Timeout = 90000)] + [InlineData(false)] + [InlineData(true)] + public async Task Acknowledged_projected_notification_does_not_poison_the_next_stock_item(bool builtIn) + { + var ct = Deadline(); + await using var fixture = await DeliveryFixture.CreateAsync($"ProjectedPool{builtIn}", "None", ct); + using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct); + var client = (SessionClient)session; + var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId; + var projected = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri)); + const uint handle = 7; + var projectedItem = await AddItemAsync(client, sub, projected, handle, 1, ct); + var first = await PublishDataAsync(client, ct); + var firstValue = DataChanges(first.NotificationMessage).ShouldHaveSingleItem(); + firstValue.Handle.ShouldBe(handle); + firstValue.Value.StatusCode.ShouldBe(StatusCodes.Good); + firstValue.Value.ClrValue().ShouldBe(1); + + fixture.Access.Valid = false; + var sequence = first.NotificationMessage.SequenceNumber; + var replay = await client.RepublishAsync(H(), sub, sequence, ct); + var revoked = DataChanges(replay.NotificationMessage).ShouldHaveSingleItem(); + revoked.Handle.ShouldBe(handle); + revoked.Value.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied); + revoked.Value.WrappedValue.IsNull.ShouldBeTrue(); + StatusCode.IsGood((await client.DeleteMonitoredItemsAsync(H(), sub, [projectedItem], ct)).Results[0]).ShouldBeTrue(); + + NodeId ordinary; + object expected; + if (builtIn) + { + const byte level = 91; + new SdkServiceLevelPublisher(fixture.Rig.Server.CurrentInstance!, NullLogger.Instance).Publish(level); + ordinary = VariableIds.Server_ServiceLevel; + expected = level; + } + else + { + const double value = 42.5; + var raw = fixture.Rig.EnsureRawVariable("stock", "Double", writable: false); + fixture.Rig.Sink.WriteValue(raw, value, OpcUaStatus.Good, DateTime.UtcNow, AddressSpaceRealm.Raw); + ordinary = Raw(session, raw); + expected = value; + } + await AddItemAsync(client, sub, ordinary, handle, 1, ct); + + // Hold the pool's next rent so the SDK can return the acknowledged payload to the empty fast slot. + // Publish handles acknowledgements before renting the notification for the next monitored item. + var held = (MonitoredItemNotification)MonitoredItemNotificationActivator.Instance.CreateInstance(); + try + { + var next = await client.PublishAsync(H(), [new SubscriptionAcknowledgement + { + SubscriptionId = sub, + SequenceNumber = sequence + }], ct); + StatusCode.IsGood(next.Results[0]).ShouldBeTrue("the retained mapped notification was acknowledged"); + // A keep-alive cannot consume the stock payload slot. + if (next.NotificationMessage.NotificationData.Count == 0) + next = await PublishDataAsync(client, ct); + var delivered = DataChanges(next.NotificationMessage).ShouldHaveSingleItem(); + delivered.Handle.ShouldBe(handle); + delivered.Value.StatusCode.ShouldBe(StatusCodes.Good); + delivered.Value.ClrValue().ShouldBe(expected); + } + finally + { + held.Reuse(); + } + } + [Theory(Timeout = 90000)] [InlineData("None", false)] [InlineData("Warm", false)] @@ -119,25 +192,38 @@ public sealed class GrpcDataSdkDeliveryWireTests public async Task A_newer_sample_cannot_refresh_an_older_queued_samples_age(string mode) { var ct = Deadline(); - await using var fixture = await DeliveryFixture.CreateAsync("Age" + mode, mode, ct); + var clock = new TestSampleClock(); + await using var fixture = await DeliveryFixture.CreateAsync("Age" + mode, mode, ct, sampleClock: clock); using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct); var client = (SessionClient)session; - var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId; + var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 1, true, 0, ct)).SubscriptionId; var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri)); await AddItemAsync(client, sub, node, 7, 10, ct); - await PublishDataAsync(client, ct); + var initial = DataChanges((await PublishDataAsync(client, ct)).NotificationMessage).ShouldHaveSingleItem(); + initial.Value.StatusCode.ShouldBe(StatusCodes.Good); + initial.Value.ClrValue().ShouldBe(1); await client.SetPublishingModeAsync(H(), false, [sub], ct); - fixture.Push(42, originAge: TimeSpan.FromSeconds(10)).ShouldBeTrue(); - await Task.Delay(TimeSpan.FromMilliseconds(150), ct); - fixture.Push(43, originAge: TimeSpan.Zero).ShouldBeTrue(); - await Task.Delay(TimeSpan.FromMilliseconds(150), ct); + var oldTimestamp = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); + var newTimestamp = oldTimestamp.AddSeconds(1); + // Both updates enter the real SDK queue while fresh. Advancing the proof clock + // after the newer sample arrives expires only the old sample at delivery. + fixture.Push(42, originAge: TimeSpan.FromSeconds(4), sourceTimestamp: oldTimestamp).ShouldBeTrue(); + fixture.Push(43, originAge: TimeSpan.Zero, sourceTimestamp: newTimestamp).ShouldBeTrue(); + clock.Advance(TimeSpan.FromSeconds(2)); await client.SetPublishingModeAsync(H(), true, [sub], ct); - var delivered = await PublishDataAsync(client, ct); - var values = DataChanges(delivered.NotificationMessage); - values.Count.ShouldBeGreaterThanOrEqualTo(2, "both queued samples must reach this delivery for the age check to be meaningful"); - values.ShouldNotContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 42)); - var replay = await client.RepublishAsync(H(), sub, delivered.NotificationMessage.SequenceNumber, ct); - DataChanges(replay.NotificationMessage).ShouldNotContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 42)); + var stale = await PublishDataAsync(client, ct); + AssertDenied(stale.NotificationMessage); + var replay = await client.RepublishAsync(H(), sub, stale.NotificationMessage.SequenceNumber, ct); + AssertDenied(replay.NotificationMessage); + var fresh = await PublishDataAsync(client, ct); + fresh.NotificationMessage.SequenceNumber.ShouldBe(stale.NotificationMessage.SequenceNumber + 1); + var row = DataChanges(fresh.NotificationMessage).ShouldHaveSingleItem(); + row.Handle.ShouldBe(7u); + row.Value.StatusCode.ShouldBe(StatusCodes.Good); + row.Value.ClrValue().ShouldBe(43); + row.Value.SourceTimestamp.ShouldBe((DateTimeUtc)newTimestamp); + var staleAfterFresh = await client.RepublishAsync(H(), sub, stale.NotificationMessage.SequenceNumber, ct); + AssertDenied(staleAfterFresh.NotificationMessage); } [Theory(Timeout = 90000)] @@ -146,7 +232,8 @@ public sealed class GrpcDataSdkDeliveryWireTests public async Task Ambiguous_equal_samples_are_denied_then_recover_with_a_fresh_snapshot(string mode) { var ct = Deadline(); - await using var fixture = await DeliveryFixture.CreateAsync("Equal" + mode, mode, ct); + var clock = new TestSampleClock(); + await using var fixture = await DeliveryFixture.CreateAsync("Equal" + mode, mode, ct, sampleClock: clock); using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct); var client = (SessionClient)session; var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId; @@ -154,19 +241,34 @@ public sealed class GrpcDataSdkDeliveryWireTests await AddItemAsync(client, sub, node, 7, 10, ct); await PublishDataAsync(client, ct); await client.SetPublishingModeAsync(H(), false, [sub], ct); - fixture.Push(42, originAge: TimeSpan.FromSeconds(10)).ShouldBeTrue(); - await Task.Delay(TimeSpan.FromMilliseconds(150), ct); - fixture.Push(42, originAge: TimeSpan.Zero).ShouldBeTrue(); - await Task.Delay(TimeSpan.FromMilliseconds(150), ct); + var equalTimestamp = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); + // The acquisition ages differ, but either sample would be fresh if selected. + // Matching value, quality and original timestamp leave the proof ambiguous. + fixture.Push(42, originAge: TimeSpan.FromSeconds(4), sourceTimestamp: equalTimestamp).ShouldBeTrue(); + fixture.Push(42, originAge: TimeSpan.Zero, sourceTimestamp: equalTimestamp).ShouldBeTrue(); + fixture.Access.BaselineRequests.ShouldBe(0); await client.SetPublishingModeAsync(H(), true, [sub], ct); var ambiguous = await PublishDataAsync(client, ct); - DataChanges(ambiguous.NotificationMessage).ShouldNotContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 42)); + AssertDenied(ambiguous.NotificationMessage); fixture.Access.BaselineRequests.ShouldBeGreaterThan(0); - fixture.Push(43, completeSnapshot: true).ShouldBeTrue(); - var fresh = await PublishDataAsync(client, ct); - DataChanges(fresh.NotificationMessage).ShouldContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 43)); var replay = await client.RepublishAsync(H(), sub, ambiguous.NotificationMessage.SequenceNumber, ct); - DataChanges(replay.NotificationMessage).ShouldNotContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 42)); + AssertDenied(replay.NotificationMessage); + var freshTimestamp = equalTimestamp.AddSeconds(1); + fixture.Push(43, completeSnapshot: true, sourceTimestamp: freshTimestamp).ShouldBeTrue(); + var fresh = await PublishDataAsync(client, ct); + var rows = DataChanges(fresh.NotificationMessage); + rows.ShouldNotBeEmpty(); + rows.ShouldAllBe(x => x.Handle == 7 && x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 43) && + x.Value.SourceTimestamp == (DateTimeUtc)freshTimestamp); + var ambiguousAfterFresh = await client.RepublishAsync(H(), sub, ambiguous.NotificationMessage.SequenceNumber, ct); + AssertDenied(ambiguousAfterFresh.NotificationMessage); + } + + private static void AssertDenied(NotificationMessage message) + { + var rows = DataChanges(message); + rows.ShouldNotBeEmpty(); + rows.ShouldAllBe(x => x.Handle == 7 && x.Value.StatusCode == StatusCodes.BadUserAccessDenied && x.Value.WrappedValue.IsNull); } [Theory(Timeout = 90000)] @@ -379,17 +481,21 @@ public sealed class GrpcDataSdkDeliveryWireTests access.Disposals.ShouldBeGreaterThan(0, "node removal must retire the item even while the client keeps it alive"); } - private sealed class DeliveryFixture(ServerEventRig rig, string identifier, ServingIdentity serving, FakeAccess access) : IAsyncDisposable + private sealed class DeliveryFixture(ServerEventRig rig, string identifier, ServingIdentity serving, FakeAccess access, + TimeProvider? sampleClock) : IAsyncDisposable { public ServerEventRig Rig => rig; public string Identifier => identifier; public FakeAccess Access => access; - public SampleProof Proof = new(); - public bool Push(int value, bool completeSnapshot = false, TimeSpan? originAge = null) => ((IProjectedValueSink)rig.Sink).TryPublish([ - new ProjectedValueWrite(DataRealm.Raw, identifier, 1, serving, new DataValueSnapshot(value, StatusCodes.Good.Code, null, null), - new(originAge ?? TimeSpan.Zero, originAge ?? TimeSpan.Zero), TimeProvider.System.GetTimestamp(), Proof) { IsCompleteSnapshot = completeSnapshot } + public SampleProof Proof = new(sampleClock); + public bool Push(int value, bool completeSnapshot = false, TimeSpan? originAge = null, DateTime? sourceTimestamp = null) => + ((IProjectedValueSink)rig.Sink).TryPublish([ + new ProjectedValueWrite(DataRealm.Raw, identifier, 1, serving, + new DataValueSnapshot(value, StatusCodes.Good.Code, sourceTimestamp, null), + new(originAge ?? TimeSpan.Zero, originAge ?? TimeSpan.Zero), Proof.Clock.GetTimestamp(), Proof) { IsCompleteSnapshot = completeSnapshot } ]); - public static async Task CreateAsync(string name, string mode, CancellationToken ct, bool writable = false, bool promoteWarm = true) + public static async Task CreateAsync(string name, string mode, CancellationToken ct, bool writable = false, + bool promoteWarm = true, TimeProvider? sampleClock = null) { var rig = await StartModeAsync(name, mode, ct); if (mode == "Warm" && promoteWarm) Promote(rig.Server.CreateStandbyProjection()!); @@ -404,17 +510,25 @@ public sealed class GrpcDataSdkDeliveryWireTests rig.Nm.TryEnsureProjectedVariable(new(DataRealm.Raw, identifier, parent, metadata, 1, () => true), out _).ShouldBeTrue(); var access = new FakeAccess(view with { MappingId = null, MappingRevision = 0, Subject = "origin/Speed" }, serving); rig.Nm.ProjectedDataAccess = access; - var fixture = new DeliveryFixture(rig, identifier, serving, access); + var fixture = new DeliveryFixture(rig, identifier, serving, access, sampleClock); fixture.Push(1, completeSnapshot: true).ShouldBeTrue(); return fixture; } public ValueTask DisposeAsync() => rig.DisposeAsync(); } - private sealed class SampleProof : IProjectedSamplePublicationProof + private sealed class TestSampleClock : TimeProvider + { + private long _ticks; + public override long TimestampFrequency => TimeSpan.TicksPerSecond; + public override long GetTimestamp() => Interlocked.Read(ref _ticks); + public void Advance(TimeSpan value) => Interlocked.Add(ref _ticks, value.Ticks); + } + + private sealed class SampleProof(TimeProvider? clock = null) : IProjectedSamplePublicationProof { public bool IsValid { get; private set; } = true; - public TimeProvider Clock => TimeProvider.System; + public TimeProvider Clock => clock ?? TimeProvider.System; public void Invalidate() => IsValid = false; } private sealed class FakeAccess(DataView origin, ServingIdentity serving) : IProjectedDataAccess diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkMappedAccessTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkMappedAccessTests.cs index 552d15b95..590e08aab 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkMappedAccessTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkMappedAccessTests.cs @@ -14,8 +14,8 @@ public sealed class GrpcDataSdkMappedAccessTests { var valid = true; var value = new DataValue(new Variant(42), StatusCodes.Good); - var item = new MonitoredItemNotification { ClientHandle = 7, Value = value }; - item.Message = new ProjectedNotificationMarker(7, value, () => valid); + var item = new ProjectedSdkNotification(new MonitoredItemNotification { ClientHandle = 7, Value = value }, + new ProjectedNotificationMarker(7, value, () => valid)); var message = Message(item); valid = false; var output = ProjectedNotificationRewriter.Project(message, republish); @@ -29,13 +29,31 @@ public sealed class GrpcDataSdkMappedAccessTests { var oldValue = new DataValue(new Variant(42), StatusCodes.Good); var newValue = new DataValue(new Variant(43), StatusCodes.Good); - var item = new MonitoredItemNotification { ClientHandle = 7, Value = newValue }; - item.Message = new ProjectedNotificationMarker(7, oldValue, () => true); + var item = new ProjectedSdkNotification(new MonitoredItemNotification { ClientHandle = 7, Value = newValue }, + new ProjectedNotificationMarker(7, oldValue, () => true)); var output = ProjectedNotificationRewriter.Project(Message(item), false); output.NotificationData[0].TryGetValue(out var data).ShouldBeTrue(); data!.MonitoredItems[0].Value.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied); } + [Fact] + public void Retired_projected_payload_cannot_publish_when_its_marker_is_absent() + { + var value = new DataValue(new Variant(42), StatusCodes.Good); + var item = new ProjectedSdkNotification(new MonitoredItemNotification { ClientHandle = 7, Value = value }, + new ProjectedNotificationMarker(7, value, () => true)); + var cloned = item.Clone().ShouldBeOfType(); + item.Reuse(); + + var replay = ProjectedNotificationRewriter.Project(Message(cloned), true); + replay.NotificationData[0].TryGetValue(out var authorized).ShouldBeTrue(); + authorized!.MonitoredItems[0].Value.ShouldBe(value); + + var retired = ProjectedNotificationRewriter.Project(Message(item), true); + retired.NotificationData[0].TryGetValue(out var denied).ShouldBeTrue(); + denied!.MonitoredItems[0].Value.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied); + } + private static NotificationMessage Message(MonitoredItemNotification item) => new() { SequenceNumber = 1, diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkProjectionLifetimeTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkProjectionLifetimeTests.cs index aec3846ee..dae9e2329 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkProjectionLifetimeTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkProjectionLifetimeTests.cs @@ -89,6 +89,74 @@ public sealed class GrpcDataSdkProjectionLifetimeTests : IDisposable finally { await started.Host.DisposeAsync(); } } + [Fact(Timeout = 30000)] + public async Task Committed_lookup_progresses_during_sdk_page_apply_without_exposing_staged_nodes() + { + var started = await StartAsync(); + try + { + var manager = started.Server.NodeManager!; + manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = manager.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var sink = new SdkAddressSpaceSink(manager); + var ns = (ushort)started.Server.CurrentInstance.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri); + var authority = 1; + var original = Definition(parent, "committed", () => Volatile.Read(ref authority) != 0); + var staged = Definition(parent, "staged", () => true); + var originalId = new NodeId(original.LocalIdentifier, ns); + var stagedId = new NodeId(staged.LocalIdentifier, ns); + sink.TryApply(parent, [original], () => true).ShouldBeTrue(); + + var token = TestContext.Current.CancellationToken; + var beforeCommit = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var commit = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var applying = Task.Run(() => sink.TryApply(parent, [staged], () => + { + // The page has installed its provisional SDK nodes and still owns the SDK lock. + beforeCommit.TrySetResult(); + return commit.Task.WaitAsync(TimeSpan.FromSeconds(15), token).GetAwaiter().GetResult(); + }), token); + + Task? lookingUp = null; + var foundOriginal = false; + var foundStaged = false; + var foundRevoked = false; + ProjectedVariableDefinition? resolved = null; + ProjectedVariableDefinition? stagedDefinition = null; + ProjectedVariableDefinition? revokedDefinition = null; + try + { + await beforeCommit.Task.WaitAsync(TimeSpan.FromSeconds(5), token); + lookingUp = Task.Run(() => + { + foundOriginal = sink.TryResolve(originalId, out resolved); + foundStaged = sink.TryResolve(stagedId, out stagedDefinition); + Volatile.Write(ref authority, 0); + foundRevoked = sink.TryResolve(originalId, out revokedDefinition); + }, token); + // Source proof validation may reach this lookup while the SDK lock is held. + await lookingUp.WaitAsync(TimeSpan.FromSeconds(5), token); + } + finally + { + commit.TrySetResult(false); + (await applying.WaitAsync(TimeSpan.FromSeconds(5), token)).ShouldBeFalse(); + if (lookingUp is not null) + await lookingUp.WaitAsync(TimeSpan.FromSeconds(5), token); + } + + foundOriginal.ShouldBeTrue(); + resolved.ShouldBeSameAs(original); + foundStaged.ShouldBeFalse(); + stagedDefinition.ShouldBeNull(); + foundRevoked.ShouldBeFalse(); + revokedDefinition.ShouldBeNull(); + sink.TryResolve(stagedId, out var afterAbort).ShouldBeFalse(); + afterAbort.ShouldBeNull(); + } + finally { await started.Host.DisposeAsync(); } + } + private static ProjectedVariableDefinition Definition(NodeId parent, string name, Func guard) { var origin = new DataAddress("origin", "urn:raw", "string", name); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkProjectionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkProjectionTests.cs index 93fe84da3..eb76dcd2a 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkProjectionTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkProjectionTests.cs @@ -113,6 +113,10 @@ public sealed class GrpcDataSdkProjectionTests : IDisposable sink.TryPublish([update]).ShouldBeTrue(); var variable = ((NodeHandle)manager.GetManagerHandle(node.Value)!).Node.ShouldBeOfType(); variable.StatusCode.ShouldBe(StatusCodes.Good); + var badVersion = update with { Proof = new SampleProof(), SourceVersion = 0 }; + sink.TryPublish([badVersion]).ShouldBeFalse(); + StatusCode.IsBad(variable.StatusCode).ShouldBeTrue(); + sink.TryPublish([update]).ShouldBeTrue(); proof.Invalidate(); sink.TryPublish([update]).ShouldBeFalse(); StatusCode.IsBad(variable.StatusCode).ShouldBeTrue("a rejected stale sample must not leave a Good value visible"); 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 edfcc2ab4..344942182 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 @@ -191,9 +191,13 @@ public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase catalog.Last.Caller.ApiKeyId.ShouldBe("peer-key"); catalog.Last.Parent.ShouldBe(lifecycle.Active.ShouldHaveSingleItem().Anchor); catalog.Last.Budget.MaxItems.ShouldBe(3); - coordinator.BeginAttempt("replacement"); - sink.Removals.ShouldBe(1); + var replacement = Prepare(coordinator, Artifact()); + anchor.AuthorityIsCurrent().ShouldBeFalse(); + sink.Removals.ShouldBe(0, "an unresolved deployment suspends the bounded anchor lifetime"); controller.GetOrSchedule(context).ShouldBe(ProjectedBrowseReadiness.Unavailable); + lifecycle.Stage(replacement, [], [TestConnection()]); + coordinator.Complete(replacement, true).ShouldBeTrue(); + sink.Removals.ShouldBe(1, "a completed deployment without the mapping retires its anchor"); catalog.Release.TrySetResult(); } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataComposedBrowseWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataComposedBrowseWireTests.cs index 22fb99347..91996b623 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataComposedBrowseWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataComposedBrowseWireTests.cs @@ -1,3 +1,4 @@ +using System.Threading.Channels; using Microsoft.Extensions.Logging.Abstractions; using Opc.Ua; using Opc.Ua.Client; @@ -134,9 +135,234 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests }); } + [Fact(Timeout = 90000), Trait("Phase", "P10Wire")] + public async Task Cold_sdk_read_publishes_with_default_one_mib_transport_budget() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; origin.Publish(42); + var published = Channel.CreateUnbounded(); + await WithComposedServer(origin, origin.Raw, async (session, sink, resolver, applier, access, placements, anchor) => + { + var discovery = new ConfiguredProjectionDiscovery(placements, resolver, applier, sink, access, + new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8); + await using var lease = await discovery.ResolveAsync(Reference("map", DataRealm.Raw, origin.Raw.Address), ct); + lease.ShouldNotBeNull(); + await subscriptions.Opened.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var client = (SessionClient)session; + var first = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Both, + [new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], ct); + first.Results[0].StatusCode.ShouldBe(StatusCodes.BadWaitingForInitialData); + var update = await published.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + update.Snapshot.Value.ShouldBe(42); + var result = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Both, + [new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], ct); + StatusCode.IsGood(result.Results[0].StatusCode).ShouldBeTrue(); + result.Results[0].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42); + }, onPublished: update => published.Writer.TryWrite(update), maxUnaryBytes: 1024 * 1024); + } + + [Theory(Timeout = 90000), Trait("Phase", "P10Wire")] + [InlineData(DataWriteState.DriverConfirmedSuccess)] + [InlineData(DataWriteState.OutcomeUnknown)] + public async Task Sdk_mapped_write_uses_default_one_mib_budget_and_is_dispatched_once(DataWriteState outcome) + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + var writes = new RecordingOriginWrites(outcome); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions, writes: _ => writes); + peer = origin; + await WithComposedServer(origin, origin.Raw, async (session, sink, resolver, applier, access, placements, anchor) => + { + var discovery = new ConfiguredProjectionDiscovery(placements, resolver, applier, sink, access, + new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8); + await using var lease = await discovery.ResolveAsync(Reference("map", DataRealm.Raw, origin.Raw.Address), ct); + lease.ShouldNotBeNull(); + await subscriptions.Opened.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var response = await ((SessionClient)session).WriteAsync(new RequestHeader(), + [new WriteValue { NodeId = anchor, AttributeId = Attributes.Value, Value = new Opc.Ua.DataValue(new Variant(77), StatusCodes.Good) }], ct); + response.Results.ToArray()!.ShouldHaveSingleItem().ShouldBe(outcome == DataWriteState.DriverConfirmedSuccess + ? StatusCodes.Good : StatusCodes.UncertainLastUsableValue); + writes.Calls.ShouldBe(1, "neither a success nor an ambiguous outcome may be replayed"); + writes.Value.ShouldBe(77); writes.Budget.ShouldNotBeNull().MaxBytes.ShouldBe(1024 * 1024); + }, maxUnaryBytes: 1024 * 1024, allowWrite: true); + } + + private sealed class RecordingOriginWrites(DataWriteState outcome) : IDataWriteService + { + private int _calls; + internal int Calls => Volatile.Read(ref _calls); + internal object? Value; + internal DataBudget? Budget; + public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) + { + Interlocked.Increment(ref _calls); Budget = request.Budget; Value = request.Items.Single().Value.GetScalar(); + var status = outcome == DataWriteState.DriverConfirmedSuccess ? StatusCodes.Good.Code : StatusCodes.BadTimeout.Code; + return Task.FromResult>([new(request.Items[0].CorrelationId, new(outcome, status, null))]); + } + } + + [Theory(Timeout = 90000), Trait("Phase", "P11Wire")] + [InlineData(false)] + [InlineData(true)] + public async Task Actual_sdk_monitored_item_recovers_from_an_older_snapshot_using_the_quiet_current_cadence(bool holdHealthyNotification) + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; + subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, access, _, anchor) => + { + var client = (SessionClient)session; + // Browsing materializes the value root through the real registry without adding a headless demand. + await BrowseAll(client, anchor, 1); + ((IProjectedNodeLookup)sink).TryResolve(anchor, out var definition).ShouldBeTrue(); + definition.ShouldNotBeNull().Metadata.ValueKind.ShouldBe(DataValueKind.Int32); + var slow = (await client.CreateSubscriptionAsync(new RequestHeader(), 200, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, slow, anchor, 1, 200, ct); + var slowStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + await client.SetPublishingModeAsync(new RequestHeader(), false, [slow], ct); + var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, fast, anchor, 2, 50, ct); + var fastStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + fastStream.Interval.ShouldNotBe(slowStream.Interval); + (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); + access.HasLiveDemand(DataRealm.Raw, definition!.LocalIdentifier).ShouldBeTrue(); + + // A queue of one overwrites repeated values with the same timestamp. The slow item's + // retained evidence is genuinely ambiguous; the fast item consumes each sample. + var timestamp = origin.Clock.GetUtcNow().AddMinutes(-1); + fastStream.EmitValue(2, 42, timestamp, TimeSpan.Zero); + (await PublishComposedValue(client, 2, ct)).WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42); + fastStream.EmitValue(3, 44, timestamp, TimeSpan.Zero); + (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); + fastStream.EmitValue(4, 42, timestamp, TimeSpan.Zero); + (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); + subscriptions.SnapshotVersion = 4; subscriptions.SnapshotValue = 42; + subscriptions.HoldNextSnapshotEnd = true; + await client.SetPublishingModeAsync(new RequestHeader(), false, [fast], ct); + await client.SetPublishingModeAsync(new RequestHeader(), true, [slow], ct); + var rejected = await PublishComposedValue(client, 1, ct); + StatusCode.IsGood(rejected.StatusCode).ShouldBeFalse("ambiguous retained evidence must fail closed and request a baseline"); + var held = await subscriptions.SnapshotEndHeld.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + held.ShouldBeSameAs(slowStream); + subscriptions.Opens.ShouldBe(2, "refreshing the slow item must retain both existing upstream streams"); + await client.SetPublishingModeAsync(new RequestHeader(), false, [slow], ct); + if (!holdHealthyNotification) + await client.SetPublishingModeAsync(new RequestHeader(), true, [fast], ct); + + var currentTimestamp = timestamp.AddSeconds(1); + fastStream.EmitValue(5, 43, currentTimestamp, TimeSpan.FromSeconds(28)); + if (!holdHealthyNotification) + { + var healthy = await PublishComposedValue(client, 2, ct); + healthy.StatusCode.ShouldBe(StatusCodes.Good); + healthy.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(43, + "ordinary deltas must continue while the other cadence's snapshot is held"); + } + var current = await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 43) && !x.IsCompleteSnapshot, ct); + current.SourceProof.IsValid.ShouldBeTrue(); + origin.Clock.Advance(TimeSpan.FromSeconds(1)); + held.ReleaseSnapshotEnd(); + // No further source frame is sent. The old N barrier must complete recovery using already admitted N+1. + var recovered = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 43), ct); + recovered.SourceProof.ShouldBeSameAs(current.SourceProof); + recovered.ReceivedTimestamp.ShouldBe(current.ReceivedTimestamp); + recovered.OriginAgeBounds.ShouldBe(current.OriginAgeBounds); + recovered.Snapshot.SourceTimestampUtc.ShouldBe(currentTimestamp.UtcDateTime); + slowStream.RemoveCommands.ShouldBe(1); + slowStream.AddCommands.ShouldBe(1); + fastStream.RemoveCommands.ShouldBe(0); + fastStream.AddCommands.ShouldBe(0); + if (holdHealthyNotification) + { + // The fast item still holds the original 43. Replaying that exact cached evidence for + // another item's recovery must not manufacture a second, ambiguous healthy candidate. + await client.SetPublishingModeAsync(new RequestHeader(), true, [fast], ct); + var healthy = await PublishComposedValue(client, 2, ct); + healthy.StatusCode.ShouldBe(StatusCodes.Good, + "another cadence's complete replay must preserve the healthy item's queued evidence"); + healthy.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(43); + healthy.SourceTimestamp.ShouldBe((DateTimeUtc)currentTimestamp.UtcDateTime); + fastStream.RemoveCommands.ShouldBe(0, "a healthy item must not request a replacement registration"); + fastStream.AddCommands.ShouldBe(0, "a healthy item must retain its existing registration"); + } + await client.SetPublishingModeAsync(new RequestHeader(), false, [fast], ct); + await client.SetPublishingModeAsync(new RequestHeader(), true, [slow], ct); + var notification = await PublishComposedNotification(client, 1, ct); + var delivered = notification.Value; + delivered.StatusCode.ShouldBe(StatusCodes.Good); + delivered.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(43); + delivered.SourceTimestamp.ShouldBe((DateTimeUtc)currentTimestamp.UtcDateTime); + subscriptions.Opens.ShouldBe(2); + origin.Clock.Advance(TimeSpan.FromSeconds(2)); + var replay = await client.RepublishAsync(new RequestHeader(), slow, notification.Sequence, ct); + var expired = ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value; + StatusCode.IsGood(expired.StatusCode).ShouldBeFalse( + "recovery must retain the original ingress age: 28 seconds plus three elapsed seconds exceeds the 30 second limit"); + }, onPublished: update => published.Writer.TryWrite(update)); + } + + private static async Task AddComposedItem(SessionClient client, uint subscription, NodeId node, uint handle, + double interval, CancellationToken ct) + { + var response = await client.CreateMonitoredItemsAsync(new RequestHeader(), subscription, TimestampsToReturn.Both, + [new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = node, AttributeId = Attributes.Value }, + MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters + { ClientHandle = handle, SamplingInterval = interval, QueueSize = 1, DiscardOldest = true, + Filter = new ExtensionObject(new DataChangeFilter { Trigger = Opc.Ua.DataChangeTrigger.StatusValueTimestamp }) } }], ct); + response.Results[0].StatusCode.ShouldBe(StatusCodes.Good); + } + + private static async Task PublishComposedValue(SessionClient client, uint handle, CancellationToken ct) => + (await PublishComposedNotification(client, handle, ct)).Value; + + private static IEnumerable ComposedChanges(NotificationMessage message) + { + foreach (var payload in message.NotificationData.ToArray()!) + if (payload.TryGetValue(out var changes)) + foreach (var change in changes.MonitoredItems.ToArray()!) yield return change; + } + + private static async Task<(Opc.Ua.DataValue Value, uint Sequence)> PublishComposedNotification( + SessionClient client, uint handle, CancellationToken ct) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromSeconds(10)); + while (true) + { + var response = await client.PublishAsync(new RequestHeader(), default, timeout.Token); + foreach (var change in ComposedChanges(response.NotificationMessage)) + if (change.ClientHandle == handle) return (change.Value, response.NotificationMessage.SequenceNumber); + } + } + + private static async Task NextPublished(ChannelReader reader, + Func predicate, CancellationToken ct) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromSeconds(10)); + while (true) + { + var update = await reader.ReadAsync(timeout.Token); + if (predicate(update)) return update; + } + } + private async Task WithComposedServer(LocalDataFixture origin, DataView root, Func exercise, - bool restrictToPlant = false) + bool restrictToPlant = false, Action? onPublished = null, bool mountAtRealmRoot = false, + long maxUnaryBytes = 8_000_000, bool allowWrite = false, IGrpcDataAdapterConnectionSource? connectionSource = null, + int? staleTimeoutMilliseconds = null, Func? renewalSinkFactory = null, + Action? onCoordinator = null, int? localPermissions = null) { var ct = TestContext.Current.CancellationToken; var pki = Path.Combine(Path.GetTempPath(), $"composed-projection-{Guid.NewGuid():N}"); @@ -153,23 +379,27 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests }, () => new OtOpcUaSdkServer(), ct); try { - var connections = new FakeConnections(origin); + var connections = connectionSource ?? new FakeConnections(origin); var authority = new DataPlaneAuthorityState(); var coordinator = new LocalCatalogCoordinator(new CatalogActivation(), authority, () => new ServingIdentity("node-a", "boot", "Primary", 0, 0, 1)); + onCoordinator?.Invoke(coordinator); var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, origin.Clock), origin.Clock); using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(16, 128, origin.Clock, policy), new BrowseContinuationRegistry(16, origin.Clock), connections, policy, 16, 2); using var placements = new ProjectedMappingDeploymentRuntime(coordinator, resolver); - var attempt = Prepare(coordinator, restrictToPlant); + var attempt = Prepare(coordinator, restrictToPlant, allowWrite, localPermissions); var mapping = Mapping(root); + if (staleTimeoutMilliseconds is { } stale) mapping.StaleTimeoutMilliseconds = stale; if (root.Realm == DataRealm.Uns) { mapping.Realm = mapping.RemoteRealm = DataRealm.Uns; mapping.LocalParentKind = "UnsArea"; mapping.LocalParentId = "area"; } + if (mountAtRealmRoot) { mapping.LocalParentKind = "Cluster"; mapping.LocalParentId = "cluster"; } mapping.AllowedOperations |= DataOperations.Read | DataOperations.Metadata; + if (allowWrite) { mapping.AllowedOperations |= DataOperations.Write; mapping.WriteThrough = true; } placements.Stage(attempt, [mapping], [Connection()]); coordinator.Complete(attempt, true).ShouldBeTrue(); var manager = started.Server.NodeManager!; @@ -187,9 +417,10 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests : MappedNodeResolution.Deny; var sink = new SdkAddressSpaceSink(manager); using var applier = new ProjectedNamespaceApplier(resolver, sink, 2); + await using var publisher = new QueuedComposedPublisher(sink, onPublished); using var access = new ProjectedDataAccess(resolver, sink, connections, id => placements.TryGetConnectionId(id, out var connection) ? connection : null, - policy, new DirectPublisher(sink), origin.Clock, new(8, 4, 8_000_000, 2)); + policy, publisher, origin.Clock, new(8, 4, maxUnaryBytes, 2), renewalSink: renewalSinkFactory?.Invoke(sink) ?? sink); using var browse = new ProjectedBrowseAccess(placements, resolver, applier, sink, (uri, id) => manager.TryGetNodeId(uri, id, out var node) ? node : null, new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8); @@ -256,13 +487,71 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests new UserIdentity("apikey", System.Text.Encoding.UTF8.GetBytes("test-secret")), default, ct); } - private sealed class DirectPublisher(SdkAddressSpaceSink sink) : IProjectedValuePublisher + // The real publication port accepts owned work before the SDK worker takes the node-manager lock. + // Keep that ordering here too: Runtime must never enter the SDK while holding a source gate. + private sealed class QueuedComposedPublisher : IProjectedValuePublisher, IAsyncDisposable { + private sealed record Batch(ProjectedValueUpdate[] Updates, long Bytes); + private readonly Channel _pending = Channel.CreateBounded(new BoundedChannelOptions(16) + { SingleReader = true, FullMode = BoundedChannelFullMode.Wait, AllowSynchronousContinuations = false }); + private readonly object _gate = new(); + private readonly SdkAddressSpaceSink _sink; + private readonly Action? _onPublished; + private readonly Task _worker; + private int _count; + private long _bytes; + private bool _disposed; + public QueuedComposedPublisher(SdkAddressSpaceSink sink, Action? onPublished) + { _sink = sink; _onPublished = onPublished; _worker = Task.Run(ApplyAsync); } public bool TryBind(ProjectedValueRoute route) => true; - public bool TryPublish(IReadOnlyList updates) => ((IProjectedValueSink)sink).TryPublish( - updates.Select(x => new ProjectedValueWrite(x.Route.Realm, x.Route.LocalIdentifier, x.Route.ProjectionGeneration, - x.Route.Serving, x.Snapshot, x.OriginAgeBounds, x.ReceivedTimestamp, x.SourceProof, x.IsCompleteSnapshot)).ToArray()); + public bool TryPublish(IReadOnlyList updates) + { + long bytes; + try { bytes = checked(256 + updates.Sum(x => checked(512 + OwnedDataSample.Estimate(x.Snapshot.Value)))); } + catch (Exception error) when (error is ArgumentException or OverflowException) { return false; } + lock (_gate) + { + if (_disposed || _count >= 16 || bytes > 8_000_000 - _bytes) return false; + _count++; _bytes += bytes; + } + try + { + var owned = updates.Select(x => x with + { Snapshot = x.Snapshot with { Value = OwnedDataSample.CopyLegacy(x.Snapshot.Value) } }).ToArray(); + if (_pending.Writer.TryWrite(new(owned, bytes))) return true; + } + catch + { + Release(bytes); + throw; + } + Release(bytes); + return false; + } + private void Release(long bytes) { lock (_gate) { _count--; _bytes -= bytes; } } + private async Task ApplyAsync() + { + await foreach (var batch in _pending.Reader.ReadAllAsync()) + { + try + { + if (batch.Updates.Any(x => !x.SourceProof.IsValid || + (x.MaximumSampleAge is { } maximum && !x.OriginAgeBounds.Advance( + x.SourceProof.Clock.GetElapsedTime(x.ReceivedTimestamp)).IsFresh(maximum)))) continue; + var accepted = ((IProjectedValueSink)_sink).TryPublish(batch.Updates.Select(x => new ProjectedValueWrite( + x.Route.Realm, x.Route.LocalIdentifier, x.Route.ProjectionGeneration, x.Route.Serving, x.Snapshot, + x.OriginAgeBounds, x.ReceivedTimestamp, x.SourceProof, x.IsCompleteSnapshot, x.SourceVersion)).ToArray()); + if (accepted) foreach (var update in batch.Updates) _onPublished?.Invoke(update); + } + finally { Release(batch.Bytes); } + } + } public void Retire(ProjectedValueRoute route) { } + public async ValueTask DisposeAsync() + { + lock (_gate) { _disposed = true; _pending.Writer.TryComplete(); } + await _worker; + } } private sealed class PeerAuthenticator(DataAuthenticatedContext context) : IOpcUaUserAuthenticator diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConfiguredDiscoveryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConfiguredDiscoveryWireTests.cs index ac4310f70..4d40de772 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConfiguredDiscoveryWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConfiguredDiscoveryWireTests.cs @@ -163,7 +163,7 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests private static DataConnection Connection() => new() { DataConnectionId = "link", ClusterId = "cluster", Enabled = true, ExpectedClusterId = "cluster" }; - private static CatalogAttempt Prepare(LocalCatalogCoordinator coordinator, bool restrictToPlant = false) + private static CatalogAttempt Prepare(LocalCatalogCoordinator coordinator, bool restrictToPlant = false, bool allowWrite = false, int? localPermissions = null) { var bytes = Encoding.UTF8.GetBytes(""" {"Clusters":[{"ClusterId":"cluster","Name":"Cluster","Enterprise":"ent","Site":"site","CreatedBy":"test","RedundancyMode":0,"Enabled":true}], @@ -178,6 +178,9 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests if (restrictToPlant) bytes = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(bytes).Replace( "\"ScopeKind\":0,\"PermissionFlags\":7", "\"ScopeKind\":7,\"ScopeId\":\"folder\",\"PermissionFlags\":7", StringComparison.Ordinal)); + if (allowWrite) bytes = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(bytes).Replace("\"PermissionFlags\":7", "\"PermissionFlags\":23", StringComparison.Ordinal)); + if (localPermissions is { } permissions) bytes = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(bytes).Replace( + allowWrite ? "\"PermissionFlags\":23" : "\"PermissionFlags\":7", $"\"PermissionFlags\":{permissions}", StringComparison.Ordinal)); var attempt = coordinator.BeginAttempt(Convert.ToHexStringLower(SHA256.HashData(bytes))); coordinator.InstallAuthority(attempt, DeploymentArtifact.ParseDataPlaneAuthority(bytes, "node-a")).ShouldBeTrue(); using var parsed = DeploymentArtifact.Open(bytes); @@ -223,6 +226,13 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests { public readonly Channel Opened = Channel.CreateUnbounded(); public readonly Channel Closed = Channel.CreateUnbounded(); + // Opt-in controlled origin frames; the existing discovery cases keep their empty snapshots. + public TimeProvider? SampleClock; + public int SnapshotValue = 7; + public long SnapshotVersion = 1; + public bool HoldNextSnapshotEnd; + public readonly Channel ItemsAdded = Channel.CreateUnbounded(); + public readonly Channel SnapshotEndHeld = Channel.CreateUnbounded(); private int _opens; public int Opens => Volatile.Read(ref _opens); public Task SubscribeAsync(CancellationToken cancellationToken) @@ -230,15 +240,29 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests var number = Interlocked.Increment(ref _opens); return Task.FromResult(new Stream(this, serving(), number)); } - private sealed class Stream(FakeSubscriptions owner, ServingIdentity serving, int number) : IDataSubscription, IDataSubscriptionProvenance + public sealed class Stream(FakeSubscriptions owner, ServingIdentity serving, int number) : IDataSubscription, IDataSubscriptionProvenance { private readonly Channel _frames = Channel.CreateUnbounded(); private readonly Dictionary _ids = new(); + private readonly object _gate = new(); + private string? _subscriptionId; + private long _epoch; + private DataItemHandle? _currentHandle; + private bool _snapshotEndHeld; + public TimeSpan Interval { get; private set; } + private int _removeCommands, _addCommands; + public int RemoveCommands => Volatile.Read(ref _removeCommands); + public int AddCommands => Volatile.Read(ref _addCommands); private long _sequence; private ulong _handle; public ServingIdentity Serving => serving; public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) { + lock (_gate) + { + _subscriptionId = command.SubscriptionId; _epoch = command.StreamEpoch; + if (command is RemoveSubscriptionItems) Interlocked.Increment(ref _removeCommands); + if (command is AddSubscriptionItems) Interlocked.Increment(ref _addCommands); IReadOnlyList items = command switch { OpenSubscription open => open.Items, AddSubscriptionItems add => add.Items, _ => [] }; var acks = items.Select(item => new DataSubscriptionItemAck(item.ClientItemId, DataItemStatus.Good, new DataItemHandle(command.SubscriptionId, command.StreamEpoch, ++_handle, 1), item.Settings, null)).ToArray(); @@ -249,10 +273,47 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests if (items.Count > 0) { owner.Opened.Writer.TryWrite(number); + Interval = items[0].Settings.PublishingInterval; + _currentHandle = acks[0].Handle; _frames.Writer.TryWrite(new DataSubscriptionControl(command.SubscriptionId, command.StreamEpoch, ++_sequence, DataStreamControlKind.SnapshotBegin, [], serving.CatalogEpoch, serving.AuthorityEpoch, null)); - _frames.Writer.TryWrite(new DataSubscriptionControl(command.SubscriptionId, command.StreamEpoch, ++_sequence, DataStreamControlKind.SnapshotEnd, [], serving.CatalogEpoch, serving.AuthorityEpoch, null)); + if (owner.SampleClock is { } clock) + EmitValueCore(owner.SnapshotVersion, owner.SnapshotValue, clock.GetUtcNow(), TimeSpan.Zero, snapshot: true); + if (owner.HoldNextSnapshotEnd) + { + owner.HoldNextSnapshotEnd = false; _snapshotEndHeld = true; + owner.SnapshotEndHeld.Writer.TryWrite(this); + } + else EndSnapshot(); + owner.ItemsAdded.Writer.TryWrite(this); } return Task.CompletedTask; + } + } + public void EmitValue(long version, int value, DateTimeOffset sourceTimestamp, TimeSpan age) + { + lock (_gate) EmitValueCore(version, value, sourceTimestamp, age, snapshot: false); + } + public void EmitValueWithoutSourceTimestamp(long version, int value, TimeSpan age) + { + lock (_gate) EmitValueCore(version, value, null, age, snapshot: false); + } + private void EmitValueCore(long version, int value, DateTimeOffset? sourceTimestamp, TimeSpan age, bool snapshot) + { + var sample = new DataSample( + ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromScalar(DataValueKind.Int32, value), + 0, sourceTimestamp, sourceTimestamp, serving, version); + _frames.Writer.TryWrite(new DataSubscriptionValues(_subscriptionId!, _epoch, ++_sequence, snapshot, + [new DataSubscriptionValue(_currentHandle!, sample, new(age, age), DataReadiness.Ready)])); + } + private void EndSnapshot() => _frames.Writer.TryWrite(new DataSubscriptionControl(_subscriptionId!, _epoch, + ++_sequence, DataStreamControlKind.SnapshotEnd, [], serving.CatalogEpoch, serving.AuthorityEpoch, null)); + public void ReleaseSnapshotEnd() + { + lock (_gate) + { + if (!_snapshotEndHeld) throw new InvalidOperationException("No origin snapshot is held."); + _snapshotEndHeld = false; EndSnapshot(); + } } public IAsyncEnumerable ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken); public ValueTask DisposeAsync() { _frames.Writer.TryComplete(); owner.Closed.Writer.TryWrite(number); return ValueTask.CompletedTask; } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConnectionClientTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConnectionClientTests.cs index 0bdd44799..53ac4fd95 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConnectionClientTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConnectionClientTests.cs @@ -19,6 +19,221 @@ public sealed class GrpcDataConnectionClientTests 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, Trait("Phase", "P11")] + public async Task Compact_capable_peer_is_explicitly_offered_codec_one_on_the_subscription_call() + { + var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); + var handle = new DataItemHandle("s", 1, 1, 1); + var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, settings, null)])); + using var value = new DataSubscriptionValues("s", 1, 2, true, + [new(handle, new DataSample(DataValue.FromScalar(DataValueKind.Int32, 42), 0, null, null, Serving, 1))]); + var compact = DataProtoMapper.EncodeValues(value, true); + ack.Serving = compact.Serving = DataProtoMapper.EncodeServing(Serving); + var handler = new StreamWireHandler([ack, compact]) { CompactCodec = 1 }; + 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 reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken); + (await reader.MoveNextAsync()).ShouldBeTrue(); + (await reader.MoveNextAsync()).ShouldBeTrue(); + using var received = reader.Current.ShouldBeOfType(); + received.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(42); + handler.CompactHeader.ShouldBe("1"); + var diagnostic = connection.CaptureDiagnostics(1, 1, "artifact"); + diagnostic.CompactFrameCount.ShouldBe(1); diagnostic.FallbackFrameCount.ShouldBe(0); + diagnostic.SerializedValueFrameBytes.ShouldBe(compact.CalculateSize()); + } + + [Fact, Trait("Phase", "P11")] + public async Task Compact_frame_without_capability_negotiation_is_rejected() + { + var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); + var handle = new DataItemHandle("s", 1, 1, 1); + var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, settings, null)])); + using var value = new DataSubscriptionValues("s", 1, 2, true, + [new(handle, new DataSample(DataValue.FromScalar(DataValueKind.Int32, 42), 0, null, null, Serving, 1))]); + var compact = DataProtoMapper.EncodeValues(value, true); + ack.Serving = compact.Serving = DataProtoMapper.EncodeServing(Serving); + var handler = new StreamWireHandler([ack, compact]); + 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 reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken); + (await reader.MoveNextAsync()).ShouldBeTrue(); + await Should.ThrowAsync(async () => await reader.MoveNextAsync()); + handler.CompactHeader.ShouldBeNull(); + } + + [Theory, Trait("Phase", "P11")] + [InlineData(false, 1, false, false, false)] + [InlineData(false, 1, true, false, true)] + [InlineData(true, 0, false, false, false)] + [InlineData(true, 2, false, false, false)] + [InlineData(true, 1, false, true, false)] + public async Task Compact_opt_out_and_peer_compatibility_are_enforced(bool enabled, int codec, bool compactFrame, bool offered, bool reject) + { + var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); + var handle = new DataItemHandle("s", 1, 1, 1); + var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, settings, null)])); + using var value = new DataSubscriptionValues("s", 1, 2, true, + [new(handle, new DataSample(DataValue.FromScalar(DataValueKind.Int32, 42), 0, null, null, Serving, 1))]); + var wire = DataProtoMapper.EncodeValues(value, compactFrame); + ack.Serving = wire.Serving = DataProtoMapper.EncodeServing(Serving); + var handler = new StreamWireHandler([ack, wire]) { CompactCodec = codec }; + 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, enableCompactBatches: enabled); + 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 reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken); + (await reader.MoveNextAsync()).ShouldBeTrue(); + if (reject) await Should.ThrowAsync(async () => await reader.MoveNextAsync()); + else { (await reader.MoveNextAsync()).ShouldBeTrue(); ((IDisposable)reader.Current).Dispose(); } + handler.CompactHeader.ShouldBe(offered ? "1" : null); + var diagnostic = connection.CaptureDiagnostics(1, 1, "artifact"); + diagnostic.CompactFrameCount.ShouldBe(0); diagnostic.FallbackFrameCount.ShouldBe(reject ? 0 : 1); + diagnostic.SerializedValueFrameBytes.ShouldBe(reject ? 0 : wire.CalculateSize()); + } + + [Fact, Trait("Phase", "P11")] + public async Task Unary_read_carries_its_local_age_observation_but_never_serializes_it() + { + var ct = TestContext.Current.CancellationToken; + var clock = new ManualTimeProvider(); + 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 CapabilityBudgetHandler()), manager.Acquire("link"), 65536, 1, clock); + var reads = await connection.ReadAsync(new([new("0", View, null)], Budget), ct); + try + { + var result = reads.ShouldHaveSingleItem(); + var observed = result.FreshnessObservedTimestamp.ShouldNotBeNull(); + clock.Advance(TimeSpan.FromSeconds(1)); + result.AgeBounds.Advance(clock.GetElapsedTime(observed, clock.GetTimestamp())).Upper.ShouldBe(TimeSpan.FromSeconds(1)); + var wire = DataProtoMapper.EncodeReadResponse(reads); + var decoded = DataProtoMapper.DecodeReadResponse(wire, causalRequestElapsed: TimeSpan.Zero); + try { decoded.ShouldHaveSingleItem().FreshnessObservedTimestamp.ShouldBeNull(); } + finally { foreach (var item in decoded) item.Dispose(); } + } + finally { foreach (var item in reads) item.Dispose(); } + } + + [Fact, Trait("Phase", "P10")] + public async Task Single_item_read_and_browse_allow_the_bounded_multi_kind_capability_handshake() + { + var handler = new CapabilityBudgetHandler(); + 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 budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 65536); + var reads = await connection.ReadAsync(new([new("0", View, null)], budget), TestContext.Current.CancellationToken); + using (reads.ShouldHaveSingleItem()) reads[0].Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(42); + var page = await connection.BrowseAsync(new(View, null, null, budget), TestContext.Current.CancellationToken); + page.Items.ShouldHaveSingleItem().BrowseName.ShouldBe("child"); + handler.ReadCalls.ShouldBe(1); handler.BrowseCalls.ShouldBe(1); + } + + [Theory, Trait("Phase", "P10")] + [InlineData(false)] + [InlineData(true)] + public async Task Single_item_operation_still_rejects_an_oversized_response_after_capability_handshake(bool browse) + { + var handler = new CapabilityBudgetHandler { OversizedResult = true }; + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1); + var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 65536); + if (browse) + { + await Should.ThrowAsync(() => connection.BrowseAsync(new(View, null, null, budget), TestContext.Current.CancellationToken)); + handler.BrowseCalls.ShouldBe(1); + } + else + { + await Should.ThrowAsync(() => connection.ReadAsync(new([new("0", View, null)], budget), TestContext.Current.CancellationToken)); + handler.ReadCalls.ShouldBe(1); + } + } + + [Fact, Trait("Phase", "P10")] + public async Task Duplicate_capability_kinds_are_rejected_before_operation_dispatch() + { + var handler = new CapabilityBudgetHandler { DuplicateKind = 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("0", View, null)], Budget), TestContext.Current.CancellationToken)); + handler.ReadCalls.ShouldBe(0); + } + + [Fact, Trait("Phase", "P10")] + public async Task Excessive_distinct_capability_kinds_are_rejected_before_operation_dispatch() + { + var handler = new CapabilityBudgetHandler { ExcessiveKinds = 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("0", View, null)], Budget), TestContext.Current.CancellationToken)); + handler.ReadCalls.ShouldBe(0); + } + + private sealed class CapabilityBudgetHandler : HttpMessageHandler + { + internal bool OversizedResult, DuplicateKind, ExcessiveKinds; + internal int ReadCalls, BrowseCalls; + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal)) + { + var caps = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 3, Serving, DataReadiness.Ready, + DataOperations.Read | DataOperations.Browse, new HashSet { DataValueKind.Int32, DataValueKind.String, DataValueKind.Boolean }, + Limits, false, 0, "c", false, true, true)); + if (DuplicateKind) caps.ValueKinds.Add(caps.ValueKinds[0]); + if (ExcessiveKinds) + { + caps.ValueKinds.Clear(); + caps.ValueKinds.AddRange(Enumerable.Range(1, Enum.GetValues().Length).Select(value => (W.ValueKind)value)); + } + return Task.FromResult(Frame(caps)); + } + if (request.RequestUri.AbsolutePath.EndsWith("/Read", StringComparison.Ordinal)) + { + Interlocked.Increment(ref ReadCalls); + var items = Enumerable.Range(0, OversizedResult ? 2 : 1).Select(i => new ReadResult(i.ToString(), DataItemStatus.Good, + DataReadiness.Ready, TimeSpan.Zero, new(DataValue.FromScalar(DataValueKind.Int32, 42), 0, null, null, Serving, 1), null, + AgeBounds: new(TimeSpan.Zero, TimeSpan.Zero))).ToArray(); + try { var wire = DataProtoMapper.EncodeReadResponse(items); wire.Serving = DataProtoMapper.EncodeServing(Serving); return Task.FromResult(Frame(wire)); } + finally { foreach (var item in items) item.Dispose(); } + } + if (request.RequestUri.AbsolutePath.EndsWith("/Browse", StringComparison.Ordinal)) + { + Interlocked.Increment(ref BrowseCalls); + var metadata = Enumerable.Range(0, OversizedResult ? 2 : 1).Select(i => new DataMetadata(View with + { Address = View.Address with { Identifier = "x/child" + i }, Subject = "x/child" + i }, "child", "Variable", DataValueKind.Int32, + -1, [], false, DataOperations.Read, 1, null, null, false, Serving: Serving)).ToArray(); + var wire = DataProtoMapper.EncodeBrowseResponse(new DataBrowseBranch(View, DataItemStatus.Good, metadata, true, null, + new MetadataLease(1, 1, TimeSpan.FromSeconds(1)))); + wire.Serving = DataProtoMapper.EncodeServing(Serving); return Task.FromResult(Frame(wire)); + } + throw new InvalidOperationException("Unexpected gRPC method."); + } + } + [Fact, Trait("Phase", "P09")] public async Task Coalesced_notice_is_reported_separately_from_unknown_overflow() { @@ -50,6 +265,11 @@ public sealed class GrpcDataConnectionClientTests connection.CaptureDiagnostics(2, 3, "artifact").State.ShouldBe("connecting"); await connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken); var live = connection.CaptureDiagnostics(2, 3, "artifact"); + live.AccountingInstanceId.ShouldNotBeNullOrWhiteSpace(); + connection.CaptureDiagnostics(4, 5, "next-artifact").AccountingInstanceId.ShouldBe(live.AccountingInstanceId); + await using var replacement = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], new Security(new WireHandler()), manager.Acquire("link"), 65536, 1); + replacement.CaptureDiagnostics(2, 3, "artifact").AccountingInstanceId.ShouldNotBe(live.AccountingInstanceId); live.State.ShouldBe("ready"); live.SelectedEndpoint.ShouldBe("https://example.test:8443"); live.Serving.ShouldBe(Serving); live.ActiveCalls.ShouldBe(0); live.ScopeVersion.ShouldBe(3); live.ProtocolMinor.ShouldBe(3); live.LastSampleAtUtc.ShouldBeNull(); @@ -562,11 +782,14 @@ public sealed class GrpcDataConnectionClientTests } private sealed class StreamWireHandler(IReadOnlyList frames) : HttpMessageHandler { + internal int CompactCodec; + internal string? CompactHeader; 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)))); + DataOperations.Subscribe, new HashSet { DataValueKind.Int32 }, Limits, CompactCodec > 0, CompactCodec, "c", false, true)))); + CompactHeader = request.Headers.TryGetValues("x-data-compact-codec", out var values) ? values.Single() : null; using var stream = new MemoryStream(); foreach (var frame in frames) { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCrossCadenceProofWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCrossCadenceProofWireTests.cs new file mode 100644 index 000000000..2de92b5c6 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCrossCadenceProofWireTests.cs @@ -0,0 +1,72 @@ +using Opc.Ua; +using Opc.Ua.Client; +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; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Lost_cadence_retains_only_original_freshness_while_another_cadence_covers_the_source() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + var gated = new GateLaterSubscriptions(subscriptions); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => gated); + peer = origin; subscriptions.SampleClock = origin.Clock; + try + { + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var slow = (await client.CreateSubscriptionAsync(new RequestHeader(), 200, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, slow, anchor, 1, 200, ct); + var slowStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var initialSlow = await PublishComposedNotification(client, 1, ct); + initialSlow.Value.StatusCode.ShouldBe(StatusCodes.Good); + var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, fast, anchor, 2, 50, ct); + var fastStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + fastStream.ShouldNotBeSameAs(slowStream); + var initialFast = await PublishComposedNotification(client, 2, ct); + initialFast.Value.StatusCode.ShouldBe(StatusCodes.Good); + + await slowStream.DisposeAsync(); + await gated.RetryBlocked.Task.WaitAsync(TimeSpan.FromSeconds(10), ct); + var oldSlow = await client.RepublishAsync(new RequestHeader(), slow, initialSlow.Sequence, ct); + StatusCode.IsGood(ComposedChanges(oldSlow.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode) + .ShouldBeTrue("continuously proven coverage preserves the original still-fresh source evidence"); + var oldFast = await client.RepublishAsync(new RequestHeader(), fast, initialFast.Sequence, ct); + oldFast.NotificationMessage.ShouldNotBeNull(); + StatusCode.IsGood(ComposedChanges(oldFast.NotificationMessage).Single(x => x.ClientHandle == 2).Value.StatusCode) + .ShouldBeTrue("the still-live cadence retains its own notification proof"); + origin.Clock.Advance(TimeSpan.FromSeconds(3)); + var expiredSlow = await client.RepublishAsync(new RequestHeader(), slow, initialSlow.Sequence, ct); + StatusCode.IsGood(ComposedChanges(expiredSlow.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode) + .ShouldBeFalse("peer coverage cannot renew the original notification's two-second age bound"); + }, staleTimeoutMilliseconds: 2000); + } + finally { gated.Release.TrySetResult(); } + } + + private sealed class GateLaterSubscriptions(IDataSubscriptionService inner) : IDataSubscriptionService + { + private int _calls; + internal readonly TaskCompletionSource RetryBlocked = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource Release = new(TaskCreationOptions.RunContinuationsAsynchronously); + public async Task SubscribeAsync(CancellationToken ct) + { + if (Interlocked.Increment(ref _calls) > 2) + { + RetryBlocked.TrySetResult(); + await Release.Task.WaitAsync(ct); + } + return await inner.SubscribeAsync(ct); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeployedFreshnessWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeployedFreshnessWireTests.cs new file mode 100644 index 000000000..641fd5e3e --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeployedFreshnessWireTests.cs @@ -0,0 +1,143 @@ +using System.Threading.Channels; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using BrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest; +using ReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest; +using ReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Deployed_framed_grpc_challenge_delivers_finite_age_to_sdk_monitored_item() + { + var ct = TestContext.Current.CancellationToken; + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + LocalDataFixture? peer = null; + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (context, target) => + new LocalSubscriptionService(peer!.Services, context, target, demand, new(16, 8, 100_000, TimeSpan.FromMinutes(1)), capacity)); + peer = origin; origin.Publish(42); + await using var deployment = NewFreshnessDeployment(origin); + var deployed = new DeployedGrpcDataConnectionSource(deployment); + await WaitForDeployedFreshness(deployed, ct); + var published = Channel.CreateUnbounded(); + var source = new DeployedFreshnessSplitSource(origin, deployed); + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, sub, anchor, 1, 100, ct); + var update = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 42), ct).WaitAsync(TimeSpan.FromSeconds(8), ct); + update.OriginAgeBounds.Upper.ShouldNotBeNull(); + Opc.Ua.DataValue notification; + do { notification = await PublishComposedValue(client, 1, ct); } + while (!StatusCode.IsGood(notification.StatusCode)); + notification.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42); + }, onPublished: x => published.Writer.TryWrite(x), connectionSource: source); + } + + [Fact(Timeout = 30000), Trait("Phase", "P11Wire")] + public async Task Deployed_framed_grpc_challenge_respects_batch_limit_and_scope_revocation() + { + var ct = TestContext.Current.CancellationToken; + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + LocalDataFixture? peer = null; + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (context, target) => + new LocalSubscriptionService(peer!.Services, context, target, demand, new(16, 8, 100_000, TimeSpan.FromMinutes(1)), capacity)); + peer = origin; origin.Publish(42); + await using var deployment = NewFreshnessDeployment(origin); + var source = new DeployedGrpcDataConnectionSource(deployment); + await WaitForDeployedFreshness(source, ct); + await using var lease = (await source.AcquireAsync("link", ct)).ShouldNotBeNull(); + await using var stream = await lease.Connection.SubscribeAsync(ct); + var support = stream.ShouldBeAssignableTo(); + support.SupportsFreshnessChallenges.ShouldBeTrue(); + support.FreshnessMaxItems.ShouldBe(2); + var handle = new DataItemHandle("s", 1, 1, 1); + await Should.ThrowAsync(() => stream.SendAsync( + new ChallengeSubscriptionFreshness("s", 1, "freshness-1", TimeSpan.FromSeconds(5), [handle, handle, handle]), ct)); + deployment.BeginAttempt("new-artifact"); + await Should.ThrowAsync(() => stream.SendAsync( + new ChallengeSubscriptionFreshness("s", 1, "freshness-1", TimeSpan.FromSeconds(5), [handle]), ct)); + } + + [Fact(Timeout = 30000), Trait("Phase", "P11Wire")] + public async Task Deployed_scope_does_not_advertise_challenges_for_unsupported_stream() + { + var ct = TestContext.Current.CancellationToken; + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + LocalDataFixture? peer = null; + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (context, target) => + new LocalSubscriptionService(peer!.Services, context, target, demand, new(16, 8, 100_000, TimeSpan.FromMinutes(1)), capacity)); + peer = origin; + await using var inner = origin.Connection(); + await using var lease = new DataConnectionDeploymentLease(inner, CancellationToken.None, DataOperations.Subscribe, + TimeSpan.FromSeconds(5), 2, 2, 1_000_000, 2, 8, 1_000_000, () => true, () => { }); + await using var stream = await lease.SubscribeAsync(ct); + var support = stream.ShouldBeAssignableTo(); + support.SupportsFreshnessChallenges.ShouldBeFalse(); + support.FreshnessMaxItems.ShouldBe(0); + await Should.ThrowAsync(() => stream.SendAsync( + new ChallengeSubscriptionFreshness("s", 1, "freshness-1", TimeSpan.FromSeconds(5), [new DataItemHandle("s", 1, 1, 1)]), ct)); + } + + private static DataConnectionDeploymentRuntime NewFreshnessDeployment(LocalDataFixture origin) + { + var runtime = new DataConnectionDeploymentRuntime("consumer", "owner", new FreshnessSecurity(origin), new ImmediateFreshnessScope(), 4, origin.Clock); + runtime.Apply(new DataConnectionDeploymentSnapshot(1, "freshness-artifact", [new DataConnection + { + DataConnectionId = "link", ClusterId = "owner", Revision = 1, Enabled = true, ConsumerNodeIds = ["consumer"], + TargetMode = DataTargetMode.Node, ExpectedClusterId = "cluster", ExpectedNodeId = "node-a", Endpoints = ["https://fixture.test"], + SecretReference = "secret", SecretScopeClusterId = "owner", AllowedOperations = DataOperations.Subscribe, + MaxMessageBytes = 1_000_000, MaxBatchItems = 2, MaxPageItems = 2, MaxStreams = 2, + MaxMonitoredItems = 8, MaxPendingBytes = 1_000_000, TimeoutMilliseconds = 5000 + }])); + return runtime; + } + private static async Task WaitForDeployedFreshness(DeployedGrpcDataConnectionSource source, CancellationToken ct) + { + for (var i = 0; i < 250; i++) + { + var lease = await source.AcquireAsync("link", ct); + if (lease is not null) { await lease.DisposeAsync(); return; } + await Task.Delay(20, ct); + } + throw new TimeoutException("Deployed route did not become ready."); + } + private sealed class ImmediateFreshnessScope : IDataConnectionScopeActivator + { + public Task SetScopeAsync(long version, IReadOnlyDictionary allowlist, CancellationToken cancellationToken) => Task.CompletedTask; + } + private sealed class DeployedFreshnessSplitSource(LocalDataFixture origin, DeployedGrpcDataConnectionSource deployed) : IGrpcDataAdapterConnectionSource + { + public async ValueTask AcquireAsync(string id, CancellationToken ct) + { + var lease = await deployed.AcquireAsync(id, ct); + return lease is null ? null : new SplitLease(origin.Connection(), lease); + } + private sealed class SplitLease(IDataConnection local, IGrpcDataAdapterConnectionLease deployedLease) : IGrpcDataAdapterConnectionLease, IDataConnection + { + public IDataConnection Connection => this; + public CancellationToken CancellationToken => deployedLease.CancellationToken; + public DataTarget Target => deployedLease.Connection.Target; + public TimeProvider Clock => deployedLease.Connection.Clock; + public Task GetCapabilitiesAsync(DataBudget b, CancellationToken ct) => local.GetCapabilitiesAsync(b, ct); + public Task BrowseAsync(BrowseRequest r, CancellationToken ct) => local.BrowseAsync(r, ct); + public Task>> GetMetadataAsync(MetadataRequest r, CancellationToken ct) => local.GetMetadataAsync(r, ct); + public Task> ReadAsync(ReadRequest r, CancellationToken ct) => local.ReadAsync(r, ct); + public Task> WriteAsync(WriteBatch r, CancellationToken ct) => local.WriteAsync(r, ct); + public Task SubscribeAsync(CancellationToken ct) => deployedLease.Connection.SubscribeAsync(ct); + public async ValueTask DisposeAsync() { await local.DisposeAsync(); await deployedLease.DisposeAsync(); } + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeployedWriteDeadlineTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeployedWriteDeadlineTests.cs new file mode 100644 index 000000000..ac6ccadbd --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeployedWriteDeadlineTests.cs @@ -0,0 +1,132 @@ +using System.Buffers.Binary; +using System.Net; +using Google.Protobuf; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +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 W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; +using BrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest; +using ReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest; +using ReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Theory(Timeout = 90000), Trait("Phase", "P11Wire")] + [InlineData(false, true)] + [InlineData(true, false)] + public async Task Deployed_sdk_write_honors_default_and_explicit_short_connection_deadlines(bool useShortTimeout, bool shouldDispatch) + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + var route = new DefaultBoundRecordingRoute(); + DataWriteExecutor? executor = null; + using var origin = new LocalDataFixture(servingGeneration: 1, + targetSubscriptions: (_, _) => subscriptions, writes: _ => executor!); + peer = origin; route.View = origin.Raw; + var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000, + TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1)); + var capabilities = new DataCapabilitiesProvider("cluster", () => origin.Serving, () => true, limits); + var policy = new DataOperationPolicy(origin.Authority, new TriePermissionEvaluator(origin.Authority.Tries, origin.Clock), origin.Clock); + executor = new DataWriteExecutor(origin.Context, () => origin.Catalog, policy, capabilities, route, + new WriteOperationRegistry(origin.Serving.Incarnation, 16, 16_384, TimeSpan.FromMinutes(1), origin.Clock), + new WriteValueBudget(16_384), origin.Clock, DriverWriteBounds.Default); + var definition = new DataConnection + { + DataConnectionId = "link", ClusterId = "owner", Revision = 1, Enabled = true, ConsumerNodeIds = ["consumer"], + TargetMode = DataTargetMode.Node, ExpectedClusterId = "cluster", ExpectedNodeId = "node-a", Endpoints = ["https://fixture.test"], + SecretReference = "secret", SecretScopeClusterId = "owner", AllowedOperations = DataOperations.Write, + MaxMessageBytes = 1_000_000, MaxBatchItems = 2, MaxPageItems = 2, MaxStreams = 2, + MaxMonitoredItems = 8, MaxPendingBytes = 1_000_000 + }; + if (useShortTimeout) definition.TimeoutMilliseconds = 5000; + await using var deployment = new DataConnectionDeploymentRuntime("consumer", "owner", new DeployedWriteSecurity(origin, executor), new ImmediateFreshnessScope(), 4, origin.Clock); + deployment.Apply(new(1, "write-artifact", [definition])); + var deployed = new DeployedGrpcDataConnectionSource(deployment); + await WaitForDeployedFreshness(deployed, ct); + var source = new DeployedWriteSplitSource(origin, deployed); + await WithComposedServer(origin, origin.Raw, async (session, sink, resolver, applier, access, placements, anchor) => + { + var discovery = new ConfiguredProjectionDiscovery(placements, resolver, applier, sink, access, + new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8); + await using var lease = await discovery.ResolveAsync(Reference("map", DataRealm.Raw, origin.Raw.Address), ct); + lease.ShouldNotBeNull(); + await subscriptions.Opened.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var response = await ((SessionClient)session).WriteAsync(new RequestHeader { TimeoutHint = 30000 }, + [new WriteValue { NodeId = anchor, AttributeId = Attributes.Value, + Value = new Opc.Ua.DataValue(new Variant(77), StatusCodes.Good) }], ct); + var status = response.Results.ToArray()!.ShouldHaveSingleItem(); + if (shouldDispatch) status.ShouldBe(StatusCodes.Good); + else StatusCode.IsBad(status).ShouldBeTrue(); + route.Dispatches.ShouldBe(shouldDispatch ? 1 : 0); + }, maxUnaryBytes: 1024 * 1024, allowWrite: true, connectionSource: source); + } + + private sealed class DeployedWriteSecurity(LocalDataFixture origin, DataWriteExecutor executor) : IDataConnectionSecurityProvider + { + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken ct) => + ValueTask.FromResult(new("v1", "ca", "key", () => new DeployedWriteHandler(origin, executor))); + } + private sealed class DeployedWriteHandler(LocalDataFixture origin, DataWriteExecutor executor) : HttpMessageHandler + { + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + IMessage message; + if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal)) + { + await using var connection = origin.Connection(); + var caps = await connection.GetCapabilitiesAsync(LocalDataFixture.Budget, ct); + message = DataProtoMapper.EncodeCapabilities(caps with { ResponseServingIdentity = true }); + } + else + { + var bytes = await request.Content!.ReadAsByteArrayAsync(ct); + var batch = DataProtoMapper.DecodeWriteRequest(W.WriteRequest.Parser.ParseFrom(bytes.AsSpan(5).ToArray()), 100, 1_000_000); + try + { + var outcomes = await executor.WriteAsync(batch, ct); + var response = DataProtoMapper.EncodeWriteResponse(outcomes); + response.Serving = DataProtoMapper.EncodeServing(origin.Serving); message = response; + } + finally { foreach (var item in batch.Items) item.Value.Dispose(); } + } + var payload = message.ToByteArray(); var framed = new byte[payload.Length + 5]; + BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), payload.Length); payload.CopyTo(framed, 5); + var responseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent(framed) }; + responseMessage.Content.Headers.ContentType = new("application/grpc"); responseMessage.TrailingHeaders.Add("grpc-status", "0"); + return responseMessage; + } + } + private sealed class DeployedWriteSplitSource(LocalDataFixture origin, DeployedGrpcDataConnectionSource deployed) : IGrpcDataAdapterConnectionSource + { + public async ValueTask AcquireAsync(string id, CancellationToken ct) + { + var lease = await deployed.AcquireAsync(id, ct); + return lease is null ? null : new SplitLease(origin.Connection(), lease); + } + private sealed class SplitLease(IDataConnection local, IGrpcDataAdapterConnectionLease deployedLease) : IGrpcDataAdapterConnectionLease, IDataConnection + { + public IDataConnection Connection => this; + public CancellationToken CancellationToken => deployedLease.CancellationToken; + public DataTarget Target => deployedLease.Connection.Target; + public TimeProvider Clock => deployedLease.Connection.Clock; + public Task GetCapabilitiesAsync(DataBudget b, CancellationToken ct) => local.GetCapabilitiesAsync(b, ct); + public Task BrowseAsync(BrowseRequest r, CancellationToken ct) => local.BrowseAsync(r, ct); + public Task>> GetMetadataAsync(MetadataRequest r, CancellationToken ct) => local.GetMetadataAsync(r, ct); + public Task> ReadAsync(ReadRequest r, CancellationToken ct) => local.ReadAsync(r, ct); + public Task> WriteAsync(WriteBatch r, CancellationToken ct) => deployedLease.Connection.WriteAsync(r, ct); + public Task SubscribeAsync(CancellationToken ct) => local.SubscribeAsync(ct); + public async ValueTask DisposeAsync() { await local.DisposeAsync(); await deployedLease.DisposeAsync(); } + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataExpiredOverlapFailoverWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataExpiredOverlapFailoverWireTests.cs new file mode 100644 index 000000000..39dd4f55b --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataExpiredOverlapFailoverWireTests.cs @@ -0,0 +1,431 @@ +using System.Reflection; +using System.Threading.Channels; +using Opc.Ua; +using Opc.Ua.Client; +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; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Theory(Timeout = 90000), Trait("Phase", "P11Renewal")] + [InlineData(false)] + [InlineData(true)] + public async Task Two_cadences_release_expired_overlap_without_borrowing_witnesses_during_failover(bool sweepExpired) + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? first = null, second = null; + var firstSubscriptions = new FakeSubscriptions(() => first!.Serving); + var secondSubscriptions = new FakeSubscriptions(() => second!.Serving); + using var originA = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => firstSubscriptions); + first = originA; firstSubscriptions.SampleClock = originA.Clock; + using var originB = new LocalDataFixture(servingGeneration: 2, targetSubscriptions: (_, _) => secondSubscriptions, + clock: originA.Clock, servingNode: "node-b", servingIncarnation: "serving-2"); + second = originB; secondSubscriptions.SampleClock = originB.Clock; + secondSubscriptions.SnapshotValue = 8; + var started = originA.Clock.GetTimestamp(); + var connections = new OverlapFailoverConnections(originA); + var published = Channel.CreateUnbounded(); + await WithComposedServer(originA, originA.Raw, async (session, sink, resolver, _, access, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var slow = (await client.CreateSubscriptionAsync(new RequestHeader(), 200, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, slow, anchor, 1, 200, ct); + var slowStream = await firstSubscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct); + var oldNotification = await PublishComposedNotification(client, 1, ct); + oldNotification.Value.StatusCode.ShouldBe(StatusCodes.Good); + originA.Clock.Advance(TimeSpan.FromMilliseconds(125)); + var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, fast, anchor, 2, 50, ct); + var fastStream = await firstSubscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + fastStream.Interval.ShouldNotBe(slowStream.Interval); + (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); + while (published.Reader.TryRead(out _)) { } + // Stagger P2, then keep the fast cadence on its independently pinned + // P2 while the slow cadence adopts P3. + while (originA.Clock.GetElapsedTime(started, originA.Clock.GetTimestamp()) < TimeSpan.FromSeconds(7.5)) + { originA.Clock.Advance(TimeSpan.FromMilliseconds(125)); await Task.Delay(20, ct); } + var p2First = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > started, ct); + originA.Clock.Advance(TimeSpan.FromMilliseconds(125)); + var p2Fast = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > p2First.ReceivedTimestamp, ct); + PauseFastRenewalTimer(originA.Clock); + while (published.Reader.TryRead(out _)) { } + var remaining = TimeSpan.FromSeconds(15) - originA.Clock.GetElapsedTime(started, originA.Clock.GetTimestamp()); + if (remaining > TimeSpan.Zero) originA.Clock.Advance(remaining); + p2First.SourceProof.IsValid.ShouldBeTrue(); + var p3Task = NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > p2Fast.ReceivedTimestamp, ct); + for (var i = 0; i < 4 && !p3Task.IsCompleted; i++) + { originA.Clock.Advance(TimeSpan.FromMilliseconds(250)); await Task.Delay(100, ct); } + var p3 = await p3Task; + p3.SourceProof.IsValid.ShouldBeTrue(); + var captured = CapturePredecessorAuthority(access, sink); + var previous = captured.Previous.ShouldNotBeNull(); + previous.ShouldBeSameAs(captured.FastProof, "the fast demand must independently retain P2"); + captured.Current.ShouldBeSameAs(captured.SlowProof, "the slow demand must independently retain P3"); + captured.FastDemand.IsValid.ShouldBeTrue(); captured.SlowDemand.IsValid.ShouldBeTrue(); + previous.Lease.IsValid.ShouldBeTrue(); captured.Current.Lease.IsValid.ShouldBeTrue(); + fastStream.EmitValue(2, 9, originA.Clock.GetUtcNow(), TimeSpan.Zero); + var previousSample = await NextPublished(published.Reader, x => !x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 9), ct); + previousSample.SourceProof.ShouldBeSameAs(p2Fast.SourceProof); + var previousNotification = await PublishComposedNotification(client, 2, ct); + previousNotification.Value.StatusCode.ShouldBe(StatusCodes.Good); + + access.RetryJitterForTests = _ => TimeSpan.FromMilliseconds(5); + connections.SetCurrent(null); + await slowStream.DisposeAsync(); await fastStream.DisposeAsync(); + await connections.BothOfflineEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + originA.Clock.Advance(TimeSpan.FromSeconds(16)); + previous.Lease.IsValid.ShouldBeFalse(); captured.Current.Lease.IsValid.ShouldBeFalse(); + CapturePredecessorAuthority(access, sink).Previous.ShouldBeSameAs(previous, + "both paused attempts still retain the expired predecessor before recovery"); + var held = CapturePredecessorAuthority(access, sink); + held.FastProof.ShouldBeSameAs(previous); + held.SlowProof.ShouldBeSameAs(captured.Current); + if (sweepExpired) + { + const BindingFlags fields = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + var cache = resolver.GetType().GetField("_cache", fields)!.GetValue(resolver)!; + var cacheGate = cache.GetType().GetField("_sync", fields)!.GetValue(cache)!; + lock (cacheGate) + { + cache.GetType().GetMethod("ReclaimExpired", fields)!.Invoke(cache, null); + var retired = (System.Collections.IDictionary)cache.GetType().GetField("_retiredPerNode", fields)!.GetValue(cache)!; + retired.Values.Cast().ShouldHaveSingleItem().ShouldBe(2, + "both pinned expired proofs must already be retired before recovery"); + } + } + // No validity read on SourceState or its sample proofs occurs before + // releasing the held retry; each demand retains its own old witness. + connections.SetCurrent(originB); + var recovered1 = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.Route.Serving == originB.Serving, ct) + .WaitAsync(TimeSpan.FromSeconds(10), ct); + var recovered2 = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.Route.Serving == originB.Serving, ct) + .WaitAsync(TimeSpan.FromSeconds(10), ct); + recovered1.SourceProof.ShouldNotBeSameAs(recovered2.SourceProof); + recovered1.SourceProof.IsValid.ShouldBeTrue(); recovered2.SourceProof.IsValid.ShouldBeTrue(); + // Publish responses share the session across both subscriptions. Keep + // both handles instead of discarding whichever arrives first. + using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct)) + { + timeout.CancelAfter(TimeSpan.FromSeconds(10)); + var observed = new HashSet(); + while (observed.Count < 2) + { + var response = await client.PublishAsync(new RequestHeader(), default, timeout.Token); + foreach (var change in ComposedChanges(response.NotificationMessage)) + { + if (change.ClientHandle is not (1 or 2)) continue; + change.Value.StatusCode.ShouldBe(StatusCodes.Good); + change.Value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8); + observed.Add(change.ClientHandle); + } + } + } + original.SourceProof.IsValid.ShouldBeFalse(); + previousSample.SourceProof.IsValid.ShouldBeFalse(); + p3.SourceProof.IsValid.ShouldBeFalse(); + var replay = await client.RepublishAsync(new RequestHeader(), slow, oldNotification.Sequence, ct); + StatusCode.IsGood(ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode).ShouldBeFalse(); + var previousReplay = await client.RepublishAsync(new RequestHeader(), fast, previousNotification.Sequence, ct); + StatusCode.IsGood(ComposedChanges(previousReplay.NotificationMessage).Single(x => x.ClientHandle == 2).Value.StatusCode).ShouldBeFalse(); + }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections); + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Renewal")] + public async Task Expired_overlap_after_stream_loss_cannot_block_same_item_new_primary_recovery() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? first = null, second = null; + var firstSubscriptions = new FakeSubscriptions(() => first!.Serving); + var secondSubscriptions = new FakeSubscriptions(() => second!.Serving); + using var originA = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => firstSubscriptions); + first = originA; firstSubscriptions.SampleClock = originA.Clock; + using var originB = new LocalDataFixture(servingGeneration: 2, targetSubscriptions: (_, _) => secondSubscriptions, + clock: originA.Clock, servingNode: "node-b", servingIncarnation: "serving-2"); + second = originB; secondSubscriptions.SampleClock = originB.Clock; + secondSubscriptions.SnapshotValue = 8; + var connections = new OverlapFailoverConnections(originA); + var published = Channel.CreateUnbounded(); + await WithComposedServer(originA, originA.Raw, async (session, _, _, _, access, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, sub, anchor, 1, 100, ct); + var oldStream = await firstSubscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var initial = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct); + var firstNotification = await PublishComposedNotification(client, 1, ct); + firstNotification.Value.StatusCode.ShouldBe(StatusCodes.Good); + originA.Clock.Advance(TimeSpan.FromSeconds(9)); + await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > initial.ReceivedTimestamp, ct); + + const BindingFlags fields = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + var ownerGate = access.GetType().GetField("_sync", fields)!.GetValue(access)!; + var sources = (System.Collections.IDictionary)access.GetType().GetField("_sources", fields)!.GetValue(access)!; + object state; + lock (ownerGate) + state = sources.Values.Cast().Single(x => x.GetType().GetField("_previousProof", fields)!.GetValue(x) is not null); + var stateGate = state.GetType().GetField("Gate", fields)!.GetValue(state)!; + ProjectedNodeProof previous, current; + lock (stateGate) + { + previous = (ProjectedNodeProof)state.GetType().GetField("_previousProof", fields)!.GetValue(state).ShouldNotBeNull(); + current = (ProjectedNodeProof)state.GetType().GetField("_proof", fields)!.GetValue(state).ShouldNotBeNull(); + } + previous.Lease.IsValid.ShouldBeTrue(); current.Lease.IsValid.ShouldBeTrue(); + // Lose the physical stream while both metadata witnesses are still live. + // No test or diagnostic reads SourceState.IsValid: that getter currently + // prunes the predecessor and would mask the retention defect. + access.RetryJitterForTests = _ => TimeSpan.FromMilliseconds(5); + connections.SetCurrent(null); + await oldStream.DisposeAsync(); + var active = state.GetType().GetField("_activeAttempts", fields)!; + SpinWait.SpinUntil(() => { lock (stateGate) return (int)active.GetValue(state)! == 0; }, TimeSpan.FromSeconds(5)).ShouldBeTrue(); + await connections.OfflineEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + originA.Clock.Advance(TimeSpan.FromSeconds(16)); + previous.Lease.IsValid.ShouldBeFalse(); current.Lease.IsValid.ShouldBeFalse(); + lock (stateGate) + state.GetType().GetField("_previousProof", fields)!.GetValue(state).ShouldBeSameAs(previous, + "the paused retry cannot release its predecessor before the controlled recovery boundary"); + + connections.SetCurrent(originB); + var recovered = await NextPublished(published.Reader, + x => x.IsCompleteSnapshot && x.Route.Serving == originB.Serving && Equals(x.Snapshot.Value, 8), ct) + .WaitAsync(TimeSpan.FromSeconds(10), ct); + recovered.SourceProof.IsValid.ShouldBeTrue(); + var value = await PublishComposedValue(client, 1, ct); + value.StatusCode.ShouldBe(StatusCodes.Good); + value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8); + var replay = await client.RepublishAsync(new RequestHeader(), sub, firstNotification.Sequence, ct); + StatusCode.IsGood(ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode).ShouldBeFalse(); + }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections); + } + + [Theory(Timeout = 90000), Trait("Phase", "P11Renewal")] + [InlineData(false, true)] + [InlineData(true, true)] + [InlineData(true, false)] + public async Task New_primary_renews_same_monitored_item_after_a_prior_mapped_read(bool warmByRead, bool subscribeBeforeFailover) + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? first = null, second = null; + var firstSubscriptions = new FakeSubscriptions(() => first!.Serving) { SnapshotVersion = 2 }; + var secondSubscriptions = new FakeSubscriptions(() => second!.Serving) { SnapshotValue = 8 }; + using var originA = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => firstSubscriptions); + first = originA; + firstSubscriptions.SampleClock = originA.Clock; + using var originB = new LocalDataFixture(servingGeneration: 2, targetSubscriptions: (_, _) => secondSubscriptions, + clock: originA.Clock, servingNode: "node-b", servingIncarnation: "serving-2"); + second = originB; + secondSubscriptions.SampleClock = originB.Clock; + originA.Publish(42); + var connections = new OverlapFailoverConnections(originA); + var published = Channel.CreateUnbounded(); + var identifier = ProjectedDataIds.Identifier("map", originA.Raw.Address); + const BindingFlags fields = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + + await WithComposedServer(originA, originA.Raw, async (session, _, resolver, _, access, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + ProjectedValueUpdate? mappedRead = null; + if (warmByRead) + { + var pending = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Both, + [new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], ct); + pending.Results[0].StatusCode.ShouldBe(StatusCodes.BadWaitingForInitialData); + mappedRead = await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 42), ct); + mappedRead.Route.Serving.ShouldBe(originA.Serving); + var cached = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Both, + [new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], ct); + StatusCode.IsGood(cached.Results[0].StatusCode).ShouldBeTrue(); + cached.Results[0].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42); + + var oldSource = mappedRead.SourceProof.SourceIdentity; + var gate = oldSource.GetType().GetField("Gate", fields)!.GetValue(oldSource)!; + lock (gate) + { + oldSource.GetType().GetField("ReadOwned", fields)!.GetValue(oldSource).ShouldBe(true); + oldSource.GetType().GetField("_pin", fields)!.GetValue(oldSource).ShouldNotBeNull(); + } + } + + resolver.TryResolveProjected(DataRealm.Raw, identifier, out var oldProof).ShouldBeTrue(); + var oldLease = oldProof.ShouldNotBeNull().Lease.ShouldBeOfType(); + oldLease.Serving.ShouldBe(originA.Serving); + oldLease.IsValid.ShouldBeTrue(); + + var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + uint? oldSequence = null; + access.RetryJitterForTests = _ => TimeSpan.FromMilliseconds(5); + if (subscribeBeforeFailover) + { + await AddComposedItem(client, subscription, anchor, 1, 100, ct); + var oldStream = await firstSubscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var oldBaseline = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct); + oldBaseline.Route.Serving.ShouldBe(originA.Serving); + if (mappedRead is not null) + oldBaseline.SourceProof.SourceIdentity.ShouldBeSameAs(mappedRead.SourceProof.SourceIdentity, + "the old subscription and successful mapped Read must own the same source"); + var oldNotification = await PublishComposedNotification(client, 1, ct); + oldNotification.Value.StatusCode.ShouldBe(StatusCodes.Good); + oldNotification.Value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(7); + oldSequence = oldNotification.Sequence; + + connections.SetCurrent(null); + await oldStream.DisposeAsync(); + await connections.OfflineEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + connections.SetCurrent(originB); + } + else + { + mappedRead.ShouldNotBeNull(); + firstSubscriptions.Opens.ShouldBe(0, "the old source must have only a unary Read owner"); + SpinWait.SpinUntil(() => !access.HasLiveDemand(DataRealm.Raw, identifier), TimeSpan.FromSeconds(2)).ShouldBeTrue(); + connections.SetCurrent(originB); + originA.Clock.Advance(oldLease.Remaining + TimeSpan.FromSeconds(1)); + oldLease.IsValid.ShouldBeFalse(); + + var readProof = oldProof.ShouldNotBeNull(); + var cache = (ProjectedCatalogCache)resolver.GetType().GetField("_cache", fields)!.GetValue(resolver)!; + var beforeBrowse = cache.CaptureRetainedDiagnostics(DataRealm.Raw, identifier); + beforeBrowse.Retained.ShouldBeTrue(); + beforeBrowse.Retired.ShouldBeFalse("the expired Read-owned proof is still indexed before authenticated Browse"); + beforeBrowse.RemoteLeaseValid.ShouldBe(false); + beforeBrowse.Generation.ShouldBe(readProof.Generation); + + // Authenticated Browse installs the new primary's proof before + // the first item attaches. No old cohort migrates in this case. + await BrowseAll(client, anchor, 1); + resolver.TryResolveProjected(DataRealm.Raw, identifier, out var browsedProof).ShouldBeTrue(); + var newPrimaryProof = browsedProof.ShouldNotBeNull(); + newPrimaryProof.ShouldNotBeSameAs(readProof); + newPrimaryProof.Lease.Serving.ShouldBe(originB.Serving); + cache.IsCurrentProof(newPrimaryProof).ShouldBeTrue(); + resolver.IsUsableProof(readProof).ShouldBeFalse(); + await AddComposedItem(client, subscription, anchor, 1, 100, ct); + } + + var newStream = await secondSubscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + await NextPublished(published.Reader, + x => x.IsCompleteSnapshot && x.Route.Serving == originB.Serving && Equals(x.Snapshot.Value, 8), ct); + var firstNotification = await PublishComposedNotification(client, 1, ct); + firstNotification.Value.StatusCode.ShouldBe(StatusCodes.Good); + firstNotification.Value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8); + resolver.TryResolveProjected(DataRealm.Raw, identifier, out var firstProof).ShouldBeTrue(); + var firstLease = firstProof.ShouldNotBeNull().Lease.ShouldBeOfType(); + firstLease.Serving.ShouldBe(originB.Serving); + + secondSubscriptions.SnapshotValue = 9; + secondSubscriptions.SnapshotVersion = 2; + originA.Clock.Advance(firstLease.UsableDuration / 2 + TimeSpan.FromSeconds(1)); + await NextPublished(published.Reader, + x => x.IsCompleteSnapshot && x.Route.Serving == originB.Serving && Equals(x.Snapshot.Value, 9), ct); + firstLease.IsValid.ShouldBeTrue("healthy overlap must finish before the new primary's first lease expires"); + resolver.TryResolveProjected(DataRealm.Raw, identifier, out var renewedProof).ShouldBeTrue(); + var successorProof = renewedProof.ShouldNotBeNull(); + successorProof.ShouldNotBeSameAs(firstProof); + var successorLease = successorProof.Lease.ShouldBeOfType(); + (await secondSubscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct)) + .ShouldBeSameAs(newStream); + var renewedValue = await PublishComposedValue(client, 1, ct); + renewedValue.StatusCode.ShouldBe(StatusCodes.Good); + renewedValue.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(9); + + // Cross the first lease without also making its successor due for + // renewal. The next ordinary samples belong to this accepted cohort. + originA.Clock.Advance(firstLease.Remaining + TimeSpan.FromMilliseconds(250)); + firstLease.IsValid.ShouldBeFalse(); + successorLease.Remaining.ShouldBeGreaterThan(successorLease.UsableDuration / 2); + for (var value = 10; value <= 11; value++) + { + newStream.EmitValue(value - 7, value, originA.Clock.GetUtcNow(), TimeSpan.Zero); + var ordinary = await NextPublished(published.Reader, + x => !x.IsCompleteSnapshot && x.Route.Serving == originB.Serving && Equals(x.Snapshot.Value, value), ct); + ordinary.SourceVersion.ShouldBe(value - 7L); + using var deliveryTimeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + deliveryTimeout.CancelAfter(TimeSpan.FromSeconds(10)); + var statuses = new List(); + try + { + Opc.Ua.DataValue delivered; + do + { + delivered = await PublishComposedValue(client, 1, deliveryTimeout.Token); + if (statuses.Count < 8) statuses.Add(delivered.StatusCode); + } + while (!StatusCode.IsGood(delivered.StatusCode)); + delivered.StatusCode.ShouldBe(StatusCodes.Good); + delivered.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(value); + } + catch (Exception error) when (error is not OutOfMemoryException) + { + throw new InvalidOperationException($"Post-expiry SDK value {value} was not delivered. " + + $"Statuses: {string.Join(", ", statuses)}. Sample proof valid={ordinary.SourceProof.IsValid}, " + + $"source valid={ordinary.SourceProof.IsSourceValid}, adds={newStream.AddCommands}, removes={newStream.RemoveCommands}.", error); + } + } + + var expiredSequences = new List { firstNotification.Sequence }; + if (oldSequence is { } previousSequence) expiredSequences.Add(previousSequence); + foreach (var sequence in expiredSequences) + { + var replay = await client.RepublishAsync(new RequestHeader(), subscription, sequence, ct); + StatusCode.IsGood(ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode) + .ShouldBeFalse(); + } + }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections); + } + + private sealed class OverlapFailoverConnections(LocalDataFixture initial) : IGrpcDataAdapterConnectionSource + { + private LocalDataFixture? _current = initial; + private readonly object _routeIdentity = new(); + internal readonly TaskCompletionSource OfflineEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource BothOfflineEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _online = new(TaskCreationOptions.RunContinuationsAsynchronously); + private int _offlineWaiters; + internal void SetCurrent(LocalDataFixture? fixture) + { + Volatile.Write(ref _current, fixture); + if (fixture is not null) _online.TrySetResult(); + } + public async ValueTask AcquireAsync(string id, CancellationToken ct) + { + if (id != "link") return null; + var current = Volatile.Read(ref _current); + if (current is null) + { + OfflineEntered.TrySetResult(); + if (Interlocked.Increment(ref _offlineWaiters) >= 2) BothOfflineEntered.TrySetResult(); + await _online.Task.WaitAsync(ct); + current = Volatile.Read(ref _current); + } + return current is not null ? new Lease(new Connection(current.Connection()), _routeIdentity) : null; + } + private sealed class Lease(IDataConnection connection, object identity) : IGrpcDataAdapterConnectionLease + { + public IDataConnection Connection => connection; + public CancellationToken CancellationToken => CancellationToken.None; + public object RouteIdentity => identity; + public ValueTask DisposeAsync() => connection.DisposeAsync(); + } + private sealed class Connection(IDataConnection inner) : IDataConnection + { + public DataTarget Target => new(DataTargetMode.Cluster, "cluster", null); + public TimeProvider Clock => inner.Clock; + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken ct) => inner.GetCapabilitiesAsync(budget, ct); + public Task BrowseAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest request, CancellationToken ct) => inner.BrowseAsync(request, ct); + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken ct) => inner.GetMetadataAsync(request, ct); + public Task> ReadAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest request, CancellationToken ct) => inner.ReadAsync(request, ct); + public Task> WriteAsync(WriteBatch request, CancellationToken ct) => inner.WriteAsync(request, ct); + public Task SubscribeAsync(CancellationToken ct) => inner.SubscribeAsync(ct); + public ValueTask DisposeAsync() => inner.DisposeAsync(); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFederatedBrowseTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFederatedBrowseTests.cs index d492cfba2..3fd81b972 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFederatedBrowseTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFederatedBrowseTests.cs @@ -11,6 +11,40 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; [Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] public sealed class GrpcDataFederatedBrowseTests { + [Fact, Trait("Phase", "P11")] + public void Exact_renewal_allows_one_pinned_predecessor_for_a_one_node_mapping() + { + using var fixture = new LocalDataFixture(); + var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); + var cache = new ProjectedCatalogCache(2, 3, fixture.Clock, policy); + var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); + var request = Request(fixture.Clock) with { Caller = caller }; cache.CaptureGeneration("mapping"); + var local = fixture.Activation.CaptureAuthority(); + MetadataAuthorityLease Lease() => new(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(1)), + fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(1), TimeSpan.Zero, fixture.Clock); + var initialLease = Lease(); var original = ParentProof(fixture, request, initialLease, local); + cache.TryPublish(request, new(ProjectionPageStatus.Ready, [original], true, null, 1, initialLease, local, original)).ShouldBeTrue(); + cache.TryResolveProjected(DataRealm.Raw, original.LocalIdentifier, out var installed).ShouldBeTrue(); + cache.TryPinProjected(DataRealm.Raw, original.LocalIdentifier, out var oldPin).ShouldBeTrue(); + try + { + fixture.Clock.Advance(TimeSpan.FromSeconds(2)); + var freshLease = Lease(); var fresh = ParentProof(fixture, request, freshLease, local); + cache.TryRenewExact(installed!, fresh, maximumMappingNodes: 1, out var renewed).ShouldBeTrue(); + renewed.ShouldNotBeNull(); + cache.TryPinProjected(DataRealm.Raw, original.LocalIdentifier, out var currentPin).ShouldBeTrue(); + try + { + fixture.Clock.Advance(TimeSpan.FromSeconds(2)); + var laterLease = Lease(); var later = ParentProof(fixture, request, laterLease, local); + cache.TryRenewExact(installed!, later, maximumMappingNodes: 1, out _).ShouldBeFalse( + "a node cannot accumulate an unbounded chain of pinned historical proofs"); + } + finally { currentPin!.Dispose(); } + } + finally { oldPin!.Dispose(); } + } + [Fact] public void Missing_or_unavailable_parent_is_not_reported_as_a_successful_empty_branch() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFixtureMutationRevisionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFixtureMutationRevisionTests.cs new file mode 100644 index 000000000..7f9bdbc36 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFixtureMutationRevisionTests.cs @@ -0,0 +1,129 @@ +using System.Text.Json; +using GrpcDataSeed; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Phase", "P10")] +public sealed class GrpcDataFixtureMutationRevisionTests +{ + [Fact] + public void Key_only_preserves_narrow_mapping_placement_and_every_entity_field() + { + string[] mutations = ["{\"key_action\":\"rotate\"}", "{\"key_action\":\"rotate_staged\"}", + "{\"key_action\":\"revoke\"}", "{\"key_action\":\"expire\"}", "{\"key_action\":\"retire_old\"}", + "{\"key_action\":\"expire\",\"key_expiry_seconds\":20}"]; + foreach (var json in mutations) + { + using var mutation = JsonDocument.Parse(json); + var entities = Entities(); + entities.Connection.ConsumerNodeIds = ["consumer-1:4053", "consumer-2:4053"]; + foreach (var mapping in entities.Mappings) + { + mapping.ConsumerNodeIds = ["consumer-1:4053"]; + mapping.BranchName = "narrow"; + mapping.Enabled = true; + mapping.RowVersion = [1, 2]; + } + var before = JsonSerializer.Serialize(new { entities.Connection, entities.Mappings, entities.Exports }); + foreach (var mapping in entities.Mappings) + FixtureMutationRevisions.InheritConsumerPlacement(mutation.RootElement, entities.Connection, mapping); + var receipt = FixtureMutationRevisions.Advance(mutation.RootElement, entities.Connection, entities.Mappings, entities.Exports); + JsonSerializer.Serialize(new { entities.Connection, entities.Mappings, entities.Exports }).ShouldBe(before); + receipt.CredentialOnly.ShouldBeTrue(); + } + } + + [Fact] + public void Configuration_mutation_still_inherits_connection_placement_and_advances_revisions() + { + foreach (var json in new[] { "{\"mapping_enabled\":true}", "{\"key_action\":\"rotate\",\"mapping_enabled\":true}" }) + { + using var mutation = JsonDocument.Parse(json); + var entities = Entities(); + entities.Connection.ConsumerNodeIds = ["consumer-1:4053", "consumer-2:4053"]; + foreach (var mapping in entities.Mappings) + { + mapping.ConsumerNodeIds = ["consumer-1:4053"]; + FixtureMutationRevisions.InheritConsumerPlacement(mutation.RootElement, entities.Connection, mapping); + } + FixtureMutationRevisions.Advance(mutation.RootElement, entities.Connection, entities.Mappings, entities.Exports); + foreach (var mapping in entities.Mappings) mapping.ConsumerNodeIds.ShouldBe(entities.Connection.ConsumerNodeIds); + entities.Connection.Revision.ShouldBe(8); + entities.Mappings.Select(item => item.Revision).ShouldBe([12L, 13L]); + } + } + + private static (DataConnection Connection, RemoteNamespaceMapping[] Mappings, DataExport[] Exports) Entities() => + (new() { DataConnectionId = "consumer-source", Revision = 7 }, + [new() { RemoteNamespaceMappingId = "map-raw", Revision = 11 }, new() { RemoteNamespaceMappingId = "map-uns", Revision = 12 }], + [new() { DataExportId = "export-raw", Revision = 13 }, new() { DataExportId = "export-uns", Revision = 14 }]); + + [Theory] + [InlineData("rotate")] + [InlineData("rotate_staged")] + [InlineData("expire")] + [InlineData("retire_old")] + [InlineData("revoke")] + public void Credential_only_actions_preserve_connection_mapping_and_export_revisions(string action) + { + using var mutation = JsonDocument.Parse(JsonSerializer.Serialize(new { key_action = action })); + AssertCredentialOnly(mutation.RootElement); + } + + [Fact] + public void Expiry_with_only_its_expiry_parameter_preserves_placement_revisions() + { + using var mutation = JsonDocument.Parse("{\"key_action\":\"expire\",\"key_expiry_seconds\":20}"); + AssertCredentialOnly(mutation.RootElement); + } + + private static void AssertCredentialOnly(JsonElement mutation) + { + var entities = Entities(); + var receipt = FixtureMutationRevisions.Advance(mutation, entities.Connection, entities.Mappings, entities.Exports); + entities.Connection.Revision.ShouldBe(7); + entities.Mappings.Select(item => item.Revision).ShouldBe([11L, 12L]); + entities.Exports.Select(item => item.Revision).ShouldBe([13L, 14L]); + receipt.CredentialOnly.ShouldBeTrue(); + receipt.Before.Connection.ShouldBe(receipt.After.Connection); + receipt.Before.Mappings.ShouldBe(receipt.After.Mappings); + receipt.Before.Exports.ShouldBe(receipt.After.Exports); + } + + [Fact] + public void Real_and_mixed_configuration_mutations_still_advance_every_selected_revision() + { + string[] mutations = ["{}", "{\"target_mode\":\"Node\"}", "{\"mapping_enabled\":false}", + "{\"export_allowed_operations\":3}", "{\"rename_tag\":{\"tag_id\":\"source-scalar\",\"name\":\"new-name\"}}", + "{\"key_action\":\"rotate\",\"mapping_enabled\":true}", "{\"key_action\":\"rotate\",\"connection_id\":\"consumer-source\"}", + "{\"key_action\":\"rotate\",\"unknown_field\":true}"]; + foreach (var json in mutations) + { + using var mutation = JsonDocument.Parse(json); + var entities = Entities(); + var receipt = FixtureMutationRevisions.Advance(mutation.RootElement, entities.Connection, entities.Mappings, entities.Exports); + entities.Connection.Revision.ShouldBe(8); + entities.Mappings.Select(item => item.Revision).ShouldBe([12L, 13L]); + entities.Exports.Select(item => item.Revision).ShouldBe([14L, 15L]); + receipt.CredentialOnly.ShouldBeFalse(); + receipt.Before.Connection.ShouldBe(7); + receipt.After.Connection.ShouldBe(8); + } + } + + [Fact] + public void Missing_or_unrecognized_key_action_never_classifies_as_credential_only() + { + foreach (var json in new[] { "{\"key_expiry_seconds\":20}", "{\"key_action\":\"unknown\"}", "{\"key_action\":null}", "[]" }) + { + using var mutation = JsonDocument.Parse(json); + var entities = Entities(); + var receipt = FixtureMutationRevisions.Advance(mutation.RootElement, entities.Connection, entities.Mappings, entities.Exports); + receipt.CredentialOnly.ShouldBeFalse(); + entities.Connection.Revision.ShouldBe(8); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFramedLifecycleWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFramedLifecycleWireTests.cs new file mode 100644 index 000000000..46db21d4b --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFramedLifecycleWireTests.cs @@ -0,0 +1,301 @@ +using System.Buffers.Binary; +using System.IO.Pipelines; +using System.Net; +using System.Threading.Channels; +using Google.Protobuf; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Framed_grpc_pinned_sdk_item_never_substitutes_healthy_other_node_and_old_republish_is_denied() + { + var ct = TestContext.Current.CancellationToken; + var capacityA = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var capacityB = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var demandA = new DeferredSubscriptionDemand(); demandA.Accept(); + var demandB = new DeferredSubscriptionDemand(); demandB.Accept(); + var limits = new SubscriptionSessionLimits(16, 8, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? peerA = null, peerB = null; + using var originA = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (context, target) => + new LocalSubscriptionService(peerA!.Services, context, target, demandA, limits, capacityA)); + peerA = originA; originA.Publish(7); + using var originB = new LocalDataFixture(servingGeneration: 2, targetSubscriptions: (context, target) => + new LocalSubscriptionService(peerB!.Services, context, target, demandB, limits, capacityB), + clock: originA.Clock, servingNode: "node-b", servingIncarnation: "serving-2"); + peerB = originB; originB.Publish(8); + using var connections = new FramedClusterConnections(originA, originB, pinnedToFirst: true); + var published = Channel.CreateUnbounded(); + await WithComposedServer(originA, originA.Raw, async (session, sink, resolver, applier, access, placements, anchor) => + { + var discovery = new ConfiguredProjectionDiscovery(placements, resolver, applier, sink, access, + new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8); + var configured = await discovery.ResolveAsync(Reference("map", DataRealm.Raw, originA.Raw.Address), ct); + configured.ShouldNotBeNull(); + (await connections.Opened.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct)).Node.ShouldBe("node-a"); + await configured.DisposeAsync(); + (await connections.Closed.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct)).ShouldBe("node-a"); + while (published.Reader.TryRead(out _)) { } + var client = (SessionClient)session; + var subscriptionId = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscriptionId, anchor, 1, 100, ct); + var physicalA = await connections.Opened.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + physicalA.Node.ShouldBe("node-a"); + var old = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct); + (Opc.Ua.DataValue Value, uint Sequence) initial; + do { initial = await PublishComposedNotification(client, 1, ct); } + while (!StatusCode.IsGood(initial.Value.StatusCode)); + initial.Value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(7); + + connections.Select(originB); + await physicalA.Session.DisposeAsync(); + (await connections.Closed.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct)).ShouldBe("node-a"); + // Two node-b capability probes prove that at least one full retry rejected the + // other node's otherwise healthy primary identity and proceeded to retry. + await connections.NodeBProbed.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + await connections.NodeBProbed.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + old.SourceProof.IsValid.ShouldBeFalse(); + connections.Opened.Reader.TryRead(out var replacement).ShouldBeFalse($"a pinned node must not open {replacement.Node}"); + while (published.Reader.TryRead(out var update)) + update.Route.Serving.NodeId.ShouldNotBe("node-b"); + var replay = await client.RepublishAsync(new RequestHeader(), subscriptionId, initial.Sequence, ct); + StatusCode.IsGood(ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode) + .ShouldBeFalse("a pinned item's old notification cannot remain good after its source stream is lost"); + }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections, localPermissions: 4); + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Framed_grpc_new_primary_rebinds_same_subscribe_only_sdk_item_and_rejects_old_republish() + { + var ct = TestContext.Current.CancellationToken; + var capacityA = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var capacityB = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var demandA = new DeferredSubscriptionDemand(); demandA.Accept(); + var demandB = new DeferredSubscriptionDemand(); demandB.Accept(); + var limits = new SubscriptionSessionLimits(16, 8, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? peerA = null, peerB = null; + using var originA = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (context, target) => + new LocalSubscriptionService(peerA!.Services, context, target, demandA, limits, capacityA)); + peerA = originA; originA.Publish(7); + using var originB = new LocalDataFixture(servingGeneration: 2, targetSubscriptions: (context, target) => + new LocalSubscriptionService(peerB!.Services, context, target, demandB, limits, capacityB), + clock: originA.Clock, servingNode: "node-b", servingIncarnation: "serving-2"); + peerB = originB; originB.Publish(8); + using var connections = new FramedClusterConnections(originA, originB); + var published = Channel.CreateUnbounded(); + await WithComposedServer(originA, originA.Raw, async (session, sink, resolver, applier, access, placements, anchor) => + { + // The configured, deployment-owned interest materializes the node before the + // restricted SDK caller appears. The caller itself has Subscribe only. + var discovery = new ConfiguredProjectionDiscovery(placements, resolver, applier, sink, access, + new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8); + var configured = await discovery.ResolveAsync(Reference("map", DataRealm.Raw, originA.Raw.Address), ct); + configured.ShouldNotBeNull(); + var configuredStream = await connections.Opened.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + configuredStream.Node.ShouldBe("node-a"); + await configured.DisposeAsync(); + (await connections.Closed.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct)).ShouldBe("node-a"); + while (published.Reader.TryRead(out _)) { } + + var client = (SessionClient)session; + var deniedBrowse = await client.BrowseAsync(new RequestHeader(), null, 10, [new BrowseDescription + { + NodeId = anchor, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences, + IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All, + }], ct); + StatusCode.IsGood(deniedBrowse.Results[0].StatusCode).ShouldBeFalse(); + var deniedRead = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Neither, + [new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], ct); + deniedRead.Results[0].StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied); + + var subscriptionId = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscriptionId, anchor, 1, 100, ct); + var physicalA = await connections.Opened.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + physicalA.Node.ShouldBe("node-a"); + var old = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct); + old.Route.Serving.ShouldBe(originA.Serving); + (Opc.Ua.DataValue Value, uint Sequence) initial; + do { initial = await PublishComposedNotification(client, 1, ct); } + while (!StatusCode.IsGood(initial.Value.StatusCode)); + initial.Value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(7); + var browseCalls = connections.BrowseCalls; + + connections.Select(originB); + await physicalA.Session.DisposeAsync(); // End the actual origin stream, leaving the SDK monitored item alive. + (await connections.Closed.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct)).ShouldBe("node-a"); + var physicalB = await connections.Opened.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + physicalB.Node.ShouldBe("node-b"); + var next = await NextPublished(published.Reader, + x => x.IsCompleteSnapshot && x.Route.Serving == originB.Serving && Equals(x.Snapshot.Value, 8), ct); + next.SourceProof.IsValid.ShouldBeTrue(); + old.SourceProof.IsValid.ShouldBeFalse("the ended serving incarnation cannot revive old evidence"); + connections.MetadataCallsOnB.ShouldBeGreaterThan(0, "new-primary renewal must validate metadata through gRPC"); + connections.BrowseCalls.ShouldBe(browseCalls, "recovery must not depend on a new browse grant or request"); + + Opc.Ua.DataValue current; + do { current = await PublishComposedValue(client, 1, ct); } + while (!StatusCode.IsGood(current.StatusCode)); + current.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8); + var oldReplay = await client.RepublishAsync(new RequestHeader(), subscriptionId, initial.Sequence, ct); + StatusCode.IsGood(ComposedChanges(oldReplay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode) + .ShouldBeFalse("the same monitored item must not make its old notification valid under the new serving identity"); + }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections, localPermissions: 4); + } + + /// Two independently authenticated local origins behind an HTTP/2 framed gRPC client. + private sealed class FramedClusterConnections : IGrpcDataAdapterConnectionSource, IDisposable + { + private readonly LocalDataFixture _first, _second; + private readonly bool _pinnedToFirst; + private LocalDataFixture _current; + private readonly DataConnectionManager _manager = new("consumer", 1); + private int _browseCalls, _metadataCallsOnB; + internal readonly Channel<(string Node, DataSubscriptionSession Session)> Opened = Channel.CreateUnbounded<(string, DataSubscriptionSession)>(); + internal readonly Channel Closed = Channel.CreateUnbounded(); + internal readonly Channel NodeBProbed = Channel.CreateUnbounded(); + internal int BrowseCalls => Volatile.Read(ref _browseCalls); + internal int MetadataCallsOnB => Volatile.Read(ref _metadataCallsOnB); + internal FramedClusterConnections(LocalDataFixture first, LocalDataFixture second, bool pinnedToFirst = false) + { + _first = first; _second = second; _current = first; _pinnedToFirst = pinnedToFirst; + _manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + } + internal void Select(LocalDataFixture current) => Volatile.Write(ref _current, current); + public ValueTask AcquireAsync(string id, CancellationToken ct) + { + if (id != "link") return ValueTask.FromResult(null); + var target = _pinnedToFirst ? new DataTarget(DataTargetMode.Node, "cluster", "node-a") + : new DataTarget(DataTargetMode.Cluster, "cluster", null); + var connection = new GrpcDataConnection("link", target, + [new Uri("https://node-a.test"), new Uri("https://node-b.test")], new Security(this), _manager.Acquire("link"), + 1_000_000, 2, _first.Clock, eligibleNodeIds: _pinnedToFirst ? null : new HashSet { "node-a", "node-b" }); + return ValueTask.FromResult(new Lease(connection)); + } + public void Dispose() => _manager.Dispose(); + private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease + { + public IDataConnection Connection => connection; + public CancellationToken CancellationToken => CancellationToken.None; + public ValueTask DisposeAsync() => connection.DisposeAsync(); + } + private sealed class Security(FramedClusterConnections owner) : IDataConnectionSecurityProvider + { + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string id, Uri endpoint, CancellationToken ct) + { + var origin = endpoint.Host == "node-a.test" ? owner._first : owner._second; + return ValueTask.FromResult(new("v1", "ca", "key", () => new Handler(owner, origin))); + } + } + private sealed class Handler(FramedClusterConnections owner, LocalDataFixture origin) : HttpMessageHandler + { + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + if (!ReferenceEquals(Volatile.Read(ref owner._current), origin)) throw new HttpRequestException("Endpoint is not the selected primary."); + if (request.RequestUri!.AbsolutePath.EndsWith("/Subscribe", StringComparison.Ordinal)) + { + var incoming = new Pipe(); var outgoing = new Pipe(); + _ = CopyRequestAsync(request.Content!, incoming.Writer, ct); + _ = ServeAsync(incoming.Reader.AsStream(), outgoing.Writer.AsStream(), ct); + return Response(new StreamContent(outgoing.Reader.AsStream())); + } + await using var local = origin.Services.Create(origin.Context, new(DataTargetMode.Cluster, "cluster", null)); + IMessage message; + if (request.RequestUri.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal)) + { + var caps = await local.GetCapabilitiesAsync(LocalDataFixture.Budget, ct); + if (ReferenceEquals(origin, owner._second)) owner.NodeBProbed.Writer.TryWrite(true); + message = DataProtoMapper.EncodeCapabilities(caps with { SubscriptionAgeReadiness = true, + ResponseServingIdentity = true, SubscriptionFreshnessChallenges = true }); + } + else + { + var bytes = await request.Content!.ReadAsByteArrayAsync(ct); + var payload = bytes.AsSpan(5).ToArray(); + if (request.RequestUri.AbsolutePath.EndsWith("/Browse", StringComparison.Ordinal)) + { + Interlocked.Increment(ref owner._browseCalls); + var result = await local.BrowseAsync(DataProtoMapper.DecodeBrowseRequest(W.BrowseRequest.Parser.ParseFrom(payload)), ct); + var wire = DataProtoMapper.EncodeBrowseResponse(result); wire.Serving = DataProtoMapper.EncodeServing(origin.Serving); message = wire; + } + else if (request.RequestUri.AbsolutePath.EndsWith("/GetMetadata", StringComparison.Ordinal)) + { + if (ReferenceEquals(origin, owner._second)) Interlocked.Increment(ref owner._metadataCallsOnB); + var result = await local.GetMetadataAsync(DataProtoMapper.DecodeMetadataRequest(W.MetadataRequest.Parser.ParseFrom(payload)), ct); + var wire = DataProtoMapper.EncodeMetadataResponse(result); wire.Serving = DataProtoMapper.EncodeServing(origin.Serving); message = wire; + } + else throw new InvalidOperationException("Unexpected RPC in lifecycle test."); + } + return Response(new ByteArrayContent(Frame(message))); + } + private static async Task CopyRequestAsync(HttpContent content, PipeWriter writer, CancellationToken ct) + { + try { await content.CopyToAsync(writer.AsStream(), ct); } + catch (Exception) { } + finally { await writer.CompleteAsync(); } + } + private async Task ServeAsync(Stream input, Stream output, CancellationToken ct) + { + using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(ct); + try + { + await using var local = origin.Services.Create(origin.Context, new(DataTargetMode.Cluster, "cluster", null)); + await using var stream = await local.SubscribeAsync(lifetime.Token); + var session = stream.ShouldBeOfType(); + owner.Opened.Writer.TryWrite((origin.Serving.NodeId, session)); + var reader = Task.Run(async () => + { + while (true) + { + var prefix = new byte[5]; await input.ReadExactlyAsync(prefix, lifetime.Token); + var bytes = new byte[BinaryPrimitives.ReadInt32BigEndian(prefix.AsSpan(1))]; + await input.ReadExactlyAsync(bytes, lifetime.Token); + await stream.SendAsync(DataProtoMapper.DecodeCommand(W.SubscriptionCommand.Parser.ParseFrom(bytes)), lifetime.Token); + } + }, lifetime.Token); + try + { + await foreach (var frame in stream.ReadAllAsync(lifetime.Token)) + { + try + { + var wire = frame is DataSubscriptionValues values ? DataProtoMapper.EncodeValues(values, false, true) + : DataProtoMapper.EncodeControlOrAck(frame); + wire.Serving = DataProtoMapper.EncodeServing(origin.Serving); + await output.WriteAsync(Frame(wire), lifetime.Token); await output.FlushAsync(lifetime.Token); + } + finally { (frame as IDisposable)?.Dispose(); } + } + } + finally + { + lifetime.Cancel(); + try { await reader; } catch (Exception) { } + } + } + catch (Exception) { } + finally { await output.DisposeAsync(); owner.Closed.Writer.TryWrite(origin.Serving.NodeId); } + } + private static byte[] Frame(IMessage message) + { + var payload = message.ToByteArray(); var bytes = new byte[payload.Length + 5]; + BinaryPrimitives.WriteInt32BigEndian(bytes.AsSpan(1, 4), payload.Length); payload.CopyTo(bytes, 5); return bytes; + } + private static HttpResponseMessage Response(HttpContent content) + { + var result = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = content }; + content.Headers.ContentType = new("application/grpc"); result.TrailingHeaders.Add("grpc-status", "0"); return result; + } + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFreshnessBatchWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFreshnessBatchWireTests.cs new file mode 100644 index 000000000..0a8c824af --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFreshnessBatchWireTests.cs @@ -0,0 +1,100 @@ +using System.Reflection; +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; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Multi_batch_challenge_preserves_versions_and_serializes_overlapping_snapshots() + { + var ct = TestContext.Current.CancellationToken; + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 8, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? peer = null; + using var origin = new LocalDataFixture(additionalRawNodes: 32, servingGeneration: 1, targetSubscriptions: (context, target) => + new LocalSubscriptionService(peer!.Services, context, target, demand, limits, capacity)); + peer = origin; origin.Publish(42); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + using var entered = new ManualResetEventSlim(); using var release = new ManualResetEventSlim(); + DataSubscriptionSession? server = null; var armed = 0; var held = 0; + var security = new FreshnessSecurity(origin, session => + { + server = session; + session.BeforeDirectCommitForTests = () => + { + if (Volatile.Read(ref armed) != 0 && Interlocked.Exchange(ref held, 1) == 0) + { entered.Set(); release.Wait(ct); } + }; + }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "cluster", "node-a"), + [new Uri("https://fixture.test")], security, manager.Acquire("link"), 1_000_000, 1, origin.Clock); + await using var stream = await connection.SubscribeAsync(ct); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValueTimestamp, null); + var views = new List { origin.Raw }; + views.AddRange(Enumerable.Range(0, 32).Select(i => origin.Raw with + { Address = origin.Raw.Address with { Identifier = origin.Raw.Address.Identifier + i }, Subject = origin.Raw.Subject + i })); + var items = views.Select((view, i) => new DataSubscriptionItem($"item-{i}", view, settings)).ToArray(); + await stream.SendAsync(new OpenSubscription("batch", 1, "open", TimeSpan.FromSeconds(10), items, false, + TimeSpan.FromSeconds(30), new(TimeSpan.FromSeconds(10), 33, 100_000)), ct); + await using var reader = stream.ReadAllAsync(ct).GetAsyncEnumerator(ct); + (await reader.MoveNextAsync()).ShouldBeTrue(); + var handles = reader.Current.ShouldBeOfType().Items.Select(x => x.Handle.ShouldNotBeNull()).ToArray(); + while (await reader.MoveNextAsync()) + { + if (reader.Current is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) break; + (reader.Current as IDisposable)?.Dispose(); + } + Volatile.Write(ref armed, 1); + await stream.SendAsync(new ChallengeSubscriptionFreshness("batch", 1, "freshness-1", TimeSpan.FromSeconds(10), handles), ct); + entered.Wait(TimeSpan.FromSeconds(5), ct).ShouldBeTrue(); + try + { + server.ShouldNotBeNull(); + HubTest.Publish(origin.Hub, origin.Ticket, 2, 43); origin.Hub.ProcessPending(); + origin.Clock.Advance(TimeSpan.FromMilliseconds(200)); + await stream.SendAsync(new ChallengeSubscriptionFreshness("batch", 1, "freshness-2", TimeSpan.FromSeconds(10), handles), ct); + var nonce = typeof(DataSubscriptionSession).GetField("_freshnessChallengeId", BindingFlags.Instance | BindingFlags.NonPublic)!; + var barrier = typeof(DataSubscriptionSession).GetField("_barrier", BindingFlags.Instance | BindingFlags.NonPublic)!; + SpinWait.SpinUntil(() => (int)barrier.GetValue(server)! == 1, TimeSpan.FromSeconds(5)).ShouldBeTrue(); + var snapshots = typeof(DataSubscriptionSession).GetField("_snapshots", BindingFlags.Instance | BindingFlags.NonPublic)!; + ((System.Collections.ICollection)snapshots.GetValue(server)!).Count.ShouldBe(1); + // The second command is deferred and cannot capture another snapshot yet. + ((string?)nonce.GetValue(server)).ShouldBe("freshness-1"); + } + finally { release.Set(); } + var firstEnd = false; var secondEnd = false; var sawFirstAck = false; var sawSecondAck = false; + var observed = new Dictionary(); var sawNew = false; + while (await reader.MoveNextAsync()) + { + switch (reader.Current) + { + case DataSubscriptionAck ack when ack.CommandId == "freshness-1": sawFirstAck = true; break; + case DataSubscriptionAck ack when ack.CommandId == "freshness-2": + firstEnd.ShouldBeTrue("the second snapshot must not be admitted before the first finishes"); + sawSecondAck = true; break; + case DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }: + if (!firstEnd) firstEnd = true; else if (sawSecondAck) secondEnd = true; + break; + case DataSubscriptionValues values: + using (values) + foreach (var value in values.Items) + { + if (!firstEnd) value.Sample.Version.ShouldBe(1, "a later delta must not overtake the frozen first snapshot"); + if (observed.TryGetValue(value.Handle.Handle, out var previous)) value.Sample.Version.ShouldBeGreaterThanOrEqualTo(previous); + observed[value.Handle.Handle] = value.Sample.Version; + sawNew |= value.Sample.Version == 2; + } + break; + } + if (firstEnd && secondEnd && sawNew) break; + } + sawFirstAck.ShouldBeTrue(); sawSecondAck.ShouldBeTrue(); secondEnd.ShouldBeTrue(); sawNew.ShouldBeTrue(); + observed.Count.ShouldBe(33); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFreshnessChallengeTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFreshnessChallengeTests.cs new file mode 100644 index 000000000..d02dadca9 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFreshnessChallengeTests.cs @@ -0,0 +1,101 @@ +using System.Reflection; +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("Feature", "GrpcData"), Trait("Phase", "P11")] +public sealed class GrpcDataFreshnessChallengeTests +{ + [Fact(Timeout = 30000)] + public async Task Revoked_authority_cannot_obtain_a_challenge_snapshot() + { + var ct = TestContext.Current.CancellationToken; + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (context, target) => + new LocalSubscriptionService(fixture!.Services, context, target, demand, + new(16, 8, 100_000, TimeSpan.FromMinutes(1)), capacity))) + { + fixture.Publish(42); + await using var connection = fixture.Connection(); + await using var stream = await connection.SubscribeAsync(ct); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + await stream.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10), + [new("item", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), ct); + await using var reader = stream.ReadAllAsync(ct).GetAsyncEnumerator(ct); + (await reader.MoveNextAsync()).ShouldBeTrue(); + var handle = reader.Current.ShouldBeOfType().Items.Single().Handle.ShouldNotBeNull(); + while (await reader.MoveNextAsync()) + { + if (reader.Current is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) break; + (reader.Current as IDisposable)?.Dispose(); + } + fixture.Authority.Apply("cluster", "revoked", [], [], + new Dictionary>()); + await stream.SendAsync(new ChallengeSubscriptionFreshness("s", 1, "freshness-1", TimeSpan.FromSeconds(10), [handle]), ct); + (await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeFalse(); + } + } + + [Fact(Timeout = 30000)] + public async Task Challenge_does_not_relabel_a_value_whose_age_was_already_captured() + { + var ct = TestContext.Current.CancellationToken; + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (context, target) => + new LocalSubscriptionService(fixture!.Services, context, target, demand, + new(16, 8, 100_000, TimeSpan.FromMinutes(1)), capacity))) + { + fixture.Publish(42); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(ct); + var session = subscription.ShouldBeOfType(); + using var captured = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + var once = 0; + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10), + [new("item", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), ct); + await using var reader = subscription.ReadAllAsync(ct).GetAsyncEnumerator(ct); + (await reader.MoveNextAsync()).ShouldBeTrue(); + var handle = reader.Current.ShouldBeOfType().Items.Single().Handle.ShouldNotBeNull(); + (await reader.MoveNextAsync()).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin); + (await reader.MoveNextAsync()).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Dispose(); + (await reader.MoveNextAsync()).ShouldBeTrue(); + reader.Current.ShouldBeOfType().Kind.ShouldBe(DataStreamControlKind.SnapshotEnd); + session.BeforeDirectCommitForTests = () => + { + if (Interlocked.Exchange(ref once, 1) == 0) { captured.Set(); release.Wait(ct); } + }; + HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 43); fixture.Hub.ProcessPending(); + fixture.Clock.Advance(TimeSpan.FromMilliseconds(200)); + var oldFrame = Task.Run(async () => { (await reader.MoveNextAsync()).ShouldBeTrue(); return reader.Current; }, ct); + try + { + captured.Wait(TimeSpan.FromSeconds(5), ct).ShouldBeTrue(); + await subscription.SendAsync(new ChallengeSubscriptionFreshness("s", 1, "freshness-1", TimeSpan.FromSeconds(10), [handle]), ct); + var field = typeof(DataSubscriptionSession).GetField("_freshnessChallengeId", BindingFlags.Instance | BindingFlags.NonPublic)!; + SpinWait.SpinUntil(() => (string?)field.GetValue(session) == "freshness-1", TimeSpan.FromSeconds(5)).ShouldBeTrue(); + } + finally { release.Set(); } + using (var value = (await oldFrame).ShouldBeOfType()) + value.Items.Single().FreshnessChallengeId.ShouldBeNull(); + while (await reader.MoveNextAsync()) + { + if (reader.Current is not DataSubscriptionValues value) continue; + using (value) + if (value.Items.Single().FreshnessChallengeId == "freshness-1") return; + } + throw new Xunit.Sdk.XunitException("The authorized challenge snapshot was not delivered."); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFreshnessHistoryTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFreshnessHistoryTests.cs new file mode 100644 index 000000000..263421d55 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFreshnessHistoryTests.cs @@ -0,0 +1,127 @@ +using System.Buffers.Binary; +using System.IO.Pipelines; +using System.Net; +using Google.Protobuf; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Phase", "P11")] +public sealed class GrpcDataFreshnessHistoryTests +{ + [Fact(Timeout = 90000)] + public async Task More_than_1024_challenges_release_history_and_reused_sequences_are_rejected() + { + var ct = TestContext.Current.CancellationToken; + 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", "node"), + [new Uri("https://test.invalid")], new HistorySecurity(), manager.Acquire("link"), 65536, 1); + await using var stream = await connection.SubscribeAsync(ct); + var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); + var view = new DataView(new("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x"); + await stream.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), + [new("item", view, settings)], false, TimeSpan.FromMinutes(1), new(TimeSpan.FromSeconds(5), 1, 65536)), ct); + await using var frames = stream.ReadAllAsync(ct).GetAsyncEnumerator(ct); + (await frames.MoveNextAsync()).ShouldBeTrue(); + var handle = frames.Current.ShouldBeOfType().Items.Single().Handle.ShouldNotBeNull(); + for (var i = 1; i <= 1025; i++) + { + var id = $"freshness-{i}"; + await stream.SendAsync(new ChallengeSubscriptionFreshness("s", 1, id, TimeSpan.FromSeconds(5), [handle]), ct); + (await frames.MoveNextAsync()).ShouldBeTrue(); + frames.Current.ShouldBeOfType().CommandId.ShouldBe(id); + } + await Should.ThrowAsync(() => stream.SendAsync( + new ChallengeSubscriptionFreshness("s", 1, "freshness-1", TimeSpan.FromSeconds(5), [handle]), ct)); + await stream.SendAsync(new ChallengeSubscriptionFreshness("s", 1, "freshness-1026", TimeSpan.FromSeconds(5), [handle]), ct); + (await frames.MoveNextAsync()).ShouldBeTrue(); + frames.Current.ShouldBeOfType().CommandId.ShouldBe("freshness-1026"); + foreach (var expectedBounded in new[] { false, false, true }) + { + (await frames.MoveNextAsync()).ShouldBeTrue(); + using var values = frames.Current.ShouldBeOfType(); + var item = values.Items.ShouldHaveSingleItem(); + (item.AgeBounds.Upper is not null).ShouldBe(expectedBounded, + "unknown and evicted challenge IDs must never inherit the latest proof"); + (item.FreshnessObservedTimestamp is not null).ShouldBe(expectedBounded); + } + } + + private sealed class HistorySecurity : IDataConnectionSecurityProvider + { + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string id, Uri endpoint, CancellationToken ct) => + ValueTask.FromResult(new("v1", "ca", "key", () => new HistoryHandler())); + } + private sealed class HistoryHandler : HttpMessageHandler + { + private static readonly ServingIdentity Serving = new("node", "boot", "Primary", 1, 1, 1); + protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal)) + { + var limits = new DataLimits(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)); + var caps = new DataCapabilities(1, 4, Serving, DataReadiness.Ready, DataOperations.Subscribe, + new HashSet { DataValueKind.Int32 }, limits, false, 0, "c", true, true, false, true); + return Task.FromResult(Response(new ByteArrayContent(Frame(DataProtoMapper.EncodeCapabilities(caps))))); + } + var incoming = new Pipe(); var outgoing = new Pipe(); + _ = request.Content!.CopyToAsync(incoming.Writer.AsStream(), ct); + _ = ServeAsync(incoming.Reader.AsStream(), outgoing.Writer.AsStream(), ct); + return Task.FromResult(Response(new StreamContent(outgoing.Reader.AsStream()))); + } + private static async Task ServeAsync(Stream input, Stream output, CancellationToken ct) + { + try + { + DataItemHandle? handle = null; string? clientId = null; DataSubscriptionSettings? settings = null; long sequence = 0; + while (true) + { + var prefix = new byte[5]; await input.ReadExactlyAsync(prefix, ct); + var bytes = new byte[BinaryPrimitives.ReadInt32BigEndian(prefix.AsSpan(1))]; await input.ReadExactlyAsync(bytes, ct); + var command = DataProtoMapper.DecodeCommand(W.SubscriptionCommand.Parser.ParseFrom(bytes)); + if (command is OpenSubscription open) + { + clientId = open.Items.Single().ClientItemId; settings = open.Items.Single().Settings; + handle = new(command.SubscriptionId, command.StreamEpoch, 1, 1); + } + var ack = new DataSubscriptionAck(command.SubscriptionId, command.StreamEpoch, ++sequence, command.CommandId, + [new(clientId!, DataItemStatus.Good, handle, settings, null)]); + var wire = DataProtoMapper.EncodeControlOrAck(ack); wire.Serving = DataProtoMapper.EncodeServing(Serving); + await output.WriteAsync(Frame(wire), ct); await output.FlushAsync(ct); + if (command is ChallengeSubscriptionFreshness { CommandId: "freshness-1026" }) + { + var version = 0; + foreach (var nonce in new[] { "unknown", "freshness-1", "freshness-1026" }) + { + using var values = new DataSubscriptionValues(command.SubscriptionId, command.StreamEpoch, ++sequence, false, + [new(handle!, new DataSample(DataValue.FromScalar(DataValueKind.Int32, 42), 0, null, null, Serving, ++version), + new(TimeSpan.Zero, null), DataReadiness.Ready, nonce)]); + var update = DataProtoMapper.EncodeValues(values, false, true); + update.Serving = DataProtoMapper.EncodeServing(Serving); + await output.WriteAsync(Frame(update), ct); await output.FlushAsync(ct); + } + } + } + } + catch (Exception) { } + finally { await output.DisposeAsync(); } + } + private static byte[] Frame(IMessage message) + { + var payload = message.ToByteArray(); var bytes = new byte[payload.Length + 5]; + BinaryPrimitives.WriteInt32BigEndian(bytes.AsSpan(1, 4), payload.Length); payload.CopyTo(bytes, 5); return bytes; + } + private static HttpResponseMessage Response(HttpContent content) + { + var result = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = content }; + content.Headers.ContentType = new("application/grpc"); result.TrailingHeaders.Add("grpc-status", "0"); return result; + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHotRouteContinuityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHotRouteContinuityTests.cs new file mode 100644 index 000000000..8bc06ce34 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHotRouteContinuityTests.cs @@ -0,0 +1,217 @@ +using System.Linq.Expressions; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +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 GrpcDataHotRouteContinuityTests +{ + // Reflection keeps the red test buildable before the continuity snapshot API is introduced. + private sealed class SnapshotSource { public object? Current { get; set; } } + private static (DataConnectionDeploymentRuntime Runtime, SnapshotSource Source, Type SnapshotType) Create() + { + var snapshotType = typeof(DataConnectionDeploymentRuntime).Assembly.GetType( + "ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.DataConnectionConsumerRoleSnapshot"); + var source = new SnapshotSource(); + if (snapshotType is null) + return (new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), new Activator(), 4, + consumerMayAcquire: () => true), source, typeof(object)); + source.Current = System.Activator.CreateInstance(snapshotType!, RedundancyMode.Hot, true, 1L); + var body = Expression.Convert(Expression.Property(Expression.Constant(source), nameof(SnapshotSource.Current)), snapshotType!); + var provider = Expression.Lambda(typeof(Func<,>).MakeGenericType(typeof(RedundancyMode), snapshotType!), body, + Expression.Parameter(typeof(RedundancyMode), "artifactMode")).Compile(); + var constructor = typeof(DataConnectionDeploymentRuntime).GetConstructors().Single(x => + x.GetParameters().Any(p => p.Name == "consumerRoleSnapshot")); + var runtime = (DataConnectionDeploymentRuntime)constructor.Invoke(["node-a", "owner", new Security(), new Activator(), 4, + null, (Func)(() => true), true, provider]); + return (runtime, source, snapshotType!); + } + private static void Set(SnapshotSource source, Type type, RedundancyMode mode, bool eligible, long epoch) => + source.Current = System.Activator.CreateInstance(type, mode, eligible, epoch); + private static DataConnection Definition() => new() + { + DataConnectionId = "link", 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 async Task Acquire(DataConnectionDeploymentRuntime runtime) + { + for (var i = 0; i < 100; i++) + { + if (runtime.TryAcquire("link", out var lease)) return lease!; + await Task.Delay(20, TestContext.Current.CancellationToken); + } + throw new TimeoutException("Route did not become ready."); + } + [Fact] + public async Task Hot_eligible_role_transitions_preserve_the_existing_route_but_epoch_aba_invalidates_it() + { + var (runtime, source, type) = Create(); + await using (runtime) + { + runtime.Apply(new(1, "artifact-1", [Definition()], RedundancyMode.Hot)); + using var lease = await Acquire(runtime); + runtime.NotifyConsumerRoleChanged(); + lease.CancellationToken.IsCancellationRequested.ShouldBeFalse(); + using (var retained = await Acquire(runtime)) retained.CancellationToken.ShouldBe(lease.CancellationToken); + // The current verdict is positive again, but the intervening Unknown/owner change + // changed the epoch even when its callback was missed. + Set(source, type, RedundancyMode.Hot, true, 2); + await Should.ThrowAsync(() => lease.GetCapabilitiesAsync(new(TimeSpan.FromSeconds(1), 1, 1024), TestContext.Current.CancellationToken)); + runtime.NotifyConsumerRoleChanged(); + lease.CancellationToken.IsCancellationRequested.ShouldBeTrue(); + } + } + [Theory] + [InlineData(RedundancyMode.Warm)] + [InlineData(RedundancyMode.None)] + public async Task Host_effective_non_hot_mode_drains_even_when_artifact_is_hot(RedundancyMode mode) + { + var (runtime, source, type) = Create(); + await using (runtime) + { + runtime.Apply(new(1, "artifact-1", [Definition()], RedundancyMode.Hot)); + using var lease = await Acquire(runtime); + Set(source, type, mode, true, 1); + runtime.NotifyConsumerRoleChanged(); + lease.CancellationToken.IsCancellationRequested.ShouldBeTrue(); + } + } + [Fact] + public async Task Retained_metadata_guard_survives_borrower_disposal_but_not_unobserved_epoch_loss() + { + var (runtime, source, type) = Create(); + await using (runtime) + { + runtime.Apply(new(1, "artifact-1", [Definition()], RedundancyMode.Hot)); + var borrowed = await Acquire(runtime); + var clock = new ManualTimeProvider(); + var cache = new ProjectedCatalogCache(4, 4, clock); + var serving = new ServingIdentity("remote", "boot", "Primary", 1, 1, 1); + var remote = new MetadataAuthorityLease(serving, new MetadataLease(1, 1, TimeSpan.FromSeconds(15)), + clock.GetTimestamp(), TimeSpan.FromSeconds(15), TimeSpan.Zero, clock); + var proof = new BoundProjectionLease(remote, borrowed.CancellationToken, new Authority(), cache, "mapping", + cache.CaptureGeneration("mapping"), () => true, borrowed.RouteCurrent); + borrowed.Dispose(); + proof.IsValid.ShouldBeTrue(); + Set(source, type, RedundancyMode.Hot, true, 2); + proof.IsValid.ShouldBeFalse(); + proof.CaptureDiagnostics().RouteAlive.ShouldBeFalse(); + } + } + [Theory] + [InlineData(RedundancyMode.Warm)] + [InlineData(RedundancyMode.None)] + public async Task Non_hot_retained_metadata_does_not_revive_after_missed_ineligible_transition(RedundancyMode mode) + { + var (runtime, source, type) = Create(); + await using (runtime) + { + Set(source, type, mode, true, 1); + runtime.Apply(new(1, "artifact-1", [Definition()], RedundancyMode.Hot)); + var borrowed = await Acquire(runtime); + var clock = new ManualTimeProvider(); + var cache = new ProjectedCatalogCache(4, 4, clock); + var serving = new ServingIdentity("remote", "boot", "Primary", 1, 1, 1); + var remote = new MetadataAuthorityLease(serving, new MetadataLease(1, 1, TimeSpan.FromSeconds(15)), + clock.GetTimestamp(), TimeSpan.FromSeconds(15), TimeSpan.Zero, clock); + var proof = new BoundProjectionLease(remote, borrowed.CancellationToken, new Authority(), cache, "mapping", + cache.CaptureGeneration("mapping"), () => true, borrowed.RouteCurrent); + borrowed.Dispose(); + proof.IsValid.ShouldBeTrue(); + Set(source, type, mode, false, 2); + proof.IsValid.ShouldBeFalse(); + Set(source, type, mode, true, 3); + proof.IsValid.ShouldBeFalse(); + } + } + [Fact] + public void Read_epoch_is_stable_between_known_roles_and_changes_on_unknown_and_owner_replacement() + { + var role = new RedundancyRoleView(); + var owner = role.RegisterDataServingOwner(); + role.PublishDataServingRole(owner, RedundancyRole.Primary, true); + var original = role.ReadEligibilityEpoch; + role.PublishDataServingRole(owner, RedundancyRole.Secondary, false); + role.ReadEligibilityEpoch.ShouldBe(original); + role.PublishDataServingRole(owner, null, false); + role.PublishDataServingRole(owner, RedundancyRole.Primary, true); + role.ReadEligibilityEpoch.ShouldBeGreaterThan(original); + var afterUnknown = role.ReadEligibilityEpoch; + role.RetireDataServingOwner(owner); + var replacement = role.RegisterDataServingOwner(); + role.PublishDataServingRole(replacement, RedundancyRole.Primary, true); + role.ReadEligibilityEpoch.ShouldBeGreaterThan(afterUnknown); + } + [Fact] + public async Task Hot_retained_guard_reads_role_without_waiting_for_dispatch_fence() + { + var role = new RedundancyRoleView(); + var owner = role.RegisterDataServingOwner(); + role.PublishDataServingRole(owner, RedundancyRole.Primary, true); + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), new Activator(), 4, + consumerRoleSnapshot: mode => + { + var observed = role.CaptureDataServingRole(); + return new(mode, observed.Role is "Primary" or "Secondary", observed.ReadEligibilityEpoch); + }); + runtime.Apply(new(1, "artifact-1", [Definition()], RedundancyMode.Hot)); + using var borrowed = await Acquire(runtime); + var clock = new ManualTimeProvider(); + var cache = new ProjectedCatalogCache(4, 4, clock); + var serving = new ServingIdentity("remote", "boot", "Primary", 1, 1, 1); + var remote = new MetadataAuthorityLease(serving, new MetadataLease(1, 1, TimeSpan.FromSeconds(15)), + clock.GetTimestamp(), TimeSpan.FromSeconds(15), TimeSpan.Zero, clock); + var proof = new BoundProjectionLease(remote, borrowed.CancellationToken, new Authority(), cache, "mapping", + cache.CaptureGeneration("mapping"), () => true, borrowed.RouteCurrent); + borrowed.Dispose(); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var held = Task.Run(() => + { + using (role.DispatchFence.Enter()) + { + entered.SetResult(); + release.Task.GetAwaiter().GetResult(); + } + }, TestContext.Current.CancellationToken); + try + { + await entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + proof.IsValid.ShouldBeTrue(); + } + finally { release.SetResult(); await held; } + } + private sealed class Authority : IDataMappedCatalogAuthority + { + public long CatalogEpoch => 1; + public long AuthorityEpoch => 1; + public bool IsActive => true; + } + private sealed class Security : IDataConnectionSecurityProvider + { + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => + ValueTask.FromResult(new("1", "trust", "key", () => new EmptyHandler())); + } + private sealed class EmptyHandler : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => throw new InvalidOperationException("Unexpected network call."); + } + private sealed class Activator : IDataConnectionScopeActivator + { + public Task SetScopeAsync(long version, IReadOnlyDictionary allowlist, CancellationToken cancellationToken) => Task.CompletedTask; + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataIngressMailboxAdmissionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataIngressMailboxAdmissionTests.cs new file mode 100644 index 000000000..746930d47 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataIngressMailboxAdmissionTests.cs @@ -0,0 +1,202 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P11")] +public sealed class GrpcDataIngressMailboxAdmissionTests +{ + [Fact(Timeout = 30000)] + public void Loss_signal_during_value_current_validation_cannot_restore_old_good_sample() + { + using var hub = HubTest.Create(partitions: 1, bytes: 100_000); + var source = HubTest.Ticket("driver", "signal-race"); + HubTest.BindAndPublish(hub, source, 1, 1); + hub.ProcessPending(); + HubTest.Publish(hub, source, 2, 2); + var observed = false; + hub.BeforePendingValueCurrentForTests = () => + { + hub.BeforePendingValueCurrentForTests = null; + observed = true; + hub.Invalidate(source, "controlled loss signal"); + }; + hub.ProcessPending(); + observed.ShouldBeTrue(); + using var result = hub.Read(source); + result.Readiness.ShouldNotBe(DataReadiness.Ready, "a loss signal must not be consumed before an older queued value becomes Good"); + } + + [Fact(Timeout = 30000)] + public async Task Overlapping_same_source_commit_fails_closed_before_newer_value_can_overtake() + { + var ct = TestContext.Current.CancellationToken; + using var hub = HubTest.Create(partitions: 1, bytes: 100_000); + var source = HubTest.Ticket("driver", "same-source-overlap"); + HubTest.BindAndPublish(hub, source, 1, 1); + hub.ProcessPending(); + hub.TryReserveIngress(source, 288, out var firstReservation).ShouldBeTrue(); + hub.TryReserveIngress(source, 288, out var secondReservation).ShouldBeTrue(); + using (firstReservation!) + using (secondReservation!) + using (var entered = new ManualResetEventSlim()) + using (var release = new ManualResetEventSlim()) + { + hub.AfterValueSequenceForTests = () => + { + hub.AfterValueSequenceForTests = null; + entered.Set(); + release.Wait(ct); + }; + var first = Task.Run(() => + { + var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 2), 0, null, null, HubTest.Serving, 2); + if (!firstReservation!.TryCommit(sample, 2)) sample.Dispose(); + }, ct); + try + { + entered.Wait(TimeSpan.FromSeconds(5), ct).ShouldBeTrue(); + var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 3), 0, null, null, HubTest.Serving, 3); + var accepted = secondReservation!.TryCommit(sample, 3); + if (!accepted) sample.Dispose(); + accepted.ShouldBeFalse("overlapping commits for one ordered source must signal loss rather than reorder"); + } + finally { release.Set(); await first.WaitAsync(TimeSpan.FromSeconds(5), ct); } + hub.ProcessPending(); + using var result = hub.Read(source); + result.Readiness.ShouldNotBe(DataReadiness.Ready); + } + } + + [Fact(Timeout = 30000)] + public async Task In_flight_commit_finishing_after_disposal_releases_transferred_sample_and_source_pin() + { + var ct = TestContext.Current.CancellationToken; + var hub = HubTest.Create(partitions: 1, bytes: 100_000); + var source = HubTest.Ticket("driver", "close-race"); + hub.TryBind(source).ShouldBeTrue(); + hub.TryReserveIngress(source, 288, out var reservation).ShouldBeTrue(); + using (reservation!) + using (var entered = new ManualResetEventSlim()) + using (var release = new ManualResetEventSlim()) + { + hub.AfterValueSequenceForTests = () => { entered.Set(); release.Wait(ct); }; + var commit = Task.Run(() => + { + var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 9), 0, null, null, HubTest.Serving, 1); + var accepted = reservation!.TryCommit(sample, 1); + if (!accepted) sample.Dispose(); + return accepted; + }, ct); + try + { + entered.Wait(TimeSpan.FromSeconds(5), ct).ShouldBeTrue(); + hub.Dispose(); + hub.Resources.RetainedBytes.ShouldBeGreaterThan(0, "the entered physical commit remains charged"); + } + finally { release.Set(); } + (await commit.WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeTrue("the entered writer transfers ownership to closed-mailbox cleanup"); + for (var i = 0; i < 250 && (hub.Resources.RetainedBytes != 0 || hub.CaptureAccounting().TrackedSources != 0); i++) + await Task.Delay(20, ct); + hub.Resources.RetainedBytes.ShouldBe(0); + hub.CaptureAccounting().TrackedSources.ShouldBe(0); + } + hub.Dispose(); + } + + [Fact(Timeout = 30000)] + public void Finite_control_backlog_cannot_starve_an_unrelated_admitted_value() + { + using var hub = new PartitionedSampleHub(new DataResourceLimits + { + PartitionCount = 1, MaxRetainedBytes = 1_000_000, MaxTrackedSources = 10, + MaxIngressItemsPerPartition = 10, MaxDirtySourcesPerPartition = 10, MaxControlItemsPerPartition = 256, + MaxSnapshotItems = 10, MaxSnapshotBytes = 10_000, MaxSnapshotCatchUpItems = 256, + MaxSnapshotLifetime = TimeSpan.FromMinutes(1) + }, new ManualTimeProvider(), autoDrain: false); + var controlSource = HubTest.Ticket("driver", "controls"); + var valueSource = HubTest.Ticket("driver", "value"); + HubTest.BindAndPublish(hub, controlSource, 1, 1); + HubTest.BindAndPublish(hub, valueSource, 1, 1); + hub.ProcessPending(); + for (var sequence = 2; sequence <= 130; sequence++) + hub.TryPublishStatus(controlSource, sequence, 0x80310000u, null, null).ShouldBeTrue(); + HubTest.Publish(hub, valueSource, 2, 42); + hub.DrainOneSliceForTests(valueSource.Key); + using var read = hub.Read(valueSource); + read.Readiness.ShouldBe(DataReadiness.Ready); + read.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(42, "an admitted value must progress despite a full control slice"); + } + + [Fact(Timeout = 30000)] + public async Task Producer_commits_while_cache_gate_is_held_and_auto_drain_preserves_complete_observation() + { + var ct = TestContext.Current.CancellationToken; + var clock = new ManualTimeProvider(); + using var hub = new PartitionedSampleHub(new DataResourceLimits + { + PartitionCount = 1, MaxRetainedBytes = 100_000, MaxTrackedSources = 10, + MaxIngressItemsPerPartition = 10, MaxDirtySourcesPerPartition = 10, MaxControlItemsPerPartition = 10, + MaxSnapshotItems = 10, MaxSnapshotBytes = 10_000, MaxSnapshotCatchUpItems = 128, + MaxSnapshotLifetime = TimeSpan.FromMinutes(1) + }, clock); + var source = HubTest.Ticket("driver", "tag"); + HubTest.BindAndPublish(hub, source, 1, 1); + hub.ProcessPending(); + hub.TryCaptureInterestSnapshot([source], HubTest.Budget, ct, out var snapshot, out var interest).ShouldBeTrue(); + using (snapshot!) + using (interest!) + using (var entered = new ManualResetEventSlim()) + using (var release = new ManualResetEventSlim()) + { + var owner = Task.Run(() => hub.WithPartitionLockForTest(source.Key, () => { entered.Set(); release.Wait(ct); }), ct); + Task? blockedRead = null; + var received = clock.GetTimestamp(); + var sourceTime = new DateTimeOffset(2026, 11, 17, 0, 0, 1, TimeSpan.Zero); + var serverTime = sourceTime.AddMilliseconds(4); + try + { + entered.Wait(TimeSpan.FromSeconds(5), ct).ShouldBeTrue(); + var producer = Task.Run(() => + { + hub.TryReserveIngress(source, 288, out var reservation).ShouldBeTrue(); + using (reservation!) + { + var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 42), 0x400u, sourceTime, serverTime, HubTest.Serving, 2); + if (!reservation!.TryCommit(sample, 2)) { sample.Dispose(); throw new InvalidOperationException("Commit rejected while cache gate held"); } + } + }, ct); + await producer.WaitAsync(TimeSpan.FromSeconds(5), ct); + interest!.IsReset.ShouldBeFalse(); + blockedRead = Task.Run(() => hub.Read(source), ct); + (await Task.WhenAny(blockedRead, Task.Delay(100, ct))).ShouldNotBe(blockedRead, "cache readers remain ordered behind the held gate"); + clock.Advance(TimeSpan.FromSeconds(1)); + } + finally { release.Set(); await owner.WaitAsync(TimeSpan.FromSeconds(5), ct); } + if (blockedRead is not null) (await blockedRead.WaitAsync(TimeSpan.FromSeconds(5), ct)).Dispose(); + CachedSourceRead? latest = null; + for (var i = 0; i < 250; i++) + { + latest?.Dispose(); latest = hub.Read(source); + if (latest.Sample?.Version == 2) break; + await Task.Delay(20, ct); + } + using (latest!) + { + latest!.Readiness.ShouldBe(DataReadiness.Ready); + latest.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(42); + latest.Sample.StatusCode.ShouldBe(0x400u); + latest.Sample.SourceTimestampUtc.ShouldBe(sourceTime); + latest.Sample.ServerTimestampUtc.ShouldBe(serverTime); + latest.Sample.Serving.ShouldBe(HubTest.Serving); + latest.Sample.Version.ShouldBe(2); + latest.ReceivedTimestamp.ShouldBe(received); + } + interest!.TryReadChanges(32, out var changes).ShouldBeTrue(); + changes.ShouldContain(x => x.Ticket == source); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataIngressMailboxRaceTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataIngressMailboxRaceTests.cs new file mode 100644 index 000000000..6be752a88 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataIngressMailboxRaceTests.cs @@ -0,0 +1,134 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P11")] +public sealed class GrpcDataIngressMailboxRaceTests +{ + [Theory(Timeout = 30000)] + [InlineData("status")] + [InlineData("remove")] + [InlineData("rebind")] + public async Task Queued_reserved_value_cannot_cross_a_later_source_fence(string fence) + { + using var hub = HubTest.Create(partitions: 1, bytes: 100_000); + var source = HubTest.Ticket("driver", "mailbox"); + HubTest.BindAndPublish(hub, source, 1, 1); + hub.ProcessPending(); + hub.TryReserveIngress(source, 288, out var reservation).ShouldBeTrue(); + using (reservation!) + { + var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 2), 0, null, null, HubTest.Serving, 2); + var transferred = false; + try + { + await WhilePartitionHeld(hub, source, () => + transferred = reservation!.TryCommit(sample, 2)); + transferred.ShouldBeTrue("the reserved mailbox accepts without waiting for the partition worker"); + } + finally { if (!transferred) sample.Dispose(); } + } + if (fence == "status") hub.TryPublishStatus(source, 3, 0x80310000u, null, null).ShouldBeTrue(); + else if (fence == "remove") hub.TryRemove(source, 3).ShouldBeTrue(); + else + { + var replacement = new SourceTicket(source.Key, new SourceGeneration(2, 1)); + hub.TryBind(replacement).ShouldBeTrue(); + HubTest.Publish(hub, replacement, 1, 3); + hub.ProcessPending(); + using var current = hub.Read(replacement); + current.Readiness.ShouldBe(DataReadiness.Ready); + current.Sample!.Value.GetScalar().ShouldBe(3); + } + hub.ProcessPending(); + using var old = hub.Read(source); + if (fence == "status" && old.Sample is not null) + old.Sample.StatusCode.ShouldBe(0x80310000u); + else old.Readiness.ShouldNotBe(DataReadiness.Ready); + } + + [Fact(Timeout = 30000)] + public async Task Mailbox_keeps_original_receipt_age_and_releases_owned_bytes() + { + var clock = new ManualTimeProvider(); + var hub = HubTest.Create(partitions: 1, bytes: 100_000, clock: clock); + var source = HubTest.Ticket("driver", "age"); + try + { + hub.TryBind(source).ShouldBeTrue(); + var received = clock.GetTimestamp(); + hub.TryReserveIngress(source, 288, out var reservation).ShouldBeTrue(); + using (reservation!) + { + var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 7), 0, null, null, HubTest.Serving, 1); + var transferred = false; + try + { + await WhilePartitionHeld(hub, source, () => + { + transferred = reservation!.TryCommit(sample, 1); + clock.Advance(TimeSpan.FromSeconds(5)); + }); + transferred.ShouldBeTrue(); + } + finally { if (!transferred) sample.Dispose(); } + } + hub.ProcessPending(); + using (var read = hub.Read(source)) + { + read.Readiness.ShouldBe(DataReadiness.Ready); + read.ReceivedTimestamp.ShouldBe(received); + clock.GetElapsedTime(read.ReceivedTimestamp).ShouldBe(TimeSpan.FromSeconds(5)); + } + } + finally { hub.Dispose(); } + hub.Resources.RetainedBytes.ShouldBe(0); + hub.CaptureAccounting().TrackedSources.ShouldBe(0); + } + + [Fact(Timeout = 30000)] + public void Late_commit_after_disposal_rejects_without_taking_payload_and_releases_charge_once() + { + var hub = HubTest.Create(partitions: 1, bytes: 100_000); + var source = HubTest.Ticket("driver", "dispose"); + hub.TryBind(source).ShouldBeTrue(); + hub.TryReserveIngress(source, 288, out var reservation).ShouldBeTrue(); + hub.Dispose(); + hub.Resources.RetainedBytes.ShouldBeGreaterThan(0, "the outstanding physical reservation remains charged"); + using (var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 9), 0, null, null, HubTest.Serving, 1)) + { + reservation!.TryCommit(sample, 1).ShouldBeFalse(); + sample.Value.GetScalar().ShouldBe(9, "a rejected commit leaves the borrowed sample with its caller"); + } + reservation!.Dispose(); + reservation.Dispose(); + hub.Resources.RetainedBytes.ShouldBe(0); + hub.CaptureAccounting().TrackedSources.ShouldBe(0); + } + + private static async Task WhilePartitionHeld(PartitionedSampleHub hub, SourceTicket source, Action action) + { + var ct = TestContext.Current.CancellationToken; + using var entered = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + var holder = Task.Run(() => hub.WithPartitionLockForTest(source.Key, () => + { + entered.Set(); + release.Wait(ct); + }), ct); + try + { + entered.Wait(TimeSpan.FromSeconds(5), ct).ShouldBeTrue(); + await Task.Run(action, ct).WaitAsync(TimeSpan.FromSeconds(5), ct); + } + finally + { + release.Set(); + await holder.WaitAsync(TimeSpan.FromSeconds(5), ct); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataIngressOverflowTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataIngressOverflowTests.cs index a2de6d06b..f1fd92a7d 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataIngressOverflowTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataIngressOverflowTests.cs @@ -201,7 +201,8 @@ public sealed class GrpcDataIngressOverflowTests entered.Wait(TimeSpan.FromSeconds(5), cancellationToken).ShouldBeTrue(); var producer = Task.Run(() => { - hub.TryReserveIngress(source, 288, out _).ShouldBeFalse(); + hub.TryReserveIngress(source, 288, out var reservation).ShouldBeTrue(); + reservation!.Dispose(); hub.TryRemove(source, 2).ShouldBeFalse(); hub.IsTicketCurrentNonBlocking(source).ShouldBeFalse(); }, cancellationToken); 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 16248c99b..5657a372d 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 @@ -129,22 +129,26 @@ internal sealed class LocalDataFixture : IDisposable internal LocalDataFixture(int additionalRawNodes = 0, Func? subscriptions = null, Func? targetSubscriptions = null, - bool advanceAuthority = false, string role = "Primary", long servingGeneration = 0, bool nestedCatalog = false, bool nestedUnsCatalog = false) + bool advanceAuthority = false, string role = "Primary", long servingGeneration = 0, bool nestedCatalog = false, bool nestedUnsCatalog = false, + Func? writes = null, bool denyReadExport = false, + ManualTimeProvider? clock = null, string servingNode = "node-a", string servingIncarnation = "serving-1") { - Serving = Serving with { Role = role, ServingGeneration = servingGeneration }; + if (clock is not null) Clock = clock; + Serving = Serving with { NodeId = servingNode, Incarnation = servingIncarnation, Role = role, ServingGeneration = servingGeneration }; + Ticket = new(SourceKey.ForDriver("cluster", "driver", "Plant/Driver/Device/Speed", servingNode, servingIncarnation), new(1, 1)); Hub = HubTest.Create(clock: Clock, bytes: 1_000_000); Hub.TryBind(Ticket).ShouldBeTrue(); var key = new ApiKey { ApiKeyId = "peer-key", Name = "peer-key", Principal = "peer", SecretHash = "hash", Enabled = true }; Authority.Apply("cluster", "first", [key], [new NodeAcl { NodeAclId = "grant", ClusterId = "cluster", Principal = "peer", ScopeKind = nestedUnsCatalog ? NodeAclScopeKind.Cluster : NodeAclScopeKind.RawFolder, - ScopeId = nestedUnsCatalog ? null : "folder", PermissionFlags = NodePermissions.ReadOnly }], + ScopeId = nestedUnsCatalog ? null : "folder", PermissionFlags = writes is null ? NodePermissions.ReadOnly : NodePermissions.Operator }], new Dictionary> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] }); if (advanceAuthority) { Authority.Apply("cluster", "second", [key], [new NodeAcl { NodeAclId = "grant", ClusterId = "cluster", Principal = "peer", ScopeKind = NodeAclScopeKind.RawFolder, - ScopeId = "folder", PermissionFlags = NodePermissions.ReadOnly }], + ScopeId = "folder", PermissionFlags = writes is null ? NodePermissions.ReadOnly : NodePermissions.Operator }], new Dictionary> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] }); Serving = Serving with { AuthorityEpoch = Authority.Current.GenerationId }; } @@ -153,6 +157,7 @@ internal sealed class LocalDataFixture : IDisposable Activation.Complete(epoch, true); Context = new("peer", key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(key), Clock.GetUtcNow().AddMinutes(10), Authority.Current.GenerationId); var operations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe; + if (denyReadExport) operations &= ~DataOperations.Read; var rootMetadata = new DataMetadata(Root, "Plant", "Folder", DataValueKind.Null, -1, [], false, operations, 1, null, null, false); var rawMetadata = new DataMetadata(Raw, "Speed", "Variable", DataValueKind.Int32, -1, [], true, operations, 1, Ticket.Key.StableSourceId, "rpm", false); var unsMetadata = rawMetadata with { View = Uns }; @@ -186,11 +191,11 @@ internal sealed class LocalDataFixture : IDisposable var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1)); var capabilities = new DataCapabilitiesProvider("cluster", () => Serving, () => Catalog.IsActive, limits); Services = new LocalDataServices(() => Catalog, Hub, new DataOperationPolicy(Authority, - new TriePermissionEvaluator(Authority.Tries, Clock), Clock), capabilities, Clock, subscriptions: subscriptions, + new TriePermissionEvaluator(Authority.Tries, Clock), Clock), capabilities, Clock, writes: writes, subscriptions: subscriptions, targetSubscriptions: targetSubscriptions); } - internal IDataConnection Connection() => Services.Create(Context, new(DataTargetMode.Node, "cluster", "node-a")); + internal IDataConnection Connection() => Services.Create(Context, new(DataTargetMode.Node, "cluster", Serving.NodeId)); internal void Publish(int value, bool beforeActivation = false) { using var owned = DataValue.FromScalar(DataValueKind.Int32, value); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataLeaseClientTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataLeaseClientTests.cs new file mode 100644 index 000000000..b81278fac --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataLeaseClientTests.cs @@ -0,0 +1,120 @@ +using System.Buffers.Binary; +using System.Net; +using Google.Protobuf; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Phase", "P11")] +public sealed class GrpcDataMetadataLeaseClientTests +{ + private static readonly ServingIdentity Serving = new("node", "boot", "Primary", 1, 1, 1); + private static readonly DataView View = new(new("cluster", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x"); + private static readonly DataLimits Limits = new(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)); + private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 1, 65536); + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Metadata_lease_requires_capability_and_is_anchored_before_transport_delay(bool negotiated) + { + var ct = TestContext.Current.CancellationToken; + var clock = new ManualTimeProvider(); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + var handler = new Handler(clock, negotiated, new(1, 1, TimeSpan.FromSeconds(5))); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "cluster", "node"), + [new Uri("https://test.invalid")], new Security(handler), + manager.Acquire("link"), 65536, 1, clock); + var started = clock.GetTimestamp(); + var item = (await connection.GetMetadataAsync(new([View], Budget), ct)).ShouldHaveSingleItem(); + item.Status.ShouldBe(DataItemStatus.Good); + handler.OfferedMinor.ShouldBe(5); + if (!negotiated) + { + item.Lease.ShouldBeNull(); item.LeaseRequestStartedTimestamp.ShouldBeNull(); return; + } + item.Lease.ShouldNotBeNull(); item.LeaseRequestStartedTimestamp.ShouldBe(started); + clock.GetElapsedTime(item.LeaseRequestStartedTimestamp!.Value, clock.GetTimestamp()).ShouldBe(TimeSpan.FromSeconds(2)); + var lease = new MetadataAuthorityLease(Serving, item.Lease!, item.LeaseRequestStartedTimestamp.Value, + TimeSpan.FromSeconds(5), TimeSpan.Zero, clock); + lease.IsValid.ShouldBeTrue(); + clock.Advance(TimeSpan.FromSeconds(3)); + lease.IsValid.ShouldBeFalse("response delay must not extend metadata authority"); + } + + [Theory] + [InlineData(2, 1, 5)] + [InlineData(1, 2, 5)] + [InlineData(1, 1, 6)] + public async Task Metadata_lease_rejects_unexpected_epochs_or_excess_duration(long catalog, long authority, int seconds) + { + var ct = TestContext.Current.CancellationToken; + var clock = new ManualTimeProvider(); + 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, "cluster", "node"), + [new Uri("https://test.invalid")], new Security(new Handler(clock, true, new(catalog, authority, TimeSpan.FromSeconds(seconds)))), + manager.Acquire("link"), 65536, 1, clock); + await Should.ThrowAsync(() => connection.GetMetadataAsync(new([View], Budget), ct)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Metadata_lease_is_not_attached_to_a_different_view_with_the_same_address(bool wrongRealm) + { + var ct = TestContext.Current.CancellationToken; + var clock = new ManualTimeProvider(); + var other = wrongRealm ? View with { Realm = DataRealm.Uns } : View with { Subject = "other-subject" }; + 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, "cluster", "node"), + [new Uri("https://test.invalid")], new Security(new Handler(clock, true, new(1, 1, TimeSpan.FromSeconds(5)), other)), + manager.Acquire("link"), 65536, 1, clock); + var item = (await connection.GetMetadataAsync(new([View], Budget), ct)).ShouldHaveSingleItem(); + item.Lease.ShouldBeNull(); item.LeaseRequestStartedTimestamp.ShouldBeNull(); + } + + private sealed class Security(Handler handler) : IDataConnectionSecurityProvider + { + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string id, Uri endpoint, CancellationToken ct) => + ValueTask.FromResult(new("v1", "ca", "key", () => handler)); + } + private sealed class Handler(ManualTimeProvider clock, bool negotiated, MetadataLease lease, DataView? responseView = null) : HttpMessageHandler + { + internal int OfferedMinor; + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + IMessage message; + if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal)) + { + var requestBytes = await request.Content!.ReadAsByteArrayAsync(ct); + OfferedMinor = W.CapabilitiesRequest.Parser.ParseFrom(requestBytes.AsSpan(5).ToArray()).ProtocolMinor; + message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 4, Serving, DataReadiness.Ready, + DataOperations.Metadata, new HashSet { DataValueKind.Int32 }, Limits, false, 0, "cluster", + ResponseServingIdentity: true, MetadataItemLeases: negotiated)); + } + else + { + clock.Advance(TimeSpan.FromSeconds(2)); + var metadata = new DataMetadata(responseView ?? View, "x", "Variable", DataValueKind.Int32, -1, [], false, + DataOperations.Metadata | DataOperations.Subscribe, 1, null, null, false); + var response = DataProtoMapper.EncodeMetadataResponse([new("0", DataItemStatus.Good, metadata, null, lease)]); + response.Serving = DataProtoMapper.EncodeServing(Serving); message = response; + } + var payload = message.ToByteArray(); var bytes = new byte[payload.Length + 5]; + BinaryPrimitives.WriteInt32BigEndian(bytes.AsSpan(1, 4), payload.Length); payload.CopyTo(bytes, 5); + var result = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent(bytes) }; + result.Content.Headers.ContentType = new("application/grpc"); result.TrailingHeaders.Add("grpc-status", "0"); + return result; + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataLeaseIssuanceTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataLeaseIssuanceTests.cs new file mode 100644 index 000000000..456912e54 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataLeaseIssuanceTests.cs @@ -0,0 +1,47 @@ +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", "P11")] +public sealed class GrpcDataMetadataLeaseIssuanceTests +{ + [Fact] + public async Task Metadata_lease_is_per_item_and_capped_by_target_credential() + { + using var fixture = new LocalDataFixture(servingGeneration: 1); + var ct = TestContext.Current.CancellationToken; + 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 capabilities = await connection.GetCapabilitiesAsync(LocalDataFixture.Budget, ct); + capabilities.MetadataItemLeases.ShouldBeTrue(); + var started = fixture.Clock.GetTimestamp(); + var results = await connection.GetMetadataAsync(new([fixture.Raw, fixture.Uns], LocalDataFixture.Budget), ct); + results[0].Status.ShouldBe(DataItemStatus.Good); + results[0].Lease.ShouldNotBeNull().Duration.ShouldBeLessThanOrEqualTo(TimeSpan.FromSeconds(1)); + results[0].Lease!.CatalogEpoch.ShouldBe(fixture.Serving.CatalogEpoch); + results[0].Lease!.AuthorityEpoch.ShouldBe(fixture.Serving.AuthorityEpoch); + results[0].LeaseRequestStartedTimestamp.ShouldBe(started); + results[1].Status.ShouldNotBe(DataItemStatus.Good); + results[1].Lease.ShouldBeNull(); + results[1].LeaseRequestStartedTimestamp.ShouldBeNull(); + } + + [Fact] + public async Task Stale_authority_and_unready_role_never_issue_a_metadata_lease() + { + var ct = TestContext.Current.CancellationToken; + using var fixture = new LocalDataFixture(servingGeneration: 1); + var stale = fixture.Context with { AuthorityEpoch = fixture.Context.AuthorityEpoch + 1 }; + await using var connection = fixture.Services.Create(stale, new(DataTargetMode.Node, "cluster", "node-a")); + var results = await connection.GetMetadataAsync(new([fixture.Raw], LocalDataFixture.Budget), ct); + results.ShouldHaveSingleItem().Status.ShouldNotBe(DataItemStatus.Good); + results[0].Lease.ShouldBeNull(); + + using var secondary = new LocalDataFixture(role: "Secondary", servingGeneration: 1); + await using var secondaryConnection = secondary.Connection(); + await Should.ThrowAsync(() => secondaryConnection.GetMetadataAsync( + new([secondary.Raw], LocalDataFixture.Budget), ct)); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalCacheCapacityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalCacheCapacityTests.cs new file mode 100644 index 000000000..ad5fc6f8e --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalCacheCapacityTests.cs @@ -0,0 +1,217 @@ +using System.Collections; +using System.Reflection; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataMetadataRenewalCacheTests +{ + [Theory, Trait("Phase", "P11Renewal")] + [InlineData(false)] + [InlineData(true)] + public void Only_the_same_expired_overlap_can_add_a_recovery_pin_without_a_new_cache_entry(bool sweepExpired) + { + using var fixture = new RenewalCacheFixture(); + var predecessor = fixture.Install(); + fixture.Cache.TryPinProjected(DataRealm.Raw, predecessor.LocalIdentifier, out var oldPin).ShouldBeTrue(); + fixture.Clock.Advance(TimeSpan.FromSeconds(5)); + fixture.Cache.TryRenewOverlap(predecessor, fixture.Proof(), 1, out var successor).ShouldBeTrue(); + var current = successor.ShouldNotBeNull(); + fixture.Cache.TryPinProjected(DataRealm.Raw, current.LocalIdentifier, out var currentPin).ShouldBeTrue(); + try + { + fixture.Clock.Advance(TimeSpan.FromSeconds(16)); + predecessor.Lease.IsValid.ShouldBeFalse(); current.Lease.IsValid.ShouldBeFalse(); + if (sweepExpired) Sweep(fixture); + var before = RetainedBytes(fixture); + fixture.Cache.TryPinExpiredRecoveryPair(predecessor, current, out var recoveryPin).ShouldBeTrue(); + var ownedRecoveryPin = recoveryPin.ShouldNotBeNull(); + RetainedBytes(fixture).ShouldBe(before, "the recovery pin cannot admit another physical cache entry"); + fixture.Cache.IsUsableProof(predecessor).ShouldBeFalse(); fixture.Cache.IsUsableProof(current).ShouldBeFalse(); + ownedRecoveryPin.Dispose(); + RetainedBytes(fixture).ShouldBe(before); + } + finally { oldPin?.Dispose(); currentPin?.Dispose(); } + } + + [Theory, Trait("Phase", "P11Renewal")] + [InlineData("both_live")] + [InlineData("successor_live")] + [InlineData("route_dead")] + [InlineData("binding_dead")] + [InlineData("generation_dead")] + [InlineData("invalidated")] + [InlineData("unrelated")] + [InlineData("route_mismatch")] + [InlineData("binding_mismatch")] + [InlineData("target_mismatch")] + [InlineData("serving_mismatch")] + [InlineData("schema_mismatch")] + public void Invalid_recovery_pair_never_adds_a_pin_or_charge(string failure) + { + using var fixture = new RenewalCacheFixture(); + var predecessor = fixture.Install(); + fixture.Cache.TryPinProjected(DataRealm.Raw, predecessor.LocalIdentifier, out var oldPin).ShouldBeTrue(); + fixture.Clock.Advance(TimeSpan.FromSeconds(5)); + fixture.Cache.TryRenewOverlap(predecessor, fixture.Proof(), 1, out var successor).ShouldBeTrue(); + var current = successor.ShouldNotBeNull(); + fixture.Cache.TryPinProjected(DataRealm.Raw, current.LocalIdentifier, out var currentPin).ShouldBeTrue(); + try + { + var candidate = failure switch + { + "unrelated" => fixture.Proof(), + "route_mismatch" => fixture.Proof("route"), + "binding_mismatch" => fixture.Proof("binding"), + "target_mismatch" => fixture.Proof("target"), + "serving_mismatch" => fixture.Proof("role"), + "schema_mismatch" => current with { Metadata = current.Metadata with { BrowseName = "different" } }, + _ => current + }; + if (failure == "successor_live") fixture.Clock.Advance(TimeSpan.FromSeconds(10)); + else if (failure != "both_live") fixture.Clock.Advance(TimeSpan.FromSeconds(16)); + switch (failure) + { + case "route_dead": fixture.RouteCurrent = false; break; + case "binding_dead": fixture.BindingCurrent = false; break; + case "generation_dead": fixture.Cache.ForgetMapping("mapping"); break; + case "invalidated": fixture.Invalidate(predecessor); break; + } + var before = RetainedBytes(fixture); + fixture.Cache.TryPinExpiredRecoveryPair(predecessor, candidate, out var pin).ShouldBeFalse(); + pin.ShouldBeNull(); + RetainedBytes(fixture).ShouldBe(before, "a rejected pairing cannot add a cache charge"); + } + finally { oldPin?.Dispose(); currentPin?.Dispose(); } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Browse_refuses_cross_serving_replacement_of_a_healthy_or_different_placement(bool expiredWithDifferentPermissions) + { + using var fixture = new RenewalCacheFixture(clusterTarget: true); + var original = fixture.Install(); + if (expiredWithDifferentPermissions) fixture.Clock.Advance(TimeSpan.FromSeconds(16)); + var incoming = fixture.Proof(expiredWithDifferentPermissions ? "acl" : null, original.Lease.Serving with + { + NodeId = "node-b", Incarnation = "serving-2", ServingGeneration = 2 + }); + var before = fixture.Cache.CaptureRetainedDiagnostics(DataRealm.Raw, original.LocalIdentifier); + before.Retired.ShouldBeFalse(); + before.RemoteLeaseValid.ShouldBe(!expiredWithDifferentPermissions); + var beforeBytes = RetainedBytes(fixture); + var commits = 0; + (bool Success, string? Cursor) Commit() { commits++; return (true, null); } + + // With one allowed entry, the expired case would fit if admission + // first swept that proof and then compared only the surviving entries. + fixture.TryPublishPage(incoming, Commit, out var committed, maximumMappingNodes: 1).ShouldBeFalse(); + committed.ShouldBeNull(); + commits.ShouldBe(0); + fixture.Cache.CaptureRetainedDiagnostics(DataRealm.Raw, original.LocalIdentifier).ShouldBe(before); + RetainedBytes(fixture).ShouldBe(beforeBytes); + if (!expiredWithDifferentPermissions) + fixture.Cache.IsCurrentProof(original).ShouldBeTrue(); + } + + [Theory] + [InlineData(2)] + [InlineData(3)] + public void Browse_replaces_an_expired_identical_placement_but_refuses_a_third_charged_serving(int maximumMappingNodes) + { + using var fixture = new RenewalCacheFixture(clusterTarget: true); + var predecessor = fixture.Install(); + var identifier = predecessor.LocalIdentifier; + fixture.Cache.TryPinProjected(DataRealm.Raw, identifier, out var predecessorPin).ShouldBeTrue(); + using var ownedPredecessor = predecessorPin.ShouldNotBeNull(); + fixture.Clock.Advance(TimeSpan.FromSeconds(16)); + var successor = fixture.Proof(alternateServing: predecessor.Lease.Serving with + { + NodeId = "node-b", Incarnation = "serving-2", ServingGeneration = 2 + }); + var commits = 0; + (bool Success, string? Cursor) Commit() { commits++; return (true, null); } + fixture.TryPublishPage(successor, Commit, out var accepted).ShouldBeTrue(); + var current = accepted.ShouldNotBeNull().Items.ShouldHaveSingleItem(); + commits.ShouldBe(1); + fixture.Cache.IsCurrentProof(current).ShouldBeTrue(); + fixture.Cache.IsUsableProof(predecessor).ShouldBeFalse(); + fixture.Cache.TryPinProjected(DataRealm.Raw, identifier, out var currentPin).ShouldBeTrue(); + using var ownedCurrent = currentPin.ShouldNotBeNull(); + fixture.Clock.Advance(TimeSpan.FromSeconds(16)); + + const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + var cacheType = fixture.Cache.GetType(); + var indexed = (IDictionary)cacheType.GetField("_nodes", flags)!.GetValue(fixture.Cache)!; + var retired = (IDictionary)cacheType.GetField("_retiredByProof", flags)!.GetValue(fixture.Cache)!; + var mappingCounts = (IDictionary)cacheType.GetField("_mappingNodeCounts", flags)!.GetValue(fixture.Cache)!; + var nodeKey = (DataRealm.Raw, identifier); + var currentEntry = indexed[nodeKey].ShouldNotBeNull(); + var predecessorEntry = retired[predecessor].ShouldNotBeNull(); + var pins = currentEntry.GetType().GetField("Pins", flags)!; + pins.GetValue(currentEntry).ShouldBe(1); + pins.GetValue(predecessorEntry).ShouldBe(1); + retired.Count.ShouldBe(1); + mappingCounts["mapping"].ShouldBe(2); + var beforeBytes = RetainedBytes(fixture); + var incoming = fixture.Proof(alternateServing: current.Lease.Serving with + { + NodeId = "node-c", Incarnation = "serving-3", ServingGeneration = 3 + }); + + fixture.TryPublishPage(incoming, Commit, out var rejected, maximumMappingNodes).ShouldBeFalse(); + rejected.ShouldBeNull(); + commits.ShouldBe(1); + indexed[nodeKey].ShouldBeSameAs(currentEntry); + retired[predecessor].ShouldBeSameAs(predecessorEntry); + pins.GetValue(currentEntry).ShouldBe(1); + pins.GetValue(predecessorEntry).ShouldBe(1); + retired.Count.ShouldBe(1); + mappingCounts["mapping"].ShouldBe(2); + RetainedBytes(fixture).ShouldBe(beforeBytes); + } + + private static long RetainedBytes(RenewalCacheFixture fixture) => + (long)fixture.Cache.GetType().GetField("_retainedBytes", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(fixture.Cache)!; + private static void Sweep(RenewalCacheFixture fixture) + { + const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + var gate = fixture.Cache.GetType().GetField("_sync", flags)!.GetValue(fixture.Cache)!; + lock (gate) fixture.Cache.GetType().GetMethod("ReclaimExpired", flags)!.Invoke(fixture.Cache, null); + } + + [Fact, Trait("Phase", "P11Renewal")] + public void Two_pinned_retired_proofs_cannot_admit_a_third_physical_entry() + { + using var fixture = new RenewalCacheFixture(); + var predecessor = fixture.Install(); + fixture.Cache.TryPinProjected(DataRealm.Raw, predecessor.LocalIdentifier, out var oldPin).ShouldBeTrue(); + fixture.Clock.Advance(TimeSpan.FromSeconds(5)); + fixture.Cache.TryRenewOverlap(predecessor, fixture.Proof(), 1, out var successor).ShouldBeTrue(); + var current = successor.ShouldNotBeNull(); + fixture.Cache.TryPinProjected(DataRealm.Raw, current.LocalIdentifier, out var currentPin).ShouldBeTrue(); + try + { + fixture.Clock.Advance(TimeSpan.FromSeconds(16)); + predecessor.Lease.IsValid.ShouldBeFalse(); current.Lease.IsValid.ShouldBeFalse(); + const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + var gate = fixture.Cache.GetType().GetField("_sync", flags)!.GetValue(fixture.Cache)!; + lock (gate) + { + fixture.Cache.GetType().GetMethod("ReclaimExpired", flags)!.Invoke(fixture.Cache, null); + var retired = (IDictionary)fixture.Cache.GetType().GetField("_retiredPerNode", flags)!.GetValue(fixture.Cache)!; + retired.Values.Cast().ShouldHaveSingleItem().ShouldBe(2); + } + fixture.Cache.TryRenewExact(current, fixture.Proof(), 2, out _).ShouldBeFalse( + "two separately pinned physical predecessors exhaust the per-node ownership limit even after the live entry was swept"); + oldPin!.Dispose(); oldPin = null; + fixture.Cache.TryRenewExact(current, fixture.Proof(), 2, out var recovered).ShouldBeTrue( + "after one owner releases its own pin, one predecessor and its replacement fit the bound"); + recovered.ShouldNotBeNull(); + } + finally { oldPin?.Dispose(); currentPin?.Dispose(); } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalCacheTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalCacheTests.cs new file mode 100644 index 000000000..c14deae2d --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalCacheTests.cs @@ -0,0 +1,111 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Phase", "P11Renewal")] +public sealed partial class GrpcDataMetadataRenewalCacheTests +{ + [Fact] + public void Overlap_is_one_charged_predecessor_and_never_extends_its_original_lease() + { + using var fixture = new RenewalCacheFixture(); + var initial = fixture.Install(); + fixture.Cache.TryPinProjected(DataRealm.Raw, initial.LocalIdentifier, out var oldPin).ShouldBeTrue(); + fixture.Clock.Advance(TimeSpan.FromSeconds(5)); + fixture.Cache.TryRenewOverlap(initial, fixture.Proof(), 1, out var successor).ShouldBeTrue(); + successor.ShouldNotBeNull(); + fixture.Cache.IsUsableProof(initial).ShouldBeTrue(); + fixture.Cache.IsUsableProof(successor).ShouldBeTrue(); + fixture.Cache.TryPinProjected(DataRealm.Raw, initial.LocalIdentifier, out var currentPin).ShouldBeTrue(); + fixture.Cache.TryRenewOverlap(successor, fixture.Proof(), 1, out _).ShouldBeFalse("a second predecessor cannot be retained"); + fixture.Clock.Advance(TimeSpan.FromSeconds(10)); + fixture.Cache.IsUsableProof(initial).ShouldBeFalse(); + fixture.Cache.IsUsableProof(successor).ShouldBeTrue(); + oldPin!.Dispose(); + fixture.Clock.Advance(TimeSpan.FromSeconds(1)); + fixture.Cache.TryRenewOverlap(successor, fixture.Proof(), 1, out var later).ShouldBeTrue(); + fixture.Cache.IsUsableProof(successor).ShouldBeTrue(); + fixture.Cache.IsUsableProof(initial).ShouldBeFalse("later authority must never revive an expired predecessor"); + currentPin!.Dispose(); + fixture.Cache.IsUsableProof(successor).ShouldBeFalse("last predecessor pin release detaches the overlap"); + fixture.Cache.IsUsableProof(later!).ShouldBeTrue(); + } + + [Theory] + [InlineData("acl")] + [InlineData("route")] + [InlineData("binding")] + [InlineData("target")] + [InlineData("role")] + public void Changed_authority_or_provenance_cannot_bridge_existing_evidence(string change) + { + using var fixture = new RenewalCacheFixture(); + var original = fixture.Install(); + fixture.Cache.TryPinProjected(DataRealm.Raw, original.LocalIdentifier, out var pin).ShouldBeTrue(); + try + { + fixture.Cache.TryRenewOverlap(original, fixture.Proof(change), 1, out _).ShouldBeFalse(); + fixture.Cache.IsUsableProof(original).ShouldBeTrue(); + } + finally { pin!.Dispose(); } + } + + private sealed class RenewalCacheFixture : IDisposable + { + private readonly LocalDataFixture _local = new(servingGeneration: 1); + private readonly IDataMappedCatalogAuthority _authority; + private readonly object _route = new(), _binding = new(); + private readonly Dictionary _remoteLeases = new(); + internal bool RouteCurrent = true, BindingCurrent = true; + private readonly DataTarget _target; + private readonly ProjectedBrowseRequest _request; + internal ProjectedCatalogCache Cache { get; } + internal ManualTimeProvider Clock => _local.Clock; + internal RenewalCacheFixture(bool clusterTarget = false) + { + _target = clusterTarget ? new(DataTargetMode.Cluster, "origin", null) : new(DataTargetMode.Node, "cluster", "node-a"); + var policy = new DataOperationPolicy(_local.Authority, new TriePermissionEvaluator(_local.Authority.Tries, Clock), Clock); + Cache = new(2, 3, Clock, policy); + _authority = _local.Activation.CaptureAuthority(); + var view = new DataView(new DataAddress("origin", "urn:raw", "string", "plant"), DataRealm.Raw, "mapping", 1, "local/anchor"); + var caller = new DataCallerIdentity(_local.Context.PrincipalId, _local.Context.ApiKeyId, _local.Context.CredentialVersion, _local.Context.CredentialExpiresUtc); + _request = new("mapping", view, null, null, caller, new(TimeSpan.FromSeconds(3), 20, 10000), Clock.GetTimestamp()); + Cache.CaptureGeneration("mapping"); + } + internal ProjectedNodeProof Proof(string? change = null, ServingIdentity? alternateServing = null) + { + var serving = alternateServing ?? (change == "role" ? _local.Serving with { Role = "Secondary" } : _local.Serving); + var remote = new MetadataAuthorityLease(serving, new(1, 1, TimeSpan.FromSeconds(15)), Clock.GetTimestamp(), TimeSpan.FromSeconds(15), TimeSpan.Zero, Clock); + var lease = new BoundProjectionLease(remote, CancellationToken.None, _authority, Cache, "mapping", 1, () => BindingCurrent, + () => RouteCurrent, change == "route" ? new object() : _route, + change == "target" ? _target with { ExpectedNodeId = "node-b" } : _target, change == "binding" ? new object() : _binding); + _remoteLeases.Add(lease, remote); + var operations = change == "acl" ? DataOperations.Browse | DataOperations.Read : DataOperations.Browse; + var view = _request.Parent; + var subject = new MappedNamespaceSubject(view, new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant"] }, ["folder"], serving, operations); + var resolver = new MappedSubjectResolver([subject], serving.CatalogEpoch, _authority); + var metadata = new DataMetadata(view, "branch", "Folder", DataValueKind.Null, -1, [], false, operations, 1, null, null, false, Serving: serving); + var origin = metadata with { View = view with { MappingId = null, MappingRevision = 0, Subject = "origin/plant" } }; + return new(ProjectedDataIds.Identifier("mapping", view.Address), metadata, subject, resolver, lease, 1, origin, TimeSpan.FromSeconds(30)); + } + internal void Invalidate(ProjectedNodeProof proof) => _remoteLeases[proof.Lease].Invalidate(); + internal bool TryPublishPage(ProjectedNodeProof proof, Func<(bool Success, string? Cursor)>? commit, + out ProjectedParentSnapshot? committed, int maximumMappingNodes = int.MaxValue) => + Cache.TryPublish(_request with { RequestStartedTimestamp = Clock.GetTimestamp() }, + new(ProjectionPageStatus.Ready, [proof], true, null, proof.Generation, proof.Lease, _authority, proof), + commit, out committed, maximumMappingNodes); + internal ProjectedNodeProof Install() + { + var proof = Proof(); + TryPublishPage(proof, null, out _).ShouldBeTrue(); + Cache.TryResolveProjected(DataRealm.Raw, proof.LocalIdentifier, out var installed).ShouldBeTrue(); + return installed!; + } + public void Dispose() => _local.Dispose(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalContinuityWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalContinuityWireTests.cs new file mode 100644 index 000000000..dcbcce8e6 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalContinuityWireTests.cs @@ -0,0 +1,593 @@ +using System.Threading.Channels; +using System.Reflection; +using System.Runtime.CompilerServices; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000), Trait("Phase", "P11Renewal")] + public async Task Two_sdk_cadences_renew_before_expiry_without_reviving_old_notification_evidence() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + var connections = new RenewalConnections(origin); + await WithComposedServer(origin, origin.Raw, async (session, sink, resolver, _, access, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var identifier = ProjectedDataIds.Identifier("map", origin.Raw.Address); + resolver.TryResolveProjected(DataRealm.Raw, identifier, out var initialProof).ShouldBeTrue(); + var initial = initialProof.ShouldNotBeNull(); + var initialLease = initial.Lease.ShouldBeOfType(); + var slow = (await client.CreateSubscriptionAsync(new RequestHeader(), 200, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, slow, anchor, 1, 200, ct); + var slowStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct); + var notification = await PublishComposedNotification(client, 1, ct); + notification.Value.StatusCode.ShouldBe(StatusCodes.Good); + var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, fast, anchor, 2, 50, ct); + var fastStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + fastStream.Interval.ShouldNotBe(slowStream.Interval); + (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); + while (connections.MetadataRequests.Reader.TryRead(out _)) { } + while (published.Reader.TryRead(out _)) { } + using var simultaneousSuccessors = new Barrier(2); + access.BeforeSuccessorAdoptionForTests = () => + { + if (!simultaneousSuccessors.SignalAndWait(TimeSpan.FromSeconds(5))) + throw new TimeoutException("Both cadence successors must prepare before either adopts."); + }; + + // The 15-second lease must be renewed and a successor baseline accepted + // while its predecessor still has authority. Metadata alone is not data. + origin.Clock.Advance(TimeSpan.FromSeconds(9)); + await connections.MetadataRequests.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct); + var freshTask = NextPublished(published.Reader, + x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct); + for (var i = 0; i < 8 && !freshTask.IsCompleted; i++) + { + origin.Clock.Advance(TimeSpan.FromMilliseconds(500)); + await Task.Delay(100, ct); + } + var fresh = await freshTask; + var otherFresh = await NextPublished(published.Reader, + x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct); + access.BeforeSuccessorAdoptionForTests = null; + otherFresh.SourceProof.ShouldNotBeSameAs(fresh.SourceProof, "each cadence must establish its own successor coverage"); + original.SourceProof.IsValid.ShouldBeTrue(); + fresh.SourceProof.IsValid.ShouldBeTrue(); + otherFresh.SourceProof.IsValid.ShouldBeTrue(); + fresh.SourceVersion.ShouldBe(original.SourceVersion, "a fresh baseline may report an unchanged source version"); + resolver.TryResolveProjected(DataRealm.Raw, identifier, out var renewedProof).ShouldBeTrue(); + var renewed = renewedProof.ShouldNotBeNull(); + renewed.ShouldNotBeSameAs(initial); + var renewedLease = renewed.Lease.ShouldBeOfType(); + renewedLease.Serving.ShouldBe(initialLease.Serving); + initialLease.IsValid.ShouldBeTrue(); + var crossExpiry = initialLease.Remaining + TimeSpan.FromMilliseconds(250); + (renewedLease.Remaining - crossExpiry).ShouldBeGreaterThan(renewedLease.UsableDuration / 2, + "the ordinary samples must follow predecessor expiry before the successor is due for renewal"); + origin.Clock.Advance(crossExpiry); + initialLease.IsValid.ShouldBeFalse(); + original.SourceProof.IsValid.ShouldBeFalse(); + fresh.SourceProof.IsValid.ShouldBeTrue(); + otherFresh.SourceProof.IsValid.ShouldBeTrue(); + + var streamBefore = ProjectedStreamDiagnostics.Capture(); + var deliveryBefore = ProjectedDeliveryDiagnostics.Capture(); + ProjectedValueUpdate? slowUpdate = null, fastUpdate = null; + try + { + slowStream.EmitValue(2, 8, origin.Clock.GetUtcNow(), TimeSpan.Zero); + slowUpdate = await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 8), ct); + slowUpdate.SourceProof.IsValid.ShouldBeTrue(); + slowUpdate.SourceProof.IsSourceValid.ShouldBeTrue(); + var slowValue = await PublishComposedValue(client, 1, ct); + slowValue.StatusCode.ShouldBe(StatusCodes.Good); + slowValue.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8); + fastStream.EmitValue(3, 9, origin.Clock.GetUtcNow(), TimeSpan.Zero); + // NextPublished is signaled only after the SDK sink accepts this + // actual sample; it is not merely publisher queue admission. + fastUpdate = await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 9), ct); + fastUpdate.SourceProof.IsValid.ShouldBeTrue(); + fastUpdate.SourceProof.IsSourceValid.ShouldBeTrue(); + var fastValue = await PublishComposedValue(client, 2, ct); + fastValue.StatusCode.ShouldBe(StatusCodes.Good); + fastValue.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(9); + } + catch (Exception error) when (error is not OutOfMemoryException) + { + throw new InvalidOperationException(DescribeRenewalDelivery(access, sink, anchor, original, fresh, otherFresh, + slowUpdate, fastUpdate, slowStream, fastStream, streamBefore, deliveryBefore), error); + } + // An expired Republish can request another baseline. Check its denial + // after receiving the ordinary samples from both renewed registrations. + var replay = await client.RepublishAsync(new RequestHeader(), slow, notification.Sequence, ct); + StatusCode.IsGood(ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode).ShouldBeFalse(); + subscriptions.Opens.ShouldBe(2, "normal metadata renewal retains both physical streams"); + }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections); + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Renewal")] + public async Task Cache_commit_followed_by_sdk_rejection_retries_with_the_actual_committed_proof() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + var connections = new RenewalConnections(origin); + var rejected = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscription, anchor, 1, 100, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + origin.Clock.Advance(TimeSpan.FromSeconds(9)); + await rejected.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + original.SourceProof.IsValid.ShouldBeTrue("the failed SDK transaction must preserve only the live predecessor"); + for (var i = 0; i < 3; i++) { origin.Clock.Advance(TimeSpan.FromSeconds(1)); await Task.Delay(50, ct); } + var successor = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct); + origin.Clock.Advance(TimeSpan.FromSeconds(4)); + original.SourceProof.IsValid.ShouldBeFalse(); + successor.SourceProof.IsValid.ShouldBeTrue("the adopted SDK guard must refer to the committed successor lease"); + }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections, + renewalSinkFactory: inner => new RejectFirstCommittedRenewal(inner, rejected)); + } + + private sealed class RejectFirstCommittedRenewal(IProjectedNamespacePageSink inner, TaskCompletionSource rejected) : IProjectedNamespacePageSink + { + private int _reject = 1; + public bool TryApply(NodeId parent, IReadOnlyList nodes, Func commit) => inner.TryApply(parent, nodes, commit); + public bool TryRemove(NodeId node, ProjectedVariableDefinition expected) => inner.TryRemove(node, expected); + public bool TryApplyRootLeaf(NodeId node, ProjectedVariableDefinition definition, Func commit) => inner.TryApplyRootLeaf(node, definition, commit); + public bool TryRenewExact(NodeId node, ProjectedVariableDefinition expected, ProjectedVariableDefinition replacement, Func commit) + { + var result = inner.TryRenewExact(node, expected, replacement, () => + { + if (!commit()) return false; + return Interlocked.Exchange(ref _reject, 0) == 0; + }); + if (!result && Volatile.Read(ref _reject) == 0) rejected.TrySetResult(); + return result; + } + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Renewal")] + public async Task Unknown_route_provenance_does_not_create_a_proactive_overlap() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + var connections = new RenewalConnections(origin, identified: false); + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscription, anchor, 1, 100, ct); + var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct); + while (connections.MetadataRequests.Reader.TryRead(out _)) { } + origin.Clock.Advance(TimeSpan.FromSeconds(9)); + stream.EmitValue(2, 8, origin.Clock.GetUtcNow(), TimeSpan.Zero); + var current = await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 8), ct); + current.SourceProof.IsValid.ShouldBeTrue(); + original.SourceProof.IsValid.ShouldBeTrue(); + connections.MetadataRequests.Reader.TryRead(out _).ShouldBeFalse("an unknown route identity cannot authorize predecessor overlap"); + }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections); + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Renewal")] + public async Task Missing_successor_snapshot_cannot_be_replaced_by_a_later_ordinary_delta() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + var connections = new RenewalConnections(origin) { SuppressFirstRenewalSnapshot = true }; + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var slow = (await client.CreateSubscriptionAsync(new RequestHeader(), 200, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, slow, anchor, 1, 200, ct); + var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, fast, anchor, 2, 50, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); + while (published.Reader.TryRead(out _)) { } + origin.Clock.Advance(TimeSpan.FromSeconds(9)); + var healthyTask = NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct); + for (var i = 0; i < 8 && (!connections.MissingRebindHeld.Task.IsCompleted || !healthyTask.IsCompleted); i++) + { + origin.Clock.Advance(TimeSpan.FromMilliseconds(500)); + await Task.Delay(100, ct); + } + await connections.MissingRebindHeld.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + var healthy = await healthyTask; + original.SourceProof.IsValid.ShouldBeTrue("both prerequisites must complete while predecessor authority is still live"); + healthy.SourceProof.IsValid.ShouldBeTrue(); + connections.ReleaseMissingRebind.TrySetResult(); + while (published.Reader.TryRead(out _)) { } + var firstRebind = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var secondRebind = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (ReferenceEquals(firstRebind, stream) || ReferenceEquals(secondRebind, stream)).ShouldBeTrue(); + var before = ProjectedStreamDiagnostics.Capture()["Value"]; + stream.EmitValue(2, 8, origin.Clock.GetUtcNow(), TimeSpan.Zero); + stream.EmitValue(3, 9, origin.Clock.GetUtcNow(), TimeSpan.Zero); + var closed = subscriptions.Closed.Reader.ReadAsync(ct).AsTask(); + var processed = Task.Run(() => SpinWait.SpinUntil(() => ProjectedStreamDiagnostics.Capture()["Value"] >= before + 2, + TimeSpan.FromSeconds(5)), ct); + var completed = await Task.WhenAny(closed, processed).WaitAsync(TimeSpan.FromSeconds(7), ct); + if (ReferenceEquals(completed, processed)) + { + (await processed).ShouldBeTrue(); + using var noPublication = new CancellationTokenSource(TimeSpan.FromSeconds(1)); + var available = false; + try { available = await published.Reader.WaitToReadAsync(noPublication.Token); } + catch (OperationCanceledException) when (noPublication.IsCancellationRequested) { } + available.ShouldBeFalse("ordinary deltas cannot establish successor coverage after an empty snapshot"); + } + else + healthy.SourceProof.IsValid.ShouldBeTrue("the independent healthy cadence must retain coverage"); + }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections); + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Renewal")] + public async Task Bad_source_quality_is_preserved_during_complete_metadata_handoff() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + var connections = new RenewalConnections(origin) { BadFirstRenewalSnapshot = true }; + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscription, anchor, 1, 100, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8; + origin.Clock.Advance(TimeSpan.FromSeconds(9)); + var next = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.SourceVersion == 2, ct); + next.SourceProof.IsValid.ShouldBeTrue(); + next.Snapshot.StatusCode.ShouldBe(StatusCodes.BadNoCommunication.Code); + var delivered = await PublishComposedValue(client, 1, ct); + delivered.StatusCode.ShouldBe(StatusCodes.BadNoCommunication); + subscriptions.Opens.ShouldBe(1, "an authenticated Bad source value is not a transport failure"); + origin.Clock.Advance(TimeSpan.FromSeconds(7)); + original.SourceProof.IsValid.ShouldBeFalse(); + next.SourceProof.IsValid.ShouldBeTrue(); + }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections); + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Renewal")] + public async Task Accepted_bad_complete_baselines_do_not_reset_reconnect_backoff() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + var connections = new RenewalConnections(origin) { BadEverySnapshot = true }; + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, access, _, anchor) => + { + var delays = Channel.CreateUnbounded(); + access.RetryJitterForTests = delay => { delays.Writer.TryWrite(delay); return TimeSpan.FromMilliseconds(1); }; + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscription, anchor, 1, 100, ct); + var first = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct)).Snapshot.StatusCode.ShouldBe(StatusCodes.BadNoCommunication.Code); + await first.DisposeAsync(); + (await delays.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBe(TimeSpan.FromMilliseconds(100)); + var second = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct)).Snapshot.StatusCode.ShouldBe(StatusCodes.BadNoCommunication.Code); + await second.DisposeAsync(); + (await delays.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBe(TimeSpan.FromMilliseconds(200), + "accepted source-quality Bad must not erase a failure streak"); + }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections); + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Renewal")] + public async Task Snapshot_request_during_held_renewal_remove_is_coalesced_without_a_second_remove() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + var connections = new RenewalConnections(origin) { HoldFirstRenewalRemoveAck = true }; + try + { + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, access, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscription, anchor, 1, 100, ct); + var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + origin.Clock.Advance(TimeSpan.FromSeconds(9)); + await connections.RenewalRemoveAckHeld.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + original.SourceProof.IsValid.ShouldBeTrue(); + const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; + var gate = typeof(ProjectedDataAccess).GetField("_sync", flags)!.GetValue(access)!; + IProjectedDemandLease demand; + lock (gate) demand = ((System.Collections.IEnumerable)typeof(ProjectedDataAccess).GetField("_demands", flags)! + .GetValue(access)!).Cast().OfType().Single(); + access.RequestFreshSnapshot(demand).ShouldBeTrue(); + // AddEvent follows RefreshEvent through the same cohort reader. Its + // actual upstream Add proves the refresh was processed, not just queued. + await AddComposedItem(client, subscription, anchor, 2, 100, ct); + var added = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + added.ShouldBeSameAs(stream); + stream.RemoveCommands.ShouldBe(1, "the in-flight renewal already provides the requested fresh baseline"); + connections.ReleaseRenewalRemoveAck.TrySetResult(); + var successor = await NextPublished(published.Reader, + update => update.IsCompleteSnapshot && update.ReceivedTimestamp > original.ReceivedTimestamp, ct); + successor.SourceProof.IsValid.ShouldBeTrue(); + var delivered = new HashSet(); + using var deliveryTimeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + deliveryTimeout.CancelAfter(TimeSpan.FromSeconds(10)); + while (delivered.Count < 2) + { + var response = await client.PublishAsync(new RequestHeader(), default, deliveryTimeout.Token); + foreach (var notification in ComposedChanges(response.NotificationMessage)) + { + if (notification.ClientHandle is not (1 or 2)) continue; + notification.Value.StatusCode.ShouldBe(StatusCodes.Good); + delivered.Add(notification.ClientHandle); + } + } + subscriptions.Opens.ShouldBe(1); + }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections); + } + finally { connections.ReleaseRenewalRemoveAck.TrySetResult(); } + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Renewal")] + public async Task Acknowledged_renewal_without_snapshot_end_expires_and_releases_its_old_attempt() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + var connections = new RenewalConnections(origin); + FakeSubscriptions.Stream? held = null; + try + { + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscription, anchor, 1, 100, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct); + subscriptions.HoldNextSnapshotEnd = true; + origin.Clock.Advance(TimeSpan.FromSeconds(9)); + held = await subscriptions.SnapshotEndHeld.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + original.SourceProof.IsValid.ShouldBeTrue(); + origin.Clock.Advance(TimeSpan.FromSeconds(7)); + original.SourceProof.IsValid.ShouldBeFalse(); + await subscriptions.Closed.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct); + }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections); + } + finally { held?.ReleaseSnapshotEnd(); } + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Renewal")] + public async Task Ignored_metadata_cancellation_keeps_physical_quota_until_the_rpc_actually_finishes() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + var connections = new RenewalConnections(origin); + try + { + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, access, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscription, anchor, 1, 100, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct); + connections.HoldMetadata = true; + origin.Clock.Advance(TimeSpan.FromSeconds(9)); + await connections.MetadataHeld.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + var count = typeof(ProjectedDataAccess).GetField("_unaryCount", BindingFlags.NonPublic | BindingFlags.Instance)!; + ((int)count.GetValue(access)!).ShouldBe(1); + origin.Clock.Advance(TimeSpan.FromSeconds(16)); + await client.DeleteSubscriptionsAsync(new RequestHeader(), [subscription], ct); + ((int)count.GetValue(access)!).ShouldBe(1, "timeout and disposed interest do not release an unfinished physical RPC"); + connections.ReleaseMetadata.TrySetResult(); + SpinWait.SpinUntil(() => (int)count.GetValue(access)! == 0, TimeSpan.FromSeconds(5)).ShouldBeTrue(); + }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections); + } + finally { connections.ReleaseMetadata.TrySetResult(); } + } + + private sealed class RenewalConnections(LocalDataFixture fixture, bool identified = true) : IGrpcDataAdapterConnectionSource + { + private readonly object _routeIdentity = new(); + internal readonly Channel MetadataRequests = Channel.CreateUnbounded(); + internal bool HoldMetadata; + internal bool SuppressFirstRenewalSnapshot; + internal bool BadFirstRenewalSnapshot, BadEverySnapshot; + internal bool HoldFirstRenewalRemoveAck; + private int _subscriptions; + internal readonly TaskCompletionSource MissingRebindHeld = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource ReleaseMissingRebind = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource RenewalRemoveAckHeld = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource ReleaseRenewalRemoveAck = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource MetadataHeld = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource ReleaseMetadata = new(TaskCreationOptions.RunContinuationsAsynchronously); + public ValueTask AcquireAsync(string id, CancellationToken ct) => + ValueTask.FromResult(id == "link" ? new Lease(new Connection(fixture.Connection(), this), identified ? _routeIdentity : null) : null); + private sealed class Lease(IDataConnection connection, object? routeIdentity) : IGrpcDataAdapterConnectionLease + { + public IDataConnection Connection => connection; + public CancellationToken CancellationToken => CancellationToken.None; + // This opt-in member binds every borrowed connection to this fixture's + // one stable route. It also compiles before the interface gains the seam. + public object? RouteIdentity => routeIdentity; + public ValueTask DisposeAsync() => connection.DisposeAsync(); + } + private sealed class Connection(IDataConnection inner, RenewalConnections owner) : IDataConnection + { + public DataTarget Target => inner.Target; + public TimeProvider Clock => inner.Clock; + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken ct) => inner.GetCapabilitiesAsync(budget, ct); + public Task BrowseAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest request, CancellationToken ct) => inner.BrowseAsync(request, ct); + public async Task>> GetMetadataAsync(MetadataRequest request, CancellationToken ct) + { + owner.MetadataRequests.Writer.TryWrite(true); + if (owner.HoldMetadata) + { + owner.MetadataHeld.TrySetResult(); + await owner.ReleaseMetadata.Task; + } + return await inner.GetMetadataAsync(request, ct); + } + public Task> ReadAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest request, CancellationToken ct) => inner.ReadAsync(request, ct); + public Task> WriteAsync(WriteBatch request, CancellationToken ct) => inner.WriteAsync(request, ct); + public async Task SubscribeAsync(CancellationToken ct) + { + var stream = await inner.SubscribeAsync(ct); + var number = Interlocked.Increment(ref owner._subscriptions); + if (owner.HoldFirstRenewalRemoveAck && number == 1) return new HeldRemovalAckStream(stream, owner); + if (owner.SuppressFirstRenewalSnapshot && number == 1) return new MissingSnapshotStream(stream, owner); + return owner.BadEverySnapshot || owner.BadFirstRenewalSnapshot && number == 1 + ? new QualitySnapshotStream(stream, owner.BadEverySnapshot) : stream; + } + public ValueTask DisposeAsync() => inner.DisposeAsync(); + } + private sealed class HeldRemovalAckStream(IDataSubscription inner, RenewalConnections owner) : IDataSubscription, IDataSubscriptionProvenance + { + private string? _heldCommand; + private int _held; + public ServingIdentity Serving => ((IDataSubscriptionProvenance)inner).Serving; + public Task SendAsync(DataSubscriptionCommand command, CancellationToken ct) + { + if (command is RemoveSubscriptionItems) Interlocked.CompareExchange(ref _heldCommand, command.CommandId, null); + return inner.SendAsync(command, ct); + } + public async IAsyncEnumerable ReadAllAsync([EnumeratorCancellation] CancellationToken ct) + { + await foreach (var frame in inner.ReadAllAsync(ct).WithCancellation(ct)) + { + if (frame is DataSubscriptionAck ack && ack.CommandId == Volatile.Read(ref _heldCommand) && + Interlocked.Exchange(ref _held, 1) == 0) + { + owner.RenewalRemoveAckHeld.TrySetResult(); + await owner.ReleaseRenewalRemoveAck.Task.WaitAsync(ct); + } + yield return frame; + } + } + public ValueTask DisposeAsync() => inner.DisposeAsync(); + } + private sealed class QualitySnapshotStream(IDataSubscription inner, bool everySnapshot) : IDataSubscription, IDataSubscriptionProvenance + { + private int _renewal; + public ServingIdentity Serving => ((IDataSubscriptionProvenance)inner).Serving; + public Task SendAsync(DataSubscriptionCommand command, CancellationToken ct) + { + if (command is AddSubscriptionItems) Interlocked.Exchange(ref _renewal, 1); + return inner.SendAsync(command, ct); + } + public async IAsyncEnumerable ReadAllAsync([EnumeratorCancellation] CancellationToken ct) + { + await foreach (var frame in inner.ReadAllAsync(ct).WithCancellation(ct)) + { + if (frame is DataSubscriptionValues { IsSnapshot: true } values && (everySnapshot || Volatile.Read(ref _renewal) != 0)) + { + var converted = values.Items.Select(item => + { + var sample = item.Sample; + var owned = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromScalar(sample.Value.Kind, sample.Value.GetScalar()); + return item with { Sample = new DataSample(owned, StatusCodes.BadNoCommunication.Code, + sample.SourceTimestampUtc, sample.ServerTimestampUtc, sample.Serving, sample.Version) }; + }).ToArray(); + var replacement = new DataSubscriptionValues(values.SubscriptionId, values.StreamEpoch, values.Sequence, true, converted); + values.Dispose(); + yield return replacement; + continue; + } + if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) Interlocked.Exchange(ref _renewal, 0); + yield return frame; + } + } + public ValueTask DisposeAsync() => inner.DisposeAsync(); + } + private sealed class MissingSnapshotStream(IDataSubscription inner, RenewalConnections owner) : IDataSubscription, IDataSubscriptionProvenance + { + private int _suppress; + public ServingIdentity Serving => ((IDataSubscriptionProvenance)inner).Serving; + public async Task SendAsync(DataSubscriptionCommand command, CancellationToken ct) + { + if (command is AddSubscriptionItems) + { + owner.MissingRebindHeld.TrySetResult(); + await owner.ReleaseMissingRebind.Task.WaitAsync(ct); + Interlocked.Exchange(ref _suppress, 1); + } + await inner.SendAsync(command, ct); + } + public async IAsyncEnumerable ReadAllAsync([EnumeratorCancellation] CancellationToken ct) + { + await foreach (var frame in inner.ReadAllAsync(ct).WithCancellation(ct)) + { + if (frame is DataSubscriptionValues { IsSnapshot: true } && Volatile.Read(ref _suppress) != 0) + { (frame as IDisposable)?.Dispose(); continue; } + if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) Interlocked.Exchange(ref _suppress, 0); + yield return frame; + } + } + public ValueTask DisposeAsync() => inner.DisposeAsync(); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalDeliveryDiagnosticsTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalDeliveryDiagnosticsTests.cs new file mode 100644 index 000000000..1044caf13 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalDeliveryDiagnosticsTests.cs @@ -0,0 +1,65 @@ +using System.Collections; +using System.Reflection; +using Opc.Ua; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + private static string DescribeRenewalDelivery(ProjectedDataAccess access, SdkAddressSpaceSink sink, NodeId anchor, + ProjectedValueUpdate original, ProjectedValueUpdate first, ProjectedValueUpdate second, ProjectedValueUpdate? slow, + ProjectedValueUpdate? fast, FakeSubscriptions.Stream slowStream, FakeSubscriptions.Stream fastStream, + IReadOnlyDictionary streamBefore, IReadOnlyDictionary deliveryBefore) + { + const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + static string Observe(Func observation) + { + try { return observation()?.ToString() ?? "null"; } + catch (Exception error) { return "error:" + error.GetType().Name; } + } + static string Proof(ProjectedValueUpdate? update) => update is null ? "missing" : + $"valid={Observe(() => update.SourceProof.IsValid)},source={Observe(() => update.SourceProof.IsSourceValid)},version={update.SourceVersion},received={update.ReceivedTimestamp}"; + static string Delta(IReadOnlyDictionary before, IReadOnlyDictionary after) => + string.Join(",", after.Where(pair => pair.Value != before.GetValueOrDefault(pair.Key)) + .Select(pair => $"{pair.Key}:{pair.Value - before.GetValueOrDefault(pair.Key)}")); + var proofStates = $"original({Proof(original)});first({Proof(first)});second({Proof(second)});slow({Proof(slow)});fast({Proof(fast)})"; + var demands = Observe(() => + { + var gate = typeof(ProjectedDataAccess).GetField("_sync", flags)!.GetValue(access)!; + object[] captured; + lock (gate) captured = ((IEnumerable)typeof(ProjectedDataAccess).GetField("_demands", flags)!.GetValue(access)!).Cast().ToArray(); + return string.Join(";", captured.OfType().Select(demand => + $"valid={Observe(() => demand.IsValid)},generation={demand.ProjectionGeneration},serving={demand.Serving.ServingGeneration}")); + }); + var definition = Observe(() => + { + var found = ((IProjectedNodeLookup)sink).TryResolve(anchor, out var current); + return found && current is not null ? $"authority={Observe(() => current.AuthorityIsCurrent())},lifetime={current.Lifetime.IsActive},generation={current.ProjectionGeneration}" : "missing"; + }); + var items = Observe(() => + { + var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!; + var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!; + var keys = (IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!; + return string.Join(";", keys.Cast().OfType() + .Where(item => item.ClientHandle is 1 or 2).Select(item => + { + var type = item.GetType(); + var binding = type.GetField("_binding", flags)?.GetValue(item); + var proof = binding?.GetType().GetProperty("Proof", flags)?.GetValue(binding) as IProjectedSamplePublicationProof; + var candidates = type.GetField("_candidates", flags)?.GetValue(item) as ICollection; + var demand = type.GetField("_demand", flags)?.GetValue(item) as IProjectedDemandLease; + return $"handle={item.ClientHandle},mode={item.MonitoringMode},current={Observe(() => type.GetProperty("IsCurrent", flags)?.GetValue(item))}," + + $"demand={Observe(() => demand?.IsValid)},bindingProof={Observe(() => proof?.IsValid)},bindingSource={Observe(() => proof?.IsSourceValid)}," + + $"candidates={candidates?.Count},needsSnapshot={Observe(() => type.GetField("_needsSnapshot", flags)?.GetValue(item))}"; + })); + }); + static string Stream(FakeSubscriptions.Stream stream) => + $"add={stream.AddCommands},remove={stream.RemoveCommands},handle={Observe(() => stream.GetType().GetField("_currentHandle", flags)?.GetValue(stream))}"; + return $"Renewal delivery diagnostics: {proofStates}; demands=[{demands}]; definition=[{definition}]; items=[{items}]; slowStream=[{Stream(slowStream)}]; fastStream=[{Stream(fastStream)}]; " + + $"streamDelta=[{Delta(streamBefore, ProjectedStreamDiagnostics.Capture())}]; deliveryDelta=[{Delta(deliveryBefore, ProjectedDeliveryDiagnostics.Capture())}]"; + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalPredecessorWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalPredecessorWireTests.cs new file mode 100644 index 000000000..3ce3f35c9 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalPredecessorWireTests.cs @@ -0,0 +1,140 @@ +using System.Collections; +using System.Reflection; +using System.Threading.Channels; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000), Trait("Phase", "P11Renewal")] + public async Task Live_predecessor_cadence_publishes_ordinary_delta_after_peer_adopts_next_authority() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + var started = origin.Clock.GetTimestamp(); + var published = Channel.CreateUnbounded(); + var connections = new RenewalConnections(origin); + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, access, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var slow = (await client.CreateSubscriptionAsync(new RequestHeader(), 200, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, slow, anchor, 1, 200, ct); + var slowStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + origin.Clock.Advance(TimeSpan.FromMilliseconds(125)); + var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, fast, anchor, 2, 50, ct); + var fastStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + fastStream.Interval.ShouldNotBe(slowStream.Interval); + (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); + while (published.Reader.TryRead(out _)) { } + + // Stagger timer phases so each cadence establishes P2 independently. + while (origin.Clock.GetElapsedTime(started, origin.Clock.GetTimestamp()) < TimeSpan.FromSeconds(7.5)) + { origin.Clock.Advance(TimeSpan.FromMilliseconds(125)); await Task.Delay(20, ct); } + var p2First = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > started, ct); + origin.Clock.Advance(TimeSpan.FromMilliseconds(125)); + var p2Fast = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > p2First.ReceivedTimestamp, ct); + p2Fast.SourceProof.IsValid.ShouldBeTrue(); + + // Hold only the fast cadence's next renewal tick. Its transport, demand, + // original P2 lease and value stream continue to run independently. + PauseFastRenewalTimer(origin.Clock); + while (published.Reader.TryRead(out _)) { } + var remaining = TimeSpan.FromSeconds(15) - origin.Clock.GetElapsedTime(started, origin.Clock.GetTimestamp()); + if (remaining > TimeSpan.Zero) origin.Clock.Advance(remaining); + p2First.SourceProof.IsValid.ShouldBeTrue(); // Also releases the expired P1 cache pin. + var p3Task = NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > p2Fast.ReceivedTimestamp, ct); + for (var i = 0; i < 4 && !p3Task.IsCompleted; i++) + { origin.Clock.Advance(TimeSpan.FromMilliseconds(250)); await Task.Delay(100, ct); } + var p3 = await p3Task; + p3.SourceProof.IsValid.ShouldBeTrue(); + var state = CapturePredecessorAuthority(access, sink); + state.SlowDemand.IsValid.ShouldBeTrue(); + state.FastDemand.IsValid.ShouldBeTrue(); + state.Current.ShouldBeSameAs(state.SlowProof); + state.Previous.ShouldBeSameAs(state.FastProof); + state.FastProof.Lease.IsValid.ShouldBeTrue(); + state.Current.Lease.IsValid.ShouldBeTrue(); + p2Fast.SourceProof.IsValid.ShouldBeTrue(); + p2Fast.SourceProof.IsSourceValid.ShouldBeTrue(); + + subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8; + var before = ProjectedStreamDiagnostics.Capture()["FreshAge"]; + fastStream.EmitValue(2, 8, origin.Clock.GetUtcNow(), TimeSpan.Zero); + SpinWait.SpinUntil(() => ProjectedStreamDiagnostics.Capture()["FreshAge"] > before, TimeSpan.FromSeconds(5)).ShouldBeTrue( + "the fast cadence's ordinary frame must reach Runtime admission"); + var delta = await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 8), ct); + delta.IsCompleteSnapshot.ShouldBeFalse(); + delta.SourceProof.ShouldBeSameAs(p2Fast.SourceProof); + delta.SourceProof.IsValid.ShouldBeTrue(); + delta.SourceVersion.ShouldBe(2); + subscriptions.Opens.ShouldBe(2); + + var originalP2Lease = state.FastProof.Lease; + var originalP3Lease = state.Current.Lease; + var untilP2Expired = TimeSpan.FromSeconds(23) - origin.Clock.GetElapsedTime(started, origin.Clock.GetTimestamp()); + if (untilP2Expired > TimeSpan.Zero) origin.Clock.Advance(untilP2Expired); + delta.OriginAgeBounds.Advance(origin.Clock.GetElapsedTime(delta.ReceivedTimestamp, origin.Clock.GetTimestamp())) + .IsFresh(TimeSpan.FromSeconds(30)).ShouldBeTrue("the sample must still be fresh when its original authority expires"); + originalP2Lease.IsValid.ShouldBeFalse(); + delta.SourceProof.IsValid.ShouldBeFalse("P2 evidence cannot borrow P3's longer authority lifetime"); + originalP3Lease.IsValid.ShouldBeTrue(); + p3.SourceProof.IsValid.ShouldBeTrue(); + }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections); + } + + private static void PauseFastRenewalTimer(ManualTimeProvider clock) + { + const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + var sync = typeof(ManualTimeProvider).GetField("_lock", flags)!.GetValue(clock)!; + lock (sync) + { + var timers = (IEnumerable)typeof(ManualTimeProvider).GetField("_timers", flags)!.GetValue(clock)!; + var fastDue = clock.GetUtcNow().AddMilliseconds(250); + var matches = timers.Cast().Where(timer => + Equals(timer.GetType().GetField("Period", flags)!.GetValue(timer), TimeSpan.FromMilliseconds(250)) && + Equals(timer.GetType().GetField("Due", flags)!.GetValue(timer), fastDue)).ToArray(); + matches.Length.ShouldBe(1, "the staggered fast renewal timer must be uniquely identifiable"); + ((ITimer)matches[0]).Dispose(); + } + } + + private static (ProjectedNodeProof Current, ProjectedNodeProof? Previous, ProjectedNodeProof SlowProof, + ProjectedNodeProof FastProof, IProjectedDemandLease SlowDemand, IProjectedDemandLease FastDemand) + CapturePredecessorAuthority(ProjectedDataAccess access, SdkAddressSpaceSink sink) + { + const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!; + var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!; + var keys = (IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!; + var items = keys.Cast().OfType().Where(item => item.ClientHandle is 1 or 2).ToArray(); + IProjectedDemandLease Demand(uint handle) => (IProjectedDemandLease)items.Single(item => item.ClientHandle == handle) + .GetType().GetField("_demand", flags)!.GetValue(items.Single(item => item.ClientHandle == handle))!; + ProjectedNodeProof Proof(IProjectedDemandLease demand) => (ProjectedNodeProof)demand.GetType().GetProperty("Proof", flags)!.GetValue(demand)!; + var slow = Demand(1); var fast = Demand(2); + var sync = typeof(ProjectedDataAccess).GetField("_sync", flags)!.GetValue(access)!; + object source; + lock (sync) source = ((IDictionary)typeof(ProjectedDataAccess).GetField("_sources", flags)!.GetValue(access)!).Values.Cast().Single(); + var sourceGate = source.GetType().GetField("Gate", flags)!.GetValue(source)!; + lock (sourceGate) + { + var current = (ProjectedNodeProof)source.GetType().GetField("_proof", flags)!.GetValue(source)!; + var previous = (ProjectedNodeProof?)source.GetType().GetField("_previousProof", flags)!.GetValue(source); + return (current, previous, Proof(slow), Proof(fast), slow, fast); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalPublisherTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalPublisherTests.cs new file mode 100644 index 000000000..b9bbee8e5 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalPublisherTests.cs @@ -0,0 +1,68 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Feature", "GrpcData")] +[Trait("Phase", "P11Renewal")] +public sealed class GrpcDataMetadataRenewalPublisherTests : RuntimeActorTestBase +{ + [Theory] + [InlineData(true, false)] + [InlineData(false, false)] + [InlineData(true, true)] + public void Pre_admission_expired_predecessor_never_retires_a_proven_successor(bool predecessor, bool throws) + { + var clock = new ManualTimeProvider(); + var actor = CreateTestProbe(); + using var publisher = new ActorProjectedValuePublisher(() => actor.Ref, _ => true, 2, 100_000, clock); + var id = ProjectedDataIds.Identifier("mapping", new DataAddress("cluster", "urn:raw", "string", "node")); + var route = new ProjectedValueRoute("grpc-data:link", ProjectedDataIds.DependencyReference(DataRealm.Raw, id), + DataRealm.Raw, id, 1, new ServingIdentity("node", "boot", "Primary", 1, 1, 1), Guid.NewGuid()); + var proof = new TestProof(clock) { SampleValid = false, Obsolete = predecessor, ThrowCapability = throws }; + publisher.TryBind(route).ShouldBeTrue(); + publisher.TryPublish([new(route, new DataValueSnapshot(7, 0, null, null), new(TimeSpan.Zero, TimeSpan.Zero), + clock.GetTimestamp(), proof, true, TimeSpan.FromSeconds(1), 1)]).ShouldBeFalse(); + publisher.IsCurrent(route).ShouldBe(predecessor && !throws); + proof.Invalidations.ShouldBe(predecessor && !throws ? 0 : 1); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Only_an_explicitly_retired_predecessor_may_be_dropped_without_retiring_the_live_route(bool predecessor) + { + var clock = new ManualTimeProvider(); + var actor = CreateTestProbe(); + using var publisher = new ActorProjectedValuePublisher(() => actor.Ref, _ => true, 2, 100_000, clock); + var id = ProjectedDataIds.Identifier("mapping", new DataAddress("cluster", "urn:raw", "string", "node")); + var route = new ProjectedValueRoute("grpc-data:link", ProjectedDataIds.DependencyReference(DataRealm.Raw, id), + DataRealm.Raw, id, 1, new ServingIdentity("node", "boot", "Primary", 1, 1, 1), Guid.NewGuid()); + var proof = new TestProof(clock); + publisher.TryBind(route).ShouldBeTrue(); + publisher.TryPublish([new(route, new DataValueSnapshot(7, 0, null, null), new(TimeSpan.Zero, TimeSpan.Zero), + clock.GetTimestamp(), proof, true, TimeSpan.FromSeconds(1), 1)]).ShouldBeTrue(); + proof.Obsolete = predecessor; + if (predecessor) proof.SampleValid = false; + clock.Advance(TimeSpan.FromSeconds(2)); + publisher.PendingBytes.ShouldBe(0); + publisher.IsCurrent(route).ShouldBe(predecessor); + proof.Invalidations.ShouldBe(predecessor ? 0 : 1); + } + + private sealed class TestProof(TimeProvider clock) : IProjectedSamplePublicationProof, IObsoleteProjectedSample + { + internal bool SampleValid = true, Obsolete, ThrowCapability; + internal int Invalidations; + public TimeProvider Clock => clock; + public bool IsValid => SampleValid; + public bool IsSourceValid => true; + public bool CanDropExpiredPredecessor => ThrowCapability ? throw new InvalidOperationException("authority callback failed") : Obsolete; + public void Invalidate() => Invalidations++; + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalRetryTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalRetryTests.cs new file mode 100644 index 000000000..e5569cf36 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataMetadataRenewalRetryTests.cs @@ -0,0 +1,35 @@ +using System.Threading.Channels; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataProjectedAccessTests +{ + [Fact(Timeout = 30000), Trait("Phase", "P11Renewal")] + public async Task Accepted_healthy_complete_baseline_resets_retry_backoff_for_each_new_outage() + { + var ct = TestContext.Current.CancellationToken; + using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { ScalarSnapshots = true }; + using var access = fixture.Create(); + var delays = Channel.CreateUnbounded(); + access.RetryJitterForTests = delay => { delays.Writer.TryWrite(delay); return TimeSpan.FromMilliseconds(1); }; + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var demand).ShouldBeTrue(); + try + { + access.StartSubscription(demand!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + (await fixture.ReadUpdateAsync()).IsCompleteSnapshot.ShouldBeTrue(); + for (var attempt = 0; attempt < 3; attempt++) + { + fixture.EndAllStreams(); + var delay = await delays.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct); + delay.ShouldBe(TimeSpan.FromMilliseconds(100), "a successfully admitted healthy baseline ends the previous failure streak"); + var baseline = await fixture.ReadUpdateAsync(); + baseline.IsCompleteSnapshot.ShouldBeTrue(); + baseline.SourceProof.IsValid.ShouldBeTrue(); + } + } + finally { demand?.Dispose(); } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProbeFailureClassifierTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProbeFailureClassifierTests.cs new file mode 100644 index 000000000..dfda83289 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProbeFailureClassifierTests.cs @@ -0,0 +1,162 @@ +using System.Security.Authentication; +using System.Text.Json; +using Grpc.Core; +using GrpcDataProbe; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using Shouldly; +using Xunit; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Phase", "P10")] +public sealed class GrpcDataProbeFailureClassifierTests +{ + private static readonly DataTarget Pin = new(DataTargetMode.Node, "SOURCE", "source-1:4053", DataConsistency.Primary); + private static DataCapabilities MissingRead() => new(1, 5, + new("source-1:4053", "fixture-incarnation", "Primary", 11, 10, 2), DataReadiness.Ready, + DataOperations.Browse | DataOperations.Metadata, new HashSet { DataValueKind.UInt16 }, + new(10, 10, 1024 * 1024, 10, 2, 1024 * 1024, TimeSpan.FromSeconds(15), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(30)), + false, 0, "SOURCE", SubscriptionAgeReadiness: true, ResponseServingIdentity: true, WriteServingGenerationEnforced: true); + private static ProbeFailureEvidence WrappedPermissionDenied() => ProbeFailureClassifier.Capture( + new InvalidOperationException("No ready authenticated data endpoint.", + new RpcException(new Status(StatusCode.PermissionDenied, "private denial detail"))), ProbeFailurePhase.Read); + + [Fact] + public void Missing_read_on_exact_ready_pinned_primary_accepts_only_explicit_wrapped_permission_denied() + { + ProbeFailureClassifier.IsPinnedReadPermissionDenied(Pin, MissingRead(), WrappedPermissionDenied()).ShouldBeTrue(); + } + + [Fact] + public void Read_denial_rejects_transport_tls_target_backoff_wrong_rpc_and_incomplete_chains() + { + var valid = WrappedPermissionDenied(); + ProbeFailureEvidence[] failures = [ + valid with { Truncated = true }, + valid with { Chain = [new("NoReadyEndpoint"), new("RpcFailure", "PermissionDenied"), new("Other")] }, + valid with { Chain = [new("RpcFailure", "PermissionDenied")] }, + valid with { Chain = [new("NoReadyEndpoint", "PermissionDenied"), new("RpcFailure", "PermissionDenied")] }, + ProbeFailureClassifier.Capture(new InvalidOperationException("No ready authenticated data endpoint.", + new InvalidOperationException("Endpoint is not an authenticated ready target.")), ProbeFailurePhase.Read), + ProbeFailureClassifier.Capture(new InvalidOperationException("Data endpoint discovery is backing off."), ProbeFailurePhase.Read), + ProbeFailureClassifier.Capture(new HttpRequestException("private", new AuthenticationException("private")), ProbeFailurePhase.Read), + ProbeFailureClassifier.Capture(new InvalidOperationException("No ready authenticated data endpoint.", + new RpcException(new Status(StatusCode.Unavailable, "private"))), ProbeFailurePhase.Read), + ProbeFailureClassifier.Capture(new InvalidOperationException("No ready authenticated data endpoint.", + new RpcException(new Status(StatusCode.Unauthenticated, "private"))), ProbeFailurePhase.Read) + ]; + foreach (var failure in failures) + ProbeFailureClassifier.IsPinnedReadPermissionDenied(Pin, MissingRead(), failure).ShouldBeFalse(); + } + + [Fact] + public void Read_denial_requires_missing_negotiated_read_and_exact_source_primary_configuration() + { + var caps = MissingRead(); + DataCapabilities?[] invalid = [null, caps with { Operations = caps.Operations | DataOperations.Read }, + caps with { Readiness = DataReadiness.Unavailable }, caps with { ClusterId = "OTHER" }, + caps with { Serving = caps.Serving with { NodeId = "source-2:4053" } }, + caps with { Serving = caps.Serving with { Role = "Secondary" } }, + caps with { Serving = caps.Serving with { ServingGeneration = 0 } }, + caps with { ResponseServingIdentity = false }]; + foreach (var candidate in invalid) + ProbeFailureClassifier.IsPinnedReadPermissionDenied(Pin, candidate, WrappedPermissionDenied()).ShouldBeFalse(); + DataTarget[] wrongTargets = [new(DataTargetMode.Cluster, "SOURCE", null), Pin with { Consistency = DataConsistency.ReadyReplica }, + Pin with { ExpectedNodeId = "source-2:4053" }, Pin with { ExpectedClusterId = "OTHER" }]; + foreach (var target in wrongTargets) + ProbeFailureClassifier.IsPinnedReadPermissionDenied(target, caps, WrappedPermissionDenied()).ShouldBeFalse(); + } + + [Fact] + public void Wrapped_read_denial_cannot_pass_during_another_operation_phase() + { + foreach (var phase in new[] { "GetCapabilities", "Metadata", "Write", "Subscribe", "Other" }) + ProbeFailureClassifier.IsPinnedReadPermissionDenied(Pin, MissingRead(), WrappedPermissionDenied() with { Phase = phase }).ShouldBeFalse(); + } + + [Fact] + public void Retired_ca_accepts_known_rpc_status_only_with_exact_typed_transport_tls_chain() + { + foreach (var status in new[] { StatusCode.Internal, StatusCode.Unavailable }) + { + var error = new RpcException(new Status(status, "private gRPC details", + new HttpRequestException("https://private.invalid", new AuthenticationException("private TLS details")))); + var evidence = ProbeFailureClassifier.Capture(error, ProbeFailurePhase.WireRetiredCa); + ProbeFailureClassifier.IsRetiredCaTlsRejection(evidence).ShouldBeTrue(); + JsonSerializer.Serialize(evidence).ShouldNotContain("private"); + } + } + + [Fact] + public void Retired_ca_rejects_generic_rpc_errors_wrong_phase_unknown_frames_and_truncation() + { + var valid = new ProbeFailureEvidence("WireRetiredCa", "TlsFailure", false, + [new("RpcFailure", "Internal"), new("TransportFailure"), new("TlsFailure")]); + ProbeFailureEvidence[] invalid = [valid with { Phase = "WirePositiveCapabilities" }, valid with { Truncated = true }, + valid with { Category = "RpcFailure" }, + valid with { Chain = [new("RpcFailure", "Internal")] }, + valid with { Chain = [new("RpcFailure", "Unavailable")] }, + valid with { Chain = [new("RpcFailure", "PermissionDenied"), new("TransportFailure"), new("TlsFailure")] }, + valid with { Chain = [new("RpcFailure", "Internal"), new("Other"), new("TlsFailure")] }, + valid with { Chain = [new("RpcFailure", "Internal"), new("TransportFailure"), new("TlsFailure"), new("Other")] }]; + foreach (var evidence in invalid) + ProbeFailureClassifier.IsRetiredCaTlsRejection(evidence).ShouldBeFalse(); + } + + [Fact] + public void Exact_authenticated_target_ineligibility_is_distinct_from_unknown_failure() + { + var error = new InvalidOperationException("No ready authenticated data endpoint.", + new InvalidOperationException("Endpoint is not an authenticated ready target.")); + var result = ProbeFailureClassifier.Capture(error, ProbeFailurePhase.GetCapabilities); + result.Phase.ShouldBe("GetCapabilities"); + result.Category.ShouldBe("TargetIneligible"); + result.Truncated.ShouldBeFalse(); + result.Chain.Select(frame => frame.Code).ShouldBe(["NoReadyEndpoint", "TargetIneligible"]); + } + + [Fact] + public void Transport_tls_rpc_backoff_and_unknown_messages_never_prove_target_ineligibility() + { + const string secret = "never-publish-bearer-or-uri"; + Exception[] errors = [ + new HttpRequestException("https://" + secret, new AuthenticationException(secret)), + new RpcException(new Status(StatusCode.Unavailable, secret)), + new InvalidOperationException("Data endpoint discovery is backing off."), + new InvalidOperationException("Endpoint is not an authenticated ready target. " + secret), + new InvalidOperationException("Endpoint is not an authenticated ready target.", new AuthenticationException(secret)) + ]; + foreach (var error in errors) + { + var result = ProbeFailureClassifier.Capture(error, ProbeFailurePhase.GetCapabilities); + result.Category.ShouldNotBe("TargetIneligible"); + var json = JsonSerializer.Serialize(result); + json.ShouldNotContain(secret); + json.ShouldNotContain("https://"); + } + var rpc = ProbeFailureClassifier.Capture(errors[1], ProbeFailurePhase.Read); + rpc.Chain.ShouldHaveSingleItem().RpcStatus.ShouldBe("Unavailable"); + } + + [Fact] + public void Chains_are_limited_to_eight_frames_and_truncation_is_not_accepted_as_target_proof() + { + Exception error = new InvalidOperationException("Endpoint is not an authenticated ready target."); + for (var i = 0; i < 8; i++) + error = new InvalidOperationException("No ready authenticated data endpoint.", error); + var result = ProbeFailureClassifier.Capture(error, ProbeFailurePhase.GetCapabilities); + result.Chain.Count.ShouldBe(8); + result.Truncated.ShouldBeTrue(); + result.Category.ShouldNotBe("TargetIneligible"); + } + + [Fact] + public void Security_material_absence_and_unknown_phase_are_fixed_codes() + { + var result = ProbeFailureClassifier.Capture(new UnauthorizedAccessException("Connection credential or trust unavailable."), + (ProbeFailurePhase)1234); + result.Phase.ShouldBe("Other"); + result.Chain.ShouldHaveSingleItem().Code.ShouldBe("SecurityMaterialUnavailable"); + result.Category.ShouldNotBe("TargetIneligible"); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedAccessTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedAccessTests.cs index 627147beb..6f663c532 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedAccessTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedAccessTests.cs @@ -13,7 +13,7 @@ using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; [Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] -public sealed class GrpcDataProjectedAccessTests +public sealed partial class GrpcDataProjectedAccessTests { [Fact] public void Acquisition_pins_the_exact_materialized_origin_and_disposal_fences_it() @@ -165,6 +165,42 @@ public sealed class GrpcDataProjectedAccessTests finally { release.Set(); await fixture.NoPins.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); } } + [Fact(Timeout = 30000), Trait("Phase", "P10")] + public async Task Cold_sdk_read_budget_is_bounded_to_the_configured_transport_limit_and_publishes() + { + using var fixture = new AccessFixture(readOnly: true); using var access = fixture.Create(maxBytes: 1024 * 1024); + fixture.Publish(42); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue(); + var sdkBudget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024); + access.ScheduleRead(demand!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeTrue(); + var update = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + update.Snapshot.Value.ShouldBe(42); + fixture.ReadBudget.ShouldNotBeNull().MaxBytes.ShouldBe(1024 * 1024); + await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + } + + [Fact(Timeout = 30000), Trait("Phase", "P10")] + public async Task Clamped_read_reserves_the_full_configured_budget_until_physical_completion() + { + using var fixture = new AccessFixture(readOnly: true) { BlockAcquire = true }; using var access = fixture.Create(maxBytes: 1024 * 1024); + fixture.Publish(42); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var first).ShouldBeTrue(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var second).ShouldBeTrue(); + var sdkBudget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024); + try + { + access.ScheduleRead(first!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeTrue(); + await fixture.AcquireEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + access.ScheduleRead(second!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeFalse(); + second!.IsValid.ShouldBeTrue("a rejected admission leaves ownership with the caller"); + fixture.ReleaseAcquire.TrySetResult(); + await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + SpinWait.SpinUntil(() => access.ScheduleRead(second, sdkBudget, fixture.Clock.GetTimestamp()), TimeSpan.FromSeconds(5)).ShouldBeTrue(); + second = null; // admitted work owns the lease + } + finally { fixture.ReleaseAcquire.TrySetResult(); first?.Dispose(); second?.Dispose(); } + } + [Fact(Timeout = 30000)] public async Task Read_without_subscribe_permission_preserves_origin_age_timestamps_and_source_proof() { @@ -204,6 +240,62 @@ public sealed class GrpcDataProjectedAccessTests old.SourceProof.IsValid.ShouldBeFalse(); } + [Fact(Timeout = 30000), Trait("Phase", "P10")] + public async Task Sdk_write_budget_is_bounded_to_configured_limit_and_dispatches_once() + { + using var fixture = new AccessFixture(writable: true); using var access = fixture.Create(maxBytes: 1024 * 1024); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var demand).ShouldBeTrue(); + try + { + var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024); + var result = await access.WriteAsync(demand!, 42, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken); + result.State.ShouldBe(DataWriteState.OutcomeUnknown); + fixture.SentWrite.ShouldNotBeNull().Budget.MaxBytes.ShouldBe(1024 * 1024); + fixture.WriteCalls.ShouldBe(1); + } + finally { demand?.Dispose(); } + } + + [Fact(Timeout = 30000), Trait("Phase", "P10")] + public async Task Clamped_write_rejects_oversized_value_before_dispatch() + { + using var fixture = new AccessFixture(writable: true, array: true); using var access = fixture.Create(maxBytes: 1024); + var metadata = fixture.Proof.Metadata with { Dimensions = [0] }; + fixture.Proof = fixture.Proof with { Metadata = metadata, OriginMetadata = fixture.Proof.OriginMetadata with { Dimensions = [0] } }; + fixture.Definition = fixture.Definition with { Metadata = metadata }; + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var demand).ShouldBeTrue(); + try + { + var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024); + var result = await access.WriteAsync(demand!, new int[64], budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken); + result.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); fixture.WriteCalls.ShouldBe(0); + } + finally { demand?.Dispose(); } + } + + [Fact(Timeout = 30000), Trait("Phase", "P10")] + public async Task Cancelled_clamped_write_keeps_capacity_until_the_physical_send_finishes() + { + using var fixture = new AccessFixture(writable: true) { BlockWrite = true }; using var access = fixture.Create(maxBytes: 1024 * 1024); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var first).ShouldBeTrue(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var second).ShouldBeTrue(); + using var cancel = new CancellationTokenSource(); + try + { + var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024); + var pending = access.WriteAsync(first!, 42, budget, fixture.Clock.GetTimestamp(), cancel.Token); + await fixture.WriteEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + cancel.Cancel(); + (await pending.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.OutcomeUnknown); + var denied = await access.WriteAsync(second!, 43, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken); + denied.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); + fixture.WriteCalls.ShouldBe(1); + fixture.ReleaseWrite.TrySetResult(); + await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + } + finally { fixture.ReleaseWrite.TrySetResult(); first?.Dispose(); second?.Dispose(); } + } + [Fact(Timeout = 30000)] public async Task Strict_write_dispatch_uses_exact_origin_and_preserves_unknown_without_publishing_value() { @@ -261,6 +353,337 @@ public sealed class GrpcDataProjectedAccessTests finally { first?.Dispose(); second?.Dispose(); } } + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Refreshing_one_registration_keeps_the_shared_stream_and_other_registration_live() + { + using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { ScalarSnapshots = true }; using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var slow).ShouldBeTrue(); + access.TryAcquire(fixture.SecondNodeId, fixture.Caller, DataOperations.Subscribe, out var healthy).ShouldBeTrue(); + try + { + access.StartSubscription(slow!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + access.StartSubscription(healthy!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + await fixture.TwoStreamItems.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var first = await fixture.ReadUpdateAsync(); var second = await fixture.ReadUpdateAsync(); + var baseline = new[] { first, second }.Single(x => x.Route.LocalIdentifier == fixture.Proof.LocalIdentifier); + baseline.IsCompleteSnapshot.ShouldBeTrue(); baseline.Snapshot.Value.ShouldBe(7); + access.RequestFreshSnapshot(slow!).ShouldBeTrue(); + await fixture.ThirdStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.StreamOpens.ShouldBe(1, "refreshing one registration must not restart its healthy cohort"); + fixture.StreamClosed.Task.IsCompleted.ShouldBeFalse(); + var commands = fixture.StreamCommands.ToArray(); + var initial = commands.OfType().Single().Items.Single(); + var other = commands.OfType().First().Items.Single(); + var removed = commands.OfType().Single(); + var rebound = commands.OfType().Last().Items.Single(); + rebound.View.ShouldBe(initial.View); + rebound.ClientItemId.ShouldNotBe(initial.ClientItemId); + removed.Items.ShouldHaveSingleItem().ShouldBe(fixture.StreamHandles[initial.ClientItemId]); + var recovered = await fixture.ReadUpdateAsync(); + recovered.Route.ShouldBe(baseline.Route); + recovered.IsCompleteSnapshot.ShouldBeTrue(); recovered.Snapshot.Value.ShouldBe(7); + baseline.SourceProof.IsValid.ShouldBeFalse("the last proven registration for this source was removed"); + recovered.SourceProof.IsValid.ShouldBeTrue(); + fixture.EmitValue(other.ClientItemId, 2, 42); + var update = await fixture.ReadUpdateAsync(); + update.Snapshot.Value.ShouldBe(42); + healthy!.IsValid.ShouldBeTrue(); + } + finally { slow?.Dispose(); healthy?.Dispose(); } + } + + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Snapshot_waiting_for_end_cannot_publish_after_its_freshness_expires() + { + using var fixture = new AccessFixture(streams: true, subscribeOnly: true) + { ScalarSnapshots = true, HoldNextSnapshotEnd = true }; + fixture.Proof = fixture.Proof with { MaximumSampleAge = TimeSpan.FromMilliseconds(500) }; + // The fake stream supplies a finite bound at this observation, before its queued frame is read. + fixture.SnapshotObservedTimestamp = fixture.Clock.GetTimestamp(); + using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var demand).ShouldBeTrue(); + try + { + access.StartSubscription(demand!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + await fixture.SnapshotEndHeld.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + SpinWait.SpinUntil(() => Volatile.Read(ref fixture.Pins) >= 2, TimeSpan.FromSeconds(5)).ShouldBeTrue(); + var id = fixture.StreamCommands.OfType().Single().Items.Single().ClientItemId; + fixture.Advance(TimeSpan.FromSeconds(1)); + fixture.ReleaseSnapshotEnd(); + fixture.EmitValue(id, 2, 42); + var admitted = await fixture.ReadUpdateAsync(); + admitted.Snapshot.Value.ShouldBe(42, "the expired pending snapshot must not be admitted before the fresh delta"); + admitted.SourceVersion.ShouldBe(2); + } + finally { demand?.Dispose(); } + } + + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Decoder_observation_time_is_not_replaced_by_later_pump_time() + { + using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { ScalarSnapshots = true }; + fixture.Proof = fixture.Proof with { MaximumSampleAge = TimeSpan.FromMilliseconds(500) }; + fixture.SnapshotObservedTimestamp = fixture.Clock.GetTimestamp(); + fixture.Advance(TimeSpan.FromSeconds(1)); + using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var demand).ShouldBeTrue(); + try + { + access.StartSubscription(demand!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + await fixture.FirstStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var id = fixture.StreamCommands.OfType().Single().Items.Single().ClientItemId; + fixture.EmitValue(id, 2, 42); + var admitted = await fixture.ReadUpdateAsync(); + admitted.Snapshot.Value.ShouldBe(42, "a delayed handoff must not extend the decoder's age bound"); + admitted.SourceVersion.ShouldBe(2); + } + finally { demand?.Dispose(); } + } + + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Healthy_delta_is_published_while_another_registration_snapshot_is_open() + { + using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { ScalarSnapshots = true }; using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var slow).ShouldBeTrue(); + access.TryAcquire(fixture.SecondNodeId, fixture.Caller, DataOperations.Subscribe, out var healthy).ShouldBeTrue(); + try + { + access.StartSubscription(slow!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + access.StartSubscription(healthy!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + await fixture.TwoStreamItems.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + await fixture.ReadUpdateAsync(); await fixture.ReadUpdateAsync(); + var healthyId = fixture.StreamCommands.OfType().Single().Items.Single().ClientItemId; + fixture.HoldNextSnapshotEnd = true; + access.RequestFreshSnapshot(slow!).ShouldBeTrue(); + await fixture.SnapshotEndHeld.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.EmitValue(healthyId, 2, 42); + var live = await fixture.ReadUpdateAsync(); + live.Snapshot.Value.ShouldBe(42); live.IsCompleteSnapshot.ShouldBeFalse(); + fixture.ReleaseSnapshotEnd(); + var recovered = await fixture.ReadUpdateAsync(); + recovered.Route.LocalIdentifier.ShouldBe(fixture.Proof.LocalIdentifier); recovered.IsCompleteSnapshot.ShouldBeTrue(); + } + finally { slow?.Dispose(); healthy?.Dispose(); } + } + + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Two_mappings_of_one_origin_keep_separate_local_routes_and_shared_stream() + { + using var fixture = new AccessFixture(streams: true, subscribeOnly: true, aliases: true) { ScalarSnapshots = true }; using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var first).ShouldBeTrue(); + access.TryAcquire(fixture.SecondNodeId, fixture.Caller, DataOperations.Subscribe, out var second).ShouldBeTrue(); + try + { + first!.OriginView.ShouldBe(second!.OriginView); + access.StartSubscription(first, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + access.StartSubscription(second, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + await fixture.TwoStreamItems.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var one = await fixture.ReadUpdateAsync(); var two = await fixture.ReadUpdateAsync(); + new[] { one.Route.LocalIdentifier, two.Route.LocalIdentifier }.ShouldBe(new[] { fixture.Proof.LocalIdentifier, fixture.SecondProof!.LocalIdentifier }, ignoreOrder: true); + one.Route.PublicationId.ShouldNotBe(two.Route.PublicationId); + fixture.StreamOpens.ShouldBe(1); + var other = fixture.StreamCommands.OfType().Single().Items.Single(); + await access.DisposeConfiguredAsync(first); + var surviving = one.Route.LocalIdentifier == fixture.SecondProof.LocalIdentifier ? one : two; + surviving.SourceProof.IsValid.ShouldBeTrue(); + fixture.EmitValue(other.ClientItemId, 2, 9); + var live = await fixture.ReadUpdateAsync(); live.Route.ShouldBe(surviving.Route); live.Snapshot.Value.ShouldBe(9); + } + finally { first?.Dispose(); second?.Dispose(); } + } + + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Withdrawing_one_cadence_keeps_the_shared_source_proof_live() + { + using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { ScalarSnapshots = true }; using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var first).ShouldBeTrue(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var second).ShouldBeTrue(); + try + { + access.StartSubscription(first!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + access.StartSubscription(second!, TimeSpan.FromSeconds(2)).ShouldBeTrue(); + await fixture.SecondTotalStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var baseline = await fixture.ReadUpdateAsync(); + var other = fixture.StreamCommands.OfType().Single(x => x.Items[0].Settings.PublishingInterval == TimeSpan.FromSeconds(2)).Items.Single(); + // The other cadence must have actually delivered, not merely started its Open. + fixture.EmitValue(other.ClientItemId, 2, 41); + (await fixture.ReadUpdateAsync()).Snapshot.Value.ShouldBe(41); + await access.DisposeConfiguredAsync(first!); + baseline.SourceProof.IsValid.ShouldBeTrue(); + fixture.EmitValue(other.ClientItemId, 3, 42); + var live = await fixture.ReadUpdateAsync(); + live.Route.ShouldBe(baseline.Route); live.Snapshot.Value.ShouldBe(42); second!.IsValid.ShouldBeTrue(); + } + finally { first?.Dispose(); second?.Dispose(); } + } + + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Latest_sample_cache_uses_one_global_budget_and_invalidation_releases_it() + { + using var fixture = new AccessFixture(streams: true, aliases: true); using var access = fixture.Create(maxBytes: 1100); + var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 1100); + fixture.Publish(7); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var first).ShouldBeTrue(); + access.ScheduleRead(first!, budget, fixture.Clock.GetTimestamp()).ShouldBeTrue(); + (await fixture.ReadUpdateAsync()).Snapshot.Value.ShouldBe(7); + SpinWait.SpinUntil(() => access.CachedSampleBytesForTests > 0, TimeSpan.FromSeconds(5)).ShouldBeTrue(); + var charge = access.CachedSampleBytesForTests; + charge.ShouldBeLessThanOrEqualTo(1100); + access.TryAcquire(fixture.SecondNodeId, fixture.Caller, DataOperations.Read, out var second).ShouldBeTrue(); + SpinWait.SpinUntil(() => access.ScheduleRead(second!, budget, fixture.Clock.GetTimestamp()), TimeSpan.FromSeconds(5)).ShouldBeTrue(); + (await fixture.ReadUpdateAsync()).Snapshot.Value.ShouldBe(7); + // A second source cannot allocate another sample past the shared limit. + access.CachedSampleBytesForTests.ShouldBe(charge); + fixture.PublishVersion(2, 9); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var replacement).ShouldBeTrue(); + SpinWait.SpinUntil(() => access.ScheduleRead(replacement!, budget, fixture.Clock.GetTimestamp()), TimeSpan.FromSeconds(5)).ShouldBeTrue(); + (await fixture.ReadUpdateAsync()).Snapshot.Value.ShouldBe(9); + SpinWait.SpinUntil(() => access.CachedSampleBytesForTests == charge, TimeSpan.FromSeconds(5)).ShouldBeTrue(); + fixture.InvalidateMapping(); + await fixture.SourceRetired.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + SpinWait.SpinUntil(() => access.CachedSampleBytesForTests == 0, TimeSpan.FromSeconds(5)).ShouldBeTrue(); + } + + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Quiet_recovery_replays_the_newest_admitted_sample_with_its_elapsed_age() + { + using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { ScalarSnapshots = true, HoldRemoveAck = true }; using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var slow).ShouldBeTrue(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var other).ShouldBeTrue(); + try + { + access.StartSubscription(slow!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + access.StartSubscription(other!, TimeSpan.FromSeconds(2)).ShouldBeTrue(); + await fixture.SecondTotalStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + await fixture.ReadUpdateAsync(); + var opens = fixture.StreamCommands.OfType().ToArray(); + var slowId = opens.Single(x => x.Items[0].Settings.PublishingInterval == TimeSpan.FromSeconds(1)).Items[0].ClientItemId; + var otherId = opens.Single(x => x.Items[0].Settings.PublishingInterval == TimeSpan.FromSeconds(2)).Items[0].ClientItemId; + access.RequestFreshSnapshot(slow!).ShouldBeTrue(); + await fixture.ItemRemoved.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.EmitValue(otherId, 2, 8); + var advance = await fixture.ReadUpdateAsync(); + fixture.Advance(TimeSpan.FromSeconds(2)); + fixture.ReleaseRemoveAck(slowId); + var recovered = await fixture.ReadUpdateAsync(); + recovered.IsCompleteSnapshot.ShouldBeTrue(); recovered.Snapshot.ShouldBe(advance.Snapshot); + recovered.Route.ShouldBe(advance.Route); + advance.SourceVersion.ShouldBe(2); recovered.SourceVersion.ShouldBe(advance.SourceVersion); + recovered.OriginAgeBounds.ShouldBe(advance.OriginAgeBounds); + recovered.ReceivedTimestamp.ShouldBe(advance.ReceivedTimestamp); + recovered.OriginAgeBounds.Advance(fixture.Clock.GetElapsedTime(recovered.ReceivedTimestamp, fixture.Clock.GetTimestamp())).Upper.ShouldBe(TimeSpan.FromSeconds(2)); + } + finally { slow?.Dispose(); other?.Dispose(); } + } + + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Expired_cached_sample_is_not_used_as_a_recovery_baseline() + { + using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { ScalarSnapshots = true, HoldRemoveAck = true }; + fixture.Proof = fixture.Proof with { MaximumSampleAge = TimeSpan.FromMilliseconds(500) }; + using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var slow).ShouldBeTrue(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var other).ShouldBeTrue(); + try + { + access.StartSubscription(slow!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + access.StartSubscription(other!, TimeSpan.FromSeconds(2)).ShouldBeTrue(); + await fixture.SecondTotalStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + await fixture.ReadUpdateAsync(); + var opens = fixture.StreamCommands.OfType().ToArray(); + var slowId = opens.Single(x => x.Items[0].Settings.PublishingInterval == TimeSpan.FromSeconds(1)).Items[0].ClientItemId; + var otherId = opens.Single(x => x.Items[0].Settings.PublishingInterval == TimeSpan.FromSeconds(2)).Items[0].ClientItemId; + access.RequestFreshSnapshot(slow!).ShouldBeTrue(); + await fixture.ItemRemoved.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.EmitValue(otherId, 2, 8); await fixture.ReadUpdateAsync(); + fixture.Advance(TimeSpan.FromSeconds(1)); fixture.ReleaseRemoveAck(slowId); + await fixture.ThirdStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var rebound = fixture.StreamCommands.OfType().Single().Items.Single(); + fixture.EmitValue(rebound.ClientItemId, 3, 9); + var recovered = await fixture.ReadUpdateAsync(); recovered.Snapshot.Value.ShouldBe(9); recovered.IsCompleteSnapshot.ShouldBeTrue(); + } + finally { slow?.Dispose(); other?.Dispose(); } + } + + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Read_owned_source_survives_withdrawal_of_the_matching_subscription() + { + using var fixture = new AccessFixture(streams: true) { ScalarSnapshots = true }; using var access = fixture.Create(); + fixture.Publish(7); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var read).ShouldBeTrue(); + access.ScheduleRead(read!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue(); + var baseline = await fixture.ReadUpdateAsync(); + await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var subscription).ShouldBeTrue(); + try + { + access.StartSubscription(subscription!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + await fixture.FirstStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var id = fixture.StreamCommands.OfType().Single().Items.Single().ClientItemId; + fixture.EmitValue(id, 2, 8); + var live = await fixture.ReadUpdateAsync(); live.Route.ShouldBe(baseline.Route); + await access.DisposeConfiguredAsync(subscription!); + baseline.SourceProof.IsValid.ShouldBeTrue(); + } + finally { subscription?.Dispose(); } + } + + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Recovery_waits_for_a_current_complete_baseline_after_another_cadence_advances() + { + using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { ScalarSnapshots = true, HoldRemoveAck = true }; using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var slow).ShouldBeTrue(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var other).ShouldBeTrue(); + try + { + access.StartSubscription(slow!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + access.StartSubscription(other!, TimeSpan.FromSeconds(2)).ShouldBeTrue(); + await fixture.SecondTotalStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + await fixture.ReadUpdateAsync(); + var slowId = fixture.StreamCommands.OfType().Single(x => x.Items[0].Settings.PublishingInterval == TimeSpan.FromSeconds(1)).Items.Single().ClientItemId; + var otherId = fixture.StreamCommands.OfType().Single(x => x.Items[0].Settings.PublishingInterval == TimeSpan.FromSeconds(2)).Items.Single().ClientItemId; + access.RequestFreshSnapshot(slow!).ShouldBeTrue(); + await fixture.ItemRemoved.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.EmitValue(otherId, 2, 8); + var advance = await fixture.ReadUpdateAsync(); advance.Snapshot.Value.ShouldBe(8); + fixture.ReleaseRemoveAck(slowId); + await fixture.ThirdStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var rebound = fixture.StreamCommands.OfType().Single().Items.Single(); + var recovery = await fixture.ReadUpdateAsync(); + recovery.Snapshot.Value.ShouldBe(8); recovery.IsCompleteSnapshot.ShouldBeTrue(); + fixture.EmitValue(rebound.ClientItemId, 3, 9); + (await fixture.ReadUpdateAsync()).Snapshot.Value.ShouldBe(9); + } + finally { slow?.Dispose(); other?.Dispose(); } + } + + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Withdrawal_during_refresh_does_not_reassociate_the_registration() + { + using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { HoldRemoveAck = true }; using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var slow).ShouldBeTrue(); + access.TryAcquire(fixture.SecondNodeId, fixture.Caller, DataOperations.Subscribe, out var healthy).ShouldBeTrue(); + try + { + access.StartSubscription(slow!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + access.StartSubscription(healthy!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + await fixture.TwoStreamItems.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var other = fixture.StreamCommands.OfType().Single().Items.Single(); + access.RequestFreshSnapshot(slow!).ShouldBeTrue(); + await fixture.ItemRemoved.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + slow!.Dispose(); + fixture.EmitValue(other.ClientItemId, 2, 42); + (await fixture.ReadUpdateAsync()).Snapshot.Value.ShouldBe(42); + fixture.ReleaseRemoveAck(); + fixture.EmitValue(other.ClientItemId, 3, 43); + (await fixture.ReadUpdateAsync()).Snapshot.Value.ShouldBe(43); + fixture.StreamCommands.OfType().Count().ShouldBe(1); + fixture.StreamOpens.ShouldBe(1); healthy!.IsValid.ShouldBeTrue(); + slow.IsValid.ShouldBeFalse(); + } + finally { slow?.Dispose(); healthy?.Dispose(); } + } + [Fact(Timeout = 30000)] public async Task Subscribe_only_demand_can_request_a_fresh_snapshot_without_read_permission() { @@ -271,8 +694,9 @@ public sealed class GrpcDataProjectedAccessTests access.StartSubscription(demand!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); await fixture.FirstStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); access.RequestFreshSnapshot(demand!).ShouldBeTrue(); - await fixture.SecondStreamOpened.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); - fixture.StreamClosed.Task.IsCompleted.ShouldBeTrue(); + await fixture.SecondTotalStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.StreamOpens.ShouldBe(1); + fixture.StreamClosed.Task.IsCompleted.ShouldBeFalse(); demand!.IsValid.ShouldBeTrue(); } finally { demand?.Dispose(); } @@ -348,6 +772,28 @@ public sealed class GrpcDataProjectedAccessTests internal readonly TaskCompletionSource SecondStreamOpened = new(TaskCreationOptions.RunContinuationsAsynchronously); internal readonly TaskCompletionSource TwoStreamItems = new(TaskCreationOptions.RunContinuationsAsynchronously); internal readonly TaskCompletionSource ItemRemoved = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource ThirdStreamItem = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource SecondTotalStreamItem = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly Channel Updates = Channel.CreateUnbounded(); + internal bool ScalarSnapshots, HoldRemoveAck, HoldNextSnapshotEnd; + internal long? SnapshotObservedTimestamp; + internal readonly TaskCompletionSource SnapshotEndHeld = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal async Task ReadUpdateAsync() => await Updates.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + internal readonly System.Collections.Concurrent.ConcurrentQueue StreamCommands = new(); + internal readonly System.Collections.Concurrent.ConcurrentDictionary StreamHandles = new(); + private readonly System.Collections.Concurrent.ConcurrentQueue _streamsByOwner = new(); + internal bool BlockStreamDispose; + internal bool HoldSecondOpen; + internal readonly TaskCompletionSource SecondOpenEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource ReleaseSecondOpen = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource StreamDisposeEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource ReleaseStreamDispose = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal void EndFirstStream() => _streamsByOwner.First().End(); + internal void EndAllStreams() { foreach (var stream in _streamsByOwner.ToArray()) stream.End(); } + private int _totalStreamItems; + internal void EmitValue(string id, long version, int value) => _streamsByOwner.Single(x => x.HasItem(id)).EmitValue(id, version, value); + internal void ReleaseRemoveAck(string? id = null) => (id is null ? _streamsByOwner.Single() : _streamsByOwner.Single(x => x.HasItem(id))).ReleaseRemoveAck(); + internal void ReleaseSnapshotEnd() => _streamsByOwner.Single().ReleaseSnapshotEnd(); internal readonly TaskCompletionSource StreamClosed = new(TaskCreationOptions.RunContinuationsAsynchronously); private readonly bool _streams; private readonly bool _array; @@ -367,12 +813,20 @@ public sealed class GrpcDataProjectedAccessTests Published = new(TaskCreationOptions.RunContinuationsAsynchronously); } internal void Publish(int value) => _local.Publish(value); + internal void Advance(TimeSpan elapsed) => _local.Clock.Advance(elapsed); + internal void PublishVersion(long version, int value) => _local.Hub.WithPartitionLockForTest(_local.Ticket.Key, () => { HubTest.Publish(_local.Hub, _local.Ticket, version, value); _local.Hub.ProcessPending(); }); internal WriteBatch? SentWrite; - internal bool BlockAcquire, RoleAllowed = true; + internal int WriteCalls; + internal DataBudget? ReadBudget; + internal bool BlockAcquire, BlockWrite, BlockReadReturn, RoleAllowed = true; + internal readonly TaskCompletionSource ReadResultHeld = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource ReleaseReadResult = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource WriteEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource ReleaseWrite = new(TaskCreationOptions.RunContinuationsAsynchronously); internal long RoleGeneration = 1; internal readonly TaskCompletionSource AcquireEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); internal readonly TaskCompletionSource ReleaseAcquire = new(TaskCreationOptions.RunContinuationsAsynchronously); - internal AccessFixture(bool readOnly = false, bool writable = false, bool streams = false, bool subscribeOnly = false, bool array = false) + internal AccessFixture(bool readOnly = false, bool writable = false, bool streams = false, bool subscribeOnly = false, bool array = false, bool aliases = false) { _streams = streams; _array = array; var authority = _local.Authority; @@ -397,19 +851,20 @@ public sealed class GrpcDataProjectedAccessTests Definition = new(DataRealm.Raw, Proof.LocalIdentifier, new NodeId("parent", 2), metadata, 1, () => Current); if (streams) { - var secondOrigin = origin with { Address = origin.Address with { Identifier = origin.Address.Identifier + "2" }, Subject = origin.Subject + "2" }; - var secondView = mapped with { Address = secondOrigin.Address, Subject = mapped.Subject + "2" }; + var secondOrigin = aliases ? origin : origin with { Address = origin.Address with { Identifier = origin.Address.Identifier + "2" }, Subject = origin.Subject + "2" }; + var secondView = mapped with { Address = secondOrigin.Address, Subject = mapped.Subject + "2", MappingId = aliases ? "mapping-two" : "mapping" }; var secondSubject = subject with { View = secondView, Scope = subject.Scope with { Segments = ["Plant", "branch", "Speed2"] } }; var secondMetadata = metadata with { View = secondView, BrowseName = "Speed2" }; - SecondProof = new(ProjectedDataIds.Identifier("mapping", secondOrigin.Address), secondMetadata, secondSubject, new([secondSubject], 1, _local.Activation.CaptureAuthority()), lease, 1, secondMetadata with { View = secondOrigin }, TimeSpan.FromSeconds(30)); + SecondProof = new(ProjectedDataIds.Identifier(aliases ? "mapping-two" : "mapping", secondOrigin.Address), secondMetadata, secondSubject, new([secondSubject], 1, _local.Activation.CaptureAuthority()), lease, 1, secondMetadata with { View = secondOrigin }, TimeSpan.FromSeconds(30)); SecondDefinition = new(DataRealm.Raw, SecondProof.LocalIdentifier, new NodeId("parent", 2), secondMetadata, 1, () => Current); } } - internal ProjectedDataAccess Create(int maxDemands = 4) => new(this, this, this, _ => "link", _policy, this, _local.Clock, new(maxDemands, 4, 2000000, 2), () => (RoleAllowed, RoleGeneration)); + internal ProjectedDataAccess Create(int maxDemands = 4, long maxBytes = 2000000) => new(this, this, this, _ => "link", _policy, this, _local.Clock, new(maxDemands, 4, maxBytes, 2), () => (RoleAllowed, RoleGeneration)); public TimeProvider Clock => _local.Clock; public event Action? Invalidated; internal readonly TaskCompletionSource ConnectionDisposed = new(TaskCreationOptions.RunContinuationsAsynchronously); internal readonly TaskCompletionSource NoPins = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource SourceRetired = new(TaskCreationOptions.RunContinuationsAsynchronously); internal void InvalidateMapping(string mapping = "mapping") { if (mapping == "mapping") Current = false; Invalidated?.Invoke(mapping, 2); } public bool TryResolveProjected(DataRealm realm, string id, out ProjectedNodeProof? proof) { proof = Current && realm == DataRealm.Raw ? id == Proof.LocalIdentifier ? Proof : id == SecondProof?.LocalIdentifier ? SecondProof : null : null; return proof is not null; } public bool TryPinProjected(DataRealm realm, string id, out IDisposable? pin) { if (!Current || id != Proof.LocalIdentifier && id != SecondProof?.LocalIdentifier) { pin = null; return false; } Pins++; pin = new Pin(this); return true; } @@ -431,45 +886,81 @@ public sealed class GrpcDataProjectedAccessTests public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken); public Task BrowseAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest request, CancellationToken cancellationToken) => inner.BrowseAsync(request, cancellationToken); public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => inner.GetMetadataAsync(request, cancellationToken); - public Task> ReadAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest request, CancellationToken cancellationToken) + public async Task> ReadAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest request, CancellationToken cancellationToken) { - if (!owner._array) return inner.ReadAsync(request, cancellationToken); - var value = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromArray(DataValueKind.Int32, owner.ReadElements.Cast().ToArray(), [owner.ReadElements.Length]); - var sample = new DataSample(value, 0, null, owner.Clock.GetUtcNow(), owner.Proof.Lease.Serving, 1); - return Task.FromResult>([new(request.Items[0].CorrelationId, DataItemStatus.Good, DataReadiness.Ready, TimeSpan.Zero, sample, null, AgeBounds: new(TimeSpan.Zero, TimeSpan.Zero))]); + owner.ReadBudget = request.Budget; + IReadOnlyList result; + if (!owner._array) result = await inner.ReadAsync(request, cancellationToken); + else + { + var value = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromArray(DataValueKind.Int32, owner.ReadElements.Cast().ToArray(), [owner.ReadElements.Length]); + var sample = new DataSample(value, 0, null, owner.Clock.GetUtcNow(), owner.Proof.Lease.Serving, 1); + result = [new(request.Items[0].CorrelationId, DataItemStatus.Good, DataReadiness.Ready, TimeSpan.Zero, sample, null, AgeBounds: new(TimeSpan.Zero, TimeSpan.Zero))]; + } + try + { + if (owner.BlockReadReturn) + { + owner.ReadResultHeld.TrySetResult(); + await owner.ReleaseReadResult.Task.WaitAsync(cancellationToken); + } + return result; + } + catch { foreach (var item in result) item.Dispose(); throw; } } - public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) + public async Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) { - owner.SentWrite = request; + owner.SentWrite = request; Interlocked.Increment(ref owner.WriteCalls); if (request.Items[0].Value.Kind == DataValueKind.Array) owner.CapturedArray = request.Items[0].Value.GetArray().ToArray(); - return Task.FromResult>([new(request.Items[0].CorrelationId, new(DataWriteState.OutcomeUnknown, StatusCodes.Bad.Code, null))]); + owner.WriteEntered.TrySetResult(); + if (owner.BlockWrite) await owner.ReleaseWrite.Task; // Simulates a transport that cannot be canceled after dispatch. + return [new(request.Items[0].CorrelationId, new(DataWriteState.OutcomeUnknown, StatusCodes.Bad.Code, null))]; } public Task SubscribeAsync(CancellationToken cancellationToken) { if (!owner._streams) return inner.SubscribeAsync(cancellationToken); - if (Interlocked.Increment(ref owner.StreamOpens) == 2) owner.SecondStreamOpened.TrySetResult(); - return Task.FromResult(new TestStream(owner, owner.Proof.Lease.Serving)); + var number = Interlocked.Increment(ref owner.StreamOpens); + if (number == 2) owner.SecondStreamOpened.TrySetResult(); + var stream = new TestStream(owner, owner.Proof.Lease.Serving, number); owner._streamsByOwner.Enqueue(stream); + return Task.FromResult(stream); } public ValueTask DisposeAsync() => inner.DisposeAsync(); } - private sealed class TestStream(AccessFixture owner, ServingIdentity serving) : IDataSubscription, IDataSubscriptionProvenance + private sealed class TestStream(AccessFixture owner, ServingIdentity serving, int number) : IDataSubscription, IDataSubscriptionProvenance { private readonly Channel _frames = Channel.CreateUnbounded(); + private readonly object _gate = new(); + private string? _subscriptionId; + private long _epoch; + private DataSubscriptionAck? _heldRemoveAck; + private bool _snapshotEndHeld; private long _sequence; private ulong _handle; private int _items; private readonly Dictionary _ids = new(); public ServingIdentity Serving => serving; - public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) + public async Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) { + if (number == 2 && owner.HoldSecondOpen && command is OpenSubscription) + { + owner.SecondOpenEntered.TrySetResult(); + await owner.ReleaseSecondOpen.Task.WaitAsync(cancellationToken); + } + lock (_gate) + { + owner.StreamCommands.Enqueue(command); _subscriptionId = command.SubscriptionId; _epoch = command.StreamEpoch; IReadOnlyList items = command switch { OpenSubscription open => open.Items, AddSubscriptionItems add => add.Items, _ => [] }; var acks = items.Select(item => new DataSubscriptionItemAck(item.ClientItemId, DataItemStatus.Good, new DataItemHandle(command.SubscriptionId, command.StreamEpoch, ++_handle, 1), item.Settings, null)).ToArray(); - foreach (var ack in acks) if (ack.Handle is not null) _ids[ack.Handle] = ack.ClientItemId; + foreach (var ack in acks) if (ack.Handle is not null) { _ids[ack.Handle] = ack.ClientItemId; owner.StreamHandles[ack.ClientItemId] = ack.Handle; } if (command is RemoveSubscriptionItems remove) acks = remove.Items.Select(handle => new DataSubscriptionItemAck(_ids[handle], DataItemStatus.Good, handle, null, null)).ToArray(); - _frames.Writer.TryWrite(new DataSubscriptionAck(command.SubscriptionId, command.StreamEpoch, ++_sequence, command.CommandId, acks)); + if (command is RemoveSubscriptionItems && owner.HoldRemoveAck) + _heldRemoveAck = new DataSubscriptionAck(command.SubscriptionId, command.StreamEpoch, 0, command.CommandId, acks); + else _frames.Writer.TryWrite(new DataSubscriptionAck(command.SubscriptionId, command.StreamEpoch, ++_sequence, command.CommandId, acks)); if (items.Count > 0) { _items += items.Count; owner.FirstStreamItem.TrySetResult(); if (_items >= 2) owner.TwoStreamItems.TrySetResult(); + var total = Interlocked.Add(ref owner._totalStreamItems, items.Count); + if (total >= 2) owner.SecondTotalStreamItem.TrySetResult(); if (total >= 3) owner.ThirdStreamItem.TrySetResult(); _frames.Writer.TryWrite(new DataSubscriptionControl(command.SubscriptionId, command.StreamEpoch, ++_sequence, DataStreamControlKind.SnapshotBegin, [], serving.CatalogEpoch, serving.AuthorityEpoch, null)); if (owner._array && acks.Length > 0) { @@ -478,13 +969,57 @@ public sealed class GrpcDataProjectedAccessTests _frames.Writer.TryWrite(new DataSubscriptionValues(command.SubscriptionId, command.StreamEpoch, ++_sequence, true, [new DataSubscriptionValue(acks[0].Handle!, sample, new(TimeSpan.Zero, TimeSpan.Zero), DataReadiness.Ready)])); } - _frames.Writer.TryWrite(new DataSubscriptionControl(command.SubscriptionId, command.StreamEpoch, ++_sequence, DataStreamControlKind.SnapshotEnd, [], serving.CatalogEpoch, serving.AuthorityEpoch, null)); + if (owner.ScalarSnapshots && acks.Length > 0) + { + var sample = new DataSample(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromScalar(DataValueKind.Int32, 7), 0, null, owner.Clock.GetUtcNow(), serving, 1); + _frames.Writer.TryWrite(new DataSubscriptionValues(command.SubscriptionId, command.StreamEpoch, ++_sequence, true, + [new DataSubscriptionValue(acks[0].Handle!, sample, new(TimeSpan.Zero, TimeSpan.Zero), DataReadiness.Ready, + FreshnessObservedTimestamp: owner.SnapshotObservedTimestamp)])); + } + if (owner.HoldNextSnapshotEnd) + { + owner.HoldNextSnapshotEnd = false; _snapshotEndHeld = true; owner.SnapshotEndHeld.TrySetResult(); + } + else _frames.Writer.TryWrite(new DataSubscriptionControl(command.SubscriptionId, command.StreamEpoch, ++_sequence, DataStreamControlKind.SnapshotEnd, [], serving.CatalogEpoch, serving.AuthorityEpoch, null)); } if (command is RemoveSubscriptionItems) owner.ItemRemoved.TrySetResult(); - return Task.CompletedTask; + } + } + internal void ReleaseSnapshotEnd() + { + lock (_gate) + { + if (!_snapshotEndHeld) throw new InvalidOperationException("No snapshot end is held."); + _snapshotEndHeld = false; + _frames.Writer.TryWrite(new DataSubscriptionControl(_subscriptionId!, _epoch, ++_sequence, DataStreamControlKind.SnapshotEnd, [], serving.CatalogEpoch, serving.AuthorityEpoch, null)); + } + } + internal bool HasItem(string id) { lock (_gate) return _ids.Values.Contains(id); } + internal void ReleaseRemoveAck() + { + lock (_gate) + { + var ack = _heldRemoveAck ?? throw new InvalidOperationException("No removal acknowledgement is held."); + _heldRemoveAck = null; + _frames.Writer.TryWrite(new DataSubscriptionAck(ack.SubscriptionId, ack.StreamEpoch, ++_sequence, ack.CommandId, ack.Items)); + } + } + internal void EmitValue(string id, long version, int value) + { + lock (_gate) + { + var sample = new DataSample(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromScalar(DataValueKind.Int32, value), 0, null, owner.Clock.GetUtcNow(), serving, version); + _frames.Writer.TryWrite(new DataSubscriptionValues(_subscriptionId!, _epoch, ++_sequence, false, + [new DataSubscriptionValue(owner.StreamHandles[id], sample, new(TimeSpan.Zero, TimeSpan.Zero), DataReadiness.Ready)])); + } } public IAsyncEnumerable ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken); - public ValueTask DisposeAsync() { _frames.Writer.TryComplete(); owner.StreamClosed.TrySetResult(); return ValueTask.CompletedTask; } + internal void End() => _frames.Writer.TryComplete(); + public async ValueTask DisposeAsync() + { + _frames.Writer.TryComplete(); owner.StreamClosed.TrySetResult(); + if (owner.BlockStreamDispose) { owner.StreamDisposeEntered.TrySetResult(); await owner.ReleaseStreamDispose.Task; } + } } private sealed class ConnectionLease(IDataConnection connection, AccessFixture owner) : IGrpcDataAdapterConnectionLease { @@ -494,8 +1029,8 @@ public sealed class GrpcDataProjectedAccessTests } internal Action? BeforeBind; public bool TryBind(ProjectedValueRoute route) { BeforeBind?.Invoke(); return true; } - public bool TryPublish(IReadOnlyList updates) { Published.TrySetResult(updates[0]); return true; } - public void Retire(ProjectedValueRoute route) { } + public bool TryPublish(IReadOnlyList updates) { Published.TrySetResult(updates[0]); Updates.Writer.TryWrite(updates[0]); return true; } + public void Retire(ProjectedValueRoute route) { SourceRetired.TrySetResult(); } public void Dispose() => _local.Dispose(); } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedPageGenerationWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedPageGenerationWireTests.cs new file mode 100644 index 000000000..cd5163764 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedPageGenerationWireTests.cs @@ -0,0 +1,153 @@ +using System.Collections; +using System.Reflection; +using System.Threading.Channels; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000), Trait("Phase", "P11Renewal")] + public async Task Key_only_generation_change_reauthorizes_the_whole_page_after_one_active_child_renews() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(additionalRawNodes: 1, servingGeneration: 1, + targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + LocalCatalogCoordinator? coordinator = null; + await WithComposedServer(origin, origin.Root, async (session, sink, _, _, _, placements, anchor) => + { + var client = (SessionClient)session; + var initial = await BrowseAll(client, anchor, 10); + initial.Count.ShouldBe(2); + var scalar = ExpandedNodeId.ToNodeId(initial.Single(item => item.BrowseName.Name == "Speed").NodeId, session.NamespaceUris); + var sibling = ExpandedNodeId.ToNodeId(initial.Single(item => item.BrowseName.Name == "Speed0").NodeId, session.NamespaceUris); + var lookup = (IProjectedNodeLookup)sink; + lookup.TryResolve(scalar, out var oldScalar).ShouldBeTrue(); + lookup.TryResolve(sibling, out var oldSibling).ShouldBeTrue(); + oldScalar.ShouldNotBeNull(); oldSibling.ShouldNotBeNull(); + oldScalar.ProjectionGeneration.ShouldBe(oldSibling.ProjectionGeneration); + var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscription, scalar, 1, 100, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + + // Identical mapping revision and placement, with a new local authority/cache + // generation as in a key-only deployment. Only Speed has active demand. + var replacement = Prepare(coordinator!); + var mapping = Mapping(origin.Root); + mapping.AllowedOperations |= DataOperations.Read | DataOperations.Metadata; + mapping.Revision.ShouldBe(oldScalar.Metadata.View.MappingRevision); + placements.Stage(replacement, [mapping], [Connection()]); + coordinator!.Complete(replacement, true).ShouldBeTrue(); + subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8; + origin.Clock.Advance(TimeSpan.FromSeconds(5)); + var recovered = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.SourceVersion == 2, ct); + recovered.SourceProof.IsValid.ShouldBeTrue(); + original.SourceProof.IsValid.ShouldBeFalse(); + lookup.TryResolve(scalar, out var newScalar).ShouldBeTrue(); + newScalar.ShouldNotBeNull().ProjectionGeneration.ShouldNotBe(oldScalar.ProjectionGeneration); + var manager = sink.GetType().GetField("_nodeManager", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(sink)!; + var definitions = (IDictionary)manager.GetType().GetField("_projectedDefinitions", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(manager)!; + var staleSibling = (ProjectedVariableDefinition)definitions[sibling]!; + staleSibling.ProjectionGeneration.ShouldBe(oldSibling.ProjectionGeneration); + staleSibling.Lifetime.IsActive.ShouldBeTrue(); + staleSibling.AuthorityIsCurrent().ShouldBeFalse(); + + // A fresh authenticated complete page must reauthorize every compatible + // sibling rather than reject the page because the inactive one is old. + var after = await BrowseAll(client, anchor, 10); + after.Select(item => item.BrowseName.Name).Order().ShouldBe(new[] { "Speed", "Speed0" }); + lookup.TryResolve(sibling, out var newSibling).ShouldBeTrue(); + newSibling.ShouldNotBeNull().ProjectionGeneration.ShouldBe(newScalar.ProjectionGeneration); + newSibling.Lifetime.ShouldBeSameAs(staleSibling.Lifetime); + original.SourceProof.IsValid.ShouldBeFalse("reauthorizing a page must not revive captured old samples"); + }, onPublished: update => published.Writer.TryWrite(update), onCoordinator: value => coordinator = value); + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Renewal")] + public async Task Reauthorizing_a_page_rejects_incompatible_or_retired_children_and_failed_authority() + { + using var origin = new LocalDataFixture(additionalRawNodes: 1, servingGeneration: 1); + LocalCatalogCoordinator? coordinator = null; + await WithComposedServer(origin, origin.Root, async (session, sink, _, _, _, placements, anchor) => + { + var client = (SessionClient)session; + var initial = await BrowseAll(client, anchor, 10); + initial.Count.ShouldBe(2); + var ids = initial.Select(item => ExpandedNodeId.ToNodeId(item.NodeId, session.NamespaceUris)).ToArray(); + var manager = sink.GetType().GetField("_nodeManager", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(sink)!; + var definitions = (IDictionary)manager.GetType().GetField("_projectedDefinitions", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(manager)!; + var old = ids.Select(id => (ProjectedVariableDefinition)definitions[id]!).ToArray(); + var page = (IProjectedNamespacePageSink)sink; + old.All(item => item.AuthorityIsCurrent() && item.Lifetime.IsActive).ShouldBeTrue(); + var premature = old.Select(item => item with { ProjectionGeneration = item.ProjectionGeneration + 1, + AuthorityIsCurrent = () => true }).ToArray(); + var prematurelyCommitted = false; + page.TryApply(anchor, premature, () => { prematurelyCommitted = true; return true; }).ShouldBeFalse(); + prematurelyCommitted.ShouldBeFalse(); + var replacement = Prepare(coordinator!); + var mapping = Mapping(origin.Root); + mapping.AllowedOperations |= DataOperations.Read | DataOperations.Metadata; + placements.Stage(replacement, [mapping], [Connection()]); + coordinator!.Complete(replacement, true).ShouldBeTrue(); + old.All(item => !item.AuthorityIsCurrent() && item.Lifetime.IsActive).ShouldBeTrue(); + + var fresh = old.Select(item => item with + { + ProjectionGeneration = item.ProjectionGeneration + 1, + AuthorityIsCurrent = () => true, + Lifetime = new ProjectedNodeLifetime() + }).ToArray(); + var commits = 0; + bool Commit() { commits++; return true; } + void Unchanged() + { + foreach (var (id, index) in ids.Select((id, index) => (id, index))) + definitions[id].ShouldBeSameAs(old[index]); + } + + var badSchema = fresh.ToArray(); + badSchema[1] = badSchema[1] with { Metadata = badSchema[1].Metadata with { ValueKind = DataValueKind.String } }; + page.TryApply(anchor, badSchema, Commit).ShouldBeFalse(); + commits.ShouldBe(0); Unchanged(); + var badRevision = fresh.ToArray(); + badRevision[1] = badRevision[1] with { Metadata = badRevision[1].Metadata with + { View = badRevision[1].Metadata.View with { MappingRevision = badRevision[1].Metadata.View.MappingRevision + 1 } } }; + page.TryApply(anchor, badRevision, Commit).ShouldBeFalse(); + commits.ShouldBe(0); Unchanged(); + var stale = fresh.ToArray(); + stale[1] = stale[1] with { AuthorityIsCurrent = () => false }; + page.TryApply(anchor, stale, Commit).ShouldBeFalse(); + commits.ShouldBe(0); Unchanged(); + var rollback = fresh.ToArray(); + rollback[1] = rollback[1] with { ProjectionGeneration = old[1].ProjectionGeneration - 1 }; + page.TryApply(anchor, rollback, Commit).ShouldBeFalse(); + commits.ShouldBe(0); Unchanged(); + page.TryApply(anchor, fresh, () => false).ShouldBeFalse(); + Unchanged(); + var authorityCurrent = true; + var expiring = fresh.ToArray(); + expiring[1] = expiring[1] with { AuthorityIsCurrent = () => authorityCurrent }; + page.TryApply(anchor, expiring, () => { authorityCurrent = false; return true; }).ShouldBeFalse(); + authorityCurrent.ShouldBeFalse("the guard must be checked again after the commit runs"); + Unchanged(); + var retiredDuringCommit = false; + page.TryApply(anchor, fresh, () => { old[1].Lifetime.ForceRetire(); retiredDuringCommit = true; return true; }).ShouldBeFalse(); + retiredDuringCommit.ShouldBeTrue(); + Unchanged(); + page.TryApply(anchor, fresh, Commit).ShouldBeFalse(); + commits.ShouldBe(0); Unchanged(); + }, onCoordinator: value => coordinator = value); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedReadFreshnessTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedReadFreshnessTests.cs new file mode 100644 index 000000000..c3c82de7c --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedReadFreshnessTests.cs @@ -0,0 +1,49 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataProjectedAccessTests +{ + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Unstamped_unary_result_uses_conservative_pre_call_anchor() + { + var ct = TestContext.Current.CancellationToken; + using var fixture = new AccessFixture(readOnly: true, array: true) { BlockReadReturn = true }; + fixture.Proof = fixture.Proof with { MaximumSampleAge = TimeSpan.FromMilliseconds(500) }; + using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue(); + try + { + access.ScheduleRead(demand!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue(); + await fixture.ReadResultHeld.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + fixture.Advance(TimeSpan.FromSeconds(1)); + fixture.ReleaseReadResult.TrySetResult(); + await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + fixture.Published.Task.IsCompleted.ShouldBeFalse("missing observation must not reset age at response handoff"); + } + finally { fixture.ReleaseReadResult.TrySetResult(); demand?.Dispose(); } + } + + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Delayed_unary_result_cannot_reanchor_an_expired_sample() + { + var ct = TestContext.Current.CancellationToken; + using var fixture = new AccessFixture(readOnly: true) { BlockReadReturn = true }; + fixture.Proof = fixture.Proof with { MaximumSampleAge = TimeSpan.FromMilliseconds(500) }; + fixture.Publish(7); + using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue(); + try + { + access.ScheduleRead(demand!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue(); + await fixture.ReadResultHeld.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + fixture.Advance(TimeSpan.FromSeconds(1)); + fixture.ReleaseReadResult.TrySetResult(); + await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + fixture.Published.Task.IsCompleted.ShouldBeFalse("the finite age must include the held response interval"); + } + finally { fixture.ReleaseReadResult.TrySetResult(); demand?.Dispose(); } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedReconnectLifetimeTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedReconnectLifetimeTests.cs new file mode 100644 index 000000000..11ae900bb --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedReconnectLifetimeTests.cs @@ -0,0 +1,151 @@ +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; + +public sealed partial class GrpcDataProjectedAccessTests +{ + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task New_cadence_accepts_equal_version_baseline_when_cached_evidence_has_expired() + { + using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { ScalarSnapshots = true }; + fixture.Proof = fixture.Proof with { MaximumSampleAge = TimeSpan.FromMilliseconds(500) }; + using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var first).ShouldBeTrue(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var second).ShouldBeTrue(); + try + { + access.StartSubscription(first!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + var original = await fixture.ReadUpdateAsync(); + original.SourceVersion.ShouldBe(1); + fixture.Advance(TimeSpan.FromSeconds(1)); + access.StartSubscription(second!, TimeSpan.FromSeconds(2)).ShouldBeTrue(); + var fresh = await fixture.ReadUpdateAsync(); + fresh.SourceVersion.ShouldBe(1); + fresh.IsCompleteSnapshot.ShouldBeTrue(); + fresh.ReceivedTimestamp.ShouldNotBe(original.ReceivedTimestamp); + fresh.OriginAgeBounds.Advance(fixture.Clock.GetElapsedTime(fresh.ReceivedTimestamp, fixture.Clock.GetTimestamp())) + .IsFresh(TimeSpan.FromMilliseconds(500)).ShouldBeTrue(); + } + finally { first?.Dispose(); second?.Dispose(); } + } + + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Pending_second_open_cannot_preserve_or_revive_the_last_proven_source_era() + { + using var fixture = new AccessFixture(streams: true, subscribeOnly: true) + { ScalarSnapshots = true, HoldSecondOpen = true, BlockStreamDispose = true }; + using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var first).ShouldBeTrue(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var second).ShouldBeTrue(); + try + { + access.StartSubscription(first!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + var original = await fixture.ReadUpdateAsync(); + original.SourceProof.IsValid.ShouldBeTrue(); + access.StartSubscription(second!, TimeSpan.FromSeconds(2)).ShouldBeTrue(); + await fixture.SecondOpenEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.EndFirstStream(); + await fixture.StreamDisposeEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + original.SourceProof.IsValid.ShouldBeFalse("a pending Open has not established source coverage"); + fixture.ReleaseSecondOpen.TrySetResult(); + var fresh = await fixture.ReadUpdateAsync(); + fresh.IsCompleteSnapshot.ShouldBeTrue(); + fresh.SourceProof.IsValid.ShouldBeTrue(); + original.SourceProof.IsValid.ShouldBeFalse("a later baseline cannot revive old queued evidence"); + } + finally + { + fixture.ReleaseSecondOpen.TrySetResult(); fixture.ReleaseStreamDispose.TrySetResult(); + first?.Dispose(); second?.Dispose(); + } + } + + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Removing_last_source_handle_closes_its_coverage_even_when_cohort_has_another_source() + { + using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { ScalarSnapshots = true, BlockStreamDispose = true }; + using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var first).ShouldBeTrue(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var second).ShouldBeTrue(); + access.TryAcquire(fixture.SecondNodeId, fixture.Caller, DataOperations.Subscribe, out var otherSource).ShouldBeTrue(); + try + { + access.StartSubscription(first!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + var original = await fixture.ReadUpdateAsync(); + access.StartSubscription(second!, TimeSpan.FromSeconds(2)).ShouldBeTrue(); + access.StartSubscription(otherSource!, TimeSpan.FromSeconds(2)).ShouldBeTrue(); + await fixture.TwoStreamItems.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var secondId = fixture.StreamCommands.OfType().Single(x => + x.Items[0].Settings.PublishingInterval == TimeSpan.FromSeconds(2)).Items[0].ClientItemId; + var otherId = fixture.StreamCommands.OfType().Single().Items[0].ClientItemId; + fixture.EmitValue(secondId, 2, 8); + ProjectedValueUpdate observed; + do { observed = await fixture.ReadUpdateAsync(); } while (!Equals(observed.Snapshot.Value, 8)); + await access.DisposeConfiguredAsync(second!); + original.SourceProof.IsValid.ShouldBeTrue("the first source stream is still alive"); + fixture.EndFirstStream(); + await fixture.StreamDisposeEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + original.SourceProof.IsValid.ShouldBeFalse("the other open cohort now owns only a different source"); + fixture.EmitValue(otherId, 2, 99); + var stillLive = await fixture.ReadUpdateAsync(); + stillLive.Snapshot.Value.ShouldBe(99); + stillLive.Route.LocalIdentifier.ShouldBe(fixture.SecondProof!.LocalIdentifier); + } + finally { fixture.ReleaseStreamDispose.TrySetResult(); first?.Dispose(); second?.Dispose(); otherSource?.Dispose(); } + } + + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Reconnect_waits_for_uncancellable_physical_dispose_and_cancelled_demand_never_reopens() + { + using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { ScalarSnapshots = true, BlockStreamDispose = true }; + using var access = fixture.Create(maxDemands: 1); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var demand).ShouldBeTrue(); + try + { + access.StartSubscription(demand!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + var original = await fixture.ReadUpdateAsync(); + original.IsCompleteSnapshot.ShouldBeTrue(); + fixture.EndFirstStream(); + await fixture.StreamDisposeEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + original.SourceProof.IsValid.ShouldBeFalse("a lost attempt cannot keep queued evidence authoritative"); + demand!.Dispose(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var blocked).ShouldBeFalse( + "physical ownership remains charged until ignored-cancellation disposal completes"); + blocked.ShouldBeNull(); + await Task.Delay(300, TestContext.Current.CancellationToken); + fixture.StreamOpens.ShouldBe(1, "a second physical stream cannot overlap the undrained first stream"); + fixture.ReleaseStreamDispose.TrySetResult(); + await fixture.NoPins.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + await Task.Delay(300, TestContext.Current.CancellationToken); + fixture.StreamOpens.ShouldBe(1, "disposed interest must never be reacquired"); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var replacement).ShouldBeTrue(); + replacement!.Dispose(); + } + finally { fixture.ReleaseStreamDispose.TrySetResult(); demand?.Dispose(); } + } + + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Revoked_mapping_during_retry_does_not_reopen_or_revive_old_evidence() + { + using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { ScalarSnapshots = true, BlockStreamDispose = true }; + using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var demand).ShouldBeTrue(); + try + { + access.StartSubscription(demand!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + var original = await fixture.ReadUpdateAsync(); + fixture.EndFirstStream(); + await fixture.StreamDisposeEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.InvalidateMapping(); + fixture.ReleaseStreamDispose.TrySetResult(); + await Task.Delay(500, TestContext.Current.CancellationToken); + fixture.StreamOpens.ShouldBe(1); + original.SourceProof.IsValid.ShouldBeFalse(); + demand!.IsValid.ShouldBeFalse(); + } + finally { fixture.ReleaseStreamDispose.TrySetResult(); demand?.Dispose(); } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedRetryJitterTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedRetryJitterTests.cs new file mode 100644 index 000000000..77916cedf --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedRetryJitterTests.cs @@ -0,0 +1,40 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataProjectedAccessTests +{ + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Concurrent_cohort_retries_use_independently_sampled_delays() + { + var ct = TestContext.Current.CancellationToken; + using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { ScalarSnapshots = true }; + using var access = fixture.Create(); + var calls = 0; + var sampledBoth = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + access.RetryJitterForTests = _ => + { + var call = Interlocked.Increment(ref calls); + if (call == 2) sampledBoth.TrySetResult(); + return call == 1 ? TimeSpan.FromMilliseconds(20) : TimeSpan.FromSeconds(2); + }; + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var first).ShouldBeTrue(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var second).ShouldBeTrue(); + try + { + access.StartSubscription(first!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + access.StartSubscription(second!, TimeSpan.FromSeconds(2)).ShouldBeTrue(); + await fixture.SecondStreamOpened.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + SpinWait.SpinUntil(() => fixture.StreamHandles.Count == 2, TimeSpan.FromSeconds(5)).ShouldBeTrue(); + fixture.EndAllStreams(); + await sampledBoth.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + SpinWait.SpinUntil(() => Volatile.Read(ref fixture.StreamOpens) >= 3, TimeSpan.FromSeconds(5)).ShouldBeTrue(); + await Task.Delay(200, ct); + Volatile.Read(ref fixture.StreamOpens).ShouldBe(3, "the later sampled retry must remain independently delayed"); + Volatile.Read(ref calls).ShouldBe(2); + } + finally { first?.Dispose(); second?.Dispose(); } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedStreamReconnectWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedStreamReconnectWireTests.cs new file mode 100644 index 000000000..abadc0c27 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedStreamReconnectWireTests.cs @@ -0,0 +1,324 @@ +using System.Threading.Channels; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Existing_sdk_item_rebinds_to_verified_new_primary_without_reusing_old_evidence() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? first = null, second = null; + var firstSubscriptions = new FakeSubscriptions(() => first!.Serving); + var secondSubscriptions = new FakeSubscriptions(() => second!.Serving); + using var originA = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => firstSubscriptions); + first = originA; firstSubscriptions.SampleClock = originA.Clock; + using var originB = new LocalDataFixture(servingGeneration: 2, targetSubscriptions: (_, _) => secondSubscriptions, + clock: originA.Clock, servingNode: "node-b", servingIncarnation: "serving-2"); + second = originB; secondSubscriptions.SampleClock = originB.Clock; + secondSubscriptions.SnapshotValue = 8; secondSubscriptions.SnapshotVersion = 1; + var connections = new SwitchableConnections(originA); + var published = Channel.CreateUnbounded(); + await WithComposedServer(originA, originA.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var subscriptionId = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscriptionId, anchor, 1, 100, ct); + var oldStream = await firstSubscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var old = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct); + var initial = await PublishComposedNotification(client, 1, ct); + initial.Value.StatusCode.ShouldBe(StatusCodes.Good); + connections.SetCurrent(originB); + await oldStream.DisposeAsync(); + var next = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct); + next.Route.Serving.ShouldBe(originB.Serving); + next.SourceProof.IsValid.ShouldBeTrue(); + old.SourceProof.IsValid.ShouldBeFalse(); + var value = await PublishComposedValue(client, 1, ct); + value.StatusCode.ShouldBe(StatusCodes.Good); + value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8); + var replay = await client.RepublishAsync(new RequestHeader(), subscriptionId, initial.Sequence, ct); + StatusCode.IsGood(ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode).ShouldBeFalse(); + }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections); + } + + private sealed class SwitchableConnections(LocalDataFixture initial) : IGrpcDataAdapterConnectionSource + { + private LocalDataFixture _current = initial; + internal void SetCurrent(LocalDataFixture current) => Volatile.Write(ref _current, current); + public ValueTask AcquireAsync(string id, CancellationToken ct) => + ValueTask.FromResult(id == "link" ? new Lease(new ClusterConnection(Volatile.Read(ref _current).Connection())) : null); + private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease + { + public IDataConnection Connection => connection; + public CancellationToken CancellationToken => CancellationToken.None; + public ValueTask DisposeAsync() => connection.DisposeAsync(); + } + private sealed class ClusterConnection(IDataConnection inner) : IDataConnection + { + public DataTarget Target => new(DataTargetMode.Cluster, "cluster", null); + public TimeProvider Clock => inner.Clock; + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken ct) => inner.GetCapabilitiesAsync(budget, ct); + public Task BrowseAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest request, CancellationToken ct) => inner.BrowseAsync(request, ct); + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken ct) => inner.GetMetadataAsync(request, ct); + public Task> ReadAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest request, CancellationToken ct) => inner.ReadAsync(request, ct); + public Task> WriteAsync(WriteBatch request, CancellationToken ct) => inner.WriteAsync(request, ct); + public Task SubscribeAsync(CancellationToken ct) => inner.SubscribeAsync(ct); + public ValueTask DisposeAsync() => inner.DisposeAsync(); + } + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Subscribe_only_sdk_caller_renews_exact_node_without_browse_read_or_extra_subscription() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + await WithComposedServer(origin, origin.Raw, async (session, sink, resolver, applier, access, placements, anchor) => + { + // Deployment-owned discovery materializes the node before the restricted session + // subscribes; it is fully disposed before the caller's monitored item is created. + var discovery = new ConfiguredProjectionDiscovery(placements, resolver, applier, sink, access, + new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8); + var configured = await discovery.ResolveAsync(Reference("map", DataRealm.Raw, origin.Raw.Address), ct); + configured.ShouldNotBeNull(); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + await configured.DisposeAsync(); + await subscriptions.Closed.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + while (published.Reader.TryRead(out _)) { } + var client = (SessionClient)session; + var deniedBrowse = await client.BrowseAsync(new RequestHeader(), null, 10, [new BrowseDescription + { + NodeId = anchor, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences, + IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All + }], ct); + StatusCode.IsGood(deniedBrowse.Results[0].StatusCode).ShouldBeFalse(); + var deniedRead = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Neither, + [new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], ct); + deniedRead.Results[0].StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied); + var subscriptionId = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscriptionId, anchor, 1, 100, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + subscriptions.Opens.ShouldBe(2); + subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8; + origin.Clock.Advance(TimeSpan.FromSeconds(16)); + var update = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct); + update.SourceProof.IsValid.ShouldBeTrue(); + subscriptions.Opens.ShouldBe(3, "exact metadata renewal must not create another physical subscription"); + (await PublishComposedValue(client, 1, ct)).WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8); + }, onPublished: update => published.Writer.TryWrite(update), localPermissions: 4); + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Quiet_live_stream_renews_expired_metadata_without_client_browse_or_forced_close() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var subscriptionId = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscriptionId, anchor, 1, 100, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var old = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8; + origin.Clock.Advance(TimeSpan.FromSeconds(16)); + old.SourceProof.IsValid.ShouldBeFalse(); + // The peer stream is still open: the owned maintenance timer must initiate renewal. + await subscriptions.Closed.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var renewed = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct); + renewed.SourceProof.IsValid.ShouldBeTrue(); + var value = await PublishComposedValue(client, 1, ct); + value.StatusCode.ShouldBe(StatusCodes.Good); + value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8); + }, onPublished: update => published.Writer.TryWrite(update)); + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Existing_sdk_item_stays_denied_during_deployment_and_recovers_after_compatible_authority_returns() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + LocalCatalogCoordinator? coordinator = null; + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, placements, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var subscriptionId = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscriptionId, anchor, 1, 100, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct); + var initial = await PublishComposedNotification(client, 1, ct); + initial.Value.StatusCode.ShouldBe(StatusCodes.Good); + + var replacement = Prepare(coordinator!); // Suspends authority before completing the compatible deployment. + original.SourceProof.IsValid.ShouldBeFalse(); + try + { + var replay = await client.RepublishAsync(new RequestHeader(), subscriptionId, initial.Sequence, ct); + StatusCode.IsGood(ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode).ShouldBeFalse(); + } + catch (ServiceResultException error) { StatusCode.IsBad(error.StatusCode).ShouldBeTrue(); } + var mapping = Mapping(origin.Raw); + mapping.AllowedOperations |= DataOperations.Read | DataOperations.Metadata; + placements.Stage(replacement, [mapping], [Connection()]); + coordinator!.Complete(replacement, true).ShouldBeTrue(); + subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8; + origin.Clock.Advance(TimeSpan.FromSeconds(5)); + var recovered = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct); + recovered.SourceProof.IsValid.ShouldBeTrue(); + original.SourceProof.IsValid.ShouldBeFalse("the previous authority evidence must not revive"); + var value = await PublishComposedValue(client, 1, ct); + value.StatusCode.ShouldBe(StatusCodes.Good); + value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8); + }, onPublished: update => published.Writer.TryWrite(update), onCoordinator: value => coordinator = value); + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Metadata_retry_recovers_after_cache_commit_loses_the_sdk_guard_race() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + var forced = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var subscriptionId = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscriptionId, anchor, 1, 100, ct); + var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + origin.Clock.Advance(TimeSpan.FromSeconds(16)); + subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8; + await stream.DisposeAsync(); + await forced.Task.WaitAsync(TimeSpan.FromSeconds(10), ct); + var update = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct); + update.SourceProof.IsValid.ShouldBeTrue(); + var value = await PublishComposedValue(client, 1, ct); + value.StatusCode.ShouldBe(StatusCodes.Good); + value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8); + }, onPublished: update => published.Writer.TryWrite(update), + renewalSinkFactory: inner => new ExpiringCommitSink(inner, () => + { + origin.Clock.Advance(TimeSpan.FromSeconds(16)); + forced.TrySetResult(); + })); + } + + private sealed class ExpiringCommitSink(IProjectedNamespacePageSink inner, Action afterCommit) : IProjectedNamespacePageSink + { + private int _forced; + public bool TryApply(NodeId parent, IReadOnlyList nodes, Func commit) => inner.TryApply(parent, nodes, commit); + public bool TryRemove(NodeId node, ProjectedVariableDefinition expected) => inner.TryRemove(node, expected); + public bool TryApplyRootLeaf(NodeId node, ProjectedVariableDefinition definition, Func commit) => inner.TryApplyRootLeaf(node, definition, commit); + public bool TryRenewExact(NodeId node, ProjectedVariableDefinition expected, ProjectedVariableDefinition replacement, Func commit) => + inner.TryRenewExact(node, expected, replacement, () => + { + var accepted = commit(); + if (accepted && Interlocked.Exchange(ref _forced, 1) == 0) afterCommit(); + return accepted; + }); + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Existing_sdk_monitored_item_renews_expired_metadata_without_another_client_browse() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; + subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, access, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); // Initial discovery only; no browse after expiry. + var subscriptionId = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscriptionId, anchor, 1, 100, ct); + var firstStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + origin.Clock.Advance(TimeSpan.FromSeconds(16)); // The configured metadata lease lasts at most 15 seconds. + original.SourceProof.IsValid.ShouldBeFalse(); + subscriptions.SnapshotVersion = 2; + subscriptions.SnapshotValue = 8; + await firstStream.DisposeAsync(); + var renewed = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct); + renewed.SourceProof.IsValid.ShouldBeTrue(); + access.HasLiveDemand(DataRealm.Raw, renewed.Route.LocalIdentifier).ShouldBeTrue(); + var notification = await PublishComposedValue(client, 1, ct); + notification.StatusCode.ShouldBe(StatusCodes.Good); + notification.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8); + }, onPublished: update => published.Writer.TryWrite(update)); + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Existing_sdk_monitored_item_recovers_after_upstream_stream_ends() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; + subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, access, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + ((IProjectedNodeLookup)sink).TryResolve(anchor, out var definition).ShouldBeTrue(); + var subscriptionId = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscriptionId, anchor, 1, 100, ct); + var firstStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct); + var first = await PublishComposedNotification(client, 1, ct); + first.Value.StatusCode.ShouldBe(StatusCodes.Good); + first.Value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(7); + + subscriptions.SnapshotVersion = 2; + subscriptions.SnapshotValue = 8; + await firstStream.DisposeAsync(); // Model an upstream session lifetime ending while the SDK item stays alive. + var next = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + next.ShouldNotBeSameAs(firstStream); + var recovered = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct); + recovered.SourceProof.IsValid.ShouldBeTrue(); + access.HasLiveDemand(DataRealm.Raw, definition!.LocalIdentifier).ShouldBeTrue(); + subscriptions.Opens.ShouldBe(2); + var second = await PublishComposedValue(client, 1, ct); + second.StatusCode.ShouldBe(StatusCodes.Good); + second.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8); + var oldReplay = await client.RepublishAsync(new RequestHeader(), subscriptionId, first.Sequence, ct); + StatusCode.IsGood(ComposedChanges(oldReplay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode) + .ShouldBeFalse("a new attempt must not revive a notification from the old source era"); + }, onPublished: update => published.Writer.TryWrite(update)); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedWriteAdmissionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedWriteAdmissionTests.cs new file mode 100644 index 000000000..37d75d373 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedWriteAdmissionTests.cs @@ -0,0 +1,76 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataProjectedAccessTests +{ + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Full_write_quota_rejects_large_array_without_encoding_and_restores_capacity_after_completion() + { + using var fixture = new AccessFixture(writable: true, array: true) { BlockWrite = true }; + MakeArrayLengthVariable(fixture); + using var access = fixture.Create(maxBytes: 4 * 1024 * 1024); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var first).ShouldBeTrue(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var second).ShouldBeTrue(); + var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024); + // Fits the conservative post-fix encoding bound; rejection must come from the full quota. + var large = new int[20_000]; + try + { + var pending = access.WriteAsync(first!, new[] { 1, 2, 3 }, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken); + await fixture.WriteEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var before = GC.GetAllocatedBytesForCurrentThread(); + var rejected = access.WriteAsync(second!, large, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken); + rejected.IsCompleted.ShouldBeTrue("full quota must be rejected synchronously"); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + (await rejected).State.ShouldBe(DataWriteState.RejectedBeforeDispatch); + allocated.ShouldBeLessThan(128 * 1024L, "a quota-rejected array must not be boxed or copied"); + fixture.WriteCalls.ShouldBe(1); + + fixture.ReleaseWrite.TrySetResult(); + (await pending.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.OutcomeUnknown); + var deadline = DateTime.UtcNow.AddSeconds(5); + DataWriteOutcome result; + do + { + result = await access.WriteAsync(second!, new[] { 4, 5, 6 }, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken); + if (result.State != DataWriteState.RejectedBeforeDispatch) break; + await Task.Delay(10, TestContext.Current.CancellationToken); + } while (DateTime.UtcNow < deadline); + result.State.ShouldBe(DataWriteState.OutcomeUnknown); + fixture.WriteCalls.ShouldBe(2); + } + finally { fixture.ReleaseWrite.TrySetResult(); first?.Dispose(); second?.Dispose(); } + } + + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Oversized_array_is_rejected_without_encoding_or_dispatch() + { + using var fixture = new AccessFixture(writable: true, array: true); + MakeArrayLengthVariable(fixture); + using var access = fixture.Create(maxBytes: 1024); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var demand).ShouldBeTrue(); + var large = new int[60_000]; + try + { + var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024); + var before = GC.GetAllocatedBytesForCurrentThread(); + var rejected = access.WriteAsync(demand!, large, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken); + rejected.IsCompleted.ShouldBeTrue(); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + (await rejected).State.ShouldBe(DataWriteState.RejectedBeforeDispatch); + allocated.ShouldBeLessThan(128 * 1024L, "an oversized array must be rejected before boxing or copying"); + fixture.WriteCalls.ShouldBe(0); + } + finally { demand?.Dispose(); } + } + + private static void MakeArrayLengthVariable(AccessFixture fixture) + { + var metadata = fixture.Proof.Metadata with { Dimensions = [0] }; + fixture.Proof = fixture.Proof with { Metadata = metadata, OriginMetadata = fixture.Proof.OriginMetadata with { Dimensions = [0] } }; + fixture.Definition = fixture.Definition with { Metadata = metadata }; + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedWriteDeadlineTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedWriteDeadlineTests.cs new file mode 100644 index 000000000..f5146afa8 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedWriteDeadlineTests.cs @@ -0,0 +1,75 @@ +using Opc.Ua; +using Opc.Ua.Client; +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; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Theory(Timeout = 90000)] + [InlineData(30000u, true)] + [InlineData(5000u, false)] + public async Task Sdk_projected_write_honors_caller_deadline_and_default_origin_dispatch_bound(uint timeoutHint, bool shouldDispatch) + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + var route = new DefaultBoundRecordingRoute(); + DataWriteExecutor? executor = null; + using var origin = new LocalDataFixture(servingGeneration: 1, + targetSubscriptions: (_, _) => subscriptions, writes: _ => executor!); + peer = origin; + route.View = origin.Raw; + var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000, + TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1)); + var capabilities = new DataCapabilitiesProvider("cluster", () => origin.Serving, () => true, limits); + var policy = new DataOperationPolicy(origin.Authority, new TriePermissionEvaluator(origin.Authority.Tries, origin.Clock), origin.Clock); + executor = new DataWriteExecutor(origin.Context, () => origin.Catalog, policy, capabilities, route, + new WriteOperationRegistry(origin.Serving.Incarnation, 16, 16_384, TimeSpan.FromMinutes(1), origin.Clock), + new WriteValueBudget(16_384), origin.Clock, DriverWriteBounds.Default); + + await WithComposedServer(origin, origin.Raw, async (session, sink, resolver, applier, access, placements, anchor) => + { + var discovery = new ConfiguredProjectionDiscovery(placements, resolver, applier, sink, access, + new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8); + await using var lease = await discovery.ResolveAsync(Reference("map", DataRealm.Raw, origin.Raw.Address), ct); + lease.ShouldNotBeNull(); + await subscriptions.Opened.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var response = await ((SessionClient)session).WriteAsync(new RequestHeader { TimeoutHint = timeoutHint }, + [new WriteValue { NodeId = anchor, AttributeId = Attributes.Value, + Value = new Opc.Ua.DataValue(new Variant(77), StatusCodes.Good) }], ct); + var status = response.Results.ToArray()!.ShouldHaveSingleItem(); + if (shouldDispatch) status.ShouldBe(StatusCodes.Good); + else StatusCode.IsBad(status).ShouldBeTrue(); + route.Dispatches.ShouldBe(shouldDispatch ? 1 : 0); + }, maxUnaryBytes: 1024 * 1024, allowWrite: true); + } + + private sealed class DefaultBoundRecordingRoute : IDataWriteRoute + { + public DataView View { get; set; } = null!; + public int Dispatches; + private readonly LateWriteObserver _observer = new(16, TimeSpan.FromMinutes(1)); + public bool TryResolve(DataView requested, out WriteRouteTarget? target) + { + target = requested == View ? new("driver", "Plant/Driver/Device/Speed", "driver-incarnation", 1, 1) : null; + return target is not null; + } + public Task DispatchAsync(WriteAdmissionTicket ticket, WriteClaim claim, CancellationToken cancellationToken) + { + _observer.TryReserve(out var reservation).ShouldBeTrue(); + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + reservation.ShouldNotBeNull().Observe(completion.Task, claim, ticket); + Interlocked.Increment(ref Dispatches); + claim.TryMarkDispatched().ShouldBeTrue(); + var outcome = new DataWriteOutcome(DataWriteState.DriverConfirmedSuccess, 0, null); + completion.TrySetResult(outcome); + return Task.FromResult(outcome); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectionValidityDiagnosticsTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectionValidityDiagnosticsTests.cs new file mode 100644 index 000000000..9308104b0 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectionValidityDiagnosticsTests.cs @@ -0,0 +1,115 @@ +using System.Reflection; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Feature", "GrpcData"), Trait("Category", "Unit")] +[Trait("Phase", "P11")] +public sealed class GrpcDataProjectionValidityDiagnosticsTests +{ + [Theory] + [InlineData("route", "RouteAlive")] + [InlineData("local", "LocalAuthorityActive")] + [InlineData("remote", "RemoteLeaseValid")] + [InlineData("binding", "MappingBindingCurrent")] + [InlineData("generation", "CacheGenerationCurrent")] + public void Diagnostics_report_the_independent_failed_fence_without_granting_authority(string failure, string failedFlag) + { + var clock = new ManualTimeProvider(); + var cache = new ProjectedCatalogCache(4, 4, clock); + var generation = cache.CaptureGeneration("mapping"); + var serving = new ServingIdentity("node", "incarnation", "Primary", 1, 1); + var remote = new MetadataAuthorityLease(serving, new MetadataLease(1, 1, TimeSpan.FromSeconds(15)), + clock.GetTimestamp(), TimeSpan.FromSeconds(15), TimeSpan.Zero, clock); + var local = new TestAuthority(); + using var route = new CancellationTokenSource(); + var bindingCurrent = true; + var lease = new BoundProjectionLease(remote, route.Token, local, cache, "mapping", generation, () => bindingCurrent); + lease.IsValid.ShouldBeTrue(); + switch (failure) + { + case "route": route.Cancel(); break; + case "local": local.Active = false; break; + case "remote": clock.Advance(TimeSpan.FromSeconds(15)); break; + case "binding": bindingCurrent = false; break; + case "generation": + cache.MarkUnavailable("mapping", new DataView(new DataAddress("origin", "urn:raw", "string", "p"), DataRealm.Raw, "mapping", 1, "p")); + break; + default: throw new InvalidOperationException(); + } + lease.IsValid.ShouldBeFalse(); + var capture = typeof(BoundProjectionLease).GetMethod("CaptureDiagnostics", BindingFlags.Instance | BindingFlags.NonPublic); + capture.ShouldNotBeNull("the bounded diagnostic must expose each validity fence independently"); + var result = capture!.Invoke(lease, null).ShouldNotBeNull(); + foreach (var flag in new[] { "RouteAlive", "LocalAuthorityActive", "RemoteLeaseValid", "MappingBindingCurrent", "CacheGenerationCurrent" }) + ((bool)result.GetType().GetProperty(flag)!.GetValue(result)!).ShouldBe(flag != failedFlag, flag); + lease.IsValid.ShouldBeFalse("observing a failed fence must never renew or grant authority"); + } + + private sealed class TestAuthority : IDataMappedCatalogAuthority + { + public long CatalogEpoch => 1; + public long AuthorityEpoch => 1; + public bool Active = true; + public bool IsActive => Active; + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Retained_cache_observation_reports_only_fixed_flags_and_never_grants_an_expired_proof(bool bound) + { + using var fixture = new LocalDataFixture(); + var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); + var cache = new ProjectedCatalogCache(4, 4, fixture.Clock, policy); + var generation = cache.CaptureGeneration("mapping"); + var view = new DataView(new DataAddress("origin", "urn:raw", "string", "plant"), DataRealm.Raw, "mapping", 1, "local/anchor"); + var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); + var request = new ProjectedBrowseRequest("mapping", view, null, null, caller, + new DataBudget(TimeSpan.FromSeconds(3), 20, 10000), fixture.Clock.GetTimestamp()); + var local = fixture.Activation.CaptureAuthority(); + var serving = fixture.Serving with { ServingGeneration = 1 }; + var remote = new MetadataAuthorityLease(serving, new MetadataLease(1, 1, TimeSpan.FromSeconds(15)), + fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(15), TimeSpan.Zero, fixture.Clock); + IDataAuthorizationLease lease = bound ? new BoundProjectionLease(remote, CancellationToken.None, local, cache, + "mapping", generation, () => true) : remote; + var scope = new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant"] }; + var subject = new MappedNamespaceSubject(view, scope, ["folder"], serving, DataOperations.Browse); + var resolver = new MappedSubjectResolver([subject], serving.CatalogEpoch, local); + var metadata = new DataMetadata(view, "branch", "Folder", DataValueKind.Null, -1, [], false, + DataOperations.Browse, 1, null, null, false, Serving: serving); + var origin = metadata with { View = view with { MappingId = null, MappingRevision = 0, Subject = "origin/plant" } }; + var proof = new ProjectedNodeProof(ProjectedDataIds.Identifier("mapping", view.Address), metadata, subject, resolver, lease, generation, origin); + cache.TryPublish(request, new(ProjectionPageStatus.Ready, [proof], true, null, generation, lease, local, proof)).ShouldBeTrue(); + cache.TryPinProjected(DataRealm.Raw, proof.LocalIdentifier, out var pin).ShouldBeTrue(); + try + { + var capture = typeof(ProjectedCatalogCache).GetMethod("CaptureRetainedDiagnostics", BindingFlags.Instance | BindingFlags.NonPublic).ShouldNotBeNull(); + object Observe() => capture.Invoke(cache, [DataRealm.Raw, proof.LocalIdentifier]).ShouldNotBeNull(); + object? Field(object result, string name) => result.GetType().GetProperty(name)!.GetValue(result); + var before = Observe(); + Field(before, "Retained").ShouldBe(true); + Field(before, "Retired").ShouldBe(false); + Field(before, "RemoteLeaseValid").ShouldBe(bound ? (bool?)true : null); + before.GetType().GetProperties().Select(x => x.Name).Order().ShouldBe(new[] + { "CacheGenerationCurrent", "Generation", "LocalAuthorityActive", "MappingBindingCurrent", "RemoteLeaseValid", "Retained", "Retired", "RouteAlive" }); + fixture.Clock.Advance(TimeSpan.FromSeconds(15)); + cache.TryResolveProjected(DataRealm.Raw, proof.LocalIdentifier, out _).ShouldBeFalse(); + var expired = Observe(); + Field(expired, "Retained").ShouldBe(true); + Field(expired, "RemoteLeaseValid").ShouldBe(bound ? (bool?)false : null); + cache.MarkUnavailable("mapping", view); + var retired = Observe(); + Field(retired, "Retained").ShouldBe(true); + Field(retired, "Retired").ShouldBe(true); + Field(retired, "CacheGenerationCurrent").ShouldBe(bound ? (bool?)false : null); + cache.TryResolveProjected(DataRealm.Raw, proof.LocalIdentifier, out _).ShouldBeFalse(); + } + finally { pin!.Dispose(); } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataRootMountWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataRootMountWireTests.cs new file mode 100644 index 000000000..54d6c53c3 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataRootMountWireTests.cs @@ -0,0 +1,30 @@ +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Theory(Timeout = 90000)] + [InlineData(DataRealm.Raw)] + [InlineData(DataRealm.Uns)] + public async Task Cluster_parent_mount_is_browsable_from_the_native_realm_root(DataRealm realm) + { + using var origin = new LocalDataFixture(servingGeneration: 1, nestedCatalog: true, nestedUnsCatalog: true); + var root = realm == DataRealm.Raw ? origin.Root : origin.Uns with { Address = origin.Uns.Address with { Identifier = "Area" }, Subject = "Area" }; + await WithComposedServer(origin, root, async (session, _, _, _, _, _, anchor) => + { + // Both native realm trees hang beneath the SDK shared root in its Raw namespace. + var uri = V3NodeIds.RawNamespaceUri; + var localRoot = new NodeId(V3NodeIds.SharedRootFolderId, checked((ushort)session.NamespaceUris.GetIndex(uri))); + var references = await BrowseAll((SessionClient)session, localRoot, 10); + references.ShouldContain(x => ExpandedNodeId.ToNodeId(x.NodeId, session.NamespaceUris) == anchor); + var children = await BrowseAll((SessionClient)session, anchor, 10); + children.ShouldNotBeEmpty(); + }, mountAtRealmRoot: true); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkBadQualityEvidenceTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkBadQualityEvidenceTests.cs new file mode 100644 index 000000000..8dfa10423 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkBadQualityEvidenceTests.cs @@ -0,0 +1,220 @@ +using System.Reflection; +using System.Threading.Channels; +using Microsoft.Extensions.Logging.Abstractions; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Theory(Timeout = 90000), Trait("Phase", "P11Renewal")] + [InlineData("ambiguous")] + [InlineData("missing_timestamp")] + [InlineData("different_timestamp")] + [InlineData("different_status")] + [InlineData("expired_proof")] + public async Task Bad_null_sdk_notification_cannot_borrow_unproven_sample_evidence(string scenario) + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; + subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscription, anchor, 1, 100, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var source = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + await client.SetPublishingModeAsync(new RequestHeader(), false, [subscription], ct); + + var witness = new RenewableTestWitness(source.SourceProof); + var timestamp = origin.Clock.GetUtcNow().UtcDateTime; + var snapshot = source.Snapshot with { Value = 42, StatusCode = StatusCodes.BadNoCommunication.Code, + SourceTimestampUtc = timestamp, ServerTimestampUtc = timestamp }; + var sample = new ProjectedValueWrite(source.Route.Realm, source.Route.LocalIdentifier, source.Route.ProjectionGeneration, + source.Route.Serving, snapshot, new DataAgeBounds(TimeSpan.Zero, TimeSpan.Zero), origin.Clock.GetTimestamp(), witness, false, 2); + ((IProjectedValueSink)sink).TryPublish([sample]).ShouldBeTrue(); + if (scenario is "ambiguous" or "missing_timestamp") + ((IProjectedValueSink)sink).TryPublish([sample with { Snapshot = snapshot with { Value = 43 }, SourceVersion = 3 }]).ShouldBeTrue(); + + const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; + var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!; + var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!; + var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!; + var item = keys.Cast().OfType().Single(x => x.ClientHandle == 1); + var candidates = (System.Collections.IEnumerable)item.GetType().GetField("_candidates", flags)!.GetValue(item)!; + candidates.Cast().Count().ShouldBe(scenario is "ambiguous" or "missing_timestamp" ? 2 : 1); + item.SetMonitoringMode(MonitoringMode.Disabled); + if (scenario == "different_status") + { + // Keep the proved status and the injected status distinct if the + // SDK samples the node again as publishing resumes. + item.ModifyAttributes(item.DiagnosticsMasks, TimestampsToReturn.Both, item.ClientHandle, + item.Filter, item.Filter, null, 0, 8, false).ShouldBeNull(); + } + item.SetMonitoringMode(MonitoringMode.Reporting); + if (scenario == "expired_proof") witness.Valid = false; + var sourceTime = scenario switch + { + "missing_timestamp" => DateTimeUtc.MinValue, + "different_timestamp" => (DateTimeUtc)timestamp.AddSeconds(1), + _ => (DateTimeUtc)timestamp + }; + var status = scenario == "different_status" ? StatusCodes.BadTimeout : StatusCodes.BadNoCommunication; + // Deliberately inject a notification at the public SDK queue boundary; + // this tests identity fences, not a claim that the SDK creates duplicates. + var queue = typeof(Opc.Ua.Server.MonitoredItem).GetMethods().Single(x => x.Name == "QueueValue" && x.GetParameters().Length == 3); + var injectedServerTime = scenario == "different_status" ? (DateTimeUtc)timestamp.AddSeconds(3) : DateTimeUtc.MinValue; + queue.Invoke(item, [new Opc.Ua.DataValue(Variant.Null, status, sourceTime, injectedServerTime), ServiceResult.Good, true]); + await client.SetPublishingModeAsync(new RequestHeader(), true, [subscription], ct); + if (scenario == "different_status") + { + // The distinct proven sample can arrive before the injected + // notification, including in the same Publish response. + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromSeconds(10)); + var provenSampleSeen = false; + var denialSeen = false; + while (!denialSeen) + { + var response = await client.PublishAsync(new RequestHeader(), default, timeout.Token); + foreach (var change in ComposedChanges(response.NotificationMessage).Where(change => change.ClientHandle == 1)) + { + var value = change.Value; + if (!provenSampleSeen && value.StatusCode == StatusCodes.BadNoCommunication && + value.SourceTimestamp == (DateTimeUtc)timestamp && value.WrappedValue.IsNull) + { + provenSampleSeen = true; + continue; + } + value.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied); + value.WrappedValue.IsNull.ShouldBeTrue(); + if (value.ServerTimestamp == injectedServerTime) denialSeen = true; + } + } + return; + } + var denied = await PublishComposedValue(client, 1, ct); + denied.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied); + denied.WrappedValue.IsNull.ShouldBeTrue(); + }, onPublished: update => published.Writer.TryWrite(update)); + } + + [Theory(Timeout = 90000), Trait("Phase", "P11Renewal")] + [InlineData(TimestampsToReturn.Server, false)] + [InlineData(TimestampsToReturn.Neither, false)] + [InlineData(TimestampsToReturn.Both, true)] + public async Task Single_bad_null_sample_without_source_timestamp_keeps_original_witness( + TimestampsToReturn mode, bool sourceTimestampAbsent) + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; + subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + var created = await client.CreateMonitoredItemsAsync(new RequestHeader(), subscription, mode, + [new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }, + MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters + { ClientHandle = 1, SamplingInterval = 100, QueueSize = 1, DiscardOldest = true, + Filter = new ExtensionObject(new DataChangeFilter { Trigger = Opc.Ua.DataChangeTrigger.StatusValueTimestamp }) } }], ct); + created.Results[0].StatusCode.ShouldBe(StatusCodes.Good); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var source = await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + var witness = new RenewableTestWitness(source.SourceProof); + var now = origin.Clock.GetUtcNow().UtcDateTime; + var snapshot = source.Snapshot with { Value = 42, StatusCode = StatusCodes.BadNoCommunication.Code, + SourceTimestampUtc = sourceTimestampAbsent ? null : now, ServerTimestampUtc = now }; + var sample = new ProjectedValueWrite(source.Route.Realm, source.Route.LocalIdentifier, source.Route.ProjectionGeneration, + source.Route.Serving, snapshot, new DataAgeBounds(TimeSpan.Zero, TimeSpan.Zero), origin.Clock.GetTimestamp(), witness, false, 2); + ((IProjectedValueSink)sink).TryPublish([sample]).ShouldBeTrue(); + var delivered = await PublishComposedNotification(client, 1, ct); + delivered.Value.StatusCode.ShouldBe(StatusCodes.BadNoCommunication); + delivered.Value.WrappedValue.IsNull.ShouldBeTrue(); + witness.Valid = false; + var replay = await client.RepublishAsync(new RequestHeader(), subscription, delivered.Sequence, ct); + var replayed = ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value; + replayed.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied); + replayed.WrappedValue.IsNull.ShouldBeTrue(); + }, onPublished: update => published.Writer.TryWrite(update)); + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Renewal")] + public async Task Bad_source_snapshot_retains_matching_evidence_at_the_sdk_notification_boundary() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; + subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + var connections = new RenewalConnections(origin) { BadFirstRenewalSnapshot = true }; + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscription, anchor, 1, 100, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + await client.SetPublishingModeAsync(new RequestHeader(), false, [subscription], ct); + + const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; + var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!; + var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!; + var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!; + var item = keys.Cast().OfType().Single(x => x.ClientHandle == 1); + item.ModifyAttributes(item.DiagnosticsMasks, TimestampsToReturn.Both, item.ClientHandle, + item.Filter, item.Filter, null, 0, 1, true).ShouldBeNull(); + + subscriptions.SnapshotVersion = 2; + subscriptions.SnapshotValue = 8; + origin.Clock.Advance(TimeSpan.FromSeconds(9)); + var next = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.SourceVersion == 2, ct); + next.SourceProof.IsValid.ShouldBeTrue(); + next.Snapshot.StatusCode.ShouldBe(StatusCodes.BadNoCommunication.Code); + var lossPending = item.GetType().GetField("_queuedLoss", flags)!.GetValue(item) is not null; + var candidates = (System.Collections.IEnumerable)item.GetType().GetField("_candidates", flags)!.GetValue(item)!; + var samples = candidates.Cast().Select(candidate => + (ProjectedValueWrite)candidate.GetType().GetProperty("Sample")!.GetValue(candidate)!).ToArray(); + var before = ProjectedDeliveryDiagnostics.Capture(); + var notifications = new Queue(); + var diagnostics = new Queue(); + item.Publish(new Opc.Ua.Server.OperationContext(item), notifications, diagnostics, 1, NullLogger.Instance); + var raw = notifications.ShouldHaveSingleItem().Value; + var after = ProjectedDeliveryDiagnostics.Capture(); + var shape = $"raw status=0x{raw.StatusCode.Code:X8}, null={raw.WrappedValue.IsNull}, " + + $"source={raw.SourceTimestamp}, server={raw.ServerTimestamp}, pending loss={lossPending}, " + + $"candidates={samples.Length}, candidate statuses=[{string.Join(',', samples.Select(s => $"0x{s.Snapshot.StatusCode:X8}"))}], " + + $"source timestamps=[{string.Join(',', samples.Select(s => s.Snapshot.SourceTimestampUtc?.ToString("O") ?? "absent"))}], " + + $"unique={after["CandidateUnique"] - before["CandidateUnique"]}, missing={after["CandidateMissing"] - before["CandidateMissing"]}, " + + $"ambiguous={after["CandidateAmbiguous"] - before["CandidateAmbiguous"]}, " + + $"binding={after["CurrentBindingRejected"] - before["CurrentBindingRejected"]}, " + + $"proof={after["CurrentProofRejected"] - before["CurrentProofRejected"]}, " + + $"marker={after["MarkerAuthorizationRejected"] - before["MarkerAuthorizationRejected"]}"; + (after["CandidateUnique"] - before["CandidateUnique"]).ShouldBe(1, shape); + raw.StatusCode.ShouldBe(StatusCodes.BadNoCommunication); + }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkItemDiagnosticsTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkItemDiagnosticsTests.cs new file mode 100644 index 000000000..d0dc1d335 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkItemDiagnosticsTests.cs @@ -0,0 +1,96 @@ +using System.Collections.Concurrent; +using System.Reflection; +using System.Text.Json; +using GrpcDataNodeProbe; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Fixture_sdk_item_diagnostics_report_live_suppressed_and_retired_states() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; + subscriptions.SampleClock = origin.Clock; + LocalCatalogCoordinator? coordinator = null; + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, sub, anchor, 1, 100, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; + var manager = (OtOpcUaNodeManager)typeof(SdkAddressSpaceSink).GetField("_nodeManager", flags)!.GetValue(sink)!; + var initial = SdkItemDiagnostics.Capture(manager, anchor); + initial.Available.ShouldBeTrue(); + initial.Truncated.ShouldBeFalse(); + initial.ProcessTimestamp.ShouldBeGreaterThan(0); + initial.ProcessFrequency.ShouldBeGreaterThan(0); + var live = initial.Items.ShouldHaveSingleItem(); + live.Retired.ShouldBe(false); live.Suppressed.ShouldBe(false); live.HealthTracked.ShouldBe(true); + live.DemandPresent.ShouldBe(true); live.DemandValid.ShouldBe(true); + live.DefinitionLifetimeActive.ShouldBe(true); live.DefinitionAuthorityCurrent.ShouldBe(true); + live.SourceBindingValid.ShouldBe(true); live.LatestProofValid.ShouldBe(true); + _ = Prepare(coordinator!); + manager.RevalidateMonitoredItems(); + var suppressed = SdkItemDiagnostics.Capture(manager, anchor).Items.ShouldHaveSingleItem(); + suppressed.Suppressed.ShouldBe(true); suppressed.HealthTracked.ShouldBe(true); + suppressed.DemandValid.ShouldBe(false); + + var items = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!; + var keys = (System.Collections.IEnumerable)items.GetType().GetProperty("Keys")!.GetValue(items)!; + var item = keys.Cast().OfType().Single(x => x.ClientHandle == 1); + item.GetType().GetMethod("Retire", flags)!.Invoke(item, null); + var retired = SdkItemDiagnostics.Capture(manager, anchor).Items.ShouldHaveSingleItem(); + retired.Retired.ShouldBe(true); retired.HealthTracked.ShouldBe(false); retired.DemandPresent.ShouldBe(false); + }, onCoordinator: value => coordinator = value); + } + + [Fact, Trait("Phase", "P11Wire")] + public void Fixture_sdk_item_diagnostics_bound_results_and_do_not_serialize_item_objects() + { + var target = new NodeId("target", 2); + var fake = new DiagnosticManager(); + for (var i = 0; i < 20; i++) fake.Add(target); + var captured = SdkItemDiagnostics.Capture(fake, target); + captured.Available.ShouldBeTrue(); captured.Truncated.ShouldBeTrue(); captured.Items.Count.ShouldBe(16); + var json = JsonSerializer.Serialize(captured); + json.ShouldNotContain("target"); + json.ShouldNotContain("private-payload"); + SdkItemDiagnostics.Capture(fake, new NodeId("other", 2)).Items.ShouldBeEmpty(); + SdkItemDiagnostics.Capture(null, target).Available.ShouldBeFalse(); + } + + private sealed class DiagnosticManager + { + private readonly ConcurrentDictionary _liveItems = new(); + private readonly object _projectedHealthGate = new(); + private readonly Dictionary _projectedHealthIndex = new(); + public void Add(NodeId node) { var item = new DiagnosticItem(node); item.Keep(); _liveItems[item] = new(); _projectedHealthIndex[item] = new(); } + } + private sealed class DiagnosticTracked { public bool Suppressed => false; } + private sealed class DiagnosticItem(NodeId node) + { + private NodeId ProjectedNodeId => node; + private bool HealthRetired => false; + private readonly object _bindingSync = new(); + private readonly object? _demand = null, _binding = null, _latestEvidence = null, _definition = null; + private readonly List _candidates = []; + public int MonitoringMode => 1; + public string PrivatePayload => "private-payload"; + public void Keep() { GC.KeepAlive(_demand); GC.KeepAlive(_binding); GC.KeepAlive(_latestEvidence); GC.KeepAlive(_definition); } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkRenewalEvidenceTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkRenewalEvidenceTests.cs new file mode 100644 index 000000000..084e08d19 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkRenewalEvidenceTests.cs @@ -0,0 +1,95 @@ +using System.Threading.Channels; +using Opc.Ua; +using Opc.Ua.Client; +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; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Same_acquisition_successor_refreshes_only_health_evidence_not_queued_or_republished_proof() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var slow = (await client.CreateSubscriptionAsync(new RequestHeader(), 200, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, slow, anchor, 1, 200, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var source = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + await client.SetPublishingModeAsync(new RequestHeader(), false, [slow], ct); + var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, fast, anchor, 2, 50, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); + + var predecessor = new RenewableTestWitness(source.SourceProof); + var successor = new RenewableTestWitness(source.SourceProof); + var stamp = origin.Clock.GetUtcNow().UtcDateTime; + var snapshot = source.Snapshot with { Value = 42, SourceTimestampUtc = stamp, ServerTimestampUtc = stamp }; + var received = origin.Clock.GetTimestamp(); + var oldBounds = new DataAgeBounds(TimeSpan.Zero, TimeSpan.Zero); + var newBounds = new DataAgeBounds(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1)); + var old = new ProjectedValueWrite(source.Route.Realm, source.Route.LocalIdentifier, source.Route.ProjectionGeneration, + source.Route.Serving, snapshot, oldBounds, received, predecessor, false, 2); + ((IProjectedValueSink)sink).TryPublish([old]).ShouldBeTrue(); + var oldNotification = await PublishComposedNotification(client, 2, ct); + oldNotification.Value.StatusCode.ShouldBe(StatusCodes.Good); + oldNotification.Value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42); + await client.SetPublishingModeAsync(new RequestHeader(), false, [fast], ct); + + var next = old with { Proof = successor, OriginAgeBounds = newBounds, IsCompleteSnapshot = true }; + ((IProjectedValueSink)sink).TryPublish([next]).ShouldBeTrue(); + var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; + var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!; + var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!; + var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!; + var item = keys.Cast().OfType().Single(x => x.ClientHandle == 1); + var latest = item.GetType().GetField("_latestEvidence", flags)!.GetValue(item).ShouldNotBeNull(); + latest.GetType().GetProperty("Proof")!.GetValue(latest).ShouldBeSameAs(successor, + "health needs the successor's independently validated metadata witness"); + latest.GetType().GetProperty("Age")!.GetValue(latest).ShouldBe(newBounds); + latest.GetType().GetProperty("ReceivedTimestamp")!.GetValue(latest).ShouldBe(received); + var candidates = (System.Collections.IEnumerable)item.GetType().GetField("_candidates", flags)!.GetValue(item)!; + var held = candidates.Cast().Select(candidate => + (ProjectedValueWrite)candidate.GetType().GetProperty("Sample")!.GetValue(candidate)!) + .Single(candidate => Equals(candidate.Snapshot.Value, 42)); + held.Proof.ShouldBeSameAs(predecessor, "the successor may not rewrite the queued candidate's proof"); + held.OriginAgeBounds.ShouldBe(oldBounds); + held.ReceivedTimestamp.ShouldBe(received); + + predecessor.Valid = false; // Models expiry of the old metadata lease only. + origin.Clock.Advance(TimeSpan.FromMilliseconds(100)); + item.GetType().GetField("_queuedLoss", flags)!.GetValue(item).ShouldBeNull("a valid successor must keep current health Good"); + await client.SetPublishingModeAsync(new RequestHeader(), true, [slow], ct); + var queued = await PublishComposedValue(client, 1, ct); + StatusCode.IsGood(queued.StatusCode).ShouldBeFalse("the held old candidate keeps its original expired witness"); + queued.WrappedValue.IsNull.ShouldBeTrue(); + var replay = await client.RepublishAsync(new RequestHeader(), fast, oldNotification.Sequence, ct); + var oldReplay = ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 2).Value; + StatusCode.IsGood(oldReplay.StatusCode).ShouldBeFalse("the successor must not extend the old notification's metadata proof"); + oldReplay.WrappedValue.IsNull.ShouldBeTrue(); + }, onPublished: update => published.Writer.TryWrite(update)); + } + + private sealed class RenewableTestWitness(IProjectedSamplePublicationProof source) : IProjectedSamplePublicationProof + { + public bool Valid = true; + public bool IsValid => Valid && source.IsValid; + public bool IsSourceValid => source.IsSourceValid; + public object SourceIdentity => source.SourceIdentity; + public TimeProvider Clock => source.Clock; + public void Invalidate() => Valid = false; + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSampleFidelityWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSampleFidelityWireTests.cs new file mode 100644 index 000000000..5f02575f3 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSampleFidelityWireTests.cs @@ -0,0 +1,60 @@ +using System.Threading.Channels; +using Opc.Ua; +using Opc.Ua.Client; +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; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000), Trait("Phase", "P10Wire")] + public async Task Sdk_mapped_read_preserves_one_controlled_samples_independent_timestamps_quality_value_and_version() + { + var ct = TestContext.Current.CancellationToken; + using var origin = new LocalDataFixture(servingGeneration: 1); + var sourceTime = origin.Clock.GetUtcNow().AddMinutes(-1).AddTicks(1234); + var serverTime = origin.Clock.GetUtcNow().AddSeconds(-30).AddTicks(5678); + const uint quality = 0x40A40480u; + const long version = 73; + origin.Hub.TryReserveIngress(origin.Ticket, 288, out var reservation).ShouldBeTrue(); + using (reservation!) + { + var sample = new DataSample(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromScalar(DataValueKind.Int32, 42), quality, + sourceTime, serverTime, origin.Serving, version); + if (!reservation!.TryCommit(sample, version)) + { + sample.Dispose(); + throw new InvalidOperationException("Controlled acquisition was not admitted."); + } + } + origin.Hub.ProcessPending(); + var published = Channel.CreateUnbounded(); + await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + var children = await BrowseAll(client, anchor, 10); + var node = ExpandedNodeId.ToNodeId(children.Single(x => x.BrowseName.Name == "Speed").NodeId, session.NamespaceUris); + async Task ReadAsync() + { + var result = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Both, + [new ReadValueId { NodeId = node, AttributeId = Attributes.Value }], ct); + return result.Results[0]; + } + var first = await ReadAsync(); + first.StatusCode.ShouldBe(StatusCodes.BadWaitingForInitialData); + var admitted = await published.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + admitted.SourceVersion.ShouldBe(version); + admitted.Snapshot.StatusCode.ShouldBe(quality); + admitted.Snapshot.SourceTimestampUtc.ShouldBe(sourceTime.UtcDateTime); + admitted.Snapshot.ServerTimestampUtc.ShouldBe(serverTime.UtcDateTime); + var result = await ReadAsync(); + result.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42); + result.StatusCode.Code.ShouldBe(quality); + result.SourceTimestamp.ShouldBe((DateTimeUtc)sourceTime.UtcDateTime); + result.ServerTimestamp.ShouldBe((DateTimeUtc)serverTime.UtcDateTime); + }, onPublished: value => published.Writer.TryWrite(value)); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSourceLossTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSourceLossTests.cs new file mode 100644 index 000000000..b0d523e76 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSourceLossTests.cs @@ -0,0 +1,643 @@ +using System.Threading.Channels; +using Microsoft.Extensions.Logging.Abstractions; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Failed_first_sdk_item_construction_removes_new_fanout_and_component_reference() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; origin.Publish(7); + var published = Channel.CreateUnbounded(); + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Both, + [new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], ct); + await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 7), ct); + var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; + var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!; + var samples = (System.Collections.IDictionary)manager.GetType().GetField("_projectedSamples", flags)!.GetValue(manager)!; + var original = (ProjectedValueWrite)samples[anchor].ShouldNotBeNull(); + var count = manager.GetType().GetProperty("MonitoredNodeCount", flags).ShouldNotBeNull(); + var beforeNodes = (int)count.GetValue(manager)!; + var cacheField = typeof(Opc.Ua.Server.CustomNodeManager2).GetField("m_componentCache", flags).ShouldNotBeNull(); + int References() + { + if (cacheField.GetValue(manager) is not System.Collections.IDictionary cache || !cache.Contains(anchor)) return 0; + var entry = cache[anchor].ShouldNotBeNull(); + return (int)entry.GetType().GetField("RefCount")!.GetValue(entry)!; + } + var beforeReferences = References(); + samples[anchor] = original with { Proof = new ThrowingSourceProof(original.Proof) }; + try + { + var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + var result = await client.CreateMonitoredItemsAsync(new RequestHeader(), sub, TimestampsToReturn.Both, + [new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }, + MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters + { ClientHandle = 1, SamplingInterval = 100, QueueSize = 1, DiscardOldest = true } }], ct); + StatusCode.IsBad(result.Results[0].StatusCode).ShouldBeTrue("the injected check must fail after creating the first fanout"); + } + catch (ServiceResultException error) { StatusCode.IsBad(error.StatusCode).ShouldBeTrue(); } + finally { samples[anchor] = original; } + ((int)count.GetValue(manager)!).ShouldBe(beforeNodes, "failed first construction cannot retain an empty monitored node"); + References().ShouldBe(beforeReferences, "failed first construction must return its component-cache reference"); + }, onPublished: update => published.Writer.TryWrite(update)); + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Failed_sdk_item_construction_releases_candidate_and_fanout_ownership() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, sub, anchor, 1, 100, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; + var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!; + var samples = (System.Collections.IDictionary)manager.GetType().GetField("_projectedSamples", flags)!.GetValue(manager)!; + var original = (ProjectedValueWrite)samples[anchor].ShouldNotBeNull(); + var budget = manager.GetType().GetField("_projectedCandidateBudget", flags)!.GetValue(manager)!; + var entries = budget.GetType().GetProperty("RetainedEntries").ShouldNotBeNull(); + var before = (int)entries.GetValue(budget)!; + var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!; + var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!; + var existing = keys.Cast().OfType().Single(x => x.ClientHandle == 1); + var handle = (Opc.Ua.Server.NodeHandle)existing.ManagerHandle; + var node = handle.MonitoredNode; + var fanoutBefore = node.DataChangeMonitoredItems.Count; + var componentCache = (System.Collections.IDictionary)typeof(Opc.Ua.Server.CustomNodeManager2) + .GetField("m_componentCache", flags)!.GetValue(manager)!; + var cacheKey = string.IsNullOrEmpty(handle.ComponentPath) ? handle.NodeId : handle.RootId; + var cacheEntry = componentCache[cacheKey].ShouldNotBeNull(); + var references = cacheEntry.GetType().GetField("RefCount").ShouldNotBeNull(); + var referencesBefore = (int)references.GetValue(cacheEntry)!; + samples[anchor] = original with { Proof = new ThrowingSourceProof(original.Proof) }; + try + { + var result = await client.CreateMonitoredItemsAsync(new RequestHeader(), sub, TimestampsToReturn.Both, + [new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }, + MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters + { ClientHandle = 2, SamplingInterval = 100, QueueSize = 1, DiscardOldest = true } }], ct); + StatusCode.IsBad(result.Results[0].StatusCode).ShouldBeTrue("the injected source check must fail after the item is constructed"); + } + catch (ServiceResultException error) { StatusCode.IsBad(error.StatusCode).ShouldBeTrue(); } + finally { samples[anchor] = original; } + ((int)entries.GetValue(budget)!).ShouldBe(before, "failed construction cannot retain the initial sample candidate charge"); + node.DataChangeMonitoredItems.Count.ShouldBe(fanoutBefore, "failed construction cannot remain registered in node fanout"); + ((int)references.GetValue(cacheEntry)!).ShouldBe(referencesBefore, "failed construction must return its component-cache reference"); + }); + } + + private sealed class ThrowingSourceProof(IProjectedSamplePublicationProof inner) : IProjectedSamplePublicationProof + { + public bool IsValid => inner.IsValid; + public object SourceIdentity => inner.SourceIdentity; + public bool IsSourceValid => throw new IOException("test source validity failure"); + public TimeProvider Clock => inner.Clock; + public void Invalidate() => inner.Invalidate(); + } + + [Theory(Timeout = 90000), Trait("Phase", "P11Wire")] + [InlineData(true)] + [InlineData(false)] + public async Task Disabled_sdk_item_does_not_keep_a_ghost_loss_control(bool disableBeforeLoss) + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + var held = new HoldSourceLossRetries(subscriptions); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => held); + peer = origin; subscriptions.SampleClock = origin.Clock; + try + { + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + var created = await client.CreateMonitoredItemsAsync(new RequestHeader(), sub, TimestampsToReturn.Both, + [new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }, + MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters + { ClientHandle = 1, SamplingInterval = 100, QueueSize = 1, DiscardOldest = true } }], ct); + created.Results[0].StatusCode.ShouldBe(StatusCodes.Good); + var itemId = created.Results[0].MonitoredItemId; + var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; + var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!; + var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!; + var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!; + var item = keys.Cast().OfType().Single(x => x.ClientHandle == 1); + var queuedLoss = item.GetType().GetField("_queuedLoss", flags).ShouldNotBeNull(); + async Task SetMode(MonitoringMode mode) + { + var changed = await client.SetMonitoringModeAsync(new RequestHeader(), sub, mode, [itemId], ct); + changed.Results[0].ShouldBe(StatusCodes.Good); + } + if (disableBeforeLoss) await SetMode(MonitoringMode.Disabled); + await stream.DisposeAsync(); + await held.RetryBlocked.Task.WaitAsync(TimeSpan.FromSeconds(10), ct); + origin.Clock.Advance(TimeSpan.FromMilliseconds(100)); + if (!disableBeforeLoss) + { + queuedLoss.GetValue(item).ShouldNotBeNull("the loss must first be queued while reporting"); + await SetMode(MonitoringMode.Disabled); + } + queuedLoss.GetValue(item).ShouldBeNull("disabled items cannot retain a control the SDK silently dropped"); + await SetMode(MonitoringMode.Reporting); + origin.Clock.Advance(TimeSpan.FromMilliseconds(100)); + var unavailable = await PublishComposedValue(client, 1, ct); + StatusCode.IsGood(unavailable.StatusCode).ShouldBeFalse(); + unavailable.WrappedValue.IsNull.ShouldBeTrue(); + }); + } + finally { held.Release.TrySetResult(); } + } + + [Theory(Timeout = 90000), Trait("Phase", "P11Wire")] + [InlineData(false)] + [InlineData(true)] + public async Task Retiring_an_sdk_item_removes_its_health_entry_before_timer_or_demand_reuse(bool directDispose) + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, sub, anchor, 1, 100, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; + var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!; + var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!; + var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!; + var item = keys.Cast().OfType().Single(x => x.ClientHandle == 1); + var health = (System.Collections.IDictionary)manager.GetType().GetField("_projectedHealthIndex", flags)!.GetValue(manager)!; + health.Count.ShouldBe(1); + var demandField = item.GetType().GetField("_demand", flags).ShouldNotBeNull(); + var originalDemand = (IProjectedDemandLease)demandField.GetValue(item).ShouldNotBeNull(); + var slotsAtDisposal = -1; + demandField.SetValue(item, new ObserveDemandDisposal(originalDemand, () => slotsAtDisposal = health.Count)); + var before = origin.Clock.GetTimestamp(); + if (directDispose) ((IDisposable)item).Dispose(); + else item.GetType().GetMethod("Retire", flags).ShouldNotBeNull().Invoke(item, null); + origin.Clock.GetTimestamp().ShouldBe(before, "unregistration cannot wait for a health timer sweep"); + slotsAtDisposal.ShouldBe(0, "the health slot must be released before its demand capacity can be reused"); + health.Count.ShouldBe(0, "retirement must release the bounded health slot before the demand can be reused"); + var stillLive = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!; + stillLive.Cast().ShouldContain(item, "retirement can precede SDK item deletion"); + }); + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Partial_sdk_queue_drain_retains_a_pending_loss_control_once() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + var held = new HoldSourceLossRetries(subscriptions); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => held); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + try + { + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 1, true, 0, ct)).SubscriptionId; + var created = await client.CreateMonitoredItemsAsync(new RequestHeader(), sub, TimestampsToReturn.Both, + [new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }, + MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters + { ClientHandle = 1, SamplingInterval = 100, QueueSize = 3, DiscardOldest = true, + Filter = new ExtensionObject(new DataChangeFilter { Trigger = Opc.Ua.DataChangeTrigger.StatusValueTimestamp }) } }], ct); + created.Results[0].StatusCode.ShouldBe(StatusCodes.Good); + var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + await client.SetPublishingModeAsync(new RequestHeader(), false, [sub], ct); + var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; + var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!; + var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!; + var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!; + var item = keys.Cast().OfType().Single(x => x.ClientHandle == 1); + // Zero SDK sampling delay makes the queued ordering deterministic; source cadence is unchanged. + item.ModifyAttributes(item.DiagnosticsMasks, TimestampsToReturn.Both, item.ClientHandle, + item.Filter, item.Filter, null, 0, 3, true).ShouldBeNull(); + item.QueueSize.ShouldBe(3u); + stream.EmitValue(2, 8, origin.Clock.GetUtcNow(), TimeSpan.Zero); + await NextPublished(published.Reader, x => !x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct); + await stream.DisposeAsync(); + await held.RetryBlocked.Task.WaitAsync(TimeSpan.FromSeconds(10), ct); + origin.Clock.Advance(TimeSpan.FromMilliseconds(100)); + var queuedLoss = item.GetType().GetField("_queuedLoss", flags).ShouldNotBeNull(); + queuedLoss.GetValue(item).ShouldNotBeNull(); + Convert.ToInt32(item.ItemsInQueue).ShouldBeGreaterThanOrEqualTo(2, "the SDK must actually retain a value before the loss"); + // The client subscription can buffer several item callbacks before one + // response. Call the actual SDK item with maximum one to exercise a + // demonstrable partial item dequeue rather than assuming response boundaries. + var context = new Opc.Ua.Server.OperationContext(item); + var first = new Queue(); + var firstDiagnostics = new Queue(); + item.Publish(context, first, firstDiagnostics, 1, NullLogger.Instance).ShouldBeTrue(); + first.Count.ShouldBe(1); + first.Single().Value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8, + "the first partial dequeue must contain the earlier sample, not the loss control"); + queuedLoss.GetValue(item).ShouldNotBeNull("a partial drain must keep the later loss control"); + origin.Clock.Advance(TimeSpan.FromMilliseconds(300)); + var second = new Queue(); + var secondDiagnostics = new Queue(); + item.Publish(context, second, secondDiagnostics, 1, NullLogger.Instance).ShouldBeFalse(); + var loss = second.ShouldHaveSingleItem().Value; + StatusCode.IsGood(loss.StatusCode).ShouldBeFalse(); + loss.WrappedValue.IsNull.ShouldBeTrue(); + queuedLoss.GetValue(item).ShouldBeNull(); + origin.Clock.Advance(TimeSpan.FromSeconds(1)); + queuedLoss.GetValue(item).ShouldBeNull("a reported loss must not be requeued"); + }, onPublished: update => published.Writer.TryWrite(update)); + } + finally { held.Release.TrySetResult(); } + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Throwing_current_authority_sanitizes_a_loss_notification() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + var held = new HoldSourceLossRetries(subscriptions); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => held); + peer = origin; subscriptions.SampleClock = origin.Clock; + try + { + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, sub, anchor, 1, 100, ct); + var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + await stream.DisposeAsync(); + await held.RetryBlocked.Task.WaitAsync(TimeSpan.FromSeconds(10), ct); + origin.Clock.Advance(TimeSpan.FromMilliseconds(100)); + var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; + var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!; + var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!; + var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!; + var item = keys.Cast().OfType().Single(x => x.ClientHandle == 1); + var demandField = item.GetType().GetField("_demand", flags).ShouldNotBeNull(); + var demand = (IProjectedDemandLease)demandField.GetValue(item).ShouldNotBeNull(); + demandField.SetValue(item, new ThrowingStatusDemand(demand)); + try + { + var result = await PublishComposedValue(client, 1, ct); + result.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied); + result.WrappedValue.IsNull.ShouldBeTrue(); + } + finally { demandField.SetValue(item, demand); } + }); + } + finally { held.Release.TrySetResult(); } + } + + private sealed class ThrowingStatusDemand(IProjectedDemandLease inner) : IProjectedDemandLease + { + public DataView OriginView => inner.OriginView; + public DataRealm Realm => inner.Realm; + public string LocalIdentifier => inner.LocalIdentifier; + public long ProjectionGeneration => inner.ProjectionGeneration; + public TimeSpan MaximumSampleAge => inner.MaximumSampleAge; + public ServingIdentity Serving => inner.Serving; + public CancellationToken CancellationToken => inner.CancellationToken; + public bool IsValid => throw new IOException("test authority callback failed"); + public void Dispose() { } + } + + private sealed class ObserveDemandDisposal(IProjectedDemandLease inner, Action beforeDispose) : IProjectedDemandLease + { + public DataView OriginView => inner.OriginView; + public DataRealm Realm => inner.Realm; + public string LocalIdentifier => inner.LocalIdentifier; + public long ProjectionGeneration => inner.ProjectionGeneration; + public TimeSpan MaximumSampleAge => inner.MaximumSampleAge; + public ServingIdentity Serving => inner.Serving; + public CancellationToken CancellationToken => inner.CancellationToken; + public bool IsValid => inner.IsValid; + public void Dispose() { beforeDispose(); inner.Dispose(); } + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Dequeued_old_loss_is_suppressed_when_a_new_baseline_wins_before_delivery() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + var held = new HoldSourceLossRetries(subscriptions); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => held); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + var dequeued = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var releaseDequeue = new ManualResetEventSlim(); + try + { + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, sub, anchor, 1, 100, ct); + var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; + var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!; + var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!; + var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!; + var item = keys.Cast().OfType().Single(x => x.ClientHandle == 1); + var hook = item.GetType().GetField("AfterLossDequeueForTests", flags).ShouldNotBeNull(); + hook.SetValue(item, (Action)(() => { dequeued.TrySetResult(); releaseDequeue.Wait(ct); })); + subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8; + await stream.DisposeAsync(); + await held.RetryBlocked.Task.WaitAsync(TimeSpan.FromSeconds(10), ct); + origin.Clock.Advance(TimeSpan.FromMilliseconds(100)); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromSeconds(10)); + var pending = client.PublishAsync(new RequestHeader(), default, timeout.Token); + await dequeued.Task.WaitAsync(TimeSpan.FromSeconds(10), ct); + held.Release.TrySetResult(); + await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct); + releaseDequeue.Set(); + var old = await pending; + ComposedChanges(old.NotificationMessage).ShouldNotContain(x => x.ClientHandle == 1, + "a dequeued old-era loss must be suppressed after a new baseline"); + var recovered = await PublishComposedValue(client, 1, ct); + recovered.StatusCode.ShouldBe(StatusCodes.Good); + recovered.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8); + }, onPublished: update => published.Writer.TryWrite(update)); + } + finally { releaseDequeue.Set(); held.Release.TrySetResult(); } + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Queued_sdk_loss_status_cannot_override_a_recovered_baseline() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + var held = new HoldSourceLossRetries(subscriptions); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => held); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + try + { + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, sub, anchor, 1, 100, ct); + var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + await client.SetPublishingModeAsync(new RequestHeader(), false, [sub], ct); + var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; + var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!; + var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!; + var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!; + var item = keys.Cast().OfType().Single(x => x.ClientHandle == 1); + await stream.DisposeAsync(); + await held.RetryBlocked.Task.WaitAsync(TimeSpan.FromSeconds(10), ct); + origin.Clock.Advance(TimeSpan.FromMilliseconds(100)); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromSeconds(10)); + var queuedLoss = item.GetType().GetField("_queuedLoss", flags).ShouldNotBeNull(); + while (queuedLoss.GetValue(item) is null) await Task.Delay(10, timeout.Token); + subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8; + held.Release.TrySetResult(); + await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct); + await client.SetPublishingModeAsync(new RequestHeader(), true, [sub], ct); + var recovered = await PublishComposedValue(client, 1, ct); + recovered.StatusCode.ShouldBe(StatusCodes.Good, "a queued old-era loss must not follow a newer proven baseline"); + recovered.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8); + }, onPublished: update => published.Writer.TryWrite(update)); + } + finally { held.Release.TrySetResult(); } + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Replayed_sdk_loss_status_never_reveals_data_after_authority_is_suspended() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + var held = new HoldSourceLossRetries(subscriptions); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => held); + peer = origin; subscriptions.SampleClock = origin.Clock; + LocalCatalogCoordinator? coordinator = null; + try + { + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, placements, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, sub, anchor, 1, 100, ct); + var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + await stream.DisposeAsync(); + await held.RetryBlocked.Task.WaitAsync(TimeSpan.FromSeconds(10), ct); + origin.Clock.Advance(TimeSpan.FromMilliseconds(100)); + var unavailable = await PublishComposedNotification(client, 1, ct); + StatusCode.IsGood(unavailable.Value.StatusCode).ShouldBeFalse(); + unavailable.Value.WrappedValue.IsNull.ShouldBeTrue(); + var replacement = Prepare(coordinator!); + try + { + var replay = await client.RepublishAsync(new RequestHeader(), sub, unavailable.Sequence, ct); + var value = ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value; + StatusCode.IsGood(value.StatusCode).ShouldBeFalse(); + value.WrappedValue.IsNull.ShouldBeTrue(); + } + catch (ServiceResultException error) { error.StatusCode.ShouldBe(StatusCodes.BadMessageNotAvailable); } + finally + { + var mapping = Mapping(origin.Raw); + mapping.AllowedOperations |= DataOperations.Read | DataOperations.Metadata; + placements.Stage(replacement, [mapping], [Connection()]); + coordinator!.Complete(replacement, true).ShouldBeTrue(); + } + }, onCoordinator: value => coordinator = value); + } + finally { held.Release.TrySetResult(); } + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Sdk_item_does_not_report_source_loss_while_an_exact_proven_peer_remains() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + var held = new GateLaterSubscriptions(subscriptions); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => held); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + try + { + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var slow = (await client.CreateSubscriptionAsync(new RequestHeader(), 200, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, slow, anchor, 1, 200, ct); + var slowStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var first = await PublishComposedNotification(client, 1, ct); + first.Value.StatusCode.ShouldBe(StatusCodes.Good); + var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, fast, anchor, 2, 50, ct); + var fastStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); + await slowStream.DisposeAsync(); + await held.RetryBlocked.Task.WaitAsync(TimeSpan.FromSeconds(10), ct); + origin.Clock.Advance(TimeSpan.FromMilliseconds(100)); + var replay = await client.RepublishAsync(new RequestHeader(), slow, first.Sequence, ct); + StatusCode.IsGood(ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode) + .ShouldBeTrue("continuous exact-source coverage preserves the original still-fresh evidence"); + await client.SetPublishingModeAsync(new RequestHeader(), false, [fast], ct); + fastStream.EmitValue(2, 42, origin.Clock.GetUtcNow(), TimeSpan.Zero); + await NextPublished(published.Reader, x => !x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 42), ct); + var next = await PublishComposedValue(client, 1, ct); + next.StatusCode.ShouldBe(StatusCodes.Good, "a covered peer loss must not enqueue a false outage status"); + next.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42); + }, onPublished: update => published.Writer.TryWrite(update)); + } + finally { held.Release.TrySetResult(); } + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Sdk_item_reports_source_loss_then_recovers_on_a_new_complete_baseline() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + var held = new HoldSourceLossRetries(subscriptions); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => held); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + try + { + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, sub, anchor, 1, 100, ct); + var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var initial = await PublishComposedNotification(client, 1, ct); + initial.Value.StatusCode.ShouldBe(StatusCodes.Good); + initial.Value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(7); + subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8; + await stream.DisposeAsync(); + await held.RetryBlocked.Task.WaitAsync(TimeSpan.FromSeconds(10), ct); + origin.Clock.Advance(TimeSpan.FromMilliseconds(100)); + var unavailable = await PublishComposedNotification(client, 1, ct); + StatusCode.IsGood(unavailable.Value.StatusCode).ShouldBeFalse("a stopped source must actively change the SDK item's quality"); + unavailable.Value.WrappedValue.IsNull.ShouldBeTrue(); + unavailable.Value.SourceTimestamp.ShouldBe(DateTimeUtc.MinValue); + var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; + var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!; + var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!; + var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!; + var item = keys.Cast().OfType().Single(x => x.ClientHandle == 1); + var queuedLoss = item.GetType().GetField("_queuedLoss", flags).ShouldNotBeNull(); + origin.Clock.Advance(TimeSpan.FromSeconds(1)); + queuedLoss.GetValue(item).ShouldBeNull("one reported loss must not enqueue another status on each sweep"); + var replay = await client.RepublishAsync(new RequestHeader(), sub, initial.Sequence, ct); + StatusCode.IsGood(ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode).ShouldBeFalse(); + held.Release.TrySetResult(); + var baseline = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct); + baseline.SourceProof.IsValid.ShouldBeTrue(); + var recovered = await PublishComposedValue(client, 1, ct); + recovered.StatusCode.ShouldBe(StatusCodes.Good); + recovered.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8); + var obsolete = await client.RepublishAsync(new RequestHeader(), sub, unavailable.Sequence, ct); + ComposedChanges(obsolete.NotificationMessage).ShouldNotContain(x => x.ClientHandle == 1, + "an old loss status must not overwrite the new complete baseline"); + }, onPublished: update => published.Writer.TryWrite(update)); + } + finally { held.Release.TrySetResult(); } + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Sdk_item_reports_stale_silent_source_without_closing_a_live_stream() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, sub, anchor, 1, 100, ct); + var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var initial = await PublishComposedNotification(client, 1, ct); + initial.Value.StatusCode.ShouldBe(StatusCodes.Good); + origin.Clock.Advance(TimeSpan.FromSeconds(5)); // The 2-second age bound expired; the maintenance timer fired. + var stale = await PublishComposedValue(client, 1, ct); + StatusCode.IsGood(stale.StatusCode).ShouldBeFalse("an open but silent stream cannot leave its last value indefinitely Good"); + stale.WrappedValue.IsNull.ShouldBeTrue(); + stale.SourceTimestamp.ShouldBe(DateTimeUtc.MinValue); + subscriptions.Closed.Reader.TryRead(out _).ShouldBeFalse("a stale sample alone need not close a still-live stream"); + stream.EmitValue(2, 8, origin.Clock.GetUtcNow(), TimeSpan.Zero); + var recovered = await PublishComposedValue(client, 1, ct); + recovered.StatusCode.ShouldBe(StatusCodes.Good); + recovered.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8); + var replay = await client.RepublishAsync(new RequestHeader(), sub, initial.Sequence, ct); + StatusCode.IsGood(ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode).ShouldBeFalse(); + }, staleTimeoutMilliseconds: 2000); + } + + private sealed class HoldSourceLossRetries(IDataSubscriptionService inner) : IDataSubscriptionService + { + private int _opens; + internal readonly TaskCompletionSource RetryBlocked = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource Release = new(TaskCreationOptions.RunContinuationsAsynchronously); + public async Task SubscribeAsync(CancellationToken ct) + { + if (Interlocked.Increment(ref _opens) > 1) + { + RetryBlocked.TrySetResult(); + await Release.Task.WaitAsync(ct); + } + return await inner.SubscribeAsync(ct); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkTimestampEvidenceTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkTimestampEvidenceTests.cs new file mode 100644 index 000000000..9e0f7e193 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkTimestampEvidenceTests.cs @@ -0,0 +1,216 @@ +using System.Threading.Channels; +using Opc.Ua; +using Opc.Ua.Client; +using SdkServerMonitoredItem = Opc.Ua.Server.MonitoredItem; +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; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Sdk_older_duplicate_cannot_consume_newer_timestamp_evidence() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; + subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + var created = await client.CreateMonitoredItemsAsync(new RequestHeader(), sub, TimestampsToReturn.Both, + [new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }, + MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters + { ClientHandle = 1, SamplingInterval = 100, QueueSize = 3, DiscardOldest = true, + Filter = new ExtensionObject(new DataChangeFilter { Trigger = Opc.Ua.DataChangeTrigger.StatusValueTimestamp }) } }], ct); + created.Results[0].StatusCode.ShouldBe(StatusCodes.Good); + var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + await client.SetPublishingModeAsync(new RequestHeader(), false, [sub], ct); + var timestamp = origin.Clock.GetUtcNow().AddMinutes(-1); + stream.EmitValue(2, 42, timestamp, TimeSpan.Zero); + await NextPublished(published.Reader, x => !x.IsCompleteSnapshot && + x.Snapshot.SourceTimestampUtc == timestamp.UtcDateTime && Equals(x.Snapshot.Value, 42), ct); + var later = timestamp.AddSeconds(1); + stream.EmitValue(3, 42, later, TimeSpan.Zero); + var newer = await NextPublished(published.Reader, x => !x.IsCompleteSnapshot && x.Snapshot.SourceTimestampUtc == later.UtcDateTime, ct); + + // Force duplicate notifications at the SDK's public queue boundary. This is + // an identity-contract injection, not a claim that normal filtering duplicates them. + var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; + var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!; + var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!; + var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!; + var item = keys.Cast().OfType().Single(x => x.ClientHandle == 1); + item.SetMonitoringMode(MonitoringMode.Disabled); + item.SetMonitoringMode(MonitoringMode.Reporting); + var queue = typeof(SdkServerMonitoredItem).GetMethods().Single(x => x.Name == "QueueValue" && x.GetParameters().Length == 3); + void Inject(DateTimeOffset sourceTime) + { + var injected = new Opc.Ua.DataValue(new Variant(42), StatusCodes.Good, + (DateTimeUtc)sourceTime.UtcDateTime, DateTimeUtc.MinValue); + queue.Invoke(item, [injected, ServiceResult.Good, true]); + } + await client.SetPublishingModeAsync(new RequestHeader(), true, [sub], ct); + Inject(timestamp); + var first = await PublishComposedValue(client, 1, ct); + first.SourceTimestamp.ShouldBe((DateTimeUtc)timestamp.UtcDateTime); + first.StatusCode.ShouldBe(StatusCodes.Good); + subscriptions.SnapshotVersion = 3; + subscriptions.SnapshotValue = 42; + subscriptions.HoldNextSnapshotEnd = true; + Inject(timestamp); + var duplicate = await PublishComposedValue(client, 1, ct); + StatusCode.IsGood(duplicate.StatusCode).ShouldBeFalse("an old duplicate must not acquire newer evidence"); + var held = await subscriptions.SnapshotEndHeld.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + try + { + var candidates = (System.Collections.IEnumerable)item.GetType().GetField("_candidates", flags)!.GetValue(item)!; + var retained = candidates.Cast().Select(candidate => + (ProjectedValueWrite)candidate.GetType().GetProperty("Sample")!.GetValue(candidate)!).ToArray(); + var surviving = retained.Single(candidate => candidate.Snapshot.SourceTimestampUtc == later.UtcDateTime); + surviving.Proof.ShouldBeSameAs(newer.SourceProof); + surviving.OriginAgeBounds.ShouldBe(newer.OriginAgeBounds); + surviving.ReceivedTimestamp.ShouldBe(newer.ReceivedTimestamp); + } + finally { held.ReleaseSnapshotEnd(); } + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good, + "a completed replacement baseline restores delivery after the rejection"); + }, onPublished: update => published.Writer.TryWrite(update)); + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Sdk_rejects_ambiguous_evidence_when_origin_source_timestamps_are_absent() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; + subscriptions.SampleClock = origin.Clock; + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var slow = (await client.CreateSubscriptionAsync(new RequestHeader(), 200, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, slow, anchor, 1, 200, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + await client.SetPublishingModeAsync(new RequestHeader(), false, [slow], ct); + var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, fast, anchor, 2, 50, ct); + var fastStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); + foreach (var (version, value) in new[] { (2L, 42), (3L, 44), (4L, 42) }) + { + fastStream.EmitValueWithoutSourceTimestamp(version, value, TimeSpan.Zero); + (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); + } + await client.SetPublishingModeAsync(new RequestHeader(), false, [fast], ct); + await client.SetPublishingModeAsync(new RequestHeader(), true, [slow], ct); + var valueWithoutProof = await PublishComposedValue(client, 1, ct); + StatusCode.IsGood(valueWithoutProof.StatusCode).ShouldBeFalse("absent timestamps cannot distinguish the two retained 42 acquisitions"); + }); + } + + [Theory(Timeout = 90000), Trait("Phase", "P11Wire")] + [InlineData(TimestampsToReturn.Server)] + [InlineData(TimestampsToReturn.Neither)] + public async Task Sdk_rejects_ambiguous_evidence_when_source_timestamp_was_not_requested(TimestampsToReturn mode) + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; + subscriptions.SampleClock = origin.Clock; + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var slow = (await client.CreateSubscriptionAsync(new RequestHeader(), 200, 300, 1, 0, true, 0, ct)).SubscriptionId; + var created = await client.CreateMonitoredItemsAsync(new RequestHeader(), slow, mode, + [new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }, + MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters + { ClientHandle = 1, SamplingInterval = 200, QueueSize = 1, DiscardOldest = true, + Filter = new ExtensionObject(new DataChangeFilter { Trigger = Opc.Ua.DataChangeTrigger.StatusValueTimestamp }) } }], ct); + created.Results[0].StatusCode.ShouldBe(StatusCodes.Good); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + await client.SetPublishingModeAsync(new RequestHeader(), false, [slow], ct); + var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, fast, anchor, 2, 50, ct); + var fastStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); + var timestamp = origin.Clock.GetUtcNow().AddMinutes(-1); + fastStream.EmitValue(2, 42, timestamp, TimeSpan.Zero); + (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); + fastStream.EmitValue(3, 42, timestamp.AddSeconds(1), TimeSpan.Zero); + (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); + await client.SetPublishingModeAsync(new RequestHeader(), false, [fast], ct); + await client.SetPublishingModeAsync(new RequestHeader(), true, [slow], ct); + var value = await PublishComposedValue(client, 1, ct); + StatusCode.IsGood(value.StatusCode).ShouldBeFalse("an omitted source timestamp cannot identify either retained acquisition"); + }); + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Sdk_uses_unique_source_timestamp_to_select_coalesced_value_evidence() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; + subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var slow = (await client.CreateSubscriptionAsync(new RequestHeader(), 200, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, slow, anchor, 1, 200, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + await client.SetPublishingModeAsync(new RequestHeader(), false, [slow], ct); + + var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, fast, anchor, 2, 50, ct); + var fastStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); + + var earlier = origin.Clock.GetUtcNow().AddMinutes(-1); + var later = earlier.AddSeconds(1); + fastStream.EmitValue(2, 42, earlier, TimeSpan.FromSeconds(28)); + (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); + origin.Clock.Advance(TimeSpan.FromSeconds(3)); + fastStream.EmitValue(3, 42, later, TimeSpan.FromSeconds(28)); + (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); + var selected = await NextPublished(published.Reader, + x => !x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 42) && x.Snapshot.SourceTimestampUtc == later.UtcDateTime, ct); + + await client.SetPublishingModeAsync(new RequestHeader(), false, [fast], ct); + await client.SetPublishingModeAsync(new RequestHeader(), true, [slow], ct); + var delivered = await PublishComposedNotification(client, 1, ct); + delivered.Value.StatusCode.ShouldBe(StatusCodes.Good); + delivered.Value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42); + delivered.Value.SourceTimestamp.ShouldBe((DateTimeUtc)later.UtcDateTime); + selected.SourceProof.IsValid.ShouldBeTrue(); + + var replay = await client.RepublishAsync(new RequestHeader(), slow, delivered.Sequence, ct); + StatusCode.IsGood(ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode).ShouldBeTrue(); + origin.Clock.Advance(TimeSpan.FromSeconds(3)); + var expiredReplay = await client.RepublishAsync(new RequestHeader(), slow, delivered.Sequence, ct); + StatusCode.IsGood(ComposedChanges(expiredReplay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode) + .ShouldBeFalse("the selected acquisition's original 28-second age must not be refreshed by delivery or Republish"); + }, onPublished: update => published.Writer.TryWrite(update)); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSecondaryWriteBackoffTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSecondaryWriteBackoffTests.cs new file mode 100644 index 000000000..e5090efa2 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSecondaryWriteBackoffTests.cs @@ -0,0 +1,90 @@ +using System.Buffers.Binary; +using System.Net; +using Google.Protobuf; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +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 GrpcDataSecondaryWriteBackoffTests +{ + [Fact] + public async Task Rejected_secondary_write_does_not_back_off_immediate_replica_read() + { + var ct = TestContext.Current.CancellationToken; + var handler = new SecondaryHandler(); + 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", DataConsistency.ReadyReplica), + [new Uri("https://a.test")], new Security(handler), manager.Acquire("link"), 65536, 1, new ManualTimeProvider()); + var view = new DataView(new("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x"); + var budget = new DataBudget(TimeSpan.FromSeconds(5), 16, 65536); + async Task ReadGood() + { + var reads = await connection.ReadAsync(new([new("0", view, null)], budget), ct); + try { reads.ShouldHaveSingleItem().Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(42); } + finally { foreach (var read in reads) read.Dispose(); } + } + await ReadGood(); + using var value = DataValue.FromScalar(DataValueKind.Int32, 7); + var writes = await connection.WriteAsync(new([new("write", "command", view, value, 1, "boot", TimeSpan.FromSeconds(4))], budget), ct); + writes.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); + handler.WriteCalls.ShouldBe(0); + await ReadGood(); + handler.ReadCalls.ShouldBe(2); + handler.CapabilityCalls.ShouldBe(3); + } + + 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", "ca", "key", () => handler)); + } + + private sealed class SecondaryHandler : HttpMessageHandler + { + private static readonly ServingIdentity Serving = new("a", "boot", "Secondary", 1, 1, 1); + private static readonly DataLimits Limits = new(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)); + public int CapabilityCalls, ReadCalls, WriteCalls; + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + IMessage message; + if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal)) + { + CapabilityCalls++; + message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 3, Serving, DataReadiness.Ready, + DataOperations.Read | DataOperations.Write, new HashSet { DataValueKind.Int32 }, Limits, + false, 0, "c", false, true, true)); + } + else if (request.RequestUri.AbsolutePath.EndsWith("/Read", StringComparison.Ordinal)) + { + ReadCalls++; + using var result = new ReadResult("0", DataItemStatus.Good, DataReadiness.Ready, TimeSpan.Zero, + new(DataValue.FromScalar(DataValueKind.Int32, 42), 0, null, null, Serving, 1), null, + AgeBounds: new(TimeSpan.Zero, TimeSpan.Zero)); + var response = DataProtoMapper.EncodeReadResponse([result]); + response.Serving = DataProtoMapper.EncodeServing(Serving); message = response; + } + else if (request.RequestUri.AbsolutePath.EndsWith("/Write", StringComparison.Ordinal)) + { + WriteCalls++; + throw new InvalidOperationException("A secondary must never receive a write."); + } + else throw new InvalidOperationException("Unexpected gRPC method."); + var payload = message.ToByteArray(); + var framed = new byte[payload.Length + 5]; + BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), payload.Length); + payload.CopyTo(framed, 5); + var http = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent(framed) }; + http.Content.Headers.ContentType = new("application/grpc"); + http.TrailingHeaders.Add("grpc-status", "0"); + return Task.FromResult(http); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataStreamFreshnessWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataStreamFreshnessWireTests.cs new file mode 100644 index 000000000..a00bd375c --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataStreamFreshnessWireTests.cs @@ -0,0 +1,233 @@ +using System.Buffers.Binary; +using System.IO.Pipelines; +using System.Net; +using System.Threading.Channels; +using Google.Protobuf; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; +using ReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest; +using ReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult; +using BrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Grpc_stream_snapshot_reaches_an_sdk_monitored_item_with_finite_age() + { + var ct = TestContext.Current.CancellationToken; + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 8, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? peer = null; + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (context, target) => + new LocalSubscriptionService(peer!.Services, context, target, demand, limits, capacity)); + peer = origin; origin.Publish(42); + using var connections = new FreshnessWireConnections(origin); + var published = Channel.CreateUnbounded(); + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, sub, anchor, 1, 100, ct); + var update = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 42), ct); + update.OriginAgeBounds.Upper.ShouldNotBeNull(); + update.SourceProof.IsValid.ShouldBeTrue("the stream must stay live through SDK publication"); + Opc.Ua.DataValue notification; + do { notification = await PublishComposedValue(client, 1, ct); } + while (!StatusCode.IsGood(notification.StatusCode)); + notification.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42); + }, onPublished: x => published.Writer.TryWrite(x), connectionSource: connections); + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Subscribe_only_export_delivers_fresh_sdk_value_while_read_is_denied() + { + var ct = TestContext.Current.CancellationToken; + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + LocalDataFixture? peer = null; + using var origin = new LocalDataFixture(servingGeneration: 1, denyReadExport: true, targetSubscriptions: (context, target) => + new LocalSubscriptionService(peer!.Services, context, target, demand, + new(16, 8, 100_000, TimeSpan.FromMinutes(1)), capacity)); + peer = origin; origin.Publish(42); + await using (var direct = origin.Connection()) + { + var reads = await direct.ReadAsync(new ReadRequest([new("read", origin.Raw, null)], LocalDataFixture.Budget), ct); + try { reads.ShouldHaveSingleItem().Status.ShouldBe(DataItemStatus.Denied); } + finally { foreach (var read in reads) read.Dispose(); } + } + using var connections = new FreshnessWireConnections(origin); + var published = Channel.CreateUnbounded(); + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, sub, anchor, 1, 100, ct); + var update = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 42), ct); + update.OriginAgeBounds.Upper.ShouldNotBeNull(); + Opc.Ua.DataValue notification; + do { notification = await PublishComposedValue(client, 1, ct); } + while (!StatusCode.IsGood(notification.StatusCode)); + notification.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42); + }, onPublished: x => published.Writer.TryWrite(x), connectionSource: connections); + } + + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Grpc_quiet_renewal_does_not_rejuvenate_expired_sample_and_new_version_recovers() + { + var ct = TestContext.Current.CancellationToken; + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 8, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? peer = null; + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (context, target) => + new LocalSubscriptionService(peer!.Services, context, target, demand, limits, capacity)); + peer = origin; origin.Publish(42); + using var connections = new FreshnessWireConnections(origin); + var published = Channel.CreateUnbounded(); + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, sub, anchor, 1, 100, ct); + await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 42), ct); + (Opc.Ua.DataValue Value, uint Sequence) initial; + do { initial = await PublishComposedNotification(client, 1, ct); } + while (!StatusCode.IsGood(initial.Value.StatusCode)); + origin.Clock.Advance(TimeSpan.FromSeconds(3)); + var replay = await client.RepublishAsync(new RequestHeader(), sub, initial.Sequence, ct); + var expired = ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value; + StatusCode.IsGood(expired.StatusCode).ShouldBeFalse("a new challenge cannot reset the age of an old sample"); + HubTest.Publish(origin.Hub, origin.Ticket, 2, 43); origin.Hub.ProcessPending(); + origin.Clock.Advance(TimeSpan.FromMilliseconds(200)); + await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 43), ct); + Opc.Ua.DataValue fresh; + do { fresh = await PublishComposedValue(client, 1, ct); } + while (!StatusCode.IsGood(fresh.StatusCode)); + fresh.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(43); + }, onPublished: x => published.Writer.TryWrite(x), connectionSource: connections, staleTimeoutMilliseconds: 2000); + } + + // Catalog access stays local to keep this test focused on the real remote stream decoder. + private sealed class FreshnessWireConnections : IGrpcDataAdapterConnectionSource, IDisposable + { + private readonly LocalDataFixture _origin; + private readonly DataConnectionManager _manager = new("consumer", 1); + internal FreshnessWireConnections(LocalDataFixture origin) + { + _origin = origin; + _manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + } + public ValueTask AcquireAsync(string id, CancellationToken ct) + { + if (id != "link") return ValueTask.FromResult(null); + var local = _origin.Connection(); + var remote = new GrpcDataConnection("link", new(DataTargetMode.Node, "cluster", "node-a"), + [new Uri("https://fixture.test")], new FreshnessSecurity(_origin), _manager.Acquire("link"), + 1_000_000, 1, _origin.Clock); + return ValueTask.FromResult(new Lease(new SplitConnection(local, remote))); + } + public void Dispose() => _manager.Dispose(); + private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease + { + public IDataConnection Connection => connection; + public CancellationToken CancellationToken => CancellationToken.None; + public ValueTask DisposeAsync() => connection.DisposeAsync(); + } + private sealed class SplitConnection(IDataConnection local, IDataConnection remote) : IDataConnection + { + public DataTarget Target => remote.Target; + public TimeProvider Clock => remote.Clock; + public Task GetCapabilitiesAsync(DataBudget b, CancellationToken ct) => local.GetCapabilitiesAsync(b, ct); + public Task BrowseAsync(BrowseRequest r, CancellationToken ct) => local.BrowseAsync(r, ct); + public Task>> GetMetadataAsync(MetadataRequest r, CancellationToken ct) => local.GetMetadataAsync(r, ct); + public Task> ReadAsync(ReadRequest r, CancellationToken ct) => local.ReadAsync(r, ct); + public Task> WriteAsync(WriteBatch r, CancellationToken ct) => local.WriteAsync(r, ct); + public Task SubscribeAsync(CancellationToken ct) => remote.SubscribeAsync(ct); + public async ValueTask DisposeAsync() { await remote.DisposeAsync(); await local.DisposeAsync(); } + } + } + + private sealed class FreshnessSecurity(LocalDataFixture origin, Action? onSession = null) : IDataConnectionSecurityProvider + { + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string id, Uri endpoint, CancellationToken ct) => + ValueTask.FromResult(new("v1", "ca", "key", () => new FreshnessHandler(origin, onSession))); + } + + private sealed class FreshnessHandler(LocalDataFixture origin, Action? onSession) : HttpMessageHandler + { + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal)) + { + await using var local = origin.Connection(); + var capabilities = await local.GetCapabilitiesAsync(LocalDataFixture.Budget, ct); + return Response(new ByteArrayContent(Frame(DataProtoMapper.EncodeCapabilities(capabilities with + { SubscriptionAgeReadiness = true, ResponseServingIdentity = true, SubscriptionFreshnessChallenges = true })))); + } + var incoming = new Pipe(); var outgoing = new Pipe(); + _ = request.Content!.CopyToAsync(incoming.Writer.AsStream(), ct); + _ = ServeAsync(incoming.Reader.AsStream(), outgoing.Writer.AsStream(), ct); + return Response(new StreamContent(outgoing.Reader.AsStream())); + } + private async Task ServeAsync(Stream input, Stream output, CancellationToken ct) + { + try + { + await using var local = origin.Connection(); + await using var stream = await local.SubscribeAsync(ct); + if (stream is DataSubscriptionSession session) onSession?.Invoke(session); + var reader = Task.Run(async () => + { + while (true) + { + var prefix = new byte[5]; + await input.ReadExactlyAsync(prefix, ct); + var bytes = new byte[BinaryPrimitives.ReadInt32BigEndian(prefix.AsSpan(1))]; + await input.ReadExactlyAsync(bytes, ct); + await stream.SendAsync(DataProtoMapper.DecodeCommand(W.SubscriptionCommand.Parser.ParseFrom(bytes)), ct); + } + }, ct); + await foreach (var frame in stream.ReadAllAsync(ct)) + { + try + { + var wire = frame is DataSubscriptionValues values + ? DataProtoMapper.EncodeValues(values, false, true) + : DataProtoMapper.EncodeControlOrAck(frame); + wire.Serving = DataProtoMapper.EncodeServing(origin.Serving); + await output.WriteAsync(Frame(wire), ct); await output.FlushAsync(ct); + } + finally { (frame as IDisposable)?.Dispose(); } + } + await reader; + } + catch (Exception) { } + finally { await output.DisposeAsync(); } + } + private static byte[] Frame(IMessage message) + { + var payload = message.ToByteArray(); var bytes = new byte[payload.Length + 5]; + BinaryPrimitives.WriteInt32BigEndian(bytes.AsSpan(1, 4), payload.Length); + payload.CopyTo(bytes, 5); return bytes; + } + private static HttpResponseMessage Response(HttpContent content) + { + var result = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = content }; + content.Headers.ContentType = new("application/grpc"); result.TrailingHeaders.Add("grpc-status", "0"); return result; + } + } +} 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 cf552a5ca..e5fd99766 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 @@ -477,6 +477,161 @@ public sealed class GrpcDataStreamOrderingTests } } + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Dirty_aliases_wait_when_snapshot_controls_leave_only_two_outbound_slots() + { + var ct = TestContext.Current.CancellationToken; + var demand = new CountingSnapshotDemand(14); + var capacity = new SubscriptionTransportCapacity(4, 4, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 8, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(subscriptions: context => + new LocalSubscriptionService(fixture!.Services, context, new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity))) + using (var releaseTick = new ManualResetEventSlim()) + { + fixture.Publish(1); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + var items = Enumerable.Range(0, 12).Select(i => new DataSubscriptionItem("item-" + i, fixture.Raw, settings)).ToArray(); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(ct); + var session = subscription.ShouldBeOfType(); + var beforeDirty = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var tickDone = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var firstEnd = 0; var intercepted = 0; var capturedTotal = -1; var capturedValues = -1; + session.SnapshotEndCommittedForTests = () => Interlocked.CompareExchange(ref firstEnd, 1, 0); + session.BeforeDirtyTickForTests = (total, values, interests) => + { + if (Volatile.Read(ref firstEnd) == 0 || interests == 0 || Interlocked.CompareExchange(ref intercepted, 1, 0) != 0) return; + capturedTotal = total; capturedValues = values; + beforeDirty.TrySetResult(); releaseTick.Wait(ct); + }; + session.AfterTickForTests = () => { if (Volatile.Read(ref intercepted) != 0) tickDone.TrySetResult(); }; + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10), items, + false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), ct); + await using var reader = subscription.ReadAllAsync(ct).GetAsyncEnumerator(ct); + var depth = 0; var ends = 0; var sawDelta = false; var frames = new List(); + async Task ReadFrame() + { + var moved = await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct); + moved.ShouldBeTrue("stream ended before ordered snapshots completed: " + string.Join(" | ", frames)); + if (frames.Count < 100) frames.Add(reader.Current switch + { + DataSubscriptionControl c => $"{c.Sequence}:control:{c.Kind}:{c.Diagnostic}", + DataSubscriptionAck a => $"{a.Sequence}:ack:{a.CommandId}", + DataSubscriptionValues v => $"{v.Sequence}:values:{v.IsSnapshot}", + _ => $"{reader.Current.Sequence}:other" + }); + if (reader.Current is DataSubscriptionControl control) + { + if (control.Kind == DataStreamControlKind.SnapshotBegin) { depth.ShouldBe(0); depth++; } + if (control.Kind == DataStreamControlKind.SnapshotEnd) { depth.ShouldBe(1); depth--; ends++; } + control.Kind.ShouldNotBe(DataStreamControlKind.Reset); + } + else if (reader.Current is DataSubscriptionValues values) + { + if (values.IsSnapshot) depth.ShouldBe(1); + else { values.Items[0].Sample.Value.GetScalar().ShouldBe(2); sawDelta = true; } + values.Dispose(); + } + } + try + { + await ReadFrame(); await ReadFrame(); await ReadFrame(); + await subscription.SendAsync(new AddSubscriptionItems("s", 1, "add-a", TimeSpan.FromSeconds(10), [new("a", fixture.Raw, settings)]), ct); + await subscription.SendAsync(new AddSubscriptionItems("s", 1, "add-b", TimeSpan.FromSeconds(10), [new("b", fixture.Raw, settings)]), ct); + await demand.Reached.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + fixture.Hub.WithPartitionLockForTest(fixture.Ticket.Key, () => { HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); fixture.Hub.ProcessPending(); }); + for (var i = 0; i < 3; i++) await ReadFrame(); + demand.Release(); + while (ends == 0) await ReadFrame(); + await beforeDirty.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + capturedTotal.ShouldBe(6, "two one-item snapshots occupy six actual outbound frames"); + capturedValues.ShouldBe(2, "the remaining four frames are real snapshot controls"); + releaseTick.Set(); + await tickDone.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + while (ends < 3) await ReadFrame(); + fixture.Clock.Advance(TimeSpan.FromSeconds(1)); + while (!sawDelta) await ReadFrame(); + depth.ShouldBe(0); + } + finally { releaseTick.Set(); demand.Release(); } + } + } + + [Fact(Timeout = 30000), Trait("Phase", "P11")] + public async Task Concurrent_snapshot_jobs_do_not_nest_or_interleave() + { + var demand = new CountingSnapshotDemand(14); + var capacity = new SubscriptionTransportCapacity(4, 4, 1_000_000); + var limits = new SubscriptionSessionLimits(16, 8, 100_000, TimeSpan.FromMinutes(1)); + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(subscriptions: context => + new LocalSubscriptionService(fixture!.Services, context, new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity))) + { + fixture.Publish(1); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + var items = Enumerable.Range(0, 12).Select(i => new DataSubscriptionItem("item-" + i, fixture.Raw, settings)).ToArray(); + await using var connection = fixture.Connection(); + await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); + await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10), items, + false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken); + await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken); + var trace = new List(); + async Task NextFrame() + { + var moved = await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + moved.ShouldBeTrue("stream ended; bounded frames: " + string.Join(" | ", trace)); + if (trace.Count < 64) + trace.Add(reader.Current switch + { + DataSubscriptionControl control => $"{control.Sequence}:control:{control.Kind}:{control.Diagnostic}", + DataSubscriptionAck ack => $"{ack.Sequence}:ack:{ack.CommandId}", + DataSubscriptionValues values => $"{values.Sequence}:values:snapshot={values.IsSnapshot}:versions={string.Join(",", values.Items.Select(item => item.Sample.Version))}", + _ => $"{reader.Current.Sequence}:other" + }); + } + await NextFrame(); reader.Current.ShouldBeOfType(); + await NextFrame(); reader.Current.ShouldBeOfType().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin); + await NextFrame(); reader.Current.ShouldBeOfType().Dispose(); + // Stop reading while the first snapshot exceeds the bounded queue, and wait until two further adds have reached the worker. + await subscription.SendAsync(new AddSubscriptionItems("s", 1, "add-a", TimeSpan.FromSeconds(10), [new("a", fixture.Raw, settings)]), TestContext.Current.CancellationToken); + await subscription.SendAsync(new AddSubscriptionItems("s", 1, "add-b", TimeSpan.FromSeconds(10), [new("b", fixture.Raw, settings)]), TestContext.Current.CancellationToken); + await demand.Reached.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.Hub.WithPartitionLockForTest(fixture.Ticket.Key, () => { HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); fixture.Hub.ProcessPending(); }); + // The worker is held in the third acquisition, leaving room for its control frames + // without overflowing the two reserved control slots. + for (var i = 0; i < 3; i++) + { + await NextFrame(); + reader.Current.ShouldBeOfType().Dispose(); + } + demand.Release(); + var depth = 1; var ends = 0; var sawDelta = false; + while (ends < 3) + { + await NextFrame(); + if (reader.Current is DataSubscriptionControl control) + { + if (control.Kind == DataStreamControlKind.SnapshotBegin) { depth.ShouldBe(0, "a previous snapshot must finish first"); depth++; } + else if (control.Kind == DataStreamControlKind.SnapshotEnd) { depth.ShouldBe(1); depth--; ends++; } + } + else if (reader.Current is DataSubscriptionValues value) + { + if (value.IsSnapshot) depth.ShouldBe(1); + else { value.Items[0].Sample.Value.GetScalar().ShouldBe(2); sawDelta = true; } + value.Dispose(); + } + } + fixture.Clock.Advance(TimeSpan.FromSeconds(1)); + while (!sawDelta) + { + await NextFrame(); + if (reader.Current is not DataSubscriptionValues delta) continue; + using (delta) { if (!delta.IsSnapshot) { delta.Items[0].Sample.Value.GetScalar().ShouldBe(2); sawDelta = true; } } + } + } + } + [Fact(Timeout = 30000)] public async Task Snapshot_larger_than_queue_finishes_frozen_values_before_a_racing_delta() { @@ -998,3 +1153,17 @@ internal sealed class BlockingValueWriteSink : IDataSubscriptionDeliverySink public void Dispose() { if (Frame is DataSubscriptionValues) disposed.TrySetResult(true); } } } + +internal sealed class CountingSnapshotDemand(int target) : ISubscriptionDemandSource +{ + private int _count; + internal readonly TaskCompletionSource Reached = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal void Release() => _release.TrySetResult(); + public async ValueTask AcquireAsync(SubscriptionAuthorizedView view, DataSubscriptionSettings settings, CancellationToken cancellationToken) + { + if (Interlocked.Increment(ref _count) == target) { Reached.TrySetResult(); await _release.Task.WaitAsync(cancellationToken); } + return new SubscriptionDemandResult(DataItemStatus.Good, settings, 1, new Lease()); + } + private sealed class Lease : IDisposable { public void Dispose() { } } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSuppressedItemRecoveryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSuppressedItemRecoveryWireTests.cs new file mode 100644 index 000000000..486941133 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSuppressedItemRecoveryWireTests.cs @@ -0,0 +1,84 @@ +using System.Reflection; +using System.Threading.Channels; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Suppressed_sdk_item_receives_fresh_snapshot_after_held_metadata_renewal_without_another_revalidation() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + var renewalEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var releaseRenewal = new ManualResetEventSlim(); + LocalCatalogCoordinator? coordinator = null; + try + { + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, placements, anchor) => + { + var manager = (OtOpcUaNodeManager)typeof(SdkAddressSpaceSink) + .GetField("_nodeManager", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(sink)!; + var suppressed = typeof(OtOpcUaNodeManager).GetField("_suppressedItems", BindingFlags.Instance | BindingFlags.NonPublic)!; + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscription, anchor, 1, 100, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var original = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + + var replacement = Prepare(coordinator!); + manager.RevalidateMonitoredItems(); + ((int)suppressed.GetValue(manager)!).ShouldBe(1, "the old authorized item must be detached while its proof is withdrawn"); + original.SourceProof.IsValid.ShouldBeFalse(); + var denied = await PublishComposedValue(client, 1, ct); + StatusCode.IsBad(denied.StatusCode).ShouldBeTrue(); + var mapping = Mapping(origin.Raw); + mapping.AllowedOperations |= DataOperations.Read | DataOperations.Metadata; + placements.Stage(replacement, [mapping], [Connection()]); + coordinator!.Complete(replacement, true).ShouldBeTrue(); + subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8; + origin.Clock.Advance(TimeSpan.FromSeconds(5)); + await renewalEntered.Task.WaitAsync(TimeSpan.FromSeconds(10), ct); + ((int)suppressed.GetValue(manager)!).ShouldBe(1, "restored authority alone precedes the held metadata renewal"); + releaseRenewal.Set(); + var fresh = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct); + fresh.SourceProof.IsValid.ShouldBeTrue(); + original.SourceProof.IsValid.ShouldBeFalse(); + // No explicit revalidation or browse after restoration. The original item must resume. + origin.Clock.Advance(TimeSpan.FromMilliseconds(100)); + var recovered = await PublishComposedValue(client, 1, ct); + recovered.StatusCode.ShouldBe(StatusCodes.Good); + recovered.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8); + }, onPublished: update => published.Writer.TryWrite(update), onCoordinator: value => coordinator = value, + renewalSinkFactory: inner => new HeldRenewalSink(inner, renewalEntered, releaseRenewal)); + } + finally { releaseRenewal.Set(); } + } + + private sealed class HeldRenewalSink(IProjectedNamespacePageSink inner, TaskCompletionSource entered, + ManualResetEventSlim release) : IProjectedNamespacePageSink + { + public bool TryApply(NodeId parent, IReadOnlyList nodes, Func commit) => inner.TryApply(parent, nodes, commit); + public bool TryRemove(NodeId node, ProjectedVariableDefinition expected) => inner.TryRemove(node, expected); + public bool TryApplyRootLeaf(NodeId node, ProjectedVariableDefinition definition, Func commit) => inner.TryApplyRootLeaf(node, definition, commit); + public bool TryRenewExact(NodeId node, ProjectedVariableDefinition expected, ProjectedVariableDefinition replacement, Func commit) + { + entered.TrySetResult(); + if (!release.Wait(TimeSpan.FromSeconds(15))) return false; + return inner.TryRenewExact(node, expected, replacement, commit); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSuppressedTombstoneWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSuppressedTombstoneWireTests.cs new file mode 100644 index 000000000..252a7756a --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSuppressedTombstoneWireTests.cs @@ -0,0 +1,66 @@ +using System.Reflection; +using System.Threading.Channels; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task Tombstoning_a_suppressed_projected_item_retires_health_and_demand_before_client_delete() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; + subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + LocalCatalogCoordinator? coordinator = null; + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var sub = (await client.CreateSubscriptionAsync(new Opc.Ua.RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, sub, anchor, 1, 100, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + await NextPublished(published.Reader, x => x.IsCompleteSnapshot, ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(Opc.Ua.StatusCodes.Good); + + const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; + var manager = (OtOpcUaNodeManager)typeof(SdkAddressSpaceSink).GetField("_nodeManager", flags)!.GetValue(sink)!; + var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!; + var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!; + var item = keys.Cast().OfType().Single(x => x.ClientHandle == 1); + var health = (System.Collections.IDictionary)manager.GetType().GetField("_projectedHealthIndex", flags)!.GetValue(manager)!; + health.Contains(item).ShouldBeTrue(); + var demandField = item.GetType().GetField("_demand", flags).ShouldNotBeNull(); + var originalDemand = (IProjectedDemandLease)demandField.GetValue(item).ShouldNotBeNull(); + var slotsAtDisposal = -1; + demandField.SetValue(item, new ObserveDemandDisposal(originalDemand, () => slotsAtDisposal = health.Count)); + var anchors = (System.Collections.IDictionary)manager.GetType().GetField("_projectedAnchors", flags)!.GetValue(manager)!; + var entry = anchors[anchor].ShouldNotBeNull(); + var definition = (ProjectedAnchorDefinition)entry.GetType().GetField("Item1")!.GetValue(entry)!; + + _ = Prepare(coordinator!); + manager.RevalidateMonitoredItems(); + ((int)manager.GetType().GetField("_suppressedItems", flags)!.GetValue(manager)!).ShouldBe(1, + "the projected item must be detached before its anchor is removed"); + var before = origin.Clock.GetTimestamp(); + ((IProjectedAnchorSink)sink).TryRemoveProjectedAnchor(anchor, definition).ShouldBeTrue(); + origin.Clock.GetTimestamp().ShouldBe(before, "tombstone cleanup cannot depend on a later health timer"); + var remaining = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!; + remaining.Cast().ShouldNotContain(item); + health.Contains(item).ShouldBeFalse("a removed item cannot retain a health slot"); + slotsAtDisposal.ShouldBe(0, "the health slot must be released before demand capacity is returned"); + demandField.GetValue(item).ShouldBeNull(); + // The client subscription remains alive and has not issued DeleteMonitoredItems. + }, onPublished: update => published.Writer.TryWrite(update), onCoordinator: value => coordinator = value); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataWriteAdmissionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataWriteAdmissionTests.cs index f26277cc8..e74823bca 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataWriteAdmissionTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataWriteAdmissionTests.cs @@ -158,6 +158,33 @@ public sealed class GrpcDataWriteAdmissionTests route.Dispatched.Order().ShouldBe(["failed", "ok"]); } + [Fact] + public async Task Batch_preflight_time_counts_against_the_write_deadline() + { + using var fixture = new LocalDataFixture(); + var route = new RecordingRoute(fixture.Raw); + var executor = CreateExecutor(fixture, route); + using var value = DataValue.FromScalar(DataValueKind.Int32, 42); + var item = new WriteItem("one", "slow-preflight", fixture.Raw, value, 1, fixture.Serving.Incarnation, TimeSpan.FromSeconds(5)); + var items = new DelayedPreflightItems(item, fixture.Clock); + var result = await executor.WriteAsync(new(items, LocalDataFixture.Budget), TestContext.Current.CancellationToken); + result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); + route.Dispatched.ShouldBeEmpty("batch preflight consumed the remaining dispatch budget"); + } + + [Fact] + public async Task Slow_route_resolution_cannot_extend_the_original_write_deadline() + { + using var fixture = new LocalDataFixture(); + var route = new DelayedResolutionRoute(fixture.Raw, fixture.Clock); + var executor = CreateExecutor(fixture, route); + using var value = DataValue.FromScalar(DataValueKind.Int32, 42); + var result = await executor.WriteAsync(new([new("one", "slow-route", fixture.Raw, value, 1, + fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget), TestContext.Current.CancellationToken); + result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); + route.Dispatched.ShouldBeEmpty("the route delay exhausted the remaining physical dispatch budget"); + } + [Fact] public async Task Executor_rejects_a_stale_generation_before_route_or_registry_claim() { @@ -468,6 +495,32 @@ public sealed class GrpcDataWriteAdmissionTests } } + private sealed class DelayedPreflightItems(WriteItem item, ManualTimeProvider clock) : IReadOnlyList + { + private int _advanced; + public int Count => 1; + public WriteItem this[int index] => index == 0 ? item : throw new ArgumentOutOfRangeException(nameof(index)); + public IEnumerator GetEnumerator() + { + if (Interlocked.Exchange(ref _advanced, 1) == 0) clock.Advance(TimeSpan.FromSeconds(4)); + yield return item; + } + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + + private sealed class DelayedResolutionRoute(DataView view, ManualTimeProvider clock) : IDataWriteRoute + { + private readonly RecordingRoute _inner = new(view); + public string[] Dispatched => _inner.Dispatched; + public bool TryResolve(DataView requested, out WriteRouteTarget? target) + { + clock.Advance(TimeSpan.FromSeconds(4)); + return _inner.TryResolve(requested, out target); + } + public Task DispatchAsync(WriteAdmissionTicket ticket, WriteClaim claim, CancellationToken cancellationToken) => + _inner.DispatchAsync(ticket, claim, cancellationToken); + } + private sealed class RecordingRoute(DataView view, DataView? alternate = null) : IDataWriteRoute { private readonly System.Collections.Concurrent.ConcurrentQueue _dispatched = new(); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataDriverDemandActorTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataDriverDemandActorTests.cs index 1406950ce..ac6238955 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataDriverDemandActorTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataDriverDemandActorTests.cs @@ -13,6 +13,50 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; [Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P06")] public sealed class GrpcDataDriverDemandActorTests : RuntimeActorTestBase { + [Fact] + public async Task Baseline_quiet_acquisitions_refresh_receipt_without_fabricating_change_or_source_time() + { + var clock = new ManualTimeProvider(); + using var hub = HubTest.Create(clock: clock); + var publisher = new SourceSamplePublisher(hub, new("node-a", "serving-1", "Primary", 1, 1)); + const string driverId = "stub-driver-1"; + var incarnation = publisher.RegisterDriverIncarnation(driverId); + publisher.RegisterDriverShape(driverId, "tag", new(DataValueKind.Int32, null, -1)).ShouldBeTrue(); + publisher.EnsureDriverBinding("cluster", driverId, "tag", incarnation).ShouldBeTrue(); + publisher.TryCaptureDriver(driverId, "tag", incarnation, out var ticket).ShouldBeTrue(); + var driver = new BaselineAcquisitionDriver(); + var parent = CreateTestProbe(); + var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster", commsLossTimeout: TimeSpan.Zero, + sourcePublisher: publisher, sourceIncarnation: incarnation, acquisitionCapacity: new SubscriptionAcquisitionCapacity(8)), + TestContext.Current.CancellationToken); + actor.Tell(new DriverInstanceActor.InitializeRequested("{}")); + parent.ExpectMsg(m => m.Connected, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + await actor.Ask( + new DriverInstanceActor.Subscribe(["tag"], TimeSpan.FromSeconds(1)), PresenceBudget, TestContext.Current.CancellationToken); + driver.Entered.Task.IsCompletedSuccessfully.ShouldBeTrue("baseline must observe actual acquisitions"); + var original = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); + driver.FireAcquired("tag", 41, original); + parent.ExpectMsg(PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken).Items.ShouldHaveSingleItem().Value.ShouldBe(41); + hub.ProcessPending(); + using (var first = hub.Read(ticket)) + { + first.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(41); + first.ReceivedTimestamp.ShouldBe(clock.GetTimestamp()); + } + clock.Advance(TimeSpan.FromMinutes(2)); + driver.FireAcquired("tag", 41, original); + hub.ProcessPending(); + using var second = hub.Read(ticket); + second.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(41); + second.Sample.SourceTimestampUtc.ShouldBe(new DateTimeOffset(original)); + second.Sample.ServerTimestampUtc.ShouldBe(new DateTimeOffset(original)); + second.ReceivedTimestamp.ShouldBe(clock.GetTimestamp()); + second.Sample.Version.ShouldBe(2); + parent.ExpectNoMsg(TimeSpan.FromMilliseconds(100), TestContext.Current.CancellationToken); + } + [Fact] public async Task Desired_revision_is_acknowledged_only_after_the_actual_driver_operation() { @@ -380,6 +424,38 @@ public sealed class GrpcDataDriverDemandActorTests : RuntimeActorTestBase private sealed record Handle(string DiagnosticId) : ISubscriptionHandle; } + private sealed class BaselineAcquisitionDriver : StubDriver, ISubscribable, IAcknowledgedBaselineAcquisitionSource + { + internal readonly TaskCompletionSource Entered = + new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly ISubscriptionHandle _handle = new Handle(); + private Action? _callback; + private AcquisitionSubscriptionRequest? _request; + private int? _last; + public event EventHandler? OnDataChange; + public Task SubscribeAsync(IReadOnlyList references, TimeSpan interval, CancellationToken ct) => + Task.FromResult(_handle); + public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask; + public Task SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request, + Action callback, CancellationToken ct) + { + _request = request; + _callback = callback; + Entered.TrySetResult(request); + return Task.FromResult(new AcquisitionSubscriptionResult(_handle, request.RequestedSamplingInterval, + request.DesiredRevision, request.ProducerIncarnation)); + } + internal void FireAcquired(string reference, int value, DateTime timestamp) + { + var snapshot = new DataValueSnapshot(value, 0, timestamp, timestamp); + _callback!(new(_request!.DesiredRevision, _request.ProducerIncarnation, [new(reference, snapshot)])); + if (_last == value) return; + _last = value; + OnDataChange?.Invoke(this, new DataChangeEventArgs(_handle, reference, snapshot)); + } + private sealed class Handle : ISubscriptionHandle { public string DiagnosticId => "baseline"; } + } + private sealed class ControlledAcquisitionDriver : StubDriver, ISubscribable, IAcknowledgedAcquisitionSource { internal readonly TaskCompletionSource Entered = @@ -408,8 +484,8 @@ public sealed class GrpcDataDriverDemandActorTests : RuntimeActorTestBase internal void Fail() => _complete.TrySetException(new InvalidOperationException("device rejected replacement")); internal void FireLegacy(int value) => OnDataChange?.Invoke(this, new DataChangeEventArgs(_legacy, "legacy", new DataValueSnapshot(value, 0, null, null))); - internal void FireAcquired(string reference, int value) => _callback!(new(_request!.DesiredRevision, - _request.ProducerIncarnation, [new(reference, new DataValueSnapshot(value, 0, DateTime.UtcNow, DateTime.UtcNow))])); + internal void FireAcquired(string reference, int value, DateTime? timestamp = null) => _callback!(new(_request!.DesiredRevision, + _request.ProducerIncarnation, [new(reference, new DataValueSnapshot(value, 0, timestamp ?? DateTime.UtcNow, timestamp ?? DateTime.UtcNow))])); private sealed class Handle : ISubscriptionHandle { public string DiagnosticId => "controlled"; } } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataModbusBaselineFreshnessTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataModbusBaselineFreshnessTests.cs new file mode 100644 index 000000000..b64dd9e2b --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataModbusBaselineFreshnessTests.cs @@ -0,0 +1,84 @@ +using Akka.Actor; +using System.Threading.Channels; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Driver.Modbus; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; + +[Trait("Feature", "GrpcData"), Trait("Category", "Integration"), Trait("Phase", "P11")] +public sealed class GrpcDataModbusBaselineFreshnessTests : RuntimeActorTestBase +{ + [Fact] + public async Task Real_modbus_unchanged_poll_refreshes_source_cache_without_native_change() + { + var clock = new ManualTimeProvider(); + using var hub = HubTest.Create(clock: clock); + var publisher = new SourceSamplePublisher(hub, new("node-a", "serving-1", "Primary", 1, 1)); + const string driverId = "modbus-quiet"; + var incarnation = publisher.RegisterDriverIncarnation(driverId); + publisher.RegisterDriverShape(driverId, "Temp", new(DataValueKind.Int16, null, -1)).ShouldBeTrue(); + publisher.EnsureDriverBinding("cluster", driverId, "Temp", incarnation).ShouldBeTrue(); + publisher.TryCaptureDriver(driverId, "Temp", incarnation, out var ticket).ShouldBeTrue(); + var transport = new GatedTransport(); + await using var driver = new ModbusDriver(new ModbusDriverOptions + { + Host = "fake", Probe = new ModbusProbeOptions { Enabled = false }, + RawTags = [new RawTagEntry("Temp", """{"region":"HoldingRegisters","address":0,"dataType":"Int16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0}""", false)] + }, driverId, _ => transport); + var changeCount = 0; + driver.OnDataChange += (_, _) => Interlocked.Increment(ref changeCount); + var parent = CreateTestProbe(); + var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster", commsLossTimeout: TimeSpan.Zero, + sourcePublisher: publisher, sourceIncarnation: incarnation, acquisitionCapacity: new SubscriptionAcquisitionCapacity(8)), + TestContext.Current.CancellationToken); + actor.Tell(new DriverInstanceActor.InitializeRequested("{}")); + parent.ExpectMsg(m => m.Connected, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + await actor.Ask( + new DriverInstanceActor.Subscribe(["Temp"], TimeSpan.FromMilliseconds(100)), PresenceBudget, + TestContext.Current.CancellationToken); + + (await transport.NextRead()).SetResult(100); + var secondRead = await transport.NextRead(); // First poll and its callbacks completed. + hub.ProcessPending(); + using (var first = hub.Read(ticket)) + { + first.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe((short)100); + first.ReceivedTimestamp.ShouldBe(clock.GetTimestamp()); + } + clock.Advance(TimeSpan.FromMinutes(2)); + secondRead.SetResult(100); + await transport.NextRead(); // Second poll and its callbacks completed. + hub.ProcessPending(); + using var second = hub.Read(ticket); + second.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe((short)100); + second.ReceivedTimestamp.ShouldBe(clock.GetTimestamp()); + second.Sample.Version.ShouldBe(2); + Volatile.Read(ref changeCount).ShouldBe(1); + Sys.Stop(actor); + } + + private sealed class GatedTransport : IModbusTransport + { + private readonly Channel> _reads = Channel.CreateUnbounded>(); + public Task ConnectAsync(CancellationToken ct) => Task.CompletedTask; + public async Task SendAsync(byte unitId, byte[] pdu, CancellationToken ct) + { + pdu[0].ShouldBe((byte)3); + var response = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _reads.Writer.TryWrite(response); + var value = await response.Task.WaitAsync(ct); + return [3, 2, (byte)(value >> 8), (byte)value]; + } + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + internal Task> NextRead() => _reads.Reader.ReadAsync(TestContext.Current.CancellationToken) + .AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/GrpcDataProjectedMuxLifetimeTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/GrpcDataProjectedMuxLifetimeTests.cs new file mode 100644 index 000000000..b7a855e33 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/GrpcDataProjectedMuxLifetimeTests.cs @@ -0,0 +1,86 @@ +using System.Collections; +using System.Reflection; +using Akka.Actor; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; +using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.VirtualTags; + +[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P11")] +public sealed class GrpcDataProjectedMuxLifetimeTests : RuntimeActorTestBase +{ + [Fact] + public void Unregister_then_terminate_releases_delivered_quota_and_allows_new_subscriber() + { + var mux = ActorOfAsTestActorRef(DependencyMuxActor.Props()); + var original = CreateTestProbe(); + var replacement = CreateTestProbe(); + var watcher = CreateTestProbe(); + var refs = new[] { "a", "b", "c", "d" }; + var payload = new byte[4 * 1024 * 1024 - 1024]; + var proof = new Proof(); + mux.Tell(new DependencyMuxActor.RegisterInterest(refs, original.Ref)); + mux.Tell(Batch(refs, payload, proof)); + var wake = original.ExpectMsg(PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + wake.Consume(items => items.Count.ShouldBe(4)); + var actor = mux.UnderlyingActor; + SubscriberCount(actor).ShouldBe(1); + UsedBytes(actor).ShouldBeGreaterThan(15 * 1024 * 1024L); + + mux.Tell(new DependencyMuxActor.UnregisterInterest(original.Ref)); + SubscriberCount(actor).ShouldBe(1, "the live consumer may still own its delivered values"); + UsedBytes(actor).ShouldBeGreaterThan(15 * 1024 * 1024L); + mux.Tell(new DependencyMuxActor.RegisterInterest(["replacement"], replacement.Ref)); + var rejected = new Proof(); + mux.Tell(Batch(["replacement"], payload, rejected)); + rejected.IsValid.ShouldBeFalse("delivered values still consume the shared quota"); + replacement.ExpectNoMsg(TimeSpan.FromMilliseconds(100), TestContext.Current.CancellationToken); + + watcher.Watch(original.Ref); + Sys.Stop(original.Ref); + watcher.ExpectTerminated(original.Ref, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + AwaitAssert(() => + { + SubscriberCount(actor).ShouldBe(1, "the replacement has its own empty mailbox"); + HasSubscriber(actor, original.Ref).ShouldBeFalse(); + HasSubscriber(actor, replacement.Ref).ShouldBeTrue(); + UsedBytes(actor).ShouldBe(0); + }, duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var fresh = new Proof(); + mux.Tell(Batch(["replacement"], payload, fresh)); + var resumed = replacement.ExpectMsg(PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + resumed.Consume(items => items.ShouldHaveSingleItem().Value.ShouldBeSameAs(payload)); + fresh.IsValid.ShouldBeTrue(); + } + + private static DependencyMuxActor.ProjectedBatch Batch(IReadOnlyList refs, byte[] payload, Proof proof) => + new(refs.Select(reference => new DependencyMuxActor.ProjectedDependency("source", reference, + new ProjectedValueWrite(DataRealm.Raw, reference, 1, new ServingIdentity("node", "incarnation", "Primary", 1, 1), + new DataValueSnapshot(payload, 0, null, null), new DataAgeBounds(TimeSpan.Zero, TimeSpan.Zero), 0, proof))).ToArray()); + + private static int SubscriberCount(DependencyMuxActor actor) => + ((IDictionary)typeof(DependencyMuxActor).GetField("_projectedSubscribers", BindingFlags.Instance | BindingFlags.NonPublic)! + .GetValue(actor)!).Count; + private static bool HasSubscriber(DependencyMuxActor actor, IActorRef subscriber) => + ((IDictionary)typeof(DependencyMuxActor).GetField("_projectedSubscribers", BindingFlags.Instance | BindingFlags.NonPublic)! + .GetValue(actor)!).Contains(subscriber); + private static long UsedBytes(DependencyMuxActor actor) + { + var quota = typeof(DependencyMuxActor).GetField("_projectedQuota", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(actor)!; + return (long)quota.GetType().GetField("_used", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(quota)!; + } + + private sealed class Proof : IProjectedSamplePublicationProof + { + private int _valid = 1; + public bool IsValid => Volatile.Read(ref _valid) != 0; + public TimeProvider Clock => TimeProvider.System; + public void Invalidate() => Interlocked.Exchange(ref _valid, 0); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj index 93ea8b0a9..aff5c484c 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj @@ -33,6 +33,8 @@ host's Part 9 condition (ForwardNativeAlarm → NativeAlarmProjector), not merely that it was raised. --> + + @@ -47,6 +49,9 @@ + + +