diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs index 684a41759..05ae4cab2 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs @@ -583,6 +583,8 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistor internal Func RouteCurrent => _routeCurrent; /// The configured row's operations, already masked to the understood set. internal DataOperations AllowedOperations => _allowed; + /// The connection row's batch size: a history request with more items is refused (H3 splits below it). + internal int MaxBatchItems => _batch; public IDataConnection Connection => this; public CancellationToken CancellationToken => _scope; public DataTarget Target => _inner.Target; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs index 71971f68c..2aa93be69 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs @@ -89,7 +89,13 @@ public sealed partial class GrpcDataConnection : IDataHistoryService Check(); cancellationToken.ThrowIfCancellationRequested(); Selected selected; - try { selected = await SelectAsync(_endpoints[index], start, request.Budget, false, cancellationToken).ConfigureAwait(false); ProbeSucceeded(); } + // 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; } @@ -291,6 +297,9 @@ public sealed partial class GrpcDataConnection : IDataHistoryService 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(); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs index 6ac215124..47ef06202 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs @@ -49,6 +49,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl private readonly Dictionary> _pendingReleases = new(StringComparer.OrdinalIgnoreCase); private readonly CancellationTokenSource _stop = new(); private Task _releaseFlush = Task.CompletedTask; + private bool _flushScheduled; private int _disposed; /// Creates the gateway. @@ -103,8 +104,10 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl var outcomes = new ProjectedHistoryOutcome?[nodes.Count]; var demands = new IProjectedDemandLease?[nodes.Count]; var targets = new ProjectedHistoryTarget?[nodes.Count]; + var assembled = new long[nodes.Count]; + var assemblyRefused = new bool[nodes.Count]; var callerKey = CallerKey(caller); - long budget = DefaultAssemblyBudget; + long budget = DefaultAssemblyBudget, received = 0; try { // 1. Resolve, authorize and pin every node; check each resumed cursor against what it was issued under. @@ -114,7 +117,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl var cursor = node.Resume as RemoteCursor; if (node.Resume is not null && (cursor is null || !ReferenceEquals(cursor.Owner, this))) { - node.Resume.Release(); + node.Resume.ReleaseEvenIfClaimed(); outcomes[i] = Fail(BadContinuationPointInvalid); continue; } @@ -145,38 +148,77 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl if (target is not null) budget = Math.Min(budget, _assemblyBudget(target.MappingId) is { } b and > 0 ? b : DefaultAssemblyBudget); if (budget == long.MaxValue) budget = DefaultAssemblyBudget; - // 3. One call per (connection, details, resumed endpoint): a resumed item pins its issuing endpoint, so cursors of - // different endpoints, and fresh items (which may move), never share a call. - var groups = Enumerable.Range(0, nodes.Count).Where(i => outcomes[i] is null) - .GroupBy(i => new GroupKey(targets[i]!.ConnectionId, DetailsOf(nodes[i], details), ResumeKey(nodes[i]))) - .ToArray(); - foreach (var group in groups) + // 3. Calls per (connection, details, resumed endpoint): a resumed item pins its issuing endpoint, so cursors of + // different endpoints, and fresh items (which may move), never share a call. Calls are RUNS of consecutive + // request positions with one key, read in request order (H3 review D7), so the assembly budget is consumed in + // request order and a budget shortfall only ever refuses nodes later in the request. Each run is sub-batched. + var runs = new List<(GroupKey Key, List Indices)>(); + for (var i = 0; i < nodes.Count; i++) { - var indices = group.ToArray(); - if (cancellationToken.IsCancellationRequested) { FailAll(indices, BadTimeout); continue; } - TimeSpan remaining; - if (deadline > TimeSpan.Zero) + if (outcomes[i] is not null) continue; + var key = new GroupKey(targets[i]!.ConnectionId, DetailsOf(nodes[i], details), ResumeKey(nodes[i])); + if (runs.Count > 0 && runs[^1].Key == key) runs[^1].Indices.Add(i); + else runs.Add((key, [i])); + } + + foreach (var (key, list) in runs) + { + var indices = list.ToArray(); + if (cancellationToken.IsCancellationRequested || Remaining() <= TimeSpan.Zero) { FailAll(indices, BadTimeout); continue; } + if (received >= budget) { FailAll(indices, BadTooManyOperations); continue; } + await ReadGroupAsync(key, indices, cancellationToken).ConfigureAwait(false); + } + + // 4. Charge the assembly budget in REQUEST order (H3 review D7): the first node that does not fit, and every later + // node with data, is BadTooManyOperations; its next origin cursor is released. + var left = budget; + var exhausted = false; + for (var i = 0; i < nodes.Count; i++) + { + if (assemblyRefused[i]) { exhausted = true; continue; } + if (outcomes[i] is not { } outcome || assembled[i] == 0 && !exhausted) continue; + if (exhausted || assembled[i] > left) { - remaining = deadline - _clock.GetElapsedTime(started); - if (remaining <= TimeSpan.Zero) { FailAll(indices, BadTimeout); continue; } + exhausted = true; + (outcome.Continuation as RemoteCursor)?.ReleaseOrigin(); + outcomes[i] = Fail(BadTooManyOperations); + continue; } - else remaining = TimeSpan.FromHours(1); // unbounded locally: the connection's HistoryTimeout still caps each call - if (budget <= 0) { FailAll(indices, BadTooManyOperations); continue; } - await ReadGroupAsync(group.Key, indices, remaining, cancellationToken).ConfigureAwait(false); + + left -= assembled[i]; } return outcomes.Select(o => o ?? Fail(BadNoCommunication)).ToArray(); } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // Last resort (H3 review D1): whatever escaped, fail per node — a timeout when the deadline fired — and release every + // origin cursor this request still owns. Nothing escapes to the SDK override. + var timedOut = cancellationToken.IsCancellationRequested || Remaining() <= TimeSpan.Zero || ex is OperationCanceledException; + for (var i = 0; i < nodes.Count; i++) + { + if (outcomes[i] is not null) continue; + nodes[i].Resume?.ReleaseEvenIfClaimed(); + outcomes[i] = Fail(timedOut ? BadTimeout : BadNoCommunication); + } + + return outcomes.Select(o => o!).ToArray(); + } finally { foreach (var demand in demands) demand?.Dispose(); } - async Task ReadGroupAsync(GroupKey key, int[] indices, TimeSpan remaining, CancellationToken ct) + TimeSpan Remaining() => deadline > TimeSpan.Zero + ? deadline - _clock.GetElapsedTime(started) + : TimeSpan.FromHours(1); // unbounded locally: the connection's HistoryTimeout still caps each call + + async Task ReadGroupAsync(GroupKey key, int[] indices, CancellationToken ct) { IGrpcDataAdapterConnectionLease? lease = null; try { + var remaining = Remaining(); using var timeout = new CancellationTokenSource(remaining, _clock); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeout.Token); lease = await _connections.AcquireAsync(key.ConnectionId, linked.Token).ConfigureAwait(false); @@ -191,109 +233,106 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl } var route = lease.RouteIdentity; - var items = new List(indices.Length); - var sent = new List(indices.Length); + var sendable = new List(indices.Length); foreach (var i in indices) { - if (nodes[i].Resume is RemoteCursor cursor) + // The connection lease moved (expiry, redeployment, credential change): its tokens are gone. + if (nodes[i].Resume is RemoteCursor cursor && !Equals(cursor.RouteIdentity, route)) { - // The connection lease moved (expiry, redeployment, credential change): its tokens are gone. - if (!Equals(cursor.RouteIdentity, route)) - { - cursor.ReleaseOrigin(); - outcomes[i] = Fail(BadContinuationPointInvalid); - continue; - } - - items.Add(new DataHistoryReadItem(sent.Count.ToString(System.Globalization.CultureInfo.InvariantCulture), - targets[i]!.OriginMetadata.View, cursor.AggregateId, cursor.Token)); - } - else - { - items.Add(new DataHistoryReadItem(sent.Count.ToString(System.Globalization.CultureInfo.InvariantCulture), - targets[i]!.OriginMetadata.View, nodes[i].AggregateId)); + cursor.ReleaseOrigin(); + outcomes[i] = Fail(BadContinuationPointInvalid); + continue; } - sent.Add(i); + sendable.Add(i); } - if (items.Count == 0) return; - IReadOnlyList answers; - try + if (sendable.Count == 0) return; + var batch = await BatchSizeAsync(lease.Connection, sendable.Count, remaining, linked.Token).ConfigureAwait(false); + for (var offset = 0; offset < sendable.Count;) { - answers = await history.ReadAsync(new DataHistoryReadRequest(key.Details, items, - new DataBudget(remaining, items.Count, (int)Math.Min(int.MaxValue, budget))), linked.Token).ConfigureAwait(false); - } - catch (OperationCanceledException) - { - // Our deadline or the SDK request ending: a timeout, never an origin fault (the connection records none). - foreach (var i in sent) outcomes[i] = Fail(BadTimeout); - return; - } - - try - { - if (answers.Count != items.Count) + var now = Remaining(); + if (ct.IsCancellationRequested || now <= TimeSpan.Zero) { FailAll(sendable.Skip(offset).ToArray(), BadTimeout); return; } + // A budget shortfall refuses the remaining nodes unsent — never an endpoint failure (H3 review D4). A call may + // carry at most one item per MinimumBytesPerItem of its byte budget (the origin's admission rule). + var fitting = (int)Math.Min(int.MaxValue, (budget - received) / MinimumBytesPerItem); + if (fitting <= 0) { FailAll(sendable.Skip(offset).ToArray(), BadTooManyOperations); return; } + var from = offset; + var chunk = sendable.Skip(from).Take(Math.Min(batch, fitting)).ToArray(); + offset += chunk.Length; + var items = chunk.Select((i, k) => new DataHistoryReadItem(k.ToString(System.Globalization.CultureInfo.InvariantCulture), + targets[i]!.OriginMetadata.View, + nodes[i].Resume is RemoteCursor c ? c.AggregateId : nodes[i].AggregateId, + (nodes[i].Resume as RemoteCursor)?.Token)).ToArray(); + IReadOnlyList answers; + try { - foreach (var i in sent) outcomes[i] = Fail(BadNoCommunication); + answers = await history.ReadAsync(new DataHistoryReadRequest(key.Details, items, + new DataBudget(now, items.Length, budget - received)), linked.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + // Our deadline or the SDK request ending: a timeout, never an origin fault (the connection records none). + FailAll(sendable.Skip(from).ToArray(), BadTimeout); return; } - for (var k = 0; k < answers.Count; k++) + try { - var i = sent[k]; - var answer = answers[k]; - if (answer.CorrelationId != items[k].CorrelationId) + if (answers.Count != items.Length) { - outcomes[i] = Fail(BadNoCommunication); + FailAll(chunk, BadNoCommunication); continue; } - // The per-request assembly budget, in request order across the whole batch: once a node does not fit, - // it and every later node is BadTooManyOperations (never a partial answer; its origin cursor released). - long nodeBytes = 0; - foreach (var sample in answer.Samples) nodeBytes += sample.Value.EstimatedRetainedBytes; - if (nodeBytes > budget) + for (var k = 0; k < answers.Count; k++) { - budget = 0; - if (answer.Continuation is { } dropped) EnqueueRelease(key.ConnectionId, dropped); - outcomes[i] = Fail(BadTooManyOperations); - continue; + var i = chunk[k]; + var answer = answers[k]; + if (answer.CorrelationId != items[k].CorrelationId) + { + if (answer.Continuation is { } stray) EnqueueRelease(key.ConnectionId, stray); + outcomes[i] = Fail(BadNoCommunication); + continue; + } + + if (answer.StatusCode == BadTooManyOperations && answer.Diagnostic?.Contains("budget", StringComparison.OrdinalIgnoreCase) == true) + assemblyRefused[i] = true; // the connection's own share of the assembly budget ran out + long nodeBytes = 0; + foreach (var sample in answer.Samples) nodeBytes += sample.Value.EstimatedRetainedBytes; + assembled[i] = nodeBytes; + received += nodeBytes; + var target = targets[i]!; + RemoteCursor? next = null; + if (answer.Continuation is { } token) + { + next = new RemoteCursor(this, target.OriginMetadata.View.Realm, demands[i]!.LocalIdentifier, token, key.ConnectionId, route, + target, callerKey, key.Details, nodes[i].Resume is RemoteCursor prior ? prior.AggregateId : nodes[i].AggregateId); + } + + outcomes[i] = new ProjectedHistoryOutcome(answer.StatusCode, + Convert(answer.Samples, target.OriginMetadata, key.Details is DataHistoryProcessedDetails), next); } - - budget -= nodeBytes; - - var target = targets[i]!; - RemoteCursor? next = null; - if (answer.Continuation is { } token) - { - next = new RemoteCursor(this, target.OriginMetadata.View.Realm, demands[i]!.LocalIdentifier, token, key.ConnectionId, route, - target, callerKey, key.Details, nodes[i].Resume is RemoteCursor prior ? prior.AggregateId : nodes[i].AggregateId); - } - - outcomes[i] = new ProjectedHistoryOutcome(answer.StatusCode, Convert(answer.Samples, target.OriginMetadata, key.Details is DataHistoryProcessedDetails), next); + } + finally + { + foreach (var answer in answers) answer.Dispose(); } } - finally - { - foreach (var answer in answers) answer.Dispose(); - } - } catch (OperationCanceledException) { - foreach (var i in indices) - { - if (outcomes[i] is not null) continue; - if (nodes[i].Resume is RemoteCursor c) c.ReleaseOrigin(); - outcomes[i] = Fail(BadTimeout); - } - return; + FailAll(indices.Where(i => outcomes[i] is null).ToArray(), BadTimeout); } - catch (Exception ex) when (ex is InvalidOperationException or UnauthorizedAccessException or ArgumentException or ObjectDisposedException) + catch (Exception ex) when (ex is not OutOfMemoryException) { - foreach (var i in indices) outcomes[i] ??= Fail(nodes[i].Resume is null ? BadNoCommunication : BadContinuationPointInvalid); - return; + // An unexpected fault (an escaping RpcException, a malformed answer): per node, never out of the batch. + var timedOut = ct.IsCancellationRequested || Remaining() <= TimeSpan.Zero; + foreach (var i in indices.Where(i => outcomes[i] is null).ToArray()) + { + if (nodes[i].Resume is RemoteCursor c) c.ReleaseOrigin(); + outcomes[i] = Fail(timedOut ? BadTimeout : nodes[i].Resume is null ? BadNoCommunication : BadContinuationPointInvalid); + } } finally { @@ -311,6 +350,32 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl } } + /// + /// The sub-batch size of one call (H3 review D4): the deployed connection's own batch size, and — when more than one node + /// is sent — the origin's advertised MaxBatchItems (best effort: a failed probe keeps the connection's size). + /// + private static async Task BatchSizeAsync(IDataConnection connection, int count, TimeSpan remaining, CancellationToken ct) + { + var batch = connection is DataConnectionDeploymentLease lease ? lease.MaxBatchItems : DefaultBatchItems; + if (count > 1) + { + try + { + var capabilities = await connection.GetCapabilitiesAsync(new DataBudget(remaining, 1, 1L << 20), ct).ConfigureAwait(false); + if (capabilities.Limits.MaxBatchItems > 0) batch = Math.Min(batch, capabilities.Limits.MaxBatchItems); + } + catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException) { } + } + + return Math.Max(1, batch); + } + + /// The sub-batch size when the connection is not a deployment lease (tests, direct facades). + internal const int DefaultBatchItems = 100; + + /// An origin admits at most one item per this many bytes of a request's byte budget. + internal const long MinimumBytesPerItem = 256; + private static ProjectedHistoryOutcome Fail(uint status) => new(status, []); private static DataHistoryDetails DetailsOf(ProjectedHistoryNode node, DataHistoryDetails request) => @@ -358,6 +423,9 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl return converted; } + /// Queues a release directly (tests: the flush's wake-up under concurrent enqueues). + internal void EnqueueReleaseForTests(string connectionId, byte[] token) => EnqueueRelease(connectionId, token); + /// Queues an origin token for a coalesced best-effort release on its connection. private void EnqueueRelease(string connectionId, byte[] token) { @@ -366,7 +434,10 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl { if (!_pendingReleases.TryGetValue(connectionId, out var list)) _pendingReleases[connectionId] = list = []; list.Add(token); - if (!_releaseFlush.IsCompleted) return; + // H3 review D6: a flag under the gate, not Task.IsCompleted — a flush past its last check but not yet completed + // would otherwise swallow this token (a lost wakeup). The flush clears the flag under the same gate. + if (_flushScheduled) return; + _flushScheduled = true; _releaseFlush = Task.Run(FlushReleasesAsync); } } @@ -374,7 +445,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl private async Task FlushReleasesAsync() { try { await Task.Delay(ReleaseCoalesce, _stop.Token).ConfigureAwait(false); } - catch (OperationCanceledException) { return; } + catch (OperationCanceledException) { lock (_releaseGate) _flushScheduled = false; return; } Dictionary> batch; lock (_releaseGate) { @@ -402,15 +473,19 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl } lock (_releaseGate) + { if (_pendingReleases.Count > 0 && Volatile.Read(ref _disposed) == 0) _releaseFlush = Task.Run(FlushReleasesAsync); + else _flushScheduled = false; + } } /// public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + // Cancel only: a flush still running reads _stop.Token, so it is never disposed under it (H3 review D6). The source + // has no timer, so leaving it to the GC releases nothing. _stop.Cancel(); - _stop.Dispose(); } /// diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs index a246ccf00..cf78f7ddb 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs @@ -193,6 +193,31 @@ public sealed class GrpcDataHistoryClientTests await Should.ThrowAsync(() => connection.ReadHistoryAsync(Request(), cancel.Token)); } + [Fact] + [Trait("Phase", "H3")] + public async Task A_caller_cancel_during_the_capability_probe_is_an_OperationCanceledException_never_an_RpcException() + { + // H3 review D1: the probe that never answers used to surface RpcException(Cancelled) and fault the consumer's HistoryRead. + var a = new Endpoint("a") { ProbeDelay = TimeSpan.FromSeconds(30) }; + await using var connection = Connect([a]); + using var cancel = new CancellationTokenSource(TimeSpan.FromMilliseconds(200)); + var error = await Should.ThrowAsync(() => connection.ReadHistoryAsync(Request(), cancel.Token)); + error.ShouldNotBeAssignableTo(); + a.HistoryCalls.ShouldBe(0); + } + + [Fact] + [Trait("Phase", "H3")] + public async Task The_capability_probe_is_capped_by_HistoryTimeout_too() + { + var a = new Endpoint("a"); + await using var connection = Connect([a], historyTimeout: TimeSpan.FromSeconds(2)); + var request = Request() with { Budget = Request().Budget with { Timeout = TimeSpan.FromMinutes(10) } }; + (await connection.ReadHistoryAsync(request, TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0u); + a.LastProbeTimeout.ShouldNotBeNull(); + a.LastProbeTimeout!.Value.ShouldBeLessThanOrEqualTo(TimeSpan.FromSeconds(2)); + } + [Fact] public async Task A_failure_mid_assembly_releases_the_origin_chunk_tokens_it_holds() { @@ -225,6 +250,10 @@ public sealed class GrpcDataHistoryClientTests public bool Malformed { get; set; } /// Delay before answering a HistoryRead (honours the request's token). public TimeSpan? Delay { get; set; } + /// Delay before answering the capability probe (honours the request's token). + public TimeSpan? ProbeDelay { get; set; } + /// The grpc-timeout of the last capability probe. + public TimeSpan? LastProbeTimeout { get; private set; } /// Fail every HistoryRead after the first with this status. public Grpc.Core.StatusCode? FailAfterFirst { get; set; } public int Chunks { get; init; } = 1; @@ -247,6 +276,8 @@ public sealed class GrpcDataHistoryClientTests IMessage message; if (path.EndsWith("/GetCapabilities", StringComparison.Ordinal)) { + if (request.Headers.TryGetValues("grpc-timeout", out var probeTimeouts)) LastProbeTimeout = ParseTimeout(probeTimeouts.Single()); + if (ProbeDelay is { } probeDelay) await Task.Delay(probeDelay, token); var asked = request.Headers.Contains("x-otopcua-data-features"); var caps = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 5, Serving, Ready ? DataReadiness.Ready : DataReadiness.Unavailable, !Ready ? DataOperations.None : DataOperationSets.V1 | (history && asked && Granted ? DataOperations.HistoryRead : DataOperations.None), diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs index e79f450f3..5b89a1f11 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs @@ -134,7 +134,7 @@ internal sealed class LocalDataFixture : IDisposable bool advanceAuthority = false, string role = "Primary", long servingGeneration = 0, bool nestedCatalog = false, bool nestedUnsCatalog = false, Func? writes = null, bool denyReadExport = false, ManualTimeProvider? clock = null, string servingNode = "node-a", string servingIncarnation = "serving-1", - IOriginHistoryPort? history = null) + IOriginHistoryPort? history = null, DataValueKind rawValueKind = DataValueKind.Int32, int maxBatchItems = 100) { if (clock is not null) Clock = clock; Serving = Serving with { NodeId = servingNode, Incarnation = servingIncarnation, Role = role, ServingGeneration = servingGeneration }; @@ -163,7 +163,7 @@ internal sealed class LocalDataFixture : IDisposable if (denyReadExport) operations &= ~DataOperations.Read; if (history is not null) operations |= DataOperations.HistoryRead; var rootMetadata = new DataMetadata(Root, "Plant", "Folder", DataValueKind.Null, -1, [], false, operations, 1, null, null, false); - var rawMetadata = new DataMetadata(Raw, "Speed", "Variable", DataValueKind.Int32, -1, [], true, operations, 1, Ticket.Key.StableSourceId, "rpm", false); + var rawMetadata = new DataMetadata(Raw, "Speed", "Variable", rawValueKind, -1, [], true, operations, 1, Ticket.Key.StableSourceId, "rpm", false); var unsMetadata = rawMetadata with { View = Uns }; var folder = Root with { Address = Root.Address with { Identifier = "Plant/Driver" }, Subject = "Plant/Driver" }; var unsRoot = Uns with { Address = Uns.Address with { Identifier = "Area" }, Subject = "Area" }; @@ -192,7 +192,7 @@ internal sealed class LocalDataFixture : IDisposable Catalog = new LocalExportCatalog("cluster", Serving, Activation.CaptureAuthority(), nodes, [new() { DataExportId = "raw-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "RawFolder", RootEntityId = "folder", PrincipalId = "peer", AllowedOperations = operations }, new() { DataExportId = "uns-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = nestedUnsCatalog ? "UnsArea" : "UnsTagReference", RootEntityId = nestedUnsCatalog ? "area" : "reference", PrincipalId = "peer", AllowedOperations = operations }]); - var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1)); + var limits = new DataLimits(100, maxBatchItems, 1_000_000, 100, 10, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1)); var capabilities = new DataCapabilitiesProvider("cluster", () => Serving, () => Catalog.IsActive, limits); Services = new LocalDataServices(() => Catalog, Hub, new DataOperationPolicy(Authority, new TriePermissionEvaluator(Authority.Tries, Clock), Clock), capabilities, Clock, writes: writes, subscriptions: subscriptions, diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs index a6771aa60..d991e70ed 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs @@ -240,6 +240,151 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests }, localPermissions: 15, allowHistory: granted, connectionSource: new PersistentConnections(origin)); } + [Fact(Timeout = 90000)] + [Trait("Phase", "H3")] + public async Task A_Float32_node_whose_backend_returns_Double_reads_Good_through_the_projection_as_it_does_locally() + { + // H3 review: SQL backends store every float as a Double. The origin port normalises Raw / AtTime to the node's type + // (Single) before the wire, so the projected rows are Good Singles — never a BadTypeMismatch per row while local works. + await using var originServer = await HistoryOrigin.StartAsync(5, dataType: "Float", value: i => i + 0.5); + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port, rawValueKind: DataValueKind.Float); + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var raw = await RawHistory(client, anchor, 0, default); + StatusCode.IsGood(raw.StatusCode).ShouldBeTrue(raw.StatusCode.ToString()); + var values = Values(raw); + values.Count.ShouldBe(5); + values.ShouldAllBe(v => StatusCode.IsGood(v.StatusCode)); + values.Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe(Enumerable.Range(0, 5).Select(i => (object?)(float)(i + 0.5))); + var details = new ReadAtTimeDetails { ReqTimes = [(DateTimeUtc)HistoryT0.AddSeconds(2)] }; + var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false, + [new HistoryReadValueId { NodeId = anchor }], TestContext.Current.CancellationToken); + var atTime = Values(response.Results.ToArray()!.Single()).ShouldHaveSingleItem(); + StatusCode.IsGood(atTime.StatusCode).ShouldBeTrue(atTime.StatusCode.ToString()); + SdkValueBoundary.ToClr(atTime.WrappedValue).ShouldBeOfType().ShouldBe(2.5f); + }, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin)); + } + + [Theory(Timeout = 90000)] + [Trait("Phase", "H3")] + [InlineData(HistoryMode.Hang)] + [InlineData(HistoryMode.Throw)] + public async Task A_history_call_that_never_answers_or_faults_fails_only_the_projected_half_and_releases_its_cursor(HistoryMode mode) + { + // H3 review D1: a deadline during the connection's capability probe used to escape as an RpcException and fault the + // whole HistoryRead. Now the projected half fails per node (BadTimeout when the deadline fired), the local half of the + // same batch is served, and the claimed origin cursor is released (positive control: the origin store returns to 0). + await using var originServer = await HistoryOrigin.StartAsync(7); + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); + var connections = new HistorySwitchConnections(origin); + ProjectedHistoryAccess? history = null; + OtOpcUaNodeManager? manager = null; + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + manager!.HistorianDataSource = new SeriesSource(Enumerable.Range(0, 3) + .Select(i => new DataValueSnapshot(i, 0, HistoryT0.AddSeconds(i), HistoryT0.AddSeconds(i))).ToArray()); + manager.EnsureVariable("Plant/LocalH", "Plant", "LocalH", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "local"); + var local = manager.TryGetVariable("Plant/LocalH", AddressSpaceRealm.Raw)!.NodeId; + var page = await RawHistory(client, anchor, 2, default); + page.ContinuationPoint.IsEmpty.ShouldBeFalse(); + origin.Services.HistoryOpenContinuations.ShouldBe(1); + + connections.Mode = mode; + manager.HistoryReadDeadline = TimeSpan.FromSeconds(1); + var response = await client.HistoryReadAsync(new RequestHeader { TimeoutHint = 20_000 }, new ExtensionObject(RawDetails(2)), + TimestampsToReturn.Both, false, + [new HistoryReadValueId { NodeId = local }, new HistoryReadValueId { NodeId = anchor, ContinuationPoint = page.ContinuationPoint }], + TestContext.Current.CancellationToken); + var results = response.Results.ToArray()!; + StatusCode.IsGood(results[0].StatusCode).ShouldBeTrue("the local half of the batch is still served"); + Values(results[0]).Count.ShouldBe(2); + results[1].StatusCode.Code.ShouldBe(mode == HistoryMode.Hang ? StatusCodes.BadTimeout.Code : StatusCodes.BadContinuationPointInvalid.Code); + await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0); + origin.Services.HistoryOpenContinuations.ShouldBe(0, "the claimed cursor's origin continuation was released"); + }, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (h, m) => { history = h; manager = m; }); + } + + [Fact(Timeout = 90000)] + [Trait("Phase", "H3")] + public async Task A_group_larger_than_the_origin_batch_is_split_into_sub_batches() + { + // H3 review D4: three projected nodes against an origin that admits two items per request. + await using var originServer = await HistoryOrigin.StartAsync(7, extra: 2); + using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, history: originServer.Port, maxBatchItems: 2); + var connections = new HistorySwitchConnections(origin); + await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray(); + children.Length.ShouldBe(3); + var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false, + children.Select(c => new HistoryReadValueId { NodeId = c }).ToArray(), TestContext.Current.CancellationToken); + var results = response.Results.ToArray()!; + results.ShouldAllBe(r => StatusCode.IsGood(r.StatusCode)); + results.ShouldAllBe(r => Values(r).Count == 3); + connections.HistoryCallSizes.ShouldBe([2, 1]); + foreach (var r in results) await RawHistory(client, children[Array.IndexOf(results, r)], 3, r.ContinuationPoint); + }, localPermissions: 15, allowHistory: true, connectionSource: connections); + } + + [Fact(Timeout = 90000)] + [Trait("Phase", "H3")] + public async Task The_assembly_budget_is_charged_in_request_order_across_groups() + { + // H3 review D7: request [A fresh, B resumed, C fresh] runs as two groups ({A, C} then {B}); with room for two nodes the + // refused one must be C — the last in REQUEST order — not B. + await using var originServer = await HistoryOrigin.StartAsync(7, extra: 2); + using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, history: originServer.Port); + await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray(); + children.Length.ShouldBe(3); + var first = await RawHistory(client, children[1], 3, default); + first.ContinuationPoint.IsEmpty.ShouldBeFalse(); + var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false, + [new HistoryReadValueId { NodeId = children[0] }, new HistoryReadValueId { NodeId = children[1], ContinuationPoint = first.ContinuationPoint }, + new HistoryReadValueId { NodeId = children[2] }], TestContext.Current.CancellationToken); + var results = response.Results.ToArray()!; + StatusCode.IsGood(results[0].StatusCode).ShouldBeTrue(results[0].StatusCode.ToString()); + StatusCode.IsGood(results[1].StatusCode).ShouldBeTrue("the resumed node is second in request order: it fits"); + results[2].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code); + Values(results[2]).ShouldBeEmpty(); + }, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin), + configureMapping: m => m.MaxHistoryAssemblyBytesPerRequest = 2 * 3 * 288 + 100); // ≈ 288 B a value: two 3-value nodes fit + } + + [Fact(Timeout = 90000)] + [Trait("Phase", "H3")] + public async Task Releases_queued_while_a_flush_is_finishing_are_never_lost() + { + // H3 review D6: the flush used to be re-armed from Task.IsCompleted, so a token queued after its last check but before it + // completed waited for the NEXT release — or forever. Many concurrent enqueues must all reach the connection. + await using var originServer = await HistoryOrigin.StartAsync(1); + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); + var connections = new HistorySwitchConnections(origin); + ProjectedHistoryAccess? history = null; + await WithComposedServer(origin, origin.Raw, async (_, _, _, _, _, _, _) => + { + const int count = 2000; + await Task.WhenAll(Enumerable.Range(0, 8).Select(t => Task.Run(() => + { + for (var i = t; i < count; i += 8) history!.EnqueueReleaseForTests("link", BitConverter.GetBytes(i)); + }))); + var deadline = DateTime.UtcNow.AddSeconds(20); + while (connections.ReleasedTokens < count && DateTime.UtcNow < deadline) + { + await history!.FlushReleasesForTestsAsync(); + await Task.Delay(10, TestContext.Current.CancellationToken); + } + connections.ReleasedTokens.ShouldBe(count); + }, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (h, _) => history = h); + } + // ------------------------------------------------------------------------------------------------------------------ private static ReadRawModifiedDetails RawDetails(uint count) => new() @@ -278,6 +423,73 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests } } + public enum HistoryMode { Pass, Hang, Throw } + + /// + /// One long-lived origin connection whose HISTORY path can be switched to never answer (then fault as a cancelled gRPC call, + /// as a probe cancelled by its deadline did) or to fault at once; releases always pass through and are counted. + /// + private sealed class HistorySwitchConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource + { + private IDataConnection? _inner; + private readonly object _gate = new(); + private int _released; + private readonly List _sizes = []; + public HistoryMode Mode { get; set; } + public int ReleasedTokens => Volatile.Read(ref _released); + public IReadOnlyList HistoryCallSizes { get { lock (_sizes) return _sizes.ToArray(); } } + + public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) + { + if (connectionId != "link") return ValueTask.FromResult(null); + lock (_gate) _inner ??= peer.Connection(); + return ValueTask.FromResult(new Borrowed(new Switch(_inner, this), _gate)); + } + + private sealed class Borrowed(IDataConnection connection, object route) : IGrpcDataAdapterConnectionLease + { + public IDataConnection Connection => connection; + public CancellationToken CancellationToken => CancellationToken.None; + public object? RouteIdentity => route; + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + + private sealed class Switch(IDataConnection inner, HistorySwitchConnections owner) : IDataConnection, IDataHistoryService + { + public DataTarget Target => inner.Target; + public TimeProvider Clock => inner.Clock; + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken); + public Task BrowseAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest request, CancellationToken cancellationToken) => inner.BrowseAsync(request, cancellationToken); + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => inner.GetMetadataAsync(request, cancellationToken); + public Task> ReadAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest request, CancellationToken cancellationToken) => inner.ReadAsync(request, cancellationToken); + public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken); + public Task SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken); + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + + public async Task> ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) + { + lock (owner._sizes) owner._sizes.Add(request.Items.Count); + switch (owner.Mode) + { + case HistoryMode.Hang: + try { await Task.Delay(Timeout.Infinite, cancellationToken); } + catch (OperationCanceledException ex) + { throw new Grpc.Core.RpcException(new Grpc.Core.Status(Grpc.Core.StatusCode.Cancelled, "probe cancelled", ex)); } + break; + case HistoryMode.Throw: + throw new Grpc.Core.RpcException(new Grpc.Core.Status(Grpc.Core.StatusCode.Internal, "boom")); + } + return await ((IDataHistoryService)inner).ReadAsync(request, cancellationToken); + } + + public async Task ReleaseAsync(IReadOnlyList continuations, CancellationToken cancellationToken) + { + Interlocked.Add(ref owner._released, continuations.Count); + await ((IDataHistoryService)inner).ReleaseAsync(continuations, cancellationToken); + } + } + } + /// One long-lived origin connection, as a deployed gRPC connection is; replaces it (a redeploy). private sealed class PersistentConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource { @@ -324,7 +536,8 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests private HistoryOrigin(OpcUaApplicationHost host, string pki, OtOpcUaNodeManager nm, SeriesSource source) { _host = host; _pki = pki; _nm = nm; Source = source; Port = new OriginHistoryPort(nm); } - public static async Task StartAsync(int samples, int maxRawPerRead = 0, int extra = 0) + public static async Task StartAsync(int samples, int maxRawPerRead = 0, int extra = 0, string dataType = "Int32", + Func? value = null) { var pki = Path.Combine(Path.GetTempPath(), $"h3-origin-{Guid.NewGuid():N}"); var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions @@ -334,9 +547,9 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests }, NullLogger.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken); var nm = started.Server.NodeManager!; var source = new SeriesSource(Enumerable.Range(0, samples) - .Select(i => new DataValueSnapshot(i, 0, HistoryT0.AddSeconds(i), HistoryT0.AddSeconds(i))).ToArray()) { MaxRawValuesPerRead = maxRawPerRead }; + .Select(i => new DataValueSnapshot(value?.Invoke(i) ?? i, 0, HistoryT0.AddSeconds(i), HistoryT0.AddSeconds(i))).ToArray()) { MaxRawValuesPerRead = maxRawPerRead }; nm.HistorianDataSource = source; - nm.EnsureVariable("Plant/Driver/Device/Speed", null, "Speed", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed"); + nm.EnsureVariable("Plant/Driver/Device/Speed", null, "Speed", dataType, false, AddressSpaceRealm.Raw, historianTagname: "speed"); nm.EnsureVariable("Plant/Driver/Device/Other", null, "Other", "Int32", false, AddressSpaceRealm.Raw); for (var i = 0; i < extra; i++) nm.EnsureVariable("Plant/Driver/Device/Speed" + i, null, "Speed" + i, "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed" + i); @@ -381,7 +594,8 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests public Task ReadAtTimeAsync(string fullReference, IReadOnlyList timestampsUtc, CancellationToken cancellationToken) { Interlocked.Increment(ref _calls); - return Task.FromResult(new HistorianRead(timestampsUtc.Select(t => new DataValueSnapshot(1, 0, t, t)).ToList(), null)); + return Task.FromResult(new HistorianRead(timestampsUtc.Select(t => series.LastOrDefault(s => s.SourceTimestampUtc <= t) + ?? new DataValueSnapshot(null, 0x809B0000u, t, t)).Select(s => s with { SourceTimestampUtc = s.SourceTimestampUtc }).ToList(), null)); } public Task ReadEventsAsync(