fix(heidenhain): #990 deterministic control-loop stop, stable down-host status, throttled optional-role login, backoff survives re-init
This commit is contained in:
+116
-3
@@ -220,17 +220,130 @@ public sealed class HeidenhainReviewFixTests
|
||||
}
|
||||
}
|
||||
|
||||
private static HeidenhainDeviceRuntime NewRuntime(int port, Action<string, DataValueSnapshot> publish)
|
||||
// ---- #990 M-16: stopping a control loop is deterministic wherever the loop is. ----
|
||||
|
||||
/// <summary>Idle in the poll delay: the stopped runtime must not leave Good snapshots in the cache.</summary>
|
||||
[Fact]
|
||||
public async Task Disposing_an_idle_runtime_invalidates_its_values()
|
||||
{
|
||||
var control = new SimulatedControl();
|
||||
control.Runtime[23] = () => SimulatedControl.U16(4);
|
||||
await using var sim = Lsv2Simulator.WithControl(control);
|
||||
var published = new ConcurrentQueue<DataValueSnapshot>();
|
||||
var runtime = NewRuntime(sim.Port, (_, v) => published.Enqueue(v), statusMs: 60_000);
|
||||
runtime.Start();
|
||||
await WaitFor(() => published.Any(v => v.StatusCode == HeidenhainStatus.Good));
|
||||
await runtime.DisposeAsync();
|
||||
published.Last().StatusCode.ShouldBe(HeidenhainStatus.BadNoCommunication);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mid-batch: the closing session short-circuits the batch; that must NOT run the comms-loss outage
|
||||
/// path (a Backoff transition + "communication lost" retire) for a deliberate stop.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Disposing_mid_batch_is_not_reported_as_a_comms_loss()
|
||||
{
|
||||
var inRead = new ManualResetEventSlim();
|
||||
var release = new ManualResetEventSlim();
|
||||
var control = new SimulatedControl();
|
||||
control.Runtime[23] = () => { inRead.Set(); release.Wait(TimeSpan.FromSeconds(5)); return SimulatedControl.U16(4); };
|
||||
await using var sim = Lsv2Simulator.WithControl(control);
|
||||
var states = new ConcurrentQueue<HeidenhainConnectionState>();
|
||||
var runtime = NewRuntime(sim.Port, (_, _) => { }, onState: (_, n) => states.Enqueue(n));
|
||||
runtime.Start();
|
||||
inRead.Wait(TimeSpan.FromSeconds(5), Ct).ShouldBeTrue();
|
||||
var dispose = runtime.DisposeAsync().AsTask();
|
||||
await Task.Delay(200, Ct);
|
||||
release.Set();
|
||||
await dispose;
|
||||
states.ShouldNotContain(HeidenhainConnectionState.Backoff);
|
||||
runtime.State.ShouldBe(HeidenhainConnectionState.Stopped);
|
||||
}
|
||||
|
||||
/// <summary>Positive control: a genuine session loss still takes the Backoff / outage path.</summary>
|
||||
[Fact]
|
||||
public async Task A_real_session_loss_still_retires_to_backoff()
|
||||
{
|
||||
var control = new SimulatedControl();
|
||||
control.Runtime[23] = SimReply.Drop;
|
||||
await using var sim = Lsv2Simulator.WithControl(control);
|
||||
var states = new ConcurrentQueue<HeidenhainConnectionState>();
|
||||
var runtime = NewRuntime(sim.Port, (_, _) => { }, onState: (_, n) => states.Enqueue(n));
|
||||
await using var _ = runtime;
|
||||
runtime.Start();
|
||||
await WaitFor(() => states.Contains(HeidenhainConnectionState.Backoff));
|
||||
}
|
||||
|
||||
private static async Task WaitFor(Func<bool> condition)
|
||||
{
|
||||
var deadline = DateTime.UtcNow.AddSeconds(5);
|
||||
while (!condition())
|
||||
{
|
||||
if (DateTime.UtcNow > deadline) throw new TimeoutException("condition not reached");
|
||||
await Task.Delay(20, Ct);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- #990 M-17: a down control's host status does not flap, and its since-time is stable. ----
|
||||
|
||||
[Fact]
|
||||
public async Task A_down_control_host_status_does_not_flap_and_keeps_its_since_time()
|
||||
{
|
||||
var options = new HeidenhainDriverOptions
|
||||
{
|
||||
TimeoutMs = 500,
|
||||
Polling = new HeidenhainPollingOptions { StatusMs = 100, CustomMs = 100, SlowMs = 100 },
|
||||
Devices = [new HeidenhainDeviceOptions { Host = "127.0.0.1", Port = 1, DeviceName = "dev1" }],
|
||||
RawTags = [TestTags.Raw("Status/ExecutionState")],
|
||||
Reconnect = new HeidenhainReconnectOptions { InitialDelayMs = 100, MaxDelayMs = 200 },
|
||||
};
|
||||
await using var d = new HeidenhainDriver(options, "hh", null, new HeidenhainCredentials(null), null, null);
|
||||
var events = new ConcurrentQueue<HostStatusChangedEventArgs>();
|
||||
d.OnHostStatusChanged += (_, e) => events.Enqueue(e);
|
||||
await d.InitializeAsync("{}", Ct);
|
||||
await d.SubscribeAsync([options.RawTags[0].RawPath], TimeSpan.FromSeconds(1), Ct);
|
||||
await WaitFor(() => d.GetHostStatuses().Single().State == HostState.Stopped);
|
||||
var since = d.GetHostStatuses().Single().LastChangedUtc;
|
||||
await Task.Delay(1200, Ct); // several Backoff <-> Connecting retries
|
||||
d.MaxConsecutiveFailures.ShouldBeGreaterThan(3);
|
||||
events.Count(e => e.NewState == HostState.Stopped).ShouldBe(1);
|
||||
events.ShouldNotContain(e => e.OldState == HostState.Stopped); // never leaves Stopped while down
|
||||
d.GetHostStatuses().Single().LastChangedUtc.ShouldBe(since);
|
||||
}
|
||||
|
||||
// ---- #990 M-19: a re-init (the comms-loss watchdog's remedy) keeps the reconnect backoff. ----
|
||||
|
||||
[Fact]
|
||||
public async Task Reinitialize_of_a_down_control_carries_the_backoff_count()
|
||||
{
|
||||
var options = new HeidenhainDriverOptions
|
||||
{
|
||||
TimeoutMs = 500,
|
||||
Devices = [new HeidenhainDeviceOptions { Host = "127.0.0.1", Port = 1, DeviceName = "dev1" }],
|
||||
RawTags = [TestTags.Raw("Status/ExecutionState")],
|
||||
Reconnect = new HeidenhainReconnectOptions { InitialDelayMs = 100, MaxDelayMs = 400 },
|
||||
};
|
||||
await using var d = new HeidenhainDriver(options, "hh", null, new HeidenhainCredentials(null), null, null);
|
||||
await d.InitializeAsync("{}", Ct);
|
||||
await d.SubscribeAsync([options.RawTags[0].RawPath], TimeSpan.FromSeconds(1), Ct);
|
||||
await WaitFor(() => d.MaxConsecutiveFailures >= 4);
|
||||
var before = d.MaxConsecutiveFailures;
|
||||
await d.ReinitializeAsync("{}", Ct);
|
||||
d.MaxConsecutiveFailures.ShouldBeGreaterThanOrEqualTo(before - 1); // carried (not reset to 0)
|
||||
}
|
||||
|
||||
private static HeidenhainDeviceRuntime NewRuntime(int port, Action<string, DataValueSnapshot> publish,
|
||||
int statusMs = 100, Action<HeidenhainConnectionState, HeidenhainConnectionState>? onState = null)
|
||||
{
|
||||
var options = new HeidenhainDriverOptions
|
||||
{
|
||||
TimeoutMs = 500,
|
||||
Polling = new HeidenhainPollingOptions { StatusMs = statusMs, CustomMs = 100, SlowMs = 100 },
|
||||
Reconnect = new HeidenhainReconnectOptions { InitialDelayMs = 100, MaxDelayMs = 800 },
|
||||
};
|
||||
var device = new HeidenhainDeviceOptions { Host = "127.0.0.1", Port = port, DeviceName = "dev1" };
|
||||
return new HeidenhainDeviceRuntime(device, options, [TestTags.Def("Status/ExecutionState")],
|
||||
(_, _) => ValueTask.FromResult(""), publish, (_, _, _) => { },
|
||||
(_, _) => ValueTask.FromResult(""), publish, (_, o, n) => onState?.Invoke(o, n),
|
||||
(h, p, t) => new Lsv2Client(h, p, t), TimeProvider.System, NullLogger.Instance);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ public sealed class HeidenhainSessionTests
|
||||
public required SimulatedControl Control { get; init; }
|
||||
public required HeidenhainSession Session { get; init; }
|
||||
public required IReadOnlyList<HeidenhainTagDefinition> Tags { get; init; }
|
||||
public required ManualTime Time { get; init; }
|
||||
|
||||
public async Task<Dictionary<string, HeidenhainSample>> ReadAsync(params string[] addresses)
|
||||
{
|
||||
@@ -45,14 +46,23 @@ public sealed class HeidenhainSessionTests
|
||||
bool telemetry = true, bool dnc = true, bool data = false, int maxAlarms = 64, bool timers = false,
|
||||
HeidenhainSession.PasswordSource? passwords = null)
|
||||
{
|
||||
var time = new ManualTime();
|
||||
var sim = Lsv2Simulator.WithControl(control);
|
||||
var client = new Lsv2Client("127.0.0.1", sim.Port, TimeSpan.FromSeconds(1));
|
||||
var settings = new HeidenhainSessionSettings(telemetry, dnc, data, maxAlarms, timers,
|
||||
tags.Any(t => t.Address.Kind == HeidenhainAddressKind.Plc), tags.Any(t => t.Address.Kind == HeidenhainAddressKind.DataPath));
|
||||
var session = new HeidenhainSession(client, settings, passwords ?? ((_, _) => ValueTask.FromResult("")));
|
||||
var session = new HeidenhainSession(client, settings, passwords ?? ((_, _) => ValueTask.FromResult("")), time);
|
||||
await client.OpenAsync(Ct);
|
||||
await session.InitializeAsync(Ct);
|
||||
return new Harness { Sim = sim, Control = control, Session = session, Tags = tags };
|
||||
return new Harness { Sim = sim, Control = control, Session = session, Tags = tags, Time = time };
|
||||
}
|
||||
|
||||
/// <summary>A manually advanced clock for the optional-login retry schedule (#990 M-18).</summary>
|
||||
private sealed class ManualTime : TimeProvider
|
||||
{
|
||||
private DateTimeOffset _now = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
public override DateTimeOffset GetUtcNow() => _now;
|
||||
public void Advance(TimeSpan by) => _now += by;
|
||||
}
|
||||
|
||||
private static List<HeidenhainTagDefinition> Standard(params string[] addresses) => addresses.Select(a => TestTags.Def(a)).ToList();
|
||||
@@ -312,6 +322,7 @@ public sealed class HeidenhainSessionTests
|
||||
var tags = role == "DATA" ? [TestTags.Def("DATA:/x", "Int64")] : Standard("Status/ExecutionState");
|
||||
await using var h = await OpenAsync(c, tags, data: true,
|
||||
passwords: (r, _) => { if (r == role) Interlocked.Increment(ref resolved); return ValueTask.FromResult("fresh"); });
|
||||
h.Time.Advance(HeidenhainSession.LoginRetryInitial + TimeSpan.FromMilliseconds(1)); // past the retry window
|
||||
var s = await h.Session.ReadBatchAsync(tags, Ct);
|
||||
s[0].Status.ShouldBe(HeidenhainStatus.Good);
|
||||
attempts.ShouldBe(2);
|
||||
@@ -382,14 +393,44 @@ public sealed class HeidenhainSessionTests
|
||||
c.Runtime[23] = () => logins < 3 ? SimReply.Refuse(23) : SimReply.Ok("S_RI", [0, 4]);
|
||||
c.Runtime[26] = () => logins < 3 ? SimReply.Refuse(23) : SimReply.Ok("S_RI", [0, 7]);
|
||||
await using var h = await OpenAsync(c, Standard("Status/ExecutionState", "Status/ProgramState"));
|
||||
h.Time.Advance(TimeSpan.FromSeconds(6));
|
||||
(await h.ReadAsync("Status/ExecutionState", "Status/ProgramState")).Values
|
||||
.ShouldAllBe(s => s.Status == HeidenhainStatus.BadUserAccessDenied);
|
||||
h.Time.Advance(TimeSpan.FromSeconds(11));
|
||||
var recovered = await h.ReadAsync("Status/ExecutionState", "Status/ProgramState");
|
||||
recovered["Status/ExecutionState"].Value.ShouldBe(4);
|
||||
recovered["Status/ProgramState"].Value.ShouldBe(7);
|
||||
logins.ShouldBe(3);
|
||||
}
|
||||
|
||||
/// <summary>#990 M-18: a refused optional login is not re-sent on every batch; it follows a growing schedule.</summary>
|
||||
[Fact]
|
||||
public async Task Refused_optional_login_is_throttled_not_retried_every_batch()
|
||||
{
|
||||
var logins = 0;
|
||||
var c = new SimulatedControl
|
||||
{
|
||||
Login = (r, _) => r == "DNC" && Interlocked.Increment(ref logins) < 100 ? SimReply.Refuse(25) : SimReply.Ok("T_OK", []),
|
||||
};
|
||||
c.Runtime[23] = () => SimReply.Refuse(23);
|
||||
await using var h = await OpenAsync(c, Standard("Status/ExecutionState"));
|
||||
logins.ShouldBe(1); // the init attempt
|
||||
for (var i = 0; i < 50; i++) await h.ReadAsync("Status/ExecutionState");
|
||||
logins.ShouldBe(1); // 50 batches inside the 5 s window: no further A_LG
|
||||
|
||||
h.Time.Advance(TimeSpan.FromSeconds(5.1)); // window elapsed -> exactly one more attempt
|
||||
await h.ReadAsync("Status/ExecutionState");
|
||||
await h.ReadAsync("Status/ExecutionState");
|
||||
logins.ShouldBe(2);
|
||||
|
||||
h.Time.Advance(TimeSpan.FromSeconds(5.1)); // the window doubled to 10 s: still closed (positive control below)
|
||||
await h.ReadAsync("Status/ExecutionState");
|
||||
logins.ShouldBe(2);
|
||||
h.Time.Advance(TimeSpan.FromSeconds(5)); // 10.1 s since the last attempt -> retried
|
||||
await h.ReadAsync("Status/ExecutionState");
|
||||
logins.ShouldBe(3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Every_request_the_session_emits_is_allowlisted()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user