099238894c
- OpcUaPublishActor: deferred alarm states, qualities and condition marks replay as one arrival-ordered list (a withdrawal followed by a re-establishing transition ended unknown); marks held per (realm, condition) so withdrawals are bounded by the condition set - OpcUaClientDriver: signal/withdraw re-check the registration under _alarmStateLock; removals take the lock - DriverHostActor: a withdrawal under a raised F5 diagnostic updates its count - docs: Unsignalable/backstop residual; AlarmInitialStatePublished must stay in-process - tests: arrival-order replay (+ mirror), backstop positive control, F5 count
387 lines
21 KiB
C#
387 lines
21 KiB
C#
using Akka.Actor;
|
|
using Akka.Event;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
using PublishActor = ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
|
|
|
/// <summary>
|
|
/// A1 (plan §5.1 T1/T2/F2/F5): native "standing alarms delivered" signals become
|
|
/// <see cref="PublishActor.MarkConditionsKnown"/>, sent to the publish actor AFTER the
|
|
/// <see cref="PublishActor.AlarmStateUpdate"/>s this host already forwarded for the same driver (Akka per-pair order),
|
|
/// plus the two Akka-scheduled timers that enter the same chain: the OpcUaClient-only backstop and the F5 signal
|
|
/// timeout.
|
|
/// </summary>
|
|
public sealed partial class DriverHostActor
|
|
{
|
|
private sealed record ConditionSignalTimedOut(string DriverInstanceId, long Epoch);
|
|
private sealed record ConditionBackstopElapsed(string DriverInstanceId, long Epoch);
|
|
|
|
/// <summary>Per driver instance: the current connectivity epoch, the child that sent the last edge, its connection
|
|
/// epoch at the last Good edge, when its quality went Good, when the current F5 window started, the conditions not
|
|
/// yet established since then, and the conditions the driver reported unsignalable.</summary>
|
|
private sealed class ConditionSignalTracker
|
|
{
|
|
public long Epoch;
|
|
public IActorRef? Owner;
|
|
public long? ConnectionEpoch;
|
|
public DateTime? GoodSinceUtc;
|
|
public DateTime? PendingSinceUtc;
|
|
public readonly HashSet<string> Pending = new(StringComparer.Ordinal);
|
|
public readonly HashSet<string> Unsignalable = new(StringComparer.Ordinal);
|
|
public bool DiagnosticRaised;
|
|
}
|
|
|
|
private readonly ConditionSignalOptions _conditionSignals;
|
|
private readonly Dictionary<string, ConditionSignalTracker> _conditionSignalTrackers = new(StringComparer.Ordinal);
|
|
|
|
private static string SignalTimeoutKey(string driverInstanceId) => "cond-signal-timeout:" + driverInstanceId;
|
|
private static string BackstopKey(string driverInstanceId) => "cond-backstop:" + driverInstanceId;
|
|
|
|
/// <summary>The injected clock (review nit: never <see cref="DateTime.UtcNow"/> here).</summary>
|
|
private DateTime ConditionClockUtc => _writeClock.GetUtcNow().UtcDateTime;
|
|
|
|
private void ReceiveConditionSignals()
|
|
{
|
|
Receive<DriverInstanceActor.AlarmInitialStatePublished>(OnAlarmInitialState);
|
|
Receive<ConditionSignalTimedOut>(OnConditionSignalTimedOut);
|
|
Receive<ConditionBackstopElapsed>(OnConditionBackstopElapsed);
|
|
Receive<PublishActor.ConditionMarksDiscarded>(OnConditionMarksDiscarded);
|
|
}
|
|
|
|
private void ReceiveConditionSignalsWhileStale()
|
|
{
|
|
Receive<DriverInstanceActor.AlarmInitialStatePublished>(m =>
|
|
_log.Debug("DriverHost {Node}: dropping an initial alarm-state signal from {Id} while Stale", _localNode, m.DriverInstanceId));
|
|
Receive<ConditionSignalTimedOut>(_ => { });
|
|
Receive<ConditionBackstopElapsed>(_ => { });
|
|
Receive<PublishActor.ConditionMarksDiscarded>(_ => { });
|
|
}
|
|
|
|
private ConditionSignalTracker Tracker(string driverInstanceId)
|
|
{
|
|
if (!_conditionSignalTrackers.TryGetValue(driverInstanceId, out var t))
|
|
_conditionSignalTrackers[driverInstanceId] = t = new ConditionSignalTracker();
|
|
return t;
|
|
}
|
|
|
|
private string? DriverTypeOf(string driverInstanceId) =>
|
|
_children.TryGetValue(driverInstanceId, out var child) ? child.DriverType : null;
|
|
|
|
/// <summary>Whether <paramref name="sender"/> is the CURRENT child for <paramref name="driverInstanceId"/> — not a
|
|
/// stopped (retired) incarnation whose late message must not recreate a tracker after
|
|
/// <see cref="ForgetConditionSignals"/>, nor anything else.</summary>
|
|
private bool IsCurrentChild(string driverInstanceId, IActorRef sender) =>
|
|
!_retiredChildren.Contains(sender)
|
|
&& _children.TryGetValue(driverInstanceId, out var child) && Equals(child.Actor, sender);
|
|
|
|
/// <summary>
|
|
/// A connectivity edge restarts the F5 window (from quality Good) and the backstop; a Bad edge cancels both.
|
|
/// Review S2 / round 2 F1: every edge withdraws "known" from the driver's conditions — on the Bad edge the source
|
|
/// can no longer vouch for their state (an alarm raised during the outage would otherwise read known-inactive,
|
|
/// Good after the reconnect until the replay), and the Good edge withdraws again, unconditionally. They become
|
|
/// known again only on the reconnected source's next signal (or transition). The Bad edge also forgets the
|
|
/// unsignalable set (F2).
|
|
/// </summary>
|
|
private void OnConditionSignalConnectivity(string driverInstanceId, bool connected, IActorRef sender, long? connectionEpoch)
|
|
{
|
|
if (!IsCurrentChild(driverInstanceId, sender))
|
|
{
|
|
// A stopped incarnation (or a stray sender): never recreate or reset the tracker. A stopped incarnation's
|
|
// Bad edge still withdraws known unless the CURRENT child of the same id is connected (its state is the
|
|
// live one); a sender that was never a child of this host changes nothing.
|
|
if (!_retiredChildren.Contains(sender)) return;
|
|
var currentConnected = _conditionSignalTrackers.TryGetValue(driverInstanceId, out var live) && live.GoodSinceUtc is not null
|
|
&& _children.TryGetValue(driverInstanceId, out var current) && Equals(live.Owner, current.Actor);
|
|
if (!connected && !currentConnected) WithdrawDriverConditionsKnown(driverInstanceId);
|
|
return;
|
|
}
|
|
|
|
var t = Tracker(driverInstanceId);
|
|
t.Owner = sender;
|
|
t.Epoch++;
|
|
Timers.Cancel(SignalTimeoutKey(driverInstanceId));
|
|
Timers.Cancel(BackstopKey(driverInstanceId));
|
|
t.Pending.Clear();
|
|
t.PendingSinceUtc = null;
|
|
// Review round 2 F1: withdraw on EVERY edge — the Good one too, unconditionally (ahead of the Good quality
|
|
// annotation): whatever made a condition known since the Bad edge (an ack-revert projection, a missed Bad
|
|
// edge, a new incarnation) cannot vouch for the reconnected source's state.
|
|
WithdrawDriverConditionsKnown(driverInstanceId);
|
|
if (!connected)
|
|
{
|
|
// Review round 2 F2: an unsignalable report belongs to the subscription that made it; the reconnected
|
|
// subscription reports again if it still cannot signal. Kept, it would arm the backstop on the next Good
|
|
// edge and turn a later FAILED refresh into known-by-timer instead of F5's unknown.
|
|
t.Unsignalable.Clear();
|
|
t.GoodSinceUtc = null;
|
|
t.ConnectionEpoch = null;
|
|
return;
|
|
}
|
|
|
|
t.GoodSinceUtc = ConditionClockUtc;
|
|
t.ConnectionEpoch = connectionEpoch;
|
|
if (_alarmRefsByDriver.TryGetValue(driverInstanceId, out var refs))
|
|
foreach (var (rawPath, _) in refs) t.Pending.Add(rawPath);
|
|
ArmSignalTimeout(driverInstanceId, t);
|
|
if (t.Unsignalable.Count > 0) ScheduleBackstop(driverInstanceId, t);
|
|
}
|
|
|
|
/// <summary>(Re)start the F5 window for the tracker's pending conditions, from now.</summary>
|
|
private void ArmSignalTimeout(string driverInstanceId, ConditionSignalTracker t)
|
|
{
|
|
if (t.Pending.Count == 0 || DriverTypeOf(driverInstanceId) is not { } type) return;
|
|
t.PendingSinceUtc = ConditionClockUtc;
|
|
Timers.StartSingleTimer(SignalTimeoutKey(driverInstanceId), new ConditionSignalTimedOut(driverInstanceId, t.Epoch),
|
|
_conditionSignals.SignalTimeoutFor(type));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Open-question answer (re-arm F5): after a deploy re-indexed the alarm refs, a CONNECTED driver's newly added
|
|
/// refs join <c>Pending</c> and the F5 window restarts now; refs the deploy removed leave it. (Today a deploy that
|
|
/// adds alarm refs also changes the driver's config — its RawTags are folded in — so the driver is respawned and
|
|
/// the new incarnation's Good edge re-arms F5 anyway; this covers an in-place deploy.)
|
|
/// </summary>
|
|
/// <param name="previousRefs">Each driver's alarm RawPaths before the reindex.</param>
|
|
private void RearmConditionSignalsAfterReindex(IReadOnlyDictionary<string, HashSet<string>> previousRefs)
|
|
{
|
|
foreach (var (driverInstanceId, t) in _conditionSignalTrackers)
|
|
{
|
|
if (t.GoodSinceUtc is null) continue; // armed on the next Good edge
|
|
var current = _alarmRefsByDriver.TryGetValue(driverInstanceId, out var refs)
|
|
? refs.Select(r => r.RawPath).ToHashSet(StringComparer.Ordinal)
|
|
: new HashSet<string>(StringComparer.Ordinal);
|
|
previousRefs.TryGetValue(driverInstanceId, out var before);
|
|
var added = current.Where(r => before is null || !before.Contains(r)).ToList();
|
|
t.Pending.IntersectWith(current);
|
|
t.Unsignalable.IntersectWith(current);
|
|
if (added.Count > 0)
|
|
{
|
|
t.Pending.UnionWith(added);
|
|
ArmSignalTimeout(driverInstanceId, t);
|
|
}
|
|
else if (t.Pending.Count == 0)
|
|
{
|
|
ClearPendingWindow(driverInstanceId, t);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// A1 review round 2 N2: the publish actor discarded a deferred mark of this driver (G3, or the deferral was full),
|
|
/// so those conditions are still unknown in the node manager. Put them back in the F5 window (from now), so a
|
|
/// driver that does not re-signal raises the "not signalled" diagnostic for them.
|
|
/// </summary>
|
|
private void OnConditionMarksDiscarded(PublishActor.ConditionMarksDiscarded msg)
|
|
{
|
|
if (!_conditionSignalTrackers.TryGetValue(msg.Source, out var t) || t.GoodSinceUtc is null) return;
|
|
if (!_alarmRefsByDriver.TryGetValue(msg.Source, out var refs)) return;
|
|
var owned = refs.Select(r => r.RawPath).ToHashSet(StringComparer.Ordinal);
|
|
IEnumerable<string> back = msg.ConditionIds is null
|
|
? owned
|
|
: msg.ConditionIds
|
|
.Where(id => _driverRefByAlarmNodeId.TryGetValue(id, out var target) && target.DriverInstanceId == msg.Source)
|
|
.Select(id => _driverRefByAlarmNodeId[id].RawPath)
|
|
.Where(owned.Contains);
|
|
var before = t.Pending.Count;
|
|
t.Pending.UnionWith(back);
|
|
if (t.Pending.Count == before) return;
|
|
_log.Warning("DriverHost {Node}: {Count} deferred condition-known mark(s) of {Driver} were discarded; back in the F5 window until it signals again",
|
|
_localNode, t.Pending.Count - before, msg.Source);
|
|
ArmSignalTimeout(msg.Source, t);
|
|
}
|
|
|
|
private void OnAlarmInitialState(DriverInstanceActor.AlarmInitialStatePublished msg)
|
|
{
|
|
if (!IsCurrentChild(msg.DriverInstanceId, Sender))
|
|
{
|
|
_log.Debug("DriverHost {Node}: dropping an initial alarm-state signal for {Id} from a sender that is not its current child",
|
|
_localNode, msg.DriverInstanceId);
|
|
return;
|
|
}
|
|
|
|
var t = Tracker(msg.DriverInstanceId);
|
|
// Review S2: a signal from an earlier connection (queued across a Connected→Reconnecting→Connected bounce)
|
|
// covers state the reconnect withdrew; it must not mark anything known.
|
|
if (msg.ConnectionEpoch is { } epoch && t.ConnectionEpoch != epoch)
|
|
{
|
|
_log.Debug("DriverHost {Node}: dropping a stale initial alarm-state signal from {Id} (connection {Epoch}, current {Current})",
|
|
_localNode, msg.DriverInstanceId, epoch, t.ConnectionEpoch);
|
|
return;
|
|
}
|
|
|
|
if (msg.Args.Withdrawn)
|
|
{
|
|
// #926: the source lost events after establishing these conditions. Take "known" back (same chain as its
|
|
// projections, so it lands after them), keep them out of the backstop (which would re-mark them known by
|
|
// timer), and put them back in the F5 window so a source that never re-signals is diagnosed.
|
|
t.Unsignalable.ExceptWith(msg.Args.ConditionIds);
|
|
var withdrawn = MarkDriverConditionsKnown(msg.DriverInstanceId, msg.Args.ConditionIds, known: false);
|
|
if (t.GoodSinceUtc is not null && _alarmRefsByDriver.TryGetValue(msg.DriverInstanceId, out var owned))
|
|
{
|
|
var ownedPaths = owned.Select(r => r.RawPath).ToHashSet(StringComparer.Ordinal);
|
|
var before = t.Pending.Count;
|
|
t.Pending.UnionWith(msg.Args.ConditionIds.Where(ownedPaths.Contains));
|
|
// An F5 window already running covers them; otherwise start one now. A diagnostic already raised for
|
|
// that window must count them too (#926 review r2).
|
|
if (t.Pending.Count != before)
|
|
{
|
|
if (t.PendingSinceUtc is null) ArmSignalTimeout(msg.DriverInstanceId, t);
|
|
else if (t.DiagnosticRaised) _conditionSignals.Hub?.UpdateUnsignalled(msg.DriverInstanceId, t.Pending.Count);
|
|
}
|
|
}
|
|
_log.Info("DriverHost {Node}: driver {Driver} withdrew {Count} condition(s) ({Routed} routed) — state no longer known (events lost)",
|
|
_localNode, msg.DriverInstanceId, msg.Args.ConditionIds.Count, withdrawn);
|
|
return;
|
|
}
|
|
|
|
if (msg.Args.Unsignalable)
|
|
{
|
|
// InitialStateUnsignalable: no real signal will come. Only a driver type with a backstop (OpcUaClient) marks
|
|
// these known — after its settle window from quality Good. Any other type: they stay unknown.
|
|
t.Unsignalable.UnionWith(msg.Args.ConditionIds);
|
|
ScheduleBackstop(msg.DriverInstanceId, t);
|
|
return;
|
|
}
|
|
|
|
var marked = MarkDriverConditionsKnown(msg.DriverInstanceId, msg.Args.ConditionIds);
|
|
t.Unsignalable.ExceptWith(msg.Args.ConditionIds);
|
|
NoteConditionsEstablished(msg.DriverInstanceId, t, msg.Args.ConditionIds);
|
|
_log.Debug("DriverHost {Node}: driver {Driver} established {Count} condition(s) ({Marked} routed)",
|
|
_localNode, msg.DriverInstanceId, msg.Args.ConditionIds.Count, marked);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Keep F5's "still unknown" set consistent with the node manager: a condition leaves <c>Pending</c> when the
|
|
/// node manager marks it known — on its driver's signal, and on a native transition (a native projection is an
|
|
/// established state there). An emptied set ends the F5 window and clears the diagnostic.
|
|
/// </summary>
|
|
private void NoteConditionsEstablished(string driverInstanceId, ConditionSignalTracker t, IEnumerable<string> rawPaths)
|
|
{
|
|
if (t.Pending.Count == 0) return;
|
|
var before = t.Pending.Count;
|
|
t.Pending.ExceptWith(rawPaths);
|
|
if (t.Pending.Count == 0) ClearPendingWindow(driverInstanceId, t);
|
|
// A2 review (A1 phase-run failure): a diagnostic raised before this transition must not keep claiming the
|
|
// condition — the node manager holds it established now.
|
|
else if (t.DiagnosticRaised && t.Pending.Count != before)
|
|
_conditionSignals.Hub?.UpdateUnsignalled(driverInstanceId, t.Pending.Count);
|
|
}
|
|
|
|
/// <summary>A forwarded native transition established <paramref name="rawPath"/> (see <see cref="NoteConditionsEstablished"/>).</summary>
|
|
private void NoteNativeTransitionEstablished(string driverInstanceId, string rawPath)
|
|
{
|
|
if (_conditionSignalTrackers.TryGetValue(driverInstanceId, out var t) && t.GoodSinceUtc is not null)
|
|
NoteConditionsEstablished(driverInstanceId, t, [rawPath]);
|
|
}
|
|
|
|
private void ClearPendingWindow(string driverInstanceId, ConditionSignalTracker t)
|
|
{
|
|
Timers.Cancel(SignalTimeoutKey(driverInstanceId));
|
|
t.PendingSinceUtc = null;
|
|
// F5: a late signal clears the "not signalled" diagnostic.
|
|
if (!t.DiagnosticRaised) return;
|
|
t.DiagnosticRaised = false;
|
|
_conditionSignals.Hub?.ClearUnsignalled(driverInstanceId);
|
|
_log.Info("DriverHost {Node}: driver {Driver} signalled its initial alarm state late — diagnostic cleared",
|
|
_localNode, driverInstanceId);
|
|
}
|
|
|
|
/// <summary>Review S2: withdraw "known" from every condition node of <paramref name="driverInstanceId"/> (one
|
|
/// <see cref="PublishActor.MarkConditionsKnown"/> with <c>Known: false</c> per realm), on the same chain as its
|
|
/// alarm projections and quality annotations.</summary>
|
|
private void WithdrawDriverConditionsKnown(string driverInstanceId)
|
|
{
|
|
if (_opcUaPublishActor is null || !_alarmRefsByDriver.TryGetValue(driverInstanceId, out var refs)) return;
|
|
var byRealm = new Dictionary<AddressSpaceRealm, List<string>>();
|
|
foreach (var (_, nodes) in refs)
|
|
{
|
|
foreach (var n in nodes)
|
|
{
|
|
if (!byRealm.TryGetValue(n.Realm, out var list)) byRealm[n.Realm] = list = new List<string>();
|
|
list.Add(n.NodeId);
|
|
}
|
|
}
|
|
|
|
foreach (var (realm, ids) in byRealm)
|
|
_opcUaPublishActor.Tell(new PublishActor.MarkConditionsKnown(driverInstanceId, ids, realm, Known: false));
|
|
}
|
|
|
|
private void ScheduleBackstop(string driverInstanceId, ConditionSignalTracker t)
|
|
{
|
|
if (t.GoodSinceUtc is not { } goodSince) return; // armed on the next Good edge
|
|
if (DriverTypeOf(driverInstanceId) is not { } type || _conditionSignals.BackstopSettleFor(type) is not { } settle)
|
|
{
|
|
_log.Debug("DriverHost {Node}: driver {Driver} reported unsignalable conditions but its type has no backstop — they stay unknown",
|
|
_localNode, driverInstanceId);
|
|
return;
|
|
}
|
|
|
|
var remaining = goodSince + settle - ConditionClockUtc;
|
|
Timers.StartSingleTimer(BackstopKey(driverInstanceId), new ConditionBackstopElapsed(driverInstanceId, t.Epoch),
|
|
remaining > TimeSpan.Zero ? remaining : TimeSpan.Zero);
|
|
}
|
|
|
|
private void OnConditionBackstopElapsed(ConditionBackstopElapsed msg)
|
|
{
|
|
if (!_conditionSignalTrackers.TryGetValue(msg.DriverInstanceId, out var t) || t.Epoch != msg.Epoch || t.GoodSinceUtc is null)
|
|
return;
|
|
var ids = t.Unsignalable.ToList();
|
|
t.Unsignalable.Clear();
|
|
var marked = MarkDriverConditionsKnown(msg.DriverInstanceId, ids);
|
|
NoteConditionsEstablished(msg.DriverInstanceId, t, ids);
|
|
_log.Info("DriverHost {Node}: backstop settled — {Count} unsignalable condition(s) of {Driver} marked known (residual: an upstream alarm active and never re-transitioned reads inactive)",
|
|
_localNode, marked, msg.DriverInstanceId);
|
|
}
|
|
|
|
private void OnConditionSignalTimedOut(ConditionSignalTimedOut msg)
|
|
{
|
|
if (!_conditionSignalTrackers.TryGetValue(msg.DriverInstanceId, out var t) || t.Epoch != msg.Epoch || t.Pending.Count == 0)
|
|
return;
|
|
// F5: the conditions STAY unknown (Uncertain on a consumer) — never known-inactive.
|
|
var elapsed = (t.PendingSinceUtc ?? t.GoodSinceUtc) is { } since ? ConditionClockUtc - since : TimeSpan.Zero;
|
|
t.DiagnosticRaised = true;
|
|
if (_conditionSignals.Hub is { } hub) hub.ReportUnsignalled(msg.DriverInstanceId, elapsed, t.Pending.Count);
|
|
else OtOpcUaTelemetry.DataConnConditionsUnsignalled.Add(t.Pending.Count,
|
|
new KeyValuePair<string, object?>("driver", msg.DriverInstanceId));
|
|
_log.Warning("DriverHost {Node}: initial alarm state not signalled — driver {Driver}, {Count} condition(s) still unknown after {Elapsed}",
|
|
_localNode, msg.DriverInstanceId, t.Pending.Count, elapsed);
|
|
}
|
|
|
|
/// <summary>Route driver condition ids (RawPaths) to their condition nodes and send one mark per realm.</summary>
|
|
private int MarkDriverConditionsKnown(string driverInstanceId, IReadOnlyCollection<string> conditionIds, bool known = true)
|
|
{
|
|
if (_opcUaPublishActor is null || conditionIds.Count == 0) return 0;
|
|
var byRealm = new Dictionary<AddressSpaceRealm, List<string>>();
|
|
foreach (var id in conditionIds)
|
|
{
|
|
if (!_alarmNodeIdByDriverRef.TryGetValue((driverInstanceId, id), out var nodes)) continue;
|
|
foreach (var n in nodes)
|
|
{
|
|
if (!byRealm.TryGetValue(n.Realm, out var list)) byRealm[n.Realm] = list = new List<string>();
|
|
list.Add(n.NodeId);
|
|
}
|
|
}
|
|
|
|
var count = 0;
|
|
foreach (var (realm, ids) in byRealm)
|
|
{
|
|
_opcUaPublishActor.Tell(new PublishActor.MarkConditionsKnown(driverInstanceId, ids, realm, Known: known));
|
|
count += ids.Count;
|
|
}
|
|
|
|
return count;
|
|
}
|
|
|
|
private void ForgetConditionSignals(string driverInstanceId)
|
|
{
|
|
if (!_conditionSignalTrackers.Remove(driverInstanceId)) return;
|
|
Timers.Cancel(SignalTimeoutKey(driverInstanceId));
|
|
Timers.Cancel(BackstopKey(driverInstanceId));
|
|
_conditionSignals.Hub?.ClearUnsignalled(driverInstanceId);
|
|
}
|
|
}
|