Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs
T
Joseph Doherty 9d969c4724 fix(grpc-data): follow-ups review r1 — the unknown-mapping hold spares a transient mapping's own keys and pauses with no live stream (#933); cancel abandoned root fetches (#934)
S1: a held key that a transiently unknown mapping listed itself (_lastListed) is
held without a bound; only a definitive refusal of that mapping (Denied /
NotFound / Unsupported / ConditionCapacity, remembered across retries and stream
ends) starts its MaxUnknownHold clock. Consistent with a never-opening stream.
S2: the hold clock runs only while a stream is past its barrier (paused at the
stream end, shifted at the next barrier).
N1: in-stream root re-resolves run under a per-stream source cancelled when the
stream ends. N2: no held-expiry timer without a sink (spin). N3: MaxUnknownHold
must be positive. N5: #933 test lower bound taken before the hold starts; tests
for S1, S2, N1, N2, N3 and a second failed re-resolve — each red on revert.
2026-11-25 12:02:33 -05:00

514 lines
29 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>A3: the deployed mapping placements the condition runtime reads (an adapter over <see cref="ProjectedMappingDeploymentRuntime"/>).</summary>
public interface IProjectedConditionMappings
{
/// <summary>The currently published placements (copies; read on change only).</summary>
IReadOnlyList<ProjectedMappingPlacement> Current { get; }
/// <summary>Raised after the published placement set changes.</summary>
event Action? Changed;
/// <summary>
/// A4 F1–F3: a catalog attempt (a deploy) is in progress. Its <see cref="Current"/> is an empty set that says "not
/// decided yet", not "every mapping removed" — the conditions of a connection that drops out now are HELD, and
/// removed only if the settled set no longer has that connection.
/// </summary>
bool Suspended => false;
/// <summary>
/// A4 review r2 S1: <see cref="Current"/> and <see cref="Suspended"/> as ONE consistent pair. A reader that pairs a live
/// "settled" flag with a placement list copied earlier (still the deploy's empty set) would release held conditions.
/// </summary>
(IReadOnlyList<ProjectedMappingPlacement> Current, bool Suspended) Snapshot => (Current, Suspended);
}
/// <summary>The production adapter over <see cref="ProjectedMappingDeploymentRuntime"/>.</summary>
/// <remarks>
/// A4 review r2 S1: the placements and the "attempt undecided" flag arrive TOGETHER in one
/// <see cref="ProjectedMappingSet"/> captured under the runtime's transition lock, and are kept as one volatile reference —
/// never the runtime's live flag next to a list copied by an earlier notification. Sets delivered out of order (two
/// transitions notifying concurrently) are ordered by <see cref="ProjectedMappingSet.Sequence"/>; an older one is ignored.
/// </remarks>
public sealed class DeployedConditionMappings : IProjectedConditionMappings
{
private ProjectedMappingSet _set = null!;
public DeployedConditionMappings(ProjectedMappingDeploymentRuntime runtime)
{
ArgumentNullException.ThrowIfNull(runtime);
runtime.SetChanged += OnSetChanged;
// After subscribing: a transition racing the constructor is either in this read or delivered to the handler.
Publish(runtime.Set);
}
private void OnSetChanged(ProjectedMappingSet set)
{
if (Publish(set)) Changed?.Invoke();
}
private bool Publish(ProjectedMappingSet set)
{
while (true)
{
var seen = Volatile.Read(ref _set);
if (seen is not null && seen.Sequence >= set.Sequence) return false;
if (ReferenceEquals(Interlocked.CompareExchange(ref _set, set, seen), seen)) return true;
}
}
public IReadOnlyList<ProjectedMappingPlacement> Current => Volatile.Read(ref _set).Placements;
public event Action? Changed;
/// <inheritdoc />
public bool Suspended => Volatile.Read(ref _set).Suspended;
/// <inheritdoc />
public (IReadOnlyList<ProjectedMappingPlacement> Current, bool Suspended) Snapshot
{
get { var set = Volatile.Read(ref _set); return (set.Placements, set.Suspended); }
}
}
/// <summary>A3 host limits (§5.5 "Budget").</summary>
/// <param name="Linger">How long a connection's condition items stay open after the last event item goes (default 30 s).</param>
/// <param name="MaxImportedConditionNodes">Per consumer node (default 122,500 = 2,500 × 49).</param>
/// <param name="MaxImportedConditionBytes">Per consumer node (default = L2-measured <see cref="BytesPerCondition"/> × 2,500 ≈ 381 MiB).</param>
/// <param name="ReconnectDelay">Pause before re-opening an ended condition stream.</param>
public sealed record ProjectedConditionOptions(TimeSpan Linger, int MaxImportedConditionNodes, long MaxImportedConditionBytes,
TimeSpan ReconnectDelay)
{
/// <summary>Counted, not estimated (plan §5.5 table): the worst case per condition.</summary>
public const int NodesPerCondition = 49;
/// <summary>
/// Retained managed bytes per imported condition, measured by the A3 L2 harness (1,000 conditions in one mapping on a
/// running SDK 2.0.1 server: node + children + ids + registry/indexes + EventId registry + verdict cache; X0's
/// node-only harness measured 160,997). A3b review S5: the WORST case — two placements, every EventId slot, three
/// event items, the runner's Live + Buffer records. A3 review round 2: measured with the retained heap
/// (<c>GCMemoryInfo</c>, not <c>GC.GetTotalMemory</c>, which counted ~125 MiB of committed-but-free regions) and the
/// settled working set, 8 EventId slots (§5.6): max of three runs = 158,629 B (working set; heap 111,715 B), rounded up.
/// </summary>
public const long BytesPerCondition = 160_000;
/// <summary>§9.3 L2: the host byte cap = measured per-condition bytes × 2,500 (the host condition cap).</summary>
public const long DefaultMaxImportedConditionBytes = BytesPerCondition * 2_500;
/// <summary>
/// #930 (N2/N3): the base in-stream retry delay of a mapping the origin refused DEFINITIVELY (<c>Denied</c>,
/// <c>NotFound</c>, <c>Unsupported</c>, for its item or its root metadata) or that is over capacity
/// (<see cref="ProjectedConditionMappingStatus.ConditionCapacity"/>); doubled per consecutive retry up to 4×. A transient
/// refusal or a snapshot timeout retries after <c>ConditionSnapshotTimeoutMilliseconds</c> × 2ⁿ (≤ 8×). Either way the
/// mapping's item is re-added on the OPEN stream — the healthy mappings are never re-snapshotted for it.
/// </summary>
public TimeSpan LongRetryDelay { get; init; } = TimeSpan.FromMinutes(5);
/// <summary>#931 (N4): the ceiling of the exponential reconnect backoff after streams that end before their barrier.</summary>
public TimeSpan MaxReconnectDelay { get; init; } = TimeSpan.FromSeconds(60);
/// <summary>
/// A4 review r2 S2: the longest a connection's conditions are HELD for an undecided deploy (a catalog attempt that
/// began and has not completed). Past it they are released (removed) as if the attempt had settled without the
/// connection. Any completion settles sooner; this bounds an attempt that never completes. The default is 2.5× the
/// deploy apply deadline (<c>DeployTimings.ApplyDeadline</c>, 120 s): an attempt still open by then is not finishing.
/// Before it, the held conditions go <c>BadNoCommunication</c> on the connection's stale timeout, as for any stream gap.
/// </summary>
public TimeSpan MaxHold { get; init; } = TimeSpan.FromMinutes(5);
/// <summary>
/// #933: the longest a materialised condition that no KNOWN mapping lists is kept (<c>BadNoCommunication</c>) because
/// another mapping of the connection is unknown (Unavailable, Denied, retrying). Past it the condition is removed — a
/// removal with RefreshRequired, never "known inactive" (§5.1 T2) — and re-created if the unknown mapping lists it again.
/// Scoping the hold to "mappings that could list the key" is not provable on the consumer: a mapping lists a key when the
/// origin's CURRENT catalog places the condition under that mapping's root, and placements are origin deploy-time
/// configuration (a dropped key may have moved into the unknown mapping's scope). The default (20 min) is ~4× the longest
/// transient retry cycle at the default 30 s snapshot timeout (× 8 = 4 min, + the retry's own timeout) and spans the first
/// two in-stream re-checks of a definitive refusal (<see cref="LongRetryDelay"/> 5 min, then 10 min), so a transient
/// outage or a corrected grant never removes anything; only a durable one does.
/// </summary>
public TimeSpan MaxUnknownHold { get; init; } = TimeSpan.FromMinutes(20);
public static ProjectedConditionOptions Default { get; } =
new(TimeSpan.FromSeconds(30), 122_500, DefaultMaxImportedConditionBytes, TimeSpan.FromSeconds(1));
}
/// <summary>Why a condition-bearing mapping is not contributing conditions.</summary>
public enum ProjectedConditionMappingStatus { Pending, Snapshotting, Complete, Unavailable, ConditionCapacity }
/// <summary>
/// A3 (plan §5.4, §5.5): the consumer's condition runtime.
/// <list type="bullet">
/// <item><b>Gate</b> (<see cref="CanSee"/>): the mapping gate for <c>CreateMonitoredItems</c> on ANY current placement
/// mapping — the mapping's Subscribe + AlarmSubscribe bits and a local Subscribe grant on the placement folder's local
/// scope — regardless of <c>Security:Acl:Enabled</c>.</item>
/// <item><b>Demand</b>: the first admitted event item opens, per condition-bearing connection, ONE stream with one
/// root-scoped condition item per enabled condition-bearing mapping (under the connection's service principal);
/// they close together after the last item goes plus <see cref="ProjectedConditionOptions.Linger"/>.</item>
/// <item><b>Barrier + budget</b>: <c>total &gt; MaxConditions</c> ⇒ that mapping is
/// <see cref="ProjectedConditionMappingStatus.ConditionCapacity"/> and its item removed before anything is
/// materialised; host caps reject the mappings that would cross them, in deployed order; conditions are materialised
/// only after every mapping completed its snapshot (or timed out ⇒ Unavailable).</item>
/// <item><b>Versions</b>: per key and epoch; a <c>removed</c> record and a snapshot begin bypass the gate; a removal is
/// applied unconditionally and forgets the key's version.</item>
/// <item><b>Lifetime</b>: a stream end is "re-snapshot", never "conditions removed"; only a COMPLETE re-snapshot that
/// no longer lists a key removes it. Past <c>ConditionStaleTimeoutMilliseconds</c> without a stream the conditions go
/// <c>BadNoCommunication</c> (one event each) — never "known inactive" (§5.1 T2).</item>
/// </list>
/// </summary>
public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess, IDisposable
{
private readonly IProjectedConditionMappings _mappings;
private readonly IGrpcDataAdapterConnectionSource _connections;
private readonly DataOperationPolicy _policy;
private readonly Func<IProjectedConditionSink?> _sink;
private readonly TimeProvider _clock;
private readonly ProjectedConditionOptions _options;
private readonly ILogger _log;
private readonly object _gate = new();
/// <summary>Mutated under <see cref="_gate"/> only; concurrent so a method call reads its runner's <c>Serving</c> without
/// taking <see cref="_gate"/> (#931 N6: <c>_gate</c> can sit behind a stop that waits on <c>_staleGate</c>).</summary>
private readonly ConcurrentDictionary<string, ConnectionRunner> _runners = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Review r1 S3/S4: a stopped runner's completion (its loop AND its removal) per connection; the next runner of
/// that connection awaits it before opening a stream or taking the materialised set, so the two never overlap.</summary>
private readonly Dictionary<string, ConnectionRunner> _stopping = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// A4 F1–F3: runners stopped WITHOUT removal because their connection dropped out of a suspended (deploying) mapping
/// set. The connection's next runner takes their materialised set over (same conditions, same EventIds, no re-create);
/// a settled set without the connection releases them (removal). Under <see cref="_gate"/>.
/// </summary>
/// <remarks>A4 review r2 S2: concurrent (mutated under <see cref="_gate"/> only) so a diagnostics poll reports a held
/// connection as <c>held</c> without taking <c>_gate</c>.</remarks>
private readonly ConcurrentDictionary<string, ConnectionRunner> _held = new(StringComparer.OrdinalIgnoreCase);
private readonly ConditionLedger _ledger;
private int _demand;
private long _mappingVersion = 1;
private ITimer? _linger;
private bool _disposed;
public ProjectedConditionAccess(IProjectedConditionMappings mappings, IGrpcDataAdapterConnectionSource connections,
DataOperationPolicy policy, Func<IProjectedConditionSink?>? sink, TimeProvider clock, ProjectedConditionOptions? options = null,
ILogger? logger = null, DataConnectionConditionDiagnostics? diagnostics = null)
{
_mappings = mappings ?? throw new ArgumentNullException(nameof(mappings));
Diagnostics = diagnostics ?? new DataConnectionConditionDiagnostics();
_connections = connections ?? throw new ArgumentNullException(nameof(connections));
_policy = policy ?? throw new ArgumentNullException(nameof(policy));
_sink = sink ?? (() => Sink);
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_options = options ?? ProjectedConditionOptions.Default;
// #933 review r1 N3: zero or negative would remove every held key at once — the bound must be a real duration.
if (_options.MaxUnknownHold <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(options), _options.MaxUnknownHold, "MaxUnknownHold must be positive.");
_log = logger ?? NullLogger.Instance;
_ledger = new ConditionLedger(_options);
_mappings.Changed += OnMappingsChanged;
Diagnostics.AttachConsumer(CaptureConsumer);
}
/// <summary>A4: the diagnostics/metrics this runtime reports into (shared with the diagnostics readers).</summary>
public DataConnectionConditionDiagnostics Diagnostics { get; }
/// <summary>A4: one connection's consumer condition state; null when no current mapping of it is condition-bearing.</summary>
private DataConnectionConditionDiagnostics.ConsumerState? CaptureConsumer(string connectionId)
{
var mappings = _mappings.Current.Where(x => string.Equals(x.Mapping.DataConnectionId, connectionId, StringComparison.OrdinalIgnoreCase)
&& x.Authority.IsActive && IsConditionBearing(x.Mapping)).ToArray();
// A4 review r2 S2: a connection held for an undecided deploy has no current mapping, but its conditions exist and are
// charged — report them as "held" instead of hiding them.
if (!_runners.ContainsKey(connectionId) && _held.TryGetValue(connectionId, out var held))
{
var (_, heldAt, heldCount, heldUnknown, _) = held.Capture();
return new("held", heldAt, heldCount, heldUnknown, [], _ledger.Total, _ledger.ConditionLimit);
}
if (mappings.Length == 0) return null;
// #931 N6 spirit: a diagnostics poll never takes _gate either.
if (!_runners.TryGetValue(connectionId, out var runner))
return new("idle", null, 0, 0, OrderMappings(mappings).Select(x => new ConditionMappingDiagnostics(x.Mapping.RemoteNamespaceMappingId,
ProjectedConditionMappingStatus.Pending.ToString(), 0, x.Mapping.MaxConditions)).ToArray(), _ledger.Total, _ledger.ConditionLimit);
var (state, snapshotAt, materialised, unknown, rows) = runner.Capture();
return new(state, snapshotAt, materialised, unknown, rows, _ledger.Total, _ledger.ConditionLimit);
}
/// <summary>The node manager the host binds once the server is up (used when no sink delegate was supplied).</summary>
public IProjectedConditionSink? Sink { get; set; }
/// <summary>Whether a mapping is condition-bearing: enabled, Subscribe + AlarmSubscribe granted.</summary>
public static bool IsConditionBearing(RemoteNamespaceMapping mapping) =>
mapping.Enabled && (mapping.AllowedOperations & (DataOperations.Subscribe | DataOperations.AlarmSubscribe))
== (DataOperations.Subscribe | DataOperations.AlarmSubscribe);
/// <inheritdoc />
/// <remarks>Review r1 S2: also folds each current mapping's <c>Authority.IsActive</c>, which flips without a deploy.</remarks>
public long AuthorityGeneration
{
get
{
var active = 17L;
foreach (var mapping in _mappings.Current) active = unchecked(active * 31 + (mapping.Authority.IsActive ? 1 : 2));
return unchecked((Interlocked.Read(ref _mappingVersion) << 32) ^ _policy.AuthorityEpoch ^ (active << 1));
}
}
/// <inheritdoc />
public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements)
{
if (caller is null || string.IsNullOrWhiteSpace(caller.Principal) || placements.Count == 0) return false;
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
var current = _mappings.Current;
foreach (var placement in placements)
if (Gate(identity, current, placement.MappingId, placement.Realm, placement.FolderLocalSubject)) return true;
return false;
}
/// <inheritdoc />
public bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject)
{
if (caller is null || string.IsNullOrWhiteSpace(caller.Principal)) return false;
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
return Gate(identity, _mappings.Current, mappingId, null, folderLocalSubject);
}
/// <inheritdoc />
public bool IsConditionBearingMapping(string mappingId) =>
_mappings.Current.Any(x => string.Equals(x.Mapping.RemoteNamespaceMappingId, mappingId, StringComparison.OrdinalIgnoreCase)
&& x.Authority.IsActive && IsConditionBearing(x.Mapping));
/// <summary>The mapping gate for one (mapping, folder) placement; <paramref name="realm"/> null = the mapping's own.</summary>
private bool Gate(DataCallerIdentity identity, IReadOnlyList<ProjectedMappingPlacement> current, string mappingId, DataRealm? realm,
string folderLocalSubject)
{
var mapping = current.FirstOrDefault(x => string.Equals(x.Mapping.RemoteNamespaceMappingId, mappingId, StringComparison.OrdinalIgnoreCase));
if (mapping is null || !mapping.Authority.IsActive || !IsConditionBearing(mapping.Mapping) || (realm is { } r && mapping.Mapping.Realm != r))
return false;
if (!TryFolderScope(mapping, folderLocalSubject, out var scope)) return false;
try { return _policy.AuthorizeLocal(identity, OpcUaOperation.CreateMonitoredItems, scope); }
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; }
}
/// <summary>The local scope of a placement's folder: the mapping's local scope plus the folder's path below the anchor.</summary>
internal static bool TryFolderScope(ProjectedMappingPlacement mapping, string folderLocalSubject, out NodeScope scope)
{
scope = mapping.Scope;
var anchor = string.Join('/', mapping.Scope.Segments);
if (string.Equals(folderLocalSubject, anchor, StringComparison.Ordinal)) return true;
if (!folderLocalSubject.StartsWith(anchor + "/", StringComparison.Ordinal)) return false;
var below = folderLocalSubject[(anchor.Length + 1)..].Split('/');
if (below.Any(string.IsNullOrEmpty)) return false;
scope = mapping.Scope with { Segments = Array.AsReadOnly(mapping.Scope.Segments.Concat(below).ToArray()) };
return true;
}
/// <inheritdoc />
public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller)
{
lock (_gate)
{
if (_disposed) return null;
_demand++;
_linger?.Dispose(); _linger = null;
ReconcileRunners();
}
return new DemandLease(this);
}
private void ReleaseDemand()
{
lock (_gate)
{
if (_disposed || --_demand > 0) return;
_linger?.Dispose();
_linger = _clock.CreateTimer(_ => OnLingerExpired(), null, _options.Linger, Timeout.InfiniteTimeSpan);
}
}
private void OnLingerExpired()
{
List<ConnectionRunner> stopped;
lock (_gate)
{
if (_disposed || _demand > 0) return;
stopped = _runners.Values.ToList();
_runners.Clear();
foreach (var runner in stopped) { runner.Stop(removeConditions: true); Park(runner); }
ReleaseHeld(_ => true);
}
}
/// <summary>A4 review r2 S2: the hold bound — a still-held runner (the same one) is released once <see cref="ProjectedConditionOptions.MaxHold"/> passes.</summary>
private void OnHoldExpired(string connectionId, ConnectionRunner runner)
{
lock (_gate)
{
if (_disposed || !_held.TryGetValue(connectionId, out var held) || !ReferenceEquals(held, runner)) return;
_log.LogWarning("Imported conditions: connection {Connection} held for an undecided deploy longer than {MaxHold}; releasing its conditions",
connectionId, _options.MaxHold);
ReleaseHeld(id => string.Equals(id, connectionId, StringComparison.OrdinalIgnoreCase));
}
}
/// <summary>A4 F1–F3, under _gate: releases (removes the conditions of) the held runners <paramref name="release"/> selects.</summary>
private void ReleaseHeld(Func<string, bool> release)
{
foreach (var id in _held.Keys.Where(release).ToList())
{
_held.TryRemove(id, out var held);
held!.ReleaseHeld();
Park(held);
}
}
private void OnMappingsChanged()
{
Interlocked.Increment(ref _mappingVersion);
lock (_gate)
{
if (_disposed) return;
ReconcileRunners();
// A4 review r2 S2: a held connection keeps its counters (it is still reported, as "held").
var retained = _mappings.Current.Select(x => x.Mapping.DataConnectionId).ToHashSet(StringComparer.OrdinalIgnoreCase);
retained.UnionWith(_held.Keys);
Diagnostics.RetainConsumers(retained);
}
}
/// <summary>Starts a runner per condition-bearing connection while demand exists; restarts one whose mapping set changed. Under _gate.</summary>
private void ReconcileRunners()
{
// A4 review r2 S1: ONE consistent (placements, suspended) pair — a live flag next to an older list would release.
var (current, suspended) = _mappings.Snapshot;
var byConnection = current.Where(x => x.Authority.IsActive && IsConditionBearing(x.Mapping))
.GroupBy(x => x.Mapping.DataConnectionId, StringComparer.OrdinalIgnoreCase)
.ToDictionary(x => x.Key, x => OrderMappings(x).ToArray(), StringComparer.OrdinalIgnoreCase);
// A4 F1–F3: only a SETTLED set that no longer has the connection removes its held conditions.
if (!suspended) ReleaseHeld(id => !byConnection.ContainsKey(id) || _demand <= 0);
if (_demand <= 0) return;
foreach (var id in _runners.Keys.Where(id => !byConnection.ContainsKey(id)).ToList())
{
_runners.TryRemove(id, out var gone);
if (suspended)
{
// A4 F1–F3: every deploy begins with an empty, undecided set. Removing here tore down every imported condition
// and re-created it after the deploy (a fresh node ⇒ a phantom event per condition, new EventIds, the old ones
// BadEventIdUnknown, and the removal's RefreshRequired gated away because nothing was visible any more). Hold:
// the next runner of this connection takes the conditions over and re-snapshots onto them.
gone!.Stop(removeConditions: false);
// A4 review r2 S2: bounded — stale on the connection's stale timeout, released past MaxHold.
gone.Hold(_clock.CreateTimer(_ => OnHoldExpired(id, gone), null, _options.MaxHold, Timeout.InfiniteTimeSpan));
_held[id] = gone;
continue;
}
gone!.Stop(removeConditions: true);
Park(gone);
}
foreach (var (id, mappings) in byConnection)
{
var signature = Signature(mappings);
if (_runners.TryGetValue(id, out var running))
{
if (running.Signature == signature) continue;
// A changed mapping set: a new stream with a complete snapshot. ConditionIds never change (N4); placements,
// notifiers and SourceName follow the new set at its barrier.
running.Stop(removeConditions: false);
}
// S3/S4: the predecessor (still running or still removing) hands over only after it has fully stopped.
ConnectionRunner? held = null;
if (running is null && _held.TryRemove(id, out held)) held.EndHold(); // under _gate: no stale mark lands after this
var predecessor = running ?? held ?? (_stopping.Remove(id, out var stopping) ? stopping : null);
// A4 review r2 S3: a runner that takes a HELD set over tells clients to refresh once at its first barrier.
var runner = new ConnectionRunner(this, id, mappings, signature, predecessor, tookOverHeld: held is not null);
_runners[id] = runner;
runner.Start();
}
}
/// <summary>
/// Under _gate: parks a removing runner so the connection's next runner awaits its removal (S3/S4). #931 N8: the entry
/// is dropped once that removal has finished — a removing stop hands over an empty set, so nothing is left to wait for,
/// and a connection that never returns no longer pins its last runner.
/// </summary>
private void Park(ConnectionRunner runner)
{
_stopping[runner.ConnectionId] = runner;
runner.Stopped.ContinueWith(_ =>
{
lock (_gate)
if (_stopping.TryGetValue(runner.ConnectionId, out var parked) && ReferenceEquals(parked, runner)) _stopping.Remove(runner.ConnectionId);
}, TaskScheduler.Default);
}
/// <summary>Test observation (#931 N8): whether a stopped runner of the connection is still parked.</summary>
public bool IsParked(string connectionId)
{
lock (_gate) return _stopping.ContainsKey(connectionId);
}
/// <summary>§5.2: Raw mappings before UNS, then mapping id ordinal (deployed configuration only).</summary>
internal static IEnumerable<ProjectedMappingPlacement> OrderMappings(IEnumerable<ProjectedMappingPlacement> mappings) =>
mappings.OrderBy(x => x.Mapping.Realm == DataRealm.Raw ? 0 : 1)
.ThenBy(x => x.Mapping.RemoteNamespaceMappingId, StringComparer.Ordinal);
private static string Signature(IEnumerable<ProjectedMappingPlacement> mappings) =>
string.Join('|', mappings.Select(x => $"{x.Mapping.RemoteNamespaceMappingId}:{x.Mapping.Revision}:{x.Mapping.MaxConditions}:{x.Anchor.Subject}"));
/// <summary>Test/diagnostic observation: a connection's mapping statuses (null when no runner).</summary>
public IReadOnlyDictionary<string, ProjectedConditionMappingStatus>? MappingStatuses(string connectionId)
{
lock (_gate) return _runners.TryGetValue(connectionId, out var runner) ? runner.Statuses : null;
}
/// <summary>Test/diagnostic observation: imported conditions charged against the node-wide host caps (review r1 B4).</summary>
public long ChargedConditions => _ledger.Total;
/// <summary>Test observation: whether a connection has an open runner.</summary>
public bool IsRunning(string connectionId)
{
lock (_gate) return _runners.ContainsKey(connectionId);
}
/// <summary>Test observation (verification r2 N1): a weak reference to the connection's current (or still stopping) runner.</summary>
public WeakReference? RunnerReference(string connectionId)
{
lock (_gate)
return _runners.TryGetValue(connectionId, out var runner) || _stopping.TryGetValue(connectionId, out runner) ? new WeakReference(runner) : null;
}
/// <summary>Test observation: snapshot barriers a connection completed.</summary>
public int BarriersCompleted(string connectionId)
{
lock (_gate) return _runners.TryGetValue(connectionId, out var runner) ? runner.Barriers : 0;
}
public void Dispose()
{
List<ConnectionRunner> runners;
lock (_gate)
{
if (_disposed) return;
_disposed = true;
_linger?.Dispose();
runners = _runners.Values.ToList();
_runners.Clear();
// Review r2 NIT: the held runners are already stopped; end their hold timers and drop them.
foreach (var held in _held.Values) held.EndHold();
_held.Clear();
}
_mappings.Changed -= OnMappingsChanged;
foreach (var runner in runners) runner.Stop(removeConditions: false);
}
private sealed class DemandLease(ProjectedConditionAccess owner) : IDisposable
{
private int _disposed;
public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) owner.ReleaseDemand(); }
}
}