Merge runtime follow-ups: a retired driver child's late ConnectivityChanged no longer overrules a connected replacement (#1070, race confirmed deterministically), node-manager-only wiring guard for the authorizer delegates (#1079)

This commit is contained in:
Joseph Doherty
2026-12-04 14:11:56 -05:00
7 changed files with 454 additions and 4 deletions
+5
View File
@@ -139,6 +139,11 @@ non-`Healthy` state **and** its `LastSuccessfulRead` has been frozen for 90 s. T
`forceRaise`, MQTT's new initial push). Instead the host **audits**: refs still latched 30 s after a
reconnect log a Warning and increment `otopcua.driver.comms_latched_refs`. Non-zero on that counter
means a driver reconnects without re-publishing.
- ⚠️ **A stopped incarnation's late connectivity is dropped once its replacement connected (#1070).** A Restart /
respawn's old child announces Bad from `PostStop`, which can land AFTER the new child connected and pushed (two
senders, no ordering) — it used to stick the nodes Bad and cancel the audit. `IsStaleRetiredConnectivity` drops a
retired child's `Connected=true` always and its `false` once the current child is `Connected`; before that the Bad
edge still covers the gap. `DriverHostStaleConnectivityTests`.
- **Every dedup on the recovery path is keyed on (value, status), not value.** A device that comes back
usually comes back holding the same reading, so a value-only dedup swallows the recovery and the node
stays Bad forever — the v3-gate trap, now closed in the Calculation driver, the virtual-tag actor and
+11
View File
@@ -603,6 +603,17 @@ An operator **Restart** deliberately KEEPS the latch (#1053): the nodes stay in
respawned incarnation is what must re-publish them. The stopped incarnation's `PostStop` comms-loss announcement re-latches
the current ref set and cancels the audit the old incarnation armed; the new incarnation's `Connected` re-arms it.
⚠️ **A stopped incarnation's connectivity can arrive late, and is then dropped (#1070).** `Context.Stop` is asynchronous and
messages from two children are not ordered, so the old child's `PostStop` `ConnectivityChanged(false)` can reach the host
AFTER the replacement connected and pushed its initial values — the old child gets to its stop only once whatever it is
running returns (a synchronous driver call such as a health publish). Applied then, it stamped every value node
`BadNoCommunication` with nothing left to re-publish them, re-latched them and cancelled the new incarnation's audit: nodes
stuck Bad with the tripwire disarmed. `DriverHostActor.IsStaleRetiredConnectivity` now drops, whole, any `Connected=true` from a
retired child and its `Connected=false` once the current child of the same id has announced Connected (`ChildEntry.Connected`).
A retired child's Bad edge is still applied while the replacement has not connected (or there is none) — that is the gap
cover above. Same rule the condition-signal tracker already applied. Pinned by `DriverHostStaleConnectivityTests` (the race
made deterministic by wedging the old child in `GetHostStatuses`).
### The connect path feeds the circuit breaker (R2-10 T10 closure)
`IDriver.InitializeAsync` is routed through the capability invoker as
+3 -1
View File
@@ -853,7 +853,9 @@ Behaviours worth knowing before enabling it:
deploy; only gRPC-data projected / imported-condition items, gated in both modes, can lapse (#972 — between
`8ad03e9c5` and the fix, the pass enforced grants with the flag off). With the flag off a local Raw/UNS item is
answered allow before the pass's memo (#1033: a 10k-item pass ~6.5–7 ms / ~1.4 MB ⇒ ~0.5–1 ms / ~0.2 KB; the same
shortcut in the per-request `Permits` was measured and not taken — a 1,000-node Read did not change). Without the timer a key that expired by the
shortcut in the per-request `Permits` was measured and not taken — a 1,000-node Read did not change; it relies on the node
manager being the only wirer of the authorizer's `ImportedConditionClassifier` / `MappedNamespacePredicate`, to its own
delegates — source-scan guard `AuthorizerClassifierWiringGuardTests`, #1079). Without the timer a key that expired by the
clock kept streaming until a deployment happened to land — **indefinitely** on a fleet that has been
deployed once and left running, which is exactly the shape a production fleet settles into.
@@ -6314,7 +6314,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
/// (<see cref="IsProjectedDescendant"/>) only [2]/[3], and <c>AuthorizeIfRequired</c> then takes the
/// <c>localBypass</c>. The one wiring where the full path differs — a mapped-subject resolver with no projected
/// predicate, which asks the resolver about every node and denies the local ones it cannot place — is excluded, so
/// that configuration keeps its existing verdict.
/// that configuration keeps its existing verdict. Sound only because this manager is the sole wirer of both delegates,
/// to its own methods — pinned by <c>AuthorizerClassifierWiringGuardTests</c> (#1079).
/// </summary>
/// <remarks>
/// Measured (10k flag-off items): a pass went from ~6.5–7 ms and ~1.4 MB (the pass-local memo's tuple keys and
@@ -765,6 +765,12 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// <summary>When this child was spawned — the diagnostics' last-change time until it publishes health.</summary>
public DateTime SpawnedUtc { get; } = DateTime.UtcNow;
/// <summary>
/// The last connectivity edge THIS incarnation announced (false until its first <c>Connected=true</c>).
/// #1070: a stopped predecessor's late Bad edge is dropped once this is true.
/// </summary>
public bool Connected { get; set; }
// Convenience accessors for sites that don't need the full spec.
/// <summary>Gets the driver type name from the child's spec.</summary>
public string DriverType => Spec.DriverType;
@@ -2006,8 +2012,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
private void ForwardBatchToMux(DriverInstanceActor.AttributeValueBatchPublished msg)
{
// A burst from an incarnation this host already stopped: forwarding it would undo the SourceRemoved
// eviction (see _retiredChildren). Its ConnectivityChanged is NOT filtered — the respawn path relies on
// that Bad fan to cover the gap.
// eviction (see _retiredChildren). Its ConnectivityChanged is filtered only once the replacement has
// connected (#1070, IsStaleRetiredConnectivity) — until then the respawn path relies on that Bad fan to
// cover the gap.
if (_retiredChildren.Contains(Sender))
{
_log.Debug("DriverHost {Node}: dropped a {Count}-item value burst from a stopped incarnation of {Id}",
@@ -2125,6 +2132,17 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// </summary>
private void OnDriverConnectivityChanged(DriverInstanceActor.ConnectivityChanged msg)
{
if (IsStaleRetiredConnectivity(msg))
{
_log.Debug(
"DriverHost {Node}: dropped a stale ConnectivityChanged(connected={Connected}) for {Id} from a stopped incarnation ({Stale})",
_localNode, msg.Connected, msg.DriverInstanceId, Sender);
return;
}
if (_children.TryGetValue(msg.DriverInstanceId, out var announcing) && Equals(announcing.Actor, Sender))
announcing.Connected = msg.Connected;
if (msg.Connected && _acquisitionDemands.ContainsKey(msg.DriverInstanceId) &&
_children.TryGetValue(msg.DriverInstanceId, out var activeChild) && Equals(activeChild.Actor, Sender))
SendDesiredSubscriptions(activeChild.Actor, msg.DriverInstanceId);
@@ -2178,6 +2196,38 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_localNode, msg.DriverInstanceId, msg.Connected ? "connected" : "disconnected", annotated, statusCode);
}
/// <summary>
/// #1070 — whether <paramref name="msg"/> comes from a child this host already stopped (a
/// <see cref="_retiredChildren"/> member) and would overrule the CURRENT incarnation's state.
/// </summary>
/// <remarks>
/// <para>
/// <c>Context.Stop</c> is asynchronous and messages from two different children are not ordered, so a
/// stopped child's <c>PostStop</c> comms-loss announcement can reach this host AFTER its replacement
/// connected and published its initial push — the old child only gets to its stop once whatever it is
/// running returns (a synchronous driver call, e.g. a health publish). Applied then, it stamped every value
/// node <c>BadNoCommunication</c> with nothing left to re-publish them, re-latched them and cancelled the
/// recovery audit the new incarnation had armed: nodes stuck Bad with the tripwire disarmed.
/// </para>
/// <para>
/// Stale, and dropped whole: any <c>Connected=true</c> from a retired child (it vouches for a connection
/// that has been torn down — applied, it would arm an audit and annotate conditions Good for a driver
/// that may not be connected yet), and its <c>Connected=false</c> once the current child of the same id
/// has announced it is connected. A retired child's Bad edge is still APPLIED while the replacement has
/// not connected (or there is none): that is the 03/S15 gap cover an operator Restart and a respawn rely
/// on, and the replacement's own push clears it. Same rule the condition-signal tracker already applies
/// (<c>OnConditionSignalConnectivity</c>). A sender that was never a child of this host is not filtered.
/// </para>
/// </remarks>
/// <param name="msg">The connectivity announcement; <c>Sender</c> is its producer.</param>
/// <returns><see langword="true"/> when the message must be dropped.</returns>
private bool IsStaleRetiredConnectivity(DriverInstanceActor.ConnectivityChanged msg)
{
if (!_retiredChildren.Contains(Sender)) return false;
if (msg.Connected) return true;
return _children.TryGetValue(msg.DriverInstanceId, out var current) && current.Connected;
}
/// <summary>
/// Archreview <b>03/S15</b> — the value-node half of the comms-loss fan-out: stamp
/// <see cref="OpcUaStatus.BadNoCommunication"/> on every raw NodeId <b>and</b> every referencing UNS
@@ -0,0 +1,147 @@
using System.Text.RegularExpressions;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
/// <summary>
/// #1079 — the node manager is the ONLY code that wires <c>DataPlaneAuthorizer.ImportedConditionClassifier</c> and
/// <c>DataPlaneAuthorizer.MappedNamespacePredicate</c>, and it wires them only to its own
/// <c>ClassifyImportedCondition</c> / <c>IsProjectedDescendant</c>.
/// </summary>
/// <remarks>
/// <para>
/// Why it matters: the #1033 flag-off revalidation fast path (<c>OtOpcUaNodeManager.IsLocalNodeUngated</c>) answers a
/// local Raw/UNS item "allow" WITHOUT consulting the authorizer, on the reasoning that the imported-condition
/// classifier answers only the imported-condition namespace and the projected predicate only the projected ones —
/// so for a node in the manager's own Raw/UNS namespaces both would have passed it through to the
/// <c>localBypass</c>. That holds only for the node manager's own delegates. A second wiring site (a host, a
/// service, a test seam promoted to production) that installed a broader classifier would change the full path's
/// verdict while the fast path kept answering allow — two answers to one question, with nothing failing.
/// </para>
/// <para>
/// A textual scan over <c>src/**/*.cs</c> (the <c>RoleAuthorityGuardTests</c> idiom), because the thing guarded is
/// an assignment site, which reflection cannot see. Tests are not scanned: they set these on a standalone
/// authorizer that has no node manager and so no fast path.
/// </para>
/// <para>
/// <b>Falsification control:</b> <see cref="The_scan_detects_a_second_wiring_site_and_a_foreign_delegate"/> feeds the
/// same scan offending snippets and asserts it flags each — proof the guard can fail.
/// </para>
/// </remarks>
public sealed class AuthorizerClassifierWiringGuardTests
{
private const string NodeManagerFile = "OtOpcUaNodeManager.cs";
/// <summary>The one delegate each property may be given (or null, via a ternary's null arm).</summary>
private static readonly IReadOnlyDictionary<string, string> AllowedDelegate = new Dictionary<string, string>
{
["ImportedConditionClassifier"] = "ClassifyImportedCondition",
["MappedNamespacePredicate"] = "IsProjectedDescendant",
};
/// <summary>An assignment (plain, <c>??=</c>, or an object-initializer member) — not <c>==</c> or <c>=&gt;</c>.</summary>
private static readonly Regex Assignment = new(
@"\b(?<prop>ImportedConditionClassifier|MappedNamespacePredicate)\s*(?:\?\?=|=(?![=>]))\s*(?<rhs>[^;,}]*)",
RegexOptions.Compiled);
/// <summary>An allowed right-hand side: the method group alone, or <c>cond ? null : MethodGroup</c>.</summary>
private static readonly Regex AllowedRhs = new(
@"^(?:[^?;]+\?\s*null\s*:\s*)?(?<method>[A-Za-z_][A-Za-z0-9_]*)\s*$",
RegexOptions.Compiled);
[Fact]
public void Only_the_node_manager_wires_the_classifier_and_the_predicate_and_only_to_its_own_delegates()
{
var found = new Dictionary<string, int>();
var violations = new List<string>();
foreach (var path in SourceFiles())
{
var (fileViolations, assignments) = Scan(Path.GetFileName(path), File.ReadAllText(path));
violations.AddRange(fileViolations.Select(v => $"{Path.GetRelativePath(SolutionRoot(), path)}:{v}"));
if (Path.GetFileName(path) == NodeManagerFile)
foreach (var prop in assignments) found[prop] = found.GetValueOrDefault(prop) + 1;
}
violations.ShouldBeEmpty(
"the #1033 flag-off fast path (IsLocalNodeUngated) assumes only OtOpcUaNodeManager wires these, to its own delegates");
// Non-vacuity: the scan must actually see the real wiring sites, or a regex drift would pass silently.
found.GetValueOrDefault("ImportedConditionClassifier").ShouldBeGreaterThanOrEqualTo(1);
found.GetValueOrDefault("MappedNamespacePredicate").ShouldBeGreaterThanOrEqualTo(1);
}
[Fact]
public void The_scan_detects_a_second_wiring_site_and_a_foreign_delegate()
{
Scan("Rogue.cs", " authorizer.MappedNamespacePredicate = _ => true;").Violations.Count.ShouldBe(1);
Scan("Rogue.cs", " var a = new DataPlaneAuthorizer(p) { ImportedConditionClassifier = (_, _, _) => null };")
.Violations.Count.ShouldBe(1);
Scan("Rogue.cs", " authorizer.ImportedConditionClassifier ??= Classify;").Violations.Count.ShouldBe(1);
Scan(NodeManagerFile, " value.MappedNamespacePredicate = _ => true;").Violations.Count.ShouldBe(1);
Scan(NodeManagerFile, " value.ImportedConditionClassifier = IsProjectedDescendant;").Violations.Count.ShouldBe(1);
// …and does not flag what is not a wiring: reads, comparisons, the declaration, a comment, the real shapes.
Scan("Rogue.cs", " if (authorizer.MappedNamespacePredicate is not null && x.ImportedConditionClassifier == y) { }")
.Violations.ShouldBeEmpty();
Scan("DataPlaneAuthorizer.cs", " public Func<NodeId, bool>? MappedNamespacePredicate { get; set; }").Violations.ShouldBeEmpty();
Scan("Rogue.cs", " // authorizer.MappedNamespacePredicate = _ => true;").Violations.ShouldBeEmpty();
Scan(NodeManagerFile,
" value.MappedNamespacePredicate = _projectedDataAccess is null ? null : IsProjectedDescendant;\n" +
" value.ImportedConditionClassifier = ClassifyImportedCondition; // A3: before RealmOf, always")
.Violations.ShouldBeEmpty();
}
/// <summary>Scans one file's text; returns violations (<c>line: text</c>) and the property of every assignment seen.</summary>
private static (List<string> Violations, List<string> Assignments) Scan(string fileName, string text)
{
var violations = new List<string>();
var assignments = new List<string>();
var lines = text.Split('\n');
for (var i = 0; i < lines.Length; i++)
{
var line = lines[i];
if (line.TrimStart().StartsWith("//", StringComparison.Ordinal)) continue;
var code = StripTrailingComment(line);
foreach (Match m in Assignment.Matches(code))
{
var prop = m.Groups["prop"].Value;
assignments.Add(prop);
if (fileName != NodeManagerFile)
{
violations.Add($"{i + 1}: {line.Trim()} (only {NodeManagerFile} may wire {prop})");
continue;
}
var rhs = AllowedRhs.Match(m.Groups["rhs"].Value.Trim());
if (!rhs.Success || rhs.Groups["method"].Value != AllowedDelegate[prop])
violations.Add($"{i + 1}: {line.Trim()} ({prop} may only be {AllowedDelegate[prop]} or null)");
}
}
return (violations, assignments);
}
private static string StripTrailingComment(string line)
{
var idx = line.IndexOf("//", StringComparison.Ordinal);
return idx < 0 ? line : line[..idx];
}
private static string SolutionRoot()
{
var dir = new DirectoryInfo(AppContext.BaseDirectory);
while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "ZB.MOM.WW.OtOpcUa.slnx")))
dir = dir.Parent;
dir.ShouldNotBeNull("Could not find solution root (ZB.MOM.WW.OtOpcUa.slnx).");
return dir!.FullName;
}
private static IEnumerable<string> SourceFiles()
{
var sep = Path.DirectorySeparatorChar;
return Directory.EnumerateFiles(Path.Combine(SolutionRoot(), "src"), "*.cs", SearchOption.AllDirectories)
.Where(f => !f.Contains($"{sep}obj{sep}", StringComparison.Ordinal)
&& !f.Contains($"{sep}bin{sep}", StringComparison.Ordinal));
}
}
@@ -0,0 +1,234 @@
using Akka.Actor;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
using static ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness.V3ArtifactSeeder;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
/// <summary>
/// <b>#1070 — a stopped incarnation's late <c>ConnectivityChanged(false)</c> must not overrule the live one.</b>
/// <para>
/// An operator Restart stops the old child (<c>Context.Stop</c> is asynchronous) and spawns its replacement in
/// the same handler. The old child announces comms loss from <c>PostStop</c>, which runs only once its mailbox
/// gets to the stop — and a child busy in a synchronous driver call gets there late. Messages from two
/// different senders are not ordered, so that announcement can reach the host AFTER the new incarnation has
/// connected and published its initial push. Applied then, it stamped every value node
/// <c>BadNoCommunication</c> (nothing re-publishes: the new child already did), re-latched them and cancelled
/// the new incarnation's recovery audit — nodes stuck Bad with the tripwire disarmed.
/// </para>
/// <para>
/// The race is made deterministic here: the old driver's <see cref="IHostConnectivityProbe.GetHostStatuses"/>
/// (called synchronously on the child's mailbox thread by its health publish) blocks on a gate, so the old
/// child cannot process its stop until the test releases it — after the new child's initial push has been
/// observed at the publish actor.
/// </para>
/// </summary>
public sealed class DriverHostStaleConnectivityTests : RuntimeActorTestBase
{
private static readonly NodeId TestNode = NodeId.Parse("driver-stale-connectivity");
private static readonly RevisionHash RevA = RevisionHash.Parse(new string('e', 64));
/// <summary>The child's reconnect retry runs on <c>DriverInstanceActor.DefaultReconnectInterval</c> (10 s), which the
/// host exposes no seam to shorten.</summary>
private static readonly TimeSpan ReconnectBudget = TimeSpan.FromSeconds(25);
private const string DriverId = "drv-stale";
private const string SpeedRef = "Plant/Modbus/dev1/speed";
/// <summary>
/// The old incarnation's Bad edge lands after the new incarnation connected and pushed Good. It must be dropped.
/// <para>
/// Positive control (the absence half is otherwise vacuous): after the stale message is provably in the
/// host's mailbox, a Force Reconnect of the CURRENT child must produce exactly one status batch before the
/// re-subscribe's value push. Pre-fix the stale announcement adds a second, earlier status batch.
/// </para>
/// </summary>
[Fact]
public void A_stopped_incarnations_late_comms_loss_after_the_new_one_connected_is_dropped()
{
var oldDriver = new GatedProbeDriver(DriverId);
var newDriver = new GatedProbeDriver(DriverId);
var (host, publish) = Arrange(new SequenceDriverFactory(oldDriver, newDriver));
// Steady state on the old incarnation: its subscribe pushed 5 Good.
publish.FishForMessage<OpcUaPublishActor.AttributeValueBatchUpdate>(_ => true, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
// Wedge the old child's mailbox thread inside a synchronous driver call.
oldDriver.BlockHostStatuses();
oldDriver.RaiseHostStatusChanged();
oldDriver.HostStatusesEntered.Wait(PresenceBudget, TestContext.Current.CancellationToken).ShouldBeTrue(
"the old child must be parked inside GetHostStatuses before the restart");
// Restart: the old child is stopped (its stop cannot run yet) and the new one spawns, connects and pushes.
host.Tell(new RestartDriver("c1", DriverId, "test-operator", Guid.NewGuid()));
var statusBefore = DrainUntilValueBatch(publish, PresenceBudget);
statusBefore.ShouldBe(0, "nothing may stamp Bad while the old child is wedged");
newDriver.SubscribeCount.ShouldBeGreaterThanOrEqualTo(1);
// Let the old child stop. Its PostStop Tells ConnectivityChanged(false) and THEN shuts the driver down, so once
// ShutdownAsync has been entered the stale message is already in the host's mailbox — ahead of anything the
// test sends from here on.
oldDriver.ReleaseHostStatuses();
AwaitCondition(() => oldDriver.ShutdownCalled, PresenceBudget, TestContext.Current.CancellationToken);
// Positive control: a real outage of the CURRENT incarnation.
host.Tell(new ReconnectDriver("c1", DriverId, "test-operator", Guid.NewGuid()));
var statusAfter = DrainUntilValueBatch(publish, ReconnectBudget);
statusAfter.ShouldBe(1,
"exactly the live incarnation's comms loss — a second batch is the stopped incarnation's late Bad overruling a connected driver");
}
/// <summary>
/// The other side of the rule (03/S15, kept): while the replacement has NOT yet connected, the stopped
/// incarnation's Bad edge is still the only thing covering the gap and must be applied.
/// </summary>
[Fact]
public void A_stopped_incarnations_comms_loss_before_the_new_one_connects_still_stamps_Bad()
{
var oldDriver = new GatedProbeDriver(DriverId);
var newDriver = new GatedProbeDriver(DriverId);
var hold = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
newDriver.InitializeGate = hold.Task;
var (host, publish) = Arrange(new SequenceDriverFactory(oldDriver, newDriver));
publish.FishForMessage<OpcUaPublishActor.AttributeValueBatchUpdate>(_ => true, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
host.Tell(new RestartDriver("c1", DriverId, "test-operator", Guid.NewGuid()));
var staled = publish.FishForMessage<OpcUaPublishActor.AttributeStatusBatchUpdate>(_ => true, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
staled.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.BadNoCommunication);
staled.Items.Select(i => i.NodeId).ShouldContain(SpeedRef);
// And the replacement's own push still recovers them.
hold.SetResult();
var recovered = publish.FishForMessage<OpcUaPublishActor.AttributeValueBatchUpdate>(_ => true, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
recovered.Items.ShouldAllBe(i => i.StatusCode == OpcUaStatus.Good);
}
private (IActorRef Host, Akka.TestKit.TestProbe Publish) Arrange(IDriverFactory factory)
{
var db = NewInMemoryDbFactory();
var deploymentId = SeedV3Deployment(db, RevA,
rawTags: new[] { (Driver: DriverId, DriverName: "Modbus", Device: "dev1", Tag: "speed", DataType: "Double", Writable: false) },
unsRefs: new[] { (Area: "filling", Line: "line1", Equip: "station1", BackingTag: "speed", Effective: (string?)null) },
enabled: true);
var (host, publish, _) = SpawnHostAndApply(this, db, TestNode, deploymentId, RevA, driverFactory: factory);
return (host, publish);
}
/// <summary>Counts status batches arriving at the publish probe until the next value batch, which it consumes.</summary>
private static int DrainUntilValueBatch(Akka.TestKit.TestProbe publish, TimeSpan budget)
{
var statusBatches = 0;
publish.FishForMessage(m =>
{
if (m is OpcUaPublishActor.AttributeStatusBatchUpdate s && s.Items.Any(i => i.NodeId == SpeedRef)) statusBatches++;
return m is OpcUaPublishActor.AttributeValueBatchUpdate;
}, budget, cancellationToken: TestContext.Current.CancellationToken);
return statusBatches;
}
/// <summary>Hands out the given drivers in order, one per spawn (the last one repeats).</summary>
private sealed class SequenceDriverFactory(params IDriver[] drivers) : IDriverFactory
{
private int _next;
public IDriver? TryCreate(string driverType, string driverInstanceId, string driverConfigJson) =>
drivers[Math.Min(Interlocked.Increment(ref _next) - 1, drivers.Length - 1)];
public IReadOnlyCollection<string> SupportedTypes { get; } = ["Modbus"];
}
/// <summary>
/// A subscribable driver that pushes the same 5 Good on every subscribe and whose
/// <see cref="GetHostStatuses"/> can be made to block — a synchronous call on the owning child's mailbox
/// thread, so a blocked call holds that child's stop back.
/// </summary>
private sealed class GatedProbeDriver(string instanceId) : IDriver, ISubscribable, IHostConnectivityProbe
{
private readonly StubHandle _handle = new();
private readonly ManualResetEventSlim _release = new(initialState: true);
private int _subscribeCount;
private volatile bool _blocking;
private volatile bool _shutdownCalled;
public event EventHandler<DataChangeEventArgs>? OnDataChange;
public event EventHandler<HostStatusChangedEventArgs>? OnHostStatusChanged;
public ManualResetEventSlim HostStatusesEntered { get; } = new();
public Task? InitializeGate { get; set; }
public int SubscribeCount => Volatile.Read(ref _subscribeCount);
public bool ShutdownCalled => _shutdownCalled;
public string DriverInstanceId => instanceId;
public string DriverType => "Modbus";
public void BlockHostStatuses()
{
_release.Reset();
_blocking = true;
}
public void ReleaseHostStatuses()
{
_blocking = false;
_release.Set();
}
public void RaiseHostStatusChanged() =>
OnHostStatusChanged?.Invoke(this, new HostStatusChangedEventArgs("dev1", HostState.Running, HostState.Stopped));
public IReadOnlyList<HostConnectivityStatus> GetHostStatuses()
{
if (_blocking)
{
HostStatusesEntered.Set();
_release.Wait(TimeSpan.FromSeconds(60));
}
return [new HostConnectivityStatus("dev1", HostState.Running, DateTime.UnixEpoch)];
}
public Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken) =>
InitializeGate is { } gate ? gate.WaitAsync(cancellationToken) : Task.CompletedTask;
public Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask;
public Task ShutdownAsync(CancellationToken cancellationToken)
{
_shutdownCalled = true;
return Task.CompletedTask;
}
// Stable health so the #527 watchdog never trips on its own.
public DriverHealth GetHealth() => new(DriverState.Healthy, DateTime.UtcNow, null);
public Task<ISubscriptionHandle> SubscribeAsync(
IReadOnlyList<string> fullReferences, TimeSpan publishingInterval, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _subscribeCount);
if (fullReferences.Contains(SpeedRef))
{
var snapshot = new DataValueSnapshot(5.0, OpcUaStatus.Good, DateTime.UtcNow, DateTime.UtcNow);
OnDataChange?.Invoke(this, new DataChangeEventArgs(_handle, SpeedRef, snapshot));
}
return Task.FromResult<ISubscriptionHandle>(_handle);
}
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken) => Task.CompletedTask;
}
}