feat: add immutable partitioned data publication hub
This commit is contained in:
@@ -48,7 +48,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
/// </list>
|
||||
///
|
||||
/// Children (DriverInstance/VirtualTag/etc.) are fully wired: <c>DispatchDeployment</c> drives
|
||||
/// <see cref="PushDesiredSubscriptions"/> which runs the spawn-plan via <see cref="IDriverFactory"/>,
|
||||
/// <see cref="ApplyDesiredSubscriptions"/> which runs the spawn-plan via <see cref="IDriverFactory"/>,
|
||||
/// maintains the <c>FullName→NodeId</c> live-value routing map, and forwards results to the
|
||||
/// OPC UA publish actor via <c>ForwardBatchToMux</c> — one whole driver production burst per message,
|
||||
/// and the ONLY value ingress from driver children (<see cref="DriverInstanceActor"/> wraps even a
|
||||
@@ -184,6 +184,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
private readonly ITelemetryLocalHub? _telemetryHub;
|
||||
|
||||
private readonly CommonsNodeId _localNode;
|
||||
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? _sourcePublisher;
|
||||
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? _catalogCoordinator;
|
||||
private ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.CatalogAttempt? _catalogAttempt;
|
||||
private readonly IActorRef? _ackRouter;
|
||||
private readonly IDriverFactory _driverFactory;
|
||||
|
||||
@@ -271,7 +274,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
/// <summary>The single VirtualTag-host child that spawns/reconciles Equipment-namespace
|
||||
/// VirtualTagActors and bridges their results onto the OPC UA publish actor. Spawned in
|
||||
/// <see cref="PreStart"/> when an OPC UA publish actor is wired; receives
|
||||
/// <see cref="VirtualTagHostActor.ApplyVirtualTags"/> from <see cref="PushDesiredSubscriptions"/>.</summary>
|
||||
/// <see cref="VirtualTagHostActor.ApplyVirtualTags"/> from <see cref="ApplyDesiredSubscriptions"/>.</summary>
|
||||
private IActorRef? _virtualTagHost;
|
||||
|
||||
/// <summary>The single ScriptedAlarm-host child that owns the per-node
|
||||
@@ -279,7 +282,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
/// OPC UA publish actor + the cluster <c>alerts</c> topic. Spawned in <see cref="PreStart"/>
|
||||
/// alongside the VirtualTag host (requires both an OPC UA publish actor and a
|
||||
/// <see cref="ScriptRootLogger"/>); receives <see cref="ScriptedAlarmHostActor.ApplyScriptedAlarms"/>
|
||||
/// from <see cref="PushDesiredSubscriptions"/>.</summary>
|
||||
/// from <see cref="ApplyDesiredSubscriptions"/>.</summary>
|
||||
private IActorRef? _scriptedAlarmHost;
|
||||
|
||||
/// <summary>The scripted-alarm plans last sent to <see cref="_scriptedAlarmHost"/>, re-sent when it reports a
|
||||
@@ -330,7 +333,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
|
||||
/// <summary>
|
||||
/// Driver live-value routing map: <c>(DriverInstanceId, RawPath) → materialised NodeId(s) (realm-tagged)</c>.
|
||||
/// Rebuilt every apply by <see cref="PushDesiredSubscriptions"/> from the composition's <c>RawTags</c>
|
||||
/// Rebuilt every apply by <see cref="ApplyDesiredSubscriptions"/> from the composition's <c>RawTags</c>
|
||||
/// ∪ <c>UnsReferenceVariables</c>, and resolved in <see cref="ForwardBatchToMux"/> so a driver value
|
||||
/// published by wire-ref RawPath fans to its raw node AND every referencing UNS node with identical
|
||||
/// value/quality/timestamp — the single-source-fan-out (no independent buffer, so no drift). A set
|
||||
@@ -342,7 +345,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
/// Inverse of <see cref="_nodeIdByDriverRef"/>: <c>(Realm, BARE <c>s=</c> id) → (DriverInstanceId,
|
||||
/// RawPath)</c>. v3 Batch 4: keyed by BOTH the raw NodeId (<see cref="AddressSpaceRealm.Raw"/>) AND every
|
||||
/// referencing UNS NodeId (<see cref="AddressSpaceRealm.Uns"/>) — all mapping to the same driver ref
|
||||
/// (the single value source). Rebuilt every apply by <see cref="PushDesiredSubscriptions"/> from the
|
||||
/// (the single value source). Rebuilt every apply by <see cref="ApplyDesiredSubscriptions"/> from the
|
||||
/// composition's <c>RawTags</c> ∪ <c>UnsReferenceVariables</c>, and resolved by
|
||||
/// <see cref="HandleRouteNodeWrite"/> so an inbound operator write to EITHER NodeId is forwarded to the
|
||||
/// owning driver child as a write of its wire-ref RawPath.
|
||||
@@ -405,7 +408,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Condition NodeId → (EquipmentId, tag Name, OPC UA alarm type, HistorizeToAveva) for building
|
||||
/// the AlarmTransitionEvent fan-out. Built in the same PushDesiredSubscriptions alarm branch.
|
||||
/// the AlarmTransitionEvent fan-out. Built in the same ApplyDesiredSubscriptions alarm branch.
|
||||
/// HistorizeToAveva (bool?, null ⇒ historize) is the native per-condition opt-out parsed from
|
||||
/// <c>TagConfig.alarm.historizeToAveva</c>; it is threaded onto the transition so the
|
||||
/// HistorianAdapterActor's <c>is not false</c> gate suppresses the durable AVEVA row only on an
|
||||
@@ -642,6 +645,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
|
||||
private sealed record ChildEntry(IActorRef Actor, DriverInstanceSpec Spec, bool Stubbed)
|
||||
{
|
||||
public long? SourceIncarnation { get; init; }
|
||||
/// <summary>The driver's synchronous native-ack pre-check, when it offers one (lmxopcua#760).</summary>
|
||||
public IAlarmAcknowledgePreflight? AckPreflight { get; init; }
|
||||
|
||||
@@ -790,7 +794,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
TimeProvider? writeClock = null,
|
||||
IScriptRunner? scriptedAlarmRunner = null,
|
||||
TimeSpan? childShutdownTimeout = null,
|
||||
bool enforceSnapshotOrdering = false) =>
|
||||
bool enforceSnapshotOrdering = false,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null) =>
|
||||
// WARNING: this forwarding list is POSITIONAL, and Props.Create compiles it into an
|
||||
// expression tree. Six IActorRef? parameters and several interface-typed ones mean a
|
||||
// mis-ordered argument is usually type-compatible and therefore compiles clean, then binds
|
||||
@@ -805,7 +811,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
sharesHistorizationScopeWithLocal, applyWedgeTimeout, reprovisionBackoff, commsRecoveryAuditDelay,
|
||||
sharesAlarmQueueWithLocal, applyOutcomeTimeout, captureWhilePrimaryUnreachable, historyUpdateRoleView,
|
||||
scripting, ackPreflightView, writeBounds, writeClock, scriptedAlarmRunner, childShutdownTimeout,
|
||||
enforceSnapshotOrdering));
|
||||
enforceSnapshotOrdering, sourcePublisher, catalogCoordinator));
|
||||
|
||||
/// <summary>Initializes a new DriverHostActor with the specified dependencies.</summary>
|
||||
/// <param name="dbFactory">Database context factory for configuration database access.</param>
|
||||
@@ -941,8 +947,12 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
TimeProvider? writeClock = null,
|
||||
IScriptRunner? scriptedAlarmRunner = null,
|
||||
TimeSpan? childShutdownTimeout = null,
|
||||
bool enforceSnapshotOrdering = false)
|
||||
bool enforceSnapshotOrdering = false,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null)
|
||||
{
|
||||
_sourcePublisher = sourcePublisher;
|
||||
_catalogCoordinator = catalogCoordinator;
|
||||
_snapshotOrdering = enforceSnapshotOrdering ? new SnapshotRevisionGate() : null;
|
||||
_childShutdownTimeout = childShutdownTimeout;
|
||||
_scriptedAlarmRunner = scriptedAlarmRunner;
|
||||
@@ -1015,10 +1025,10 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
Context.System.EventStream.Subscribe(Self, typeof(ReconnectDriver));
|
||||
|
||||
// Spawn the VirtualTag host BEFORE Bootstrap so the bootstrap-restore path (which routes
|
||||
// through PushDesiredSubscriptions and Tells ApplyVirtualTags) has a live host to target.
|
||||
// through ApplyDesiredSubscriptions and Tells ApplyVirtualTags) has a live host to target.
|
||||
SpawnVirtualTagHost();
|
||||
// Same rationale for the ScriptedAlarm host — the bootstrap-restore path Tells it
|
||||
// ApplyScriptedAlarms through the same PushDesiredSubscriptions pass.
|
||||
// ApplyScriptedAlarms through the same ApplyDesiredSubscriptions pass.
|
||||
SpawnScriptedAlarmHost();
|
||||
StartPrimaryVerdictPublishing();
|
||||
StartReachabilityTracking();
|
||||
@@ -1208,14 +1218,14 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
return;
|
||||
}
|
||||
|
||||
if (_opcUaPublishActor is null)
|
||||
if (_opcUaPublishActor is null && _sourcePublisher is null)
|
||||
{
|
||||
_log.Debug("DriverHost {Node}: no OPC UA publish actor wired; skipping VirtualTag host spawn", _localNode);
|
||||
return;
|
||||
}
|
||||
|
||||
_virtualTagHost = Context.ActorOf(
|
||||
VirtualTagHostActor.Props(_opcUaPublishActor, _dependencyMux, _virtualTagEvaluator, _historyWriter, _telemetryHub),
|
||||
VirtualTagHostActor.Props(_opcUaPublishActor, _dependencyMux, _virtualTagEvaluator, _historyWriter, _telemetryHub, _sourcePublisher),
|
||||
"virtual-tag-host");
|
||||
}
|
||||
|
||||
@@ -1572,10 +1582,16 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// it directly. Passing only the deploymentId would drive a ConfigDb read — unreachable here by
|
||||
// definition — and the rebuild would no-op, leaving OPC UA clients browsing an empty server
|
||||
// while the drivers below poll happily. (Found on the docker-dev live gate.)
|
||||
try { PushDesiredSubscriptionsFromArtifact(deploymentId, blob); }
|
||||
catch
|
||||
{
|
||||
if (_catalogAttempt is not null) _catalogCoordinator?.Complete(_catalogAttempt, topologySucceeded: false);
|
||||
throw;
|
||||
}
|
||||
_opcUaPublishActor?.Tell(
|
||||
new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(correlation, deploymentId, blob));
|
||||
|
||||
PushDesiredSubscriptionsFromArtifact(deploymentId, blob);
|
||||
new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(correlation, deploymentId, blob, CatalogAttempt: _catalogAttempt));
|
||||
if (_opcUaPublishActor is null && _catalogAttempt is not null)
|
||||
_catalogCoordinator?.Complete(_catalogAttempt, topologySucceeded: true);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1778,7 +1794,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// pays at most a doubling or two, which beats over-allocating on every burst that doesn't.
|
||||
writes ??= new List<ValueWrite>(count);
|
||||
foreach (var n in nodeIds)
|
||||
writes.Add(new ValueWrite(n.NodeId, item.Value, item.StatusCode, item.TimestampUtc, n.Realm));
|
||||
writes.Add(new ValueWrite(n.NodeId, item.Value, item.StatusCode, item.TimestampUtc, n.Realm,
|
||||
item.SourceTimestampUtc, item.ServerTimestampUtc));
|
||||
}
|
||||
else if (_log.IsDebugEnabled)
|
||||
{
|
||||
@@ -1856,6 +1873,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// return for exactly that reason.
|
||||
if (!msg.Connected)
|
||||
{
|
||||
if (!_retiredChildren.Contains(Sender) &&
|
||||
(msg.ProducerIncarnation is null || _sourcePublisher?.IsDriverIncarnationActive(msg.DriverInstanceId, msg.ProducerIncarnation.Value) == true))
|
||||
_sourcePublisher?.PublishDriverStatus(msg.DriverInstanceId, OpcUaStatus.BadNoCommunication);
|
||||
FanCommsLossToDependencyMux(msg.DriverInstanceId);
|
||||
// And the EXTERNAL data plane, which the dependency-mux fan-out stopped one seam short of.
|
||||
FanCommsLossToValueNodes(msg.DriverInstanceId);
|
||||
@@ -3028,7 +3048,6 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// until OpcUaPublishActor replies RebuildCompleted (HandleRebuildCompleted) or the outcome
|
||||
// timeout fires (sent degraded, "outcome unknown"). With no publish actor there is no address
|
||||
// space to wait for, so the ack goes out clean immediately — exactly the old behaviour.
|
||||
AwaitAddressSpaceOutcomeThenAck(msg.DeploymentId, msg.Revision, msg.Correlation);
|
||||
// Rebuild the address space + push subscriptions FROM the bytes this apply already has, so
|
||||
// nothing downstream re-reads the artifact: under FetchAndCache OpcUaPublishActor has no
|
||||
// central SQL to read at all, and under Direct a bytes-less RebuildAddressSpace would make
|
||||
@@ -3043,13 +3062,18 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// ReportOutcome: the reply (to Self — this Tell runs inside a receive, so the implicit sender is
|
||||
// this actor) releases the held ack. Plain Tell + reply message, no Ask/await, so nothing here
|
||||
// resumes off the actor thread.
|
||||
_opcUaPublishActor?.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(
|
||||
msg.Correlation, msg.DeploymentId, appliedBlob, ReportOutcome: true));
|
||||
// SubscribeBulk pass: hand each driver its desired tag references so live values flow into
|
||||
// the just-rebuilt address space instead of staying BadWaitingForInitialData.
|
||||
PushDesiredSubscriptionsFromParsed(msg.DeploymentId, parsed);
|
||||
// Cache the applied bytes as this node's last-known-good (idempotent store; skips empty).
|
||||
CacheAppliedArtifact(msg.DeploymentId, msg.Revision, appliedBlob, parsed);
|
||||
var catalogFailed = _opcUaPublishActor is null && _catalogAttempt is not null
|
||||
&& _catalogCoordinator is not null
|
||||
&& !_catalogCoordinator.Complete(_catalogAttempt, topologySucceeded: true)
|
||||
&& _catalogAttempt.Expected;
|
||||
AwaitAddressSpaceOutcomeThenAck(msg.DeploymentId, msg.Revision, msg.Correlation, catalogFailed);
|
||||
_opcUaPublishActor?.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(
|
||||
msg.Correlation, msg.DeploymentId, appliedBlob, ReportOutcome: true, CatalogAttempt: _catalogAttempt));
|
||||
// Reaching here means the artifact came from central, so the node is no longer serving a
|
||||
// cache-sourced configuration. Note this only clears on a real apply: a dispatch of the
|
||||
// revision already booted from cache short-circuits in HandleDispatchFromSteady without
|
||||
@@ -3064,6 +3088,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (_catalogAttempt is not null) _catalogCoordinator?.Complete(_catalogAttempt, topologySucceeded: false);
|
||||
// A throw after the Applied ack was put on hold — the Failed ack below is this apply's one
|
||||
// answer, so the held Applied must never follow it when the address-space outcome lands.
|
||||
DropPendingAck(msg.Correlation);
|
||||
@@ -3101,13 +3126,13 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
/// With no publish actor wired (tests, a node with no OPC UA data plane) there is no outcome to wait
|
||||
/// for, so the ack is sent clean at once — byte-for-byte the earlier behaviour.
|
||||
/// </summary>
|
||||
private void AwaitAddressSpaceOutcomeThenAck(DeploymentId deploymentId, RevisionHash revision, CorrelationId correlation)
|
||||
private void AwaitAddressSpaceOutcomeThenAck(DeploymentId deploymentId, RevisionHash revision, CorrelationId correlation,
|
||||
bool catalogFailed = false)
|
||||
{
|
||||
if (_opcUaPublishActor is null)
|
||||
{
|
||||
_currentRevisionUnconfirmed = false;
|
||||
UpsertNodeDeploymentState(deploymentId, NodeDeploymentStatus.Applied, failureReason: null);
|
||||
SendAck(deploymentId, ApplyAckOutcome.Applied, failureReason: null, correlation);
|
||||
ReleasePendingAck(new PendingAck(deploymentId, revision, correlation), catalogFailed,
|
||||
catalogFailed ? "the expected local data catalog could not be activated" : null);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -3262,7 +3287,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
private byte[]? ReconcileDrivers(DeploymentId deploymentId)
|
||||
{
|
||||
var blob = LoadArtifactBlob(deploymentId);
|
||||
return blob is null ? null : ReconcileDriversFromBlob(deploymentId, blob);
|
||||
return ReconcileDriversFromBlob(deploymentId, blob);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -3362,6 +3387,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
/// children left running — the honest reading of bytes that cannot be understood.</exception>
|
||||
private ReconciledArtifact ReconcileDriversFromParsed(DeploymentId deploymentId, byte[]? blob)
|
||||
{
|
||||
BeginCatalogAttempt(blob);
|
||||
blob ??= Array.Empty<byte>();
|
||||
if (blob.Length == 0)
|
||||
{
|
||||
@@ -3376,6 +3402,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
var parsed = DeploymentArtifact.Open(blob);
|
||||
try
|
||||
{
|
||||
StageCatalog(parsed);
|
||||
ApplyDriverSpecs(parsed.ParseDriverInstances(_localNode.Value));
|
||||
}
|
||||
catch
|
||||
@@ -3396,6 +3423,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
/// <returns>The reconciled blob, or <see langword="null"/> when it was empty.</returns>
|
||||
private byte[]? ReconcileDriversFromBlob(DeploymentId deploymentId, byte[]? blob)
|
||||
{
|
||||
BeginCatalogAttempt(blob);
|
||||
blob ??= Array.Empty<byte>();
|
||||
if (blob.Length == 0)
|
||||
{
|
||||
@@ -3411,6 +3439,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
try
|
||||
{
|
||||
using var parsed = DeploymentArtifact.Open(blob);
|
||||
StageCatalog(parsed);
|
||||
specs = parsed.ParseDriverInstances(_localNode.Value);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
@@ -3425,6 +3454,44 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
return blob;
|
||||
}
|
||||
|
||||
private void BeginCatalogAttempt(byte[]? blob)
|
||||
{
|
||||
if (_catalogCoordinator is null) return;
|
||||
var revision = blob is { Length: > 0 }
|
||||
? Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(blob)) : "unavailable";
|
||||
_catalogAttempt = _catalogCoordinator.BeginAttempt(revision);
|
||||
}
|
||||
|
||||
private void StageCatalog(ParsedDeploymentArtifact parsed)
|
||||
{
|
||||
if (_catalogCoordinator is null || _catalogAttempt is null) return;
|
||||
_catalogAttempt.SetExpected(parsed.ExpectsLocalDataCatalog());
|
||||
try
|
||||
{
|
||||
var authority = parsed.ParseDataPlaneAuthority(_localNode.Value);
|
||||
if (!_catalogCoordinator.InstallAuthority(_catalogAttempt, authority)) return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Error(ex, "DriverHost {Node}: failed to install desired data authority; catalog remains closed", _localNode);
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (!string.Equals(_catalogCoordinator.Serving.NodeId, _localNode.Value, StringComparison.Ordinal))
|
||||
{
|
||||
_log.Error("DriverHost {Node}: data catalog serving identity names another node", _localNode);
|
||||
return;
|
||||
}
|
||||
var snapshot = parsed.ParseLocalCatalogSnapshot(_localNode.Value);
|
||||
if (snapshot is not null) _catalogCoordinator.Stage(_catalogAttempt, snapshot, _localNode.Value);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Error(ex, "DriverHost {Node}: failed to stage desired data catalog; catalog remains closed", _localNode);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// No bytes is no answer, not "a configuration with no drivers". Parsing zero bytes
|
||||
/// yields zero specs, and <c>DriverSpawnPlanner</c> then plans EVERY running child for StopChild: a
|
||||
@@ -3449,7 +3516,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
var plan = DriverSpawnPlanner.Compute(snapshots, specs);
|
||||
|
||||
foreach (var id in plan.ToStop) StopChild(id);
|
||||
foreach (var spec in plan.ToSpawn) SpawnChild(spec);
|
||||
foreach (var spec in plan.ToSpawn) SpawnChild(spec, deferSubscriptions: _sourcePublisher is not null);
|
||||
|
||||
// v3: a dependency-consumer driver's declared dependency refs change when its tags/scripts are
|
||||
// edited. That edit changes its DriverConfig, which respawns it, and the respawned driver's
|
||||
@@ -3606,10 +3673,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
/// No re-ack: the deployment is already Applied.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Its two ConfigDb reads (<see cref="ReconcileDrivers"/> and
|
||||
/// <see cref="PushDesiredSubscriptions"/>) stay SYNCHRONOUS deliberately: this runs in
|
||||
/// <see cref="PreStart"/>, before the host has processed a single message, so there is no live
|
||||
/// traffic behind them to block — unlike the apply path, which moved its read off the mailbox.
|
||||
/// The artifact read in <see cref="ReconcileDrivers"/> stays synchronous because this runs in
|
||||
/// <see cref="PreStart"/>, before the host has processed a single message. The same bytes drive
|
||||
/// reconciliation, subscriptions and the address-space rebuild.
|
||||
/// </remarks>
|
||||
private void RestoreApplied(DeploymentId deploymentId, RevisionHash? revision)
|
||||
{
|
||||
@@ -3621,8 +3687,15 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// were NOT restored: the adopted revision is unconfirmed (fourth review M2), and a re-dispatch of it
|
||||
// re-applies instead of short-circuiting a clean Applied.
|
||||
if (appliedBlob is null) _currentRevisionUnconfirmed = true;
|
||||
_opcUaPublishActor?.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(correlation, deploymentId, appliedBlob));
|
||||
PushDesiredSubscriptions(deploymentId);
|
||||
if (appliedBlob is not null)
|
||||
PushDesiredSubscriptionsFromArtifact(deploymentId, appliedBlob);
|
||||
if (_opcUaPublishActor is null && _catalogAttempt is not null)
|
||||
{
|
||||
var complete = _catalogCoordinator?.Complete(_catalogAttempt, topologySucceeded: appliedBlob is not null) ?? false;
|
||||
if (!complete && _catalogAttempt.Expected) _currentRevisionUnconfirmed = true;
|
||||
}
|
||||
else if (_catalogAttempt?.Expected == true)
|
||||
_currentRevisionUnconfirmed = true;
|
||||
// Populate the node-local cache from the artifact this restored node is now serving. The
|
||||
// cache invariant is "holds what the node currently serves"; without this only a FRESH
|
||||
// apply (BeginDirectApply) ever wrote it, so a node whose cache was lost — a wiped/fresh volume,
|
||||
@@ -3633,10 +3706,12 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// it. (Found on the docker-dev live gate.)
|
||||
if (revision is { } rev)
|
||||
CacheAppliedArtifact(deploymentId, rev, appliedBlob);
|
||||
_opcUaPublishActor?.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(correlation, deploymentId, appliedBlob, CatalogAttempt: _catalogAttempt));
|
||||
_log.Info("DriverHost {Node}: restored served state for applied deployment {Id} on bootstrap", _localNode, deploymentId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (_catalogAttempt is not null) _catalogCoordinator?.Complete(_catalogAttempt, topologySucceeded: false);
|
||||
// The revision was adopted from the row but its served state was NOT restored (fourth review M2): mark it
|
||||
// unconfirmed so a re-dispatch of it re-applies instead of short-circuiting a clean Applied.
|
||||
_currentRevisionUnconfirmed = true;
|
||||
@@ -3644,66 +3719,12 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SubscribeBulk pass. After an apply, read the deployment's Equipment-namespace tags,
|
||||
/// group their driver-side FullName references by driver instance, and hand each running driver
|
||||
/// child its desired subscription set via <see cref="DriverInstanceActor.SetDesiredSubscriptions"/>.
|
||||
/// The child retains the set and (re)subscribes on every Connected entry, so values stream into
|
||||
/// the OPC UA sink and resume after reconnects. Drivers with no configured tags get an empty set
|
||||
/// (which clears any stale subscription from a previous deployment).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The <b>bootstrap-restore</b> entry point only. Neither apply path reaches it any more:
|
||||
/// <see cref="HandleArtifactForApply"/> already holds the apply's single parse and calls
|
||||
/// <see cref="PushDesiredSubscriptionsFromParsed"/> directly, so this ConfigDb read exists for
|
||||
/// <see cref="RestoreApplied"/>, which restores from a deployment id recovered out of
|
||||
/// NodeDeploymentState and may hold no blob of its own.
|
||||
/// </remarks>
|
||||
private void PushDesiredSubscriptions(DeploymentId deploymentId)
|
||||
{
|
||||
// Phase 4 belt-and-suspenders: a ConfigDb read, so it can only be the restore path on a node that
|
||||
// has one (every apply path calls PushDesiredSubscriptionsFromParsed with its parse in hand).
|
||||
// No ConfigDb ⇒ nothing to load.
|
||||
if (_dbFactory is null)
|
||||
{
|
||||
_log.Warning("DriverHost {Node}: no ConfigDb to load artifact for SubscribeBulk ({Id}); skipping", _localNode, deploymentId);
|
||||
return;
|
||||
}
|
||||
|
||||
byte[] blob;
|
||||
try
|
||||
{
|
||||
// Synchronous by design: the only caller is the PreStart restore path above, where nothing
|
||||
// is queued behind this read (the apply path reads off the mailbox instead).
|
||||
using var db = _dbFactory.CreateDbContext();
|
||||
blob = db.Deployments.AsNoTracking()
|
||||
.Where(d => d.DeploymentId == deploymentId.Value)
|
||||
.Select(d => d.ArtifactBlob)
|
||||
.FirstOrDefault() ?? Array.Empty<byte>();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warning(ex, "DriverHost {Node}: failed to load artifact for SubscribeBulk ({Id})", _localNode, deploymentId);
|
||||
return;
|
||||
}
|
||||
|
||||
PushDesiredSubscriptionsFromArtifact(deploymentId, blob);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The artifact-processing half of <see cref="PushDesiredSubscriptions"/>, split out so the
|
||||
/// boot-from-cache path can drive it with bytes already in hand.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Separated because the cache path runs precisely when the ConfigDb read above cannot
|
||||
/// succeed — re-reading the artifact there would fail by definition.
|
||||
/// </remarks>
|
||||
/// <summary>Apply subscriptions from the artifact bytes already loaded for cache boot or restore.</summary>
|
||||
private void PushDesiredSubscriptionsFromArtifact(DeploymentId deploymentId, byte[] blob)
|
||||
{
|
||||
// The same "no bytes is no answer" rule as ReconcileDrivers. An empty artifact parses
|
||||
// to a composition with no raw tags, which hands every child an EMPTY desired set — and an empty set
|
||||
// drops the live subscription handle rather than re-subscribing. Reachable independently of the
|
||||
// reconcile guard: this method does its OWN ConfigDb read, so the row can go missing between the two.
|
||||
// drops the live subscription handle rather than re-subscribing.
|
||||
if (blob.Length == 0)
|
||||
{
|
||||
_log.Warning(
|
||||
@@ -3777,6 +3798,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
/// <param name="composition">The composition this node should serve.</param>
|
||||
private void ApplyDesiredSubscriptions(AddressSpaceComposition composition)
|
||||
{
|
||||
_catalogCoordinator?.BeforeSubscriptionApplyForTests?.Invoke();
|
||||
// v3 Batch 4: the driver subscribes + publishes by RawPath (the wire-ref == RawPath == RawTagPlan.NodeId
|
||||
// per the v3 identity contract). Value-subscription set = the non-alarm raw tags' RawPaths; alarm-bearing
|
||||
// raw tags are Part 9 conditions, fed via the native alarm event stream (ForwardNativeAlarm), so they are
|
||||
@@ -3817,6 +3839,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
|
||||
// Rebuild the driver live-value + write routing maps from the RawTags ∪ UnsReferenceVariables pass.
|
||||
// Clear-and-repopulate every apply so renames/removals/re-points are reflected.
|
||||
var previousSourceRefs = _sourcePublisher is null ? null : _nodeIdByDriverRef.Keys.ToArray();
|
||||
_nodeIdByDriverRef.Clear();
|
||||
_driverRefByNodeId.Clear();
|
||||
_alarmNodeIdByDriverRef.Clear();
|
||||
@@ -3856,6 +3879,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
|
||||
// Value tag: register the RAW NodeId (Raw realm) AND every referencing UNS NodeId (Uns realm)
|
||||
// against the SAME driver ref — the single value source fans to all of them.
|
||||
_sourcePublisher?.RegisterDriverShape(t.DriverInstanceId, t.NodeId,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceValueShape.FromDriverType(t.DataType, t.IsArray));
|
||||
if (!_nodeIdByDriverRef.TryGetValue(key, out var set))
|
||||
{
|
||||
_nodeIdByDriverRef[key] = set = new HashSet<NodeRealmRef>();
|
||||
@@ -3877,6 +3902,15 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
}
|
||||
}
|
||||
|
||||
if (previousSourceRefs is not null)
|
||||
foreach (var previous in previousSourceRefs)
|
||||
if (!_nodeIdByDriverRef.ContainsKey(previous))
|
||||
{
|
||||
if (_sourcePublisher!.TryCaptureDriver(previous.DriverInstanceId, previous.RawPath, out var ticket))
|
||||
_sourcePublisher.TryRemove(ticket);
|
||||
_sourcePublisher.ForgetDriverShape(previous.DriverInstanceId, previous.RawPath);
|
||||
}
|
||||
|
||||
// Forget the projected prior state of conditions this composition no longer carries, and keep
|
||||
// the rest. Clearing it whole on every apply made the next driver Acknowledge of a still-active alarm
|
||||
// project Active=false (the default prior), and the next Clear of an unacknowledged one project
|
||||
@@ -3916,7 +3950,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// VirtualTagActor per plan and streams their evaluated values back onto the just-rebuilt
|
||||
// address space. Runs on BOTH the fresh-apply path (HandleArtifactForApply) and the bootstrap-restore
|
||||
// path (RestoreApplied) because both call this method, so one send covers both.
|
||||
// NOTE: the Stale-recovery path (TryRecoverFromStale) does NOT call PushDesiredSubscriptions,
|
||||
// NOTE: the Stale-recovery path (TryRecoverFromStale) does NOT apply desired subscriptions,
|
||||
// so — like drivers — VirtualTags remain empty after a Stale recovery until the next
|
||||
// deployment dispatch. This is intentional and consistent with driver recovery: the Stale
|
||||
// path only restores the revision marker + NodeDeploymentState; a subsequent dispatch
|
||||
@@ -3969,7 +4003,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
return set.ValueRefs.Count;
|
||||
}
|
||||
|
||||
private void SpawnChild(DriverInstanceSpec spec)
|
||||
private void SpawnChild(DriverInstanceSpec spec, bool deferSubscriptions = false)
|
||||
{
|
||||
// An instance id removed by an earlier deployment (StopChild ⇒ Evict, which also holds back late
|
||||
// items) may come back; lift the hold BEFORE the child exists, since it publishes health as it starts.
|
||||
@@ -4014,6 +4048,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// ("actor name is not unique"). Children are tracked by the _children dict (by IActorRef), never
|
||||
// by path, so the suffix is invisible to every caller.
|
||||
var actorName = ActorNameFor(spec.DriverInstanceId, _childSpawnGeneration++);
|
||||
var sourceIncarnation = _sourcePublisher?.RegisterDriverIncarnation(spec.DriverInstanceId);
|
||||
if (stub)
|
||||
{
|
||||
child = Context.ActorOf(
|
||||
@@ -4022,7 +4057,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
reconnectInterval: null,
|
||||
startStubbed: true,
|
||||
healthPublisher: _healthPublisher,
|
||||
clusterId: clusterId),
|
||||
clusterId: clusterId, sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation),
|
||||
actorName);
|
||||
}
|
||||
else
|
||||
@@ -4040,7 +4075,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
invoker: invoker,
|
||||
writeTimeout: _writeBounds.Timeout,
|
||||
writeClock: _writeClock,
|
||||
shutdownTimeout: _childShutdownTimeout),
|
||||
shutdownTimeout: _childShutdownTimeout,
|
||||
sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation),
|
||||
actorName);
|
||||
child.Tell(new DriverInstanceActor.InitializeRequested(spec.DriverConfig));
|
||||
}
|
||||
@@ -4048,6 +4084,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
_children[spec.DriverInstanceId] = new ChildEntry(child, spec, stub)
|
||||
{
|
||||
AckPreflight = stub ? null : driver as IAlarmAcknowledgePreflight,
|
||||
SourceIncarnation = sourceIncarnation,
|
||||
};
|
||||
PublishAckPreflight();
|
||||
|
||||
@@ -4072,7 +4109,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// Deliberately not "fixed" by withholding the send: a child that never gets a set is the 03/S16
|
||||
// defect, and the operator-Restart and supervision paths have no bulk push coming at all.
|
||||
// Sent after InitializeRequested above, which keeps init-before-subscribe ordering.
|
||||
SendDesiredSubscriptions(child, spec.DriverInstanceId);
|
||||
if (!deferSubscriptions) SendDesiredSubscriptions(child, spec.DriverInstanceId);
|
||||
|
||||
// v3: if the (real, non-stub) driver consumes other tags' live values, spawn a mux-adapter
|
||||
// child that registers its dependency refs on the per-node dependency mux and forwards changes
|
||||
@@ -4104,6 +4141,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
{
|
||||
if (!_children.TryGetValue(driverInstanceId, out var entry)) return;
|
||||
StopDependencyAdapter(driverInstanceId);
|
||||
_sourcePublisher?.RetireCurrentDriver(driverInstanceId);
|
||||
RetireChild(entry.Actor);
|
||||
Context.Stop(entry.Actor);
|
||||
_children.Remove(driverInstanceId);
|
||||
@@ -4222,6 +4260,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
|
||||
// Stop the existing child actor — DriverInstanceActor.PostStop calls ShutdownAsync.
|
||||
StopDependencyAdapter(msg.DriverInstanceId);
|
||||
_sourcePublisher?.RetireCurrentDriver(msg.DriverInstanceId);
|
||||
RetireChild(entry.Actor);
|
||||
Context.Stop(entry.Actor);
|
||||
_children.Remove(msg.DriverInstanceId);
|
||||
@@ -4362,7 +4401,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
{
|
||||
_currentRevision = RevisionHash.Parse(latestSealed.RevisionHash);
|
||||
// Adopted, NOT applied (fourth review M2): Stale recovery restores only the revision marker — drivers
|
||||
// and the address space stay empty until a dispatch (see PushDesiredSubscriptions' note). Unconfirmed,
|
||||
// and the address space stay empty until a dispatch (see the stale-recovery note). Unconfirmed,
|
||||
// so a dispatch of this same revision re-applies rather than short-circuiting a clean Applied over an
|
||||
// empty address space.
|
||||
_currentRevisionUnconfirmed = true;
|
||||
|
||||
Reference in New Issue
Block a user