diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs new file mode 100644 index 000000000..8d2ed3ce0 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs @@ -0,0 +1,624 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +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; + +/// A3: the deployed mapping placements the condition runtime reads (an adapter over ). +public interface IProjectedConditionMappings +{ + /// The currently published placements (copies; read on change only). + IReadOnlyList Current { get; } + + /// Raised after the published placement set changes. + event Action? Changed; +} + +/// The production adapter over . +public sealed class DeployedConditionMappings : IProjectedConditionMappings +{ + private readonly ProjectedMappingDeploymentRuntime _runtime; + private volatile IReadOnlyList _current; + + public DeployedConditionMappings(ProjectedMappingDeploymentRuntime runtime) + { + _runtime = runtime ?? throw new ArgumentNullException(nameof(runtime)); + _current = runtime.Active; + runtime.Changed += placements => { _current = placements; Changed?.Invoke(); }; + } + + public IReadOnlyList Current => _current; + public event Action? Changed; +} + +/// A3 host limits (§5.5 "Budget"). +/// How long a connection's condition items stay open after the last event item goes (default 30 s). +/// Per consumer node (default 122,500 = 2,500 × 49). +/// Per consumer node (default 400 MiB; provisional until L2). +/// Pause before re-opening an ended condition stream. +public sealed record ProjectedConditionOptions(TimeSpan Linger, int MaxImportedConditionNodes, long MaxImportedConditionBytes, + TimeSpan ReconnectDelay) +{ + /// Counted, not estimated (plan §5.5 table): the worst case per condition. + public const int NodesPerCondition = 49; + /// Measured retained managed size per condition (≈ 157 KiB, SDK 2.0.1). + public const long BytesPerCondition = 160_997; + + public static ProjectedConditionOptions Default { get; } = + new(TimeSpan.FromSeconds(30), 122_500, 400L * 1024 * 1024, TimeSpan.FromSeconds(1)); +} + +/// Why a condition-bearing mapping is not contributing conditions. +public enum ProjectedConditionMappingStatus { Pending, Snapshotting, Complete, Unavailable, ConditionCapacity } + +/// +/// A3 (plan §5.4, §5.5): the consumer's condition runtime. +/// +/// Gate (): the mapping gate for CreateMonitoredItems 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 Security:Acl:Enabled. +/// Demand: 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 . +/// Barrier + budget: total > MaxConditions ⇒ that mapping is +/// 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). +/// Versions: per key and epoch; a removed record and a snapshot begin bypass the gate; a removal is +/// applied unconditionally and forgets the key's version. +/// Lifetime: a stream end is "re-snapshot", never "conditions removed"; only a COMPLETE re-snapshot that +/// no longer lists a key removes it. Past ConditionStaleTimeoutMilliseconds without a stream the conditions go +/// BadNoCommunication (one event each) — never "known inactive" (§5.1 T2). +/// +/// +public sealed class ProjectedConditionAccess : IProjectedConditionAccess, IDisposable +{ + private readonly IProjectedConditionMappings _mappings; + private readonly IGrpcDataAdapterConnectionSource _connections; + private readonly DataOperationPolicy _policy; + private readonly Func _sink; + private readonly TimeProvider _clock; + private readonly ProjectedConditionOptions _options; + private readonly ILogger _log; + private readonly object _gate = new(); + private readonly Dictionary _runners = new(StringComparer.OrdinalIgnoreCase); + private int _demand; + private long _mappingVersion = 1; + private ITimer? _linger; + private bool _disposed; + + public ProjectedConditionAccess(IProjectedConditionMappings mappings, IGrpcDataAdapterConnectionSource connections, + DataOperationPolicy policy, Func sink, TimeProvider clock, ProjectedConditionOptions? options = null, + ILogger? logger = null) + { + _mappings = mappings ?? throw new ArgumentNullException(nameof(mappings)); + _connections = connections ?? throw new ArgumentNullException(nameof(connections)); + _policy = policy ?? throw new ArgumentNullException(nameof(policy)); + _sink = sink ?? throw new ArgumentNullException(nameof(sink)); + _clock = clock ?? throw new ArgumentNullException(nameof(clock)); + _options = options ?? ProjectedConditionOptions.Default; + _log = logger ?? NullLogger.Instance; + _mappings.Changed += OnMappingsChanged; + } + + /// Whether a mapping is condition-bearing: enabled, Subscribe + AlarmSubscribe granted. + public static bool IsConditionBearing(RemoteNamespaceMapping mapping) => + mapping.Enabled && (mapping.AllowedOperations & (DataOperations.Subscribe | DataOperations.AlarmSubscribe)) + == (DataOperations.Subscribe | DataOperations.AlarmSubscribe); + + /// + public long AuthorityGeneration => unchecked((Interlocked.Read(ref _mappingVersion) << 32) ^ _policy.AuthorityEpoch); + + /// + public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList 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) + { + var mapping = current.FirstOrDefault(x => string.Equals(x.Mapping.RemoteNamespaceMappingId, placement.MappingId, StringComparison.OrdinalIgnoreCase)); + if (mapping is null || !mapping.Authority.IsActive || !IsConditionBearing(mapping.Mapping) || mapping.Mapping.Realm != placement.Realm) + continue; + if (!TryFolderScope(mapping, placement.FolderLocalSubject, out var scope)) continue; + try + { + if (_policy.AuthorizeLocal(identity, OpcUaOperation.CreateMonitoredItems, scope)) return true; + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { } + } + return false; + } + + /// The local scope of a placement's folder: the mapping's local scope plus the folder's path below the anchor. + 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; + } + + /// + 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 stopped; + lock (_gate) + { + if (_disposed || _demand > 0) return; + stopped = _runners.Values.ToList(); + _runners.Clear(); + } + foreach (var runner in stopped) runner.Stop(removeConditions: true); + } + + private void OnMappingsChanged() + { + Interlocked.Increment(ref _mappingVersion); + lock (_gate) + { + if (_disposed) return; + ReconcileRunners(); + } + } + + /// Starts a runner per condition-bearing connection while demand exists; restarts one whose mapping set changed. Under _gate. + private void ReconcileRunners() + { + if (_demand <= 0) return; + var byConnection = _mappings.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); + foreach (var id in _runners.Keys.Where(id => !byConnection.ContainsKey(id)).ToList()) + { + _runners.Remove(id, out var gone); + gone!.Stop(removeConditions: true); + } + 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); + } + var runner = new ConnectionRunner(this, id, mappings, signature, running?.TakeMaterialised()); + _runners[id] = runner; + runner.Start(); + } + } + + /// §5.2: Raw mappings before UNS, then mapping id ordinal (deployed configuration only). + internal static IEnumerable OrderMappings(IEnumerable mappings) => + mappings.OrderBy(x => x.Mapping.Realm == DataRealm.Raw ? 0 : 1) + .ThenBy(x => x.Mapping.RemoteNamespaceMappingId, StringComparer.Ordinal); + + private static string Signature(IEnumerable mappings) => + string.Join('|', mappings.Select(x => $"{x.Mapping.RemoteNamespaceMappingId}:{x.Mapping.Revision}:{x.Mapping.MaxConditions}:{x.Anchor.Subject}")); + + /// Test/diagnostic observation: a connection's mapping statuses (null when no runner). + public IReadOnlyDictionary? MappingStatuses(string connectionId) + { + lock (_gate) return _runners.TryGetValue(connectionId, out var runner) ? runner.Statuses : null; + } + + /// Test observation: whether a connection has an open runner. + public bool IsRunning(string connectionId) + { + lock (_gate) return _runners.ContainsKey(connectionId); + } + + /// Test observation: snapshot barriers a connection completed. + public int BarriersCompleted(string connectionId) + { + lock (_gate) return _runners.TryGetValue(connectionId, out var runner) ? runner.Barriers : 0; + } + + public void Dispose() + { + List runners; + lock (_gate) + { + if (_disposed) return; + _disposed = true; + _linger?.Dispose(); + runners = _runners.Values.ToList(); + _runners.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(); } + } + + // ----------------------------------------------------------------------------------------------------------------- + // One connection: one stream, one root item per condition-bearing mapping + // ----------------------------------------------------------------------------------------------------------------- + + private sealed class MappingState(ProjectedMappingPlacement placement) + { + public ProjectedMappingPlacement Placement { get; } = placement; + public string MappingId => Placement.Mapping.RemoteNamespaceMappingId; + public DataView Root { get; } = new(placement.Anchor.Address, placement.Mapping.Realm, null, 0, placement.Anchor.Address.Identifier); + public string? RootSubject { get; set; } + public ulong? Handle { get; set; } + public ProjectedConditionMappingStatus Status { get; set; } = ProjectedConditionMappingStatus.Pending; + public int Total { get; set; } + /// The mapping's current records by key (the complete snapshot, then deltas). + public Dictionary Records { get; } = new(StringComparer.Ordinal); + public Dictionary Infos { get; } = new(StringComparer.Ordinal); + public Dictionary Versions { get; } = new(StringComparer.Ordinal); + public bool Contributes => Status == ProjectedConditionMappingStatus.Complete; + } + + private sealed class ConnectionRunner + { + private readonly ProjectedConditionAccess _owner; + private readonly string _connectionId; + private readonly ProjectedMappingPlacement[] _mappings; + private readonly CancellationTokenSource _stop = new(); + private readonly object _statusGate = new(); + private Task _loop = Task.CompletedTask; + private MappingState[] _states = []; + /// Keys currently materialised at the sink (owned by the loop; handed over on a restart). + private HashSet _materialised; + private ITimer? _stale; + private int _barriers; + + public ConnectionRunner(ProjectedConditionAccess owner, string connectionId, ProjectedMappingPlacement[] mappings, string signature, + HashSet? materialised) + { + _owner = owner; _connectionId = connectionId; _mappings = mappings; Signature = signature; + _materialised = materialised ?? new HashSet(StringComparer.Ordinal); + } + + public string Signature { get; } + public int Barriers => Volatile.Read(ref _barriers); + + public IReadOnlyDictionary Statuses + { + get { lock (_statusGate) return _states.ToDictionary(x => x.MappingId, x => x.Status, StringComparer.OrdinalIgnoreCase); } + } + + public void Start() => _loop = Task.Run(() => RunAsync(_stop.Token)); + + public HashSet TakeMaterialised() + { + var taken = _materialised; + _materialised = new HashSet(StringComparer.Ordinal); + return taken; + } + + public void Stop(bool removeConditions) + { + _stop.Cancel(); + _stale?.Dispose(); + if (!removeConditions) return; + _ = _loop.ContinueWith(_ => + { + var keys = _materialised.ToArray(); + if (keys.Length > 0 && _owner._sink() is { } sink) sink.RemoveConditions(_connectionId, keys); + _materialised.Clear(); + }, TaskScheduler.Default); + } + + private async Task RunAsync(CancellationToken ct) + { + var epoch = 0L; + while (!ct.IsCancellationRequested) + { + epoch++; + try { await RunStreamAsync(epoch, ct).ConfigureAwait(false); } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; } + catch (Exception ex) + { + _owner._log.LogInformation(ex, "Imported conditions: stream for connection {Connection} ended; re-snapshotting", _connectionId); + } + // §5.5 lifetime rule: a stream end is "re-snapshot", never "conditions removed". Arm staleness instead. + ArmStale(); + OtOpcUaTelemetry.DataConnConditionResyncs.Add(1); + try { await Task.Delay(_owner._options.ReconnectDelay, _owner._clock, ct).ConfigureAwait(false); } + catch (OperationCanceledException) { return; } + } + } + + private void ArmStale() + { + if (_stale is not null || _materialised.Count == 0) return; + var timeout = TimeSpan.FromMilliseconds(Math.Max(1, _mappings.Min(x => x.Mapping.ConditionStaleTimeoutMilliseconds))); + _stale = _owner._clock.CreateTimer(_ => + { + if (!_stop.IsCancellationRequested) _owner._sink()?.MarkConnectionStale(_connectionId); + }, null, timeout, Timeout.InfiniteTimeSpan); + } + + private void DisarmStale() + { + _stale?.Dispose(); + _stale = null; + } + + private async Task RunStreamAsync(long epoch, CancellationToken ct) + { + var states = _mappings.Select(x => new MappingState(x)).ToArray(); + lock (_statusGate) _states = states; + await using var lease = await _owner._connections.AcquireAsync(_connectionId, ct).ConfigureAwait(false) + ?? throw new InvalidOperationException("Connection unavailable."); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, lease.CancellationToken); + var token = linked.Token; + var connection = lease.Connection; + // The remote root's origin subject: placement addresses are made relative to it (SourceName, folder subject). + try + { + var budget = new DataBudget(TimeSpan.FromSeconds(10), Math.Max(1, states.Length), 1024 * 1024); + var metadata = await connection.GetMetadataAsync(new MetadataRequest(states.Select(x => x.Root).ToArray(), budget), token) + .ConfigureAwait(false); + for (var i = 0; i < states.Length && i < metadata.Count; i++) + if (metadata[i] is { Status: DataItemStatus.Good, Value: { } root }) states[i].RootSubject = root.View.Subject; + } + catch (Exception ex) when (ex is not OperationCanceledException) { } + + await using var subscription = await connection.SubscribeAsync(token).ConfigureAwait(false); + var subscriptionId = "conditions-" + Guid.NewGuid().ToString("N"); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + var items = states.Select(x => new DataSubscriptionItem(x.MappingId, x.Root, settings, new DataConditionScope(IncludeInfo: true))).ToArray(); + await subscription.SendAsync(new OpenSubscription(subscriptionId, epoch, "open", TimeSpan.FromSeconds(30), items, false, + TimeSpan.FromMinutes(60), new DataBudget(TimeSpan.FromSeconds(30), 1000, 4 * 1024 * 1024)), token).ConfigureAwait(false); + + var snapshotTimeout = TimeSpan.FromMilliseconds(Math.Max(1, states.Max(x => x.Placement.Mapping.ConditionSnapshotTimeoutMilliseconds))); + var barrierPassed = false; + _timedOut = false; + var timeout = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var barrierTimer = _owner._clock.CreateTimer(_ => + { + // ConditionSnapshotTimeoutMilliseconds: the incomplete mappings are Unavailable and the rest proceed. + lock (_statusGate) + foreach (var s in states.Where(s => s.Status is ProjectedConditionMappingStatus.Pending or ProjectedConditionMappingStatus.Snapshotting)) + s.Status = ProjectedConditionMappingStatus.Unavailable; + _timedOut = true; + timeout.TrySetResult(); + }, null, snapshotTimeout, Timeout.InfiniteTimeSpan); + + await using var frames = subscription.ReadAllAsync(token).GetAsyncEnumerator(token); + Task? next = null; + while (true) + { + next ??= frames.MoveNextAsync().AsTask(); + if (!barrierPassed && !timeout.Task.IsCompleted + && await Task.WhenAny(next, timeout.Task).ConfigureAwait(false) != next) + { + barrierPassed = TryPassBarrier(states); + continue; + } + if (!barrierPassed && timeout.Task.IsCompleted && !next.IsCompleted) + { + barrierPassed = TryPassBarrier(states); + if (!barrierPassed) { await next.ConfigureAwait(false); } + else continue; + } + if (!await next.ConfigureAwait(false)) return; + next = null; + var changed = await ProcessAsync(frames.Current, states, subscription, subscriptionId, epoch, token).ConfigureAwait(false); + if (!barrierPassed) { barrierPassed = TryPassBarrier(states); continue; } + if (changed.Count > 0) Publish(states, changed); + } + } + + private bool TryPassBarrier(MappingState[] states) + { + lock (_statusGate) + if (states.Any(x => x.Status is ProjectedConditionMappingStatus.Pending or ProjectedConditionMappingStatus.Snapshotting)) return false; + Interlocked.Increment(ref _barriers); + DisarmStale(); + PassBarrier(states); + if (_timedOut) _owner._sink()?.RequireRefresh(_connectionId); // an incomplete (re)snapshot + return true; + } + + private async Task> ProcessAsync(DataSubscriptionFrame frame, MappingState[] states, IDataSubscription subscription, + string subscriptionId, long epoch, CancellationToken token) + { + var changed = new HashSet(StringComparer.Ordinal); + switch (frame) + { + case DataSubscriptionAck ack: + foreach (var itemAck in ack.Items) + { + var state = states.FirstOrDefault(x => x.MappingId == itemAck.ClientItemId); + if (state is null) continue; + lock (_statusGate) + { + if (itemAck.Status == DataItemStatus.Good && itemAck.Handle is { } handle) state.Handle = handle.Handle; + else if (state.Status != ProjectedConditionMappingStatus.ConditionCapacity) state.Status = ProjectedConditionMappingStatus.Unavailable; + } + } + break; + case DataSubscriptionConditions conditions: + var mapping = states.FirstOrDefault(x => x.Handle == conditions.Handle.Handle); + if (mapping is null || mapping.Status is ProjectedConditionMappingStatus.Unavailable or ProjectedConditionMappingStatus.ConditionCapacity) break; + if (conditions.IsSnapshot && conditions.Total is { } total) + { + if (!Admit(mapping, total, states)) + { + // §5.5: the over-limit item is REMOVED (it costs an item slot and the origin's re-listing). + await subscription.SendAsync(new RemoveSubscriptionItems(subscriptionId, epoch, "remove-" + mapping.MappingId, + TimeSpan.FromSeconds(30), [conditions.Handle]), token).ConfigureAwait(false); + foreach (var key in mapping.Records.Keys) changed.Add(key); + mapping.Records.Clear(); + break; + } + // A snapshot begin bypasses the version gate: it resets every key. + foreach (var key in mapping.Records.Keys) changed.Add(key); + mapping.Records.Clear(); mapping.Versions.Clear(); + lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.Snapshotting; + } + foreach (var record in conditions.Items) + { + if (!ImportedConditionIds.IsWellFormedConditionKey(record.ConditionKey)) continue; + if (record.Info is { } info) mapping.Infos[record.ConditionKey] = info; + if (record.Removed) + { + // A removal is applied unconditionally and forgets the key's version. + mapping.Records.Remove(record.ConditionKey); + mapping.Versions.Remove(record.ConditionKey); + changed.Add(record.ConditionKey); + continue; + } + if (mapping.Versions.TryGetValue(record.ConditionKey, out var last) && record.Version <= last) continue; + mapping.Versions[record.ConditionKey] = record.Version; + mapping.Records[record.ConditionKey] = record; + changed.Add(record.ConditionKey); + } + if (conditions.SnapshotComplete) + lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.Complete; + break; + } + return changed; + } + + private volatile bool _timedOut; + + /// §5.5 admission at snapshot begin: the mapping limit, then the host caps (deployed order). + private bool Admit(MappingState mapping, int total, MappingState[] states) + { + mapping.Total = total; + if (total > mapping.Placement.Mapping.MaxConditions) + { + lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.ConditionCapacity; + OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1); + _owner._log.LogWarning("Imported conditions: mapping {Mapping} lists {Total} conditions, over its MaxConditions {Max} — Unavailable(ConditionCapacity)", + mapping.MappingId, total, mapping.Placement.Mapping.MaxConditions); + return false; + } + // Host caps: conditions are charged once per key; before materialising, `total` is the bound. Mappings earlier in + // deployed order are charged first. + long charged = 0; + foreach (var other in states) + { + if (ReferenceEquals(other, mapping)) break; + if (other.Status is ProjectedConditionMappingStatus.Snapshotting or ProjectedConditionMappingStatus.Complete) charged += other.Total; + } + var after = charged + total; + if (after * ProjectedConditionOptions.NodesPerCondition > _owner._options.MaxImportedConditionNodes + || after * ProjectedConditionOptions.BytesPerCondition > _owner._options.MaxImportedConditionBytes) + { + lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.ConditionCapacity; + OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1); + _owner._log.LogWarning("Imported conditions: mapping {Mapping} ({Total}) would cross the host condition caps — Unavailable(ConditionCapacity)", + mapping.MappingId, total); + return false; + } + if (after * ProjectedConditionOptions.NodesPerCondition > _owner._options.MaxImportedConditionNodes * 8L / 10) + _owner._log.LogWarning("Imported conditions: host condition budget above 80% ({Count} conditions)", after); + return true; + } + + /// The barrier: materialise the union; a key the previous materialisation held but this complete set lacks is removed. + private void PassBarrier(MappingState[] states) + { + var keys = states.Where(x => x.Contributes).SelectMany(x => x.Records.Keys).ToHashSet(StringComparer.Ordinal); + var gone = _materialised.Where(k => !keys.Contains(k)).ToArray(); + // Only a key no complete mapping lists is removed; a key of a mapping that did not complete is kept (unknown ≠ gone). + var incomplete = states.Any(x => !x.Contributes && x.Status != ProjectedConditionMappingStatus.ConditionCapacity); + if (gone.Length > 0 && !incomplete && _owner._sink() is { } sink) + { + sink.RemoveConditions(_connectionId, gone); + foreach (var key in gone) _materialised.Remove(key); + } + Publish(states, keys); + } + + private void Publish(MappingState[] states, IEnumerable keys) + { + if (_owner._sink() is not { } sink) return; + var updates = new List(); + var removals = new List(); + foreach (var key in keys) + { + var update = Merge(states, key); + if (update is null) + { + if (_materialised.Remove(key)) removals.Add(key); + continue; + } + updates.Add(update); + _materialised.Add(key); + } + if (removals.Count > 0) sink.RemoveConditions(_connectionId, removals); + if (updates.Count > 0) sink.ApplyConditions(updates); + } + + /// One key across the connection's complete mappings: placements (primary first), latest record, SourceName. + private ImportedConditionUpdate? Merge(MappingState[] states, string key) + { + DataConditionState? latest = null; + DataConditionInfo? info = null; + var placements = new List<(int Order, ImportedConditionPlacement Placement)>(); + for (var i = 0; i < states.Length; i++) + { + var state = states[i]; + if (!state.Contributes || !state.Records.TryGetValue(key, out var record)) continue; + if (latest is null || record.Version > latest.Version) latest = record; + if (state.Infos.TryGetValue(key, out var stateInfo)) info ??= stateInfo; + if (!state.Infos.TryGetValue(key, out var placementInfo)) continue; + foreach (var view in placementInfo.Placements.Where(p => p.Realm == state.Placement.Mapping.Realm) + .OrderBy(p => p.Address.Identifier, StringComparer.Ordinal)) + placements.Add((i, ToPlacement(state, view))); + } + if (latest is null || placements.Count == 0) return null; + var ordered = placements.OrderBy(x => x.Order).Select(x => x.Placement).ToArray(); + var primary = ordered[0]; + var anchor = states[placements.Min(x => x.Order)].Placement.Anchor.Subject; + return new ImportedConditionUpdate(_connectionId, latest, info, ordered, anchor + "/" + primary.RelativePath); + } + + private static ImportedConditionPlacement ToPlacement(MappingState state, DataView view) + { + var relative = view.Subject; + if (state.RootSubject is { Length: > 0 } root && relative.StartsWith(root + "/", StringComparison.Ordinal)) + relative = relative[(root.Length + 1)..]; + var cut = relative.LastIndexOf('/'); + var anchor = state.Placement.Anchor.Subject; + var folder = cut < 0 ? anchor : anchor + "/" + relative[..cut]; + return new ImportedConditionPlacement(state.MappingId, state.Placement.Mapping.Realm, view, folder, relative); + } + } +}