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.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
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 ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
///
/// Recorded-v1-client compatibility gate, REAL-ORIGIN variant (#918; plan §4.3, exit gate of X0, H2, A2 and A3).
/// pins the transport layer over a fixed fake origin, so it cannot see a
/// v1 regression inside the origin itself (LocalDataServices.Implemented, DataCapabilitiesProvider,
/// LocalExportCatalog.Compile metadata). This variant replays recorded v1 requests
/// (, parsed from the golden hex) against the real
/// wired to the real origin stack, and compares the responses with goldens
/// captured on pre-H2 master 1086593a.
/// Real: , ,
/// (real API key), + node ACL +
/// /, ,
/// over a (Raw + UNS exports),
/// , (samples go through real ingress),
/// , (+ its operation registry and value budget),
/// / DataSubscriptionSession (snapshot from the hub).
/// Faked: the physical driver write dispatch (: resolves every catalog tag
/// to a fixed route and answers DriverConfirmedSuccess), the physical upstream acquisition
/// (: Good, settings unrevised), the gRPC/HTTP2 transport (hand-built
/// ; marshalling is ToByteArray()) and the clock (,
/// which never advances and never fires a timer, so ages are zero and no heartbeat/lease timer runs).
/// Normalised: nothing. Every input that could vary is fixed instead: the API key id/secret, the serving
/// incarnation, the clock, and the catalog/authority epochs (process-local counters starting at 1). Browse pages are
/// sized so no continuation token (HMAC'd with a per-process random key) is ever emitted. If a later phase finds a
/// genuinely varying field it must normalise it in , list it here and in
/// docs/plans/evidence/grpc-data-ext/X0.md §2, and never re-record.
/// RULE for H2/A2/A3: extend 's snapshot with that phase's new-shape data (historized tags
/// with HistoryInfo, conditions, the new operation bits on the exports), then these tests must still see the same
/// golden bytes WITHOUT the header.
/// H2 extension: every export also grants HistoryRead, the origin has a historian
/// (: Flow and the FlowRate reference are historized, aggregates served), so a
/// header-requesting caller WOULD see CapabilitiesResponse.history, the bit 32 and Metadata.history —
/// and the header-less replay must still be byte-identical. Asserted in GrpcDataHistoryWireTests that the
/// history-shaped data really is there with the header.
///
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")]
public sealed class GrpcDataV1RealOriginCompatibilityTests
{
public static TheoryData Scenarios => new(RealOriginRequests.Scenarios);
[Fact]
public void Recorded_v1_requests_still_encode_identically()
{
RealOriginRequests.Scenarios.ShouldBe(GrpcDataV1RealOriginGoldens.Requests.Keys, ignoreOrder: true);
foreach (var scenario in RealOriginRequests.Scenarios)
Hex(RealOriginRequests.Bytes(scenario)).ShouldBe(GrpcDataV1RealOriginGoldens.Requests[scenario], $"recorded {scenario} request");
}
[Theory]
[MemberData(nameof(Scenarios))]
public async Task V1_client_without_feature_header_gets_the_recorded_v1_response_bytes(string scenario)
{
await using var origin = new RealOrigin();
var actual = await origin.DriveAsync(scenario, new Metadata());
actual.ShouldBe(GrpcDataV1RealOriginGoldens.Responses[scenario], $"{scenario} response diverged from the recorded v1 bytes");
}
[Theory]
[MemberData(nameof(Scenarios))]
public async Task Feature_header_changes_nothing_while_no_requested_feature_is_servable(string scenario)
{
// 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);
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 conditionsOnly.DriveAsync(scenario, new Metadata { { "x-otopcua-data-features", "conditions" } }))
.ShouldBe(GrpcDataV1RealOriginGoldens.Responses[scenario], $"{scenario}: conditions are not supported before A2");
}
public static TheoryData V1Rejections()
{
var data = new TheoryData();
foreach (var header in new[] { "", "history,conditions" })
foreach (var scenario in new[] { "GetCapabilities/major-2", "Browse/no-browse-grant", "GetMetadata/no-metadata-grant",
"Read/no-read-grant", "Subscribe/no-subscribe-grant" })
data.Add(scenario, header);
return data;
}
/// The v1 rejection statuses (code, detail, trailers) a real origin produces, with and without the header.
[Theory]
[MemberData(nameof(V1Rejections))]
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]);
await using var origin = new RealOrigin(ExportOperations(shape));
var request = shape == "major-2" ? new W.CapabilitiesRequest { ProtocolMajor = 2, ProtocolMinor = 5 }.ToByteArray() : null;
var failure = await Should.ThrowAsync(() => origin.DriveAsync(rpc, headers, 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();
}
/// A real origin whose exports do not grant Write answers each v1 write item in the body (pinned bytes).
[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 } };
await using var origin = new RealOrigin(ExportOperations("no-write-grant"));
var actual = await origin.DriveAsync("Write", headers);
actual.ShouldBe(GrpcDataV1RealOriginGoldens.Responses["Write/no-write-grant"]);
origin.Dispatched.ShouldBeEmpty();
}
[Fact]
public async Task Real_origin_actually_dispatched_the_admitted_writes()
{
// Positive control for the write goldens: the admitted items reached the (fake) driver route.
await using var origin = new RealOrigin();
await origin.DriveAsync("Write", new Metadata());
origin.Dispatched.ShouldBe(["op-raw", "op-uns"], ignoreOrder: true);
}
private static DataOperations ExportOperations(string shape) => shape switch
{
"no-browse-grant" => DataOperationSets.V1 & ~DataOperations.Browse,
"no-metadata-grant" => DataOperationSets.V1 & ~DataOperations.Metadata,
"no-read-grant" => DataOperationSets.V1 & ~DataOperations.Read,
"no-write-grant" => DataOperationSets.V1 & ~DataOperations.Write,
"no-subscribe-grant" => DataOperationSets.V1 & ~DataOperations.Subscribe,
_ => DataOperationSets.V1,
};
internal static string Hex(byte[] bytes) => Convert.ToHexString(bytes);
/// X0: no field varies (see the class remarks). A later phase lists any explicit normalisation here.
internal static IMessage Normalise(IMessage message) => message;
}
/// The recorded v1 client requests against 's catalog. Changing any value invalidates the goldens.
internal static class RealOriginRequests
{
private const string RawNs = "https://zb.com/otopcua/raw";
private const string UnsNs = "https://zb.com/otopcua/uns";
internal static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 16, 65_536);
internal static DataView Raw(string path) => new(new("cluster", RawNs, "string", path), DataRealm.Raw, null, 0, path);
internal static DataView Uns(string path) => new(new("cluster", UnsNs, "string", path), DataRealm.Uns, null, 0, path);
internal static readonly DataView Device = Raw("Plant/Modbus/dev1");
internal static readonly DataView Speed = Raw("Plant/Modbus/dev1/Speed");
internal static readonly DataView Temperature = Raw("Plant/Modbus/dev1/Temperature");
internal static readonly DataView Label = Raw("Plant/Modbus/dev1/Label");
internal static readonly DataView Running = Raw("Plant/Modbus/dev1/Running");
internal static readonly DataView Levels = Raw("Plant/Modbus/dev1/Levels");
internal static readonly DataView Flow = Raw("Plant/Modbus/dev1/Flow");
internal static readonly DataView HighTemp = Raw("Plant/Modbus/dev1/HighTemp");
internal static readonly DataView Missing = Raw("Plant/Modbus/dev1/Missing");
// UNS equipment folders are minted under their entity id; references under the name path.
internal static readonly DataView Equipment = new(new("cluster", UnsNs, "string", "equipment-1"), DataRealm.Uns, null, 0, "Area1/Line1/Filler");
internal static readonly DataView UnsSpeed = Uns("Area1/Line1/Filler/Speed");
internal static readonly DataView UnsFlow = Uns("Area1/Line1/Filler/FlowRate");
internal static readonly DataView UnsLevels = Uns("Area1/Line1/Filler/Levels");
internal static readonly string[] Scenarios =
["GetCapabilities", "Browse", "Browse/uns", "GetMetadata", "Read", "Write", "Subscribe"];
internal static IMessage Message(string scenario) => scenario switch
{
"GetCapabilities" => new W.CapabilitiesRequest { ProtocolMajor = 1, ProtocolMinor = 5 },
"Browse" => DataProtoMapper.EncodeBrowseRequest(new BrowseRequest(Device, null, null, Budget)),
"Browse/uns" => DataProtoMapper.EncodeBrowseRequest(new BrowseRequest(Equipment, null, null, Budget)),
"GetMetadata" => DataProtoMapper.EncodeMetadataRequest(new MetadataRequest(
[Speed, Temperature, Label, Running, Levels, Flow, HighTemp, UnsSpeed, UnsFlow, UnsLevels, Missing], Budget)),
"Read" => DataProtoMapper.EncodeReadRequest(new ReadRequest(
[
new("r-speed", Speed, TimeSpan.FromSeconds(2)), new("r-temp", Temperature, null), new("r-label", Label, null),
new("r-running", Running, null), new("r-levels", Levels, null), new("r-flow", Flow, null),
new("r-uns-speed", UnsSpeed, null), new("r-missing", Missing, null),
], Budget)),
"Write" => WriteRequest(),
"Subscribe" => DataProtoMapper.EncodeCommand(new OpenSubscription("sub-1", 1, "open-1", TimeSpan.FromSeconds(5),
[
new("item-speed", Speed, new(TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null)),
new("item-uns-speed", UnsSpeed, new(TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null)),
new("item-levels", Levels, new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null)),
new("item-missing", Missing, new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null)),
], false, TimeSpan.FromMinutes(5), Budget)),
_ => throw new ArgumentOutOfRangeException(nameof(scenario)),
};
private static W.WriteRequest WriteRequest()
{
using var raw = DataValue.FromScalar(DataValueKind.Int32, 17);
using var uns = DataValue.FromScalar(DataValueKind.Int32, 18);
using var readOnly = DataValue.FromScalar(DataValueKind.Double, 1.5);
using var missing = DataValue.FromScalar(DataValueKind.String, "abc");
return DataProtoMapper.EncodeWriteRequest(new WriteBatch(
[
new("w-raw", "op-raw", Speed, raw, RealOrigin.CatalogEpoch, RealOrigin.Incarnation, TimeSpan.FromSeconds(4), 1),
new("w-uns", "op-uns", UnsSpeed, uns, RealOrigin.CatalogEpoch, RealOrigin.Incarnation, TimeSpan.FromSeconds(4), 1),
new("w-readonly", "op-readonly", Temperature, readOnly, RealOrigin.CatalogEpoch, RealOrigin.Incarnation, TimeSpan.FromSeconds(4), 1),
new("w-missing", "op-missing", Missing, missing, RealOrigin.CatalogEpoch, RealOrigin.Incarnation, TimeSpan.FromSeconds(4), 1),
], Budget));
}
internal static byte[] Bytes(string scenario) => Message(scenario).ToByteArray();
}
///
/// The real origin stack for one node of cluster cluster, compiled from a small deterministic deployed
/// snapshot: Raw Plant/Modbus/dev1/{Speed (Int32, writable), Temperature (Double), Label (String), Running
/// (Boolean), Levels (UInt16[3]), Flow (Double, historized), HighTemp (Boolean, alarm-bearing)} and UNS
/// Area1/Line1/Filler/{Speed, FlowRate (display override of Flow), Levels}, with one Raw and one UNS export.
///
internal sealed class RealOrigin : IAsyncDisposable
{
internal const string Incarnation = "serving-1";
internal const long CatalogEpoch = 1;
private const string Pepper = "pepper";
// Fixed (not ApiKeySecret.Generate) so no CSPRNG value enters the call.
private const string KeyId = "00112233aabbccdd";
private const string Secret = "v1-real-origin-fixed-secret";
private readonly FrozenClock _clock = new();
private readonly PartitionedSampleHub _hub;
private readonly Route _route = new();
private readonly DataConnectionAuthenticator _authenticator;
private readonly LocalDataServices _services;
internal ServingIdentity Serving { get; }
/// The fake historian behind the origin's history port (H2), or null when constructed without one.
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)
{
History = historian ? new FakeHistoryPort() : null;
var fence = new DataWriteDispatchFence();
var authority = new DataPlaneAuthorityState(fence);
var activation = new CatalogActivation(fence);
var key = new ApiKey { ApiKeyId = KeyId, Name = "peer", Principal = "peer", SecretHash = ApiKeySecret.ComputeHash(Secret, Pepper), Enabled = true };
authority.Apply("cluster", "rev-1", [key],
[new NodeAcl { NodeAclId = "grant", ClusterId = "cluster", Principal = "peer", ScopeKind = NodeAclScopeKind.Cluster,
PermissionFlags = permissions }],
new Dictionary>());
var epoch = activation.Begin("rev-1");
activation.AuthorityInstalled(epoch, authority.Current.GenerationId);
activation.Complete(epoch, true);
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),
Serving, activation.CaptureAuthority());
_hub = new PartitionedSampleHub(new DataResourceLimits
{
PartitionCount = 1, MaxRetainedBytes = 1_000_000, MaxTrackedSources = 100,
MaxIngressItemsPerPartition = 100, MaxDirtySourcesPerPartition = 100, MaxControlItemsPerPartition = 100,
MaxSnapshotItems = 100, MaxSnapshotBytes = 100_000, MaxSnapshotCatchUpItems = 1,
MaxSnapshotLifetime = TimeSpan.FromMinutes(1),
}, _clock, autoDrain: false);
Publish(catalog, "Speed", DataValue.FromScalar(DataValueKind.Int32, 42));
Publish(catalog, "Temperature", DataValue.FromScalar(DataValueKind.Double, 21.5));
Publish(catalog, "Label", DataValue.FromScalar(DataValueKind.String, "batch-7"));
Publish(catalog, "Running", DataValue.FromScalar(DataValueKind.Boolean, true));
Publish(catalog, "Levels", DataValue.FromArray(DataValueKind.UInt16, new object[] { (ushort)1, (ushort)2, (ushort)3 }, [3]));
// Flow and HighTemp are deliberately never published (WaitingForInitialData).
_hub.ProcessPending();
var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
var capabilities = new DataCapabilitiesProvider("cluster", () => Serving, () => catalog.IsActive, limits);
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, _clock), _clock);
var registry = new WriteOperationRegistry(Incarnation, 16, 16_384, TimeSpan.FromMinutes(1), _clock);
var values = new WriteValueBudget(16_384);
var bounds = new DriverWriteBounds(TimeSpan.FromMilliseconds(100));
var sessionLimits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(10));
var transport = new SubscriptionTransportCapacity(4, 4, 1_000_000, _clock);
LocalDataServices? services = null;
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);
_services = services;
_authenticator = new DataConnectionAuthenticator(authority, Options.Create(new ApiKeyOptions { Pepper = Pepper }), _clock);
}
internal IReadOnlyList Dispatched => _route.Dispatched;
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 = "{}") =>
new() { TagId = id, DeviceId = "device-1", Name = name, DataType = type, AccessLevel = access, TagConfig = config };
return new DraftSnapshot
{
GenerationId = 1, ClusterId = "cluster",
ServerClusters = [new() { ClusterId = "cluster", Name = "Cluster", Enterprise = "Enterprise", Site = "Site", CreatedBy = "test", RedundancyMode = RedundancyMode.None }],
RawFolders = [new() { RawFolderId = "folder-1", ClusterId = "cluster", Name = "Plant" }],
DriverInstances = [new() { DriverInstanceId = "driver-1", ClusterId = "cluster", RawFolderId = "folder-1", Name = "Modbus", DriverType = "Modbus", DriverConfig = "{}" }],
Devices = [new() { DeviceId = "device-1", DriverInstanceId = "driver-1", Name = "dev1", DeviceConfig = "{}" }],
Tags =
[
Tag("tag-speed", "Speed", "Int32", TagAccessLevel.ReadWrite),
Tag("tag-temperature", "Temperature", "Double"),
Tag("tag-label", "Label", "String"),
Tag("tag-running", "Running", "Boolean"),
Tag("tag-levels", "Levels", "UInt16", config: """{"isArray":true,"arrayLength":3}"""),
Tag("tag-flow", "Flow", "Double", config: """{"isHistorized":true,"historianTagname":"Plant.Flow"}"""),
Tag("tag-hightemp", "HighTemp", "Boolean", config: """{"alarm":{"alarmType":"OffNormalAlarm","severity":700}}"""),
],
UnsAreas = [new() { UnsAreaId = "area-1", ClusterId = "cluster", Name = "Area1" }],
UnsLines = [new() { UnsLineId = "line-1", UnsAreaId = "area-1", Name = "Line1" }],
Equipment = [new() { EquipmentId = "equipment-1", UnsLineId = "line-1", Name = "Filler", MachineCode = "F1" }],
UnsTagReferences =
[
new() { UnsTagReferenceId = "ref-speed", EquipmentId = "equipment-1", TagId = "tag-speed" },
new() { UnsTagReferenceId = "ref-flow", EquipmentId = "equipment-1", TagId = "tag-flow", DisplayNameOverride = "FlowRate" },
new() { UnsTagReferenceId = "ref-levels", EquipmentId = "equipment-1", TagId = "tag-levels" },
],
DataExports =
[
new() { DataExportId = "export-raw", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw,
RootKind = "Cluster", RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = operations,
MaxConcurrentHistoryReads = concurrentReads, MaxHistoryResponseBytes = responseBytes, MaxHistoryValuesPerPage = valuesPerPage },
new() { DataExportId = "export-uns", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns,
RootKind = "Cluster", RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = operations,
MaxConcurrentHistoryReads = concurrentReads, MaxHistoryResponseBytes = responseBytes, MaxHistoryValuesPerPage = valuesPerPage },
],
};
}
private void Publish(LocalExportCatalog catalog, string tag, DataValue value)
{
using (value)
{
var source = catalog.Nodes.Single(x => x.EntityKind == "RawTag" && x.Metadata.BrowseName == tag).Source!;
var ticket = new SourceTicket(source, new(1, 1));
if (!_hub.TryBind(ticket) || !_hub.TryReserveIngress(ticket, value.EstimatedRetainedBytes, out var reservation))
throw new InvalidOperationException("Hub refused the fixture sample.");
using (reservation!)
{
var sample = new DataSample(value.Retain(), 0, FrozenClock.Now.AddSeconds(-1), FrozenClock.Now, Serving, 1);
if (!reservation!.TryCommit(sample, 1)) { sample.Dispose(); throw new InvalidOperationException("Hub refused the commit."); }
}
}
}
/// Drives one HistoryRead through the real service (H2); is the HTTP/2 connection.
internal async Task HistoryAsync(W.HistoryReadRequest request, Metadata headers, string connectionId = "conn-1",
CancellationTokenSource? cancel = null, ServerCallContext? existing = null)
{
var options = new DataConnectionOptions { Enabled = true, ListenPort = 9443, AllowedHosts = ["source.local"], CertificatePath = "server.pem" };
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancel?.Token ?? CancellationToken.None, TestContext.Current.CancellationToken);
var context = existing ?? new Context("HistoryRead", headers, linked.Token);
var http = new DefaultHttpContext();
http.Connection.Id = connectionId;
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($"{ApiKeySecret.Prefix}_{KeyId}_{Secret}");
http.Items[typeof(DataTarget)] = new DataTarget(DataTargetMode.Node, "cluster", "node-a");
context.UserState["__HttpContext"] = http;
var service = new DataConnectionGrpcService(_services, Options.Create(options), _authenticator);
return await service.HistoryRead(request, context);
}
/// The origin facade, for direct runtime-consumer history (H2).
internal IDataConnection Connect() => _services.Create(_authenticator.Authenticate($"{ApiKeySecret.Prefix}_{KeyId}_{Secret}"),
new DataTarget(DataTargetMode.Node, "cluster", "node-a"));
internal LocalDataServices Services => _services;
internal static Context NewContext(string rpc, Metadata headers, CancellationToken token) => new(rpc, headers, token);
internal async Task DriveAsync(string scenario, Metadata headers, byte[]? request = null)
{
var rpc = scenario.Split('/')[0];
var bytes = request ?? Convert.FromHexString(GrpcDataV1RealOriginGoldens.Requests[scenario]);
var options = new DataConnectionOptions { Enabled = true, ListenPort = 9443, AllowedHosts = ["source.local"], CertificatePath = "server.pem" };
using var call = new CancellationTokenSource();
using var linked = CancellationTokenSource.CreateLinkedTokenSource(call.Token, TestContext.Current.CancellationToken);
var context = new Context(rpc, headers, linked.Token);
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($"{ApiKeySecret.Prefix}_{KeyId}_{Secret}");
http.Items[typeof(DataTarget)] = new DataTarget(DataTargetMode.Node, "cluster", "node-a");
context.UserState["__HttpContext"] = http;
var service = new DataConnectionGrpcService(_services, Options.Create(options), _authenticator);
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),
"Subscribe" => null!,
_ => throw new ArgumentOutOfRangeException(nameof(scenario)),
};
if (rpc != "Subscribe")
return GrpcDataV1RealOriginCompatibilityTests.Hex(GrpcDataV1RealOriginCompatibilityTests.Normalise(response).ToByteArray());
// The v1 client's initial frames: the ack, snapshot begin, the snapshot values, snapshot end. The real session
// streams forever, so the "client" cancels the call once it has seen snapshot end.
var writer = new Writer(call);
var running = service.Subscribe(new V1CompatibilityHarness.Reader(W.SubscriptionCommand.Parser.ParseFrom(bytes)), writer, context);
try { await running.WaitAsync(TimeSpan.FromSeconds(30), TestContext.Current.CancellationToken); }
catch (Exception) when (writer.SawSnapshotEnd) { }
if (!writer.SawSnapshotEnd) throw new InvalidOperationException("Subscribe ended before snapshot end.");
return string.Join("|", writer.Frames.Select(f =>
GrpcDataV1RealOriginCompatibilityTests.Hex(GrpcDataV1RealOriginCompatibilityTests.Normalise(f).ToByteArray())));
}
public ValueTask DisposeAsync() { _hub.Dispose(); return ValueTask.CompletedTask; }
/// Fake physical driver write: every catalog tag routes to one fixed driver route and succeeds.
private sealed class Route : IDataWriteRoute
{
private readonly System.Collections.Concurrent.ConcurrentQueue _dispatched = new();
private readonly LateWriteObserver _observer = new(16, TimeSpan.FromMinutes(1));
internal string[] Dispatched => _dispatched.ToArray();
public bool TryResolve(DataView view, out WriteRouteTarget? target)
{
target = new("driver-1", view.Address.Identifier, "driver-incarnation", 1, 1);
return true;
}
public Task DispatchAsync(WriteAdmissionTicket ticket, WriteClaim claim, CancellationToken ct)
{
if (!_observer.TryReserve(out var reservation)) throw new InvalidOperationException("Observer exhausted.");
// Same order as the driver host: observe the physical call, mark dispatched, then let it complete.
var physical = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
reservation!.Observe(physical.Task, claim, ticket);
_dispatched.Enqueue(ticket.Proof.Admission.OperationId);
if (!claim.TryMarkDispatched()) throw new InvalidOperationException("Claim refused dispatch.");
var outcome = new DataWriteOutcome(DataWriteState.DriverConfirmedSuccess, 0, null);
physical.TrySetResult(outcome);
return Task.FromResult(outcome);
}
}
/// Fake physical upstream acquisition: Good, settings unrevised.
private sealed class Demand : ISubscriptionDemandSource
{
public ValueTask AcquireAsync(SubscriptionAuthorizedView view, DataSubscriptionSettings settings,
CancellationToken cancellationToken) => ValueTask.FromResult(new SubscriptionDemandResult(DataItemStatus.Good, settings, 1, new Lease()));
private sealed class Lease : IDisposable { public void Dispose() { } }
}
private sealed class Writer(CancellationTokenSource call) : IServerStreamWriter
{
private readonly object _lock = new();
public List Frames { get; } = [];
public bool SawSnapshotEnd { get; private set; }
public WriteOptions? WriteOptions { get; set; }
public Task WriteAsync(W.SubscriptionFrame frame)
{
lock (_lock)
{
if (SawSnapshotEnd) return Task.CompletedTask;
Frames.Add(frame.Clone());
if (frame.FrameCase == W.SubscriptionFrame.FrameOneofCase.Control && frame.Control.Kind == (int)DataStreamControlKind.SnapshotEnd)
{ SawSnapshotEnd = true; call.Cancel(); }
}
return Task.CompletedTask;
}
public Task WriteAsync(W.SubscriptionFrame frame, CancellationToken cancellationToken) => WriteAsync(frame);
}
internal sealed class Context(string rpc, Metadata headers, CancellationToken token) : 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 => token;
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;
}
}
/// A clock that never moves and never fires a timer, so every age, lease and timestamp is fixed.
internal sealed class FrozenClock : TimeProvider
{
internal static readonly DateTimeOffset Now = new(2026, 11, 23, 12, 0, 0, TimeSpan.Zero);
public override DateTimeOffset GetUtcNow() => Now;
public override long GetTimestamp() => Now.UtcTicks;
public override long TimestampFrequency => TimeSpan.TicksPerSecond;
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) => new Never();
private sealed class Never : ITimer
{
public bool Change(TimeSpan dueTime, TimeSpan period) => true;
public void Dispose() { }
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}