Merge driver follow-ups A: Modbus RTU response correlation + cancel redial + rebuild e2e (#1029/#1055), MTConnect malformed-item BadDecodingError + cross-chunk condition severity (#1055/#1037), TwinCAT write fail-fast + retired-client reads (#1035), OpcUaClient skipped-tag ledger append + zone-qualified IPv6 probe (#1039)

This commit is contained in:
Joseph Doherty
2026-12-03 15:25:42 -05:00
28 changed files with 1137 additions and 38 deletions
@@ -0,0 +1,152 @@
using System.Collections.Concurrent;
using Akka.Actor;
using Akka.TestKit;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Engines;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Modbus;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
/// <summary>
/// #1029 / #981 S-2 end to end: a deploy that fully REBUILDS the address space while a REAL
/// <see cref="ModbusDriver"/> is kept (its config is untouched) recreates every node at
/// <c>BadWaitingForInitialData</c> and re-subscribes the driver. The driver's deadband baseline from the earlier
/// subscription must not swallow the forced first raise, or a tag whose device value is still inside its deadband
/// (what a deadband is for) stays Bad until the process value drifts. A node-modelling sink stands in for the OPC UA
/// node manager: it resets every node on rebuild and only a driver publish makes one Good again.
/// </summary>
[Collection("opcua-publish-meters")]
public sealed class ModbusDeployRebuildEndToEndTests : RuntimeActorTestBase
{
private static readonly NodeId TestNode = NodeId.Parse("node-1:4054");
private const string SpeedPath = "Plant/Modbus/dev1/speed";
private const uint Good = 0;
private const string SpeedTagConfig = """{"region":"HoldingRegisters","address":0,"dataType":"Int16","byteOrder":"BigEndian","bitIndex":0,"stringLength":0,"deadband":5}""";
private static readonly (string, string, string, string, string, bool)[] Initial =
[("drv-1", "Modbus", "dev1", "speed", "Int16", false), ("drv-2", "Modbus2", "dev2", "pressure", "Float", false)];
// drv-2's driver folder renamed: a raw CONTAINER rename = full rebuild; drv-1 (the real Modbus driver) is untouched.
private static readonly (string, string, string, string, string, bool)[] Renamed =
[("drv-1", "Modbus", "dev1", "speed", "Int16", false), ("drv-2", "Modbus2Renamed", "dev2", "pressure", "Float", false)];
private static RevisionHash Rev(char c) => RevisionHash.Parse(new string(c, 64));
[Fact]
public void A_full_rebuild_with_a_kept_Modbus_driver_leaves_no_deadbanded_node_at_BadWaitingForInitialData()
{
var ct = TestContext.Current.CancellationToken;
var db = NewInMemoryDbFactory();
var sink = new NodeModelSink();
var factory = new KeptModbusFactory();
var coordinator = CreateTestProbe();
var publish = Sys.ActorOf(OpcUaPublishActor.PropsForTests(
sink: sink, applier: new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance)));
var host = Sys.ActorOf(DriverHostActor.Props(
db, TestNode, coordinator.Ref, driverFactory: factory,
localRoles: new HashSet<string> { "driver" }, dependencyMux: CreateTestProbe().Ref,
opcUaPublishActor: publish, virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
virtualTagHostOverride: CreateTestProbe().Ref));
void Deploy((string, string, string, string, string, bool)[] tags, RevisionHash rev)
{
var id = V3ArtifactSeeder.SeedV3Deployment(db, rev, tags, [], enabled: true,
tagConfigByTag: new Dictionary<string, string> { ["speed"] = SpeedTagConfig },
driverConfigByDriver: new Dictionary<string, string> { ["drv-1"] = """{"host":"fake","probe":{"enabled":false}}""" });
host.Tell(new DispatchDeployment(id, rev, CorrelationId.NewId()));
var ack = coordinator.FishForMessage<ApplyAck>(m => m.DeploymentId == id, PresenceBudget, cancellationToken: ct);
ack.Outcome.ShouldBe(ApplyAckOutcome.Applied);
ack.Degraded.ShouldBeFalse(ack.DegradedReason);
}
Deploy(Initial, Rev('a'));
AwaitAssert(() => sink.StatusOf(SpeedPath).ShouldBe(Good, "the first deploy's initial publish; log: " + string.Join(";", sink.Log)), PresenceBudget, cancellationToken: ct);
factory.Transport.Reads.ShouldBeGreaterThan(0);
// Same device value (inside the 5-unit deadband); the rebuild resets the node and the kept driver is re-subscribed.
Deploy(Renamed, Rev('b'));
sink.RebuildCount.ShouldBe(1, "the container rename must be a full rebuild");
AwaitAssert(() => sink.StatusOf(SpeedPath).ShouldBe(Good,
"the rebuilt node must receive the kept driver's first raise, not stay BadWaitingForInitialData"),
PresenceBudget, cancellationToken: ct);
factory.Created.ShouldBe(1, "the Modbus driver must have been KEPT across the rebuild, not respawned");
}
private sealed class ConstantTransport : IModbusTransport
{
private int _reads;
public int Reads => Volatile.Read(ref _reads);
public Task ConnectAsync(CancellationToken ct) => Task.CompletedTask;
public Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
{
Interlocked.Increment(ref _reads);
return Task.FromResult(new byte[] { 3, 2, 0, 100 }); // register = 100, forever
}
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
/// <summary>Materialises ONE real Modbus driver for drv-1 (deadband 5); everything else is a recording stub.</summary>
private sealed class KeptModbusFactory : IDriverFactory
{
private readonly RecordingSubscribableDriverFactory _others = new("Modbus");
private int _created;
public ConstantTransport Transport { get; } = new();
public ModbusDriver? Driver;
public int Created => Volatile.Read(ref _created);
public IDriver? TryCreate(string driverType, string driverInstanceId, string driverConfigJson)
{
if (driverInstanceId != "drv-1") return _others.TryCreate(driverType, driverInstanceId, driverConfigJson);
Interlocked.Increment(ref _created);
// The deploy folds the artifact's raw tags + driver config into driverConfigJson and the driver re-parses it at
// Initialize, so only the TRANSPORT is injected here.
return Driver = new ModbusDriver(new ModbusDriverOptions { Host = "fake" }, driverInstanceId, _ => Transport);
}
public IReadOnlyCollection<string> SupportedTypes => ["Modbus"];
}
/// <summary>Models node status: a created/rebuilt variable is BadWaitingForInitialData until a value is written.</summary>
private sealed class NodeModelSink : IOpcUaAddressSpaceSink
{
private const uint BadWaiting = 0x80320000;
private readonly ConcurrentDictionary<string, uint> _status = new();
public int RebuildCount;
public ConcurrentQueue<string> Log = new();
public uint StatusOf(string nodeId) => _status.TryGetValue(nodeId, out var s) ? s : uint.MaxValue;
public void WriteValue(string nodeId, object? value, uint statusCode, DateTime sourceTimestampUtc, AddressSpaceRealm realm = AddressSpaceRealm.Uns)
{
Log.Enqueue($"W {nodeId} {statusCode:X}");
if (_status.ContainsKey(nodeId)) _status[nodeId] = statusCode; // writes are non-creating, like the real node manager
}
public void WriteAlarmQuality(string alarmNodeId, uint statusCode, DateTime sourceTimestampUtc, AddressSpaceRealm realm) { }
public void WriteAlarmCondition(string alarmNodeId, AlarmConditionSnapshot state, DateTime occurredUtc, AddressSpaceRealm realm = AddressSpaceRealm.Uns) { }
public void MaterialiseAlarmCondition(string alarmNodeId, string equipmentNodeId, string displayName, string alarmType, int severity, AddressSpaceRealm realm, bool isNative = false) { }
public void EnsureFolder(string folderNodeId, string? parentNodeId, string displayName, AddressSpaceRealm realm = AddressSpaceRealm.Uns) { }
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, AddressSpaceRealm realm, string? historianTagname = null, bool isArray = false, uint? arrayLength = null, bool refuseArrayOnScalar = false) =>
LogAndAdd(variableNodeId);
private void LogAndAdd(string id) { Log.Enqueue("E " + id); _status.TryAdd(id, BadWaiting); }
public void RebuildAddressSpace()
{
Interlocked.Increment(ref RebuildCount);
_status.Clear();
}
public void RaiseNodesAddedModelChange(string affectedNodeId, AddressSpaceRealm realm = AddressSpaceRealm.Uns) { }
public void WireAlarmNotifiers(string alarmNodeId, AddressSpaceRealm alarmRealm, IReadOnlyList<string> notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm) { }
public void AddReference(string sourceNodeId, AddressSpaceRealm sourceRealm, string targetNodeId, AddressSpaceRealm targetRealm, string referenceType = "Organizes") { }
}
}
@@ -55,6 +55,8 @@ public static class V3ArtifactSeeder
/// hand that child an explicit EMPTY set rather than skipping it.</param>
/// <param name="virtualTags">Optional Equipment VirtualTags (#995): each gets its own script row with
/// <c>Source</c> as its body; <c>EquipmentId</c> must name a seeded equipment (<c>EQ-{area}-{line}-{equip}</c>).</param>
/// <param name="driverConfigByDriver">Optional <c>DriverConfig</c> JSON per driver id (the deploy folds the raw
/// tags into it); absent ids keep <c>"{}"</c>.</param>
/// <returns>The seeded deployment's id.</returns>
public static DeploymentId SeedV3Deployment(
IDbContextFactory<OtOpcUaConfigDbContext> db, RevisionHash rev,
@@ -64,15 +66,17 @@ public static class V3ArtifactSeeder
IReadOnlyDictionary<string, string>? tagConfigByTag = null,
string[]? taglessDrivers = null,
IReadOnlyDictionary<string, Guid>? driverRowIds = null,
(string VirtualTagId, string EquipmentId, string Name, string Source)[]? virtualTags = null)
(string VirtualTagId, string EquipmentId, string Name, string Source)[]? virtualTags = null,
IReadOnlyDictionary<string, string>? driverConfigByDriver = null)
{
string ConfigOf(string id) => driverConfigByDriver is not null && driverConfigByDriver.TryGetValue(id, out var c) ? c : "{}";
Guid RowId(string id) => driverRowIds is not null && driverRowIds.TryGetValue(id, out var g) ? g : Guid.Empty;
var drivers = rawTags
.Select(t => (t.Driver, t.DriverName))
.Distinct()
.Select(d => new { DriverInstanceRowId = RowId(d.Driver), DriverInstanceId = d.Driver, RawFolderId = "rf-plant", Name = d.DriverName, DriverType = "Modbus", DriverConfig = "{}", ClusterId = "c1", Enabled = enabled })
.Select(d => new { DriverInstanceRowId = RowId(d.Driver), DriverInstanceId = d.Driver, RawFolderId = "rf-plant", Name = d.DriverName, DriverType = "Modbus", DriverConfig = ConfigOf(d.Driver), ClusterId = "c1", Enabled = enabled })
.Concat((taglessDrivers ?? Array.Empty<string>())
.Select(id => new { DriverInstanceRowId = RowId(id), DriverInstanceId = id, RawFolderId = "rf-plant", Name = id, DriverType = "Modbus", DriverConfig = "{}", ClusterId = "c1", Enabled = enabled }))
.Select(id => new { DriverInstanceRowId = RowId(id), DriverInstanceId = id, RawFolderId = "rf-plant", Name = id, DriverType = "Modbus", DriverConfig = ConfigOf(id), ClusterId = "c1", Enabled = enabled }))
.ToArray();
var devices = rawTags
.Select(t => (t.Driver, t.Device))