Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/HistoryReadPortParityTests.cs
T

852 lines
43 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.Core.Abstractions;
using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult;
using SdkHistoryReadResult = Opc.Ua.HistoryReadResult;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
/// <summary>Boots one SDK server with the historized nodes the port parity cases read.</summary>
public sealed class HistoryReadPortServerFixture : IAsyncLifetime
{
private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), $"otopcua-histport-{Guid.NewGuid():N}");
private OpcUaApplicationHost? _host;
/// <summary>The node manager under test.</summary>
public OtOpcUaNodeManager Nm { get; private set; } = null!;
/// <summary>Every node-manager log entry's structured properties.</summary>
public CapturingLogger Log { get; } = new();
/// <summary>Serialises the cases (they share the node manager's source and continuation store).</summary>
public SemaphoreSlim Gate { get; } = new(1, 1);
/// <summary>The historized nodes: (realm, identifier) → NodeId.</summary>
public Dictionary<string, (AddressSpaceRealm Realm, string Id, NodeId NodeId)> Nodes { get; } = new();
public async ValueTask InitializeAsync()
{
var started = await OpcUaHostStart.StartAsync(
port => new OpcUaApplicationHost(
new OpcUaApplicationHostOptions
{
ApplicationName = "OtOpcUa.HistoryPortTest",
ApplicationUri = $"urn:OtOpcUa.HistoryPortTest:{Guid.NewGuid():N}",
OpcUaPort = port,
PublicHostname = "localhost",
PkiStoreRoot = _pkiRoot,
},
NullLogger<OpcUaApplicationHost>.Instance),
() => new OtOpcUaSdkServer(Log), CancellationToken.None);
_host = started.Host;
Nm = started.Server.NodeManager!;
Nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
Add("dbl", "port/dbl", "Double", AddressSpaceRealm.Uns);
Add("str", "port/str", "String", AddressSpaceRealm.Uns);
Add("bool", "port/bool", "Boolean", AddressSpaceRealm.Uns);
Add("int", "port/int", "Int32", AddressSpaceRealm.Uns);
Add("raw", "Plant/dev/raw1", "Double", AddressSpaceRealm.Raw);
Add("plain", "port/plain", "Double", AddressSpaceRealm.Uns, historized: false);
}
/// <summary>Adds one more historized node (the epoch-bump case removes one).</summary>
public NodeId Add(string key, string id, string dataType, AddressSpaceRealm realm, bool historized = true)
{
Nm.EnsureVariable(id, parentFolderNodeId: null, displayName: key, dataType: dataType, writable: false,
realm: realm, historianTagname: historized ? "P." + key : null);
var nodeId = Nm.TryGetVariable(id, realm)!.NodeId;
Nodes[key] = (realm, id, nodeId);
return nodeId;
}
public async ValueTask DisposeAsync()
{
if (_host is not null) await _host.DisposeAsync();
if (Directory.Exists(_pkiRoot))
{
try { Directory.Delete(_pkiRoot, recursive: true); }
catch { /* best-effort */ }
}
}
}
/// <summary>Records each log entry's level and structured properties.</summary>
public sealed class CapturingLogger : Microsoft.Extensions.Logging.ILogger<OtOpcUaNodeManager>
{
private readonly System.Collections.Concurrent.ConcurrentQueue<(Microsoft.Extensions.Logging.LogLevel Level, IReadOnlyList<KeyValuePair<string, object?>> Properties)> _entries = new();
public IReadOnlyList<(Microsoft.Extensions.Logging.LogLevel Level, IReadOnlyList<KeyValuePair<string, object?>> Properties)> Entries => _entries.ToArray();
public void Clear() => _entries.Clear();
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true;
public void Log<TState>(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId, TState state,
Exception? exception, Func<TState, Exception?, string> formatter) =>
_entries.Enqueue((logLevel, state as IReadOnlyList<KeyValuePair<string, object?>> ?? []));
}
/// <summary>
/// H1 (gRPC data history plan §3.1): the override-level history port is the ONE pipeline the SDK overrides and a remote
/// peer's HistoryRead (H2) are served through. Every case runs the same request two ways against the same fake backend —
/// the SDK override path (<c>HistoryRead</c> on the node manager, the path every local OPC UA client takes) and the port
/// directly with <c>(realm, identifier)</c> items — and requires identical per-node outcomes.
/// <para>
/// What this class proves is port ≡ adapter. Since H1 the override IS an adapter over the port, so that equality
/// alone cannot detect a behaviour change the port introduced. The tie to PRE-H1 behaviour is (a) the pinned literal
/// outcomes in these cases, which were recorded and run green against the pre-port node manager (the port calls then
/// stubbed onto the override), and (b) the legacy history suites (<c>NodeManagerHistoryRead*Tests</c>,
/// <c>HistoryUpdateTests</c>, the raw-cap fuzz …), unchanged and re-run by the H1 gate.
/// </para>
/// </summary>
[Trait("Feature", "GrpcData")]
[Trait("Phase", "H1")]
public sealed class HistoryReadPortParityTests(HistoryReadPortServerFixture fx) : IClassFixture<HistoryReadPortServerFixture>
{
private static readonly DateTime T0 = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
private static DateTime T(int seconds) => T0.AddSeconds(seconds);
private static DataValueSnapshot S(object? value, int seconds, uint status = 0) =>
new(value, status, T(seconds), T(seconds));
// ---------------------------------------------------------------------------------------------------------
// Processed refusals
// ---------------------------------------------------------------------------------------------------------
[Fact]
public async Task Aggregate_refused_for_the_nodes_data_type_897_and_by_SupportsAggregateFor_and_unknown_aggregates()
{
await RunAsync(async () =>
{
var source = new ParitySource { ProcessedResult = [S(1.5, 0, StatusCodes.Good.Code)] };
fx.Nm.HistorianDataSource = source;
var details = Processed(ObjectIds.AggregateFunction_Average);
var nodes = new[] { "dbl", "str", "bool", "dbl", "bool" };
var aggregates = new[]
{
ObjectIds.AggregateFunction_Average,
ObjectIds.AggregateFunction_Average, // #897: numeric aggregate on a String node
ObjectIds.AggregateFunction_TimeAverage, // the backend's own SupportsAggregateFor refusal
new NodeId(987654u), // an aggregate the server cannot name
ObjectIds.AggregateFunction_Average, // Boolean is served
};
details.AggregateType = aggregates;
var viaOverride = Override(details, nodes);
var callsAfterOverride = source.ProcessedCalls;
var viaPort = Port(details, nodes);
viaOverride.Select(o => o.Error).ShouldBe(new[]
{
StatusCodes.Good.Code, StatusCodes.BadAggregateNotSupported.Code, StatusCodes.BadAggregateNotSupported.Code,
StatusCodes.BadAggregateNotSupported.Code, StatusCodes.Good.Code,
});
viaOverride[0].Values.ShouldBe("T0+0=1.5:Double/00000000");
viaOverride[0].ResultStatus.ShouldBe(StatusCodes.Good.Code);
viaOverride[1].ResultStatus.ShouldBe(StatusCodes.Good.Code, "a refusal sets only the operation status (the SDK seeds the result slot)");
viaOverride[1].Values.ShouldBe("");
callsAfterOverride.ShouldBe(2, "refused nodes are never sent to the backend");
source.RefusedAggregateAsked.ShouldBeTrue();
viaPort.ShouldBe(viaOverride);
source.ProcessedCalls.ShouldBe(4);
});
}
[Fact]
public async Task Non_default_aggregate_configuration_is_rejected_per_node_and_the_defaults_are_served()
{
await RunAsync(async () =>
{
var source = new ParitySource { ProcessedResult = [S(2.0, 0)] };
fx.Nm.HistorianDataSource = source;
var rejected = Processed(ObjectIds.AggregateFunction_Average);
rejected.AggregateConfiguration = new AggregateConfiguration
{
UseServerCapabilitiesDefaults = false, TreatUncertainAsBad = true, PercentDataBad = 100, PercentDataGood = 100,
};
var spelled = Processed(ObjectIds.AggregateFunction_Average);
spelled.AggregateConfiguration = new AggregateConfiguration
{
UseServerCapabilitiesDefaults = false, TreatUncertainAsBad = false, PercentDataBad = 100, PercentDataGood = 100,
UseSlopedExtrapolation = false,
};
var r1 = Override(rejected, "dbl");
r1.Single().Error.ShouldBe(StatusCodes.BadAggregateConfigurationRejected.Code);
Port(rejected, "dbl").ShouldBe(r1);
var r2 = Override(spelled, "dbl");
r2.Single().Error.ShouldBe(StatusCodes.Good.Code);
Port(spelled, "dbl").ShouldBe(r2);
source.ProcessedCalls.ShouldBe(2);
await Task.CompletedTask;
});
}
// ---------------------------------------------------------------------------------------------------------
// Raw
// ---------------------------------------------------------------------------------------------------------
[Fact]
public async Task Modified_read_with_bounds_is_BadInvalidArgument_on_both_slots()
{
await RunAsync(async () =>
{
fx.Nm.HistorianDataSource = new ParitySource();
var details = Raw(T(0), T(10), 10, bounds: true);
details.IsReadModified = true;
var viaOverride = Override(details, "dbl", "str");
viaOverride.ShouldAllBe(o => o.Error == StatusCodes.BadInvalidArgument.Code && o.ResultStatus == StatusCodes.BadInvalidArgument.Code);
Port(details, "dbl", "str").ShouldBe(viaOverride);
await Task.CompletedTask;
});
}
[Fact]
public async Task Modified_read_without_bounds_on_a_trail_less_backend_is_unsupported_on_both_paths()
{
await RunAsync(async () =>
{
fx.Nm.HistorianDataSource = new ParitySource();
var details = Raw(T(0), T(10), 10, bounds: false);
details.IsReadModified = true;
var viaOverride = Override(details, "dbl");
viaOverride.Single().Error.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
Port(details, "dbl").ShouldBe(viaOverride);
await Task.CompletedTask;
});
}
[Fact]
public async Task Stored_and_AtTime_values_are_normalised_to_the_nodes_data_type()
{
await RunAsync(async () =>
{
var source = new ParitySource();
source.Series["P.int"] = [S(7.0, 0), S("x", 1), S(41.0, 2)];
source.AtTimeResult = [S(7.0, 0), S("not a number", 1)];
fx.Nm.HistorianDataSource = source;
var raw = Override(Raw(T(0), T(10), 0, bounds: false), "int");
raw.Single().Values.ShouldBe("T0+0=7:Int32/00000000 | T0+1=null/80740000 | T0+2=41:Int32/00000000");
Port(Raw(T(0), T(10), 0, bounds: false), "int").ShouldBe(raw);
var atTime = new ReadAtTimeDetails { ReqTimes = new[] { (DateTimeUtc)T(0), (DateTimeUtc)T(1) } };
var viaOverride = Override(atTime, "int");
viaOverride.Single().Values.ShouldBe("T0+0=7:Int32/00000000 | T0+1=null/80740000");
source.LastAtTimeType.ShouldBe(TypeCode.Int32, "the node's scalar type rides to the backend");
Port(atTime, "int").ShouldBe(viaOverride);
await Task.CompletedTask;
});
}
[Fact]
public async Task End_only_and_reverse_raw_page_newest_first()
{
await RunAsync(async () =>
{
foreach (var native in new[] { true, false })
{
var source = new ParitySource { NativeReverse = native };
source.Series["P.dbl"] = Enumerable.Range(0, 7).Select(i => S((double)i, i)).ToList();
fx.Nm.HistorianDataSource = source;
var endOnly = Raw(DateTime.MinValue, T(5), 2, bounds: false);
var o = DrainOverride(endOnly, "dbl");
o.ShouldBe("T0+5=5:Double/00000000 | T0+4=4:Double/00000000 | T0+3=3:Double/00000000 | T0+2=2:Double/00000000 | T0+1=1:Double/00000000 | T0+0=0:Double/00000000");
DrainPort(endOnly, "dbl").ShouldBe(o);
var reverse = Raw(T(6), T(1), 3, bounds: false);
var r = DrainOverride(reverse, "dbl");
r.ShouldBe("T0+6=6:Double/00000000 | T0+5=5:Double/00000000 | T0+4=4:Double/00000000 | T0+3=3:Double/00000000 | T0+2=2:Double/00000000");
DrainPort(reverse, "dbl").ShouldBe(r);
source.ReverseOnForwardOnly.ShouldBe(0);
}
await Task.CompletedTask;
});
}
[Fact]
public async Task Bounds_placeholders_lead_and_end_a_bounded_read()
{
await RunAsync(async () =>
{
var source = new ParitySource();
source.Series["P.dbl"] = [S(1.0, 2), S(2.0, 3)];
fx.Nm.HistorianDataSource = source;
// Nothing at or before StartTime and nothing at or after EndTime: both bounds are placeholders.
var details = Raw(T(0), T(5), 0, bounds: true);
var viaOverride = Override(details, "dbl");
viaOverride.Single().Values.ShouldBe(
"T0+0=null/80D70000 | T0+2=1:Double/00000000 | T0+3=2:Double/00000000 | T0+5=null/80D70000");
Port(details, "dbl").ShouldBe(viaOverride);
// Paged at N = 1: the start bound alone, then the data, then the end bound.
var paged = Raw(T(0), T(5), 1, bounds: true);
var drained = DrainOverride(paged, "dbl");
drained.ShouldBe(viaOverride.Single().Values);
DrainPort(paged, "dbl").ShouldBe(drained);
// No data and no bound at all (a tag with no history) ⇒ GoodNoData with no values (the pre-bounds answer).
var empty = Raw(T(100), T(200), 0, bounds: true);
var none = Override(empty, "str");
none.Single().ResultStatus.ShouldBe(StatusCodes.GoodNoData.Code);
none.Single().Values.ShouldBe("");
Port(empty, "str").ShouldBe(none);
await Task.CompletedTask;
});
}
[Fact]
public async Task Uncapped_raw_pages_at_the_backend_ceiling_with_a_continuation_point()
{
await RunAsync(async () =>
{
var source = new ParitySource { Ceiling = 4 };
source.Series["P.raw"] = Enumerable.Range(0, 11).Select(i => S((double)i, i)).ToList();
fx.Nm.HistorianDataSource = source;
var details = Raw(T(0), T(100), 0, bounds: false);
var first = Override(details, "raw").Single();
first.HasContinuation.ShouldBeTrue("an uncapped read above the ceiling returns a page and a continuation point");
Port(details, "raw").ShouldBe([first]);
var all = string.Join(" | ", Enumerable.Range(0, 11).Select(i => $"T0+{i}={i}:Double/00000000"));
DrainOverride(details, "raw").ShouldBe(all);
DrainPort(details, "raw").ShouldBe(all);
await Task.CompletedTask;
});
}
[Fact]
public async Task An_epoch_bump_invalidates_a_continuation_point_on_both_paths()
{
await RunAsync(async () =>
{
var source = new ParitySource();
source.Series["P.dbl"] = Enumerable.Range(0, 5).Select(i => S((double)i, i)).ToList();
fx.Nm.HistorianDataSource = source;
var details = Raw(T(0), T(100), 2, bounds: false);
var (_, overrideCp) = ReadOverrideRaw(details, "dbl", cp: null);
var portCp = ReadPortRaw(details, "dbl", cp: null).Cp;
overrideCp.ShouldNotBeNull();
portCp.ShouldNotBeNull();
// Removing ANY node bumps the history epoch: every outstanding cursor is conservatively invalid.
fx.Add("victim", "port/victim-" + Guid.NewGuid().ToString("N"), "Double", AddressSpaceRealm.Uns);
fx.Nm.RemoveVariableNode(fx.Nodes["victim"].Id, AddressSpaceRealm.Uns).ShouldBeTrue();
var afterOverride = ReadOverrideRaw(details, "dbl", overrideCp).Outcome;
afterOverride.Error.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
afterOverride.ResultStatus.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
ReadPortRaw(details, "dbl", portCp).Outcome.ShouldBe(afterOverride);
await Task.CompletedTask;
});
}
[Fact]
public async Task A_continuation_point_is_bound_to_its_node_and_realm()
{
await RunAsync(async () =>
{
var source = new ParitySource();
source.Series["P.dbl"] = Enumerable.Range(0, 5).Select(i => S((double)i, i)).ToList();
source.Series["P.raw"] = Enumerable.Range(0, 5).Select(i => S((double)i, i)).ToList();
fx.Nm.HistorianDataSource = source;
var details = Raw(T(0), T(100), 2, bounds: false);
var overrideCp = ReadOverrideRaw(details, "dbl", cp: null).Cp;
var crossed = ReadOverrideRaw(details, "raw", overrideCp).Outcome;
crossed.Error.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
var portCp = ReadPortRaw(details, "dbl", cp: null).Cp;
ReadPortRaw(details, "raw", portCp).Outcome.ShouldBe(crossed);
await Task.CompletedTask;
});
}
[Fact]
public async Task A_peer_scope_pages_like_the_session_scope_and_binds_details_principal_incarnation_and_epoch()
{
await RunAsync(async () =>
{
var source = new ParitySource();
source.Series["P.raw"] = Enumerable.Range(0, 9).Select(i => S((double)i, i)).ToList();
fx.Nm.HistorianDataSource = source;
var (realm, id, _) = fx.Nodes["raw"];
var details = new HistoryReadRawVariant(T(0), T(100), 2, ReturnBounds: false);
var store = new PeerHistoryContinuationStore("svc-consumer", "conn-1", capacity: 4);
var incarnation = "inc-1";
// One scope per request (it snapshots the serving incarnation at first use), as H2 creates per RPC.
IHistoryContinuationScope Peer() => new PeerHistoryContinuationScope(store, "svc-consumer", () => incarnation);
HistoryReadNodeOutcome Read(IHistoryContinuationScope scope, HistoryReadVariant d, byte[]? cp) =>
fx.Nm.ReadHistory(d, [new HistoryReadPortItem(realm, id, cp)], scope, CancellationToken.None)[0];
string DrainWith(Func<IHistoryContinuationScope> scope)
{
var parts = new List<string>();
byte[]? cp = null;
do
{
var o = Read(scope(), details, cp);
o.Status.Code.ShouldBe(StatusCodes.Good.Code);
parts.AddRange(o.Values.Select(Render));
cp = o.ContinuationPoint;
}
while (cp is not null);
return string.Join(" | ", parts);
}
DrainWith(Peer).ShouldBe(DrainWith(() => fx.Nm.SessionHistoryContinuationScope(session: null)));
store.Count.ShouldBe(0, "every page's token was taken");
// A resume under other details, by another incarnation, or after an epoch bump is refused.
var cp1 = Read(Peer(), details, null).ContinuationPoint!;
Read(Peer(), details with { NumValuesPerNode = 3 }, cp1).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
// A serving-incarnation change on the SAME live connection (in-process failover) is a key mismatch in one store.
var cp2 = Read(Peer(), details, null).ContinuationPoint!;
incarnation = "inc-2";
Read(Peer(), details, cp2).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
// Another principal's scope over the store cannot resume the owner's cursor.
var cpOther = Read(Peer(), details, null).ContinuationPoint!;
var intruder = new PeerHistoryContinuationScope(store, "someone-else", () => incarnation);
Read(intruder, details, cpOther).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
var cp3 = Read(Peer(), details, null).ContinuationPoint!;
fx.Add("victim2", "port/victim-" + Guid.NewGuid().ToString("N"), "Double", AddressSpaceRealm.Uns);
fx.Nm.RemoveVariableNode(fx.Nodes["victim2"].Id, AddressSpaceRealm.Uns).ShouldBeTrue();
Read(Peer(), details, cp3).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
// The take was single-use: the same token again is still a miss, and nothing is left behind.
Read(Peer(), details, cp1).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
store.Count.ShouldBe(0, "every presented token was consumed, matched or not");
// A wiring fault (a scope for a principal the store does not belong to) is its own status, never "unsupported".
var miswired = Read(new PeerHistoryContinuationScope(store, "someone-else", () => incarnation), details, null);
miswired.Status.Code.ShouldBe(StatusCodes.BadInternalError.Code);
miswired.Error!.StatusCode.Code.ShouldBe(StatusCodes.BadInternalError.Code);
await Task.CompletedTask;
});
}
[Fact]
public async Task A_cursor_is_bound_to_its_namespace_not_only_realm_and_identifier()
{
await RunAsync(async () =>
{
var source = new ParitySource();
source.Series["P.raw"] = Enumerable.Range(0, 6).Select(i => S((double)i, i)).ToList();
fx.Nm.HistorianDataSource = source;
var (realm, id, nodeId) = fx.Nodes["raw"];
var details = new HistoryReadRawVariant(T(0), T(100), 2, ReturnBounds: false);
var local = fx.Nm.HistoryBindingTag(nodeId);
// mapped/raw folds into the Raw realm: the same (Raw, identifier) in the projected namespace is ANOTHER node.
var mapped = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ProjectedDataIds.RawNamespaceUri;
local.ShouldNotBe(mapped);
var scope = fx.Nm.SessionHistoryContinuationScope(session: null);
HistoryReadNodeOutcome Read(string tag, byte[]? cp) =>
fx.Nm.ReadHistory(details, [new HistoryReadPortItem(realm, id, cp, BindingTag: tag)], scope, CancellationToken.None)[0];
Read(mapped, Read(local, null).ContinuationPoint).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
Read(local, Read(mapped, null).ContinuationPoint).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
Read(local, Read(local, null).ContinuationPoint).Status.Code.ShouldBe(StatusCodes.Good.Code);
// The SDK adapter tags with the same value: an override-issued cursor resumes through the port with the local
// tag and is refused with the mapped one.
var sdk = Raw(T(0), T(100), 2, bounds: false);
Read(local, ReadOverrideRaw(sdk, "raw", null).Cp).Status.Code.ShouldBe(StatusCodes.Good.Code);
Read(mapped, ReadOverrideRaw(sdk, "raw", null).Cp).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
await Task.CompletedTask;
});
}
[Fact]
public async Task A_backend_failure_logs_the_original_NodeId_on_the_local_path()
{
await RunAsync(async () =>
{
fx.Nm.HistorianDataSource = new ParitySource { Throw = true };
var nodeId = fx.Nodes["dbl"].NodeId;
static object? NodeIdProperty(CapturingLogger log) => log.Entries
.Where(e => e.Level == Microsoft.Extensions.Logging.LogLevel.Error)
.SelectMany(e => e.Properties).Single(p => p.Key == "NodeId").Value;
foreach (var details in new HistoryReadDetails[]
{
Raw(T(0), T(10), 5, bounds: false),
new ReadAtTimeDetails { ReqTimes = new[] { (DateTimeUtc)T(0) } },
})
{
fx.Log.Clear();
Override(details, "dbl").Single().Error.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
NodeIdProperty(fx.Log).ShouldBe(nodeId, "the {NodeId} property keeps meaning a NodeId");
// A peer item carries no SDK NodeId: it logs as Realm:Identifier.
fx.Log.Clear();
fx.Nm.ReadHistory(HistoryReadVariant.From(details), [new HistoryReadPortItem(AddressSpaceRealm.Uns, "port/dbl")],
fx.Nm.SessionHistoryContinuationScope(session: null), CancellationToken.None);
NodeIdProperty(fx.Log).ShouldBe("Uns:port/dbl");
}
await Task.CompletedTask;
});
}
[Fact]
public async Task A_mixed_batch_maps_every_outcome_back_to_its_own_handle_index()
{
await RunAsync(async () =>
{
var source = new ParitySource { ProcessedResult = [S(1.0, 0)] };
source.Series["P.dbl"] = Enumerable.Range(0, 5).Select(i => S((double)i, i)).ToList();
source.Series["P.raw"] = Enumerable.Range(0, 5).Select(i => S(10.0 + i, i)).ToList();
fx.Nm.HistorianDataSource = source;
// "plain" has no HistoryRead access bit: the SDK drops it before the override, so every later handle's Index
// differs from its position in the port's item list.
var processed = Processed(ObjectIds.AggregateFunction_Average);
processed.AggregateType = new[]
{
ObjectIds.AggregateFunction_Minimum, ObjectIds.AggregateFunction_Maximum,
ObjectIds.AggregateFunction_Average, ObjectIds.AggregateFunction_Count,
};
var nodes = new[] { "plain", "dbl", "str", "raw" };
var viaOverride = Override(processed, nodes);
viaOverride.Select(o => o.Error).ShouldBe(new[]
{
StatusCodes.BadHistoryOperationUnsupported.Code, StatusCodes.Good.Code,
StatusCodes.BadAggregateNotSupported.Code, StatusCodes.Good.Code,
});
source.ProcessedAsked.OrderBy(kv => kv.Key).Select(kv => $"{kv.Key}:{kv.Value}")
.ShouldBe(new[] { "P.dbl:Maximum", "P.raw:Count" }, "each node reached the backend with ITS aggregate");
Port(processed, nodes).ShouldBe(viaOverride);
// Raw: per-node continuation points route to their own node.
var raw = Raw(T(0), T(100), 2, bounds: false);
var first = InvokeOverride(raw, [("plain", null), ("dbl", null), ("raw", null)]);
var cpDbl = first.Results[1]!.ContinuationPoint.ToNullableArray();
var cpRaw = first.Results[2]!.ContinuationPoint.ToNullableArray();
cpDbl.ShouldNotBeNull();
cpRaw.ShouldNotBeNull();
var second = InvokeOverride(raw, [("plain", null), ("raw", cpRaw), ("dbl", cpDbl)]);
ToOutcome(second.Errors[1], second.Results[1]).Values.ShouldStartWith("T0+2=12:Double");
ToOutcome(second.Errors[2], second.Results[2]).Values.ShouldStartWith("T0+2=2:Double");
var portFirst = PortRead(raw, [("plain", null), ("dbl", null), ("raw", null)]);
portFirst.Select(o => o.Outcome).ShouldBe(Enumerable.Range(0, 3).Select(i => ToOutcome(first.Errors[i], first.Results[i])));
var portSecond = PortRead(raw, [("plain", null), ("raw", portFirst[2].Cp), ("dbl", portFirst[1].Cp)]);
portSecond[1].Outcome.ShouldBe(ToOutcome(second.Errors[1], second.Results[1]));
portSecond[2].Outcome.ShouldBe(ToOutcome(second.Errors[2], second.Results[2]));
await Task.CompletedTask;
});
}
[Fact]
public async Task Modified_reads_page_and_resume_through_the_port_as_through_the_override()
{
await RunAsync(async () =>
{
var source = new ParitySource();
source.Trail["P.dbl"] = Enumerable.Range(0, 7)
.Select(i => new HistoryModifiedValue(S((double)i, i / 2), T(1000 + i), HistoryModificationType.Replace, "alice", i + 1, T(i / 2)))
.ToList();
fx.Nm.HistorianDataSource = source;
var details = Raw(T(0), T(100), 3, bounds: false);
details.IsReadModified = true;
var expected = "T0+0=0:Double/00000000 | T0+0=1:Double/00000000 | T0+1=2:Double/00000000 | T0+1=3:Double/00000000 | " +
"T0+2=4:Double/00000000 | T0+2=5:Double/00000000 | T0+3=6:Double/00000000";
DrainOverride(details, "dbl").ShouldBe(expected);
DrainPort(details, "dbl").ShouldBe(expected);
// A modified cursor is bound to the modified kind: a plain raw resume is refused (and the reverse) — on the
// override path and on the port alike.
var plain = Raw(T(0), T(100), 3, bounds: false);
source.Series["P.dbl"] = Enumerable.Range(0, 7).Select(i => S((double)i, i)).ToList();
foreach (var (name, read) in new (string, Func<HistoryReadDetails, byte[]?, (Outcome Outcome, byte[]? Cp)>)[]
{
("override", (d, cp) => ReadOverrideRaw(d, "dbl", cp)),
("port", (d, cp) => ReadPortRaw(d, "dbl", cp)),
})
{
var modifiedCp = read(details, null).Cp!;
var crossed = read(plain, modifiedCp).Outcome;
crossed.Error.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code, name);
crossed.ResultStatus.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code, name);
var rawCp = read(plain, null).Cp!;
read(details, rawCp).Outcome.Error.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code, name);
}
await Task.CompletedTask;
});
}
[Fact]
public async Task The_outcome_status_carries_GoodNoData_and_Bad_operation_statuses_verbatim()
{
await RunAsync(async () =>
{
fx.Nm.HistorianDataSource = new ParitySource();
HistoryReadNodeOutcome Read(HistoryReadVariant d, string key) =>
fx.Nm.ReadHistory(d, [new HistoryReadPortItem(fx.Nodes[key].Realm, fx.Nodes[key].Id)],
fx.Nm.SessionHistoryContinuationScope(session: null), CancellationToken.None)[0];
// §3.3: an empty window is GoodNoData (the result slot), not the Good operation status.
Read(new HistoryReadRawVariant(T(0), T(10), 5, ReturnBounds: false), "dbl").Status.Code.ShouldBe(StatusCodes.GoodNoData.Code);
Read(new HistoryReadAtTimeVariant([]), "dbl").Status.Code.ShouldBe(StatusCodes.GoodNoData.Code);
// A Bad operation status wins, with or without a result slot.
Read(new HistoryReadRawVariant(T(0), T(10), 5, ReturnBounds: true, IsReadModified: true), "dbl")
.Status.Code.ShouldBe(StatusCodes.BadInvalidArgument.Code);
Read(new HistoryReadRawVariant(T(0), T(10), 5, ReturnBounds: false), "plain")
.Status.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
await Task.CompletedTask;
});
}
[Fact]
public async Task A_node_with_no_historian_tagname_is_unsupported_on_both_paths()
{
await RunAsync(async () =>
{
fx.Nm.HistorianDataSource = new ParitySource();
// The SDK filters nodes without the HistoryRead access bit before the override; the port sees every item.
var viaPort = Port(Raw(T(0), T(10), 0, bounds: false), "plain");
viaPort.Single().Error.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
var atTime = Port(new ReadAtTimeDetails { ReqTimes = new[] { (DateTimeUtc)T(0) } }, "plain");
atTime.Single().Error.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
await Task.CompletedTask;
});
}
// ---------------------------------------------------------------------------------------------------------
// Harness
// ---------------------------------------------------------------------------------------------------------
/// <summary>One node's observable outcome: the operation (errors) slot, the result slot, values and the CP presence.</summary>
public sealed record Outcome(uint Error, uint? ResultStatus, string Values, bool HasContinuation);
private async Task RunAsync(Func<Task> body)
{
await fx.Gate.WaitAsync(TestContext.Current.CancellationToken);
try
{
fx.Nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
fx.Nm.MaxTieClusterOverfetch = 65536;
await body();
}
finally
{
fx.Nm.HistorianDataSource = NullHistorianDataSource.Instance;
fx.Gate.Release();
}
}
private static ReadRawModifiedDetails Raw(DateTime start, DateTime end, uint n, bool bounds) => new()
{
StartTime = start, EndTime = end, NumValuesPerNode = n, ReturnBounds = bounds, IsReadModified = false,
};
private static ReadProcessedDetails Processed(NodeId aggregate) => new()
{
StartTime = T(0), EndTime = T(60), ProcessingInterval = 10_000, AggregateType = new[] { aggregate },
AggregateConfiguration = new AggregateConfiguration { UseServerCapabilitiesDefaults = true },
};
private Outcome[] Override(HistoryReadDetails details, params string[] nodes)
{
var (results, errors) = InvokeOverride(details, nodes.Select(k => (k, (byte[]?)null)).ToArray());
return nodes.Select((_, i) => ToOutcome(errors[i], results[i])).ToArray();
}
private (SdkHistoryReadResult?[] Results, ServiceResult?[] Errors) InvokeOverride(
HistoryReadDetails details, (string Key, byte[]? Cp)[] nodes)
{
var context = new OperationContext(new RequestHeader(), secureChannelContext: null, RequestType.HistoryRead,
requestLifetime: RequestLifetime.None, identity: null);
var nodesToRead = nodes.Select(n => new HistoryReadValueId
{
NodeId = fx.Nodes[n.Key].NodeId, ContinuationPoint = ByteString.From(n.Cp),
}).ToList();
var results = new List<SdkHistoryReadResult>(nodes.Select(_ => (SdkHistoryReadResult)null!));
var errors = new List<ServiceResult>(nodes.Select(_ => (ServiceResult)null!));
fx.Nm.HistoryRead(context, details, TimestampsToReturn.Both, releaseContinuationPoints: false, nodesToRead, results, errors);
return (results.ToArray(), errors.ToArray());
}
private Outcome[] Port(HistoryReadDetails details, params string[] nodes) =>
PortRead(details, nodes.Select(k => (k, (byte[]?)null)).ToArray()).Select(o => o.Outcome).ToArray();
private (Outcome Outcome, byte[]? Cp)[] PortRead(HistoryReadDetails details, (string Key, byte[]? Cp)[] nodes)
{
var items = nodes.Select((n, i) => new HistoryReadPortItem(
fx.Nodes[n.Key].Realm, fx.Nodes[n.Key].Id, n.Cp,
details is ReadProcessedDetails p ? p.AggregateType[i] : default,
BindingTag: fx.Nm.HistoryBindingTag(fx.Nodes[n.Key].NodeId), NodeId: fx.Nodes[n.Key].NodeId)).ToArray();
var outcomes = fx.Nm.ReadHistory(HistoryReadVariant.From(details), items,
fx.Nm.SessionHistoryContinuationScope(session: null), CancellationToken.None);
// A slot the port leaves unset is the one the SDK seeded before the override ran (an empty, Good result).
return outcomes.Select(o => (ToOutcome(o.Error, o.Result ?? new SdkHistoryReadResult()), o.ContinuationPoint)).ToArray();
}
private (Outcome Outcome, byte[]? Cp) ReadOverrideRaw(HistoryReadDetails details, string node, byte[]? cp)
{
var (results, errors) = InvokeOverride(details, [(node, cp)]);
return (ToOutcome(errors[0], results[0]), results[0]?.ContinuationPoint.ToNullableArray());
}
private (Outcome Outcome, byte[]? Cp) ReadPortRaw(HistoryReadDetails details, string node, byte[]? cp) =>
PortRead(details, [(node, cp)])[0];
private string DrainOverride(HistoryReadDetails details, string node) =>
Drain(cp => ReadOverrideRaw(details, node, cp));
private string DrainPort(HistoryReadDetails details, string node) =>
Drain(cp => ReadPortRaw(details, node, cp));
private static string Drain(Func<byte[]?, (Outcome Outcome, byte[]? Cp)> read)
{
var parts = new List<string>();
byte[]? cp = null;
for (var page = 0; page < 100; page++)
{
var (outcome, next) = read(cp);
outcome.Error.ShouldBe(StatusCodes.Good.Code, $"page {page}");
if (outcome.Values.Length > 0) parts.Add(outcome.Values);
cp = next;
if (cp is null) return string.Join(" | ", parts);
}
throw new InvalidOperationException("paging did not terminate");
}
private static Outcome ToOutcome(ServiceResult? error, SdkHistoryReadResult? result)
{
var values = "";
if (result?.HistoryData is { IsNull: false } body && ExtensionObject.ToEncodeable(body) is HistoryData data)
values = string.Join(" | ", (data.DataValues.ToArray() ?? []).Select(Render));
return new Outcome(error?.StatusCode.Code ?? uint.MaxValue, result?.StatusCode.Code, values, result?.ContinuationPoint.ToNullableArray() is not null);
}
private static string Render(DataValue v)
{
var clr = SdkValueBoundary.ToClr(v.WrappedValue);
var when = v.SourceTimestamp.ToDateTime();
var stamp = when == DateTime.MinValue ? "none" : $"T0+{(when - T0).TotalSeconds:0.#######}";
return $"{stamp}={(clr is null ? "null" : $"{clr}:{clr.GetType().Name}")}/{v.StatusCode.Code:X8}";
}
/// <summary>A series-backed fake with scripted processed / AtTime answers and the Gateway's Boolean TimeAverage refusal.</summary>
internal sealed class ParitySource : IHistorianDataSource
{
public Dictionary<string, List<DataValueSnapshot>> Series { get; } = new();
public Dictionary<string, List<HistoryModifiedValue>> Trail { get; } = new();
public System.Collections.Concurrent.ConcurrentDictionary<string, HistoryAggregateType> ProcessedAsked { get; } = new();
public IReadOnlyList<DataValueSnapshot> ProcessedResult { get; init; } = [];
public IReadOnlyList<DataValueSnapshot> AtTimeResult { get; set; } = [];
public bool NativeReverse { get; init; } = true;
public int Ceiling { get; init; }
public bool Throw { get; init; }
public int ProcessedCalls;
public int ReverseOnForwardOnly;
public bool RefusedAggregateAsked { get; private set; }
public TypeCode? LastAtTimeType { get; private set; }
public bool SupportsReverseRaw => NativeReverse;
public int MaxRawValuesPerRead => Ceiling;
public bool SupportsAggregateFor(HistoryAggregateType aggregate, TypeCode? valueType)
{
if (aggregate == HistoryAggregateType.TimeAverage && valueType == TypeCode.Boolean)
{
RefusedAggregateAsked = true;
return false;
}
return true;
}
public Task<HistorianRead> ReadRawAsync(
string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode, CancellationToken cancellationToken)
{
static DateTime Ts(DataValueSnapshot s) => s.SourceTimestampUtc ?? DateTime.MinValue;
if (Throw) throw new InvalidOperationException("backend down");
var series = Series.TryGetValue(fullReference, out var s) ? s : [];
List<DataValueSnapshot> window;
if (startUtc > endUtc)
{
if (!NativeReverse)
{
Interlocked.Increment(ref ReverseOnForwardOnly);
throw new InvalidOperationException("start_time must be less than or equal to end_time.");
}
window = series.Where(x => Ts(x) > endUtc && Ts(x) <= startUtc).Reverse().ToList();
}
else if (startUtc == endUtc) window = series.Where(x => Ts(x) == startUtc).ToList();
else window = series.Where(x => Ts(x) >= startUtc && Ts(x) < endUtc).ToList();
if (Ceiling > 0 && (maxValuesPerNode == 0 || maxValuesPerNode > Ceiling) && window.Count > Ceiling)
throw new HistoryReadLimitExceededException(Ceiling, "over the ceiling");
var page = maxValuesPerNode == 0 ? window : window.Take((int)maxValuesPerNode).ToList();
return Task.FromResult(new HistorianRead(page, null));
}
public Task<HistorianRead> ReadProcessedAsync(
string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval,
HistoryAggregateType aggregate, CancellationToken cancellationToken)
{
Interlocked.Increment(ref ProcessedCalls);
ProcessedAsked[fullReference] = aggregate;
return Task.FromResult(new HistorianRead(ProcessedResult, null));
}
public Task<HistoryModifiedReadResult> ReadModifiedAsync(
string fullReference, DateTime startUtc, DateTime endUtc, uint maxValues, HistoryModifiedCursor? resumeAfter,
CancellationToken cancellationToken)
{
if (!Trail.TryGetValue(fullReference, out var trail)) throw new NotSupportedException("no trail");
var window = trail.Where(m => m.SourceTimeUtc >= startUtc && m.SourceTimeUtc < endUtc)
.OrderBy(m => m.SourceTimeUtc).ThenBy(m => m.ModifiedId)
.Where(m => resumeAfter is null || m.SourceTimeUtc > resumeAfter.SourceTimeUtc
|| (m.SourceTimeUtc == resumeAfter.SourceTimeUtc && m.ModifiedId > resumeAfter.ModifiedId))
.ToList();
var page = maxValues == 0 ? window : window.Take((int)maxValues).ToList();
return Task.FromResult(new HistoryModifiedReadResult(page, page.Count < window.Count));
}
public Task<HistorianRead> ReadAtTimeAsync(
string fullReference, IReadOnlyList<DateTime> timestampsUtc, CancellationToken cancellationToken) =>
Task.FromResult(new HistorianRead(AtTimeResult, null));
public Task<HistorianRead> ReadAtTimeAsync(
string fullReference, IReadOnlyList<DateTime> timestampsUtc, TypeCode? valueType, CancellationToken cancellationToken)
{
LastAtTimeType = valueType;
if (Throw) throw new InvalidOperationException("backend down");
return Task.FromResult(new HistorianRead(AtTimeResult, 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() { }
}
}