Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/ModbusDeployRebuildEndToEndTests.cs
T
Joseph Doherty 0245641720 fix(modbus): #1029 RTU reply must answer its request (FC + write-echo address); e2e rebuild-with-kept-driver; #1055 AutoReconnect=false redials once after a caller-cancel discard
#1029: ModbusRtuFraming.ReadResponsePduAsync takes the request PDU and refuses a CRC-valid, right-unit reply whose
function code (exception frames included) or write-echo start address differs (new DesyncReason.ResponseMismatch).
Runtime.Tests e2e: a full rebuild with a kept real ModbusDriver (deadbanded tag, same device value) leaves no node at
BadWaitingForInitialData; falsified by removing the S-2 baseline clear. V3ArtifactSeeder gained driverConfigByDriver.

#1055 (Modbus half): the RTU transport's caller-cancel teardown now grants ONE redial even with AutoReconnect=false, so
an unsubscribe/probe cancel no longer leaves the transport dead until the 90 s watchdog re-init; a link fault still stays down.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 15:04:36 -05:00

153 lines
9.1 KiB
C#

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") { }
}
}