using System.Globalization; using System.Text; using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.OpcUaServer; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// /// H2 origin ingress for remote HistoryRead (plan §3.2, §6). The order per item is: the caller and catalog are ready /// for this target (ReadyReplica allowed), the export grants HistoryRead on the view, the origin ACL grants /// HistoryRead on the view (always, whatever Security:Acl:Enabled says), and only then the historian /// tagname is looked up. A refusal at ANY of those steps — unknown view, folder, not exported, denied, not historized — /// is the same answer with no backend call, so a peer cannot tell denied from unhistorized. /// public sealed partial class LocalDataServices { /// The single answer for every per-item refusal (denied ≡ unhistorized ≡ unknown). internal const uint Refused = 0x80720000u; // Bad_HistoryOperationUnsupported internal const uint BadTooManyOperations = 0x80100000u; internal const uint BadInternalError = 0x80020000u; internal const uint BadContinuationPointInvalid = 0x804A0000u; private const int ResponseMarginBytes = 64 * 1024; private DataConnectionHistoryDiagnostics? _historyDiagnostics; /// /// H4: where origin history answers are counted and this origin's live history state is reported (diagnostics and the /// otopcua.dataconn.history.* metrics). Before H4 the counter sat on a private meter the host never exported. /// public DataConnectionHistoryDiagnostics? HistoryDiagnostics { get => _historyDiagnostics; init { _historyDiagnostics = value; value?.AttachOrigin(() => (HistoryServing is not null, HistorySessionCount, HistoryOpenContinuations)); } } private readonly IOriginHistoryPort? _history; private readonly OriginHistorySessions _historySessions; /// What this origin can serve remotely; null without a historian backend (then nothing is advertised). internal OriginHistoryServing? HistoryServing { get { try { return _history?.Serving; } catch (Exception) { return null; } } } /// Live history sessions (diagnostics/tests). internal int HistorySessionCount => _historySessions.Count; /// Open origin continuations (page cursors + chunk remainders) across every session (diagnostics/tests). public int HistoryOpenContinuations => _historySessions.OpenContinuations; /// 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); private static AddressSpaceRealm Realm(LocalDataNode node) => node.Metadata.View.Realm == DataRealm.Raw ? AddressSpaceRealm.Raw : AddressSpaceRealm.Uns; /// The caller's history capabilities, when HistoryRead is among its operations. /// /// Present whenever this origin HAS a historian (H2 review): negotiation is header ∩ supported ∩ origin-has-historian, /// and readiness / grants are answered by the RPC's Ready(…, HistoryRead) (Unavailable / PermissionDenied), so a /// not-ready or demoted endpoint makes the consumer fail over exactly like a v1 Read, instead of "unsupported". /// The limits are the principal's export limits, or the schema defaults when no export grants it history. /// internal DataHistoryCapabilities? HistoryCapabilitiesFor(LocalExportCatalog? catalog, DataAuthenticatedContext context) { if (HistoryServing is not { } serving) return null; // Without a HistoryRead grant on some export the peer learns that history exists here, and nothing about it. if (catalog?.HistoryLimitsFor(context.PrincipalId) is not { } limits) return new DataHistoryCapabilities(false, false, false, [], 0, 10_000, 4, PeerHistoryIdle); return new DataHistoryCapabilities(true, serving.Aggregates.Count > 0, true, serving.Aggregates, serving.TimestampResolutionTicks, limits.ValuesPerPage, limits.ConcurrentReads, PeerHistoryIdle); } /// The origin continuation idle expiry advertised to peers (the H1 store default). internal static readonly TimeSpan PeerHistoryIdle = TimeSpan.FromSeconds(60); /// /// The serving identity a peer continuation binds: process incarnation + serving generation + role, so an origin /// restart, a failover or a role change on a still-open channel invalidates its tokens (H1 review note). /// private string ServingIncarnation() { var serving = _catalog()?.Serving ?? throw new InvalidOperationException("No serving catalog."); return string.Create(CultureInfo.InvariantCulture, $"{serving.Incarnation}/{serving.ServingGeneration}/{serving.Role}"); } internal async Task> ReadHistoryAsync(DataAuthenticatedContext context, DataTarget target, DataHistoryReadRequest request, DataHistoryChannel channel, bool chunked, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Items); ArgumentNullException.ThrowIfNull(request.Details); ArgumentNullException.ThrowIfNull(channel); var catalog = _catalog(); 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, 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)); var results = new DataHistoryReadResult?[request.Items.Count]; try { var session = _historySessions.Get(context, channel, SessionCapacity(limits.ConcurrentReads, batchLimit)); var incarnation = ServingIncarnation(); // 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 nodes = new LocalDataNode?[request.Items.Count]; 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, 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 } var values = ValuesPerNode(details); if (details is not DataHistoryRawDetails && (values > limits.ValuesPerPage || values * valueBytes > budget)) { 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), 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; foreach (var group in pending.GroupBy(x => keys[x.Index]!)) { 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) { var slice = members.Skip(start).Take(subBatch).ToArray(); if (used >= budget || deadline.IsCancellationRequested) { 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); } } } // Authority may have moved while the backend answered: re-check every served item before handing anything back. for (var i = 0; i < results.Length; i++) 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] = Deferral.None; } var final = results.Select(x => x!).ToArray(); final = chunked ? 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) { ArgumentNullException.ThrowIfNull(continuations); ArgumentNullException.ThrowIfNull(channel); cancellationToken.ThrowIfCancellationRequested(); // 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) { if (!catalog.TryResolve(view, out node) || node.Source is null || !node.Supported) return false; if (!Allowed(catalog, context, node, DataOperations.HistoryRead)) return false; return IsHistorized(node); } 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; private static void ValidateDetails(DataHistoryReadRequest request) { switch (request.Details) { case DataHistoryProcessedDetails processed when processed.ProcessingInterval < TimeSpan.Zero: throw new ArgumentOutOfRangeException(nameof(request), "Negative processing interval."); case DataHistoryAtTimeDetails atTime when atTime.RequestedTimesUtc is null: throw new ArgumentException("Missing requested times.", nameof(request)); case DataHistoryRawDetails or DataHistoryProcessedDetails or DataHistoryAtTimeDetails: return; default: throw new ArgumentException("Unsupported history details.", nameof(request)); } } private static string DetailsKey(DataHistoryDetails details) => details switch { DataHistoryRawDetails r => string.Create(CultureInfo.InvariantCulture, $"raw|{r.StartUtc?.UtcTicks}|{r.EndUtc?.UtcTicks}|{r.NumValuesPerNode}|{r.ReturnBounds}"), DataHistoryProcessedDetails p => string.Create(CultureInfo.InvariantCulture, $"processed|{p.StartUtc?.UtcTicks}|{p.EndUtc?.UtcTicks}|{p.ProcessingInterval.Ticks}|{p.Configuration}"), DataHistoryAtTimeDetails a => "attime|" + a.UseSimpleBounds + "|" + string.Join(',', a.RequestedTimesUtc.Select(t => t.UtcTicks.ToString(CultureInfo.InvariantCulture))), _ => throw new ArgumentException("Unsupported history details."), }; /// Maps a port outcome; Raw/AtTime values whose kind disagrees with the catalog are BadTypeMismatch, never coerced. private DataHistoryReadResult ToResult(DataHistoryReadItem item, LocalDataNode node, OriginHistoryOutcome outcome, DataHistoryDetails details) { if (outcome.WiringFault) { // A miswired continuation scope is a SERVER fault: distinct from denied/unsupported, logged, never retried as "no history". Logger.LogWiringFault(node.Metadata.View.Address.Identifier); return new(item.CorrelationId, BadInternalError, [], null, "Origin history continuation wiring fault."); } var checkKind = details is not DataHistoryProcessedDetails; var samples = new List(outcome.Samples.Count); foreach (var sample in outcome.Samples) { DataValue value; var status = sample.StatusCode; try { value = OwnedDataSample.Copy(sample.Value); } catch (ArgumentException) { value = DataValue.Null(); status = DataHistoryProtoMapper.BadTypeMismatch; } if (checkKind && !DataHistoryProtoMapper.KindMatches(node.Metadata, value)) { value.Dispose(); value = DataValue.Null(); status = DataHistoryProtoMapper.BadTypeMismatch; } samples.Add(new DataHistorySample(value, status, OwnedDataSample.Timestamp(sample.SourceTimestampUtc), OwnedDataSample.Timestamp(sample.ServerTimestampUtc))); } return new(item.CorrelationId, outcome.StatusCode, samples, outcome.Continuation); } /// /// 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, 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] != Deferral.None) { 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); continue; } 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) { session.Cursors.Release(result.Continuation); result.Dispose(); 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, 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; retry with a lower NumValuesPerNode."); continue; } results[i] = new(result.CorrelationId, result.StatusCode, result.Samples.Take(fit).ToArray(), saved, null, ChunkContinues: true); } return results; } /// A direct consumer is never handed chunks: a node deferred by the request budget is BadTooManyOperations. private static DataHistoryReadResult[] Direct(DataHistoryReadResult[] results, Deferral[] deferred) { for (var i = 0; i < results.Length; 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; } /// 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 DataHistoryReadResult[] Record(DataHistoryReadRequest request, DataHistoryReadResult[] results) { var variant = DataConnectionHistoryDiagnostics.Variant(request.Details); foreach (var result in results) { if (_historyDiagnostics is { } diagnostics) diagnostics.RecordOriginRead(variant, result.StatusCode); else DataConnectionHistoryDiagnostics.Count(DataConnectionHistoryDiagnostics.OriginSide, variant, result.StatusCode); } return results; } } /// History log helpers (kept out of the hot path). internal static class LocalDataServicesHistoryLog { public static void LogWiringFault(this Microsoft.Extensions.Logging.ILogger logger, string identifier) => Microsoft.Extensions.Logging.LoggerExtensions.LogError(logger, "Remote HistoryRead continuation scope is miswired for {Identifier}; answered BadInternalError", identifier); }