feat: add immutable partitioned data publication hub

This commit is contained in:
Joseph Doherty
2026-11-16 01:13:10 -05:00
parent b2249ce2cb
commit 8f28a0eabf
47 changed files with 6184 additions and 173 deletions
@@ -9815,7 +9815,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
SdkValueBoundary.FromClr(snapshot.Value),
new StatusCode(snapshot.StatusCode),
snapshot.SourceTimestampUtc ?? DateTime.MinValue,
snapshot.ServerTimestampUtc);
snapshot.ServerTimestampUtc ?? DateTime.MinValue);
/// <inheritdoc />
public override void CreateAddressSpace(IDictionary<NodeId, IList<IReference>> externalReferences)
@@ -195,7 +195,7 @@ public sealed class DataPlaneAuthorizer
/// own path — the owner's Browse TRANSIT (an ancestor of a Tag grant) is not inherited, so a principal holding
/// only a Tag grant cannot enumerate the equipment's alarms and virtual tags by browsing.
/// </summary>
internal const string OwnedNodeSegment = "\u0000owned";
internal const string OwnedNodeSegment = DataScopeSubjects.OwnedNodeSegment;
/// <summary>
/// The single segment, directly under the UNS realm, that an identifier no live node holds is placed at
@@ -18,6 +18,27 @@ public sealed class CatalogActivation
return new CapturedAuthority(this, current);
}
/// <summary>Create an initially inactive token for a staged, not-yet-published catalog.</summary>
internal IDataMappedCatalogAuthority CaptureStagedAuthority(long catalogEpoch, long authorityEpoch)
{
if (catalogEpoch <= 0 || authorityEpoch <= 0) throw new ArgumentOutOfRangeException(nameof(catalogEpoch));
return new StagedAuthority(this, catalogEpoch, authorityEpoch);
}
private sealed class StagedAuthority(CatalogActivation owner, long catalogEpoch, long authorityEpoch) : IDataMappedCatalogAuthority
{
public long CatalogEpoch => catalogEpoch;
public long AuthorityEpoch => authorityEpoch;
public bool IsActive
{
get
{
var current = owner.Current;
return current.IsReady && current.CatalogEpoch == catalogEpoch && current.AuthorityEpoch == authorityEpoch;
}
}
}
private sealed class CapturedAuthority(CatalogActivation owner, CatalogActivationState captured) : IDataMappedCatalogAuthority
{
public long CatalogEpoch => captured.CatalogEpoch;
@@ -0,0 +1,34 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Live process provenance and implemented capability limits, independent of any mount.</summary>
public sealed class DataCapabilitiesProvider
{
private readonly Func<ServingIdentity> _serving;
private readonly Func<bool> _ready;
public DataCapabilitiesProvider(string clusterId, Func<ServingIdentity> serving, Func<bool> ready, DataLimits limits)
{
ArgumentException.ThrowIfNullOrWhiteSpace(clusterId);
ClusterId = clusterId;
_serving = serving ?? throw new ArgumentNullException(nameof(serving));
_ready = ready ?? throw new ArgumentNullException(nameof(ready));
Limits = limits ?? throw new ArgumentNullException(nameof(limits));
limits.Validate();
}
public string ClusterId { get; }
public DataLimits Limits { get; }
public ServingIdentity Serving => _serving();
public bool IsReady => _ready();
internal DataCapabilities Get(DataOperations operations, DataLimits limits)
{
var serving = Serving;
var ready = IsReady;
serving.Validate(requireEpochs: ready);
if (!string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)) operations &= ~DataOperations.Write;
return new(1, 0, serving, ready ? DataReadiness.Ready : DataReadiness.Unavailable,
ready ? operations : DataOperations.None,
Enum.GetValues<DataValueKind>().Where(x => x != DataValueKind.Unspecified).ToHashSet(),
limits, true, 1, ClusterId);
}
}
@@ -0,0 +1,51 @@
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Node-wide admission limits for the source cache and retained work.</summary>
public sealed class DataResourceLimits
{
public int PartitionCount { get; init; } = 4;
public long MaxRetainedBytes { get; init; } = 64 * 1024 * 1024;
public int MaxTrackedSources { get; init; } = 100_000;
public int MaxIngressItemsPerPartition { get; init; } = 1024;
public int MaxDirtySourcesPerPartition { get; init; } = 1024;
public int MaxControlItemsPerPartition { get; init; } = 256;
public int MaxSnapshotItems { get; init; } = 10_000;
public long MaxSnapshotBytes { get; init; } = 16 * 1024 * 1024;
public int MaxSnapshotCatchUpItems { get; init; } = 1024;
public TimeSpan MaxSnapshotLifetime { get; init; } = TimeSpan.FromSeconds(30);
internal void Validate()
{
if (PartitionCount <= 0 || MaxRetainedBytes <= 0 || MaxTrackedSources <= 0 ||
MaxIngressItemsPerPartition <= 0 || MaxDirtySourcesPerPartition <= 0 ||
MaxControlItemsPerPartition <= 0 || MaxSnapshotItems <= 0 || MaxSnapshotBytes <= 0 ||
MaxSnapshotCatchUpItems <= 0 || MaxSnapshotLifetime <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(DataResourceLimits));
}
}
/// <summary>Atomic accounting shared by partitions, reservations, snapshots and readers.</summary>
public sealed class DataResourceBudget
{
private long _retainedBytes;
internal DataResourceBudget(long maximum) => MaximumBytes = maximum;
public long MaximumBytes { get; }
public long RetainedBytes => Interlocked.Read(ref _retainedBytes);
internal bool TryReserve(long bytes)
{
if (bytes <= 0 || bytes > MaximumBytes) return false;
while (true)
{
var current = Interlocked.Read(ref _retainedBytes);
if (current > MaximumBytes - bytes) return false;
if (Interlocked.CompareExchange(ref _retainedBytes, current + bytes, current) == current) return true;
}
}
internal void Release(long bytes)
{
if (bytes > 0 && Interlocked.Add(ref _retainedBytes, -bytes) < 0)
throw new InvalidOperationException("Resource charge released more than once.");
}
}
@@ -0,0 +1,146 @@
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Identifies one deployment attempt, including retries of the same artifact.</summary>
public sealed record CatalogAttempt(long Epoch, string Revision)
{
private int _expected;
internal bool Expected => Volatile.Read(ref _expected) != 0;
internal void SetExpected(bool expected) => Volatile.Write(ref _expected, expected ? 1 : 0);
}
/// <summary>Coordinates desired authority, private catalog staging and served topology activation.</summary>
public sealed class LocalCatalogCoordinator
{
private readonly object _gate = new();
private readonly CatalogActivation _activation;
private readonly DataPlaneAuthorityState _authority;
private readonly Func<ServingIdentity> _serving;
private CatalogAttempt? _attempt;
private LocalExportCatalog? _staged;
private LocalExportCatalog? _published;
private bool _terminal;
private bool _catalogValid;
// A test can hold the host's existing subscription boundary to observe ordering.
internal Action? BeforeSubscriptionApplyForTests { get; set; }
public LocalCatalogCoordinator(CatalogActivation activation, DataPlaneAuthorityState authority, Func<ServingIdentity> serving)
{
_activation = activation ?? throw new ArgumentNullException(nameof(activation));
_authority = authority ?? throw new ArgumentNullException(nameof(authority));
_serving = serving ?? throw new ArgumentNullException(nameof(serving));
}
/// <summary>Only a matching, activated candidate may be observed by data facades.</summary>
public LocalExportCatalog? Current
{
get
{
// A producer never waits for the control path or spins indefinitely under role churn.
for (var retry = 0; retry < 3; retry++)
{
var catalog = Volatile.Read(ref _published);
if (catalog is null || !catalog.IsActive) return null;
var current = _serving();
if (current.NodeId != catalog.Serving.NodeId || current.Incarnation != catalog.Serving.Incarnation) return null;
if (current.Role == catalog.Serving.Role)
{
var verified = _serving();
if (verified.NodeId != catalog.Serving.NodeId || verified.Incarnation != catalog.Serving.Incarnation) return null;
if (verified.Role != catalog.Serving.Role || !ReferenceEquals(Volatile.Read(ref _published), catalog)) continue;
return catalog.IsActive ? catalog : null;
}
var adjusted = catalog.WithServingRole(catalog.Serving with { Role = current.Role });
if (ReferenceEquals(Interlocked.CompareExchange(ref _published, adjusted, catalog), catalog))
continue;
}
return null;
}
}
/// <summary>Live process provenance for producers; epochs remain zero while no catalog is served.</summary>
public ServingIdentity Serving
{
get
{
var current = Current;
return current?.Serving ?? _serving() with { CatalogEpoch = 0, AuthorityEpoch = 0 };
}
}
public CatalogAttempt BeginAttempt(string revision)
{
lock (_gate)
{
var attempt = new CatalogAttempt(_activation.Begin(revision), revision);
_attempt = attempt;
_staged = null;
_terminal = false;
_catalogValid = false;
Volatile.Write(ref _published, null);
return attempt;
}
}
/// <summary>Install independently readable credentials even when catalog topology is invalid.</summary>
public bool InstallAuthority(CatalogAttempt attempt, DataPlaneAuthorityProjection projection)
{
ArgumentNullException.ThrowIfNull(attempt);
ArgumentNullException.ThrowIfNull(projection);
lock (_gate)
{
if (_terminal || !ReferenceEquals(_attempt, attempt)) return false;
var installed = _authority.Apply(projection.ClusterId, attempt.Revision, projection.Keys, projection.Grants,
projection.ScopePaths, projection.EquipmentScopePaths, projection.ScriptedAlarmOwners,
projection.UnsFolderScopes, projection.TagReferencingEquipment);
_catalogValid = projection.CatalogValid && !string.IsNullOrWhiteSpace(installed.ClusterId);
return _activation.AuthorityInstalled(attempt.Epoch, installed.GenerationId);
}
}
public bool Stage(CatalogAttempt attempt, DraftSnapshot snapshot, string? expectedNodeId = null)
{
ArgumentNullException.ThrowIfNull(attempt);
ArgumentNullException.ThrowIfNull(snapshot);
lock (_gate)
{
var state = _activation.Current;
if (_terminal || !ReferenceEquals(_attempt, attempt) || !_catalogValid || state.AuthorityEpoch <= 0
|| _authority.Current.GenerationId != state.AuthorityEpoch) return false;
var serving = _serving() with { CatalogEpoch = attempt.Epoch, AuthorityEpoch = state.AuthorityEpoch };
if ((expectedNodeId is not null && serving.NodeId != expectedNodeId)
|| !string.Equals(snapshot.ClusterId, _authority.Current.ClusterId, StringComparison.OrdinalIgnoreCase)
|| !snapshot.ClusterNodes.Any(node => node.NodeId == serving.NodeId
&& string.Equals(node.ClusterId, snapshot.ClusterId, StringComparison.OrdinalIgnoreCase)
&& node.Enabled && !node.MaintenanceMode)) return false;
var token = _activation.CaptureStagedAuthority(attempt.Epoch, state.AuthorityEpoch);
_staged = LocalExportCatalog.Compile(snapshot, serving, token);
return true;
}
}
public bool Complete(CatalogAttempt attempt, bool topologySucceeded)
{
ArgumentNullException.ThrowIfNull(attempt);
lock (_gate)
{
if (_terminal || !ReferenceEquals(_attempt, attempt)) return false;
_terminal = true;
var state = _activation.Current;
var valid = topologySucceeded && _staged is not null && _catalogValid
&& state.AuthorityEpoch == _authority.Current.GenerationId;
if (valid) Volatile.Write(ref _published, _staged);
if (!_activation.Complete(attempt.Epoch, valid))
{
Volatile.Write(ref _published, null);
return false;
}
return true;
}
}
}
@@ -0,0 +1,30 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Strictly caller-bound local data facade; it creates no namespace projection.</summary>
public sealed class LocalDataConnection : IDataConnection, IDataConnectionPublicationGate
{
private readonly LocalDataServices _services;
private readonly DataAuthenticatedContext _context;
private int _disposed;
internal LocalDataConnection(LocalDataServices services, DataAuthenticatedContext context, DataTarget target)
{ _services = services; _context = context; Target = target; }
public DataTarget Target { get; }
public TimeProvider Clock => _services.Clock;
public bool CanPublish(ServingIdentity expectedServing) => Volatile.Read(ref _disposed) == 0 && _services.CanPublish(_context, expectedServing);
private void Check() => ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken)
{ Check(); return _services.GetCapabilitiesAsync(_context, budget, cancellationToken); }
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken)
{ Check(); return _services.BrowseAsync(_context, request, cancellationToken); }
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
{ Check(); return _services.GetMetadataAsync(_context, request, cancellationToken); }
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken)
{ Check(); return _services.ReadAsync(_context, request, cancellationToken); }
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken)
{ Check(); return _services.WriteAsync(_context, request, cancellationToken); }
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
{ Check(); return _services.SubscribeAsync(_context, cancellationToken); }
public ValueTask DisposeAsync() { Interlocked.Exchange(ref _disposed, 1); return ValueTask.CompletedTask; }
}
@@ -0,0 +1,344 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Runtime.CompilerServices;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Origin-local cached data ports; every facade retains its authenticated caller.</summary>
public sealed class LocalDataServices : IDataConnectionFactory
{
private readonly Func<LocalExportCatalog?> _catalog;
private readonly PartitionedSampleHub _hub;
private readonly DataOperationPolicy _policy;
private readonly DataCapabilitiesProvider _capabilities;
private readonly Func<DataAuthenticatedContext, IDataWriteService>? _writes;
private readonly Func<DataAuthenticatedContext, IDataSubscriptionService>? _subscriptions;
private readonly byte[] _continuationKey = RandomNumberGenerator.GetBytes(32);
private readonly ConditionalWeakTable<DataAuthenticatedContext, DataCallerIdentity> _callers = new();
private sealed record Continuation(DataView Parent, string? Filter, int Offset, string Principal,
string KeyId, string CredentialVersion, ServingIdentity Serving, long Started, long DurationTicks);
public LocalDataServices(Func<LocalExportCatalog?> catalog, PartitionedSampleHub hub,
DataOperationPolicy policy, DataCapabilitiesProvider capabilities, TimeProvider clock,
Func<DataAuthenticatedContext, IDataWriteService>? writes = null,
Func<DataAuthenticatedContext, IDataSubscriptionService>? subscriptions = null)
{
_catalog = catalog ?? throw new ArgumentNullException(nameof(catalog));
_hub = hub ?? throw new ArgumentNullException(nameof(hub));
_policy = policy ?? throw new ArgumentNullException(nameof(policy));
_capabilities = capabilities ?? throw new ArgumentNullException(nameof(capabilities));
Clock = clock ?? throw new ArgumentNullException(nameof(clock));
if (!ReferenceEquals(hub.Clock, clock)) throw new ArgumentException("Hub and facade must use one clock.", nameof(clock));
_writes = writes;
_subscriptions = subscriptions;
}
public TimeProvider Clock { get; }
private DataOperations Implemented => DataOperations.Browse | DataOperations.Metadata | DataOperations.Read
| (_writes is null ? DataOperations.None : DataOperations.Write)
| (_subscriptions is null ? DataOperations.None : DataOperations.Subscribe);
private DataCallerIdentity Caller(DataAuthenticatedContext context) => _callers.GetValue(context, static value =>
new(value.PrincipalId, value.ApiKeyId, value.CredentialVersion, value.CredentialExpiresUtc));
internal bool CanPublish(DataAuthenticatedContext context, ServingIdentity expectedServing)
{
var catalog = _catalog();
return catalog is not null && Ready(catalog) && catalog.Serving == expectedServing
&& _policy.IsCallerUsable(Caller(context));
}
private sealed class PublicationReadLease(CachedSourceRead read, Func<bool> gate) : IDataPublicationLease
{
private int _disposed;
public bool IsValid => Volatile.Read(ref _disposed) == 0 && read.IsValid && gate();
public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) read.Dispose(); }
}
public IDataConnection Create(DataAuthenticatedContext context, DataTarget target)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(target);
context.Validate(); target.Validate();
var serving = _capabilities.Serving;
if (!string.Equals(target.ExpectedClusterId, _capabilities.ClusterId, StringComparison.OrdinalIgnoreCase)
|| (target.Mode == DataTargetMode.Node && !string.Equals(target.ExpectedNodeId, serving.NodeId, StringComparison.OrdinalIgnoreCase)))
throw new ArgumentException("Target does not identify this data service.", nameof(target));
if (!_policy.IsCallerUsable(Caller(context))) throw new UnauthorizedAccessException("Authenticated caller is no longer usable.");
return new LocalDataConnection(this, context, target);
}
private bool Ready(LocalExportCatalog catalog) => catalog.IsActive && _capabilities.IsReady
&& catalog.Serving == _capabilities.Serving && catalog.AuthorityEpoch == _policy.AuthorityEpoch;
private bool Allowed(LocalExportCatalog catalog, DataAuthenticatedContext context, LocalDataNode node, DataOperations operation)
{
if (!Ready(catalog) || !_policy.IsCallerUsable(Caller(context))
|| (node.Metadata.AllowedOperations & operation) != operation
|| !catalog.AllowsExport(context.PrincipalId, node, operation)) return false;
var required = operation switch
{
DataOperations.Browse => OpcUaOperation.Browse,
DataOperations.Read => OpcUaOperation.Read,
DataOperations.Write => OpcUaOperation.WriteOperate,
DataOperations.Subscribe => OpcUaOperation.CreateMonitoredItems,
DataOperations.Metadata => OpcUaOperation.Browse,
_ => throw new ArgumentOutOfRangeException(nameof(operation))
};
var allowed = _policy.AuthorizeLocal(Caller(context), required, node.Scope);
if (!allowed && operation == DataOperations.Metadata)
allowed = _policy.AuthorizeLocal(Caller(context), OpcUaOperation.Read, node.Scope);
return allowed && Ready(catalog);
}
private DataLimits Limits(LocalExportCatalog catalog, DataAuthenticatedContext context) =>
catalog.LimitsFor(context.PrincipalId, _capabilities.Limits);
private void CheckBudget(DataBudget budget, int count, int limit, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(budget);
cancellationToken.ThrowIfCancellationRequested(); budget.Validate();
if (count < 0 || count > Math.Min(budget.MaxItems, limit) || count > budget.MaxBytes / 256)
throw new ArgumentOutOfRangeException(nameof(count), "Request exceeds the admitted item/byte budget.");
}
private bool Expired(long start, DataBudget budget) => Clock.GetElapsedTime(start) >= budget.Timeout;
private DataMetadata Metadata(LocalExportCatalog catalog, DataAuthenticatedContext context, LocalDataNode node)
{
var operations = DataOperations.None;
foreach (var operation in new[] { DataOperations.Browse, DataOperations.Metadata, DataOperations.Read, DataOperations.Write, DataOperations.Subscribe })
if ((node.Supported || operation == DataOperations.Browse)
&& (node.SourceEnabled || operation is DataOperations.Browse or DataOperations.Metadata)
&& (Implemented & operation) != 0 && (node.Metadata.AllowedOperations & operation) != 0
&& (operation != DataOperations.Write || node.Metadata.Writable
&& string.Equals(_capabilities.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase))
&& Allowed(catalog, context, node, operation)) operations |= operation;
return node.Metadata with { AllowedOperations = operations, Writable = node.Metadata.Writable && operations.HasFlag(DataOperations.Write) };
}
internal Task<DataCapabilities> GetCapabilitiesAsync(DataAuthenticatedContext context, DataBudget budget, CancellationToken cancellationToken)
{
CheckBudget(budget, 0, 0, cancellationToken);
var catalog = _catalog();
if (!_policy.IsCallerUsable(Caller(context))) throw new UnauthorizedAccessException();
var capabilities = _capabilities.Get(catalog is null ? DataOperations.None : catalog.ExportOperations(context.PrincipalId) & Implemented,
catalog is null ? _capabilities.Limits : Limits(catalog, context));
if (catalog is null || !Ready(catalog)) capabilities = capabilities with { Readiness = DataReadiness.Unavailable, Operations = DataOperations.None };
return Task.FromResult(capabilities);
}
internal Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(DataAuthenticatedContext context, MetadataRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Views);
var catalog = _catalog();
CheckBudget(request.Budget, request.Views.Count, catalog is null ? _capabilities.Limits.MaxBatchItems : Limits(catalog, context).MaxBatchItems, cancellationToken);
if (catalog is null) return Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(request.Views.Select((_, i) =>
new DataItemResult<DataMetadata>(i.ToString(System.Globalization.CultureInfo.InvariantCulture), DataItemStatus.Unavailable, null, null)).ToArray());
var start = Clock.GetTimestamp();
var results = new List<DataItemResult<DataMetadata>>(request.Views.Count);
long bytes = 0;
for (var i = 0; i < request.Views.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
var view = request.Views[i]; view.Validate();
var status = !Ready(catalog) || Expired(start, request.Budget) ? DataItemStatus.Unavailable
: !_policy.IsCallerUsable(Caller(context)) ? DataItemStatus.Denied
: !catalog.TryResolveAddress(view, out _) ? catalog.ContainsAddress(view) ? DataItemStatus.Denied : DataItemStatus.NotFound
: DataItemStatus.Good;
DataMetadata? metadata = null;
if (status == DataItemStatus.Good && catalog.TryResolveAddress(view, out var node))
{
if (!Allowed(catalog, context, node, DataOperations.Metadata)) status = DataItemStatus.Denied;
else if (!node.Supported) status = DataItemStatus.Unsupported;
else
{
metadata = Metadata(catalog, context, node);
bytes = checked(bytes + MetadataBytes(metadata));
if (bytes > Math.Min(request.Budget.MaxBytes, _capabilities.Limits.MaxMessageBytes))
{ status = DataItemStatus.LimitExceeded; metadata = null; }
}
}
results.Add(new(i.ToString(System.Globalization.CultureInfo.InvariantCulture), status, metadata, null));
}
if (!Ready(catalog) || !_policy.IsCallerUsable(Caller(context)))
return Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(results.Select(x => x with
{ Status = !Ready(catalog) ? DataItemStatus.Unavailable : DataItemStatus.Denied, Value = null }).ToArray());
return Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(results);
}
internal Task<IReadOnlyList<ReadResult>> ReadAsync(DataAuthenticatedContext context, ReadRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Items);
var catalog = _catalog();
CheckBudget(request.Budget, request.Items.Count, catalog is null ? _capabilities.Limits.MaxBatchItems : Limits(catalog, context).MaxBatchItems, cancellationToken);
if (catalog is null) return Task.FromResult<IReadOnlyList<ReadResult>>(request.Items.Select(item =>
new ReadResult(item.CorrelationId, DataItemStatus.Unavailable, DataReadiness.Unavailable, null, null, null)).ToArray());
var start = Clock.GetTimestamp();
var results = new List<ReadResult>(request.Items.Count);
long bytes = 0;
try
{
foreach (var item in request.Items)
{
cancellationToken.ThrowIfCancellationRequested(); item.View.Validate();
if (item.MaximumAge is { } maximumAge && maximumAge < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(item.MaximumAge));
ReadResult Empty(DataItemStatus status, DataReadiness readiness = DataReadiness.Unavailable) =>
new(item.CorrelationId, status, readiness, null, null, null);
if (!Ready(catalog) || Expired(start, request.Budget)) { results.Add(Empty(DataItemStatus.Unavailable)); continue; }
if (!_policy.IsCallerUsable(Caller(context))) { results.Add(Empty(DataItemStatus.Denied)); continue; }
if (!catalog.TryResolve(item.View, out var node))
{ results.Add(Empty(catalog.ContainsAddress(item.View) ? DataItemStatus.Denied : DataItemStatus.NotFound)); continue; }
if (!Allowed(catalog, context, node, DataOperations.Read)) { results.Add(Empty(DataItemStatus.Denied)); continue; }
if (!node.Supported) { results.Add(Empty(DataItemStatus.Unsupported)); continue; }
if (!node.SourceEnabled) { results.Add(Empty(DataItemStatus.Unavailable)); continue; }
if (node.Source is not { } key) { results.Add(Empty(DataItemStatus.Unsupported)); continue; }
if (!_hub.TryGetCurrentTicket(key, out var ticket))
{ results.Add(Empty(DataItemStatus.WaitingForInitialData, DataReadiness.WaitingForInitialData)); continue; }
var read = _hub.Read(ticket);
if (read.Sample is not { } sample || read.Readiness != DataReadiness.Ready)
{ results.Add(new(item.CorrelationId, read.Status, read.Readiness, null, null, null)); read.Dispose(); continue; }
if (sample.Serving.NodeId != key.ServingNodeId || sample.Serving.Incarnation != key.ServingIncarnation
|| !_hub.TryGetCurrentTicket(key, out var current) || current != ticket)
{ read.Dispose(); results.Add(Empty(DataItemStatus.Unavailable)); continue; }
if (!ValueMatches(node.Metadata, sample.Value))
{ read.Dispose(); results.Add(Empty(DataItemStatus.TypeMismatch)); continue; }
bytes = checked(bytes + sample.Value.EstimatedRetainedBytes + 256);
if (bytes > Math.Min(request.Budget.MaxBytes, _capabilities.Limits.MaxMessageBytes))
{ read.Dispose(); results.Add(Empty(DataItemStatus.LimitExceeded)); continue; }
var age = Clock.GetElapsedTime(read.ReceivedTimestamp);
if (age < TimeSpan.Zero) { read.Dispose(); results.Add(Empty(DataItemStatus.Unavailable)); continue; }
// Catalog/authority headers describe current serving. Acquisition age, value version
// and original timestamps remain unchanged, including provisional boot acquisitions.
var exposed = sample with { Value = sample.Value.Retain(), Serving = catalog.Serving };
exposed.Validate();
if (!Allowed(catalog, context, node, DataOperations.Read)
|| !_hub.TryGetCurrentTicket(key, out current) || current != ticket)
{ exposed.Dispose(); read.Dispose(); results.Add(Empty(DataItemStatus.Denied)); continue; }
var publication = new PublicationReadLease(read, () => CanPublish(context, exposed.Serving)
&& !Expired(start, request.Budget));
results.Add(new(item.CorrelationId, item.MaximumAge is { } max && age > max ? DataItemStatus.Stale : DataItemStatus.Good,
DataReadiness.Ready, age, exposed, null, publication));
}
if (!Ready(catalog) || !_policy.IsCallerUsable(Caller(context)))
for (var i = 0; i < results.Count; i++)
{ var result = results[i]; result.Dispose(); results[i] = new(result.CorrelationId,
Ready(catalog) ? DataItemStatus.Denied : DataItemStatus.Unavailable, DataReadiness.Unavailable, null, null, null); }
return Task.FromResult<IReadOnlyList<ReadResult>>(results);
}
catch { foreach (var result in results) result.Dispose(); throw; }
}
internal Task<DataBrowseBranch> BrowseAsync(DataAuthenticatedContext context, BrowseRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request); request.Parent.Validate();
var catalog = _catalog();
var limits = catalog is null ? _capabilities.Limits : Limits(catalog, context);
CheckBudget(request.Budget, 0, limits.MaxPageItems, cancellationToken);
DataBrowseBranch Empty(DataItemStatus status) => new(request.Parent, status, [], true, null, null);
if (catalog is null || !Ready(catalog)) return Task.FromResult(Empty(DataItemStatus.Unavailable));
if (!catalog.TryResolve(request.Parent, out var parent) || !Allowed(catalog, context, parent, DataOperations.Browse))
return Task.FromResult(Empty(DataItemStatus.Denied));
var start = Clock.GetTimestamp();
var offset = 0;
if (request.Continuation is not null)
{
var continuation = DecodeContinuation(request.Continuation);
if (continuation is null || continuation.Parent != request.Parent || continuation.Filter != request.Filter
|| continuation.Principal != context.PrincipalId || continuation.KeyId != context.ApiKeyId
|| continuation.CredentialVersion != context.CredentialVersion || continuation.Serving != catalog.Serving
|| Clock.GetElapsedTime(continuation.Started).Ticks >= continuation.DurationTicks)
return Task.FromResult(Empty(DataItemStatus.InvalidContinuation));
offset = continuation.Offset;
}
var children = catalog.Children(parent);
if (offset < 0 || offset > children.Count) return Task.FromResult(Empty(DataItemStatus.InvalidContinuation));
var page = new List<DataMetadata>();
long bytes = 256;
var maximum = Math.Min(request.Budget.MaxItems, limits.MaxPageItems);
var scanned = 0;
while (offset < children.Count && page.Count < maximum && scanned++ < maximum)
{
cancellationToken.ThrowIfCancellationRequested();
if (Expired(start, request.Budget)) return Task.FromResult(Empty(DataItemStatus.Unavailable));
var child = children[offset++];
if ((request.Filter is { Length: > 0 } filter && !child.Metadata.BrowseName.Contains(filter, StringComparison.Ordinal))
|| !Allowed(catalog, context, child, DataOperations.Browse)) continue;
var metadata = Metadata(catalog, context, child);
var size = MetadataBytes(metadata);
if (bytes + size > Math.Min(request.Budget.MaxBytes, limits.MaxMessageBytes))
{
offset--;
if (page.Count == 0) return Task.FromResult(Empty(DataItemStatus.LimitExceeded));
break;
}
bytes += size; page.Add(metadata);
}
if (!Allowed(catalog, context, parent, DataOperations.Browse)) return Task.FromResult(Empty(DataItemStatus.Denied));
var complete = offset == children.Count;
var token = complete ? null : EncodeContinuation(new(request.Parent, request.Filter, offset, context.PrincipalId,
context.ApiKeyId, context.CredentialVersion, catalog.Serving, start, limits.MaxMetadataLease.Ticks));
return Task.FromResult(new DataBrowseBranch(request.Parent, DataItemStatus.Good, page, complete, token,
new MetadataLease(catalog.Serving.CatalogEpoch, catalog.Serving.AuthorityEpoch, limits.MaxMetadataLease)));
}
internal async Task<IReadOnlyList<WriteItemResult>> WriteAsync(DataAuthenticatedContext context, WriteBatch request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Items);
var catalog = _catalog(); CheckBudget(request.Budget, request.Items.Count,
catalog is null ? _capabilities.Limits.MaxBatchItems : Limits(catalog, context).MaxBatchItems, cancellationToken);
var results = new WriteItemResult[request.Items.Count];
var allowed = new List<WriteItem>(); var indexes = new List<int>();
for (var i = 0; i < request.Items.Count; i++)
{
var item = request.Items[i];
if (_writes is not null && catalog is not null && Ready(catalog)
&& string.Equals(_capabilities.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)
&& catalog.TryResolve(item.View, out var node)
&& node.SourceEnabled && node.Supported && node.Metadata.Writable && Allowed(catalog, context, node, DataOperations.Write))
{ allowed.Add(item); indexes.Add(i); }
else results[i] = new(item.CorrelationId, new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Write unavailable or denied before dispatch."));
}
if (allowed.Count > 0)
{
var outcomes = await _writes!(context).WriteAsync(new(allowed, request.Budget), cancellationToken).ConfigureAwait(false);
if (outcomes.Count != allowed.Count) throw new InvalidOperationException("Write delegate returned an invalid result count.");
for (var i = 0; i < outcomes.Count; i++) results[indexes[i]] = outcomes[i];
}
return results;
}
internal Task<IDataSubscription> SubscribeAsync(DataAuthenticatedContext context, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var catalog = _catalog();
if (_subscriptions is null || catalog is null || !Ready(catalog) || !_policy.IsCallerUsable(Caller(context)))
throw new InvalidOperationException("Subscriptions are unavailable.");
return _subscriptions(context).SubscribeAsync(cancellationToken);
}
private static bool ValueMatches(DataMetadata metadata, DataValue value) => value.Kind == DataValueKind.Null || metadata.ValueKind == value.Kind
&& (value.Kind != DataValueKind.Array || metadata.ArrayElementKind == value.ArrayElementKind
&& metadata.Dimensions.Count == value.Dimensions!.Count
&& metadata.Dimensions.Zip(value.Dimensions).All(x => x.First == 0 || x.First == x.Second));
private static long MetadataBytes(DataMetadata metadata) => checked(512L + 2L *
(metadata.BrowseName.Length + metadata.NodeKind.Length + metadata.View.Address.Identifier.Length
+ metadata.View.Address.NamespaceUri.Length + metadata.View.Subject.Length + (metadata.EngineeringUnits?.Length ?? 0))
+ 8L * metadata.Dimensions.Count);
private string EncodeContinuation(Continuation value)
{
var payload = JsonSerializer.SerializeToUtf8Bytes(value);
return Convert.ToBase64String(payload) + "." + Convert.ToBase64String(HMACSHA256.HashData(_continuationKey, payload));
}
private Continuation? DecodeContinuation(string token)
{
if (token.Length > 16_384) return null;
var parts = token.Split('.'); if (parts.Length != 2) return null;
try
{
var payload = Convert.FromBase64String(parts[0]); var signature = Convert.FromBase64String(parts[1]);
if (!CryptographicOperations.FixedTimeEquals(HMACSHA256.HashData(_continuationKey, payload), signature)) return null;
return JsonSerializer.Deserialize<Continuation>(payload);
}
catch (Exception ex) when (ex is FormatException or JsonException) { return null; }
}
}
@@ -0,0 +1,185 @@
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
public sealed partial class LocalExportCatalog
{
/// <summary>Stable data-service realm root; its identifier kind cannot collide with an SDK string NodeId.</summary>
public static DataView RealmRoot(string clusterId, DataRealm realm)
{
ArgumentException.ThrowIfNullOrWhiteSpace(clusterId); DataContractValidation.Required(realm);
return new(new(clusterId, realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri,
"realm-root", clusterId), realm, null, 0, realm == DataRealm.Raw ? "raw" : "uns");
}
/// <summary>Compile origin views from the deployed snapshot using the same identity and ACL producers as the SDK.</summary>
public static LocalExportCatalog Compile(DraftSnapshot snapshot, ServingIdentity serving,
IDataMappedCatalogAuthority activation, int maximumNodes = 100_000)
{
ArgumentNullException.ThrowIfNull(snapshot);
serving.Validate(requireEpochs: true);
if (DataConnectionValidator.Validate(snapshot).Count != 0)
throw new InvalidDataException("Origin catalog configuration is invalid.");
var cluster = snapshot.ClusterId;
var ids = StringComparer.OrdinalIgnoreCase;
bool Same(string a, string b) => ids.Equals(a, b);
var folders = snapshot.RawFolders.Where(x => Same(x.ClusterId, cluster)).ToArray();
var drivers = snapshot.DriverInstances.Where(x => Same(x.ClusterId, cluster)).ToArray();
var driverIds = drivers.Select(x => x.DriverInstanceId).ToHashSet(ids);
var devices = snapshot.Devices.Where(x => driverIds.Contains(x.DriverInstanceId)).ToArray();
var deviceIds = devices.Select(x => x.DeviceId).ToHashSet(ids);
var groups = snapshot.TagGroups.Where(x => deviceIds.Contains(x.DeviceId)).ToArray();
var tags = snapshot.Tags.Where(x => deviceIds.Contains(x.DeviceId)).ToArray();
var areas = snapshot.UnsAreas.Where(x => Same(x.ClusterId, cluster)).ToArray();
var areaIds = areas.Select(x => x.UnsAreaId).ToHashSet(ids);
var lines = snapshot.UnsLines.Where(x => areaIds.Contains(x.UnsAreaId)).ToArray();
var lineIds = lines.Select(x => x.UnsLineId).ToHashSet(ids);
var equipment = snapshot.Equipment.Where(x => lineIds.Contains(x.UnsLineId)).ToArray();
var equipmentIds = equipment.Select(x => x.EquipmentId).ToHashSet(ids);
var tagIds = tags.Select(x => x.TagId).ToHashSet(ids);
var references = snapshot.UnsTagReferences.Where(x => equipmentIds.Contains(x.EquipmentId) && tagIds.Contains(x.TagId)).ToArray();
var virtuals = snapshot.VirtualTags.Where(x => equipmentIds.Contains(x.EquipmentId)).ToArray();
var count = 2L + folders.Length + drivers.Length + devices.Length + groups.Length + tags.Length
+ areas.Length + lines.Length + equipment.Length + references.Length + virtuals.Length;
if (maximumNodes <= 0 || count > maximumNodes) throw new ArgumentOutOfRangeException(nameof(maximumNodes), "Origin catalog node budget exceeded.");
var tagById = tags.ToDictionary(x => x.TagId, ids);
var deviceById = devices.ToDictionary(x => x.DeviceId, ids);
var driverById = drivers.ToDictionary(x => x.DriverInstanceId, ids);
var referenceNames = references.Select(x => (x.EquipmentId, x.TagId, EffectiveName: x.DisplayNameOverride ?? tagById[x.TagId].Name)).ToArray();
var scopeResolver = new AclScopePathResolver(
folders.ToDictionary(x => x.RawFolderId, x => (x.ParentRawFolderId, x.Name), ids),
drivers.ToDictionary(x => x.DriverInstanceId, x => (x.RawFolderId, x.Name), ids),
devices.ToDictionary(x => x.DeviceId, x => (x.DriverInstanceId, x.Name), ids),
groups.ToDictionary(x => x.TagGroupId, x => (x.ParentTagGroupId, x.DeviceId, x.Name), ids),
tags.ToDictionary(x => x.TagId, x => (x.DeviceId, x.TagGroupId, x.Name), ids),
areas.ToDictionary(x => x.UnsAreaId, x => x.Name, ids),
lines.ToDictionary(x => x.UnsLineId, x => (x.UnsAreaId, x.Name), ids),
equipment.ToDictionary(x => x.EquipmentId, x => (x.UnsLineId, x.Name), ids), referenceNames);
var composition = AddressSpaceComposer.Compose(areas, lines, equipment, drivers, [], virtuals,
snapshot.Scripts, references, tags, folders, devices, groups);
var nodes = new List<LocalDataNode>((int)count);
var views = new Dictionary<(DataRealm Realm, string Kind, string Id), DataView>();
var rawViewsByPath = new Dictionary<string, DataView>(StringComparer.Ordinal);
const DataOperations navigation = DataOperations.Browse | DataOperations.Metadata;
const DataOperations data = navigation | DataOperations.Read | DataOperations.Subscribe;
NodeScope Scope(NodeAclScopeKind kind, string id, DataRealm realm)
{
var token = realm == DataRealm.Raw ? "raw" : "uns";
var paths = scopeResolver.ResolveOne(kind, id).Where(x => x.Segments.Count > 0 && x.Segments[0] == token).ToArray();
if (paths.Length != 1) throw new InvalidDataException("Origin entity has ambiguous or missing policy ancestry.");
return new() { ClusterId = cluster, Kind = realm == DataRealm.Raw ? NodeHierarchyKind.Raw : NodeHierarchyKind.Uns,
Segments = Array.AsReadOnly(paths[0].Segments.Skip(1).ToArray()) };
}
DataView View(DataRealm realm, string identifier, NodeScope scope) => new(
new(cluster, realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri, "string", identifier),
realm, null, 0, string.Join('/', scope.Segments));
void Add(string kind, string id, string name, DataView view, NodeScope scope, DataView? parent,
BackingSourceKey? source = null, DataValueKind valueKind = DataValueKind.Null, bool writable = false,
bool array = false, uint? length = null, bool supported = true, bool enabled = true)
{
var operations = source is null ? navigation : data | (writable ? DataOperations.Write : DataOperations.None);
var metadata = new DataMetadata(view, name, source is null ? "Folder" : supported ? "Variable" : "UnsupportedVariable",
array && supported ? DataValueKind.Array : valueKind, array && supported ? 1 : -1,
array && supported ? Array.AsReadOnly(new[] { length is { } n ? checked((int)n) : 0 }) : [],
writable, operations, serving.CatalogEpoch, source?.StableSourceId, null, false,
array && supported ? valueKind : null);
nodes.Add(new(kind, id, metadata, scope, parent, source, supported, enabled));
views.Add((view.Realm, kind, id.ToUpperInvariant()), view);
if (view.Realm == DataRealm.Raw && view.Address.IdentifierKind == "string") rawViewsByPath.Add(view.Address.Identifier, view);
}
foreach (var realm in new[] { DataRealm.Raw, DataRealm.Uns })
{
var root = RealmRoot(cluster, realm);
Add("Cluster", cluster, realm.ToString(), root,
new() { ClusterId = cluster, Kind = realm == DataRealm.Raw ? NodeHierarchyKind.Raw : NodeHierarchyKind.Uns, Segments = [] }, null);
}
DataView RawParent(NodeScope scope) => scope.Segments.Count <= 1 ? RealmRoot(cluster, DataRealm.Raw)
: rawViewsByPath.GetValueOrDefault(string.Join('/', scope.Segments.Take(scope.Segments.Count - 1)))
?? throw new InvalidDataException("Origin raw parent is not compiled.");
var rawEntities = new List<(string Kind, string Id, string Name, NodeScope Scope)>();
rawEntities.AddRange(folders.Select(x => ("RawFolder", x.RawFolderId, x.Name, Scope(NodeAclScopeKind.RawFolder, x.RawFolderId, DataRealm.Raw))));
rawEntities.AddRange(drivers.Select(x => ("RawDriver", x.DriverInstanceId, x.Name, Scope(NodeAclScopeKind.RawDriver, x.DriverInstanceId, DataRealm.Raw))));
rawEntities.AddRange(devices.Select(x => ("RawDevice", x.DeviceId, x.Name, Scope(NodeAclScopeKind.RawDevice, x.DeviceId, DataRealm.Raw))));
rawEntities.AddRange(groups.Select(x => ("RawTagGroup", x.TagGroupId, x.Name, Scope(NodeAclScopeKind.RawTagGroup, x.TagGroupId, DataRealm.Raw))));
foreach (var entity in rawEntities.OrderBy(x => x.Scope.Segments.Count).ThenBy(x => x.Id, StringComparer.Ordinal))
{
var path = RawPaths.Build(entity.Scope.Segments);
Add(entity.Kind, entity.Id, entity.Name, View(DataRealm.Raw, path, entity.Scope), entity.Scope, RawParent(entity.Scope));
}
var rawPlans = composition.RawTags.ToDictionary(x => x.NodeId, StringComparer.Ordinal);
var rawSources = new Dictionary<string, (BackingSourceKey Key, bool Enabled)>(StringComparer.Ordinal);
foreach (var plan in composition.RawTags)
{
var scope = Scope(NodeAclScopeKind.Tag, plan.TagId, DataRealm.Raw);
var source = SourceKey.ForDriver(cluster, driverById[plan.DriverInstanceId].DriverInstanceId, plan.NodeId, serving.NodeId, serving.Incarnation);
var enabled = deviceById[tagById[plan.TagId].DeviceId].Enabled && driverById[plan.DriverInstanceId].Enabled;
rawSources.Add(plan.NodeId, (source, enabled));
var kind = ValueKind(plan.DataType);
var supported = kind != DataValueKind.Unspecified && (!plan.IsArray || DataValue.IsSupportedArrayElementKind(kind));
Add("RawTag", plan.TagId, plan.Name, View(DataRealm.Raw, plan.NodeId, scope), scope, RawParent(scope), source,
supported ? kind : DataValueKind.Null, plan.Writable && (!plan.IsArray || plan.ArrayWritable),
plan.IsArray, plan.ArrayLength, supported, enabled);
}
foreach (var area in areas)
{
var scope = Scope(NodeAclScopeKind.UnsArea, area.UnsAreaId, DataRealm.Uns);
Add("UnsArea", area.UnsAreaId, area.Name, View(DataRealm.Uns, area.UnsAreaId, scope), scope, RealmRoot(cluster, DataRealm.Uns));
}
foreach (var line in lines)
{
var scope = Scope(NodeAclScopeKind.UnsLine, line.UnsLineId, DataRealm.Uns);
Add("UnsLine", line.UnsLineId, line.Name, View(DataRealm.Uns, line.UnsLineId, scope), scope, views[(DataRealm.Uns, "UnsArea", line.UnsAreaId.ToUpperInvariant())]);
}
foreach (var item in equipment)
{
var scope = Scope(NodeAclScopeKind.Equipment, item.EquipmentId, DataRealm.Uns);
Add("Equipment", item.EquipmentId, item.Name, View(DataRealm.Uns, item.EquipmentId, scope), scope,
views[(DataRealm.Uns, "UnsLine", item.UnsLineId.ToUpperInvariant())]);
}
foreach (var reference in composition.UnsReferenceVariables)
{
var scope = new NodeScope { ClusterId = cluster, Kind = NodeHierarchyKind.Uns,
Segments = Array.AsReadOnly(reference.NodeId.Split(RawPaths.Separator)) };
var source = rawSources[reference.BackingRawPath];
var plan = rawPlans[reference.BackingRawPath];
var kind = ValueKind(reference.DataType);
var supported = kind != DataValueKind.Unspecified && (!reference.BackingIsArray || DataValue.IsSupportedArrayElementKind(kind));
Add("UnsTagReference", reference.UnsTagReferenceId, reference.EffectiveName, View(DataRealm.Uns, reference.NodeId, scope), scope,
views[(DataRealm.Uns, "Equipment", reference.EquipmentId.ToUpperInvariant())], source.Key, supported ? kind : DataValueKind.Null,
reference.Writable && (!reference.BackingIsArray || reference.BackingArrayWritable),
reference.BackingIsArray, plan.ArrayLength, supported, source.Enabled);
}
foreach (var value in composition.EquipmentVirtualTags)
{
var owner = Scope(NodeAclScopeKind.Equipment, value.EquipmentId, DataRealm.Uns);
var scope = DataScopeSubjects.Owned(owner);
var identifier = string.IsNullOrWhiteSpace(value.FolderPath) ? V3NodeIds.Uns(value.EquipmentId, value.Name)
: V3NodeIds.Uns(new[] { value.EquipmentId }.Concat(value.FolderPath.Split(RawPaths.Separator)).Append(value.Name));
var view = View(DataRealm.Uns, identifier, owner) with { Subject = string.Join('/', owner.Segments.Append(value.Name)) };
var kind = ValueKind(value.DataType);
Add("VirtualTag", value.VirtualTagId, value.Name, view, scope, views[(DataRealm.Uns, "Equipment", value.EquipmentId.ToUpperInvariant())],
SourceKey.ForVirtual(cluster, value.VirtualTagId, serving.NodeId, serving.Incarnation),
kind == DataValueKind.Unspecified ? DataValueKind.Null : kind, supported: kind != DataValueKind.Unspecified, enabled: value.Enabled);
}
return new(cluster, serving, activation, nodes, snapshot.DataExports, maximumNodes);
}
private static DataValueKind ValueKind(string type) => type switch
{
"Boolean" => DataValueKind.Boolean, "SByte" => DataValueKind.Int8, "Byte" => DataValueKind.UInt8,
"Int16" => DataValueKind.Int16, "Int32" => DataValueKind.Int32, "Int64" => DataValueKind.Int64,
"UInt16" => DataValueKind.UInt16, "UInt32" => DataValueKind.UInt32, "UInt64" => DataValueKind.UInt64,
"Float" or "Single" => DataValueKind.Float, "Double" => DataValueKind.Double, "String" => DataValueKind.String,
"ByteString" => DataValueKind.Bytes, "DateTime" => DataValueKind.Timestamp, "Guid" => DataValueKind.Guid,
_ => DataValueKind.Unspecified
};
}
@@ -0,0 +1,177 @@
using System.Collections.ObjectModel;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>An origin-owned view, with policy placement separate from its backing acquisition.</summary>
public sealed record LocalDataNode(string EntityKind, string EntityId, DataMetadata Metadata,
NodeScope Scope, DataView? Parent, BackingSourceKey? Source, bool Supported = true, bool SourceEnabled = true);
/// <summary>Immutable origin-only catalog. Projected peer nodes cannot become export authority.</summary>
public sealed partial class LocalExportCatalog
{
private readonly Dictionary<(DataAddress Address, DataRealm Realm), LocalDataNode> _nodes = new();
private readonly Dictionary<DataView, LocalDataNode[]> _children;
private readonly ExportRule[] _exports;
private readonly IDataMappedCatalogAuthority _activation;
private sealed record ExportRule(string Principal, DataRealm Realm, DataView? Root, bool WholeRealm,
DataOperations Operations, int Batch, int Page, int Items, int Streams);
public LocalExportCatalog(string clusterId, ServingIdentity serving, IDataMappedCatalogAuthority activation,
IEnumerable<LocalDataNode> nodes, IEnumerable<DataExport> exports, int maximumNodes = 100_000)
{
ArgumentException.ThrowIfNullOrWhiteSpace(clusterId);
ArgumentNullException.ThrowIfNull(serving);
ArgumentNullException.ThrowIfNull(activation);
ArgumentNullException.ThrowIfNull(nodes);
ArgumentNullException.ThrowIfNull(exports);
serving.Validate(requireEpochs: true);
if (maximumNodes <= 0) throw new ArgumentOutOfRangeException(nameof(maximumNodes));
ClusterId = clusterId;
Serving = serving;
_activation = activation;
foreach (var input in nodes)
{
if (_nodes.Count >= maximumNodes) throw new ArgumentOutOfRangeException(nameof(nodes), "Catalog node budget exceeded.");
ArgumentNullException.ThrowIfNull(input);
input.Metadata.Validate();
var view = input.Metadata.View;
if (view.MappingId is not null || !string.Equals(view.Address.OriginClusterId, clusterId, StringComparison.OrdinalIgnoreCase)
|| !string.Equals(input.Scope.ClusterId, clusterId, StringComparison.OrdinalIgnoreCase)
|| input.EntityKind == "RemoteNamespaceMapping" || input.Metadata.CatalogRevision != serving.CatalogEpoch
|| input.Scope.Kind is not (NodeHierarchyKind.Raw or NodeHierarchyKind.Uns)
|| view.Address.NamespaceUri != (view.Realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri)
|| view.Realm != (input.Scope.Kind == NodeHierarchyKind.Raw ? DataRealm.Raw : DataRealm.Uns)
|| (input.Source is { } source && (!string.Equals(source.OriginClusterId, clusterId, StringComparison.OrdinalIgnoreCase)
|| source.ServingNodeId != serving.NodeId || source.ServingIncarnation != serving.Incarnation)))
throw new ArgumentException("Catalog contains a nonlocal or projected node.", nameof(nodes));
var node = input with
{
Metadata = input.Metadata with { View = view with { Address = view.Address with { OriginClusterId = clusterId } },
Dimensions = Array.AsReadOnly(input.Metadata.Dimensions.ToArray()) },
Scope = input.Scope with { Segments = Array.AsReadOnly(input.Scope.Segments.ToArray()) }
};
if (!_nodes.TryAdd((node.Metadata.View.Address, view.Realm), node))
throw new ArgumentException("Catalog contains duplicate addresses.", nameof(nodes));
}
foreach (var pair in _nodes.ToArray())
if (pair.Value.Parent is { } parent)
{
if (!TryResolve(parent, out var resolved)) throw new ArgumentException("Catalog parent is not origin-local.", nameof(nodes));
_nodes[pair.Key] = pair.Value with { Parent = resolved.Metadata.View };
}
// A bounded parent walk makes a corrupt cycle a rejected generation, rather than an export escape.
foreach (var node in _nodes.Values)
{
var seen = new HashSet<DataView>();
var current = node;
while (current.Parent is { } parent)
{
if (!seen.Add(parent)) throw new ArgumentException("Catalog contains a parent cycle.", nameof(nodes));
current = _nodes[(parent.Address, parent.Realm)];
}
}
_children = _nodes.Values.Where(x => x.Parent is not null).GroupBy(x => x.Parent!)
.ToDictionary(x => x.Key, x => x.OrderBy(n => n.Metadata.BrowseName, StringComparer.Ordinal)
.ThenBy(n => n.Metadata.View.Address.Identifier, StringComparer.Ordinal).ToArray());
var rules = new List<ExportRule>();
foreach (var export in exports.Where(x => x.Enabled && string.Equals(x.ClusterId, clusterId, StringComparison.OrdinalIgnoreCase)))
{
var wholeRealm = export.RootKind == "Cluster" && string.Equals(export.RootEntityId, clusterId, StringComparison.OrdinalIgnoreCase);
var roots = _nodes.Values.Where(x => x.EntityKind == export.RootKind
&& string.Equals(x.EntityId, export.RootEntityId, StringComparison.OrdinalIgnoreCase)
&& x.Metadata.View.Realm == export.Realm).ToArray();
if ((!wholeRealm && roots.Length != 1) || string.IsNullOrWhiteSpace(export.PrincipalId)
|| export.AllowedOperations == DataOperations.None || export.MaxBatchItems <= 0 || export.MaxPageItems <= 0
|| export.MaxMonitoredItems <= 0 || export.MaxStreams <= 0)
throw new ArgumentException("Export has no valid origin root or policy.", nameof(exports));
rules.Add(new(export.PrincipalId, export.Realm, wholeRealm ? null : roots[0].Metadata.View, wholeRealm,
export.AllowedOperations, export.MaxBatchItems, export.MaxPageItems, export.MaxMonitoredItems, export.MaxStreams));
}
_exports = rules.ToArray();
Nodes = new ReadOnlyCollection<LocalDataNode>(_nodes.Values.ToArray());
}
public string ClusterId { get; }
public ServingIdentity Serving { get; }
public long AuthorityEpoch => _activation.AuthorityEpoch;
public bool IsActive => _activation.IsActive && _activation.CatalogEpoch == Serving.CatalogEpoch
&& _activation.AuthorityEpoch == Serving.AuthorityEpoch;
public IReadOnlyList<LocalDataNode> Nodes { get; }
private LocalExportCatalog(LocalExportCatalog current, ServingIdentity serving)
{
serving.Validate(requireEpochs: true);
if (serving.NodeId != current.Serving.NodeId || serving.Incarnation != current.Serving.Incarnation
|| serving.CatalogEpoch != current.Serving.CatalogEpoch || serving.AuthorityEpoch != current.Serving.AuthorityEpoch)
throw new ArgumentException("A new process or catalog generation requires a newly compiled catalog.", nameof(serving));
ClusterId = current.ClusterId; Serving = serving; _activation = current._activation;
_nodes = current._nodes; _children = current._children; _exports = current._exports; Nodes = current.Nodes;
}
/// <summary>A role-only transition changes serving provenance without freshening source acquisitions.</summary>
public LocalExportCatalog WithServingRole(ServingIdentity serving) => new(this, serving);
public bool TryResolve(DataView view, out LocalDataNode node)
{
var address = LocalAddress(view.Address);
if (_nodes.TryGetValue((address, view.Realm), out var found)
&& found.Metadata.View == (view with { Address = address }))
{ node = found; return true; }
node = null!;
return false;
}
private DataAddress LocalAddress(DataAddress address) => string.Equals(address.OriginClusterId, ClusterId, StringComparison.OrdinalIgnoreCase)
? address with { OriginClusterId = ClusterId } : address;
internal bool ContainsAddress(DataView view) => _nodes.ContainsKey((LocalAddress(view.Address), view.Realm));
internal bool TryResolveAddress(DataView view, out LocalDataNode node)
{
if (view.MappingId is null && view.MappingRevision == 0 && _nodes.TryGetValue((LocalAddress(view.Address), view.Realm), out var found))
{ node = found; return true; }
node = null!; return false;
}
public IReadOnlyList<LocalDataNode> Children(LocalDataNode parent) =>
_children.TryGetValue(parent.Metadata.View, out var children) ? Array.AsReadOnly(children) : [];
internal bool AllowsExport(string principal, LocalDataNode node, DataOperations operation)
{
foreach (var rule in _exports)
{
if (!string.Equals(principal, rule.Principal, StringComparison.OrdinalIgnoreCase)
|| rule.Realm != node.Metadata.View.Realm || (rule.Operations & operation) != operation) continue;
if (rule.WholeRealm || IsAncestor(rule.Root!, node.Metadata.View)
|| (operation == DataOperations.Browse && IsAncestor(node.Metadata.View, rule.Root!))) return true;
}
return false;
}
private bool IsAncestor(DataView ancestor, DataView candidate)
{
var current = candidate;
for (var depth = 0; depth <= _nodes.Count; depth++)
{
if (current == ancestor) return true;
if (!TryResolve(current, out var node) || node.Parent is null) return false;
current = node.Parent;
}
return false;
}
internal DataLimits LimitsFor(string principal, DataLimits limits)
{
var rules = _exports.Where(x => string.Equals(x.Principal, principal, StringComparison.OrdinalIgnoreCase)).ToArray();
return rules.Length == 0 ? limits : limits with
{
MaxBatchItems = Math.Min(limits.MaxBatchItems, rules.Min(x => x.Batch)),
MaxPageItems = Math.Min(limits.MaxPageItems, rules.Min(x => x.Page)),
MaxMonitoredItems = Math.Min(limits.MaxMonitoredItems, rules.Min(x => x.Items)),
MaxStreams = Math.Min(limits.MaxStreams, rules.Min(x => x.Streams))
};
}
internal DataOperations ExportOperations(string principal) => _exports
.Where(x => string.Equals(x.Principal, principal, StringComparison.OrdinalIgnoreCase))
.Aggregate(DataOperations.None, (operations, rule) => operations | rule.Operations);
}
@@ -0,0 +1,122 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Validates borrowed driver values before creating the immutable data-plane value.</summary>
internal static class OwnedDataSample
{
private const int MaxElements = 65_536;
private const long MaxBytes = 4 * 1024 * 1024;
private const int MaxRank = 4;
public static long Estimate(object? value, SourceValueShape? shape = null)
{
checked
{
const long baseline = 256;
long size;
if (value is byte[] bytes && shape is { Kind: DataValueKind.Array, ElementKind: DataValueKind.UInt8, Rank: 1 })
{
if (bytes.LongLength > MaxElements) throw new ArgumentException("Array exceeds ingestion limit.");
size = baseline + 128L + 8L + 48L * bytes.LongLength;
}
else if (value is byte[] bytesValue) size = baseline + 32L + bytesValue.LongLength;
else if (value is string text) size = baseline + 32L + 2L * text.Length;
else if (value is Array array)
{
if (array.Rank > MaxRank || array.LongLength > MaxElements || array.GetType().GetElementType() is not { } elementType || Kind(elementType) == DataValueKind.Unspecified)
throw new ArgumentException("Unsupported array shape or type.");
for (var dimension = 0; dimension < array.Rank; dimension++)
if (array.GetLowerBound(dimension) != 0) throw new ArgumentException("Non-zero array lower bounds are unsupported.");
size = baseline + 128L + 8L * array.Rank + 48L * array.LongLength;
if (elementType == typeof(string))
foreach (var element in array)
size += 2L * ((string?)element ?? throw new ArgumentException("Null array element.")).Length;
}
else
{
if (value is not null && Kind(value.GetType()) == DataValueKind.Unspecified)
throw new ArgumentException("Unsupported mutable value.");
size = baseline + 32L;
}
if (size > MaxBytes) throw new ArgumentException("Value exceeds ingestion limit.");
if (value is not null && shape is { } declared)
{
var isByteArray = value is byte[] && declared.Kind == DataValueKind.Array && declared.ElementKind == DataValueKind.UInt8;
if (declared.Kind == DataValueKind.Array)
{
if (value is not Array declaredArray || declaredArray.Rank != declared.Rank ||
(!isByteArray && Kind(declaredArray.GetType().GetElementType()!) != declared.ElementKind))
throw new ArgumentException("Value does not match its declared array shape.");
}
else if (declared.Kind == DataValueKind.Bytes ? value is not byte[] : Kind(value.GetType()) != declared.Kind)
throw new ArgumentException("Value does not match its declared type.");
}
return size;
}
}
public static DataValue Copy(object? value, SourceValueShape? shape = null)
{
if (value is null) return DataValue.Null();
if (value is byte[] bytes && shape is not { Kind: DataValueKind.Array }) return DataValue.FromBytes(bytes);
if (value is Array array)
{
var elementKind = Kind(array.GetType().GetElementType()!);
var elements = new object[array.Length];
var index = 0;
foreach (var item in array) elements[index++] = Normalize(item!);
var dimensions = new int[array.Rank];
for (var i = 0; i < dimensions.Length; i++) dimensions[i] = array.GetLength(i);
return DataValue.FromArray(elementKind, elements, dimensions);
}
return DataValue.FromScalar(Kind(value.GetType()), Normalize(value));
}
// The legacy SDK path has its own managed defensive copy. It is deliberately outside the hub's
// budget and must be measured separately; never expose the hub's immutable backing to it.
public static object? CopyLegacy(object? value) => value is Array array
? CopyLegacyArray(array, new Dictionary<Array, Array>(ReferenceEqualityComparer.Instance)) : value;
private static Array CopyLegacyArray(Array original, Dictionary<Array, Array> seen)
{
if (seen.TryGetValue(original, out var existing)) return existing;
var copy = (Array)original.Clone();
seen.Add(original, copy);
if (original.GetType().GetElementType()?.IsValueType != false || original.Length == 0) return copy;
var indices = new int[original.Rank];
void Walk(int dimension)
{
var end = original.GetUpperBound(dimension);
for (var i = original.GetLowerBound(dimension); i <= end; i++)
{
indices[dimension] = i;
if (dimension + 1 < original.Rank) Walk(dimension + 1);
else if (original.GetValue(indices) is Array nested) copy.SetValue(CopyLegacyArray(nested, seen), indices);
}
}
Walk(0);
return copy;
}
public static DateTimeOffset? Timestamp(DateTime? value) => value is null ? null :
new DateTimeOffset(value.Value.Kind == DateTimeKind.Unspecified
? DateTime.SpecifyKind(value.Value, DateTimeKind.Utc)
: value.Value.ToUniversalTime());
private static object Normalize(object value) => value switch
{
DateTime time => Timestamp(time)!.Value,
DateTimeOffset offset => offset.ToUniversalTime(),
_ => value
};
private static DataValueKind Kind(Type type) => type == typeof(bool) ? DataValueKind.Boolean :
type == typeof(sbyte) ? DataValueKind.Int8 : type == typeof(short) ? DataValueKind.Int16 :
type == typeof(int) ? DataValueKind.Int32 : type == typeof(long) ? DataValueKind.Int64 :
type == typeof(byte) ? DataValueKind.UInt8 : type == typeof(ushort) ? DataValueKind.UInt16 :
type == typeof(uint) ? DataValueKind.UInt32 : type == typeof(ulong) ? DataValueKind.UInt64 :
type == typeof(float) ? DataValueKind.Float : type == typeof(double) ? DataValueKind.Double :
type == typeof(string) ? DataValueKind.String : type == typeof(Guid) ? DataValueKind.Guid :
type == typeof(DateTime) || type == typeof(DateTimeOffset) ? DataValueKind.Timestamp : DataValueKind.Unspecified;
}
@@ -0,0 +1,219 @@
using System.Collections.Concurrent;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Canonical acquisition identity, independent of any authorized view or principal.</summary>
public sealed record BackingSourceKey(string OriginClusterId, string SourceKind, string StableSourceId,
string ServingNodeId, string ServingIncarnation);
public readonly record struct SourceGeneration(long Incarnation, long Lifecycle);
internal sealed class SourceBindingFence
{
private int _retired;
internal bool IsRetired => Volatile.Read(ref _retired) != 0;
internal void Retire() => Interlocked.Exchange(ref _retired, 1);
}
/// <summary>An individual binding; two bindings of the same key and generation remain distinct.</summary>
public readonly record struct SourceTicket(BackingSourceKey Key, SourceGeneration Generation)
{
internal SourceBindingFence? Binding { get; } = new();
}
/// <summary>Shared producer lifetime; retirement immediately fences every source bound to this token.</summary>
public sealed class ProducerFence
{
private int _retired;
public ProducerFence(long incarnation)
{
if (incarnation <= 0) throw new ArgumentOutOfRangeException(nameof(incarnation));
Incarnation = incarnation;
}
public long Incarnation { get; }
public bool IsRetired => Volatile.Read(ref _retired) != 0;
public void Retire() => Interlocked.Exchange(ref _retired, 1);
}
public interface IIngressReservation : IDisposable
{
/// <summary>On success transfers the sample; on failure it remains owned by the caller.</summary>
bool TryCommit(DataSample owned, long sequence);
}
public interface ISourceSampleHub
{
bool TryBind(SourceTicket ticket);
bool TryBind(SourceTicket ticket, ProducerFence? fence);
bool TryGetCurrentTicket(BackingSourceKey key, out SourceTicket ticket);
bool IsTicketCurrentNonBlocking(SourceTicket ticket);
void InvalidatePartitionFor(BackingSourceKey key, string reason);
bool TryReserveIngress(SourceTicket ticket, long estimatedRetainedBytes, out IIngressReservation? reservation);
void Invalidate(SourceTicket ticket, string reason);
bool TryPublishStatus(SourceTicket ticket, long sequence, uint statusCode, DateTimeOffset? sourceTimestampUtc, DateTimeOffset? serverTimestampUtc);
bool TryRemove(SourceTicket ticket, long sequence);
}
/// <summary>A recipient-owned cache read. Dispose releases its independent sample lease and admission charge.</summary>
public sealed class CachedSourceRead : IDisposable
{
private readonly DataResourceBudget _budget;
private readonly SamplePartition? _guard;
private readonly object? _source;
private readonly object? _sourceGate;
private readonly long _sourceVersion, _routingEpoch;
private readonly long _sourceSignal;
private long _charge;
internal CachedSourceRead(DataResourceBudget budget, DataItemStatus status, DataReadiness readiness,
DataSample? sample, long version, long partitionEpoch, long receivedTimestamp, long charge,
SamplePartition? guard = null, object? source = null, object? sourceGate = null,
long sourceVersion = 0, long sourceSignal = 0, long routingEpoch = 0)
{ _budget = budget; Status = status; Readiness = readiness; Sample = sample; SourceVersion = version;
PartitionEpoch = partitionEpoch; ReceivedTimestamp = receivedTimestamp; _charge = charge;
_guard = guard; _source = source; _sourceGate = sourceGate; _sourceVersion = sourceVersion;
_sourceSignal = sourceSignal; _routingEpoch = routingEpoch; }
public DataItemStatus Status { get; }
public DataReadiness Readiness { get; }
public DataSample? Sample { get; }
public long SourceVersion { get; }
public long PartitionEpoch { get; }
public long ReceivedTimestamp { get; }
/// <summary>True only while the captured source, producer and partition fences remain current.</summary>
public bool IsValid => Volatile.Read(ref _charge) != 0 && _guard is not null && _source is not null && _sourceGate is not null &&
_guard.IsReadValid(_source, _sourceGate, _sourceVersion, _sourceSignal, PartitionEpoch, _routingEpoch);
public void Dispose()
{
var charge = Interlocked.Exchange(ref _charge, 0);
if (charge == 0) return;
Sample?.Dispose(); _budget.Release(charge);
if (_guard is not null && _source is not null) _guard.ReleaseRead(_source);
}
}
/// <summary>
/// Partitioned source owner. Producer admission never waits on a worker or socket.
/// Reads and snapshots are raw runtime acquisition state, not authorized external results.
/// A facade must prove current catalog and authority and attach current trusted serving
/// provenance before returning a sample; acquisitions may have zero preactivation epochs.
/// </summary>
public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable
{
internal const long SampleOverhead = 256;
internal const long ReferenceOverhead = 256;
private readonly DataResourceLimits _limits;
private readonly bool _autoDrain;
private readonly object _routingLock = new();
private readonly ConcurrentDictionary<SnapshotLease, byte> _snapshots = new();
private SamplePartition[] _partitions;
private int _trackedSources;
private int _snapshotItems;
private long _routingEpoch = 1;
private int _disposed;
public PartitionedSampleHub(DataResourceLimits limits, TimeProvider clock) : this(limits, clock, true) { }
internal PartitionedSampleHub(DataResourceLimits limits, TimeProvider clock, bool autoDrain)
{
ArgumentNullException.ThrowIfNull(limits); ArgumentNullException.ThrowIfNull(clock); limits.Validate();
_limits = limits; Clock = clock; _autoDrain = autoDrain; Resources = new(limits.MaxRetainedBytes);
_partitions = CreatePartitions(limits.PartitionCount);
}
public TimeProvider Clock { get; }
public DataResourceBudget Resources { get; }
internal DataResourceLimits Limits => _limits;
internal long RoutingEpoch => Interlocked.Read(ref _routingEpoch);
internal bool IsDisposed => Volatile.Read(ref _disposed) != 0;
private SamplePartition[] CreatePartitions(int count) => Enumerable.Range(0, count).Select(i => new SamplePartition(this, i)).ToArray();
// Routing stays stable for this process; repartitioning resets affected epochs.
public int GetPartition(BackingSourceKey key)
{
ArgumentNullException.ThrowIfNull(key);
return GetPartitionFor(key, Volatile.Read(ref _partitions).Length);
}
private SamplePartition Partition(BackingSourceKey key) { var partitions = Volatile.Read(ref _partitions); return partitions[GetPartitionFor(key, partitions.Length)]; }
internal static int GetPartitionFor(BackingSourceKey key, int count) => (int)(unchecked((uint)key.GetHashCode()) % (uint)count);
internal bool TryTrackSource() { while (true) { var current = Volatile.Read(ref _trackedSources); if (current >= _limits.MaxTrackedSources) return false; if (Interlocked.CompareExchange(ref _trackedSources, current + 1, current) == current) return true; } }
internal void UntrackSource() => Interlocked.Decrement(ref _trackedSources);
internal bool TryTrackSnapshotItems(int count) { while (true) { var current = Volatile.Read(ref _snapshotItems); if (count > _limits.MaxSnapshotItems - current) return false; if (Interlocked.CompareExchange(ref _snapshotItems, current + count, current) == current) return true; } }
internal void UntrackSnapshotItems(int count) => Interlocked.Add(ref _snapshotItems, -count);
internal void ForgetSnapshot(SnapshotLease snapshot) => _snapshots.TryRemove(snapshot, out _);
internal void Schedule(SamplePartition partition) { if (_autoDrain) partition.Schedule(); }
private static bool ValidKey(BackingSourceKey? key) => key is not null &&
!string.IsNullOrWhiteSpace(key.OriginClusterId) && !string.IsNullOrWhiteSpace(key.SourceKind) &&
!string.IsNullOrWhiteSpace(key.StableSourceId) && !string.IsNullOrWhiteSpace(key.ServingNodeId) &&
!string.IsNullOrWhiteSpace(key.ServingIncarnation) &&
(long)key.OriginClusterId.Length + key.SourceKind.Length + key.StableSourceId.Length + key.ServingNodeId.Length + key.ServingIncarnation.Length <= 4096;
public bool TryBind(SourceTicket ticket) => TryBind(ticket, null);
public bool TryBind(SourceTicket ticket, ProducerFence? fence) => !IsDisposed && ValidKey(ticket.Key) && Partition(ticket.Key).TryBind(ticket, fence);
public bool TryGetCurrentTicket(BackingSourceKey key, out SourceTicket ticket)
{ if (!IsDisposed && ValidKey(key)) return Partition(key).TryGetCurrentTicket(key, out ticket); ticket = default; return false; }
public bool IsTicketCurrentNonBlocking(SourceTicket ticket) => !IsDisposed && ValidKey(ticket.Key) && Partition(ticket.Key).IsTicketCurrentNonBlocking(ticket);
public void InvalidatePartitionFor(BackingSourceKey key, string reason)
{ ArgumentException.ThrowIfNullOrWhiteSpace(reason); if (!IsDisposed && ValidKey(key)) Partition(key).InvalidatePartition(); }
public bool TryReserveIngress(SourceTicket ticket, long estimatedRetainedBytes, out IIngressReservation? reservation)
{ if (!IsDisposed && ValidKey(ticket.Key)) return Partition(ticket.Key).TryReserve(ticket, estimatedRetainedBytes, out reservation); reservation = null; return false; }
public void Invalidate(SourceTicket ticket, string reason) { ArgumentException.ThrowIfNullOrWhiteSpace(reason); if (!IsDisposed && ValidKey(ticket.Key)) Partition(ticket.Key).Invalidate(ticket); }
public bool TryPublishStatus(SourceTicket ticket, long sequence, uint statusCode, DateTimeOffset? sourceTimestampUtc, DateTimeOffset? serverTimestampUtc) =>
!IsDisposed && ValidKey(ticket.Key) && Partition(ticket.Key).TryStatus(ticket, sequence, statusCode, sourceTimestampUtc, serverTimestampUtc);
public bool TryRemove(SourceTicket ticket, long sequence) => !IsDisposed && ValidKey(ticket.Key) && Partition(ticket.Key).TryRemove(ticket, sequence);
public CachedSourceRead Read(SourceTicket ticket) => IsDisposed || !ValidKey(ticket.Key) ? EmptyRead(DataItemStatus.Unavailable, DataReadiness.Unavailable, 0) : Partition(ticket.Key).Read(ticket);
internal CachedSourceRead EmptyRead(DataItemStatus status, DataReadiness readiness, long epoch) => new(Resources, status, readiness, null, 0, epoch, 0, 0);
internal void ProcessPending() { foreach (var partition in Volatile.Read(ref _partitions)) partition.Drain(); }
internal void WithPartitionLockForTest(BackingSourceKey key, Action action) => Partition(key).WithLockForTest(action);
public bool TryCaptureSnapshot(IReadOnlyList<SourceTicket> tickets, DataBudget budget, CancellationToken cancellationToken, out SnapshotLease? snapshot)
{
snapshot = null; ArgumentNullException.ThrowIfNull(tickets); ArgumentNullException.ThrowIfNull(budget); budget.Validate();
if (IsDisposed || cancellationToken.IsCancellationRequested || tickets.Count == 0 || tickets.Count > budget.MaxItems ||
tickets.Count > _limits.MaxSnapshotItems || tickets.Any(t => !ValidKey(t.Key)) || tickets.Distinct().Count() != tickets.Count || !TryTrackSnapshotItems(tickets.Count)) return false;
var routing = RoutingEpoch; var items = new Dictionary<SourceTicket, SnapshotItem>(); var watermarks = new Dictionary<int, long>(); var epochs = new Dictionary<int, long>();
long charge = 0;
try
{
var partitions = Volatile.Read(ref _partitions);
foreach (var group in tickets.GroupBy(t => GetPartitionFor(t.Key, partitions.Length)))
{
if (cancellationToken.IsCancellationRequested || routing != RoutingEpoch ||
!partitions[group.Key].Capture(group, items, out var watermark, out var epoch, ref charge, Math.Min(budget.MaxBytes, _limits.MaxSnapshotBytes))) return false;
watermarks.Add(group.Key, watermark);
epochs.Add(group.Key, epoch);
}
if (cancellationToken.IsCancellationRequested || routing != RoutingEpoch) return false;
snapshot = new SnapshotLease(this, items, watermarks, epochs, partitions, routing, charge, tickets.Count,
budget.Timeout < _limits.MaxSnapshotLifetime ? budget.Timeout : _limits.MaxSnapshotLifetime, cancellationToken);
charge = 0; items = null!;
_snapshots.TryAdd(snapshot, 0);
if (!snapshot.IsReset) return true;
snapshot.Dispose(); ForgetSnapshot(snapshot); snapshot = null; return false;
}
finally
{
if (items is not null) { foreach (var item in items.Values) { item.Sample?.Dispose(); item.ReleaseSource(); } Resources.Release(charge); UntrackSnapshotItems(tickets.Count); }
}
}
public void Repartition(int count)
{
if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));
lock (_routingLock)
{
if (IsDisposed) throw new ObjectDisposedException(nameof(PartitionedSampleHub));
Interlocked.Increment(ref _routingEpoch);
var old = Volatile.Read(ref _partitions);
foreach (var snapshot in _snapshots.Keys) snapshot.Dispose();
foreach (var partition in old) partition.Dispose();
// Retire all old binding tokens before exposing new owners; otherwise an old
// ticket can race the swap and bind in a new partition before its fence closes.
Volatile.Write(ref _partitions, CreatePartitions(count));
}
}
public void Dispose()
{
lock (_routingLock)
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
Interlocked.Increment(ref _routingEpoch);
foreach (var snapshot in _snapshots.Keys) snapshot.Dispose();
foreach (var partition in _partitions) partition.Dispose();
}
}
}
@@ -0,0 +1,486 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using System.Collections.Concurrent;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>One bounded source owner; no network or caller callbacks run under its lock.</summary>
internal sealed class SamplePartition : IDisposable
{
private const long SourceOverhead = 768;
private const long ControlOverhead = 256;
private const long ChangeOverhead = 192;
private readonly PartitionedSampleHub _hub;
private readonly object _gate = new();
private readonly ConcurrentDictionary<BackingSourceKey, SourceState> _sources = new();
private readonly Queue<Pending> _queue = new();
private readonly Dictionary<BackingSourceKey, Pending> _dirty = new();
private readonly Queue<(long Version, BackingSourceKey Key)> _changes = new();
private long _epoch = 1;
private long _cleanedEpoch = 1;
private long _watermark;
private long _ordinal;
private int _queuedValues;
private int _queuedControls;
private int _reservations;
private int _scheduled;
private int _retiredSweepRequested;
private int _reclaimRequested;
private bool _disposed;
private readonly long _routingEpoch;
internal SamplePartition(PartitionedSampleHub hub, int id) { _hub = hub; Id = id; _routingEpoch = hub.RoutingEpoch; }
internal int Id { get; }
internal long Epoch { get { lock (_gate) return _epoch; } }
private static bool Valid(SourceTicket ticket)
{
var k = ticket.Key;
return k is not null && !string.IsNullOrWhiteSpace(k.OriginClusterId) && !string.IsNullOrWhiteSpace(k.SourceKind) &&
!string.IsNullOrWhiteSpace(k.StableSourceId) && !string.IsNullOrWhiteSpace(k.ServingNodeId) &&
!string.IsNullOrWhiteSpace(k.ServingIncarnation) && ticket.Generation.Incarnation > 0 && ticket.Generation.Lifecycle > 0 &&
(long)k.OriginClusterId.Length + k.SourceKind.Length + k.StableSourceId.Length + k.ServingNodeId.Length + k.ServingIncarnation.Length <= 4096;
}
private static int Compare(SourceGeneration a, SourceGeneration b) => a.Incarnation != b.Incarnation ? a.Incarnation.CompareTo(b.Incarnation) : a.Lifecycle.CompareTo(b.Lifecycle);
private static long SourceCharge(BackingSourceKey key) => checked(SourceOverhead + 2L * (key.OriginClusterId.Length + key.SourceKind.Length + key.StableSourceId.Length + key.ServingNodeId.Length + key.ServingIncarnation.Length));
internal bool TryBind(SourceTicket ticket, ProducerFence? fence)
{
if (!Valid(ticket) || ticket.Binding is null || ticket.Binding.IsRetired || (fence is not null && (fence.IsRetired || fence.Incarnation != ticket.Generation.Incarnation))) return false;
if (!Monitor.TryEnter(_gate))
{
if (_sources.TryGetValue(ticket.Key, out var existing))
{
var gate = Volatile.Read(ref existing.Gate);
if (Compare(ticket.Generation, gate.Generation) > 0) { gate.Binding.Retire(); Interlocked.Exchange(ref gate.Retired, 1); Interlocked.Increment(ref gate.Invalidated); }
}
return false;
}
try
{
if (_disposed || ticket.Binding.IsRetired) return false;
if (_sources.TryGetValue(ticket.Key, out var state))
{
var order = Compare(ticket.Generation, state.Generation);
ApplyGate(state);
ApplyPartitionEpoch(state);
if (order == 0)
{
if (state.Ticket != ticket || state.Removed || Volatile.Read(ref state.Gate.Retired) != 0 || state.Fence?.IsRetired == true ||
(state.Fence is not null && !ReferenceEquals(state.Fence, fence))) return false;
if (state.Fence is null && fence is not null) Volatile.Write(ref state.Fence, fence);
return state.Fence?.IsRetired != true;
}
if (order < 0) return false;
state.Ticket.Binding!.Retire();
Interlocked.Exchange(ref state.Gate.Retired, 1);
state.Generation = ticket.Generation; state.Removed = false; state.Readiness = DataReadiness.WaitingForInitialData; Interlocked.Increment(ref state.InvalidationVersion);
state.Ticket = ticket;
state.Fence = fence; state.PartitionEpoch = _epoch;
Volatile.Write(ref state.Gate, new SourceGate(ticket.Generation, ticket.Binding));
state.AppliedInvalidations = 0;
state.LastSubmitted = 0; state.LastApplied = 0; state.Barrier = 0; ReleaseCache(state);
RecordChange(ticket.Key); return true;
}
var charge = SourceCharge(ticket.Key);
if (!_hub.TryTrackSource()) { InvalidatePartition(); return false; }
if (!_hub.Resources.TryReserve(charge)) { _hub.UntrackSource(); InvalidatePartition(); return false; }
if (!_sources.TryAdd(ticket.Key, new SourceState(ticket, charge, fence, _epoch))) { _hub.Resources.Release(charge); _hub.UntrackSource(); return false; }
return true;
}
finally { Monitor.Exit(_gate); }
}
internal bool TryGetCurrentTicket(BackingSourceKey key, out SourceTicket ticket)
{
lock (_gate)
{
if (!_disposed && _sources.TryGetValue(key, out var state))
{ ApplyGate(state); ApplyPartitionEpoch(state); if (!state.Removed && Volatile.Read(ref state.Gate.Retired) == 0 && state.Fence?.IsRetired != true) { ticket = state.Ticket; return true; } }
ticket = default; return false;
}
}
internal bool IsTicketCurrentNonBlocking(SourceTicket ticket)
{
if (!_sources.TryGetValue(ticket.Key, out var state)) return false;
var gate = Volatile.Read(ref state.Gate);
var fence = Volatile.Read(ref state.Fence);
return gate.Generation == ticket.Generation && ReferenceEquals(gate.Binding, ticket.Binding) && !gate.Binding.IsRetired && Volatile.Read(ref gate.Retired) == 0 &&
fence?.IsRetired != true && ReferenceEquals(gate, Volatile.Read(ref state.Gate));
}
internal void WithLockForTest(Action action) { lock (_gate) action(); }
private bool Current(SourceTicket ticket, out SourceState state)
{
if (!_sources.TryGetValue(ticket.Key, out state!)) return false;
ApplyGate(state);
ApplyPartitionEpoch(state);
return !state.Removed && state.Ticket == ticket && ticket.Binding is { IsRetired: false } && Volatile.Read(ref state.Gate.Retired) == 0 && state.Fence?.IsRetired != true;
}
private void ApplyGate(SourceState state)
{
var gate = Volatile.Read(ref state.Gate);
var signal = Volatile.Read(ref gate.Invalidated);
if (state.AppliedInvalidations != signal)
{
InvalidateSource(state);
state.AppliedInvalidations = signal;
}
}
private void Signal(SourceTicket ticket, bool retired = false)
{
if (!_sources.TryGetValue(ticket.Key, out var state)) return;
var gate = Volatile.Read(ref state.Gate);
if (gate.Generation != ticket.Generation || !ReferenceEquals(gate.Binding, ticket.Binding)) return;
if (retired)
{
gate.Binding.Retire();
Interlocked.Exchange(ref gate.Retired, 1);
Interlocked.Exchange(ref _retiredSweepRequested, 1);
_hub.Schedule(this);
}
Interlocked.Increment(ref gate.Invalidated);
}
internal bool TryReserve(SourceTicket ticket, long estimated, out IIngressReservation? reservation)
{
reservation = null;
if (!Monitor.TryEnter(_gate)) { Signal(ticket); return false; }
try
{
if (_disposed || !Current(ticket, out var state)) return false;
if (estimated <= 0 || estimated > long.MaxValue - PartitionedSampleHub.SampleOverhead ||
Volatile.Read(ref _reservations) >= _hub.Limits.MaxIngressItemsPerPartition + _hub.Limits.MaxDirtySourcesPerPartition ||
!_hub.Resources.TryReserve(estimated + PartitionedSampleHub.SampleOverhead))
{ InvalidateSource(state); return false; }
Interlocked.Increment(ref _reservations);
Interlocked.Increment(ref state.Reservations);
Interlocked.Increment(ref state.MetadataOwners);
reservation = new Reservation(this, state, ticket, estimated, estimated + PartitionedSampleHub.SampleOverhead,
state.InvalidationVersion, _epoch);
return true;
}
finally { Monitor.Exit(_gate); }
}
private bool Commit(SourceState reservedState, SourceTicket ticket, long estimate, long charge, long invalidationVersion, long partitionEpoch, DataSample sample, long sequence)
{
if (!Monitor.TryEnter(_gate))
{ ReleaseReservation(reservedState); _hub.Resources.Release(charge); Signal(ticket); return false; }
try
{
ReleaseReservation(reservedState);
if (_disposed || !Current(ticket, out var state)) { _hub.Resources.Release(charge); return false; }
if (state.InvalidationVersion != invalidationVersion || _epoch != partitionEpoch) { _hub.Resources.Release(charge); return false; }
try
{
ArgumentNullException.ThrowIfNull(sample.Value);
ArgumentNullException.ThrowIfNull(sample.Serving);
sample.Serving.Validate(requireEpochs: false);
if (sequence <= state.LastSubmitted || sample.Version != sequence || sample.Value.EstimatedRetainedBytes > estimate ||
sample.Serving.NodeId != ticket.Key.ServingNodeId || sample.Serving.Incarnation != ticket.Key.ServingIncarnation)
{ _hub.Resources.Release(charge); InvalidateSource(state); return false; }
}
catch (Exception e) when (e is ArgumentException or ObjectDisposedException or OverflowException)
{ _hub.Resources.Release(charge); InvalidateSource(state); return false; }
var pending = new Pending(ticket, sequence, ++_ordinal, sample, charge, _hub.Clock.GetTimestamp()) { AdmissionEpoch = state.InvalidationVersion, PartitionEpoch = partitionEpoch };
if (_queuedValues < _hub.Limits.MaxIngressItemsPerPartition)
{ _queue.Enqueue(pending); _queuedValues++; }
else if (_dirty.TryGetValue(ticket.Key, out var previous))
{ ReleasePending(previous); _dirty[ticket.Key] = pending; }
else if (_dirty.Count < _hub.Limits.MaxDirtySourcesPerPartition) _dirty.Add(ticket.Key, pending);
else { _hub.Resources.Release(charge); InvalidatePartition(); return false; }
state.LastSubmitted = sequence;
_hub.Schedule(this);
return true;
}
finally { Monitor.Exit(_gate); }
}
private void ReleaseReservation(SourceState state)
{
Interlocked.Decrement(ref _reservations);
var lastReservation = Interlocked.Decrement(ref state.Reservations) == 0;
ReleaseMetadataOwner(state);
if (lastReservation && Volatile.Read(ref state.Gate.Retired) != 0 && !Volatile.Read(ref _disposed)) RequestReclaim();
}
private void Abandon(SourceState state, long charge) { ReleaseReservation(state); _hub.Resources.Release(charge); }
internal void Invalidate(SourceTicket ticket) => Signal(ticket);
private void InvalidateSource(SourceState state) { state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); ReleaseCache(state); }
internal bool TryStatus(SourceTicket ticket, long sequence, uint status, DateTimeOffset? source, DateTimeOffset? server)
{
if (!Monitor.TryEnter(_gate)) { Signal(ticket); return false; }
try
{
var partitionEpoch = Interlocked.Read(ref _epoch);
if (_disposed || !Current(ticket, out var state) || sequence <= state.LastSubmitted) return false;
if (_queuedControls >= _hub.Limits.MaxControlItemsPerPartition || !_hub.Resources.TryReserve(ControlOverhead)) { InvalidatePartition(); return false; }
var wasReady = state.Readiness == DataReadiness.Ready;
state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); state.Barrier = sequence; state.LastSubmitted = sequence;
_queue.Enqueue(new Pending(ticket, sequence, ++_ordinal, status, source, server, wasReady, ControlOverhead) { AdmissionEpoch = state.InvalidationVersion, PartitionEpoch = partitionEpoch }); _queuedControls++;
_hub.Schedule(this); return true;
}
finally { Monitor.Exit(_gate); }
}
internal bool TryRemove(SourceTicket ticket, long sequence)
{
if (!Monitor.TryEnter(_gate)) { Signal(ticket, retired: true); return false; }
try
{
// Retirement must still be able to release a source after its shared fence closed.
if (_disposed || !_sources.TryGetValue(ticket.Key, out var state)) return false;
ApplyGate(state); ApplyPartitionEpoch(state);
if (state.Removed || state.Ticket != ticket || Volatile.Read(ref state.Gate.Retired) != 0 || sequence <= state.LastSubmitted) return false;
if (_queuedControls >= _hub.Limits.MaxControlItemsPerPartition || !_hub.Resources.TryReserve(ControlOverhead))
{ state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); RequestReclaim(); InvalidatePartition(); return false; }
state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); state.LastSubmitted = sequence; ReleaseCache(state);
RequestReclaim();
_queue.Enqueue(new Pending(ticket, sequence, ++_ordinal, ControlOverhead) { PartitionEpoch = _epoch }); _queuedControls++;
_hub.Schedule(this); return true;
}
finally { Monitor.Exit(_gate); }
}
internal void Schedule()
{
if (Interlocked.Exchange(ref _scheduled, 1) == 0)
ThreadPool.QueueUserWorkItem(static p => ((SamplePartition)p!).Run(), this);
}
private void Run()
{
try { Drain(); }
finally
{
Volatile.Write(ref _scheduled, 0);
lock (_gate) if (!_disposed && (_cleanedEpoch != _epoch || Volatile.Read(ref _retiredSweepRequested) != 0 || Volatile.Read(ref _reclaimRequested) != 0 || _queue.Count != 0 || _dirty.Count != 0)) Schedule();
}
}
internal void Drain()
{
lock (_gate)
{
CleanupInvalidatedEpoch();
CleanupRetiredSources();
while (!_disposed && (_queue.Count != 0 || _dirty.Count != 0))
{
Pending? dirty = null;
foreach (var value in _dirty.Values) if (dirty is null || value.Ordinal < dirty.Ordinal) dirty = value;
Pending p;
if (dirty is not null && (_queue.Count == 0 || dirty.Ordinal < _queue.Peek().Ordinal))
{ p = dirty; _dirty.Remove(p.Ticket.Key); }
else
{ p = _queue.Dequeue(); if (p.IsControl) _queuedControls--; else _queuedValues--; }
if (p.PartitionEpoch != _epoch || !Current(p.Ticket, out var state) || p.AdmissionEpoch != state.InvalidationVersion || p.Sequence <= state.LastApplied)
{ ReleasePending(p); continue; }
state.LastApplied = p.Sequence;
if (p.Sample is not null)
{
ReleaseCache(state); state.Sample = p.Sample; state.SampleCharge = p.Charge; state.Received = p.Received;
state.Readiness = p.Sequence < state.Barrier ? DataReadiness.Invalidated : DataReadiness.Ready;
}
else
{
if (p.IsStatus && state.Sample is not null)
{
var old = state.Sample;
// Missing timestamps on a status-only event mean no new acquisition timestamp.
state.Sample = old with { StatusCode = p.Status,
SourceTimestampUtc = p.SourceTimestamp ?? old.SourceTimestampUtc,
ServerTimestampUtc = p.ServerTimestamp ?? old.ServerTimestampUtc, Version = p.Sequence };
state.Readiness = p.WasReady ? DataReadiness.Ready : DataReadiness.Invalidated;
}
else if (state.Sample is null) state.Readiness = DataReadiness.WaitingForInitialData;
_hub.Resources.Release(p.Charge);
}
RecordChange(p.Ticket.Key);
}
ReclaimTombstones();
}
}
private void RecordChange(BackingSourceKey key)
{
_watermark++;
if (_changes.Count == _hub.Limits.MaxSnapshotCatchUpItems)
{ _changes.Dequeue(); _hub.Resources.Release(ChangeOverhead); }
if (!_hub.Resources.TryReserve(ChangeOverhead)) { InvalidatePartition(); return; }
_changes.Enqueue((_watermark, key));
}
internal void InvalidatePartition()
{
Interlocked.Increment(ref _epoch);
_hub.Schedule(this);
}
private void ApplyPartitionEpoch(SourceState state)
{
if (state.PartitionEpoch == _epoch) return;
InvalidateSource(state);
state.PartitionEpoch = _epoch;
}
private void CleanupInvalidatedEpoch()
{
var epoch = Interlocked.Read(ref _epoch);
if (_cleanedEpoch == epoch) return;
foreach (var pair in _sources) ApplyPartitionEpoch(pair.Value);
while (_changes.TryDequeue(out _)) _hub.Resources.Release(ChangeOverhead);
_cleanedEpoch = epoch;
}
private void CleanupRetiredSources()
{
if (Interlocked.Exchange(ref _retiredSweepRequested, 0) == 0) return;
foreach (var pair in _sources)
{
var state = pair.Value;
if (Volatile.Read(ref state.Gate.Retired) == 0) continue;
ApplyGate(state);
state.Removed = true;
InvalidateSource(state);
RequestReclaim();
}
}
private void RequestReclaim() { Interlocked.Exchange(ref _reclaimRequested, 1); _hub.Schedule(this); }
private void ReclaimTombstones()
{
if (Interlocked.Exchange(ref _reclaimRequested, 0) == 0) return;
foreach (var pair in _sources)
{
var state = pair.Value;
if (!state.Removed || Volatile.Read(ref state.Readers) != 0 || Volatile.Read(ref state.Reservations) != 0 || Volatile.Read(ref state.Snapshots) != 0) continue;
if (_sources.TryRemove(pair.Key, out var removed) && ReferenceEquals(removed, state))
RetireSourceState(state);
}
}
private void RetireSourceState(SourceState state)
{
state.Ticket.Binding!.Retire();
Interlocked.Exchange(ref state.Gate.Retired, 1);
if (Interlocked.Exchange(ref state.RegistryRetired, 1) == 0) ReleaseMetadataOwner(state);
}
private void ReleaseMetadataOwner(SourceState state)
{
if (Interlocked.Decrement(ref state.MetadataOwners) != 0) return;
_hub.Resources.Release(state.SourceCharge);
_hub.UntrackSource();
}
private void ReleaseCache(SourceState state) { if (state.Sample is not null) { state.Sample.Dispose(); state.Sample = null; _hub.Resources.Release(state.SampleCharge); state.SampleCharge = 0; } }
private void ReleasePending(Pending p) { p.Sample?.Dispose(); _hub.Resources.Release(p.Charge); }
internal CachedSourceRead Read(SourceTicket ticket) => Read(ticket, out _);
internal CachedSourceRead Read(SourceTicket ticket, out long watermark)
{
lock (_gate)
{
watermark = _watermark;
if (_disposed || !Current(ticket, out var state)) return _hub.EmptyRead(DataItemStatus.NotFound, DataReadiness.Unavailable, _epoch);
if (state.Readiness != DataReadiness.Ready || state.Sample is null)
return _hub.EmptyRead(state.Readiness == DataReadiness.WaitingForInitialData ? DataItemStatus.WaitingForInitialData : DataItemStatus.Unavailable, state.Readiness, _epoch);
var gate = Volatile.Read(ref state.Gate);
var signal = Volatile.Read(ref gate.Invalidated);
if (signal != state.AppliedInvalidations) return _hub.EmptyRead(DataItemStatus.Unavailable, DataReadiness.Invalidated, _epoch);
var charge = checked(state.Sample.Value.EstimatedRetainedBytes + PartitionedSampleHub.ReferenceOverhead);
if (!_hub.Resources.TryReserve(charge)) return _hub.EmptyRead(DataItemStatus.ResourceExhausted, DataReadiness.Unavailable, _epoch);
Interlocked.Increment(ref state.Readers);
Interlocked.Increment(ref state.MetadataOwners);
return new CachedSourceRead(_hub.Resources, DataItemStatus.Good, state.Readiness,
state.Sample with { Value = state.Sample.Value.Retain() }, state.LastApplied, state.PartitionEpoch, state.Received, charge,
this, state, gate, Volatile.Read(ref state.InvalidationVersion), signal, _routingEpoch);
}
}
internal void ReleaseRead(object source)
{
var state = (SourceState)source;
var lastRead = Interlocked.Decrement(ref state.Readers) == 0;
ReleaseMetadataOwner(state);
if (lastRead && Volatile.Read(ref state.Gate.Retired) != 0 && !Volatile.Read(ref _disposed)) RequestReclaim();
}
internal bool IsReadValid(object source, object sourceGate, long sourceVersion, long sourceSignal, long partitionEpoch, long routingEpoch)
{
var state = (SourceState)source;
var gate = (SourceGate)sourceGate;
return !_hub.IsDisposed && _hub.RoutingEpoch == routingEpoch && Interlocked.Read(ref _epoch) == partitionEpoch &&
ReferenceEquals(gate, Volatile.Read(ref state.Gate)) && !gate.Binding.IsRetired && Volatile.Read(ref gate.Retired) == 0 &&
Volatile.Read(ref gate.Invalidated) == sourceSignal && Volatile.Read(ref state.InvalidationVersion) == sourceVersion &&
Volatile.Read(ref state.Fence)?.IsRetired != true;
}
internal bool Capture(IEnumerable<SourceTicket> tickets, Dictionary<SourceTicket, SnapshotItem> items, out long watermark, out long epoch, ref long charge, long limit)
{
lock (_gate)
{
watermark = _watermark; epoch = _epoch;
if (_disposed) return false;
foreach (var ticket in tickets)
{
var exists = Current(ticket, out var state);
var ready = exists && state.Readiness == DataReadiness.Ready && state.Sample is not null;
var bytes = PartitionedSampleHub.ReferenceOverhead + (ready ? state.Sample!.Value.EstimatedRetainedBytes : 0);
if (bytes > limit - charge || !_hub.Resources.TryReserve(bytes)) return false;
charge += bytes;
var sample = ready ? state.Sample! with { Value = state.Sample.Value.Retain() } : null;
if (exists) { Interlocked.Increment(ref state.Snapshots); Interlocked.Increment(ref state.MetadataOwners); }
items.Add(ticket, new SnapshotItem(exists ? state.Readiness : DataReadiness.Unavailable,
exists ? (ready ? DataItemStatus.Good : DataItemStatus.Unavailable) : DataItemStatus.NotFound, sample,
exists ? state.InvalidationVersion : -1) { Owner = exists ? this : null, Source = exists ? state : null });
}
return true;
}
}
internal void ReleaseSnapshot(object source)
{
var state = (SourceState)source;
var lastSnapshot = Interlocked.Decrement(ref state.Snapshots) == 0;
ReleaseMetadataOwner(state);
if (lastSnapshot && Volatile.Read(ref state.Gate.Retired) != 0 && !Volatile.Read(ref _disposed)) RequestReclaim();
}
internal bool IsSnapshotCurrent(long epoch, long watermark, IEnumerable<KeyValuePair<SourceTicket, SnapshotItem>> tickets)
{
lock (_gate)
{
if (_disposed || epoch != _epoch || (_changes.Count > 0 && watermark < _changes.Peek().Version - 1)) return false;
return tickets.All(t => Current(t.Key, out var state) && state.InvalidationVersion == t.Value.InvalidationVersion);
}
}
internal long CurrentWatermark { get { lock (_gate) return _watermark; } }
public void Dispose()
{
lock (_gate)
{
if (_disposed) return; _disposed = true; InvalidatePartition(); CleanupInvalidatedEpoch();
while (_queue.TryDequeue(out var p)) ReleasePending(p);
foreach (var p in _dirty.Values) ReleasePending(p);
_dirty.Clear(); _queuedValues = 0; _queuedControls = 0;
foreach (var pair in _sources) { pair.Value.Removed = true; RetireSourceState(pair.Value); }
_sources.Clear();
}
}
private sealed class SourceGate(SourceGeneration generation, SourceBindingFence binding)
{ public readonly SourceGeneration Generation = generation; public readonly SourceBindingFence Binding = binding; public long Invalidated; public int Retired; }
private sealed class SourceState(SourceTicket ticket, long sourceCharge, ProducerFence? fence, long partitionEpoch)
{
public SourceTicket Ticket = ticket; public SourceGeneration Generation = ticket.Generation; public readonly long SourceCharge = sourceCharge;
public SourceGate Gate = new(ticket.Generation, ticket.Binding!);
public ProducerFence? Fence = fence; public long PartitionEpoch = partitionEpoch;
public long AppliedInvalidations;
// The registry owns one metadata reference; each retained read, snapshot and reservation owns one more.
public int MetadataOwners = 1; public int RegistryRetired;
public int Readers; public int Reservations; public int Snapshots;
public bool Removed; public DataReadiness Readiness = DataReadiness.WaitingForInitialData;
public DataSample? Sample; public long SampleCharge; public long Received;
public long LastSubmitted; public long LastApplied; public long Barrier; public long InvalidationVersion;
}
private sealed class Pending
{
public Pending(SourceTicket ticket, long sequence, long ordinal, DataSample sample, long charge, long received)
{ Ticket = ticket; Sequence = sequence; Ordinal = ordinal; Sample = sample; Charge = charge; Received = received; }
public Pending(SourceTicket ticket, long sequence, long ordinal, uint status, DateTimeOffset? source, DateTimeOffset? server, bool wasReady, long charge)
{ Ticket = ticket; Sequence = sequence; Ordinal = ordinal; Status = status; SourceTimestamp = source; ServerTimestamp = server; WasReady = wasReady; Charge = charge; IsControl = true; IsStatus = true; }
public Pending(SourceTicket ticket, long sequence, long ordinal, long charge) { Ticket = ticket; Sequence = sequence; Ordinal = ordinal; Charge = charge; IsControl = true; }
public SourceTicket Ticket; public long Sequence; public long Ordinal; public DataSample? Sample; public long Charge; public long Received; public long AdmissionEpoch; public long PartitionEpoch;
public bool IsControl; public bool IsStatus; public uint Status; public DateTimeOffset? SourceTimestamp; public DateTimeOffset? ServerTimestamp; public bool WasReady;
}
private sealed class Reservation(SamplePartition partition, SourceState state, SourceTicket ticket, long estimate, long charge,
long invalidationVersion, long partitionEpoch) : IIngressReservation
{
private int _completed;
public bool TryCommit(DataSample owned, long sequence)
{ ArgumentNullException.ThrowIfNull(owned); return Interlocked.Exchange(ref _completed, 1) == 0 && partition.Commit(state, ticket, estimate, charge, invalidationVersion, partitionEpoch, owned, sequence); }
public void Dispose() { if (Interlocked.Exchange(ref _completed, 1) == 0) partition.Abandon(state, charge); }
}
}
@@ -0,0 +1,91 @@
using System.Collections.ObjectModel;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Frozen item state. Its sample belongs to the containing snapshot.</summary>
public sealed record SnapshotItem(DataReadiness Readiness, DataItemStatus Status, DataSample? Sample, long InvalidationVersion)
{
internal SamplePartition? Owner { get; init; }
internal object? Source { get; init; }
internal void ReleaseSource() { if (Owner is not null && Source is not null) Owner.ReleaseSnapshot(Source); }
}
/// <summary>Retained immutable snapshots and per-partition catch-up watermarks.</summary>
public sealed class SnapshotLease : IDisposable
{
private readonly PartitionedSampleHub _hub;
private readonly SamplePartition[] _partitions;
private readonly long _routingEpoch;
private readonly long _charge;
private readonly int _itemCount;
private readonly Dictionary<int, long> _epochs;
private readonly Dictionary<SourceTicket, int> _owners;
private readonly Dictionary<SourceTicket, long> _positions;
private readonly Dictionary<SourceTicket, long> _versions;
private readonly object _gate = new();
private CancellationTokenRegistration _cancellation;
private ITimer? _timer;
private int _released;
internal SnapshotLease(PartitionedSampleHub hub, Dictionary<SourceTicket, SnapshotItem> items,
Dictionary<int, long> watermarks, Dictionary<int, long> epochs, SamplePartition[] partitions,
long routingEpoch, long charge, int itemCount, TimeSpan lifetime, CancellationToken cancellationToken)
{
_hub = hub; _partitions = partitions; _routingEpoch = routingEpoch; _charge = charge; _itemCount = itemCount;
_epochs = epochs;
Items = new ReadOnlyDictionary<SourceTicket, SnapshotItem>(items);
Watermarks = new ReadOnlyDictionary<int, long>(watermarks);
_owners = items.Keys.ToDictionary(t => t, t => PartitionedSampleHub.GetPartitionFor(t.Key, partitions.Length));
_positions = items.Keys.ToDictionary(t => t, t => watermarks[_owners[t]]);
_versions = items.ToDictionary(p => p.Key, p => p.Value.Sample?.Version ?? 0);
_timer = hub.Clock.CreateTimer(static o => ((SnapshotLease)o!).Dispose(), this, lifetime, Timeout.InfiniteTimeSpan);
_cancellation = cancellationToken.Register(static o => ((SnapshotLease)o!).Dispose(), this);
}
public IReadOnlyDictionary<SourceTicket, SnapshotItem> Items { get; }
public IReadOnlyDictionary<int, long> Watermarks { get; }
public bool IsReset
{
get
{
lock (_gate)
{
if (_released != 0) return true;
if (_hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch) { Release(); return true; }
foreach (var group in Items.GroupBy(p => _owners[p.Key]))
{
var watermark = group.Min(p => _positions[p.Key]);
if (!_partitions[group.Key].IsSnapshotCurrent(_epochs[group.Key], watermark, group)) { Release(); return true; }
}
return false;
}
}
}
/// <summary>Returns the latest newer sample as an independently disposable, globally charged read.</summary>
public bool TryReadDelta(SourceTicket ticket, out CachedSourceRead? delta)
{
delta = null;
lock (_gate)
{
if (IsReset || !_owners.TryGetValue(ticket, out var owner)) return false;
var read = _partitions[owner].Read(ticket, out var readWatermark);
if (read.Status == DataItemStatus.ResourceExhausted) { read.Dispose(); Release(); return false; }
if (read.Readiness != DataReadiness.Ready || read.Sample is null) { read.Dispose(); Release(); return false; }
if (IsReset) { read.Dispose(); return false; }
var version = read.Sample.Version;
if (version <= _versions[ticket]) { read.Dispose(); return false; }
_versions[ticket] = version;
_positions[ticket] = readWatermark;
delta = read; return true;
}
}
private void Release()
{
if (Interlocked.Exchange(ref _released, 1) != 0) return;
_timer?.Dispose(); _cancellation.Unregister();
foreach (var item in Items.Values) { item.Sample?.Dispose(); item.ReleaseSource(); }
_hub.Resources.Release(_charge); _hub.UntrackSnapshotItems(_itemCount);
_hub.ForgetSnapshot(this);
}
public void Dispose() { lock (_gate) Release(); }
}
@@ -0,0 +1,490 @@
using System.Collections.Concurrent;
using System.Globalization;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Trusted acquisition shape; aliases share this source-level descriptor.</summary>
public readonly record struct SourceValueShape(DataValueKind Kind, DataValueKind? ElementKind, int Rank)
{
public static SourceValueShape FromDriverType(string dataType, bool isArray)
{
var kind = dataType switch
{
"Boolean" or "Bool" => DataValueKind.Boolean,
"SByte" => DataValueKind.Int8, "Byte" => DataValueKind.UInt8,
"Int16" => DataValueKind.Int16, "UInt16" => DataValueKind.UInt16,
"Int32" or "Int" => DataValueKind.Int32, "UInt32" or "UInt" => DataValueKind.UInt32,
"Int64" => DataValueKind.Int64, "UInt64" => DataValueKind.UInt64,
"Float" => DataValueKind.Float, "Double" => DataValueKind.Double,
"String" => DataValueKind.String, "ByteString" => DataValueKind.Bytes,
"DateTime" => DataValueKind.Timestamp, "Guid" => DataValueKind.Guid,
_ => DataValueKind.Unspecified
};
return isArray ? new(DataValueKind.Array, kind, 1) : new(kind, null, -1);
}
}
/// <summary>Constructs acquisition identities independently of catalog views and principals.</summary>
public static class SourceKey
{
public static BackingSourceKey ForDriver(string cluster, string driver, string reference, string node, string incarnation) =>
new(cluster.ToUpperInvariant(), "driver", string.Concat(driver.Length.ToString(CultureInfo.InvariantCulture), ":", driver, reference), node, incarnation);
public static BackingSourceKey ForVirtual(string cluster, string virtualTagId, string node, string incarnation) =>
new(cluster.ToUpperInvariant(), "virtual", virtualTagId, node, incarnation);
internal static bool TryDriver(BackingSourceKey key, out string driver, out string reference)
{
driver = reference = string.Empty;
if (key.SourceKind != "driver") return false;
var colon = key.StableSourceId.IndexOf(':');
if (colon <= 0 || !int.TryParse(key.StableSourceId.AsSpan(0, colon), NumberStyles.None, CultureInfo.InvariantCulture, out var length) ||
length < 0 || length > key.StableSourceId.Length - colon - 1) return false;
driver = key.StableSourceId.Substring(colon + 1, length);
reference = key.StableSourceId[(colon + 1 + length)..];
return true;
}
}
/// <summary>Sequences source data and lifecycle changes before the asynchronous actor boundary.</summary>
public sealed class SourceSamplePublisher
{
private readonly ISourceSampleHub _hub;
private readonly Func<ServingIdentity?> _serving;
private readonly string? _originClusterId;
private readonly object _gate = new();
private readonly Dictionary<BackingSourceKey, SourceTicket> _tickets = new();
private readonly Dictionary<(string Driver, string Reference), BackingSourceKey> _drivers = new();
private readonly Dictionary<string, BackingSourceKey> _virtuals = new(StringComparer.Ordinal);
private sealed class SourceSlot
{
public readonly object Gate = new();
public SourceBinding? Current;
public long Sequence;
public int RepairQueued;
public int RepairAttempts;
}
private sealed class SourceBinding(SourceTicket ticket, SourceSlot slot, ProducerFence? producer, SourceValueShape? shape)
{
public SourceTicket Ticket { get; } = ticket;
public SourceSlot Slot { get; } = slot;
public ProducerFence? Producer { get; } = producer;
public SourceValueShape? Shape { get; } = shape;
public int InFlight;
public bool Active => Producer is null || !Producer.IsRetired;
}
private readonly ConcurrentDictionary<BackingSourceKey, SourceSlot> _slots = new();
private readonly ConcurrentDictionary<(string Driver, string Reference), SourceBinding> _driverRoutes = new();
private readonly Dictionary<(string Driver, string Reference), SourceValueShape> _driverShapes = new();
private const int MaxRegisteredDriverShapes = 100_000;
private const int MaxProducerIncarnations = 100_000;
private readonly ConcurrentDictionary<string, SourceBinding> _virtualRoutes = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, ProducerFence> _driverIncarnations = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, ProducerFence> _virtualIncarnations = new(StringComparer.Ordinal);
private readonly ConcurrentQueue<SourceSlot> _repairQueue = new();
private const int MaxPendingRepairs = 4096;
private int _repairCount;
private int _repairWorkerScheduled;
private readonly Timer _repairTimer;
private long _nextDriverIncarnation;
public SourceSamplePublisher(ISourceSampleHub hub, ServingIdentity serving) : this(hub, () => serving, null) { }
public SourceSamplePublisher(ISourceSampleHub hub, Func<ServingIdentity?> serving, string? originClusterId = null)
{
_hub = hub ?? throw new ArgumentNullException(nameof(hub));
_serving = serving ?? throw new ArgumentNullException(nameof(serving));
_originClusterId = originClusterId;
_repairTimer = new Timer(static state => ((SourceSamplePublisher)state!).ScheduleRepairWorker(), this,
Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
}
public SourceTicket Bind(BackingSourceKey key, SourceGeneration generation)
{
var ticket = new SourceTicket(key, generation);
lock (_gate)
{
if (!_slots.TryGetValue(key, out var slot)) slot = new SourceSlot();
lock (slot.Gate)
{
ProducerFence? producer = null;
if (SourceKey.TryDriver(key, out var driver, out var reference))
_driverIncarnations.TryGetValue(driver, out producer);
else if (key.SourceKind == "virtual")
_virtualIncarnations.TryGetValue(key.StableSourceId, out producer);
if (producer is not null && producer.Incarnation != generation.Incarnation) producer = null;
if (!_hub.TryBind(ticket, producer)) throw new InvalidOperationException("The source generation could not be bound.");
_slots.TryAdd(key, slot);
_nextDriverIncarnation = Math.Max(_nextDriverIncarnation, generation.Incarnation);
SourceValueShape? shape = null;
if (SourceKey.TryDriver(key, out var shapeDriver, out var shapeRef) &&
_driverShapes.TryGetValue((shapeDriver, shapeRef), out var registeredShape)) shape = registeredShape;
var binding = new SourceBinding(ticket, slot, producer, shape);
_tickets[key] = ticket;
Volatile.Write(ref slot.Current, binding);
if (SourceKey.TryDriver(key, out driver, out reference))
{
_drivers[(driver, reference)] = key;
_driverRoutes[(driver, reference)] = binding;
}
else if (key.SourceKind == "virtual")
{
_virtuals[key.StableSourceId] = key;
_virtualRoutes[key.StableSourceId] = binding;
}
return ticket;
}
}
}
public bool TryCapture(BackingSourceKey key, out SourceTicket ticket)
{
ticket = default;
if (!_slots.TryGetValue(key, out var slot)) return false;
var binding = Volatile.Read(ref slot.Current);
if (binding is null || !binding.Active) return false;
ticket = binding.Ticket;
return true;
}
public bool TryCaptureDriver(string driver, string reference, out SourceTicket ticket)
{
ticket = default;
if (!_driverRoutes.TryGetValue((driver, reference), out var binding) || !binding.Active ||
!ReferenceEquals(Volatile.Read(ref binding.Slot.Current), binding)) return false;
ticket = binding.Ticket;
return true;
}
public bool TryCaptureDriver(string driver, string reference, long incarnation, out SourceTicket ticket)
{
ticket = default;
if (!_driverIncarnations.TryGetValue(driver, out var producer) || producer.Incarnation != incarnation || producer.IsRetired ||
!_driverRoutes.TryGetValue((driver, reference), out var binding) || !ReferenceEquals(binding.Producer, producer) ||
!ReferenceEquals(Volatile.Read(ref binding.Slot.Current), binding)) return false;
ticket = binding.Ticket;
return !producer.IsRetired;
}
public long RegisterDriverIncarnation(string driver)
{
lock (_gate)
{
if (!_driverIncarnations.ContainsKey(driver) && _driverIncarnations.Count >= MaxProducerIncarnations)
throw new InvalidOperationException("Driver producer registry is full.");
if (_driverIncarnations.TryGetValue(driver, out var old)) old.Retire();
var token = checked(++_nextDriverIncarnation);
_driverIncarnations[driver] = new ProducerFence(token);
return token;
}
}
public bool IsDriverIncarnationActive(string driver, long incarnation) =>
_driverIncarnations.TryGetValue(driver, out var producer) && producer.Incarnation == incarnation && !producer.IsRetired;
public void RetireCurrentDriver(string driver)
{ if (_driverIncarnations.TryGetValue(driver, out var producer)) RetireDriver(driver, producer.Incarnation); }
public bool RegisterDriverShape(string driver, string reference, SourceValueShape shape)
{
lock (_gate)
{
var key = (driver, reference);
if (_driverShapes.TryGetValue(key, out var old) && old == shape) return true;
if (!_driverShapes.ContainsKey(key) && _driverShapes.Count >= MaxRegisteredDriverShapes) return false;
_driverShapes[key] = shape;
if (_driverRoutes.TryGetValue(key, out var binding)) TryRebind(binding.Ticket, out _);
return true;
}
}
public void ForgetDriverShape(string driver, string reference)
{ lock (_gate) _driverShapes.Remove((driver, reference)); }
public bool EnsureDriverBinding(string cluster, string driver, string reference, long incarnation)
{
// A slow control-plane reconciliation or retirement must not stall legacy acquisition.
if (!Monitor.TryEnter(_gate)) return false;
try
{
if (!_driverIncarnations.TryGetValue(driver, out var producer) || producer.Incarnation != incarnation || producer.IsRetired) return false;
if (!_driverShapes.ContainsKey((driver, reference))) return false;
var serving = _serving();
if (serving is null || string.IsNullOrWhiteSpace(cluster)) return false;
var key = SourceKey.ForDriver(cluster, driver, reference, serving.NodeId, serving.Incarnation);
if (!_slots.TryGetValue(key, out var slot)) return EnsureBinding(key, incarnation);
if (!Monitor.TryEnter(slot.Gate))
{
var binding = Volatile.Read(ref slot.Current);
if (binding?.Producer is { } current && ReferenceEquals(current, producer) && !current.IsRetired)
_hub.Invalidate(binding.Ticket, "source binding contention");
return false;
}
try { return EnsureBinding(key, incarnation); }
finally { Monitor.Exit(slot.Gate); }
}
finally { Monitor.Exit(_gate); }
}
public void RetireDriver(string driver, long incarnation)
{
// The hub sees the same fence. Reads and snapshots are denied before the slow per-tag walk.
if (!_driverIncarnations.TryGetValue(driver, out var producer) || producer.Incarnation != incarnation) return;
producer.Retire();
lock (_gate)
{
if (!_driverIncarnations.TryGetValue(driver, out var current) || !ReferenceEquals(current, producer)) return;
_driverIncarnations.TryRemove(driver, out _);
foreach (var key in _drivers.Where(x => x.Key.Driver == driver).Select(x => x.Value).ToArray())
if (_tickets.TryGetValue(key, out var ticket)) TryRemove(ticket);
}
}
public void PublishDriverStatus(string driver, uint status)
{
lock (_gate)
foreach (var key in _drivers.Where(x => x.Key.Driver == driver).Select(x => x.Value).ToArray())
if (_tickets.TryGetValue(key, out var ticket)) TryPublishStatus(ticket, status, out _);
}
public bool TryCaptureVirtual(string id, out SourceTicket ticket)
{
ticket = default;
if (!_virtualRoutes.TryGetValue(id, out var binding) || !binding.Active ||
!ReferenceEquals(Volatile.Read(ref binding.Slot.Current), binding)) return false;
ticket = binding.Ticket;
return true;
}
public long RegisterVirtualIncarnation(string id)
{
lock (_gate)
{
if (!_virtualIncarnations.ContainsKey(id) && _virtualIncarnations.Count >= MaxProducerIncarnations)
throw new InvalidOperationException("Virtual producer registry is full.");
if (_virtualIncarnations.TryGetValue(id, out var old)) RetireVirtualIncarnation(id, old.Incarnation);
var token = checked(++_nextDriverIncarnation);
_virtualIncarnations[id] = new ProducerFence(token);
return token;
}
}
public bool IsVirtualIncarnationActive(string id, long incarnation) =>
_virtualIncarnations.TryGetValue(id, out var producer) && producer.Incarnation == incarnation && !producer.IsRetired;
public void RetireCurrentVirtual(string id)
{ if (_virtualIncarnations.TryGetValue(id, out var producer)) RetireVirtualIncarnation(id, producer.Incarnation); }
public bool EnsureVirtualBinding(string id, long incarnation)
{
lock (_gate)
{
if (!_virtualIncarnations.TryGetValue(id, out var producer) || producer.Incarnation != incarnation || producer.IsRetired) return false;
var serving = _serving();
if (serving is null) return false;
if (_virtuals.TryGetValue(id, out var existing)) return EnsureBinding(existing, incarnation);
if (string.IsNullOrWhiteSpace(_originClusterId)) return false;
return EnsureBinding(SourceKey.ForVirtual(_originClusterId, id, serving.NodeId, serving.Incarnation), incarnation);
}
}
private bool EnsureBinding(BackingSourceKey key, long incarnation)
{
if (_tickets.TryGetValue(key, out var existing))
{
if (existing.Generation.Incarnation == incarnation && _hub.IsTicketCurrentNonBlocking(existing)) return true;
if (existing.Generation.Incarnation == incarnation)
{
try { Bind(key, existing.Generation with { Lifecycle = checked(existing.Generation.Lifecycle + 1) }); return true; }
catch (InvalidOperationException) { _hub.Invalidate(existing, "source rebind unavailable"); return false; }
}
// A failed removal has already retired/fenced the old generation in the hub.
TryRemove(existing);
}
try { Bind(key, new SourceGeneration(incarnation, 1)); return true; }
catch (InvalidOperationException) { return false; }
}
public void RetireVirtualIncarnation(string id, long incarnation)
{
if (!_virtualIncarnations.TryGetValue(id, out var producer) || producer.Incarnation != incarnation) return;
producer.Retire();
lock (_gate)
if (_virtualIncarnations.TryGetValue(id, out var current) && ReferenceEquals(current, producer))
{
_virtualIncarnations.TryRemove(id, out _);
if (_virtualRoutes.TryGetValue(id, out var binding) && ReferenceEquals(binding.Producer, producer))
TryRemove(binding.Ticket);
}
}
public bool TryCaptureVirtual(string id, long incarnation, out SourceTicket ticket)
{
ticket = default;
if (!_virtualIncarnations.TryGetValue(id, out var producer) || producer.Incarnation != incarnation || producer.IsRetired ||
!_virtualRoutes.TryGetValue(id, out var binding) || !ReferenceEquals(binding.Producer, producer) ||
!ReferenceEquals(Volatile.Read(ref binding.Slot.Current), binding)) return false;
ticket = binding.Ticket;
return !producer.IsRetired;
}
public bool TryPublish(SourceTicket ticket, DataValueSnapshot snapshot)
{
if (!_slots.TryGetValue(ticket.Key, out var slot)) return false;
var binding = Volatile.Read(ref slot.Current);
if (binding is null || binding.Ticket != ticket || !binding.Active) return false;
Interlocked.Increment(ref binding.InFlight);
IIngressReservation? reservation = null;
DataValue? value = null;
DataSample? sample = null;
try
{
if (!binding.Active || !ReferenceEquals(Volatile.Read(ref slot.Current), binding)) return false;
var size = OwnedDataSample.Estimate(snapshot.Value, binding.Shape);
if (!_hub.TryReserveIngress(ticket, size, out reservation) || reservation is null)
{
_hub.Invalidate(ticket, "source ingress capacity");
if (!_hub.IsTicketCurrentNonBlocking(ticket)) ScheduleRepair(slot, ticket);
return false;
}
value = OwnedDataSample.Copy(snapshot.Value, binding.Shape);
if (!Monitor.TryEnter(slot.Gate))
{ _hub.Invalidate(ticket, "source serialization contention"); return false; }
try
{
if (!binding.Active || !ReferenceEquals(Volatile.Read(ref slot.Current), binding)) return false;
var serving = _serving();
if (serving is null || serving.NodeId != ticket.Key.ServingNodeId || serving.Incarnation != ticket.Key.ServingIncarnation ||
string.IsNullOrWhiteSpace(serving.Role) || serving.CatalogEpoch < 0 || serving.AuthorityEpoch < 0)
{ _hub.Invalidate(ticket, "serving identity unavailable"); return false; }
var sequence = checked(++slot.Sequence);
sample = new DataSample(value, snapshot.StatusCode, OwnedDataSample.Timestamp(snapshot.SourceTimestampUtc),
OwnedDataSample.Timestamp(snapshot.ServerTimestampUtc), serving, sequence);
value = null;
if (!reservation.TryCommit(sample, sequence))
{
_hub.Invalidate(ticket, "source commit rejected");
if (!_hub.IsTicketCurrentNonBlocking(ticket)) ScheduleRepair(slot, ticket);
return false;
}
sample = null;
return true;
}
finally { Monitor.Exit(slot.Gate); }
}
catch (Exception ex) when (ex is ArgumentException or OverflowException or InvalidOperationException)
{ _hub.Invalidate(ticket, "unsupported or oversized source sample"); return false; }
finally
{
value?.Dispose();
sample?.Dispose();
reservation?.Dispose();
Interlocked.Decrement(ref binding.InFlight);
}
}
/// <summary>Synchronously invalidates a malformed callback's captured source generation.</summary>
public void Invalidate(SourceTicket ticket, string reason) => _hub.Invalidate(ticket, reason);
private void ScheduleRepair(SourceSlot slot, SourceTicket ticket)
{
if (Interlocked.CompareExchange(ref slot.RepairQueued, 1, 0) != 0) return;
if (Interlocked.Increment(ref _repairCount) > MaxPendingRepairs)
{
Interlocked.Decrement(ref _repairCount);
Volatile.Write(ref slot.RepairQueued, 0);
_hub.InvalidatePartitionFor(ticket.Key, "source repair capacity");
return;
}
Volatile.Write(ref slot.RepairAttempts, 0);
_repairQueue.Enqueue(slot);
ScheduleRepairWorker();
}
private void ScheduleRepairWorker()
{
if (Interlocked.CompareExchange(ref _repairWorkerScheduled, 1, 0) == 0)
ThreadPool.QueueUserWorkItem(static state => ((SourceSamplePublisher)state!).RunRepairs(), this);
}
private void RunRepairs()
{
var remaining = Math.Min(64, Volatile.Read(ref _repairCount));
while (remaining-- > 0 && _repairQueue.TryDequeue(out var slot))
{
var binding = Volatile.Read(ref slot.Current);
var completed = binding is null || !binding.Active;
if (!completed)
{
lock (_gate)
{
var current = Volatile.Read(ref slot.Current);
completed = current is null || !current.Active ||
EnsureBinding(current.Ticket.Key, current.Ticket.Generation.Incarnation);
}
}
if (!completed && Interlocked.Increment(ref slot.RepairAttempts) >= 16)
{
var last = Volatile.Read(ref slot.Current);
if (last is not null) _hub.InvalidatePartitionFor(last.Ticket.Key, "source repair exhausted");
completed = true;
}
if (completed)
{
Volatile.Write(ref slot.RepairQueued, 0);
Interlocked.Decrement(ref _repairCount);
}
else _repairQueue.Enqueue(slot);
}
Volatile.Write(ref _repairWorkerScheduled, 0);
if (Volatile.Read(ref _repairCount) > 0)
_repairTimer.Change(TimeSpan.FromMilliseconds(250), Timeout.InfiniteTimeSpan);
}
public bool TryPublishStatus(SourceTicket ticket, uint status, out SourceTicket next)
{
lock (_gate)
{
next = default;
if (!_slots.TryGetValue(ticket.Key, out var slot)) return false;
lock (slot.Gate)
{
var binding = Volatile.Read(ref slot.Current);
if (binding is null || binding.Ticket != ticket || !binding.Active) return false;
next = ticket;
if (Volatile.Read(ref binding.InFlight) > 0)
{
try { next = Bind(ticket.Key, ticket.Generation with { Lifecycle = checked(ticket.Generation.Lifecycle + 1) }); }
catch (InvalidOperationException)
{
_hub.Invalidate(ticket, "source status fence failed");
if (!_hub.IsTicketCurrentNonBlocking(ticket)) ScheduleRepair(slot, ticket);
return false;
}
_hub.Invalidate(next, "status overtook in-flight source sample");
}
if (_hub.TryPublishStatus(next, checked(++slot.Sequence), status, null, null)) return true;
_hub.Invalidate(next, "source status capacity");
if (!_hub.IsTicketCurrentNonBlocking(next)) ScheduleRepair(slot, next);
return false;
}
}
}
public bool TryRemove(SourceTicket ticket)
{
lock (_gate)
{
if (!_slots.TryGetValue(ticket.Key, out var slot)) return false;
lock (slot.Gate)
{
var binding = Volatile.Read(ref slot.Current);
if (binding is null || binding.Ticket != ticket) return false;
Volatile.Write(ref slot.Current, null);
_slots.TryRemove(ticket.Key, out _);
_tickets.Remove(ticket.Key);
if (SourceKey.TryDriver(ticket.Key, out var driver, out var reference))
{ _drivers.Remove((driver, reference)); _driverRoutes.TryRemove((driver, reference), out _); }
else if (ticket.Key.SourceKind == "virtual")
{ _virtuals.Remove(ticket.Key.StableSourceId); _virtualRoutes.TryRemove(ticket.Key.StableSourceId, out _); }
if (_hub.TryRemove(ticket, checked(++slot.Sequence))) return true;
_hub.Invalidate(ticket, "source removal capacity");
return false;
}
}
}
/// <summary>Closes an old physical binding and opens a newer, initially unready generation.</summary>
public bool TryRebind(SourceTicket ticket, out SourceTicket next)
{
lock (_gate)
{
next = default;
if (!TryRemove(ticket)) return false;
var generation = ticket.Generation with { Lifecycle = checked(ticket.Generation.Lifecycle + 1) };
try { next = Bind(ticket.Key, generation); return true; }
catch (InvalidOperationException) { return false; }
}
}
}
@@ -36,6 +36,19 @@ public static partial class DeploymentArtifact
internal sealed partial class ParsedDeploymentArtifact
{
/// <summary>Materialize this node's eligible catalog inputs while the artifact document is alive.</summary>
internal DraftSnapshot? ParseLocalCatalogSnapshot(string nodeId) => ReadDataProjection(nodeId)?.Snapshot;
/// <summary>Legacy artifacts and empty data sections do not require an activated data catalog.</summary>
internal bool ExpectsLocalDataCatalog()
{
var root = Root;
if (root.ValueKind != JsonValueKind.Object) return false;
return new[] { "DataConnections", "DataExports", "RemoteNamespaceMappings" }
.Any(name => root.TryGetProperty(name, out var value)
&& (value.ValueKind != JsonValueKind.Array || value.GetArrayLength() != 0));
}
private static readonly JsonSerializerOptions DataJsonOptions = new()
{
PropertyNameCaseInsensitive = true,
@@ -172,6 +185,7 @@ internal sealed partial class ParsedDeploymentArtifact
UnsTagReferences = ReadTopology<UnsTagReference>(root, "UnsTagReferences"),
VirtualTags = ReadTopology<VirtualTag>(root, "VirtualTags"),
ScriptedAlarms = ReadTopology<ScriptedAlarm>(root, "ScriptedAlarms"),
Scripts = ReadTopology<Script>(root, "Scripts"),
DataConnections = connections,
DataExports = exports,
RemoteNamespaceMappings = mappings,
@@ -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;
@@ -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();
@@ -108,7 +108,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// </param>
public sealed record RebuildAddressSpace(
CorrelationId Correlation, DeploymentId? DeploymentId = null, byte[]? Artifact = null,
bool ReportOutcome = false);
bool ReportOutcome = false, DataConnections.CatalogAttempt? CatalogAttempt = null,
bool StageCatalog = false);
/// <summary>
/// the reply to a <see cref="RebuildAddressSpace"/> carrying
@@ -166,6 +167,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
private readonly object _incarnation = new();
private readonly TestHooks? _hooks;
private readonly DataConnections.CatalogActivation _dataCatalog;
private readonly DataConnections.LocalCatalogCoordinator? _catalogCoordinator;
private long _dataCatalogEpoch;
/// <summary>
@@ -335,7 +337,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
IOpcUaEndpointState? endpointState = null,
WarmRedundancySettings? redundancy = null,
IStandbyProjection? standbyProjection = null,
DataConnections.CatalogActivation? dataCatalog = null) =>
DataConnections.CatalogActivation? dataCatalog = null,
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null) =>
Akka.Actor.Props.Create(() => new OpcUaPublishActor(
sink ?? NullOpcUaAddressSpaceSink.Instance,
serviceLevel ?? NullServiceLevelPublisher.Instance,
@@ -352,7 +355,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
utcNow,
endpointState,
redundancy,
standbyProjection, dataCatalog)).WithDispatcher(DispatcherId);
standbyProjection, dataCatalog, catalogCoordinator)).WithDispatcher(DispatcherId);
/// <summary>Test-only Props that omits the pinned-dispatcher requirement and skips the
/// DPS subscribe so unit tests can spin up the actor on a vanilla TestKit cluster.</summary>
@@ -399,7 +402,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
IOpcUaEndpointState? endpointState = null,
WarmRedundancySettings? redundancy = null,
IStandbyProjection? standbyProjection = null,
DataConnections.CatalogActivation? dataCatalog = null) =>
DataConnections.CatalogActivation? dataCatalog = null,
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null) =>
Akka.Actor.Props.Create(() => new OpcUaPublishActor(
sink ?? NullOpcUaAddressSpaceSink.Instance,
serviceLevel ?? NullServiceLevelPublisher.Instance,
@@ -416,7 +420,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
utcNow,
endpointState,
redundancy,
standbyProjection, dataCatalog));
standbyProjection, dataCatalog, catalogCoordinator));
/// <summary>Test-only Props exposing the deferred-write bound and the plan-step seams.</summary>
internal static Props PropsForTests(
@@ -425,12 +429,14 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
TestHooks? hooks,
int deferredWriteCapacity = DefaultDeferredWriteCapacity,
NodeId? localNode = null,
IDataPlaneAuthoritySink? dataPlaneAuthority = null) =>
IDataPlaneAuthoritySink? dataPlaneAuthority = null,
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null) =>
// CreateBy, not Create(expression): Akka's expression path activates through a PUBLIC constructor, and the
// seam-carrying constructor is internal so the test seams stay off the public API (review M3).
Akka.Actor.Props.CreateBy(new TestProducer(() => new OpcUaPublishActor(
sink, NullServiceLevelPublisher.Instance, false, localNode, null, applier, null, null, null, null,
false, dataPlaneAuthority, null, deferredWriteCapacity, hooks, endpointState: null)));
false, dataPlaneAuthority, null, deferredWriteCapacity, hooks, endpointState: null,
catalogCoordinator: catalogCoordinator)));
/// <summary>Produces the actor through its internal (seam-carrying) constructor, for <see cref="PropsForTests(IOpcUaAddressSpaceSink, AddressSpaceApplier?, TestHooks?, int, NodeId?, IDataPlaneAuthoritySink?)"/>.</summary>
private sealed class TestProducer(Func<OpcUaPublishActor> create) : IIndirectActorProducer
@@ -480,10 +486,11 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
IOpcUaEndpointState? endpointState = null,
WarmRedundancySettings? redundancy = null,
IStandbyProjection? standbyProjection = null,
DataConnections.CatalogActivation? dataCatalog = null)
DataConnections.CatalogActivation? dataCatalog = null,
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null)
: this(sink, serviceLevel, subscribeRedundancyTopic, localNode, dbFactory, applier, dbHealthProbe, staleWindow,
probeFreshnessWindow, healthTickInterval, dbLess, dataPlaneAuthority, utcNow, DefaultDeferredWriteCapacity, hooks: null,
endpointState, redundancy, standbyProjection, dataCatalog)
endpointState, redundancy, standbyProjection, dataCatalog, catalogCoordinator)
{
}
@@ -510,12 +517,14 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
IOpcUaEndpointState? endpointState,
WarmRedundancySettings? redundancy = null,
IStandbyProjection? standbyProjection = null,
DataConnections.CatalogActivation? dataCatalog = null)
DataConnections.CatalogActivation? dataCatalog = null,
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null)
{
_redundancy = redundancy ?? WarmRedundancySettings.Unset;
_standbyProjection = standbyProjection;
_deferred = new DeferredWrites(Math.Max(1, deferredWriteCapacity));
_hooks = hooks;
_catalogCoordinator = catalogCoordinator;
_dataCatalog = dataCatalog ?? hooks?.DataCatalog ?? new DataConnections.CatalogActivation();
_sink = sink;
_dataPlaneAuthority = dataPlaneAuthority;
@@ -743,10 +752,44 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
private void HandleRebuild(RebuildAddressSpace msg)
{
if (_catalogCoordinator is not null && msg.CatalogAttempt is null)
{
var revision = msg.Artifact is { Length: > 0 } bytes
? Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes)) : "unavailable";
msg = msg with { CatalogAttempt = _catalogCoordinator.BeginAttempt(revision), StageCatalog = true };
}
if (msg.Artifact is { Length: > 0 } artifact) CheckRedundancyMode(artifact);
StartRebuild(msg, Sender);
}
private void StageStandaloneCatalog(RebuildAddressSpace msg, ParsedDeploymentArtifact parsed)
{
if (_catalogCoordinator is null || msg.CatalogAttempt is null) return;
msg.CatalogAttempt.SetExpected(parsed.ExpectsLocalDataCatalog());
if (_localNode is null) return;
try
{
var authority = _hooks?.ParseAuthority is { } parse
? parse(parsed, _localNode.Value.Value) : parsed.ParseDataPlaneAuthority(_localNode.Value.Value);
if (!_catalogCoordinator.InstallAuthority(msg.CatalogAttempt, authority)) return;
}
catch (Exception ex)
{
_log.Error(ex, "OpcUaPublish: standalone data authority could not be installed");
return;
}
try
{
if (!string.Equals(_catalogCoordinator.Serving.NodeId, _localNode.Value.Value, StringComparison.Ordinal)) return;
var snapshot = parsed.ParseLocalCatalogSnapshot(_localNode.Value.Value);
if (snapshot is not null) _catalogCoordinator.Stage(msg.CatalogAttempt, snapshot, _localNode.Value.Value);
}
catch (Exception ex)
{
_log.Error(ex, "OpcUaPublish: standalone data catalog could not be staged");
}
}
/// <summary>
/// The entry half of a rebuild, on the actor thread. The raw-sink fallback (no applier) and the
/// no-artifact case complete synchronously; otherwise the artifact parse, the cluster-scoped composition
@@ -771,13 +814,18 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
var desiredRevision = msg.Artifact is { Length: > 0 } desiredBytes
? Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(desiredBytes))
: "unavailable";
_dataCatalogEpoch = _dataCatalog.Begin(desiredRevision);
if (_catalogCoordinator is null) _dataCatalogEpoch = _dataCatalog.Begin(desiredRevision);
// Only a node with NO applier at all (the F10b/dev seam) falls back to the raw-sink rebuild — and that
// fallback WIPES the served address space without re-materialising, so it must NEVER be reached by a
// real driver node that has an applier (that node diff-and-applies from its in-hand bytes below).
if (_applier is null)
{
if (msg.StageCatalog && msg.Artifact is { Length: > 0 } standaloneBytes)
{
try { using var parsed = DeploymentArtifact.Open(standaloneBytes); StageStandaloneCatalog(msg, parsed); }
catch (Exception ex) { _log.Error(ex, "OpcUaPublish: unable to stage standalone data catalog"); }
}
// Every rebuild is traced, whichever path completes it: the applier path opens its span in ApplyPlan
// (the actor-thread half), the two synchronous completions below open their own.
using var span = OtOpcUaTelemetry.StartAddressSpaceRebuildSpan();
@@ -825,7 +873,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
var artifact = msg.Artifact;
var baseComposition = _lastApplied;
var nodeId = _localNode?.Value;
var wantAuthority = _dataPlaneAuthority is not null;
var wantAuthority = _dataPlaneAuthority is not null && _catalogCoordinator is null;
var incarnation = _incarnation;
var hooks = _hooks;
Task.Run<object>(() =>
@@ -835,6 +883,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
// result — and an empty composition is not a benign no-op here (see the no-bytes guard above). The
// throw lands in PlanFailed: logged at Error, _lastApplied untouched, last-known-good still served.
using var parsed = DeploymentArtifact.Open(artifact);
if (msg.StageCatalog) StageStandaloneCatalog(msg, parsed);
// The authority parse is isolated from the address-space plan (review fix I2): before the plan moved
// off-thread a throw here was contained by FeedDataPlaneAuthority's own catch; it must not now
// become PlanFailed and degrade an apply whose topology is perfectly readable.
@@ -1048,6 +1097,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
public object? Value;
public uint Status;
public DateTime TimestampUtc;
public DateTime? OriginalSourceTimestampUtc;
public DateTime? OriginalServerTimestampUtc;
}
private readonly Dictionary<(AddressSpaceRealm, string), VariableEntry> _variables = new();
@@ -1069,6 +1120,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
_variables[key] = new VariableEntry
{
HasValue = true, Value = write.Value, Status = write.StatusCode, TimestampUtc = write.SourceTimestampUtc,
OriginalSourceTimestampUtc = write.OriginalSourceTimestampUtc,
OriginalServerTimestampUtc = write.OriginalServerTimestampUtc,
};
return true;
}
@@ -1110,7 +1163,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
foreach (var ((realm, id), e) in _variables)
{
if (!include((realm, id))) continue;
if (e.HasValue) values.Add(new ValueWrite(id, e.Value, e.Status, e.TimestampUtc, realm));
if (e.HasValue) values.Add(new ValueWrite(id, e.Value, e.Status, e.TimestampUtc, realm,
e.OriginalSourceTimestampUtc, e.OriginalServerTimestampUtc));
else statuses.Add(new StatusWrite(id, e.Status, e.TimestampUtc, realm));
}
@@ -1154,6 +1208,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
catch (Exception ex)
{
_log.Error(ex, "OpcUaPublish: sink.CompleteAddressSpaceApply threw (correlation={Correlation})", msg.Correlation);
outcome = (true, $"address-space completion threw: {ex.Message}");
}
// Land what arrived while the plan was in flight on the nodes the apply just created — before the answer,
@@ -1161,6 +1216,13 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
ReplayDeferredWrites(_replayScope);
_replayScope = ReplayScope.Nothing;
if (msg.CatalogAttempt is not null && _catalogCoordinator is not null)
{
var activated = _catalogCoordinator.Complete(msg.CatalogAttempt, topologySucceeded: !outcome.Degraded);
if (!activated && msg.CatalogAttempt.Expected && !outcome.Degraded)
outcome = (true, "the expected local data catalog could not be activated");
}
if (msg.ReportOutcome)
requester.Tell(new RebuildCompleted(msg.Correlation, msg.DeploymentId, outcome.Degraded, outcome.Reason));
}
@@ -1174,7 +1236,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
try
{
var result = ApplyPlanCore(ready, out var rebuilt);
_dataCatalog.Complete(_dataCatalogEpoch, !result.Degraded && ready.AuthorityError is null);
if (_catalogCoordinator is null)
_dataCatalog.Complete(_dataCatalogEpoch, !result.Degraded && ready.AuthorityError is null);
// What this apply created or reset (see _replayScope). A throwing pass still scopes to what it did.
var conditions = AddedConditions(previous, ready.Composition);
if (rebuilt)
@@ -56,10 +56,14 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
/// §9): re-evaluate once against the latest inputs. Private to the actor.
/// </summary>
private sealed class RunnerRecovered { public static readonly RunnerRecovered Instance = new(); private RunnerRecovered() { } }
private sealed class RetrySourceBinding { public static readonly RetrySourceBinding Instance = new(); private RetrySourceBinding() { } }
private ICancelable? _sourceBindingRetry;
/// <summary>The asynchronous evaluation started by <see cref="Evaluate"/> finished. Private to the actor.</summary>
private sealed record EvaluationCompleted(
Task<VirtualTagEvalResult> Evaluation, uint WorstInputStatus, DateTime TimestampUtc);
Task<VirtualTagEvalResult> Evaluation, uint WorstInputStatus, DateTime TimestampUtc, long ActorIncarnation);
private static long s_actorIncarnation;
private readonly long _actorIncarnation = Interlocked.Increment(ref s_actorIncarnation);
/// <inheritdoc />
public IStash Stash { get; set; } = null!;
@@ -101,9 +105,12 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
/// publishes it (to repair the reset OPC UA node) but must NOT re-record it to the historian — it is a
/// stale value stamped with a fresh deploy-time timestamp, never a real evaluation sample. Defaults to
/// <c>false</c> so every existing construction site stays source-compatible.</param>
public sealed record EvaluationResult(string VirtualTagId, object? Value, DateTime TimestampUtc, CorrelationId Correlation, uint StatusCode = OpcUaStatus.Good, bool IsReassert = false);
public sealed record EvaluationResult(string VirtualTagId, object? Value, DateTime TimestampUtc, CorrelationId Correlation,
uint StatusCode = OpcUaStatus.Good, bool IsReassert = false, bool SourceHandled = false);
private readonly string _virtualTagId;
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? _sourcePublisher;
private long? _sourceIncarnation;
private readonly string _scriptId;
private readonly string _expression;
private readonly IVirtualTagEvaluator _evaluator;
@@ -162,7 +169,9 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
ITelemetryLocalHub? telemetryHub = null,
ScriptLogRateLimiter? failureLogLimiter = null,
bool changeTriggered = true,
int? timerIntervalMs = null) =>
int? timerIntervalMs = null,
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
long? sourceIncarnation = null) =>
Akka.Actor.Props.Create(() => new VirtualTagActor(
virtualTagId, expression,
evaluator ?? NullVirtualTagEvaluator.Instance,
@@ -173,7 +182,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
telemetryHub,
failureLogLimiter,
changeTriggered,
timerIntervalMs));
timerIntervalMs, sourcePublisher, sourceIncarnation));
/// <summary>Initializes a virtual tag actor with the given configuration and dependencies.</summary>
/// <param name="virtualTagId">Unique identifier for the virtual tag.</param>
@@ -202,8 +211,12 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
ITelemetryLocalHub? telemetryHub = null,
ScriptLogRateLimiter? failureLogLimiter = null,
bool changeTriggered = true,
int? timerIntervalMs = null)
int? timerIntervalMs = null,
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
long? sourceIncarnation = null)
{
_sourcePublisher = sourcePublisher;
_sourceIncarnation = sourceIncarnation;
_changeTriggered = changeTriggered;
_timerIntervalMs = timerIntervalMs is > 0 ? Math.Max(timerIntervalMs.Value, MinTimerIntervalMs) : null;
_virtualTagId = virtualTagId;
@@ -219,6 +232,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
Receive<DependencyValueChanged>(OnDependencyChanged);
Receive<DependencyValueBatch>(OnDependencyBatch);
Receive<ReassertValue>(_ => OnReassertValue());
Receive<RetrySourceBinding>(_ => RetrySource());
Receive<TimerTick>(_ => Evaluate(DateTime.UtcNow));
Receive<RunnerRecovered>(_ =>
{
@@ -233,6 +247,13 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
/// <inheritdoc />
protected override void PreStart()
{
if (_sourcePublisher is not null && _sourceIncarnation is { } previous &&
!_sourcePublisher.IsVirtualIncarnationActive(_virtualTagId, previous))
{
var current = _sourcePublisher.RegisterVirtualIncarnation(_virtualTagId);
_sourceIncarnation = current;
if (!_sourcePublisher.EnsureVirtualBinding(_virtualTagId, current)) ScheduleSourceRetry();
}
if (_timerIntervalMs is { } ms)
{
// lmxopcua#783: timer-driven evaluation. Cancelled in PostStop, so a stop / redeploy respawn
@@ -252,10 +273,27 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
/// <inheritdoc />
protected override void PostStop()
{
if (_sourceIncarnation is { } incarnation) _sourcePublisher?.RetireVirtualIncarnation(_virtualTagId, incarnation);
_sourceBindingRetry?.Cancel();
_timer?.Cancel();
_mux?.Tell(new DependencyMuxActor.UnregisterInterest(Self));
}
private void ScheduleSourceRetry()
{
_sourceBindingRetry?.Cancel();
_sourceBindingRetry = Context.System.Scheduler.ScheduleTellOnceCancelable(
TimeSpan.FromMilliseconds(250), Self, RetrySourceBinding.Instance, Self);
}
private void RetrySource()
{
_sourceBindingRetry = null;
if (_sourcePublisher is null || _sourceIncarnation is not { } incarnation) return;
if (!_sourcePublisher.EnsureVirtualBinding(_virtualTagId, incarnation)) { ScheduleSourceRetry(); return; }
if (AllDependenciesArrived()) Evaluate(DateTime.UtcNow);
}
/// <summary>Re-emit the last emitted value/quality to the parent bridge, bypassing the value dedup, so a
/// deploy that re-materialised our published UNS node to <c>BadWaitingForInitialData</c> recovers even when
/// the recomputed value is unchanged (permanent Bad otherwise, with a static dependency). No-op until the
@@ -353,14 +391,15 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
if (evaluation.IsCompleted)
{
// Synchronous evaluators (passthrough, null evaluator, fakes) and cheap failures: same turn, as before.
ApplyEvaluation(evaluation, worst, timestampUtc);
ApplyEvaluation(FreezeEvaluation(evaluation), worst, timestampUtc);
return;
}
// A real script run is in flight: free the dispatcher thread, hold every later input until it lands.
var self = Self;
var actorIncarnation = _actorIncarnation;
evaluation.ContinueWith(
t => self.Tell(new EvaluationCompleted(t, worst, timestampUtc)),
t => self.Tell(new EvaluationCompleted(FreezeEvaluation(t), worst, timestampUtc, actorIncarnation)),
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
BecomeStacked(Evaluating);
}
@@ -371,6 +410,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
{
Receive<EvaluationCompleted>(msg =>
{
if (msg.ActorIncarnation != _actorIncarnation) return;
UnbecomeStacked();
ApplyEvaluation(msg.Evaluation, msg.WorstInputStatus, msg.TimestampUtc);
Stash.UnstashAll();
@@ -381,6 +421,24 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
ReceiveAny(_ => Stash.Stash());
}
private static Task<VirtualTagEvalResult> FreezeEvaluation(Task<VirtualTagEvalResult> task)
{
if (!task.IsCompletedSuccessfully || !task.Result.Success || ReferenceEquals(task.Result, VirtualTagEvalResult.NoChange))
return task;
try
{
var result = task.Result;
return Task.FromResult(result with
{
Value = ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.OwnedDataSample.CopyLegacy(result.Value)
});
}
catch (Exception ex)
{
return Task.FromException<VirtualTagEvalResult>(ex);
}
}
/// <summary>
/// A runner failure (BadResourceUnavailable) carries the task that completes when the runner is back: evaluate
/// again then, with whatever inputs are current, instead of holding the Bad until the next input change — which,
@@ -434,6 +492,10 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
return;
}
// A completed evaluation is a fresh acquisition even when the legacy SDK value is unchanged.
// Publish before the SDK dedup so a quiet equal value can recover an invalidated cache.
PublishSource(result.Value, worst, timestampUtc);
// Dedup on (value, STATUS) — 02/S14 generalising 02/S13's recover-from-Bad bypass. Keying on
// value alone swallows every recovery whose value is unchanged, which is what a device coming
// back usually produces, and the node then stays Bad forever.
@@ -450,7 +512,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
// reaches here — it was held above).
_lastPublishedStatus = worst;
OtOpcUaTelemetry.VirtualTagEval.Add(1, new KeyValuePair<string, object?>("outcome", "ok"));
var evalResult = new EvaluationResult(_virtualTagId, result.Value, timestampUtc, CorrelationId.NewId(), worst);
var evalResult = new EvaluationResult(_virtualTagId, result.Value, timestampUtc, CorrelationId.NewId(), worst, SourceHandled: _sourcePublisher is not null);
Context.Parent.Tell(evalResult);
}
@@ -490,8 +552,9 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
_hasPublished = true;
_lastPublishedStatus = worstInputStatus;
PublishSourceStatus(worstInputStatus);
Context.Parent.Tell(new EvaluationResult(
_virtualTagId, _hasLastValue ? _lastValue : null, timestampUtc, CorrelationId.NewId(), worstInputStatus));
_virtualTagId, _hasLastValue ? _lastValue : null, timestampUtc, CorrelationId.NewId(), worstInputStatus, SourceHandled: _sourcePublisher is not null));
}
/// <summary>02/S13 failure tail shared by the evaluator-threw catch and the <c>!Success</c> branch.
@@ -528,8 +591,23 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
_hasPublished = true;
_lastPublishedStatus = badStatus;
PublishSourceStatus(badStatus);
Context.Parent.Tell(new EvaluationResult(
_virtualTagId, _hasLastValue ? _lastValue : null, timestampUtc, CorrelationId.NewId(), badStatus));
_virtualTagId, _hasLastValue ? _lastValue : null, timestampUtc, CorrelationId.NewId(), badStatus, SourceHandled: _sourcePublisher is not null));
}
private void PublishSource(object? value, uint status, DateTime timestamp)
{
if (_sourcePublisher is null || _sourceIncarnation is not { } incarnation ||
!_sourcePublisher.TryCaptureVirtual(_virtualTagId, incarnation, out var ticket)) return;
_sourcePublisher.TryPublish(ticket, new DataValueSnapshot(value, status, timestamp, timestamp));
}
private void PublishSourceStatus(uint status)
{
if (_sourcePublisher is null || _sourceIncarnation is not { } incarnation ||
!_sourcePublisher.TryCaptureVirtual(_virtualTagId, incarnation, out var ticket)) return;
_sourcePublisher.TryPublishStatus(ticket, status, out _);
}
/// <summary>Inputs-ready gate (the retired cascade engine's rule): true once
@@ -38,15 +38,19 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
/// feedback storm.
/// </para>
/// </summary>
public sealed class VirtualTagHostActor : ReceiveActor
public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
{
public ITimerScheduler Timers { get; set; } = null!;
/// <summary>Reconciles the live VirtualTag children to exactly the supplied desired set:
/// stops children whose vtagId is gone, spawns children for new vtagIds, and rebuilds the
/// vtagId→NodeId map so renames are reflected.</summary>
/// <param name="Plans">The desired Equipment-namespace VirtualTag plans.</param>
public sealed record ApplyVirtualTags(IReadOnlyList<EquipmentVirtualTagPlan> Plans);
private readonly IActorRef _publishActor;
private readonly IActorRef? _publishActor;
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? _sourcePublisher;
private readonly HashSet<string> _publishedVirtualIds = new(StringComparer.Ordinal);
private readonly Dictionary<string, long> _virtualSourceIncarnations = new(StringComparer.Ordinal);
private readonly IActorRef? _mux;
private readonly IVirtualTagEvaluator _evaluator;
// Sink for historized VirtualTag results (plans with Historize=true). NullHistoryWriter when no
@@ -80,9 +84,10 @@ public sealed class VirtualTagHostActor : ReceiveActor
/// <param name="telemetryHub">Optional node-local live-telemetry hub passed to each spawned child so
/// its script-log entries also emit to the live-telemetry hub; null (tests) skips the emit.</param>
/// <returns>The <see cref="Props"/> used to spawn a <see cref="VirtualTagHostActor"/>.</returns>
public static Props Props(IActorRef publishActor, IActorRef? mux, IVirtualTagEvaluator evaluator,
IHistoryWriter? historyWriter = null, ITelemetryLocalHub? telemetryHub = null) =>
Akka.Actor.Props.Create(() => new VirtualTagHostActor(publishActor, mux, evaluator, historyWriter, telemetryHub));
public static Props Props(IActorRef? publishActor, IActorRef? mux, IVirtualTagEvaluator evaluator,
IHistoryWriter? historyWriter = null, ITelemetryLocalHub? telemetryHub = null,
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null) =>
Akka.Actor.Props.Create(() => new VirtualTagHostActor(publishActor, mux, evaluator, historyWriter, telemetryHub, sourcePublisher));
/// <summary>Initializes a new instance of the <see cref="VirtualTagHostActor"/> class.</summary>
/// <param name="publishActor">The OPC UA publish actor results are bridged to.</param>
@@ -91,12 +96,13 @@ public sealed class VirtualTagHostActor : ReceiveActor
/// <param name="historyWriter">Sink for historized results; null ⇒ <see cref="NullHistoryWriter.Instance"/>.</param>
/// <param name="telemetryHub">Optional node-local live-telemetry hub passed to each spawned child so
/// its script-log entries also emit to the live-telemetry hub; null (tests) skips the emit.</param>
public VirtualTagHostActor(IActorRef publishActor, IActorRef? mux, IVirtualTagEvaluator evaluator,
IHistoryWriter? historyWriter = null, ITelemetryLocalHub? telemetryHub = null)
public VirtualTagHostActor(IActorRef? publishActor, IActorRef? mux, IVirtualTagEvaluator evaluator,
IHistoryWriter? historyWriter = null, ITelemetryLocalHub? telemetryHub = null,
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null)
{
ArgumentNullException.ThrowIfNull(publishActor);
ArgumentNullException.ThrowIfNull(evaluator);
_publishActor = publishActor;
_sourcePublisher = sourcePublisher;
_mux = mux;
_evaluator = evaluator;
_history = historyWriter ?? NullHistoryWriter.Instance;
@@ -109,6 +115,15 @@ public sealed class VirtualTagHostActor : ReceiveActor
private void OnApply(ApplyVirtualTags msg)
{
Timers.Cancel("source-binding-retry");
var virtualIds = msg.Plans.Select(p => p.VirtualTagId).ToHashSet(StringComparer.Ordinal);
foreach (var id in _publishedVirtualIds.Where(id => !virtualIds.Contains(id)))
{
if (_virtualSourceIncarnations.Remove(id, out _)) _sourcePublisher?.RetireCurrentVirtual(id);
if (_sourcePublisher?.TryCaptureVirtual(id, out var ticket) == true) _sourcePublisher.TryRemove(ticket);
}
_publishedVirtualIds.Clear();
_publishedVirtualIds.UnionWith(virtualIds);
// Apply-boundary compile-cache drop (gated — 02/P7): the production evaluator roots one
// collectible AssemblyLoadContext per compiled expression, so a changed script set must drop the
// stale ALCs. But clearing on EVERY apply forces a full recompilation even on a byte-identical
@@ -143,6 +158,7 @@ public sealed class VirtualTagHostActor : ReceiveActor
// PostStop, which unregisters its interest from the mux.
foreach (var vtagId in _children.Keys.Where(id => !desired.Contains(id)).ToList())
{
if (_virtualSourceIncarnations.Remove(vtagId, out _)) _sourcePublisher?.RetireCurrentVirtual(vtagId);
Context.Stop(_children[vtagId]);
_children.Remove(vtagId);
}
@@ -158,6 +174,9 @@ public sealed class VirtualTagHostActor : ReceiveActor
&& _planByVtag.TryGetValue(p.VirtualTagId, out var prev)
&& !prev.Equals(p))
{
if (_virtualSourceIncarnations.Remove(p.VirtualTagId, out _)) _sourcePublisher?.RetireCurrentVirtual(p.VirtualTagId);
if (_sourcePublisher?.TryCaptureVirtual(p.VirtualTagId, out var ticket) == true)
_sourcePublisher.TryRebind(ticket, out _);
Context.Stop(_children[p.VirtualTagId]); // PostStop unregisters the old mux interest.
_children.Remove(p.VirtualTagId);
}
@@ -191,6 +210,22 @@ public sealed class VirtualTagHostActor : ReceiveActor
// Auto-name the child: vtagIds can contain characters illegal in actor names, so let Akka
// assign a safe unique name. The child self-registers with the mux in PreStart.
long? sourceIncarnation = null;
if (_sourcePublisher is not null)
{
if (!_virtualSourceIncarnations.TryGetValue(p.VirtualTagId, out var currentToken))
currentToken = _sourcePublisher.RegisterVirtualIncarnation(p.VirtualTagId);
sourceIncarnation = currentToken;
}
if (sourceIncarnation is { } token)
{
_virtualSourceIncarnations[p.VirtualTagId] = token;
if (!_sourcePublisher!.EnsureVirtualBinding(p.VirtualTagId, token))
{
Timers.StartSingleTimer("source-binding-retry", msg, TimeSpan.FromMilliseconds(250));
continue;
}
}
var child = Context.ActorOf(VirtualTagActor.Props(
virtualTagId: p.VirtualTagId,
expression: p.Expression,
@@ -201,7 +236,9 @@ public sealed class VirtualTagHostActor : ReceiveActor
mux: _mux,
telemetryHub: _telemetryHub,
changeTriggered: p.ChangeTriggered,
timerIntervalMs: p.TimerIntervalMs));
timerIntervalMs: p.TimerIntervalMs,
sourcePublisher: _sourcePublisher,
sourceIncarnation: sourceIncarnation));
Context.Watch(child);
_children[p.VirtualTagId] = child;
newlySpawned.Add(p.VirtualTagId);
@@ -246,9 +283,19 @@ public sealed class VirtualTagHostActor : ReceiveActor
// reports BadOutOfService instead of serving a value computed from a stale input.
foreach (var p in msg.Plans.Where(p => !p.Enabled))
{
if (_sourcePublisher is not null && !_virtualSourceIncarnations.ContainsKey(p.VirtualTagId))
{
var token = _sourcePublisher.RegisterVirtualIncarnation(p.VirtualTagId);
_virtualSourceIncarnations[p.VirtualTagId] = token;
}
if (_sourcePublisher is not null &&
!_sourcePublisher.EnsureVirtualBinding(p.VirtualTagId, _virtualSourceIncarnations[p.VirtualTagId]))
Timers.StartSingleTimer("source-binding-retry", msg, TimeSpan.FromMilliseconds(250));
var nodeId = NodeIdFor(p);
var now = DateTime.UtcNow;
_publishActor.Tell(new OpcUaPublishActor.AttributeValueUpdate(
if (_sourcePublisher?.TryCaptureVirtual(p.VirtualTagId, out var ticket) == true)
_sourcePublisher.TryPublish(ticket, new DataValueSnapshot(null, OpcUaStatus.BadOutOfService, null, null));
_publishActor?.Tell(new OpcUaPublishActor.AttributeValueUpdate(
nodeId, null, OpcUaStatus.BadOutOfService, now, AddressSpaceRealm.Uns));
_mux?.Tell(new DependencyMuxActor.VirtualTagOutput(nodeId, null, now, OpcUaStatus.BadOutOfService));
}
@@ -302,7 +349,9 @@ public sealed class VirtualTagHostActor : ReceiveActor
// failure/timeout) carrying the last-known value. Bridge result.StatusCode through verbatim; the
// sink maps it to StatusCodes.Good/Bad on the node so a broken script no longer freezes Good.
// VirtualTags materialise as equipment nodes in the UNS realm — publish there.
_publishActor.Tell(new OpcUaPublishActor.AttributeValueUpdate(
if (!result.IsReassert && !result.SourceHandled && _sourcePublisher?.TryCaptureVirtual(result.VirtualTagId, out var ticket) == true)
_sourcePublisher.TryPublish(ticket, new DataValueSnapshot(result.Value, result.StatusCode, result.TimestampUtc, result.TimestampUtc));
_publishActor?.Tell(new OpcUaPublishActor.AttributeValueUpdate(
nodeId, result.Value, result.StatusCode, result.TimestampUtc, AddressSpaceRealm.Uns));
// lmxopcua#791: feed the VirtualTags (and Calculation tags / scripted alarms) that read this one. A
@@ -331,6 +380,8 @@ public sealed class VirtualTagHostActor : ReceiveActor
var stale = _children.Where(kv => kv.Value.Equals(msg.ActorRef)).Select(kv => kv.Key).ToList();
foreach (var id in stale)
{
_sourcePublisher?.RetireCurrentVirtual(id);
_virtualSourceIncarnations.Remove(id);
_children.Remove(id);
// Keep _planByVtag in lock-step with _children so it never holds a plan for a dead child.
// (The next apply also resets it, and the change-detect guard short-circuits on the missing
@@ -431,7 +431,7 @@ internal sealed class WorkerHost
VariantCodec.Decode(input.Value),
input.StatusCode,
input.SourceTsTicks == 0 ? null : new DateTime(input.SourceTsTicks, DateTimeKind.Utc),
new DateTime(input.ServerTsTicks, DateTimeKind.Utc));
input.ServerTsTicks == 0 ? null : new DateTime(input.ServerTsTicks, DateTimeKind.Utc));
}
// ctx.Now follows the HOST clock (design §4.3) but keeps ticking: a fixed instant would never let a script