using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.DataConnections; [Trait("Category", "Unit")] [Trait("Feature", "GrpcData")] [Trait("Phase", "P01")] public sealed class GrpcDataContractsTests { [Fact] public void Realm_and_serving_provenance_are_part_of_view_identity() { var address = new DataAddress("cluster", "urn:test", "string", "same/path"); var raw = new DataView(address, DataRealm.Raw, "mapping", 1, "subject"); var uns = raw with { Realm = DataRealm.Uns }; raw.ShouldNotBe(uns); var first = new ServingIdentity("node-a", "incarnation", "primary", 1, 2); var second = first with { NodeId = "node-b" }; first.ShouldNotBe(second); new DataTarget(DataTargetMode.Node, "cluster", "node-a").Validate(); Should.Throw(() => new DataTarget(DataTargetMode.Node, "cluster", null).Validate()); } [Fact] public void Required_enums_reject_unspecified_and_unknown_values() { Should.Throw(() => DataContractValidation.Required(DataRealm.Unspecified)); Should.Throw(() => DataContractValidation.Required((DataTargetMode)99)); Should.Throw(() => new DataWriteOutcome(DataWriteState.Unspecified, 0, null).Validate()); } [Fact] public void Only_driver_confirmed_success_is_success() { new DataWriteOutcome(DataWriteState.DriverConfirmedSuccess, 0, null).IsConfirmedSuccess.ShouldBeTrue(); new DataWriteOutcome(DataWriteState.AcceptedUnconfirmed, 0, null).IsConfirmedSuccess.ShouldBeFalse(); new DataWriteOutcome(DataWriteState.OutcomeUnknown, 0, null).IsConfirmedSuccess.ShouldBeFalse(); } [Fact] public void Sample_preserves_optional_timestamps_and_owned_bytes() { var bytes = new byte[] { 1, 2 }; using var value = DataValue.FromBytes(bytes); bytes[0] = 9; value.GetBytes().ToArray().ShouldBe(new byte[] { 1, 2 }); using var sample = new DataSample(value.Retain(), 0x80000001, null, null, new ServingIdentity("node", "incarnation", "primary", 1, 2), 3); sample.SourceTimestampUtc.ShouldBeNull(); sample.ServerTimestampUtc.ShouldBeNull(); sample.StatusCode.ShouldBe(0x80000001u); } [Fact] public void Retained_size_covers_payload_and_shape_without_returning_mutable_storage() { using var bytes = DataValue.FromBytes(new byte[10]); using var text = DataValue.FromScalar(DataValueKind.String, "abcd"); using var array = DataValue.FromArray(DataValueKind.String, new object[] { "abc", "de" }, new[] { 2 }); bytes.EstimatedRetainedBytes.ShouldBe(298); text.EstimatedRetainedBytes.ShouldBe(296); array.EstimatedRetainedBytes.ShouldBe(498); using var lease = array.Retain(); lease.EstimatedRetainedBytes.ShouldBe(array.EstimatedRetainedBytes); lease.Dispose(); Should.Throw(() => lease.EstimatedRetainedBytes); } [Fact] public void Lease_deadline_is_anchored_to_request_start_and_bounded() { var lease = new MetadataLease(2, 3, TimeSpan.FromSeconds(15)); lease.Deadline(100, TimeSpan.FromSeconds(1), TimeProvider.System).ShouldBeLessThan( 100 + (long)(15 * TimeProvider.System.TimestampFrequency)); Should.Throw(() => new MetadataLease(2, 3, TimeSpan.Zero).Validate()); } [Fact] public void Compact_handle_is_scoped_to_stream_and_item_revision() { var first = new DataItemHandle("stream", 1, 10, 1); first.ShouldNotBe(first with { StreamEpoch = 2 }); first.ShouldNotBe(first with { ItemRevision = 2 }); Should.Throw(() => (first with { Handle = 0 }).Validate()); } [Fact] public void Write_admission_keeps_original_credential_separate_from_principal() { var view = new DataView(new DataAddress("cluster", "urn:test", "string", "tag"), DataRealm.Raw, null, 0, "subject"); var expiry = DateTimeOffset.UtcNow.AddMinutes(1); var ticket = new DataWriteAdmission("principal", view, 1, 2, "node-incarnation", "driver-incarnation", "operation", 100, "key-a", expiry, "fingerprint"); ticket.Validate(); ticket.PrincipalId.ShouldBe("principal"); ticket.ApiKeyId.ShouldBe("key-a"); ticket.CredentialVersion.ShouldBe("fingerprint"); ticket.CredentialExpiresUtc.ShouldBe(expiry); Should.Throw(() => (ticket with { ApiKeyId = "" }).Validate()); Should.Throw(() => (ticket with { CredentialVersion = "" }).Validate()); } [Fact] public void Empty_array_metadata_retains_its_element_type() { var view = new DataView(new DataAddress("cluster", "urn:test", "string", "tag"), DataRealm.Raw, null, 0, "subject"); var integerArray = new DataMetadata(view, "tag", "variable", DataValueKind.Array, 1, new[] { 0 }, false, DataOperations.Read, 1, null, null, false, DataValueKind.Int32); var stringArray = integerArray with { ArrayElementKind = DataValueKind.String }; integerArray.Validate(); stringArray.Validate(); integerArray.ShouldNotBe(stringArray); Should.Throw(() => (integerArray with { ArrayElementKind = null }).Validate()); Should.Throw(() => (integerArray with { ArrayElementKind = DataValueKind.Array }).Validate()); Should.Throw(() => (integerArray with { ValueKind = DataValueKind.Int32 }).Validate()); } [Fact] public void Capabilities_bind_expected_cluster_and_validate_required_discovery_fields() { var limits = new DataLimits(10, 10, 1024, 10, 1, 1024, TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); var capabilities = new DataCapabilities(1, 0, new ServingIdentity("node", "incarnation", "primary", 1, 1), DataReadiness.Ready, DataOperations.Read, new HashSet { DataValueKind.Int32 }, limits, false, 0, "cluster-a"); capabilities.Validate(); capabilities.ClusterId.ShouldBe("cluster-a"); Should.Throw(() => (capabilities with { ClusterId = "" }).Validate()); Should.Throw(() => (capabilities with { Readiness = DataReadiness.Unspecified }).Validate()); Should.Throw(() => (capabilities with { Serving = capabilities.Serving with { NodeId = "" } }).Validate()); Should.Throw(() => (capabilities with { ProtocolMajor = 0 }).Validate()); Should.Throw(() => (capabilities with { Limits = limits with { MaxBatchItems = 0 } }).Validate()); } [Fact] public void Wire_enum_numbers_are_stable() { Enum.GetNames().ShouldBe(new[] { "Unspecified", "Null", "Boolean", "Int8", "Int16", "Int32", "Int64", "UInt8", "UInt16", "UInt32", "UInt64", "Float", "Double", "String", "Bytes", "Timestamp", "Guid", "Array" }); Enum.GetValues().Select(x => (int)x).ShouldBe(Enumerable.Range(0, 18)); Enum.GetNames().ShouldBe(new[] { "Unspecified", "Good", "Denied", "NotFound", "Unsupported", "InvalidArgument", "Unavailable", "WaitingForInitialData", "Stale", "LimitExceeded", "InvalidContinuation", "TypeMismatch", "ResourceExhausted" }); Enum.GetValues().Select(x => (int)x).ShouldBe(Enumerable.Range(0, 13)); Enum.GetNames().ShouldBe(new[] { "Unspecified", "Ready", "WaitingForInitialData", "Unavailable", "Invalidated" }); Enum.GetValues().Select(x => (int)x).ShouldBe(Enumerable.Range(0, 5)); Enum.GetNames().ShouldBe(new[] { "Unspecified", "RejectedBeforeDispatch", "DriverConfirmedSuccess", "DriverConfirmedFailure", "AcceptedUnconfirmed", "OutcomeUnknown" }); Enum.GetValues().Select(x => (int)x).ShouldBe(Enumerable.Range(0, 6)); Enum.GetNames().ShouldBe(new[] { "Unspecified", "Status", "StatusValue", "StatusValueTimestamp" }); Enum.GetValues().Select(x => (int)x).ShouldBe(Enumerable.Range(0, 4)); Enum.GetNames().ShouldBe(new[] { "Unspecified", "SnapshotBegin", "SnapshotEnd", "CatalogInvalidated", "AuthorityInvalidated", "Heartbeat", "Reset", "Coalesced" }); Enum.GetValues().Select(x => (int)x).ShouldBe(Enumerable.Range(0, 8)); ((int)DataRealm.Raw).ShouldBe(1); ((int)DataRealm.Uns).ShouldBe(2); ((int)DataTargetMode.Node).ShouldBe(1); ((int)DataTargetMode.Cluster).ShouldBe(2); ((int)DataConsistency.Primary).ShouldBe(1); ((int)DataConsistency.ReadyReplica).ShouldBe(2); } [Fact] public void Settings_and_versioned_samples_reject_malformed_values() { var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, 1); settings.Validate(); Should.Throw(() => (settings with { Deadband = double.NaN }).Validate()); Should.Throw(() => (settings with { SamplingInterval = TimeSpan.FromSeconds(-1) }).Validate()); using var sample = new DataSample(DataValue.Null(), 0, null, null, new ServingIdentity("node", "incarnation", "primary", 1, 1), 1); sample.Validate(); Should.Throw(() => (sample with { Version = 0 }).Validate()); Should.Throw(() => (sample with { Serving = sample.Serving with { CatalogEpoch = 0 } }).Validate()); } [Fact] public void Limits_advertise_a_positive_per_value_element_budget() { var limits = new DataLimits(10, 10, 1024, 10, 1, 1024, TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); limits.MaxValueElements.ShouldBe(100_000); limits.Validate(); Should.Throw(() => (limits with { MaxValueElements = 0 }).Validate()); } [Fact] public void Authenticated_context_binds_the_original_credential_and_authority() { var expiry = DateTimeOffset.UtcNow.AddMinutes(1); var context = new DataAuthenticatedContext("principal", "key", "fingerprint", expiry, 7); context.Validate(); context.CredentialVersion.ShouldBe("fingerprint"); Should.Throw(() => (context with { CredentialVersion = "" }).Validate()); Should.Throw(() => (context with { AuthorityEpoch = 0 }).Validate()); typeof(IDataConnectionFactory).GetMethod(nameof(IDataConnectionFactory.Create))!.ReturnType.ShouldBe(typeof(IDataConnection)); } [Fact] public void Unmapped_view_rejects_a_mapping_revision() { var view = new DataView(new DataAddress("cluster", "urn:test", "string", "tag"), DataRealm.Raw, null, 1, "untrusted-subject"); Should.Throw(() => view.Validate()); } }