feat: add immutable partitioned data publication hub
This commit is contained in:
@@ -42,7 +42,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// annotates this driver's native alarm conditions' source-data Quality from it (comms lost → Bad,
|
||||
/// restored → Good) — independently of alarm transitions, since a comms-lost driver emits no alarm
|
||||
/// events. Fire-and-forget.</summary>
|
||||
public sealed record ConnectivityChanged(string DriverInstanceId, bool Connected);
|
||||
public sealed record ConnectivityChanged(string DriverInstanceId, bool Connected, long? ProducerIncarnation = null);
|
||||
|
||||
/// <summary>
|
||||
/// Sent to the parent from <see cref="PostRestart"/> so the host re-provisions THIS incarnation.
|
||||
@@ -142,16 +142,19 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// <para>A struct deliberately: an <c>AttributeValueItem[]</c> then holds its items inline, so a burst of
|
||||
/// N values costs one array allocation instead of one array plus N boxes. Indexed access through
|
||||
/// <see cref="IReadOnlyList{T}"/> does not box.</para></summary>
|
||||
public readonly record struct AttributeValueItem(string FullReference, object? Value, uint StatusCode, DateTime TimestampUtc);
|
||||
public readonly record struct AttributeValueItem(string FullReference, object? Value, uint StatusCode, DateTime TimestampUtc,
|
||||
DateTime? SourceTimestampUtc = null, DateTime? ServerTimestampUtc = null);
|
||||
/// <summary>The ONLY value message a driver child sends: every changed attribute of ONE driver production
|
||||
/// burst in one message (a single data change is a one-item batch). The parent fans the whole batch to the mux and the OPC UA
|
||||
/// publish path in one hop each. Status codes ride verbatim.</summary>
|
||||
public sealed record AttributeValueBatchPublished(string DriverInstanceId, IReadOnlyList<AttributeValueItem> Items);
|
||||
private sealed record DataChangeForward(string FullReference, DataValueSnapshot Snapshot);
|
||||
private sealed record DataChangeForward(string FullReference, DataValueSnapshot Snapshot, long? ProducerIncarnation);
|
||||
/// <summary>Self-sent when a batch-capable driver (<see cref="IBatchSubscribable"/>) raises
|
||||
/// <see cref="IBatchSubscribable.OnDataChangeBatch"/> — marshals the whole burst off the driver's
|
||||
/// thread onto the actor thread in one hop. Parallels <see cref="DataChangeForward"/>.</summary>
|
||||
private sealed record DataChangeBatchForward(IReadOnlyList<DataChangeItem> Items);
|
||||
private sealed record DataChangeBatchForward(IReadOnlyList<DataChangeItem> Items, long? ProducerIncarnation);
|
||||
private sealed record RetrySourceBindings(IReadOnlyList<string> References, int Offset, bool Failed,
|
||||
int Attempt, long Version, long ProducerIncarnation);
|
||||
/// <summary>Published to the parent whenever the subscribed driver (an <see cref="IAlarmSource"/>) fires
|
||||
/// <see cref="IAlarmSource.OnAlarmEvent"/>. The parent (<see cref="DriverHostActor"/>) projects + routes it
|
||||
/// to the materialised Part 9 condition. Parallels <see cref="AttributeValueBatchPublished"/>.</summary>
|
||||
@@ -389,6 +392,10 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// <summary>The batch data-change handler, attached INSTEAD of <see cref="_dataChangeHandler"/> when the
|
||||
/// driver is an <see cref="IBatchSubscribable"/>. Exactly one of the two is ever non-null.</summary>
|
||||
private EventHandler<DataChangeBatchEventArgs>? _batchChangeHandler;
|
||||
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? _sourcePublisher;
|
||||
private long? _sourceIncarnation;
|
||||
private long _sourceBindingVersion;
|
||||
private const int SourceBindingBatchSize = 128;
|
||||
private EventHandler<AlarmEventArgs>? _alarmEventHandler;
|
||||
private EventHandler<RediscoveryEventArgs>? _rediscoveryHandler;
|
||||
private EventHandler<HostStatusChangedEventArgs>? _hostStatusHandler;
|
||||
@@ -491,7 +498,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
TimeSpan? queuedWriteBudget = null,
|
||||
TimeSpan? initializeTimeout = null,
|
||||
TimeSpan? writeTimeout = null,
|
||||
TimeProvider? writeClock = null) =>
|
||||
TimeProvider? writeClock = null,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
|
||||
long? sourceIncarnation = null) =>
|
||||
Akka.Actor.Props.Create(() => new DriverInstanceActor(
|
||||
driver,
|
||||
reconnectInterval ?? DefaultReconnectInterval,
|
||||
@@ -506,7 +515,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
queuedWriteBudget,
|
||||
initializeTimeout,
|
||||
writeTimeout,
|
||||
writeClock));
|
||||
writeClock, sourcePublisher, sourceIncarnation));
|
||||
|
||||
/// <summary>
|
||||
/// Returns true when the driver should boot in DEV-STUB mode based on host platform and
|
||||
@@ -568,8 +577,12 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
TimeSpan? queuedWriteBudget = null,
|
||||
TimeSpan? initializeTimeout = null,
|
||||
TimeSpan? writeTimeout = null,
|
||||
TimeProvider? writeClock = null)
|
||||
TimeProvider? writeClock = null,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
|
||||
long? sourceIncarnation = null)
|
||||
{
|
||||
_sourcePublisher = sourcePublisher;
|
||||
_sourceIncarnation = sourceIncarnation;
|
||||
_writeTimeout = writeTimeout is { } wt && wt > TimeSpan.Zero ? wt : DefaultWriteTimeout;
|
||||
_writeClock = writeClock ?? TimeProvider.System;
|
||||
_incarnation = Interlocked.Increment(ref s_initGenerationSource);
|
||||
@@ -605,6 +618,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// <inheritdoc />
|
||||
protected override void PreStart()
|
||||
{
|
||||
if (_sourcePublisher is not null && _sourceIncarnation is { } previous &&
|
||||
!_sourcePublisher.IsDriverIncarnationActive(_driverInstanceId, previous))
|
||||
_sourceIncarnation = _sourcePublisher.RegisterDriverIncarnation(_driverInstanceId);
|
||||
// Warm up the snapshot store immediately so AdminUI sees current state as soon as the
|
||||
// actor starts, before any state transition fires. Also start the periodic heartbeat so
|
||||
// long-lived Healthy drivers keep their snapshot fresh for newly-joined SignalR clients.
|
||||
@@ -725,7 +741,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
// Announce connectivity to the host so it can clear any comms-lost Quality annotation on this
|
||||
// driver's native alarm conditions (Bad → Good). Fire-and-forget; the host defaults conditions to a
|
||||
// non-Good "waiting for initial data" quality at materialise, and this is what confirms them Good.
|
||||
Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: true));
|
||||
Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: true, ProducerIncarnation: _sourceIncarnation));
|
||||
|
||||
// Baseline for the comms-loss watchdog. Re-stamped on every Connected entry so a driver that
|
||||
// reconnects but never manages a read is measured from THIS connect, not from a stale earlier one.
|
||||
@@ -750,9 +766,11 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
Receive<WriteCompleted>(OnWriteCompleted);
|
||||
ReceiveAsync<RouteAlarmAck>(HandleAcknowledgeAsync);
|
||||
ReceiveAsync<Subscribe>(HandleSubscribeAsync);
|
||||
ReceiveAsync<Unsubscribe>(_ => UnsubscribeAsync());
|
||||
ReceiveAsync<Unsubscribe>(_ => { CancelSourceBindingRetry(); return UnsubscribeAsync(); });
|
||||
Receive<RetrySourceBindings>(RetrySourceBindingBatch);
|
||||
Receive<SetDesiredSubscriptions>(msg =>
|
||||
{
|
||||
CancelSourceBindingRetry();
|
||||
StoreDesiredSubscriptions(msg);
|
||||
if (_desiredRefs.Count > 0) Self.Tell(new Subscribe(_desiredRefs, _desiredInterval));
|
||||
else if (_subscriptionHandle is not null) Self.Tell(new Unsubscribe());
|
||||
@@ -967,7 +985,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
{
|
||||
// Announce comms loss to the host so it annotates this driver's native alarm conditions Bad
|
||||
// (a comms-lost driver emits no alarm events, so this is the ONLY signal that the source is unreachable).
|
||||
Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: false));
|
||||
Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: false, ProducerIncarnation: _sourceIncarnation));
|
||||
|
||||
// Tear the dead transport down before re-initialising, or every retry leaks one.
|
||||
Receive<RetryConnect>(_ => InitializeAsync(_currentConfigJson ?? "{}", teardownFirst: true));
|
||||
@@ -1467,6 +1485,8 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
// in this handler so continuations resume on the actor context.
|
||||
var replyTo = Sender;
|
||||
var self = Self;
|
||||
CancelSourceBindingRetry();
|
||||
var sourceBindingVersion = _sourceBindingVersion;
|
||||
if (_driver is not ISubscribable subscribable)
|
||||
{
|
||||
replyTo.Tell(new SubscriptionFailed("Driver does not implement ISubscribable"));
|
||||
@@ -1480,6 +1500,14 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
|
||||
try
|
||||
{
|
||||
var sourceBindingNeedsRetry = false;
|
||||
if (_sourcePublisher is not null && _sourceIncarnation is { } incarnation)
|
||||
{
|
||||
var count = Math.Min(msg.FullReferences.Count, SourceBindingBatchSize);
|
||||
for (var i = 0; i < count; i++)
|
||||
sourceBindingNeedsRetry |= !TryEnsureSourceBinding(msg.FullReferences[i], incarnation);
|
||||
sourceBindingNeedsRetry |= count < msg.FullReferences.Count;
|
||||
}
|
||||
// EXACTLY ONE of the two data-change events is subscribed. An IBatchSubscribable driver raises
|
||||
// OnDataChangeBatch once per production burst AND the per-tag OnDataChange for every item in
|
||||
// that same burst (the per-tag event is kept for legacy consumers — Galaxy cold reads, driver
|
||||
@@ -1492,13 +1520,30 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
// A null/empty raise from a buggy driver must never enter the mailbox: an unguarded null
|
||||
// would throw in the handler, restart the actor, and tear down the driver transport.
|
||||
if (args?.Items is not { Count: > 0 }) return;
|
||||
self.Tell(new DataChangeBatchForward(args.Items));
|
||||
var owned = new DataChangeItem[args.Items.Count];
|
||||
for (var i = 0; i < owned.Length; i++)
|
||||
{
|
||||
var item = args.Items[i];
|
||||
if (item is null) { owned[i] = null!; continue; }
|
||||
PublishSource(item.FullReference, item.Snapshot);
|
||||
owned[i] = new DataChangeItem(item.FullReference, CopyLegacySnapshot(item.Snapshot));
|
||||
}
|
||||
self.Tell(new DataChangeBatchForward(owned, _sourceIncarnation));
|
||||
};
|
||||
batchable.OnDataChangeBatch += _batchChangeHandler;
|
||||
}
|
||||
else
|
||||
{
|
||||
_dataChangeHandler = (_, args) => self.Tell(new DataChangeForward(args.FullReference, args.Snapshot));
|
||||
_dataChangeHandler = (_, args) =>
|
||||
{
|
||||
if (args is null)
|
||||
{
|
||||
self.Tell(new DataChangeForward(string.Empty, null!, _sourceIncarnation));
|
||||
return;
|
||||
}
|
||||
PublishSource(args.FullReference, args.Snapshot);
|
||||
self.Tell(new DataChangeForward(args.FullReference, CopyLegacySnapshot(args.Snapshot), _sourceIncarnation));
|
||||
};
|
||||
subscribable.OnDataChange += _dataChangeHandler;
|
||||
}
|
||||
|
||||
@@ -1511,6 +1556,10 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
async ct => await subscribable.SubscribeAsync(msg.FullReferences, msg.PublishingInterval, ct),
|
||||
cts.Token);
|
||||
|
||||
if (sourceBindingNeedsRetry && _sourceIncarnation is { } retryIncarnation)
|
||||
Timers.StartSingleTimer("source-binding-retry", new RetrySourceBindings(msg.FullReferences,
|
||||
0, false, 0, sourceBindingVersion, retryIncarnation), TimeSpan.FromMilliseconds(250));
|
||||
|
||||
replyTo.Tell(new SubscriptionEstablished(_subscriptionHandle.DiagnosticId, msg.FullReferences.Count));
|
||||
_log.Info("DriverInstance {Id}: subscribed to {Count} refs ({Diag})",
|
||||
_driverInstanceId, msg.FullReferences.Count, _subscriptionHandle.DiagnosticId);
|
||||
@@ -1523,6 +1572,44 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
}
|
||||
}
|
||||
|
||||
private void CancelSourceBindingRetry()
|
||||
{
|
||||
Timers.Cancel("source-binding-retry");
|
||||
_sourceBindingVersion++;
|
||||
}
|
||||
|
||||
private bool TryEnsureSourceBinding(string reference, long incarnation)
|
||||
{
|
||||
try { return _sourcePublisher?.EnsureDriverBinding(_clusterId, _driverInstanceId, reference, incarnation) == true; }
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
_log.Warning(ex, "DriverInstance {Id}: source binding unavailable; legacy subscription remains active", _driverInstanceId);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void RetrySourceBindingBatch(RetrySourceBindings retry)
|
||||
{
|
||||
if (retry.Version != _sourceBindingVersion || _sourceIncarnation != retry.ProducerIncarnation || _subscriptionHandle is null)
|
||||
return;
|
||||
var end = Math.Min(retry.References.Count, retry.Offset + SourceBindingBatchSize);
|
||||
var failed = retry.Failed;
|
||||
for (var i = retry.Offset; i < end; i++)
|
||||
failed |= !TryEnsureSourceBinding(retry.References[i], retry.ProducerIncarnation);
|
||||
if (end < retry.References.Count)
|
||||
{
|
||||
Timers.StartSingleTimer("source-binding-retry", retry with { Offset = end, Failed = failed }, TimeSpan.FromMilliseconds(1));
|
||||
return;
|
||||
}
|
||||
if (failed)
|
||||
{
|
||||
var attempt = Math.Min(retry.Attempt + 1, 7);
|
||||
var delayMs = Math.Min(30_000, 250 * (1 << attempt));
|
||||
Timers.StartSingleTimer("source-binding-retry", retry with { Offset = 0, Failed = false, Attempt = attempt },
|
||||
TimeSpan.FromMilliseconds(delayMs));
|
||||
}
|
||||
}
|
||||
|
||||
private async Task UnsubscribeAsync()
|
||||
{
|
||||
if (_driver is not ISubscribable subscribable || _subscriptionHandle is null)
|
||||
@@ -1557,6 +1644,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// instead.</para></summary>
|
||||
private void DetachSubscription()
|
||||
{
|
||||
CancelSourceBindingRetry();
|
||||
DetachDataSubscription();
|
||||
DetachAlarmSource();
|
||||
}
|
||||
@@ -1895,12 +1983,44 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// 3-state Good/Uncertain/Bad enum here, which the node manager then re-expanded to a bare
|
||||
/// <c>0x80000000</c> — so no driver's sub-code ever reached a client, and the status constants each
|
||||
/// driver maintains were diagnostic in logs only.</para></summary>
|
||||
private void PublishSource(string reference, DataValueSnapshot? snapshot)
|
||||
{
|
||||
if (_sourcePublisher is null) return;
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceTicket ticket = default;
|
||||
var found = false;
|
||||
try
|
||||
{
|
||||
found = _sourceIncarnation is { } incarnation
|
||||
? _sourcePublisher.TryCaptureDriver(_driverInstanceId, reference, incarnation, out ticket)
|
||||
: _sourcePublisher.TryCaptureDriver(_driverInstanceId, reference, out ticket);
|
||||
if (!found && snapshot is not null && _sourceIncarnation is { } current &&
|
||||
_sourcePublisher.EnsureDriverBinding(_clusterId, _driverInstanceId, reference, current))
|
||||
found = _sourcePublisher.TryCaptureDriver(_driverInstanceId, reference, current, out ticket);
|
||||
if (!found) return;
|
||||
if (snapshot is null) _sourcePublisher.Invalidate(ticket, "malformed driver callback");
|
||||
else _sourcePublisher.TryPublish(ticket, snapshot);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
if (found) _sourcePublisher.Invalidate(ticket, "source callback failed");
|
||||
_log.Warning(ex, "DriverInstance {Id}: source callback unavailable; legacy publication continues", _driverInstanceId);
|
||||
}
|
||||
}
|
||||
|
||||
// A malformed snapshot still crosses the mailbox in an incarnation-tagged envelope. The actor's
|
||||
// existing supervision path handles it; the producer's callback thread must never throw for it.
|
||||
private static DataValueSnapshot CopyLegacySnapshot(DataValueSnapshot? snapshot) => snapshot is null
|
||||
? null!
|
||||
: snapshot with { Value = ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.OwnedDataSample.CopyLegacy(snapshot.Value) };
|
||||
|
||||
private void OnDataChangeForward(DataChangeForward msg)
|
||||
{
|
||||
var ts = msg.Snapshot.SourceTimestampUtc ?? msg.Snapshot.ServerTimestampUtc;
|
||||
if (msg.ProducerIncarnation != _sourceIncarnation) return;
|
||||
var ts = msg.Snapshot.SourceTimestampUtc ?? msg.Snapshot.ServerTimestampUtc ?? DateTime.MinValue;
|
||||
Context.Parent.Tell(new AttributeValueBatchPublished(
|
||||
_driverInstanceId,
|
||||
new[] { new AttributeValueItem(msg.FullReference, msg.Snapshot.Value, msg.Snapshot.StatusCode, ts) }));
|
||||
new[] { new AttributeValueItem(msg.FullReference, msg.Snapshot.Value, msg.Snapshot.StatusCode, ts,
|
||||
msg.Snapshot.SourceTimestampUtc, msg.Snapshot.ServerTimestampUtc) }));
|
||||
}
|
||||
|
||||
/// <summary>Forward one batch-capable driver production burst to the parent as a single message.
|
||||
@@ -1909,12 +2029,14 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// driver's snapshot, never from this actor's clock).</para></summary>
|
||||
private void OnDataChangeBatchForward(DataChangeBatchForward msg)
|
||||
{
|
||||
if (msg.ProducerIncarnation != _sourceIncarnation) return;
|
||||
var items = new AttributeValueItem[msg.Items.Count];
|
||||
for (var i = 0; i < msg.Items.Count; i++)
|
||||
{
|
||||
var item = msg.Items[i];
|
||||
var ts = item.Snapshot.SourceTimestampUtc ?? item.Snapshot.ServerTimestampUtc;
|
||||
items[i] = new AttributeValueItem(item.FullReference, item.Snapshot.Value, item.Snapshot.StatusCode, ts);
|
||||
var ts = item.Snapshot.SourceTimestampUtc ?? item.Snapshot.ServerTimestampUtc ?? DateTime.MinValue;
|
||||
items[i] = new AttributeValueItem(item.FullReference, item.Snapshot.Value, item.Snapshot.StatusCode, ts,
|
||||
item.Snapshot.SourceTimestampUtc, item.Snapshot.ServerTimestampUtc);
|
||||
}
|
||||
Context.Parent.Tell(new AttributeValueBatchPublished(_driverInstanceId, items));
|
||||
}
|
||||
@@ -2040,6 +2162,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// <inheritdoc />
|
||||
protected override void PostStop()
|
||||
{
|
||||
if (_sourceIncarnation is { } incarnation) _sourcePublisher?.RetireDriver(_driverInstanceId, incarnation);
|
||||
// Archreview 03/S15 — announce comms loss on the way out. Every OTHER route into Reconnecting
|
||||
// (watchdog trip, failed initial connect, Force Reconnect) announces it from the Reconnecting
|
||||
// entry; stopping did not, so an operator's Restart and a supervision respawn tore this child down
|
||||
@@ -2052,7 +2175,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
// overwriting it would claim an outage that never happened.
|
||||
if (_connectedSinceUtc != default)
|
||||
{
|
||||
Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: false));
|
||||
Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: false, ProducerIncarnation: _sourceIncarnation));
|
||||
}
|
||||
|
||||
DetachSubscription();
|
||||
|
||||
Reference in New Issue
Block a user