test(grpc-data): A2a — recorded-v1-client gates: fake and real origins serve conditions; header-less stays golden and never sees arm 9

This commit is contained in:
Joseph Doherty
2026-11-24 12:19:17 -05:00
parent 6bb8fa6914
commit b24af31e1a
2 changed files with 123 additions and 21 deletions
@@ -55,10 +55,41 @@ public sealed class GrpcDataV1CompatibilityTests
{
// 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);
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" } }))
.ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc}: conditions are not supported before A2");
(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);
}
[Fact]
@@ -85,9 +116,10 @@ public sealed class GrpcDataV1CompatibilityTests
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; conditions are not supported before A2.
DataConnectionGrpcService.CallFeatures(requested).ShouldBe(new DataCallFeatures(DataFeatures.History | DataFeatures.Conditions, DataFeatures.History));
DataConnectionGrpcService.SupportedFeatures.ShouldBe(DataFeatures.History);
// 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));
@@ -225,13 +257,18 @@ internal static class V1CompatibilityHarness
/// 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) => (await DriveWithContextAsync(rpc, headers, operations, request, history)).Bytes;
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)
DataOperations operations = DataOperationSets.V1, byte[]? request = null, bool history = true, bool conditions = true)
{
var (service, context) = Create(rpc, headers, operations, history);
var (service, context) = Create(rpc, headers, operations, history, conditions);
return (await DriveAsync(service, context, rpc, request ?? Convert.FromHexString(GrpcDataV1Goldens.Requests[rpc])), context);
}
@@ -255,7 +292,7 @@ internal static class V1CompatibilityHarness
}
internal static (DataConnectionGrpcService Service, CallContext Context) Create(string rpc, Metadata headers,
DataOperations operations = DataOperationSets.V1, bool history = true)
DataOperations operations = DataOperationSets.V1, bool history = true, bool conditions = true)
{
var (bearer, id, hash) = ApiKeySecret.Generate("pepper");
var authority = new DataPlaneAuthorityState();
@@ -270,19 +307,21 @@ 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(operations, history), Options.Create(options), authenticator), context);
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) : IDataConnectionFactory
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, history);
new Origin(target, (history ? operations | DataOperations.HistoryRead : operations)
| (conditions && operations.HasFlag(DataOperations.Subscribe) ? DataOperations.AlarmSubscribe : DataOperations.None),
history, conditions);
}
/// <summary>A deterministic v1 origin exercising every optional v1 field the encoders emit.</summary>
private sealed class Origin(DataTarget target, DataOperations operations, bool history) : IDataConnection, IDataConnectionPublicationGate, IDataConnectionDiscoveryGate
private sealed class Origin(DataTarget target, DataOperations operations, bool history, bool conditions) : 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);
@@ -297,7 +336,8 @@ internal static class V1CompatibilityHarness
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));
history ? new DataHistoryCapabilities(true, true, true, ["Average"], 1, 10_000, 4, TimeSpan.FromSeconds(60)) : null,
conditions ? new DataConditionCapabilities(true, 0, 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,
@@ -357,6 +397,9 @@ internal static class V1CompatibilityHarness
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)
await Emit(sink, new DataSubscriptionConditions(open.SubscriptionId, open.StreamEpoch, 5, handle, true, 0, [], true), token);
}
private static async Task Emit(IDataSubscriptionDeliverySink sink, DataSubscriptionFrame frame, CancellationToken token)
{
@@ -81,12 +81,36 @@ public sealed class GrpcDataV1RealOriginCompatibilityTests
{
// H2: history is supported, but an origin WITHOUT a historian cannot serve it (and conditions are A2), so the
// effective set is empty and the bytes are v1.
await using var origin = new RealOrigin(historian: false);
await using var origin = new RealOrigin(historian: false, conditions: false);
var actual = await origin.DriveAsync(scenario, new Metadata { { "x-otopcua-data-features", "history,conditions" } });
actual.ShouldBe(GrpcDataV1RealOriginGoldens.Responses[scenario], $"{scenario} response must not change when nothing requested is servable");
await using var conditionsOnly = new RealOrigin();
await using var conditionsOnly = new RealOrigin(conditions: false);
(await conditionsOnly.DriveAsync(scenario, new Metadata { { "x-otopcua-data-features", "conditions" } }))
.ShouldBe(GrpcDataV1RealOriginGoldens.Responses[scenario], $"{scenario}: conditions are not supported before A2");
.ShouldBe(GrpcDataV1RealOriginGoldens.Responses[scenario], $"{scenario}: conditions on an origin that cannot serve them change nothing");
}
[Fact]
public async Task A2_a_header_less_real_stream_with_condition_scoped_items_gets_the_v1_bytes_and_no_arm_9()
{
await using var origin = new RealOrigin();
var open = W.SubscriptionCommand.Parser.ParseFrom(Convert.FromHexString(GrpcDataV1RealOriginGoldens.Requests["Subscribe"]));
foreach (var item in open.Open.Items) item.ConditionScope = new W.ConditionScope { IncludeInfo = true };
var actual = await origin.DriveAsync("Subscribe", new Metadata(), open.ToByteArray());
actual.ShouldBe(GrpcDataV1RealOriginGoldens.Responses["Subscribe"]);
actual.Split('|').Select(f => W.SubscriptionFrame.Parser.ParseFrom(Convert.FromHexString(f)).FrameCase)
.ShouldNotContain(W.SubscriptionFrame.FrameOneofCase.ConditionStates);
}
[Fact]
public async Task A2_a_condition_capable_real_origin_shows_condition_shapes_only_with_the_header()
{
await using var origin = new RealOrigin();
var caps = W.CapabilitiesResponse.Parser.ParseFrom(Convert.FromHexString(
await origin.DriveAsync("GetCapabilities", new Metadata { { "x-otopcua-data-features", "conditions" } })));
caps.Conditions.ShouldNotBeNull().RootScopeItems.ShouldBeTrue();
(caps.Operations & 64u).ShouldBe(64u);
(await origin.DriveAsync("GetCapabilities", new Metadata()))
.ShouldBe(GrpcDataV1RealOriginGoldens.Responses["GetCapabilities"], "header-less: no field 17, no bit 64");
}
public static TheoryData<string, string> V1Rejections()
@@ -251,7 +275,8 @@ internal sealed class RealOrigin : IAsyncDisposable
internal FakeHistoryPort? History { get; }
internal RealOrigin(DataOperations exportOperations = DataOperationSets.V1, bool historian = true, int concurrentReads = 4,
int responseBytes = 4 * 1024 * 1024, NodePermissions permissions = NodePermissions.Operator, int valuesPerPage = 10_000, string role = "Primary", bool grantHistory = true)
int responseBytes = 4 * 1024 * 1024, NodePermissions permissions = NodePermissions.Operator, int valuesPerPage = 10_000, string role = "Primary", bool grantHistory = true,
bool conditions = true)
{
History = historian ? new FakeHistoryPort() : null;
var fence = new DataWriteDispatchFence();
@@ -268,7 +293,10 @@ internal sealed class RealOrigin : IAsyncDisposable
Serving = new ServingIdentity("node-a", Incarnation, role, epoch, authority.Current.GenerationId, 1);
if (Serving.CatalogEpoch != CatalogEpoch) throw new InvalidOperationException("Catalog epoch is no longer deterministic.");
// H2 new-shape data: every export also grants HistoryRead (header-less callers must never see it).
var catalog = LocalExportCatalog.Compile(Snapshot(grantHistory ? exportOperations | DataOperations.HistoryRead : exportOperations, concurrentReads, responseBytes, valuesPerPage),
// A2a new-shape data: every export also grants AlarmSubscribe and the origin serves conditions (the HighTemp alarm).
var granted = (grantHistory ? exportOperations | DataOperations.HistoryRead : exportOperations)
| (conditions && exportOperations.HasFlag(DataOperations.Subscribe) ? DataOperations.AlarmSubscribe : DataOperations.None);
var catalog = LocalExportCatalog.Compile(Snapshot(granted, concurrentReads, responseBytes, valuesPerPage),
Serving, activation.CaptureAuthority());
_hub = new PartitionedSampleHub(new DataResourceLimits
@@ -298,13 +326,44 @@ internal sealed class RealOrigin : IAsyncDisposable
services = new LocalDataServices(() => catalog, _hub, policy, capabilities, _clock,
writes: context => new DataWriteExecutor(context, () => catalog, policy, capabilities, _route, registry, values, _clock, bounds),
targetSubscriptions: (context, target) => new LocalSubscriptionService(services!, context, target, new Demand(), sessionLimits, transport),
history: History);
history: History)
{
ConditionHub = conditions ? ConditionHub : null, ConditionSource = conditions ? new SingleConditionSource(ConditionHub) : null,
ConditionKeysSource = () => conditions ? ConditionKeys.FromSecret(ConditionSecret) : ConditionKeys.Unavailable,
};
_services = services;
_authenticator = new DataConnectionAuthenticator(authority, Options.Create(new ApiKeyOptions { Pepper = Pepper }), _clock);
}
internal IReadOnlyList<string> Dispatched => _route.Dispatched;
private const string ConditionSecret = "a2-real-origin-condition-key-secret-0123456789";
internal readonly ConditionStateHub ConditionHub = new(new PrimaryRole());
private sealed class PrimaryRole : ZB.MOM.WW.OtOpcUa.Core.Abstractions.IDriverPrimaryRoleSource
{
public bool ShouldActAsPrimary => true;
public void PublishPrimaryRole(bool isPrimary) { }
}
/// <summary>The node manager's snapshot semantics for the one alarm-bearing raw tag (HighTemp), inactive and known.</summary>
private sealed class SingleConditionSource(ConditionStateHub hub) : ZB.MOM.WW.OtOpcUa.OpcUaServer.IOriginConditionSource
{
public IReadOnlyList<ZB.MOM.WW.OtOpcUa.OpcUaServer.ConditionSnapshotSlice> SnapshotConditions(
Func<ZB.MOM.WW.OtOpcUa.Commons.OpcUa.AddressSpaceRealm, string, bool> scope, int maxConditionsPerHold)
{
const string id = "Plant/Modbus/dev1/HighTemp";
var watermark = hub.Watermark;
var records = scope(ZB.MOM.WW.OtOpcUa.Commons.OpcUa.AddressSpaceRealm.Raw, id)
? new[] { new ZB.MOM.WW.OtOpcUa.OpcUaServer.ConditionStateRecord(ZB.MOM.WW.OtOpcUa.Commons.OpcUa.AddressSpaceRealm.Raw, id, true,
watermark, false, true, false, true, true, true, ZB.MOM.WW.OtOpcUa.Commons.OpcUa.AlarmShelvingKind.Unshelved, 700, "HighTemp",
0, null, new DateTime(2026, 11, 23, 12, 0, 0, DateTimeKind.Utc), false,
new ZB.MOM.WW.OtOpcUa.OpcUaServer.ConditionActivationMarker("inc", 0)) }
: [];
return [new(watermark, records, watermark, 1, true)];
}
}
private static DraftSnapshot Snapshot(DataOperations operations, int concurrentReads, int responseBytes, int valuesPerPage)
{
Tag Tag(string id, string name, string type, TagAccessLevel access = TagAccessLevel.Read, string config = "{}") =>