fix(grpc-data): H2 review2-2..6 - byte-bounded pages, one deadline, no leaked cursors
Each node's Raw page is clamped from a per-value byte estimate of its catalog type (wide strings/arrays get small pages plus a continuation) and sub-batches are sized by estimated bytes, so the in-flight read respects MaxHistoryResponseBytes; AtTime/Processed whose values x estimate exceed the budget are refused per node with a diagnostic. One deadline per request: nodes not started when it passes are deferred (transport) or BadTimeout (direct). Every refusal releases the page cursor it was just given; releasing, invalidating or expiring a chunk releases the page cursor behind it; results are disposed on the exception path. Chunk bindings use per-node details. OpcUaServer IVT for Runtime.Tests/Host.Tests so tests can hold real page cursors.
This commit is contained in:
+76
-5
@@ -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; }
|
||||
/// <summary>When set, each item gets min(this, the page cap) generated values instead of <see cref="Samples"/>.</summary>
|
||||
public int? SamplesPerItem { get; set; }
|
||||
/// <summary>Generated value i (default: the double i).</summary>
|
||||
public Func<int, object?>? ValueFactory { get; set; }
|
||||
/// <summary>Save a real page cursor in the passed store for each answer (instead of <see cref="Continuation"/>).</summary>
|
||||
public bool RealCursors { get; set; }
|
||||
/// <summary>Each call waits this long (honouring the call's token) before answering.</summary>
|
||||
public TimeSpan? DelayPerCall { get; set; }
|
||||
/// <summary>The cursor store of the last call.</summary>
|
||||
public OriginHistoryCursors? LastCursors { get; private set; }
|
||||
/// <summary>The largest approximate payload one port call materialised.</summary>
|
||||
public long MaxCallBytes { get; private set; }
|
||||
/// <summary>Values handed out by the port in total (the origin materialised at most this many).</summary>
|
||||
public long ValuesReturned => Interlocked.Read(ref _values);
|
||||
/// <summary>Further historized raw identifiers.</summary>
|
||||
@@ -428,13 +492,15 @@ internal sealed class FakeHistoryPort : IOriginHistoryPort
|
||||
DataHistoryDetails details, IReadOnlyList<OriginHistoryItem> 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;
|
||||
}
|
||||
}
|
||||
|
||||
+20
@@ -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()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user