test(grpc-data): H1 port-vs-override parity cases and 10k-seed paged-vs-unpaged port fuzz
This commit is contained in:
@@ -0,0 +1,313 @@
|
||||
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>
|
||||
/// H1: paged-vs-unpaged fuzz THROUGH THE HISTORY PORT (plan §9 H1). Random tie-heavy series (sub-resolution stamps,
|
||||
/// bursts, gaps, tie clusters), random windows (on a tie, a step past one, between samples; forward, reverse and
|
||||
/// end-only; with and without bounds), random <c>NumValuesPerNode</c> and an optional backend row ceiling, over three
|
||||
/// backend shapes (SqlServer: ticks, native reverse; QuestDB: µs truncation, native reverse; Gateway: forward-only,
|
||||
/// walked back). The concatenated pages must equal the one-shot read, which for a plain read must also equal the
|
||||
/// series itself; paging must terminate; and on every tenth seed the SDK override path must return the SAME pages,
|
||||
/// page for page, as the port — the override is an adapter over the port, so any divergence is an adapter defect.
|
||||
/// <para>
|
||||
/// Seeds are deterministic (0 … N−1), so a failure names a reproducible seed. Iterations:
|
||||
/// <c>OTOPCUA_PORT_FUZZ_ITERATIONS</c> (default 10 000, the H1 gate minimum).
|
||||
/// </para>
|
||||
/// </summary>
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Phase", "H1")]
|
||||
public sealed class HistoryReadPortPagingFuzzTests(HistoryReadPortServerFixture fx) : IClassFixture<HistoryReadPortServerFixture>
|
||||
{
|
||||
private static readonly DateTime T0 = new(2026, 10, 22, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private enum Shape { SqlServer, QuestDb, Gateway }
|
||||
|
||||
private enum Direction { Forward, Reverse, EndOnly }
|
||||
|
||||
private static int Iterations =>
|
||||
int.TryParse(Environment.GetEnvironmentVariable("OTOPCUA_PORT_FUZZ_ITERATIONS"), out var n) && n > 0 ? n : 10_000;
|
||||
|
||||
[Fact]
|
||||
public async Task Paged_equals_unpaged_through_the_port_on_random_tie_series()
|
||||
{
|
||||
var iterations = Iterations;
|
||||
iterations.ShouldBeGreaterThanOrEqualTo(1);
|
||||
var counts = new Dictionary<string, int>();
|
||||
void Count(string key) => counts[key] = counts.GetValueOrDefault(key) + 1;
|
||||
var (realm, id, nodeId) = fx.Nodes["dbl"];
|
||||
|
||||
await fx.Gate.WaitAsync(TestContext.Current.CancellationToken);
|
||||
try
|
||||
{
|
||||
fx.Nm.MaxTieClusterOverfetch = 65536;
|
||||
for (var seed = 0; seed < iterations; seed++)
|
||||
{
|
||||
var rng = new Random(seed);
|
||||
var shape = (Shape)(seed % 3);
|
||||
var resolution = shape == Shape.QuestDb ? 10L : 1L;
|
||||
var series = RandomSeries(rng, resolution);
|
||||
var n = rng.Next(6) switch { 0 => 1u, 1 => 2u, 2 => 3u, 3 => (uint)rng.Next(4, 12), 4 => 0u, _ => (uint)rng.Next(12, 60) };
|
||||
var direction = rng.Next(5) switch { 0 => Direction.Reverse, 1 => Direction.EndOnly, _ => Direction.Forward };
|
||||
if (direction == Direction.EndOnly && n == 0) direction = Direction.Forward; // Part 11: one bound only with a cap
|
||||
var bounds = direction != Direction.EndOnly && rng.Next(4) == 0;
|
||||
// A strict row ceiling only on the native shapes (the walk-back's own budget is the raw-cap fuzz's subject).
|
||||
var ceiling = shape != Shape.Gateway && rng.Next(4) == 0 ? rng.Next(3, 12) : 0;
|
||||
|
||||
var a = PickBoundary(rng, series, resolution);
|
||||
var b = PickBoundary(rng, series, resolution);
|
||||
var (lo, hi) = a <= b ? (a, b) : (b, a);
|
||||
var (start, end) = direction switch
|
||||
{
|
||||
Direction.Forward => (lo, hi),
|
||||
Direction.Reverse => (hi, lo),
|
||||
_ => (DateTime.MinValue, hi),
|
||||
};
|
||||
var tag = $"seed {seed} {shape} N {n} ceiling {ceiling} {direction} bounds {bounds} [{start:O} .. {end:O}]";
|
||||
|
||||
// The oracle: the port's one-shot answer with no cap and no ceiling (end-only: the explicit reverse to 1970).
|
||||
fx.Nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
|
||||
fx.Nm.HistorianDataSource = new FuzzSource(series, shape, ceiling: 0);
|
||||
var oracleDetails = direction == Direction.EndOnly
|
||||
? new HistoryReadRawVariant(hi, DateTime.UnixEpoch, 0, false)
|
||||
: new HistoryReadRawVariant(start, end, 0, bounds);
|
||||
var truth = PortRead(oracleDetails, realm, id, null);
|
||||
truth.Status.ShouldBe(StatusCodes.Good.Code, $"oracle: {tag}");
|
||||
truth.Cp.ShouldBeNull($"oracle is one page: {tag}");
|
||||
if (!bounds) truth.Values.ShouldBe(SeriesOracle(series, start, end, direction, resolution), $"oracle vs series: {tag}");
|
||||
|
||||
// The read under test, through the port.
|
||||
var source = new FuzzSource(series, shape, ceiling);
|
||||
fx.Nm.HistorianDataSource = source;
|
||||
var details = new HistoryReadRawVariant(start, end, n, bounds);
|
||||
var portPages = Page(cp => PortRead(details, realm, id, cp), truth.Values.Count, tag, out var portStatus);
|
||||
source.ReverseOnForwardOnly.ShouldBe(0, $"a reverse window reached a forward-only backend: {tag}");
|
||||
|
||||
if (portStatus == StatusCodes.BadTooManyOperations)
|
||||
{
|
||||
// Legitimate only when a tie cluster is too large for the page a ceiling leaves.
|
||||
(ceiling > 0 && LargestTieCluster(series, resolution) >= ceiling - 1).ShouldBeTrue($"refused without an oversized tie cluster: {tag}");
|
||||
Count("refused");
|
||||
}
|
||||
else
|
||||
{
|
||||
portStatus.ShouldBe(StatusCodes.Good.Code, tag);
|
||||
string.Join(" | ", portPages.SelectMany(p => p)).ShouldBe(string.Join(" | ", truth.Values), $"paged ≠ unpaged: {tag}");
|
||||
if (n > 0) portPages.ShouldAllBe(p => p.Count <= n + (bounds ? 1 : 0), $"a page over N: {tag}");
|
||||
Count("exact");
|
||||
}
|
||||
|
||||
// Every tenth seed: the SDK override path returns the same pages as the port.
|
||||
if (seed % 10 == 0)
|
||||
{
|
||||
fx.Nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
|
||||
fx.Nm.HistorianDataSource = new FuzzSource(series, shape, ceiling);
|
||||
var sdkDetails = new ReadRawModifiedDetails
|
||||
{
|
||||
StartTime = start, EndTime = end, NumValuesPerNode = n, ReturnBounds = bounds, IsReadModified = false,
|
||||
};
|
||||
var overridePages = Page(cp => OverrideRead(sdkDetails, nodeId, cp), truth.Values.Count, tag, out var overrideStatus);
|
||||
overrideStatus.ShouldBe(portStatus, $"override vs port status: {tag}");
|
||||
overridePages.Select(p => string.Join(" | ", p)).ShouldBe(portPages.Select(p => string.Join(" | ", p)), $"override vs port pages: {tag}");
|
||||
Count("override compared");
|
||||
}
|
||||
|
||||
if (truth.Values.Count == 0) Count("empty");
|
||||
if (portPages.Count > 1) Count("paged");
|
||||
if (direction != Direction.Forward) Count(direction.ToString());
|
||||
if (bounds) Count("bounds");
|
||||
if (ceiling > 0) Count("ceiling");
|
||||
if (n == 0) Count("N=0");
|
||||
if (n == 1) Count("N=1");
|
||||
Count(shape.ToString());
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
fx.Nm.HistorianDataSource = NullHistorianDataSource.Instance;
|
||||
fx.Nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
|
||||
fx.Gate.Release();
|
||||
}
|
||||
|
||||
var summary = string.Join(", ", counts.OrderBy(kv => kv.Key).Select(kv => $"{kv.Key}={kv.Value}"));
|
||||
foreach (var required in new[] { "empty", "paged", "Reverse", "EndOnly", "bounds", "ceiling", "N=0", "N=1", "SqlServer", "QuestDb", "Gateway", "override compared" })
|
||||
counts.GetValueOrDefault(required).ShouldBeGreaterThan(iterations / 200, $"{required} under-represented: {summary}");
|
||||
counts.GetValueOrDefault("exact").ShouldBeGreaterThan(iterations * 9 / 10, summary);
|
||||
TestContext.Current.TestOutputHelper?.WriteLine($"port paging fuzz: {iterations} iterations — {summary}");
|
||||
}
|
||||
|
||||
private static List<List<string>> Page(
|
||||
Func<byte[]?, (uint Status, List<string> Values, byte[]? Cp)> read, int truthCount, string tag, out uint status)
|
||||
{
|
||||
var pages = new List<List<string>>();
|
||||
byte[]? cp = null;
|
||||
do
|
||||
{
|
||||
var (s, values, next) = read(cp);
|
||||
status = s;
|
||||
if ((s & 0x80000000u) != 0) return pages;
|
||||
pages.Add(values);
|
||||
cp = next;
|
||||
pages.Count.ShouldBeLessThanOrEqualTo(2 * truthCount + 4, $"paging must terminate: {tag}");
|
||||
}
|
||||
while (cp is not null);
|
||||
|
||||
return pages;
|
||||
}
|
||||
|
||||
private (uint Status, List<string> Values, byte[]? Cp) PortRead(HistoryReadRawVariant details, AddressSpaceRealm realm, string id, byte[]? cp)
|
||||
{
|
||||
var outcome = fx.Nm.ReadHistory(details, [new HistoryReadPortItem(realm, id, cp)],
|
||||
fx.Nm.SessionHistoryContinuationScope(session: null), CancellationToken.None)[0];
|
||||
return (outcome.Status.Code, outcome.Values.Select(Render).ToList(), outcome.ContinuationPoint);
|
||||
}
|
||||
|
||||
private (uint Status, List<string> Values, byte[]? Cp) OverrideRead(ReadRawModifiedDetails details, NodeId nodeId, byte[]? cp)
|
||||
{
|
||||
var context = new OperationContext(new RequestHeader(), secureChannelContext: null, RequestType.HistoryRead,
|
||||
requestLifetime: RequestLifetime.None, identity: null);
|
||||
var nodesToRead = new List<HistoryReadValueId> { new() { NodeId = nodeId, ContinuationPoint = ByteString.From(cp) } };
|
||||
var results = new List<SdkHistoryReadResult> { null! };
|
||||
var errors = new List<ServiceResult> { null! };
|
||||
fx.Nm.HistoryRead(context, details, TimestampsToReturn.Both, releaseContinuationPoints: false, nodesToRead, results, errors);
|
||||
var values = results[0]?.HistoryData is { IsNull: false } body && ExtensionObject.ToEncodeable(body) is HistoryData data
|
||||
? (data.DataValues.ToArray() ?? []).Select(Render).ToList()
|
||||
: [];
|
||||
return (errors[0].StatusCode.Code, values, results[0]?.ContinuationPoint.ToNullableArray());
|
||||
}
|
||||
|
||||
private static string Render(DataValue v) =>
|
||||
$"{v.SourceTimestamp.ToDateTime().Ticks}={SdkValueBoundary.ToClr(v.WrappedValue) ?? "null"}/{v.StatusCode.Code:X8}";
|
||||
|
||||
private static string Render(DataValueSnapshot s) =>
|
||||
$"{Ts(s).Ticks}={s.Value ?? "null"}/{s.StatusCode:X8}";
|
||||
|
||||
private static DateTime Ts(DataValueSnapshot s) => s.SourceTimestampUtc ?? DateTime.MinValue;
|
||||
|
||||
private static DateTime Trunc(DateTime t, long resolution) => new(t.Ticks - t.Ticks % resolution, DateTimeKind.Utc);
|
||||
|
||||
private static List<DataValueSnapshot> RandomSeries(Random rng, long resolution)
|
||||
{
|
||||
var list = new List<DataValueSnapshot>();
|
||||
var t = T0.Ticks - rng.Next(0, 3) * TimeSpan.TicksPerHour;
|
||||
var count = rng.Next(0, 60);
|
||||
var v = 0;
|
||||
while (list.Count < count)
|
||||
{
|
||||
t += rng.Next(6) switch
|
||||
{
|
||||
0 => rng.Next(1, 10),
|
||||
1 => rng.Next(1, 5) * TimeSpan.TicksPerMillisecond,
|
||||
2 => rng.Next(1, 3) * TimeSpan.TicksPerSecond,
|
||||
3 => rng.Next(1, 30) * TimeSpan.TicksPerMinute,
|
||||
_ => rng.Next(1, 1000) * TimeSpan.TicksPerMillisecond,
|
||||
};
|
||||
var ties = rng.Next(5) == 0 ? rng.Next(2, 9) : 1;
|
||||
for (var k = 0; k < ties; k++)
|
||||
{
|
||||
var ts = Trunc(new DateTime(t, DateTimeKind.Utc), resolution);
|
||||
var bad = rng.Next(12) == 0;
|
||||
list.Add(new DataValueSnapshot(bad ? null : (double)v, bad ? StatusCodes.Bad.Code : StatusCodes.Good.Code, ts, ts));
|
||||
v++;
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private static DateTime PickBoundary(Random rng, List<DataValueSnapshot> series, long resolution)
|
||||
{
|
||||
if (series.Count == 0) return T0.AddSeconds(rng.Next(-100, 100));
|
||||
var i = rng.Next(series.Count);
|
||||
var t = Ts(series[i]);
|
||||
switch (rng.Next(9))
|
||||
{
|
||||
case 0: return Ts(series[0]).AddSeconds(-rng.Next(1, 100));
|
||||
case 1: return Ts(series[^1]).AddSeconds(rng.Next(1, 100));
|
||||
case 2:
|
||||
case 3: return t;
|
||||
case 4: return t.AddTicks(resolution);
|
||||
case 5: return t.AddTicks(-1);
|
||||
case 6: return t.AddMilliseconds(1);
|
||||
default:
|
||||
var next = i + 1 < series.Count ? Ts(series[i + 1]) : t.AddSeconds(10);
|
||||
return new DateTime(t.Ticks + (long)((next.Ticks - t.Ticks) * rng.NextDouble()), DateTimeKind.Utc);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<string> SeriesOracle(List<DataValueSnapshot> series, DateTime start, DateTime end, Direction direction, long resolution)
|
||||
{
|
||||
var s = Trunc(start, resolution);
|
||||
var e = Trunc(end, resolution);
|
||||
IEnumerable<DataValueSnapshot> window = direction switch
|
||||
{
|
||||
Direction.Forward or Direction.Reverse when s == e => series.Where(x => Ts(x) == s),
|
||||
Direction.Forward => series.Where(x => Ts(x) >= s && Ts(x) < e),
|
||||
Direction.Reverse => series.Where(x => Ts(x) > e && Ts(x) <= s).Reverse(),
|
||||
_ => series.Where(x => Ts(x) <= e).Reverse(),
|
||||
};
|
||||
return window.Select(Render).ToList();
|
||||
}
|
||||
|
||||
private static int LargestTieCluster(List<DataValueSnapshot> series, long resolution) =>
|
||||
series.GroupBy(x => Trunc(Ts(x), resolution).Ticks).Select(g => g.Count()).DefaultIfEmpty(0).Max();
|
||||
|
||||
/// <summary>A series-backed backend of one shape; a non-zero <c>ceiling</c> is a strict row ceiling (refused above it).</summary>
|
||||
private sealed class FuzzSource(IReadOnlyList<DataValueSnapshot> series, Shape shape, int ceiling) : IHistorianDataSource
|
||||
{
|
||||
public int ReverseOnForwardOnly;
|
||||
|
||||
public bool SupportsReverseRaw => shape != Shape.Gateway;
|
||||
|
||||
public long TimestampResolutionTicks => shape == Shape.QuestDb ? 10 : 1;
|
||||
|
||||
public int MaxRawValuesPerRead => ceiling;
|
||||
|
||||
public Task<HistorianRead> ReadRawAsync(
|
||||
string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode, CancellationToken cancellationToken)
|
||||
{
|
||||
if (shape == Shape.Gateway && startUtc > endUtc)
|
||||
{
|
||||
Interlocked.Increment(ref ReverseOnForwardOnly);
|
||||
throw new InvalidOperationException("start_time must be less than or equal to end_time.");
|
||||
}
|
||||
|
||||
startUtc = Trunc(startUtc, TimestampResolutionTicks);
|
||||
endUtc = Trunc(endUtc, TimestampResolutionTicks);
|
||||
List<DataValueSnapshot> window;
|
||||
if (startUtc > endUtc) 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();
|
||||
|
||||
var probe = ceiling > 0 && (maxValuesPerNode == 0 || maxValuesPerNode > (uint)ceiling);
|
||||
if (probe && window.Count > ceiling)
|
||||
throw new HistoryReadLimitExceededException(ceiling, $"more than {ceiling} rows");
|
||||
var page = maxValuesPerNode == 0 ? window : window.Take((int)Math.Min(maxValuesPerNode, int.MaxValue)).ToList();
|
||||
return Task.FromResult(new HistorianRead(page, null));
|
||||
}
|
||||
|
||||
public Task<HistorianRead> ReadProcessedAsync(
|
||||
string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval,
|
||||
HistoryAggregateType aggregate, CancellationToken cancellationToken) =>
|
||||
Task.FromResult(new HistorianRead(Array.Empty<DataValueSnapshot>(), null));
|
||||
|
||||
public Task<HistorianRead> ReadAtTimeAsync(
|
||||
string fullReference, IReadOnlyList<DateTime> timestampsUtc, CancellationToken cancellationToken) =>
|
||||
Task.FromResult(new HistorianRead(Array.Empty<DataValueSnapshot>(), 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() { }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,618 @@
|
||||
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>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(), 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>
|
||||
/// 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. Each case also pins the
|
||||
/// override outcome to explicit expected values recorded against the pre-port node manager, so "identical" can never
|
||||
/// mean "identically wrong after the refactor".
|
||||
/// </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_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", "inc-1", capacity: 4);
|
||||
var peer = new PeerHistoryContinuationScope(store);
|
||||
|
||||
HistoryReadNodeOutcome Read(IHistoryContinuationScope scope, HistoryReadVariant d, byte[]? cp) =>
|
||||
fx.Nm.ReadHistory(d, [new HistoryReadPortItem(realm, id, cp)], scope, CancellationToken.None)[0];
|
||||
|
||||
string DrainWith(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);
|
||||
var cp2 = Read(peer, details, null).ContinuationPoint!;
|
||||
var restarted = new PeerHistoryContinuationScope(new PeerHistoryContinuationStore("svc-consumer", "inc-2", capacity: 4));
|
||||
Read(restarted, details, cp2).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(1, "cp2 was presented to another incarnation's store, so it is still held here until idle expiry");
|
||||
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)).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 IReadOnlyList<DataValueSnapshot> ProcessedResult { get; init; } = [];
|
||||
public IReadOnlyList<DataValueSnapshot> AtTimeResult { get; set; } = [];
|
||||
public bool NativeReverse { get; init; } = true;
|
||||
public int Ceiling { 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;
|
||||
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);
|
||||
return Task.FromResult(new HistorianRead(ProcessedResult, null));
|
||||
}
|
||||
|
||||
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;
|
||||
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() { }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user