fix(heidenhain): #990 deterministic control-loop stop, stable down-host status, throttled optional-role login, backoff survives re-init
This commit is contained in:
@@ -79,6 +79,8 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
|
||||
private string? _lastError;
|
||||
private int _consecutiveFailures;
|
||||
private bool _disposed;
|
||||
private bool _disposing;
|
||||
private bool _afterFailure;
|
||||
private volatile bool _pollProgress;
|
||||
|
||||
/// <summary>Consecutive sessions that ended without one published poll batch (test/diagnostic).</summary>
|
||||
@@ -95,8 +97,13 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
|
||||
TimeProvider time,
|
||||
ILogger logger,
|
||||
HeidenhainAlarmSink? alarms = null,
|
||||
HeidenhainIdentitySink? identity = null)
|
||||
HeidenhainIdentitySink? identity = null,
|
||||
int initialFailures = 0)
|
||||
{
|
||||
// #990 (M-19): a watchdog/force re-init rebuilds the runtime; the driver carries the failure count over
|
||||
// so the reconnect backoff keeps growing instead of restarting at InitialDelayMs.
|
||||
_consecutiveFailures = Math.Max(0, initialFailures);
|
||||
_afterFailure = _consecutiveFailures > 0;
|
||||
_device = device;
|
||||
_options = HeidenhainOptionsParser.Normalize(options);
|
||||
_tags = tags;
|
||||
@@ -227,7 +234,7 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
|
||||
{
|
||||
SetState(HeidenhainConnectionState.Connecting, null);
|
||||
var client = _clientFactory(_device.Host, _device.Port, TimeSpan.FromMilliseconds(_options.TimeoutMs));
|
||||
session = new HeidenhainSession(client, HeidenhainSessionSettings.From(_options, _tags), _passwords);
|
||||
session = new HeidenhainSession(client, HeidenhainSessionSettings.From(_options, _tags), _passwords, _time);
|
||||
await client.OpenAsync(ct).ConfigureAwait(false);
|
||||
await session.InitializeAsync(ct).ConfigureAwait(false);
|
||||
long generation;
|
||||
@@ -364,6 +371,7 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
|
||||
var now = _time.GetUtcNow().UtcDateTime;
|
||||
lock (_publication)
|
||||
{
|
||||
if (_disposing) return; // a deliberate stop is not an outage (#990 M-16)
|
||||
old = _session;
|
||||
_session = null;
|
||||
_generation++;
|
||||
@@ -397,6 +405,21 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
|
||||
catch (Exception ex) { _logger.LogWarning(ex, "Heidenhain {Host} alarm projection threw", HostName); }
|
||||
}
|
||||
|
||||
/// <summary>True once a connect has failed or a session was lost since the last successful connect.</summary>
|
||||
internal bool AfterFailure { get { lock (_publication) return _afterFailure; } }
|
||||
|
||||
/// <summary>
|
||||
/// The host status a runtime state presents. <c>Connecting</c> keeps the previous effective state: it is
|
||||
/// <c>Stopped</c> while the control is down (retrying) and <c>Unknown</c> only on the first connect.
|
||||
/// </summary>
|
||||
internal static HostState HostFacing(HeidenhainConnectionState s, bool afterFailure) => s switch
|
||||
{
|
||||
HeidenhainConnectionState.Connected => HostState.Running,
|
||||
HeidenhainConnectionState.Backoff => HostState.Stopped,
|
||||
HeidenhainConnectionState.Connecting when afterFailure => HostState.Stopped,
|
||||
_ => HostState.Unknown,
|
||||
};
|
||||
|
||||
private void SetState(HeidenhainConnectionState next, string? error)
|
||||
{
|
||||
HeidenhainConnectionState old;
|
||||
@@ -406,8 +429,13 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
|
||||
if (error is not null) _lastError = error;
|
||||
if (next == HeidenhainConnectionState.Connected) _lastError = null;
|
||||
if (old == next) return;
|
||||
var oldFacing = HostFacing(old, _afterFailure);
|
||||
if (next == HeidenhainConnectionState.Backoff) _afterFailure = true;
|
||||
else if (next == HeidenhainConnectionState.Connected) _afterFailure = false;
|
||||
_state = next;
|
||||
_stateChangedUtc = _time.GetUtcNow().UtcDateTime;
|
||||
// #990 (M-17): the "since" time moves only when the host-facing state does, not on every
|
||||
// Backoff<->Connecting retry edge.
|
||||
if (HostFacing(next, _afterFailure) != oldFacing) _stateChangedUtc = _time.GetUtcNow().UtcDateTime;
|
||||
}
|
||||
|
||||
try { _stateChanged(this, old, next); }
|
||||
@@ -428,8 +456,17 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
|
||||
_cts = null;
|
||||
}
|
||||
|
||||
// #990 (M-16): a deliberate stop must look the same wherever the loop is. Bump the generation FIRST so a
|
||||
// batch cut short by the closing session is dropped (Publish/Retire see a stale generation) instead of
|
||||
// running the comms-loss outage path.
|
||||
HeidenhainSession? session;
|
||||
lock (_publication) session = _session;
|
||||
lock (_publication)
|
||||
{
|
||||
_disposing = true;
|
||||
_generation++;
|
||||
session = _session;
|
||||
}
|
||||
|
||||
session?.Close();
|
||||
if (cts is not null) await cts.CancelAsync().ConfigureAwait(false);
|
||||
if (loop is not null)
|
||||
@@ -443,6 +480,8 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
|
||||
{
|
||||
_session = null;
|
||||
_generation++;
|
||||
// Whatever the loop was doing, never leave the last Good snapshots behind a stopped runtime.
|
||||
Invalidate(_time.GetUtcNow().UtcDateTime);
|
||||
}
|
||||
|
||||
SetState(HeidenhainConnectionState.Stopped, null);
|
||||
|
||||
@@ -221,7 +221,8 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
|
||||
(role, ct) => _credentials.ResolveAsync(_options, dev, role, ct),
|
||||
Publish, OnRuntimeState, _clientFactory, _time, _logger,
|
||||
(r, status, alarms) => _alarms.OnWalk(r.HostName, status, alarms),
|
||||
OnIdentity);
|
||||
OnIdentity,
|
||||
_carriedFailures.GetValueOrDefault($"{dev.Host}:{dev.Port}"));
|
||||
runtimes.Add(runtime);
|
||||
foreach (var t in tags)
|
||||
{
|
||||
@@ -265,13 +266,26 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
|
||||
{
|
||||
_initialized = false;
|
||||
await StopDevicesAsync().ConfigureAwait(false);
|
||||
_carriedFailures = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
_subscriptions.Clear();
|
||||
lock (_lifecycleLock) _state = DriverState.Unknown;
|
||||
}
|
||||
|
||||
/// <summary>Largest consecutive-failure count across the device runtimes (test/diagnostic).</summary>
|
||||
internal int MaxConsecutiveFailures => _devices.Select(d => d.ConsecutiveFailures).DefaultIfEmpty(0).Max();
|
||||
|
||||
private Dictionary<string, int> _carriedFailures = new(StringComparer.Ordinal);
|
||||
|
||||
private async Task StopDevicesAsync()
|
||||
{
|
||||
var devices = _devices;
|
||||
// #990 (M-19): carry a still-failing control's backoff count across the re-init (the watchdog rebuilds
|
||||
// every runtime every ~90 s while a control is down, which restarted the dial at InitialDelayMs).
|
||||
var carried = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
foreach (var d in devices)
|
||||
if (d.State is HeidenhainConnectionState.Backoff or HeidenhainConnectionState.Connecting && d.ConsecutiveFailures > 0)
|
||||
carried[d.HostName] = d.ConsecutiveFailures;
|
||||
_carriedFailures = carried;
|
||||
_devices = [];
|
||||
_byRawPath = new Dictionary<string, HeidenhainDeviceRuntime>();
|
||||
foreach (var d in devices) await d.DisposeAsync().ConfigureAwait(false);
|
||||
@@ -386,25 +400,28 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
|
||||
return a.Equals(b);
|
||||
}
|
||||
|
||||
private readonly Dictionary<HeidenhainDeviceRuntime, HostState> _facing = new();
|
||||
|
||||
private void OnRuntimeState(HeidenhainDeviceRuntime runtime, HeidenhainConnectionState old, HeidenhainConnectionState next)
|
||||
{
|
||||
var o = ToHostState(old);
|
||||
var n = ToHostState(next);
|
||||
// Connecting-after-failure stays Stopped (#990 M-17): no Stopped<->Unknown flap per retry.
|
||||
var n = HeidenhainDeviceRuntime.HostFacing(next, runtime.AfterFailure);
|
||||
HostState o;
|
||||
lock (_facing)
|
||||
{
|
||||
o = _facing.GetValueOrDefault(runtime, HostState.Unknown);
|
||||
_facing[runtime] = n;
|
||||
}
|
||||
|
||||
if (o == n) return;
|
||||
try { OnHostStatusChanged?.Invoke(this, new HostStatusChangedEventArgs(runtime.HostName, o, n)); }
|
||||
catch (Exception ex) { _logger.LogDebug(ex, "Heidenhain host-status handler threw"); }
|
||||
}
|
||||
|
||||
private static HostState ToHostState(HeidenhainConnectionState s) => s switch
|
||||
{
|
||||
HeidenhainConnectionState.Connected => HostState.Running,
|
||||
HeidenhainConnectionState.Backoff => HostState.Stopped,
|
||||
_ => HostState.Unknown,
|
||||
};
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<HostConnectivityStatus> GetHostStatuses() =>
|
||||
_devices.Select(d => new HostConnectivityStatus(d.HostName, ToHostState(d.State), d.StateChangedUtc)).ToList();
|
||||
_devices.Select(d => new HostConnectivityStatus(d.HostName, HeidenhainDeviceRuntime.HostFacing(d.State, d.AfterFailure), d.StateChangedUtc)).ToList();
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ResolveHost(string fullReference) =>
|
||||
|
||||
@@ -53,11 +53,23 @@ internal sealed class HeidenhainSession : IAsyncDisposable
|
||||
private volatile bool _closed;
|
||||
private volatile bool _lost;
|
||||
|
||||
public HeidenhainSession(Lsv2Client client, HeidenhainSessionSettings settings, PasswordSource passwords)
|
||||
// #990 (M-18): a non-stable optional-role login refusal is retried on an exponential per-role schedule
|
||||
// (5 s -> 5 min) instead of on every poll batch, so a control that keeps refusing is not sent the
|
||||
// cleartext password ~1.5x/s. Per session: a reconnect starts fresh.
|
||||
internal static readonly TimeSpan LoginRetryInitial = TimeSpan.FromSeconds(5);
|
||||
internal static readonly TimeSpan LoginRetryMax = TimeSpan.FromMinutes(5);
|
||||
private readonly TimeProvider _time;
|
||||
private DateTimeOffset _dncNextLogin;
|
||||
private DateTimeOffset _dataNextLogin;
|
||||
private int _dncLoginFailures;
|
||||
private int _dataLoginFailures;
|
||||
|
||||
public HeidenhainSession(Lsv2Client client, HeidenhainSessionSettings settings, PasswordSource passwords, TimeProvider? time = null)
|
||||
{
|
||||
_client = client;
|
||||
_settings = settings;
|
||||
_passwords = passwords;
|
||||
_time = time ?? TimeProvider.System;
|
||||
}
|
||||
|
||||
/// <summary>True once a transport failure ended this session.</summary>
|
||||
@@ -106,6 +118,7 @@ internal sealed class HeidenhainSession : IAsyncDisposable
|
||||
}
|
||||
catch (Lsv2RefusalException e)
|
||||
{
|
||||
ScheduleLoginRetry(role == "DNC");
|
||||
return HeidenhainStatus.FromRefusal(e.Code);
|
||||
}
|
||||
catch (QualityException e)
|
||||
@@ -374,6 +387,8 @@ internal sealed class HeidenhainSession : IAsyncDisposable
|
||||
var effective = status == NotAttempted ? HeidenhainStatus.BadNotSupported : status;
|
||||
if (!enabled || status == NotAttempted || HeidenhainStatus.IsStable(effective))
|
||||
throw new QualityException(effective, enabled ? HeidenhainStatus.State(effective) : HeidenhainCatalog.States.Disabled);
|
||||
if (_time.GetUtcNow() < (dnc ? _dncNextLogin : _dataNextLogin))
|
||||
throw new QualityException(effective, HeidenhainStatus.State(effective)); // throttled: no wire traffic
|
||||
try
|
||||
{
|
||||
await WireAsync(wire, "Login_" + role, async c =>
|
||||
@@ -381,13 +396,14 @@ internal sealed class HeidenhainSession : IAsyncDisposable
|
||||
await LoginWithCredentialAsync(role, c).ConfigureAwait(false);
|
||||
return [];
|
||||
}, ct).ConfigureAwait(false);
|
||||
if (dnc) _dncStatus = HeidenhainStatus.Good;
|
||||
else _dataStatus = HeidenhainStatus.Good;
|
||||
if (dnc) { _dncStatus = HeidenhainStatus.Good; _dncLoginFailures = 0; }
|
||||
else { _dataStatus = HeidenhainStatus.Good; _dataLoginFailures = 0; }
|
||||
}
|
||||
catch (Lsv2RefusalException e)
|
||||
{
|
||||
if (dnc) _dncStatus = HeidenhainStatus.FromRefusal(e.Code);
|
||||
else _dataStatus = HeidenhainStatus.FromRefusal(e.Code);
|
||||
ScheduleLoginRetry(dnc);
|
||||
throw;
|
||||
}
|
||||
catch (QualityException e)
|
||||
@@ -399,6 +415,14 @@ internal sealed class HeidenhainSession : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
private void ScheduleLoginRetry(bool dnc)
|
||||
{
|
||||
var failures = dnc ? ++_dncLoginFailures : ++_dataLoginFailures;
|
||||
var delay = ConnectionBackoff.ComputeDelay(LoginRetryInitial, failures, LoginRetryMax);
|
||||
if (dnc) _dncNextLogin = _time.GetUtcNow() + delay;
|
||||
else _dataNextLogin = _time.GetUtcNow() + delay;
|
||||
}
|
||||
|
||||
private async Task PrepareTelemetryAsync(Dictionary<string, Raw> wire, CancellationToken ct)
|
||||
{
|
||||
if (!_settings.TelemetryEnabled) throw new QualityException(HeidenhainStatus.BadNotSupported, HeidenhainCatalog.States.Disabled);
|
||||
|
||||
Reference in New Issue
Block a user