Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs
T
Joseph Doherty 1237e9e6d1 fix(grpc-data): H3 review D1/D4/D6/D7 — probe cancel, sub-batches, flush wake-up, request-order budget
D1: a caller cancel (the projected deadline) during the connection's capability
probe escaped as RpcException(Cancelled) and faulted the whole HistoryRead; it
is now OperationCanceledException, the probe is capped by HistoryTimeout, and
ProjectedHistoryAccess fails any escaping fault per node (BadTimeout when the
deadline fired) and releases every cursor it owns. D4: calls are sub-batched at
min(the deployed connection's batch, the origin's advertised MaxBatchItems) and
at most one item per 256 B of the remaining assembly budget; a shortfall is
BadTooManyOperations per node, never an endpoint failure. D6: the release flush
is re-armed from a flag under its gate (no lost wake-up) and the stop source is
never disposed under a running flush. D7: calls are runs of consecutive request
positions read in request order, then the budget is charged in request order.
Float32 node over a Double-returning backend reads Good Singles end to end (no
KindMatches defect). Red/green for D1/D4/D7 by mutation; D6's race did not
reproduce red.
2026-11-24 01:48:12 -05:00

610 lines
38 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Opc.Ua.Client;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult;
using SdkDataValue = Opc.Ua.DataValue;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>
/// H3 — a real consumer OPC UA session HistoryReads a projected node through the real projection stack
/// (<see cref="ProjectedDataAccess"/> + <see cref="ProjectedHistoryAccess"/>) and a real in-process origin
/// (<see cref="LocalDataServices"/> over a real <see cref="OtOpcUaNodeManager"/> history port and its
/// <c>PeerHistoryContinuationStore</c>). Replaces the H2 pin that a projected node refused HistoryRead "until H3".
/// </summary>
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
{
private static readonly DateTime HistoryT0 = new(2026, 11, 20, 10, 0, 0, DateTimeKind.Utc);
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
[Trait("Phase", "H2")] // replaces the H2 pin "a projected node refuses HistoryRead until H3"
public async Task Granted_projected_HistoryRead_is_served_verbatim_and_pages_to_completion_through_the_origin()
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
var connections = new PersistentConnections(origin);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var values = new List<SdkDataValue>();
var cp = default(ByteString);
var pages = 0;
do
{
var result = await RawHistory(client, anchor, 3, cp);
StatusCode.IsGood(result.StatusCode).ShouldBeTrue(result.StatusCode.ToString());
values.AddRange(Values(result));
cp = result.ContinuationPoint;
pages++;
} while (!cp.IsEmpty && pages < 10);
values.Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe(Enumerable.Range(0, 7).Cast<object?>());
values.Select(v => v.SourceTimestamp.ToDateTime()).ShouldBe(Enumerable.Range(0, 7).Select(i => HistoryT0.AddSeconds(i)));
pages.ShouldBe(3);
origin.Services.HistoryOpenContinuations.ShouldBe(0, "a page-through to completion leaves nothing open at the origin");
}, localPermissions: 15, allowHistory: true, connectionSource: connections);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
[Trait("Phase", "H2")] // replaces the H2 pin "a projected node refuses HistoryRead until H3"
public async Task Without_the_local_HistoryRead_grant_on_the_mapping_scope_it_is_BadUserAccessDenied_and_unsent()
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var result = await RawHistory(client, anchor, 3, default);
result.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
result.ContinuationPoint.IsEmpty.ShouldBeTrue();
originServer.Source.Calls.ShouldBe(0);
}, localPermissions: 7, allowHistory: true, connectionSource: new PersistentConnections(origin));
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task Consumer_session_close_releases_the_origin_continuations()
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
ProjectedHistoryAccess? history = null;
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var page = await RawHistory(client, anchor, 2, default);
page.ContinuationPoint.IsEmpty.ShouldBeFalse();
origin.Services.HistoryOpenContinuations.ShouldBe(1);
await session.CloseAsync(TestContext.Current.CancellationToken);
await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0);
origin.Services.HistoryOpenContinuations.ShouldBe(0, "the SDK disposed the Remote point and the release reached the origin");
history!.ReleaseCallsForTests.ShouldBe(1);
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin),
onHistory: (h, _) => history = h);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task ReleaseContinuationPoints_forwards_one_release_and_the_point_is_then_invalid()
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
ProjectedHistoryAccess? history = null;
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var page = await RawHistory(client, anchor, 2, default);
origin.Services.HistoryOpenContinuations.ShouldBe(1);
var released = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(2)), TimestampsToReturn.Both, true,
[new HistoryReadValueId { NodeId = anchor, ContinuationPoint = page.ContinuationPoint }], TestContext.Current.CancellationToken);
StatusCode.IsGood(released.Results[0].StatusCode).ShouldBeTrue();
await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0);
origin.Services.HistoryOpenContinuations.ShouldBe(0);
var resumed = await RawHistory(client, anchor, 2, page.ContinuationPoint);
resumed.StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin), onHistory: (h, _) => history = h);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task A_resume_after_lease_expiry_or_an_origin_rebuild_epoch_bump_is_invalid_and_a_fresh_read_succeeds()
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
var connections = new PersistentConnections(origin);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
// Lease expiry / redeployment: the deployed connection (route) is replaced — its tokens never resume.
var page = await RawHistory(client, anchor, 2, default);
connections.Rotate();
(await RawHistory(client, anchor, 2, page.ContinuationPoint)).StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
var fresh = await RawHistory(client, anchor, 2, default);
StatusCode.IsGood(fresh.StatusCode).ShouldBeTrue();
// Origin rebuild: its history epoch moves (a removal), so the origin itself refuses the resumed token.
originServer.BumpEpoch();
(await RawHistory(client, anchor, 2, fresh.ContinuationPoint)).StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
StatusCode.IsGood((await RawHistory(client, anchor, 2, default)).StatusCode).ShouldBeTrue();
}, localPermissions: 15, allowHistory: true, connectionSource: connections);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task Uncapped_raw_returns_the_origin_continuation_and_aggregates_are_refused_both_ways()
{
await using var originServer = await HistoryOrigin.StartAsync(25, maxRawPerRead: 10);
originServer.Source.Aggregates = new HashSet<HistoryAggregateType> { HistoryAggregateType.Average };
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
// NumValuesPerNode = 0: the origin pages at its ceiling and the consumer hands back its continuation (Part 11).
var uncapped = await RawHistory(client, anchor, 0, default);
StatusCode.IsGood(uncapped.StatusCode).ShouldBeTrue();
uncapped.ContinuationPoint.IsEmpty.ShouldBeFalse();
Values(uncapped).Count.ShouldBeLessThan(25);
// The origin refuses an aggregate its backend does not serve.
var refused = await ProcessedHistory(client, anchor, ObjectIds.AggregateFunction_Count);
refused.StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code);
// The consumer refuses an aggregate it cannot name, unsent.
var calls = originServer.Source.Calls;
var unknown = await ProcessedHistory(client, anchor, new NodeId("no-such-aggregate", 1));
unknown.StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code);
originServer.Source.Calls.ShouldBe(calls);
// A served aggregate passes through.
var average = await ProcessedHistory(client, anchor, ObjectIds.AggregateFunction_Average);
StatusCode.IsGood(average.StatusCode).ShouldBeTrue(average.StatusCode.ToString());
// Found by the H3 live gate (H02): an aggregate's value has ITS OWN type (a Double Average of an Int32 node),
// never the node's — it must not be refused BadTypeMismatch against the catalog's value kind.
var interval = Values(average).ShouldHaveSingleItem();
StatusCode.IsGood(interval.StatusCode).ShouldBeTrue(interval.StatusCode.ToString());
SdkValueBoundary.ToClr(interval.WrappedValue).ShouldBeOfType<double>().ShouldBe(3.0);
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin));
}
[Theory(Timeout = 90000)]
[Trait("Phase", "H3")]
[InlineData(1_000_000, 3)]
[InlineData(25_000, 2)] // ≈ 288 B a value × 40 per node: two nodes fit, the third is refused
[InlineData(15_000, 1)]
[InlineData(1_200, 0)]
public async Task The_per_request_assembly_budget_is_shared_across_the_batch(int budget, int expectedGood)
{
await using var originServer = await HistoryOrigin.StartAsync(7, extra: 2);
using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, history: originServer.Port);
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
var children = (await BrowseAll(client, anchor, 10))
.Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
children.Length.ShouldBe(3);
var details = new ReadAtTimeDetails { ReqTimes = Enumerable.Range(0, 40).Select(i => (DateTimeUtc)HistoryT0.AddSeconds(i)).ToArray() };
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false,
children.Select(c => new HistoryReadValueId { NodeId = c }).ToArray(), TestContext.Current.CancellationToken);
var results = response.Results.ToArray()!;
var statuses = results.Select(r => r.StatusCode.Code).ToArray();
statuses.Count(s => StatusCode.IsGood(s)).ShouldBe(expectedGood, string.Join(",", statuses.Select(x => x.ToString("X8"))));
foreach (var r in results.Where(r => !StatusCode.IsGood(r.StatusCode)))
{
r.StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code);
Values(r).ShouldBeEmpty("never a partial answer under an error status");
}
foreach (var r in results.Where(r => StatusCode.IsGood(r.StatusCode))) Values(r).Count.ShouldBe(40);
// The budget is consumed in request order: once a node does not fit, every later node is refused too.
statuses.TakeWhile(x => StatusCode.IsGood(x)).Count().ShouldBe(expectedGood);
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin),
configureMapping: m => m.MaxHistoryAssemblyBytesPerRequest = budget);
}
[Theory(Timeout = 90000)]
[Trait("Phase", "H3")]
[InlineData(false)]
[InlineData(true)]
public async Task Historizing_and_the_HistoryRead_bit_follow_the_mapping_grant_and_never_HistoryWrite(bool granted)
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var read = await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Neither,
[new ReadValueId { NodeId = anchor, AttributeId = Attributes.Historizing },
new ReadValueId { NodeId = anchor, AttributeId = Attributes.AccessLevel }], TestContext.Current.CancellationToken);
read.Results[0].WrappedValue.TryGetValue(out bool historizing).ShouldBeTrue();
historizing.ShouldBe(granted);
read.Results[1].WrappedValue.TryGetValue(out byte level).ShouldBeTrue();
((level & AccessLevels.HistoryRead) != 0).ShouldBe(granted);
(level & AccessLevels.HistoryWrite).ShouldBe((byte)0);
if (granted) return;
var result = await RawHistory(client, anchor, 3, default);
result.StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
originServer.Source.Calls.ShouldBe(0);
}, localPermissions: 15, allowHistory: granted, connectionSource: new PersistentConnections(origin));
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task A_Float32_node_whose_backend_returns_Double_reads_Good_through_the_projection_as_it_does_locally()
{
// H3 review: SQL backends store every float as a Double. The origin port normalises Raw / AtTime to the node's type
// (Single) before the wire, so the projected rows are Good Singles — never a BadTypeMismatch per row while local works.
await using var originServer = await HistoryOrigin.StartAsync(5, dataType: "Float", value: i => i + 0.5);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port, rawValueKind: DataValueKind.Float);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var raw = await RawHistory(client, anchor, 0, default);
StatusCode.IsGood(raw.StatusCode).ShouldBeTrue(raw.StatusCode.ToString());
var values = Values(raw);
values.Count.ShouldBe(5);
values.ShouldAllBe(v => StatusCode.IsGood(v.StatusCode));
values.Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe(Enumerable.Range(0, 5).Select(i => (object?)(float)(i + 0.5)));
var details = new ReadAtTimeDetails { ReqTimes = [(DateTimeUtc)HistoryT0.AddSeconds(2)] };
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = anchor }], TestContext.Current.CancellationToken);
var atTime = Values(response.Results.ToArray()!.Single()).ShouldHaveSingleItem();
StatusCode.IsGood(atTime.StatusCode).ShouldBeTrue(atTime.StatusCode.ToString());
SdkValueBoundary.ToClr(atTime.WrappedValue).ShouldBeOfType<float>().ShouldBe(2.5f);
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin));
}
[Theory(Timeout = 90000)]
[Trait("Phase", "H3")]
[InlineData(HistoryMode.Hang)]
[InlineData(HistoryMode.Throw)]
public async Task A_history_call_that_never_answers_or_faults_fails_only_the_projected_half_and_releases_its_cursor(HistoryMode mode)
{
// H3 review D1: a deadline during the connection's capability probe used to escape as an RpcException and fault the
// whole HistoryRead. Now the projected half fails per node (BadTimeout when the deadline fired), the local half of the
// same batch is served, and the claimed origin cursor is released (positive control: the origin store returns to 0).
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
var connections = new HistorySwitchConnections(origin);
ProjectedHistoryAccess? history = null;
OtOpcUaNodeManager? manager = null;
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
manager!.HistorianDataSource = new SeriesSource(Enumerable.Range(0, 3)
.Select(i => new DataValueSnapshot(i, 0, HistoryT0.AddSeconds(i), HistoryT0.AddSeconds(i))).ToArray());
manager.EnsureVariable("Plant/LocalH", "Plant", "LocalH", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "local");
var local = manager.TryGetVariable("Plant/LocalH", AddressSpaceRealm.Raw)!.NodeId;
var page = await RawHistory(client, anchor, 2, default);
page.ContinuationPoint.IsEmpty.ShouldBeFalse();
origin.Services.HistoryOpenContinuations.ShouldBe(1);
connections.Mode = mode;
manager.HistoryReadDeadline = TimeSpan.FromSeconds(1);
var response = await client.HistoryReadAsync(new RequestHeader { TimeoutHint = 20_000 }, new ExtensionObject(RawDetails(2)),
TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = local }, new HistoryReadValueId { NodeId = anchor, ContinuationPoint = page.ContinuationPoint }],
TestContext.Current.CancellationToken);
var results = response.Results.ToArray()!;
StatusCode.IsGood(results[0].StatusCode).ShouldBeTrue("the local half of the batch is still served");
Values(results[0]).Count.ShouldBe(2);
results[1].StatusCode.Code.ShouldBe(mode == HistoryMode.Hang ? StatusCodes.BadTimeout.Code : StatusCodes.BadContinuationPointInvalid.Code);
await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0);
origin.Services.HistoryOpenContinuations.ShouldBe(0, "the claimed cursor's origin continuation was released");
}, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (h, m) => { history = h; manager = m; });
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task A_group_larger_than_the_origin_batch_is_split_into_sub_batches()
{
// H3 review D4: three projected nodes against an origin that admits two items per request.
await using var originServer = await HistoryOrigin.StartAsync(7, extra: 2);
using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, history: originServer.Port, maxBatchItems: 2);
var connections = new HistorySwitchConnections(origin);
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
children.Length.ShouldBe(3);
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false,
children.Select(c => new HistoryReadValueId { NodeId = c }).ToArray(), TestContext.Current.CancellationToken);
var results = response.Results.ToArray()!;
results.ShouldAllBe(r => StatusCode.IsGood(r.StatusCode));
results.ShouldAllBe(r => Values(r).Count == 3);
connections.HistoryCallSizes.ShouldBe([2, 1]);
foreach (var r in results) await RawHistory(client, children[Array.IndexOf(results, r)], 3, r.ContinuationPoint);
}, localPermissions: 15, allowHistory: true, connectionSource: connections);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task The_assembly_budget_is_charged_in_request_order_across_groups()
{
// H3 review D7: request [A fresh, B resumed, C fresh] runs as two groups ({A, C} then {B}); with room for two nodes the
// refused one must be C — the last in REQUEST order — not B.
await using var originServer = await HistoryOrigin.StartAsync(7, extra: 2);
using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, history: originServer.Port);
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
children.Length.ShouldBe(3);
var first = await RawHistory(client, children[1], 3, default);
first.ContinuationPoint.IsEmpty.ShouldBeFalse();
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = children[0] }, new HistoryReadValueId { NodeId = children[1], ContinuationPoint = first.ContinuationPoint },
new HistoryReadValueId { NodeId = children[2] }], TestContext.Current.CancellationToken);
var results = response.Results.ToArray()!;
StatusCode.IsGood(results[0].StatusCode).ShouldBeTrue(results[0].StatusCode.ToString());
StatusCode.IsGood(results[1].StatusCode).ShouldBeTrue("the resumed node is second in request order: it fits");
results[2].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code);
Values(results[2]).ShouldBeEmpty();
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin),
configureMapping: m => m.MaxHistoryAssemblyBytesPerRequest = 2 * 3 * 288 + 100); // ≈ 288 B a value: two 3-value nodes fit
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task Releases_queued_while_a_flush_is_finishing_are_never_lost()
{
// H3 review D6: the flush used to be re-armed from Task.IsCompleted, so a token queued after its last check but before it
// completed waited for the NEXT release — or forever. Many concurrent enqueues must all reach the connection.
await using var originServer = await HistoryOrigin.StartAsync(1);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
var connections = new HistorySwitchConnections(origin);
ProjectedHistoryAccess? history = null;
await WithComposedServer(origin, origin.Raw, async (_, _, _, _, _, _, _) =>
{
const int count = 2000;
await Task.WhenAll(Enumerable.Range(0, 8).Select(t => Task.Run(() =>
{
for (var i = t; i < count; i += 8) history!.EnqueueReleaseForTests("link", BitConverter.GetBytes(i));
})));
var deadline = DateTime.UtcNow.AddSeconds(20);
while (connections.ReleasedTokens < count && DateTime.UtcNow < deadline)
{
await history!.FlushReleasesForTestsAsync();
await Task.Delay(10, TestContext.Current.CancellationToken);
}
connections.ReleasedTokens.ShouldBe(count);
}, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (h, _) => history = h);
}
// ------------------------------------------------------------------------------------------------------------------
private static ReadRawModifiedDetails RawDetails(uint count) => new()
{
StartTime = HistoryT0.AddSeconds(-1), EndTime = HistoryT0.AddHours(1), NumValuesPerNode = count, IsReadModified = false, ReturnBounds = false,
};
private static async Task<Opc.Ua.HistoryReadResult> RawHistory(SessionClient client, NodeId node, uint count, ByteString cp)
{
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(count)), TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = node, ContinuationPoint = cp }], TestContext.Current.CancellationToken);
return response.Results.ToArray()!.Single();
}
private static async Task<Opc.Ua.HistoryReadResult> ProcessedHistory(SessionClient client, NodeId node, NodeId aggregate)
{
var details = new ReadProcessedDetails
{
StartTime = HistoryT0, EndTime = HistoryT0.AddMinutes(1), ProcessingInterval = 10_000, AggregateType = [aggregate],
AggregateConfiguration = new AggregateConfiguration { UseServerCapabilitiesDefaults = true },
};
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = node }], TestContext.Current.CancellationToken);
return response.Results.ToArray()!.Single();
}
private static IReadOnlyList<SdkDataValue> Values(Opc.Ua.HistoryReadResult result) =>
result.HistoryData.IsNull || ExtensionObject.ToEncodeable(result.HistoryData) is not HistoryData data ? [] : data.DataValues.ToArray() ?? [];
private static async Task AwaitReleases(ProjectedHistoryAccess history, Func<bool> done)
{
for (var i = 0; i < 200 && !done(); i++)
{
await history.FlushReleasesForTestsAsync();
if (!done()) await Task.Delay(10, TestContext.Current.CancellationToken);
}
}
public enum HistoryMode { Pass, Hang, Throw }
/// <summary>
/// One long-lived origin connection whose HISTORY path can be switched to never answer (then fault as a cancelled gRPC call,
/// as a probe cancelled by its deadline did) or to fault at once; releases always pass through and are counted.
/// </summary>
private sealed class HistorySwitchConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource
{
private IDataConnection? _inner;
private readonly object _gate = new();
private int _released;
private readonly List<int> _sizes = [];
public HistoryMode Mode { get; set; }
public int ReleasedTokens => Volatile.Read(ref _released);
public IReadOnlyList<int> HistoryCallSizes { get { lock (_sizes) return _sizes.ToArray(); } }
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken)
{
if (connectionId != "link") return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(null);
lock (_gate) _inner ??= peer.Connection();
return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new Borrowed(new Switch(_inner, this), _gate));
}
private sealed class Borrowed(IDataConnection connection, object route) : IGrpcDataAdapterConnectionLease
{
public IDataConnection Connection => connection;
public CancellationToken CancellationToken => CancellationToken.None;
public object? RouteIdentity => route;
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
private sealed class Switch(IDataConnection inner, HistorySwitchConnections owner) : IDataConnection, IDataHistoryService
{
public DataTarget Target => inner.Target;
public TimeProvider Clock => inner.Clock;
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken);
public Task<DataBrowseBranch> BrowseAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest request, CancellationToken cancellationToken) => inner.BrowseAsync(request, cancellationToken);
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => inner.GetMetadataAsync(request, cancellationToken);
public Task<IReadOnlyList<ReadResult>> ReadAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest request, CancellationToken cancellationToken) => inner.ReadAsync(request, cancellationToken);
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken);
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
public async Task<IReadOnlyList<DataHistoryReadResult>> ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken)
{
lock (owner._sizes) owner._sizes.Add(request.Items.Count);
switch (owner.Mode)
{
case HistoryMode.Hang:
try { await Task.Delay(Timeout.Infinite, cancellationToken); }
catch (OperationCanceledException ex)
{ throw new Grpc.Core.RpcException(new Grpc.Core.Status(Grpc.Core.StatusCode.Cancelled, "probe cancelled", ex)); }
break;
case HistoryMode.Throw:
throw new Grpc.Core.RpcException(new Grpc.Core.Status(Grpc.Core.StatusCode.Internal, "boom"));
}
return await ((IDataHistoryService)inner).ReadAsync(request, cancellationToken);
}
public async Task ReleaseAsync(IReadOnlyList<byte[]> continuations, CancellationToken cancellationToken)
{
Interlocked.Add(ref owner._released, continuations.Count);
await ((IDataHistoryService)inner).ReleaseAsync(continuations, cancellationToken);
}
}
}
/// <summary>One long-lived origin connection, as a deployed gRPC connection is; <see cref="Rotate"/> replaces it (a redeploy).</summary>
private sealed class PersistentConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource
{
private (IDataConnection Connection, object Route)? _current;
private readonly object _gate = new();
public void Rotate()
{
lock (_gate)
{
if (_current is { } old) _ = old.Connection.DisposeAsync();
_current = null;
}
}
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken)
{
if (connectionId != "link") return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(null);
lock (_gate)
{
_current ??= (peer.Connection(), new object());
return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new Borrowed(_current.Value.Connection, _current.Value.Route));
}
}
private sealed class Borrowed(IDataConnection connection, object route) : IGrpcDataAdapterConnectionLease
{
public IDataConnection Connection => connection;
public CancellationToken CancellationToken => CancellationToken.None;
public object? RouteIdentity => route;
public ValueTask DisposeAsync() => ValueTask.CompletedTask; // non-owning, like a deployment lease
}
}
/// <summary>A real origin node manager with a historized raw <c>Plant/Driver/Device/Speed</c> behind a real history port.</summary>
private sealed class HistoryOrigin : IAsyncDisposable
{
private readonly OpcUaApplicationHost _host;
private readonly string _pki;
private readonly OtOpcUaNodeManager _nm;
public SeriesSource Source { get; }
public OriginHistoryPort Port { get; }
private HistoryOrigin(OpcUaApplicationHost host, string pki, OtOpcUaNodeManager nm, SeriesSource source)
{ _host = host; _pki = pki; _nm = nm; Source = source; Port = new OriginHistoryPort(nm); }
public static async Task<HistoryOrigin> StartAsync(int samples, int maxRawPerRead = 0, int extra = 0, string dataType = "Int32",
Func<int, object>? value = null)
{
var pki = Path.Combine(Path.GetTempPath(), $"h3-origin-{Guid.NewGuid():N}");
var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
{
ApplicationName = "H3Origin", ApplicationUri = $"urn:h3-origin:{Guid.NewGuid():N}", OpcUaPort = port,
PublicHostname = "127.0.0.1", PkiStoreRoot = pki, EnabledSecurityProfiles = [OpcUaSecurityProfile.None],
}, NullLogger<OpcUaApplicationHost>.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken);
var nm = started.Server.NodeManager!;
var source = new SeriesSource(Enumerable.Range(0, samples)
.Select(i => new DataValueSnapshot(value?.Invoke(i) ?? i, 0, HistoryT0.AddSeconds(i), HistoryT0.AddSeconds(i))).ToArray()) { MaxRawValuesPerRead = maxRawPerRead };
nm.HistorianDataSource = source;
nm.EnsureVariable("Plant/Driver/Device/Speed", null, "Speed", dataType, false, AddressSpaceRealm.Raw, historianTagname: "speed");
nm.EnsureVariable("Plant/Driver/Device/Other", null, "Other", "Int32", false, AddressSpaceRealm.Raw);
for (var i = 0; i < extra; i++)
nm.EnsureVariable("Plant/Driver/Device/Speed" + i, null, "Speed" + i, "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed" + i);
return new HistoryOrigin(started.Host, pki, nm, source);
}
public void BumpEpoch() => _nm.RemoveVariableNode("Plant/Driver/Device/Other", AddressSpaceRealm.Raw).ShouldBeTrue();
public async ValueTask DisposeAsync()
{
await _host.DisposeAsync();
if (Directory.Exists(_pki)) try { Directory.Delete(_pki, recursive: true); } catch (IOException) { }
}
}
private sealed class SeriesSource(IReadOnlyList<DataValueSnapshot> series) : IHistorianDataSource
{
private int _calls;
public int Calls => Volatile.Read(ref _calls);
public int MaxRawValuesPerRead { get; init; }
public IReadOnlySet<HistoryAggregateType> Aggregates { get; set; } = HistoryAggregateTypes.All;
public IReadOnlySet<HistoryAggregateType> SupportedAggregates => Aggregates;
public bool SupportsReverseRaw => true;
public Task<HistorianRead> ReadRawAsync(string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode,
CancellationToken cancellationToken)
{
Interlocked.Increment(ref _calls);
IEnumerable<DataValueSnapshot> window = startUtc <= endUtc
? series.Where(s => s.SourceTimestampUtc >= startUtc && s.SourceTimestampUtc < endUtc)
: series.Where(s => s.SourceTimestampUtc <= startUtc && s.SourceTimestampUtc > endUtc).Reverse();
return Task.FromResult(new HistorianRead((maxValuesPerNode == 0 ? window : window.Take((int)maxValuesPerNode)).ToList(), null));
}
public Task<HistorianRead> ReadProcessedAsync(string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval,
HistoryAggregateType aggregate, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _calls);
return Task.FromResult(new HistorianRead([new DataValueSnapshot(3.0, 0, startUtc, startUtc)], null));
}
public Task<HistorianRead> ReadAtTimeAsync(string fullReference, IReadOnlyList<DateTime> timestampsUtc, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _calls);
return Task.FromResult(new HistorianRead(timestampsUtc.Select(t => series.LastOrDefault(s => s.SourceTimestampUtc <= t)
?? new DataValueSnapshot(null, 0x809B0000u, t, t)).Select(s => s with { SourceTimestampUtc = s.SourceTimestampUtc }).ToList(), null));
}
public Task<HistoricalEventsResult> ReadEventsAsync(
string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents, CancellationToken cancellationToken) =>
Task.FromResult(new HistoricalEventsResult(Array.Empty<HistoricalEvent>(), null));
public HistorianHealthSnapshot GetHealthSnapshot() => NullHistorianDataSource.Instance.GetHealthSnapshot();
public void Dispose() { }
}
}