fix(grpc-data): A3a review r1 — buffered in-stream re-snapshots, late completion + stale-on-incomplete + bounded retry, Primary-pinned condition streams, node-wide host-cap ledger, runner hand-over after stop, metadata failure Unavailable; NM: revalidation through the imported gate, demand released first, rebuild unwires, instance-keyed promotion, incremental folder index, verdict TTL + expiry, removal RefreshRequired, chunked refresh/replay, folder-only demand
Runtime tests: B1 multi-frame + capacity re-snapshot, B2 late completion / stale-on-incomplete / refused retry, B4 cross-connection / reverse order / records>total / delta growth, S3/S4 hand-over, S6, deviation 9, S2 IsActive generation; absence assertions now follow must-arrive controls.
This commit is contained in:
@@ -95,6 +95,10 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
|
||||
private readonly ILogger _log;
|
||||
private readonly object _gate = new();
|
||||
private readonly Dictionary<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);
|
||||
private readonly ConditionLedger _ledger;
|
||||
private int _demand;
|
||||
private long _mappingVersion = 1;
|
||||
private ITimer? _linger;
|
||||
@@ -111,6 +115,7 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_options = options ?? ProjectedConditionOptions.Default;
|
||||
_log = logger ?? NullLogger.Instance;
|
||||
_ledger = new ConditionLedger(_options);
|
||||
_mappings.Changed += OnMappingsChanged;
|
||||
}
|
||||
|
||||
@@ -123,7 +128,16 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
|
||||
== (DataOperations.Subscribe | DataOperations.AlarmSubscribe);
|
||||
|
||||
/// <inheritdoc />
|
||||
public long AuthorityGeneration => unchecked((Interlocked.Read(ref _mappingVersion) << 32) ^ _policy.AuthorityEpoch);
|
||||
/// <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)
|
||||
@@ -132,20 +146,30 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
|
||||
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) { }
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
@@ -190,8 +214,8 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
|
||||
if (_disposed || _demand > 0) return;
|
||||
stopped = _runners.Values.ToList();
|
||||
_runners.Clear();
|
||||
foreach (var runner in stopped) { runner.Stop(removeConditions: true); _stopping[runner.ConnectionId] = runner; }
|
||||
}
|
||||
foreach (var runner in stopped) runner.Stop(removeConditions: true);
|
||||
}
|
||||
|
||||
private void OnMappingsChanged()
|
||||
@@ -215,6 +239,7 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
|
||||
{
|
||||
_runners.Remove(id, out var gone);
|
||||
gone!.Stop(removeConditions: true);
|
||||
_stopping[id] = gone;
|
||||
}
|
||||
foreach (var (id, mappings) in byConnection)
|
||||
{
|
||||
@@ -226,7 +251,9 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
|
||||
// notifiers and SourceName follow the new set at its barrier.
|
||||
running.Stop(removeConditions: false);
|
||||
}
|
||||
var runner = new ConnectionRunner(this, id, mappings, signature, running?.TakeMaterialised());
|
||||
// S3/S4: the predecessor (still running or still removing) hands over only after it has fully stopped.
|
||||
var predecessor = running ?? (_stopping.Remove(id, out var stopping) ? stopping : null);
|
||||
var runner = new ConnectionRunner(this, id, mappings, signature, predecessor);
|
||||
_runners[id] = runner;
|
||||
runner.Start();
|
||||
}
|
||||
@@ -246,6 +273,9 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
|
||||
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)
|
||||
{
|
||||
@@ -278,386 +308,4 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
|
||||
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;
|
||||
// The origin view of the remote root, built exactly as RemoteNamespaceResolver builds it (subject = the mapping's
|
||||
// RemoteRootEntityId): a UNS root's address identifier is an opaque id, and the origin refuses a root item whose subject
|
||||
// is not its own (live a3b-cond-2: map-uns item Denied).
|
||||
public DataView Root { get; } = new(placement.Anchor.Address, placement.Mapping.Realm, null, 0,
|
||||
string.IsNullOrWhiteSpace(placement.Mapping.RemoteRootEntityId) ? placement.Anchor.Address.Identifier : placement.Mapping.RemoteRootEntityId);
|
||||
public string? RootSubject { get; set; }
|
||||
/// <summary>The origin's canonical view of the remote root (from metadata): the root item must carry the origin's own
|
||||
/// subject — a view built from the address alone (subject = identifier) is refused for an opaque-id UNS root.</summary>
|
||||
public DataView? RootView { get; set; }
|
||||
public ulong? Handle { get; set; }
|
||||
public ProjectedConditionMappingStatus Status { get; set; } = ProjectedConditionMappingStatus.Pending;
|
||||
public int Total { get; set; }
|
||||
/// <summary>The mapping's current records by key (the complete snapshot, then deltas).</summary>
|
||||
public Dictionary<string, DataConditionState> Records { get; } = new(StringComparer.Ordinal);
|
||||
public Dictionary<string, DataConditionInfo> Infos { get; } = new(StringComparer.Ordinal);
|
||||
public Dictionary<string, long> 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 = [];
|
||||
/// <summary>Keys currently materialised at the sink (owned by the loop; handed over on a restart).</summary>
|
||||
private HashSet<string> _materialised;
|
||||
private ITimer? _stale;
|
||||
private int _barriers;
|
||||
|
||||
public ConnectionRunner(ProjectedConditionAccess owner, string connectionId, ProjectedMappingPlacement[] mappings, string signature,
|
||||
HashSet<string>? materialised)
|
||||
{
|
||||
_owner = owner; _connectionId = connectionId; _mappings = mappings; Signature = signature;
|
||||
_materialised = materialised ?? new HashSet<string>(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
public string Signature { get; }
|
||||
public int Barriers => Volatile.Read(ref _barriers);
|
||||
private ServingIdentity? _serving;
|
||||
/// <summary>A3b: the serving identity of the CURRENT condition stream (null while no stream is open).</summary>
|
||||
public ServingIdentity? Serving => Volatile.Read(ref _serving);
|
||||
|
||||
public IReadOnlyDictionary<string, ProjectedConditionMappingStatus> 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<string> TakeMaterialised()
|
||||
{
|
||||
var taken = _materialised;
|
||||
_materialised = new HashSet<string>(StringComparer.Ordinal);
|
||||
return taken;
|
||||
}
|
||||
|
||||
public void Stop(bool removeConditions)
|
||||
{
|
||||
_stop.Cancel();
|
||||
Volatile.Write(ref _serving, null);
|
||||
_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);
|
||||
}
|
||||
finally { Volatile.Write(ref _serving, null); }
|
||||
// §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;
|
||||
states[i].RootView = root.View;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException) { }
|
||||
|
||||
await using var subscription = await connection.SubscribeAsync(token).ConfigureAwait(false);
|
||||
Volatile.Write(ref _serving, (subscription as IDataSubscriptionProvenance)?.Serving);
|
||||
_owner._log.LogInformation("Imported conditions: stream {Epoch} for connection {Connection} opened ({Mappings} mapping(s), serving {Serving})",
|
||||
epoch, _connectionId, states.Length, Serving?.NodeId ?? "(no provenance)");
|
||||
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.RootView ?? 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<bool>? 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();
|
||||
_owner._log.LogInformation("Imported conditions: connection {Connection} snapshot barrier passed ({Statuses}; {Records} record(s){TimedOut})",
|
||||
_connectionId, string.Join(", ", states.Select(x => x.MappingId + "=" + x.Status)), states.Where(x => x.Contributes).Sum(x => x.Records.Count),
|
||||
_timedOut ? "; snapshot timed out" : "");
|
||||
PassBarrier(states);
|
||||
if (_timedOut) _owner._sink()?.RequireRefresh(_connectionId); // an incomplete (re)snapshot
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task<HashSet<string>> ProcessAsync(DataSubscriptionFrame frame, MappingState[] states, IDataSubscription subscription,
|
||||
string subscriptionId, long epoch, CancellationToken token)
|
||||
{
|
||||
var changed = new HashSet<string>(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;
|
||||
}
|
||||
if (itemAck.Status != DataItemStatus.Good)
|
||||
_owner._log.LogWarning("Imported conditions: mapping {Mapping} item refused by the origin ({Status}: {Diagnostic})",
|
||||
state.MappingId, itemAck.Status, itemAck.Diagnostic);
|
||||
}
|
||||
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;
|
||||
|
||||
/// <summary>§5.5 admission at snapshot begin: the mapping limit, then the host caps (deployed order).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The barrier: materialise the union; a key the previous materialisation held but this complete set lacks is removed.</summary>
|
||||
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<string> keys)
|
||||
{
|
||||
if (_owner._sink() is not { } sink) return;
|
||||
var updates = new List<ImportedConditionUpdate>();
|
||||
var removals = new List<string>();
|
||||
foreach (var key in keys)
|
||||
{
|
||||
var update = Merge(states, key);
|
||||
if (update is null)
|
||||
{
|
||||
_owner._log.LogWarning("Imported conditions: connection {Connection} key has no placement in a complete mapping (not materialised)", _connectionId);
|
||||
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);
|
||||
if (updates.Count + removals.Count > 0)
|
||||
_owner._log.LogDebug("Imported conditions: connection {Connection} applied {Updates} update(s), {Removals} removal(s)",
|
||||
_connectionId, updates.Count, removals.Count);
|
||||
}
|
||||
|
||||
/// <summary>One key across the connection's complete mappings: placements (primary first), latest record, SourceName.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user