diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ZB.MOM.WW.OtOpcUa.OpcUaServer.csproj b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ZB.MOM.WW.OtOpcUa.OpcUaServer.csproj
index 785c72227..522def786 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ZB.MOM.WW.OtOpcUa.OpcUaServer.csproj
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ZB.MOM.WW.OtOpcUa.OpcUaServer.csproj
@@ -29,6 +29,8 @@
+
+
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs
index a4ad17d4b..46962383d 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs
@@ -102,77 +102,95 @@ public sealed partial class LocalDataServices
if (request.Details is DataHistoryAtTimeDetails atTime && atTime.RequestedTimesUtc.Count > limits.ValuesPerPage)
return Record(request, All(BadTooManyOperations, "More requested times than the origin's history values per page."));
if (!_historySessions.TryAdmit(context.PrincipalId, limits.ConcurrentReads)) return Record(request, All(BadTooManyOperations));
+ var results = new DataHistoryReadResult?[request.Items.Count];
try
{
var session = _historySessions.Get(context, channel, SessionCapacity(limits.ConcurrentReads, batchLimit));
- var details = Clamp(request.Details, limits.ValuesPerPage);
- var detailsKey = DetailsKey(details);
var incarnation = ServingIncarnation();
- // Per-request memory bound: the response budget (transport: the export's response cap; direct: the caller's
- // MaxBytes). Nodes are read in sub-batches sized so a sub-batch at the per-page ceiling fits it, and no further
- // sub-batch starts once the budget is spent — those nodes are deferred (transport) or BadTooManyOperations (direct).
+ // Per-request memory bound, in BYTES: the response budget (transport: the export's response cap; direct: the
+ // caller's MaxBytes). Each node's page is clamped from a per-value byte estimate of its catalog type (wide arrays
+ // and strings get small pages, returning a continuation for the rest); nodes are read in sub-batches whose
+ // estimated in-flight bytes fit the budget, and no sub-batch starts once the budget is spent or the request's one
+ // deadline has passed — those nodes are deferred (transport) or BadTooManyOperations / BadTimeout (direct).
var budget = ResponseBudget(chunked, limits.ResponseBytes, request.Budget.MaxBytes);
- var subBatch = (int)Math.Clamp(budget / Math.Max(1L, (long)limits.ValuesPerPage * 64L), 1L, Math.Max(1, request.Items.Count));
- var results = new DataHistoryReadResult?[request.Items.Count];
var nodes = new LocalDataNode?[request.Items.Count];
- var deferred = new bool[request.Items.Count];
- var pending = new List<(int Index, OriginHistoryItem Item)>();
+ var nodeDetails = new DataHistoryDetails?[request.Items.Count];
+ var keys = new string?[request.Items.Count];
+ var deferred = new Deferral[request.Items.Count];
+ var pending = new List<(int Index, OriginHistoryItem Item, long PageBytes)>();
for (var i = 0; i < request.Items.Count; i++)
{
var item = request.Items[i];
if (!Gate(catalog, context, item.View, out var node)) { results[i] = new(item.CorrelationId, Refused, [], null); continue; }
nodes[i] = node;
+ var valueBytes = EstimateValueBytes(node.Metadata, request.Details);
+ var details = NodeDetails(request.Details, limits.ValuesPerPage, budget, valueBytes);
+ nodeDetails[i] = details;
+ keys[i] = DetailsKey(details);
var continuation = item.Continuation;
if (session.TakeChunk(item.Continuation) is { } chunk)
{
- // A chunk token resumes the transport's remainder; it is bound to the view, details and serving identity.
- if (chunk.View != node.Metadata.View || chunk.DetailsKey != detailsKey || chunk.Incarnation != incarnation)
- { results[i] = Invalid(item, chunk); continue; }
+ // A chunk token resumes the transport's remainder; it is bound to the view, the node's details and serving identity.
+ if (chunk.View != node.Metadata.View || chunk.DetailsKey != keys[i] || chunk.Incarnation != incarnation)
+ { results[i] = Invalid(item, chunk, session); continue; }
if (!chunk.Deferred)
{ results[i] = new(item.CorrelationId, chunk.StatusCode, chunk.Remaining, chunk.Continuation, chunk.Diagnostic); continue; }
continuation = chunk.Continuation; // a deferred node is read now, from where it was
}
- if (Buckets(details) > limits.ValuesPerPage)
+ var values = ValuesPerNode(details);
+ if (details is not DataHistoryRawDetails && (values > limits.ValuesPerPage || values * valueBytes > budget))
{
- results[i] = new(item.CorrelationId, BadTooManyOperations, [], null, "More processing intervals than the origin's history values per page.");
+ session.Cursors.Release(continuation);
+ results[i] = new(item.CorrelationId, BadTooManyOperations, [], null, details is DataHistoryAtTimeDetails
+ ? "Too many requested times for the origin's history limits; request fewer times per call."
+ : "Too many processing intervals for the origin's history limits; use a longer interval or a shorter window.");
continue;
}
pending.Add((i, new OriginHistoryItem(Realm(node), node.Metadata.View.Address.Identifier, BindingTag(node.Metadata.View),
- item.AggregateId, continuation)));
+ item.AggregateId, continuation), values * valueBytes));
}
+ // ONE deadline for the whole request (H2 review): a node not started when it passes is deferred, never read late.
+ using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ deadline.CancelAfter(request.Budget.Timeout);
long used = 0;
- for (var start = 0; start < pending.Count; start += subBatch)
+ foreach (var group in pending.GroupBy(x => keys[x.Index]!))
{
- var slice = pending.Skip(start).Take(subBatch).ToArray();
- if (used >= budget)
+ var members = group.ToArray();
+ var pageBytes = Math.Max(1L, members.Max(x => x.PageBytes));
+ var subBatch = (int)Math.Clamp(budget / pageBytes, 1L, members.Length);
+ for (var start = 0; start < members.Length; start += subBatch)
{
- foreach (var (index, portItem) in slice)
+ var slice = members.Skip(start).Take(subBatch).ToArray();
+ if (used >= budget || deadline.IsCancellationRequested)
{
- deferred[index] = true;
- results[index] = new(request.Items[index].CorrelationId, 0, [], portItem.Continuation);
+ var reason = used >= budget ? Deferral.Budget : Deferral.Deadline;
+ cancellationToken.ThrowIfCancellationRequested();
+ foreach (var (index, portItem, _) in slice)
+ {
+ deferred[index] = reason;
+ results[index] = new(request.Items[index].CorrelationId, 0, [], portItem.Continuation);
+ }
+ continue;
+ }
+ IReadOnlyList outcomes;
+ try
+ {
+ outcomes = await _history.ReadAsync(session.Cursors, context.PrincipalId, ServingIncarnation, nodeDetails[slice[0].Index]!,
+ slice.Select(x => x.Item).ToArray(), deadline.Token).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
+ {
+ // The deadline passed before the port answered: every in-flight node is BadTimeout, as the port itself answers.
+ outcomes = slice.Select(_ => new OriginHistoryOutcome(0x800A0000u, [], null, false)).ToArray();
+ }
+ cancellationToken.ThrowIfCancellationRequested(); // a caller cancel is never a backend outcome
+ for (var k = 0; k < slice.Length; k++)
+ {
+ var index = slice[k].Index;
+ var result = ToResult(request.Items[index], nodes[index]!, outcomes[k], nodeDetails[index]!);
+ results[index] = result;
+ foreach (var sample in result.Samples) used += SampleBytes(sample, nodes[index]!.Metadata);
}
- continue;
- }
- using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
- deadline.CancelAfter(request.Budget.Timeout);
- IReadOnlyList outcomes;
- try
- {
- outcomes = await _history.ReadAsync(session.Cursors, context.PrincipalId, ServingIncarnation, details,
- slice.Select(x => x.Item).ToArray(), deadline.Token).ConfigureAwait(false);
- }
- catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
- {
- // The budget expired before the port answered: every in-flight node is BadTimeout, as the port itself answers.
- outcomes = slice.Select(_ => new OriginHistoryOutcome(0x800A0000u, [], null, false)).ToArray();
- }
- cancellationToken.ThrowIfCancellationRequested(); // a caller cancel is never a backend outcome
- for (var k = 0; k < slice.Length; k++)
- {
- var index = slice[k].Index;
- var result = ToResult(request.Items[index], nodes[index]!, outcomes[k], details);
- results[index] = result;
- foreach (var sample in result.Samples) used += SampleBytes(sample, nodes[index]!.Metadata);
}
}
// Authority may have moved while the backend answered: re-check every served item before handing anything back.
@@ -180,19 +198,64 @@ public sealed partial class LocalDataServices
if (nodes[i] is { } node && results[i]!.StatusCode != Refused
&& (!Ready(catalog) || !Allowed(catalog, context, node, DataOperations.HistoryRead) || !IsHistorized(node)))
{
+ session.Cursors.Release(results[i]!.Continuation);
results[i]!.Dispose();
results[i] = new(request.Items[i].CorrelationId, Refused, [], null);
- deferred[i] = false;
+ deferred[i] = Deferral.None;
}
var final = results.Select(x => x!).ToArray();
final = chunked
- ? Chunk(final, nodes, deferred, session, detailsKey, incarnation, budget, RemainderBudget(limits, budget))
+ ? Chunk(final, nodes, deferred, session, keys, incarnation, budget, RemainderBudget(limits, budget))
: Direct(final, deferred);
return Record(request, final);
}
+ catch
+ {
+ foreach (var result in results) result?.Dispose();
+ throw;
+ }
finally { _historySessions.Leave(context.PrincipalId); }
}
+ /// Why a node was not read in this request.
+ private enum Deferral { None, Budget, Deadline }
+
+ ///
+ /// A conservative per-value wire-size estimate from the node's catalog type (value + status + two timestamps +
+ /// framing): scalars 48 B, strings/bytes 1 KiB (no declared length), arrays element size × declared length (1,024
+ /// elements when unknown). Processed values are aggregate doubles.
+ ///
+ internal static long EstimateValueBytes(DataMetadata metadata, DataHistoryDetails details)
+ {
+ const long overhead = 40;
+ if (details is DataHistoryProcessedDetails) return overhead + 16;
+ static long Scalar(DataValueKind kind) => kind is DataValueKind.String or DataValueKind.Bytes ? 1024 : 16;
+ if (metadata.ValueKind != DataValueKind.Array) return overhead + Scalar(metadata.ValueKind);
+ var length = metadata.Dimensions.Count > 0 && metadata.Dimensions[0] > 0 ? metadata.Dimensions[0] : 1024;
+ return overhead + 16 + (long)length * (Scalar(metadata.ArrayElementKind ?? DataValueKind.Double) + 4);
+ }
+
+ ///
+ /// The node's request details: a Raw page is the requested count clamped to the per-page ceiling AND to what the byte
+ /// budget can carry at the node's value size (at least one value). Deterministic per (request, node type, limits), so a
+ /// resume binds the same details hash.
+ ///
+ private static DataHistoryDetails NodeDetails(DataHistoryDetails details, int valuesPerPage, long budget, long valueBytes)
+ {
+ if (details is not DataHistoryRawDetails raw) return details;
+ var byBytes = (uint)Math.Clamp(budget / Math.Max(1L, valueBytes), 1L, valuesPerPage);
+ var requested = raw.NumValuesPerNode == 0 ? (uint)valuesPerPage : raw.NumValuesPerNode;
+ return raw with { NumValuesPerNode = Math.Min(requested, Math.Min((uint)valuesPerPage, byBytes)) };
+ }
+
+ /// Values one node can return for these details (Raw page, Processed intervals, AtTime times).
+ private static long ValuesPerNode(DataHistoryDetails details) => details switch
+ {
+ DataHistoryRawDetails raw => raw.NumValuesPerNode + (raw.ReturnBounds ? 2 : 0),
+ DataHistoryAtTimeDetails atTime => atTime.RequestedTimesUtc.Count,
+ _ => Buckets(details),
+ };
+
internal Task ReleaseHistoryAsync(DataAuthenticatedContext context, IReadOnlyList continuations, DataHistoryChannel channel,
CancellationToken cancellationToken)
{
@@ -234,20 +297,16 @@ public sealed partial class LocalDataServices
return IsHistorized(node);
}
- private static DataHistoryReadResult Invalid(DataHistoryReadItem item, OriginHistorySession.Chunk chunk)
+ private static DataHistoryReadResult Invalid(DataHistoryReadItem item, OriginHistorySession.Chunk chunk, OriginHistorySession session)
{
foreach (var sample in chunk.Remaining) sample.Dispose();
+ session.Cursors.Release(chunk.Continuation); // the page cursor behind the chunk is gone with it
return new(item.CorrelationId, BadContinuationPointInvalid, [], null);
}
private static string BindingTag(DataView view) =>
"peer:" + (view.Realm == DataRealm.Raw ? "raw:" : "uns:") + view.Address.NamespaceUri;
- /// Raw pages at the export's per-page ceiling: 0 (all) or more than it is served as pages of the ceiling.
- private static DataHistoryDetails Clamp(DataHistoryDetails details, int valuesPerPage) => details is DataHistoryRawDetails raw
- && (raw.NumValuesPerNode == 0 || raw.NumValuesPerNode > (uint)valuesPerPage)
- ? raw with { NumValuesPerNode = (uint)valuesPerPage } : details;
-
private static void ValidateDetails(DataHistoryReadRequest request)
{
switch (request.Details)
@@ -309,18 +368,19 @@ public sealed partial class LocalDataServices
/// continuation. A single value larger than the whole budget, or a chunk the session / budget cannot hold, is
/// BadTooManyOperations for that node — explicit, never a silent truncation.
///
- private static DataHistoryReadResult[] Chunk(DataHistoryReadResult[] results, LocalDataNode?[] nodes, bool[] deferred,
- OriginHistorySession session, string detailsKey, string incarnation, long budget, long remainderBudget)
+ private static DataHistoryReadResult[] Chunk(DataHistoryReadResult[] results, LocalDataNode?[] nodes, Deferral[] deferred,
+ OriginHistorySession session, string?[] keys, string incarnation, long budget, long remainderBudget)
{
long used = 0;
for (var i = 0; i < results.Length; i++)
{
var result = results[i];
used += 32 + 3L * (result.CorrelationId.Length + (result.Diagnostic?.Length ?? 0));
- if (deferred[i])
+ if (deferred[i] != Deferral.None)
{
- var token = session.SaveChunk(new OriginHistorySession.Chunk(nodes[i]!.Metadata.View, detailsKey, incarnation, [],
+ var token = session.SaveChunk(new OriginHistorySession.Chunk(nodes[i]!.Metadata.View, keys[i]!, incarnation, [],
0, result.Continuation, null, 0, 0, Deferred: true), remainderBudget);
+ if (token is null) session.Cursors.Release(result.Continuation);
results[i] = token is null
? new(result.CorrelationId, BadTooManyOperations, [], null, "Origin history session is full.")
: new(result.CorrelationId, 0, [], token, null, ChunkContinues: true);
@@ -337,19 +397,23 @@ public sealed partial class LocalDataServices
}
if (oversized)
{
+ session.Cursors.Release(result.Continuation);
result.Dispose();
- results[i] = new(result.CorrelationId, BadTooManyOperations, [], null, "A history value exceeds the origin's response limit.");
+ results[i] = new(result.CorrelationId, BadTooManyOperations, [], null,
+ "A history value exceeds the origin's response limit; it cannot be served remotely.");
continue;
}
if (fit == result.Samples.Count) continue;
var remaining = result.Samples.Skip(fit).ToArray();
var bytes = remaining.Sum(x => SampleBytes(x, nodes[i]?.Metadata));
- var saved = session.SaveChunk(new OriginHistorySession.Chunk(nodes[i]!.Metadata.View, detailsKey, incarnation, remaining,
+ var saved = session.SaveChunk(new OriginHistorySession.Chunk(nodes[i]!.Metadata.View, keys[i]!, incarnation, remaining,
result.StatusCode, result.Continuation, result.Diagnostic, 0, bytes), remainderBudget);
if (saved is null)
{
+ session.Cursors.Release(result.Continuation);
result.Dispose();
- results[i] = new(result.CorrelationId, BadTooManyOperations, [], null, "Origin history remainder budget is full.");
+ results[i] = new(result.CorrelationId, BadTooManyOperations, [], null,
+ "Origin history remainder budget is full; retry with a lower NumValuesPerNode.");
continue;
}
results[i] = new(result.CorrelationId, result.StatusCode, result.Samples.Take(fit).ToArray(), saved, null, ChunkContinues: true);
@@ -358,12 +422,14 @@ public sealed partial class LocalDataServices
}
/// A direct consumer is never handed chunks: a node deferred by the request budget is BadTooManyOperations.
- private static DataHistoryReadResult[] Direct(DataHistoryReadResult[] results, bool[] deferred)
+ private static DataHistoryReadResult[] Direct(DataHistoryReadResult[] results, Deferral[] deferred)
{
for (var i = 0; i < results.Length; i++)
- if (deferred[i])
+ if (deferred[i] == Deferral.Budget)
results[i] = new(results[i].CorrelationId, BadTooManyOperations, [], null,
"Request byte budget spent before this node was read; read it in a later request.");
+ else if (deferred[i] == Deferral.Deadline)
+ results[i] = new(results[i].CorrelationId, 0x800A0000u, [], null, "Request deadline passed before this node was read.");
return results;
}
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OriginHistorySessions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OriginHistorySessions.cs
index 6f90b1b5c..d4a3d5673 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OriginHistorySessions.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OriginHistorySessions.cs
@@ -90,7 +90,12 @@ internal sealed class OriginHistorySession
/// Releases a chunk or a page token (idempotent).
public void Release(byte[]? token)
{
- if (TakeChunk(token) is { } chunk) { foreach (var sample in chunk.Remaining) sample.Dispose(); return; }
+ if (TakeChunk(token) is { } chunk)
+ {
+ foreach (var sample in chunk.Remaining) sample.Dispose();
+ Cursors.Release(chunk.Continuation); // the page cursor behind the chunk goes with it
+ return;
+ }
Cursors.Release(token);
}
@@ -117,6 +122,7 @@ internal sealed class OriginHistorySession
private void Drop(Chunk chunk)
{
_owner.ReleaseBytes(Principal, chunk.Bytes);
+ Cursors.Release(chunk.Continuation);
foreach (var sample in chunk.Remaining) sample.Dispose();
}
}
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataHistoryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataHistoryWireTests.cs
index 4cfe48fdb..33051cd8c 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataHistoryWireTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataHistoryWireTests.cs
@@ -334,6 +334,26 @@ public sealed class GrpcDataHistoryWireTests
origin.Services.HistoryRetainedBytes("peer").ShouldBe(0, "every remainder was taken");
}
+ [Fact]
+ public async Task Wide_values_get_a_byte_sized_page_so_in_flight_bytes_respect_the_response_budget()
+ {
+ await using var origin = new RealOrigin(responseBytes: 256 * 1024, valuesPerPage: 10_000);
+ origin.History!.AlsoHistorized.Add("Plant/Modbus/dev1/Label");
+ origin.History.SamplesPerItem = 10_000;
+ origin.History.ValueFactory = i => new string('w', 900);
+ origin.History.Continuation = [5, 5, 5];
+ var request = DataHistoryProtoMapper.EncodeRequest(new DataHistoryReadRequest(new DataHistoryRawDetails(T0, T0.AddHours(1), 0, false),
+ Enumerable.Range(0, 20).Select(i => I("w" + i, RealOriginRequests.Label)).ToArray(), Budget with { MaxItems = 100 }));
+ var response = await origin.HistoryAsync(request, History);
+ response.CalculateSize().ShouldBeLessThanOrEqualTo(256 * 1024);
+ // Budget 192 KiB at a 1 KiB estimate per string ⇒ a page of ~190 values; never the 10,000 a narrow tag would get.
+ origin.History.MaxCallBytes.ShouldBeLessThanOrEqualTo(256 * 1024, "the in-flight sub-batch respects the response budget");
+ var first = response.Items[0];
+ first.StatusCode.ShouldBe(0u, "a wide tag stays readable");
+ (first.Samples.Count > 0 || first.ChunkContinues).ShouldBeTrue();
+ response.Items.ShouldAllBe(x => x.StatusCode == 0u);
+ }
+
[Fact]
public async Task Processed_intervals_and_AtTime_times_above_the_page_ceiling_are_refused_unsent()
{
@@ -367,6 +387,40 @@ public sealed class GrpcDataHistoryWireTests
item.Samples.ShouldBeEmpty();
}
+ [Fact]
+ public async Task A_refused_node_releases_the_page_cursor_it_was_just_given()
+ {
+ await using var origin = new RealOrigin(responseBytes: 1);
+ origin.History!.AlsoHistorized.Add("Plant/Modbus/dev1/Label");
+ origin.History.RealCursors = true; // the fake saves a REAL page cursor in the session's store and returns its token
+ origin.History.Samples = [new(new string('x', 40_000), 0, T0.UtcDateTime, null)];
+ var item = (await origin.HistoryAsync(Raw(I("label", RealOriginRequests.Label)), History)).Items.Single();
+ item.StatusCode.ShouldBe(0x80100000u);
+ origin.History.LastCursors.ShouldNotBeNull().Count.ShouldBe(0, "the refused node's page cursor is not left behind");
+ }
+
+ [Fact]
+ public async Task The_request_has_one_deadline_and_nodes_not_started_before_it_are_deferred_or_BadTimeout()
+ {
+ await using var origin = new RealOrigin(valuesPerPage: 10_000);
+ origin.History!.SamplesPerItem = 1;
+ origin.History.DelayPerCall = TimeSpan.FromMilliseconds(250);
+ var items = Enumerable.Range(0, 40).Select(i => I("i" + i, RealOriginRequests.Flow)).ToArray();
+ var budget = Budget with { MaxItems = 100, Timeout = TimeSpan.FromMilliseconds(400) };
+ // Transport: unread nodes come back as deferred chunk tokens.
+ var response = await origin.HistoryAsync(DataHistoryProtoMapper.EncodeRequest(new DataHistoryReadRequest(
+ new DataHistoryRawDetails(T0, T0.AddHours(1), 0, false), items, budget)), History);
+ response.Items.Count(x => x.ChunkContinues && x.Samples.Count == 0).ShouldBeGreaterThan(0, "nodes not started before the deadline are deferred");
+ origin.History.Calls.ShouldBeLessThan(6, "no sub-batch starts after the request's single deadline");
+ // Direct consumer: the same nodes are BadTimeout.
+ await using var connection = origin.Connect();
+ var results = await ((IDataHistoryService)connection).ReadAsync(new DataHistoryReadRequest(
+ new DataHistoryRawDetails(T0, T0.AddHours(1), 0, false), items, budget), TestContext.Current.CancellationToken);
+ results.Count(x => x.StatusCode == 0x800A0000u).ShouldBeGreaterThan(0);
+ results.ShouldAllBe(x => !x.ChunkContinues);
+ foreach (var r in results) r.Dispose();
+ }
+
[Fact]
public async Task A_direct_consumer_gets_BadTooManyOperations_for_nodes_past_its_request_budget()
{
@@ -377,7 +431,7 @@ public sealed class GrpcDataHistoryWireTests
var results = await history.ReadAsync(new DataHistoryReadRequest(new DataHistoryRawDetails(T0, T0.AddHours(1), 0, false),
Enumerable.Range(0, 50).Select(i => I("i" + i, RealOriginRequests.Flow)).ToArray(), Budget with { MaxItems = 100, MaxBytes = 64 * 1024 }),
TestContext.Current.CancellationToken);
- results[0].Samples.Count.ShouldBe(2000);
+ results[0].Samples.Count.ShouldBeInRange(1, 64 * 1024 / 56, "the page is clamped to what the request budget can carry");
results.Last().StatusCode.ShouldBe(0x80100000u);
results.ShouldAllBe(r => !r.ChunkContinues);
origin.History.ValuesReturned.ShouldBeLessThanOrEqualTo(10 * 2000);
@@ -411,6 +465,16 @@ internal sealed class FakeHistoryPort : IOriginHistoryPort
public DataHistoryDetails? LastDetails { get; private set; }
/// When set, each item gets min(this, the page cap) generated values instead of .
public int? SamplesPerItem { get; set; }
+ /// Generated value i (default: the double i).
+ public Func? ValueFactory { get; set; }
+ /// Save a real page cursor in the passed store for each answer (instead of ).
+ public bool RealCursors { get; set; }
+ /// Each call waits this long (honouring the call's token) before answering.
+ public TimeSpan? DelayPerCall { get; set; }
+ /// The cursor store of the last call.
+ public OriginHistoryCursors? LastCursors { get; private set; }
+ /// The largest approximate payload one port call materialised.
+ public long MaxCallBytes { get; private set; }
/// Values handed out by the port in total (the origin materialised at most this many).
public long ValuesReturned => Interlocked.Read(ref _values);
/// Further historized raw identifiers.
@@ -428,13 +492,15 @@ internal sealed class FakeHistoryPort : IOriginHistoryPort
DataHistoryDetails details, IReadOnlyList items, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _calls);
- LastItems = items; LastDetails = details;
+ LastItems = items; LastDetails = details; LastCursors = cursors;
lock (_all) _all.AddRange(items);
_entered.TrySetResult();
if (Hold is { } hold) await hold.WaitAsync(cancellationToken);
+ if (DelayPerCall is { } delay) await Task.Delay(delay, cancellationToken);
await Task.Yield();
// Emulates the real port's single-use store: an unknown/consumed token is BadContinuationPointInvalid.
- return items.Select(item =>
+ long callBytes = 0;
+ var outcomes = items.Select(item =>
{
if (WiringFault) return new OriginHistoryOutcome(0x80020000u, [], null, true);
if (item.Continuation is { } token && !_issued.TryRemove(Convert.ToHexString(token), out _))
@@ -444,10 +510,15 @@ internal sealed class FakeHistoryPort : IOriginHistoryPort
if (SamplesPerItem is { } count)
{
var cap = details is DataHistoryRawDetails { NumValuesPerNode: > 0 } raw ? (int)Math.Min(raw.NumValuesPerNode, (uint)count) : count;
- samples = Enumerable.Range(0, cap).Select(i => new OriginHistorySample((double)i, 0, DateTime.UnixEpoch.AddSeconds(i), null)).ToArray();
+ samples = Enumerable.Range(0, cap).Select(i => new OriginHistorySample(ValueFactory?.Invoke(i) ?? (double)i, 0, DateTime.UnixEpoch.AddSeconds(i), null)).ToArray();
}
Interlocked.Add(ref _values, samples.Count);
- return new OriginHistoryOutcome(0, samples, Continuation, false);
+ foreach (var x in samples) callBytes += 48 + (x.Value is string text ? text.Length : 16);
+ var page = RealCursors ? cursors.Store.Save(new ZB.MOM.WW.OtOpcUa.OpcUaServer.HistoryContinuationState("t", DateTime.UnixEpoch,
+ DateTime.UnixEpoch, 0, 1) { BoundIdentifier = item.Identifier }, principal, "inc", "h") : Continuation;
+ return new OriginHistoryOutcome(0, samples, page, false);
}).ToArray();
+ lock (_all) MaxCallBytes = Math.Max(MaxCallBytes, callBytes);
+ return outcomes;
}
}
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataOriginHistorySessionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataOriginHistorySessionTests.cs
index 897d100d3..acaf1157d 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataOriginHistorySessionTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataOriginHistorySessionTests.cs
@@ -53,6 +53,26 @@ public sealed class GrpcDataOriginHistorySessionTests
sessions.RetainedBytes("a").ShouldBe(0, "clearing a session returns its remainder bytes");
}
+ [Fact]
+ public void Releasing_or_expiring_a_chunk_also_releases_the_page_cursor_behind_it()
+ {
+ var clock = new ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness.ManualTimeProvider();
+ var sessions = new OriginHistorySessions(clock);
+ var session = sessions.Get(Caller("a"), Channel("1"), 8);
+ var view = new DataView(new("c", "u", "string", "x"), DataRealm.Raw, null, 0, "x");
+ byte[] Page() => session.Cursors.Store.Save(new ZB.MOM.WW.OtOpcUa.OpcUaServer.HistoryContinuationState("t", DateTime.UnixEpoch,
+ DateTime.UnixEpoch, 0, 1) { BoundIdentifier = "x" }, "a", "inc", "h");
+ var released = session.SaveChunk(new OriginHistorySession.Chunk(view, "k", "i", [], 0, Page(), null, 0, 10), 1000).ShouldNotBeNull();
+ session.SaveChunk(new OriginHistorySession.Chunk(view, "k", "i", [], 0, Page(), null, 0, 0, Deferred: true), 1000).ShouldNotBeNull();
+ session.Cursors.Count.ShouldBe(2);
+ session.Release(released);
+ session.Cursors.Count.ShouldBe(1, "release dropped the chunk AND its page cursor");
+ clock.Advance(TimeSpan.FromSeconds(61));
+ session.ChunkCount.ShouldBe(0);
+ session.Cursors.Count.ShouldBe(0, "idle expiry of a chunk dropped its page cursor too");
+ sessions.RetainedBytes("a").ShouldBe(0);
+ }
+
[Fact]
public void Remainder_bytes_are_budgeted_per_principal_across_sessions()
{