using Microsoft.Extensions.DependencyInjection;
using System.Net;
using System.Net.Sockets;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
using ZB.MOM.WW.OtOpcUa.Driver.Modbus;
namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests;
///
/// E2E integration coverage for the TestDriverConnect /
/// round-trip through the
/// AdminOperationsActor cluster singleton.
///
/// The positive test targets the Modbus Docker fixture that ships with the
/// lmxopcua-fix up modbus profile (default endpoint
/// 10.100.0.35:5020 from MODBUS_SIM_ENDPOINT). Outside owned fixture
/// mode the positive test skips when the fixture is unreachable. Negative tests own their
/// loopback sockets and require no external target.
///
[Trait("Category", "Integration")]
[Trait("Driver", "Modbus")]
public sealed class DriverTestConnectE2eTests
{
private const string DefaultEndpoint = "10.100.0.35:5020";
private const string EndpointEnvVar = "MODBUS_SIM_ENDPOINT";
private static bool LocalOnly => Environment.GetEnvironmentVariable("OTOPCUA_LOCAL_FIXTURE_MODE") == "1";
private static CancellationToken Ct => TestContext.Current.CancellationToken;
///
/// Resolves the Modbus sim endpoint from the environment (or falls back to the shared
/// Docker host default) and returns host + port separately.
///
private static (string host, int port) ResolveSimEndpoint()
{
var raw = Environment.GetEnvironmentVariable(EndpointEnvVar);
if (LocalOnly)
{
if (string.IsNullOrWhiteSpace(raw))
throw new InvalidOperationException("Local Test-Connect requires MODBUS_SIM_ENDPOINT before probing.");
return ("127.0.0.1", DriverProbeHandshakeE2eTests.ParseLocalFixturePort(raw));
}
raw ??= DefaultEndpoint;
var parts = raw.Split(':', 2);
var host = parts[0];
var port = parts.Length == 2 && int.TryParse(parts[1], out var p) ? p : 5020;
return (host, port);
}
///
/// Happy-path probe: connects to the running Modbus pymodbus simulator and asserts
/// the reports Ok = true with a
/// sub-5 s latency. Outside owned fixture mode this skips when the fixture is unreachable.
///
[Fact]
public async Task TestConnect_Modbus_AgainstFixture_ReportsOk()
{
var (host, port) = ResolveSimEndpoint();
if (!LocalOnly && !DockerFixtureAvailability.IsReachable(host, port: port))
Assert.Skip($"Modbus fixture at {host}:{port} unreachable — start with `lmxopcua-fix up modbus standard`.");
await using var harness = await TwoNodeClusterHarness.StartAsync(driverProbe: new ModbusDriverProbe());
await using var scope = harness.NodeA.Services.CreateAsyncScope();
var client = scope.ServiceProvider.GetRequiredService();
var configJson = $"{{\"Host\":\"{host}\",\"Port\":{port}}}";
var correlationId = Guid.NewGuid();
var msg = new TestDriverConnect("Modbus", configJson, TimeoutSeconds: 10, correlationId);
var result = await client.AskAsync(msg, Ct);
result.CorrelationId.ShouldBe(correlationId);
result.Ok.ShouldBeTrue($"Probe reported failure: {result.Message}");
result.Message!.ShouldContain("Modbus FC03");
result.LatencyMs.ShouldNotBeNull();
result.LatencyMs!.Value.ShouldBeLessThan(5_000);
}
///
/// Wrong-port probe: releases an ephemeral loopback port and verifies that TCP refuses it.
/// The cluster-routed Modbus probe must report the exact connection-refused result.
///
[Fact]
public async Task TestConnect_Modbus_AgainstWrongPort_ReportsFailure()
{
await using var harness = await TwoNodeClusterHarness.StartAsync(driverProbe: new ModbusDriverProbe());
await using var scope = harness.NodeA.Services.CreateAsyncScope();
var client = scope.ServiceProvider.GetRequiredService();
// A bound, non-listening socket can silently drop SYNs on macOS.
// Release the ephemeral port and verify the kernel rejects it immediately.
IPEndPoint endpoint;
using (var reservation = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
reservation.Bind(new IPEndPoint(IPAddress.Loopback, 0));
endpoint = (IPEndPoint)reservation.LocalEndPoint!;
}
using var witness = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
using var witnessDeadline = CancellationTokenSource.CreateLinkedTokenSource(Ct);
witnessDeadline.CancelAfter(TimeSpan.FromSeconds(2));
var refused = await Should.ThrowAsync(
() => witness.ConnectAsync(endpoint, witnessDeadline.Token).AsTask());
refused.SocketErrorCode.ShouldBe(SocketError.ConnectionRefused);
var host = endpoint.Address.ToString();
var refusedPort = endpoint.Port;
var configJson = $"{{\"Host\":\"{host}\",\"Port\":{refusedPort}}}";
var correlationId = Guid.NewGuid();
var msg = new TestDriverConnect("Modbus", configJson, TimeoutSeconds: 5, correlationId);
var result = await client.AskAsync(msg, Ct);
result.CorrelationId.ShouldBe(correlationId);
result.Ok.ShouldBeFalse();
result.Message.ShouldBe("Connect failed: ConnectionRefused");
}
///
/// Black-hole probe: targets an owned loopback listener that accepts TCP but never answers FC03.
/// Uses a 3-second timeout to keep the wall-clock cost low. Asserts the probe
/// reports Ok = false with a message containing "timed out".
///
/// This test exercises directly against
/// its own listener. The positive and wrong-port tests cover the cluster singleton round-trip.
///
[Fact]
public async Task TestConnect_Modbus_AgainstBlackHole_ReportsTimeout()
{
var probe = new ModbusDriverProbe();
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
var accepted = listener.AcceptTcpClientAsync(Ct).AsTask();
var configJson = $"{{\"Host\":\"127.0.0.1\",\"Port\":{port}}}";
var timeout = TimeSpan.FromSeconds(3);
using var cts = new CancellationTokenSource(timeout);
ZB.MOM.WW.OtOpcUa.Core.Abstractions.DriverProbeResult result;
try
{
result = await probe.ProbeAsync(configJson, timeout, cts.Token);
using var peer = await accepted.WaitAsync(TimeSpan.FromSeconds(5), Ct);
}
finally
{
listener.Stop();
if (accepted.IsCompletedSuccessfully) (await accepted).Dispose();
}
result.Ok.ShouldBeFalse("The owned silent Modbus peer should time out.");
result.Message.ShouldNotBeNull();
result.Message!.ToLowerInvariant().ShouldContain("timed out");
}
}