using System.Buffers.Binary; using System.Net; using Google.Protobuf; using Shouldly; using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; using Xunit; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; [Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")] public sealed class GrpcDataConnectionClientTests { private static readonly DataLimits Limits = new(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)); private static readonly ServingIdentity Serving = new("a", "boot", "Primary", 1, 1, 1); private static readonly DataView View = new(new("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x"); private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 16, 65536); [Fact, 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() { 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)])); var control = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionControl("s", 1, 2, DataStreamControlKind.Coalesced, [], 1, 1, null)); ack.Serving = control.Serving = DataProtoMapper.EncodeServing(Serving); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], new Security(new StreamWireHandler([ack, control])), 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 frames = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken); (await frames.MoveNextAsync()).ShouldBeTrue(); (await frames.MoveNextAsync()).ShouldBeTrue(); var diagnostics = connection.CaptureDiagnostics(1, 1, "artifact"); diagnostics.CoalescedCount.ShouldBe(1); diagnostics.OverflowCount.ShouldBeNull(); diagnostics.RegistrationCount.ShouldBe(1); } [Fact, Trait("Phase", "P09")] public async Task Transport_diagnostics_report_verified_endpoint_and_ambiguous_write_without_secrets() { 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://user:secret@example.test:8443/private?token=secret")], new Security(new WireHandler { LoseWrite = true }), manager.Acquire("link"), 65536, 1); 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(); using var value = DataValue.FromScalar(DataValueKind.Int32, 1); var outcome = await connection.WriteAsync(new([new("item", "one", View, value, 1, "boot", TimeSpan.FromSeconds(4), 1)], Budget), TestContext.Current.CancellationToken); outcome.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown); connection.CaptureDiagnostics(2, 3, "artifact").WriteUnknownCount.ShouldBe(1); manager.ApplyScope(new Dictionary>()); connection.CaptureDiagnostics(2, 3, "artifact").State.ShouldBe("disabled"); } [Fact] public void Security_material_does_not_render_the_presented_bearer() { var security = new DataConnectionSecurity("credential-v1", "trust-fingerprint", "sensitive-bearer-value", () => new WireHandler()); security.ToString().ShouldNotContain("sensitive-bearer-value"); } [Fact] public async Task Configured_pending_byte_cap_is_enforced_before_stream_command_send() { var handle = new DataItemHandle("s", 1, 1, 1); var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, settings, null)])); ack.Serving = DataProtoMapper.EncodeServing(Serving); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], new Security(new StreamWireHandler([ack])), manager.Acquire("link"), 65536, 1, maxPendingCommandBytes: 128); await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); await Should.ThrowAsync(() => subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken)); } [Fact] public async Task Pending_command_bytes_are_shared_across_streams() { var handle = new DataItemHandle("s", 1, 1, 1); var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, settings, null)])); ack.Serving = DataProtoMapper.EncodeServing(Serving); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], new Security(new StreamWireHandler([ack])), manager.Acquire("link"), 65536, 1, maxPendingCommandBytes: 500); await using var first = await connection.SubscribeAsync(TestContext.Current.CancellationToken); await using var second = await connection.SubscribeAsync(TestContext.Current.CancellationToken); await first.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken); await Should.ThrowAsync(() => second.SendAsync(new OpenSubscription("s2", 1, "open2", TimeSpan.FromSeconds(5), [new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken)); } [Fact] public void Local_stream_capacity_must_be_positive_independently_of_peer_limits() { using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); using var scope = manager.Acquire("link"); Should.Throw(() => new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], new Security(new WireHandler()), scope, 65536, 1, maxStreams: 0)); } [Fact] public async Task Negotiated_envelope_peer_must_advertise_a_positive_serving_generation() { using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], new Security(new WireHandler { ZeroServingGeneration = true }), manager.Acquire("link"), 65536, 1); await Should.ThrowAsync(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken)); } [Fact] public async Task Strict_generation_mismatch_is_rejected_without_dispatch_or_rebinding() { var first = new FailoverHandler("a", true); var second = new FailoverHandler("b", false); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), [new Uri("https://a.test"), new Uri("https://b.test")], new PairSecurity(first, second), manager.Acquire("link"), 65536, 2, eligibleNodeIds: new HashSet { "a", "b" }); using var value = DataValue.FromScalar(DataValueKind.Int32, 1); var result = await connection.WriteAsync(new([new("retry", "one", View, value, 1, "boot", TimeSpan.FromSeconds(4), 2)], Budget), TestContext.Current.CancellationToken); result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); first.WrittenIds.ShouldBeEmpty(); second.WrittenIds.ShouldBeEmpty(); } [Theory] [InlineData(false)] [InlineData(true)] public async Task Strict_discovery_skips_unavailable_or_mismatching_peer_before_first_dispatch(bool unavailable) { var first = new FailoverHandler("a", false, generation: 1, unavailable: unavailable); var second = new FailoverHandler("b", false, generation: 2); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), [new Uri("https://a.test"), new Uri("https://b.test")], new PairSecurity(first, second), manager.Acquire("link"), 65536, 2, eligibleNodeIds: new HashSet { "a", "b" }); using var value = DataValue.FromScalar(DataValueKind.Int32, 1); var result = await connection.WriteAsync(new([new("item", "one", View, value, 1, "boot", TimeSpan.FromSeconds(4), 2)], Budget), TestContext.Current.CancellationToken); result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess); first.WrittenIds.ShouldBeEmpty(); second.WrittenIds.ShouldBe(new[] { "item" }); } [Theory] [InlineData(false)] [InlineData(true)] public async Task Failed_legacy_metadata_does_not_block_strict_item_on_matching_endpoint(bool malformed) { var first = new FailoverHandler("a", true, generation: 1); var second = new FailoverHandler("b", false, generation: 2, metadataFailure: !malformed, badMetadata: malformed); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), [new Uri("https://a.test"), new Uri("https://b.test")], new PairSecurity(first, second), manager.Acquire("link"), 65536, 2, eligibleNodeIds: new HashSet { "a", "b" }); using var legacy = DataValue.FromScalar(DataValueKind.Int32, 1); using var strict = DataValue.FromScalar(DataValueKind.Int32, 2); var result = await connection.WriteAsync(new([ new("retry", "legacy", View, legacy, 1, "boot", TimeSpan.FromSeconds(4)), new("strict", "strict", View, strict, 1, "boot", TimeSpan.FromSeconds(4), 2)], Budget), TestContext.Current.CancellationToken); result.Select(x => x.Outcome.State).ShouldBe([DataWriteState.RejectedBeforeDispatch, DataWriteState.DriverConfirmedSuccess]); first.WrittenIds.ShouldBe(new[] { "retry" }); second.WrittenIds.ShouldBe(new[] { "strict" }); } [Fact] public async Task Failed_legacy_metadata_preserves_strict_item_for_a_later_matching_endpoint() { var first = new FailoverHandler("a", true, generation: 1); var second = new FailoverHandler("b", false, generation: 2, metadataFailure: true); var third = new FailoverHandler("c", false, generation: 3, metadataFailure: 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.Cluster, "c", null), [new Uri("https://a.test"), new Uri("https://b.test"), new Uri("https://c.test")], new TripleSecurity(first, second, third), manager.Acquire("link"), 65536, 3, eligibleNodeIds: new HashSet { "a", "b", "c" }); using var legacy = DataValue.FromScalar(DataValueKind.Int32, 1); using var strict = DataValue.FromScalar(DataValueKind.Int32, 2); var result = await connection.WriteAsync(new([ new("retry", "legacy", View, legacy, 1, "boot", TimeSpan.FromSeconds(4)), new("strict", "strict", View, strict, 1, "boot", TimeSpan.FromSeconds(4), 3)], Budget), TestContext.Current.CancellationToken); result.Select(x => x.Outcome.State).ShouldBe([DataWriteState.RejectedBeforeDispatch, DataWriteState.DriverConfirmedSuccess]); first.WrittenIds.ShouldBe(new[] { "retry" }); second.WrittenIds.ShouldBeEmpty(); third.WrittenIds.ShouldBe(new[] { "strict" }); } [Fact] public async Task Strict_generation_rejection_is_not_rebound_to_another_primary() { var first = new FailoverHandler("a", true); var second = new FailoverHandler("b", false); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), [new Uri("https://a.test"), new Uri("https://b.test")], new PairSecurity(first, second), manager.Acquire("link"), 65536, 2, eligibleNodeIds: new HashSet { "a", "b" }); using var value = DataValue.FromScalar(DataValueKind.Int32, 1); var result = await connection.WriteAsync(new([new("retry", "one", View, value, 1, "boot", TimeSpan.FromSeconds(4), 1)], Budget), TestContext.Current.CancellationToken); result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); first.WrittenIds.ShouldBe(new[] { "retry" }); second.WrittenIds.ShouldBeEmpty(); } [Fact] public async Task Legacy_peer_remains_readable_but_does_not_advertise_writable_metadata() { var handler = new WireHandler { NoWriteGenerationEnforcement = 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 caps = await connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken); (caps.Operations & DataOperations.Read).ShouldBe(DataOperations.Read); (caps.Operations & DataOperations.Write).ShouldBe(DataOperations.None); var branch = await connection.BrowseAsync(new(View, null, null, Budget), TestContext.Current.CancellationToken); branch.Items.ShouldHaveSingleItem().Writable.ShouldBeFalse(); (branch.Items[0].AllowedOperations & DataOperations.Write).ShouldBe(DataOperations.None); var metadata = await connection.GetMetadataAsync(new([View], Budget), TestContext.Current.CancellationToken); metadata.ShouldHaveSingleItem().Value!.Writable.ShouldBeFalse(); (metadata[0].Value!.AllowedOperations & DataOperations.Write).ShouldBe(DataOperations.None); } [Fact] public async Task Peer_without_generation_enforcement_is_never_sent_a_write() { var handler = new WireHandler { NoWriteGenerationEnforcement = true, LoseWrite = 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); using var value = DataValue.FromScalar(DataValueKind.Int32, 42); var result = await connection.WriteAsync(new([new("item", "op", View, value, 1, "boot", TimeSpan.FromSeconds(4))], Budget), TestContext.Current.CancellationToken); result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); handler.WriteCalls.ShouldBe(0); } [Fact] public async Task Lost_write_reply_is_unknown_and_is_not_resent() { var handler = new WireHandler { LoseWrite = true }; var security = new Security(handler); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], security, manager.Acquire("link"), 65536, 1); using var value = DataValue.FromScalar(DataValueKind.Int32, 42); var result = await connection.WriteAsync(new([new("item", "op", View, value, 1, "boot", TimeSpan.FromSeconds(4))], Budget), TestContext.Current.CancellationToken); result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown); handler.WriteCalls.ShouldBe(1); } [Fact] public async Task Browse_rejects_a_lease_from_another_authority_generation() { var handler = new WireHandler { BadBrowseLease = true }; using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1); await Should.ThrowAsync(() => connection.BrowseAsync(new(View, null, null, Budget), TestContext.Current.CancellationToken)); } [Fact] public async Task Read_rejects_a_response_from_another_boot() { var handler = new WireHandler { WrongReadServing = true }; using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1); await Should.ThrowAsync(() => connection.ReadAsync(new([new("item", View, null)], Budget), TestContext.Current.CancellationToken)); } [Fact] public async Task No_ready_primary_backs_off_before_probing_again() { var clock = new ManualTimeProvider(); var handler = new UnreadyHandler(); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1, clock, new HashSet { "a" }); await Should.ThrowAsync(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken)); await Should.ThrowAsync(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken)); handler.Calls.ShouldBe(1); clock.Advance(TimeSpan.FromMinutes(1)); await Should.ThrowAsync(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken)); handler.Calls.ShouldBe(2); } private sealed class UnreadyHandler : HttpMessageHandler { public int Calls { get; private set; } protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { Calls++; return Task.FromResult(Frame(DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, Serving with { Role = "Secondary" }, DataReadiness.Ready, DataOperations.Read, new HashSet { DataValueKind.Int32 }, Limits, false, 0, "c", false, true)))); } } [Fact] public async Task Discovery_consumes_each_write_items_original_budget_independently() { var clock = new ManualTimeProvider(); var handler = new FailoverHandler("a", false, () => clock.Advance(TimeSpan.FromMilliseconds(600))); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://a.test")], new PairSecurity(handler, handler), manager.Acquire("link"), 65536, 1, clock); using var first = DataValue.FromScalar(DataValueKind.Int32, 1); using var second = DataValue.FromScalar(DataValueKind.Int32, 2); var result = await connection.WriteAsync(new([new("expired", "one", View, first, 1, "boot", TimeSpan.FromMilliseconds(500)), new("live", "two", View, second, 1, "boot", TimeSpan.FromSeconds(3))], Budget), TestContext.Current.CancellationToken); result[0].Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); result[1].Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess); handler.WrittenIds.ShouldBe(new[] { "live" }); } [Fact] public async Task Failover_metadata_cannot_restart_a_rejected_items_budget() { var clock = new ManualTimeProvider(); var first = new FailoverHandler("a", true); var second = new FailoverHandler("b", false, onMetadata: () => clock.Advance(TimeSpan.FromMilliseconds(600))); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), [new Uri("https://a.test"), new Uri("https://b.test")], new PairSecurity(first, second), manager.Acquire("link"), 65536, 2, clock, new HashSet { "a", "b" }); using var value = DataValue.FromScalar(DataValueKind.Int32, 1); var result = await connection.WriteAsync(new([new("retry", "one", View, value, 1, "boot", TimeSpan.FromMilliseconds(500))], Budget), TestContext.Current.CancellationToken); result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); second.WrittenIds.ShouldBeEmpty(); } [Fact] public async Task Cluster_failover_retries_only_authenticated_pre_dispatch_rejection() { var first = new FailoverHandler("a", true); var second = new FailoverHandler("b", false); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), [new Uri("https://a.test"), new Uri("https://b.test")], new PairSecurity(first, second), manager.Acquire("link"), 65536, 2, eligibleNodeIds: new HashSet { "a", "b" }); using var firstValue = DataValue.FromScalar(DataValueKind.Int32, 1); using var secondValue = DataValue.FromScalar(DataValueKind.Int32, 2); var result = await connection.WriteAsync(new([new("retry", "one", View, firstValue, 1, "boot", TimeSpan.FromSeconds(4)), new("unknown", "two", View, secondValue, 1, "boot", TimeSpan.FromSeconds(4))], Budget), TestContext.Current.CancellationToken); result[0].Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess); result[1].Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown); second.WrittenIds.ShouldBe(new[] { "retry" }); } private sealed class PairSecurity(FailoverHandler first, FailoverHandler second) : IDataConnectionSecurityProvider { public event Action? Changed { add { } remove { } } public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => ValueTask.FromResult(new("v1", "ca1", "key", () => endpoint.Host == "a.test" ? first : second)); } private sealed class TripleSecurity(FailoverHandler first, FailoverHandler second, FailoverHandler third) : IDataConnectionSecurityProvider { public event Action? Changed { add { } remove { } } public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => ValueTask.FromResult(new("v1", "ca1", "key", () => endpoint.Host switch { "a.test" => first, "b.test" => second, _ => third })); } private sealed class FailoverHandler(string node, bool rejectFirst, Action? onCapabilities = null, Action? onMetadata = null, long generation = 1, bool unavailable = false, bool metadataFailure = false, bool badMetadata = false) : HttpMessageHandler { public List WrittenIds { get; } = []; protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var serving = new ServingIdentity(node, "boot", "Primary", 1, 1, generation); IMessage message; if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal)) { onCapabilities?.Invoke(); if (unavailable) throw new HttpRequestException("unavailable"); message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 3, serving, DataReadiness.Ready, DataOperations.Read | DataOperations.Write | DataOperations.Metadata, new HashSet { DataValueKind.Int32 }, Limits, false, 0, "c", false, true, true)); } else if (request.RequestUri.AbsolutePath.EndsWith("/GetMetadata", StringComparison.Ordinal)) { onMetadata?.Invoke(); if (metadataFailure) throw new HttpRequestException("metadata unavailable"); var metadata = new DataMetadata(View, "x", "tag", DataValueKind.Int32, -1, [], true, DataOperations.Write, badMetadata ? 2 : 1, null, null, false); var wire = DataProtoMapper.EncodeMetadataResponse([new("0", DataItemStatus.Good, metadata, null)]); wire.Serving = DataProtoMapper.EncodeServing(serving); message = wire; } else { var bytes = await request.Content!.ReadAsByteArrayAsync(cancellationToken); var write = W.WriteRequest.Parser.ParseFrom(bytes.AsSpan(5).ToArray()); WrittenIds.AddRange(write.Items.Select(x => x.CorrelationId)); var result = new W.WriteResponse { Serving = DataProtoMapper.EncodeServing(serving) }; foreach (var item in write.Items) result.Items.Add(DataProtoMapper.EncodeWriteResult(new(item.CorrelationId, new(rejectFirst ? item.CorrelationId == "retry" ? DataWriteState.RejectedBeforeDispatch : DataWriteState.OutcomeUnknown : DataWriteState.DriverConfirmedSuccess, 1, null)))); message = result; } return Frame(message); } } private static HttpResponseMessage Frame(IMessage message) { var payload = message.ToByteArray(); var framed = new byte[payload.Length + 5]; BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), payload.Length); payload.CopyTo(framed, 5); var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent(framed) }; response.Content.Headers.ContentType = new("application/grpc"); response.TrailingHeaders.Add("grpc-status", "0"); return response; } [Fact] public async Task Reconnect_cannot_reuse_the_same_subscription_epoch() { var handle = new DataItemHandle("s", 1, 1, 1); var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, settings, null)])); ack.Serving = DataProtoMapper.EncodeServing(Serving); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], new Security(new StreamWireHandler([ack])), manager.Acquire("link"), 65536, 1); var open = new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget); await using (var first = await connection.SubscribeAsync(TestContext.Current.CancellationToken)) { await first.SendAsync(open, TestContext.Current.CancellationToken); await using var reader = first.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken); (await reader.MoveNextAsync()).ShouldBeTrue(); } await using var second = await connection.SubscribeAsync(TestContext.Current.CancellationToken); await Should.ThrowAsync(() => second.SendAsync(open, TestContext.Current.CancellationToken)); } [Fact] public async Task Acknowledged_command_payload_is_not_retained_by_a_delayed_timer_continuation() { var handle = new DataItemHandle("s", 1, 1, 1); var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, settings, null)])); ack.Serving = DataProtoMapper.EncodeServing(Serving); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], new Security(new StreamWireHandler([ack])), manager.Acquire("link"), 65536, 1); WeakReference? pendingIdentity = null; var timerEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var releaseTimer = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); connection.PendingIdentityObserverForTests = weak => pendingIdentity = weak; connection.AfterTimerCancelledForTests = async () => { timerEntered.TrySetResult(); await releaseTimer.Task; }; try { await SendOneAndDrainAsync(connection, settings); await timerEntered.Task.WaitAsync(TestContext.Current.CancellationToken); for (var i = 0; i < 3; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } pendingIdentity.ShouldNotBeNull(); pendingIdentity.IsAlive.ShouldBeFalse(); } finally { releaseTimer.TrySetResult(); } } private static async Task SendOneAndDrainAsync(GrpcDataConnection connection, DataSubscriptionSettings settings) { await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(20), [new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken); await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken); (await reader.MoveNextAsync()).ShouldBeTrue(); (await reader.MoveNextAsync()).ShouldBeFalse(); } [Fact] public async Task Stream_acknowledgement_is_bound_to_the_sent_copy_not_a_mutated_caller_list() { var handle = new DataItemHandle("s", 1, 1, 1); var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null), null)])); ack.Serving = DataProtoMapper.EncodeServing(Serving); var handler = new StreamWireHandler([ack]); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1); await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); var items = new List { new("item", View, new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null)) }; await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), items, false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken); items.Clear(); await using var enumerator = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken); (await enumerator.MoveNextAsync()).ShouldBeTrue(); enumerator.Current.ShouldBeOfType(); } [Fact] public async Task Stream_rejects_reuse_of_a_removed_handle_for_a_new_item() { var handle = new DataItemHandle("s", 1, 1, 1); var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); W.SubscriptionFrame Ack(long sequence, string id, string clientId, DataItemHandle item) { var wire = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, sequence, id, [new(clientId, DataItemStatus.Good, item, settings, null)])); wire.Serving = DataProtoMapper.EncodeServing(Serving); return wire; } var handler = new StreamWireHandler([Ack(1, "open", "item", handle), Ack(2, "remove", "item", handle), Ack(3, "add", "other", handle)]); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1); await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken); await using var enumerator = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken); (await enumerator.MoveNextAsync()).ShouldBeTrue(); await subscription.SendAsync(new RemoveSubscriptionItems("s", 1, "remove", TimeSpan.FromSeconds(5), [handle]), TestContext.Current.CancellationToken); (await enumerator.MoveNextAsync()).ShouldBeTrue(); await subscription.SendAsync(new AddSubscriptionItems("s", 1, "add", TimeSpan.FromSeconds(5), [new("other", View, settings)]), TestContext.Current.CancellationToken); await Should.ThrowAsync(async () => await enumerator.MoveNextAsync()); } [Fact] public async Task Stream_rejects_a_sample_version_regression_before_yield() { var handle = new DataItemHandle("s", 1, 1, 1); var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, settings, null)])); ack.Serving = DataProtoMapper.EncodeServing(Serving); W.SubscriptionFrame ValueFrame(long seq, long version) { using var frame = new DataSubscriptionValues("s", 1, seq, false, [new(handle, new DataSample(DataValue.FromScalar(DataValueKind.Int32, 42), 0, null, null, Serving, version))]); var wire = DataProtoMapper.EncodeValues(frame, false); wire.Serving = DataProtoMapper.EncodeServing(Serving); return wire; } var handler = new StreamWireHandler([ack, ValueFrame(2, 100), ValueFrame(3, 99)]); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1); await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken); await using var enumerator = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken); (await enumerator.MoveNextAsync()).ShouldBeTrue(); (await enumerator.MoveNextAsync()).ShouldBeTrue(); ((IDisposable)enumerator.Current).Dispose(); await Should.ThrowAsync(async () => await enumerator.MoveNextAsync()); } private sealed class StreamWireHandler(IReadOnlyList frames) : HttpMessageHandler { 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, 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) { var bytes = frame.ToByteArray(); var prefix = new byte[5]; BinaryPrimitives.WriteInt32BigEndian(prefix.AsSpan(1), bytes.Length); stream.Write(prefix); stream.Write(bytes); } var sent = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _ = DrainRequestAsync(request.Content!, sent, cancellationToken); var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new StreamContent(new GatedResponseStream(stream.ToArray(), sent.Task)) }; response.Content.Headers.ContentType = new("application/grpc"); response.TrailingHeaders.Add("grpc-status", "0"); return Task.FromResult(response); } private static async Task DrainRequestAsync(HttpContent content, TaskCompletionSource sent, CancellationToken ct) { try { await content.CopyToAsync(new SignalSink(sent), ct); } catch (Exception) { sent.TrySetCanceled(); } } } private sealed class SignalSink(TaskCompletionSource sent) : Stream { public override bool CanRead => false; public override bool CanSeek => false; public override bool CanWrite => true; public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } public override void Flush() { } public override void Write(byte[] buffer, int offset, int count) { if (count > 0) sent.TrySetResult(); } public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) { if (buffer.Length > 0) sent.TrySetResult(); return ValueTask.CompletedTask; } public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); public override void SetLength(long value) => throw new NotSupportedException(); } private sealed class GatedResponseStream(byte[] bytes, Task sent) : MemoryStream(bytes) { public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) { await sent.WaitAsync(cancellationToken); return await base.ReadAsync(buffer, cancellationToken); } public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { await sent.WaitAsync(cancellationToken); return await base.ReadAsync(buffer, offset, count, cancellationToken); } } [Fact] public async Task Disposal_winning_before_stream_install_keeps_raw_send_charged() { var handler = new BlockedDuplexHandler(); var installReached = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var proceed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); using var manager = new DataConnectionManager("consumer", 1); var consumers = new HashSet { "consumer" }; manager.ApplyScope(new Dictionary { ["link"] = new(1, consumers) }); var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1, maxStreams: 1); connection.BeforeStreamInstallForTests = async () => { await handler.Started.Task.WaitAsync(TestContext.Current.CancellationToken); installReached.TrySetResult(); await proceed.Task.WaitAsync(TestContext.Current.CancellationToken); }; var opening = connection.SubscribeAsync(TestContext.Current.CancellationToken); Task? closing = null; try { await installReached.Task.WaitAsync(TestContext.Current.CancellationToken); closing = connection.DisposeAsync().AsTask(); proceed.TrySetResult(); await Should.ThrowAsync(() => opening); manager.ApplyScope(new Dictionary { ["link"] = new(2, consumers) }); await Should.ThrowAsync(() => closing.WaitAsync(TimeSpan.FromMilliseconds(500), TestContext.Current.CancellationToken)); Should.Throw(() => manager.Acquire("link")); } finally { proceed.TrySetResult(); handler.Release.TrySetResult(); try { await opening; } catch (Exception) { } if (closing is not null) await closing; await connection.DisposeAsync(); } } [Fact] public async Task Stream_capacity_is_reserved_before_blocked_capability_discovery() { var provider = new IgnoringSecurity(); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], provider, manager.Acquire("link"), 65536, 1, maxStreams: 1); var first = connection.SubscribeAsync(TestContext.Current.CancellationToken); try { await provider.Started.Task.WaitAsync(TestContext.Current.CancellationToken); await Should.ThrowAsync(() => connection.SubscribeAsync(TestContext.Current.CancellationToken)); provider.Sends.ShouldBe(1); } finally { provider.Release.TrySetResult(); try { await first; } catch (Exception) { } } } [Theory] [InlineData(false)] [InlineData(true)] public async Task Duplex_disposal_waits_for_ignored_preheaders_http_send(bool startReader) { var handler = new BlockedDuplexHandler(); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1); var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); IAsyncEnumerator? reader = null; Task? moving = null; try { await handler.Started.Task.WaitAsync(TestContext.Current.CancellationToken); if (startReader) { reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken); moving = reader.MoveNextAsync().AsTask(); } var closing = subscription.DisposeAsync().AsTask(); await Should.ThrowAsync(() => closing.WaitAsync(TimeSpan.FromMilliseconds(500), TestContext.Current.CancellationToken)); } finally { handler.Release.TrySetResult(); if (moving is not null) { try { await moving; } catch (Exception) { } } if (reader is not null) await reader.DisposeAsync(); await subscription.DisposeAsync(); } } private sealed class BlockedDuplexHandler : HttpMessageHandler { public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal)) return Frame(DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, Serving, DataReadiness.Ready, DataOperations.Subscribe, new HashSet { DataValueKind.Int32 }, Limits, false, 0, "c", false, true))); Started.TrySetResult(); await Release.Task; var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent([]) }; response.Content.Headers.ContentType = new("application/grpc"); response.TrailingHeaders.Add("grpc-status", "0"); return response; } } [Fact] public async Task Ignored_response_body_cancellation_remains_charged_after_rotation() { var provider = new IgnoringBodySecurity(); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], provider, manager.Acquire("link"), 65536, 1, maxConcurrentUnaryCalls: 1); var first = connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken); try { await provider.Started.Task.WaitAsync(TestContext.Current.CancellationToken); provider.Rotate(); await provider.Disposed.Task.WaitAsync(TestContext.Current.CancellationToken); first.IsCompleted.ShouldBeFalse(); var failure = await Should.ThrowAsync(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken)); failure.Message.ShouldBe("Unary capacity exhausted."); provider.Sends.ShouldBe(1); } finally { provider.Release.TrySetResult(); try { await first; } catch (Exception) { } } await WaitForReady(connection); provider.Sends.ShouldBe(2); } private sealed class IgnoringBodySecurity : IDataConnectionSecurityProvider { private int _version; public event Action? Changed; public int Sends; public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public TaskCompletionSource Disposed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => ValueTask.FromResult(new(_version.ToString(), "ca", "key", () => new IgnoringBodyHandler(this))); public void Rotate() { _version++; Changed?.Invoke("link"); } } private sealed class IgnoringBodyHandler(IgnoringBodySecurity owner) : HttpMessageHandler { protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (Interlocked.Increment(ref owner.Sends) > 1) return Task.FromResult(Frame(DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, Serving, DataReadiness.Ready, DataOperations.Read, new HashSet { DataValueKind.Int32 }, Limits, false, 0, "c", false, true)))); var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new StreamContent(new IgnoringBodyStream(owner)) }; response.Content.Headers.ContentType = new("application/grpc"); response.TrailingHeaders.Add("grpc-status", "0"); return Task.FromResult(response); } protected override void Dispose(bool disposing) { if (disposing) owner.Disposed.TrySetResult(); base.Dispose(disposing); } } private sealed class IgnoringBodyStream(IgnoringBodySecurity owner) : Stream { public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => false; public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) { owner.Started.TrySetResult(); await owner.Release.Task; return 0; } public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { owner.Started.TrySetResult(); await owner.Release.Task; return 0; } public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); public override void Flush() { } public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); public override void SetLength(long value) => throw new NotSupportedException(); public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); } [Fact] public async Task Ignored_http_cancellation_remains_charged_after_channel_dispose_and_rotation() { var provider = new IgnoringSecurity(); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], provider, manager.Acquire("link"), 65536, 1, maxConcurrentUnaryCalls: 1); var first = connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken); try { await provider.Started.Task.WaitAsync(TestContext.Current.CancellationToken); provider.Rotate(); await provider.Disposed.Task.WaitAsync(TestContext.Current.CancellationToken); first.IsCompleted.ShouldBeFalse(); var failure = await Should.ThrowAsync(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken)); failure.Message.ShouldBe("Unary capacity exhausted."); provider.Sends.ShouldBe(1); } finally { provider.Release.TrySetResult(); try { await first; } catch (Exception) { } } await WaitForReady(connection); provider.Sends.ShouldBe(2); } private static async Task WaitForReady(GrpcDataConnection connection) { for (var attempt = 0; attempt < 100; attempt++) { try { await connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken); return; } catch (InvalidOperationException) { await Task.Delay(50, TestContext.Current.CancellationToken); } } throw new TimeoutException("Fresh channel did not recover."); } private sealed class IgnoringSecurity : IDataConnectionSecurityProvider { private int _version; public event Action? Changed; public int Sends; public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public TaskCompletionSource Disposed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => ValueTask.FromResult(new(_version.ToString(), "ca", "key", () => new IgnoringHandler(this))); public void Rotate() { _version++; Changed?.Invoke("link"); } } private sealed class IgnoringHandler(IgnoringSecurity owner) : HttpMessageHandler { protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (Interlocked.Increment(ref owner.Sends) == 1) { owner.Started.TrySetResult(); await owner.Release.Task; } return Frame(DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, Serving, DataReadiness.Ready, DataOperations.Read, new HashSet { DataValueKind.Int32 }, Limits, false, 0, "c", false, true))); } protected override void Dispose(bool disposing) { if (disposing) owner.Disposed.TrySetResult(); base.Dispose(disposing); } } [Fact] public async Task Connection_disposal_retains_scope_until_physical_channel_cleanup_finishes() { var provider = new BlockingSecurity(); using var manager = new DataConnectionManager("consumer", 1); var members = new HashSet { "consumer" }; manager.ApplyScope(new Dictionary { ["link"] = new(1, members) }); var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], provider, manager.Acquire("link"), 65536, 1); try { await connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken); var disposal = connection.DisposeAsync().AsTask(); await provider.Entered.Task.WaitAsync(TestContext.Current.CancellationToken); manager.ApplyScope(new Dictionary { ["link"] = new(2, members) }); disposal.IsCompleted.ShouldBeFalse(); Should.Throw(() => manager.Acquire("link")); } finally { provider.Release.Set(); await connection.DisposeAsync(); } } [Fact] public async Task Blocked_channel_disposal_remains_charged_during_rotation() { var provider = new BlockingSecurity(); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], provider, manager.Acquire("link"), 65536, 1); try { await connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken); provider.Rotate(); await provider.Entered.Task.WaitAsync(TestContext.Current.CancellationToken); await Should.ThrowAsync(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken)); provider.Created.ShouldBe(1); } finally { provider.Release.Set(); } } private sealed class BlockingSecurity : IDataConnectionSecurityProvider { public event Action? Changed; public int Created { get; private set; } public ManualResetEventSlim Release { get; } = new(); public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => ValueTask.FromResult(new("v1", "ca1", "key", () => { Created++; return new BlockingHandler(this); })); public void Rotate() => Changed?.Invoke("link"); } private sealed class BlockingHandler(BlockingSecurity owner) : HttpMessageHandler { protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => Task.FromResult(Frame(DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, Serving, DataReadiness.Ready, DataOperations.Read, new HashSet { DataValueKind.Int32 }, Limits, false, 0, "c", false, true)))); protected override void Dispose(bool disposing) { if (disposing) { owner.Entered.TrySetResult(); owner.Release.Wait(); } base.Dispose(disposing); } } [Fact] public async Task Rotation_during_resolution_cannot_install_stale_security() { var provider = new DelayedSecurity(); using var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], provider, manager.Acquire("link"), 65536, 1); var pending = connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken); await provider.Started.Task.WaitAsync(TestContext.Current.CancellationToken); provider.Rotate(); provider.Resolved.SetResult(new("old", "old-ca", "key", () => { provider.Installed = true; throw new InvalidOperationException("Stale handler installed."); })); await Should.ThrowAsync(() => pending); provider.Installed.ShouldBeFalse(); } private sealed class DelayedSecurity : IDataConnectionSecurityProvider { public event Action? Changed; public bool Installed { get; set; } public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public TaskCompletionSource Resolved { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) { Started.TrySetResult(); return new(Resolved.Task); } public void Rotate() => Changed?.Invoke("link"); } private sealed class Security(HttpMessageHandler handler) : IDataConnectionSecurityProvider { public event Action? Changed { add { } remove { } } public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => ValueTask.FromResult(new("v1", "ca1", "key", () => handler)); } private sealed class WireHandler : HttpMessageHandler { public bool LoseWrite { get; init; } public bool NoWriteGenerationEnforcement { get; init; } public bool WrongReadServing { get; init; } public bool ZeroServingGeneration { get; init; } public bool BadBrowseLease { get; init; } public int WriteCalls { get; private set; } protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { IMessage message; if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal)) message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, NoWriteGenerationEnforcement ? 2 : 3, ZeroServingGeneration ? Serving with { ServingGeneration = 0 } : Serving, DataReadiness.Ready, DataOperations.Read | DataOperations.Write | DataOperations.Browse | DataOperations.Metadata, new HashSet { DataValueKind.Int32 }, Limits, false, 0, "c", false, true, !NoWriteGenerationEnforcement)); else if (request.RequestUri.AbsolutePath.EndsWith("/Write", StringComparison.Ordinal)) { WriteCalls++; if (LoseWrite) throw new HttpRequestException("Lost response after send."); message = new W.WriteResponse { Serving = DataProtoMapper.EncodeServing(Serving) }; } else if (request.RequestUri.AbsolutePath.EndsWith("/Browse", StringComparison.Ordinal)) { var children = NoWriteGenerationEnforcement ? new[] { new DataMetadata(View, "x", "tag", DataValueKind.Int32, -1, [], true, DataOperations.Read | DataOperations.Write, 1, null, null, false) } : []; var browse = DataProtoMapper.EncodeBrowseResponse(new DataBrowseBranch(View, DataItemStatus.Good, children, true, null, new MetadataLease(Serving.CatalogEpoch, BadBrowseLease ? Serving.AuthorityEpoch + 1 : Serving.AuthorityEpoch, TimeSpan.FromSeconds(1)))); browse.Serving = DataProtoMapper.EncodeServing(Serving); message = browse; } else if (request.RequestUri.AbsolutePath.EndsWith("/GetMetadata", StringComparison.Ordinal)) { var metadata = new DataMetadata(View, "x", "tag", DataValueKind.Int32, -1, [], true, DataOperations.Read | DataOperations.Write, 1, null, null, false); var wire = DataProtoMapper.EncodeMetadataResponse([new("0", DataItemStatus.Good, metadata, null)]); wire.Serving = DataProtoMapper.EncodeServing(Serving); message = wire; } else if (request.RequestUri.AbsolutePath.EndsWith("/Read", StringComparison.Ordinal)) message = new W.ReadResponse { Serving = DataProtoMapper.EncodeServing(WrongReadServing ? Serving with { Incarnation = "other" } : Serving) }; else throw new InvalidOperationException("Unexpected call."); var payload = message.ToByteArray(); var framed = new byte[payload.Length + 5]; BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), payload.Length); payload.CopyTo(framed, 5); var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent(framed) }; response.Content.Headers.ContentType = new("application/grpc"); response.TrailingHeaders.Add("grpc-status", "0"); return Task.FromResult(response); } } [Fact] public void Only_explicit_rejection_can_be_selected_for_mutation_retry() { var outcomes = new[] { new WriteItemResult("rejected", new(DataWriteState.RejectedBeforeDispatch, 1, null)), new WriteItemResult("unknown", new(DataWriteState.OutcomeUnknown, 1, null)), new WriteItemResult("accepted", new(DataWriteState.AcceptedUnconfirmed, 1, null)), new WriteItemResult("success", new(DataWriteState.DriverConfirmedSuccess, 0, null)) }; GrpcDataConnection.RetryableWriteIndexes(outcomes).ShouldBe(new[] { 0 }); } [Fact] public void Demotion_is_negative_proof_only_for_an_entirely_rejected_batch_from_the_same_boot() { var expected = new ServingIdentity("a", "boot", "Primary", 4, 5); var demoted = expected with { Role = "Secondary", AuthorityEpoch = 6 }; var rejected = new WriteItemResult("a", new(DataWriteState.RejectedBeforeDispatch, 1, null)); var unknown = new WriteItemResult("b", new(DataWriteState.OutcomeUnknown, 1, null)); GrpcDataConnection.AcceptWriteServing(expected, demoted, [rejected]).ShouldBeTrue(); GrpcDataConnection.AcceptWriteServing(expected, demoted, [rejected, unknown]).ShouldBeFalse(); GrpcDataConnection.AcceptWriteServing(expected, demoted with { Incarnation = "new" }, [rejected]).ShouldBeFalse(); GrpcDataConnection.AcceptWriteServing(expected, demoted with { NodeId = "b" }, [rejected]).ShouldBeFalse(); GrpcDataConnection.AcceptWriteServing(expected, demoted, []).ShouldBeFalse(); } [Fact] public void Channel_identity_includes_both_security_versions() { var endpoint = new Uri("https://node.example:8443"); var first = new DataConnectionChannelIdentity("link", endpoint, "credential-1", "trust-1"); first.ShouldNotBe(first with { CredentialVersion = "credential-2" }); first.ShouldNotBe(first with { TrustFingerprint = "trust-2" }); } }