b7ca71f188
#916: Metadata.stable_source_id carried the internal acquisition key (<len>:<driverInstanceId><RawPath>) on every export, so a UNS-only peer learned driver ids and RawPaths. No consumer uses the field beyond byte accounting; it is optional on the wire and absent decodes as null. It is now never sent; the internal BackingSourceKey is unchanged. #917: alarm-bearing raw tags never get a value but were exported as Variables. They are now the existing explicit UnsupportedVariable kind (browsable, Unsupported on every value op). The node is kept so exports rooted at it still compile and A1 condition placements are unaffected. The real-origin v1 goldens are not re-recorded: GrpcDataV1RealOriginCorrections applies exactly these two edits to the parsed goldens, pinned by a test. Evidence: docs/plans/evidence/grpc-data-ext/V1-916-917.md
720 lines
47 KiB
C#
720 lines
47 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.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;
|
|
|
|
/// <summary>
|
|
/// Recorded-v1-client compatibility gate, REAL-ORIGIN variant (#918; plan §4.3, exit gate of X0, H2, A2 and A3).
|
|
/// <see cref="GrpcDataV1CompatibilityTests"/> pins the transport layer over a fixed fake origin, so it cannot see a
|
|
/// v1 regression inside the origin itself (<c>LocalDataServices.Implemented</c>, <c>DataCapabilitiesProvider</c>,
|
|
/// <c>LocalExportCatalog.Compile</c> metadata). This variant replays recorded v1 requests
|
|
/// (<see cref="GrpcDataV1RealOriginGoldens.Requests"/>, parsed from the golden hex) against the real
|
|
/// <see cref="DataConnectionGrpcService"/> wired to the real origin stack, and compares the responses with goldens
|
|
/// captured on pre-H2 master <c>1086593a</c>.
|
|
/// <para><b>Real:</b> <see cref="DataConnectionGrpcService"/>, <see cref="DataProtoMapper"/>,
|
|
/// <see cref="DataConnectionAuthenticator"/> (real API key), <see cref="DataPlaneAuthorityState"/> + node ACL +
|
|
/// <see cref="TriePermissionEvaluator"/>/<see cref="DataOperationPolicy"/>, <see cref="CatalogActivation"/>,
|
|
/// <see cref="LocalExportCatalog.Compile"/> over a <see cref="DraftSnapshot"/> (Raw + UNS exports),
|
|
/// <see cref="DataCapabilitiesProvider"/>, <see cref="PartitionedSampleHub"/> (samples go through real ingress),
|
|
/// <see cref="LocalDataServices"/>, <see cref="DataWriteExecutor"/> (+ its operation registry and value budget),
|
|
/// <see cref="LocalSubscriptionService"/> / <c>DataSubscriptionSession</c> (snapshot from the hub).</para>
|
|
/// <para><b>Faked:</b> the physical driver write dispatch (<see cref="IDataWriteRoute"/>: resolves every catalog tag
|
|
/// to a fixed route and answers DriverConfirmedSuccess), the physical upstream acquisition
|
|
/// (<see cref="ISubscriptionDemandSource"/>: Good, settings unrevised), the gRPC/HTTP2 transport (hand-built
|
|
/// <see cref="ServerCallContext"/>; marshalling is <c>ToByteArray()</c>) and the clock (<see cref="FrozenClock"/>,
|
|
/// which never advances and never fires a timer, so ages are zero and no heartbeat/lease timer runs).</para>
|
|
/// <para><b>Normalised:</b> 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 <see cref="Normalise"/>, list it here and in
|
|
/// <c>docs/plans/evidence/grpc-data-ext/X0.md</c> §2, and never re-record.</para>
|
|
/// RULE for H2/A2/A3: extend <see cref="RealOrigin"/>'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.
|
|
/// <para><b>H2 extension:</b> every export also grants <c>HistoryRead</c>, the origin has a historian
|
|
/// (<see cref="RealOrigin.History"/>: Flow and the FlowRate reference are historized, aggregates served), so a
|
|
/// header-requesting caller WOULD see <c>CapabilitiesResponse.history</c>, the bit 32 and <c>Metadata.history</c> —
|
|
/// and the header-less replay must still be byte-identical. Asserted in <c>GrpcDataHistoryWireTests</c> that the
|
|
/// history-shaped data really is there with the header.</para>
|
|
/// </summary>
|
|
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")]
|
|
public sealed class GrpcDataV1RealOriginCompatibilityTests
|
|
{
|
|
public static TheoryData<string> 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");
|
|
}
|
|
|
|
/// <summary>
|
|
/// #916/#917: the corrections are exact and not vacuous — an unedited golden re-serialises byte-identically, the
|
|
/// uncorrected scenarios are the raw goldens, the recorded UNS browse really leaked the driver id + RawPath, and the
|
|
/// corrected bytes carry neither the leak nor a value-bearing HighTemp.
|
|
/// </summary>
|
|
[Fact]
|
|
public void V1_corrections_916_917_are_exact_and_the_recorded_leak_was_real()
|
|
{
|
|
foreach (var scenario in RealOriginRequests.Scenarios.Where(s => s != "Subscribe"))
|
|
{
|
|
var golden = GrpcDataV1RealOriginGoldens.Responses[scenario];
|
|
IMessage parsed = scenario.Split('/')[0] switch
|
|
{
|
|
"GetCapabilities" => W.CapabilitiesResponse.Parser.ParseFrom(Convert.FromHexString(golden)),
|
|
"Browse" => W.BrowseResponse.Parser.ParseFrom(Convert.FromHexString(golden)),
|
|
"GetMetadata" => W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(golden)),
|
|
"Read" => W.ReadResponse.Parser.ParseFrom(Convert.FromHexString(golden)),
|
|
_ => W.WriteResponse.Parser.ParseFrom(Convert.FromHexString(golden)),
|
|
};
|
|
Hex(parsed.ToByteArray()).ShouldBe(golden, $"{scenario}: re-serialising a golden is byte-identical");
|
|
if (GrpcDataV1RealOriginCorrections.Corrected.Contains(scenario))
|
|
GrpcDataV1RealOriginCorrections.Expected(scenario).ShouldNotBe(golden, $"{scenario} carries a corrected field");
|
|
else
|
|
GrpcDataV1RealOriginCorrections.Expected(scenario).ShouldBe(golden);
|
|
}
|
|
var leak = Hex(System.Text.Encoding.UTF8.GetBytes("driver-1Plant/Modbus/dev1/"));
|
|
GrpcDataV1RealOriginGoldens.Responses["Browse/uns"].ShouldContain(leak, Case.Sensitive, "the recorded v1 UNS browse leaked it (#916)");
|
|
foreach (var scenario in GrpcDataV1RealOriginCorrections.Corrected)
|
|
GrpcDataV1RealOriginCorrections.Expected(scenario).ShouldNotContain(leak, Case.Sensitive);
|
|
var metadata = W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(GrpcDataV1RealOriginCorrections.Expected("GetMetadata")));
|
|
metadata.Items.Count(x => x.Status == (int)DataItemStatus.Unsupported).ShouldBe(1);
|
|
metadata.Items.ShouldNotContain(x => x.Value != null && x.Value.View.Address.Identifier == RealOriginRequests.HighTemp.Address.Identifier);
|
|
}
|
|
|
|
[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(GrpcDataV1RealOriginCorrections.Expected(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, conditions: false);
|
|
var actual = await origin.DriveAsync(scenario, new Metadata { { "x-otopcua-data-features", "history,conditions" } });
|
|
actual.ShouldBe(GrpcDataV1RealOriginCorrections.Expected(scenario), $"{scenario} response must not change when nothing requested is servable");
|
|
await using var conditionsOnly = new RealOrigin(conditions: false);
|
|
(await conditionsOnly.DriveAsync(scenario, new Metadata { { "x-otopcua-data-features", "conditions" } }))
|
|
.ShouldBe(GrpcDataV1RealOriginCorrections.Expected(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");
|
|
}
|
|
|
|
/// <summary>A2b: a call that did not negotiate <c>conditions</c> never reaches the origin's method port.</summary>
|
|
[Theory]
|
|
[InlineData("")]
|
|
[InlineData("history")]
|
|
public async Task A2b_CallConditionMethod_without_the_conditions_feature_is_FAILED_PRECONDITION_and_never_dispatched(string header)
|
|
{
|
|
await using var origin = new RealOrigin();
|
|
var headers = header.Length == 0 ? new Metadata() : new Metadata { { "x-otopcua-data-features", header } };
|
|
var error = await Should.ThrowAsync<RpcException>(() => origin.DriveAsync("CallConditionMethod", headers, MethodRequest()));
|
|
error.StatusCode.ShouldBe(StatusCode.FailedPrecondition);
|
|
origin.ConditionPort!.Calls.ShouldBeEmpty();
|
|
// And an origin that cannot serve conditions refuses it the same way even with the header.
|
|
await using var noConditions = new RealOrigin(conditions: false);
|
|
(await Should.ThrowAsync<RpcException>(() => noConditions.DriveAsync("CallConditionMethod",
|
|
new Metadata { { "x-otopcua-data-features", "conditions" } }, MethodRequest()))).StatusCode.ShouldBe(StatusCode.FailedPrecondition);
|
|
}
|
|
|
|
/// <summary>A2b: with the header, capabilities carry the method bits + mask and the call reaches the origin port once.</summary>
|
|
[Fact]
|
|
public async Task A2b_a_condition_capable_real_origin_serves_CallConditionMethod_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.Operations & 384u).ShouldBe(384u);
|
|
caps.Conditions.Methods.ShouldBe(7u);
|
|
var response = W.ConditionMethodResponse.Parser.ParseFrom(Convert.FromHexString(
|
|
await origin.DriveAsync("CallConditionMethod", new Metadata { { "x-otopcua-data-features", "conditions" } }, MethodRequest())));
|
|
response.State.ShouldBe((int)DataWriteState.AcceptedUnconfirmed);
|
|
response.Serving.Incarnation.ShouldBe(RealOrigin.Incarnation);
|
|
origin.ConditionPort!.Calls.ShouldHaveSingleItem().ShouldSatisfyAllConditions(
|
|
c => c.ConditionId.ShouldBe("Plant/Modbus/dev1/HighTemp"), c => c.Principal.ShouldBe("peer"), c => c.Method.ShouldBe("Acknowledge"));
|
|
(await origin.DriveAsync("GetCapabilities", new Metadata()))
|
|
.ShouldBe(GrpcDataV1RealOriginGoldens.Responses["GetCapabilities"], "header-less: no field 17, no bits 64/128/256");
|
|
}
|
|
|
|
private static byte[] MethodRequest() => DataConditionProtoMapper.EncodeMethodRequest(new DataConditionMethodRequest("op-1",
|
|
RealOriginRequests.HighTemp, DataConditionMethods.Acknowledge, new("inc", 0), "ack", RealOrigin.Incarnation, TimeSpan.FromSeconds(5),
|
|
"remote operator")).ToByteArray();
|
|
|
|
public static TheoryData<string, string> V1Rejections()
|
|
{
|
|
var data = new TheoryData<string, string>();
|
|
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;
|
|
}
|
|
|
|
/// <summary>The v1 rejection statuses (code, detail, trailers) a real origin produces, with and without the header.</summary>
|
|
[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<RpcException>(() => 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();
|
|
}
|
|
|
|
/// <summary>A real origin whose exports do not grant Write answers each v1 write item in the body (pinned bytes).</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 } };
|
|
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);
|
|
|
|
/// <summary>X0: no field varies (see the class remarks). A later phase lists any explicit normalisation here.</summary>
|
|
internal static IMessage Normalise(IMessage message) => message;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The deliberate pre-deploy v1 corrections (#916, #917; v1 was merged but never deployed, #915). The goldens in
|
|
/// <see cref="GrpcDataV1RealOriginGoldens"/> are NOT re-recorded: the expected bytes are the recorded golden with exactly
|
|
/// these edits applied to its parsed message, and every other byte must still match. Re-serialising an unedited golden is
|
|
/// byte-identical (asserted), so the edit is the only difference. Nothing here changes the wire SHAPE — both corrections
|
|
/// use fields and values a v1 client already handles (an absent optional field; the existing UnsupportedVariable kind and
|
|
/// Unsupported status, which the consumer already treats as "not a value node").
|
|
/// <list type="bullet">
|
|
/// <item><b>#916</b> — <c>Metadata.stable_source_id</c> is never sent (it was <c><len>:<driverInstanceId><RawPath></c>, even on
|
|
/// UNS exports). Cleared on every Metadata of every Browse/GetMetadata response.</item>
|
|
/// <item><b>#917</b> — the alarm-bearing raw tag (HighTemp) is exported as <c>UnsupportedVariable</c>: in a Browse page it is
|
|
/// <c>node_kind = "UnsupportedVariable"</c>, <c>value_kind = NULL</c>, <c>allowed_operations = Browse</c> (the existing
|
|
/// unsupported-node masking); a GetMetadata item for it is <c>status = Unsupported</c> with no value and no lease.</item>
|
|
/// </list>
|
|
/// </summary>
|
|
internal static class GrpcDataV1RealOriginCorrections
|
|
{
|
|
internal static readonly string[] Corrected = ["Browse", "Browse/uns", "GetMetadata"];
|
|
|
|
internal static string Expected(string scenario)
|
|
{
|
|
var golden = GrpcDataV1RealOriginGoldens.Responses[scenario];
|
|
if (!Corrected.Contains(scenario)) return golden;
|
|
var bytes = Convert.FromHexString(golden);
|
|
var alarm = RealOriginRequests.HighTemp.Address.Identifier;
|
|
IMessage corrected;
|
|
if (scenario == "GetMetadata")
|
|
{
|
|
var response = W.MetadataResponse.Parser.ParseFrom(bytes);
|
|
foreach (var item in response.Items)
|
|
{
|
|
if (item.Value is null) continue;
|
|
if (item.Value.View.Address.Identifier == alarm && item.Value.View.Realm == (int)DataRealm.Raw)
|
|
{ item.Status = (int)DataItemStatus.Unsupported; item.Value = null; item.Lease = null; continue; }
|
|
item.Value.ClearStableSourceId();
|
|
}
|
|
corrected = response;
|
|
}
|
|
else
|
|
{
|
|
var response = W.BrowseResponse.Parser.ParseFrom(bytes);
|
|
foreach (var item in response.Items)
|
|
{
|
|
item.ClearStableSourceId();
|
|
if (item.View.Address.Identifier == alarm && item.View.Realm == (int)DataRealm.Raw)
|
|
{ item.NodeKind = "UnsupportedVariable"; item.ValueKind = W.ValueKind.Null; item.AllowedOperations = (uint)DataOperations.Browse; }
|
|
}
|
|
corrected = response;
|
|
}
|
|
return GrpcDataV1RealOriginCompatibilityTests.Hex(corrected.ToByteArray());
|
|
}
|
|
}
|
|
|
|
/// <summary>The recorded v1 client requests against <see cref="RealOrigin"/>'s catalog. Changing any value invalidates the goldens.</summary>
|
|
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();
|
|
}
|
|
|
|
/// <summary>
|
|
/// The real origin stack for one node of cluster <c>cluster</c>, compiled from a small deterministic deployed
|
|
/// snapshot: Raw <c>Plant/Modbus/dev1/{Speed (Int32, writable), Temperature (Double), Label (String), Running
|
|
/// (Boolean), Levels (UInt16[3]), Flow (Double, historized), HighTemp (Boolean, alarm-bearing)}</c> and UNS
|
|
/// <c>Area1/Line1/Filler/{Speed, FlowRate (display override of Flow), Levels}</c>, with one Raw and one UNS export.
|
|
/// </summary>
|
|
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; }
|
|
|
|
/// <summary>The fake historian behind the origin's history port (H2), or null when constructed without one.</summary>
|
|
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,
|
|
bool conditions = 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<AclScopeRef, IReadOnlyList<NodeAclPath>>());
|
|
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).
|
|
// 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)
|
|
// A2b new-shape data: the same exports also grant the method bits (header-less callers must never see them).
|
|
| (conditions && exportOperations.HasFlag(DataOperations.Subscribe) ? DataOperationSets.ConditionMethods : DataOperations.None);
|
|
var catalog = LocalExportCatalog.Compile(Snapshot(granted, 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)
|
|
{
|
|
ConditionHub = conditions ? ConditionHub : null, ConditionSource = conditions ? ConditionPort = 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";
|
|
|
|
/// <summary>A2b: the node-manager condition port (null when the origin serves no conditions).</summary>
|
|
internal SingleConditionSource? ConditionPort { get; private set; }
|
|
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>
|
|
internal 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)];
|
|
}
|
|
|
|
/// <summary>A2b: every method call that reached the node-manager port (a native ack, accepted).</summary>
|
|
public List<ZB.MOM.WW.OtOpcUa.OpcUaServer.OriginConditionMethodCall> Calls { get; } = [];
|
|
|
|
public ZB.MOM.WW.OtOpcUa.OpcUaServer.OriginConditionMethodOutcome TryExecuteConditionMethod(
|
|
ZB.MOM.WW.OtOpcUa.OpcUaServer.OriginConditionMethodCall call)
|
|
{
|
|
lock (Calls) Calls.Add(call);
|
|
return new(true, true, 0, null);
|
|
}
|
|
}
|
|
|
|
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."); }
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>Drives one HistoryRead through the real service (H2); <paramref name="connectionId"/> is the HTTP/2 connection.</summary>
|
|
internal async Task<W.HistoryReadResponse> 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);
|
|
}
|
|
|
|
/// <summary>The origin facade, for direct runtime-consumer history (H2).</summary>
|
|
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<string> 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),
|
|
"CallConditionMethod" => await service.CallConditionMethod(W.ConditionMethodRequest.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; }
|
|
|
|
/// <summary>Fake physical driver write: every catalog tag routes to one fixed driver route and succeeds.</summary>
|
|
private sealed class Route : IDataWriteRoute
|
|
{
|
|
private readonly System.Collections.Concurrent.ConcurrentQueue<string> _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<DataWriteOutcome> 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<DataWriteOutcome>(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);
|
|
}
|
|
}
|
|
|
|
/// <summary>Fake physical upstream acquisition: Good, settings unrevised.</summary>
|
|
private sealed class Demand : ISubscriptionDemandSource
|
|
{
|
|
public ValueTask<SubscriptionDemandResult> 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<W.SubscriptionFrame>
|
|
{
|
|
private readonly object _lock = new();
|
|
public List<W.SubscriptionFrame> 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<string, List<AuthProperty>>());
|
|
protected override ContextPropagationToken CreatePropagationTokenCore(ContextPropagationOptions? options) => throw new NotSupportedException();
|
|
protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders) => Task.CompletedTask;
|
|
}
|
|
}
|
|
|
|
/// <summary>A clock that never moves and never fires a timer, so every age, lease and timestamp is fixed.</summary>
|
|
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;
|
|
}
|
|
}
|