feat: expose mapped raw and uns data through grpc adapters
This commit is contained in:
@@ -0,0 +1,732 @@
|
||||
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; }
|
||||
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 Func<(bool Allowed, long Generation)> _localWriteRole;
|
||||
private readonly Dictionary<SourceKey, SourceState> _sources = 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 readonly Dictionary<CohortKey, Cohort> _cohorts = new();
|
||||
private readonly Dictionary<Demand, Cohort> _demandCohorts = 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)
|
||||
{
|
||||
_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));
|
||||
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;
|
||||
private static ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue EncodeValue(DataMetadata metadata, object? value)
|
||||
{
|
||||
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];
|
||||
for (var i = 0; i < values.Length; i++)
|
||||
{
|
||||
var item = array.GetValue(i) ?? throw new ArgumentException("Null array element.");
|
||||
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);
|
||||
}
|
||||
private 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)) 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) ||
|
||||
proof.Metadata.View.MappingId is not { } mapping || proof.Lease.Serving.ServingGeneration <= 0 ||
|
||||
_connectionForMapping(mapping) is not { Length: > 0 } connectionId) 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) 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, identity, operation, pin, nodePin, connectionId, localRole.Generation, null);
|
||||
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 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)); }
|
||||
private static OpcUaOperation Operation(DataOperations operation) => operation switch
|
||||
{
|
||||
DataOperations.Browse => OpcUaOperation.Browse,
|
||||
DataOperations.Read => OpcUaOperation.Read,
|
||||
DataOperations.Write => OpcUaOperation.WriteOperate,
|
||||
DataOperations.Subscribe => OpcUaOperation.CreateMonitoredItems,
|
||||
_ => 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
|
||||
{
|
||||
private int _disposed;
|
||||
private int _holds;
|
||||
private bool _cleaned;
|
||||
private readonly TaskCompletionSource _completed = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private readonly CancellationTokenSource _stop = new();
|
||||
internal ProjectedNodeProof Proof => proof;
|
||||
internal ProjectedVariableDefinition Definition => definition;
|
||||
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;
|
||||
pin.Dispose(); 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 => proof.MaximumSampleAge;
|
||||
public DataView OriginView => proof.OriginMetadata.View;
|
||||
public DataRealm Realm => definition.Realm;
|
||||
public string LocalIdentifier => definition.LocalIdentifier;
|
||||
public long ProjectionGeneration => proof.Generation;
|
||||
public ServingIdentity Serving => proof.Lease.Serving;
|
||||
public CancellationToken CancellationToken => _stop.Token;
|
||||
public bool IsValid
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) != 0) return false;
|
||||
try
|
||||
{
|
||||
var role = operation == DataOperations.Write ? owner._localWriteRole() : (Allowed: true, Generation: 1L);
|
||||
return role.Allowed && role.Generation == writeRoleGeneration && role.Generation > 0 && nodePin.IsValid && definition.AuthorityIsCurrent() && owner._nodes.TryResolve(nodeId, out var now) && now is not null && ReferenceEquals(now.Lifetime, definition.Lifetime) && now.ProjectionGeneration == definition.ProjectionGeneration && now.Metadata.View == definition.Metadata.View &&
|
||||
owner._catalog.TryResolveProjected(Realm, LocalIdentifier, out var current) && ReferenceEquals(current, proof) &&
|
||||
string.Equals(owner._connectionForMapping(proof.Metadata.View.MappingId!), connectionId, StringComparison.OrdinalIgnoreCase) &&
|
||||
(configured is not null ? configured.Matches(proof.Metadata.View.MappingId!, proof.Metadata.View, proof.Resolver.LocalAuthority) && (proof.Subject.AllowedOperations & DataOperations.Subscribe) != 0 :
|
||||
caller is not null && owner._policy.AuthorizeMapped(caller, Operation(operation), proof.Metadata.View, Serving, proof.Subject, proof.Resolver, proof.Lease)) &&
|
||||
Volatile.Read(ref _disposed) == 0;
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; }
|
||||
}
|
||||
}
|
||||
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);
|
||||
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;
|
||||
internal readonly object Gate = new(); internal long LastVersion;
|
||||
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;
|
||||
public TimeProvider Clock => _owner.Clock;
|
||||
public bool IsValid
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
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.TryResolveProjected(definition.Realm, definition.LocalIdentifier, out var now) && ReferenceEquals(now, proof) &&
|
||||
string.Equals(_owner._connectionForMapping(proof.Metadata.View.MappingId!), _key.Connection, StringComparison.OrdinalIgnoreCase); }
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; }
|
||||
}
|
||||
}
|
||||
}
|
||||
public void Invalidate()
|
||||
{
|
||||
IDisposable? pin; IProjectedNodePin? nodePin;
|
||||
lock (Gate)
|
||||
{
|
||||
if (_proof is null) return;
|
||||
_proof = null; _definition = null; pin = _pin; _pin = null; nodePin = _nodePin; _nodePin = null;
|
||||
}
|
||||
try { _owner._publisher.Retire(_route); }
|
||||
catch (Exception) { }
|
||||
finally { nodePin?.Dispose(); pin?.Dispose(); }
|
||||
}
|
||||
}
|
||||
private bool RemoveSourceLocked(SourceKey key, out SourceState? source)
|
||||
{
|
||||
if (!_sources.Remove(key, out source)) return false;
|
||||
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 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);
|
||||
lock (_sync)
|
||||
{
|
||||
if (_sources.TryGetValue(key, out var existing))
|
||||
{
|
||||
if (existing.IsValid) 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);
|
||||
if (!source.IsValid || !_publisher.TryBind(route)) { source.Invalidate(); return null; }
|
||||
_sources.Add(key, source); _sourceSweepNodes.Add(key, _sourceSweep.AddLast(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;
|
||||
lock (_sync)
|
||||
{
|
||||
if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || budget.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !item.TryHold()) return false;
|
||||
_unaryCount++; _unaryBytes += budget.MaxBytes;
|
||||
}
|
||||
_ = Task.Run(() => ReadCoreAsync(item, budget, requestStartedTimestamp)); return true;
|
||||
}
|
||||
private async Task ReadCoreAsync(Demand demand, DataBudget budget, long started)
|
||||
{
|
||||
IGrpcDataAdapterConnectionLease? connection = null;
|
||||
try
|
||||
{
|
||||
var remaining = budget.Timeout - Clock.GetElapsedTime(started, Clock.GetTimestamp());
|
||||
if (remaining <= TimeSpan.Zero || !demand.IsValid) return;
|
||||
var connectionId = _connectionForMapping(demand.Proof.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) return;
|
||||
using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken);
|
||||
var result = await connection.Connection.ReadAsync(new DataReadRequest([new ReadItem("0", demand.OriginView, 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 != demand.Serving || sample.Version <= 0 || !demand.IsValid || route.IsCancellationRequested) return;
|
||||
result[0].AgeBounds.Validate();
|
||||
if (!result[0].AgeBounds.IsFresh(demand.MaximumSampleAge)) return;
|
||||
if (sample.Value.EstimatedRetainedBytes > budget.MaxBytes) return;
|
||||
var payload = DecodeValue(sample.Value, demand.Proof.OriginMetadata);
|
||||
var snapshot = new DataValueSnapshot(payload, sample.StatusCode, sample.SourceTimestampUtc?.UtcDateTime, sample.ServerTimestampUtc?.UtcDateTime);
|
||||
var received = Clock.GetTimestamp(); var source = GetSource(demand, connectionId);
|
||||
if (source is null) return;
|
||||
lock (source.Gate)
|
||||
{
|
||||
if (!demand.IsValid || !source.IsValid || sample.Version <= source.LastVersion) return;
|
||||
if (_publisher.TryPublish([new(source.Route, snapshot, result[0].AgeBounds, received, source, true, demand.MaximumSampleAge)])) source.LastVersion = sample.Version;
|
||||
else 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;
|
||||
ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue owned;
|
||||
try
|
||||
{
|
||||
budget.Validate();
|
||||
owned = EncodeValue(item.Proof.OriginMetadata, value);
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return rejected; }
|
||||
var elapsed = Clock.GetElapsedTime(requestStartedTimestamp, Clock.GetTimestamp());
|
||||
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout || owned.EstimatedRetainedBytes > budget.MaxBytes) { owned.Dispose(); return rejected; }
|
||||
lock (_sync)
|
||||
{
|
||||
if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || budget.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !item.TryHold()) { owned.Dispose(); return rejected; }
|
||||
_unaryCount++; _unaryBytes += budget.MaxBytes;
|
||||
}
|
||||
var task = Task.Run(() => WriteCoreAsync(item, owned, budget, requestStartedTimestamp, cancellationToken));
|
||||
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 { value.Dispose(); demand.ReleaseHold(); 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; }
|
||||
cohort.Start(); return true;
|
||||
}
|
||||
}
|
||||
private sealed class Cohort
|
||||
{
|
||||
private abstract record Event;
|
||||
private sealed record AddEvent(Demand Demand) : Event;
|
||||
private sealed record RemoveEvent(Demand Demand) : Event;
|
||||
private sealed record FrameEvent(DataSubscriptionFrame Frame, long Bytes) : 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; }
|
||||
private readonly ProjectedDataAccess _owner;
|
||||
private readonly 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);
|
||||
private readonly string _id = Guid.NewGuid().ToString("N");
|
||||
private const long Epoch = 1;
|
||||
private int _started, _closing, _restart;
|
||||
private long _sequence;
|
||||
private long _frameBytes;
|
||||
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 Restart()
|
||||
{
|
||||
if (Volatile.Read(ref _restart) != 0) return true;
|
||||
if (Closing) return false;
|
||||
Interlocked.Exchange(ref _restart, 1); Stop(); return true;
|
||||
}
|
||||
private async Task PumpAsync(IDataSubscription stream)
|
||||
{
|
||||
try
|
||||
{
|
||||
await foreach (var frame in stream.ReadAllAsync(_stop.Token).ConfigureAwait(false))
|
||||
{
|
||||
var bytes = frame is DataSubscriptionValues values ? checked(512L + values.Items.Sum(x => x.Sample.Value.EstimatedRetainedBytes)) : 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), _stop.Token).ConfigureAwait(false); }
|
||||
catch { Interlocked.Add(ref _frameBytes, -bytes); (frame as IDisposable)?.Dispose(); throw; }
|
||||
}
|
||||
}
|
||||
catch (Exception) { }
|
||||
finally { _events.Writer.TryWrite(new EndEvent()); }
|
||||
}
|
||||
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()
|
||||
{
|
||||
IGrpcDataAdapterConnectionLease? connection = null; IDataSubscription? stream = null; Task? pump = null;
|
||||
var opened = false; var inSnapshot = false; long snapshotBytes = 0;
|
||||
var pending = new List<(Registration Registration, ProjectedValueUpdate Update, long Version)>();
|
||||
try
|
||||
{
|
||||
connection = await _owner._connections.AcquireAsync(_connectionId, _stop.Token).ConfigureAwait(false);
|
||||
if (connection is null || !ReferenceEquals(connection.Connection.Clock, _owner.Clock) || connection.CancellationToken.IsCancellationRequested) return;
|
||||
using var route = CancellationTokenSource.CreateLinkedTokenSource(_stop.Token, connection.CancellationToken);
|
||||
stream = await connection.Connection.SubscribeAsync(route.Token).ConfigureAwait(false);
|
||||
if (stream is not IDataSubscriptionProvenance provenance || provenance.Serving != _key.Serving) return;
|
||||
pump = PumpAsync(stream);
|
||||
await foreach (var message in _events.Reader.ReadAllAsync(route.Token).ConfigureAwait(false))
|
||||
{
|
||||
if (message is AddEvent add)
|
||||
{
|
||||
if (!add.Demand.IsValid) continue;
|
||||
var registration = new Registration(add.Demand, Guid.NewGuid().ToString("N"));
|
||||
_registrations[add.Demand] = registration; _byId[registration.Id] = registration;
|
||||
DataSubscriptionCommand command = !opened
|
||||
? new OpenSubscription(_id, Epoch, Guid.NewGuid().ToString("N"), TimeSpan.FromSeconds(5), [Item(registration)], false, TimeSpan.FromMinutes(1), new(TimeSpan.FromSeconds(5), 1, _owner._limits.MaxUnaryBytes))
|
||||
: new AddSubscriptionItems(_id, Epoch, Guid.NewGuid().ToString("N"), TimeSpan.FromSeconds(5), [Item(registration)]);
|
||||
await stream.SendAsync(command, route.Token).ConfigureAwait(false); opened = true;
|
||||
}
|
||||
else if (message is RemoveEvent remove)
|
||||
{
|
||||
if (_registrations.TryGetValue(remove.Demand, out var registration))
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
if (_registrations.Values.All(x => x.Removed)) break;
|
||||
}
|
||||
else if (message is EndEvent) break;
|
||||
else if (message is FrameEvent delivered)
|
||||
{
|
||||
var frame = delivered.Frame;
|
||||
try
|
||||
{
|
||||
if (frame.SubscriptionId != _id || frame.StreamEpoch != Epoch || frame.Sequence <= _sequence) break;
|
||||
_sequence = frame.Sequence;
|
||||
if (frame is DataSubscriptionAck ack)
|
||||
{
|
||||
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) { Stop(); continue; }
|
||||
_registrations.Remove(removed.Demand); _byId.Remove(removed.Id);
|
||||
if (removed.Handle is { } removedHandle) _byHandle.Remove(removedHandle);
|
||||
SourceState? retiredSource = null;
|
||||
lock (_owner._sync)
|
||||
{
|
||||
_owner._demandCohorts.Remove(removed.Demand);
|
||||
if (!_registrations.Values.Any(x => !x.Removed && x.Demand.OriginView == removed.Demand.OriginView && x.Demand.ProjectionGeneration == removed.Demand.ProjectionGeneration))
|
||||
{
|
||||
var sourceKey = new SourceKey(_key.Connection, removed.Demand.OriginView, _key.Serving, removed.Demand.ProjectionGeneration);
|
||||
_owner.RemoveSourceLocked(sourceKey, out retiredSource);
|
||||
}
|
||||
}
|
||||
retiredSource?.Invalidate();
|
||||
removed.Demand.ReleaseHold();
|
||||
}
|
||||
else foreach (var response in ack.Items)
|
||||
{
|
||||
if (!_byId.TryGetValue(response.ClientItemId, out var registration) || response.Status != DataItemStatus.Good || response.Handle is null) { Stop(); break; }
|
||||
registration.Handle = response.Handle; _byHandle[response.Handle] = registration;
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (frame is DataSubscriptionControl control)
|
||||
{
|
||||
if (control.CatalogEpoch != _key.Serving.CatalogEpoch || control.AuthorityEpoch != _key.Serving.AuthorityEpoch) break;
|
||||
if (control.Kind == DataStreamControlKind.SnapshotBegin) { inSnapshot = true; pending.Clear(); snapshotBytes = 0; }
|
||||
else if (control.Kind == DataStreamControlKind.SnapshotEnd && inSnapshot)
|
||||
{
|
||||
foreach (var item in pending) Publish(item.Registration, item.Update with { IsCompleteSnapshot = true }, item.Version);
|
||||
pending.Clear(); snapshotBytes = 0; inSnapshot = false;
|
||||
}
|
||||
else if (control.Kind is DataStreamControlKind.Reset or DataStreamControlKind.CatalogInvalidated or DataStreamControlKind.AuthorityInvalidated) break;
|
||||
}
|
||||
else if (frame is DataSubscriptionValues values)
|
||||
{
|
||||
foreach (var item in values.Items)
|
||||
{
|
||||
if (!_byHandle.TryGetValue(item.Handle, out var registration) || registration.Removed || !registration.Demand.IsValid ||
|
||||
item.Sample.Serving != _key.Serving || item.Sample.Version <= 0 || item.Readiness != DataReadiness.Ready ||
|
||||
!item.AgeBounds.IsFresh(registration.Demand.MaximumSampleAge) || item.Sample.Value.EstimatedRetainedBytes > _owner._limits.MaxUnaryBytes)
|
||||
{ Stop(); break; }
|
||||
var source = _owner.GetSource(registration.Demand, _connectionId); if (source is null) { Stop(); break; }
|
||||
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, _owner.Clock.GetTimestamp(), source, false, registration.Demand.MaximumSampleAge);
|
||||
if (inSnapshot)
|
||||
{
|
||||
snapshotBytes = checked(snapshotBytes + sample.Value.EstimatedRetainedBytes + 512);
|
||||
if (pending.Count >= _owner._limits.MaxDemands || snapshotBytes > _owner._limits.MaxUnaryBytes) { Stop(); break; }
|
||||
pending.Add((registration, update, sample.Version));
|
||||
}
|
||||
else Publish(registration, update, sample.Version);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally { Interlocked.Add(ref _frameBytes, -delivered.Bytes); (frame as IDisposable)?.Dispose(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception) { }
|
||||
finally
|
||||
{
|
||||
Stop();
|
||||
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) { }
|
||||
while (_events.Reader.TryRead(out var remaining)) if (remaining is FrameEvent f) { Interlocked.Add(ref _frameBytes, -f.Bytes); (f.Frame as IDisposable)?.Dispose(); }
|
||||
Demand[] owned; var transferred = new HashSet<Demand>(); var retired = new List<SourceState>();
|
||||
lock (_owner._sync)
|
||||
{
|
||||
owned = _owner._demandCohorts.Where(x => ReferenceEquals(x.Value, this)).Select(x => x.Key).ToArray();
|
||||
foreach (var item in owned) _owner._demandCohorts.Remove(item);
|
||||
if (_owner._cohorts.TryGetValue(_key, out var current) && ReferenceEquals(current, this)) _owner._cohorts.Remove(_key);
|
||||
foreach (var item in owned)
|
||||
{
|
||||
var sourceKey = new SourceKey(_key.Connection, item.OriginView, _key.Serving, item.ProjectionGeneration);
|
||||
if (_owner.RemoveSourceLocked(sourceKey, out var state) && state is not null) retired.Add(state);
|
||||
}
|
||||
}
|
||||
foreach (var source in retired) source.Invalidate();
|
||||
lock (_owner._sync)
|
||||
{
|
||||
if (Volatile.Read(ref _restart) != 0 && !_owner._disposed)
|
||||
{
|
||||
var eligible = owned.Where(d => !d.Disposed).ToArray();
|
||||
if (eligible.Length > 0 && !_owner._cohorts.ContainsKey(_key) && _owner._cohorts.Count < _owner._limits.MaxStreams)
|
||||
{
|
||||
var replacement = new Cohort(_owner, _key, _connectionId); _owner._cohorts.Add(_key, replacement);
|
||||
foreach (var demand in eligible)
|
||||
if (replacement.Add(demand)) { _owner._demandCohorts[demand] = replacement; transferred.Add(demand); }
|
||||
if (transferred.Count > 0) replacement.Start(); else _owner._cohorts.Remove(_key);
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (var item in owned) if (!transferred.Contains(item)) { item.Dispose(); item.ReleaseHold(); }
|
||||
_stop.Dispose();
|
||||
}
|
||||
}
|
||||
private void Publish(Registration registration, ProjectedValueUpdate update, long version)
|
||||
{
|
||||
if (!registration.Demand.IsValid || update.SourceProof is not SourceState source) return;
|
||||
lock (source.Gate)
|
||||
{
|
||||
if (!source.IsValid || version <= source.LastVersion) return;
|
||||
if (_owner._publisher.TryPublish([update])) source.LastVersion = version; else source.Invalidate();
|
||||
}
|
||||
}
|
||||
}
|
||||
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.Restart();
|
||||
}
|
||||
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(); _sourcesByMapping.Clear(); _sourceSweep.Clear(); _sourceSweepNodes.Clear(); lock (_sourceRetirementGate) _pendingSourceRetirement.Clear(); }
|
||||
foreach (var source in sources) source.Invalidate();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user