test(grpc-data): X0 review - v1 gate drives the service from golden request hex and pins rejection statuses

This commit is contained in:
Joseph Doherty
2026-11-23 18:28:48 -05:00
parent 4d29d539d8
commit dac185a963
@@ -17,10 +17,14 @@ 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).
/// A v1 client's requests are replayed byte-for-byte against the server, and every response
/// must serialize to the golden bytes captured from the pre-X0 server (master <c>2e4e4063</c>).
/// The origin facade is deterministic, so no field is time-varying and nothing is normalised:
/// <see cref="Normalise"/> is the single place a later phase may list a genuinely varying field.
/// 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
@@ -30,8 +34,9 @@ public sealed class GrpcDataV1CompatibilityTests
public static TheoryData<string> Rpcs => new(RpcNames);
[Fact]
public void Recorded_v1_requests_are_unchanged()
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");
}
@@ -84,6 +89,48 @@ public sealed class GrpcDataV1CompatibilityTests
: 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();
}
internal static string Hex(byte[] bytes) => Convert.ToHexString(bytes);
@@ -138,17 +185,20 @@ internal static class V1Requests
/// </summary>
internal static class V1CompatibilityHarness
{
internal static async Task<string> DriveAsync(string rpc, Metadata headers) => (await DriveWithContextAsync(rpc, headers)).Bytes;
/// <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>
internal static async Task<string> DriveAsync(string rpc, Metadata headers, DataOperations operations = DataOperationSets.V1,
byte[]? request = null) => (await DriveWithContextAsync(rpc, headers, operations, request)).Bytes;
internal static async Task<(string Bytes, ServerCallContext Context)> DriveWithContextAsync(string rpc, Metadata headers)
internal static async Task<(string Bytes, ServerCallContext Context)> DriveWithContextAsync(string rpc, Metadata headers,
DataOperations operations = DataOperationSets.V1, byte[]? request = null)
{
var (service, context) = Create(rpc, headers);
return (await DriveAsync(service, context, rpc), context);
var (service, context) = Create(rpc, headers, operations);
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)
private static async Task<string> DriveAsync(DataConnectionGrpcService service, ServerCallContext context, string rpc, byte[] bytes)
{
var bytes = V1Requests.Bytes(rpc);
IMessage response = rpc switch
{
"GetCapabilities" => await service.GetCapabilities(W.CapabilitiesRequest.Parser.ParseFrom(bytes), context),
@@ -166,7 +216,8 @@ internal static class V1CompatibilityHarness
return string.Join("|", writer.Frames.Select(f => GrpcDataV1CompatibilityTests.Hex(GrpcDataV1CompatibilityTests.Normalise(f).ToByteArray())));
}
internal static (DataConnectionGrpcService Service, CallContext Context) Create(string rpc, Metadata headers)
internal static (DataConnectionGrpcService Service, CallContext Context) Create(string rpc, Metadata headers,
DataOperations operations = DataOperationSets.V1)
{
var (bearer, id, hash) = ApiKeySecret.Generate("pepper");
var authority = new DataPlaneAuthorityState();
@@ -181,18 +232,18 @@ internal static class V1CompatibilityHarness
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(), Options.Create(options), authenticator), context);
return (new DataConnectionGrpcService(new Factory(operations), Options.Create(options), authenticator), context);
}
internal static HttpContext Http(ServerCallContext context) => (HttpContext)context.UserState["__HttpContext"];
private sealed class Factory : IDataConnectionFactory
private sealed class Factory(DataOperations operations) : IDataConnectionFactory
{
public IDataConnection Create(DataAuthenticatedContext context, DataTarget target) => new Origin(target);
public IDataConnection Create(DataAuthenticatedContext context, DataTarget target) => new Origin(target, operations);
}
/// <summary>A deterministic v1 origin exercising every optional v1 field the encoders emit.</summary>
private sealed class Origin(DataTarget target) : IDataConnection, IDataConnectionPublicationGate, IDataConnectionDiscoveryGate
private sealed class Origin(DataTarget target, DataOperations operations) : IDataConnection, IDataConnectionPublicationGate, IDataConnectionDiscoveryGate
{
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);
@@ -203,8 +254,7 @@ internal static class V1CompatibilityHarness
public bool CanPublishCapabilities(DataCapabilities expected) => true;
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken token) => Task.FromResult(new DataCapabilities(
1, 3, Serving, DataReadiness.Ready,
DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe,
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));