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 01c1ad0da..da9867fd2 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 @@ -43,6 +43,9 @@ public sealed partial class LocalDataServices /// Live history sessions (diagnostics/tests). internal int HistorySessionCount => _historySessions.Count; + /// Remainder bytes retained for a principal across its sessions (diagnostics/tests). + internal long HistoryRetainedBytes(string principal) => _historySessions.RetainedBytes(principal); + private bool IsHistorized(LocalDataNode node) => _history is not null && node.Source is not null && node.Metadata.View.Address.IdentifierKind == "string" && _history.IsHistorized(Realm(node), node.Metadata.View.Address.Identifier); @@ -78,65 +81,92 @@ public sealed partial class LocalDataServices ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Items); ArgumentNullException.ThrowIfNull(request.Details); ArgumentNullException.ThrowIfNull(channel); var catalog = _catalog(); - CheckBudget(request.Budget, request.Items.Count, catalog is null ? _capabilities.Limits.MaxBatchItems : Limits(catalog, context).MaxBatchItems, - cancellationToken); + var batchLimit = catalog is null ? _capabilities.Limits.MaxBatchItems : Limits(catalog, context).MaxBatchItems; + CheckBudget(request.Budget, request.Items.Count, batchLimit, cancellationToken); foreach (var item in request.Items) { ArgumentNullException.ThrowIfNull(item); item.View.Validate(); } ValidateDetails(request); - DataHistoryReadResult[] All(uint status) => - request.Items.Select(x => new DataHistoryReadResult(x.CorrelationId, status, [], null)).ToArray(); + DataHistoryReadResult[] All(uint status, string? diagnostic = null) => + request.Items.Select(x => new DataHistoryReadResult(x.CorrelationId, status, [], null, diagnostic)).ToArray(); if (catalog is null || !Ready(catalog) || context.AuthorityEpoch != catalog.AuthorityEpoch || !RoleAllows(target, catalog.Serving)) throw new InvalidOperationException("History is unavailable for this target."); if (!_policy.IsCallerUsable(Caller(context))) throw new UnauthorizedAccessException(); if (_history is null || HistoryServing is null || catalog.HistoryLimitsFor(context.PrincipalId) is not { } limits) return Record(request, All(Refused)); + // AtTime: every requested time is one value of every node; above the per-page ceiling the request is refused unsent. + 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)); try { - var session = _historySessions.Get(context, channel, Math.Max(1, limits.ConcurrentReads * Math.Max(1, Limits(catalog, context).MaxBatchItems))); + 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). + 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 portIndexes = new List(); - var portItems = new List(); + var deferred = new bool[request.Items.Count]; + var pending = new List<(int Index, OriginHistoryItem Item)>(); 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 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. - results[i] = chunk.View == node.Metadata.View && chunk.DetailsKey == detailsKey && chunk.Incarnation == incarnation - ? new(item.CorrelationId, chunk.StatusCode, chunk.Remaining, chunk.Continuation, chunk.Diagnostic) - : Invalid(item, chunk); + if (chunk.View != node.Metadata.View || chunk.DetailsKey != detailsKey || chunk.Incarnation != incarnation) + { results[i] = Invalid(item, chunk); 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) + { + results[i] = new(item.CorrelationId, BadTooManyOperations, [], null, "More processing intervals than the origin's history values per page."); continue; } - portIndexes.Add(i); - portItems.Add(new OriginHistoryItem(Realm(node), node.Metadata.View.Address.Identifier, BindingTag(node.Metadata.View), - item.AggregateId, item.Continuation)); + pending.Add((i, new OriginHistoryItem(Realm(node), node.Metadata.View.Address.Identifier, BindingTag(node.Metadata.View), + item.AggregateId, continuation))); } - if (portItems.Count > 0) + long used = 0; + for (var start = 0; start < pending.Count; start += subBatch) { + var slice = pending.Skip(start).Take(subBatch).ToArray(); + if (used >= budget) + { + foreach (var (index, portItem) in slice) + { + deferred[index] = true; + results[index] = new(request.Items[index].CorrelationId, 0, [], portItem.Continuation); + } + 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, portItems, deadline.Token) - .ConfigureAwait(false); + 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 = portItems.Select(_ => new OriginHistoryOutcome(0x800A0000u, [], null, false)).ToArray(); + outcomes = slice.Select(_ => new OriginHistoryOutcome(0x800A0000u, [], null, false)).ToArray(); } cancellationToken.ThrowIfCancellationRequested(); // a caller cancel is never a backend outcome - for (var k = 0; k < portIndexes.Count; k++) + for (var k = 0; k < slice.Length; k++) { - var index = portIndexes[k]; - results[index] = ToResult(request.Items[index], nodes[index]!, outcomes[k], details); + 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. @@ -146,9 +176,12 @@ public sealed partial class LocalDataServices { results[i]!.Dispose(); results[i] = new(request.Items[i].CorrelationId, Refused, [], null); + deferred[i] = false; } var final = results.Select(x => x!).ToArray(); - if (chunked) final = Chunk(final, nodes, session, detailsKey, incarnation, Math.Min(limits.ResponseBytes, _capabilities.Limits.MaxMessageBytes)); + final = chunked + ? Chunk(final, nodes, deferred, session, detailsKey, incarnation, budget, RemainderBudget(limits, budget)) + : Direct(final, deferred); return Record(request, final); } finally { _historySessions.Leave(context.PrincipalId); } @@ -159,12 +192,34 @@ public sealed partial class LocalDataServices { ArgumentNullException.ThrowIfNull(continuations); ArgumentNullException.ThrowIfNull(channel); cancellationToken.ThrowIfCancellationRequested(); - if (_catalog() is not { } catalog || catalog.HistoryLimitsFor(context.PrincipalId) is not { } limits) return Task.CompletedTask; - var session = _historySessions.Get(context, channel, Math.Max(1, limits.ConcurrentReads * Math.Max(1, Limits(catalog, context).MaxBatchItems))); + // A release never creates a session: an unknown channel holds nothing to release. + if (_historySessions.TryGet(context, channel) is not { } session) return Task.CompletedTask; foreach (var token in continuations) session.Release(token); return Task.CompletedTask; } + /// Records per session: the principal's concurrent reads × its batch, overflow-safe (both are bounded by the validator). + private static int SessionCapacity(int concurrentReads, int batch) => + (int)Math.Clamp((long)Math.Max(1, concurrentReads) * Math.Max(1, batch), 1L, 1_000_000L); + + /// The per-request response budget in encoded bytes. + private long ResponseBudget(bool chunked, int responseBytes, long callerBytes) => chunked + ? Math.Max(16 * 1024, Math.Min(responseBytes, _capabilities.Limits.MaxMessageBytes) - ResponseMarginBytes) + : Math.Max(16 * 1024, callerBytes); + + /// + /// The principal's retained-remainder budget across ALL its sessions: concurrent reads × max(response budget, one + /// page at 64 B a value). A remainder past it is BadTooManyOperations for that node (explicit, nothing dropped). + /// + private static long RemainderBudget((int ConcurrentReads, int ValuesPerPage, int ResponseBytes) limits, long budget) => + Math.Max(1, limits.ConcurrentReads) * Math.Max(budget, (long)limits.ValuesPerPage * 64L); + + /// Processed: intervals per node (each one value); 1 for other variants. + private static long Buckets(DataHistoryDetails details) => details is DataHistoryProcessedDetails p + && p.StartUtc is { } s && p.EndUtc is { } e && p.ProcessingInterval > TimeSpan.Zero + ? (long)Math.Ceiling(Math.Abs((e - s).Ticks) / (double)p.ProcessingInterval.Ticks) + : 1; + /// The per-item ingress gate (order: catalog/view, export grant + origin ACL, historized). One answer for every refusal. private bool Gate(LocalExportCatalog catalog, DataAuthenticatedContext context, DataView view, out LocalDataNode node) { @@ -241,44 +296,74 @@ public sealed partial class LocalDataServices } /// - /// Splits the response under the byte cap: a result that does not fit keeps what fits, stores the rest as a single-use - /// chunk remainder, and answers ChunkContinues with the chunk token; the final chunk carries the real status and - /// page continuation. A remainder the session cannot hold is BadTooManyOperations (never a silent truncation). + /// Transport split under the response budget, sized from the real encoded size. A result that does not fit keeps + /// what fits and stores the rest as a single-use chunk (its bytes charged to the principal's remainder budget); a node + /// not read because the budget was spent is stored as a DEFERRED chunk (no bytes) and read on resume. Either way the + /// answer is ChunkContinues + the chunk token, and the final chunk carries the real status and page + /// 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, OriginHistorySession session, - string detailsKey, string incarnation, int capBytes) + private static DataHistoryReadResult[] Chunk(DataHistoryReadResult[] results, LocalDataNode?[] nodes, bool[] deferred, + OriginHistorySession session, string detailsKey, string incarnation, long budget, long remainderBudget) { - long budget = Math.Max(16 * 1024, capBytes - ResponseMarginBytes); long used = 0; - var anySample = false; for (var i = 0; i < results.Length; i++) { var result = results[i]; - used += 128 + 2L * (result.CorrelationId.Length + (result.Diagnostic?.Length ?? 0)); - var fit = 0; - foreach (var sample in result.Samples) + used += 32 + 3L * (result.CorrelationId.Length + (result.Diagnostic?.Length ?? 0)); + if (deferred[i]) { - var size = SampleBytes(sample); - if (used + size > budget && (anySample || fit > 0)) break; - used += size; fit++; anySample = true; - } - if (fit == result.Samples.Count) continue; - var node = nodes[i]!; - var remaining = result.Samples.Skip(fit).ToArray(); - var token = session.SaveChunk(new OriginHistorySession.Chunk(node.Metadata.View, detailsKey, incarnation, remaining, - result.StatusCode, result.Continuation, result.Diagnostic, 0)); - if (token is null) - { - result.Dispose(); - results[i] = new(result.CorrelationId, BadTooManyOperations, [], null, "Origin history session is full."); + var token = session.SaveChunk(new OriginHistorySession.Chunk(nodes[i]!.Metadata.View, detailsKey, incarnation, [], + 0, result.Continuation, null, 0, 0, Deferred: true), remainderBudget); + results[i] = token is null + ? new(result.CorrelationId, BadTooManyOperations, [], null, "Origin history session is full.") + : new(result.CorrelationId, 0, [], token, null, ChunkContinues: true); continue; } - results[i] = new(result.CorrelationId, result.StatusCode, result.Samples.Take(fit).ToArray(), token, null, ChunkContinues: true); + var fit = 0; + var oversized = false; + foreach (var sample in result.Samples) + { + var size = SampleBytes(sample, nodes[i]?.Metadata); + if (size > budget) { oversized = true; break; } + if (used + size > budget) break; + used += size; fit++; + } + if (oversized) + { + result.Dispose(); + results[i] = new(result.CorrelationId, BadTooManyOperations, [], null, "A history value exceeds the origin's response limit."); + 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, + result.StatusCode, result.Continuation, result.Diagnostic, 0, bytes), remainderBudget); + if (saved is null) + { + result.Dispose(); + results[i] = new(result.CorrelationId, BadTooManyOperations, [], null, "Origin history remainder budget is full."); + continue; + } + results[i] = new(result.CorrelationId, result.StatusCode, result.Samples.Take(fit).ToArray(), saved, null, ChunkContinues: true); } return results; } - private static long SampleBytes(DataHistorySample sample) => Math.Max(48, sample.Value.EstimatedRetainedBytes - 192); + /// A direct consumer is never handed chunks: a node deferred by the request budget is BadTooManyOperations. + private static DataHistoryReadResult[] Direct(DataHistoryReadResult[] results, bool[] deferred) + { + for (var i = 0; i < results.Length; i++) + if (deferred[i]) + results[i] = new(results[i].CorrelationId, BadTooManyOperations, [], null, + "Request byte budget spent before this node was read; read it in a later request."); + return results; + } + + /// The encoded wire size of one sample (what the response actually carries), plus its repeated-field framing. + private static long SampleBytes(DataHistorySample sample, DataMetadata? catalog) => + DataHistoryProtoMapper.EncodeSample(sample, catalog).CalculateSize() + 6L; private static DataHistoryReadResult[] Record(DataHistoryReadRequest request, DataHistoryReadResult[] 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 20b9880f6..6f90b1b5c 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OriginHistorySessions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OriginHistorySessions.cs @@ -7,59 +7,84 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// /// The ORIGIN's remote-history session of one (authenticated principal, credential, transport channel): the H1 page /// cursor store plus the transport's chunk remainders (plan §3.2). A peer never reaches another session's tokens; the -/// session is cleared when its channel closes, and idle expiry is the backstop. +/// session is cleared when its channel closes, and idle expiry is the backstop. Remainder BYTES are charged to the +/// principal's budget in , so retained memory is bounded across all its sessions. /// internal sealed class OriginHistorySession { private readonly Lock _gate = new(); private readonly Dictionary _chunks = new(); private readonly TimeProvider _clock; + private readonly OriginHistorySessions _owner; + private CancellationTokenRegistration _closed; - internal OriginHistorySession(string principal, string channelId, int capacity, TimeProvider clock) + internal OriginHistorySession(OriginHistorySessions owner, string principal, string channelId, int capacity, TimeProvider clock) { + _owner = owner; _clock = clock; + Principal = principal; Capacity = capacity; Cursors = new OriginHistoryCursors(principal, channelId, capacity, null, clock); } + /// The owning principal. + public string Principal { get; } + /// The H1 page-continuation store of this session. public OriginHistoryCursors Cursors { get; } /// The most live records of each kind. public int Capacity { get; } - /// Live chunk remainders. + internal void Bind(CancellationTokenRegistration closed) => _closed = closed; + + /// Live chunk records. public int ChunkCount { get { lock (_gate) { Sweep(_clock.GetTimestamp()); return _chunks.Count; } } } - /// A stored remainder of one node's answer: what is left, and the final status/continuation it ends with. + /// + /// A stored part of one node's answer. = the node was not read yet because the response budget + /// was spent: resuming reads it then, from (its original page token, or null = fresh). + /// Otherwise is what is left and the final status/continuation it ends with. + /// internal sealed record Chunk(DataView View, string DetailsKey, string Incarnation, IReadOnlyList Remaining, - uint StatusCode, byte[]? Continuation, string? Diagnostic, long SavedAt); + uint StatusCode, byte[]? Continuation, string? Diagnostic, long SavedAt, long Bytes = 0, bool Deferred = false); - /// Stores a remainder; null when the session is full (the caller answers BadTooManyOperations, never truncates). - public byte[]? SaveChunk(Chunk chunk) + /// + /// Stores a chunk; null when the session is full or the principal's remainder byte budget is spent (the caller answers + /// BadTooManyOperations, never a silent truncation). + /// + public byte[]? SaveChunk(Chunk chunk, long budgetBytes) { + if (!_owner.TryReserve(Principal, chunk.Bytes, budgetBytes)) return null; var token = RandomNumberGenerator.GetBytes(16); lock (_gate) { Sweep(_clock.GetTimestamp()); - if (_chunks.Count >= Capacity) return null; + if (_chunks.Count >= Capacity) + { + _owner.ReleaseBytes(Principal, chunk.Bytes); + return null; + } _chunks[new Guid(token)] = chunk with { SavedAt = _clock.GetTimestamp() }; } return token; } - /// Takes (single-use) a remainder; null when the token is not a live chunk token. + /// Takes (single-use) a chunk; null when the token is not a live chunk token. Its bytes are released. public Chunk? TakeChunk(byte[]? token) { if (token is not { Length: 16 }) return null; + Chunk? chunk; lock (_gate) { Sweep(_clock.GetTimestamp()); - return _chunks.Remove(new Guid(token), out var chunk) ? chunk : null; + if (!_chunks.Remove(new Guid(token), out chunk)) return null; } + _owner.ReleaseBytes(Principal, chunk.Bytes); + return chunk; } /// Releases a chunk or a page token (idempotent). @@ -72,10 +97,11 @@ internal sealed class OriginHistorySession /// Drops everything (the channel closed or the session was evicted). public void Clear() { + _closed.Unregister(); Cursors.Clear(); Chunk[] dropped; lock (_gate) { dropped = _chunks.Values.ToArray(); _chunks.Clear(); } - foreach (var chunk in dropped) foreach (var sample in chunk.Remaining) sample.Dispose(); + foreach (var chunk in dropped) Drop(chunk); } private void Sweep(long now) @@ -84,28 +110,49 @@ internal sealed class OriginHistorySession if (_clock.GetElapsedTime(chunk.SavedAt, now) >= Cursors.IdleExpiry) { _chunks.Remove(id); - foreach (var sample in chunk.Remaining) sample.Dispose(); + Drop(chunk); } } + + private void Drop(Chunk chunk) + { + _owner.ReleaseBytes(Principal, chunk.Bytes); + foreach (var sample in chunk.Remaining) sample.Dispose(); + } } /// -/// Every live of this origin, keyed by (principal, credential, channel), bounded, -/// plus the per-principal history admission counter (MaxConcurrentHistoryReads). +/// Every live of this origin, keyed by (principal, credential, channel), plus the +/// per-principal history admission counter (MaxConcurrentHistoryReads) and retained-remainder byte budget. +/// Bounded per principal (; past it the principal's own least-recently-used +/// session is evicted) and globally (; past it the oldest session of the principal holding the +/// most is evicted), so one principal cannot evict another's sessions while it stays within its own cap. /// -internal sealed class OriginHistorySessions(TimeProvider clock, int maxSessions = 4096) +internal sealed class OriginHistorySessions(TimeProvider clock, int maxSessions = 4096, int maxSessionsPerPrincipal = 64) { private readonly Lock _gate = new(); private readonly Dictionary _sessions = new(StringComparer.Ordinal); private readonly Dictionary _inFlight = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _retained = new(StringComparer.OrdinalIgnoreCase); + + public int MaxSessions { get; } = maxSessions; + public int MaxSessionsPerPrincipal { get; } = maxSessionsPerPrincipal; + + private static string Key(DataAuthenticatedContext caller, DataHistoryChannel channel) => + string.Join('\0', caller.PrincipalId.ToUpperInvariant(), caller.ApiKeyId, caller.CredentialVersion, channel.ChannelId); + + /// The existing session of a channel, or null (a release never creates one). + public OriginHistorySession? TryGet(DataAuthenticatedContext caller, DataHistoryChannel channel) + { + lock (_gate) return _sessions.TryGetValue(Key(caller, channel), out var existing) ? existing.Session : null; + } /// The session of one channel, created on first use and cleared when fires. public OriginHistorySession Get(DataAuthenticatedContext caller, DataHistoryChannel channel, int capacity) { - var key = string.Join('\0', caller.PrincipalId.ToUpperInvariant(), caller.ApiKeyId, caller.CredentialVersion, channel.ChannelId); - OriginHistorySession? evicted = null; + var key = Key(caller, channel); + var evicted = new List(); OriginHistorySession session; - var created = false; lock (_gate) { if (_sessions.TryGetValue(key, out var existing) && existing.Session.Capacity == capacity) @@ -113,26 +160,62 @@ internal sealed class OriginHistorySessions(TimeProvider clock, int maxSessions _sessions[key] = (existing.Session, clock.GetTimestamp()); return existing.Session; } - if (_sessions.Remove(key, out var resized)) evicted = resized.Session; - else if (_sessions.Count >= maxSessions) + if (_sessions.Remove(key, out var resized)) evicted.Add(resized.Session); + var own = _sessions.Where(x => string.Equals(x.Value.Session.Principal, caller.PrincipalId, StringComparison.OrdinalIgnoreCase)).ToList(); + while (own.Count >= MaxSessionsPerPrincipal) { - var oldest = _sessions.MinBy(x => x.Value.Used); + var oldest = own.MinBy(x => x.Value.Used); + own.Remove(oldest); _sessions.Remove(oldest.Key); - evicted = oldest.Value.Session; + evicted.Add(oldest.Value.Session); } - session = new OriginHistorySession(caller.PrincipalId, channel.ChannelId, capacity, clock); + if (_sessions.Count >= MaxSessions) + { + // The principal holding the most sessions pays (never one within its cap while another exceeds the average). + var heaviest = _sessions.GroupBy(x => x.Value.Session.Principal, StringComparer.OrdinalIgnoreCase) + .MaxBy(g => g.Count())!.MinBy(x => x.Value.Used); + _sessions.Remove(heaviest.Key); + evicted.Add(heaviest.Value.Session); + } + session = new OriginHistorySession(this, caller.PrincipalId, channel.ChannelId, capacity, clock); _sessions[key] = (session, clock.GetTimestamp()); - created = true; } - evicted?.Clear(); - if (created && channel.Closed.CanBeCanceled) - channel.Closed.Register(() => Close(key, session)); + foreach (var old in evicted) old.Clear(); + if (channel.Closed.CanBeCanceled) session.Bind(channel.Closed.Register(() => Close(key, session))); return session; } /// Live sessions (diagnostics/tests). public int Count { get { lock (_gate) return _sessions.Count; } } + /// Remainder bytes retained for across its sessions. + public long RetainedBytes(string principal) { lock (_gate) return _retained.GetValueOrDefault(principal); } + + /// Reserves remainder bytes against the principal's budget; false when it would be exceeded. + public bool TryReserve(string principal, long bytes, long budget) + { + if (bytes <= 0) return true; + lock (_gate) + { + var current = _retained.GetValueOrDefault(principal); + if (current + bytes > budget) return false; + _retained[principal] = current + bytes; + return true; + } + } + + /// Returns reserved remainder bytes. + public void ReleaseBytes(string principal, long bytes) + { + if (bytes <= 0) return; + lock (_gate) + { + var left = _retained.GetValueOrDefault(principal) - bytes; + if (left > 0) _retained[principal] = left; + else _retained.Remove(principal); + } + } + /// Admits one history request of ; false past . public bool TryAdmit(string principal, int limit) { 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 f54674c0b..3ed4df031 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 @@ -129,7 +129,7 @@ public sealed class GrpcDataHistoryWireTests item.Samples[1].SourceTimestamp.ShouldBeNull(); item.Samples[1].StatusCode.ShouldBe(0x80000000u); } - origin.History.LastItems.Select(x => (x.Realm, x.Identifier)).ShouldBe( + origin.History.AllItems.Select(x => (x.Realm, x.Identifier)).ShouldBe( [(AddressSpaceRealm.Raw, "Plant/Modbus/dev1/Flow"), (AddressSpaceRealm.Uns, "Area1/Line1/Filler/FlowRate")]); var raw = origin.History.LastDetails.ShouldBeOfType(); raw.NumValuesPerNode.ShouldBe(10_000u, "an uncapped read pages at the export's per-page ceiling"); @@ -267,6 +267,95 @@ public sealed class GrpcDataHistoryWireTests await Should.ThrowAsync(() => none.HistoryAsync(Raw(I("a", RealOriginRequests.Flow)), History, existing: refused)); DataConnectionGrpcService.CallFeatures(refused).ShouldBe(new DataCallFeatures(DataFeatures.History, DataFeatures.None)); } + + [Fact] + public async Task Origin_memory_is_bounded_per_request_and_per_principal_and_nothing_is_lost() + { + await using var origin = new RealOrigin(responseBytes: 256 * 1024, valuesPerPage: 2000); + origin.History!.SamplesPerItem = 2000; + var request = DataHistoryProtoMapper.EncodeRequest(new DataHistoryReadRequest(new DataHistoryRawDetails(T0, T0.AddHours(1), 0, false), + Enumerable.Range(0, 100).Select(i => I("i" + i, RealOriginRequests.Flow)).ToArray(), Budget with { MaxItems = 100 })); + var first = await origin.HistoryAsync(request, History); + first.CalculateSize().ShouldBeLessThanOrEqualTo(256 * 1024); + // Only what the response budget can carry (plus at most one sub-batch) was read; the rest is deferred, unread. + origin.History.ValuesReturned.ShouldBeLessThanOrEqualTo(10 * 2000); + first.Items.Count(x => x.ChunkContinues && x.Samples.Count == 0).ShouldBeGreaterThan(80, "most nodes deferred, not materialised"); + var retainedBudget = 4L * Math.Max(256 * 1024 - 64 * 1024, 2000L * 64); + origin.Services.HistoryRetainedBytes("peer").ShouldBeLessThanOrEqualTo(retainedBudget); + // Following every chunk token delivers every value exactly once. + var counts = new long[100]; + var page = first; + var rounds = 0; + while (true) + { + var next = request.Clone(); next.Items.Clear(); + for (var k = 0; k < page.Items.Count; k++) + { + var item = page.Items[k]; + var index = int.Parse(item.CorrelationId[1..], System.Globalization.CultureInfo.InvariantCulture); + item.StatusCode.ShouldBe(0u); + counts[index] += item.Samples.Count; + if (item.ChunkContinues) next.Items.Add(new W.HistoryReadItem { CorrelationId = item.CorrelationId, View = request.Items[index].View, Continuation = item.Continuation }); + } + origin.Services.HistoryRetainedBytes("peer").ShouldBeLessThanOrEqualTo(retainedBudget); + if (next.Items.Count == 0) break; + page = await origin.HistoryAsync(next, History); + page.CalculateSize().ShouldBeLessThanOrEqualTo(256 * 1024); + (++rounds).ShouldBeLessThan(500); + } + counts.ShouldAllBe(c => c == 2000); + origin.Services.HistoryRetainedBytes("peer").ShouldBe(0, "every remainder was taken"); + } + + [Fact] + public async Task Processed_intervals_and_AtTime_times_above_the_page_ceiling_are_refused_unsent() + { + await using var origin = new RealOrigin(valuesPerPage: 2000); + var processed = DataHistoryProtoMapper.EncodeRequest(new DataHistoryReadRequest( + new DataHistoryProcessedDetails(T0, T0.AddHours(1), TimeSpan.FromSeconds(1), null), + [new("a", RealOriginRequests.Flow, DataHistoryAggregates.IdByName["Average"])], Budget)); + (await origin.HistoryAsync(processed, History)).Items.Single().StatusCode.ShouldBe(0x80100000u); + var times = Enumerable.Range(0, 2001).Select(i => T0.AddSeconds(i)).ToArray(); + var atTime = DataHistoryProtoMapper.EncodeRequest(new DataHistoryReadRequest(new DataHistoryAtTimeDetails(times), + [I("a", RealOriginRequests.Flow), I("b", RealOriginRequests.UnsFlow)], Budget)); + (await origin.HistoryAsync(atTime, History)).Items.Select(x => x.StatusCode).ShouldBe([0x80100000u, 0x80100000u]); + origin.History!.Calls.ShouldBe(0); + // Within the ceiling the same shapes are served. + var within = DataHistoryProtoMapper.EncodeRequest(new DataHistoryReadRequest( + new DataHistoryProcessedDetails(T0, T0.AddHours(1), TimeSpan.FromSeconds(2), null), + [new("a", RealOriginRequests.Flow, DataHistoryAggregates.IdByName["Average"])], Budget)); + (await origin.HistoryAsync(within, History)).Items.Single().StatusCode.ShouldBe(0u); + } + + [Fact] + public async Task A_single_value_larger_than_the_response_limit_is_answered_per_item() + { + await using var origin = new RealOrigin(responseBytes: 1); + origin.History!.AlsoHistorized.Add("Plant/Modbus/dev1/Label"); + origin.History.Samples = [new(new string('x', 40_000), 0, T0.UtcDateTime, null)]; + var response = await origin.HistoryAsync(Raw(I("label", RealOriginRequests.Label)), History); + var item = response.Items.Single(); + item.StatusCode.ShouldBe(0x80100000u); + item.Diagnostic.ShouldContain("exceeds"); + item.Samples.ShouldBeEmpty(); + } + + [Fact] + public async Task A_direct_consumer_gets_BadTooManyOperations_for_nodes_past_its_request_budget() + { + await using var origin = new RealOrigin(valuesPerPage: 2000); + origin.History!.SamplesPerItem = 2000; + await using var connection = origin.Connect(); + var history = (IDataHistoryService)connection; + 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.Last().StatusCode.ShouldBe(0x80100000u); + results.ShouldAllBe(r => !r.ChunkContinues); + origin.History.ValuesReturned.ShouldBeLessThanOrEqualTo(10 * 2000); + foreach (var r in results) r.Dispose(); + } } /// A scripted node-manager history port: Flow (raw) and FlowRate (UNS) are historized. @@ -285,12 +374,22 @@ internal sealed class FakeHistoryPort : IOriginHistoryPort public int Calls => Volatile.Read(ref _calls); public int HistorizedLookups => Volatile.Read(ref _lookups); public IReadOnlyList LastItems { get; private set; } = []; + private readonly List _all = []; + /// Every item the port was asked for, across calls (the origin reads in sub-batches). + public IReadOnlyList AllItems { get { lock (_all) return _all.ToArray(); } } 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; } + /// 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. + public HashSet AlsoHistorized { get; } = []; + private long _values; public bool IsHistorized(AddressSpaceRealm realm, string identifier) { Interlocked.Increment(ref _lookups); - return (realm == AddressSpaceRealm.Raw && identifier == "Plant/Modbus/dev1/Flow") + return (realm == AddressSpaceRealm.Raw && (identifier == "Plant/Modbus/dev1/Flow" || AlsoHistorized.Contains(identifier))) || (realm == AddressSpaceRealm.Uns && identifier == "Area1/Line1/Filler/FlowRate"); } @@ -299,6 +398,7 @@ internal sealed class FakeHistoryPort : IOriginHistoryPort { Interlocked.Increment(ref _calls); LastItems = items; LastDetails = details; + lock (_all) _all.AddRange(items); _entered.TrySetResult(); if (Hold is { } hold) await hold.WaitAsync(cancellationToken); await Task.Yield(); @@ -309,7 +409,14 @@ internal sealed class FakeHistoryPort : IOriginHistoryPort if (item.Continuation is { } token && !_issued.TryRemove(Convert.ToHexString(token), out _)) return new OriginHistoryOutcome(0x804A0000u, [], null, false); if (Continuation is { } next) _issued[Convert.ToHexString(next)] = true; - return new OriginHistoryOutcome(0, Samples, Continuation, false); + IReadOnlyList samples = Samples; + 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(); + } + Interlocked.Add(ref _values, samples.Count); + return new OriginHistoryOutcome(0, samples, Continuation, false); }).ToArray(); } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1RealOriginCompatibilityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1RealOriginCompatibilityTests.cs index 224c4d746..f43853e49 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1RealOriginCompatibilityTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1RealOriginCompatibilityTests.cs @@ -251,7 +251,7 @@ internal sealed class RealOrigin : IAsyncDisposable internal FakeHistoryPort? History { get; } internal RealOrigin(DataOperations exportOperations = DataOperationSets.V1, bool historian = true, int concurrentReads = 4, - int responseBytes = 4 * 1024 * 1024, NodePermissions permissions = NodePermissions.Operator) + int responseBytes = 4 * 1024 * 1024, NodePermissions permissions = NodePermissions.Operator, int valuesPerPage = 10_000) { History = historian ? new FakeHistoryPort() : null; var fence = new DataWriteDispatchFence(); @@ -268,7 +268,7 @@ internal sealed class RealOrigin : IAsyncDisposable Serving = new ServingIdentity("node-a", Incarnation, "Primary", epoch, authority.Current.GenerationId, 1); if (Serving.CatalogEpoch != CatalogEpoch) throw new InvalidOperationException("Catalog epoch is no longer deterministic."); // H2 new-shape data: every export also grants HistoryRead (header-less callers must never see it). - var catalog = LocalExportCatalog.Compile(Snapshot(exportOperations | DataOperations.HistoryRead, concurrentReads, responseBytes), + var catalog = LocalExportCatalog.Compile(Snapshot(exportOperations | DataOperations.HistoryRead, concurrentReads, responseBytes, valuesPerPage), Serving, activation.CaptureAuthority()); _hub = new PartitionedSampleHub(new DataResourceLimits @@ -305,7 +305,7 @@ internal sealed class RealOrigin : IAsyncDisposable internal IReadOnlyList Dispatched => _route.Dispatched; - private static DraftSnapshot Snapshot(DataOperations operations, int concurrentReads, int responseBytes) + private static DraftSnapshot Snapshot(DataOperations operations, int concurrentReads, int responseBytes, int valuesPerPage) { Tag Tag(string id, string name, string type, TagAccessLevel access = TagAccessLevel.Read, string config = "{}") => new() { TagId = id, DeviceId = "device-1", Name = name, DataType = type, AccessLevel = access, TagConfig = config }; @@ -339,10 +339,10 @@ internal sealed class RealOrigin : IAsyncDisposable [ new() { DataExportId = "export-raw", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "Cluster", RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = operations, - MaxConcurrentHistoryReads = concurrentReads, MaxHistoryResponseBytes = responseBytes }, + MaxConcurrentHistoryReads = concurrentReads, MaxHistoryResponseBytes = responseBytes, MaxHistoryValuesPerPage = valuesPerPage }, new() { DataExportId = "export-uns", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = "Cluster", RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = operations, - MaxConcurrentHistoryReads = concurrentReads, MaxHistoryResponseBytes = responseBytes }, + MaxConcurrentHistoryReads = concurrentReads, MaxHistoryResponseBytes = responseBytes, MaxHistoryValuesPerPage = valuesPerPage }, ], }; } 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 new file mode 100644 index 000000000..897d100d3 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataOriginHistorySessionTests.cs @@ -0,0 +1,71 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// H2 review: origin history sessions are bounded per principal and a principal cannot evict another's. +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H2")] +public sealed class GrpcDataOriginHistorySessionTests +{ + private static DataAuthenticatedContext Caller(string principal) => new(principal, "key-" + principal, "v1", null, 1); + private static DataHistoryChannel Channel(string id, CancellationTokenSource? closed = null) => new(id, closed?.Token ?? CancellationToken.None); + + [Fact] + public void A_principal_past_its_cap_evicts_its_own_oldest_session_never_another_principals() + { + var sessions = new OriginHistorySessions(TimeProvider.System, maxSessions: 100, maxSessionsPerPrincipal: 3); + var victim = sessions.Get(Caller("b"), Channel("b-1"), 4); + var a = Enumerable.Range(0, 3).Select(i => sessions.Get(Caller("a"), Channel("a-" + i), 4)).ToArray(); + sessions.Get(Caller("a"), Channel("a-3"), 4); + sessions.Count.ShouldBe(4, "a stays at its cap of 3, b keeps its one"); + sessions.TryGet(Caller("a"), Channel("a-0")).ShouldBeNull("a's least-recently-used session went"); + sessions.TryGet(Caller("b"), Channel("b-1")).ShouldBeSameAs(victim); + a[1].ShouldBeSameAs(sessions.TryGet(Caller("a"), Channel("a-1"))); + } + + [Fact] + public void At_the_global_cap_the_principal_holding_the_most_sessions_pays() + { + var sessions = new OriginHistorySessions(TimeProvider.System, maxSessions: 4, maxSessionsPerPrincipal: 10); + for (var i = 0; i < 3; i++) sessions.Get(Caller("heavy"), Channel("h-" + i), 4); + var light = sessions.Get(Caller("light"), Channel("l-0"), 4); + sessions.Get(Caller("light"), Channel("l-1"), 4); + sessions.Count.ShouldBe(4); + sessions.TryGet(Caller("light"), Channel("l-0")).ShouldBeSameAs(light); + sessions.TryGet(Caller("heavy"), Channel("h-0")).ShouldBeNull(); + } + + [Fact] + public void Lookup_for_a_release_never_creates_a_session_and_a_closed_channel_clears_and_unregisters() + { + var sessions = new OriginHistorySessions(TimeProvider.System); + sessions.TryGet(Caller("a"), Channel("x")).ShouldBeNull(); + sessions.Count.ShouldBe(0); + using var closed = new CancellationTokenSource(); + var session = sessions.Get(Caller("a"), Channel("c", closed), 4); + session.SaveChunk(new OriginHistorySession.Chunk(new(new("c", "u", "string", "x"), DataRealm.Raw, null, 0, "x"), "k", "i", [], 0, null, null, 0, 100), + 1000).ShouldNotBeNull(); + sessions.RetainedBytes("a").ShouldBe(100); + closed.Cancel(); + sessions.Count.ShouldBe(0); + sessions.RetainedBytes("a").ShouldBe(0, "clearing a session returns its remainder bytes"); + } + + [Fact] + public void Remainder_bytes_are_budgeted_per_principal_across_sessions() + { + var sessions = new OriginHistorySessions(TimeProvider.System); + var view = new DataView(new("c", "u", "string", "x"), DataRealm.Raw, null, 0, "x"); + OriginHistorySession.Chunk Chunk(long bytes) => new(view, "k", "i", [], 0, null, null, 0, bytes); + var one = sessions.Get(Caller("a"), Channel("1"), 8); + var two = sessions.Get(Caller("a"), Channel("2"), 8); + var other = sessions.Get(Caller("b"), Channel("3"), 8); + var token = one.SaveChunk(Chunk(600), 1000).ShouldNotBeNull(); + two.SaveChunk(Chunk(600), 1000).ShouldBeNull("the principal's budget spans its sessions"); + other.SaveChunk(Chunk(600), 1000).ShouldNotBeNull("another principal has its own budget"); + one.TakeChunk(token).ShouldNotBeNull(); + two.SaveChunk(Chunk(600), 1000).ShouldNotBeNull("taking a chunk returned its bytes"); + } +}