using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Health; using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime; using static ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime.GalaxyDriverFixRound1Tests; namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Health; /// /// #856: a platform must never be observable in /// before its probe binding resolves through the driver registry. The watcher records the handle /// and then publishes the binding inside one lock, but WatchedPlatforms used to read the /// handle map lock-free — so a caller could see the platform, raise a ScanState event, and have the /// pump drop it as "stale after unsubscribe" (host status stuck at Unknown). That is what made /// A_fetch_completing_after_init_populates_host_statuses time out under load. /// public sealed class PerPlatformProbeWatcherVisibilityTests { /// /// A reader spinning on WatchedPlatforms from another thread checks, at the first moment /// it sees the platform, that the registry already holds the probe entry. Before the fix this /// caught the torn state in ~85% of iterations; after it, the publish is part of what the /// reader's lock waits for, so the torn state is unobservable. /// [Fact] public async Task A_platform_visible_as_watched_already_resolves_through_the_registry() { const int iterations = 500; var ct = TestContext.Current.CancellationToken; var torn = 0; for (var i = 0; i < iterations; i++) { var registry = new SubscriptionRegistry(); var sub = new ParkableSubscriber(); using var watcher = new PerPlatformProbeWatcher(sub, new HostStatusAggregator(), registry); using var readerRunning = new ManualResetEventSlim(); var observed = Task.Run(() => { readerRunning.Set(); var deadline = DateTime.UtcNow.AddMilliseconds(WaitMs); while (watcher.WatchedPlatforms.Count == 0) { if (DateTime.UtcNow > deadline) throw new ShouldAssertException("the sync never recorded the platform"); } return registry.Contains(SubscriptionRegistry.ProbeSubscriptionId); }, ct); readerRunning.Wait(ct); await Task.Run(() => watcher.SyncPlatformsAsync(["P"], CancellationToken.None), ct); if (!await observed) torn++; } torn.ShouldBe(0, $"{torn}/{iterations} iterations saw a watched platform whose probe binding was not yet in the registry"); } }