diff --git a/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SitePairChannelProvider.cs b/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SitePairChannelProvider.cs index 27b3dffa..e121acf1 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SitePairChannelProvider.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Communication/Grpc/SitePairChannelProvider.cs @@ -427,31 +427,7 @@ public sealed class SitePairChannelProvider : IDisposable while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false)) { SweepGraveyard(); - var now = DateTime.UtcNow; - foreach (var kvp in _sites) - { - var pair = kvp.Value; - bool due; - lock (pair.Gate) - { - due = !pair.CurrentIsA && pair.ChannelA is not null && now >= pair.NextProbeUtc; - } - if (due) - { - try - { - await TryFailbackAsync(kvp.Key, ct).ConfigureAwait(false); - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception ex) - { - _logger.LogDebug(ex, "Failback probe for site {TargetSiteId} faulted", kvp.Key); - } - } - } + await RunDueFailbackProbesAsync(DateTime.UtcNow, ct).ConfigureAwait(false); } } catch (OperationCanceledException) @@ -460,6 +436,54 @@ public sealed class SitePairChannelProvider : IDisposable } } + /// COMM-8: how many failback probes one sweep runs concurrently. + internal const int FailbackProbeParallelism = 8; + + /// + /// COMM-8: probes every site that is due for failback at , + /// concurrently up to . The probes used to run one + /// after another, each up to its 5 s deadline, so 30 black-holed NodeAs made one pass take + /// ~150 s: a site whose NodeA had recovered waited minutes past its backoff, and the + /// graveyard sweep (which runs once per pass) stalled with it. Per-site state is guarded by + /// each pair's own gate, so concurrent probes of different sites do not interact. + /// + /// The time the due check is evaluated at. + /// Cancellation token. + /// A task that completes when every due probe has finished. + internal async Task RunDueFailbackProbesAsync(DateTime nowUtc, CancellationToken ct) + { + var due = new List(); + foreach (var kvp in _sites) + { + var pair = kvp.Value; + lock (pair.Gate) + { + if (!pair.CurrentIsA && pair.ChannelA is not null && nowUtc >= pair.NextProbeUtc) + due.Add(kvp.Key); + } + } + if (due.Count == 0) + return; + + await Parallel.ForEachAsync(due, + new ParallelOptions { MaxDegreeOfParallelism = FailbackProbeParallelism, CancellationToken = ct }, + async (siteId, token) => + { + try + { + await TryFailbackAsync(siteId, token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + throw; + } + catch (Exception ex) + { + _logger.LogDebug(ex, "Failback probe for site {TargetSiteId} faulted", siteId); + } + }).ConfigureAwait(false); + } + /// /// Parks a channel that is no longer reachable through instead of /// disposing it inline. diff --git a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealMxGatewayClient.cs b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealMxGatewayClient.cs index 7e0f0261..df58c538 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealMxGatewayClient.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealMxGatewayClient.cs @@ -679,16 +679,36 @@ public sealed class RealMxGatewayClient : IMxGatewayClient /// Maps MXAccess quality. A failing status proxy is authoritative bad; otherwise /// the OPC-style quality byte: ≥192 Good, ≥64 Uncertain, else Bad. /// - private static QualityCode MapQuality(int quality, IEnumerable statuses) + /// + /// DCL-10: on the per-value event path (~37 500 events/s per site at target). Takes the + /// concrete repeated field and index-loops it — IEnumerable.Any boxed the + /// repeated-field enumerator on every event although the list is normally empty or one + /// entry — and maps the quality byte through a static table (no per-call work beyond a + /// bounds check and an array read). + /// + internal static QualityCode MapQuality(int quality, IReadOnlyList statuses) { - if (statuses.Any(s => !s.IsSuccess())) - return QualityCode.Bad; - return quality switch + for (var i = 0; i < statuses.Count; i++) { - >= 192 => QualityCode.Good, - >= 64 => QualityCode.Uncertain, - _ => QualityCode.Bad, - }; + if (!statuses[i].IsSuccess()) + return QualityCode.Bad; + } + if (quality < 0) return QualityCode.Bad; + return quality < QualityByByte.Length ? QualityByByte[quality] : QualityCode.Good; + } + + /// + /// DCL-10: OPC-style quality byte → quality: ≥192 Good, ≥64 Uncertain, else Bad. Values above + /// 255 map to Good and negatives to Bad, exactly as the former range switch did. + /// + private static readonly QualityCode[] QualityByByte = BuildQualityMap(); + + private static QualityCode[] BuildQualityMap() + { + var map = new QualityCode[256]; + for (var q = 0; q < map.Length; q++) + map[q] = q >= 192 ? QualityCode.Good : q >= 64 ? QualityCode.Uncertain : QualityCode.Bad; + return map; } private static MxValue ToMxValue(object? value) => value switch diff --git a/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/Grpc/SitePairChannelProviderFailbackTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/Grpc/SitePairChannelProviderFailbackTests.cs index 7fef788c..7d1fe533 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/Grpc/SitePairChannelProviderFailbackTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/Grpc/SitePairChannelProviderFailbackTests.cs @@ -65,6 +65,49 @@ public class SitePairChannelProviderFailbackTests Assert.Equal(TimeSpan.FromSeconds(4), provider.GetFailbackBackoff(Site)); } + /// + /// COMM-8 (WP6 6.10): due failback probes run concurrently (bounded), so one slow NodeA per + /// site no longer serialises the pass — 16 sites with a 400 ms probe each finish in well + /// under the 6.4 s a serial pass takes, and never more than the bound run at once. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task DueProbes_RunConcurrently_UpToTheBound() + { + var inFlight = 0; + var maxInFlight = 0; + using var provider = Build(async (_, ct) => + { + var now = Interlocked.Increment(ref inFlight); + int seen; + while ((seen = Volatile.Read(ref maxInFlight)) < now && Interlocked.CompareExchange(ref maxInFlight, now, seen) != seen) { } + await Task.Delay(400, ct); + Interlocked.Decrement(ref inFlight); + return false; + }); + const int sites = 16; + for (var i = 0; i < sites; i++) + { + var site = $"site-{i}"; + provider.UpdateSite(site, $"http://localhost:{16000 + i}", $"http://localhost:{17000 + i}"); + GrpcChannel? first = null; + await provider.ExecuteAsync(site, (channel, _) => + { + if (first is null) { first = channel; throw GrpcRetrySafety.NotDispatched("not ready"); } + return Task.FromResult(1); + }, CancellationToken.None); + Assert.False(provider.IsOnPreferredNode(site)); + } + + var sw = System.Diagnostics.Stopwatch.StartNew(); + await provider.RunDueFailbackProbesAsync(DateTime.UtcNow.AddMinutes(1), CancellationToken.None); + sw.Stop(); + + Assert.True(sw.Elapsed < TimeSpan.FromSeconds(3), $"probe pass took {sw.ElapsedMilliseconds} ms"); + Assert.True(maxInFlight > 1, "probes did not run concurrently"); + Assert.True(maxInFlight <= SitePairChannelProvider.FailbackProbeParallelism); + } + /// Verifies that a successful real call on the preferred node after failback resets the backoff. /// A task that represents the asynchronous operation. [Fact] diff --git a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/MxGatewayQualityMapTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/MxGatewayQualityMapTests.cs new file mode 100644 index 00000000..e81cb400 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/MxGatewayQualityMapTests.cs @@ -0,0 +1,45 @@ +using Google.Protobuf.Collections; +using ZB.MOM.WW.MxGateway.Contracts.Proto; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol; +using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters; + +namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests; + +/// DCL-10 (WP6 6.10): MxGateway quality mapping is table-driven and allocation-free. +public class MxGatewayQualityMapTests +{ + /// The quality byte maps exactly as the former range switch did. + [Theory] + [InlineData(-5, QualityCode.Bad)] + [InlineData(0, QualityCode.Bad)] + [InlineData(63, QualityCode.Bad)] + [InlineData(64, QualityCode.Uncertain)] + [InlineData(191, QualityCode.Uncertain)] + [InlineData(192, QualityCode.Good)] + [InlineData(255, QualityCode.Good)] + [InlineData(1000, QualityCode.Good)] + public void QualityByte_Maps(int quality, QualityCode expected) + => Assert.Equal(expected, RealMxGatewayClient.MapQuality(quality, new RepeatedField())); + + /// A failing status is authoritative Bad; a success status defers to the byte. + [Fact] + public void FailingStatus_IsBad() + { + var ok = new RepeatedField { new MxStatusProxy { Category = MxStatusCategory.Ok } }; + var failing = new RepeatedField { new MxStatusProxy { Category = MxStatusCategory.Ok }, new MxStatusProxy() }; + Assert.Equal(QualityCode.Good, RealMxGatewayClient.MapQuality(192, ok)); + Assert.Equal(QualityCode.Bad, RealMxGatewayClient.MapQuality(192, failing)); + } + + /// The per-event path allocates nothing (the old Any() boxed the enumerator per call). + [Fact] + public void MapQuality_DoesNotAllocate() + { + var statuses = new RepeatedField { new MxStatusProxy { Category = MxStatusCategory.Ok } }; + RealMxGatewayClient.MapQuality(192, statuses); // warm + var before = GC.GetAllocatedBytesForCurrentThread(); + for (var i = 0; i < 10_000; i++) + RealMxGatewayClient.MapQuality(192, statuses); + Assert.Equal(0, GC.GetAllocatedBytesForCurrentThread() - before); + } +}