feat(grpc-data): H3 SDK side of projected history

Projected variables advertise Historizing + the HistoryRead access bit (never
HistoryWrite) only when the definition says so. The Raw/Processed/AtTime
overrides split authorized handles: local ones go to the H1 port unchanged,
projected ones to IProjectedHistoryAccess, each written back to its own slot;
nothing waits under Lock. HistoryCursorKind.Remote stores the projection's
cursor in the SDK session store; disposing the point (session close, eviction,
releaseContinuationPoints, faulted request) releases it at the origin. Mapped
HistoryRead is opened deliberately in DataPlaneAuthorizer; other mapped
operations outside the allowlist stay closed.
This commit is contained in:
Joseph Doherty
2026-11-24 00:27:51 -05:00
parent ef938b435b
commit dc6cc7779d
8 changed files with 788 additions and 12 deletions
@@ -0,0 +1,372 @@
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Opc.Ua.Server;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
using SdkHistoryReadResult = Opc.Ua.HistoryReadResult;
using DataValue = Opc.Ua.DataValue;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections;
/// <summary>
/// H3 — the SDK side of projected history: the projected access level, the mapped HistoryRead gate with ACLs on and off,
/// the local/projected split keeping per-index slots, the Remote cursor in the session store (resume, release, session
/// close, wrong node), consumer-side aggregate refusal and the never-remote modified read.
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H3")]
public sealed class ProjectedHistoryReadTests : IAsyncDisposable
{
private static readonly DateTimeOffset Now = new(2026, 11, 15, 12, 0, 0, TimeSpan.Zero);
private static readonly DateTime T0 = new(2026, 11, 15, 11, 0, 0, DateTimeKind.Utc);
private readonly string _pki = Path.Combine(Path.GetTempPath(), $"otopcua-projected-history-{Guid.NewGuid():N}");
private OpcUaApplicationHost? _host;
[Fact]
public async Task Only_a_historizing_definition_gets_the_HistoryRead_bit_and_never_HistoryWrite()
{
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
var plain = Project(nm, f, "Plain", historizing: false);
var historized = Project(nm, f, "Hist", historizing: true);
var plainNode = Variable(nm, plain);
plainNode.AccessLevel.ShouldBe(AccessLevels.CurrentRead);
plainNode.Historizing.ShouldBeFalse();
var histNode = Variable(nm, historized);
histNode.AccessLevel.ShouldBe((byte)(AccessLevels.CurrentRead | AccessLevels.HistoryRead));
histNode.UserAccessLevel.ShouldBe((byte)(AccessLevels.CurrentRead | AccessLevels.HistoryRead));
(histNode.AccessLevel & AccessLevels.HistoryWrite).ShouldBe((byte)0);
histNode.Historizing.ShouldBeTrue();
var access = new FakeAccess();
nm.ProjectedHistoryAccess = access;
var (results, errors) = Raw(nm, f.Identity, [plain, historized]);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code, "no bit ⇒ the SDK refuses before any history code");
errors[1].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
access.Calls.ShouldBe(1);
access.LastNodes.Single().NodeId.ShouldBe(historized);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Mapped_HistoryRead_needs_the_local_grant_and_the_mapping_bit_with_acls_on_and_off(bool aclEnabled)
{
// Granted: served through the projection, ACLs on or off.
var (nm, f) = await BootAsync(aclEnabled, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
var node = Project(nm, f, "Speed", historizing: true);
var access = new FakeAccess();
nm.ProjectedHistoryAccess = access;
var (results, errors) = Raw(nm, f.Identity, [node]);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
Values(results[0]).Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe([1.0, 2.0]);
access.Calls.ShouldBe(1);
// No local HistoryRead grant on the mapping scope ⇒ BadUserAccessDenied, never sent — even with ACLs off.
f.Grant(NodePermissions.Browse | NodePermissions.Read);
(_, errors) = Raw(nm, f.Identity, [node]);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
access.Calls.ShouldBe(1);
// Local grant but the mapping (subject) lacks HistoryRead ⇒ denied too.
f.Grant(NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
f.SubjectOperations = DataOperations.Browse | DataOperations.Read;
(_, errors) = Raw(nm, f.Identity, [node]);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
access.Calls.ShouldBe(1);
// No identity at all ⇒ denied.
(_, errors) = Raw(nm, null, [node]);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
access.Calls.ShouldBe(1);
}
[Fact]
public async Task A_mixed_local_and_projected_batch_keeps_every_slot()
{
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
nm.EnsureVariable("Plant/LocalA", "Plant", "LocalA", "Double", false, AddressSpaceRealm.Raw, historianTagname: "L.a");
nm.EnsureVariable("Plant/LocalB", "Plant", "LocalB", "Double", false, AddressSpaceRealm.Raw, historianTagname: "L.b");
var localA = nm.TryGetVariable("Plant/LocalA", AddressSpaceRealm.Raw)!.NodeId;
var localB = nm.TryGetVariable("Plant/LocalB", AddressSpaceRealm.Raw)!.NodeId;
var p1 = Project(nm, f, "One", historizing: true);
var p2 = Project(nm, f, "Two", historizing: true);
var access = new FakeAccess { Answer = node => node.NodeId == p1 ? [10.0] : [20.0, 21.0] };
nm.ProjectedHistoryAccess = access;
var (results, errors) = Raw(nm, f.Identity, [p1, localA, p2, localB]);
Values(results[0]).Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe([10.0]);
Values(results[2]).Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe([20.0, 21.0]);
// The local slots are the H1 port's answer (no historian ⇒ GoodNoData), untouched by the projected half.
results[1].StatusCode.Code.ShouldBe(StatusCodes.GoodNoData.Code);
results[3].StatusCode.Code.ShouldBe(StatusCodes.GoodNoData.Code);
errors.ShouldAllBe(e => StatusCode.IsGood(e.StatusCode));
access.Calls.ShouldBe(1, "one remote call for the batch's projected half");
access.LastNodes.Select(n => n.NodeId).ShouldBe([p1, p2]);
}
[Fact]
public async Task A_remote_cursor_resumes_once_and_is_released_by_releaseContinuationPoints_and_session_close()
{
var (nm, f) = await BootAsync(aclEnabled: true, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
var store = new InMemoryHistoryContinuationStore();
nm.HistoryContinuationStore = store;
var node = Project(nm, f, "Paged", historizing: true);
var other = Project(nm, f, "Other", historizing: true);
var access = new FakeAccess { Paged = true };
nm.ProjectedHistoryAccess = access;
var (results, _) = Raw(nm, f.Identity, [node]);
var cp = results[0].ContinuationPoint;
cp.IsEmpty.ShouldBeFalse();
var first = access.Issued.Single();
store.Count.ShouldBe(1);
// Resume: the SAME cursor comes back to the projection, claimed for the resume (not released).
(results, _) = Raw(nm, f.Identity, [node], cp);
access.LastNodes.Single().Resume.ShouldBeSameAs(first);
first.Released.ShouldBe(0);
var second = access.Issued[1];
var cp2 = results[0].ContinuationPoint;
// The same point again ⇒ invalid (single-use), unsent.
var calls = access.Calls;
(results, var errors) = Raw(nm, f.Identity, [node], cp);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
access.Calls.ShouldBe(calls);
// A cursor resumed on ANOTHER node ⇒ invalid and released.
(_, errors) = Raw(nm, f.Identity, [other], cp2);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
second.Released.ShouldBe(1);
// releaseContinuationPoints forwards one release.
(results, _) = Raw(nm, f.Identity, [node]);
var third = access.Issued[2];
Release(nm, f.Identity, node, results[0].ContinuationPoint);
third.Released.ShouldBe(1);
store.Count.ShouldBe(0);
// Session close (the SDK disposes every point) releases what is still open.
Raw(nm, f.Identity, [node]);
Raw(nm, f.Identity, [other]);
store.Count.ShouldBe(2);
store.Clear();
access.Issued.Skip(3).ShouldAllBe(c => c.Released == 1);
}
[Fact]
public async Task A_bad_remote_answer_carries_no_cursor_and_unknown_aggregates_and_modified_reads_are_refused_unsent()
{
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
var node = Project(nm, f, "Speed", historizing: true);
var access = new FakeAccess { Status = StatusCodes.BadAggregateNotSupported.Code, Paged = true };
nm.ProjectedHistoryAccess = access;
// The origin refuses the aggregate: verbatim, no cursor kept (and the one it returned is released).
var processed = new ReadProcessedDetails
{
StartTime = T0, EndTime = T0.AddHours(1), ProcessingInterval = 60_000,
AggregateType = [ObjectIds.AggregateFunction_Average],
};
var (results, errors) = Read(nm, f.Identity, processed, [node]);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code);
results[0].ContinuationPoint.IsEmpty.ShouldBeTrue();
access.Issued.ShouldAllBe(c => c.Released == 1);
access.LastNodes.Single().AggregateId.ShouldBe(Objects.AggregateFunction_Average);
// An aggregate the consumer cannot name ⇒ BadAggregateNotSupported without a call.
var calls = access.Calls;
processed.AggregateType = [new NodeId("not-an-aggregate", 2)];
(_, errors) = Read(nm, f.Identity, processed, [node]);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code);
access.Calls.ShouldBe(calls);
// A modified read is never served remotely.
var modified = new ReadRawModifiedDetails { StartTime = T0, EndTime = T0.AddHours(1), NumValuesPerNode = 5, IsReadModified = true };
(_, errors) = Read(nm, f.Identity, modified, [node]);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
access.Calls.ShouldBe(calls);
}
[Fact]
public void Unset_bounds_travel_absent_and_AtTime_carries_its_times()
{
OtOpcUaNodeManager.ToRemoteDetails(new ReadRawModifiedDetails { EndTime = T0, NumValuesPerNode = 3, ReturnBounds = true, IsReadModified = false })
.ShouldBe(new DataHistoryRawDetails(null, new DateTimeOffset(T0), 3, true));
var atTime = OtOpcUaNodeManager.ToRemoteDetails(new ReadAtTimeDetails { ReqTimes = [T0], UseSimpleBounds = true })
.ShouldBeOfType<DataHistoryAtTimeDetails>();
atTime.RequestedTimesUtc.ShouldBe([new DateTimeOffset(T0)]);
atTime.UseSimpleBounds.ShouldBeTrue();
}
// ------------------------------------------------------------------------------------------------------------------
private static (List<SdkHistoryReadResult> Results, List<ServiceResult> Errors) Raw(OtOpcUaNodeManager nm, IUserIdentity? identity,
NodeId[] nodes, ByteString cp = default) =>
Read(nm, identity, new ReadRawModifiedDetails
{
StartTime = T0, EndTime = T0.AddHours(1), NumValuesPerNode = 2, IsReadModified = false, ReturnBounds = false,
}, nodes, cp);
private static (List<SdkHistoryReadResult> Results, List<ServiceResult> Errors) Read(OtOpcUaNodeManager nm, IUserIdentity? identity,
HistoryReadDetails details, NodeId[] nodes, ByteString cp = default)
{
var context = new OperationContext(new RequestHeader(), null, RequestType.HistoryRead, RequestLifetime.None, identity);
var results = nodes.Select(_ => (SdkHistoryReadResult)null!).ToList();
var errors = nodes.Select(_ => (ServiceResult)null!).ToList();
nm.HistoryRead(context, details, TimestampsToReturn.Both, false,
nodes.Select(n => new HistoryReadValueId { NodeId = n, ContinuationPoint = cp }).ToList(), results, errors);
return (results, errors);
}
private static void Release(OtOpcUaNodeManager nm, IUserIdentity identity, NodeId node, ByteString cp)
{
var context = new OperationContext(new RequestHeader(), null, RequestType.HistoryRead, RequestLifetime.None, identity);
var results = new List<SdkHistoryReadResult> { null! };
var errors = new List<ServiceResult> { null! };
nm.HistoryRead(context, new ReadRawModifiedDetails { IsReadModified = false, ReturnBounds = false }, TimestampsToReturn.Both, true,
new List<HistoryReadValueId> { new() { NodeId = node, ContinuationPoint = cp } }, results, errors);
StatusCode.IsGood(errors[0].StatusCode).ShouldBeTrue();
}
private static IReadOnlyList<DataValue> Values(SdkHistoryReadResult result) =>
ExtensionObject.ToEncodeable(result.HistoryData) is HistoryData data ? data.DataValues.ToArray() ?? [] : [];
private static BaseDataVariableState Variable(OtOpcUaNodeManager nm, NodeId id) =>
((NodeHandle)nm.GetManagerHandle(id)!).Node.ShouldBeOfType<BaseDataVariableState>();
private static NodeId Project(OtOpcUaNodeManager nm, Fixture f, string name, bool historizing)
{
var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
var origin = new DataAddress("origin", "ns", "string", "Device/" + name);
var view = new DataView(origin, DataRealm.Raw, "mapping-a", 1, "Plant/Mount/" + name);
var metadata = new DataMetadata(view, name, "Tag", DataValueKind.Double, -1, [], false,
DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead, 1, null, null, false, History: new DataHistoryInfo(historizing));
var identifier = ProjectedDataIds.Identifier("mapping-a", origin);
nm.TryEnsureProjectedVariable(new ProjectedVariableDefinition(DataRealm.Raw, identifier, parent, metadata, 1, () => true)
{ Historizing = historizing }, out var node).ShouldBeTrue();
f.Views[identifier] = view;
return node!.Value;
}
private async Task<(OtOpcUaNodeManager Nm, Fixture F)> BootAsync(bool aclEnabled, NodePermissions permissions)
{
var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
{
ApplicationName = "ProjectedHistory", ApplicationUri = $"urn:ProjectedHistory:{Guid.NewGuid():N}",
OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki,
}, NullLogger<OpcUaApplicationHost>.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken);
_host = started.Host;
var nm = started.Server.NodeManager!;
nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
var f = new Fixture(aclEnabled, permissions);
nm.Authorizer = f.Gate;
nm.MappedSubjectResolver = (realm, id) => f.Resolve(realm, id);
return (nm, f);
}
public async ValueTask DisposeAsync()
{
if (_host is not null) await _host.DisposeAsync();
if (Directory.Exists(_pki))
try { Directory.Delete(_pki, recursive: true); } catch (IOException) { }
}
private sealed class Fixture
{
private readonly DataPlaneAuthorityState _state = new();
private readonly TestLease _lease = new();
internal readonly ApiKey Key = new() { ApiKeyId = "key-a", Name = "key-a", Principal = "reader", SecretHash = "hash", Enabled = true,
ExpiresUtc = Now.AddHours(1).UtcDateTime };
internal readonly DataPlaneAuthorizer Gate;
internal readonly Dictionary<string, DataView> Views = new(StringComparer.Ordinal);
internal DataOperations SubjectOperations { get; set; } =
DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead;
internal Fixture(bool aclEnabled, NodePermissions permissions)
{
Grant(permissions);
var clock = new TestClock();
Gate = new DataPlaneAuthorizer(_state, new TriePermissionEvaluator(_state.Tries, clock), aclEnabled, NullLogger.Instance, clock);
}
internal void Grant(NodePermissions permissions) =>
_state.Apply("c1", "rev-" + (int)permissions, [Key],
[new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader", ScopeKind = NodeAclScopeKind.RawFolder,
ScopeId = "folder", PermissionFlags = permissions }],
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant", "Mount"])] });
internal RoleCarryingUserIdentity Identity => new(new UserNameIdentityToken { UserName = "apikey" }, [], "reader", Key.ApiKeyId,
DataCallerIdentity.CredentialVersionFor(Key), Now.AddMinutes(2));
internal MappedNodeResolution Resolve(AddressSpaceRealm realm, string identifier)
{
if (!Views.TryGetValue(identifier, out var view)) return MappedNodeResolution.Local;
var subject = new MappedNamespaceSubject(view,
new NodeScope { ClusterId = "c1", Kind = NodeHierarchyKind.Raw, Segments = view.Subject.Split('/') },
["local-parent", "mapping-a"], _lease.Serving, SubjectOperations, WriteThrough: false);
var resolver = new MappedSubjectResolver([subject], catalogEpoch: 7, new TestCatalogAuthority(_state));
return MappedNodeResolution.Mapped(view, subject, resolver, _lease);
}
}
private sealed class FakeAccess : IProjectedHistoryAccess
{
public int Calls;
public IReadOnlyList<ProjectedHistoryNode> LastNodes = [];
public readonly List<FakeCursor> Issued = [];
public bool Paged { get; init; }
public uint Status { get; init; }
public Func<ProjectedHistoryNode, double[]> Answer { get; init; } = _ => [1.0, 2.0];
public Task<IReadOnlyList<ProjectedHistoryOutcome>> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details,
IReadOnlyList<ProjectedHistoryNode> nodes, TimeSpan deadline, CancellationToken cancellationToken)
{
Calls++;
LastNodes = nodes;
return Task.FromResult<IReadOnlyList<ProjectedHistoryOutcome>>(nodes.Select(node =>
{
FakeCursor? next = null;
if (Paged)
{
var key = node.NodeId.TryGetValue(out string id) ? id : "";
next = new FakeCursor(key);
Issued.Add(next);
}
var samples = Answer(node).Select((v, i) => new OriginHistorySample(v, 0, T0.AddSeconds(i), null)).ToArray();
return new ProjectedHistoryOutcome(Status, Status == 0 ? samples : [], next);
}).ToArray());
}
}
private sealed class FakeCursor(string identifier) : ProjectedHistoryContinuation(DataRealm.Raw, identifier)
{
public int Released;
protected override void OnRelease() => Interlocked.Increment(ref Released);
}
private sealed class TestCatalogAuthority(DataPlaneAuthorityState state) : IDataMappedCatalogAuthority
{
public long CatalogEpoch => 1;
public long AuthorityEpoch => state.Current.GenerationId;
public bool IsActive => true;
}
private sealed class TestLease : IDataAuthorizationLease
{
public ServingIdentity Serving { get; } = new("node-a", "incarnation-a", "Primary", 7, 1);
public bool IsValid => true;
}
private sealed class TestClock : TimeProvider
{
public override DateTimeOffset GetUtcNow() => Now;
}
}