Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs
T
Joseph Doherty f1b23abcb4 fix(grpc-data): H3 review round 3 nits b/c/d — no origin cursor stranded on Bad, scope moves or a serve-time throw
- b: ProjectedHistoryAccess releases the prior origin cursor on any Bad answer
  to a resumed node (and on a mismatched answer) — an unsent refusal left it
  open at the origin; idempotent.
- c: DataConnectionDeploymentLease, when its scope moves while a history
  answer is in flight, releases the dropped answer's new continuations (best
  effort); resumed items are BadContinuationPointInvalid, fresh ones
  BadNoCommunication.
- d: ProjectedHistoryRead: a throw while serving outcome i (FromClr on an
  unconvertible value, a store fault) releases outcome i's cursor unless the
  store already owns it, and every later outcome's.

Each red on revert (mutation).
2026-11-24 07:15:16 -05:00

522 lines
29 KiB
C#

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]
[Trait("Phase", "H3")]
public async Task A_throw_while_serving_one_outcome_releases_every_later_outcomes_cursor()
{
// H3 review round 3 nit (d): outcome 0's value cannot cross the SDK boundary (FromClr throws) — outcome 1's origin cursor
// must not be stranded; outcome 0's is already the session store's (saved before the throw), so it is not released twice.
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
var a = Project(nm, f, "Speed", historizing: true);
var b = Project(nm, f, "Flow", historizing: true);
var access = new FakeAccess { Paged = true, FirstValue = new object() };
nm.ProjectedHistoryAccess = access;
try { Raw(nm, f.Identity, [a, b]); }
catch (ArgumentException) { } // the fault itself is the node manager's to surface; only the cursors matter here
access.Issued.Count.ShouldBe(2);
access.Issued[1].Released.ShouldBe(1, "the later outcome's cursor is released");
access.Issued[0].Released.ShouldBe(0, "the store owns the saved cursor");
}
[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();
}
[Fact]
public async Task A_claimed_cursor_is_released_on_every_exit_that_never_sends_it()
{
// H3 review D2: Release() after a claim is a no-op, so each post-claim exit must use ReleaseEvenIfClaimed — exactly once.
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
var store = new InMemoryHistoryContinuationStore();
nm.HistoryContinuationStore = store;
var node = Project(nm, f, "Leak", historizing: true);
var paging = new FakeAccess { Paged = true };
nm.ProjectedHistoryAccess = paging;
(FakeCursor Cursor, ByteString Cp) HeldPoint()
{
var (results, _) = Raw(nm, f.Identity, [node]);
results[0].ContinuationPoint.IsEmpty.ShouldBeFalse();
return (paging.Issued[^1], results[0].ContinuationPoint);
}
// (a) the gateway disappears between the issue and the resume.
var (cursor, cp) = HeldPoint();
nm.ProjectedHistoryAccess = null;
Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
cursor.Released.ShouldBe(1);
nm.ProjectedHistoryAccess = paging;
// (b) the gateway throws (anything): BadNoCommunication, the resume released, nothing escapes.
(cursor, cp) = HeldPoint();
nm.ProjectedHistoryAccess = new FakeAccess { Throw = new InvalidCastException("boom") };
Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadNoCommunication.Code);
cursor.Released.ShouldBe(1);
nm.ProjectedHistoryAccess = paging;
// (c) the request deadline was spent by the time the projected half starts.
(cursor, cp) = HeldPoint();
nm.HistoryReadDeadline = TimeSpan.FromTicks(1);
Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code);
cursor.Released.ShouldBe(1);
nm.HistoryReadDeadline = TimeSpan.FromSeconds(60);
// (d) the projected sub-limit is exhausted (limiter rejection).
(cursor, cp) = HeldPoint();
var limiter = nm.GetNonLocalHistoryLimiter();
var taken = 0;
while (limiter.Wait(0, TestContext.Current.CancellationToken)) taken++;
try
{
Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code);
cursor.Released.ShouldBe(1);
}
finally { limiter.Release(taken); }
// Positive control: a normal resume claims the cursor and does NOT release it (the read owns the token).
(cursor, cp) = HeldPoint();
Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
cursor.Released.ShouldBe(0);
paging.Issued.Where(c => !ReferenceEquals(c, paging.Issued[^1])).ShouldAllBe(c => c.Released <= 1, "never released twice");
}
[Fact]
public async Task Projected_reads_and_remote_peers_together_cannot_take_every_history_slot_local_history_is_still_served()
{
// H3 review D3: projected reads hold at most N - max(1, N/4) of the N shared batch slots.
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
nm.MaxConcurrentHistoryReadBatches = 4; // => 3 projected slots, 1 always left for local history
nm.EnsureVariable("Plant/LocalSlot", "Plant", "LocalSlot", "Double", false, AddressSpaceRealm.Raw, historianTagname: "L.slot");
var local = nm.TryGetVariable("Plant/LocalSlot", AddressSpaceRealm.Raw)!.NodeId;
var node = Project(nm, f, "Slow", historizing: true);
var hold = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var slow = new FakeAccess { Hold = hold };
nm.ProjectedHistoryAccess = slow;
var held = Enumerable.Range(0, 3).Select(_ => Task.Run(() => Raw(nm, f.Identity, [node]))).ToArray();
var deadline = DateTime.UtcNow.AddSeconds(10);
while (Volatile.Read(ref slow.Entries) < 3 && DateTime.UtcNow < deadline) await Task.Delay(10, TestContext.Current.CancellationToken);
slow.Entries.ShouldBe(3, "three projected reads hold the three projected slots");
try
{
// A fourth projected read is refused at once, unsent; local history is still served.
// (Bounded: without the sub-limit this read would take the 4th shared slot and wait on the held gateway.)
var (_, refused) = await Task.Run(() => Raw(nm, f.Identity, [node]))
.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
refused[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code);
slow.Entries.ShouldBe(3);
// H3 review round 2: remote peers reading THIS node share the same non-local slots — refused too, unsent — so the
// origin port and the projected path together can never take the last (local) slot.
var port = new OriginHistoryPort(nm);
port.AvailableRemoteSlots.ShouldBe(0);
var peer = await port.ReadAsync(new OriginHistoryCursors("peer", "channel", 4), "peer", () => "serving",
new DataHistoryRawDetails(new DateTimeOffset(T0), new DateTimeOffset(T0.AddHours(1)), 5, false),
[new OriginHistoryItem(AddressSpaceRealm.Raw, "Plant/LocalSlot", "tag", null, null)], TestContext.Current.CancellationToken);
peer.Single().StatusCode.ShouldBe(StatusCodes.BadTooManyOperations.Code);
var (localResults, localErrors) = Raw(nm, f.Identity, [local]);
StatusCode.IsGood(localErrors[0].StatusCode).ShouldBeTrue(localErrors[0].StatusCode.ToString());
localResults[0].StatusCode.Code.ShouldBe(StatusCodes.GoodNoData.Code);
}
finally { hold.SetResult(); }
foreach (var (_, errors) in await Task.WhenAll(held)) StatusCode.IsGood(errors[0].StatusCode).ShouldBeTrue();
}
[Fact]
public async Task A_remote_cursor_presented_to_a_local_node_is_invalid_and_released()
{
// H3 review D5: the local take removes the SDK slot, so it must release the origin continuation.
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
var store = new InMemoryHistoryContinuationStore();
nm.HistoryContinuationStore = store;
nm.EnsureVariable("Plant/LocalCp", "Plant", "LocalCp", "Double", false, AddressSpaceRealm.Raw, historianTagname: "L.cp");
var local = nm.TryGetVariable("Plant/LocalCp", AddressSpaceRealm.Raw)!.NodeId;
var node = Project(nm, f, "Remote", historizing: true);
var access = new FakeAccess { Paged = true };
nm.ProjectedHistoryAccess = access;
var (results, _) = Raw(nm, f.Identity, [node]);
var (_, errors) = Raw(nm, f.Identity, [local], results[0].ContinuationPoint);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
access.Issued.Single().Released.ShouldBe(1);
store.Count.ShouldBe(0);
}
// ------------------------------------------------------------------------------------------------------------------
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];
/// <summary>When set, the FIRST node's first sample carries this value (e.g. one the SDK boundary cannot convert).</summary>
public object? FirstValue { get; init; }
/// <summary>When set, every call waits on it (a projected read holding its slot).</summary>
public TaskCompletionSource? Hold { get; set; }
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
/// <summary>When set, every call throws it (after claiming nothing — the cursors are the caller's to release).</summary>
public Exception? Throw { get; set; }
public int Entries;
public async Task<IReadOnlyList<ProjectedHistoryOutcome>> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details,
IReadOnlyList<ProjectedHistoryNode> nodes, TimeSpan deadline, CancellationToken cancellationToken)
{
Interlocked.Increment(ref Calls);
LastNodes = nodes;
if (Interlocked.Increment(ref Entries) > 0) Entered.TrySetResult();
if (Hold is { } hold) await hold.Task.ConfigureAwait(false);
if (Throw is { } error) throw error;
return (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();
if (FirstValue is { } poison && ReferenceEquals(node, nodes[0]) && samples.Length > 0) samples[0] = samples[0] with { Value = poison };
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;
}
}