Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataReceiveBoundTests.cs
T
Joseph Doherty 1724a175b6 fix(grpc-data): transport receive bound follows the call's decode limit (#963)
Grpc.Net.Client has no per-call receive limit, so Read/GetMetadata/Browse now go
through receive-bounded sibling channels (power-of-two size classes, min 16 KiB,
sharing the endpoint channel's handler). An oversized response to a scalar read is
refused from its length prefix instead of buffering up to MaxMessageBytes; such a
refusal stays a decode refusal (ArgumentException, no failover).
2026-12-01 21:11:38 -05:00

217 lines
13 KiB
C#

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;
/// <summary>
/// #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.
/// </summary>
[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<ArgumentException>(() =>
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<Grpc.Core.RpcException>().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<InvalidOperationException>(() => connection.ReadAsync(
new([new("0", View, null)], new DataBudget(TimeSpan.FromSeconds(5), 1, ChannelMaxBytes)), TestContext.Current.CancellationToken));
failure.InnerException.ShouldBeOfType<Grpc.Core.RpcException>().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<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "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<string>? Changed { add { } remove { } }
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
ValueTask.FromResult<DataConnectionSecurity?>(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<HttpResponseMessage> 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> { 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(); }
}
/// <summary>The head of a VALID ReadResponse of exactly <paramref name="declared"/> 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.</summary>
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;
}
}
/// <summary>A gRPC response body that declares <c>declared</c> payload bytes (<c>prefix</c>, then zeros) and produces them
/// lazily, counting what the client actually pulled (the observable of what the consumer buffered).</summary>
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<byte> 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<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) =>
ValueTask.FromResult(Read(buffer.Span));
public override Task<int> 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();
}
}