test: validate grpc data connections with local docker and opcua cli

This commit is contained in:
Joseph Doherty
2026-11-17 22:01:26 -05:00
parent 1df29a3124
commit 29fec57fac
194 changed files with 23327 additions and 740 deletions
@@ -31,11 +31,11 @@ else
<div class="d-flex flex-wrap gap-2 align-items-center mb-2"><strong>@row.Id</strong>@if (row.Draft is { } draft) { <span class="chip chip-idle">Draft: @(draft.Enabled ? "enabled" : "disabled")</span> } else { <span class="chip chip-warn">Removed from draft</span> }@if (!_live.Any(x => Same(x.Row.ConnectionId, row.Id))) { <span>Runtime: unavailable</span> }
@foreach (var live in _live.Where(x => Same(x.Row.ConnectionId, row.Id)))
{
<div class="w-100 small"><strong>@live.NodeId: @DataConnectionDiagnostics.State(live.Row.State)</strong> · revision @live.Row.Revision · endpoint @DataConnectionDiagnostics.Endpoint(live.Row.SelectedEndpoint)
<div class="w-100 small data-connection-diagnostics"><strong>@live.NodeId: @DataConnectionDiagnostics.State(live.Row.State)</strong> · revision @live.Row.Revision · endpoint @DataConnectionDiagnostics.Endpoint(live.Row.SelectedEndpoint)
@if (live.Row.Serving is { } serving) { <span> · serving @serving.NodeId · role @serving.Role · incarnation @serving.Incarnation</span> }
<div>Streams @live.Row.ActiveStreams · calls @live.Row.ActiveCalls · retained import views @Measure(live.Row.SourceCount) · registrations @Measure(live.Row.RegistrationCount) · resets @Measure(live.Row.ResetCount) · coalesced notices @Measure(live.Row.CoalescedCount) · overflows @Measure(live.Row.OverflowCount)</div>
<div>Writes succeeded @Measure(live.Row.WriteSucceededCount) · rejected @Measure(live.Row.WriteRejectedCount) · failed @Measure(live.Row.WriteFailedCount) · unconfirmed @Measure(live.Row.WriteUnconfirmedCount) · unknown @Measure(live.Row.WriteUnknownCount)</div>
<div>Last observed sample bound @Time(live.Row.LastSampleAtUtc) (age upper bound @DataConnectionDiagnostics.SampleAge(live.Row)) · metadata lease expires @Time(live.Row.MetadataLeaseExpiresAtUtc) · last handshake @Time(live.Row.LastVerifiedAtUtc) · observed @live.Row.AsOfUtc.ToString("u") · artifact @live.Row.ArtifactRevision · protocol @Measure(live.Row.ProtocolMajor).@Measure(live.Row.ProtocolMinor)</div></div>
<div>Last observed sample bound @Time(live.Row.LastSampleAtUtc) (age upper bound @DataConnectionDiagnostics.SampleAge(live.Row)) · metadata lease expires @Time(live.Row.MetadataLeaseExpiresAtUtc) · last handshake @Time(live.Row.LastVerifiedAtUtc) · observed @live.Row.AsOfUtc.ToString("u") · artifact @live.Row.ArtifactRevision · protocol @(live.Row.ProtocolMajor is { } major && live.Row.ProtocolMinor is { } minor ? $"{major}.{minor}" : "unavailable")</div></div>
}
@foreach (var applied in _applied.Where(x => Same(x.ConnectionId, row.Id))) { <span class="small">@applied.NodeId: last applied revision @applied.Revision (@(applied.Enabled ? "enabled" : "disabled"))</span> }
@if (row.Draft is { } editable) { <AuthorizeView Policy="@AdminUiPolicies.ConfigEditor"><button class="btn btn-sm btn-outline-primary" @onclick="() => Edit(editable)">Edit</button></AuthorizeView> }</div>
@@ -0,0 +1,5 @@
.data-connection-diagnostics {
min-width: 0;
max-width: 100%;
overflow-wrap: anywhere;
}
@@ -0,0 +1,22 @@
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
/// <summary>Observes the committed provisioning state without exposing secret or trust material.</summary>
public sealed class DataConnectionBundleCommitObserver(DataConnectionSecretProvisioner credentials, DataConnectionTrustPolicyStore trust)
: IDataConnectionBundleCommitObserver
{
/// <inheritdoc />
public async Task<DataConnectionBundleCommitObservation> ObserveAsync(string connectionId, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrWhiteSpace(connectionId);
await DataConnectionSecretProvisioner.Gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var credential = await credentials.ObserveCommittedLockedAsync(connectionId, cancellationToken).ConfigureAwait(false);
var trustState = await trust.ObserveCommittedLockedAsync(connectionId, cancellationToken).ConfigureAwait(false);
return new(credential.Scope, credential.Version, credential.Deleted, trustState.Scope, trustState.Version, trustState.Retired);
}
finally { DataConnectionSecretProvisioner.Gate.Release(); }
}
}
@@ -5,6 +5,8 @@ public sealed class DataConnectionOptions
{
public const string SectionName = "DataConnections";
public bool Enabled { get; set; }
/// <summary>Requests supported compact batches on outbound data subscriptions.</summary>
public bool UseCompactBatches { get; set; } = true;
public int ListenPort { get; set; }
public string ListenAddress { get; set; } = "0.0.0.0";
public string[] AllowedHosts { get; set; } = [];
@@ -53,7 +53,7 @@ public static class DataConnectionRegistration
return new LocalCatalogCoordinator(sp.GetRequiredService<CatalogActivation>(), sp.GetRequiredService<DataPlaneAuthorityState>(),
() =>
{
var state = CaptureRole(role, warm);
var state = CaptureReadRole(role, warm);
var servingRole = settings.IsWarm && state.WarmRole != WarmRole.Active ? "Standby" : state.Role;
return new(identity.NodeId, identity.Incarnation, servingRole, 0, 0, state.Generation);
});
@@ -108,12 +108,12 @@ public static class DataConnectionRegistration
localWriteRole: () =>
{
var role = sp.GetRequiredService<RedundancyRoleView>();
var state = CaptureRole(role, sp.GetRequiredService<DataConnectionWarmRoleView>());
var state = CaptureWriteRole(role, sp.GetRequiredService<DataConnectionWarmRoleView>());
var settings = sp.GetService<WarmRedundancySettings>() ?? WarmRedundancySettings.Unset;
var active = sp.GetRequiredService<LocalCatalogCoordinator>().Current is { IsActive: true };
return (active && role.ShouldActAsPrimary && state.Role == "Primary" &&
(!settings.IsWarm || state.WarmRole == WarmRole.Active), state.Generation);
}));
}, renewalSink: sp.GetRequiredService<IProjectedNamespacePageSink>()));
services.AddSingleton<IProjectedDataAccess>(sp => sp.GetRequiredService<ProjectedDataAccess>());
services.AddSingleton<IConfiguredProjectionDiscovery>(sp => new ConfiguredProjectionDiscovery(
sp.GetRequiredService<ProjectedMappingDeploymentRuntime>(), sp.GetRequiredService<IFederatedProjectionCatalog>(),
@@ -171,6 +171,7 @@ public static class DataConnectionRegistration
sp.GetRequiredService<DataConnectionSecretChangeHandler>(), id.ClusterId, id.NodeId);
});
services.AddSingleton<IDataConnectionSecurityProvider, DataConnectionSecurityProvider>();
services.AddSingleton<IDataConnectionBundleCommitObserver, DataConnectionBundleCommitObserver>();
services.AddSingleton<IDataConnectionScopeActivator, DataConnectionScopeActivator>();
services.AddSingleton(sp =>
{
@@ -183,7 +184,7 @@ public static class DataConnectionRegistration
sp.GetRequiredService<IDataConnectionScopeActivator>(), 256, sp.GetRequiredService<TimeProvider>(),
() =>
{
var state = CaptureRole(role, warm);
var state = CaptureReadRole(role, warm);
var mode = settings.Mode switch
{
OpcUaRedundancyMode.Warm => RedundancyMode.Warm,
@@ -192,6 +193,25 @@ public static class DataConnectionRegistration
};
return state.Generation > 0 && Enum.TryParse<RedundancyRole>(state.Role, out var actual)
&& DataConnectionRoleAdapter.MayAcquire(mode, state.WarmRole, actual);
}, useCompactBatches: options.UseCompactBatches, consumerRoleSnapshot: artifactMode =>
{
var mode = settings.Mode switch
{
OpcUaRedundancyMode.Warm => RedundancyMode.Warm,
OpcUaRedundancyMode.None => RedundancyMode.None,
_ => artifactMode
};
if (mode == RedundancyMode.Hot)
{
var hot = role.CaptureDataServingRole();
var hotEligible = hot.Generation > 0 && Enum.TryParse<RedundancyRole>(hot.Role, out var hotRole)
&& DataConnectionRoleAdapter.MayAcquire(mode, null, hotRole);
return new DataConnectionConsumerRoleSnapshot(mode, hotEligible, hot.ReadEligibilityEpoch);
}
var state = CaptureReadRole(role, warm);
var eligible = state.Generation > 0 && Enum.TryParse<RedundancyRole>(state.Role, out var actual)
&& DataConnectionRoleAdapter.MayAcquire(mode, state.WarmRole, actual);
return new DataConnectionConsumerRoleSnapshot(mode, eligible, state.Generation);
});
return runtime;
});
@@ -213,19 +233,37 @@ public static class DataConnectionRegistration
return options;
}
private static (string Role, long Generation, WarmRole? WarmRole) CaptureRole(RedundancyRoleView role, DataConnectionWarmRoleView warm)
private static (string Role, long Generation, WarmRole? WarmRole, long ReadEpoch) CaptureReadRole(
RedundancyRoleView role, DataConnectionWarmRoleView warm)
{
if (!ReferenceEquals(role.DispatchFence, warm.DispatchFence)) return ("Unknown", 0, null, 0);
// Both verdicts are immutable. The monotone primary generation brackets
// the Warm read, so a stable generation gives a pair that coexisted.
// A competing read or dispatch does not withdraw an unchanged role.
var primary = role.CaptureDataServingRole();
var warmVerdict = warm.Snapshot;
return primary.Generation == role.PrimaryGeneration
? CombineRole(primary, warmVerdict)
: ("Unknown", 0, null, 0);
}
private static (string Role, long Generation, WarmRole? WarmRole, long ReadEpoch) CaptureWriteRole(
RedundancyRoleView role, DataConnectionWarmRoleView warm)
{
if (!ReferenceEquals(role.DispatchFence, warm.DispatchFence) || !role.DispatchFence.TryEnter(out var lease))
return ("Unknown", 0, null);
return ("Unknown", 0, null, 0);
using (lease)
{
var observed = role.DataServingRole;
var primaryGeneration = role.PrimaryGeneration;
var verdict = warm.Snapshot;
if (primaryGeneration == long.MaxValue || verdict.Generation == long.MaxValue
|| primaryGeneration > long.MaxValue - verdict.Generation) return ("Unknown", long.MaxValue, null);
return (observed, primaryGeneration + verdict.Generation, verdict.Role);
}
return CombineRole(role.CaptureDataServingRole(), warm.Snapshot);
}
private static (string Role, long Generation, WarmRole? WarmRole, long ReadEpoch) CombineRole(
DataServingRoleSnapshot primary, DataConnectionWarmRoleSnapshot warm)
{
if (primary.Generation == long.MaxValue || warm.Generation == long.MaxValue
|| primary.Generation > long.MaxValue - warm.Generation)
return ("Unknown", long.MaxValue, null, long.MaxValue);
return (primary.Role, primary.Generation + warm.Generation, warm.Role, primary.ReadEligibilityEpoch);
}
private sealed class DeferredFactory(Func<IDataConnectionFactory> resolve) : IDataConnectionFactory
@@ -71,6 +71,22 @@ public sealed class DataConnectionSecretProvisioner
private Task SaveAsync(DataCredentialState state, CancellationToken ct) =>
_store.UpsertAsync(_cipher.Encrypt(StateName, JsonSerializer.Serialize(state), SecretContentType.Text), ct);
// Caller holds Gate so a combined credential/trust observation cannot straddle a commit.
internal async Task<(long? Scope, long? Version, bool? Deleted)> ObserveCommittedLockedAsync(string connectionId, CancellationToken ct)
{
var id = NormalizeId(connectionId);
var state = await ReadStateAsync(_store, _cipher, StateName, ct).ConfigureAwait(false);
// The durable scope is not committed while any retirement or bundle transition
// can still publish a connection-change notice or remove a retained credential.
if (state.PendingNotices.Count != 0 || state.PendingDeletes.Count != 0 || state.Versions.Values.Any(version => version.Pending))
return (null, null, null);
var scope = state.ScopeVersion > 0 ? state.ScopeVersion : (long?)null;
if (state.PendingNotices.Contains(id) || !state.Scope.TryGetValue(id, out var reference) ||
!state.Versions.TryGetValue(reference, out var version) || version.Pending ||
version.ScopeVersion != state.ScopeVersion || version.Version <= 0) return (scope, null, null);
return (scope, version.Version, version.Deleted);
}
/// <summary>Persists current scope before retiring removed connections.</summary>
public async Task SetScopeAsync(long version, IReadOnlyDictionary<string, string> scope, CancellationToken ct)
{
@@ -60,6 +60,22 @@ public sealed class DataConnectionTrustPolicyStore(
return row is null ? new State() : System.Text.Json.JsonSerializer.Deserialize<State>(cipher.Decrypt(row))
?? throw new InvalidOperationException("Invalid trust state.");
}
// Caller holds the shared provisioning Gate; no trust certificates are materialized.
internal async Task<(long? Scope, long? Version, bool? Retired)> ObserveCommittedLockedAsync(string connectionId, CancellationToken ct)
{
var id = DataConnectionSecretProvisioner.NormalizeId(connectionId);
var state = await ReadAsync(ct).ConfigureAwait(false);
// Pending retirement or bundle notices can still revoke a route after the
// scope was persisted; do not report that scope as committed yet.
if (state.PendingNotices.Count != 0 || state.Entries.Values.Any(entry => entry.PendingNotice))
return (null, null, null);
var scope = state.ScopeVersion > 0 ? state.ScopeVersion : (long?)null;
if (!state.Scope.Contains(id) || state.PendingNotices.Contains(id) || !state.Entries.TryGetValue(id, out var entry) ||
entry.PendingNotice || entry.Roots is null || entry.ScopeVersion != state.ScopeVersion || entry.Version <= 0)
return (scope, null, null);
return (scope, entry.Version, entry.Retired || entry.Roots.Length == 0);
}
private Task SaveAsync(State state, CancellationToken ct) => store.UpsertAsync(cipher.Encrypt(_name,
System.Text.Json.JsonSerializer.Serialize(state), ZB.MOM.WW.Secrets.Abstractions.SecretContentType.Text), ct);
private async Task CompleteScopeAsync(State state, CancellationToken ct)
@@ -2,6 +2,7 @@ using Google.Protobuf;
using Grpc.Core;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
using ZB.MOM.WW.OtOpcUa.Commons.Protos;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
@@ -140,13 +141,18 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
initial.CancelAfter(_options.UnaryTimeout);
caps = await Ready(connection, DataOperations.Subscribe, initial.Token).ConfigureAwait(false);
}
var codecHeaders = context.RequestHeaders.Where(entry => string.Equals(entry.Key, DataConnectionProtoContract.CompactCodecHeader, StringComparison.OrdinalIgnoreCase)).ToArray();
if (codecHeaders.Length > 1 || codecHeaders.Length == 1 &&
(codecHeaders[0].IsBinary || codecHeaders[0].Value != "1"))
throw new RpcException(new Status(StatusCode.InvalidArgument, "Invalid compact codec negotiation."));
var compact = codecHeaders.Length == 1 && DataProtoMapper.NegotiateCompact(caps);
subscription = await connection.SubscribeAsync(context.CancellationToken).ConfigureAwait(false);
await using (subscription)
{
if (subscription is not IDataSubscriptionTransport transport)
throw new RpcException(new Status(StatusCode.Unavailable, "Subscription transport is unavailable."));
using var stop = CancellationTokenSource.CreateLinkedTokenSource(context.CancellationToken);
var sink = new GrpcDeliverySink(responses, context, caps, _options.MaxMessageBytes,
var sink = new GrpcDeliverySink(responses, context, caps, _options.MaxMessageBytes, compact,
() => CanPublish(connection, caller, caps.Serving));
var delivery = transport.RunDeliveryAsync(sink, stop.Token);
var commands = ReceiveCommands();
@@ -174,6 +180,8 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
AddSubscriptionItems add => add with { AcknowledgementTimeout = ack },
ModifySubscriptionItems modify => modify with { AcknowledgementTimeout = ack },
RemoveSubscriptionItems remove => remove with { AcknowledgementTimeout = ack },
ChallengeSubscriptionFreshness challenge when caps.SubscriptionFreshnessChallenges && caps.SubscriptionAgeReadiness =>
challenge with { AcknowledgementTimeout = ack },
_ => throw new ArgumentException("Unsupported stream command.")
};
using var commandDeadline = CancellationTokenSource.CreateLinkedTokenSource(stop.Token);
@@ -191,7 +199,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
}
private sealed class GrpcDeliverySink(IServerStreamWriter<W.SubscriptionFrame> writer, ServerCallContext context,
DataCapabilities caps, int maximumBytes, Func<bool> hostGuard) : IDataSubscriptionDeliverySink
DataCapabilities caps, int maximumBytes, bool compact, Func<bool> hostGuard) : IDataSubscriptionDeliverySink
{
public ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame, long reservedBytes,
CancellationToken cancellationToken)
@@ -210,7 +218,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
};
if (charge > reservedBytes) throw new RpcException(new Status(StatusCode.ResourceExhausted, "Prepared frame exceeds its reservation."));
var wire = frame is DataSubscriptionValues valuesFrame
? DataProtoMapper.EncodeValues(valuesFrame, compactNegotiated: false, subscriptionAgeReadiness: true)
? DataProtoMapper.EncodeValues(valuesFrame, compactNegotiated: compact && valuesFrame.Items.Count > 0, subscriptionAgeReadiness: true)
: DataProtoMapper.EncodeControlOrAck(frame);
wire.Serving = DataProtoMapper.EncodeServing(caps.Serving);
if (wire.CalculateSize() > maximumBytes) throw new RpcException(new Status(StatusCode.ResourceExhausted, "Stream message exceeds transport limits."));
@@ -14,4 +14,7 @@ public sealed class DeferredProjectedNamespacePageSink(DeferredAddressSpaceSink
public bool TryRemove(NodeId nodeId, ProjectedVariableDefinition expected) =>
deferred.GetCapability<IProjectedNamespacePageSink>()?.TryRemove(nodeId, expected) ?? false;
public bool TryRenewExact(NodeId nodeId, ProjectedVariableDefinition expected, ProjectedVariableDefinition replacement, Func<bool> commit) =>
deferred.GetCapability<IProjectedNamespacePageSink>()?.TryRenewExact(nodeId, expected, replacement, commit) ?? false;
}
@@ -7,6 +7,8 @@ public interface IProjectedNamespacePageSink
{
bool TryApply(NodeId parent, IReadOnlyList<ProjectedVariableDefinition> nodes, Func<bool> commit);
bool TryRemove(NodeId nodeId, ProjectedVariableDefinition expected);
/// <summary>Renews one existing compatible node without asserting a parent page or sibling authority.</summary>
bool TryRenewExact(NodeId nodeId, ProjectedVariableDefinition expected, ProjectedVariableDefinition replacement, Func<bool> commit) => false;
/// <summary>Atomically promotes an owned mapping anchor to its verified leaf value.</summary>
bool TryApplyRootLeaf(NodeId anchorId, ProjectedVariableDefinition rootDefinition, Func<bool> commit) => false;
}
@@ -1,4 +1,5 @@
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Globalization;
using System.Runtime.CompilerServices;
using Microsoft.Extensions.Logging;
@@ -44,6 +45,14 @@ public sealed record ProjectedVariableDefinition(DataRealm Realm, string LocalId
public sealed record ProjectedAnchorDefinition(DataRealm Realm, string LocalIdentifier, NodeId Parent,
string BrowseName, string LocalSubject, string MappingId, long MappingRevision, Func<bool> AuthorityIsCurrent)
{
private NodeScope? _localScope;
/// <summary>The exact, locally deployed ACL placement of this mapping anchor.</summary>
public NodeScope? LocalScope
{
get => _localScope;
init => _localScope = value?.Segments is null ? null :
value with { Segments = Array.AsReadOnly(value.Segments.ToArray()) };
}
/// <summary>Stable for one installed mapping anchor incarnation.</summary>
public ProjectedNodeLifetime Lifetime { get; init; } = new();
}
@@ -748,14 +757,26 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
{
if (disposing)
{
lock (_projectedHealthGate)
{
_projectedHealthStopped = true;
_projectedHealthTimer?.Dispose();
_projectedHealthTimer = null;
_projectedHealthItems.Clear(); _projectedHealthIndex.Clear(); _projectedHealthCursor = null;
}
// #854 review: refuse new Server-object refreshes and let the ones in flight finish (the base's private
// NodeManagerOperation guard does this for its own paths).
lock (Lock) _disposing = true;
lock (Lock)
{
_disposing = true;
Volatile.Write(ref _committedProjectedDefinitions, _committedProjectedDefinitions.Clear());
}
Interlocked.MemoryBarrier(); // the flag write must not be reordered after the in-flight read (#854 re-review)
if (!SpinWait.SpinUntil(() => Volatile.Read(ref _refreshesInFlight) == 0, TimeSpan.FromSeconds(10)))
_logger.LogWarning("Node manager disposed with {Count} Server-object ConditionRefresh call(s) still in flight after 10 s",
Volatile.Read(ref _refreshesInFlight));
Volatile.Read(ref _dataPlaneAuthority).Changed -= OnAuthorityChanged;
foreach (var item in _liveItems.Keys.OfType<ProjectedMonitoredItem>()) item.Retire();
_liveItems.Clear();
_eventItems.Clear();
_allEventsItems.Clear();
@@ -4194,7 +4215,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
string.IsNullOrWhiteSpace(definition.LocalIdentifier) || string.IsNullOrWhiteSpace(definition.BrowseName) ||
string.IsNullOrWhiteSpace(definition.MappingId) || string.IsNullOrWhiteSpace(definition.LocalSubject) ||
!ProjectedDataIds.TryDecodeIdentifier(definition.LocalIdentifier, out var mappingId, out _) || mappingId != definition.MappingId ||
definition.MappingRevision <= 0 || !definition.Lifetime.IsActive || definition.AuthorityIsCurrent is null)
definition.MappingRevision <= 0 || !definition.Lifetime.IsActive || definition.AuthorityIsCurrent is null ||
definition.LocalScope is { } scope && (string.IsNullOrWhiteSpace(scope.ClusterId) || scope.Segments.Any(string.IsNullOrEmpty)))
return false;
lock (Lock)
{
@@ -4206,7 +4228,12 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
{
if (old.Definition.Parent != definition.Parent || old.Definition.MappingId != definition.MappingId ||
old.Definition.MappingRevision != definition.MappingRevision || old.Definition.LocalSubject != definition.LocalSubject ||
!old.Definition.AuthorityIsCurrent()) return false;
old.Definition.BrowseName != definition.BrowseName || !SameAnchorScope(old.Definition.LocalScope, definition.LocalScope)) return false;
if (!old.Definition.AuthorityIsCurrent())
{
if (!ReferenceEquals(old.Definition.Lifetime, definition.Lifetime) || !definition.Lifetime.IsActive) return false;
_projectedAnchors[id] = (definition, old.Node);
}
nodeId = id; return true;
}
if (GetManagerHandle(id) is not null) return false;
@@ -4226,8 +4253,14 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
}
}
private static bool SameAnchorScope(NodeScope? left, NodeScope? right) =>
left is null ? right is null : right is not null && left.ClusterId == right.ClusterId &&
left.Kind == right.Kind && left.Segments.SequenceEqual(right.Segments, StringComparer.Ordinal);
private static long ProjectedAnchorCharge(ProjectedAnchorDefinition definition) =>
checked(1024L + 2L * (definition.LocalIdentifier.Length + definition.BrowseName.Length + definition.LocalSubject.Length + definition.MappingId.Length));
checked(1024L + 2L * (definition.LocalIdentifier.Length + definition.BrowseName.Length + definition.LocalSubject.Length + definition.MappingId.Length) +
(definition.LocalScope is { } scope ? 64L + 2L * scope.ClusterId.Length +
scope.Segments.Sum(segment => 24L + 2L * segment.Length) : 0));
/// <inheritdoc />
public bool TryRemoveProjectedAnchor(NodeId nodeId, ProjectedAnchorDefinition expected)
@@ -4237,8 +4270,10 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
if (_disposing || !_projectedAnchors.TryGetValue(nodeId, out var anchor) ||
!ReferenceEquals(anchor.Definition, expected)) return false;
var mappingId = anchor.Definition.MappingId;
foreach (var id in _projectedVariables.Keys.Where(id =>
ProjectedDataIds.TryDecodeIdentifier(id.IdentifierAsString, out var mapping, out _) && mapping == mappingId).ToArray())
var descendants = _projectedVariables.Keys.Where(id =>
ProjectedDataIds.TryDecodeIdentifier(id.IdentifierAsString, out var mapping, out _) && mapping == mappingId).ToArray();
Volatile.Write(ref _committedProjectedDefinitions, _committedProjectedDefinitions.RemoveRange(descendants).Remove(nodeId));
foreach (var id in descendants)
{
if (_projectedVariables.Remove(id, out var child))
{
@@ -4274,11 +4309,19 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
/// <inheritdoc />
public bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition)
{
lock (Lock)
// Runtime demand checks can hold a source gate that SDK publication also needs.
// Resolve committed metadata without acquiring the SDK address-space lock.
var committed = Volatile.Read(ref _committedProjectedDefinitions);
if (!_disposing && committed.TryGetValue(nodeId, out var current) && current.Lifetime.IsActive &&
current.AuthorityIsCurrent() && !_disposing && current.Lifetime.IsActive &&
Volatile.Read(ref _committedProjectedDefinitions).TryGetValue(nodeId, out var latest) &&
ReferenceEquals(current, latest))
{
if (!_disposing && _projectedDefinitions.TryGetValue(nodeId, out definition) && definition.Lifetime.IsActive && definition.AuthorityIsCurrent()) return true;
definition = null; return false;
definition = current;
return true;
}
definition = null;
return false;
}
private int _maxProjectedNodes = 4096;
@@ -4310,6 +4353,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
private long _retiredProjectedBytes;
private void RetireProjectedCharge(NodeId id, ProjectedNodeLifetime lifetime)
{
RemoveCommittedProjectedDefinition(id);
if (!_projectedNodeCharges.Remove(id, out var charge)) { lifetime.ForceRetire(); return; }
_projectedNodeBytes -= charge;
Interlocked.Add(ref _retiredProjectedBytes, charge);
@@ -4330,6 +4374,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
_projectedVariables.Values.Any(child => child.Parent == pair.Key) || !pair.Value.Lifetime.TryRetire()) continue;
if (!_projectedVariables.Remove(pair.Key, out var entry)) continue;
_projectedDefinitions.Remove(pair.Key); RemoveProjectedSample(pair.Key);
RemoveCommittedProjectedDefinition(pair.Key);
if (_projectedNodeCharges.Remove(pair.Key, out var oldBytes)) _projectedNodeBytes -= oldBytes;
entry.Node.Parent?.RemoveChild(entry.Node); PredefinedNodes?.Remove(pair.Key);
if (_projectedVariables.Count + _projectedAnchors.Count - _projectedRootLeaves.Count + Volatile.Read(ref _retiredProjectedNodes) < _maxProjectedNodes && bytes <= _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes) return true;
@@ -4340,7 +4385,10 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
_projectedVariables.Values.Any(node => node.Parent == pair.Key) || !pair.Value.Definition.Lifetime.TryRetire()) continue;
if (!_projectedAnchors.TryRemove(pair.Key, out var anchor)) continue;
if (_projectedRootLeaves.TryRemove(pair.Key, out _))
{ _projectedVariables.Remove(pair.Key); _projectedDefinitions.Remove(pair.Key); RemoveProjectedSample(pair.Key); }
{
_projectedVariables.Remove(pair.Key); _projectedDefinitions.Remove(pair.Key); RemoveProjectedSample(pair.Key);
RemoveCommittedProjectedDefinition(pair.Key);
}
if (_projectedNodeCharges.Remove(pair.Key, out var oldBytes)) _projectedNodeBytes -= oldBytes;
anchor.Node.Parent?.RemoveChild(anchor.Node); PredefinedNodes?.Remove(pair.Key);
if (_projectedVariables.Count + _projectedAnchors.Count - _projectedRootLeaves.Count + Volatile.Read(ref _retiredProjectedNodes) < _maxProjectedNodes && bytes <= _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes) return true;
@@ -4348,6 +4396,17 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
return false;
}
private readonly Dictionary<NodeId, ProjectedVariableDefinition> _projectedDefinitions = new();
// Writers hold Lock. Staged entries stay private until the catalog commit and SDK checks succeed.
private ImmutableDictionary<NodeId, ProjectedVariableDefinition> _committedProjectedDefinitions =
ImmutableDictionary<NodeId, ProjectedVariableDefinition>.Empty.WithComparers(
EqualityComparer<NodeId>.Default, System.Collections.Generic.ReferenceEqualityComparer.Instance);
private void CommitProjectedDefinition(NodeId id, ProjectedVariableDefinition definition) =>
Volatile.Write(ref _committedProjectedDefinitions, _committedProjectedDefinitions.SetItem(id, definition));
private void RemoveCommittedProjectedDefinition(NodeId id) =>
Volatile.Write(ref _committedProjectedDefinitions, _committedProjectedDefinitions.Remove(id));
private readonly ProjectedCandidateBudget _projectedCandidateBudget = new(65_536, 16 * 1024 * 1024);
internal ProjectedCandidateBudget ProjectedCandidateBudget => _projectedCandidateBudget;
internal bool IsProjectedItem(NodeId nodeId) => IsProjectedDescendant(nodeId);
@@ -4495,7 +4554,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
if (value is null || value.Proof is null || value.Realm is not (DataRealm.Raw or DataRealm.Uns)) { valid = false; continue; }
var id = new NodeId(value.LocalIdentifier, value.Realm == DataRealm.Raw ? NamespaceIndexes[2] : NamespaceIndexes[3]);
if (!seen.Add(id) || !_projectedVariables.TryGetValue(id, out var target) || target.Generation != value.ProjectionGeneration ||
!value.Proof.IsValid || !target.Guard() || target.Node is not BaseDataVariableState || value.Serving.ServingGeneration <= 0 ||
!value.Proof.IsValid || value.SourceVersion is <= 0 || !target.Guard() || target.Node is not BaseDataVariableState || value.Serving.ServingGeneration <= 0 ||
(target.Metadata.Serving is { } expected && expected != value.Serving) || !ProjectedValueMatches(target.Metadata, value.Snapshot.Value))
{ valid = false; continue; }
try
@@ -4515,6 +4574,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
if (valid && targets.Any(target => !target.Value.Proof.IsValid)) valid = false;
if (!valid || targets.Count != values.Count)
{
ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.SinkRejected);
// Retire only matching generations: a late old owner cannot invalidate a new projection.
foreach (var value in values)
{
@@ -4531,6 +4591,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
}
else
{
ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.SinkAccepted);
foreach (var target in targets)
{
var source = target.Value.Snapshot.Value;
@@ -4543,6 +4604,10 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
target.Node.Timestamp = detached.Snapshot.SourceTimestampUtc ?? DateTime.MinValue;
RemoveProjectedSample(target.Id);
_projectedSamples[target.Id] = detached; _projectedSampleCharges[target.Id] = target.Charge; _projectedSampleBytes += target.Charge;
// A completed baseline may equal the value already installed by another
// cadence. Recovered monitored items have cleared their SDK queues and
// still need the value callback even when no node field changed.
if (detached.IsCompleteSnapshot) target.Node.UpdateChangeMasks(NodeStateChangeMasks.Value);
target.Node.ClearChangeMasks(SystemContext, false);
}
}
@@ -4587,6 +4652,37 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
private readonly Dictionary<NodeId, (NodeId Parent, long Generation, DataMetadata Metadata, BaseInstanceState Node, Func<bool> Guard)> _projectedVariables = new();
bool IProjectedNamespacePageSink.TryRenewExact(NodeId nodeId, ProjectedVariableDefinition expected,
ProjectedVariableDefinition replacement, Func<bool> commit)
{
ArgumentNullException.ThrowIfNull(expected);
ArgumentNullException.ThrowIfNull(replacement);
ArgumentNullException.ThrowIfNull(commit);
lock (Lock)
{
if (_disposing || !_projectedDefinitions.TryGetValue(nodeId, out var old) ||
!_projectedVariables.TryGetValue(nodeId, out var existing) ||
!ReferenceEquals(old.Lifetime, expected.Lifetime) || !old.Lifetime.IsActive ||
old.Realm != replacement.Realm || old.LocalIdentifier != replacement.LocalIdentifier ||
old.Parent != replacement.Parent || old.Metadata.View != replacement.Metadata.View ||
old.Metadata.BrowseName != replacement.Metadata.BrowseName || old.Metadata.NodeKind != replacement.Metadata.NodeKind ||
old.Metadata.ValueKind != replacement.Metadata.ValueKind || old.Metadata.ValueRank != replacement.Metadata.ValueRank ||
old.Metadata.ArrayElementKind != replacement.Metadata.ArrayElementKind ||
!old.Metadata.Dimensions.SequenceEqual(replacement.Metadata.Dimensions) || !replacement.AuthorityIsCurrent()) return false;
var renewed = replacement with { Lifetime = old.Lifetime };
var charge = checked(ProjectedNodeCharge(renewed) +
(_projectedRootLeaves.ContainsKey(nodeId) ? ProjectedAnchorCharge(_projectedAnchors[nodeId].Definition) : 0));
var delta = charge - _projectedNodeCharges[nodeId];
if (delta > _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes ||
!commit() || !renewed.AuthorityIsCurrent() || !old.Lifetime.IsActive) return false;
_projectedVariables[nodeId] = (existing.Parent, renewed.ProjectionGeneration, renewed.Metadata, existing.Node, renewed.AuthorityIsCurrent);
_projectedDefinitions[nodeId] = renewed;
_projectedNodeBytes += delta; _projectedNodeCharges[nodeId] = charge;
CommitProjectedDefinition(nodeId, renewed);
return true;
}
}
bool IProjectedNamespacePageSink.TryApply(NodeId parent, IReadOnlyList<ProjectedVariableDefinition> nodes, Func<bool> commit)
{
ArgumentNullException.ThrowIfNull(nodes);
@@ -4596,7 +4692,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
{
if (_disposing) return false;
var added = new List<NodeId>();
var renewals = new List<(NodeId Id, ProjectedVariableDefinition Definition, long Charge)>();
var renewals = new List<(NodeId Id, ProjectedVariableDefinition Definition, long Charge,
ProjectedVariableDefinition Old, BaseInstanceState Node, long OldGeneration)>();
var seen = new HashSet<NodeId>();
var applied = false;
try
@@ -4609,32 +4706,46 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
if (_projectedVariables.TryGetValue(id, out var existing))
{
if (!_projectedDefinitions.TryGetValue(id, out var old) || existing.Parent != parent ||
existing.Generation != definition.ProjectionGeneration || !definition.AuthorityIsCurrent() ||
old.Parent != parent || old.Realm != definition.Realm || old.LocalIdentifier != definition.LocalIdentifier ||
!old.Lifetime.IsActive || !definition.AuthorityIsCurrent() ||
(existing.Generation != definition.ProjectionGeneration &&
(definition.ProjectionGeneration <= existing.Generation || old.AuthorityIsCurrent())) ||
old.Metadata.View != definition.Metadata.View || old.Metadata.BrowseName != definition.Metadata.BrowseName ||
old.Metadata.NodeKind != definition.Metadata.NodeKind || old.Metadata.ValueKind != definition.Metadata.ValueKind ||
old.Metadata.ValueRank != definition.Metadata.ValueRank || old.Metadata.ArrayElementKind != definition.Metadata.ArrayElementKind ||
!old.Metadata.Dimensions.SequenceEqual(definition.Metadata.Dimensions)) return false;
var renewed = ReferenceEquals(definition.Lifetime, old.Lifetime) ? definition : definition with { Lifetime = old.Lifetime };
renewals.Add((id, renewed, checked(ProjectedNodeCharge(renewed) +
(_projectedRootLeaves.ContainsKey(id) ? ProjectedAnchorCharge(_projectedAnchors[id].Definition) : 0))));
(_projectedRootLeaves.ContainsKey(id) ? ProjectedAnchorCharge(_projectedAnchors[id].Definition) : 0)),
old, existing.Node, existing.Generation));
continue;
}
if (!TryEnsureProjectedVariable(definition, out var created) || created != id) return false;
if (!TryEnsureProjectedVariable(definition, out var created, stage: true) || created != id) return false;
added.Add(id);
}
long renewalDelta = 0;
foreach (var renewal in renewals) renewalDelta = checked(renewalDelta + renewal.Charge - _projectedNodeCharges[renewal.Id]);
bool RenewalsCurrent() => renewals.All(renewal => renewal.Old.Lifetime.IsActive &&
_projectedDefinitions.TryGetValue(renewal.Id, out var current) && ReferenceEquals(current, renewal.Old) &&
_projectedVariables.TryGetValue(renewal.Id, out var variable) && variable.Parent == parent &&
variable.Generation == renewal.OldGeneration && ReferenceEquals(variable.Node, renewal.Node) &&
(renewal.OldGeneration == renewal.Definition.ProjectionGeneration || !renewal.Old.AuthorityIsCurrent()));
if (renewalDelta > _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes ||
nodes.Any(node => !node.AuthorityIsCurrent()) || !commit() || nodes.Any(node => !node.AuthorityIsCurrent())) return false;
!RenewalsCurrent() || !added.All(_projectedDefinitions.ContainsKey) || nodes.Any(node => !node.AuthorityIsCurrent()) ||
!commit() || !RenewalsCurrent() || !added.All(_projectedDefinitions.ContainsKey) ||
nodes.Any(node => !node.AuthorityIsCurrent())) return false;
foreach (var renewal in renewals)
{
var previous = _projectedVariables[renewal.Id];
_projectedVariables[renewal.Id] = (previous.Parent, previous.Generation, renewal.Definition.Metadata,
_projectedVariables[renewal.Id] = (previous.Parent, renewal.Definition.ProjectionGeneration, renewal.Definition.Metadata,
previous.Node, renewal.Definition.AuthorityIsCurrent);
_projectedDefinitions[renewal.Id] = renewal.Definition;
_projectedNodeBytes += renewal.Charge - _projectedNodeCharges[renewal.Id];
_projectedNodeCharges[renewal.Id] = renewal.Charge;
}
var committed = _committedProjectedDefinitions.SetItems(seen.Select(id =>
new KeyValuePair<NodeId, ProjectedVariableDefinition>(id, _projectedDefinitions[id])));
Volatile.Write(ref _committedProjectedDefinitions, committed);
applied = true;
return true;
}
@@ -4687,6 +4798,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
_projectedDefinitions[anchorId] = installed;
_projectedNodeCharges[anchorId] = renewedCharge;
_projectedNodeBytes += delta;
CommitProjectedDefinition(anchorId, installed);
return true;
}
if (anchor.Node is not FolderState folder) return false;
@@ -4729,6 +4841,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
_projectedDefinitions.Add(anchorId, installed);
_projectedNodeCharges[anchorId] = anchorCharge + charge; _projectedNodeBytes += charge; charged = true;
if (!installed.AuthorityIsCurrent() || !commit() || !installed.AuthorityIsCurrent()) return false;
CommitProjectedDefinition(anchorId, installed);
accepted = true; return true;
}
finally
@@ -4759,7 +4872,10 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
}
/// <summary>Materializes one checked scalar under its exact existing parent. Access stays denied until its live proof is wired.</summary>
internal bool TryEnsureProjectedVariable(ProjectedVariableDefinition definition, out NodeId? nodeId)
internal bool TryEnsureProjectedVariable(ProjectedVariableDefinition definition, out NodeId? nodeId) =>
TryEnsureProjectedVariable(definition, out nodeId, stage: false);
private bool TryEnsureProjectedVariable(ProjectedVariableDefinition definition, out NodeId? nodeId, bool stage)
{
nodeId = null;
if (definition is null || definition.Metadata is null || definition.AuthorityIsCurrent is null ||
@@ -4813,6 +4929,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
_projectedVariables.Add(candidate, (definition.Parent, definition.ProjectionGeneration, definition.Metadata, node, definition.AuthorityIsCurrent));
_projectedDefinitions.Add(candidate, definition);
_projectedNodeCharges.Add(candidate, charge); _projectedNodeBytes += charge;
if (!stage) CommitProjectedDefinition(candidate, definition);
nodeId = candidate; return true;
}
}
@@ -5424,6 +5541,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
lock (Lock)
{
retiredProofs = _projectedSamples.Values.Select(sample => sample.Proof).Distinct().ToArray();
Volatile.Write(ref _committedProjectedDefinitions, _committedProjectedDefinitions.Clear());
foreach (var item in _liveItems.Keys.OfType<ProjectedMonitoredItem>()) item.Retire();
foreach (var id in _projectedVariables.Keys) PredefinedNodes?.Remove(id);
foreach (var id in _projectedAnchors.Keys) PredefinedNodes?.Remove(id);
@@ -5841,9 +5959,13 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
if (_projectedAnchors.TryGetValue(nodeId, out var anchor) && operation == OpcUaOperation.Browse)
{
if (!anchor.Definition.AuthorityIsCurrent()) return false;
var localId = new NodeId(anchor.Definition.LocalSubject, NamespaceIndexForRealm(realm));
return _authorizer?.AuthorizeIfRequired(identity, operation, localId, realm) is null &&
(_authorizer is not null || _mappedSubjectResolver is null);
var scope = anchor.Definition.LocalScope;
return scope is not null && scope.Kind == (realm == AddressSpaceRealm.Raw ? NodeHierarchyKind.Raw : NodeHierarchyKind.Uns) &&
scope.Segments.Count > 0 && scope.Segments.All(segment => !string.IsNullOrWhiteSpace(segment) && !segment.Contains('/')) &&
string.Join('/', scope.Segments) == anchor.Definition.LocalSubject &&
scope.Segments[^1] == anchor.Definition.BrowseName &&
_authorizer is { } authorizer && authorizer.AuthorizeProjectedAnchor(identity, scope) &&
anchor.Definition.AuthorityIsCurrent();
}
if (nodeId.NamespaceIndex == NamespaceIndexes[2] || nodeId.NamespaceIndex == NamespaceIndexes[3])
return _authorizer is { } mappedAuthorizer && mappedAuthorizer.TryAuthorizeMapped(identity, operation, nodeId, realm, out var veto) && veto is null;
@@ -6395,7 +6517,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
NodeHandle handle)
{
if (SecurityFilteringActive && monitoringMode != MonitoringMode.Disabled
&& !(monitoredItem is ProjectedMonitoredItem projected && projected.IsCurrent)
&& !(monitoredItem is ProjectedMonitoredItem projected && projected.HasCurrentDemand)
&& !Permits(IdentityOf(context), OpcUaOperation.CreateMonitoredItems, handle.NodeId))
{
return StatusCodes.BadUserAccessDenied;
@@ -6412,6 +6534,13 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
TrackLiveMonitoredItem(handle, monitoredItem);
}
protected override void OnMonitoringModeChanged(ServerSystemContext context, NodeHandle handle,
ISampledDataChangeMonitoredItem monitoredItem, MonitoringMode previousMode, MonitoringMode monitoringMode)
{
base.OnMonitoringModeChanged(context, handle, monitoredItem, previousMode, monitoringMode);
if (monitoredItem is ProjectedMonitoredItem projected) projected.ResetHealthMonitoringMode();
}
/// <summary>Starts tracking <paramref name="monitoredItem"/> for revalidation, if we own its node.</summary>
/// <param name="handle">The handle the item was created against.</param>
/// <param name="monitoredItem">The item.</param>
@@ -6422,13 +6551,14 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
internal void TrackLiveMonitoredItem(NodeHandle handle, ISampledDataChangeMonitoredItem monitoredItem)
{
if (OwnsNamespace(handle.NodeId)) _liveItems[monitoredItem] = new LiveItem(handle);
if (monitoredItem is ProjectedMonitoredItem projected) TrackProjectedHealth(projected);
}
/// <inheritdoc />
protected override void OnMonitoredItemDeleted(
ServerSystemContext context, NodeHandle handle, ISampledDataChangeMonitoredItem monitoredItem)
{
if (monitoredItem is ProjectedMonitoredItem projected) projected.Retire();
if (monitoredItem is ProjectedMonitoredItem projected) { ForgetProjectedHealth(projected); projected.Retire(); }
if (_liveItems.TryRemove(monitoredItem, out var tracked) && tracked.Suppressed) Interlocked.Decrement(ref _suppressedItems);
base.OnMonitoredItemDeleted(context, handle, monitoredItem);
}
@@ -6574,6 +6704,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
if (!tracked.Suppressed || (nodeId is not null && tracked.Handle.NodeId != nodeId.Value)) continue;
if (!_liveItems.TryRemove(item, out _)) continue;
Interlocked.Decrement(ref _suppressedItems);
if (item is ProjectedMonitoredItem projected) projected.Retire();
TellNodeRemoved(item, now);
ReleaseComponentCacheReference(item);
}
@@ -6614,6 +6745,11 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
_cacheReferenceReleased.AddOrUpdate(item, ReleasedMarker);
}
// The SDK's classic item-manager factory has no rollback callback. A failed
// item is never returned to the SDK, so return its exact cache reference here.
internal void ReleaseFailedComponentCache(ISystemContext context, NodeHandle handle) =>
RemoveNodeFromComponentCache(context, handle);
/// <summary>Data items whose component-cache reference a removal already gave back (review fix I3). Weak, so an
/// item the SDK drops without a delete (it always deletes, but a leak here would be silent) is not kept alive.</summary>
private readonly System.Runtime.CompilerServices.ConditionalWeakTable<IMonitoredItem, object> _cacheReferenceReleased = new();
@@ -6729,6 +6865,69 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
/// for every create and delete including subscription teardown, so the map cannot outlive the items.
/// </remarks>
private readonly ConcurrentDictionary<ISampledDataChangeMonitoredItem, LiveItem> _liveItems = new();
private readonly object _projectedHealthGate = new();
private readonly LinkedList<ProjectedMonitoredItem> _projectedHealthItems = new();
private readonly Dictionary<ProjectedMonitoredItem, LinkedListNode<ProjectedMonitoredItem>> _projectedHealthIndex = new();
private LinkedListNode<ProjectedMonitoredItem>? _projectedHealthCursor;
private ITimer? _projectedHealthTimer;
private bool _projectedHealthStopped;
private int _projectedHealthRunning;
private void TrackProjectedHealth(ProjectedMonitoredItem item)
{
lock (_projectedHealthGate)
{
if (_projectedHealthStopped || item.HealthRetired || _projectedHealthIndex.ContainsKey(item)) return;
_projectedHealthIndex.Add(item, _projectedHealthItems.AddLast(item));
_projectedHealthTimer ??= ProjectedBrowseClock.CreateTimer(_ => SweepProjectedHealth(), null,
TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(100));
}
}
internal void ForgetProjectedHealth(ProjectedMonitoredItem item)
{
lock (_projectedHealthGate)
{
if (!_projectedHealthIndex.Remove(item, out var node)) return;
if (ReferenceEquals(_projectedHealthCursor, node)) _projectedHealthCursor = node.Next ?? _projectedHealthItems.First;
_projectedHealthItems.Remove(node);
if (_projectedHealthItems.Count == 0) _projectedHealthCursor = null;
}
}
private void SweepProjectedHealth()
{
if (Interlocked.Exchange(ref _projectedHealthRunning, 1) != 0) return;
try
{
var items = new List<ProjectedMonitoredItem>(256);
lock (_projectedHealthGate)
{
if (_projectedHealthStopped || _projectedHealthItems.Count == 0) return;
var count = Math.Min(256, _projectedHealthItems.Count);
var cursor = _projectedHealthCursor ?? _projectedHealthItems.First!;
for (var i = 0; i < count; i++)
{
items.Add(cursor.Value);
cursor = cursor.Next ?? _projectedHealthItems.First!;
}
_projectedHealthCursor = cursor;
}
foreach (var item in items)
{
try
{
if (item.HealthRetired) { ForgetProjectedHealth(item); continue; }
if (_liveItems.TryGetValue(item, out var tracked) && tracked.Suppressed)
RevalidateProjectedItem(item, tracked, UtcNow);
var loss = item.CaptureLoss();
if (loss is null) continue;
// Sample application uses this same order (manager lock, then item lock).
lock (Lock) if (!_disposing) item.QueueLossIfCurrent(loss);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{ _logger.LogDebug(ex, "Projected health observation will be retried"); }
}
}
finally { Volatile.Write(ref _projectedHealthRunning, 0); }
}
/// <summary>A tracked monitored item: the handle it was created against, and whether we have silenced it.</summary>
/// <param name="Handle">The node handle, which carries the <see cref="MonitoredNode2"/> fan-out list.</param>
@@ -8219,6 +8418,54 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
/// <c>QueueValue</c> calls between them, and the attach/detach is what actually needs the lock.
/// </para>
/// </remarks>
// The bounded health sweep and authority-change pass share this exact-item
// transition so renewal can reattach without a second global ACL pass.
private int RevalidateProjectedItem(ProjectedMonitoredItem item, LiveItem expected, DateTime now)
{
var restored = false;
var removed = false;
var changed = 0;
lock (Lock)
{
if (_disposing || !_liveItems.TryGetValue(item, out var current) || !ReferenceEquals(current, expected)) return 0;
bool permitted;
try { permitted = item.HasCurrentDemand; }
catch (Exception ex) when (ex is not OutOfMemoryException) { permitted = false; }
if (permitted && current.Suppressed)
{
var liveNode = (GetManagerHandle(current.Handle.NodeId) as NodeHandle)?.Node;
if (liveNode is not null && ReferenceEquals(liveNode, current.Handle.Node) && current.Handle.MonitoredNode is { } fanout)
{
fanout.Add((IDataChangeMonitoredItem2)item); current.Suppressed = false;
Interlocked.Decrement(ref _suppressedItems); restored = true; changed = 1;
}
else
{
_liveItems.TryRemove(item, out _); current.Suppressed = false;
Interlocked.Decrement(ref _suppressedItems); removed = true;
}
}
else if (!permitted && !current.Suppressed)
{
try
{
item.QueueValue(new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied, DateTimeUtc.MinValue, now),
new ServiceResult(StatusCodes.BadUserAccessDenied), ignoreFilters: true);
}
catch (Exception ex) when (ex is not OutOfMemoryException) { }
current.Handle.MonitoredNode?.Remove((IDataChangeMonitoredItem2)item);
current.Suppressed = true; Interlocked.Increment(ref _suppressedItems); changed = -1;
}
}
if (removed) { item.Retire(); TellNodeRemoved(item, now); }
else if (restored)
{
try { item.RequestBaseline(); }
catch (Exception ex) when (ex is not OutOfMemoryException) { }
}
return changed;
}
public void RevalidateMonitoredItems()
{
if (!SecurityFilteringActive) return;
@@ -8239,10 +8486,16 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
// re-checked — the deploy thread running this has no session of its own.
if (item is not IMonitoredItem live) continue;
if (item is ProjectedMonitoredItem projected)
{
var changed = RevalidateProjectedItem(projected, tracked, now);
if (changed < 0) stoodDown++;
else if (changed > 0) restored++;
continue;
}
var nodeId = tracked.Handle.NodeId;
var permitted = item is ProjectedMonitoredItem projectedItem
? projectedItem.HasCurrentDemand
: IsSubscriptionStillPermitted(live.EffectiveIdentity as RoleCarryingUserIdentity, nodeId, verdicts);
var permitted = IsSubscriptionStillPermitted(live.EffectiveIdentity as RoleCarryingUserIdentity, nodeId, verdicts);
if (permitted)
{
@@ -8266,7 +8519,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IPro
Interlocked.Decrement(ref _suppressedItems);
if (!reattached)
{
if (item is ProjectedMonitoredItem projected) projected.Retire();
if (item is ProjectedMonitoredItem removedProjected) removedProjected.Retire();
TellNodeRemoved(item, now);
continue;
}
@@ -413,7 +413,7 @@ public sealed class OtOpcUaSdkServer : StandardServer
demand is null || !demand.IsValid)
{ result[i] = StatusCodes.BadUserAccessDenied; continue; }
if (!manager.CanDispatchProjectedWrite()) { result[i] = StatusCodes.BadInvalidState; continue; }
var milliseconds = requestHeader is { TimeoutHint: > 0 } ? Math.Min(requestHeader.TimeoutHint, 5000u) : 5000u;
var milliseconds = requestHeader is { TimeoutHint: > 0 } ? Math.Min(requestHeader.TimeoutHint, 30000u) : 30000u;
var budget = new DataBudget(TimeSpan.FromMilliseconds(milliseconds), 1, 4 * 1024 * 1024);
var outcome = await access.WriteAsync(demand, SdkValueBoundary.ToClr(item.Value.WrappedValue), budget, started,
requestLifetime.CancellationToken).ConfigureAwait(false);
@@ -0,0 +1,13 @@
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>Bounded aggregate observations of projected SDK notification admission.</summary>
public static class ProjectedDeliveryDiagnostics
{
internal enum Event { SinkRejected, SinkAccepted, CandidateUnique, CandidateMissing, CandidateAmbiguous,
CurrentBindingRejected, CurrentProofRejected, CurrentAgeRejected, CurrentAccepted,
MarkerHandleRejected, MarkerFingerprintRejected, MarkerAuthorizationRejected, MarkerAccepted, MarkerException }
private static readonly long[] Counts = new long[Enum.GetValues<Event>().Length];
internal static void Count(Event value) => Interlocked.Increment(ref Counts[(int)value]);
/// <summary>Captures process-wide counters without source identifiers or payloads.</summary>
public static IReadOnlyDictionary<string, long> Capture() => Enum.GetValues<Event>().ToDictionary(x => x.ToString(), x => Interlocked.Read(ref Counts[(int)x]));
}
@@ -41,6 +41,10 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre
/// <inheritdoc />
public bool TryRemove(NodeId nodeId, ProjectedVariableDefinition expected) => ((IProjectedNamespacePageSink)_nodeManager).TryRemove(nodeId, expected);
/// <inheritdoc />
public bool TryRenewExact(NodeId nodeId, ProjectedVariableDefinition expected, ProjectedVariableDefinition replacement, Func<bool> commit) =>
((IProjectedNamespacePageSink)_nodeManager).TryRenewExact(nodeId, expected, replacement, commit);
/// <inheritdoc />
public bool TryApply(NodeId parent, IReadOnlyList<ProjectedVariableDefinition> nodes, Func<bool> commit) =>
((IProjectedNamespacePageSink)_nodeManager).TryApply(parent, nodes, commit);
@@ -149,6 +149,15 @@ public sealed class DataPlaneAuthorizer
NodeId nodeId, AddressSpaceRealm realm, bool cached = true) =>
Evaluate(identity, operation, nodeId, realm, cached, localBypass: !Enabled);
/// <summary>Checks a deployed mapping's local anchor scope regardless of the legacy ACL switch.</summary>
public bool AuthorizeProjectedAnchor(RoleCarryingUserIdentity? identity, NodeScope scope)
{
if (identity is null) return false;
var caller = new DataCallerIdentity(identity.Principal, identity.ApiKeyId,
identity.CredentialVersion, identity.CredentialExpiresUtc);
return _policy.AuthorizeLocal(caller, OpcUaOperation.Browse, scope);
}
/// <summary>Checks a mapping without changing the legacy local role gate.</summary>
public bool TryAuthorizeMapped(RoleCarryingUserIdentity? identity, OpcUaOperation operation,
NodeId nodeId, AddressSpaceRealm realm, out ServiceResult? veto)
@@ -351,18 +351,25 @@ internal sealed class OrdinaryTagItemManager(IAsyncNodeManager nodeManager, ISer
throw new ServiceResultException(StatusCodes.BadUserAccessDenied);
uint? reservedId = null;
ISampledDataChangeMonitoredItem? constructed = null;
MonitoredNode2? registeredNode = null;
var cacheAdded = false;
var createdNode = false;
try
{
// Mirrors MonitoredNodeMonitoredItemManager.CreateMonitoredItem in exact tagged 2.0.1, swapping only the item type.
var cachedNode = addNodeToComponentCache(context, handle, handle.Node);
cacheAdded = true;
if (!MonitoredNodes.TryGetValue(handle.Node.NodeId, out var monitoredNode))
{
MonitoredNodes[handle.Node.NodeId] = monitoredNode = new MonitoredNode2(nodeManager, server, cachedNode,
nodeManager.IsMultipleEventConsumerNode(cachedNode.NodeId));
createdNode = true;
}
handle.Node = monitoredNode.Node;
handle.MonitoredNode = monitoredNode;
registeredNode = monitoredNode;
uint id;
do
{
@@ -371,7 +378,7 @@ internal sealed class OrdinaryTagItemManager(IAsyncNodeManager nodeManager, ISer
while (!MonitoredItems.TryAdd(id, null!));
reservedId = id;
ISampledDataChangeMonitoredItem item = projected
ISampledDataChangeMonitoredItem item = constructed = projected
? new ProjectedMonitoredItem(server, nodeManager, handle, subscriptionId, id, itemToCreate, diagnosticsMasks,
timestampsToReturn, filterToUse, euRange, samplingInterval, revisedQueueSize, createDurable,
owner, demand!, initialSample, definition!)
@@ -386,6 +393,24 @@ internal sealed class OrdinaryTagItemManager(IAsyncNodeManager nodeManager, ISer
catch
{
if (reservedId is { } id) MonitoredItems.TryRemove(id, out _);
if (constructed is IDataChangeMonitoredItem2 data && registeredNode is not null)
{
try { registeredNode.Remove(data); } catch (Exception) { }
}
if (createdNode && registeredNode is not null && !registeredNode.HasMonitoredItems &&
MonitoredNodes.TryGetValue(registeredNode.Node.NodeId, out var currentNode) && ReferenceEquals(currentNode, registeredNode) &&
MonitoredNodes.TryRemove(registeredNode.Node.NodeId, out _))
{
try { registeredNode.Dispose(); } catch (Exception) { }
}
if (cacheAdded)
{
try { owner.ReleaseFailedComponentCache(context, handle); } catch (Exception) { }
}
if (constructed is IDisposable disposable)
{
try { disposable.Dispose(); } catch (Exception) { }
}
demand?.Dispose();
throw;
}
@@ -399,7 +424,7 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem
private IProjectedDemandLease? _demand;
private ProjectedVariableDefinition? _definition;
private readonly NodeId _nodeId;
private sealed class SourceBinding(IProjectedSamplePublicationProof proof)
internal sealed class SourceBinding(IProjectedSamplePublicationProof proof)
{
private readonly object _sync = new();
private IProjectedSamplePublicationProof? _proof = proof;
@@ -429,7 +454,7 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem
}
}
private sealed record Candidate(ProjectedValueWrite Sample, Variant Value, SourceBinding Binding, long Bytes, IDisposable Charge);
private sealed class SampleEvidence(SourceBinding binding, IProjectedSamplePublicationProof proof, DataAgeBounds age, long receivedTimestamp)
internal sealed class SampleEvidence(SourceBinding binding, IProjectedSamplePublicationProof proof, DataAgeBounds age, long receivedTimestamp)
{
private IProjectedSamplePublicationProof? _proof = proof;
public SourceBinding Binding => binding;
@@ -442,6 +467,10 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem
private const long MaxCandidateBytes = 1024 * 1024;
private readonly object _bindingSync = new();
private readonly List<Candidate> _candidates = [];
private SampleEvidence? _latestEvidence;
private SampleEvidence? _reportedLoss;
private LossControl? _queuedLoss;
internal Action? AfterLossDequeueForTests;
private long _candidateBytes;
private bool _needsSnapshot;
private int _snapshotRequested;
@@ -462,6 +491,7 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem
{
_binding = new(initialSample.Proof);
AddCandidate(initialSample, _binding);
_latestEvidence = new SampleEvidence(_binding, initialSample.Proof, initialSample.OriginAgeBounds, initialSample.ReceivedTimestamp);
}
}
@@ -471,11 +501,38 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem
lock (_bindingSync)
{
var original = _binding;
var sameSource = original is not null && ReferenceEquals(original.Proof?.SourceIdentity, sample.Proof.SourceIdentity);
// A new physical attempt may use the same logical source identity, but an
// ended attempt's captured evidence must not keep the SDK queue bound to it.
var sameSource = original is { IsValid: true } && ReferenceEquals(original.Proof?.SourceIdentity, sample.Proof.SourceIdentity);
if (sample.IsCompleteSnapshot && sameSource && !_needsSnapshot)
{
var matching = _candidates.FirstOrDefault(candidate => ReferenceEquals(candidate.Binding, original) &&
SameAcquisition(candidate.Sample, sample));
if (matching is not null)
{
// A queued notification keeps its original evidence. If it has expired,
// a separately fresh observation must start a new binding and queue.
if (FreshForDemand(matching.Sample))
{
// A separately proven observation may renew health without
// changing the queued candidate's original sample witness.
if (FreshForDemand(sample))
{
var successor = new SampleEvidence(original!, sample.Proof, sample.OriginAgeBounds, sample.ReceivedTimestamp);
_latestEvidence?.Clear();
_latestEvidence = successor; _reportedLoss = null;
}
return false;
}
if (!FreshForDemand(sample)) return true;
_needsSnapshot = true;
}
}
if (!sameSource || (_needsSnapshot && sample.IsCompleteSnapshot))
{
original?.Retire();
_binding = null;
_latestEvidence?.Clear(); _latestEvidence = null; _queuedLoss = null; _reportedLoss = null;
if (Volatile.Read(ref _retired) != 0 || !sample.IsCompleteSnapshot || !sample.Proof.IsSourceValid || _demand?.IsValid != true)
{ _needsSnapshot = true; return true; }
// Pinned SDK resets the entire data queue and last value across this transition.
@@ -491,9 +548,101 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem
}
if (_binding is null) { _needsSnapshot = true; return true; }
if (_candidates.Any(candidate => ReferenceEquals(candidate.Sample, sample))) return false;
return !AddCandidate(sample, _binding);
if (_queuedLoss is not null)
{
// A newly admitted value supersedes an unconsumed outage status.
// Reset the SDK queue before its normal value callback is delivered.
var mode = MonitoringMode;
if (mode != MonitoringMode.Disabled) { SetMonitoringMode(MonitoringMode.Disabled); SetMonitoringMode(mode); }
ClearCandidates(); _queuedLoss = null;
}
if (!AddCandidate(sample, _binding)) return true;
_latestEvidence?.Clear(); _reportedLoss = null;
_latestEvidence = new SampleEvidence(_binding, sample.Proof, sample.OriginAgeBounds, sample.ReceivedTimestamp);
return false;
}
}
internal bool HealthRetired => Volatile.Read(ref _retired) != 0;
internal sealed class LossControl(ProjectedMonitoredItem owner, SampleEvidence evidence)
{
internal bool IsCurrent => owner.IsLossCurrent(evidence);
internal bool IsAuthorized
{
get
{
try { return owner.HasCurrentDemand; }
catch (Exception ex) when (ex is not OutOfMemoryException) { return false; }
}
}
internal SampleEvidence Evidence => evidence;
}
private bool IsLossCurrent(SampleEvidence evidence)
{
if (Volatile.Read(ref _retired) != 0 || !ReferenceEquals(Volatile.Read(ref _latestEvidence), evidence) ||
!ReferenceEquals(Volatile.Read(ref _binding), evidence.Binding)) return false;
var proof = evidence.Proof;
var demand = _demand;
if (proof is null || demand is null) return true;
try
{
if (!proof.IsValid || demand.MaximumSampleAge <= TimeSpan.Zero) return true;
var elapsed = proof.Clock.GetElapsedTime(evidence.ReceivedTimestamp, proof.Clock.GetTimestamp());
return elapsed < TimeSpan.Zero || !evidence.Age.Advance(elapsed).IsFresh(demand.MaximumSampleAge);
}
catch (Exception ex) when (ex is not OutOfMemoryException) { return true; }
}
internal LossControl? CaptureLoss()
{
if (Volatile.Read(ref _queuedLoss) is not null) return null;
var latest = Volatile.Read(ref _latestEvidence);
if (ReferenceEquals(Volatile.Read(ref _reportedLoss), latest)) return null;
return latest is not null && IsLossCurrent(latest) ? new LossControl(this, latest) : null;
}
// Called under the manager lock, matching the order used by ObserveSample.
// No source/caller callback is evaluated while that lock is held.
internal void QueueLossIfCurrent(LossControl loss)
{
lock (_bindingSync)
{
if (MonitoringMode == MonitoringMode.Disabled || _queuedLoss is not null || ReferenceEquals(_reportedLoss, loss.Evidence) || _retired != 0 || !ReferenceEquals(_latestEvidence, loss.Evidence) ||
!ReferenceEquals(_binding, loss.Evidence.Binding)) return;
_queuedLoss = loss;
try { QueueValue(new DataValue(Variant.Null, StatusCodes.BadNoCommunication, DateTimeUtc.MinValue, DateTimeUtc.MinValue),
new ServiceResult(StatusCodes.BadNoCommunication), ignoreFilters: true); }
catch (Exception) { _queuedLoss = null; }
}
}
private bool FreshForDemand(ProjectedValueWrite sample)
{
if (_demand is not { IsValid: true } demand || demand.MaximumSampleAge <= TimeSpan.Zero || !sample.Proof.IsValid) return false;
try
{
return sample.OriginAgeBounds.Advance(sample.Proof.Clock.GetElapsedTime(sample.ReceivedTimestamp,
sample.Proof.Clock.GetTimestamp())).IsFresh(demand.MaximumSampleAge);
}
catch (Exception ex) when (ex is ArgumentException or OverflowException) { return false; }
}
internal static bool SameAcquisition(ProjectedValueWrite left, ProjectedValueWrite right)
{
if (left.SourceVersion is not > 0 || left.SourceVersion != right.SourceVersion ||
!ReferenceEquals(left.Proof.SourceIdentity, right.Proof.SourceIdentity) || !ReferenceEquals(left.Proof.Clock, right.Proof.Clock) ||
left.Realm != right.Realm || left.LocalIdentifier != right.LocalIdentifier || left.ProjectionGeneration != right.ProjectionGeneration ||
left.Serving != right.Serving ||
left.Snapshot.StatusCode != right.Snapshot.StatusCode || left.Snapshot.SourceTimestampUtc != right.Snapshot.SourceTimestampUtc ||
left.Snapshot.ServerTimestampUtc != right.Snapshot.ServerTimestampUtc) return false;
var first = left.Snapshot.Value; var second = right.Snapshot.Value;
if (first is Array || second is Array)
return first is Array firstArray && second is Array secondArray && firstArray.GetType() == secondArray.GetType() &&
System.Collections.StructuralComparisons.StructuralEqualityComparer.Equals(firstArray, secondArray);
return Equals(first, second);
}
// The SDK removes the DataValue info-type marker when it carries no info bits.
// Keep every actual information, structure, semantics, severity and subcode bit.
internal static bool SameObservedStatus(uint source, uint observed)
{
static uint Normalize(uint value) => (value & 0x00000FFFu) == 0x00000400u ? value & ~0x00000400u : value;
return Normalize(source) == Normalize(observed);
}
private bool AddCandidate(ProjectedValueWrite sample, SourceBinding binding)
{
long bytes = 256;
@@ -531,14 +680,20 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem
private bool IsCurrentCandidate(SourceBinding? binding, SampleEvidence? candidate)
{
if (candidate is null || !ReferenceEquals(candidate.Binding, binding) || !IsCurrentBinding(binding) ||
_demand is not { } demand || demand.MaximumSampleAge <= TimeSpan.Zero) return false;
if (candidate.Proof is not { IsValid: true } proof) { RequestBaseline(); return false; }
_demand is not { } demand || demand.MaximumSampleAge <= TimeSpan.Zero) { ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.CurrentBindingRejected); return false; }
if (candidate.Proof is not { IsValid: true } proof) { ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.CurrentProofRejected); RequestBaseline(); return false; }
try
{
var age = candidate.Age.Advance(proof.Clock.GetElapsedTime(candidate.ReceivedTimestamp, proof.Clock.GetTimestamp()));
if (age.IsFresh(demand.MaximumSampleAge)) return proof.IsValid && IsCurrentBinding(binding);
if (age.IsFresh(demand.MaximumSampleAge))
{
var current = proof.IsValid && IsCurrentBinding(binding);
ProjectedDeliveryDiagnostics.Count(current ? ProjectedDeliveryDiagnostics.Event.CurrentAccepted : ProjectedDeliveryDiagnostics.Event.CurrentBindingRejected);
return current;
}
}
catch (Exception ex) when (ex is ArgumentException or OverflowException) { }
ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.CurrentAgeRejected);
RequestBaseline();
return false;
}
@@ -547,42 +702,107 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem
internal bool IsCurrent => IsCurrentBinding(Volatile.Read(ref _binding));
internal bool HasCurrentDemand => Volatile.Read(ref _retired) == 0 && _demand is { IsValid: true } &&
_definition is { } definition && _owner.IsProjectedDefinitionCurrent(_nodeId, definition);
internal void ResetHealthMonitoringMode()
{
lock (_bindingSync) { _queuedLoss = null; _reportedLoss = null; }
}
internal void Retire()
{
Interlocked.Exchange(ref _retired, 1);
lock (_bindingSync) { _binding?.Retire(); _binding = null; ClearCandidates(); }
if (Interlocked.Exchange(ref _retired, 1) != 0) return;
_owner.ForgetProjectedHealth(this);
lock (_bindingSync) { _binding?.Retire(); _binding = null; _latestEvidence?.Clear(); _latestEvidence = null; _queuedLoss = null; _reportedLoss = null; ClearCandidates(); }
_definition = null;
if (Interlocked.Exchange(ref _released, 1) == 0) Interlocked.Exchange(ref _demand, null)?.Dispose();
}
protected override void Dispose(bool disposing)
{
try { if (disposing) Retire(); }
finally { base.Dispose(disposing); }
}
public override bool Publish(OperationContext context, Queue<MonitoredItemNotification> notifications,
Queue<DiagnosticInfo> diagnostics, uint maximum, ILogger logger)
{
var captured = Volatile.Read(ref _binding);
var local = new Queue<MonitoredItemNotification>();
var localDiagnostics = new Queue<DiagnosticInfo>();
var more = base.Publish(context, local, localDiagnostics, maximum, logger);
SourceBinding? captured;
LossControl? capturedLoss;
bool more;
lock (_bindingSync)
{
captured = _binding;
capturedLoss = _queuedLoss;
more = base.Publish(context, local, localDiagnostics, maximum, logger);
}
var hadLocal = local.Count > 0;
if (capturedLoss is not null && local.Any(x => x.Value.WrappedValue.IsNull && x.Value.StatusCode.Code == StatusCodes.BadNoCommunication))
AfterLossDequeueForTests?.Invoke();
var sawLoss = false;
while (local.Count > 0)
{
var notification = local.Dequeue();
SampleEvidence? evidence = null;
lock (_bindingSync)
{
if (capturedLoss is { } loss && notification.Value.WrappedValue.IsNull &&
notification.Value.StatusCode.Code == StatusCodes.BadNoCommunication)
{
sawLoss = true;
if (ReferenceEquals(_queuedLoss, loss)) _queuedLoss = null;
if (ReferenceEquals(_latestEvidence, loss.Evidence)) _reportedLoss = loss.Evidence;
notifications.Enqueue(new ProjectedSdkNotification(notification,
new ProjectedLossMarker(notification.ClientHandle, loss)));
if (localDiagnostics.Count > 0) diagnostics.Enqueue(localDiagnostics.Dequeue());
continue;
}
// The SDK can replace a Bad source sample's value with null. Every
// Bad candidate of the same status could have produced that null;
// consider all of them before using a source timestamp to disambiguate.
var badNull = notification.Value.WrappedValue.IsNull && StatusCode.IsBad(notification.Value.StatusCode);
var matching = _candidates.Where(candidate => ReferenceEquals(candidate.Binding, captured) &&
candidate.Value.Equals(notification.Value.WrappedValue) && candidate.Sample.Snapshot.StatusCode == notification.Value.StatusCode.Code).Take(2).ToArray();
(badNull || candidate.Value.Equals(notification.Value.WrappedValue)) &&
SameObservedStatus(candidate.Sample.Snapshot.StatusCode, notification.Value.StatusCode.Code)).Take(2).ToArray();
if (matching.Length > 1 && notification.Value.SourceTimestamp != DateTimeUtc.MinValue)
{
// The SDK carries the source timestamp from the projected node. It can
// distinguish equal values from different acquisitions, but only when
// exactly one retained acquisition has that original timestamp.
matching = _candidates.Where(candidate => ReferenceEquals(candidate.Binding, captured) &&
(badNull || candidate.Value.Equals(notification.Value.WrappedValue)) &&
SameObservedStatus(candidate.Sample.Snapshot.StatusCode, notification.Value.StatusCode.Code) &&
candidate.Sample.Snapshot.SourceTimestampUtc is { } sourceTimestamp &&
(DateTimeUtc)sourceTimestamp == notification.Value.SourceTimestamp).Take(2).ToArray();
}
if (matching.Length == 1 && notification.Value.SourceTimestamp != DateTimeUtc.MinValue &&
matching[0].Sample.Snapshot.SourceTimestampUtc is { } originalTimestamp &&
(DateTimeUtc)originalTimestamp != DateTimeUtc.MinValue &&
(DateTimeUtc)originalTimestamp != notification.Value.SourceTimestamp)
{
// A contradictory timestamp cannot consume the sole remaining
// candidate's proof, even when value and status happen to match.
matching = [];
}
if (matching.Length == 1)
{
ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.CandidateUnique);
var matched = matching[0]; _candidates.Remove(matched); _candidateBytes -= matched.Bytes;
evidence = matched.Binding.Capture(matched.Sample.Proof, matched.Sample.OriginAgeBounds, matched.Sample.ReceivedTimestamp);
matched.Charge.Dispose();
}
else _needsSnapshot = true;
else { ProjectedDeliveryDiagnostics.Count(matching.Length == 0 ? ProjectedDeliveryDiagnostics.Event.CandidateMissing : ProjectedDeliveryDiagnostics.Event.CandidateAmbiguous); _needsSnapshot = true; }
}
if (evidence is null) RequestBaseline();
var originalSample = evidence;
notification.Message = new ProjectedNotificationMarker(notification.ClientHandle, notification.Value, () => IsCurrentCandidate(captured, originalSample));
notifications.Enqueue(notification);
notifications.Enqueue(new ProjectedSdkNotification(notification,
new ProjectedNotificationMarker(notification.ClientHandle, notification.Value,
() => IsCurrentCandidate(captured, originalSample))));
if (localDiagnostics.Count > 0) diagnostics.Enqueue(localDiagnostics.Dequeue());
}
if (!sawLoss && capturedLoss is not null && !more)
{
lock (_bindingSync)
if (ReferenceEquals(_queuedLoss, capturedLoss) && hadLocal)
_queuedLoss = null;
}
while (localDiagnostics.Count > 0) diagnostics.Enqueue(localDiagnostics.Dequeue());
return more;
}
@@ -608,7 +828,37 @@ internal sealed class SdkStandbyProjection(OtOpcUaNodeManager nodeManager, WarmS
public int RefreshAllEventItems() => nodeManager.RefreshAllEventItems();
}
/// <summary>Captured per-notification proof. A stale pooled helper is treated as denied.</summary>
/// <summary>Owns a projected payload and keeps its proof through the SDK's server-side clone.</summary>
internal sealed class ProjectedSdkNotification : MonitoredItemNotification
{
public ProjectedSdkNotification(MonitoredItemNotification rented, NotificationMessage marker)
{
ClientHandle = rented.ClientHandle;
Value = rented.Value;
DiagnosticInfo = rented.DiagnosticInfo;
Marker = marker;
// The SDK resets its encoded fields on return. Clear its manual fields
// before returning this stock object for ordinary or built-in items.
rented.Message = null!;
rented.DiagnosticInfo = null!;
rented.Reuse();
}
internal NotificationMessage? Marker { get; private set; }
protected override void ReuseCore()
{
// ACK, eviction and message disposal use this hook through IPooledEncodeable.
// This subclass stays out of the shared stock pool.
Marker = null;
Message = null!;
DiagnosticInfo = null!;
ResetForReuse();
}
}
/// <summary>Captured authority and value identity for a projected notification.</summary>
internal sealed class ProjectedNotificationMarker : NotificationMessage
{
private readonly uint _clientHandle;
@@ -618,13 +868,16 @@ internal sealed class ProjectedNotificationMarker : NotificationMessage
{ _clientHandle = clientHandle; _fingerprint = Fingerprint(value); _authorize = authorize; }
public bool Permits(MonitoredItemNotification notification)
{
if (notification.ClientHandle != _clientHandle || _fingerprint is null) return false;
if (notification.ClientHandle != _clientHandle || _fingerprint is null) { ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.MarkerHandleRejected); return false; }
try
{
var current = Fingerprint(notification.Value);
return current is not null && System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(_fingerprint, current) && _authorize();
if (current is null || !System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(_fingerprint, current)) { ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.MarkerFingerprintRejected); return false; }
var allowed = _authorize();
ProjectedDeliveryDiagnostics.Count(allowed ? ProjectedDeliveryDiagnostics.Event.MarkerAccepted : ProjectedDeliveryDiagnostics.Event.MarkerAuthorizationRejected);
return allowed;
}
catch { return false; }
catch { ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.MarkerException); return false; }
}
private static byte[]? Fingerprint(DataValue value)
{
@@ -652,6 +905,14 @@ internal sealed class ProjectedNotificationMarker : NotificationMessage
}
}
internal sealed class ProjectedLossMarker(uint clientHandle, ProjectedMonitoredItem.LossControl loss) : NotificationMessage
{
internal bool IsObsolete => !loss.IsCurrent;
internal bool Permits(MonitoredItemNotification notification) => notification.ClientHandle == clientHandle &&
notification.Value.WrappedValue.IsNull && notification.Value.StatusCode.Code == StatusCodes.BadNoCommunication &&
notification.Value.SourceTimestamp == DateTimeUtc.MinValue && loss.IsAuthorized;
}
/// <summary>Rechecks captured projected notification authority for every delivery and retransmission.</summary>
internal static class ProjectedNotificationRewriter
{
@@ -664,21 +925,48 @@ internal static class ProjectedNotificationRewriter
if (!payload.TryGetValue<DataChangeNotification>(out var change) || change is null)
{ payloads.Add(payload); continue; }
var items = new List<MonitoredItemNotification>(change.MonitoredItems.Count);
var originalDiagnostics = change.DiagnosticInfos.ToArray() ?? [];
var alignedDiagnostics = originalDiagnostics.Length == change.MonitoredItems.Count;
var keptDiagnostics = new List<DiagnosticInfo>(originalDiagnostics.Length);
var changedPayload = false;
var index = 0;
foreach (var item in change.MonitoredItems)
{
if (item.Message is ProjectedNotificationMarker marker && !marker.Permits(item))
var diagnostic = alignedDiagnostics ? originalDiagnostics[index] : null;
index++;
var projected = item as ProjectedSdkNotification;
var marker = projected?.Marker;
if (marker is ProjectedLossMarker loss && loss.IsObsolete)
{
changedPayload = true;
continue;
}
if (marker is ProjectedLossMarker deniedLoss && !deniedLoss.Permits(item))
{
if (deniedLoss.IsObsolete) { changedPayload = true; continue; }
items.Add(new MonitoredItemNotification { ClientHandle = item.ClientHandle,
Value = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied, DateTimeUtc.MinValue, item.Value.ServerTimestamp) });
changedPayload = true;
if (alignedDiagnostics) keptDiagnostics.Add(diagnostic!);
continue;
}
if (marker is ProjectedLossMarker currentLoss && currentLoss.IsObsolete)
{ changedPayload = true; continue; }
if (projected is not null && marker is not ProjectedLossMarker &&
(marker is not ProjectedNotificationMarker proof || !proof.Permits(item)))
{
items.Add(new MonitoredItemNotification { ClientHandle = item.ClientHandle,
Value = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied, DateTimeUtc.MinValue, item.Value.ServerTimestamp) });
changedPayload = true;
}
else items.Add(item);
if (alignedDiagnostics) keptDiagnostics.Add(diagnostic!);
}
if (changedPayload)
{
changed = true;
payloads.Add(new ExtensionObject(new DataChangeNotification { MonitoredItems = items, DiagnosticInfos = change.DiagnosticInfos }));
payloads.Add(new ExtensionObject(new DataChangeNotification { MonitoredItems = items,
DiagnosticInfos = alignedDiagnostics ? keptDiagnostics.ToArray() : change.DiagnosticInfos }));
}
else payloads.Add(payload);
}
@@ -4,6 +4,16 @@ using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
internal interface IObsoleteProjectedSample { bool CanDropExpiredPredecessor { get; } }
internal static class ProjectedEvidenceRetirement
{
internal static bool CanDrop(IProjectedSamplePublicationProof proof)
{
try { return !proof.IsValid && proof.IsSourceValid && proof is IObsoleteProjectedSample { CanDropExpiredPredecessor: true }; }
catch (Exception) { return false; }
}
}
/// <summary>Owns bounded imported-value messages through the actual SDK apply, with captured route ownership.</summary>
public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDisposable
{
@@ -128,7 +138,14 @@ public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDi
}
}
public TimeProvider Clock => source.Clock;
public void Invalidate() { try { source.Invalidate(); } finally { owner.RetireWitness(binding, identity); } }
public void Invalidate()
{
// An expired sample can remain queued across a compatible authority
// handoff. Discard that evidence without retiring the independently live
// logical source which may already own a fresh successor baseline.
if (ProjectedEvidenceRetirement.CanDrop(source) && IsSourceValid) return;
try { source.Invalidate(); } finally { owner.RetireWitness(binding, identity); }
}
}
private bool OwnsIdentity(Binding binding, object identity)
{
@@ -159,6 +176,7 @@ public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDi
{
foreach (var update in updates)
{
if (ProjectedEvidenceRetirement.CanDrop(update.SourceProof) && IsCurrent(update.Route)) continue;
try { update.SourceProof.Invalidate(); } catch (Exception) { }
Retire(update.Route);
}
@@ -187,7 +205,7 @@ public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDi
var update = captured[i];
update.OriginAgeBounds.Validate();
if (!ReferenceEquals(update.SourceProof.Clock, _clock) || !update.SourceProof.IsValid
|| _clock.GetElapsedTime(update.ReceivedTimestamp) < TimeSpan.Zero || !Authorized(update.Route)) return Refused();
|| update.SourceVersion is <= 0 || _clock.GetElapsedTime(update.ReceivedTimestamp) < TimeSpan.Zero || !Authorized(update.Route)) return Refused();
charge = checked(charge + 512 + OwnedDataSample.Estimate(update.Snapshot.Value));
}
var admitted = false;
@@ -212,7 +230,7 @@ public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDi
var writes = captured.Select((update, i) => new ProjectedValueWrite(update.Route.Realm, update.Route.LocalIdentifier,
update.Route.ProjectionGeneration, update.Route.Serving,
update.Snapshot with { Value = OwnedDataSample.CopyLegacy(update.Snapshot.Value) }, update.OriginAgeBounds,
update.ReceivedTimestamp, WitnessFor(bindings[i], update), update.IsCompleteSnapshot)).ToArray();
update.ReceivedTimestamp, WitnessFor(bindings[i], update), update.IsCompleteSnapshot, update.SourceVersion)).ToArray();
batch = new(writes, captured.Select(update => update.Route).ToArray(), Complete, ForwardToMux);
lock (_sync)
{
@@ -8,6 +8,9 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
public sealed record DataConnectionDeploymentSnapshot(long ScopeVersion, string ArtifactRevision, IReadOnlyList<DataConnection> Connections,
RedundancyMode ConsumerMode = RedundancyMode.None);
/// <summary>Host-effective role eligibility and the continuity epoch observed under its role fence.</summary>
public sealed record DataConnectionConsumerRoleSnapshot(RedundancyMode Mode, bool Eligible, long Epoch);
/// <summary>Persists the node's current connection-to-secret allowlist before any route is made ready.</summary>
public interface IDataConnectionScopeActivator
{
@@ -22,12 +25,17 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
int Streams, int Monitored, long PendingBytes);
private sealed record Desired(long ScopeVersion, string ArtifactRevision, long Generation, RedundancyMode ConsumerMode,
IReadOnlyDictionary<string, Spec> Specs, IReadOnlyDictionary<string, string> Allowlist);
private sealed class Entry(Spec spec, long generation, GrpcDataConnection connection, CancellationToken token)
private sealed class Entry(Spec spec, long generation, GrpcDataConnection connection, CancellationToken token,
RedundancyMode artifactMode, DataConnectionConsumerRoleSnapshot? role)
{
internal readonly Spec Spec = spec;
internal readonly long Generation = generation;
internal readonly GrpcDataConnection Connection = connection;
internal readonly CancellationToken Token = token;
internal readonly object RouteIdentity = new();
internal readonly RedundancyMode ArtifactMode = artifactMode;
internal readonly DataConnectionConsumerRoleSnapshot? Role = role;
internal volatile bool Live = true;
internal bool Ready;
internal int Leases;
}
@@ -39,6 +47,8 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
private readonly int _maximum;
private readonly TimeProvider _clock;
private readonly Func<bool> _consumerMayAcquire;
private readonly Func<RedundancyMode, DataConnectionConsumerRoleSnapshot?>? _consumerRoleSnapshot;
private readonly bool _useCompactBatches;
private readonly CancellationTokenSource _stop = new();
private readonly ITimer _retryTimer;
private readonly Dictionary<string, Entry> _entries = new(StringComparer.OrdinalIgnoreCase);
@@ -53,13 +63,15 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
public DataConnectionDeploymentRuntime(string nodeId, string ownerCluster, IDataConnectionSecurityProvider security,
IDataConnectionScopeActivator scopeActivator, int maxConnections, TimeProvider? clock = null,
Func<bool>? consumerMayAcquire = null)
Func<bool>? consumerMayAcquire = null, bool useCompactBatches = true,
Func<RedundancyMode, DataConnectionConsumerRoleSnapshot?>? consumerRoleSnapshot = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(nodeId); ArgumentException.ThrowIfNullOrWhiteSpace(ownerCluster);
if (maxConnections <= 0) throw new ArgumentOutOfRangeException(nameof(maxConnections));
_node = nodeId; _owner = ownerCluster; _security = security ?? throw new ArgumentNullException(nameof(security));
_activator = scopeActivator ?? throw new ArgumentNullException(nameof(scopeActivator)); _maximum = maxConnections;
_clock = clock ?? TimeProvider.System; _consumerMayAcquire = consumerMayAcquire ?? (() => true);
_clock = clock ?? TimeProvider.System; _consumerMayAcquire = consumerMayAcquire ?? (() => true); _useCompactBatches = useCompactBatches;
_consumerRoleSnapshot = consumerRoleSnapshot;
_retryTimer = _clock.CreateTimer(static state => ((DataConnectionDeploymentRuntime)state!).OnRetry(), this,
Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
_manager = new DataConnectionManager(nodeId, maxConnections);
@@ -190,6 +202,16 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
a.Batch == b.Batch && a.Page == b.Page && a.MessageBytes == b.MessageBytes && a.Streams == b.Streams &&
a.Monitored == b.Monitored && a.PendingBytes == b.PendingBytes;
private bool MayAcquire() { try { return _consumerMayAcquire(); } catch (Exception) { return false; } }
private DataConnectionConsumerRoleSnapshot? CaptureRole(RedundancyMode mode)
{ try { return _consumerRoleSnapshot?.Invoke(mode); } catch (Exception) { return null; } }
private bool RouteCurrent(Entry entry)
{
if (!entry.Live || entry.Token.IsCancellationRequested) return false;
if (entry.Role is not { Eligible: true, Epoch: > 0 and < long.MaxValue } captured)
return true;
var current = CaptureRole(entry.ArtifactMode);
return current is { Eligible: true, Epoch: > 0 and < long.MaxValue } && current.Mode == captured.Mode && current.Epoch == captured.Epoch;
}
private void ApplyManagerScopeLocked(Desired desired)
{
// The manager owns configured-node scope and physical lifetime only. Role checks
@@ -207,6 +229,15 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
{
if (_disposed || _desired is null) return;
if (_attemptPending) return;
if (_consumerRoleSnapshot is not null && _entries.Count > 0)
{
var snapshots = _entries.Values.Select(entry => (Entry: entry, Current: CaptureRole(entry.ArtifactMode))).ToArray();
if (snapshots.All(x => x.Entry.Role is { Mode: RedundancyMode.Hot, Eligible: true, Epoch: > 0 and < long.MaxValue }) &&
snapshots.Any(x => x.Current is not { Epoch: > 0 })) return;
if (snapshots.All(x => x.Entry.Role is { Mode: RedundancyMode.Hot, Eligible: true, Epoch: > 0 and < long.MaxValue } captured &&
x.Current is { Mode: RedundancyMode.Hot, Eligible: true, Epoch: > 0 and < long.MaxValue } current && captured.Epoch == current.Epoch))
{ WakeLocked(); return; }
}
DisarmRetryLocked();
var generation = checked(++_generation);
_desired = _desired with { Generation = generation };
@@ -312,6 +343,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
{
Entry? existing;
long securityGeneration;
DataConnectionConsumerRoleSnapshot? beforeRole;
lock (_sync)
{
if (_disposed || _attemptPending || _desired?.Generation != desired.Generation) break;
@@ -319,6 +351,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
_entries.TryGetValue(spec.Id, out existing);
if (existing?.Ready == true) continue;
securityGeneration = _securityGeneration;
beforeRole = CaptureRole(desired.ConsumerMode);
}
var available = false;
try
@@ -339,6 +372,12 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
if (_disposed || _attemptPending || _desired?.Generation != desired.Generation || _securityGeneration != securityGeneration) continue;
if (!MayAcquire()) { retryNeeded = true; break; }
if (_entries.TryGetValue(spec.Id, out existing)) { existing.Ready = true; continue; }
var role = CaptureRole(desired.ConsumerMode);
if (_consumerRoleSnapshot is not null && (role is null || !role.Eligible || role.Epoch <= 0 || role.Epoch == long.MaxValue))
{ retryNeeded = true; continue; }
if (_consumerRoleSnapshot is not null && (beforeRole is null || !beforeRole.Eligible || beforeRole.Epoch <= 0 ||
beforeRole.Epoch == long.MaxValue || beforeRole.Mode != role!.Mode || beforeRole.Epoch != role.Epoch))
{ retryNeeded = true; continue; }
DataConnectionScopeLease scope;
try { scope = _manager.Acquire(spec.Id); }
catch (UnauthorizedAccessException) { continue; }
@@ -346,8 +385,8 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
{
var connection = new GrpcDataConnection(spec.Id, spec.Target, spec.Endpoints, _security, scope,
spec.MessageBytes, spec.Endpoints.Length, _clock, spec.EligibleNodes,
spec.Streams, spec.Monitored, maxPendingCommandBytes: spec.PendingBytes);
_entries.Add(spec.Id, new Entry(spec, desired.Generation, connection, scope.CancellationToken) { Ready = true });
spec.Streams, spec.Monitored, maxPendingCommandBytes: spec.PendingBytes, enableCompactBatches: _useCompactBatches);
_entries.Add(spec.Id, new Entry(spec, desired.Generation, connection, scope.CancellationToken, desired.ConsumerMode, role) { Ready = true });
}
catch (Exception) { scope.Dispose(); retryNeeded = true; }
}
@@ -364,6 +403,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
}
private void Retire(Entry entry)
{
entry.Live = false;
var task = entry.Connection.DisposeAsync().AsTask();
lock (_sync) _retirements.Add(task);
_ = ObserveRetirementAsync(task);
@@ -379,14 +419,27 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
lock (_sync)
{
lease = null;
if (_disposed || !_scopeReady || !MayAcquire() || !_entries.TryGetValue(id, out var entry) || !entry.Ready ||
if (!_disposed && _desired is { } desired && _entries.TryGetValue(id, out var stale) &&
stale.Role is { Eligible: true, Epoch: > 0 and < long.MaxValue } captured &&
CaptureRole(stale.ArtifactMode) is { Epoch: > 0 and < long.MaxValue } observed &&
(observed.Mode != captured.Mode || !observed.Eligible || observed.Epoch != captured.Epoch))
{
_entries.Remove(id);
var generation = checked(++_generation);
_desired = desired with { Generation = generation };
_routeRevisions[id] = generation;
ApplyManagerScopeLocked(_desired);
Retire(stale);
if (!_attemptPending) WakeLocked();
}
if (_disposed || !_scopeReady || !MayAcquire() || !_entries.TryGetValue(id, out var entry) || !entry.Ready || !RouteCurrent(entry) ||
entry.Token.IsCancellationRequested || entry.Leases >= 1024) return false;
entry.Leases++;
lease = new DataConnectionDeploymentLease(entry.Connection, entry.Token, entry.Spec.Operations, entry.Spec.Timeout,
entry.Spec.Batch, entry.Spec.Page, entry.Spec.MessageBytes, entry.Spec.Streams, entry.Spec.Monitored, entry.Spec.PendingBytes,
() => { lock (_sync) return !_disposed && _scopeReady && MayAcquire() && entry.Ready &&
() => { lock (_sync) return !_disposed && _scopeReady && MayAcquire() && entry.Ready && RouteCurrent(entry) &&
_entries.TryGetValue(id, out var current) && ReferenceEquals(entry, current); },
() => { lock (_sync) entry.Leases--; });
() => { lock (_sync) entry.Leases--; }, () => RouteCurrent(entry), entry.RouteIdentity);
return true;
}
}
@@ -423,13 +476,18 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDisposable
private readonly long _pendingBytes;
private readonly Func<bool> _current;
private readonly Action _release;
private readonly Func<bool> _routeCurrent;
internal object? RouteIdentity { get; }
private int _disposed;
internal DataConnectionDeploymentLease(IDataConnection inner, CancellationToken scope, DataOperations allowed, TimeSpan timeout,
int batch, int page, int bytes, int streams, int monitored, long pendingBytes, Func<bool> current, Action release)
int batch, int page, int bytes, int streams, int monitored, long pendingBytes, Func<bool> current, Action release, Func<bool>? routeCurrent = null, object? routeIdentity = null)
{
_inner = inner; _scope = scope; _allowed = allowed; _timeout = timeout; _batch = batch; _page = page; _bytes = bytes;
_streams = streams; _monitored = monitored; _pendingBytes = pendingBytes; _current = current; _release = release;
_routeCurrent = routeCurrent ?? (() => !scope.IsCancellationRequested);
RouteIdentity = routeIdentity;
}
internal Func<bool> RouteCurrent => _routeCurrent;
public IDataConnection Connection => this;
public CancellationToken CancellationToken => _scope;
public DataTarget Target => _inner.Target;
@@ -495,14 +553,31 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDisposable
{
public ServingIdentity Serving { get; } = serving;
}
private class ScopedSubscription(DataConnectionDeploymentLease owner, IDataSubscription inner) : IDataSubscription
private class ScopedSubscription(DataConnectionDeploymentLease owner, IDataSubscription inner) : IDataSubscription, IDataSubscriptionFreshnessSupport
{
public bool SupportsFreshnessChallenges => inner is IDataSubscriptionFreshnessSupport { SupportsFreshnessChallenges: true };
public int FreshnessMaxItems => inner is IDataSubscriptionFreshnessSupport support && support.SupportsFreshnessChallenges
? Math.Min(support.FreshnessMaxItems, Math.Min(owner._batch, owner._monitored)) : 0;
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
{
owner.Check(DataOperations.Subscribe);
var count = command switch { OpenSubscription o => o.Items.Count, AddSubscriptionItems a => a.Items.Count,
ModifySubscriptionItems m => m.Items.Count, RemoveSubscriptionItems r => r.Items.Count, _ => owner._monitored + 1 };
ModifySubscriptionItems m => m.Items.Count, RemoveSubscriptionItems r => r.Items.Count,
ChallengeSubscriptionFreshness c => c.Items.Count, _ => owner._monitored + 1 };
if (count > owner._monitored) throw new ArgumentOutOfRangeException(nameof(command));
if (command is ChallengeSubscriptionFreshness challenge)
{
if (!SupportsFreshnessChallenges) throw new InvalidOperationException("Peer did not negotiate freshness challenges.");
if (count <= 0 || count > FreshnessMaxItems) throw new ArgumentOutOfRangeException(nameof(command));
// Conservative preflight before any wire encoding, including UTF-8 expansion and per-handle overhead.
var bytes = 128L + 4L * (challenge.SubscriptionId?.Length ?? 0) + 4L * (challenge.CommandId?.Length ?? 0);
foreach (var handle in challenge.Items)
{
if (handle is null) throw new ArgumentException("Invalid challenge handle.", nameof(command));
bytes = checked(bytes + 128L + 4L * (handle.SubscriptionId?.Length ?? 0));
}
if (bytes > Math.Min(owner._bytes, owner._pendingBytes)) throw new ArgumentOutOfRangeException(nameof(command));
}
if (command is OpenSubscription open) command = open with { SnapshotBudget = owner.Limit(open.SnapshotBudget, owner._monitored) };
return inner.SendAsync(command, cancellationToken);
}
@@ -22,6 +22,8 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
private readonly Dictionary<ulong, Item> _items = new();
private readonly Dictionary<string, Item> _itemsByClient = new(StringComparer.Ordinal);
private readonly LinkedList<InterestGroup> _interests = new();
private readonly HashSet<InterestGroup> _temporaryInterests = [];
private readonly Dictionary<ulong, int> _challengedHandles = new();
private LinkedListNode<InterestGroup>? _interestCursor;
private readonly List<SnapshotLease> _snapshots = [];
private readonly List<IDisposable> _snapshotAdmissions = [];
@@ -36,12 +38,17 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
private SubscriptionItemHandleTable? _handles;
private ITimer? _expiry, _tick, _ackTimer, _preOpen;
private string? _subscriptionId;
private string? _freshnessChallengeId;
private ServingIdentity? _serving;
private long _epoch, _sequence, _dirtySequence, _ackId, _lastHeartbeat;
private long _lastFreshnessSequence;
private int _mode, _closed, _closing, _tickQueued, _queuedValues, _barrier, _admissionCursor, _coalesced;
private readonly Task _worker;
internal Task Completion => _worker;
internal Action? BeforeDirectCommitForTests { get; set; }
internal Action? SnapshotEndCommittedForTests { get; set; }
internal Action<int, int, int>? BeforeDirtyTickForTests { get; set; }
internal Action? AfterTickForTests { get; set; }
internal Action<DataItemHandle, long>? OnCandidateQueuedForTests { get; set; }
private sealed class SharedSessionLease(IDisposable lease) : IDisposable
@@ -97,7 +104,7 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
internal bool SnapshotComplete;
}
private sealed class SnapshotJob(SnapshotLease snapshot, IDisposable admission, InterestGroup group,
IReadOnlyList<Item> items, IReadOnlyList<PartitionWatermark> watermarks)
IReadOnlyList<Item> items, IReadOnlyList<PartitionWatermark> watermarks, bool temporaryInterest = false)
{
internal readonly SnapshotLease Snapshot = snapshot;
internal readonly IDisposable Admission = admission;
@@ -105,6 +112,8 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
internal readonly IReadOnlyList<Item> Items = items;
internal readonly IReadOnlyList<PartitionWatermark> Watermarks = watermarks;
internal int Index;
internal bool Started;
internal readonly bool TemporaryInterest = temporaryInterest;
}
private sealed class StagedChange(Item previous, SubscriptionAuthorizedView view, DataSubscriptionSettings settings,
IDisposable demand, SnapshotLease snapshot, SourceInterestLease interest, IDisposable admission,
@@ -278,6 +287,7 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
AddSubscriptionItems add => add with { Items = CopyItems(add.Items) },
ModifySubscriptionItems modify => modify with { Items = CopyItems(modify.Items) },
RemoveSubscriptionItems remove => remove with { Items = CopyHandles(remove.Items) },
ChallengeSubscriptionFreshness challenge => challenge with { Items = CopyHandles(challenge.Items) },
_ => throw new ArgumentException("Unknown subscription command.", nameof(command))
};
if (bytes > _limits.MaxPendingBytes) throw new ArgumentOutOfRangeException(nameof(command));
@@ -329,13 +339,15 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
else
{
if (_handles is null || command.SubscriptionId != _subscriptionId || command.StreamEpoch != _epoch) { Stop(); break; }
if (command is ModifySubscriptionItems && HasIncompleteSnapshot())
if (command is ModifySubscriptionItems && HasIncompleteSnapshot() ||
command is ChallengeSubscriptionFreshness && HasOutstandingSnapshots())
{ _deferred.Enqueue(work); retained = true; Interlocked.CompareExchange(ref _barrier, 1, 0); continue; }
switch (command)
{
case AddSubscriptionItems add: await AddAsync(add.Items, add.CommandId, work.Started, add.AcknowledgementTimeout).ConfigureAwait(false); break;
case ModifySubscriptionItems modify: await ModifyAsync(modify, work.Started).ConfigureAwait(false); break;
case RemoveSubscriptionItems remove: await RemoveAsync(remove).ConfigureAwait(false); break;
case ChallengeSubscriptionFreshness challenge: await ChallengeFreshnessAsync(challenge).ConfigureAwait(false); break;
default: Stop(); break;
}
}
@@ -358,6 +370,8 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
_itemsByClient.Clear();
foreach (var interest in _interests) interest.Lease.Dispose();
_interests.Clear();
foreach (var interest in _temporaryInterests) interest.Lease.Dispose();
_temporaryInterests.Clear();
foreach (var snapshot in _snapshots) snapshot.Dispose();
_snapshots.Clear();
foreach (var admission in _snapshotAdmissions) admission.Dispose();
@@ -375,6 +389,11 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
lock (_gate) return _interests.Any(group => !group.SnapshotComplete);
}
private bool HasOutstandingSnapshots()
{
lock (_gate) return _snapshots.Count != 0;
}
private void ReleaseBarrier(int expected)
{
if (Interlocked.CompareExchange(ref _barrier, 0, expected) != expected) return;
@@ -508,7 +527,6 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
await EnqueueAsync(ControlAck(commandId, acks,
() => !snapshot!.IsReset && admission.Permit.IsValid && admitted.All(item => item.View.CanPublish()))).ConfigureAwait(false);
var marks = snapshot!.Watermarks.Select(x => new PartitionWatermark(x.Key, x.Value)).ToArray();
await EnqueueAsync(Control(DataStreamControlKind.SnapshotBegin, marks, snapshot, admission.Permit)).ConfigureAwait(false);
foreach (var item in admitted)
{
if (item.Ticket is not { } ticket || !snapshot.Items.TryGetValue(ticket, out var captured)) continue;
@@ -519,6 +537,54 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
await PumpSnapshotsAsync().ConfigureAwait(false);
}
private async Task ChallengeFreshnessAsync(ChallengeSubscriptionFreshness challenge)
{
// Limit both capture work and retained memory through the same snapshot admission as Open/Add.
if (challenge.CommandId.Length > 32 || !challenge.CommandId.StartsWith("freshness-", StringComparison.Ordinal) ||
!long.TryParse(challenge.CommandId.AsSpan("freshness-".Length), System.Globalization.NumberStyles.None,
System.Globalization.CultureInfo.InvariantCulture, out var sequence) || sequence <= _lastFreshnessSequence ||
challenge.Items.Count == 0 || challenge.Items.Count > _services.SubscriptionLimits.MaxBatchItems ||
challenge.Items.Distinct().Count() != challenge.Items.Count) { Stop(); return; }
var items = new List<Item>(challenge.Items.Count);
lock (_gate)
{
foreach (var handle in challenge.Items)
{
if (!_handles!.IsCurrent(handle) || !_items.TryGetValue(handle.Handle, out var item) ||
item.Handle != handle || item.Ticket is null || !item.View.CanPublish()) { Stop(); return; }
items.Add(item);
}
}
var tickets = items.Select(x => x.Ticket!.Value).Distinct().ToArray();
if (!_capacity.Snapshots.TryAcquire(_context.PrincipalId, 1, out var rawAdmission))
{ CloseWithReset("Freshness snapshot admission exhausted; retry later."); return; }
var permit = (SnapshotAdmissionScheduler.Permit)rawAdmission!;
if (!permit.TryRetain(out var hold)) { permit.Dispose(); Stop(); return; }
var admission = new SnapshotOwnership(permit, hold!);
var budget = new DataBudget(challenge.AcknowledgementTimeout, tickets.Length, _limits.MaxPendingBytes);
if (!_services.SubscriptionHub.TryCaptureInterestSnapshot(tickets, budget, _stop.Token, out var snapshot, out var interest, permit))
{ admission.Dispose(); Stop(); return; }
var group = new InterestGroup(interest!);
_lastFreshnessSequence = sequence;
lock (_gate)
{
_snapshots.Add(snapshot!); _snapshotAdmissions.Add(admission); _temporaryInterests.Add(group);
foreach (var item in items)
{
_challengedHandles.TryGetValue(item.Handle.Handle, out var count);
_challengedHandles[item.Handle.Handle] = checked(count + 1);
}
}
// Values created after this store compute their age after the causal challenge.
Volatile.Write(ref _freshnessChallengeId, challenge.CommandId);
var acks = items.Select(item => new DataSubscriptionItemAck(item.ClientItemId, DataItemStatus.Good, item.Handle, item.Settings, null)).ToArray();
await EnqueueAsync(ControlAck(challenge.CommandId, acks,
() => !snapshot!.IsReset && permit.IsValid && items.All(item => item.View.CanPublish()))).ConfigureAwait(false);
var marks = snapshot!.Watermarks.Select(x => new PartitionWatermark(x.Key, x.Value)).ToArray();
_snapshotJobs.AddLast(new SnapshotJob(snapshot, admission, group, items, marks, temporaryInterest: true));
await PumpSnapshotsAsync().ConfigureAwait(false);
}
private async Task RemoveAsync(RemoveSubscriptionItems remove)
{
var acks = new List<DataSubscriptionItemAck>();
@@ -738,6 +804,8 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
private async Task TickAsync()
{
try
{
lock (_gate)
{
for (var count = 0; count < Math.Min(32, _snapshotAdmissions.Count); count++)
@@ -749,8 +817,6 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
}
for (var count = 0; count < 32 && _committedSnapshots.TryDequeue(out var committed); count++)
{
await EnqueueAsync(Control(DataStreamControlKind.SnapshotBegin, committed.Watermarks, committed.Snapshot,
((SnapshotOwnership)committed.Admission).Permit)).ConfigureAwait(false);
_snapshotJobs.AddLast(committed);
}
if (_services.Clock.GetElapsedTime(_lastHeartbeat) >= TimeSpan.FromSeconds(5))
@@ -797,12 +863,13 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
}
}
await PumpSnapshotsAsync().ConfigureAwait(false);
BeforeDirtyTickForTests?.Invoke(_outbound.Reader.Count, Volatile.Read(ref _queuedValues), interests.Count);
foreach (var interest in interests)
{
if (!interest.TryReadChanges(32, out var changes)) { CloseWithReset("Source change history expired."); return; }
foreach (var change in changes) MarkDirty(change.Ticket.Key);
}
var availableValues = Math.Max(0, Math.Max(1, _limits.MaxPendingFrames - 2) - Volatile.Read(ref _queuedValues));
var availableValues = AvailableValueSlots();
if (availableValues > 0)
foreach (var scheduled in _scheduler.TakeSlice(Math.Min(32, availableValues)))
{
@@ -814,7 +881,7 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
var dueItems = new List<Item>();
lock (_gate)
{
availableValues = Math.Max(0, Math.Max(1, _limits.MaxPendingFrames - 2) - Volatile.Read(ref _queuedValues));
availableValues = AvailableValueSlots();
for (var count = 0; count < Math.Min(32, availableValues) && _due.Count > 0 && _due.Min.Due <= now; count++)
{
var entry = _due.Min; _due.Remove(entry);
@@ -823,6 +890,8 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
}
}
foreach (var item in dueItems) await ConsiderAsync(item).ConfigureAwait(false);
}
finally { AfterTickForTests?.Invoke(); }
}
private async Task<bool> RecoverWaitingAsync(Item item, SourceTicket ticket)
@@ -848,7 +917,6 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
group.Node = _interests.AddLast(group); item.Interest = group;
}
var marks = snapshot!.Watermarks.Select(x => new PartitionWatermark(x.Key, x.Value)).ToArray();
await EnqueueAsync(Control(DataStreamControlKind.SnapshotBegin, marks, snapshot, admission.Permit)).ConfigureAwait(false);
var captured = snapshot.Items[ticket];
if (captured.Sample is not null) item.LastConsidered = captured.Sample.Version;
_snapshotJobs.AddLast(new SnapshotJob(snapshot, admission!, group, [item], marks));
@@ -861,13 +929,21 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
var budget = Math.Min(32, _snapshotJobs.Count * 2);
while (budget-- > 0 && _snapshotJobs.First is { } node && Volatile.Read(ref _closing) == 0)
{
var job = node.Value; _snapshotJobs.RemoveFirst();
var job = node.Value;
if (job.Snapshot.IsReset || !((SnapshotOwnership)job.Admission).Permit.IsValid)
{ CloseWithReset("Snapshot catch-up expired; retry later."); return; }
if (!job.Started)
{
// Leave a control slot available for command acknowledgements. A dequeued
// frame queues another tick, so a blocked boundary remains resumable.
if (_outbound.Reader.Count >= Math.Max(1, _limits.MaxPendingFrames - 1)) return;
await EnqueueAsync(Control(DataStreamControlKind.SnapshotBegin, job.Watermarks, job.Snapshot,
((SnapshotOwnership)job.Admission).Permit)).ConfigureAwait(false);
job.Started = true;
}
if (job.Index < job.Items.Count)
{
if (Volatile.Read(ref _queuedValues) >= Math.Max(1, _limits.MaxPendingFrames - 2))
{ _snapshotJobs.AddFirst(job); return; }
if (AvailableValueSlots() == 0) return;
var item = job.Items[job.Index++];
if (_handles!.IsCurrent(item.Handle) && item.Ticket is { } ticket &&
job.Snapshot.Items.TryGetValue(ticket, out var captured) && captured.Sample is not null &&
@@ -877,34 +953,66 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
((SnapshotOwnership)job.Admission).Permit);
if (delivery is null)
{
if (!_handles.IsCurrent(item.Handle)) { _snapshotJobs.AddLast(job); continue; }
if (!_handles.IsCurrent(item.Handle)) continue;
CloseWithReset("Pending snapshot memory exhausted."); return;
}
await EnqueueAsync(delivery).ConfigureAwait(false);
}
_snapshotJobs.AddLast(job);
continue;
}
if (_outbound.Reader.Count >= Math.Max(1, _limits.MaxPendingFrames - 1)) return;
_snapshotJobs.RemoveFirst();
await EnqueueAsync(Control(DataStreamControlKind.SnapshotEnd, job.Watermarks, job.Snapshot,
((SnapshotOwnership)job.Admission).Permit, () =>
{
var allComplete = false;
lock (_gate)
{
SnapshotEndCommittedForTests?.Invoke();
job.Group.SnapshotComplete = true;
if (job.TemporaryInterest) _temporaryInterests.Remove(job.Group);
_snapshots.Remove(job.Snapshot); _snapshotAdmissions.Remove(job.Admission);
allComplete = _interests.All(group => group.SnapshotComplete);
allComplete = _snapshots.Count == 0 && _interests.All(group => group.SnapshotComplete);
}
job.Snapshot.Dispose(); job.Admission.Dispose(); QueueTick();
job.Snapshot.Dispose(); job.Admission.Dispose();
if (job.TemporaryInterest) FinishChallengeSnapshot(job);
QueueTick();
if (allComplete) ReleaseBarrier(1);
}, () => { job.Snapshot.Dispose(); job.Admission.Dispose(); })).ConfigureAwait(false);
}, () =>
{
job.Snapshot.Dispose(); job.Admission.Dispose();
if (job.TemporaryInterest)
{
FinishChallengeSnapshot(job);
}
})).ConfigureAwait(false);
}
}
private void MarkDirty(BackingSourceKey source) => _scheduler.TryMarkDirty(source, Interlocked.Increment(ref _dirtySequence));
private void FinishChallengeSnapshot(SnapshotJob job)
{
lock (_gate)
{
_temporaryInterests.Remove(job.Group);
foreach (var item in job.Items)
{
if (!_challengedHandles.TryGetValue(item.Handle.Handle, out var count)) continue;
if (count > 1) _challengedHandles[item.Handle.Handle] = count - 1;
else
{
_challengedHandles.Remove(item.Handle.Handle);
if (_handles?.IsCurrent(item.Handle) == true) MarkDirty(item.View.Source);
}
}
}
job.Group.Lease.Dispose();
}
private async Task ConsiderAsync(Item item)
{
lock (_gate) if (_challengedHandles.ContainsKey(item.Handle.Handle)) return;
if (item.Ticket is not { } ticket) return;
using var read = _services.SubscriptionHub.Read(ticket);
if (read.Readiness != DataReadiness.Ready || read.Sample is null) { CloseWithReset("Source became unavailable."); return; }
@@ -986,10 +1094,12 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
}
return new PendingDelivery(sequence =>
{
// Capture the admitted challenge before computing the age; queued/prepared frames retain this witness.
var freshnessChallengeId = Volatile.Read(ref _freshnessChallengeId);
var age = _services.Clock.GetElapsedTime(received);
if (age < TimeSpan.Zero) throw new InvalidOperationException("Invalid monotonic age.");
return new DataSubscriptionValues(_subscriptionId!, _epoch, sequence, snapshot,
[new(item.Handle, owned, new DataAgeBounds(age, null), DataReadiness.Ready)], lease);
[new(item.Handle, owned, new DataAgeBounds(age, null), DataReadiness.Ready, freshnessChallengeId)], lease);
}, Gate, Commit, () => { owned.Dispose(); lease.Dispose(); }, true,
() => Volatile.Read(ref _closing) != 0 || !_handles!.IsCurrent(item.Handle), Eligible,
snapshot ? bytes =>
@@ -1034,6 +1144,15 @@ internal sealed class DataSubscriptionSession : IDataSubscriptionTransport
_services.CanUseSubscription(_context, _target, _serving),
() => { delivered?.Invoke(); return true; }, dropped, obsolete: () => Volatile.Read(ref _closing) != 0);
}
// Snapshot controls and ACKs share the same bounded channel as values. Check
// both limits before removing scheduler work or advancing a snapshot item.
private int AvailableValueSlots()
{
var valueSlots = Math.Max(0, Math.Max(1, _limits.MaxPendingFrames - 2) - Volatile.Read(ref _queuedValues));
var channelSlots = Math.Max(0, _limits.MaxPendingFrames - _outbound.Reader.Count);
return Math.Min(valueSlots, channelSlots);
}
private Task EnqueueAsync(PendingDelivery delivery)
{
if (Volatile.Read(ref _closed) != 0 || Volatile.Read(ref _closing) != 0) { delivery.Dispose(); return Task.CompletedTask; }
@@ -38,6 +38,8 @@ internal sealed class DataWriteExecutor(DataAuthenticatedContext context, Func<L
public async Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request);
// The caller's budget covers validation and all batch preflight work.
var started = clock.GetTimestamp();
ArgumentNullException.ThrowIfNull(request.Items);
request.Budget.Validate();
cancellationToken.ThrowIfCancellationRequested();
@@ -51,7 +53,6 @@ internal sealed class DataWriteExecutor(DataAuthenticatedContext context, Func<L
totalBytes = checked(totalBytes + RetainedBytes(item));
}
if (totalBytes > request.Budget.MaxBytes) throw new ArgumentOutOfRangeException(nameof(request), "Write batch exceeds its byte limit.");
var started = clock.GetTimestamp();
var pending = request.Items.Select(item => ExecuteItem(item, request.Budget, started, cancellationToken)).ToArray();
return await Task.WhenAll(pending).ConfigureAwait(false);
}
@@ -94,12 +95,37 @@ internal sealed class DataWriteExecutor(DataAuthenticatedContext context, Func<L
return new(item.CorrelationId, existing);
}
var remaining = budget.Timeout - clock.GetElapsedTime(start);
if (item.RemainingBudget < remaining) remaining = item.RemainingBudget;
// Preserve one absolute request deadline, including the per-item bound; do not
// restart it after route lookup, byte admission, or retained-value preparation.
var allowance = item.RemainingBudget < budget.Timeout ? item.RemainingBudget : budget.Timeout;
long expiration;
try
{
if (allowance <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(item));
var timestampTicks = checked((long)((decimal)allowance.Ticks * clock.TimestampFrequency / TimeSpan.TicksPerSecond));
expiration = checked(start + timestampTicks);
}
catch (Exception ex) when (ex is OverflowException or ArgumentException)
{
var rejected = Rejected("Invalid write deadline or value.");
claim.Complete(rejected);
return new(item.CorrelationId, rejected);
}
bool HasDispatchBudget(long now)
{
try
{
var elapsed = clock.GetElapsedTime(start, now);
return elapsed >= TimeSpan.Zero && elapsed < allowance && now < expiration &&
allowance - elapsed >= bounds.GatewayAsk;
}
catch (Exception ex) when (ex is ArgumentException or OverflowException) { return false; }
}
WriteRouteTarget? target;
try { target = remaining >= bounds.GatewayAsk && route.TryResolve(node.Metadata.View, out var resolved) ? resolved : null; }
try { target = !cancellationToken.IsCancellationRequested && HasDispatchBudget(clock.GetTimestamp()) &&
route.TryResolve(node.Metadata.View, out var resolved) ? resolved : null; }
catch { target = null; }
if (target is null)
if (target is null || cancellationToken.IsCancellationRequested || !HasDispatchBudget(clock.GetTimestamp()))
{
var rejected = Rejected("Insufficient budget or no active driver route.");
claim.Complete(rejected);
@@ -116,7 +142,6 @@ internal sealed class DataWriteExecutor(DataAuthenticatedContext context, Func<L
try
{
var issued = clock.GetTimestamp();
var expiration = checked(issued + (long)(remaining.TotalSeconds * clock.TimestampFrequency));
var admission = new DataWriteAdmission(context.PrincipalId, node.Metadata.View, current.AuthorityEpoch,
current.Serving.CatalogEpoch, current.Serving.Incarnation, target.DriverIncarnation, item.OperationId,
expiration, context.ApiKeyId, context.CredentialExpiresUtc, context.CredentialVersion);
@@ -132,6 +157,13 @@ internal sealed class DataWriteExecutor(DataAuthenticatedContext context, Func<L
claim.Complete(rejected);
return new(item.CorrelationId, rejected);
}
if (cancellationToken.IsCancellationRequested || !HasDispatchBudget(clock.GetTimestamp()))
{
ticket.Dispose();
var rejected = Rejected("Insufficient budget or no active driver route.");
claim.Complete(rejected);
return new(item.CorrelationId, rejected);
}
_ = DispatchAsync(route, ticket, claim);
return new(item.CorrelationId, await claim.Completion.WaitAsync(cancellationToken).ConfigureAwait(false));
}
@@ -20,6 +20,8 @@ public sealed class DeployedGrpcDataConnectionSource(DataConnectionDeploymentRun
{
public Core.Abstractions.DataConnections.IDataConnection Connection => lease.Connection;
public CancellationToken CancellationToken => lease.CancellationToken;
public object? RouteIdentity => lease.RouteIdentity;
public Func<bool> RouteCurrent => lease.RouteCurrent;
public ValueTask DisposeAsync() => lease.DisposeAsync();
}
}
@@ -64,6 +64,19 @@ internal sealed class DriverHostSubscriptionDemandSource : ISubscriptionDemandSo
// Counts actual reference keys visited to materialize physical desired sets.
internal long ReferenceVisitCount => Interlocked.Read(ref _referenceVisits);
internal SubscriptionDemandAccounting CaptureAccounting()
{
int interests, drivers, desired, applied, retiring;
lock (_gate)
{
interests = _interests.Count; drivers = _drivers.Count;
desired = _drivers.Values.Sum(state => state.References.Count);
applied = _drivers.Values.Sum(state => Volatile.Read(ref state.Applied)?.References.Length ?? 0);
retiring = _drivers.Values.Count(state => state.Interests == 0);
}
var registry = _registry.CaptureAccounting();
return new(interests, registry.Groups, registry.Interests, drivers, desired, applied, retiring);
}
internal Task WaitForDriverIdleForTest(string driver)
{
lock (_gate) return _drivers.TryGetValue(driver, out var state) ? state.IdleForTest.Task : Task.CompletedTask;
@@ -5,12 +5,28 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Combines the remote metadata lease with local catalog and connection retirement fences.</summary>
internal sealed class BoundProjectionLease(MetadataAuthorityLease remote, CancellationToken route,
IDataMappedCatalogAuthority local, ProjectedCatalogCache cache, string mapping, long generation, Func<bool> bindingCurrent) : IDataAuthorizationLease
IDataMappedCatalogAuthority local, ProjectedCatalogCache cache, string mapping, long generation, Func<bool> bindingCurrent,
Func<bool>? routeCurrent = null, object? routeIdentity = null, DataTarget? target = null, object? bindingIdentity = null) : IDataAuthorizationLease
{
public ServingIdentity Serving => remote.Serving;
public bool IsValid => !route.IsCancellationRequested && local.IsActive && remote.IsValid && bindingCurrent() && cache.IsCurrentGeneration(mapping, generation);
internal object? RouteIdentity => routeIdentity;
internal DataTarget? Target => target;
internal object? BindingIdentity => bindingIdentity;
internal TimeSpan Remaining => remote.Remaining;
internal TimeSpan UsableDuration => remote.UsableDuration;
private bool RouteAlive => !route.IsCancellationRequested && (routeCurrent?.Invoke() ?? true);
internal bool LiveContext => RouteAlive && local.IsActive && bindingCurrent() && cache.IsCurrentGeneration(mapping, generation);
internal bool ExpiredNaturally => remote.ExpiredNaturally && LiveContext;
public bool IsValid => LiveContext && remote.IsValid;
internal ProjectionLeaseDiagnostics CaptureDiagnostics() => new(RouteAlive, local.IsActive,
remote.IsValid, bindingCurrent(), cache.IsCurrentGeneration(mapping, generation));
}
// Read-only observations, not an authorization decision. The five fences can change
// between reads, and callers must continue to use IsValid for authority.
internal sealed record ProjectionLeaseDiagnostics(bool RouteAlive, bool LocalAuthorityActive, bool RemoteLeaseValid,
bool MappingBindingCurrent, bool CacheGenerationCurrent);
/// <summary>A page holds its physical connection lease until the caller commits or aborts it.</summary>
internal sealed class PreparedPage : IProjectedPreparedPage
{
@@ -13,6 +13,8 @@ public sealed partial class GrpcDataConnection
private DateTime? _lastSampleAtUtc, _metadataLeaseExpiresAtUtc, _lastVerifiedAtUtc;
private TimeSpan? _sampleAgeUpper;
private long _sampleReceivedTimestamp;
private long _compactFrameCount, _fallbackFrameCount, _serializedValueFrameBytes;
private readonly string _accountingInstanceId = Guid.NewGuid().ToString("N");
private long _resetCount, _coalescedCount, _writeSucceededCount, _writeRejectedCount, _writeUnknownCount, _writeFailedCount, _writeUnconfirmedCount;
internal DataConnectionDiagnosticsSnapshot CaptureDiagnostics(long revision, long scopeVersion, string artifactRevision)
@@ -28,7 +30,9 @@ public sealed partial class GrpcDataConnection
WriteUnknownCount: Interlocked.Read(ref _writeUnknownCount), ProtocolMajor: _diagnosticMajor, ProtocolMinor: _diagnosticMinor, LastVerifiedAtUtc: _lastVerifiedAtUtc,
WriteFailedCount: Interlocked.Read(ref _writeFailedCount), WriteUnconfirmedCount: Interlocked.Read(ref _writeUnconfirmedCount),
SampleAgeUpperBound: ObservedUpperAge(),
CoalescedCount: Interlocked.Read(ref _coalescedCount));
CoalescedCount: Interlocked.Read(ref _coalescedCount),
CompactFrameCount: Interlocked.Read(ref _compactFrameCount), FallbackFrameCount: Interlocked.Read(ref _fallbackFrameCount),
SerializedValueFrameBytes: Interlocked.Read(ref _serializedValueFrameBytes), AccountingInstanceId: _accountingInstanceId);
}
private TimeSpan? ObservedUpperAge()
@@ -34,6 +34,9 @@ public sealed partial class GrpcDataConnection : IDataConnection
internal readonly CancellationTokenSource Retired = new();
}
private sealed record Selected(ChannelEntry Channel, DataCapabilities Capabilities);
// Capability discovery is a protocol envelope, not an operation result page.
// Bound its advertised kinds by the locally understood finite enum.
private static readonly int MaxCapabilityKinds = Enum.GetValues<DataValueKind>().Length - 1;
private readonly object _sync = new();
private readonly string _id;
private readonly Uri[] _endpoints;
@@ -42,6 +45,7 @@ public sealed partial class GrpcDataConnection : IDataConnection
private readonly DataConnectionScopeLease _scope;
private readonly int _maxMessageBytes, _maxChannels, _maxStreams, _maxMonitoredItems, _maxPendingCommands;
private readonly TimeSpan _maxCommandTimeout;
private readonly bool _enableCompactBatches;
private readonly SemaphoreSlim _unaryCapacity;
private readonly CommandStateBudget _commandBudget;
private readonly Dictionary<DataConnectionChannelIdentity, ChannelEntry> _channels = new();
@@ -66,7 +70,8 @@ public sealed partial class GrpcDataConnection : IDataConnection
IDataConnectionSecurityProvider security, DataConnectionScopeLease scope, int maxMessageBytes,
int maxChannels, TimeProvider? clock = null, IReadOnlySet<string>? eligibleNodeIds = null,
int maxStreams = 16, int maxMonitoredItems = 10_000, int maxPendingCommands = 256,
int maxConcurrentUnaryCalls = 64, TimeSpan? maxCommandTimeout = null, long maxPendingCommandBytes = 4 * 1024 * 1024)
int maxConcurrentUnaryCalls = 64, TimeSpan? maxCommandTimeout = null, long maxPendingCommandBytes = 4 * 1024 * 1024,
bool enableCompactBatches = true)
{
ArgumentException.ThrowIfNullOrWhiteSpace(connectionId);
ArgumentNullException.ThrowIfNull(target); target.Validate();
@@ -80,6 +85,7 @@ public sealed partial class GrpcDataConnection : IDataConnection
_maxCommandTimeout = maxCommandTimeout ?? TimeSpan.FromSeconds(30);
if (_maxCommandTimeout <= TimeSpan.Zero || _maxCommandTimeout > TimeSpan.FromDays(1)) throw new ArgumentOutOfRangeException(nameof(maxCommandTimeout));
_maxStreams = maxStreams; _maxMonitoredItems = maxMonitoredItems; _maxPendingCommands = maxPendingCommands;
_enableCompactBatches = enableCompactBatches;
_unaryCapacity = new(maxConcurrentUnaryCalls, maxConcurrentUnaryCalls);
_commandBudget = new CommandStateBudget(Math.Min(maxPendingCommandBytes, 4L * 1024 * 1024));
if (target.Mode == DataTargetMode.Cluster && (eligibleNodeIds is null || eligibleNodeIds.Count == 0 || eligibleNodeIds.Any(string.IsNullOrWhiteSpace)))
@@ -227,9 +233,11 @@ public sealed partial class GrpcDataConnection : IDataConnection
{
var channel = await ChannelAsync(endpoint, ct).ConfigureAwait(false);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _scope.CancellationToken, channel.Retired.Token, _shutdown.Token);
var response = await channel.Client.GetCapabilitiesAsync(new W.CapabilitiesRequest { ProtocolMajor = 1, ProtocolMinor = 3 },
var response = await channel.Client.GetCapabilitiesAsync(new W.CapabilitiesRequest { ProtocolMajor = 1, ProtocolMinor = 5 },
Options(channel, start, budget, linked.Token)).ResponseAsync.ConfigureAwait(false);
var caps = DataProtoMapper.DecodeCapabilities(response, new DataDecodeLimits(budget.MaxItems, _maxMessageBytes));
if (response.ValueKinds.Count > MaxCapabilityKinds || response.ValueKinds.Distinct().Count() != response.ValueKinds.Count)
throw new ArgumentException("Invalid capability value kinds.");
var caps = DataProtoMapper.DecodeCapabilities(response, new DataDecodeLimits(MaxCapabilityKinds, _maxMessageBytes));
if (!caps.ResponseServingIdentity || (write && (caps.ProtocolMinor < 3 || !caps.WriteServingGenerationEnforced)) || caps.Serving.ServingGeneration <= 0 || !ClusterEndpointSelector.IsEligible(Target, caps, write) ||
Target.Mode == DataTargetMode.Cluster && !_eligibleNodeIds!.Contains(caps.Serving.NodeId))
throw new InvalidOperationException("Endpoint is not an authenticated ready target.");
@@ -299,18 +307,31 @@ public sealed partial class GrpcDataConnection : IDataConnection
var serving = DataProtoMapper.DecodeServing(wire.Serving);
return result with { Serving = serving, Items = result.Items.Select(x => ExposeMetadata(x, serving, selected.Capabilities)).ToArray() };
}, cancellationToken);
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) =>
QueryAsync(request.Budget, async (selected, budget, options) =>
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
{
// Covers endpoint selection, dispatch, transport and decoding, never a peer-supplied clock.
var started = Clock.GetTimestamp();
return QueryAsync(request.Budget, async (selected, budget, options) =>
{
var wire = await selected.Channel.Client.GetMetadataAsync(DataProtoMapper.EncodeMetadataRequest(request with { Budget = budget }), options).ResponseAsync.ConfigureAwait(false);
Verify(wire.Serving, selected); var result = DataProtoMapper.DecodeMetadataResponse(wire, Limits(budget, selected.Capabilities));
if (result.Count != request.Views.Count || result.Where((x, i) => x.CorrelationId != i.ToString(System.Globalization.CultureInfo.InvariantCulture) ||
x.Value is not null && (x.Value.View.Address != request.Views[i].Address || x.Value.CatalogRevision != selected.Capabilities.Serving.CatalogEpoch)).Any())
x.Value is not null && (x.Value.View.Address != request.Views[i].Address || x.Value.CatalogRevision != selected.Capabilities.Serving.CatalogEpoch) ||
selected.Capabilities.MetadataItemLeases && x.Lease is { } lease &&
(lease.CatalogEpoch != selected.Capabilities.Serving.CatalogEpoch || lease.AuthorityEpoch != selected.Capabilities.Serving.AuthorityEpoch ||
lease.Duration > selected.Capabilities.Limits.MaxMetadataLease)).Any())
throw new InvalidOperationException("Metadata response has unexpected items.");
Verify(wire.Serving, selected);
var serving = DataProtoMapper.DecodeServing(wire.Serving);
return (IReadOnlyList<DataItemResult<DataMetadata>>)result.Select(x => x.Value is null ? x : x with { Value = ExposeMetadata(x.Value, serving, selected.Capabilities) }).ToArray();
return (IReadOnlyList<DataItemResult<DataMetadata>>)result.Select((x, i) => x with
{
Value = x.Value is null ? null : ExposeMetadata(x.Value, serving, selected.Capabilities),
Lease = selected.Capabilities.MetadataItemLeases && x.Value?.View == request.Views[i] ? x.Lease : null,
LeaseRequestStartedTimestamp = selected.Capabilities.MetadataItemLeases && x.Value?.View == request.Views[i] && x.Lease is not null
? started : null,
}).ToArray();
}, cancellationToken);
}
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken)
{
var start = Clock.GetTimestamp();
@@ -318,7 +339,8 @@ public sealed partial class GrpcDataConnection : IDataConnection
{
var wire = await selected.Channel.Client.ReadAsync(DataProtoMapper.EncodeReadRequest(request with { Budget = budget }), options).ResponseAsync.ConfigureAwait(false);
Verify(wire.Serving, selected);
var result = DataProtoMapper.DecodeReadResponse(wire, Limits(budget, selected.Capabilities), Clock.GetElapsedTime(start));
var observedAt = Clock.GetTimestamp();
var result = DataProtoMapper.DecodeReadResponse(wire, Limits(budget, selected.Capabilities), Clock.GetElapsedTime(start, observedAt));
try
{
if (result.Count != request.Items.Count || !result.Select(x => x.CorrelationId).SequenceEqual(request.Items.Select(x => x.CorrelationId)) ||
@@ -326,7 +348,8 @@ public sealed partial class GrpcDataConnection : IDataConnection
throw new InvalidOperationException("Read response has unexpected items or serving identity.");
Verify(wire.Serving, selected);
if (result.LastOrDefault(x => x.Sample is not null) is { } observed) RecordSampleAge(observed.AgeBounds);
return result;
// The decoded results transfer their owned leases to these stamped copies.
return (IReadOnlyList<ReadResult>)result.Select(item => item with { FreshnessObservedTimestamp = observedAt }).ToArray();
}
catch { foreach (var item in result) item.Dispose(); throw; }
}, cancellationToken);
@@ -366,14 +389,22 @@ public sealed partial class GrpcDataConnection : IDataConnection
if (!ProbeAllowed()) return results;
var eligible = Enumerable.Range(0, request.Items.Count).ToArray();
var attempted = false;
var readReadyButWriteIneligible = false;
foreach (var endpoint in _endpoints)
{
if (eligible.Length == 0) break;
cancellationToken.ThrowIfCancellationRequested();
Selected selected;
try { selected = await SelectAsync(endpoint, start, request.Budget, true, cancellationToken).ConfigureAwait(false); ProbeSucceeded(); }
try { selected = await SelectAsync(endpoint, start, request.Budget, false, cancellationToken).ConfigureAwait(false); ProbeSucceeded(); }
catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException or TimeoutException)
{ continue; }
if (!SupportsWrites(selected.Capabilities) || !ClusterEndpointSelector.IsEligible(Target, selected.Capabilities, true))
{
// A read-ready endpoint can be intentionally ineligible for writes. Do not
// turn that policy decision into discovery backoff for subsequent reads.
readReadyButWriteIneligible = true;
continue;
}
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, selected.Channel.Retired.Token, _shutdown.Token);
// Caller-bound generations are strict: never replace any supplied precondition or rebind.
var strictMismatch = eligible.Where(i => request.Items[i].ExpectedServingGeneration is { } generation &&
@@ -467,7 +498,7 @@ public sealed partial class GrpcDataConnection : IDataConnection
eligible = dispatchStarted ? deferred.ToArray() : deferred.Concat(eligible).ToArray();
}
}
if (!attempted && eligible.Length > 0) ProbeFailed();
if (!attempted && eligible.Length > 0 && !readReadyButWriteIneligible) ProbeFailed();
return results;
}
private static void VerifyWriteEnvelope(W.Serving? serving, Selected selected, IReadOnlyList<WriteItemResult> results)
@@ -512,8 +543,11 @@ public sealed partial class GrpcDataConnection : IDataConnection
var transferred = false;
try
{
var call = selected.Channel.Client.Subscribe(Headers(selected.Channel), cancellationToken: lifetime.Token);
subscription = new RemoteSubscription(this, call, selected, lifetime, _maxMessageBytes,
var compact = _enableCompactBatches && DataProtoMapper.NegotiateCompact(selected.Capabilities);
var headers = Headers(selected.Channel);
if (compact) headers.Add(DataConnectionProtoContract.CompactCodecHeader, DataConnectionProtoContract.CompactCodecVersion.ToString(System.Globalization.CultureInfo.InvariantCulture));
var call = selected.Channel.Client.Subscribe(headers, cancellationToken: lifetime.Token);
subscription = new RemoteSubscription(this, call, selected, lifetime, compact, _maxMessageBytes,
Math.Min(_maxMonitoredItems, selected.Capabilities.Limits.MaxMonitoredItems), _maxPendingCommands,
_maxCommandTimeout, _commandBudget, ClaimStreamEpoch, PendingIdentityObserverForTests, AfterTimerCancelledForTests, () => { lock (_sync) { _streams.Remove(subscription!); Interlocked.Decrement(ref _activeStreams); CheckDrainedLocked(); } });
if (BeforeStreamInstallForTests is { } pause) await pause().ConfigureAwait(false);
@@ -556,11 +590,16 @@ public sealed partial class GrpcDataConnection : IDataConnection
private sealed class RemoteSubscription(GrpcDataConnection owner,
AsyncDuplexStreamingCall<W.SubscriptionCommand, W.SubscriptionFrame> call, Selected selected,
CancellationTokenSource lifetime, int maxBytes, int maxItems, int maxPendingCommands,
CancellationTokenSource lifetime, bool compactNegotiated, int maxBytes, int maxItems, int maxPendingCommands,
TimeSpan maxCommandTimeout, CommandStateBudget commandBudget, Func<string, long, bool> claimEpoch, Action<WeakReference>? observePending,
Func<Task>? afterTimerCancelled, Action release) : IDataSubscription, IDataSubscriptionProvenance
Func<Task>? afterTimerCancelled, Action release) : IDataSubscription, IDataSubscriptionProvenance, IDataSubscriptionFreshnessSupport
{
public ServingIdentity Serving { get; } = selected.Capabilities.Serving;
public bool SupportsFreshnessChallenges => selected.Capabilities.SubscriptionFreshnessChallenges && selected.Capabilities.SubscriptionAgeReadiness;
public int FreshnessMaxItems => selected.Capabilities.Limits.MaxBatchItems;
private readonly Dictionary<string, long> _freshnessStarts = new(StringComparer.Ordinal);
private readonly Queue<string> _freshnessOrder = new();
private long _lastFreshnessSequence;
private readonly SemaphoreSlim _send = new(1, 1);
private readonly Task _headersReceipt = call.ResponseHeadersAsync;
private Dictionary<ulong, DataItemHandle> _handles = new();
@@ -568,7 +607,7 @@ public sealed partial class GrpcDataConnection : IDataConnection
private HashSet<ulong> _usedHandles = new();
private Dictionary<ulong, long> _versions = new();
private sealed record PendingCommand(string Id, string[]? ClientIds, DataItemHandle[]? Removed,
bool IsModify, TimeSpan Timeout, long Bytes, CancellationTokenSource Timer);
bool IsModify, bool IsChallenge, TimeSpan Timeout, long Bytes, CancellationTokenSource Timer);
private readonly Dictionary<string, PendingCommand> _pending = new(StringComparer.Ordinal);
private long _pendingBytes, _usedCommandBytes;
private readonly HashSet<string> _usedCommands = new(StringComparer.Ordinal);
@@ -630,8 +669,9 @@ public sealed partial class GrpcDataConnection : IDataConnection
if (command.SubscriptionId != _id || command.StreamEpoch != _epoch || command.StreamEpoch <= 0)
throw new InvalidOperationException("Command belongs to another stream epoch.");
var count = command switch { OpenSubscription o => o.Items.Count, AddSubscriptionItems a => a.Items.Count,
ModifySubscriptionItems m => m.Items.Count, RemoveSubscriptionItems r => r.Items.Count, _ => maxItems + 1 };
ModifySubscriptionItems m => m.Items.Count, RemoveSubscriptionItems r => r.Items.Count, ChallengeSubscriptionFreshness c => c.Items.Count, _ => maxItems + 1 };
if (count > maxItems) throw new InvalidOperationException("Command item capacity exceeded.");
if (command is ChallengeSubscriptionFreshness && !SupportsFreshnessChallenges) throw new InvalidOperationException("Peer did not negotiate freshness challenges.");
var encoded = DataProtoMapper.EncodeCommand(command);
if (encoded.CalculateSize() > Math.Min(maxBytes, selected.Capabilities.Limits.MaxMessageBytes))
throw new InvalidOperationException("Command byte capacity exceeded.");
@@ -642,23 +682,41 @@ public sealed partial class GrpcDataConnection : IDataConnection
ModifySubscriptionItems => encoded.Modify.Items.Select(x => x.ClientItemId).ToArray(),
_ => null
};
var removed = command is RemoveSubscriptionItems ? encoded.Remove.Items.Select(DataProtoMapper.DecodeHandle).ToArray() : null;
var removed = command switch { RemoveSubscriptionItems => encoded.Remove.Items.Select(DataProtoMapper.DecodeHandle).ToArray(),
ChallengeSubscriptionFreshness => encoded.FreshnessChallenge.Items.Select(DataProtoMapper.DecodeHandle).ToArray(), _ => null };
long charge = checked(256L + 2L * encoded.CommandId.Length + (ids?.Sum(x => 64L + 2L * x.Length) ?? 0L) +
(removed?.Sum(x => 96L + 2L * x.SubscriptionId.Length) ?? 0L));
var pending = new PendingCommand(encoded.CommandId, ids, removed, command is ModifySubscriptionItems,
command.AcknowledgementTimeout, charge, CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token));
command is ChallengeSubscriptionFreshness, command.AcknowledgementTimeout, charge, CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token));
lock (_pending)
{
var commandLimit = (int)Math.Min(100_000L, Math.Max(1024L, 4L * maxItems));
long usedCharge = checked(64L + 2L * pending.Id.Length);
if (_pending.Count >= maxPendingCommands || _usedCommands.Count >= commandLimit || _usedCommands.Contains(pending.Id) ||
long sequence = 0;
if (pending.IsChallenge && (pending.Id.Length > 32 || !pending.Id.StartsWith("freshness-", StringComparison.Ordinal) ||
!long.TryParse(pending.Id.AsSpan("freshness-".Length), System.Globalization.NumberStyles.None,
System.Globalization.CultureInfo.InvariantCulture, out sequence) || sequence <= _lastFreshnessSequence))
{ pending.Timer.Dispose(); throw new InvalidOperationException("Freshness challenge sequence is invalid."); }
if (!pending.IsChallenge && pending.Id.StartsWith("freshness-", StringComparison.Ordinal))
{ pending.Timer.Dispose(); throw new InvalidOperationException("Reserved command identifier."); }
long usedCharge = pending.IsChallenge ? 0 : checked(64L + 2L * pending.Id.Length);
if (_pending.Count >= maxPendingCommands || (!pending.IsChallenge && (_usedCommands.Count >= commandLimit || _usedCommands.Contains(pending.Id))) ||
!commandBudget.TryReserve(checked(charge + usedCharge)))
{ pending.Timer.Dispose(); throw new InvalidOperationException("Command capacity or duplicate command."); }
_usedCommands.Add(pending.Id); _pending.Add(pending.Id, pending);
if (pending.IsChallenge) _lastFreshnessSequence = sequence;
else _usedCommands.Add(pending.Id);
_pending.Add(pending.Id, pending);
_pendingBytes += charge; _usedCommandBytes += usedCharge;
}
if (pending.ClientIds is not null) observePending?.Invoke(new WeakReference(pending.ClientIds));
_ = ExpireUnacknowledgedAsync(pending.Id, pending.Timeout, pending.Timer);
if (pending.IsChallenge)
{
lock (_pending)
{
_freshnessStarts.Add(pending.Id, owner.Clock.GetTimestamp()); _freshnessOrder.Enqueue(pending.Id);
while (_freshnessOrder.Count > 16) _freshnessStarts.Remove(_freshnessOrder.Dequeue());
}
}
try { await call.RequestStream.WriteAsync(encoded, linked.Token).ConfigureAwait(false); }
catch { await lifetime.CancelAsync().ConfigureAwait(false); throw; }
}
@@ -699,6 +757,8 @@ public sealed partial class GrpcDataConnection : IDataConnection
if (_id is null || wire.SubscriptionId != _id || wire.StreamEpoch != _epoch || wire.Sequence != _sequence + 1)
throw new InvalidOperationException("Unexpected stream epoch or sequence.");
DataSubscriptionFrame frame;
if (wire.CompactValues is not null && !compactNegotiated)
throw new InvalidOperationException("Unnegotiated compact subscription frame.");
if (wire.Values is not null || wire.CompactValues is not null)
frame = DataProtoMapper.DecodeValues(wire, _handles, maxItems,
Math.Min(maxBytes, selected.Capabilities.Limits.MaxMessageBytes), selected.Capabilities.Serving,
@@ -730,10 +790,19 @@ public sealed partial class GrpcDataConnection : IDataConnection
var handle = item.Handle ?? throw new InvalidOperationException("Successful acknowledgement has no handle.");
if (pending.Removed is { } removedItems)
{
if (removedItems[i] != handle || !next.Remove(handle.Handle) ||
!nextClients.Remove(item.ClientItemId, out var removed) || removed != handle.Handle)
throw new InvalidOperationException("Unexpected removed handle.");
nextVersions.Remove(handle.Handle);
if (removedItems[i] != handle) throw new InvalidOperationException("Unexpected acknowledged handle.");
if (pending.IsChallenge)
{
if (!next.TryGetValue(handle.Handle, out var currentHandle) || currentHandle != handle ||
!nextClients.TryGetValue(item.ClientItemId, out var currentClient) || currentClient != handle.Handle)
throw new InvalidOperationException("Unexpected challenged handle.");
}
else
{
if (!next.Remove(handle.Handle) || !nextClients.Remove(item.ClientItemId, out var removed) || removed != handle.Handle)
throw new InvalidOperationException("Unexpected removed handle.");
nextVersions.Remove(handle.Handle);
}
}
else
{
@@ -776,11 +845,40 @@ public sealed partial class GrpcDataConnection : IDataConnection
nextVersions[item.Handle.Handle] = item.Sample.Version;
}
Verify(wire.Serving, selected); linked.Token.ThrowIfCancellationRequested(); _versions = nextVersions;
if (SupportsFreshnessChallenges)
{
var bounded = new List<DataSubscriptionValue>(values.Items.Count);
try
{
foreach (var item in values.Items)
{
long start;
lock (_pending) start = item.FreshnessChallengeId is { } nonce && _freshnessStarts.TryGetValue(nonce, out var known) ? known : -1;
var bounds = item.AgeBounds;
long? observed = null;
if (start >= 0 && bounds.Lower is { } lower)
{
observed = owner.Clock.GetTimestamp();
bounds = new(bounds.Lower, lower + owner.Clock.GetElapsedTime(start, observed.Value));
}
bounded.Add(item with { Sample = item.Sample with { Value = item.Sample.Value.Retain() }, AgeBounds = bounds,
FreshnessObservedTimestamp = observed });
}
frame = new DataSubscriptionValues(values.SubscriptionId, values.StreamEpoch, values.Sequence, values.IsSnapshot, bounded, values);
}
catch { foreach (var item in bounded) item.Sample.Dispose(); throw; }
}
}
_sequence = wire.Sequence;
}
catch { if (frame is IDisposable owned) owned.Dispose(); throw; }
if (frame is DataSubscriptionValues { Items.Count: > 0 } observedValues) owner.RecordSampleAge(observedValues.Items[^1].AgeBounds);
if (frame is DataSubscriptionValues observedValues)
{
if (wire.CompactValues is not null) Interlocked.Increment(ref owner._compactFrameCount);
else Interlocked.Increment(ref owner._fallbackFrameCount);
Interlocked.Add(ref owner._serializedValueFrameBytes, wire.CalculateSize());
if (observedValues.Items.Count > 0) owner.RecordSampleAge(observedValues.Items[^1].AgeBounds);
}
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Reset }) Interlocked.Increment(ref owner._resetCount);
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Coalesced }) Interlocked.Increment(ref owner._coalescedCount);
yield return frame;
@@ -9,6 +9,13 @@ public interface IGrpcDataAdapterConnectionLease : IAsyncDisposable
{
IDataConnection Connection { get; }
CancellationToken CancellationToken { get; }
/// <summary>Opaque stable identity for one route and credential lifetime; null disables overlap.</summary>
object? RouteIdentity => null;
/// <summary>A detached route guard that remains meaningful after this borrower is released.</summary>
Func<bool> RouteCurrent
{
get { var token = CancellationToken; return () => !token.IsCancellationRequested; }
}
}
public interface IGrpcDataAdapterConnectionSource
@@ -31,7 +38,7 @@ public sealed record ProjectedValueRoute(string DriverInstanceId, string Depende
public sealed record ProjectedValueUpdate(ProjectedValueRoute Route, DataValueSnapshot Snapshot, DataAgeBounds OriginAgeBounds,
long ReceivedTimestamp, IProjectedSamplePublicationProof SourceProof, bool IsCompleteSnapshot = false,
TimeSpan? MaximumSampleAge = null);
TimeSpan? MaximumSampleAge = null, long? SourceVersion = null);
public interface IProjectedValuePublisher
{
@@ -0,0 +1,16 @@
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Actual logical demand and acknowledged physical driver references, without identity labels.</summary>
/// <remarks>Physical references count unique references within each driver; logical interests include Raw/UNS and principal boundaries.</remarks>
public sealed record SubscriptionDemandAccounting(int LogicalInterests, int SharingGroups, int RegistryInterests,
int TrackedDrivers, int DesiredPhysicalReferences, int AppliedPhysicalReferences, int RetiringDrivers);
/// <summary>Actual source-cache resource charges and in-flight snapshot/interest item counts.</summary>
/// <remarks>Counts are individually synchronized observations, not an atomic transaction across partitions.</remarks>
public sealed record SampleHubAccounting(int TrackedSources, int SnapshotItems, int InterestItems,
long RetainedBytes, long MaximumRetainedBytes, int PartitionCount);
/// <summary>Bounded origin accounting sampled from the owners of physical demand and cache resources.</summary>
/// <remarks>Components are captured sequentially and may advance between observations. ReservedDrivers includes late physical cleanup.</remarks>
public sealed record GrpcDataWorkloadAccounting(DateTimeOffset CapturedAtUtc, SubscriptionDemandAccounting Demand,
SampleHubAccounting Hub, int ReservedDrivers, int MaximumReservedDrivers);
@@ -0,0 +1,11 @@
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Numeric committed bundle observations, without credential or trust material.</summary>
public sealed record DataConnectionBundleCommitObservation(long? CredentialScopeVersion, long? CredentialVersion, bool? CredentialDeleted,
long? TrustScopeVersion, long? TrustVersion, bool? TrustRetired);
/// <summary>Observes committed node-local credential and trust versions for a connection.</summary>
public interface IDataConnectionBundleCommitObserver
{
Task<DataConnectionBundleCommitObservation> ObserveAsync(string connectionId, CancellationToken cancellationToken);
}
@@ -13,6 +13,7 @@ public sealed record LocalDataRuntimeLimits(int MaxDrivers, int MaxInterests, in
public sealed class LocalDataRuntimeComposition : IDisposable
{
private readonly DriverHostSubscriptionDemandSource _demand;
private readonly PartitionedSampleHub _hub;
private int _disposed;
public LocalDataRuntimeComposition(LocalCatalogCoordinator catalog, PartitionedSampleHub hub,
DataOperationPolicy policy, DataCapabilitiesProvider capabilities, TimeProvider clock, DataWriteRuntime writes,
@@ -23,6 +24,7 @@ public sealed class LocalDataRuntimeComposition : IDisposable
ArgumentNullException.ThrowIfNull(clock); ArgumentNullException.ThrowIfNull(writes);
ArgumentNullException.ThrowIfNull(host); ArgumentNullException.ThrowIfNull(acquisitionCapacity);
ArgumentNullException.ThrowIfNull(limits);
_hub = hub;
if (!ReferenceEquals(hub.Clock, clock)) throw new ArgumentException("Local hub and services must share one clock.", nameof(clock));
var sessionLimits = new SubscriptionSessionLimits(limits.MaxCommands, limits.MaxPendingFrames, limits.MaxPendingBytes, limits.MaxSessionLifetime);
sessionLimits.Validate();
@@ -33,10 +35,15 @@ public sealed class LocalDataRuntimeComposition : IDisposable
LocalDataServices? services = null;
services = new LocalDataServices(() => catalog.Current, hub, policy, capabilities, clock,
writes: context => writes.ForCaller(context, () => host),
targetSubscriptions: (context, target) => new LocalSubscriptionService(services!, context, target, _demand, sessionLimits, capacity));
targetSubscriptions: (context, target) => new LocalSubscriptionService(services!, context, target, _demand, sessionLimits, capacity),
subscriptionFreshnessChallenges: true);
Services = services;
}
public LocalDataServices Services { get; }
public SubscriptionAcquisitionCapacity AcquisitionCapacity { get; }
/// <summary>Samples actual demand and cache owners; component reads are not cross-component atomic.</summary>
public GrpcDataWorkloadAccounting CaptureWorkloadAccounting() => new(_hub.Clock.GetUtcNow(),
_demand.CaptureAccounting(), _hub.CaptureAccounting(), AcquisitionCapacity.ReservedDriverCount,
AcquisitionCapacity.MaxReservations);
public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) _demand.Dispose(); }
}
@@ -18,6 +18,7 @@ public sealed class LocalDataServices : IDataConnectionFactory
private readonly Func<DataAuthenticatedContext, IDataWriteService>? _writes;
private readonly Func<DataAuthenticatedContext, IDataSubscriptionService>? _subscriptions;
private readonly Func<DataAuthenticatedContext, DataTarget, IDataSubscriptionService>? _targetSubscriptions;
private readonly bool _subscriptionFreshnessChallenges;
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,
@@ -27,7 +28,8 @@ public sealed class LocalDataServices : IDataConnectionFactory
DataOperationPolicy policy, DataCapabilitiesProvider capabilities, TimeProvider clock,
Func<DataAuthenticatedContext, IDataWriteService>? writes = null,
Func<DataAuthenticatedContext, IDataSubscriptionService>? subscriptions = null,
Func<DataAuthenticatedContext, DataTarget, IDataSubscriptionService>? targetSubscriptions = null)
Func<DataAuthenticatedContext, DataTarget, IDataSubscriptionService>? targetSubscriptions = null,
bool subscriptionFreshnessChallenges = false)
{
_catalog = catalog ?? throw new ArgumentNullException(nameof(catalog));
_hub = hub ?? throw new ArgumentNullException(nameof(hub));
@@ -38,6 +40,7 @@ public sealed class LocalDataServices : IDataConnectionFactory
_writes = writes;
_subscriptions = subscriptions;
_targetSubscriptions = targetSubscriptions;
_subscriptionFreshnessChallenges = subscriptionFreshnessChallenges;
}
public TimeProvider Clock { get; }
@@ -214,7 +217,9 @@ public sealed class LocalDataServices : IDataConnectionFactory
catalog is null ? _capabilities.Limits : Limits(catalog, context));
if (catalog is null || !Ready(catalog) || context.AuthorityEpoch != catalog.AuthorityEpoch || !RoleAllows(target, catalog.Serving))
capabilities = capabilities with { Readiness = DataReadiness.Unavailable, Operations = DataOperations.None };
return Task.FromResult(capabilities with { WriteServingGenerationEnforced = true, ProtocolMinor = Math.Max(3, capabilities.ProtocolMinor) });
return Task.FromResult(capabilities with { WriteServingGenerationEnforced = true, SubscriptionAgeReadiness = true,
ResponseServingIdentity = true, SubscriptionFreshnessChallenges = _subscriptionFreshnessChallenges,
MetadataItemLeases = true, ProtocolMinor = Math.Max(5, capabilities.ProtocolMinor) });
}
internal Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(DataAuthenticatedContext context, DataTarget target, MetadataRequest request, CancellationToken cancellationToken)
@@ -236,6 +241,7 @@ public sealed class LocalDataServices : IDataConnectionFactory
: !catalog.TryResolveAddress(view, out _) ? catalog.ContainsAddress(view) ? DataItemStatus.Denied : DataItemStatus.NotFound
: DataItemStatus.Good;
DataMetadata? metadata = null;
MetadataLease? itemLease = null;
if (status == DataItemStatus.Good && catalog.TryResolveAddress(view, out var node))
{
if (!Allowed(catalog, context, node, DataOperations.Metadata)) status = DataItemStatus.Denied;
@@ -243,16 +249,32 @@ public sealed class LocalDataServices : IDataConnectionFactory
else
{
metadata = Metadata(catalog, context, target, node);
bytes = checked(bytes + MetadataBytes(metadata));
bytes = checked(bytes + MetadataBytes(metadata) + 64);
if (bytes > Math.Min(request.Budget.MaxBytes, _capabilities.Limits.MaxMessageBytes))
{ status = DataItemStatus.LimitExceeded; metadata = null; }
else if (context.AuthorityEpoch == catalog.AuthorityEpoch && RoleAllows(target, catalog.Serving) &&
ReferenceEquals(_catalog(), catalog) && Allowed(catalog, context, node, DataOperations.Metadata))
{
var duration = Limits(catalog, context).MaxMetadataLease;
if (context.CredentialExpiresUtc is { } expiry)
{
var remaining = expiry - Clock.GetUtcNow();
if (remaining < duration) duration = remaining;
}
if (duration > TimeSpan.Zero && Ready(catalog) && ReferenceEquals(_catalog(), catalog) &&
context.AuthorityEpoch == catalog.AuthorityEpoch && _policy.IsCallerUsable(Caller(context)))
itemLease = new MetadataLease(catalog.Serving.CatalogEpoch, catalog.Serving.AuthorityEpoch, duration);
}
}
}
results.Add(new(i.ToString(System.Globalization.CultureInfo.InvariantCulture), status, metadata, null));
results.Add(new(i.ToString(System.Globalization.CultureInfo.InvariantCulture), status, metadata, null,
itemLease, itemLease is null ? null : start));
}
if (!Ready(catalog) || !_policy.IsCallerUsable(Caller(context)))
if (!Ready(catalog) || !ReferenceEquals(_catalog(), catalog) || context.AuthorityEpoch != catalog.AuthorityEpoch ||
!RoleAllows(target, catalog.Serving) || !_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());
{ Status = !Ready(catalog) || !RoleAllows(target, catalog.Serving) ? DataItemStatus.Unavailable : DataItemStatus.Denied,
Value = null, Lease = null, LeaseRequestStartedTimestamp = null }).ToArray());
return Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(results);
}
@@ -295,7 +317,8 @@ public sealed class LocalDataServices : IDataConnectionFactory
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);
var observedAt = Clock.GetTimestamp();
var age = Clock.GetElapsedTime(read.ReceivedTimestamp, observedAt);
if (age < TimeSpan.Zero) { read.Dispose(); results.Add(Empty(DataItemStatus.Unavailable)); continue; }
// Catalog/authority headers describe current serving. Cache ingress age, value version
// and original timestamps remain unchanged, including provisional boot acquisitions.
@@ -307,7 +330,7 @@ public sealed class LocalDataServices : IDataConnectionFactory
var publication = new PublicationReadLease(read, () => CanPublish(context, exposed.Serving, target)
&& !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, new DataAgeBounds(age, age)));
DataReadiness.Ready, age, exposed, null, publication, new DataAgeBounds(age, age), observedAt));
}
if (!Ready(catalog) || !_policy.IsCallerUsable(Caller(context)))
for (var i = 0; i < results.Count; i++)
@@ -37,6 +37,18 @@ public sealed class MetadataAuthorityLease : IDataAuthorizationLease
public long CatalogEpoch { get; }
public long AuthorityEpoch { get; }
public ServingIdentity Serving { get; }
internal TimeSpan Remaining
{
get
{
if (Volatile.Read(ref _invalidated) != 0) return TimeSpan.Zero;
var elapsed = _clock.GetElapsedTime(_requestStart, _clock.GetTimestamp());
return elapsed < TimeSpan.Zero || elapsed >= _usableDuration ? TimeSpan.Zero : _usableDuration - elapsed;
}
}
internal TimeSpan UsableDuration => _usableDuration;
internal bool ExpiredNaturally => Volatile.Read(ref _invalidated) == 0 &&
_clock.GetElapsedTime(_requestStart, _clock.GetTimestamp()) >= _usableDuration;
public bool IsValid
{
get
@@ -153,6 +153,8 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable
private int _interestItems;
private long _snapshotValidationWork;
internal Action<SourceTicket>? BeforeReadForTests { get; set; }
internal Action? BeforePendingValueCurrentForTests { get; set; }
internal Action? AfterValueSequenceForTests { get; set; }
internal Action? BeforeSnapshotValidationForTests { get; set; }
internal long SnapshotValidationWorkForTests => Interlocked.Read(ref _snapshotValidationWork);
internal void CountSnapshotValidationForTests() => Interlocked.Increment(ref _snapshotValidationWork);
@@ -168,6 +170,10 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable
}
public TimeProvider Clock { get; }
public DataResourceBudget Resources { get; }
/// <summary>Captures actual bounded resource counters without enumerating source identities.</summary>
public SampleHubAccounting CaptureAccounting() => new(Volatile.Read(ref _trackedSources),
Volatile.Read(ref _snapshotItems), Volatile.Read(ref _interestItems), Resources.RetainedBytes,
Resources.MaximumBytes, Volatile.Read(ref _partitions).Length);
internal DataResourceLimits Limits => _limits;
internal long RoutingEpoch => Interlocked.Read(ref _routingEpoch);
internal bool IsDisposed => Volatile.Read(ref _disposed) != 0;
@@ -223,7 +229,8 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable
return 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 ProcessPending() { foreach (var partition in Volatile.Read(ref _partitions)) partition.DrainForTests(); }
internal void DrainOneSliceForTests(BackingSourceKey key) => Partition(key).Drain();
internal void WithPartitionLockForTest(BackingSourceKey key, Action action) => Partition(key).WithLockForTest(action);
internal PartitionControlSignal ControlSignalForTests(BackingSourceKey key) => Partition(key).Control;
@@ -1,5 +1,6 @@
using System.Collections.Concurrent;
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
@@ -49,26 +50,57 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
/// <summary>Reconciles against the live SDK binding; safe to call after the deferred sink binds.</summary>
public void RefreshAnchors()
{
lock (_lifecycle.TransitionGate)
lock (_anchorGate)
{
if (Volatile.Read(ref _disposed) != 0) return;
// During an unresolved deployment the old guard is already invalid. Retain its
// bounded SDK lifetime so an identical placement can be reauthorized later.
if (_lifecycle.Suspended) return;
var placements = _lifecycle.Active;
foreach (var entry in _installed.ToArray())
{
var old = entry.Value;
if (Current(old.Placement)) continue;
var next = placements.FirstOrDefault(candidate => CompatiblePlacement(old.Placement, candidate));
if (next is not null && Current(next))
{
var renewed = new ProjectedAnchorDefinition(next.Mapping.Realm, old.Definition.LocalIdentifier,
old.Definition.Parent, next.Mapping.BranchName, next.Anchor.Subject,
next.Mapping.RemoteNamespaceMappingId, next.Mapping.Revision, () => Current(next))
{ LocalScope = next.Scope, Lifetime = old.Definition.Lifetime };
if (_anchors.TryEnsureProjectedAnchor(renewed, out var node) && node == old.Node)
{
if (Current(next))
{
_installed[entry.Key] = new(old.Node, renewed, next);
continue;
}
_installed.TryRemove(entry.Key, out _);
_anchors.TryRemoveProjectedAnchor(old.Node, renewed);
continue;
}
}
_installed.TryRemove(entry.Key, out _);
_anchors.TryRemoveProjectedAnchor(old.Node, old.Definition);
}
foreach (var placement in placements)
{
var mappingId = placement.Mapping.RemoteNamespaceMappingId;
if (_installed.ContainsKey(mappingId) || !Current(placement) || placement.Parent.Address.IdentifierKind != "string") continue;
var parent = _resolveNode(placement.Parent.Address.NamespaceUri, placement.Parent.Address.Identifier);
if (_installed.ContainsKey(mappingId) || !Current(placement)) continue;
// Transport realm roots deliberately use a disjoint identifier kind. Resolve only
// the exact trusted local root to the native SDK root, never a remote claimed ID.
var localRoot = LocalExportCatalog.RealmRoot(placement.Parent.Address.OriginClusterId, placement.Mapping.Realm);
var isRoot = placement.Parent == localRoot && string.Equals(placement.Parent.Address.OriginClusterId,
placement.Mapping.ClusterId, StringComparison.OrdinalIgnoreCase);
if (!isRoot && placement.Parent.Address.IdentifierKind != "string") continue;
var parent = _resolveNode(isRoot ? V3NodeIds.RawNamespaceUri : placement.Parent.Address.NamespaceUri,
isRoot ? V3NodeIds.SharedRootFolderId : placement.Parent.Address.Identifier);
if (parent is not { } parentNode) continue;
var id = ProjectedDataIds.Identifier(mappingId, placement.Anchor.Address);
var definition = new ProjectedAnchorDefinition(placement.Mapping.Realm, id, parentNode, placement.Mapping.BranchName,
placement.Anchor.Subject, mappingId, placement.Mapping.Revision, () => Current(placement));
placement.Anchor.Subject, mappingId, placement.Mapping.Revision, () => Current(placement))
{ LocalScope = placement.Scope };
if (_anchors.TryEnsureProjectedAnchor(definition, out var node) && node is { } anchorNode)
{
if (Current(placement)) _installed[mappingId] = new(anchorNode, definition, placement);
@@ -78,6 +110,19 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
}
}
private static bool CompatiblePlacement(ProjectedMappingPlacement previous, ProjectedMappingPlacement next) =>
previous.Parent == next.Parent && previous.Anchor == next.Anchor && previous.Mapping.Realm == next.Mapping.Realm &&
string.Equals(previous.Mapping.RemoteNamespaceMappingId, next.Mapping.RemoteNamespaceMappingId, StringComparison.OrdinalIgnoreCase) &&
previous.Mapping.Revision == next.Mapping.Revision &&
string.Equals(previous.Mapping.DataConnectionId, next.Mapping.DataConnectionId, StringComparison.OrdinalIgnoreCase) &&
previous.Mapping.LocalParentKind == next.Mapping.LocalParentKind &&
string.Equals(previous.Mapping.LocalParentId, next.Mapping.LocalParentId, StringComparison.OrdinalIgnoreCase) &&
previous.Mapping.RemoteRootEntityId == next.Mapping.RemoteRootEntityId &&
previous.Mapping.BranchName == next.Mapping.BranchName && previous.Scope.Kind == next.Scope.Kind &&
string.Equals(previous.Scope.ClusterId, next.Scope.ClusterId, StringComparison.OrdinalIgnoreCase) &&
previous.Scope.Segments.SequenceEqual(next.Scope.Segments, StringComparer.Ordinal) &&
previous.LocalAncestry.SequenceEqual(next.LocalAncestry, StringComparer.OrdinalIgnoreCase);
private sealed class PageGuard(ProjectedBrowseAccess owner, IProjectedPageGuard source)
{
public bool IsCurrent() => Volatile.Read(ref owner._disposed) == 0 && source.IsCurrent;
@@ -13,6 +13,8 @@ public sealed record ProjectedNodeProof(string LocalIdentifier, DataMetadata Met
public sealed record ProjectedParentSnapshot(ProjectionPageStatus Status, IReadOnlyList<ProjectedNodeProof> Items,
bool Complete, string? Continuation, long Generation, IDataAuthorizationLease? Lease = null,
IDataMappedCatalogAuthority? LocalAuthority = null, ProjectedNodeProof? ParentProof = null);
internal sealed record RetainedProjectionDiagnostics(bool Retained, bool Retired, long? Generation,
bool? RouteAlive, bool? LocalAuthorityActive, bool? RemoteLeaseValid, bool? MappingBindingCurrent, bool? CacheGenerationCurrent);
/// <summary>One bounded parent query, with the original monotonic request-start timestamp.</summary>
public sealed record ProjectedBrowseRequest(string MappingId, DataView Parent, string? Filter, string? Continuation,
DataCallerIdentity Caller, DataBudget Budget, long RequestStartedTimestamp)
@@ -39,6 +41,9 @@ public interface IFederatedProjectionCatalog
IProjectedPageGuard? CaptureParentGuard(ProjectedBrowseRequest request, ProjectedParentSnapshot expected) => null;
Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken);
bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof);
/// <summary>Checks authority for evidence already acquired under an exact proof.</summary>
bool IsUsableProof(ProjectedNodeProof proof) => proof.Lease.IsValid &&
TryResolveProjected(proof.Metadata.View.Realm, proof.LocalIdentifier, out var current) && ReferenceEquals(current, proof);
bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin);
event Action<string, long>? Invalidated;
}
@@ -48,11 +53,13 @@ public sealed class ProjectedCatalogCache
{
private readonly record struct ParentKey(string Mapping, DataView Parent, string? Filter, string? Cursor, DataCallerIdentity? Caller, ConfiguredProjectionCapability? Capability);
private sealed class ParentEntry(ProjectedParentSnapshot snapshot) { internal readonly object Version = new(); internal ProjectedParentSnapshot Snapshot = snapshot; internal LinkedListNode<ParentKey>? Sweep; }
private sealed class NodeEntry(ProjectedNodeProof proof) { internal ProjectedNodeProof Proof = proof; internal int Pins; internal bool Retired; internal LinkedListNode<(DataRealm Realm, string Id)>? Sweep; }
private sealed class NodeEntry(ProjectedNodeProof proof) { internal ProjectedNodeProof Proof = proof; internal NodeEntry? Predecessor; internal int Pins; internal bool Retired; internal LinkedListNode<(DataRealm Realm, string Id)>? Sweep; }
private readonly object _sync = new();
private readonly Dictionary<ParentKey, ParentEntry> _parents = new();
private readonly Dictionary<(DataRealm Realm, string Id), NodeEntry> _nodes = new();
private readonly HashSet<NodeEntry> _retiredPinned = new();
private readonly Dictionary<ProjectedNodeProof, NodeEntry> _retiredByProof = new(ReferenceEqualityComparer.Instance);
private readonly Dictionary<(DataRealm Realm, string Id), int> _retiredPerNode = new();
private readonly LinkedList<ParentKey> _parentSweep = new();
private readonly LinkedList<(DataRealm Realm, string Id)> _nodeSweep = new();
private readonly Dictionary<string, int> _mappingNodeCounts = new(StringComparer.OrdinalIgnoreCase);
@@ -72,6 +79,30 @@ public sealed class ProjectedCatalogCache
}
public TimeProvider Clock { get; }
public event Action<string, long>? Invalidated;
// Diagnostic lookup only: copy the retained reference while holding the cache lock,
// then release it before evaluating any lease fence or resolver callback.
internal RetainedProjectionDiagnostics CaptureRetainedDiagnostics(DataRealm realm, string localIdentifier)
{
if (realm is not (DataRealm.Raw or DataRealm.Uns) || string.IsNullOrWhiteSpace(localIdentifier) || localIdentifier.Length > 16384)
throw new ArgumentException("Invalid projected diagnostic target.");
ProjectedNodeProof? proof;
bool retired;
lock (_sync)
{
if (_nodes.TryGetValue((realm, localIdentifier), out var current))
{ proof = current.Proof; retired = current.Retired; }
else
{
var entry = _retiredPinned.FirstOrDefault(candidate => candidate.Proof.Metadata.View.Realm == realm &&
candidate.Proof.LocalIdentifier == localIdentifier);
proof = entry?.Proof; retired = entry is not null;
}
}
if (proof is null) return new(false, false, null, null, null, null, null, null);
var flags = (proof.Lease as BoundProjectionLease)?.CaptureDiagnostics();
return new(true, retired, proof.Generation, flags?.RouteAlive, flags?.LocalAuthorityActive, flags?.RemoteLeaseValid,
flags?.MappingBindingCurrent, flags?.CacheGenerationCurrent);
}
private static ParentKey Key(ProjectedBrowseRequest request) => new(request.MappingId.ToUpperInvariant(), request.Parent,
request.Filter, request.Continuation, request.Caller, request.ConfiguredCapability);
private static (string Mapping, DataView Parent) Parent(string mapping, DataView parent) => (mapping.ToUpperInvariant(), parent);
@@ -141,8 +172,13 @@ public sealed class ProjectedCatalogCache
private void RemoveNode((DataRealm Realm, string Id) key)
{
if (!_nodes.Remove(key, out var node)) return;
node.Predecessor = null;
_nodeSweep.Remove(node.Sweep!); node.Sweep = null;
if (node.Pins > 0) { node.Retired = true; _retiredPinned.Add(node); }
if (node.Pins > 0)
{
node.Retired = true; _retiredPinned.Add(node); _retiredByProof.Add(node.Proof, node);
_retiredPerNode.TryGetValue(key, out var count); _retiredPerNode[key] = checked(count + 1);
}
else { _retainedBytes -= Bytes(node.Proof); ChangeMappingCount(node, -1); }
}
private void AddNode((DataRealm Realm, string Id) key, ProjectedNodeProof proof)
@@ -191,6 +227,11 @@ public sealed class ProjectedCatalogCache
string.Equals(left.Scope.ClusterId, right.Scope.ClusterId, StringComparison.OrdinalIgnoreCase) &&
left.Scope.Segments.SequenceEqual(right.Scope.Segments, StringComparer.Ordinal) &&
left.LocalAncestry.SequenceEqual(right.LocalAncestry, StringComparer.OrdinalIgnoreCase);
private static bool SamePlacementAcrossServing(ProjectedNodeProof previous, ProjectedNodeProof incoming) =>
previous.Subject.Serving != incoming.Subject.Serving &&
previous.OriginMetadata.View == incoming.OriginMetadata.View &&
SamePlacement(previous.Subject with { Serving = incoming.Subject.Serving }, incoming.Subject);
private bool Usable(ProjectedBrowseRequest request) => request.ConfiguredCapability is { } capability
? capability.Matches(request.MappingId, request.Parent, null) : request.Caller is not null && _policy is not null && _policy.IsCallerUsable(request.Caller);
private bool Allowed(ProjectedBrowseRequest request, ProjectedNodeProof proof) => Valid(proof) &&
@@ -275,6 +316,16 @@ public sealed class ProjectedCatalogCache
items.Any(item => item.Generation != page.Generation || item.Lease.Serving != page.Lease.Serving ||
!ReferenceEquals(item.Resolver.LocalAuthority, local) || !Allowed(request, item)) ||
indexedItems.Select(item => (item.Metadata.View.Realm, item.LocalIdentifier)).Distinct().Count() != indexedItems.Length) return false;
// A new serving node may refresh the exact expired placement. Count
// all outstanding owners before the capacity sweep can unindex it.
foreach (var item in indexedItems)
{
var nodeKey = (item.Metadata.View.Realm, item.LocalIdentifier);
if (!_nodes.TryGetValue(nodeKey, out var old) || old.Proof.Subject.Serving == item.Subject.Serving) continue;
_retiredPerNode.TryGetValue(nodeKey, out var retired);
if (!SamePlacementAcrossServing(old.Proof, item) || Valid(old.Proof) ||
(long)retired + (old.Pins > 0 ? 1 : 0) + 1 > 2) return false;
}
var key = Key(request);
var estimatedPage = KeyBytes(key) + Bytes(parent) + items.Sum(Bytes);
_mappingNodeCounts.TryGetValue(request.MappingId, out var initialMappingCount);
@@ -295,7 +346,8 @@ public sealed class ProjectedCatalogCache
if (siblingNames.TryGetValue(item.Metadata.BrowseName, out var old) && old.Address != item.OriginMetadata.View.Address) return false;
foreach (var item in indexedItems)
if (_nodes.TryGetValue((item.Metadata.View.Realm, item.LocalIdentifier), out var existing) &&
(existing.Retired || !SamePlacement(existing.Proof.Subject, item.Subject))) return false;
(existing.Retired || !SamePlacement(existing.Proof.Subject, item.Subject) &&
(Valid(existing.Proof) || !SamePlacementAcrossServing(existing.Proof, item)))) return false;
var cursor = commitCursor is null ? (true, page.Continuation) : commitCursor();
if (!cursor.Item1) return false;
foreach (var item in indexedItems)
@@ -342,6 +394,92 @@ public sealed class ProjectedCatalogCache
lock (_sync) return _nodes.TryGetValue((proof.Metadata.View.Realm, proof.LocalIdentifier), out var entry) &&
!entry.Retired && ReferenceEquals(entry.Proof, proof) && Valid(proof);
}
internal bool IsUsableProof(ProjectedNodeProof proof)
{
lock (_sync)
{
if (!_nodes.TryGetValue((proof.Metadata.View.Realm, proof.LocalIdentifier), out var current) || current.Retired || !Valid(current.Proof)) return false;
if (ReferenceEquals(current.Proof, proof)) return true;
var old = current.Predecessor;
return old is { Retired: true, Pins: > 0 } && ReferenceEquals(old.Proof, proof) && Valid(proof) && SameOverlap(proof, current.Proof);
}
}
// Renew only an already-owned node; this does not create a parent page, cursor or sibling grant.
internal bool TryRenewExact(ProjectedNodeProof previous, ProjectedNodeProof replacement,
int maximumMappingNodes, out ProjectedNodeProof? committed) =>
TryRenewCore(previous, replacement, maximumMappingNodes, false, out committed);
internal bool TryRenewOverlap(ProjectedNodeProof previous, ProjectedNodeProof replacement,
int maximumMappingNodes, out ProjectedNodeProof? committed) =>
TryRenewCore(previous, replacement, maximumMappingNodes, true, out committed);
private bool TryRenewCore(ProjectedNodeProof previous, ProjectedNodeProof replacement,
int maximumMappingNodes, bool overlap, out ProjectedNodeProof? committed)
{
committed = null;
ProjectedNodeProof frozen;
try { frozen = Freeze(replacement); }
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or NullReferenceException) { return false; }
lock (_sync)
{
var key = (previous.Metadata.View.Realm, previous.LocalIdentifier);
_nodes.TryGetValue(key, out var current);
var retainedPrevious = current is not null && ReferenceEquals(current.Proof, previous) && !current.Retired ||
_retiredByProof.ContainsKey(previous);
var mapping = previous.Metadata.View.MappingId;
if (!retainedPrevious || mapping is null || _saturated ||
!_mappingGenerations.TryGetValue(mapping, out var generation) || frozen.Generation != generation ||
!SameRenewalLineage(previous, frozen) || overlap && (!Valid(previous) || !SameOverlap(previous, frozen)) ||
!Valid(frozen)) return false;
if (current is not null && !ReferenceEquals(current.Proof, previous))
{
// A previous SDK transaction can lose its final guard after the cache
// committed. Only an exact descendant of the still-pinned old proof may
// be adopted/replaced; never overwrite an unrelated current binding.
if (!SameRenewalLineage(previous, current.Proof)) return false;
if (Valid(current.Proof))
{
if (overlap && (current.Predecessor is not { Pins: > 0 } predecessor ||
!ReferenceEquals(predecessor.Proof, previous) || !SameOverlap(previous, current.Proof))) return false;
if (current.Proof.Lease.Serving != frozen.Lease.Serving ||
!SameMetadata(current.Proof.Metadata, frozen.Metadata) ||
!SameMetadata(current.Proof.OriginMetadata, frozen.OriginMetadata)) return false;
committed = current.Proof;
return true;
}
}
var addsEntry = current is null || current.Pins > 0;
if (overlap && (current is null || current.Pins <= 0 || !ReferenceEquals(current.Proof, previous))) return false;
if (_nodes.Count + _retiredPinned.Count + (addsEntry ? 1 : 0) > _maxNodes) return false;
// A replacement and one still-pinned predecessor are distinct physical owners,
// but only one logical projected node. Never admit a chain of predecessors.
_retiredPerNode.TryGetValue(key, out var oldCount);
if ((long)oldCount + (current is { Pins: > 0 } ? 1 : 0) + 1 > 2) return false;
_mappingNodeCounts.TryGetValue(mapping, out var count);
var physicalMappingLimit = (long)maximumMappingNodes + Math.Min((long)maximumMappingNodes, _maxNodes);
if ((long)count + (addsEntry ? 1 : 0) > physicalMappingLimit) return false;
var delta = Bytes(frozen) - (current is { Pins: 0 } ? Bytes(current.Proof) : 0);
if (delta > _maxBytes - _retainedBytes) return false;
AddNode(key, frozen);
if (overlap) _nodes[key].Predecessor = current;
committed = frozen;
return true;
}
}
private static bool SameMetadata(DataMetadata left, DataMetadata right) =>
left.Dimensions.SequenceEqual(right.Dimensions) && (left with { Dimensions = right.Dimensions }) == right;
private static bool SameRenewalLineage(ProjectedNodeProof left, ProjectedNodeProof right) =>
left.LocalIdentifier == right.LocalIdentifier && left.Metadata.View == right.Metadata.View &&
left.OriginMetadata.View == right.OriginMetadata.View && left.Subject.Scope.Kind == right.Subject.Scope.Kind &&
string.Equals(left.Subject.Scope.ClusterId, right.Subject.Scope.ClusterId, StringComparison.OrdinalIgnoreCase) &&
left.Subject.Scope.Segments.SequenceEqual(right.Subject.Scope.Segments, StringComparer.Ordinal) &&
left.Subject.LocalAncestry.SequenceEqual(right.Subject.LocalAncestry, StringComparer.OrdinalIgnoreCase);
private static bool SameOverlap(ProjectedNodeProof left, ProjectedNodeProof right) =>
SameRenewalLineage(left, right) && left.Generation == right.Generation && left.MaximumSampleAge == right.MaximumSampleAge &&
left.Lease.Serving == right.Lease.Serving && SameMetadata(left.Metadata, right.Metadata) && SameMetadata(left.OriginMetadata, right.OriginMetadata) &&
left.Subject.Serving == right.Subject.Serving && left.Subject.AllowedOperations == right.Subject.AllowedOperations &&
left.Subject.WriteThrough == right.Subject.WriteThrough && ReferenceEquals(left.Resolver.LocalAuthority, right.Resolver.LocalAuthority) &&
left.Lease is BoundProjectionLease a && right.Lease is BoundProjectionLease b && a.RouteIdentity is not null &&
ReferenceEquals(a.RouteIdentity, b.RouteIdentity) && a.BindingIdentity is not null && ReferenceEquals(a.BindingIdentity, b.BindingIdentity) &&
a.Target is not null && a.Target == b.Target;
public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof)
{
lock (_sync)
@@ -358,6 +496,32 @@ public sealed class ProjectedCatalogCache
entry.Pins++; pin = new Pin(this, entry); return true;
}
}
// Pins an already charged, expired successor solely for an invalid recovery
// binding. The caller must separately prove the source's exact predecessor.
internal bool TryPinExpiredRecoveryPair(ProjectedNodeProof previous, ProjectedNodeProof successor, out IDisposable? pin)
{
pin = null;
lock (_sync)
{
var key = (previous.Metadata.View.Realm, previous.LocalIdentifier);
if (!_retiredByProof.TryGetValue(previous, out var predecessor) || predecessor.Pins <= 0 ||
previous.Lease is not BoundProjectionLease oldLease || successor.Lease is not BoundProjectionLease nextLease ||
!oldLease.ExpiredNaturally || !nextLease.ExpiredNaturally || !SameOverlap(previous, successor)) return false;
_retiredPerNode.TryGetValue(key, out var retiredCount);
NodeEntry? current;
if (_nodes.TryGetValue(key, out var active))
{
if (!ReferenceEquals(active.Proof, successor) || retiredCount != 1 ||
!ReferenceEquals(active.Predecessor, predecessor)) return false;
current = active;
}
else if (retiredCount != 2 || !_retiredByProof.TryGetValue(successor, out current)) return false;
if (current.Pins <= 0) return false;
checked { current.Pins++; }
pin = new Pin(this, current);
return true;
}
}
private sealed class Pin(ProjectedCatalogCache owner, NodeEntry entry) : IDisposable
{
private int _disposed;
@@ -370,8 +534,15 @@ public sealed class ProjectedCatalogCache
if (entry.Pins == 0 && entry.Retired)
{
var key = (entry.Proof.Metadata.View.Realm, entry.Proof.LocalIdentifier);
if (owner._nodes.TryGetValue(key, out var successor) && ReferenceEquals(successor.Predecessor, entry)) successor.Predecessor = null;
if (owner._nodes.TryGetValue(key, out var current) && ReferenceEquals(current, entry)) owner.RemoveNode(key);
if (owner._retiredPinned.Remove(entry)) { owner._retainedBytes -= Bytes(entry.Proof); owner.ChangeMappingCount(entry, -1); }
if (owner._retiredPinned.Remove(entry))
{
owner._retiredByProof.Remove(entry.Proof);
var retiredCount = owner._retiredPerNode[key] - 1;
if (retiredCount == 0) owner._retiredPerNode.Remove(key); else owner._retiredPerNode[key] = retiredCount;
owner._retainedBytes -= Bytes(entry.Proof); owner.ChangeMappingCount(entry, -1);
}
}
}
}
File diff suppressed because it is too large Load Diff
@@ -13,6 +13,11 @@ public sealed record ProjectedMappingPlacement(RemoteNamespaceMapping Mapping, D
public sealed class ProjectedMappingDeploymentRuntime : IDisposable
{
private readonly object _gate = new();
// Serializes placement transitions with the SDK anchor reconciler without holding
// the catalog gate across SDK calls or introducing SDK -> transition lock ordering.
internal object TransitionGate { get; } = new();
private bool _suspended;
internal bool Suspended => Volatile.Read(ref _suspended);
private readonly LocalCatalogCoordinator _coordinator;
private readonly RemoteNamespaceResolver _resolver;
private CatalogAttempt? _attempt;
@@ -130,10 +135,12 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable
internal void AttemptBegan(CatalogAttempt attempt)
{
bool changed;
lock (TransitionGate)
lock (_gate)
{
if (_disposed || _attempt is not null && attempt.Epoch <= _attempt.Epoch) return;
_attempt = attempt;
Volatile.Write(ref _suspended, true);
Volatile.Write(ref _configuredStamp, new object());
_configuredCapabilities.Clear();
_staged = []; _connections = [];
@@ -148,12 +155,14 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable
internal void AttemptCompleted(CatalogAttempt attempt, bool completed)
{
IReadOnlyList<ProjectedMappingPlacement> published;
lock (TransitionGate)
lock (_gate)
{
if (_disposed || !ReferenceEquals(_attempt, attempt)) return;
Volatile.Write(ref _configuredStamp, new object());
_configuredCapabilities.Clear();
var catalog = completed ? _coordinator.MappingCatalog(attempt) : null;
var success = false;
if (catalog is null || !catalog.IsActive)
{
_resolver.ApplyMappings([]);
@@ -171,6 +180,7 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable
if (current is null || !ReferenceEquals(current.MappingAuthority, catalog.MappingAuthority) || !catalog.IsActive)
throw new InvalidOperationException("Catalog attempt changed during projection activation.");
Volatile.Write(ref _active, Array.AsReadOnly(placements));
success = true;
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or OverflowException)
{
@@ -178,6 +188,7 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable
Volatile.Write(ref _active, Array.Empty<ProjectedMappingPlacement>());
}
}
Volatile.Write(ref _suspended, !success);
_byMapping = _active.ToDictionary(x => x.Mapping.RemoteNamespaceMappingId, StringComparer.OrdinalIgnoreCase);
published = CopyPlacements(_active);
}
@@ -233,10 +244,12 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable
public void Dispose()
{
lock (TransitionGate)
lock (_gate)
{
if (_disposed) return;
_disposed = true;
Volatile.Write(ref _suspended, false);
Volatile.Write(ref _configuredStamp, new object());
_configuredCapabilities.Clear();
Volatile.Write(ref _active, Array.Empty<ProjectedMappingPlacement>());
@@ -0,0 +1,13 @@
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Bounded aggregate observations of projected stream admission and delivery.</summary>
public static class ProjectedStreamDiagnostics
{
internal enum Event { AcquireInvalid, AcquireDefinition, AcquireAuthorization, AcquirePin, AcquireCapacity, AcquireStale, AcquireAccepted, AcquireException,
Attempt, Frame, Reset, SnapshotEnd, Value, UnknownAge, StaleAge, FreshAge, PublishDemand, PublishStale, PublishVersion, PublishProof, PublishSink, PublishAccepted,
AttemptCanceled, AttemptInvalidData, AttemptOther, ResetHistory, ResetUnavailable, ResetSnapshot, ResetOther }
private static readonly long[] Counts = new long[Enum.GetValues<Event>().Length];
internal static void Count(Event value) => Interlocked.Increment(ref Counts[(int)value]);
/// <summary>Captures process-wide counters without source identifiers or payloads.</summary>
public static IReadOnlyDictionary<string, long> Capture() => Enum.GetValues<Event>().ToDictionary(x => x.ToString(), x => Interlocked.Read(ref Counts[(int)x]));
}
@@ -1,8 +1,10 @@
using System.Collections.ObjectModel;
using NodeId = Opc.Ua.NodeId;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
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;
@@ -94,7 +96,10 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => _cache.TryGetParent(request);
public IProjectedPageGuard? CaptureParentGuard(ProjectedBrowseRequest request, ProjectedParentSnapshot expected) => _cache.CaptureParentGuard(request, expected);
public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) => _cache.TryResolveProjected(realm, localId, out proof);
public bool IsUsableProof(ProjectedNodeProof proof) => _cache.IsUsableProof(proof);
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) => _cache.TryPinProjected(realm, localId, out pin);
internal bool TryPinExpiredRecoveryPair(ProjectedNodeProof previous, ProjectedNodeProof successor, out IDisposable? pin) =>
_cache.TryPinExpiredRecoveryPair(previous, successor, out pin);
public async Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request); request.Budget.Validate(); request.Parent.Validate();
@@ -228,7 +233,8 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
var maxLease = TimeSpan.FromMilliseconds(binding.Mapping.MetadataLeaseMilliseconds);
var lease = new BoundProjectionLease(new MetadataAuthorityLease(serving, branch.Lease, request.RequestStartedTimestamp, maxLease, TimeSpan.Zero, Clock),
connection.CancellationToken, binding.LocalAuthority, _cache, request.MappingId, generation, () => IsCurrent(binding));
connection.CancellationToken, binding.LocalAuthority, _cache, request.MappingId, generation, () => IsCurrent(binding), connection.RouteCurrent,
connection.RouteIdentity, connection.Connection.Target, binding);
if (!lease.IsValid) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
var parentScope = previousParent?.Subject.Scope ?? binding.LocalScope;
var ancestry = previousParent?.Subject.LocalAncestry ?? binding.LocalAncestry;
@@ -273,6 +279,130 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
{
lock (_sync) return !_disposed && _mappings.TryGetValue(binding.Mapping.RemoteNamespaceMappingId, out var current) && ReferenceEquals(current, binding);
}
private sealed class ExactAuthority(ProjectedNodeProof proof) : IProjectedRetainedAuthority
{
private ProjectedNodeProof _proof = proof;
public long RetainedBytes { get; } = checked(2048L + ProjectedProofSize.Estimate(proof));
internal void Adopt(ProjectedNodeProof committed) => Volatile.Write(ref _proof, committed);
internal bool IsFor(ProjectedNodeProof committed) => ReferenceEquals(Volatile.Read(ref _proof), committed);
public bool IsCurrent()
{
var proof = Volatile.Read(ref _proof);
try { return proof.Lease.IsValid && proof.Resolver.LocalAuthority.IsActive &&
proof.Resolver.Resolve(proof.Metadata.View, proof.Subject).Kind == MappedSubjectResolutionKind.Mapped; }
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; }
}
}
internal static bool DefinitionOwnsProof(ProjectedVariableDefinition definition, ProjectedNodeProof proof) =>
definition.AuthorityIsCurrent.Target is ExactAuthority authority && authority.IsFor(proof) && authority.IsCurrent();
// Refresh exactly one already-owned projected item. This deliberately creates no Browse
// page, cursor or sibling visibility and does not create a physical subscription.
internal async Task<bool> RenewExactAsync(ProjectedNodeProof previous, ProjectedVariableDefinition definition,
NodeId nodeId, DataCallerIdentity? caller, ConfiguredProjectionCapability? configured,
IProjectedNamespacePageSink sink, DataBudget budget, Func<bool> demandActive, CancellationToken cancellationToken, bool overlap = false)
{
var mapping = previous.Metadata.View.MappingId;
if (mapping is null || previous.Subject.Scope.Segments.Count == 0) return false;
ProjectedMappingBinding binding;
lock (_sync)
{
if (_disposed || !_mappings.TryGetValue(mapping, out binding!)) return false;
}
bool CallerAllowed() => demandActive() && (configured is not null
? configured.Matches(mapping, previous.Metadata.View, binding.LocalAuthority)
: caller is not null && _policy.IsCallerUsable(caller) &&
_policy.AuthorizeLocal(caller, OpcUaOperation.CreateMonitoredItems, previous.Subject.Scope));
if (!IsCurrent(binding) || !binding.LocalAuthority.IsActive || !CallerAllowed() ||
previous.Metadata.View.MappingRevision != binding.Mapping.Revision || previous.Metadata.View.Realm != binding.Mapping.Realm ||
previous.OriginMetadata.View.MappingId is not null ||
previous.Subject.Scope.Kind != binding.LocalScope.Kind ||
!string.Equals(previous.Subject.Scope.ClusterId, binding.LocalScope.ClusterId, StringComparison.OrdinalIgnoreCase) ||
previous.Subject.Scope.Segments.Count < binding.LocalScope.Segments.Count ||
!previous.Subject.Scope.Segments.Take(binding.LocalScope.Segments.Count).SequenceEqual(binding.LocalScope.Segments, StringComparer.Ordinal) ||
!previous.Subject.LocalAncestry.SequenceEqual(binding.LocalAncestry, StringComparer.OrdinalIgnoreCase)) return false;
if (!await _fetchSlots.WaitAsync(0, cancellationToken).ConfigureAwait(false)) return false;
IGrpcDataAdapterConnectionLease? connection = null;
try
{
var started = Clock.GetTimestamp();
using var timeout = new CancellationTokenSource(budget.Timeout, Clock);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token);
connection = await _source.AcquireAsync(binding.Mapping.DataConnectionId, linked.Token).ConfigureAwait(false);
if (connection is null || !ReferenceEquals(connection.Connection.Clock, Clock) ||
!string.Equals(connection.Connection.Target.ExpectedClusterId, previous.OriginMetadata.View.Address.OriginClusterId, StringComparison.OrdinalIgnoreCase)) return false;
using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken);
var capabilities = await connection.Connection.GetCapabilitiesAsync(budget, route.Token).ConfigureAwait(false);
capabilities.Validate();
var serving = capabilities.Serving;
var target = connection.Connection.Target;
if (!capabilities.MetadataItemLeases || capabilities.Readiness != DataReadiness.Ready ||
(capabilities.Operations & DataOperations.Metadata) == 0 || serving.ServingGeneration <= 0 ||
!(string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase) ||
target.Mode == DataTargetMode.Node && target.Consistency == DataConsistency.ReadyReplica && string.Equals(serving.Role, "Secondary", StringComparison.OrdinalIgnoreCase))) return false;
var elapsed = Clock.GetElapsedTime(started, Clock.GetTimestamp());
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) return false;
var results = await connection.Connection.GetMetadataAsync(new([previous.OriginMetadata.View],
budget with { MaxItems = 1, Timeout = budget.Timeout - elapsed }), route.Token).ConfigureAwait(false);
elapsed = Clock.GetElapsedTime(started, Clock.GetTimestamp());
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout || linked.IsCancellationRequested) return false;
if (results.Count != 1 || results[0].CorrelationId != "0" || results[0].Status != DataItemStatus.Good ||
results[0].Value is not { } metadata || results[0].Lease is not { } remoteLease ||
metadata.View != previous.OriginMetadata.View || metadata.Serving != serving || metadata.CatalogRevision != serving.CatalogEpoch ||
remoteLease.CatalogEpoch != serving.CatalogEpoch || remoteLease.AuthorityEpoch != serving.AuthorityEpoch ||
remoteLease.Duration <= TimeSpan.Zero || remoteLease.Duration > capabilities.Limits.MaxMetadataLease ||
metadata.BrowseName != previous.OriginMetadata.BrowseName || metadata.NodeKind != previous.OriginMetadata.NodeKind ||
metadata.ValueKind != previous.OriginMetadata.ValueKind || metadata.ValueRank != previous.OriginMetadata.ValueRank ||
metadata.ArrayElementKind != previous.OriginMetadata.ArrayElementKind ||
!metadata.Dimensions.SequenceEqual(previous.OriginMetadata.Dimensions) ||
(metadata.AllowedOperations & binding.Mapping.AllowedOperations & DataOperations.Subscribe) == 0 ||
!IsCurrent(binding) || !CallerAllowed() || connection.CancellationToken.IsCancellationRequested) return false;
metadata.Validate(); remoteLease.Validate();
var generation = _cache.CaptureGeneration(mapping);
var maximumLease = TimeSpan.FromMilliseconds(binding.Mapping.MetadataLeaseMilliseconds);
if (caller?.CredentialExpiresUtc is { } expiry)
{
var remaining = expiry - Clock.GetUtcNow();
if (remaining <= TimeSpan.Zero) return false;
if (remaining < maximumLease) maximumLease = remaining;
}
var lease = new BoundProjectionLease(new MetadataAuthorityLease(serving, remoteLease, started, maximumLease, TimeSpan.Zero, Clock),
connection.CancellationToken, binding.LocalAuthority, _cache, mapping, generation, () => IsCurrent(binding), connection.RouteCurrent,
connection.RouteIdentity, connection.Connection.Target, binding);
var subject = previous.Subject with { Serving = serving, AllowedOperations = binding.Mapping.AllowedOperations & metadata.AllowedOperations,
WriteThrough = binding.Mapping.WriteThrough && metadata.Writable };
var mapped = metadata with { View = previous.Metadata.View };
var resolver = new MappedSubjectResolver([subject], serving.CatalogEpoch, binding.LocalAuthority);
var renewed = new ProjectedNodeProof(previous.LocalIdentifier, mapped, subject, resolver, lease, generation, metadata,
TimeSpan.FromMilliseconds(binding.Mapping.StaleTimeoutMilliseconds));
var guard = new ExactAuthority(renewed);
if (!guard.IsCurrent() || caller is not null && !_policy.AuthorizeMapped(caller, OpcUaOperation.CreateMonitoredItems,
mapped.View, serving, subject, resolver, lease)) return false;
var newDefinition = new ProjectedVariableDefinition(definition.Realm, definition.LocalIdentifier, definition.Parent,
mapped, generation, guard.IsCurrent) { Lifetime = definition.Lifetime };
return sink.TryRenewExact(nodeId, definition, newDefinition, () =>
{
var duration = Clock.GetElapsedTime(started, Clock.GetTimestamp());
if (linked.IsCancellationRequested || cancellationToken.IsCancellationRequested || connection.CancellationToken.IsCancellationRequested ||
duration < TimeSpan.Zero || duration >= budget.Timeout ||
!IsCurrent(binding) || !CallerAllowed() || !guard.IsCurrent()) return false;
ProjectedNodeProof? actual;
var committed = overlap ? _cache.TryRenewOverlap(previous, renewed, binding.Mapping.MaxProjectionNodes, out actual) :
_cache.TryRenewExact(previous, renewed, binding.Mapping.MaxProjectionNodes, out actual);
if (!committed || actual is null) return false;
guard.Adopt(actual);
return guard.IsCurrent();
});
}
catch (Exception ex) when (ex is not OutOfMemoryException) { return false; }
finally
{
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
catch (Exception) { }
finally { _fetchSlots.Release(); }
}
}
public void Dispose()
{
ProjectedMappingBinding[] old;
@@ -13,7 +13,10 @@ internal sealed class SamplePartition : IDisposable
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 ConcurrentQueue<Pending> _mailbox = new();
private readonly ConcurrentQueue<SourceState> _dirty = new();
private int _dirtyCount;
private int _producerState; // sign bit closes admission; remaining bits count active writers.
private readonly LinkedList<(long Version, BackingSourceKey Key)> _changes = new();
private readonly Dictionary<long, LinkedListNode<(long Version, BackingSourceKey Key)>> _changeIndex = new();
private long _epoch = 1;
@@ -82,7 +85,7 @@ internal sealed class SamplePartition : IDisposable
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);
state.LastApplied = 0; state.Barrier = 0; ReleaseCache(state);
RecordChange(ticket.Key); return true;
}
var charge = SourceCharge(ticket.Key);
@@ -147,63 +150,151 @@ internal sealed class SamplePartition : IDisposable
_hub.Schedule(this);
}
Interlocked.Increment(ref gate.Invalidated);
Interlocked.Increment(ref gate.ProducerStamp);
}
finally { Control.EndQuiet(); }
}
private static bool TryPin(SourceState state)
{
while (true)
{
if (Volatile.Read(ref state.RegistryRetired) != 0) return false;
var count = Volatile.Read(ref state.MetadataOwners);
if (count <= 0 || count == int.MaxValue) return false;
if (Interlocked.CompareExchange(ref state.MetadataOwners, count + 1, count) == count) return true;
}
}
private static bool TryIncrementBounded(ref int count, int maximum)
{
while (true)
{
var current = Volatile.Read(ref count);
if (current >= maximum) return false;
if (Interlocked.CompareExchange(ref count, current + 1, current) == current) return true;
}
}
private static bool TryAdvance(SourceGate gate, long sequence)
{
while (true)
{
var current = Interlocked.Read(ref gate.LastSubmitted);
if (sequence <= current) return false;
if (Interlocked.CompareExchange(ref gate.LastSubmitted, sequence, current) == current) return true;
}
}
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, _hub.Clock.GetTimestamp());
return true;
}
finally { Monitor.Exit(_gate); }
if (_hub.IsDisposed || Volatile.Read(ref _disposed) || _hub.RoutingEpoch != _routingEpoch ||
!_sources.TryGetValue(ticket.Key, out var state) || !TryPin(state)) return false;
var gate = Volatile.Read(ref state.Gate);
var epoch = Interlocked.Read(ref _epoch);
var stamp = Interlocked.Read(ref gate.ProducerStamp);
var signal = Interlocked.Read(ref gate.Invalidated);
if (Volatile.Read(ref state.RegistryRetired) != 0 || !_sources.TryGetValue(ticket.Key, out var current) ||
!ReferenceEquals(current, state) || !IsTicketCurrentNonBlocking(ticket) ||
!ReferenceEquals(gate, Volatile.Read(ref state.Gate)))
{ ReleaseMetadataOwner(state); return false; }
if (estimated <= 0 || estimated > long.MaxValue - PartitionedSampleHub.SampleOverhead ||
!TryIncrementBounded(ref _reservations, (int)Math.Min(int.MaxValue, (long)_hub.Limits.MaxIngressItemsPerPartition + _hub.Limits.MaxDirtySourcesPerPartition)))
{ ReleaseMetadataOwner(state); SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ReserveCapacity); Signal(ticket); return false; }
var charge = estimated + PartitionedSampleHub.SampleOverhead;
if (!_hub.Resources.TryReserve(charge))
{ Interlocked.Decrement(ref _reservations); ReleaseMetadataOwner(state); SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ReserveCapacity); Signal(ticket); return false; }
Interlocked.Increment(ref state.Reservations);
if (!IsTicketCurrentNonBlocking(ticket) || !ReferenceEquals(gate, Volatile.Read(ref state.Gate)) ||
Interlocked.Read(ref _epoch) != epoch || Interlocked.Read(ref gate.ProducerStamp) != stamp || Interlocked.Read(ref gate.Invalidated) != signal)
{ ReleaseReservation(state); _hub.Resources.Release(charge); return false; }
reservation = new Reservation(this, state, gate, ticket, estimated, charge, stamp, signal, epoch, _hub.Clock.GetTimestamp());
return true;
}
private bool Commit(SourceState reservedState, SourceTicket ticket, long estimate, long charge, long invalidationVersion,
long partitionEpoch, long receivedTimestamp, DataSample sample, long sequence)
private bool Commit(SourceState state, SourceGate gate, SourceTicket ticket, long estimate, long charge, long stamp,
long signal, long partitionEpoch, long receivedTimestamp, DataSample sample, long sequence)
{
if (!TryEnterProducer()) { ReleaseReservation(state); _hub.Resources.Release(charge); return false; }
if (Interlocked.CompareExchange(ref gate.Committing, 1, 0) != 0)
{
ReleaseReservation(state); _hub.Resources.Release(charge); Signal(ticket); ExitProducer(); return false;
}
try { return CommitEntered(state, gate, ticket, estimate, charge, stamp, signal, partitionEpoch, receivedTimestamp, sample, sequence); }
finally { Volatile.Write(ref gate.Committing, 0); ExitProducer(); }
}
private bool CommitEntered(SourceState state, SourceGate gate, SourceTicket ticket, long estimate, long charge, long stamp,
long signal, long partitionEpoch, long receivedTimestamp, 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, receivedTimestamp) { 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;
ArgumentNullException.ThrowIfNull(sample.Value);
ArgumentNullException.ThrowIfNull(sample.Serving);
sample.Serving.Validate(requireEpochs: false);
if (sample.Version != sequence || sample.Value.EstimatedRetainedBytes > estimate ||
sample.Serving.NodeId != ticket.Key.ServingNodeId || sample.Serving.Incarnation != ticket.Key.ServingIncarnation)
throw new ArgumentException("Invalid ingress sample.");
}
catch (Exception e) when (e is ArgumentException or ObjectDisposedException or OverflowException)
{ SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.CommitInvalid); ReleaseReservation(state); _hub.Resources.Release(charge); Signal(ticket); return false; }
if (!IsTicketCurrentNonBlocking(ticket) || !ReferenceEquals(gate, Volatile.Read(ref state.Gate)) ||
partitionEpoch != Interlocked.Read(ref _epoch) || stamp != Interlocked.Read(ref gate.ProducerStamp) || signal != Interlocked.Read(ref gate.Invalidated))
{ ReleaseReservation(state); _hub.Resources.Release(charge); return false; }
if (!TryAdvance(gate, sequence))
{ ReleaseReservation(state); _hub.Resources.Release(charge); Signal(ticket); return false; }
_hub.AfterValueSequenceForTests?.Invoke();
var pending = new Pending(ticket, sequence, Interlocked.Increment(ref _ordinal), sample, charge, receivedTimestamp)
{ PartitionEpoch = partitionEpoch, Owner = state, Gate = gate, ProducerStamp = stamp, SignalStamp = signal };
var admitted = EnqueueValue(state, pending);
if (admitted != EnqueueResult.Accepted)
{
ReleaseReservation(state); _hub.Resources.Release(charge);
if (admitted == EnqueueResult.Capacity) InvalidatePartition();
else Signal(ticket);
return false;
}
// The mailbox owns the metadata pin; the in-flight copy permit ends at transfer.
Interlocked.Decrement(ref _reservations);
var lastReservation = Interlocked.Decrement(ref state.Reservations) == 0;
if (lastReservation && Volatile.Read(ref state.Gate.Retired) != 0 && !Volatile.Read(ref _disposed)) RequestReclaim();
_hub.Schedule(this);
return true;
}
private bool TryEnterProducer()
{
while (true)
{
var current = Volatile.Read(ref _producerState);
if (current < 0 || current == int.MaxValue) return false;
if (Interlocked.CompareExchange(ref _producerState, current + 1, current) == current) return true;
}
}
private void ExitProducer()
{
if (Interlocked.Decrement(ref _producerState) < 0) Schedule();
}
private enum EnqueueResult { Accepted, Stale, Capacity }
private EnqueueResult EnqueueValue(SourceState state, Pending pending)
{
while (true)
{
var existing = Volatile.Read(ref state.Dirty);
if (existing is not null)
{
if (ReferenceEquals(existing.Gate, pending.Gate) && existing.Sequence >= pending.Sequence ||
!ReferenceEquals(existing.Gate, pending.Gate) && existing.Gate is not null && pending.Gate is not null &&
Compare(existing.Gate.Generation, pending.Gate.Generation) >= 0) return EnqueueResult.Stale;
if (Interlocked.CompareExchange(ref state.Dirty, pending, existing) != existing) continue;
ReleasePending(existing); return EnqueueResult.Accepted;
}
if (TryIncrementBounded(ref _queuedValues, _hub.Limits.MaxIngressItemsPerPartition))
{
if (Volatile.Read(ref state.Dirty) is not null) { Interlocked.Decrement(ref _queuedValues); continue; }
_mailbox.Enqueue(pending); return EnqueueResult.Accepted;
}
if (!TryIncrementBounded(ref _dirtyCount, _hub.Limits.MaxDirtySourcesPerPartition))
{ if (Volatile.Read(ref state.Dirty) is not null) continue; return EnqueueResult.Capacity; }
if (Interlocked.CompareExchange(ref state.Dirty, pending, null) is null)
{ _dirty.Enqueue(state); return EnqueueResult.Accepted; }
Interlocked.Decrement(ref _dirtyCount);
}
finally { Monitor.Exit(_gate); }
}
private void ReleaseReservation(SourceState state)
{
@@ -213,7 +304,7 @@ internal sealed class SamplePartition : IDisposable
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);
internal void Invalidate(SourceTicket ticket) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ExternalInvalidate); Signal(ticket); }
private void InvalidateSource(SourceState state)
{
Control.BeginQuiet();
@@ -227,13 +318,13 @@ internal sealed class SamplePartition : IDisposable
try
{
var partitionEpoch = Interlocked.Read(ref _epoch);
if (_disposed || !Current(ticket, out var state) || sequence <= state.LastSubmitted) return false;
if (_disposed || !Current(ticket, out var state) || !TryAdvance(Volatile.Read(ref state.Gate), sequence)) return false;
if (_queuedControls >= _hub.Limits.MaxControlItemsPerPartition || !_hub.Resources.TryReserve(ControlOverhead)) { InvalidatePartition(); return false; }
var wasReady = state.Readiness == DataReadiness.Ready;
Control.Begin();
try { state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); state.Barrier = sequence; state.LastSubmitted = sequence; }
try { state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); Interlocked.Increment(ref state.Gate.ProducerStamp); state.Barrier = sequence; }
finally { Control.End(); }
_queue.Enqueue(new Pending(ticket, sequence, ++_ordinal, status, source, server, wasReady, ControlOverhead) { AdmissionEpoch = state.InvalidationVersion, PartitionEpoch = partitionEpoch }); _queuedControls++;
_queue.Enqueue(new Pending(ticket, sequence, Interlocked.Increment(ref _ordinal), status, source, server, wasReady, ControlOverhead) { AdmissionEpoch = state.InvalidationVersion, PartitionEpoch = partitionEpoch }); _queuedControls++;
_hub.Schedule(this); return true;
}
finally { Monitor.Exit(_gate); }
@@ -246,17 +337,17 @@ internal sealed class SamplePartition : IDisposable
// 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 (state.Removed || state.Ticket != ticket || Volatile.Read(ref state.Gate.Retired) != 0 || !TryAdvance(Volatile.Read(ref state.Gate), sequence)) return false;
Control.BeginQuiet();
try
{
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);
state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); Interlocked.Increment(ref state.Gate.ProducerStamp); ReleaseCache(state);
}
finally { Control.EndQuiet(); }
RequestReclaim();
_queue.Enqueue(new Pending(ticket, sequence, ++_ordinal, ControlOverhead) { PartitionEpoch = _epoch }); _queuedControls++;
_queue.Enqueue(new Pending(ticket, sequence, Interlocked.Increment(ref _ordinal), ControlOverhead) { PartitionEpoch = _epoch }); _queuedControls++;
_hub.Schedule(this); return true;
}
finally { Monitor.Exit(_gate); }
@@ -273,38 +364,63 @@ internal sealed class SamplePartition : IDisposable
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();
lock (_gate) if ((!_disposed && (_cleanedEpoch != _epoch || Volatile.Read(ref _retiredSweepRequested) != 0 || Volatile.Read(ref _reclaimRequested) != 0 || _queue.Count != 0)) || !_mailbox.IsEmpty || !_dirty.IsEmpty) Schedule();
}
}
internal void Drain()
{
lock (_gate)
{
CleanupInvalidatedEpoch();
CleanupRetiredSources();
while (!_disposed && (_queue.Count != 0 || _dirty.Count != 0))
if (!_disposed) { CleanupInvalidatedEpoch(); CleanupRetiredSources(); }
// Controls present at entry cannot be replenished while this gate is held. Drain
// that finite bounded set first, then give values their own bounded work slice.
var controlsRemaining = _queue.Count;
var valueWork = 0;
while (controlsRemaining > 0 || valueWork < 128)
{
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)
Pending? p = null;
if (controlsRemaining > 0 && _queue.TryDequeue(out var control)) { controlsRemaining--; p = control; _queuedControls--; }
else if (++valueWork > 128) break;
else if (_mailbox.TryPeek(out var first))
{
var dirtyFirst = _dirty.TryPeek(out var dirtyState) ? Volatile.Read(ref dirtyState.Dirty) : null;
if (dirtyFirst is not null && dirtyFirst.Ordinal < first.Ordinal)
{
if (!_dirty.TryDequeue(out dirtyState)) continue;
Interlocked.Decrement(ref _dirtyCount);
p = Interlocked.Exchange(ref dirtyState.Dirty, null);
}
else if (_mailbox.TryDequeue(out p)) Interlocked.Decrement(ref _queuedValues);
}
else if (_dirty.TryDequeue(out var dirtyState))
{
Interlocked.Decrement(ref _dirtyCount);
p = Interlocked.Exchange(ref dirtyState.Dirty, null);
}
else break;
if (p is null) continue;
if (_disposed || p.PartitionEpoch != _epoch ||
p.Owner is not null && (!ReferenceEquals(p.Gate, Volatile.Read(ref p.Owner.Gate)) ||
p.Gate is null || p.ProducerStamp != Interlocked.Read(ref p.Gate.ProducerStamp) || p.SignalStamp != Interlocked.Read(ref p.Gate.Invalidated)))
{ ReleasePending(p); continue; }
if (p.Owner is not null) _hub.BeforePendingValueCurrentForTests?.Invoke();
if (!Current(p.Ticket, out var state) || p.IsControl && p.AdmissionEpoch != state.InvalidationVersion || p.Sequence <= state.LastApplied ||
p.Owner is not null && (!ReferenceEquals(p.Owner, state) || p.PartitionEpoch != Interlocked.Read(ref _epoch) ||
!ReferenceEquals(p.Gate, Volatile.Read(ref state.Gate)) || p.Gate is null ||
p.ProducerStamp != Interlocked.Read(ref p.Gate.ProducerStamp) || p.SignalStamp != Interlocked.Read(ref p.Gate.Invalidated)))
{ 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;
if (p.Owner is not null) ReleaseMetadataOwner(p.Owner);
}
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 };
@@ -315,7 +431,17 @@ internal sealed class SamplePartition : IDisposable
}
RecordChange(p.Ticket.Key);
}
ReclaimTombstones();
if (!_disposed) ReclaimTombstones();
}
}
// Deterministic fixture helper: production workers always use the fixed Drain slice.
internal void DrainForTests()
{
var maximum = (long)_hub.Limits.MaxIngressItemsPerPartition + _hub.Limits.MaxDirtySourcesPerPartition + _hub.Limits.MaxControlItemsPerPartition;
for (long work = 0; work <= maximum / 128 + 1; work++)
{
Drain();
lock (_gate) if (_queue.Count == 0 && _mailbox.IsEmpty && _dirty.IsEmpty) return;
}
}
private void RecordChange(BackingSourceKey key)
@@ -328,6 +454,7 @@ internal sealed class SamplePartition : IDisposable
}
internal void InvalidatePartition()
{
SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.PartitionInvalidated);
Control.BeginQuiet();
try { Interlocked.Increment(ref _epoch); }
finally { Control.EndQuiet(); }
@@ -386,7 +513,7 @@ internal sealed class SamplePartition : IDisposable
_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); }
private void ReleasePending(Pending p) { p.Sample?.Dispose(); _hub.Resources.Release(p.Charge); if (p.Owner is not null) ReleaseMetadataOwner(p.Owner); }
internal CachedSourceRead Read(SourceTicket ticket) => Read(ticket, out _);
internal CachedSourceRead Read(SourceTicket ticket, out long watermark)
@@ -396,12 +523,12 @@ internal sealed class SamplePartition : IDisposable
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);
{ SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ReadNotReady); 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);
if (signal != state.AppliedInvalidations) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ReadInvalidated); 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);
if (!_hub.Resources.TryReserve(charge)) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ReadExhausted); 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,
@@ -477,15 +604,15 @@ internal sealed class SamplePartition : IDisposable
scanned = 0;
lock (_gate)
{
if (_disposed || epoch != _epoch) return false;
if (_disposed || epoch != _epoch) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestEpoch); return false; }
if (position == _watermark) return true;
if (!_changeIndex.TryGetValue(position + 1, out var node)) return false;
if (!_changeIndex.TryGetValue(position + 1, out var node)) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestHistoryGap); return false; }
while (node is not null && scanned < maximum)
{
var change = node.Value; position = change.Version; scanned++;
if (tickets.TryGetValue(change.Key, out var ticket))
{
if (!Current(ticket, out _)) return false;
if (!Current(ticket, out _)) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestTicket); return false; }
changes.Add(new(ticket, change.Version));
}
node = node.Next;
@@ -519,19 +646,26 @@ internal sealed class SamplePartition : IDisposable
public void Dispose()
{
Interlocked.Or(ref _producerState, int.MinValue);
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;
while (_mailbox.TryDequeue(out var value)) { Interlocked.Decrement(ref _queuedValues); ReleasePending(value); }
while (_dirty.TryDequeue(out var dirtyState))
{
Interlocked.Decrement(ref _dirtyCount);
var dirty = Interlocked.Exchange(ref dirtyState.Dirty, null);
if (dirty is not null) ReleasePending(dirty);
}
_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; }
{ public readonly SourceGeneration Generation = generation; public readonly SourceBindingFence Binding = binding; public long Invalidated, ProducerStamp, LastSubmitted; public int Retired, Committing; }
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;
@@ -543,7 +677,7 @@ internal sealed class SamplePartition : IDisposable
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;
public long LastApplied; public long Barrier; public long InvalidationVersion; public Pending? Dirty;
}
private sealed class Pending
{
@@ -553,14 +687,15 @@ internal sealed class SamplePartition : IDisposable
{ 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 SourceState? Owner; public SourceGate? Gate; public long ProducerStamp, SignalStamp;
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, long receivedTimestamp) : IIngressReservation
private sealed class Reservation(SamplePartition partition, SourceState state, SourceGate gate, SourceTicket ticket, long estimate, long charge,
long producerStamp, long signal, long partitionEpoch, long receivedTimestamp) : 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, receivedTimestamp, owned, sequence); }
{ ArgumentNullException.ThrowIfNull(owned); return Interlocked.Exchange(ref _completed, 1) == 0 && partition.Commit(state, gate, ticket, estimate, charge, producerStamp, signal, partitionEpoch, receivedTimestamp, owned, sequence); }
public void Dispose() { if (Interlocked.Exchange(ref _completed, 1) == 0) partition.Abandon(state, charge); }
}
}
@@ -0,0 +1,12 @@
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Bounded aggregate observations of origin source admission and retained history.</summary>
public static class SourceIngressDiagnostics
{
internal enum Event { ReserveLock, CommitLock, ReserveCapacity, CommitInvalid, PartitionInvalidated, ExternalInvalidate,
ReadNotReady, ReadInvalidated, ReadExhausted, InterestReset, InterestQuiet, InterestEpoch, InterestHistoryGap, InterestTicket }
private static readonly long[] Counts = new long[Enum.GetValues<Event>().Length];
internal static void Count(Event value) => Interlocked.Increment(ref Counts[(int)value]);
/// <summary>Captures process-wide counters without source identifiers or payloads.</summary>
public static IReadOnlyDictionary<string, long> Capture() => Enum.GetValues<Event>().ToDictionary(x => x.ToString(), x => Interlocked.Read(ref Counts[(int)x]));
}
@@ -56,7 +56,7 @@ public sealed class SourceInterestLease : IDisposable
{
if (Volatile.Read(ref _released) != 0 || _hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch) return true;
foreach (var cursor in Volatile.Read(ref _cursors))
if (!cursor.Partition.Control.Quiet.Matches(cursor.QuietControl)) return true;
if (!cursor.Partition.Control.Quiet.Matches(cursor.QuietControl)) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestQuiet); return true; }
return Volatile.Read(ref _released) != 0 || _hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch;
}
}
@@ -69,7 +69,7 @@ public sealed class SourceInterestLease : IDisposable
{
var result = new List<SourceInterestChange>();
changes = result;
if (IsReset) { Release(); return false; }
if (IsReset) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestReset); Release(); return false; }
var scanned = 0;
for (var visited = 0; visited < _cursors.Length && scanned < maximum; visited++)
{
@@ -78,7 +78,7 @@ public sealed class SourceInterestLease : IDisposable
maximum - scanned, result, out var used)) { Release(); result.Clear(); return false; }
scanned += used;
}
if (IsReset) { Release(); result.Clear(); return false; }
if (IsReset) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestReset); Release(); result.Clear(); return false; }
return true;
}
}
@@ -80,6 +80,10 @@ internal sealed class UpstreamDemandRegistry
if (maxKeys <= 0 || maxInterests <= 0) throw new ArgumentOutOfRangeException(nameof(maxKeys));
_maxKeys = maxKeys; _maxInterests = maxInterests;
}
internal (int Groups, int Interests) CaptureAccounting()
{
lock (_gate) return (_entries.Count, _interestCount);
}
internal bool TryAdd(DemandSharingKey key, DataSubscriptionSettings settings, out IDisposable? lease)
{
ArgumentNullException.ThrowIfNull(key); ArgumentNullException.ThrowIfNull(settings);
@@ -916,7 +916,12 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
Receive<RetrySourceBindings>(RetrySourceBindingBatch);
ReceiveAsync<SetDesiredSubscriptions>(async msg =>
{
if (msg.RequireAcquisition) { await ApplyAcquisitionDemandAsync(msg, Sender); return; }
if (msg.RequireAcquisition)
{
var replyTo = Sender;
await ApplyAcquisitionDemandAsync(msg, result => replyTo.Tell(result));
return;
}
if (_abandonedAcquisition is { } abandoned && !abandoned.Finished.IsCompleted)
{
var schedule = _deferredLegacyDemand is null;
@@ -1880,6 +1885,34 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
try
{
// With a source hub, use the driver's acknowledged physical acquisition feed even
// for the ordinary baseline. A change-only event cannot prove that an unchanged
// device value has been read again. This replaces the baseline poller; it does not
// add a second subscription or change the driver's native change notifications.
if (_sourcePublisher is not null && _sourceIncarnation is > 0 && _acquisitionCapacity is not null &&
_driver is IAcknowledgedBaselineAcquisitionSource && msg.FullReferences.Count > 0)
{
if (_previousAcquisitionCleanup is { IsCompleted: false } cleanup)
await cleanup.WaitAsync(_acquisitionTimeout);
var admission = new LegacyAdmission(this, self, stageSources: false);
Volatile.Write(ref _legacyAdmission, admission);
AttachDataChangeHandler(subscribable, self);
AcquisitionDemandApplied? applied = null;
await ApplyAcquisitionDemandAsync(new SetDesiredSubscriptions(msg.FullReferences, msg.PublishingInterval,
DesiredRevision: 1, ProducerIncarnation: _sourceIncarnation.Value, RequireAcquisition: true),
result => applied = result, baseline: true);
if (applied is not { Succeeded: true } || _subscriptionHandle is null)
throw new InvalidOperationException("Baseline acquisition was not acknowledged.");
if (!admission.Finish(_subscriptionHandle))
{
await UnsubscribeAsync();
throw new InvalidOperationException("Legacy initial callback staging capacity exceeded.");
}
replyTo.Tell(new SubscriptionEstablished(_subscriptionHandle.DiagnosticId, msg.FullReferences.Count));
_log.Info("DriverInstance {Id}: subscribed to {Count} refs ({Diag})",
_driverInstanceId, msg.FullReferences.Count, _subscriptionHandle.DiagnosticId);
return;
}
var sourceBindingNeedsRetry = false;
if (_sourcePublisher is not null && _sourceIncarnation is { } incarnation)
{
@@ -1985,7 +2018,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
// callbacks under a bounded generation gate, then accept only the returned handle. Source
// reservations capture their own monotonic ingress time at callback time; SDK delivery does
// not depend on source-hub admission.
private sealed class LegacyAdmission(DriverInstanceActor owner, IActorRef self) : IDisposable
private sealed class LegacyAdmission(DriverInstanceActor owner, IActorRef self, bool stageSources = true) : IDisposable
{
private const int MaxItems = 4096;
private const long MaxBytes = 16 * 1024 * 1024;
@@ -2027,7 +2060,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
bytes = checked(bytes + OwnedDataSample.Estimate(item.Snapshot.Value) + 2L * item.FullReference.Length);
if (bytes > MaxBytes - _bytes) throw new ArgumentException("Legacy initial callback budget exceeded.");
copied[i] = new DataChangeItem(item.FullReference, CopyLegacySnapshot(item.Snapshot));
sources[i] = owner.StageLegacySource(item);
if (stageSources) sources[i] = owner.StageLegacySource(item);
}
_items += items.Count; _bytes += bytes;
_events.Add(new StagedEvent(handle, copied, sources));
@@ -2213,36 +2246,37 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
}
}
private async Task ApplyAcquisitionDemandAsync(SetDesiredSubscriptions desired, IActorRef replyTo)
private async Task ApplyAcquisitionDemandAsync(SetDesiredSubscriptions desired,
Action<AcquisitionDemandApplied> reply, bool baseline = false)
{
var failed = new AcquisitionDemandApplied(desired.DesiredRevision, desired.ProducerIncarnation, TimeSpan.Zero, false);
if (_abandonedAcquisition is { } abandoned)
{
if (!abandoned.Finished.IsCompleted)
{
replyTo.Tell(failed with { Busy = true, RetryWhenReady = abandoned.Finished });
reply(failed with { Busy = true, RetryWhenReady = abandoned.Finished });
return;
}
if (!abandoned.Finished.IsCompletedSuccessfully || !abandoned.Finished.Result)
{
replyTo.Tell(failed);
reply(failed);
return;
}
_abandonedAcquisition = null;
}
if (_desiredAcquisition is { } current && _subscriptionHandle is not null &&
if (!baseline && _desiredAcquisition is { } current && _subscriptionHandle is not null &&
Volatile.Read(ref _activeAcquisition) is not null && current.DesiredRevision == desired.DesiredRevision &&
current.ProducerIncarnation == desired.ProducerIncarnation && current.PublishingInterval == desired.PublishingInterval &&
current.FullReferences.SequenceEqual(desired.FullReferences, StringComparer.Ordinal))
{
StoreDesiredSubscriptions(desired);
SubscribeDesiredAlarms();
replyTo.Tell(new AcquisitionDemandApplied(desired.DesiredRevision, desired.ProducerIncarnation, _acquisitionNominal, true));
reply(new AcquisitionDemandApplied(desired.DesiredRevision, desired.ProducerIncarnation, _acquisitionNominal, true));
return;
}
if (_previousAcquisitionCleanup is { IsCompleted: false } cleanup)
{
replyTo.Tell(failed with { Busy = true, RetryWhenReady = cleanup });
reply(failed with { Busy = true, RetryWhenReady = cleanup });
return;
}
if (_driver is not IAcknowledgedAcquisitionSource source || _driver is not ISubscribable subscribable ||
@@ -2251,7 +2285,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
_acquisitionCapacity is null || _activeCapacity?.IsUncertain == true || _previousAcquisitionCleanup is { IsCompleted: false } ||
_previousAcquisitionCleanup is { IsCompletedSuccessfully: true, Result: false })
{
replyTo.Tell(failed);
reply(failed);
return;
}
var shared = _activeCapacity;
@@ -2261,7 +2295,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
var reservation = _acquisitionCapacity.TryAcquire(_clusterId, _driverInstanceId, out var ready);
if (reservation is null)
{
replyTo.Tell(ready is null ? failed : failed with { Busy = true, RetryWhenReady = ready });
reply(ready is null ? failed : failed with { Busy = true, RetryWhenReady = ready });
return;
}
shared = new SharedAcquisitionReservation(reservation);
@@ -2316,32 +2350,35 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
operation.Abandon();
_abandonedAcquisition = operation;
if (!hadHandler) DetachDataSubscription();
replyTo.Tell(failed);
reply(failed);
return;
}
var activeReference = _activeCapacityReference is null ? shared.Retain() : null;
if (!operation.TryAdopt(installed))
{
activeReference?.Dispose();
replyTo.Tell(failed);
reply(failed);
return;
}
if (activeReference is not null) { _activeCapacity = shared; _activeCapacityReference = activeReference; }
_subscriptionHandle = installed.Handle;
Volatile.Write(ref _fenceLegacyHandles, true);
Interlocked.Exchange(ref _legacyAdmission, null)?.Dispose();
if (!baseline) Interlocked.Exchange(ref _legacyAdmission, null)?.Dispose();
Volatile.Write(ref _activeAcquisition, fence);
Volatile.Write(ref _acquisitionPending, 0);
StoreDesiredSubscriptions(desired);
_desiredAcquisition = desired;
if (!baseline)
{
StoreDesiredSubscriptions(desired);
_desiredAcquisition = desired;
}
_acquisitionNominal = installed.NominalSamplingInterval;
if (sourceBindingNeedsRetry)
Timers.StartSingleTimer("source-binding-retry", new RetrySourceBindings(desired.FullReferences,
0, false, 0, sourceBindingVersion, fence.Producer), TimeSpan.FromMilliseconds(250));
SubscribeDesiredAlarms();
if (!baseline) SubscribeDesiredAlarms();
if (previousHandle is not null && !ReferenceEquals(previousHandle, installed.Handle))
_previousAcquisitionCleanup = CleanupAcquiredHandleAsync(subscribable, previousHandle, shared.Retain(), shared);
replyTo.Tell(new AcquisitionDemandApplied(fence.Revision, fence.Producer, installed.NominalSamplingInterval, true));
reply(new AcquisitionDemandApplied(fence.Revision, fence.Producer, installed.NominalSamplingInterval, true));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
@@ -2349,7 +2386,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
else operation.CancelBeforeStart();
if (!hadHandler) DetachDataSubscription();
_log.Warning(ex, "DriverInstance {Id}: acquisition demand failed", _driverInstanceId);
replyTo.Tell(failed);
reply(failed);
}
finally { _pendingAcquisition = null; Volatile.Write(ref _acquisitionPending, 0); }
}
@@ -97,6 +97,9 @@ public interface IHistoryUpdateRoleView
void PublishHistoryUpdateRole(bool shouldServeHistoryUpdate);
}
/// <summary>An atomic observation of the data-plane role and its independent continuity epoch.</summary>
public sealed record DataServingRoleSnapshot(string Role, long Generation, long ReadEligibilityEpoch);
/// <summary>
/// Thread-safe <see cref="IRedundancyRoleView"/> + <see cref="IDriverPrimaryRoleSource"/> +
/// <see cref="IHistorizationRoleView"/> + <see cref="IHistoryUpdateRoleView"/>, each backed by its own volatile field.
@@ -117,11 +120,19 @@ public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRole
{
public RedundancyRoleView(DataWriteDispatchFence? dispatchFence = null) => DispatchFence = dispatchFence ?? new();
public DataWriteDispatchFence DispatchFence { get; }
private sealed record PrimaryVerdict(bool Allowed, long Generation, string ServingRole);
private PrimaryVerdict _primaryVerdict = new(PrimaryGatePolicy.ShouldServiceAsPrimary(null, 1), 0, "Unknown");
private sealed record PrimaryVerdict(bool Allowed, long Generation, string ServingRole, long ReadEligibilityEpoch);
private PrimaryVerdict _primaryVerdict = new(PrimaryGatePolicy.ShouldServiceAsPrimary(null, 1), 0, "Unknown", 1);
private long _nextDataOwner, _dataOwner;
private bool _rolePoisoned;
public long PrimaryGeneration => Volatile.Read(ref _primaryVerdict).Generation;
/// <summary>Changes on owner replacement or loss of a known readable role.</summary>
public long ReadEligibilityEpoch => Volatile.Read(ref _primaryVerdict).ReadEligibilityEpoch;
/// <summary>Captures the immutable role verdict without acquiring the dispatch fence.</summary>
public DataServingRoleSnapshot CaptureDataServingRole()
{
var verdict = Volatile.Read(ref _primaryVerdict);
return new(verdict.ServingRole, verdict.Generation, verdict.ReadEligibilityEpoch);
}
/// <summary>The actual observed role, independent of the existing primary policy's boot fallback.</summary>
public string DataServingRole => Volatile.Read(ref _primaryVerdict).ServingRole;
// seeded CLOSED, unlike the data-plane verdict. HistoryUpdate waits for a real redundancy verdict
@@ -181,10 +192,10 @@ public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRole
using (DispatchFence.Enter())
{
var current = _primaryVerdict;
if (_rolePoisoned || _nextDataOwner == long.MaxValue || current.Generation == long.MaxValue)
if (_rolePoisoned || _nextDataOwner == long.MaxValue || current.Generation == long.MaxValue || current.ReadEligibilityEpoch == long.MaxValue)
{ PoisonRole(); throw new InvalidOperationException("Serving role generation exhausted."); }
_dataOwner = ++_nextDataOwner;
Volatile.Write(ref _primaryVerdict, new(current.Allowed, current.Generation + 1, "Unknown"));
Volatile.Write(ref _primaryVerdict, new(current.Allowed, current.Generation + 1, "Unknown", current.ReadEligibilityEpoch + 1));
return _dataOwner;
}
}
@@ -199,15 +210,15 @@ public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRole
if (owner == 0 || _dataOwner != owner) return;
var current = _primaryVerdict;
_dataOwner = 0;
if (current.Generation == long.MaxValue) { PoisonRole(); return; }
Volatile.Write(ref _primaryVerdict, new(false, current.Generation + 1, "Unknown"));
if (current.Generation == long.MaxValue || current.ReadEligibilityEpoch == long.MaxValue) { PoisonRole(); return; }
Volatile.Write(ref _primaryVerdict, new(false, current.Generation + 1, "Unknown", current.ReadEligibilityEpoch + 1));
}
}
private void PoisonRole()
{
_rolePoisoned = true; _dataOwner = 0;
Volatile.Write(ref _primaryVerdict, new(false, long.MaxValue, "Unknown"));
Volatile.Write(ref _primaryVerdict, new(false, long.MaxValue, "Unknown", long.MaxValue));
}
private void PublishPrimaryVerdict(bool shouldActAsPrimary, string? observedRole, long? owner = null)
@@ -219,11 +230,14 @@ public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRole
var role = observedRole ?? current.ServingRole;
if (current.Generation == 0 || current.Allowed != shouldActAsPrimary || current.ServingRole != role)
{
if (current.Generation == long.MaxValue) { PoisonRole(); return; }
Volatile.Write(ref _primaryVerdict, new(shouldActAsPrimary, current.Generation + 1, role));
var losesReadRole = IsReadRole(current.ServingRole) && !IsReadRole(role);
if (current.Generation == long.MaxValue || losesReadRole && current.ReadEligibilityEpoch == long.MaxValue) { PoisonRole(); return; }
Volatile.Write(ref _primaryVerdict, new(shouldActAsPrimary, current.Generation + 1, role,
current.ReadEligibilityEpoch + (losesReadRole ? 1 : 0)));
}
}
}
private static bool IsReadRole(string role) => role is "Primary" or "Secondary";
/// <inheritdoc/>
public void PublishHistorizationRole(bool shouldRecordHistorizedValues)
@@ -274,8 +274,14 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers
private void RemoveSubscriber(IActorRef subscriber)
{
if (!Detach(subscriber)) return;
if (_projectedSubscribers.TryGetValue(subscriber, out var projectedMailbox)) projectedMailbox.Clear();
Context.Unwatch(subscriber);
if (_projectedSubscribers.TryGetValue(subscriber, out var projectedMailbox))
{
// The subscriber can still hold values taken from this mailbox. Clear queued work,
// but keep watching until its termination disposes the retained delivered values
// and releases their shared quota. A later registration reuses the same mailbox.
projectedMailbox.Clear();
}
else Context.Unwatch(subscriber);
_log.Debug("DependencyMux: subscriber {Sub} removed", subscriber);
}