using Grpc.Core; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Authorization; using ZB.MOM.WW.OtOpcUa.Host.Configuration; using ZB.MOM.WW.OtOpcUa.Host.Grpc; using ZB.MOM.WW.OtOpcUa.Host.OpcUa; using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; [Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P11")] public sealed class GrpcDataCompactNegotiationTests { [Theory] [InlineData(false, false)] [InlineData(true, true)] public async Task Stream_uses_compact_only_after_explicit_supported_opt_in(bool optIn, bool compact) { var headers = new Metadata(); if (optIn) headers.Add("x-data-compact-codec", "1"); var fixture = Create(headers, peerSupportsCompact: true); var writer = new Writer(); await fixture.Service.Subscribe(new Reader(), writer, fixture.Context); var frame = writer.Frames.ShouldHaveSingleItem(); (frame.CompactValues is not null).ShouldBe(compact); (frame.Values is not null).ShouldBe(!compact); frame.Serving.ShouldNotBeNull(); } [Fact] public async Task Opt_in_does_not_override_a_server_without_the_codec() { var fixture = Create(new Metadata { { "x-data-compact-codec", "1" } }, peerSupportsCompact: false); var writer = new Writer(); await fixture.Service.Subscribe(new Reader(), writer, fixture.Context); writer.Frames.ShouldHaveSingleItem().Values.ShouldNotBeNull(); } [Theory] [InlineData("2", false)] [InlineData("1", true)] public async Task Invalid_or_duplicate_codec_header_is_rejected(string value, bool duplicate) { var headers = new Metadata { { "x-data-compact-codec", value } }; if (duplicate) headers.Add("x-data-compact-codec", "1"); var fixture = Create(headers, peerSupportsCompact: true); var failure = await Should.ThrowAsync(() => fixture.Service.Subscribe(new Reader(), new Writer(), fixture.Context)); failure.StatusCode.ShouldBe(StatusCode.InvalidArgument); } private static (DataConnectionGrpcService Service, CallContext Context) Create(Metadata headers, bool peerSupportsCompact) { var (bearer, id, hash) = ApiKeySecret.Generate("pepper"); var authority = new DataPlaneAuthorityState(); authority.Apply("cluster", "v1", [new ApiKey { ApiKeyId = id, Name = "test", Principal = "peer", SecretHash = hash, Enabled = true }], [], new Dictionary>()); var authenticator = new DataConnectionAuthenticator(authority, Options.Create(new ApiKeyOptions { Pepper = "pepper" }), TimeProvider.System); var options = new DataConnectionOptions { Enabled = true, ListenPort = 9443, AllowedHosts = ["source.local"], CertificatePath = "server.pem" }; var context = new CallContext(headers); var http = new DefaultHttpContext(); http.Connection.LocalPort = 9443; http.Request.Protocol = "HTTP/2"; http.Request.Scheme = "https"; http.Request.Method = "POST"; http.Request.Host = new HostString("source.local", 9443); http.Request.Path = context.Method; http.Items[typeof(DataAuthenticatedContext)] = authenticator.Authenticate(bearer); http.Items[typeof(DataTarget)] = new DataTarget(DataTargetMode.Node, "cluster", "node"); context.UserState["__HttpContext"] = http; return (new DataConnectionGrpcService(new Factory(peerSupportsCompact), Options.Create(options), authenticator), context); } private sealed class Factory(bool compact) : IDataConnectionFactory { public IDataConnection Create(DataAuthenticatedContext context, DataTarget target) => new Connection(target, compact); } private sealed class Connection(DataTarget target, bool compact) : IDataConnection, IDataConnectionPublicationGate { internal static readonly ServingIdentity Serving = new("node", "boot", "Primary", 1, 1, 1); public DataTarget Target => target; public TimeProvider Clock => TimeProvider.System; public bool CanPublish(ServingIdentity expectedServing) => expectedServing == Serving; public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken token) => Task.FromResult(new DataCapabilities(1, 3, Serving, DataReadiness.Ready, DataOperations.Subscribe, new HashSet { DataValueKind.Int32 }, new(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)), compact, compact ? 1 : 0, "cluster", true, true)); public Task SubscribeAsync(CancellationToken token) => Task.FromResult(new Subscription()); public Task BrowseAsync(BrowseRequest request, CancellationToken token) => throw new NotSupportedException(); public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken token) => throw new NotSupportedException(); public Task> ReadAsync(ReadRequest request, CancellationToken token) => throw new NotSupportedException(); public Task> WriteAsync(WriteBatch request, CancellationToken token) => throw new NotSupportedException(); public ValueTask DisposeAsync() => ValueTask.CompletedTask; } private sealed class Subscription : IDataSubscriptionTransport { private readonly TaskCompletionSource _opened = new(TaskCreationOptions.RunContinuationsAsynchronously); public Task SendAsync(DataSubscriptionCommand command, CancellationToken token) { _opened.TrySetResult(); return Task.CompletedTask; } public IAsyncEnumerable ReadAllAsync(CancellationToken token) => throw new NotSupportedException(); public async Task RunDeliveryAsync(IDataSubscriptionDeliverySink sink, CancellationToken token) { await _opened.Task.WaitAsync(token); using var frame = new DataSubscriptionValues("s", 1, 1, true, [new(new("s", 1, 1, 1), new(DataValue.FromScalar(DataValueKind.Int32, 42), 0, null, null, Connection.Serving, 1), new(TimeSpan.Zero, TimeSpan.Zero), DataReadiness.Ready)]); using var prepared = await sink.PrepareAsync(frame, 16384, token); ((IDataPreparedSubscriptionPublication)prepared).SetPublicationGuard(() => true); await sink.WriteAsync(prepared, token); } public ValueTask DisposeAsync() => ValueTask.CompletedTask; } private sealed class Reader : IAsyncStreamReader { private int _read; public W.SubscriptionCommand Current { get; private set; } = null!; public async Task MoveNext(CancellationToken token) { if (Interlocked.Exchange(ref _read, 1) == 0) { Current = DataProtoMapper.EncodeCommand(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [], false, TimeSpan.FromMinutes(1), new(TimeSpan.FromSeconds(5), 1, 4096))); return true; } await Task.Delay(Timeout.Infinite, token); return false; } } private sealed class Writer : IServerStreamWriter { public List Frames { get; } = []; public WriteOptions? WriteOptions { get; set; } public Task WriteAsync(W.SubscriptionFrame frame) { Frames.Add(frame); return Task.CompletedTask; } public Task WriteAsync(W.SubscriptionFrame frame, CancellationToken cancellationToken) => WriteAsync(frame); } private sealed class CallContext(Metadata headers) : ServerCallContext { protected override string MethodCore => DataConnectionEndpoints.ServicePrefix + "Subscribe"; protected override string HostCore => "source.local"; protected override string PeerCore => "ipv4:127.0.0.1:0"; protected override DateTime DeadlineCore => DateTime.MaxValue; protected override Metadata RequestHeadersCore => headers; protected override CancellationToken CancellationTokenCore => TestContext.Current.CancellationToken; protected override Metadata ResponseTrailersCore { get; } = []; protected override Status StatusCore { get; set; } protected override WriteOptions? WriteOptionsCore { get; set; } protected override AuthContext AuthContextCore => new(null, new Dictionary>()); protected override ContextPropagationToken CreatePropagationTokenCore(ContextPropagationOptions? options) => throw new NotSupportedException(); protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders) => Task.CompletedTask; } }