19b8163045
Resolves, authorizes (HistoryRead demand: mapping bit + local grant on the mapping scope, ACLs on or off) and pins each projected node, groups the batch per connection / details / issuing endpoint and forwards through IDataHistoryService. Remote cursors bind caller, mapping id+revision, connection route, projection generation, origin view and serving identity, and resend the ORIGINAL details; any change => BadContinuationPointInvalid with the origin token released. Shared per-request assembly budget (min mapping MaxHistoryAssemblyBytesPerRequest) => BadTooManyOperations for the remaining nodes. Releases coalesce per connection. Replaces the H2 refusal pin with the intended behaviour (granted => served, no grant => BadUserAccessDenied).
1700 lines
117 KiB
C#
1700 lines
117 KiB
C#
using Opc.Ua;
|
|
using System.Threading.Channels;
|
|
using DataReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest;
|
|
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;
|
|
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
|
|
/// <summary>Finite ownership limits for mapped access and its physical work.</summary>
|
|
public sealed record ProjectedDataAccessLimits(int MaxDemands, int MaxUnaryOperations, long MaxUnaryBytes, int MaxStreams);
|
|
|
|
/// <summary>Admission and asynchronous transport for projected SDK access.</summary>
|
|
public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
|
{
|
|
private readonly object _sync = new();
|
|
public TimeProvider Clock { get; }
|
|
internal Func<TimeSpan, TimeSpan>? RetryJitterForTests { get; set; }
|
|
internal Action? BeforeSuccessorAdoptionForTests { get; set; }
|
|
private readonly IFederatedProjectionCatalog _catalog;
|
|
private readonly IProjectedNodeLookup _nodes;
|
|
private readonly Func<string, string?> _connectionForMapping;
|
|
private readonly DataOperationPolicy _policy;
|
|
private readonly ProjectedDataAccessLimits _limits;
|
|
private readonly IGrpcDataAdapterConnectionSource _connections;
|
|
private readonly IProjectedValuePublisher _publisher;
|
|
private readonly IProjectedNamespacePageSink? _renewalSink;
|
|
private readonly Func<(bool Allowed, long Generation)> _localWriteRole;
|
|
private readonly Dictionary<SourceKey, SourceState> _sources = new();
|
|
private readonly Dictionary<(string Connection, DataRealm Realm, string LocalIdentifier), HashSet<SourceKey>> _sourcesByProjection = new();
|
|
private readonly Dictionary<SourceKey, int> _sourceSubscriptionOwners = new();
|
|
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, HashSet<SourceKey>> _sourcesByMapping = new(StringComparer.OrdinalIgnoreCase);
|
|
private readonly object _sourceRetirementGate = new();
|
|
private readonly LinkedList<SourceKey> _sourceSweep = new();
|
|
private readonly Dictionary<SourceKey, LinkedListNode<SourceKey>> _sourceSweepNodes = new();
|
|
private readonly Dictionary<string, long> _pendingSourceRetirement = new(StringComparer.OrdinalIgnoreCase);
|
|
private bool _sourceRetirementRunning;
|
|
internal Action? BeforeSourceRetirementForTests { get; set; }
|
|
internal int PendingSourceRetirementsForTests { get { lock (_sourceRetirementGate) return _pendingSourceRetirement.Count; } }
|
|
private int _unaryCount;
|
|
private long _unaryBytes;
|
|
private long _cachedSampleBytes;
|
|
internal long CachedSampleBytesForTests => Interlocked.Read(ref _cachedSampleBytes);
|
|
private readonly Dictionary<CohortKey, Cohort> _cohorts = new();
|
|
private readonly Dictionary<Demand, Cohort> _demandCohorts = new();
|
|
private readonly Dictionary<Demand, SourceKey> _demandSourceKeys = new();
|
|
private readonly HashSet<Demand> _demands = [];
|
|
private readonly Dictionary<(DataRealm Realm, string Identifier), int> _demandCounts = new();
|
|
private bool _disposed;
|
|
public ProjectedDataAccess(IFederatedProjectionCatalog catalog, IProjectedNodeLookup nodes,
|
|
IGrpcDataAdapterConnectionSource connections, Func<string, string?> connectionForMapping,
|
|
DataOperationPolicy policy, IProjectedValuePublisher publisher, TimeProvider clock, ProjectedDataAccessLimits limits,
|
|
Func<(bool Allowed, long Generation)>? localWriteRole = null, IProjectedNamespacePageSink? renewalSink = null)
|
|
{
|
|
_catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); _nodes = nodes ?? throw new ArgumentNullException(nameof(nodes));
|
|
_connections = connections ?? throw new ArgumentNullException(nameof(connections)); _connectionForMapping = connectionForMapping ?? throw new ArgumentNullException(nameof(connectionForMapping));
|
|
_policy = policy ?? throw new ArgumentNullException(nameof(policy)); _publisher = publisher ?? throw new ArgumentNullException(nameof(publisher)); Clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
|
_limits = limits ?? throw new ArgumentNullException(nameof(limits));
|
|
_localWriteRole = localWriteRole ?? (() => (true, 1));
|
|
_renewalSink = renewalSink;
|
|
if (limits.MaxDemands <= 0 || limits.MaxUnaryOperations <= 0 || limits.MaxUnaryBytes <= 0 || limits.MaxStreams <= 0) throw new ArgumentOutOfRangeException(nameof(limits));
|
|
_catalog.Invalidated += OnCatalogInvalidated;
|
|
}
|
|
private static bool MetadataMatches(DataMetadata left, DataMetadata right) =>
|
|
left.Dimensions.SequenceEqual(right.Dimensions) && (left with { Dimensions = right.Dimensions }) == right;
|
|
// Check the borrowed input without boxing or copying it. Array encoding temporarily owns
|
|
// two reference arrays, boxed elements and scalar wrappers as well as the eventual value;
|
|
// charge a conservative per-element bound before any of those allocations occur.
|
|
private static bool FitsWriteBudget(DataMetadata metadata, object? value, long maximumBytes)
|
|
{
|
|
const long scalarOverhead = 288;
|
|
if (maximumBytes < scalarOverhead) return false;
|
|
if (value is null) return true;
|
|
if (metadata.ValueKind == DataValueKind.Array)
|
|
{
|
|
if (metadata.ValueRank != 1 || metadata.Dimensions.Count != 1 || metadata.ArrayElementKind is not { } kind ||
|
|
!ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.IsSupportedArrayElementKind(kind) ||
|
|
value is not Array array || array.Rank != 1 || array.GetLowerBound(0) != 0 ||
|
|
(metadata.Dimensions[0] != 0 && metadata.Dimensions[0] != array.Length)) return false;
|
|
const long overhead = 512, perElement = 128;
|
|
if (maximumBytes < overhead || array.LongLength > (maximumBytes - overhead) / perElement) return false;
|
|
var used = overhead + perElement * array.LongLength;
|
|
if (kind == DataValueKind.String)
|
|
{
|
|
// Both typed string arrays and the object arrays accepted by EncodeValue are
|
|
// indexable without creating an iterator or boxing individual elements.
|
|
if (array is not object[] strings) return false;
|
|
for (var i = 0; i < strings.Length; i++)
|
|
{
|
|
if (strings[i] is not string text || text.Length > (maximumBytes - used) / 2) return false;
|
|
used += 2L * text.Length;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
if (metadata.ValueKind == DataValueKind.Bytes && value is byte[] bytes)
|
|
return bytes.LongLength <= maximumBytes - scalarOverhead;
|
|
if (metadata.ValueKind == DataValueKind.String && value is string textValue)
|
|
return textValue.Length <= (maximumBytes - scalarOverhead) / 2;
|
|
return true; // Exact scalar type checks remain in EncodeValue after admission.
|
|
}
|
|
private static ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue EncodeValue(DataMetadata metadata, object? value, long maximumBytes)
|
|
{
|
|
if (value is null) return ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.Null();
|
|
if (metadata.ValueKind == DataValueKind.Array)
|
|
{
|
|
if (metadata.ValueRank != 1 || metadata.Dimensions.Count != 1 || metadata.ArrayElementKind is not { } kind || value is not Array array || array.Rank != 1 ||
|
|
(metadata.Dimensions[0] != 0 && metadata.Dimensions[0] != array.Length)) throw new ArgumentException("Incompatible array shape.");
|
|
var values = new object[array.Length];
|
|
var used = 512L + 128L * array.LongLength;
|
|
for (var i = 0; i < values.Length; i++)
|
|
{
|
|
var item = array.GetValue(i) ?? throw new ArgumentException("Null array element.");
|
|
// The caller owns the array and can replace its elements after preflight.
|
|
// Recheck each captured string against the already-reserved allowance.
|
|
if (kind == DataValueKind.String)
|
|
{
|
|
if (item is not string text || text.Length > (maximumBytes - used) / 2)
|
|
throw new ArgumentException("Array exceeds write budget.");
|
|
used += 2L * text.Length;
|
|
}
|
|
values[i] = kind == DataValueKind.Timestamp && item is DateTime time ? new DateTimeOffset(time.ToUniversalTime()) : item;
|
|
}
|
|
return ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromArray(kind, values, [array.Length]);
|
|
}
|
|
if (metadata.ValueKind == DataValueKind.Bytes && value is byte[] bytes)
|
|
return ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromBytes(bytes);
|
|
if (metadata.ValueKind == DataValueKind.Timestamp && value is DateTime timestamp) value = new DateTimeOffset(timestamp.ToUniversalTime());
|
|
return ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromScalar(metadata.ValueKind, value);
|
|
}
|
|
internal static object? DecodeValue(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue value, DataMetadata metadata)
|
|
{
|
|
if (value.Kind == DataValueKind.Null) return null;
|
|
if (value.Kind != metadata.ValueKind) throw new ArgumentException("Value kind does not match metadata.");
|
|
if (value.Kind == DataValueKind.Bytes) return value.GetBytes().ToArray();
|
|
if (value.Kind != DataValueKind.Array) return value.GetScalar();
|
|
if (metadata.ValueRank != 1 || metadata.ArrayElementKind != value.ArrayElementKind || value.Dimensions is not { Count: 1 } dims ||
|
|
metadata.Dimensions.Count != 1 || (metadata.Dimensions[0] != 0 && metadata.Dimensions[0] != dims[0])) throw new ArgumentException("Incompatible array shape.");
|
|
var items = value.GetArray();
|
|
return value.ArrayElementKind switch
|
|
{
|
|
DataValueKind.Boolean => items.Cast<bool>().ToArray(), DataValueKind.Int8 => items.Cast<sbyte>().ToArray(),
|
|
DataValueKind.UInt8 => items.Cast<byte>().ToArray(), DataValueKind.Int16 => items.Cast<short>().ToArray(),
|
|
DataValueKind.UInt16 => items.Cast<ushort>().ToArray(), DataValueKind.Int32 => items.Cast<int>().ToArray(),
|
|
DataValueKind.UInt32 => items.Cast<uint>().ToArray(), DataValueKind.Int64 => items.Cast<long>().ToArray(),
|
|
DataValueKind.UInt64 => items.Cast<ulong>().ToArray(), DataValueKind.Float => items.Cast<float>().ToArray(),
|
|
DataValueKind.Double => items.Cast<double>().ToArray(), DataValueKind.String => items.Cast<string>().ToArray(),
|
|
DataValueKind.Timestamp => items.Cast<DateTimeOffset>().Select(x => x.UtcDateTime).ToArray(),
|
|
DataValueKind.Guid => items.Cast<Guid>().ToArray(), _ => throw new ArgumentException("Unsupported array element kind.")
|
|
};
|
|
}
|
|
public bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand)
|
|
{
|
|
demand = null;
|
|
if (caller is null || operation is not (DataOperations.Browse or DataOperations.Read or DataOperations.Write or DataOperations.Subscribe or DataOperations.HistoryRead)) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireInvalid); return false; }
|
|
try
|
|
{
|
|
if (!_nodes.TryResolve(nodeId, out var definition) || definition is null || !definition.AuthorityIsCurrent() ||
|
|
!_catalog.TryResolveProjected(definition.Realm, definition.LocalIdentifier, out var proof) || proof is null ||
|
|
proof.Generation != definition.ProjectionGeneration || !MetadataMatches(proof.Metadata, definition.Metadata) ||
|
|
((operation is DataOperations.Read or DataOperations.Subscribe) && proof.MaximumSampleAge <= TimeSpan.Zero) ||
|
|
// H3: history only on a node projected Historizing (mapping bit AND origin HistoryInfo), whatever the caller holds.
|
|
(operation == DataOperations.HistoryRead && (!definition.Historizing || !ProjectedHistoryAccess.Advertises(proof))) ||
|
|
proof.Metadata.View.MappingId is not { } mapping || proof.Lease.Serving.ServingGeneration <= 0 ||
|
|
_connectionForMapping(mapping) is not { Length: > 0 } connectionId) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireDefinition); return false; }
|
|
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
|
|
var localRole = operation == DataOperations.Write ? _localWriteRole() : (Allowed: true, Generation: 1L);
|
|
if (!localRole.Allowed || localRole.Generation <= 0) return false;
|
|
var op = Operation(operation);
|
|
if (!_policy.AuthorizeMapped(identity, op, proof.Metadata.View, proof.Lease.Serving, proof.Subject, proof.Resolver, proof.Lease) ||
|
|
!definition.Lifetime.TryPin(out var nodePin) || nodePin is null) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireAuthorization); return false; }
|
|
if (!_catalog.TryPinProjected(definition.Realm, definition.LocalIdentifier, out var pin) || pin is null) { nodePin.Dispose(); ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquirePin); return false; }
|
|
var candidate = new Demand(this, nodeId, definition, proof, identity, operation, pin, nodePin, connectionId, localRole.Generation, null);
|
|
lock (_sync)
|
|
{
|
|
if (_disposed || _demands.Count >= _limits.MaxDemands) { pin.Dispose(); nodePin.Dispose(); ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireCapacity); return false; }
|
|
_demands.Add(candidate);
|
|
var key = (candidate.Realm, candidate.LocalIdentifier);
|
|
_demandCounts.TryGetValue(key, out var count); _demandCounts[key] = checked(count + 1);
|
|
}
|
|
if (!candidate.IsValid) { candidate.Dispose(); ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireStale); return false; }
|
|
demand = candidate; ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireAccepted); return true;
|
|
}
|
|
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireException); return false; }
|
|
}
|
|
internal bool TryAcquireConfigured(NodeId nodeId, ConfiguredProjectionCapability capability, out IProjectedDemandLease? demand)
|
|
{
|
|
demand = null;
|
|
try
|
|
{
|
|
if (!_nodes.TryResolve(nodeId, out var definition) || definition is null || !definition.AuthorityIsCurrent() ||
|
|
!_catalog.TryResolveProjected(definition.Realm, definition.LocalIdentifier, out var proof) || proof is null ||
|
|
proof.Generation != definition.ProjectionGeneration || !MetadataMatches(proof.Metadata, definition.Metadata) || proof.MaximumSampleAge <= TimeSpan.Zero ||
|
|
proof.Metadata.View.MappingId is not { } mapping || proof.Lease.Serving.ServingGeneration <= 0 ||
|
|
(proof.Subject.AllowedOperations & DataOperations.Subscribe) == 0 || !capability.Matches(mapping, proof.Metadata.View, proof.Resolver.LocalAuthority) ||
|
|
_connectionForMapping(mapping) is not { Length: > 0 } connectionId || !definition.Lifetime.TryPin(out var nodePin) || nodePin is null) return false;
|
|
if (!_catalog.TryPinProjected(definition.Realm, definition.LocalIdentifier, out var pin) || pin is null) { nodePin.Dispose(); return false; }
|
|
var candidate = new Demand(this, nodeId, definition, proof, null, DataOperations.Subscribe, pin, nodePin, connectionId, 1, capability);
|
|
lock (_sync)
|
|
{
|
|
if (_disposed || _demands.Count >= _limits.MaxDemands) { pin.Dispose(); nodePin.Dispose(); return false; }
|
|
_demands.Add(candidate); var key = (candidate.Realm, candidate.LocalIdentifier);
|
|
_demandCounts.TryGetValue(key, out var count); _demandCounts[key] = checked(count + 1);
|
|
}
|
|
if (!candidate.IsValid) { candidate.Dispose(); return false; }
|
|
demand = candidate; return true;
|
|
}
|
|
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; }
|
|
}
|
|
internal async ValueTask DisposeConfiguredAsync(IProjectedDemandLease lease)
|
|
{
|
|
lease.Dispose();
|
|
if (lease is Demand demand) await demand.Completion.ConfigureAwait(false);
|
|
}
|
|
public bool HasLiveDemand(DataRealm realm, string localIdentifier) { lock (_sync) return _demandCounts.ContainsKey((realm, localIdentifier)); }
|
|
/// <summary>H3: what a HistoryRead demand is bound to — its mapping, revision, deployed connection and the origin's metadata.</summary>
|
|
internal bool TryDescribeHistoryDemand(IProjectedDemandLease lease, out ProjectedHistoryTarget? target)
|
|
{
|
|
target = null;
|
|
if (lease is not Demand { RequestedOperation: DataOperations.HistoryRead } demand || !demand.IsValid) return false;
|
|
var binding = demand.CurrentBinding;
|
|
if (binding.Proof.Metadata.View.MappingId is not { } mapping) return false;
|
|
target = new ProjectedHistoryTarget(mapping, binding.Proof.Metadata.View.MappingRevision, binding.ConnectionId,
|
|
binding.Proof.OriginMetadata, binding.Proof.Lease.Serving, binding.Proof.Generation);
|
|
return true;
|
|
}
|
|
private static OpcUaOperation Operation(DataOperations operation) => operation switch
|
|
{
|
|
DataOperations.Browse => OpcUaOperation.Browse,
|
|
DataOperations.Read => OpcUaOperation.Read,
|
|
DataOperations.Write => OpcUaOperation.WriteOperate,
|
|
DataOperations.Subscribe => OpcUaOperation.CreateMonitoredItems,
|
|
DataOperations.HistoryRead => OpcUaOperation.HistoryRead,
|
|
_ => throw new ArgumentOutOfRangeException(nameof(operation))
|
|
};
|
|
private sealed class Demand(ProjectedDataAccess owner, NodeId nodeId, ProjectedVariableDefinition definition,
|
|
ProjectedNodeProof proof, DataCallerIdentity? caller, DataOperations operation, IDisposable pin, IProjectedNodePin nodePin, string connectionId, long writeRoleGeneration, ConfiguredProjectionCapability? configured) : IProjectedDemandLease
|
|
{
|
|
internal sealed record Binding(ProjectedVariableDefinition Definition, ProjectedNodeProof Proof,
|
|
IDisposable Pin, IProjectedNodePin NodePin, string ConnectionId, bool RecoveryOnly = false);
|
|
private Binding _binding = new(definition, proof, pin, nodePin, connectionId);
|
|
private int _disposed;
|
|
private int _holds;
|
|
private bool _cleaned;
|
|
private readonly TaskCompletionSource _completed = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
private readonly CancellationTokenSource _stop = new();
|
|
internal Binding CurrentBinding => Volatile.Read(ref _binding);
|
|
internal ProjectedNodeProof Proof => CurrentBinding.Proof;
|
|
internal ProjectedVariableDefinition Definition => CurrentBinding.Definition;
|
|
internal NodeId NodeId => nodeId;
|
|
internal DataCallerIdentity? Caller => caller;
|
|
internal ConfiguredProjectionCapability? Configured => configured;
|
|
internal DataOperations RequestedOperation => operation;
|
|
internal bool Disposed => Volatile.Read(ref _disposed) != 0;
|
|
internal bool TryHold() { lock (owner._sync) { if (_disposed != 0) return false; _holds++; return true; } }
|
|
internal void ReleaseHold() { lock (owner._sync) { _holds--; if (_disposed != 0 && _holds == 0) Cleanup(); } }
|
|
private void Cleanup()
|
|
{
|
|
if (_cleaned) return;
|
|
_cleaned = true;
|
|
var binding = CurrentBinding;
|
|
binding.Pin.Dispose(); binding.NodePin.Dispose(); owner._demands.Remove(this);
|
|
var key = (Realm, LocalIdentifier); var count = owner._demandCounts[key];
|
|
if (count == 1) owner._demandCounts.Remove(key); else owner._demandCounts[key] = count - 1;
|
|
_completed.TrySetResult();
|
|
}
|
|
internal Task Completion => _completed.Task;
|
|
public TimeSpan MaximumSampleAge => CurrentBinding.Proof.MaximumSampleAge;
|
|
public DataView OriginView => CurrentBinding.Proof.OriginMetadata.View;
|
|
public DataRealm Realm => CurrentBinding.Definition.Realm;
|
|
public string LocalIdentifier => CurrentBinding.Definition.LocalIdentifier;
|
|
public long ProjectionGeneration => CurrentBinding.Proof.Generation;
|
|
public ServingIdentity Serving => CurrentBinding.Proof.Lease.Serving;
|
|
public CancellationToken CancellationToken => _stop.Token;
|
|
public bool IsValid
|
|
{
|
|
get
|
|
{
|
|
if (Volatile.Read(ref _disposed) != 0) return false;
|
|
try
|
|
{
|
|
var binding = CurrentBinding;
|
|
if (binding.RecoveryOnly) return false;
|
|
var currentDefinition = binding.Definition; var currentProof = binding.Proof;
|
|
var role = operation == DataOperations.Write ? owner._localWriteRole() : (Allowed: true, Generation: 1L);
|
|
return role.Allowed && role.Generation == writeRoleGeneration && role.Generation > 0 && binding.NodePin.IsValid && currentDefinition.AuthorityIsCurrent() && owner._nodes.TryResolve(nodeId, out var now) && now is not null && ReferenceEquals(now.Lifetime, currentDefinition.Lifetime) && now.ProjectionGeneration == currentDefinition.ProjectionGeneration && now.Metadata.View == currentDefinition.Metadata.View &&
|
|
owner._catalog.IsUsableProof(currentProof) &&
|
|
string.Equals(owner._connectionForMapping(currentProof.Metadata.View.MappingId!), binding.ConnectionId, StringComparison.OrdinalIgnoreCase) &&
|
|
(configured is not null ? configured.Matches(currentProof.Metadata.View.MappingId!, currentProof.Metadata.View, currentProof.Resolver.LocalAuthority) && (currentProof.Subject.AllowedOperations & DataOperations.Subscribe) != 0 :
|
|
caller is not null && owner._policy.AuthorizeMapped(caller, Operation(operation), currentProof.Metadata.View, currentProof.Lease.Serving, currentProof.Subject, currentProof.Resolver, currentProof.Lease)) &&
|
|
ReferenceEquals(CurrentBinding, binding) && Volatile.Read(ref _disposed) == 0;
|
|
}
|
|
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; }
|
|
}
|
|
}
|
|
internal bool TryPrepareBinding(Binding expected, out Binding? replacement)
|
|
{
|
|
replacement = null;
|
|
IProjectedNodePin? nextNodePin = null;
|
|
IDisposable? nextPin = null;
|
|
try
|
|
{
|
|
if (operation != DataOperations.Subscribe || Disposed || !ReferenceEquals(CurrentBinding, expected) ||
|
|
!owner._nodes.TryResolve(nodeId, out var nextDefinition) || nextDefinition is null || !nextDefinition.AuthorityIsCurrent() ||
|
|
!ReferenceEquals(nextDefinition.Lifetime, expected.Definition.Lifetime) ||
|
|
nextDefinition.Metadata.View != expected.Definition.Metadata.View ||
|
|
nextDefinition.Metadata.BrowseName != expected.Definition.Metadata.BrowseName ||
|
|
nextDefinition.Metadata.NodeKind != expected.Definition.Metadata.NodeKind ||
|
|
nextDefinition.Metadata.ValueKind != expected.Definition.Metadata.ValueKind ||
|
|
nextDefinition.Metadata.ValueRank != expected.Definition.Metadata.ValueRank ||
|
|
nextDefinition.Metadata.ArrayElementKind != expected.Definition.Metadata.ArrayElementKind ||
|
|
!nextDefinition.Metadata.Dimensions.SequenceEqual(expected.Definition.Metadata.Dimensions) ||
|
|
!owner._catalog.TryResolveProjected(nextDefinition.Realm, nextDefinition.LocalIdentifier, out var nextProof) || nextProof is null ||
|
|
nextProof.OriginMetadata.View != expected.Proof.OriginMetadata.View || nextProof.Generation != nextDefinition.ProjectionGeneration ||
|
|
!MetadataMatches(nextProof.Metadata, nextDefinition.Metadata) || nextProof.MaximumSampleAge <= TimeSpan.Zero ||
|
|
nextProof.Metadata.View.MappingId is not { } mapping ||
|
|
owner._connectionForMapping(mapping) is not { Length: > 0 } nextConnection ||
|
|
!string.Equals(nextConnection, expected.ConnectionId, StringComparison.OrdinalIgnoreCase) ||
|
|
(configured is not null ? !configured.Matches(mapping, nextProof.Metadata.View, nextProof.Resolver.LocalAuthority) ||
|
|
(nextProof.Subject.AllowedOperations & DataOperations.Subscribe) == 0 :
|
|
caller is null || !owner._policy.AuthorizeMapped(caller, OpcUaOperation.CreateMonitoredItems,
|
|
nextProof.Metadata.View, nextProof.Lease.Serving, nextProof.Subject, nextProof.Resolver, nextProof.Lease)) ||
|
|
!nextDefinition.Lifetime.TryPin(out nextNodePin) || nextNodePin is null) return false;
|
|
if (!owner._catalog.TryPinProjected(nextDefinition.Realm, nextDefinition.LocalIdentifier, out nextPin) || nextPin is null) return false;
|
|
if (!nextDefinition.AuthorityIsCurrent() || !owner._catalog.TryResolveProjected(nextDefinition.Realm, nextDefinition.LocalIdentifier, out var pinnedProof) ||
|
|
!ReferenceEquals(pinnedProof, nextProof)) return false;
|
|
replacement = new(nextDefinition, nextProof, nextPin, nextNodePin, nextConnection);
|
|
nextPin = null; nextNodePin = null;
|
|
return true;
|
|
}
|
|
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; }
|
|
finally { try { nextPin?.Dispose(); } finally { nextNodePin?.Dispose(); } }
|
|
}
|
|
// Called under the owner's lock after all external authorization/pinning work.
|
|
internal bool TryInstallBinding(Binding expected, Binding replacement)
|
|
{
|
|
if (Disposed || !ReferenceEquals(_binding, expected)) return false;
|
|
Volatile.Write(ref _binding, replacement);
|
|
return true;
|
|
}
|
|
public void Dispose()
|
|
{
|
|
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
|
|
_ = _stop.CancelAsync();
|
|
lock (owner._sync)
|
|
{
|
|
if (owner._demandCohorts.TryGetValue(this, out var cohort)) cohort.Remove(this);
|
|
if (_holds == 0) Cleanup();
|
|
}
|
|
}
|
|
}
|
|
private sealed record SourceKey(string Connection, DataView View, ServingIdentity Serving, long Generation, DataRealm Realm, string LocalIdentifier)
|
|
{
|
|
internal (string Connection, DataRealm Realm, string LocalIdentifier) Projection => (Connection, Realm, LocalIdentifier);
|
|
}
|
|
private interface ILeaseSampleProof { bool Matches(ProjectedNodeProof proof); }
|
|
private sealed class SourceState : IProjectedSamplePublicationProof
|
|
{
|
|
private readonly ProjectedDataAccess _owner; private readonly SourceKey _key; private readonly ProjectedValueRoute _route;
|
|
private ProjectedNodeProof? _proof; private ProjectedVariableDefinition? _definition; private IDisposable? _pin; private IProjectedNodePin? _nodePin;
|
|
private ProjectedNodeProof? _previousProof; private IDisposable? _previousPin; private IProjectedNodePin? _previousNodePin;
|
|
private WeakReference<ProjectedNodeProof>? _acceptedPredecessor;
|
|
internal readonly object Gate = new(); internal long LastVersion;
|
|
private ProjectedValueUpdate? _cachedSample;
|
|
private long _cachedVersion, _cachedBytes;
|
|
private long _attemptEra;
|
|
private long _authorityGeneration;
|
|
private int _activeAttempts;
|
|
// Read publications retain their route until authority invalidation or access disposal.
|
|
internal bool ReadOwned;
|
|
internal string MappingId { get; }
|
|
internal SourceState(ProjectedDataAccess owner, SourceKey key, ProjectedNodeProof proof, ProjectedVariableDefinition definition,
|
|
IDisposable pin, IProjectedNodePin nodePin, ProjectedValueRoute route)
|
|
{ _owner = owner; _key = key; _proof = proof; _definition = definition; _pin = pin; _nodePin = nodePin; _route = route; MappingId = proof.Metadata.View.MappingId!; }
|
|
internal ProjectedValueRoute Route => _route;
|
|
internal long BeginAttempt() { lock (Gate) { _activeAttempts = checked(_activeAttempts + 1); return _attemptEra; } }
|
|
internal void EndAttempt(long era)
|
|
{
|
|
lock (Gate)
|
|
{
|
|
if (era != _attemptEra || _activeAttempts <= 0) return;
|
|
if (--_activeAttempts == 0) _attemptEra = checked(_attemptEra + 1);
|
|
}
|
|
}
|
|
internal bool IsAttemptValid(long era) { lock (Gate) return _activeAttempts > 0 && _attemptEra == era && IsValid; }
|
|
public TimeProvider Clock => _owner.Clock;
|
|
public bool IsValid
|
|
{
|
|
get
|
|
{
|
|
lock (Gate)
|
|
{
|
|
ReleaseExpiredPredecessorLocked();
|
|
var proof = _proof; var definition = _definition;
|
|
try { return proof is not null && definition is not null && _nodePin is { IsValid: true } && definition.AuthorityIsCurrent() && proof.Lease.IsValid &&
|
|
_owner._catalog.IsUsableProof(proof) &&
|
|
string.Equals(_owner._connectionForMapping(proof.Metadata.View.MappingId!), _key.Connection, StringComparison.OrdinalIgnoreCase); }
|
|
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; }
|
|
}
|
|
}
|
|
}
|
|
private void ReleaseExpiredPredecessorLocked()
|
|
{
|
|
if (_previousProof is null || _previousProof.Lease.IsValid) return;
|
|
_previousProof = null;
|
|
_previousNodePin?.Dispose(); _previousNodePin = null;
|
|
_previousPin?.Dispose(); _previousPin = null;
|
|
}
|
|
internal void ReleaseExpiredPredecessor()
|
|
{
|
|
lock (Gate) ReleaseExpiredPredecessorLocked();
|
|
}
|
|
internal bool IsProofValid(ProjectedNodeProof captured)
|
|
{
|
|
try { return IsValid && captured.Lease.IsValid && _owner._catalog.IsUsableProof(captured); }
|
|
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; }
|
|
}
|
|
internal long AuthorityGenerationFor(ProjectedNodeProof captured)
|
|
{
|
|
lock (Gate)
|
|
{
|
|
if (ReferenceEquals(_proof, captured)) return _authorityGeneration;
|
|
if (ReferenceEquals(_previousProof, captured)) return _authorityGeneration - 1;
|
|
if (_proof is not null && _owner._catalog.IsUsableProof(_proof) &&
|
|
_owner._catalog.TryResolveProjected(captured.Metadata.View.Realm, captured.LocalIdentifier, out var current) &&
|
|
ReferenceEquals(current, captured) && _owner._catalog.IsUsableProof(captured)) return checked(_authorityGeneration + 1);
|
|
throw new InvalidOperationException("Sample proof does not belong to the current renewal handoff.");
|
|
}
|
|
}
|
|
internal bool CanDropExpiredPredecessor(IDataAuthorizationLease captured, long generation, long? era)
|
|
{
|
|
lock (Gate)
|
|
{
|
|
if (generation >= _authorityGeneration || era is { } value && (_activeAttempts <= 0 || value != _attemptEra) ||
|
|
!IsValid || captured is not BoundProjectionLease old || !old.ExpiredNaturally ||
|
|
_proof?.Lease is not BoundProjectionLease current || old.RouteIdentity is null ||
|
|
!ReferenceEquals(old.RouteIdentity, current.RouteIdentity) || old.BindingIdentity is null ||
|
|
!ReferenceEquals(old.BindingIdentity, current.BindingIdentity) || old.Target is null || old.Target != current.Target) return false;
|
|
return true;
|
|
}
|
|
}
|
|
internal bool TryPrepareSuccessor(Demand demand, out Demand.Binding? binding)
|
|
{
|
|
binding = null;
|
|
lock (Gate)
|
|
{
|
|
var captured = demand.Proof;
|
|
if (ReferenceEquals(_proof, captured)) return true;
|
|
// Another cadence can already own the successor while this one
|
|
// still has an independently live predecessor. Keep its original
|
|
// witness; a predecessor is never a request to adopt backwards.
|
|
if (ReferenceEquals(_previousProof, captured)) return IsProofValid(captured);
|
|
}
|
|
return demand.TryPrepareBinding(demand.CurrentBinding, out binding);
|
|
}
|
|
internal bool TryAdoptSuccessor(Demand.Binding binding, out bool consumed)
|
|
{
|
|
consumed = false;
|
|
lock (Gate)
|
|
{
|
|
if (_proof is null || _definition is null || !IsValid || !_owner._catalog.IsUsableProof(binding.Proof) ||
|
|
!binding.NodePin.IsValid || !binding.Definition.AuthorityIsCurrent()) return false;
|
|
if (ReferenceEquals(_proof, binding.Proof)) return true;
|
|
if (_previousProof is not null) return false;
|
|
_previousProof = _proof; _previousPin = _pin; _previousNodePin = _nodePin;
|
|
_acceptedPredecessor = new WeakReference<ProjectedNodeProof>(_proof);
|
|
_proof = binding.Proof; _definition = binding.Definition; _pin = binding.Pin; _nodePin = binding.NodePin;
|
|
_authorityGeneration = checked(_authorityGeneration + 1);
|
|
consumed = true;
|
|
return true;
|
|
}
|
|
}
|
|
internal bool TryPrepareRecoveryParking(Demand.Binding expected, out Demand.Binding? parked)
|
|
{
|
|
parked = null;
|
|
lock (Gate)
|
|
{
|
|
var proof = _proof; var definition = _definition;
|
|
if (proof is null || definition is null || _nodePin is not { IsValid: true } ||
|
|
_acceptedPredecessor is null || !_acceptedPredecessor.TryGetTarget(out var previous) ||
|
|
!ReferenceEquals(previous, expected.Proof) || ReferenceEquals(proof, previous) ||
|
|
!ReferenceEquals(definition.Lifetime, expected.Definition.Lifetime) ||
|
|
definition.Realm != expected.Definition.Realm || definition.LocalIdentifier != expected.Definition.LocalIdentifier ||
|
|
definition.Parent != expected.Definition.Parent || definition.Metadata.View != expected.Definition.Metadata.View ||
|
|
_owner._catalog is not RemoteNamespaceResolver resolver ||
|
|
!resolver.TryPinExpiredRecoveryPair(previous, proof, out var pin) || pin is null) return false;
|
|
if (!definition.Lifetime.TryPin(out var nodePin) || nodePin is null) { pin.Dispose(); return false; }
|
|
parked = new(definition, proof, pin, nodePin, expected.ConnectionId, RecoveryOnly: true);
|
|
return true;
|
|
}
|
|
}
|
|
private sealed class ReadProof(SourceState source, ProjectedNodeProof captured) : IProjectedSamplePublicationProof, ILeaseSampleProof, IObsoleteProjectedSample
|
|
{
|
|
private readonly WeakReference<ProjectedNodeProof> _proof = new(captured);
|
|
private readonly IDataAuthorizationLease _lease = captured.Lease;
|
|
private readonly long _generation = source.AuthorityGenerationFor(captured);
|
|
public TimeProvider Clock => source.Clock;
|
|
public object SourceIdentity => source;
|
|
public bool IsSourceValid => source.IsValid;
|
|
public bool IsValid => _lease.IsValid && _proof.TryGetTarget(out var proof) && source.IsProofValid(proof);
|
|
public bool Matches(ProjectedNodeProof proof) => _proof.TryGetTarget(out var target) && ReferenceEquals(target, proof);
|
|
public bool CanDropExpiredPredecessor => source.CanDropExpiredPredecessor(_lease, _generation, null);
|
|
public void Invalidate() => source.Invalidate();
|
|
}
|
|
internal IProjectedSamplePublicationProof CaptureReadProof(ProjectedNodeProof proof) => new ReadProof(this, proof);
|
|
private void ClearCachedLocked()
|
|
{
|
|
_cachedSample = null; _cachedVersion = 0;
|
|
if (_cachedBytes != 0) { Interlocked.Add(ref _owner._cachedSampleBytes, -_cachedBytes); _cachedBytes = 0; }
|
|
}
|
|
// Called under Gate only after the publication has been admitted. The cache owns a
|
|
// copy, and all SourceStates share one finite budget independent of transport frames.
|
|
internal void CacheLocked(ProjectedValueUpdate update, long version)
|
|
{
|
|
ClearCachedLocked();
|
|
if (!IsValid) return;
|
|
long bytes;
|
|
try { bytes = checked(512 + OwnedDataSample.Estimate(update.Snapshot.Value)); }
|
|
catch (Exception ex) when (ex is ArgumentException or OverflowException) { return; }
|
|
while (true)
|
|
{
|
|
var used = Interlocked.Read(ref _owner._cachedSampleBytes);
|
|
if (bytes > _owner._limits.MaxUnaryBytes - used) return;
|
|
if (Interlocked.CompareExchange(ref _owner._cachedSampleBytes, used + bytes, used) == used) break;
|
|
}
|
|
try
|
|
{
|
|
var owned = OwnedDataSample.CopyLegacy(update.Snapshot.Value);
|
|
_cachedSample = update with { Snapshot = update.Snapshot with { Value = owned } };
|
|
_cachedVersion = version; _cachedBytes = bytes;
|
|
}
|
|
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or OverflowException) { }
|
|
finally { if (_cachedBytes != bytes) Interlocked.Add(ref _owner._cachedSampleBytes, -bytes); }
|
|
}
|
|
internal bool TryRecoveryLocked(Demand demand, bool successorOnly = false)
|
|
{
|
|
var sample = _cachedSample;
|
|
if (sample is null || _cachedVersion != LastVersion || !sample.SourceProof.IsValid || !demand.IsValid || !IsValid ||
|
|
successorOnly && (sample.SourceProof is not ILeaseSampleProof witness || !witness.Matches(demand.Proof))) return false;
|
|
try
|
|
{
|
|
var elapsed = _owner.Clock.GetElapsedTime(sample.ReceivedTimestamp, _owner.Clock.GetTimestamp());
|
|
if (!sample.OriginAgeBounds.Advance(elapsed).IsFresh(demand.MaximumSampleAge)) return false;
|
|
// Preserve the original receipt and bounds; downstream advances the same
|
|
// evidence again at observation, rather than resetting source age.
|
|
return _owner._publisher.TryPublish([sample with { IsCompleteSnapshot = true, MaximumSampleAge = demand.MaximumSampleAge }]);
|
|
}
|
|
catch (Exception ex) when (ex is ArgumentException or OverflowException) { return false; }
|
|
}
|
|
internal bool HasFreshCachedLocked(Demand demand)
|
|
{
|
|
var sample = _cachedSample;
|
|
if (sample is null || _cachedVersion != LastVersion || !sample.SourceProof.IsValid || !demand.IsValid || !IsValid) return false;
|
|
try
|
|
{
|
|
return sample.OriginAgeBounds.Advance(_owner.Clock.GetElapsedTime(sample.ReceivedTimestamp,
|
|
_owner.Clock.GetTimestamp())).IsFresh(demand.MaximumSampleAge);
|
|
}
|
|
catch (Exception ex) when (ex is ArgumentException or OverflowException) { return false; }
|
|
}
|
|
public void Invalidate()
|
|
{
|
|
IDisposable? pin; IProjectedNodePin? nodePin; IDisposable? previousPin; IProjectedNodePin? previousNodePin;
|
|
lock (Gate)
|
|
{
|
|
if (_proof is null) return;
|
|
_proof = null; _definition = null; pin = _pin; _pin = null; nodePin = _nodePin; _nodePin = null;
|
|
previousPin = _previousPin; _previousPin = null; previousNodePin = _previousNodePin; _previousNodePin = null; _previousProof = null; _acceptedPredecessor = null; ClearCachedLocked();
|
|
}
|
|
try { _owner._publisher.Retire(_route); }
|
|
catch (Exception) { }
|
|
finally { nodePin?.Dispose(); pin?.Dispose(); previousNodePin?.Dispose(); previousPin?.Dispose(); }
|
|
}
|
|
}
|
|
private bool RemoveSourceLocked(SourceKey key, out SourceState? source)
|
|
{
|
|
if (!_sources.Remove(key, out source)) return false;
|
|
var projectionKeys = _sourcesByProjection[key.Projection];
|
|
projectionKeys.Remove(key);
|
|
if (projectionKeys.Count == 0) _sourcesByProjection.Remove(key.Projection);
|
|
if (_sourceSweepNodes.Remove(key, out var sweep)) _sourceSweep.Remove(sweep);
|
|
if (_sourcesByMapping.TryGetValue(source.MappingId, out var keys))
|
|
{
|
|
keys.Remove(key);
|
|
if (keys.Count == 0)
|
|
{
|
|
_sourcesByMapping.TryRemove(source.MappingId, out _);
|
|
lock (_sourceRetirementGate) _pendingSourceRetirement.Remove(source.MappingId);
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
private void AddSourceOwnerLocked(SourceKey key)
|
|
{
|
|
_sourceSubscriptionOwners.TryGetValue(key, out var count);
|
|
_sourceSubscriptionOwners[key] = checked(count + 1);
|
|
}
|
|
private SourceState? ReleaseSourceOwnerLocked(SourceKey key)
|
|
{
|
|
var count = _sourceSubscriptionOwners[key];
|
|
if (count > 1) { _sourceSubscriptionOwners[key] = count - 1; return null; }
|
|
_sourceSubscriptionOwners.Remove(key);
|
|
if (_sources.TryGetValue(key, out var source) && !source.ReadOwned && RemoveSourceLocked(key, out var retired)) return retired;
|
|
return null;
|
|
}
|
|
private void OnCatalogInvalidated(string mapping, long generation)
|
|
{
|
|
// Mapping activation may hold its own lock. Never acquire the data-access
|
|
// lock on this callback; publication is allowed to consult mapping authority.
|
|
lock (_sourceRetirementGate)
|
|
{
|
|
if (Volatile.Read(ref _disposed) || !_sourcesByMapping.ContainsKey(mapping)) return;
|
|
_pendingSourceRetirement[mapping] = generation;
|
|
if (_sourceRetirementRunning) return;
|
|
_sourceRetirementRunning = true; _ = Task.Run(RetireInvalidatedSources);
|
|
}
|
|
}
|
|
private void RetireInvalidatedSources()
|
|
{
|
|
BeforeSourceRetirementForTests?.Invoke();
|
|
while (true)
|
|
{
|
|
SourceState[] retired;
|
|
KeyValuePair<string, long> item;
|
|
lock (_sourceRetirementGate)
|
|
{
|
|
if (_pendingSourceRetirement.Count == 0) { _sourceRetirementRunning = false; return; }
|
|
item = _pendingSourceRetirement.First(); _pendingSourceRetirement.Remove(item.Key);
|
|
}
|
|
lock (_sync)
|
|
{
|
|
var list = new List<SourceState>();
|
|
if (_sourcesByMapping.TryGetValue(item.Key, out var keys))
|
|
foreach (var key in keys.Where(key => key.Generation != item.Value).ToArray())
|
|
if (RemoveSourceLocked(key, out var state) && state is not null) list.Add(state);
|
|
retired = list.ToArray();
|
|
}
|
|
foreach (var source in retired) source.Invalidate();
|
|
}
|
|
}
|
|
private SourceState? GetSource(Demand demand, string connection)
|
|
{
|
|
var proof = demand.Proof; var key = new SourceKey(connection.ToUpperInvariant(), demand.OriginView, demand.Serving, demand.ProjectionGeneration, demand.Realm, demand.LocalIdentifier);
|
|
List<SourceState>? retired = null;
|
|
try
|
|
{
|
|
lock (_sync)
|
|
{
|
|
if (_disposed || !ReferenceEquals(demand.Proof, proof) || !demand.IsValid) return null;
|
|
retired = RemoveInvalidReadSourcesLocked(key);
|
|
return GetSourceLocked(demand, connection, proof, key);
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
if (retired is not null)
|
|
foreach (var previous in retired) previous.Invalidate();
|
|
}
|
|
}
|
|
|
|
private List<SourceState>? RemoveInvalidReadSourcesLocked(SourceKey key)
|
|
{
|
|
if (!_sourcesByProjection.TryGetValue(key.Projection, out var keys) ||
|
|
(keys.Count == 1 && keys.Contains(key))) return null;
|
|
|
|
// A read-owned source may outlive its last subscription. An invalid route
|
|
// at this exact projection must release its own pin before the new route
|
|
// tries to renew, including when this attachment reuses the new source.
|
|
List<SourceState>? retired = null;
|
|
foreach (var previous in keys.ToArray())
|
|
{
|
|
if (previous == key || _sourceSubscriptionOwners.ContainsKey(previous)) continue;
|
|
var source = _sources[previous];
|
|
if (!source.ReadOwned || source.IsValid) continue;
|
|
RemoveSourceLocked(previous, out _);
|
|
(retired ??= []).Add(source);
|
|
}
|
|
return retired;
|
|
}
|
|
|
|
private SourceState? GetSourceLocked(Demand demand, string connection, ProjectedNodeProof proof, SourceKey key)
|
|
{
|
|
if (_sources.TryGetValue(key, out var existing))
|
|
{
|
|
if (existing.IsValid)
|
|
{
|
|
if (demand.RequestedOperation == DataOperations.Read) existing.ReadOwned = true;
|
|
return existing;
|
|
}
|
|
RemoveSourceLocked(key, out _); existing.Invalidate();
|
|
}
|
|
if (_sources.Count >= _limits.MaxDemands)
|
|
{
|
|
var count = Math.Min(16, _sourceSweep.Count);
|
|
for (var i = 0; i < count && _sourceSweep.First is { } first; i++)
|
|
{
|
|
var sourceKey = first.Value; var state = _sources[sourceKey];
|
|
if (!state.IsValid) { RemoveSourceLocked(sourceKey, out _); state.Invalidate(); }
|
|
else { _sourceSweep.RemoveFirst(); _sourceSweep.AddLast(first); }
|
|
}
|
|
}
|
|
if (_sources.Count >= _limits.MaxDemands || !demand.Definition.Lifetime.TryPin(out var nodePin) || nodePin is null) return null;
|
|
if (!_catalog.TryPinProjected(demand.Realm, demand.LocalIdentifier, out var pin) || pin is null) { nodePin.Dispose(); return null; }
|
|
var route = new ProjectedValueRoute("grpc-data:" + connection, ProjectedDataIds.DependencyReference(demand.Realm, demand.LocalIdentifier),
|
|
demand.Realm, demand.LocalIdentifier, demand.ProjectionGeneration, demand.Serving, Guid.NewGuid());
|
|
var source = new SourceState(this, key, proof, demand.Definition, pin, nodePin, route)
|
|
{ ReadOwned = demand.RequestedOperation == DataOperations.Read };
|
|
if (!source.IsValid || !_publisher.TryBind(route)) { source.Invalidate(); return null; }
|
|
_sources.Add(key, source); _sourceSweepNodes.Add(key, _sourceSweep.AddLast(key));
|
|
if (!_sourcesByProjection.TryGetValue(key.Projection, out var projectionKeys))
|
|
_sourcesByProjection.Add(key.Projection, projectionKeys = []);
|
|
projectionKeys.Add(key);
|
|
if (!_sourcesByMapping.TryGetValue(source.MappingId, out var keys)) _sourcesByMapping[source.MappingId] = keys = new();
|
|
keys.Add(key);
|
|
// Attach before the final authority check: invalidation either observes this
|
|
// bucket or is detected here, so no source can strand its physical pins.
|
|
if (!source.IsValid) { RemoveSourceLocked(key, out _); source.Invalidate(); return null; }
|
|
return source;
|
|
}
|
|
public bool ScheduleRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp)
|
|
{
|
|
if (demand is not Demand item || item.RequestedOperation != DataOperations.Read || !item.IsValid || budget is null) return false;
|
|
try { budget.Validate(); } catch (ArgumentException) { return false; }
|
|
var elapsed = Clock.GetElapsedTime(requestStartedTimestamp, Clock.GetTimestamp());
|
|
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) return false;
|
|
// The request's byte budget is an upper bound. Narrow it to this adapter's
|
|
// configured physical limit before admission and before remote dispatch.
|
|
var boundedBudget = budget with { MaxBytes = Math.Min(budget.MaxBytes, _limits.MaxUnaryBytes) };
|
|
lock (_sync)
|
|
{
|
|
if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || boundedBudget.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !item.TryHold()) return false;
|
|
_unaryCount++; _unaryBytes += boundedBudget.MaxBytes;
|
|
}
|
|
_ = Task.Run(() => ReadCoreAsync(item, boundedBudget, requestStartedTimestamp)); return true;
|
|
}
|
|
private async Task ReadCoreAsync(Demand demand, DataBudget budget, long started)
|
|
{
|
|
IGrpcDataAdapterConnectionLease? connection = null;
|
|
try
|
|
{
|
|
var original = demand.CurrentBinding;
|
|
var originalProof = original.Proof;
|
|
var remaining = budget.Timeout - Clock.GetElapsedTime(started, Clock.GetTimestamp());
|
|
if (remaining <= TimeSpan.Zero || !demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original)) return;
|
|
var connectionId = _connectionForMapping(originalProof.Metadata.View.MappingId!);
|
|
if (string.IsNullOrWhiteSpace(connectionId)) return;
|
|
using var timeout = new CancellationTokenSource(remaining, Clock);
|
|
using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, demand.CancellationToken);
|
|
connection = await _connections.AcquireAsync(connectionId, linked.Token).ConfigureAwait(false);
|
|
if (connection is null || !ReferenceEquals(connection.Connection.Clock, Clock) || connection.CancellationToken.IsCancellationRequested ||
|
|
!demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original)) return;
|
|
using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken);
|
|
var readStarted = Clock.GetTimestamp();
|
|
var result = await connection.Connection.ReadAsync(new DataReadRequest([new ReadItem("0", originalProof.OriginMetadata.View, null)], budget with { Timeout = remaining }), route.Token).ConfigureAwait(false);
|
|
try
|
|
{
|
|
if (result.Count != 1 || result[0].CorrelationId != "0" || result[0].Status != DataItemStatus.Good || result[0].Readiness != DataReadiness.Ready ||
|
|
result[0].Sample is not { } sample || sample.Serving != originalProof.Lease.Serving || sample.Version <= 0 || !demand.IsValid ||
|
|
!ReferenceEquals(demand.CurrentBinding, original) || route.IsCancellationRequested) return;
|
|
result[0].AgeBounds.Validate();
|
|
// An unstamped implementation is conservatively anchored before the read call.
|
|
var received = result[0].FreshnessObservedTimestamp ?? readStarted;
|
|
if (!result[0].AgeBounds.Advance(Clock.GetElapsedTime(received, Clock.GetTimestamp())).IsFresh(originalProof.MaximumSampleAge)) return;
|
|
if (sample.Value.EstimatedRetainedBytes > budget.MaxBytes) return;
|
|
var payload = DecodeValue(sample.Value, originalProof.OriginMetadata);
|
|
var snapshot = new DataValueSnapshot(payload, sample.StatusCode, sample.SourceTimestampUtc?.UtcDateTime, sample.ServerTimestampUtc?.UtcDateTime);
|
|
var source = GetSource(demand, connectionId);
|
|
if (source is null) return;
|
|
lock (source.Gate)
|
|
{
|
|
if (!demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original) || !source.IsValid || sample.Version <= source.LastVersion || route.IsCancellationRequested ||
|
|
!result[0].AgeBounds.Advance(Clock.GetElapsedTime(received, Clock.GetTimestamp())).IsFresh(originalProof.MaximumSampleAge)) return;
|
|
var update = new ProjectedValueUpdate(source.Route, snapshot, result[0].AgeBounds, received, source.CaptureReadProof(originalProof), true, originalProof.MaximumSampleAge, sample.Version);
|
|
if (_publisher.TryPublish([update])) { source.LastVersion = sample.Version; source.CacheLocked(update, sample.Version); }
|
|
else if (!ProjectedEvidenceRetirement.CanDrop(update.SourceProof)) source.Invalidate();
|
|
}
|
|
}
|
|
finally { foreach (var item in result) item.Dispose(); }
|
|
}
|
|
catch (Exception) { }
|
|
finally
|
|
{
|
|
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
|
|
finally { demand.Dispose(); demand.ReleaseHold(); lock (_sync) { _unaryCount--; _unaryBytes -= budget.MaxBytes; } }
|
|
}
|
|
}
|
|
public async Task<DataWriteOutcome> WriteAsync(IProjectedDemandLease demand, object? value, DataBudget budget,
|
|
long requestStartedTimestamp, CancellationToken cancellationToken)
|
|
{
|
|
var rejected = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, StatusCodes.BadNotConnected.Code, null);
|
|
var unknown = new DataWriteOutcome(DataWriteState.OutcomeUnknown, StatusCodes.BadTimeout.Code, null);
|
|
if (demand is not Demand item || item.RequestedOperation != DataOperations.Write || !item.IsValid || budget is null || cancellationToken.IsCancellationRequested) return rejected;
|
|
try
|
|
{
|
|
budget.Validate();
|
|
// The SDK's request cap is an upper bound, not a minimum required reservation.
|
|
// Use the adapter's configured ceiling for payload checks and physical work.
|
|
budget = budget with { MaxBytes = Math.Min(budget.MaxBytes, _limits.MaxUnaryBytes) };
|
|
if (!FitsWriteBudget(item.Proof.OriginMetadata, value, budget.MaxBytes)) return rejected;
|
|
}
|
|
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or OverflowException) { return rejected; }
|
|
var elapsed = Clock.GetElapsedTime(requestStartedTimestamp, Clock.GetTimestamp());
|
|
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) return rejected;
|
|
lock (_sync)
|
|
{
|
|
if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || budget.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !item.TryHold()) return rejected;
|
|
_unaryCount++; _unaryBytes += budget.MaxBytes;
|
|
}
|
|
ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue? owned = null;
|
|
Task<DataWriteOutcome> task;
|
|
var transferred = false;
|
|
try
|
|
{
|
|
if (cancellationToken.IsCancellationRequested || !item.IsValid) return rejected;
|
|
owned = EncodeValue(item.Proof.OriginMetadata, value, budget.MaxBytes);
|
|
elapsed = Clock.GetElapsedTime(requestStartedTimestamp, Clock.GetTimestamp());
|
|
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout || owned.EstimatedRetainedBytes > budget.MaxBytes ||
|
|
cancellationToken.IsCancellationRequested || !item.IsValid) return rejected;
|
|
var reservedValue = owned;
|
|
task = Task.Run(() => WriteCoreAsync(item, reservedValue, budget, requestStartedTimestamp, cancellationToken));
|
|
transferred = true;
|
|
}
|
|
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or OverflowException or TaskSchedulerException)
|
|
{ return rejected; }
|
|
finally
|
|
{
|
|
if (!transferred)
|
|
{
|
|
try { owned?.Dispose(); }
|
|
finally
|
|
{
|
|
try { item.ReleaseHold(); }
|
|
finally { lock (_sync) { _unaryCount--; _unaryBytes -= budget.MaxBytes; } }
|
|
}
|
|
}
|
|
}
|
|
try { return await task.WaitAsync(budget.Timeout - elapsed, Clock, cancellationToken).ConfigureAwait(false); }
|
|
catch (OperationCanceledException) { return unknown; }
|
|
catch (TimeoutException) { return unknown; }
|
|
}
|
|
private async Task<DataWriteOutcome> WriteCoreAsync(Demand demand, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue value, DataBudget budget, long started, CancellationToken callerStop)
|
|
{
|
|
var rejected = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, StatusCodes.BadNotConnected.Code, null);
|
|
var unknown = new DataWriteOutcome(DataWriteState.OutcomeUnknown, StatusCodes.BadTimeout.Code, null);
|
|
IGrpcDataAdapterConnectionLease? connection = null; var dispatched = false;
|
|
try
|
|
{
|
|
var remaining = budget.Timeout - Clock.GetElapsedTime(started, Clock.GetTimestamp());
|
|
if (remaining <= TimeSpan.Zero || !demand.IsValid || callerStop.IsCancellationRequested) return rejected;
|
|
var connectionId = _connectionForMapping(demand.Proof.Metadata.View.MappingId!);
|
|
if (string.IsNullOrWhiteSpace(connectionId)) return rejected;
|
|
using var timeout = new CancellationTokenSource(remaining, Clock);
|
|
using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, callerStop, demand.CancellationToken);
|
|
connection = await _connections.AcquireAsync(connectionId, linked.Token).ConfigureAwait(false);
|
|
if (connection is null || !ReferenceEquals(connection.Connection.Clock, Clock) || connection.CancellationToken.IsCancellationRequested || !demand.IsValid) return rejected;
|
|
remaining = budget.Timeout - Clock.GetElapsedTime(started, Clock.GetTimestamp());
|
|
if (remaining <= TimeSpan.Zero || linked.IsCancellationRequested) return rejected;
|
|
using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken);
|
|
var correlation = Guid.NewGuid().ToString("N");
|
|
var item = new WriteItem(correlation, Guid.NewGuid().ToString("N"), demand.OriginView, value,
|
|
demand.Proof.OriginMetadata.CatalogRevision, demand.Serving.Incarnation, remaining, demand.Serving.ServingGeneration);
|
|
dispatched = true;
|
|
var results = await connection.Connection.WriteAsync(new WriteBatch([item], budget with { Timeout = remaining }), route.Token).ConfigureAwait(false);
|
|
if (results.Count != 1 || results[0].CorrelationId != correlation) return unknown;
|
|
return results[0].Outcome;
|
|
}
|
|
catch (Exception) { return dispatched ? unknown : rejected; }
|
|
finally
|
|
{
|
|
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
|
|
finally
|
|
{
|
|
try { value.Dispose(); }
|
|
finally
|
|
{
|
|
try { demand.ReleaseHold(); }
|
|
finally { lock (_sync) { _unaryCount--; _unaryBytes -= budget.MaxBytes; } }
|
|
}
|
|
}
|
|
}
|
|
}
|
|
private sealed record CohortKey(string Connection, ServingIdentity Serving, TimeSpan Interval);
|
|
public bool StartSubscription(IProjectedDemandLease demand, TimeSpan publishingInterval)
|
|
{
|
|
if (demand is not Demand item || item.RequestedOperation != DataOperations.Subscribe || publishingInterval <= TimeSpan.Zero || !item.IsValid) return false;
|
|
var connection = _connectionForMapping(item.Proof.Metadata.View.MappingId!);
|
|
if (string.IsNullOrWhiteSpace(connection)) return false;
|
|
var key = new CohortKey(connection.ToUpperInvariant(), item.Serving, publishingInterval);
|
|
lock (_sync)
|
|
{
|
|
if (_disposed || _demandCohorts.ContainsKey(item)) return false;
|
|
var created = false;
|
|
if (!_cohorts.TryGetValue(key, out var cohort))
|
|
{
|
|
if (_cohorts.Count >= _limits.MaxStreams) return false;
|
|
cohort = new Cohort(this, key, connection); _cohorts.Add(key, cohort); created = true;
|
|
}
|
|
if (cohort.Closing || !item.TryHold()) { if (created) _cohorts.Remove(key); return false; }
|
|
_demandCohorts.Add(item, cohort);
|
|
if (!cohort.Add(item)) { _demandCohorts.Remove(item); item.ReleaseHold(); if (created) _cohorts.Remove(key); return false; }
|
|
var sourceKey = new SourceKey(key.Connection, item.OriginView, key.Serving, item.ProjectionGeneration, item.Realm, item.LocalIdentifier);
|
|
AddSourceOwnerLocked(sourceKey); _demandSourceKeys.Add(item, sourceKey);
|
|
cohort.Start(); return true;
|
|
}
|
|
}
|
|
private sealed class Cohort
|
|
{
|
|
private sealed class AttemptProof(SourceState source, ProjectedNodeProof captured) : IProjectedSamplePublicationProof, ILeaseSampleProof, IObsoleteProjectedSample
|
|
{
|
|
private readonly WeakReference<ProjectedNodeProof> _proof = new(captured);
|
|
private readonly IDataAuthorizationLease _lease = captured.Lease;
|
|
private readonly long _generation = source.AuthorityGenerationFor(captured);
|
|
private int _active = 1;
|
|
private int _counted;
|
|
private long _era = -1;
|
|
internal SourceState Source => source;
|
|
public bool Matches(ProjectedNodeProof proof) => _proof.TryGetTarget(out var target) && ReferenceEquals(target, proof);
|
|
internal bool LeaseValid => _lease.IsValid;
|
|
public bool IsValid { get { var era = Interlocked.Read(ref _era); return era >= 0 && _lease.IsValid && _proof.TryGetTarget(out var proof) && source.IsAttemptValid(era) && source.IsProofValid(proof); } }
|
|
public bool IsSourceValid { get { var era = Interlocked.Read(ref _era); return era >= 0 && source.IsAttemptValid(era); } }
|
|
public bool CanDropExpiredPredecessor { get { var era = Interlocked.Read(ref _era); return era >= 0 && source.CanDropExpiredPredecessor(_lease, _generation, era); } }
|
|
public object SourceIdentity => source;
|
|
public TimeProvider Clock => source.Clock;
|
|
public void Invalidate() { Close(); source.Invalidate(); }
|
|
internal bool Promote()
|
|
{
|
|
if (IsValid) return true;
|
|
if (Volatile.Read(ref _active) == 0 || Interlocked.Read(ref _era) >= 0) return false;
|
|
var era = source.BeginAttempt();
|
|
Interlocked.Exchange(ref _era, era);
|
|
Interlocked.Exchange(ref _counted, 1);
|
|
if (Volatile.Read(ref _active) == 0) { ReleaseCoverage(); return false; }
|
|
return IsValid;
|
|
}
|
|
private void ReleaseCoverage()
|
|
{
|
|
if (Interlocked.Exchange(ref _counted, 0) != 0) source.EndAttempt(Interlocked.Read(ref _era));
|
|
}
|
|
internal void Close() { if (Interlocked.Exchange(ref _active, 0) != 0) ReleaseCoverage(); }
|
|
}
|
|
private abstract record Event;
|
|
private sealed record AddEvent(Demand Demand) : Event;
|
|
private sealed record RemoveEvent(Demand Demand) : Event;
|
|
private sealed record RefreshEvent(Demand Demand) : Event;
|
|
private sealed record FrameEvent(DataSubscriptionFrame Frame, long Bytes, long ReceivedTimestamp) : Event;
|
|
private sealed record FreshnessEvent : Event;
|
|
private sealed record RenewalEvent : Event;
|
|
private sealed record RenewedEvent(Demand Demand, Demand.Binding Expected, bool Success) : Event;
|
|
private sealed record EndEvent : Event;
|
|
private sealed class Registration(Demand demand, string id)
|
|
{
|
|
internal readonly Demand Demand = demand; internal readonly string Id = id;
|
|
internal DataItemHandle? Handle; internal bool Removed, Rebinding, Recovery, AwaitingCurrent, NeedsChallenge, HasBaseline, Renewal;
|
|
internal IDataAuthorizationLease? RenewalPredecessor;
|
|
}
|
|
private readonly ProjectedDataAccess _owner;
|
|
private CohortKey _key;
|
|
private readonly string _connectionId;
|
|
private readonly Channel<Event> _events;
|
|
private readonly CancellationTokenSource _stop = new();
|
|
private readonly Dictionary<Demand, Registration> _registrations = new();
|
|
private readonly Dictionary<string, Registration> _byId = new(StringComparer.Ordinal);
|
|
private readonly Dictionary<DataItemHandle, Registration> _byHandle = new();
|
|
private readonly Dictionary<string, Registration> _removing = new(StringComparer.Ordinal);
|
|
// Guarded by the owner's lock; at most one queued or active refresh per demand.
|
|
private readonly HashSet<Demand> _refreshRequests = [];
|
|
private string _id = string.Empty;
|
|
private long _epoch;
|
|
private int _started, _closing, _healthyBaseline;
|
|
private long _sequence;
|
|
private long _frameBytes;
|
|
private int _freshnessQueued;
|
|
private int _servingMismatch;
|
|
internal bool Closing => Volatile.Read(ref _closing) != 0;
|
|
internal Cohort(ProjectedDataAccess owner, CohortKey key, string connectionId)
|
|
{
|
|
_owner = owner; _key = key; _connectionId = connectionId;
|
|
_events = Channel.CreateBounded<Event>(new BoundedChannelOptions(Math.Clamp(owner._limits.MaxDemands * 2, 4, 128))
|
|
{ SingleReader = true, FullMode = BoundedChannelFullMode.Wait });
|
|
}
|
|
internal bool Add(Demand demand) => _events.Writer.TryWrite(new AddEvent(demand));
|
|
internal void Remove(Demand demand) { if (!_events.Writer.TryWrite(new RemoveEvent(demand))) Stop(); }
|
|
internal void Start() { if (Interlocked.Exchange(ref _started, 1) == 0) _ = Task.Run(RunAsync); }
|
|
internal void Stop() { if (Interlocked.Exchange(ref _closing, 1) == 0) _ = _stop.CancelAsync(); }
|
|
internal bool Refresh(Demand demand)
|
|
{
|
|
if (Closing) return false;
|
|
if (!_refreshRequests.Add(demand)) return true;
|
|
if (_events.Writer.TryWrite(new RefreshEvent(demand))) return true;
|
|
_refreshRequests.Remove(demand); return false;
|
|
}
|
|
private void FinishRefresh(Demand demand)
|
|
{
|
|
lock (_owner._sync) _refreshRequests.Remove(demand);
|
|
}
|
|
private async Task PumpAsync(IDataSubscription stream, CancellationToken attemptStop)
|
|
{
|
|
try
|
|
{
|
|
await foreach (var frame in stream.ReadAllAsync(attemptStop).ConfigureAwait(false))
|
|
{
|
|
var receivedTimestamp = _owner.Clock.GetTimestamp();
|
|
var bytes = frame is DataSubscriptionValues values ? checked(512L + values.Items.Sum(x =>
|
|
checked(x.Sample.Value.EstimatedRetainedBytes + 2L * (x.FreshnessChallengeId?.Length ?? 0)))) : 512L;
|
|
if (bytes > _owner._limits.MaxUnaryBytes || Interlocked.Add(ref _frameBytes, bytes) > _owner._limits.MaxUnaryBytes)
|
|
{ Interlocked.Add(ref _frameBytes, -bytes); (frame as IDisposable)?.Dispose(); break; }
|
|
try { await _events.Writer.WriteAsync(new FrameEvent(frame, bytes, receivedTimestamp), attemptStop).ConfigureAwait(false); }
|
|
catch { Interlocked.Add(ref _frameBytes, -bytes); (frame as IDisposable)?.Dispose(); throw; }
|
|
}
|
|
}
|
|
catch (Exception) { }
|
|
finally { try { await _events.Writer.WriteAsync(new EndEvent(), attemptStop).ConfigureAwait(false); } catch (OperationCanceledException) { } }
|
|
}
|
|
private DataSubscriptionItem Item(Registration registration) => new(registration.Id, registration.Demand.OriginView,
|
|
new DataSubscriptionSettings(_key.Interval, _key.Interval, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataChangeTrigger.StatusValueTimestamp, null));
|
|
private async Task RunAsync()
|
|
{
|
|
try
|
|
{
|
|
var delay = TimeSpan.FromMilliseconds(100);
|
|
while (!_stop.IsCancellationRequested)
|
|
{
|
|
ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.Attempt);
|
|
Interlocked.Exchange(ref _healthyBaseline, 0);
|
|
await RunAttemptAsync().ConfigureAwait(false);
|
|
if (_stop.IsCancellationRequested) break;
|
|
if (Volatile.Read(ref _healthyBaseline) != 0) delay = TimeSpan.FromMilliseconds(100);
|
|
try { await RenewInvalidDemandsAsync().ConfigureAwait(false); }
|
|
catch (Exception ex) when (ex is not OutOfMemoryException && !_stop.IsCancellationRequested)
|
|
{ /* A failed renewal is retried under the same bounded cohort. */ }
|
|
bool any;
|
|
lock (_owner._sync)
|
|
{
|
|
any = _owner._demandCohorts.Any(x => ReferenceEquals(x.Value, this));
|
|
if (!any) Stop(); // Close under admission lock before a new item can join.
|
|
}
|
|
if (!any) break;
|
|
// Each physical retry samples independently; keep the delay bounded
|
|
// even at the exponential-backoff ceiling.
|
|
var minimum = delay.TotalMilliseconds * 0.8;
|
|
var maximum = Math.Min(5000, delay.TotalMilliseconds * 1.2);
|
|
var randomized = _owner.RetryJitterForTests?.Invoke(delay) ??
|
|
TimeSpan.FromMilliseconds(minimum + Random.Shared.NextDouble() * (maximum - minimum));
|
|
var retryDelay = TimeSpan.FromMilliseconds(Math.Clamp(randomized.TotalMilliseconds, 1, 5000));
|
|
await Task.Delay(retryDelay, _stop.Token).ConfigureAwait(false);
|
|
delay = TimeSpan.FromMilliseconds(Math.Min(5000, delay.TotalMilliseconds * 2));
|
|
}
|
|
}
|
|
catch (OperationCanceledException) when (_stop.IsCancellationRequested) { }
|
|
finally
|
|
{
|
|
Stop();
|
|
Demand[] owned; var retired = new List<SourceState>();
|
|
lock (_owner._sync)
|
|
{
|
|
owned = _owner._demandCohorts.Where(x => ReferenceEquals(x.Value, this)).Select(x => x.Key).ToArray();
|
|
if (_owner._cohorts.TryGetValue(_key, out var current) && ReferenceEquals(current, this)) _owner._cohorts.Remove(_key);
|
|
foreach (var item in owned)
|
|
{
|
|
_owner._demandCohorts.Remove(item);
|
|
if (_owner._demandSourceKeys.Remove(item, out var sourceKey) &&
|
|
_owner.ReleaseSourceOwnerLocked(sourceKey) is { } state) retired.Add(state);
|
|
}
|
|
}
|
|
foreach (var source in retired) source.Invalidate();
|
|
foreach (var item in owned) { item.Dispose(); item.ReleaseHold(); }
|
|
_stop.Dispose();
|
|
}
|
|
}
|
|
private async Task RenewInvalidDemandsAsync()
|
|
{
|
|
Demand[] owned;
|
|
(Demand Demand, SourceState Source)[] sources;
|
|
lock (_owner._sync)
|
|
{
|
|
owned = _owner._demandCohorts.Where(x => ReferenceEquals(x.Value, this)).Select(x => x.Key).ToArray();
|
|
sources = owned.Select(demand => (Demand: demand, Source: _owner._demandSourceKeys.TryGetValue(demand, out var key) &&
|
|
_owner._sources.TryGetValue(key, out var source) ? source : null))
|
|
.Where(item => item.Source is not null).Select(item => (item.Demand, item.Source!)).ToArray();
|
|
}
|
|
// A stopped stream need not evaluate source validity again. Drop only the
|
|
// source-owned expired predecessor before trying to reserve its successor.
|
|
foreach (var source in sources.Select(item => item.Source).Distinct()) source.ReleaseExpiredPredecessor();
|
|
// A different cadence may still own the predecessor's pin. Park only that
|
|
// expired demand on the already charged successor; this grants no authority.
|
|
foreach (var item in sources)
|
|
{
|
|
var expected = item.Demand.CurrentBinding;
|
|
if (expected.RecoveryOnly || !item.Source.TryPrepareRecoveryParking(expected, out var parked) || parked is null) continue;
|
|
bool installed;
|
|
lock (_owner._sync)
|
|
installed = !_owner._disposed && _owner._demandCohorts.TryGetValue(item.Demand, out var current) &&
|
|
ReferenceEquals(current, this) && _owner._demandSourceKeys.TryGetValue(item.Demand, out var key) &&
|
|
_owner._sources.TryGetValue(key, out var currentSource) && ReferenceEquals(currentSource, item.Source) &&
|
|
item.Demand.TryInstallBinding(expected, parked);
|
|
var release = installed ? expected : parked;
|
|
release.NodePin.Dispose(); release.Pin.Dispose();
|
|
}
|
|
var requireNewServing = Interlocked.Exchange(ref _servingMismatch, 0) != 0;
|
|
var prepared = new List<(Demand Demand, Demand.Binding Old, Demand.Binding Next)>();
|
|
try
|
|
{
|
|
foreach (var demand in owned)
|
|
{
|
|
if (_stop.IsCancellationRequested) return;
|
|
if (demand.Disposed) { ReleaseDemand(demand); continue; }
|
|
if (demand.IsValid && !requireNewServing) continue;
|
|
var old = demand.CurrentBinding;
|
|
using var demandStop = CancellationTokenSource.CreateLinkedTokenSource(_stop.Token, demand.CancellationToken);
|
|
var attempted = false;
|
|
if (requireNewServing && _owner._catalog is RemoteNamespaceResolver refresh && _owner._renewalSink is { } refreshSink)
|
|
{
|
|
attempted = true;
|
|
await RenewOwnedAsync(demand, old, refresh, refreshSink, demandStop.Token).ConfigureAwait(false);
|
|
}
|
|
if (!demand.TryPrepareBinding(old, out var replacement) || replacement is null)
|
|
{
|
|
if (attempted || _owner._catalog is not RemoteNamespaceResolver resolver || _owner._renewalSink is null) continue;
|
|
if (!await RenewOwnedAsync(demand, old, resolver, _owner._renewalSink, demandStop.Token).ConfigureAwait(false) ||
|
|
!demand.TryPrepareBinding(old, out replacement) || replacement is null) continue;
|
|
}
|
|
if (requireNewServing && replacement.Proof.Lease.Serving == _key.Serving)
|
|
{ replacement.NodePin.Dispose(); replacement.Pin.Dispose(); continue; }
|
|
prepared.Add((demand, old, replacement));
|
|
}
|
|
var installed = new HashSet<Demand>();
|
|
var retired = new List<SourceState>();
|
|
var groups = prepared.GroupBy(item => new CohortKey(_key.Connection, item.Next.Proof.Lease.Serving, _key.Interval))
|
|
.Select(group => (Key: group.Key, Items: group.ToArray(),
|
|
Members: group.Select(item => item.Demand).ToHashSet(System.Collections.Generic.ReferenceEqualityComparer.Instance))).ToArray();
|
|
lock (_owner._sync)
|
|
{
|
|
var survivors = _owner._demandCohorts.Where(x => ReferenceEquals(x.Value, this) && !x.Key.Disposed).Select(x => x.Key).ToArray();
|
|
foreach (var group in groups)
|
|
{
|
|
if (_owner._disposed) break;
|
|
var targetKey = group.Key;
|
|
Cohort? target;
|
|
var created = false;
|
|
if (targetKey == _key) target = this;
|
|
else if (!_owner._cohorts.TryGetValue(targetKey, out target))
|
|
{
|
|
if (_owner._cohorts.Count < _owner._limits.MaxStreams)
|
|
{
|
|
target = new Cohort(_owner, targetKey, _connectionId);
|
|
_owner._cohorts.Add(targetKey, target); created = true;
|
|
}
|
|
else
|
|
{
|
|
// A drained cohort can change serving in-place when every one
|
|
// of its surviving demands has the same verified new target.
|
|
if (survivors.Length == 0 || survivors.Any(d => !group.Members.Contains(d))) continue;
|
|
_owner._cohorts.Remove(_key); _key = targetKey; _owner._cohorts.Add(_key, this); target = this;
|
|
}
|
|
}
|
|
if (target is null || target.Closing) continue;
|
|
var moved = 0;
|
|
foreach (var item in group.Items)
|
|
{
|
|
if (!_owner._demandCohorts.TryGetValue(item.Demand, out var current) || !ReferenceEquals(current, this) ||
|
|
item.Demand.Disposed || target != this && !target.Add(item.Demand) || !item.Demand.TryInstallBinding(item.Old, item.Next)) continue;
|
|
var oldKey = _owner._demandSourceKeys[item.Demand];
|
|
var nextKey = new SourceKey(targetKey.Connection, item.Next.Proof.OriginMetadata.View, targetKey.Serving,
|
|
item.Next.Proof.Generation, item.Next.Definition.Realm, item.Next.Definition.LocalIdentifier);
|
|
if (oldKey != nextKey)
|
|
{
|
|
_owner.AddSourceOwnerLocked(nextKey);
|
|
if (_owner.ReleaseSourceOwnerLocked(oldKey) is { } source) retired.Add(source);
|
|
_owner._demandSourceKeys[item.Demand] = nextKey;
|
|
}
|
|
_owner._demandCohorts[item.Demand] = target;
|
|
installed.Add(item.Demand); moved++;
|
|
}
|
|
if (created && moved == 0) _owner._cohorts.Remove(targetKey);
|
|
else if (target != this && moved != 0) target.Start();
|
|
}
|
|
}
|
|
foreach (var source in retired) source.Invalidate();
|
|
foreach (var item in prepared)
|
|
{
|
|
var dispose = installed.Contains(item.Demand) ? item.Old : item.Next;
|
|
dispose.NodePin.Dispose(); dispose.Pin.Dispose();
|
|
}
|
|
prepared.Clear();
|
|
}
|
|
finally { foreach (var item in prepared) { item.Next.NodePin.Dispose(); item.Next.Pin.Dispose(); } }
|
|
}
|
|
private async Task<bool> RenewOwnedAsync(Demand demand, Demand.Binding old, RemoteNamespaceResolver resolver,
|
|
IProjectedNamespacePageSink sink, CancellationToken cancellationToken, bool overlap = false)
|
|
{
|
|
var timeout = TimeSpan.FromSeconds(5);
|
|
if (overlap && old.Proof.Lease is BoundProjectionLease authority)
|
|
{
|
|
var remaining = authority.Remaining;
|
|
if (remaining <= TimeSpan.FromMilliseconds(1)) return false;
|
|
timeout = TimeSpan.FromTicks(Math.Min(timeout.Ticks, remaining.Ticks - remaining.Ticks / 4));
|
|
}
|
|
var budget = new DataBudget(timeout, 1, _owner._limits.MaxUnaryBytes);
|
|
lock (_owner._sync)
|
|
{
|
|
if (_owner._disposed || demand.Disposed || _owner._unaryCount >= _owner._limits.MaxUnaryOperations ||
|
|
budget.MaxBytes > _owner._limits.MaxUnaryBytes - _owner._unaryBytes) return false;
|
|
_owner._unaryCount++; _owner._unaryBytes += budget.MaxBytes;
|
|
}
|
|
try
|
|
{
|
|
return await resolver.RenewExactAsync(old.Proof, old.Definition, demand.NodeId, demand.Caller,
|
|
demand.Configured, sink, budget, () => !demand.Disposed && (!overlap ||
|
|
ReferenceEquals(demand.CurrentBinding, old) && demand.IsValid), cancellationToken, overlap).ConfigureAwait(false);
|
|
}
|
|
finally { lock (_owner._sync) { _owner._unaryCount--; _owner._unaryBytes -= budget.MaxBytes; } }
|
|
}
|
|
private async Task RunAttemptAsync()
|
|
{
|
|
IGrpcDataAdapterConnectionLease? connection = null; IDataSubscription? stream = null; Task? pump = null;
|
|
CancellationTokenSource? route = null;
|
|
ITimer? freshnessTimer = null, renewalTimer = null;
|
|
using var attemptStop = CancellationTokenSource.CreateLinkedTokenSource(_stop.Token);
|
|
var evidence = new Dictionary<SourceState, List<AttemptProof>>();
|
|
var demandSources = new Dictionary<Demand, SourceState>();
|
|
var renewals = new Dictionary<Demand, Task>();
|
|
var renewalQueued = 0;
|
|
var pendingCommands = new Dictionary<string, Registration>();
|
|
var snapshotQueue = new Queue<HashSet<Registration>>();
|
|
HashSet<Registration>? snapshotOwners = null;
|
|
void EnqueueSnapshot(HashSet<Registration> owners)
|
|
{
|
|
if ((long)snapshotQueue.Count >= (long)_owner._limits.MaxDemands + 1)
|
|
throw new InvalidDataException("Too many pending snapshot boundaries.");
|
|
snapshotQueue.Enqueue(owners);
|
|
}
|
|
_id = Guid.NewGuid().ToString("N"); _epoch = checked(_epoch + 1); _sequence = 0;
|
|
_registrations.Clear(); _byId.Clear(); _byHandle.Clear(); _removing.Clear();
|
|
Interlocked.Exchange(ref _freshnessQueued, 0);
|
|
string? challengeId = null;
|
|
long challengeSequence = 0;
|
|
var opened = false; var inSnapshot = false; long snapshotBytes = 0;
|
|
var pending = new List<(Registration Registration, ProjectedValueUpdate Update, long Version)>();
|
|
AttemptProof EvidenceFor(SourceState source, ProjectedNodeProof proof)
|
|
{
|
|
if (!evidence.TryGetValue(source, out var witnesses)) evidence[source] = witnesses = [];
|
|
foreach (var expired in witnesses.Where(witness => !witness.LeaseValid).ToArray()) { expired.Close(); witnesses.Remove(expired); }
|
|
var existing = witnesses.Find(witness => witness.Matches(proof));
|
|
if (existing is not null) return existing;
|
|
if (witnesses.Count >= 2) throw new InvalidDataException("Too many overlapping authority witnesses.");
|
|
var created = new AttemptProof(source, proof); witnesses.Add(created); return created;
|
|
}
|
|
void TrackSource(Demand demand)
|
|
{
|
|
var source = _owner.GetSource(demand, _connectionId) ?? throw new InvalidDataException("Source unavailable.");
|
|
EvidenceFor(source, demand.Proof);
|
|
demandSources[demand] = source;
|
|
}
|
|
void UntrackSource(Demand demand, bool preserve = false)
|
|
{
|
|
if (!demandSources.Remove(demand, out var source)) return;
|
|
if (_registrations.Values.Any(other => other.HasBaseline && demandSources.TryGetValue(other.Demand, out var retained) && ReferenceEquals(retained, source))) return;
|
|
if (preserve) return;
|
|
if (evidence.Remove(source, out var witnesses)) foreach (var proof in witnesses) proof.Close();
|
|
}
|
|
async Task ChallengeAsync(CancellationToken token)
|
|
{
|
|
if (challengeId is not null || stream is not IDataSubscriptionFreshnessSupport { SupportsFreshnessChallenges: true } support) return;
|
|
var chosen = _registrations.Values.Where(x => x.NeedsChallenge && !x.Removed && x.Demand.IsValid && x.Handle is not null)
|
|
.Take(Math.Min(128, support.FreshnessMaxItems)).ToArray();
|
|
if (chosen.Length == 0) return;
|
|
foreach (var item in chosen) item.NeedsChallenge = false;
|
|
challengeId = "freshness-" + checked(++challengeSequence).ToString(System.Globalization.CultureInfo.InvariantCulture);
|
|
await stream.SendAsync(new ChallengeSubscriptionFreshness(_id, _epoch, challengeId, TimeSpan.FromSeconds(5),
|
|
chosen.Select(x => x.Handle!).ToArray()), token).ConfigureAwait(false);
|
|
}
|
|
async Task RenewAsync(Demand demand, Demand.Binding expected, CancellationToken token)
|
|
{
|
|
var success = false;
|
|
try
|
|
{
|
|
if (_owner._catalog.TryResolveProjected(expected.Definition.Realm, expected.Definition.LocalIdentifier, out var current) &&
|
|
current is not null && !ReferenceEquals(current, expected.Proof) && _owner._catalog.IsUsableProof(expected.Proof) &&
|
|
_owner._nodes.TryResolve(demand.NodeId, out var definition) && definition is not null &&
|
|
RemoteNamespaceResolver.DefinitionOwnsProof(definition, current)) success = true;
|
|
else if (_owner._catalog is RemoteNamespaceResolver resolver && _owner._renewalSink is { } sink)
|
|
{
|
|
using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, demand.CancellationToken);
|
|
success = await RenewOwnedAsync(demand, expected, resolver, sink, linked.Token, overlap: true).ConfigureAwait(false);
|
|
}
|
|
await _events.Writer.WriteAsync(new RenewedEvent(demand, expected, success), token).ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex) when (ex is not OutOfMemoryException) { }
|
|
}
|
|
try
|
|
{
|
|
Demand[] initial;
|
|
lock (_owner._sync) initial = _owner._demandCohorts.Where(x => ReferenceEquals(x.Value, this)).Select(x => x.Key).ToArray();
|
|
foreach (var demand in initial) if (demand.Disposed) ReleaseDemand(demand);
|
|
initial = initial.Where(demand => !demand.Disposed && demand.IsValid && demand.Serving == _key.Serving).ToArray();
|
|
if (initial.Length == 0) return;
|
|
connection = await _owner._connections.AcquireAsync(_connectionId, attemptStop.Token).ConfigureAwait(false);
|
|
if (connection is null || !ReferenceEquals(connection.Connection.Clock, _owner.Clock) || connection.CancellationToken.IsCancellationRequested) return;
|
|
route = CancellationTokenSource.CreateLinkedTokenSource(attemptStop.Token, connection.CancellationToken);
|
|
stream = await connection.Connection.SubscribeAsync(route.Token).ConfigureAwait(false);
|
|
if (stream is not IDataSubscriptionProvenance provenance || provenance.Serving != _key.Serving)
|
|
{ Interlocked.Exchange(ref _servingMismatch, 1); return; }
|
|
freshnessTimer = _owner.Clock.CreateTimer(_ =>
|
|
{
|
|
if (Interlocked.Exchange(ref _freshnessQueued, 1) == 0 && !_events.Writer.TryWrite(new FreshnessEvent()))
|
|
Interlocked.Exchange(ref _freshnessQueued, 0);
|
|
}, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5));
|
|
var minimumLease = initial.Select(d => (d.Proof.Lease as BoundProjectionLease)?.UsableDuration ?? TimeSpan.FromSeconds(1)).Min();
|
|
var renewalInterval = TimeSpan.FromTicks(Math.Max(TimeSpan.TicksPerMillisecond,
|
|
Math.Min(TimeSpan.FromMilliseconds(250).Ticks, minimumLease.Ticks / 4)));
|
|
renewalTimer = _owner.Clock.CreateTimer(_ =>
|
|
{
|
|
if (Interlocked.Exchange(ref renewalQueued, 1) == 0 && !_events.Writer.TryWrite(new RenewalEvent()))
|
|
Interlocked.Exchange(ref renewalQueued, 0);
|
|
}, null, renewalInterval, renewalInterval);
|
|
pump = PumpAsync(stream, route.Token);
|
|
foreach (var demand in initial)
|
|
{
|
|
if (demand.Disposed) { ReleaseDemand(demand); continue; }
|
|
if (!demand.IsValid) continue;
|
|
TrackSource(demand);
|
|
var registration = new Registration(demand, Guid.NewGuid().ToString("N")) { Recovery = _epoch > 1 };
|
|
_registrations[demand] = registration; _byId[registration.Id] = registration;
|
|
var commandId = Guid.NewGuid().ToString("N"); pendingCommands.Add(commandId, registration);
|
|
DataSubscriptionCommand command = !opened
|
|
? new OpenSubscription(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [Item(registration)], false, TimeSpan.FromMinutes(1), new(TimeSpan.FromSeconds(5), 1, _owner._limits.MaxUnaryBytes))
|
|
: new AddSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [Item(registration)]);
|
|
await stream.SendAsync(command, route.Token).ConfigureAwait(false); opened = true;
|
|
}
|
|
// A temporarily unavailable proof must not leave an unopened stream parked
|
|
// forever. Retry the bounded attempt after backoff so renewal can make it usable.
|
|
if (!opened) return;
|
|
await foreach (var message in _events.Reader.ReadAllAsync(route.Token).ConfigureAwait(false))
|
|
{
|
|
if (message is AddEvent add)
|
|
{
|
|
lock (_owner._sync)
|
|
if (!_owner._demandCohorts.TryGetValue(add.Demand, out var owner) || !ReferenceEquals(owner, this)) continue;
|
|
if (_registrations.ContainsKey(add.Demand)) continue;
|
|
if (add.Demand.Disposed) { ReleaseDemand(add.Demand); continue; }
|
|
if (!add.Demand.IsValid) continue;
|
|
TrackSource(add.Demand);
|
|
var registration = new Registration(add.Demand, Guid.NewGuid().ToString("N"));
|
|
_registrations[add.Demand] = registration; _byId[registration.Id] = registration;
|
|
if (renewalTimer is not null && add.Demand.Proof.Lease is BoundProjectionLease addedLease)
|
|
{
|
|
var nextInterval = TimeSpan.FromTicks(Math.Max(TimeSpan.TicksPerMillisecond,
|
|
Math.Min(TimeSpan.FromMilliseconds(250).Ticks, addedLease.UsableDuration.Ticks / 4)));
|
|
if (nextInterval < renewalInterval) { renewalInterval = nextInterval; renewalTimer.Change(nextInterval, nextInterval); }
|
|
}
|
|
var commandId = Guid.NewGuid().ToString("N"); pendingCommands.Add(commandId, registration);
|
|
DataSubscriptionCommand command = !opened
|
|
? new OpenSubscription(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [Item(registration)], false, TimeSpan.FromMinutes(1), new(TimeSpan.FromSeconds(5), 1, _owner._limits.MaxUnaryBytes))
|
|
: new AddSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [Item(registration)]);
|
|
await stream.SendAsync(command, route.Token).ConfigureAwait(false); opened = true;
|
|
}
|
|
else if (message is RefreshEvent refresh)
|
|
{
|
|
if (!_registrations.TryGetValue(refresh.Demand, out var registration) || !refresh.Demand.IsValid)
|
|
{ FinishRefresh(refresh.Demand); continue; }
|
|
if (registration.Removed)
|
|
{
|
|
// A renewal (or an earlier refresh) already owns the remove/add
|
|
// barrier and its complete baseline satisfies this request.
|
|
if (!registration.Rebinding) FinishRefresh(refresh.Demand);
|
|
continue;
|
|
}
|
|
registration.Removed = true; registration.Rebinding = true;
|
|
if (registration.Handle is { } handle)
|
|
{
|
|
var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration;
|
|
await stream.SendAsync(new RemoveSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [handle]), route.Token).ConfigureAwait(false);
|
|
}
|
|
}
|
|
else if (message is RemoveEvent remove)
|
|
{
|
|
FinishRefresh(remove.Demand);
|
|
if (_registrations.TryGetValue(remove.Demand, out var registration))
|
|
{
|
|
registration.Rebinding = false;
|
|
if (!registration.Removed)
|
|
{
|
|
registration.Removed = true;
|
|
if (registration.Handle is { } handle)
|
|
{
|
|
var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration;
|
|
await stream.SendAsync(new RemoveSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [handle]), route.Token).ConfigureAwait(false);
|
|
}
|
|
}
|
|
}
|
|
else ReleaseDemand(remove.Demand);
|
|
if (_registrations.Values.All(x => x.Removed && !x.Rebinding)) break;
|
|
}
|
|
else if (message is FreshnessEvent)
|
|
{
|
|
Interlocked.Exchange(ref _freshnessQueued, 0);
|
|
if (_registrations.Values.Any(x => !x.Removed && !x.Demand.IsValid)) break;
|
|
foreach (var registration in _registrations.Values) registration.NeedsChallenge = true;
|
|
await ChallengeAsync(route.Token).ConfigureAwait(false);
|
|
}
|
|
else if (message is RenewalEvent)
|
|
{
|
|
Interlocked.Exchange(ref renewalQueued, 0);
|
|
if (_registrations.Values.Any(registration => registration.Renewal &&
|
|
registration.RenewalPredecessor is not { IsValid: true }))
|
|
throw new InvalidDataException("The predecessor expired before its successor baseline completed.");
|
|
foreach (var witnesses in evidence.Values)
|
|
foreach (var expired in witnesses.Where(proof => !proof.LeaseValid).ToArray()) { expired.Close(); witnesses.Remove(expired); }
|
|
foreach (var registration in _registrations.Values.ToArray())
|
|
{
|
|
var demand = registration.Demand;
|
|
if (registration.Removed || renewals.ContainsKey(demand) || !demand.IsValid ||
|
|
demand.Proof.Lease is not BoundProjectionLease lease || lease.RouteIdentity is null ||
|
|
lease.Remaining <= TimeSpan.Zero || lease.Remaining > lease.UsableDuration / 2) continue;
|
|
var expected = demand.CurrentBinding;
|
|
renewals[demand] = RenewAsync(demand, expected, route.Token);
|
|
}
|
|
}
|
|
else if (message is RenewedEvent renewed)
|
|
{
|
|
renewals.Remove(renewed.Demand);
|
|
if (!renewed.Success || !_registrations.TryGetValue(renewed.Demand, out var registration) || registration.Removed ||
|
|
!ReferenceEquals(renewed.Demand.CurrentBinding, renewed.Expected) || !renewed.Demand.IsValid ||
|
|
!renewed.Demand.TryPrepareBinding(renewed.Expected, out var replacement) || replacement is null) continue;
|
|
if (!RemoteNamespaceResolver.DefinitionOwnsProof(replacement.Definition, replacement.Proof))
|
|
{ replacement.NodePin.Dispose(); replacement.Pin.Dispose(); continue; }
|
|
var installed = false;
|
|
lock (_owner._sync)
|
|
{
|
|
if (!_owner._disposed && _owner._demandCohorts.TryGetValue(renewed.Demand, out var owner) && ReferenceEquals(owner, this))
|
|
installed = renewed.Demand.TryInstallBinding(renewed.Expected, replacement);
|
|
}
|
|
if (!installed) { replacement.NodePin.Dispose(); replacement.Pin.Dispose(); continue; }
|
|
renewed.Expected.NodePin.Dispose(); renewed.Expected.Pin.Dispose();
|
|
registration.Removed = true; registration.Rebinding = true; registration.Renewal = true;
|
|
registration.RenewalPredecessor = renewed.Expected.Proof.Lease;
|
|
if (registration.Handle is { } handle)
|
|
{
|
|
var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration;
|
|
await stream.SendAsync(new RemoveSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [handle]), route.Token).ConfigureAwait(false);
|
|
}
|
|
}
|
|
else if (message is EndEvent) break;
|
|
else if (message is FrameEvent delivered)
|
|
{
|
|
var frame = delivered.Frame;
|
|
ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.Frame);
|
|
try
|
|
{
|
|
if (frame.SubscriptionId != _id || frame.StreamEpoch != _epoch || frame.Sequence <= _sequence) break;
|
|
_sequence = frame.Sequence;
|
|
if (frame is DataSubscriptionAck ack)
|
|
{
|
|
if (ack.CommandId == challengeId)
|
|
{
|
|
challengeId = null;
|
|
if (ack.Items.Any(x => x.Status != DataItemStatus.Good || x.Handle is null ||
|
|
!_byHandle.TryGetValue(x.Handle, out var current) || current.Id != x.ClientItemId)) throw new InvalidDataException("Invalid freshness acknowledgement.");
|
|
EnqueueSnapshot(ack.Items.Select(x => _byHandle[x.Handle!]).ToHashSet());
|
|
await ChallengeAsync(route.Token).ConfigureAwait(false);
|
|
}
|
|
else if (_removing.Remove(ack.CommandId, out var removed))
|
|
{
|
|
if (ack.Items.Count != 1 || ack.Items[0].Status != DataItemStatus.Good || ack.Items[0].Handle != removed.Handle || ack.Items[0].ClientItemId != removed.Id) throw new InvalidDataException("Invalid removal acknowledgement.");
|
|
_registrations.Remove(removed.Demand); _byId.Remove(removed.Id);
|
|
if (removed.Handle is { } removedHandle) _byHandle.Remove(removedHandle);
|
|
UntrackSource(removed.Demand, removed.Renewal);
|
|
if (removed.Rebinding && removed.Demand.IsValid)
|
|
{
|
|
var replacement = new Registration(removed.Demand, Guid.NewGuid().ToString("N"))
|
|
{ Recovery = true, Renewal = removed.Renewal, RenewalPredecessor = removed.RenewalPredecessor };
|
|
_registrations[removed.Demand] = replacement; _byId[replacement.Id] = replacement;
|
|
TrackSource(removed.Demand);
|
|
var commandId = Guid.NewGuid().ToString("N"); pendingCommands.Add(commandId, replacement);
|
|
await stream.SendAsync(new AddSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [Item(replacement)]), route.Token).ConfigureAwait(false);
|
|
continue;
|
|
}
|
|
FinishRefresh(removed.Demand);
|
|
ReleaseDemand(removed.Demand);
|
|
}
|
|
else
|
|
{
|
|
if (!pendingCommands.Remove(ack.CommandId, out var expected) || ack.Items.Count != 1 ||
|
|
ack.Items[0].ClientItemId != expected.Id) throw new InvalidDataException("Unexpected snapshot acknowledgement.");
|
|
var response = ack.Items[0];
|
|
if (!_byId.TryGetValue(response.ClientItemId, out var registration) || response.Status != DataItemStatus.Good || response.Handle is null) throw new InvalidDataException("Invalid item acknowledgement.");
|
|
registration.Handle = response.Handle; _byHandle[response.Handle] = registration;
|
|
EnqueueSnapshot([registration]);
|
|
registration.NeedsChallenge = true;
|
|
if (freshnessTimer is not null)
|
|
{
|
|
var milliseconds = Math.Clamp(_registrations.Values.Min(x => x.Demand.MaximumSampleAge.TotalMilliseconds) / 2, 50, 5000);
|
|
var interval = TimeSpan.FromMilliseconds(milliseconds);
|
|
freshnessTimer.Change(interval, interval);
|
|
}
|
|
if (registration.Removed)
|
|
{
|
|
var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration;
|
|
await stream.SendAsync(new RemoveSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [response.Handle]), route.Token).ConfigureAwait(false);
|
|
}
|
|
}
|
|
await ChallengeAsync(route.Token).ConfigureAwait(false);
|
|
}
|
|
else if (frame is DataSubscriptionControl control)
|
|
{
|
|
if (control.CatalogEpoch != _key.Serving.CatalogEpoch || control.AuthorityEpoch != _key.Serving.AuthorityEpoch) break;
|
|
if (control.Kind == DataStreamControlKind.SnapshotBegin)
|
|
{
|
|
if (inSnapshot) throw new InvalidDataException("Overlapping snapshots.");
|
|
if (!snapshotQueue.TryDequeue(out snapshotOwners)) throw new InvalidDataException("Snapshot has no acknowledged owner.");
|
|
inSnapshot = true; pending.Clear(); snapshotBytes = 0;
|
|
}
|
|
else if (control.Kind == DataStreamControlKind.SnapshotEnd)
|
|
{
|
|
ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.SnapshotEnd);
|
|
if (!inSnapshot) throw new InvalidDataException("Snapshot end without begin.");
|
|
foreach (var item in pending)
|
|
{
|
|
var accepted = Publish(item.Registration, item.Update with { IsCompleteSnapshot = true }, item.Version, out var validated);
|
|
if (!accepted && item.Registration.Recovery && item.Update.SourceProof is AttemptProof recoveryProof)
|
|
{
|
|
var recoverySource = recoveryProof.Source;
|
|
lock (recoverySource.Gate)
|
|
if (!item.Registration.Removed && recoverySource.TryRecoveryLocked(item.Registration.Demand, item.Registration.Renewal))
|
|
validated = accepted = recoveryProof.Promote();
|
|
}
|
|
if (item.Registration.Renewal && !accepted)
|
|
throw new InvalidDataException("Renewal requires an accepted fresh complete baseline.");
|
|
if (validated) item.Registration.HasBaseline = true;
|
|
if (item.Registration.Recovery)
|
|
{
|
|
if (accepted || validated) { item.Registration.Recovery = false; item.Registration.Renewal = false; item.Registration.RenewalPredecessor = null; FinishRefresh(item.Registration.Demand); }
|
|
else item.Registration.AwaitingCurrent = true;
|
|
}
|
|
}
|
|
foreach (var awaiting in snapshotOwners!)
|
|
if (!awaiting.Removed && !awaiting.HasBaseline)
|
|
{
|
|
if (awaiting.Renewal) throw new InvalidDataException("Renewal snapshot did not establish a complete baseline.");
|
|
awaiting.Recovery = true; awaiting.AwaitingCurrent = true;
|
|
}
|
|
snapshotOwners = null;
|
|
pending.Clear(); snapshotBytes = 0; inSnapshot = false;
|
|
}
|
|
else if (control.Kind is DataStreamControlKind.Reset or DataStreamControlKind.CatalogInvalidated or DataStreamControlKind.AuthorityInvalidated)
|
|
{
|
|
ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.Reset);
|
|
ProjectedStreamDiagnostics.Count(control.Diagnostic switch
|
|
{
|
|
"Source change history expired." => ProjectedStreamDiagnostics.Event.ResetHistory,
|
|
"Source became unavailable." => ProjectedStreamDiagnostics.Event.ResetUnavailable,
|
|
"Snapshot catch-up expired; retry later." or "Snapshot lifetime expired; retry later." => ProjectedStreamDiagnostics.Event.ResetSnapshot,
|
|
_ => ProjectedStreamDiagnostics.Event.ResetOther
|
|
});
|
|
break;
|
|
}
|
|
}
|
|
else if (frame is DataSubscriptionValues values)
|
|
{
|
|
foreach (var item in values.Items)
|
|
{
|
|
ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.Value);
|
|
if (!_byHandle.TryGetValue(item.Handle, out var registration)) throw new InvalidDataException("Unknown item handle.");
|
|
// Frames queued before a remove barrier may arrive while withdrawal is pending.
|
|
if (registration.Removed || !registration.Demand.IsValid) continue;
|
|
if (!values.IsSnapshot && registration.Renewal && !registration.HasBaseline) continue;
|
|
if (item.Sample.Serving != _key.Serving || item.Sample.Version <= 0 || item.Readiness != DataReadiness.Ready ||
|
|
item.Sample.Value.EstimatedRetainedBytes > _owner._limits.MaxUnaryBytes)
|
|
throw new InvalidDataException("Invalid source sample.");
|
|
var ageTimestamp = item.FreshnessObservedTimestamp ?? delivered.ReceivedTimestamp;
|
|
if (!item.AgeBounds.Advance(_owner.Clock.GetElapsedTime(ageTimestamp, _owner.Clock.GetTimestamp())).IsFresh(registration.Demand.MaximumSampleAge))
|
|
{ ProjectedStreamDiagnostics.Count(item.AgeBounds.Upper is null ? ProjectedStreamDiagnostics.Event.UnknownAge : ProjectedStreamDiagnostics.Event.StaleAge); continue; }
|
|
ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.FreshAge);
|
|
var source = _owner.GetSource(registration.Demand, _connectionId); if (source is null) throw new InvalidDataException("Source unavailable.");
|
|
if (demandSources.TryGetValue(registration.Demand, out var priorSource) && !ReferenceEquals(priorSource, source))
|
|
UntrackSource(registration.Demand);
|
|
demandSources[registration.Demand] = source;
|
|
var attemptProof = EvidenceFor(source, registration.Demand.Proof);
|
|
var sample = item.Sample;
|
|
var payload = DecodeValue(sample.Value, registration.Demand.Proof.OriginMetadata);
|
|
var update = new ProjectedValueUpdate(source.Route, new DataValueSnapshot(payload, sample.StatusCode, sample.SourceTimestampUtc?.UtcDateTime, sample.ServerTimestampUtc?.UtcDateTime),
|
|
item.AgeBounds, ageTimestamp, attemptProof, false, registration.Demand.MaximumSampleAge, sample.Version);
|
|
if (values.IsSnapshot)
|
|
{
|
|
if (!inSnapshot) throw new InvalidDataException("Snapshot value outside snapshot.");
|
|
if (snapshotOwners is null || !snapshotOwners.Contains(registration)) throw new InvalidDataException("Snapshot value belongs to another command.");
|
|
snapshotBytes = checked(snapshotBytes + sample.Value.EstimatedRetainedBytes + 512);
|
|
if (pending.Count >= _owner._limits.MaxDemands || snapshotBytes > _owner._limits.MaxUnaryBytes) throw new InvalidDataException("Snapshot capacity exceeded.");
|
|
pending.Add((registration, update, sample.Version));
|
|
}
|
|
else
|
|
{
|
|
// A sibling registration's coverage cannot make this
|
|
// handle ready before its own snapshot barrier ends.
|
|
if (!registration.HasBaseline && !registration.AwaitingCurrent) continue;
|
|
var recovery = registration.Recovery && registration.AwaitingCurrent;
|
|
var accepted = Publish(registration, recovery ? update with { IsCompleteSnapshot = true } : update, sample.Version, out var validated);
|
|
if (recovery && (accepted || validated))
|
|
{ registration.HasBaseline = true; registration.Recovery = false; registration.AwaitingCurrent = false; FinishRefresh(registration.Demand); }
|
|
}
|
|
}
|
|
}
|
|
}
|
|
finally { Interlocked.Add(ref _frameBytes, -delivered.Bytes); (frame as IDisposable)?.Dispose(); }
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex) { ProjectedStreamDiagnostics.Count(ex is OperationCanceledException ? ProjectedStreamDiagnostics.Event.AttemptCanceled : ex is InvalidDataException ? ProjectedStreamDiagnostics.Event.AttemptInvalidData : ProjectedStreamDiagnostics.Event.AttemptOther); }
|
|
finally
|
|
{
|
|
foreach (var proof in evidence.Values.SelectMany(witnesses => witnesses)) proof.Close();
|
|
try { if (route is not null) await route.CancelAsync().ConfigureAwait(false); } catch (Exception) { }
|
|
try { await attemptStop.CancelAsync().ConfigureAwait(false); } catch (Exception) { }
|
|
freshnessTimer?.Dispose();
|
|
renewalTimer?.Dispose();
|
|
try { await Task.WhenAll(renewals.Values).ConfigureAwait(false); } catch (Exception) { }
|
|
try { if (stream is not null) await stream.DisposeAsync().ConfigureAwait(false); }
|
|
catch (Exception) { }
|
|
try { if (pump is not null) await pump.ConfigureAwait(false); }
|
|
catch (Exception) { }
|
|
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
|
|
catch (Exception) { }
|
|
route?.Dispose();
|
|
while (_events.Reader.TryRead(out var remaining)) if (remaining is FrameEvent f) { Interlocked.Add(ref _frameBytes, -f.Bytes); (f.Frame as IDisposable)?.Dispose(); }
|
|
lock (_owner._sync) _refreshRequests.Clear();
|
|
}
|
|
}
|
|
private void ReleaseDemand(Demand demand)
|
|
{
|
|
SourceState? retired = null;
|
|
lock (_owner._sync)
|
|
{
|
|
if (!_owner._demandCohorts.Remove(demand)) return;
|
|
if (_owner._demandSourceKeys.Remove(demand, out var key)) retired = _owner.ReleaseSourceOwnerLocked(key);
|
|
}
|
|
retired?.Invalidate();
|
|
demand.ReleaseHold();
|
|
}
|
|
private bool Publish(Registration registration, ProjectedValueUpdate update, long version, out bool validated)
|
|
{
|
|
validated = false;
|
|
if (registration.Removed || !registration.Demand.IsValid || update.SourceProof is not AttemptProof proof) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishDemand); return false; }
|
|
var source = proof.Source;
|
|
if (!source.TryPrepareSuccessor(registration.Demand, out var successor)) return false;
|
|
try
|
|
{
|
|
if (successor is not null) _owner.BeforeSuccessorAdoptionForTests?.Invoke();
|
|
lock (source.Gate)
|
|
{
|
|
if (successor is not null && !update.IsCompleteSnapshot) return false;
|
|
if (!update.OriginAgeBounds.Advance(_owner.Clock.GetElapsedTime(update.ReceivedTimestamp, _owner.Clock.GetTimestamp()))
|
|
.IsFresh(registration.Demand.MaximumSampleAge)) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishStale); return false; }
|
|
if (!source.IsValid || version < source.LastVersion || version == source.LastVersion && !update.IsCompleteSnapshot) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishVersion); return false; }
|
|
// A command or ACK only owns transport resources. Source coverage begins at
|
|
// the first validated complete baseline, never at an unacknowledged Open.
|
|
if (!proof.IsValid && (!update.IsCompleteSnapshot || !proof.Promote())) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishProof); return false; }
|
|
validated = update.IsCompleteSnapshot;
|
|
if (version == source.LastVersion && update.IsCompleteSnapshot && !registration.Recovery &&
|
|
source.HasFreshCachedLocked(registration.Demand)) return false;
|
|
if (_owner._publisher.TryPublish([update]))
|
|
{
|
|
if (successor is not null)
|
|
{
|
|
if (!update.IsCompleteSnapshot || !source.TryAdoptSuccessor(successor, out var consumed)) { source.Invalidate(); return false; }
|
|
if (consumed) successor = null;
|
|
}
|
|
if (update.IsCompleteSnapshot && (update.Snapshot.StatusCode & 0xC0000000u) == 0)
|
|
Interlocked.Exchange(ref _healthyBaseline, 1);
|
|
source.LastVersion = version; source.CacheLocked(update, version); ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishAccepted); return true;
|
|
}
|
|
if (!ProjectedEvidenceRetirement.CanDrop(update.SourceProof)) source.Invalidate();
|
|
else validated = false;
|
|
ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishSink); return false;
|
|
}
|
|
}
|
|
finally { if (successor is not null) { successor.NodePin.Dispose(); successor.Pin.Dispose(); } }
|
|
}
|
|
}
|
|
public bool RequestFreshSnapshot(IProjectedDemandLease demand)
|
|
{
|
|
if (demand is not Demand item || item.RequestedOperation != DataOperations.Subscribe || !item.IsValid) return false;
|
|
lock (_sync) return !_disposed && _demandCohorts.TryGetValue(item, out var cohort) && cohort.Refresh(item);
|
|
}
|
|
public void Dispose()
|
|
{
|
|
_catalog.Invalidated -= OnCatalogInvalidated;
|
|
Demand[] demands;
|
|
lock (_sync) { if (_disposed) return; _disposed = true; demands = _demands.ToArray(); }
|
|
foreach (var demand in demands) demand.Dispose();
|
|
Cohort[] cohorts;
|
|
lock (_sync) cohorts = _cohorts.Values.ToArray();
|
|
foreach (var cohort in cohorts) cohort.Stop();
|
|
SourceState[] sources;
|
|
lock (_sync) { sources = _sources.Values.ToArray(); _sources.Clear(); _sourcesByProjection.Clear(); _sourcesByMapping.Clear(); _sourceSweep.Clear(); _sourceSweepNodes.Clear(); lock (_sourceRetirementGate) _pendingSourceRetirement.Clear(); }
|
|
foreach (var source in sources) source.Invalidate();
|
|
}
|
|
}
|