Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1CompatibilityTests.cs
T

522 lines
34 KiB
C#

using Google.Protobuf;
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;
/// <summary>
/// Recorded-v1-client compatibility gate (plan test "C/H", exit gate of X0, H2, A2 and A3).
/// The recorded v1 client requests (<see cref="GrpcDataV1Goldens.Requests"/>, parsed from the golden hex, never
/// re-encoded) are replayed against the REAL <see cref="DataConnectionGrpcService"/> (header parsing, authentication
/// seam, readiness/permission gates, DataProtoMapper encoders, size checks, subscription sink). Only the origin
/// facade behind <see cref="IDataConnectionFactory"/> is a deterministic FAKE. Every response must serialize to the
/// golden bytes captured from the pre-X0 server (master <c>2e4e4063</c>); no field is time-varying, so nothing is
/// normalised (<see cref="Normalise"/> is the one place a later phase may list a genuinely varying field).
/// RULE for H2/A2/A3: first extend the fake origin to emit that phase's new-shape data, then this test must still see
/// the same golden bytes without the header. Never re-record the goldens.
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")]
public sealed class GrpcDataV1CompatibilityTests
{
/// <summary>Every RPC of the v1 service, in the order <see cref="GrpcDataV1Goldens"/> records them.</summary>
internal static readonly string[] RpcNames = ["GetCapabilities", "Browse", "GetMetadata", "Read", "Write", "Subscribe"];
/// <summary>
/// A2b: the fake origin grants the method bits and implements the method port; a header-less (or history-only) call
/// is refused FAILED_PRECONDITION before the origin, and the capabilities golden is unchanged (no bits 128/256).
/// </summary>
[Fact]
public async Task A2b_CallConditionMethod_is_served_only_on_a_call_that_negotiated_conditions()
{
var request = ZB.MOM.WW.OtOpcUa.Commons.DataConnections.DataConditionProtoMapper.EncodeMethodRequest(new DataConditionMethodRequest(
"op", V1Requests.Raw, DataConditionMethods.Acknowledge, new("inc", 1), null, "boot", TimeSpan.FromSeconds(5))).ToByteArray();
var before = Volatile.Read(ref V1CompatibilityHarness.Origin.MethodCalls);
foreach (var header in new[] { "", "history" })
{
var headers = header.Length == 0 ? new Metadata() : new Metadata { { "x-otopcua-data-features", header } };
(await Should.ThrowAsync<RpcException>(() => V1CompatibilityHarness.DriveAsync("CallConditionMethod", headers, request: request)))
.StatusCode.ShouldBe(StatusCode.FailedPrecondition);
}
Volatile.Read(ref V1CompatibilityHarness.Origin.MethodCalls).ShouldBe(before);
var response = W.ConditionMethodResponse.Parser.ParseFrom(Convert.FromHexString(await V1CompatibilityHarness.DriveAsync(
"CallConditionMethod", new Metadata { { "x-otopcua-data-features", "conditions" } }, request: request)));
response.State.ShouldBe((int)DataWriteState.DriverConfirmedSuccess);
(await V1CompatibilityHarness.DriveAsync("GetCapabilities", new Metadata())).ShouldBe(GrpcDataV1Goldens.Responses["GetCapabilities"]);
}
public static TheoryData<string> Rpcs => new(RpcNames);
[Fact]
public void Recorded_v1_requests_still_encode_identically()
{
// The service is driven from the golden hex itself; this only checks the request encoders did not drift.
foreach (var rpc in RpcNames)
Hex(V1Requests.Bytes(rpc)).ShouldBe(GrpcDataV1Goldens.Requests[rpc], $"recorded {rpc} request");
}
[Theory]
[MemberData(nameof(Rpcs))]
public async Task V1_client_without_feature_header_gets_the_recorded_v1_response_bytes(string rpc)
{
var actual = await V1CompatibilityHarness.DriveAsync(rpc, new Metadata());
actual.ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc} response diverged from the recorded v1 bytes");
}
[Theory]
[MemberData(nameof(Rpcs))]
public async Task Feature_header_changes_nothing_while_no_requested_feature_is_servable(string rpc)
{
// H2 supports history, but this origin advertises none (and conditions are A2): the effective set is empty.
var headers = new Metadata { { "x-otopcua-data-features", "history,conditions" } };
var actual = await V1CompatibilityHarness.DriveAsync(rpc, headers, history: false, conditions: false);
actual.ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc} response must not change when nothing requested is servable");
(await V1CompatibilityHarness.DriveAsync(rpc, new Metadata { { "x-otopcua-data-features", "conditions" } }, conditions: false))
.ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc}: conditions on an origin that cannot serve them change nothing");
}
[Fact]
public async Task A2_a_condition_capable_origin_shows_condition_shapes_only_with_the_header()
{
var headers = new Metadata { { "x-otopcua-data-features", "conditions" } };
var caps = W.CapabilitiesResponse.Parser.ParseFrom(Convert.FromHexString(await V1CompatibilityHarness.DriveAsync("GetCapabilities", headers)));
caps.Conditions.ShouldNotBeNull().MaxConditions.ShouldBe(1000);
(caps.Operations & 64u).ShouldBe(64u);
caps.History.ShouldBeNull("history was not requested");
var none = W.CapabilitiesResponse.Parser.ParseFrom(Convert.FromHexString(await V1CompatibilityHarness.DriveAsync("GetCapabilities", new Metadata())));
none.Conditions.ShouldBeNull(); (none.Operations & 64u).ShouldBe(0u);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task A2_a_header_less_stream_never_receives_arm_9_even_when_its_item_carries_a_condition_scope(bool scoped)
{
var open = W.SubscriptionCommand.Parser.ParseFrom(Convert.FromHexString(GrpcDataV1Goldens.Requests["Subscribe"]));
if (scoped) open.Open.Items[0].ConditionScope = new W.ConditionScope { IncludeInfo = true };
var v1 = await V1CompatibilityHarness.DriveAsync("Subscribe", new Metadata(), request: open.ToByteArray());
v1.ShouldBe(GrpcDataV1Goldens.Responses["Subscribe"], "the scope is stripped: the origin sees the v1 item");
v1.Split('|').Select(f => W.SubscriptionFrame.Parser.ParseFrom(Convert.FromHexString(f)).FrameCase)
.ShouldNotContain(W.SubscriptionFrame.FrameOneofCase.ConditionStates);
// Positive control: the same request WITH the header reaches the origin's condition item and arm 9 arrives.
var negotiated = await V1CompatibilityHarness.DriveAsync("Subscribe", new Metadata { { "x-otopcua-data-features", "conditions" } },
request: open.ToByteArray());
var cases = negotiated.Split('|').Select(f => W.SubscriptionFrame.Parser.ParseFrom(Convert.FromHexString(f)).FrameCase).ToArray();
if (scoped) cases.ShouldContain(W.SubscriptionFrame.FrameOneofCase.ConditionStates);
else cases.ShouldNotContain(W.SubscriptionFrame.FrameOneofCase.ConditionStates);
}
/// <summary>
/// A3: the fake origin now emits what the consumer registry consumes (begin with <c>total</c>, an info-carrying record,
/// <c>snapshot_complete</c>, a <c>removed</c> delta). A header-less caller — even one whose item carries a condition
/// scope — still gets the golden v1 bytes; the negotiated stream carries all three condition frames.
/// </summary>
[Fact]
[Trait("Phase", "A3")]
public async Task A3_consumer_condition_shapes_reach_only_a_negotiated_stream_and_v1_bytes_are_unchanged()
{
var open = W.SubscriptionCommand.Parser.ParseFrom(Convert.FromHexString(GrpcDataV1Goldens.Requests["Subscribe"]));
open.Open.Items[0].ConditionScope = new W.ConditionScope { IncludeInfo = true };
(await V1CompatibilityHarness.DriveAsync("Subscribe", new Metadata(), request: open.ToByteArray()))
.ShouldBe(GrpcDataV1Goldens.Responses["Subscribe"]);
(await V1CompatibilityHarness.DriveAsync("Subscribe", new Metadata(), request: Convert.FromHexString(GrpcDataV1Goldens.Requests["Subscribe"])))
.ShouldBe(GrpcDataV1Goldens.Responses["Subscribe"]);
var negotiated = (await V1CompatibilityHarness.DriveAsync("Subscribe", new Metadata { { "x-otopcua-data-features", "conditions" } },
request: open.ToByteArray())).Split('|').Select(f => W.SubscriptionFrame.Parser.ParseFrom(Convert.FromHexString(f)))
.Where(f => f.FrameCase == W.SubscriptionFrame.FrameOneofCase.ConditionStates)
.Select(ZB.MOM.WW.OtOpcUa.Commons.DataConnections.DataConditionProtoMapper.DecodeFrame).ToArray();
negotiated.Length.ShouldBe(3);
negotiated[0].Total.ShouldBe(1);
negotiated[1].SnapshotComplete.ShouldBeTrue();
negotiated[1].Items.Single().Info!.Placements.Single().Address.Identifier.ShouldBe("Plant/dev1/HR200");
negotiated[2].Items.Single().Removed.ShouldBeTrue();
}
[Fact]
public async Task H2_a_history_capable_origin_shows_history_shapes_only_with_the_header()
{
var headers = new Metadata { { "x-otopcua-data-features", "history" } };
var caps = W.CapabilitiesResponse.Parser.ParseFrom(Convert.FromHexString(await V1CompatibilityHarness.DriveAsync("GetCapabilities", headers)));
caps.History.ShouldNotBeNull();
(caps.Operations & 32u).ShouldBe(32u);
var metadata = W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(await V1CompatibilityHarness.DriveAsync("GetMetadata", headers)));
metadata.Items[0].Value.History.Historizing.ShouldBeTrue();
(metadata.Items[0].Value.AllowedOperations & 32u).ShouldBe(32u);
var browse = W.BrowseResponse.Parser.ParseFrom(Convert.FromHexString(await V1CompatibilityHarness.DriveAsync("Browse", headers)));
browse.Items[0].History.ShouldNotBeNull();
}
[Theory]
[MemberData(nameof(Rpcs))]
public async Task Every_rpc_records_the_requested_and_effective_feature_set(string rpc)
{
var (_, absent) = await V1CompatibilityHarness.DriveWithContextAsync(rpc, new Metadata());
DataConnectionGrpcService.CallFeatures(absent).ShouldBe(DataCallFeatures.None);
absent.UserState.ContainsKey(typeof(DataCallFeatures)).ShouldBeTrue();
var (_, requested) = await V1CompatibilityHarness.DriveWithContextAsync(rpc,
new Metadata { { "x-otopcua-data-features", "history" }, { "x-otopcua-data-features", " conditions, future" } });
// H2: history is effective on a history-capable origin; A2a: conditions on a condition-capable one.
DataConnectionGrpcService.CallFeatures(requested).ShouldBe(new DataCallFeatures(DataFeatures.History | DataFeatures.Conditions,
DataFeatures.History | DataFeatures.Conditions));
DataConnectionGrpcService.SupportedFeatures.ShouldBe(DataFeatures.History | DataFeatures.Conditions);
var (_, unservable) = await V1CompatibilityHarness.DriveWithContextAsync(rpc,
new Metadata { { "x-otopcua-data-features", "history" } }, history: false);
DataConnectionGrpcService.CallFeatures(unservable).ShouldBe(new DataCallFeatures(DataFeatures.History, DataFeatures.None));
}
public static TheoryData<string, string> MalformedHeaders()
{
var data = new TheoryData<string, string>();
foreach (var rpc in RpcNames) { data.Add(rpc, "binary"); data.Add(rpc, "oversized"); }
return data;
}
[Theory]
[MemberData(nameof(MalformedHeaders))]
public async Task Binary_or_oversized_feature_header_is_rejected_invalid_argument(string rpc, string shape)
{
var headers = shape == "binary"
? new Metadata { { "x-otopcua-data-features-bin", new byte[] { 0x68 } } }
: new Metadata { { "x-otopcua-data-features", "history," + new string(' ', 256) } };
var failure = await Should.ThrowAsync<RpcException>(() => V1CompatibilityHarness.DriveAsync(rpc, headers));
failure.StatusCode.ShouldBe(StatusCode.InvalidArgument);
// The same detail each RPC family already uses for any other invalid argument; no trailers.
failure.Status.Detail.ShouldBe(rpc == "Subscribe" ? "Invalid stream command." : "Invalid data request.");
failure.Trailers.ShouldBeEmpty();
}
public static TheoryData<string, string> V1Statuses()
{
var data = new TheoryData<string, string>();
foreach (var header in new[] { "", "history,conditions" })
{
data.Add("GetCapabilities/major-2", header);
data.Add("Browse/no-browse-grant", header);
data.Add("GetMetadata/no-metadata-grant", header);
data.Add("Read/no-read-grant", header);
data.Add("Subscribe/no-subscribe-grant", header);
}
return data;
}
/// <summary>The v1 rejection statuses (code, detail and trailers) do not change with or without the header.</summary>
[Theory]
[MemberData(nameof(V1Statuses))]
public async Task V1_rejections_keep_their_status_detail_and_trailers(string scenario, string header)
{
var headers = header.Length == 0 ? new Metadata() : new Metadata { { "x-otopcua-data-features", header } };
var (rpc, shape) = (scenario.Split('/')[0], scenario.Split('/')[1]);
var operations = shape switch
{
"no-browse-grant" => DataOperationSets.V1 & ~DataOperations.Browse,
"no-metadata-grant" => DataOperationSets.V1 & ~DataOperations.Metadata,
"no-read-grant" => DataOperationSets.V1 & ~DataOperations.Read,
"no-subscribe-grant" => DataOperationSets.V1 & ~DataOperations.Subscribe,
_ => DataOperationSets.V1,
};
var request = shape == "major-2" ? new W.CapabilitiesRequest { ProtocolMajor = 2, ProtocolMinor = 5 }.ToByteArray() : null;
var failure = await Should.ThrowAsync<RpcException>(() => V1CompatibilityHarness.DriveAsync(rpc, headers, operations, request));
var (code, detail) = shape == "major-2"
? (StatusCode.Unimplemented, "Incompatible protocol major.")
: (StatusCode.PermissionDenied, "Data operation denied.");
failure.StatusCode.ShouldBe(code);
failure.Status.Detail.ShouldBe(detail);
failure.Trailers.ShouldBeEmpty();
}
/// <summary>
/// v1 Write without a write grant is not an RpcException: each item is answered RejectedBeforeDispatch in the body
/// (after a serving re-check). Those bytes are pinned like the other goldens, with and without the header.
/// </summary>
[Theory]
[InlineData("")]
[InlineData("history,conditions")]
public async Task Write_without_a_write_grant_rejects_each_item_before_dispatch_with_the_v1_bytes(string header)
{
var headers = header.Length == 0 ? new Metadata() : new Metadata { { "x-otopcua-data-features", header } };
var actual = await V1CompatibilityHarness.DriveAsync("Write", headers, DataOperationSets.V1 & ~DataOperations.Write);
actual.ShouldBe(GrpcDataV1Goldens.Responses["Write/no-write-grant"]);
}
internal static string Hex(byte[] bytes) => Convert.ToHexString(bytes);
/// <summary>X0: no field varies. Add explicit, listed normalisations here only if a later phase needs one.</summary>
internal static IMessage Normalise(IMessage message) => message;
}
/// <summary>The recorded v1 client requests. Changing any value here invalidates the goldens.</summary>
internal static class V1Requests
{
internal static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 16, 65_536);
internal static readonly DataView Raw = new(new DataAddress("cluster", "https://zb.com/otopcua/raw", "s", "Plant/Speed"),
DataRealm.Raw, null, 0, "Plant/Speed");
internal static readonly DataView Folder = new(new DataAddress("cluster", "https://zb.com/otopcua/raw", "s", "Plant"),
DataRealm.Raw, null, 0, "Plant");
internal static readonly DataView Array = new(new DataAddress("cluster", "https://zb.com/otopcua/raw", "s", "Plant/Array"),
DataRealm.Raw, null, 0, "Plant/Array");
internal static readonly DataView Missing = new(new DataAddress("cluster", "https://zb.com/otopcua/raw", "s", "Plant/Missing"),
DataRealm.Raw, null, 0, "Plant/Missing");
internal static IMessage Message(string rpc) => rpc switch
{
"GetCapabilities" => new W.CapabilitiesRequest { ProtocolMajor = 1, ProtocolMinor = 5 },
"Browse" => DataProtoMapper.EncodeBrowseRequest(new BrowseRequest(Folder, null, null, Budget)),
"GetMetadata" => DataProtoMapper.EncodeMetadataRequest(new MetadataRequest([Raw, Missing], Budget)),
"Read" => DataProtoMapper.EncodeReadRequest(new ReadRequest([new("r1", Raw, TimeSpan.FromSeconds(2)), new("r2", Missing, null)], Budget)),
"Write" => WriteRequest(),
"Subscribe" => DataProtoMapper.EncodeCommand(new OpenSubscription("sub-1", 1, "open-1", TimeSpan.FromSeconds(5),
[new("item-1", Raw, new(TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null))],
false, TimeSpan.FromMinutes(5), Budget)),
_ => throw new ArgumentOutOfRangeException(nameof(rpc)),
};
private static W.WriteRequest WriteRequest()
{
using var first = DataValue.FromScalar(DataValueKind.Int32, 17);
using var second = DataValue.FromScalar(DataValueKind.String, "abc");
return DataProtoMapper.EncodeWriteRequest(new WriteBatch(
[
new("w1", "op-1", Raw, first, 1, "boot", TimeSpan.FromSeconds(4), 1),
new("w2", "op-2", Missing, second, 1, "boot", TimeSpan.FromSeconds(4), 1),
], Budget));
}
internal static byte[] Bytes(string rpc) => Message(rpc).ToByteArray();
}
/// <summary>
/// Drives the real <see cref="DataConnectionGrpcService"/> in-process with a recorded request and a
/// deterministic origin facade. Reusable by H2/A2/A3: pass the headers a client of that phase sends.
/// </summary>
internal static class V1CompatibilityHarness
{
/// <param name="operations">The fake origin's granted operations (default: the full v1 set).</param>
/// <param name="request">Request bytes; default is the recorded golden request for <paramref name="rpc"/>.</param>
/// <param name="history">
/// H2 new-shape data (default ON): the fake origin also grants HistoryRead, advertises history capabilities and
/// marks its scalar historized; a header-less caller must still get the golden bytes.
/// </param>
/// <param name="conditions">
/// A2a new-shape data (default ON): the fake origin also grants AlarmSubscribe, advertises condition capabilities and
/// answers a condition-scoped item with a condition frame (arm 9); a header-less caller must still get the golden bytes.
/// </param>
internal static async Task<string> DriveAsync(string rpc, Metadata headers, DataOperations operations = DataOperationSets.V1,
byte[]? request = null, bool history = true, bool conditions = true) =>
(await DriveWithContextAsync(rpc, headers, operations, request, history, conditions)).Bytes;
internal static async Task<(string Bytes, ServerCallContext Context)> DriveWithContextAsync(string rpc, Metadata headers,
DataOperations operations = DataOperationSets.V1, byte[]? request = null, bool history = true, bool conditions = true)
{
var (service, context) = Create(rpc, headers, operations, history, conditions);
return (await DriveAsync(service, context, rpc, request ?? Convert.FromHexString(GrpcDataV1Goldens.Requests[rpc])), context);
}
private static async Task<string> DriveAsync(DataConnectionGrpcService service, ServerCallContext context, string rpc, byte[] bytes)
{
IMessage response = rpc switch
{
"GetCapabilities" => await service.GetCapabilities(W.CapabilitiesRequest.Parser.ParseFrom(bytes), context),
"Browse" => await service.Browse(W.BrowseRequest.Parser.ParseFrom(bytes), context),
"GetMetadata" => await service.GetMetadata(W.MetadataRequest.Parser.ParseFrom(bytes), context),
"Read" => await service.Read(W.ReadRequest.Parser.ParseFrom(bytes), context),
"Write" => await service.Write(W.WriteRequest.Parser.ParseFrom(bytes), context),
"CallConditionMethod" => await service.CallConditionMethod(W.ConditionMethodRequest.Parser.ParseFrom(bytes), context),
"Subscribe" => null!,
_ => throw new ArgumentOutOfRangeException(nameof(rpc)),
};
if (rpc != "Subscribe")
return GrpcDataV1CompatibilityTests.Hex(GrpcDataV1CompatibilityTests.Normalise(response).ToByteArray());
var writer = new Writer();
await service.Subscribe(new Reader(W.SubscriptionCommand.Parser.ParseFrom(bytes)), writer, context);
return string.Join("|", writer.Frames.Select(f => GrpcDataV1CompatibilityTests.Hex(GrpcDataV1CompatibilityTests.Normalise(f).ToByteArray())));
}
internal static (DataConnectionGrpcService Service, CallContext Context) Create(string rpc, Metadata headers,
DataOperations operations = DataOperationSets.V1, bool history = true, bool conditions = true)
{
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<AclScopeRef, IReadOnlyList<NodeAclPath>>());
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(rpc, 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(operations, history, conditions), Options.Create(options), authenticator), context);
}
internal static HttpContext Http(ServerCallContext context) => (HttpContext)context.UserState["__HttpContext"];
private sealed class Factory(DataOperations operations, bool history, bool conditions) : IDataConnectionFactory
{
public IDataConnection Create(DataAuthenticatedContext context, DataTarget target) =>
new Origin(target, (history ? operations | DataOperations.HistoryRead : operations)
| (conditions && operations.HasFlag(DataOperations.Subscribe) ? DataOperationSets.ConditionGrants : DataOperations.None),
history, conditions);
}
/// <summary>A deterministic v1 origin exercising every optional v1 field the encoders emit.</summary>
internal sealed class Origin(DataTarget target, DataOperations operations, bool history, bool conditions) : IDataConnection, IDataConnectionPublicationGate, IDataConnectionDiscoveryGate,
IDataConditionMethodService
{
/// <summary>A2b: every method call that reached this origin (static: one harness per test call).</summary>
internal static int MethodCalls;
public Task<DataConditionMethodResult> CallConditionMethodAsync(DataConditionMethodRequest request, CancellationToken cancellationToken)
{
Interlocked.Increment(ref MethodCalls);
return Task.FromResult(new DataConditionMethodResult(DataWriteState.DriverConfirmedSuccess, 0, null, Serving));
}
internal static readonly ServingIdentity Serving = new("node", "boot", "Primary", 1, 1, 1);
private static readonly DateTimeOffset Source = new(2026, 11, 23, 12, 0, 0, TimeSpan.Zero);
private static readonly DateTimeOffset Server = Source.AddMilliseconds(250);
public DataTarget Target => target;
public TimeProvider Clock => TimeProvider.System;
public bool CanPublish(ServingIdentity expectedServing) => expectedServing == Serving;
public bool CanPublishCapabilities(DataCapabilities expected) => true;
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken token) => Task.FromResult(new DataCapabilities(
1, 3, Serving, DataReadiness.Ready, operations,
new HashSet<DataValueKind> { DataValueKind.Int32, DataValueKind.String, DataValueKind.Array },
new(16, 16, 65_536, 16, 4, 65_536, TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(10), TimeSpan.FromSeconds(5), 1000),
false, 0, "cluster", true, true, true, true, true,
history ? new DataHistoryCapabilities(true, true, true, ["Average"], 1, 10_000, 4, TimeSpan.FromSeconds(60)) : null,
conditions ? new DataConditionCapabilities(true, 7, 1000) : null));
// H2 new-shape data: HistoryRead granted, HistoryInfo present (the service strips both from a header-less call).
private DataMetadata Scalar => new(V1Requests.Raw, "Speed", "Variable", DataValueKind.Int32, -1, [], true,
DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe
| (history ? DataOperations.HistoryRead : DataOperations.None),
1, "src-1", "rpm", false, History: history ? new DataHistoryInfo(true) : null);
private DataMetadata ArrayItem => new(V1Requests.Array, "Array", "Variable", DataValueKind.Array, 1, [3], false,
DataOperations.Browse | DataOperations.Metadata | DataOperations.Read, 1, null, null, true, DataValueKind.UInt8,
History: history ? new DataHistoryInfo(false) : null);
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken token) => Task.FromResult(new DataBrowseBranch(
request.Parent, DataItemStatus.Good, [Scalar, ArrayItem], false, "next-page", new MetadataLease(1, 1, TimeSpan.FromSeconds(30))));
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken token) =>
Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(
[
new("0", DataItemStatus.Good, Scalar, null, new MetadataLease(1, 1, TimeSpan.FromSeconds(30))),
new("1", DataItemStatus.NotFound, null, "No such node."),
]);
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken token) =>
Task.FromResult<IReadOnlyList<ReadResult>>(
[
new("r1", DataItemStatus.Good, DataReadiness.Ready, TimeSpan.FromMilliseconds(120),
new DataSample(DataValue.FromScalar(DataValueKind.Int32, 42), 0, Source, Server, Serving, 7), null, new Lease()),
new("r2", DataItemStatus.Denied, DataReadiness.Unavailable, null, null, "Denied."),
]);
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken token) =>
Task.FromResult<IReadOnlyList<WriteItemResult>>(
[
new("w1", new(DataWriteState.DriverConfirmedSuccess, 0, null)),
new("w2", new(DataWriteState.RejectedBeforeDispatch, 0x80340000u, "Unknown node.")),
]);
public Task<IDataSubscription> SubscribeAsync(CancellationToken token) => Task.FromResult<IDataSubscription>(new Subscription());
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
private sealed class Lease : IDataPublicationLease { public bool IsValid => true; public void Dispose() { } }
private sealed class Subscription : IDataSubscriptionTransport
{
private readonly TaskCompletionSource<DataSubscriptionCommand> _opened = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Task SendAsync(DataSubscriptionCommand command, CancellationToken token) { _opened.TrySetResult(command); return Task.CompletedTask; }
public IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(CancellationToken token) => throw new NotSupportedException();
public async Task RunDeliveryAsync(IDataSubscriptionDeliverySink sink, CancellationToken token)
{
var open = (OpenSubscription)await _opened.Task.WaitAsync(token);
var handle = new DataItemHandle(open.SubscriptionId, open.StreamEpoch, 1, 1);
await Emit(sink, new DataSubscriptionAck(open.SubscriptionId, open.StreamEpoch, 1, open.CommandId,
[new("item-1", DataItemStatus.Good, handle, open.Items[0].Settings, null)]), token);
await Emit(sink, new DataSubscriptionControl(open.SubscriptionId, open.StreamEpoch, 2, DataStreamControlKind.SnapshotBegin,
[new(0, 3)], 1, 1, null), token);
using (var values = new DataSubscriptionValues(open.SubscriptionId, open.StreamEpoch, 3, true,
[new(handle, new(DataValue.FromScalar(DataValueKind.Int32, 42), 0, Source, Server, Serving, 7),
new(TimeSpan.Zero, TimeSpan.FromMilliseconds(120)), DataReadiness.Ready)]))
await Emit(sink, values, token);
await Emit(sink, new DataSubscriptionControl(open.SubscriptionId, open.StreamEpoch, 4, DataStreamControlKind.SnapshotEnd,
[new(0, 3)], 1, 1, "done"), token);
// A2a new-shape data: a condition-scoped item gets a snapshot-begin condition frame (arm 9).
if (open.Items[0].ConditionScope is not null)
{
// A3 new-shape data (what the consumer registry consumes): begin with `total`, a record with info and a
// placement, snapshot_complete, then a delta `removed` record at the hub watermark.
await Emit(sink, new DataSubscriptionConditions(open.SubscriptionId, open.StreamEpoch, 5, handle, true, 1, [], false), token);
var placement = new DataView(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1/HR200"),
DataRealm.Raw, null, 0, "Plant/dev1/HR200");
var key = new string('A', 43);
await Emit(sink, new DataSubscriptionConditions(open.SubscriptionId, open.StreamEpoch, 6, handle, true, null,
[new DataConditionState(key, 3, false, true, new DataConditionInfo("AlarmConditionType", "HR200",
DataConditionSourceKind.Native, [placement], 3), true, false, true, true, 0, 777, "high", 0, null, 0,
Source, true, new DataActivationMarker("inc", 1))], true), token);
await Emit(sink, new DataSubscriptionConditions(open.SubscriptionId, open.StreamEpoch, 7, handle, false, null,
[new DataConditionState(key, 3, true, false, null, false, false, false, false, 0, 0, "", 0, null, 0, null, false, null)],
false), token);
}
}
private static async Task Emit(IDataSubscriptionDeliverySink sink, DataSubscriptionFrame frame, CancellationToken token)
{
using var prepared = await sink.PrepareAsync(frame, 65_536, token);
((IDataPreparedSubscriptionPublication)prepared).SetPublicationGuard(() => true);
await sink.WriteAsync(prepared, token);
}
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
internal sealed class Reader(W.SubscriptionCommand open) : IAsyncStreamReader<W.SubscriptionCommand>
{
private int _read;
public W.SubscriptionCommand Current { get; private set; } = null!;
public async Task<bool> MoveNext(CancellationToken token)
{
if (Interlocked.Exchange(ref _read, 1) == 0) { Current = open; return true; }
await Task.Delay(Timeout.Infinite, token); return false;
}
}
internal sealed class Writer : IServerStreamWriter<W.SubscriptionFrame>
{
public List<W.SubscriptionFrame> 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);
}
internal sealed class CallContext(string rpc, Metadata headers) : ServerCallContext
{
protected override string MethodCore => DataConnectionEndpoints.ServicePrefix + rpc;
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<string, List<AuthProperty>>());
protected override ContextPropagationToken CreatePropagationTokenCore(ContextPropagationOptions? options) => throw new NotSupportedException();
protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders) => Task.CompletedTask;
}
}