feat(grpc-data): H3 ProjectedHistoryAccess over deployed connections

Resolves, authorizes (HistoryRead demand: mapping bit + local grant on the
mapping scope, ACLs on or off) and pins each projected node, groups the batch
per connection / details / issuing endpoint and forwards through
IDataHistoryService. Remote cursors bind caller, mapping id+revision,
connection route, projection generation, origin view and serving identity, and
resend the ORIGINAL details; any change => BadContinuationPointInvalid with the
origin token released. Shared per-request assembly budget (min mapping
MaxHistoryAssemblyBytesPerRequest) => BadTooManyOperations for the remaining
nodes. Releases coalesce per connection. Replaces the H2 refusal pin with the
intended behaviour (granted => served, no grant => BadUserAccessDenied).
This commit is contained in:
Joseph Doherty
2026-11-24 00:28:17 -05:00
parent dc6cc7779d
commit 19b8163045
13 changed files with 949 additions and 29 deletions
@@ -362,7 +362,9 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
bool restrictToPlant = false, Action<ProjectedValueUpdate>? onPublished = null, bool mountAtRealmRoot = false,
long maxUnaryBytes = 8_000_000, bool allowWrite = false, IGrpcDataAdapterConnectionSource? connectionSource = null,
int? staleTimeoutMilliseconds = null, Func<IProjectedNamespacePageSink, IProjectedNamespacePageSink>? renewalSinkFactory = null,
Action<LocalCatalogCoordinator>? onCoordinator = null, int? localPermissions = null, bool allowHistory = false)
Action<LocalCatalogCoordinator>? onCoordinator = null, int? localPermissions = null, bool allowHistory = false,
Action<ProjectedHistoryAccess, OtOpcUaNodeManager>? onHistory = null,
Action<ZB.MOM.WW.OtOpcUa.Configuration.Entities.RemoteNamespaceMapping>? configureMapping = null)
{
var ct = TestContext.Current.CancellationToken;
var pki = Path.Combine(Path.GetTempPath(), $"composed-projection-{Guid.NewGuid():N}");
@@ -401,6 +403,7 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
mapping.AllowedOperations |= DataOperations.Read | DataOperations.Metadata;
if (allowWrite) { mapping.AllowedOperations |= DataOperations.Write; mapping.WriteThrough = true; }
if (allowHistory) mapping.AllowedOperations |= DataOperations.HistoryRead;
configureMapping?.Invoke(mapping);
placements.Stage(attempt, [mapping], [Connection()]);
coordinator.Complete(attempt, true).ShouldBeTrue();
var manager = started.Server.NodeManager!;
@@ -427,6 +430,11 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8);
manager.ProjectedBrowseAccess = browse;
manager.ProjectedDataAccess = access;
// H3: projected HistoryRead through the same deployed connections.
using var history = new ProjectedHistoryAccess(access, connections,
id => placements.TryGetHistoryAssemblyBudget(id, out var bytes) ? bytes : null, origin.Clock);
manager.ProjectedHistoryAccess = history;
onHistory?.Invoke(history, manager);
var identifier = ProjectedDataIds.Identifier("map", root.Address);
((IProjectedNodeLookup)sink).TryGetNodeId(ProjectedDataIds.NamespaceUri(root.Realm), identifier, out var node).ShouldBeTrue();
var anchor = node.ShouldNotBeNull();
@@ -7,6 +7,8 @@ using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P04")]
@@ -131,7 +133,8 @@ internal sealed class LocalDataFixture : IDisposable
Func<DataAuthenticatedContext, DataTarget, IDataSubscriptionService>? targetSubscriptions = null,
bool advanceAuthority = false, string role = "Primary", long servingGeneration = 0, bool nestedCatalog = false, bool nestedUnsCatalog = false,
Func<DataAuthenticatedContext, IDataWriteService>? writes = null, bool denyReadExport = false,
ManualTimeProvider? clock = null, string servingNode = "node-a", string servingIncarnation = "serving-1")
ManualTimeProvider? clock = null, string servingNode = "node-a", string servingIncarnation = "serving-1",
IOriginHistoryPort? history = null)
{
if (clock is not null) Clock = clock;
Serving = Serving with { NodeId = servingNode, Incarnation = servingIncarnation, Role = role, ServingGeneration = servingGeneration };
@@ -158,6 +161,7 @@ internal sealed class LocalDataFixture : IDisposable
Context = new("peer", key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(key), Clock.GetUtcNow().AddMinutes(10), Authority.Current.GenerationId);
var operations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe;
if (denyReadExport) operations &= ~DataOperations.Read;
if (history is not null) operations |= DataOperations.HistoryRead;
var rootMetadata = new DataMetadata(Root, "Plant", "Folder", DataValueKind.Null, -1, [], false, operations, 1, null, null, false);
var rawMetadata = new DataMetadata(Raw, "Speed", "Variable", DataValueKind.Int32, -1, [], true, operations, 1, Ticket.Key.StableSourceId, "rpm", false);
var unsMetadata = rawMetadata with { View = Uns };
@@ -192,7 +196,7 @@ internal sealed class LocalDataFixture : IDisposable
var capabilities = new DataCapabilitiesProvider("cluster", () => Serving, () => Catalog.IsActive, limits);
Services = new LocalDataServices(() => Catalog, Hub, new DataOperationPolicy(Authority,
new TriePermissionEvaluator(Authority.Tries, Clock), Clock), capabilities, Clock, writes: writes, subscriptions: subscriptions,
targetSubscriptions: targetSubscriptions);
targetSubscriptions: targetSubscriptions, history: history);
}
internal IDataConnection Connection() => Services.Create(Context, new(DataTargetMode.Node, "cluster", Serving.NodeId));
@@ -0,0 +1,54 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>
/// H3 — the resume rule of a consumer Remote cursor: it resumes only under the caller, mapping revision, deployed
/// connection, projection generation, origin view and serving identity it was issued under. A mapping revision change,
/// a failover / origin restart (serving node, incarnation, generation or role), a projection rebuild or another caller
/// ⇒ the cursor never resumes (<c>BadContinuationPointInvalid</c>, origin token released).
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H3")]
public sealed class GrpcDataProjectedHistoryCursorTests
{
private static readonly DataView View = new(new DataAddress("origin", "urn:raw", "string", "Plant/Speed"), DataRealm.Raw, null, 0, "Plant/Speed");
private static readonly DataMetadata Metadata = new(View, "Speed", "Tag", DataValueKind.Int32, -1, [], false,
DataOperations.Read | DataOperations.HistoryRead, 1, null, null, false, History: new DataHistoryInfo(true));
private static readonly ProjectedHistoryTarget Issued = new("map", 3, "link", Metadata, new ServingIdentity("node-a", "boot-1", "Primary", 5, 6, 2), 7);
private const string Caller = "peer\0key\0v1";
private static readonly Dictionary<string, (ProjectedHistoryTarget Now, string Caller)> ChangeMap = new()
{
["mapping revision change"] = (Issued with { MappingRevision = 4 }, Caller),
["another mapping"] = (Issued with { MappingId = "other" }, Caller),
["another connection"] = (Issued with { ConnectionId = "link-2" }, Caller),
["projection rebuild"] = (Issued with { ProjectionGeneration = 8 }, Caller),
["failover to the pair member"] = (Issued with { Serving = Issued.Serving with { NodeId = "node-b" } }, Caller),
["origin restart"] = (Issued with { Serving = Issued.Serving with { Incarnation = "boot-2" } }, Caller),
["serving generation bump"] = (Issued with { Serving = Issued.Serving with { ServingGeneration = 3 } }, Caller),
["role change"] = (Issued with { Serving = Issued.Serving with { Role = "Secondary" } }, Caller),
["another origin view"] = (Issued with { OriginMetadata = Metadata with { View = View with { Subject = "Plant/Other" } } }, Caller),
["another caller"] = (Issued, "intruder\0key\0v1"),
["a rotated credential"] = (Issued, "peer\0key\0v2"),
};
[Fact]
public void The_same_binding_resumes_even_when_only_the_catalog_or_authority_epoch_moved()
{
ProjectedHistoryAccess.CursorMatches(Issued, Caller, Issued, Caller).ShouldBeTrue();
// A metadata renewal or ACL redeploy at the origin moves epochs, not the serving identity the token is bound to
// (the origin itself still refuses a token its own history epoch no longer matches).
ProjectedHistoryAccess.CursorMatches(Issued, Caller,
Issued with { Serving = Issued.Serving with { CatalogEpoch = 9, AuthorityEpoch = 9 } }, Caller).ShouldBeTrue();
}
public static TheoryData<string> Changes => new(ChangeMap.Keys);
[Theory]
[MemberData(nameof(Changes))]
public void Any_binding_change_refuses_the_resume(string change) =>
ProjectedHistoryAccess.CursorMatches(Issued, Caller, ChangeMap[change].Now, ChangeMap[change].Caller).ShouldBeFalse(change);
}
@@ -1,39 +1,390 @@
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
{
/// <summary>
/// H2 review 7: <c>DataOperationPolicy</c> now maps OPC UA HistoryRead to the mapping's HistoryRead bit, so a mapped
/// HistoryRead is AUTHORISABLE before H3 projects history. Pin that a projected node with the mapping bit AND a local
/// HistoryRead grant still answers a clean refusal — never data, never a fault — until H3.
/// </summary>
private static readonly DateTime HistoryT0 = new(2026, 11, 20, 10, 0, 0, DateTimeKind.Utc);
[Fact(Timeout = 90000)]
[Trait("Phase", "H2")]
public async Task HistoryRead_on_a_projected_node_stays_a_clean_refusal_until_H3()
[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()
{
using var origin = new LocalDataFixture(servingGeneration: 1);
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 details = new ReadRawModifiedDetails
var values = new List<SdkDataValue>();
var cp = default(ByteString);
var pages = 0;
do
{
StartTime = DateTime.UtcNow.AddHours(-1), EndTime = DateTime.UtcNow, NumValuesPerNode = 10,
IsReadModified = false, ReturnBounds = false,
};
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = anchor }], TestContext.Current.CancellationToken);
var result = response.Results.ToArray()!.Single();
// Pinned: the projected variable carries no HistoryRead access-level bit, so the SDK refuses before any history code.
result.StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
(result.HistoryData.IsNull || ExtensionObject.ToEncodeable(result.HistoryData) is not HistoryData { DataValues.Count: > 0 })
.ShouldBeTrue("no data is served from a projected node before H3");
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();
}, localPermissions: 15, allowHistory: true);
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());
}, 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));
}
// ------------------------------------------------------------------------------------------------------------------
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);
}
}
/// <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)
{
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(i, 0, HistoryT0.AddSeconds(i), HistoryT0.AddSeconds(i))).ToArray()) { MaxRawValuesPerRead = maxRawPerRead };
nm.HistorianDataSource = source;
nm.EnsureVariable("Plant/Driver/Device/Speed", null, "Speed", "Int32", 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 => new DataValueSnapshot(1, 0, t, t)).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() { }
}
}