using System.Buffers.Binary; using System.Text; using Google.Protobuf; using Grpc.Core; using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// /// H2 consumer side of remote history (plan §3.2, §3.3). The connection sends history on a call only when /// the selected endpoint advertised it; each call's deadline is min(the caller's remaining budget, the connection's /// HistoryTimeoutMilliseconds); FAILED_PRECONDITION / UNIMPLEMENTED (a v1 origin, or one without a historian) /// answer BadHistoryOperationUnsupported. A fresh read may move endpoint; a RESUMED read never moves — its /// token is wrapped with the endpoint and serving incarnation that issued it. Transport chunks are assembled here /// within the request's byte budget, so a caller never sees . /// public sealed partial class GrpcDataConnection : IDataHistoryService { internal const uint BadHistoryOperationUnsupported = 0x80720000u; internal const uint BadContinuationPointInvalid = 0x804A0000u; internal const uint BadTooManyOperations = 0x80100000u; internal const uint BadTimeout = 0x800A0000u; internal const uint BadNoCommunication = 0x80310000u; /// An origin admits at most one item per this many bytes of a request's byte budget (LocalDataServices.CheckBudget). internal const long MinimumBytesPerItem = 256; private const byte EnvelopeTag = 0xC7, EnvelopeVersion = 1; private TimeSpan _historyTimeout = TimeSpan.FromSeconds(30); /// The per-call history ceiling (the connection's HistoryTimeoutMilliseconds). public TimeSpan HistoryTimeout { get => _historyTimeout; init => _historyTimeout = value > TimeSpan.Zero ? value : throw new ArgumentOutOfRangeException(nameof(value)); } /// The features this consumer understands; sent on every capabilities probe (coordinator decision, plan §4.1). internal const DataFeatures ClientFeatures = DataFeatures.History; // Explicit: IDataReadService.ReadAsync(ReadRequest) shares the name, and target-typed `new(...)` callers must stay unambiguous. Task> IDataHistoryService.ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) => ReadHistoryAsync(request, cancellationToken); Task IDataHistoryService.ReleaseAsync(IReadOnlyList continuations, CancellationToken cancellationToken) => ReleaseHistoryAsync(continuations, cancellationToken); /// Remote HistoryRead (). public async Task> ReadHistoryAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Items); request.Budget.Validate(); var start = Clock.GetTimestamp(); EnterWork(); var admitted = false; try { using var admission = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, _shutdown.Token); admitted = await _unaryCapacity.WaitAsync(0, admission.Token).ConfigureAwait(false); if (!admitted) return All(request, BadTooManyOperations); // A resumed item pins the endpoint (and serving incarnation) that issued its token. var results = new DataHistoryReadResult?[request.Items.Count]; var items = new DataHistoryReadItem[request.Items.Count]; int? pinned = null; string? pinnedServing = null; for (var i = 0; i < items.Length; i++) { var item = request.Items[i]; items[i] = item; if (item.Continuation is null) continue; if (!TryUnwrap(item.Continuation, out var endpoint, out var serving, out var token) || (pinned is { } p && (p != endpoint || pinnedServing != serving)) || endpoint >= _endpoints.Length) { results[i] = new(item.CorrelationId, BadContinuationPointInvalid, [], null); continue; } pinned = endpoint; pinnedServing = serving; items[i] = item with { Continuation = token }; } var pending = Enumerable.Range(0, items.Length).Where(i => results[i] is null).ToArray(); if (pending.Length == 0) return results.Select(x => x!).ToArray(); bool Resumed(int i) => request.Items[i].Continuation is not null; DataHistoryReadResult[] Finish(Func status) { foreach (var i in pending) results[i] ??= new(request.Items[i].CorrelationId, status(i), [], null); return results.Select(x => x!).ToArray(); } // A fresh read honours discovery backoff like every v1 call; a resumed one goes to its issuing endpoint regardless. if (pinned is null && !ProbeAllowed()) return Finish(_ => BadNoCommunication); var candidates = pinned is { } fixedIndex ? [fixedIndex] : Enumerable.Range(0, _endpoints.Length).ToArray(); Exception? failure = null; var unsupported = false; foreach (var index in candidates) { Check(); cancellationToken.ThrowIfCancellationRequested(); Selected selected; // The capability probe is capped by HistoryTimeout too (H3 review), like every history call. try { selected = await SelectAsync(_endpoints[index], start, ProbeBudget(request.Budget), false, cancellationToken).ConfigureAwait(false); ProbeSucceeded(); } catch (Exception ex) when (cancellationToken.IsCancellationRequested && ex is RpcException or OperationCanceledException) { // A caller cancel (a deadline) during the probe is a cancel, never an escaping RpcException (H3 review D1). throw new OperationCanceledException("History read cancelled by the caller.", ex, cancellationToken); } catch (Exception ex) when (!cancellationToken.IsCancellationRequested && ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException or TimeoutException or ArgumentException) { failure = ex; RecordFailure(ex); continue; } if (pinnedServing is not null && pinnedServing != selected.Capabilities.Serving.Incarnation) { // The issuing endpoint restarted or failed over: its tokens are gone; never resume elsewhere. foreach (var i in pending.Where(Resumed)) results[i] = new(request.Items[i].CorrelationId, BadContinuationPointInvalid, [], null); pending = pending.Where(i => results[i] is null).ToArray(); if (pending.Length == 0) return results.Select(x => x!).ToArray(); } if (RequestedFeatures(selected.Capabilities) == DataFeatures.None || !selected.Capabilities.Operations.HasFlag(DataOperations.HistoryRead)) { // A fresh read tries the other endpoints; a pinned one cannot move. unsupported = true; if (pinned is not null) break; continue; } DataHistoryReadResult[]? served; try { served = await ServeSplitAsync(selected, index, request, items, pending, start, cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (!cancellationToken.IsCancellationRequested && ex is InvalidOperationException or ArgumentException or RpcException or HttpRequestException) { // A malformed answer (unexpected items / serving identity, undecodable) is an endpoint failure. failure = ex; RecordFailure(ex); served = null; } if (served is null) { failure ??= new InvalidOperationException("History endpoint unavailable."); if (pinned is not null) break; continue; } for (var k = 0; k < pending.Length; k++) results[pending[k]] = served[k]; return results.Select(x => x!).ToArray(); } if (failure is not null && pinned is null && !unsupported) ProbeFailed(); // Resumed items cannot move; fresh items of the same batch are a communication failure, never an invalid token. return Finish(i => Resumed(i) ? BadContinuationPointInvalid : unsupported ? BadHistoryOperationUnsupported : BadNoCommunication); } finally { if (admitted) _unaryCapacity.Release(); ExitWork(); } } /// /// Reads on one selected endpoint in sub-batches of at most the endpoint's advertised MaxBatchItems — taken from the /// capabilities this call already negotiated, so no extra probe (H3 review round 2). The assembly budget is shared across /// the sub-batches, and each sub-batch carries at most one item per of what is left /// (the origin's admission rule, round 3 S2). Once the budget is spent — exhausted, too small for one more item, or a /// sub-batch's own assembly refused (S3) — the remaining items are BadTooManyOperations marked /// , unsent. Null = the endpoint failed before answering the /// FIRST sub-batch (a fresh read may move); a later failure is recorded, nothing more is sent to that endpoint, and the /// rest is BadNoCommunication (resumed items BadContinuationPointInvalid), never moving a half-served /// request. A resumed item answered unsent has its origin token released (it is still live there). Anything that /// escapes (a caller cancel, a fault) first disposes the collected answers and releases their new continuations (S1). /// private async Task ServeSplitAsync(Selected selected, int endpoint, DataHistoryReadRequest request, DataHistoryReadItem[] items, int[] pending, long start, CancellationToken cancellationToken) { var batch = Math.Max(1, selected.Capabilities.Limits.MaxBatchItems); if (pending.Length <= batch) return (await ServeAsync(selected, endpoint, request, items, pending, start, cancellationToken).ConfigureAwait(false)).Results; var answers = new DataHistoryReadResult?[pending.Length]; long used = 0; bool spent = false, failed = false; try { for (var offset = 0; offset < pending.Length;) { var left = request.Budget.MaxBytes - used; var fitting = spent || failed ? 0 : (int)Math.Min(batch, Math.Max(0, left) / MinimumBytesPerItem); if (fitting <= 0) { for (var k = offset; k < pending.Length; k++) { var item = request.Items[pending[k]]; var resumed = item.Continuation is not null; if (resumed) _ = ReleaseOnEndpointAsync(selected, items[pending[k]].Continuation); // unsent: still live at the origin answers[k] = failed ? new(item.CorrelationId, resumed ? BadContinuationPointInvalid : BadNoCommunication, [], null) : new(item.CorrelationId, BadTooManyOperations, [], null, "History assembly budget exceeded.") { ConsumerBudgetRefused = true }; } break; } var chunk = pending.Skip(offset).Take(fitting).ToArray(); DataHistoryReadResult[]? served; try { var call = await ServeAsync(selected, endpoint, request with { Budget = request.Budget with { MaxBytes = left } }, items, chunk, start, cancellationToken).ConfigureAwait(false); served = call.Results; failed = call.EndpointFailed; // answered, but the endpoint failed or retired mid-way: send it nothing more (nit a) } catch (Exception ex) when (offset > 0 && !cancellationToken.IsCancellationRequested && ex is InvalidOperationException or ArgumentException or RpcException or HttpRequestException) { // An endpoint fault after a served sub-batch: recorded like any endpoint failure (round 3 S6), and the // request stays on this endpoint (half served) with nothing more sent to it (nit a). RecordFailure(ex); served = null; } if (served is null) { if (offset == 0) return null; failed = true; continue; } for (var k = 0; k < chunk.Length; k++) { var answer = served[k]; foreach (var sample in answer.Samples) used += sample.Value.EstimatedRetainedBytes; if (answer.ConsumerBudgetRefused) spent = true; answers[offset + k] = answer; } offset += chunk.Length; } return answers.Select(x => x!).ToArray(); } catch { Abandon(selected, answers); throw; } } /// Disposes answers that will never be handed out and releases the new origin continuations they carry. private void Abandon(Selected selected, IEnumerable answers) { foreach (var answer in answers) { if (answer is null) continue; answer.Dispose(); if (answer.Continuation is { } wrapped && TryUnwrap(wrapped, out _, out _, out var token)) _ = ReleaseOnEndpointAsync(selected, token); } } /// /// Reads on one selected endpoint and assembles its chunks. Results null = the endpoint failed before answering (a fresh /// read may move); EndpointFailed = it answered (per node) but failed or retired on the way, so a caller splitting a /// request sends it nothing more. Anything that escapes first releases every origin token this assembly holds — finished /// nodes' continuations, chunk tokens, and the tokens of a response it rejected (H3 review round 3 S6). /// private async Task<(DataHistoryReadResult[]? Results, bool EndpointFailed)> ServeAsync(Selected selected, int endpoint, DataHistoryReadRequest request, DataHistoryReadItem[] items, int[] pending, long start, CancellationToken cancellationToken) { var batch = pending.Select(i => items[i]).ToArray(); var assembled = new List[batch.Length]; var final = new DataHistoryReadResult?[batch.Length]; var completed = new bool[batch.Length]; long assembledBytes = 0; var current = batch; var map = Enumerable.Range(0, batch.Length).ToArray(); var first = true; var endpointFailed = false; var chunkTokensReleased = false; W.HistoryReadResponse? unprocessed = null; // a received response whose tokens are not yet owned by final[] / current IReadOnlyList? decoded = null; try { while (current.Length > 0) { var remaining = request.Budget.Timeout - Clock.GetElapsedTime(start); if (remaining <= TimeSpan.Zero) { foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, BadTimeout, [], null); break; } var deadline = remaining < HistoryTimeout ? remaining : HistoryTimeout; var wire = DataHistoryProtoMapper.EncodeRequest(request with { Items = current, Budget = request.Budget with { Timeout = deadline } }); using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, selected.Channel.Retired.Token, _shutdown.Token); W.HistoryReadResponse response; try { response = await selected.Channel.Client.HistoryReadAsync(wire, new CallOptions( Headers(selected.Channel, RequestedFeatures(selected.Capabilities)), DateTime.UtcNow + deadline, linked.Token)) .ResponseAsync.ConfigureAwait(false); } catch (Exception ex) when (cancellationToken.IsCancellationRequested && ex is RpcException or OperationCanceledException) { // A caller cancel is never an outcome: surface it as cancellation, and let go of held chunk tokens. if (!first) ReleaseChunkTokens(selected, current); chunkTokensReleased = true; throw new OperationCanceledException("History read cancelled by the caller.", ex, cancellationToken); } catch (RpcException ex) when (ex.StatusCode is StatusCode.FailedPrecondition or StatusCode.Unimplemented) { if (!first) ReleaseChunkTokens(selected, current); foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, BadHistoryOperationUnsupported, [], null); break; } catch (Exception ex) when (!cancellationToken.IsCancellationRequested && Retiring(selected) && ex is OperationCanceledException or RpcException { StatusCode: StatusCode.Cancelled }) { // Not the caller and not a deadline: the channel retired, the scope moved or the connection is shutting down // (a redeploy). Not a timeout and not an endpoint fault (round 3 S5): the read cannot continue here. if (!first) ReleaseChunkTokens(selected, current); foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, batch[k].Continuation is not null ? BadContinuationPointInvalid : BadNoCommunication, [], null); endpointFailed = true; break; } catch (RpcException ex) when (ex.StatusCode is StatusCode.DeadlineExceeded or StatusCode.Cancelled && !cancellationToken.IsCancellationRequested) { // The call's own deadline, or the origin cancelling it at ITS unary timeout (the effective ceiling is // min(HistoryTimeout, origin DataConnections:UnaryTimeout)): a timeout, never an endpoint failure. if (!first) ReleaseChunkTokens(selected, current); foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, BadTimeout, [], null); break; } catch (RpcException ex) when (first && ex.StatusCode is StatusCode.Unavailable or StatusCode.Unauthenticated or StatusCode.PermissionDenied && !cancellationToken.IsCancellationRequested) { RecordFailure(ex); chunkTokensReleased = true; return (null, true); } catch (RpcException ex) { RecordFailure(ex); if (!first) ReleaseChunkTokens(selected, current); // the origin still holds their remainders foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, BadNoCommunication, [], null); endpointFailed = true; break; } first = false; unprocessed = response; Verify(response.Serving, selected); decoded = DataHistoryProtoMapper.DecodeResponse(response, Limits(request.Budget, selected.Capabilities) with { MaxValueElements = int.MaxValue, MaxBytes = _maxMessageBytes }); if (decoded.Count != current.Length || decoded.Where((r, k) => r.CorrelationId != current[k].CorrelationId).Any()) throw new InvalidOperationException("History response has unexpected items."); var nextItems = new List(); var nextMap = new List(); for (var k = 0; k < decoded.Count; k++) { var target = map[k]; var result = decoded[k]; assembled[target] ??= []; foreach (var sample in result.Samples) assembledBytes += sample.Value.EstimatedRetainedBytes; assembled[target].AddRange(result.Samples); if (assembledBytes > request.Budget.MaxBytes) { // The per-request assembly budget is exhausted: this and every later node is BadTooManyOperations. _ = ReleaseOnEndpointAsync(selected, result.Continuation); final[target] = new(result.CorrelationId, BadTooManyOperations, [], null, "History assembly budget exceeded.") { ConsumerBudgetRefused = true }; continue; } if (result.ChunkContinues) { nextItems.Add(current[k] with { Continuation = result.Continuation }); nextMap.Add(target); continue; } final[target] = new(result.CorrelationId, result.StatusCode, [], Wrap(endpoint, selected.Capabilities.Serving.Incarnation, result.Continuation), result.Diagnostic); completed[target] = true; } current = nextItems.ToArray(); map = nextMap.ToArray(); unprocessed = null; decoded = null; // every token of this response is now in final[] or current } var answers = new DataHistoryReadResult[batch.Length]; for (var k = 0; k < batch.Length; k++) { var result = final[k] ?? new(batch[k].CorrelationId, BadNoCommunication, [], null); if (!completed[k]) { // Never hand back a partially assembled answer under an error status. foreach (var sample in assembled[k] ?? []) sample.Dispose(); answers[k] = result; continue; } answers[k] = result with { Samples = (IReadOnlyList?)assembled[k] ?? [] }; } return (answers, endpointFailed); } catch { foreach (var list in assembled) foreach (var sample in list ?? []) sample.Dispose(); foreach (var r in decoded ?? []) r.Dispose(); // Nothing this assembly holds is handed out: release every origin token it owns (round 3 S6). foreach (var r in final) if (r?.Continuation is { } wrapped && TryUnwrap(wrapped, out _, out _, out var token)) _ = ReleaseOnEndpointAsync(selected, token); if (!first && !chunkTokensReleased) ReleaseChunkTokens(selected, current); foreach (var item in unprocessed?.Items ?? []) if (item.HasContinuation) _ = ReleaseOnEndpointAsync(selected, item.Continuation.ToByteArray()); throw; } } /// The call was cancelled by the connection itself: its channel retired, its scope moved, or it is shutting down. private bool Retiring(Selected selected) => selected.Channel.Retired.IsCancellationRequested || _scope.CancellationToken.IsCancellationRequested || _shutdown.IsCancellationRequested; /// Releases continuations on their issuing endpoints (); best effort. public async Task ReleaseHistoryAsync(IReadOnlyList continuations, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(continuations); foreach (var group in continuations.Select(x => TryUnwrap(x, out var endpoint, out var serving, out var token) ? (Endpoint: endpoint, Serving: serving, Token: token) : (Endpoint: -1, Serving: "", Token: Array.Empty())) .Where(x => x.Endpoint >= 0 && x.Endpoint < _endpoints.Length).GroupBy(x => x.Endpoint)) { try { var start = Clock.GetTimestamp(); var budget = new DataBudget(HistoryTimeout, Math.Max(1, group.Count()), _maxMessageBytes); var selected = await SelectAsync(_endpoints[group.Key], start, budget, false, cancellationToken).ConfigureAwait(false); if (RequestedFeatures(selected.Capabilities) == DataFeatures.None) continue; foreach (var token in group.Where(x => x.Serving == selected.Capabilities.Serving.Incarnation)) await ReleaseOnEndpointAsync(selected, token.Token).ConfigureAwait(false); } catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException or TimeoutException) { RecordFailure(ex); } // best effort; origin idle expiry is the backstop } } /// Best effort: a follow-up's items carry origin CHUNK tokens; release them when the assembly is abandoned. private void ReleaseChunkTokens(Selected selected, IEnumerable items) { foreach (var item in items) _ = ReleaseOnEndpointAsync(selected, item.Continuation); } private async Task ReleaseOnEndpointAsync(Selected selected, byte[]? token) { if (token is null) return; try { // Release needs a view only to be well-formed; the origin drops the token without resolving it. var view = new DataView(new DataAddress(Target.ExpectedClusterId, "urn:release", "string", "release"), DataRealm.Raw, null, 0, "release"); var wire = DataHistoryProtoMapper.EncodeRequest(new DataHistoryReadRequest(new DataHistoryRawDetails(null, null, 0, false), [new DataHistoryReadItem("release", view, null, token)], new DataBudget(HistoryTimeout, 1, _maxMessageBytes)), releaseContinuations: true); await selected.Channel.Client.HistoryReadAsync(wire, new CallOptions(Headers(selected.Channel, RequestedFeatures(selected.Capabilities)), DateTime.UtcNow + HistoryTimeout, _shutdown.Token)).ResponseAsync.ConfigureAwait(false); } catch (Exception ex) when (ex is RpcException or OperationCanceledException or InvalidOperationException) { } } /// The capability probe's budget: the caller's, capped by . private DataBudget ProbeBudget(DataBudget budget) => budget.Timeout <= HistoryTimeout ? budget : budget with { Timeout = HistoryTimeout }; private static DataHistoryReadResult[] All(DataHistoryReadRequest request, uint status) => request.Items.Select(x => new DataHistoryReadResult(x.CorrelationId, status, [], null)).ToArray(); /// [tag][version][endpoint][len:u16][serving incarnation utf8][origin token]. internal static byte[]? Wrap(int endpoint, string serving, byte[]? token) { if (token is null) return null; var servingBytes = Encoding.UTF8.GetBytes(serving); if (endpoint is < 0 or > byte.MaxValue || servingBytes.Length > ushort.MaxValue) throw new ArgumentOutOfRangeException(nameof(endpoint)); var envelope = new byte[5 + servingBytes.Length + token.Length]; envelope[0] = EnvelopeTag; envelope[1] = EnvelopeVersion; envelope[2] = (byte)endpoint; BinaryPrimitives.WriteUInt16BigEndian(envelope.AsSpan(3), (ushort)servingBytes.Length); servingBytes.CopyTo(envelope, 5); token.CopyTo(envelope, 5 + servingBytes.Length); return envelope; } internal static bool TryUnwrap(byte[] envelope, out int endpoint, out string serving, out byte[] token) { endpoint = -1; serving = ""; token = []; if (envelope.Length < 6 || envelope[0] != EnvelopeTag || envelope[1] != EnvelopeVersion) return false; var length = BinaryPrimitives.ReadUInt16BigEndian(envelope.AsSpan(3)); if (envelope.Length <= 5 + length) return false; endpoint = envelope[2]; serving = Encoding.UTF8.GetString(envelope, 5, length); token = envelope.AsSpan(5 + length).ToArray(); return true; } }