diff --git a/docs/ReadWriteOperations.md b/docs/ReadWriteOperations.md index bb6878570..4bb6a53aa 100644 --- a/docs/ReadWriteOperations.md +++ b/docs/ReadWriteOperations.md @@ -50,7 +50,16 @@ variable-length array has no declared bound and still reserves the whole per-rea (`min(4 MiB, MaxPendingBytes)`), so such reads run one at a time at the default; a read of that kind that is waiting for capacity holds back smaller reads for 100 ms (re-armed while it waits) so a steady stream of scalar reads cannot starve it. The reservation is also the read's decode limit, so an -origin answering more than the node's shape allows is refused rather than exceeding the bound. A +origin answering more than the node's shape allows is refused rather than exceeding the bound. **Since +#963** the gRPC transport enforces the same bound before buffering: a Read / GetMetadata / Browse +response is refused from its gRPC length prefix when it exceeds the call's decode limit rounded up to +a power of two (min 16 KiB, so a scalar read's transport bound is exactly its 16 KiB reservation; a +fixed-array read's at most 2 × its reservation), instead of first buffering up to the channel's +`MaxMessageBytes` — 64 concurrent scalar reads can no longer pin 64 × 4 MiB of transport buffers. +Grpc.Net.Client has no per-call receive limit, so each size class is a sibling channel sharing the +endpoint channel's handler (one connection pool). Such a refusal is a decode refusal (no endpoint +failover or discovery back-off), as before; a response over the channel maximum keeps its existing +endpoint-failure handling. A projected Write likewise reserves what its value needs (16 KiB + identifiers + 3 × the value's size bound — the budget the origin admits a write batch against), not the whole cap. A read that is not answered in time, or answers nothing servable (unreachable, not ready, older than the mapping's stale timeout), returns `BadWaitingForInitialData` as before; a diff --git a/docs/plans/evidence/grpc-data-ext/963.md b/docs/plans/evidence/grpc-data-ext/963.md new file mode 100644 index 000000000..d26a6f19e --- /dev/null +++ b/docs/plans/evidence/grpc-data-ext/963.md @@ -0,0 +1,42 @@ +# #963 — transport receive bound follows the projected read's decode limit + +2026-12-01. Follow-up of #960 (`960-961.md`). Consumer side of gRPC data connections (`GrpcDataConnection`). + +## Root cause + +#960 sized each projected read's reservation from the node's declared shape (16 KiB for a fixed-size scalar) and used it +as the decode limit, so up to 64 reads share the default 1 MiB `MaxPendingBytes`. But the gRPC channel's +`MaxReceiveMessageSize` was the connection's `MaxMessageBytes` (4 MiB by default) for every call, so Grpc.Net.Client +accepted and fully buffered any response up to that before `DataProtoMapper.Preflight` refused it at decode. A misbehaving +origin could make 64 scalar reads briefly hold ~64 × MaxMessageBytes. + +## Fix + +Grpc.Net.Client 2.76 has no per-call receive limit (only `GrpcChannelOptions.MaxReceiveMessageSize`; `CallOptions` and the +method config carry none), so each endpoint `ChannelEntry` lazily creates receive-bounded **sibling channels** that share the +owning channel's `HttpMessageHandler` (one connection pool; `DisposeHttpClient = false`, the owner still disposes it): + +- `ReceiveClassBytes(limit, max)` = smallest power of two ≥ the call's decode limit (min 16 KiB), capped at the channel + maximum. A scalar read's class is exactly its 16 KiB reservation; a fixed-array read's at most 2 × its reservation; a + whole-cap read uses the owning channel. At most log2(max / 16 KiB) + 1 siblings per endpoint channel. +- `Read`, `GetMetadata` and `Browse` (the `QueryAsync` calls decoded against `Limits(budget, caps)`) go through + `BoundedUnaryAsync`. Grpc.Net.Client checks the 5-byte length prefix against the limit **before** renting the payload + buffer, so nothing of the oversized payload is read. +- A `ResourceExhausted` from a sibling is rethrown as `ArgumentException("Envelope exceeds receiver limits.")` — the same + outcome as the decode refusal it pre-empts (no endpoint failover / discovery back-off). A response over the channel + maximum is unchanged (`RpcException` → endpoint failure). + +Not covered: `HistoryRead`, `CallConditionMethod` and the write path's metadata call still use the owning channel (they are +not part of the small-reservation read budget). + +## Red / green + +| Test | pre-fix | fix | +|---|---|---| +| Runtime.Tests `An_oversized_origin_response_to_a_scalar_read_is_refused_from_its_length_prefix` (1 MiB valid-protobuf response to a 16 KiB read, 4 MiB channel; counts bytes the client pulled from the body) | **FAIL** — 1048581 bytes consumed, then decode refused | pass — ≤ 5 bytes (the length prefix) | +| `A_normal_scalar_read_and_a_large_string_read_still_succeed` (16 KiB scalar, 20 K-char string at 128 KiB, same string at the channel max) | pass | pass | +| `A_response_over_the_channel_maximum_keeps_endpoint_failure_handling` (control) | pass | pass | +| `Receive_class_…` (8 cases) + `A_scalar_reservation_is_its_own_receive_class` | n/a (new API) | pass | +| Host.IntegrationTests `Receive_bounded_and_channel_maximum_reads_share_one_real_tls_channel` (real Kestrel TLS/HTTP2, 16 K / 64 K / 32 K / 16 K budgets on one connection) | n/a | pass | + +Pre-fix was reproduced by forcing `BoundedClient` to return the owning client. 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 301d6141a..e4da93646 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs @@ -25,13 +25,53 @@ public sealed record DataConnectionChannelIdentity(string ConnectionId, Uri Endp /// Caller-bound remote facade. All channels and requests are bounded by configured local limits. public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySubscriptionSource { - private sealed class ChannelEntry(DataConnectionChannelIdentity identity, GrpcChannel channel, string bearer) + private sealed class ChannelEntry(DataConnectionChannelIdentity identity, GrpcChannel channel, string bearer, + Func createBounded, int maxMessageBytes) { internal readonly DataConnectionChannelIdentity Identity = identity; internal readonly GrpcChannel Channel = channel; internal readonly W.DataConnectionService.DataConnectionServiceClient Client = new(channel); internal readonly string Bearer = bearer; internal readonly CancellationTokenSource Retired = new(); + private readonly Dictionary _bounded = new(); + private bool _disposed; + + /// + /// #963: a client whose transport receive limit is at most rounded up to its size + /// class (a power of two, at least ), so the response to a bounded unary call is + /// refused from its gRPC length prefix before the payload is buffered. Grpc.Net.Client has no per-call receive + /// limit (only ), so each class is a channel over the SAME + /// handler (one connection pool); at most log2(max / min) + 1 of them exist per endpoint channel. + /// + internal W.DataConnectionService.DataConnectionServiceClient BoundedClient(int receiveLimit) + { + var size = ReceiveClassBytes(receiveLimit, maxMessageBytes); + if (size >= maxMessageBytes) return Client; + lock (_bounded) + { + if (_disposed) throw new InvalidOperationException("Channel retired."); + if (_bounded.TryGetValue(size, out var existing)) return existing.Client; + var created = createBounded(size); + _bounded.Add(size, (created, new(created))); + return _bounded[size].Client; + } + } + internal void Dispose() + { + // The bounded channels do not own the handler; dispose them before the owning channel. + lock (_bounded) { _disposed = true; foreach (var item in _bounded.Values) item.Channel.Dispose(); _bounded.Clear(); } + Channel.Dispose(); + } + } + internal const int MinReceiveClassBytes = 16 * 1024; + /// #963: the transport receive-limit size class for a decode limit: the smallest power of two ≥ the limit + /// (at least ), never above the channel's configured maximum. + internal static int ReceiveClassBytes(int receiveLimit, int maxMessageBytes) + { + if (receiveLimit >= maxMessageBytes) return maxMessageBytes; + var size = (long)MinReceiveClassBytes; + while (size < receiveLimit) size <<= 1; + return (int)Math.Min(size, maxMessageBytes); } private sealed record Selected(ChannelEntry Channel, DataCapabilities Capabilities); // Capability discovery is a protocol envelope, not an operation result page. @@ -162,7 +202,7 @@ public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySu { // Physical Dispose and arbitrary cancellation callbacks may block. Keep quota charged until both end. await Task.Yield(); - try { await Task.WhenAll(cancelled, Task.Run(item.Channel.Dispose)).ConfigureAwait(false); } + try { await Task.WhenAll(cancelled, Task.Run(item.Dispose)).ConfigureAwait(false); } catch (Exception) { } finally { @@ -205,7 +245,11 @@ public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySu var channel = GrpcChannel.ForAddress(endpoint, new GrpcChannelOptions { HttpHandler = handler, DisposeHttpClient = true, DisableResolverServiceConfig = true, MaxReceiveMessageSize = _maxMessageBytes, MaxSendMessageSize = _maxMessageBytes }); - var entry = new ChannelEntry(key, channel, security.Bearer); + // #963: receive-bounded siblings share the owning channel's handler (and so its connections) and never dispose it. + var maxSend = _maxMessageBytes; + var entry = new ChannelEntry(key, channel, security.Bearer, receive => GrpcChannel.ForAddress(endpoint, + new GrpcChannelOptions { HttpHandler = handler, DisposeHttpClient = false, DisableResolverServiceConfig = true, + MaxReceiveMessageSize = receive, MaxSendMessageSize = maxSend }), _maxMessageBytes); _channels.Add(key, entry); return entry; } catch { handler.Dispose(); throw; } @@ -245,6 +289,22 @@ public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySu new(Headers(selected.Channel, RequestedFeatures(selected.Capabilities)), DateTime.UtcNow + Remaining(start, budget), ct); private DataDecodeLimits Limits(DataBudget budget, DataCapabilities caps) => new(Math.Min(budget.MaxItems, caps.Limits.MaxBatchItems), (int)Math.Min(Math.Min(budget.MaxBytes, _maxMessageBytes), caps.Limits.MaxMessageBytes), caps.Limits.MaxValueElements); + /// + /// #963: issues a unary call whose response the transport refuses above the call's decode limit + /// (.MaxBytes, rounded up to its receive class), so a misbehaving origin cannot make each + /// of up to MaxConcurrentCalls small reads (a #960 scalar reservation is 16 KiB) buffer a channel-maximum + /// message before decode refuses it. A response refused by that tighter bound is the same outcome as the decode + /// refusal it pre-empts (, no endpoint failover); one over the channel maximum keeps the + /// channel's existing endpoint-failure handling. + /// + private static async Task BoundedUnaryAsync(Selected selected, DataDecodeLimits limits, + Func> call) + { + var client = selected.Channel.BoundedClient(limits.MaxBytes); + try { return await call(client).ResponseAsync.ConfigureAwait(false); } + catch (RpcException ex) when (ex.StatusCode == StatusCode.ResourceExhausted && !ReferenceEquals(client, selected.Channel.Client)) + { throw new ArgumentException("Envelope exceeds receiver limits.", ex); } + } private async Task SelectAsync(Uri endpoint, long start, DataBudget budget, bool write, CancellationToken ct) { var channel = await ChannelAsync(endpoint, ct).ConfigureAwait(false); @@ -311,8 +371,9 @@ public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySu QueryAsync(request.Budget, async (selected, budget, options) => { var browseStarted = Clock.GetTimestamp(); - var wire = await selected.Channel.Client.BrowseAsync(DataProtoMapper.EncodeBrowseRequest(request with { Budget = budget }), options).ResponseAsync.ConfigureAwait(false); - Verify(wire.Serving, selected); var result = DataProtoMapper.DecodeBrowseResponse(wire, Limits(budget, selected.Capabilities)); + var limits = Limits(budget, selected.Capabilities); + var wire = await BoundedUnaryAsync(selected, limits, client => client.BrowseAsync(DataProtoMapper.EncodeBrowseRequest(request with { Budget = budget }), options)).ConfigureAwait(false); + Verify(wire.Serving, selected); var result = DataProtoMapper.DecodeBrowseResponse(wire, limits); if (result.Lease is { } lease && (lease.CatalogEpoch != selected.Capabilities.Serving.CatalogEpoch || lease.AuthorityEpoch != selected.Capabilities.Serving.AuthorityEpoch || lease.Duration > selected.Capabilities.Limits.MaxMetadataLease)) throw new InvalidOperationException("Browse lease has unexpected authority or duration."); @@ -330,8 +391,9 @@ public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySu 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)); + var limits = Limits(budget, selected.Capabilities); + var wire = await BoundedUnaryAsync(selected, limits, client => client.GetMetadataAsync(DataProtoMapper.EncodeMetadataRequest(request with { Budget = budget }), options)).ConfigureAwait(false); + Verify(wire.Serving, selected); var result = DataProtoMapper.DecodeMetadataResponse(wire, limits); 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) || selected.Capabilities.MetadataItemLeases && x.Lease is { } lease && @@ -354,10 +416,11 @@ public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySu var start = Clock.GetTimestamp(); return QueryAsync(request.Budget, async (selected, budget, options) => { - var wire = await selected.Channel.Client.ReadAsync(DataProtoMapper.EncodeReadRequest(request with { Budget = budget }), options).ResponseAsync.ConfigureAwait(false); + var limits = Limits(budget, selected.Capabilities); + var wire = await BoundedUnaryAsync(selected, limits, client => client.ReadAsync(DataProtoMapper.EncodeReadRequest(request with { Budget = budget }), options)).ConfigureAwait(false); Verify(wire.Serving, selected); var observedAt = Clock.GetTimestamp(); - var result = DataProtoMapper.DecodeReadResponse(wire, Limits(budget, selected.Capabilities), Clock.GetElapsedTime(start, observedAt)); + var result = DataProtoMapper.DecodeReadResponse(wire, limits, Clock.GetElapsedTime(start, observedAt)); try { if (result.Count != request.Items.Count || !result.Select(x => x.CorrelationId).SequenceEqual(request.Items.Select(x => x.CorrelationId)) || 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 index 40cda38ed..25ba68746 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataSampleFidelityTlsWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataSampleFidelityTlsWireTests.cs @@ -47,6 +47,28 @@ public sealed class GrpcDataSampleFidelityTlsWireTests finally { foreach (var result in results) result.Dispose(); } } + [Fact(Timeout = 30000), Trait("Issue", "963")] + public async Task Receive_bounded_and_channel_maximum_reads_share_one_real_tls_channel() + { + // #963: a scalar-reservation read goes through a receive-bounded sibling channel that SHARES the endpoint channel's + // real SocketsHttpHandler; a whole-channel read uses the owning channel. Both must work over the production TLS stack. + 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); + foreach (var maxBytes in new[] { 16 * 1024, 65536, 32 * 1024, 16 * 1024 }) + { + var results = await connection.ReadAsync(new ReadRequest([new ReadItem("one", View, TimeSpan.FromSeconds(5))], + new DataBudget(TimeSpan.FromSeconds(5), 1, maxBytes)), ct); + try { results.ShouldHaveSingleItem().Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(42); } + finally { foreach (var result in results) result.Dispose(); } + } + } + private sealed class Security(GrpcDataWireFixture fixture, DataConnectionTrustPolicy trust) : IDataConnectionSecurityProvider { public event Action? Changed { add { } remove { } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataReceiveBoundTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataReceiveBoundTests.cs new file mode 100644 index 000000000..91ef1cd57 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataReceiveBoundTests.cs @@ -0,0 +1,216 @@ +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 W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// #963: a projected read reserves by its node's declared shape (#960, 16 KiB for a scalar) and decodes within that, but +/// the gRPC transport used to admit any response up to the channel's MaxMessageBytes, so each of up to 64 concurrent +/// small reads could buffer a channel-maximum message before decode refused it. The transport receive bound now follows +/// the call's decode limit. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Issue", "963")] +public sealed class GrpcDataReceiveBoundTests +{ + private const int ChannelMaxBytes = 4 * 1024 * 1024; + private static readonly DataLimits Limits = new(16, 16, ChannelMaxBytes, 16, 4, ChannelMaxBytes, 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 int ScalarReservation => checked((int)ProjectedDataAccess.ProjectedEnvelopeBytes); + + [Fact] + public async Task An_oversized_origin_response_to_a_scalar_read_is_refused_from_its_length_prefix() + { + // The origin declares (and would stream) a 1 MiB response — well under the 4 MiB channel maximum — to a read whose + // budget is a scalar reservation. Before #963 the client read all of it and only then refused it at decode. + var handler = new OriginHandler { DeclaredReadBytes = 1024 * 1024 }; + using var manager = new DataConnectionManager("consumer", 1); + await using var connection = Connect(handler, manager); + var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, ScalarReservation); + + var refused = await Should.ThrowAsync(() => + connection.ReadAsync(new([new("0", View, null)], budget), TestContext.Current.CancellationToken)); + + // Only the 5-byte gRPC length prefix was consumed: nothing of the oversized payload was buffered (pre-fix: all + // 1 MiB + 5 bytes, then the decode preflight refused it). + handler.OversizedBytesConsumed.ShouldBeLessThanOrEqualTo(5); + refused.InnerException.ShouldBeOfType().StatusCode.ShouldBe(Grpc.Core.StatusCode.ResourceExhausted); + handler.ReadCalls.ShouldBe(1); + } + + [Fact] + public async Task A_normal_scalar_read_and_a_large_string_read_still_succeed() + { + var handler = new OriginHandler(); + using var manager = new DataConnectionManager("consumer", 1); + await using var connection = Connect(handler, manager); + var ct = TestContext.Current.CancellationToken; + + var scalar = await connection.ReadAsync(new([new("0", View, null)], new DataBudget(TimeSpan.FromSeconds(5), 1, ScalarReservation)), ct); + using (scalar.ShouldHaveSingleItem()) scalar[0].Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(42); + + // A variable-size read reserves the whole cap (#960); a 20 K-char string goes through a receive class above it. + handler.StringChars = 20_000; + var large = await connection.ReadAsync(new([new("0", View, null)], new DataBudget(TimeSpan.FromSeconds(5), 1, 128 * 1024)), ct); + using (large.ShouldHaveSingleItem()) ((string)large[0].Sample.ShouldNotBeNull().Value.GetScalar()!).Length.ShouldBe(20_000); + + // And a whole-channel budget still reads it over the unbounded channel. + var full = await connection.ReadAsync(new([new("0", View, null)], new DataBudget(TimeSpan.FromSeconds(5), 1, ChannelMaxBytes)), ct); + using (full.ShouldHaveSingleItem()) ((string)full[0].Sample.ShouldNotBeNull().Value.GetScalar()!).Length.ShouldBe(20_000); + handler.ReadCalls.ShouldBe(3); + } + + [Fact] + public async Task A_response_over_the_channel_maximum_keeps_endpoint_failure_handling() + { + // Control: the channel maximum itself is unchanged (RpcException → endpoint failure, not a decode refusal). + var handler = new OriginHandler { DeclaredReadBytes = ChannelMaxBytes + 1 }; + using var manager = new DataConnectionManager("consumer", 1); + await using var connection = Connect(handler, manager); + var failure = await Should.ThrowAsync(() => connection.ReadAsync( + new([new("0", View, null)], new DataBudget(TimeSpan.FromSeconds(5), 1, ChannelMaxBytes)), TestContext.Current.CancellationToken)); + failure.InnerException.ShouldBeOfType().StatusCode.ShouldBe(Grpc.Core.StatusCode.ResourceExhausted); + handler.OversizedBytesConsumed.ShouldBeLessThanOrEqualTo(5); + } + + [Theory] + [InlineData(1, 16 * 1024)] + [InlineData(16 * 1024, 16 * 1024)] + [InlineData(16 * 1024 + 1, 32 * 1024)] + [InlineData(16 * 1024 + 256 * 10, 32 * 1024)] + [InlineData(1024 * 1024, 1024 * 1024)] + [InlineData(3 * 1024 * 1024, ChannelMaxBytes)] + [InlineData(ChannelMaxBytes, ChannelMaxBytes)] + [InlineData(int.MaxValue, ChannelMaxBytes)] + public void Receive_class_is_the_reservation_rounded_up_to_a_power_of_two_within_the_channel_maximum(int limit, int expected) => + GrpcDataConnection.ReceiveClassBytes(limit, ChannelMaxBytes).ShouldBe(expected); + + [Fact] + public void A_scalar_reservation_is_its_own_receive_class() => + GrpcDataConnection.ReceiveClassBytes(ScalarReservation, ChannelMaxBytes).ShouldBe(ScalarReservation); + + private static GrpcDataConnection Connect(HttpMessageHandler handler, DataConnectionManager manager) + { + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + return new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), [new Uri("https://example.test")], + new Security(handler), manager.Acquire("link"), ChannelMaxBytes, 1); + } + + 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 OriginHandler : HttpMessageHandler + { + internal int? DeclaredReadBytes; + internal int StringChars; + internal int ReadCalls; + private CountingStream? _oversized; + internal long OversizedBytesConsumed => _oversized?.Consumed ?? 0; + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var path = request.RequestUri!.AbsolutePath; + if (path.EndsWith("/GetCapabilities", StringComparison.Ordinal)) + return Task.FromResult(Frame(DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 3, Serving, DataReadiness.Ready, + DataOperations.Read | DataOperations.Browse, new HashSet { DataValueKind.Int32, DataValueKind.String }, + Limits, false, 0, "c", false, true, true)).ToByteArray())); + if (!path.EndsWith("/Read", StringComparison.Ordinal)) throw new InvalidOperationException("Unexpected gRPC method."); + Interlocked.Increment(ref ReadCalls); + if (DeclaredReadBytes is { } declared) + { + _oversized = new CountingStream(OversizedPrefix(declared), declared); + var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new StreamContent(_oversized) }; + response.Content.Headers.ContentType = new("application/grpc"); response.TrailingHeaders.Add("grpc-status", "0"); + return Task.FromResult(response); + } + using var value = StringChars > 0 ? DataValue.FromScalar(DataValueKind.String, new string('x', StringChars)) + : DataValue.FromScalar(DataValueKind.Int32, 42); + var items = new[] { new ReadResult("0", DataItemStatus.Good, DataReadiness.Ready, TimeSpan.Zero, + new(value, 0, null, null, Serving, 1), null, AgeBounds: new(TimeSpan.Zero, TimeSpan.Zero)) }; + try + { + var wire = DataProtoMapper.EncodeReadResponse(items); wire.Serving = DataProtoMapper.EncodeServing(Serving); + return Task.FromResult(Frame(wire.ToByteArray())); + } + finally { foreach (var item in items) item.Dispose(); } + } + + /// The head of a VALID ReadResponse of exactly bytes: the serving identity, then one + /// unknown length-delimited field whose zero-filled body pads it out (streamed lazily). Unbounded, the client buffers and + /// parses all of it and only the decode preflight refuses it. + private static byte[] OversizedPrefix(int declared) + { + var serving = new W.ReadResponse { Serving = DataProtoMapper.EncodeServing(Serving) }.ToByteArray(); + const uint paddingTag = (1000u << 3) | 2u; + for (var body = declared - serving.Length - CodedOutputStream.ComputeUInt32Size(paddingTag); body > 0; body--) + { + if (serving.Length + CodedOutputStream.ComputeUInt32Size(paddingTag) + CodedOutputStream.ComputeLengthSize(body) + body != declared) continue; + using var buffer = new MemoryStream(); + buffer.Write(serving); + var output = new CodedOutputStream(buffer, leaveOpen: true); + output.WriteTag(paddingTag); output.WriteLength(body); output.Flush(); + return buffer.ToArray(); + } + throw new InvalidOperationException("No padding fits."); + } + + private static HttpResponseMessage Frame(byte[] payload) + { + 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; + } + } + + /// A gRPC response body that declares declared payload bytes (prefix, then zeros) and produces them + /// lazily, counting what the client actually pulled (the observable of what the consumer buffered). + private sealed class CountingStream(byte[] prefix, int declared) : Stream + { + private readonly byte[] _header = [.. Header(declared), .. prefix]; + private long _position; + private readonly long _length = 5L + declared; + internal long Consumed => Interlocked.Read(ref _position); + private static byte[] Header(int declared) + { + var header = new byte[5]; BinaryPrimitives.WriteInt32BigEndian(header.AsSpan(1, 4), declared); return header; + } + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + public override int Read(Span buffer) + { + var position = Interlocked.Read(ref _position); + var take = (int)Math.Min(buffer.Length, _length - position); + if (take <= 0) return 0; + for (var i = 0; i < take; i++) buffer[i] = position + i < _header.Length ? _header[position + i] : (byte)0; + Interlocked.Add(ref _position, take); + return take; + } + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) => + ValueTask.FromResult(Read(buffer.Span)); + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + Task.FromResult(Read(buffer.AsSpan(offset, count))); + 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 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(); + } +}