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:
Joseph Doherty
2026-11-24 18:38:07 -05:00
parent 3c941458f5
commit 69aeeb770b
11 changed files with 1242 additions and 529 deletions
@@ -148,6 +148,16 @@ public interface IDataSubscriptionFreshnessSupport
bool SupportsFreshnessChallenges { get; }
int FreshnessMaxItems { get; }
}
/// <summary>
/// A3 (review r1, deviation 9): a connection that can open a subscription served by the origin's <b>Primary</b> only —
/// condition items are served by the Primary (a Secondary advertises the feature but refuses the item, A2 N7), so the
/// consumer's condition stream must not land on a ReadyReplica Secondary the v1 value path would accept.
/// </summary>
public interface IDataPrimarySubscriptionSource
{
/// <summary>Like <see cref="IDataSubscriptionService.SubscribeAsync"/>, admitting only an endpoint whose serving role is Primary.</summary>
Task<IDataSubscription> SubscribePrimaryAsync(CancellationToken cancellationToken);
}
/// <summary>Immutable serving identity captured when the subscription was established.</summary>
public interface IDataSubscriptionProvenance
{
@@ -48,6 +48,10 @@ public interface IProjectedConditionSink
/// <summary>The connection is gone past its stale timeout: <c>Quality = BadNoCommunication</c>, one event each.</summary>
void MarkConnectionStale(string connectionId);
/// <summary>Review r1 B2: these conditions' state is unknown (their mapping did not complete a snapshot) —
/// <c>Quality = BadNoCommunication</c>, one event each, never removed and never "known inactive".</summary>
void MarkConditionsStale(string connectionId, IReadOnlyCollection<string> conditionKeys);
/// <summary>Sends <c>RefreshRequiredEventType</c> to every item that may see a condition of the connection.</summary>
void RequireRefresh(string connectionId);
}
@@ -65,6 +69,10 @@ public interface IProjectedConditionAccess
/// </summary>
bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements);
/// <summary>Deviation 3 (review r1): the mapping gate on one projected folder of a condition-bearing mapping — admits a
/// folder event item (and its demand) before any imported condition is wired there.</summary>
bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject);
/// <summary>A generation that moves whenever anything the gate reads may have changed (verdict caches key on it).</summary>
long AuthorityGeneration { get; }
@@ -5655,6 +5655,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
retiredProofs = _projectedSamples.Values.Select(sample => sample.Proof).Distinct().ToArray();
Volatile.Write(ref _committedProjectedDefinitions, _committedProjectedDefinitions.Clear());
foreach (var item in _liveItems.Keys.OfType<ProjectedMonitoredItem>()) item.Retire();
UnwireAllImportedFolders(); // A3 review r1 S1: the folders go; their notifier wiring and promotion go with them
foreach (var id in _projectedVariables.Keys) PredefinedNodes?.Remove(id);
foreach (var id in _projectedAnchors.Keys) PredefinedNodes?.Remove(id);
foreach (var (id, definition) in _projectedDefinitions) RetireProjectedCharge(id, definition.Lifetime);
@@ -6576,6 +6577,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
if (unsubscribe)
{
// A3 review r1 B3: the item's condition demand goes FIRST — both early returns below skip the base call, and a
// lease released only after them leaked (demand never reached 0, streams and conditions held forever).
TrackImportedDemand(monitoredItem, unsubscribe: true);
// An item RevalidateMonitoredItems stood down is ALREADY off its notifier's fan-out, and so is
// one whose notifier a rebuild / surgical remove tombstoned (review 01 L2, TombstoneMonitoredNode).
// Handing either delete to the SDK would make it remove an item that is not there — at best a
@@ -6599,7 +6604,6 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
}
}
TrackImportedDemand(monitoredItem, unsubscribe: true);
return base.SubscribeToEvents(context, sourceId, subscriptionId, monitoredItem, unsubscribe);
}
@@ -8753,8 +8757,13 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
foreach (var (item, tracked) in _eventItems)
{
var permitted = IsSubscriptionStillPermitted(
item.EffectiveIdentity as RoleCarryingUserIdentity, tracked.Handle.NodeId, verdicts);
// A3 review r1 B3: an item on a projected notifier was admitted through the imported gate, not Permits (which
// blanket-denies a mapped CreateMonitoredItems) — revalidate it through the same gate, or every admitted folder
// item is stood down on the next ACL tick or deploy.
var identity = item.EffectiveIdentity as RoleCarryingUserIdentity;
var permitted = IsProjectedEventNotifier(tracked.Handle.NodeId)
? ImportedNotifierAdmits(identity, tracked.Handle.NodeId)
: IsSubscriptionStillPermitted(identity, tracked.Handle.NodeId, verdicts);
if (permitted != tracked.Suppressed) continue;
lock (Lock)
@@ -21,6 +21,8 @@ internal sealed class ImportedCondition(AlarmConditionState alarm, string connec
public string ConditionKey { get; } = conditionKey;
public IReadOnlyList<ImportedConditionPlacement> Placements { get; set; } = [];
public HashSet<FolderState> Folders { get; } = new(ReferenceEqualityComparer.Instance);
/// <summary>NIT (review r1): an immutable copy of <see cref="Folders"/> for the delivery paths that read off <c>Lock</c>.</summary>
public FolderState[] WiredFolders { get; set; } = [];
/// <summary>The last origin record applied (state known), re-applied with another Quality on staleness.</summary>
public AlarmConditionSnapshot? Last { get; set; }
/// <summary>The marker of the latest applied record. Written under <see cref="MethodGate"/> (A3b reads it without <c>Lock</c>).</summary>
@@ -64,10 +66,17 @@ internal sealed class ProjectedConditionRegistry
private readonly ConcurrentDictionary<AlarmConditionState, ImportedCondition> _byInstance = new(ReferenceEqualityComparer.Instance);
/// <summary>(mapping, folder local subject) → conditions placed there (wired or waiting for the folder to materialise).</summary>
internal readonly Dictionary<(string Mapping, string Subject), HashSet<NodeId>> ByFolderKey = new();
/// <summary>Projected folder node → conditions wired into it.</summary>
internal readonly Dictionary<NodeId, HashSet<NodeId>> WiredByFolder = new();
/// <summary>Projected folder node → the folder INSTANCE promoted for it and the conditions wired into it (review r1 S1: a
/// re-created folder with the same NodeId is a different notifier and is promoted afresh).</summary>
internal readonly Dictionary<NodeId, (FolderState Folder, HashSet<NodeId> Conditions)> WiredByFolder = new();
/// <summary>Review r1 S5: (mapping, local subject) → projected folder NodeId, maintained incrementally (was a scan of every
/// projected node per apply chunk); resolved against the live projected maps at use.</summary>
internal readonly Dictionary<(string Mapping, string Subject), NodeId> FolderIds = new();
internal readonly Dictionary<NodeId, (string Mapping, string Subject)> FolderKeys = new();
/// <summary>Review r1 S2: a positive verdict is re-proved at least this often (credential expiry is honoured exactly).</summary>
internal static readonly TimeSpan PositiveVerdictTtl = TimeSpan.FromSeconds(5);
private readonly object _verdictGate = new();
private readonly Dictionary<(object Identity, NodeId Condition), (long Generation, long PlacementVersion, bool Allowed)> _verdicts = new();
private readonly Dictionary<(object Identity, NodeId Condition), (long Generation, long PlacementVersion, bool Allowed, DateTimeOffset ValidUntil)> _verdicts = new();
public int Count => _byNode.Count;
public IEnumerable<ImportedCondition> All => _byNode.Values;
@@ -76,7 +85,7 @@ internal sealed class ProjectedConditionRegistry
node is AlarmConditionState alarm && _byInstance.TryGetValue(alarm, out var c) ? c : null;
public ImportedCondition? Find(NodeId id) => _byNode.TryGetValue(id, out var c) ? c : null;
public bool IsWiredTo(ImportedCondition condition, NodeState notifier) =>
notifier is FolderState folder && condition.Folders.Contains(folder) && _byInstance.ContainsKey(condition.Alarm);
notifier is FolderState folder && Array.IndexOf(condition.WiredFolders, folder) >= 0 && _byInstance.ContainsKey(condition.Alarm);
public void Add(ImportedCondition condition)
{
@@ -96,20 +105,28 @@ internal sealed class ProjectedConditionRegistry
public static (string, string) FolderKey(ImportedConditionPlacement p) => (p.MappingId, p.FolderLocalSubject);
/// <summary>The §5.4 verdict, cached per (identity, condition, authority generation, placement version).</summary>
public bool Verdict(object identity, ImportedCondition condition, long generation, Func<bool> compute)
/// <summary>
/// The §5.4 verdict, cached per (identity, condition, authority generation, placement version). Review r1 S2: a positive
/// verdict also carries the caller's credential expiry and a short TTL — a Server-object item has no other revalidation,
/// so an expired key (or anything the generation does not capture) is never served from cache past either.
/// </summary>
public bool Verdict(object identity, ImportedCondition condition, long generation, DateTimeOffset now, DateTimeOffset? credentialExpires,
Func<bool> compute)
{
var key = (identity, condition.Alarm.NodeId);
lock (_verdictGate)
{
if (_verdicts.TryGetValue(key, out var cached) && cached.Generation == generation && cached.PlacementVersion == condition.PlacementVersion)
if (_verdicts.TryGetValue(key, out var cached) && cached.Generation == generation && cached.PlacementVersion == condition.PlacementVersion
&& now < cached.ValidUntil)
return cached.Allowed;
}
var allowed = compute();
var validUntil = !allowed ? DateTimeOffset.MaxValue
: credentialExpires is { } expires && expires < now + PositiveVerdictTtl ? expires : now + PositiveVerdictTtl;
lock (_verdictGate)
{
if (_verdicts.Count >= 65_536) _verdicts.Clear(); // bounded: a flood of identities only costs recomputation
_verdicts[key] = (generation, condition.PlacementVersion, allowed);
_verdicts[key] = (generation, condition.PlacementVersion, allowed, validUntil);
}
return allowed;
}
@@ -173,7 +190,8 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
if (ProjectedConditionAccess is not { } access || identity is not RoleCarryingUserIdentity caller) return false;
var generation = access.AuthorityGeneration;
var placements = condition.Placements;
return _importedConditions.Verdict(caller, condition, generation, () => access.CanSee(caller, placements));
return _importedConditions.Verdict(caller, condition, generation, DateTimeOffset.UtcNow, caller.CredentialExpiresUtc,
() => access.CanSee(caller, placements));
}
/// <summary>The marker a queued imported event carries: re-checked at every Publish and Republish (§5.4).</summary>
@@ -247,16 +265,15 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
{
ArgumentNullException.ThrowIfNull(updates);
EnsureAddressSpaceCreated();
var refresh = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var unbindable = new List<ImportedCondition>();
for (var start = 0; start < updates.Count; start += ImportedApplyChunk)
{
lock (Lock)
{
if (_disposing) return;
var index = ProjectedFolderIndex();
for (var i = start; i < Math.Min(updates.Count, start + ImportedApplyChunk); i++)
{
try { if (ApplyImported(updates[i], index)) refresh.Add(updates[i].ConnectionId); }
try { if (ApplyImported(updates[i]) is { } c) unbindable.Add(c); }
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or ServiceResultException)
{
_logger.LogWarning(ex, "OtOpcUaNodeManager: imported condition update refused (connection {Connection})",
@@ -265,32 +282,49 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
}
}
}
// N6 (G4 step 3): a resync that left retained EventIds un-re-bindable ⇒ RefreshRequired, outside Lock.
foreach (var connectionId in refresh) RequireRefresh(connectionId);
// N6 (G4 step 3): a resync that left retained EventIds un-re-bindable ⇒ RefreshRequired, outside Lock — only to the
// items that may see one of THOSE conditions (A3b open item, review r1).
if (unbindable.Count > 0) QueueImportedRefresh(unbindable);
}
/// <inheritdoc />
public void RemoveConditions(string connectionId, IReadOnlyCollection<string> conditionKeys)
{
var keys = conditionKeys.ToArray();
var removed = new List<ImportedCondition>();
var targets = new RefreshTargets();
for (var start = 0; start < keys.Length; start += ImportedApplyChunk)
{
lock (Lock)
{
var chunk = new List<ImportedCondition>();
foreach (var key in keys.Skip(start).Take(ImportedApplyChunk))
{
if (!ImportedConditionIds.IsWellFormedConditionKey(key)) continue;
if (_importedConditions.Find(ImportedConditionNodeId(connectionId, key)) is { } c) RemoveImported(c);
if (_importedConditions.Find(ImportedConditionNodeId(connectionId, key)) is { } c) chunk.Add(c);
}
// Deviation 6 (review r1): who may have been holding these conditions is captured BEFORE they are unwired.
CollectRefreshTargets(chunk, targets);
foreach (var c in chunk) RemoveImported(c);
removed.AddRange(chunk);
}
}
// §5.2 "removal + RefreshRequired": a client holding a removed (e.g. Active/Retain) condition is told to refresh, after
// which it no longer lists it. Outside Lock.
if (removed.Count > 0) QueueRefreshRequired(targets, removed);
}
/// <inheritdoc />
public void MarkConnectionStale(string connectionId)
public void MarkConnectionStale(string connectionId) =>
MarkStale(_importedConditions.All.Where(c => string.Equals(c.ConnectionId, connectionId, StringComparison.OrdinalIgnoreCase)).ToList());
/// <inheritdoc />
public void MarkConditionsStale(string connectionId, IReadOnlyCollection<string> conditionKeys) =>
MarkStale(conditionKeys.Where(ImportedConditionIds.IsWellFormedConditionKey)
.Select(key => _importedConditions.Find(ImportedConditionNodeId(connectionId, key))).OfType<ImportedCondition>().ToList());
private void MarkStale(List<ImportedCondition> targets)
{
List<ImportedCondition> targets;
lock (Lock) targets = _importedConditions.All.Where(c => string.Equals(c.ConnectionId, connectionId, StringComparison.OrdinalIgnoreCase)).ToList();
for (var start = 0; start < targets.Count; start += ImportedApplyChunk)
{
lock (Lock)
@@ -306,22 +340,62 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
}
/// <inheritdoc />
/// <remarks>
/// A connection with no materialised condition returns early: nothing of it can be held by a client (a removal tells
/// its own holders, captured before the removal — deviation 6, review r1).
/// </remarks>
public void RequireRefresh(string connectionId)
{
List<(IEventMonitoredItem Item, bool Allowed)> targets = [];
lock (Lock)
{
var conditions = _importedConditions.All.Where(c => string.Equals(c.ConnectionId, connectionId, StringComparison.OrdinalIgnoreCase)).ToList();
if (conditions.Count == 0) return;
var items = new HashSet<IEventMonitoredItem>(_allEventsItems.Keys, ReferenceEqualityComparer.Instance);
foreach (var folder in conditions.SelectMany(c => c.Folders).Distinct())
var conditions = _importedConditions.All.Where(c => string.Equals(c.ConnectionId, connectionId, StringComparison.OrdinalIgnoreCase)).ToList();
if (conditions.Count > 0) QueueImportedRefresh(conditions);
}
/// <summary>Event items that may be holding imported conditions: the Server-object items, and each direct item with the
/// conditions wired at its notifier.</summary>
private sealed class RefreshTargets
{
public HashSet<IEventMonitoredItem> ServerItems { get; } = new(ReferenceEqualityComparer.Instance);
public Dictionary<IEventMonitoredItem, List<ImportedCondition>> Direct { get; } = new(ReferenceEqualityComparer.Instance);
}
/// <summary>Under Lock: the items that may see <paramref name="conditions"/> (bounded by the caller's chunk).</summary>
private void CollectRefreshTargets(IReadOnlyList<ImportedCondition> conditions, RefreshTargets targets)
{
if (conditions.Count == 0) return;
foreach (var item in _allEventsItems.Keys) targets.ServerItems.Add(item);
foreach (var c in conditions)
foreach (var folder in c.Folders)
if (MonitoredNodes.TryGetValue(folder.NodeId, out var monitored) && monitored.EventMonitoredItems is { } attached)
foreach (var item in attached.Values) if (item is not null) items.Add(item);
foreach (var item in items) targets.Add((item, conditions.Any(c => ImportedVisibleTo(item, c))));
}
foreach (var (item, allowed) in targets)
foreach (var item in attached.Values)
{
if (item is null) continue;
if (!targets.Direct.TryGetValue(item, out var list)) targets.Direct[item] = list = [];
list.Add(c);
}
}
/// <summary>Review r1 S5: the targets are gathered in 128-condition Lock holds; visibility is decided off Lock.</summary>
private void QueueImportedRefresh(IReadOnlyList<ImportedCondition> conditions)
{
var targets = new RefreshTargets();
for (var start = 0; start < conditions.Count; start += ImportedApplyChunk)
{
var chunk = conditions.Skip(start).Take(ImportedApplyChunk).ToList();
lock (Lock) CollectRefreshTargets(chunk, targets);
}
QueueRefreshRequired(targets, conditions);
}
/// <summary>Off Lock: one RefreshRequired per item that may see at least one of the conditions (§5.4 gate).</summary>
private void QueueRefreshRequired(RefreshTargets targets, IReadOnlyList<ImportedCondition> conditions)
{
var send = new List<IEventMonitoredItem>();
foreach (var item in targets.ServerItems)
if (conditions.Any(c => ImportedVisibleTo(item, c))) send.Add(item);
foreach (var (item, candidates) in targets.Direct)
if (!targets.ServerItems.Contains(item) && candidates.Any(c => ImportedVisibleTo(item, c))) send.Add(item);
foreach (var item in send)
{
if (!allowed) continue;
var e = new RefreshRequiredEventState(null);
e.Initialize(SystemContext, null, EventSeverity.Low, new LocalizedText("RefreshRequired"));
e.SetChildValue(SystemContext, BrowseNames.SourceNode, ObjectIds.Server, false);
@@ -335,8 +409,8 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
// Materialise / apply / remove (under Lock)
// ---------------------------------------------------------------------------------------------------------------------
/// <returns>True when a resync left retained EventIds un-re-bindable (the caller queues RefreshRequired).</returns>
private bool ApplyImported(ImportedConditionUpdate update, Dictionary<(string, string), FolderState> folders)
/// <returns>The condition when a resync left its retained EventIds un-re-bindable (the caller queues RefreshRequired).</returns>
private ImportedCondition? ApplyImported(ImportedConditionUpdate update)
{
var state = update.State;
if (update.Placements.Count == 0) throw new ArgumentException("An imported condition needs a placement.", nameof(update));
@@ -344,7 +418,7 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
if (state.Removed)
{
if (_importedConditions.Find(id) is { } gone) RemoveImported(gone);
return false;
return null;
}
var condition = _importedConditions.Find(id);
@@ -375,12 +449,12 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
_importedConditions.Add(condition);
}
UpdatePlacements(condition, update.Placements, folders);
UpdatePlacements(condition, update.Placements);
if (condition.Alarm.SourceName is { } sourceName) sourceName.Value = update.SourceName; // display only; rides the next event
if ((update.Info ?? state.Info) is { } listed) condition.SupportedMethods = listed.SupportedMethods;
// §5.1 T2: a record with state_known = false never changes the consumer's last state.
if (!state.StateKnown) return false;
if (!state.StateKnown) return null;
var snapshot = new AlarmConditionSnapshot(state.Active, state.Acknowledged, state.Confirmed, state.Enabled,
Enum.IsDefined(typeof(AlarmShelvingKind), state.Shelving) ? (AlarmShelvingKind)state.Shelving : AlarmShelvingKind.Unshelved,
(ushort)Math.Clamp(state.Severity, 1u, 1000u), state.Message ?? "", state.Quality,
@@ -397,9 +471,9 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
if (ApplyConditionState(condition.Alarm, snapshot, ts))
{
ReportImported(condition, ts);
return false;
return null;
}
return RebindImportedEventIds(condition, previous, previousTime, state);
return RebindImportedEventIds(condition, previous, previousTime, state) ? condition : null;
}
/// <summary>Reports one imported event (stamping a consumer-minted EventId, N6) through the shared reporter.</summary>
@@ -435,21 +509,15 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
// Notifier wiring (N7): lazy, symmetric
// ---------------------------------------------------------------------------------------------------------------------
/// <summary>(mapping, local subject) → materialised projected folder (anchors included). One scan per apply batch.</summary>
private Dictionary<(string, string), FolderState> ProjectedFolderIndex()
/// <summary>(mapping, local subject) → the live materialised projected folder (anchors included), or null. Under Lock.</summary>
private FolderState? FindProjectedFolder((string Mapping, string Subject) key)
{
var index = new Dictionary<(string, string), FolderState>();
if (_importedConditions.ByFolderKey.Count == 0 && _projectedVariables.Count + _projectedAnchors.Count == 0) return index;
foreach (var anchor in _projectedAnchors.Values)
if (anchor.Node is FolderState folder) index.TryAdd((anchor.Definition.MappingId, anchor.Definition.LocalSubject), folder);
foreach (var entry in _projectedVariables.Values)
if (entry.Node is FolderState folder && entry.Metadata.View.MappingId is { } mapping)
index.TryAdd((mapping, entry.Metadata.View.Subject), folder);
return index;
if (!_importedConditions.FolderIds.TryGetValue(key, out var id)) return null;
if (_projectedAnchors.TryGetValue(id, out var anchor) && anchor.Node is FolderState a) return a;
return _projectedVariables.TryGetValue(id, out var entry) && entry.Node is FolderState f ? f : null;
}
private void UpdatePlacements(ImportedCondition condition, IReadOnlyList<ImportedConditionPlacement> placements,
Dictionary<(string, string), FolderState> folders)
private void UpdatePlacements(ImportedCondition condition, IReadOnlyList<ImportedConditionPlacement> placements)
{
var before = condition.Placements.Select(ProjectedConditionRegistry.FolderKey).ToHashSet();
var after = placements.Select(ProjectedConditionRegistry.FolderKey).ToHashSet();
@@ -464,34 +532,45 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
set.Add(condition.Alarm.NodeId);
}
var desired = new HashSet<FolderState>(ReferenceEqualityComparer.Instance);
foreach (var key in after) if (folders.TryGetValue(key, out var f)) desired.Add(f);
foreach (var key in after) if (FindProjectedFolder(key) is { } f) desired.Add(f);
foreach (var folder in condition.Folders.Where(f => !desired.Contains(f)).ToList()) UnwireImportedFolder(condition, folder);
foreach (var folder in desired) WireImportedFolder(condition, folder);
}
private void WireImportedFolder(ImportedCondition condition, FolderState folder)
{
if (!condition.Folders.Add(folder)) return;
if (condition.Folders.Contains(folder)) return;
if (_importedConditions.WiredByFolder.TryGetValue(folder.NodeId, out var entry) && !ReferenceEquals(entry.Folder, folder))
{
// S1 backstop: a dead instance with this NodeId is still recorded — unwire it, then promote the new one.
foreach (var id in entry.Conditions.ToList())
if (_importedConditions.Find(id) is { } stale) UnwireImportedFolder(stale, entry.Folder);
_importedConditions.WiredByFolder.Remove(folder.NodeId);
}
condition.Folders.Add(folder);
condition.WiredFolders = [.. condition.Folders];
condition.Alarm.AddNotifier(SystemContext, NodeId.Null, isInverse: true, folder);
folder.AddNotifier(SystemContext, NodeId.Null, isInverse: false, condition.Alarm);
if (!_importedConditions.WiredByFolder.TryGetValue(folder.NodeId, out var wired))
if (!_importedConditions.WiredByFolder.TryGetValue(folder.NodeId, out entry))
{
_importedConditions.WiredByFolder[folder.NodeId] = wired = [];
_importedConditions.WiredByFolder[folder.NodeId] = entry = (folder, []);
// Projected folders are created with EventNotifier = None (NM projected page sink); promoted only while wired.
folder.EventNotifier = (byte)(folder.EventNotifier | EventNotifiers.SubscribeToEvents);
AddRootNotifier(folder);
folder.ClearChangeMasks(SystemContext, includeChildren: false);
}
wired.Add(condition.Alarm.NodeId);
entry.Conditions.Add(condition.Alarm.NodeId);
condition.PlacementVersion++;
}
private void UnwireImportedFolder(ImportedCondition condition, FolderState folder)
{
if (!condition.Folders.Remove(folder)) return;
condition.WiredFolders = [.. condition.Folders];
condition.Alarm.RemoveNotifier(SystemContext, folder, bidirectional: true);
condition.PlacementVersion++;
if (_importedConditions.WiredByFolder.TryGetValue(folder.NodeId, out var wired) && wired.Remove(condition.Alarm.NodeId) && wired.Count == 0)
if (_importedConditions.WiredByFolder.TryGetValue(folder.NodeId, out var entry) && ReferenceEquals(entry.Folder, folder)
&& entry.Conditions.Remove(condition.Alarm.NodeId) && entry.Conditions.Count == 0)
{
_importedConditions.WiredByFolder.Remove(folder.NodeId);
RemoveRootNotifier(folder);
@@ -500,24 +579,33 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
}
}
/// <summary>A projected folder (or anchor) materialised: wire every imported condition placed there (N7). Under Lock.</summary>
/// <summary>A projected folder (or anchor) materialised: index it and wire every imported condition placed there (N7). Under Lock.</summary>
private void OnProjectedFolderMaterialised(FolderState folder, string mappingId, string localSubject)
{
if (_importedConditions.FolderKeys.Remove(folder.NodeId, out var previous)) _importedConditions.FolderIds.Remove(previous);
_importedConditions.FolderIds[(mappingId, localSubject)] = folder.NodeId;
_importedConditions.FolderKeys[folder.NodeId] = (mappingId, localSubject);
if (_importedConditions.Count == 0 || !_importedConditions.ByFolderKey.TryGetValue((mappingId, localSubject), out var set)) return;
foreach (var id in set.ToList())
if (_importedConditions.Find(id) is { } c) WireImportedFolder(c, folder);
}
/// <summary>A projected folder is being removed: unwire it symmetrically first (N7). Under Lock.</summary>
/// <summary>A projected folder is being removed: unwire it symmetrically first (N7) and drop it from the index. Under Lock.</summary>
private void OnProjectedFolderRemoving(NodeId folderId)
{
if (!_importedConditions.WiredByFolder.TryGetValue(folderId, out var wired)) return;
foreach (var id in wired.ToList())
{
if (_importedConditions.Find(id) is not { } c) continue;
var folder = c.Folders.FirstOrDefault(f => f.NodeId == folderId);
if (folder is not null) UnwireImportedFolder(c, folder);
}
if (_importedConditions.FolderKeys.Remove(folderId, out var key)) _importedConditions.FolderIds.Remove(key);
if (!_importedConditions.WiredByFolder.TryGetValue(folderId, out var entry)) return;
foreach (var id in entry.Conditions.ToList())
if (_importedConditions.Find(id) is { } c) UnwireImportedFolder(c, entry.Folder);
}
/// <summary>Review r1 S1: a full rebuild discards every projected folder — unwire all of them (and clear the index) before
/// the maps are cleared, so a re-materialised folder is promoted and wired afresh. Under Lock.</summary>
private void UnwireAllImportedFolders()
{
foreach (var folderId in _importedConditions.WiredByFolder.Keys.ToList()) OnProjectedFolderRemoving(folderId);
_importedConditions.FolderIds.Clear();
_importedConditions.FolderKeys.Clear();
}
/// <summary>
@@ -525,26 +613,36 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
/// mapping removal still removes it, unwiring first). Under Lock.
/// </summary>
private bool IsPinnedEventFolder(NodeId nodeId) =>
_importedConditions.WiredByFolder.ContainsKey(nodeId)
(_importedConditions.WiredByFolder.ContainsKey(nodeId) || _importedConditions.FolderKeys.ContainsKey(nodeId))
&& MonitoredNodes.TryGetValue(nodeId, out var monitored) && monitored.EventMonitoredItems is { Count: > 0 };
/// <summary>A projected folder currently wired as a notifier of an imported condition (event items there are admitted, §5.4).</summary>
/// <summary>
/// A projected folder (or anchor) event items are admitted on through the verified path (§5.4): one wired as a notifier of
/// an imported condition, or — deviation 3, review r1 — any materialised projected folder, so a folder-only client can
/// open condition demand before any condition is wired there.
/// </summary>
private bool IsProjectedEventNotifier(NodeId nodeId)
{
if (_importedConditions.Count == 0) return false;
lock (Lock) return _importedConditions.WiredByFolder.ContainsKey(nodeId);
if (ProjectedConditionAccess is null) return false;
lock (Lock) return _importedConditions.WiredByFolder.ContainsKey(nodeId) || _importedConditions.FolderKeys.ContainsKey(nodeId);
}
/// <summary>§5.4 admission of an event item on a projected notifier: the caller sees at least one condition wired there.</summary>
/// <summary>
/// §5.4 admission (and revalidation, review r1 B3) of an event item on a projected notifier: the caller sees at least one
/// condition wired there, or passes the mapping gate on the folder's own (mapping, local subject) placement key.
/// </summary>
private bool ImportedNotifierAdmits(RoleCarryingUserIdentity? identity, NodeId notifierId)
{
List<ImportedCondition> wired;
List<ImportedCondition> wired = [];
(string Mapping, string Subject)? key = null;
lock (Lock)
{
if (!_importedConditions.WiredByFolder.TryGetValue(notifierId, out var ids)) return false;
wired = ids.Select(_importedConditions.Find).OfType<ImportedCondition>().ToList();
if (_importedConditions.WiredByFolder.TryGetValue(notifierId, out var entry))
wired = entry.Conditions.Select(_importedConditions.Find).OfType<ImportedCondition>().ToList();
if (_importedConditions.FolderKeys.TryGetValue(notifierId, out var folderKey)) key = folderKey;
}
return wired.Any(c => ImportedVisibleTo(identity, c));
if (wired.Any(c => ImportedVisibleTo(identity, c))) return true;
return key is { } k && identity is not null && ProjectedConditionAccess is { } access && access.CanSubscribeFolder(identity, k.Mapping, k.Subject);
}
/// <summary>
@@ -585,33 +683,43 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
/// <summary>
/// ConditionRefresh for imported conditions: every retained one the item may see, through the marked path. Server-object
/// items see all; a direct item only those wired to its notifier. One Lock hold (consistent with synchronous events).
/// items see all; a direct item only those wired to its notifier. Review r1 (deviation 8): chunked at
/// <see cref="ImportedApplyChunk"/> conditions per <c>Lock</c> hold; each condition's snapshot and its queueing happen in the
/// same hold (so its ordering against its live events holds), and one <see cref="EventDeliveryCache"/> per condition
/// snapshot is shared by every item it is queued to (one projection, not one per item).
/// </summary>
private void ReplayImportedConditions(List<IEventMonitoredItem> serverItems, List<IEventMonitoredItem> directItems)
{
if (_importedConditions.Count == 0) return;
lock (Lock)
var all = _importedConditions.All.ToList();
for (var start = 0; start < all.Count; start += ImportedApplyChunk)
{
var retained = _importedConditions.All.Where(c => c.Alarm.Retain?.Value == true).ToList();
if (retained.Count == 0) return;
var snapshots = new Dictionary<ImportedCondition, InstanceStateSnapshot>(ReferenceEqualityComparer.Instance);
InstanceStateSnapshot SnapshotOf(ImportedCondition c)
lock (Lock)
{
if (snapshots.TryGetValue(c, out var s)) return s;
s = new InstanceStateSnapshot();
s.Initialize(SystemContext, c.Alarm);
return snapshots[c] = s;
}
foreach (var item in serverItems)
foreach (var c in retained)
if (ImportedVisibleTo(item, c) && !ServiceResult.IsBad(ValidateEventRolePermissions(item, c.Alarm)))
new EventDeliveryCache().QueueMarked(Server, item, SnapshotOf(c), i => ImportedMarker(i, c));
foreach (var item in directItems)
{
if (!MonitoredItems.ContainsKey(item.Id) || (item.ManagerHandle as NodeHandle)?.Node is not FolderState notifier) continue;
foreach (var c in retained)
if (c.Folders.Contains(notifier) && ImportedVisibleTo(item, c) && !ServiceResult.IsBad(ValidateEventRolePermissions(item, c.Alarm)))
new EventDeliveryCache().QueueMarked(Server, item, SnapshotOf(c), i => ImportedMarker(i, c));
var direct = directItems.Where(item => MonitoredItems.ContainsKey(item.Id))
.Select(item => (Item: item, Notifier: (item.ManagerHandle as NodeHandle)?.Node as FolderState))
.Where(x => x.Notifier is not null).ToList();
for (var i = start; i < Math.Min(all.Count, start + ImportedApplyChunk); i++)
{
var c = all[i];
if (!_importedConditions.IsLive(c.Alarm) || c.Alarm.Retain?.Value != true) continue;
InstanceStateSnapshot? snapshot = null;
EventDeliveryCache? cache = null;
void Queue(IEventMonitoredItem item)
{
if (!ImportedVisibleTo(item, c) || ServiceResult.IsBad(ValidateEventRolePermissions(item, c.Alarm))) return;
if (snapshot is null)
{
snapshot = new InstanceStateSnapshot();
snapshot.Initialize(SystemContext, c.Alarm);
cache = new EventDeliveryCache();
}
cache!.QueueMarked(Server, item, snapshot, x => ImportedMarker(x, c));
}
foreach (var item in serverItems) Queue(item);
foreach (var (item, notifier) in direct)
if (c.Folders.Contains(notifier!)) Queue(item);
}
}
}
}
@@ -524,7 +524,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
}
/// <summary>A non-owning handle with the deployed operation and resource policy.</summary>
public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistoryService, IHistoryBatchLimit, IDataConditionMethodService, IDisposable
public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistoryService, IHistoryBatchLimit, IDataConditionMethodService, IDataPrimarySubscriptionSource, IDisposable
{
/// <summary>
/// A3b: a remote condition method through the deployed connection — needs the row's AlarmAcknowledge / AlarmConfirm
@@ -679,9 +679,17 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistor
catch (Exception ex) when (ex is OperationCanceledException or InvalidOperationException or UnauthorizedAccessException)
{ return request.Items.Select(x => new WriteItemResult(x.CorrelationId, new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Write outcome unknown after scope change."))).ToArray(); }
}
public async Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => SubscribeCoreAsync(primaryOnly: false, cancellationToken);
/// <inheritdoc />
public Task<IDataSubscription> SubscribePrimaryAsync(CancellationToken cancellationToken) => SubscribeCoreAsync(primaryOnly: true, cancellationToken);
private async Task<IDataSubscription> SubscribeCoreAsync(bool primaryOnly, CancellationToken cancellationToken)
{
Check(DataOperations.Subscribe); var stream = await _inner.SubscribeAsync(cancellationToken).ConfigureAwait(false);
Check(DataOperations.Subscribe);
var stream = primaryOnly && _inner is IDataPrimarySubscriptionSource primary
? await primary.SubscribePrimaryAsync(cancellationToken).ConfigureAwait(false)
: await _inner.SubscribeAsync(cancellationToken).ConfigureAwait(false);
try { Check(DataOperations.Subscribe); return stream is IDataSubscriptionProvenance provenance
? new ProvenancedScopedSubscription(this, stream, provenance.Serving)
: new ScopedSubscription(this, stream); }
@@ -23,7 +23,7 @@ public interface IDataConnectionSecurityProvider
public sealed record DataConnectionChannelIdentity(string ConnectionId, Uri Endpoint, string CredentialVersion, string TrustFingerprint);
/// <summary>Caller-bound remote facade. All channels and requests are bounded by configured local limits.</summary>
public sealed partial class GrpcDataConnection : IDataConnection
public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySubscriptionSource
{
private sealed class ChannelEntry(DataConnectionChannelIdentity identity, GrpcChannel channel, string bearer)
{
@@ -531,7 +531,14 @@ public sealed partial class GrpcDataConnection : IDataConnection
actual == expected || actual.NodeId == expected.NodeId && actual.Incarnation == expected.Incarnation &&
results.Count > 0 && results.All(x => x.Outcome.State == DataWriteState.RejectedBeforeDispatch);
public async Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => SubscribeCoreAsync(primaryOnly: false, cancellationToken);
/// <inheritdoc />
/// <remarks>A3 review r1 (deviation 9): condition streams skip a ReadyReplica Secondary. An endpoint refused only for its
/// role is not a discovery failure (no probe backoff for the value path).</remarks>
public Task<IDataSubscription> SubscribePrimaryAsync(CancellationToken cancellationToken) => SubscribeCoreAsync(primaryOnly: true, cancellationToken);
private async Task<IDataSubscription> SubscribeCoreAsync(bool primaryOnly, CancellationToken cancellationToken)
{
EnterWork();
var reserved = false;
@@ -546,11 +553,18 @@ public sealed partial class GrpcDataConnection : IDataConnection
}
var budget = new DataBudget(TimeSpan.FromSeconds(5), 1000, _maxMessageBytes);
var start = Clock.GetTimestamp(); Exception? failure = null;
var roleOnly = primaryOnly;
foreach (var endpoint in _endpoints)
{
try
{
var selected = await SelectAsync(endpoint, start, budget, false, cancellationToken).ConfigureAwait(false);
if (primaryOnly && !string.Equals(selected.Capabilities.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase))
{
failure = new InvalidOperationException("Endpoint is not the Primary.");
continue;
}
roleOnly = false;
if ((selected.Capabilities.Operations & DataOperations.Subscribe) == 0 ||
Volatile.Read(ref _activeStreams) > selected.Capabilities.Limits.MaxStreams)
throw new InvalidOperationException("Subscriptions unavailable or peer stream capacity exhausted.");
@@ -593,10 +607,10 @@ public sealed partial class GrpcDataConnection : IDataConnection
}
}
catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException)
{ failure = ex; RecordFailure(ex); }
{ failure = ex; RecordFailure(ex); roleOnly = false; }
}
ProbeFailed();
throw new InvalidOperationException("No ready subscription endpoint.", failure);
if (!roleOnly) ProbeFailed();
throw new InvalidOperationException(roleOnly ? "No Primary subscription endpoint." : "No ready subscription endpoint.", failure);
}
finally
{
@@ -0,0 +1,565 @@
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
public sealed partial class ProjectedConditionAccess
{
// -----------------------------------------------------------------------------------------------------------------
// The node-wide host-cap ledger (review r1 B4)
// -----------------------------------------------------------------------------------------------------------------
/// <summary>
/// §5.5 host caps, node-wide: one ledger across every connection. A connection is charged
/// <c>max(materialised keys, Σ mapping claims)</c> — conditions are charged once per key, a mapping's claim is its
/// admitted snapshot <c>total</c> while it snapshots and its record count afterwards (so post-snapshot growth is charged),
/// and a re-snapshot of keys the connection already holds is not double-charged. Admission is order-independent: a
/// begin is decided against everything already charged or claimed, whichever connection or mapping arrived first.
/// </summary>
private sealed class ConditionLedger(ProjectedConditionOptions options)
{
private sealed class Entry
{
public int Materialised;
public readonly Dictionary<string, int> Claims = new(StringComparer.OrdinalIgnoreCase);
public long Charge => Math.Max(Materialised, Claims.Values.Sum(x => (long)x));
}
private readonly object _gate = new();
private readonly Dictionary<string, Entry> _connections = new(StringComparer.OrdinalIgnoreCase);
public long Total { get { lock (_gate) return TotalLocked(); } }
private long TotalLocked() => _connections.Values.Sum(x => x.Charge);
private bool Over(long conditions) =>
conditions * ProjectedConditionOptions.NodesPerCondition > options.MaxImportedConditionNodes
|| conditions * ProjectedConditionOptions.BytesPerCondition > options.MaxImportedConditionBytes;
public bool HighWater(long conditions) =>
conditions * ProjectedConditionOptions.NodesPerCondition > options.MaxImportedConditionNodes * 8L / 10;
/// <summary>Sets a mapping's claim when the node total stays within both caps; otherwise leaves it unchanged.</summary>
public bool TryClaim(string connection, string mapping, int count, out long total)
{
lock (_gate)
{
if (!_connections.TryGetValue(connection, out var entry)) _connections[connection] = entry = new Entry();
var had = entry.Claims.TryGetValue(mapping, out var previous);
entry.Claims[mapping] = count;
total = TotalLocked();
if (!Over(total) || count <= previous) return true;
if (had) entry.Claims[mapping] = previous; else entry.Claims.Remove(mapping);
return false;
}
}
public void Release(string connection, string mapping)
{
lock (_gate) if (_connections.TryGetValue(connection, out var entry)) entry.Claims.Remove(mapping);
}
public void ResetClaims(string connection)
{
lock (_gate) if (_connections.TryGetValue(connection, out var entry)) entry.Claims.Clear();
}
public void SetMaterialised(string connection, int count)
{
lock (_gate)
{
if (!_connections.TryGetValue(connection, out var entry)) _connections[connection] = entry = new Entry();
entry.Materialised = count;
if (count == 0 && entry.Claims.Count == 0) _connections.Remove(connection);
}
}
}
// -----------------------------------------------------------------------------------------------------------------
// One connection: one stream, one root item per condition-bearing mapping
// -----------------------------------------------------------------------------------------------------------------
/// <summary>One mapping's records: versions per key, the listed infos, and (for a snapshot buffer) the begin's total.</summary>
private sealed class ConditionSet(int total)
{
public int Total { get; } = total;
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);
/// <summary>The per-key version rule: a removal bypasses the gate and forgets the key (and its info).</summary>
public void Apply(DataConditionState record, HashSet<string>? changed)
{
var key = record.ConditionKey;
if (record.Removed)
{
Records.Remove(key); Versions.Remove(key); Infos.Remove(key);
changed?.Add(key);
return;
}
if (record.Info is { } info) Infos[key] = info;
if (Versions.TryGetValue(key, out var last) && record.Version <= last) return;
Versions[key] = record.Version;
Records[key] = record;
changed?.Add(key);
}
}
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 DataItemHandle? ItemHandle { get; set; }
public ProjectedConditionMappingStatus Status { get; set; } = ProjectedConditionMappingStatus.Pending;
/// <summary>The origin refused the item (or its metadata failed): nothing more arrives on this stream.</summary>
public bool Refused { get; set; }
/// <summary>The mapping's committed complete set in this stream (null until its first snapshot completes).</summary>
public ConditionSet? Live { get; set; }
/// <summary>Review r1 B1: a (re-)snapshot in progress, swapped in only at <c>snapshot_complete</c>.</summary>
public ConditionSet? Buffer { get; set; }
public bool Contributes => Live is not null && Status != ProjectedConditionMappingStatus.ConditionCapacity;
/// <summary>Whether the mapping's key set is known: listed (complete) or known-empty (over capacity).</summary>
public bool Known => Contributes || Status == ProjectedConditionMappingStatus.ConditionCapacity;
public int Claim => Math.Max(Buffer?.Total ?? 0, Live?.Records.Count ?? 0);
}
private sealed class ConnectionRunner
{
private readonly ProjectedConditionAccess _owner;
private readonly ProjectedMappingPlacement[] _mappings;
private readonly CancellationTokenSource _stop = new();
private readonly object _statusGate = new();
private readonly object _staleGate = new();
private readonly ConnectionRunner? _predecessor;
private Task _loop = Task.CompletedTask;
private Task _stopped = Task.CompletedTask;
private MappingState[] _states = [];
/// <summary>Keys currently materialised at the sink. Owned by the loop; handed over only after the predecessor stopped.</summary>
private HashSet<string> _materialised = new(StringComparer.Ordinal);
private ITimer? _stale;
private long _staleGeneration;
private int _barriers;
private int _consecutiveRetries;
public ConnectionRunner(ProjectedConditionAccess owner, string connectionId, ProjectedMappingPlacement[] mappings, string signature,
ConnectionRunner? predecessor)
{
_owner = owner; ConnectionId = connectionId; _mappings = mappings; Signature = signature; _predecessor = predecessor;
}
public string ConnectionId { get; }
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);
/// <summary>Completes once the loop ended and (for a removing stop) its conditions were removed.</summary>
public Task Stopped => _stopped;
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(async () =>
{
if (_predecessor is { } previous)
{
// S3/S4: never overlap the previous runner of this connection — its in-flight Publish or its removal would
// otherwise race this runner's materialisation (an orphaned key, or a fresh key removed by the old continuation).
try { await previous.Stopped.ConfigureAwait(false); } catch (Exception ex) { _owner._log.LogDebug(ex, "Imported conditions: predecessor stop faulted"); }
_materialised = previous._materialised;
previous._materialised = new HashSet<string>(StringComparer.Ordinal);
}
await RunAsync(_stop.Token).ConfigureAwait(false);
});
public void Stop(bool removeConditions)
{
_stop.Cancel();
Volatile.Write(ref _serving, null);
lock (_staleGate) { _staleGeneration++; _stale?.Dispose(); _stale = null; }
_stopped = _loop.ContinueWith(_ =>
{
if (!removeConditions) return;
var keys = _materialised.ToArray();
if (keys.Length > 0 && _owner._sink() is { } sink) sink.RemoveConditions(ConnectionId, keys);
_materialised.Clear();
_owner._ledger.ResetClaims(ConnectionId);
_owner._ledger.SetMaterialised(ConnectionId, 0);
}, 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()
{
lock (_staleGate)
{
if (_stale is not null || _materialised.Count == 0 || _stop.IsCancellationRequested) return;
var generation = _staleGeneration;
var timeout = TimeSpan.FromMilliseconds(Math.Max(1, _mappings.Min(x => x.Mapping.ConditionStaleTimeoutMilliseconds)));
_stale = _owner._clock.CreateTimer(_ =>
{
// NIT (review r1): a callback already in flight cannot land after a fresh barrier — the barrier bumps the
// generation under the same gate this mark runs under, so it either waits for the mark or wins the check.
lock (_staleGate)
if (generation == _staleGeneration && !_stop.IsCancellationRequested) _owner._sink()?.MarkConnectionStale(ConnectionId);
}, null, timeout, Timeout.InfiniteTimeSpan);
}
}
private void DisarmStale()
{
lock (_staleGate) { _staleGeneration++; _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;
_owner._ledger.ResetClaims(ConnectionId);
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).
// S6: a root whose metadata fails is Unavailable (its item is not opened — a root item without the origin's own
// view is refused, and placements made relative to a missing root subject would be wrong).
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++)
{
if (i < metadata.Count && metadata[i] is { Status: DataItemStatus.Good, Value: { } root })
{
states[i].RootSubject = root.View.Subject;
states[i].RootView = root.View;
continue;
}
MarkRefused(states[i]);
_owner._log.LogWarning("Imported conditions: mapping {Mapping} root metadata unavailable ({Status}) — Unavailable, retried on a new stream",
states[i].MappingId, i < metadata.Count ? metadata[i].Status : DataItemStatus.Unavailable);
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
foreach (var state in states) MarkRefused(state);
_owner._log.LogWarning(ex, "Imported conditions: connection {Connection} root metadata failed — every mapping Unavailable", ConnectionId);
}
var open = states.Where(x => !x.Refused).ToArray();
if (open.Length == 0) throw new InvalidOperationException("No condition-bearing mapping root resolved.");
// Deviation 9: condition items are served by the origin's Primary only (a Secondary advertises but refuses, A2 N7).
await using var subscription = connection is IDataPrimarySubscriptionSource primary
? await primary.SubscribePrimaryAsync(token).ConfigureAwait(false)
: await connection.SubscribeAsync(token).ConfigureAwait(false);
var serving = (subscription as IDataSubscriptionProvenance)?.Serving;
if (serving is not null && !string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"Condition stream served by a {serving.Role} ({serving.NodeId}); conditions are pinned to the Primary.");
Volatile.Write(ref _serving, serving);
_owner._log.LogInformation("Imported conditions: stream {Epoch} for connection {Connection} opened ({Mappings} mapping(s), serving {Serving})",
epoch, ConnectionId, open.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 = open.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;
var timeout = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using var barrierTimer = _owner._clock.CreateTimer(_ => timeout.TrySetResult(), null, snapshotTimeout, Timeout.InfiniteTimeSpan);
// B2: a mapping still Unavailable a bounded wait after the barrier ends the stream (a fresh stream retries it).
var retry = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
ITimer? retryTimer = null;
var context = new StreamContext(subscription, subscriptionId, epoch, token);
try
{
await using var frames = subscription.ReadAllAsync(token).GetAsyncEnumerator(token);
Task<bool>? next = null;
while (true)
{
if (!barrierPassed && timeout.Task.IsCompleted)
{
// ConditionSnapshotTimeoutMilliseconds: the incomplete mappings are Unavailable and the rest proceed; a
// late completion still swaps in and re-runs the merge (B2).
lock (_statusGate)
foreach (var s in states.Where(s => s.Status is ProjectedConditionMappingStatus.Pending or ProjectedConditionMappingStatus.Snapshotting))
s.Status = ProjectedConditionMappingStatus.Unavailable;
barrierPassed = TryPassBarrier(states, timedOut: true);
}
if (barrierPassed)
{
var unavailable = states.Any(x => x.Status == ProjectedConditionMappingStatus.Unavailable);
if (retry.Task.IsCompleted && unavailable)
{
_consecutiveRetries++;
_owner._log.LogWarning("Imported conditions: connection {Connection} mapping(s) {Mappings} still Unavailable — ending the stream to retry",
ConnectionId, string.Join(", ", states.Where(x => x.Status == ProjectedConditionMappingStatus.Unavailable).Select(x => x.MappingId)));
return;
}
if (!unavailable)
{
retryTimer?.Dispose(); retryTimer = null; _consecutiveRetries = 0;
if (retry.Task.IsCompleted) retry = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
}
else if (retryTimer is null)
{
var wait = snapshotTimeout * Math.Min(1 << Math.Min(_consecutiveRetries, 3), 8);
var signal = retry;
retryTimer = _owner._clock.CreateTimer(_ => signal.TrySetResult(), null, wait, Timeout.InfiniteTimeSpan);
}
}
next ??= frames.MoveNextAsync().AsTask();
if (!next.IsCompleted)
{
var wake = barrierPassed ? retry.Task : timeout.Task;
if (await Task.WhenAny(next, wake).ConfigureAwait(false) != next) continue;
}
if (!await next.ConfigureAwait(false)) return;
next = null;
var outcome = await ProcessAsync(frames.Current, states, context).ConfigureAwait(false);
if (!barrierPassed) { barrierPassed = TryPassBarrier(states, timedOut: false); continue; }
if (outcome.Changed.Count > 0 || outcome.Reconcile) Reconcile(states, outcome.Changed, outcome.Reconcile);
if (outcome.Refresh) _owner._sink()?.RequireRefresh(ConnectionId);
}
}
finally { retryTimer?.Dispose(); }
}
private sealed record StreamContext(IDataSubscription Subscription, string SubscriptionId, long Epoch, CancellationToken Token);
private sealed record FrameOutcome(HashSet<string> Changed, bool Reconcile, bool Refresh);
private void MarkRefused(MappingState state)
{
lock (_statusGate)
{
state.Refused = true;
if (state.Status != ProjectedConditionMappingStatus.ConditionCapacity) state.Status = ProjectedConditionMappingStatus.Unavailable;
}
}
private bool TryPassBarrier(MappingState[] states, bool timedOut)
{
lock (_statusGate)
if (states.Any(x => x.Status is ProjectedConditionMappingStatus.Pending or ProjectedConditionMappingStatus.Snapshotting)) return false;
Interlocked.Increment(ref _barriers);
DisarmStale();
var incomplete = states.Any(x => !x.Known);
_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.Live!.Records.Count),
timedOut ? "; snapshot timed out" : "");
Reconcile(states, states.Where(x => x.Contributes).SelectMany(x => x.Live!.Records.Keys).ToHashSet(StringComparer.Ordinal), full: true);
// S7: an incomplete (re)snapshot — a timeout OR a refused item — tells clients to refresh.
if (incomplete) _owner._sink()?.RequireRefresh(ConnectionId);
return true;
}
private async Task<FrameOutcome> ProcessAsync(DataSubscriptionFrame frame, MappingState[] states, StreamContext context)
{
var changed = new HashSet<string>(StringComparer.Ordinal);
var reconcile = false;
var refresh = false;
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;
if (itemAck.Status == DataItemStatus.Good && itemAck.Handle is { } handle)
{
lock (_statusGate) { state.Handle = handle.Handle; state.ItemHandle = handle; }
continue;
}
MarkRefused(state);
_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.Refused || mapping.Status == ProjectedConditionMappingStatus.ConditionCapacity) break;
var limit = mapping.Placement.Mapping.MaxConditions;
if (conditions.IsSnapshot && conditions.Total is { } total)
{
// A snapshot begin: decided before anything of it is materialised; buffered until snapshot_complete (B1),
// so the committed set (and what is materialised) is untouched while it streams.
if (total > limit || !_owner._ledger.TryClaim(ConnectionId, mapping.MappingId, Math.Max(total, mapping.Live?.Records.Count ?? 0), out var after))
{
await ResetToCapacityAsync(mapping, total, total > limit ? "over its MaxConditions" : "would cross the host condition caps",
changed, context).ConfigureAwait(false);
reconcile = refresh = true;
break;
}
if (_owner._ledger.HighWater(after))
_owner._log.LogWarning("Imported conditions: host condition budget above 80% ({Count} conditions)", after);
mapping.Buffer = new ConditionSet(total);
lock (_statusGate)
if (mapping.Live is null && mapping.Status == ProjectedConditionMappingStatus.Pending) mapping.Status = ProjectedConditionMappingStatus.Snapshotting;
}
foreach (var record in conditions.Items)
{
if (!ImportedConditionIds.IsWellFormedConditionKey(record.ConditionKey)) continue;
if (mapping.Live is { } live && !conditions.IsSnapshot)
{
// A delta: applied to the committed set (published) and to any buffer, so the swap is current.
live.Apply(record, changed);
mapping.Buffer?.Apply(record, null);
}
else mapping.Buffer?.Apply(record, null);
}
// B4: records past the begin's total or the mapping limit, or committed growth past the node-wide caps.
string? over = null;
if (mapping.Buffer is { } buffer && buffer.Records.Count > Math.Min(buffer.Total, limit)) over = "listed more records than its snapshot total";
else if (mapping.Live is { } grown && grown.Records.Count > limit) over = "grew past its MaxConditions";
else if (mapping.Live is not null && !_owner._ledger.TryClaim(ConnectionId, mapping.MappingId, mapping.Claim, out _)) over = "grew past the host condition caps";
if (over is not null)
{
await ResetToCapacityAsync(mapping, mapping.Claim, over, changed, context).ConfigureAwait(false);
reconcile = refresh = true;
break;
}
if (conditions.SnapshotComplete && mapping.Buffer is { } done)
{
// The swap: old ∪ new keys are re-merged — a key only the old set listed is removed (if nothing else
// lists it and every mapping is known), every other key keeps its node.
if (mapping.Live is { } old) changed.UnionWith(old.Records.Keys);
changed.UnionWith(done.Records.Keys);
mapping.Live = done;
mapping.Buffer = null;
lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.Complete;
_owner._ledger.TryClaim(ConnectionId, mapping.MappingId, done.Records.Count, out _); // ≤ the admitted total
reconcile = true;
}
break;
}
return new FrameOutcome(changed, reconcile, refresh);
}
/// <summary>§5.5 Unavailable(ConditionCapacity): the item is removed and the mapping contributes nothing (all-or-nothing).</summary>
private async Task ResetToCapacityAsync(MappingState mapping, int observed, string reason, HashSet<string> changed, StreamContext context)
{
lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.ConditionCapacity;
if (mapping.Live is { } live) changed.UnionWith(live.Records.Keys);
mapping.Live = null;
mapping.Buffer = null;
_owner._ledger.Release(ConnectionId, mapping.MappingId);
OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1);
_owner._log.LogWarning("Imported conditions: mapping {Mapping} ({Count} conditions) {Reason} (MaxConditions {Max}) — Unavailable(ConditionCapacity)",
mapping.MappingId, observed, reason, mapping.Placement.Mapping.MaxConditions);
// §5.5: the over-limit item is REMOVED (it costs an item slot and the origin's re-listing).
if (mapping.ItemHandle is { } handle)
await context.Subscription.SendAsync(new RemoveSubscriptionItems(context.SubscriptionId, context.Epoch, "remove-" + mapping.MappingId,
TimeSpan.FromSeconds(30), [handle]), context.Token).ConfigureAwait(false);
}
/// <summary>
/// Publishes <paramref name="keys"/> across the connection's committed sets. <paramref name="full"/> also re-diffs
/// everything materialised against the union (the barrier, a swap, a capacity reset, a late completion).
/// A key no contributing mapping lists is removed only when every mapping's set is known; while any is unknown
/// (Unavailable, not yet complete) it is kept with <c>BadNoCommunication</c> (unknown ≠ gone, §5.1 T2, B2).
/// </summary>
private void Reconcile(MappingState[] states, HashSet<string> keys, bool full)
{
if (_owner._sink() is not { } sink) return;
if (full)
{
var listed = states.Where(x => x.Contributes).SelectMany(x => x.Live!.Records.Keys).ToHashSet(StringComparer.Ordinal);
foreach (var key in _materialised) if (!listed.Contains(key)) keys.Add(key);
}
var unknown = states.Any(x => !x.Known);
var updates = new List<ImportedConditionUpdate>();
var removals = new List<string>();
var stale = new List<string>();
foreach (var key in keys)
{
var update = Merge(states, key);
if (update is not null) { updates.Add(update); _materialised.Add(key); continue; }
if (!_materialised.Contains(key)) continue;
if (unknown) stale.Add(key);
else { _materialised.Remove(key); removals.Add(key); }
}
if (removals.Count > 0) sink.RemoveConditions(ConnectionId, removals);
if (stale.Count > 0) sink.MarkConditionsStale(ConnectionId, stale);
if (updates.Count > 0) sink.ApplyConditions(updates);
_owner._ledger.SetMaterialised(ConnectionId, _materialised.Count);
if (updates.Count + removals.Count + stale.Count > 0)
_owner._log.LogDebug("Imported conditions: connection {Connection} applied {Updates} update(s), {Removals} removal(s), {Stale} kept stale",
ConnectionId, updates.Count, removals.Count, stale.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.Live!.Records.TryGetValue(key, out var record)) continue;
if (latest is null || record.Version > latest.Version) latest = record;
if (!state.Live.Infos.TryGetValue(key, out var placementInfo)) continue;
info ??= placementInfo;
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);
}
}
}
@@ -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);
}
}
}
@@ -321,10 +321,21 @@ public sealed class ImportedConditionEventWireTests
public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements) =>
caller is not null && Allowed.Contains(caller.Principal);
public long AuthorityGeneration => Interlocked.Read(ref Generation);
public bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject) =>
caller is not null && Allowed.Contains(caller.Principal);
/// <summary>Leases currently held (acquired minus released).</summary>
public int Outstanding;
public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller)
{
Interlocked.Increment(ref Demands);
return null;
Interlocked.Increment(ref Outstanding);
return new Lease(this);
}
private sealed class Lease(FakeConditionAccess owner) : IDisposable
{
private int _disposed;
public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) Interlocked.Decrement(ref owner.Outstanding); }
}
}
@@ -340,7 +351,18 @@ public sealed class ImportedConditionEventWireTests
public static Fixture Install(ServerEventRig rig, string grantedPrincipal)
{
var nm = rig.Nm;
var (anchor, anchorB, device, definition) = Materialise(rig.Nm);
var access = new FakeConditionAccess();
access.Allowed.Add(grantedPrincipal);
rig.Nm.ProjectedConditionAccess = access;
return new Fixture { Rig = rig, Access = access, Anchor = anchor, AnchorB = anchorB, DeviceFolder = device, DeviceDefinition = definition };
}
/// <summary>Re-creates the same projected folders (new instances, same NodeIds) — e.g. after a full rebuild.</summary>
public void Rematerialise() => Materialise(Rig.Nm);
private static (NodeId Anchor, NodeId AnchorB, NodeId Device, ProjectedVariableDefinition Definition) Materialise(OtOpcUaNodeManager nm)
{
nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
var rootA = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant");
@@ -355,11 +377,7 @@ public sealed class ImportedConditionEventWireTests
var definition = new ProjectedVariableDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingA, devAddress), anchor!.Value,
metadata, 1, () => true);
nm.TryEnsureProjectedVariable(definition, out var device).ShouldBeTrue();
var access = new FakeConditionAccess();
access.Allowed.Add(grantedPrincipal);
nm.ProjectedConditionAccess = access;
return new Fixture { Rig = rig, Access = access, Anchor = anchor.Value, AnchorB = anchorB!.Value, DeviceFolder = device!.Value,
DeviceDefinition = definition };
return (anchor.Value, anchorB!.Value, device!.Value, definition);
}
/// <summary>Primary: the raw tag under dev1 (map-a); second: the same condition listed directly under the map-a root.</summary>
@@ -141,6 +141,7 @@ public sealed class ImportedConditionClassifierTests : IAsyncDisposable
public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements) => caller is not null && Visible;
public long AuthorityGeneration => Generation;
public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller) => null;
public bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject) => caller is not null && Visible;
}
private sealed class Fixture
@@ -37,13 +37,13 @@ public sealed class GrpcDataProjectedConditionAccessTests
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map-b", total: 2);
stream.Records("map-b", Record(Key("x"), 3), Record(Key("y"), 3));
stream.Begin("map-a", total: 3);
// Positive control: the removal is the must-arrive effect of the LAST frame, so every earlier frame was processed.
await f.WaitAsync(() => stream.Removed.Count == 1);
stream.Removed.Single().ShouldBe(stream.HandleOf("map-a"), "the over-limit item is removed, not held open");
f.Sink.Applied.ShouldBeEmpty("nothing is materialised before the barrier");
stream.Begin("map-b", total: 2);
stream.Records("map-b", Record(Key("x"), 3), Record(Key("y"), 3));
f.Sink.Applied.ShouldBeEmpty();
stream.Complete("map-b");
await f.WaitAsync(() => f.Sink.Applied.Count == 2);
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
@@ -73,9 +73,9 @@ public sealed class GrpcDataProjectedConditionAccessTests
var cappedStream = await capped.NextStreamAsync();
cappedStream.Ack();
cappedStream.Begin("map-a", total: 2000);
await capped.WaitAsync(() => cappedStream.Removed.Count == 1);
await capped.WaitAsync(() => cappedStream.Removed.Count == 1 && capped.Access.BarriersCompleted(Connection) == 1);
capped.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
capped.Sink.Applied.ShouldBeEmpty();
capped.Sink.Applied.ShouldBeEmpty("the barrier (the positive control) passed with nothing to materialise");
}
[Fact]
@@ -100,10 +100,12 @@ public sealed class GrpcDataProjectedConditionAccessTests
[Fact]
public async Task A_stream_end_re_snapshots_without_removing_and_only_a_complete_re_snapshot_removes_staleness_in_between()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
// map-b (MaxConditions 0) is the positive control: its begin is refused, which must arrive as an item removal.
await using var f = new Fixture(("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 0));
using var demand = f.Access.AcquireEventDemand(null);
var first = await f.NextStreamAsync();
first.Ack();
first.Begin("map-b", total: 1);
first.Begin("map-a", total: 2);
first.Records("map-a", Record(Key("x"), 3), Record(Key("y"), 3));
first.Complete("map-a");
@@ -116,6 +118,8 @@ public sealed class GrpcDataProjectedConditionAccessTests
second.Ack();
second.Begin("map-a", total: 1);
second.Records("map-a", Record(Key("x"), 9));
second.Begin("map-b", total: 1);
await f.WaitAsync(() => second.Removed.Count == 1); // positive control: every earlier frame was processed
f.Sink.Removed.ShouldBeEmpty("an incomplete snapshot removes nothing");
second.Complete("map-a");
await f.WaitAsync(() => f.Sink.Removed.Count == 1);
@@ -194,6 +198,269 @@ public sealed class GrpcDataProjectedConditionAccessTests
await f.WaitAsync(() => !f.Access.IsRunning(Connection) && f.Sink.Removed.Count == 1);
}
// ---------------------------------------------------------------------------------------------------------------------
// Review round 1 (a3a-review-round1.md)
// ---------------------------------------------------------------------------------------------------------------------
private static async Task<FakeStream> CompleteFirstAsync(Fixture f, params (string Mapping, DataConditionState[] Records)[] snapshots)
{
var stream = await f.NextStreamAsync();
stream.Ack();
foreach (var (mapping, records) in snapshots)
{
stream.Begin(mapping, records.Length);
stream.SnapshotRecords(mapping, records);
stream.Complete(mapping);
}
await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) >= 1);
return stream;
}
[Fact]
public async Task B1_an_in_stream_multi_frame_re_snapshot_keeps_every_condition_until_complete_then_removes_only_what_it_dropped()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3), Record(Key("y"), 3), Record(Key("z"), 3)]), ("map-b", []));
await f.WaitAsync(() => f.Sink.Live.Count == 3);
// A2 re-snapshots inside a live stream (hub reader reset, retaken incomplete apply): begin, record frames, complete.
stream.Begin("map-a", total: 2);
stream.SnapshotRecords("map-a", Record(Key("x"), 4));
stream.SnapshotRecords("map-a", Record(Key("y"), 4));
stream.Records("map-b", Record(Key("ctl"), 1)); // positive control: a delta on the other mapping must be applied
await f.WaitAsync(() => f.Sink.Live.Contains(Key("ctl")));
f.Sink.Removed.ShouldBeEmpty("a re-snapshot in progress removes nothing (B1)");
f.Sink.Live.ShouldContain(Key("z"));
stream.Complete("map-a");
await f.WaitAsync(() => f.Sink.Removed.Count == 1);
f.Sink.Removed.Single().ShouldBe(Key("z"), "only the key the COMPLETE re-snapshot no longer lists is removed");
f.Sink.Live.ShouldBe([Key("x"), Key("y"), Key("ctl")], ignoreOrder: true);
}
[Fact]
public async Task B1_an_in_stream_re_snapshot_over_capacity_removes_the_mapping_once_keeps_keys_another_mapping_lists_and_requires_refresh()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 2), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3), Record(Key("y"), 3)]), ("map-b", [Record(Key("y"), 3)]));
await f.WaitAsync(() => f.Sink.Live.Count == 2);
var refreshes = f.Sink.RefreshRequired;
stream.Begin("map-a", total: 3); // the origin now lists more than MaxConditions
await f.WaitAsync(() => stream.Removed.Count == 1 && f.Sink.Removed.Count == 1);
stream.Removed.Single().ShouldBe(stream.HandleOf("map-a"));
f.Sink.Removed.Single().ShouldBe(Key("x"), "y is still listed by map-b");
f.Sink.Live.ShouldBe([Key("y")]);
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
f.Sink.RefreshRequired.ShouldBeGreaterThan(refreshes, "clients are told the removal happened (§5.2)");
}
private static Fixture TimedFixture(int timeoutMs, params (string Id, DataRealm Realm, int MaxConditions)[] mappings)
{
var f = new Fixture(mappings);
foreach (var m in f.Mappings.Current) m.Mapping.ConditionSnapshotTimeoutMilliseconds = timeoutMs;
return f;
}
[Fact]
public async Task B2_a_snapshot_completing_after_the_timeout_is_merged_late_and_the_stream_is_kept()
{
await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map-b", total: 1);
stream.Records("map-b", Record(Key("x"), 3));
stream.Complete("map-b");
await f.WaitAsync(() => f.Sink.Applied.Count == 1);
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable);
stream.Begin("map-a", total: 1); // 2,000 conditions arriving 1 s late, in miniature
stream.SnapshotRecords("map-a", Record(Key("w"), 3));
stream.Complete("map-a");
await f.WaitAsync(() => f.Sink.Live.Contains(Key("w")));
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Complete);
(await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(900))).ShouldBeNull("a late completion cancels the retry");
}
[Fact]
public async Task B2_an_incomplete_barrier_marks_the_incomplete_mappings_materialised_keys_BadNoCommunication_never_removed()
{
await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var first = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]), ("map-b", [Record(Key("y"), 3)]));
await f.WaitAsync(() => f.Sink.Live.Count == 2);
first.End();
var second = await f.NextStreamAsync();
second.Ack();
second.Begin("map-b", total: 1);
second.SnapshotRecords("map-b", Record(Key("y"), 4));
second.Complete("map-b"); // map-a never answers: the barrier passes at the timeout
await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x")));
f.Sink.Removed.ShouldBeEmpty("unknown is not gone");
f.Sink.StaleKeys.ShouldNotContain(Key("y"));
f.Sink.RefreshRequired.ShouldBeGreaterThanOrEqualTo(1);
}
[Fact]
public async Task B2_S7_a_refused_item_is_an_incomplete_barrier_RefreshRequired_and_the_stream_is_retried_after_a_bounded_wait()
{
await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack(refused: "map-a"); // e.g. a Secondary that advertises but refuses (A2 N7)
stream.Begin("map-b", total: 1);
stream.Records("map-b", Record(Key("x"), 3));
stream.Complete("map-b");
await f.WaitAsync(() => f.Sink.Applied.Count == 1);
f.Sink.RefreshRequired.ShouldBe(1, "S7: an incomplete barrier from a non-Good ack also requires refresh");
(await f.TryNextStreamAsync(TimeSpan.FromSeconds(5))).ShouldNotBeNull("B2: an Unavailable mapping ends the stream; a new one retries it");
}
[Fact]
public async Task Deviation9_a_condition_stream_served_by_a_Secondary_is_dropped_and_reopened_on_the_Primary()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
f.Connections.Roles.Enqueue("Secondary");
using var demand = f.Access.AcquireEventDemand(null);
var secondary = await f.NextStreamAsync();
var primary = await f.NextStreamAsync();
secondary.Disposed.ShouldBeTrue("never opened items on a Secondary");
f.Connections.PrimarySubscribes.ShouldBeGreaterThanOrEqualTo(2, "the Primary-only open is asked for");
primary.Ack();
primary.Begin("map-a", 1);
primary.SnapshotRecords("map-a", Record(Key("x"), 3));
primary.Complete("map-a");
await f.WaitAsync(() => f.Sink.Live.Contains(Key("x")));
}
[Fact]
public async Task S6_a_root_whose_metadata_fails_is_Unavailable_and_its_item_is_not_opened()
{
await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
f.Connections.MetadataFails.Add(0);
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Mappings.ShouldBe(["map-b"]);
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable);
}
[Fact]
public async Task B4_the_host_caps_are_node_wide_across_connections()
{
var options = new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 3 * 49, long.MaxValue, TimeSpan.FromMilliseconds(50));
await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10, "conn-a"), ("map-b", DataRealm.Raw, 10, "conn-b"));
using var demand = f.Access.AcquireEventDemand(null);
var streams = new[] { await f.NextStreamAsync(), await f.NextStreamAsync() };
foreach (var stream in streams)
{
var mapping = stream.Mappings.Single();
stream.Ack();
stream.Begin(mapping, 2);
stream.SnapshotRecords(mapping, Record(Key(mapping + "1"), 3), Record(Key(mapping + "2"), 3));
stream.Complete(mapping);
}
await f.WaitAsync(() => f.Access.BarriersCompleted("conn-a") == 1 && f.Access.BarriersCompleted("conn-b") == 1);
streams.Sum(x => x.Removed.Count).ShouldBe(1, "two connections of 2 cannot both fit a 3-condition node cap");
f.Sink.Live.Count.ShouldBe(2);
f.Access.ChargedConditions.ShouldBeLessThanOrEqualTo(3);
}
[Fact]
public async Task B4_admission_is_order_independent_a_later_ordered_begin_arriving_first_still_counts()
{
var options = new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 3 * 49, long.MaxValue, TimeSpan.FromMilliseconds(50));
await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map-b", 2);
stream.Begin("map-a", 2);
await f.WaitAsync(() => stream.Removed.Count == 1);
stream.Removed.Single().ShouldBe(stream.HandleOf("map-a"), "the second begin is decided against the first one's claim");
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
}
[Fact]
public async Task B4_records_past_the_snapshot_total_reset_the_mapping_to_ConditionCapacity_before_materialising()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 100));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map-a", total: 1);
stream.SnapshotRecords("map-a", Enumerable.Range(0, 50).Select(i => Record(Key("k" + i), 3)).ToArray());
stream.Complete("map-a");
await f.WaitAsync(() => stream.Removed.Count == 1 && f.Access.BarriersCompleted(Connection) == 1);
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
f.Sink.Applied.ShouldBeEmpty("an origin claiming total 1 cannot materialise 50 (the barrier is the positive control)");
f.Access.ChargedConditions.ShouldBe(0);
}
[Fact]
public async Task B4_post_snapshot_delta_growth_past_MaxConditions_resets_the_mapping_and_removes_its_conditions()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 2));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]));
await f.WaitAsync(() => f.Sink.Live.Count == 1);
stream.Records("map-a", Record(Key("y"), 3), Record(Key("z"), 3));
await f.WaitAsync(() => stream.Removed.Count == 1 && f.Sink.Removed.Contains(Key("x")));
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
f.Sink.Live.ShouldBeEmpty();
}
[Fact]
public async Task S2_an_authority_deactivation_moves_the_authority_generation_so_cached_verdicts_are_re_proved()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
var before = f.Access.AuthorityGeneration;
((ActiveAuthority)f.Mappings.Current[0].Authority).Active = false; // no deploy, no epoch change
f.Access.AuthorityGeneration.ShouldNotBe(before);
}
[Fact]
public async Task S3_a_new_runner_waits_for_the_old_runners_removal_so_a_re_materialised_key_survives()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
var demand = f.Access.AcquireEventDemand(null)!;
await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]));
await f.WaitAsync(() => f.Sink.Live.Count == 1);
var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
f.Sink.RemovalGate = gate; // hold the old runner's removal open
demand.Dispose();
await f.WaitAsync(() => !f.Access.IsRunning(Connection)); // linger expired; its removal is now blocked in the sink
using var again = f.Access.AcquireEventDemand(null);
_ = Task.Delay(400, TestContext.Current.CancellationToken).ContinueWith(_ => gate.TrySetResult(), TaskScheduler.Default);
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map-a", 1);
stream.SnapshotRecords("map-a", Record(Key("x"), 4));
stream.Complete("map-a");
await f.WaitAsync(() => f.Sink.Removed.Count == 1 && f.Sink.Applied.Count == 2);
f.Sink.Live.ShouldContain(Key("x"), "the old runner's removal must not land after the new runner materialised the key");
}
[Fact]
public async Task S4_a_mapping_change_hands_the_materialised_set_over_after_the_old_loop_stopped()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]));
await f.WaitAsync(() => f.Sink.Live.Count == 1);
f.Mappings.Current[0].Mapping.MaxConditions = 11; // a changed signature ⇒ a new runner, a new stream
f.Mappings.Raise();
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map-a", 1);
stream.SnapshotRecords("map-a", Record(Key("y"), 3));
stream.Complete("map-a");
await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x")));
f.Sink.Live.ShouldBe([Key("y")], "x was handed over (not orphaned) and the new complete set removed it");
}
// ---------------------------------------------------------------------------------------------------------------------
internal static string Key(string seed) =>
@@ -223,12 +490,18 @@ public sealed class GrpcDataProjectedConditionAccessTests
public ProjectedConditionAccess Access { get; }
public Fixture(params (string Id, DataRealm Realm, int MaxConditions)[] mappings)
: this(new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 122_500, long.MaxValue, TimeSpan.FromMilliseconds(50)), mappings) { }
: this(DefaultOptions, mappings) { }
public static ProjectedConditionOptions DefaultOptions =>
new(TimeSpan.FromMilliseconds(200), 122_500, long.MaxValue, TimeSpan.FromMilliseconds(50));
public Fixture(ProjectedConditionOptions options, params (string Id, DataRealm Realm, int MaxConditions)[] mappings)
: this(options, mappings.Select(m => (m.Id, m.Realm, m.MaxConditions, Connection)).ToArray()) { }
public Fixture(ProjectedConditionOptions options, params (string Id, DataRealm Realm, int MaxConditions, string Connection)[] mappings)
{
Grant(NodePermissions.Browse | NodePermissions.Subscribe);
Mappings = new FakeMappings(mappings.Select(m => Placement(m.Id, m.Realm, m.MaxConditions)).ToList());
Mappings = new FakeMappings(mappings.Select(m => Placement(m.Id, m.Realm, m.MaxConditions, m.Connection)).ToList());
var policy = new DataOperationPolicy(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), TimeProvider.System);
Access = new ProjectedConditionAccess(Mappings, Connections, policy, () => Sink, TimeProvider.System, options, NullLogger.Instance);
}
@@ -242,11 +515,11 @@ public sealed class GrpcDataProjectedConditionAccessTests
public RoleCarryingUserIdentity Identity(string principal) => new(new UserNameIdentityToken { UserName = "apikey" }, [], principal,
_key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(_key), DateTimeOffset.UtcNow.AddMinutes(5));
private static ProjectedMappingPlacement Placement(string id, DataRealm realm, int maxConditions)
private static ProjectedMappingPlacement Placement(string id, DataRealm realm, int maxConditions, string connection)
{
var mapping = new RemoteNamespaceMapping
{
RemoteNamespaceMappingId = id, DataConnectionId = Connection, Enabled = true, Realm = realm, RemoteRealm = realm,
RemoteNamespaceMappingId = id, DataConnectionId = connection, Enabled = true, Realm = realm, RemoteRealm = realm,
AllowedOperations = DataOperations.Browse | DataOperations.Subscribe | DataOperations.AlarmSubscribe, MaxConditions = maxConditions,
ConditionStaleTimeoutMilliseconds = 100, ConditionSnapshotTimeoutMilliseconds = 30_000, BranchName = id,
RemoteNamespaceUri = realm == DataRealm.Raw ? "https://zb.com/otopcua/raw" : "https://zb.com/otopcua/uns",
@@ -261,6 +534,15 @@ public sealed class GrpcDataProjectedConditionAccessTests
public async Task<FakeStream> NextStreamAsync() => await Connections.Streams.Reader.ReadAsync(TestContext.Current.CancellationToken);
/// <summary>The next stream within <paramref name="within"/>, or null.</summary>
public async Task<FakeStream?> TryNextStreamAsync(TimeSpan within)
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
cts.CancelAfter(within);
try { return await Connections.Streams.Reader.ReadAsync(cts.Token); }
catch (OperationCanceledException) when (!TestContext.Current.CancellationToken.IsCancellationRequested) { return null; }
}
public async Task WaitAsync(Func<bool> condition)
{
var deadline = DateTime.UtcNow.AddSeconds(10);
@@ -278,7 +560,8 @@ public sealed class GrpcDataProjectedConditionAccessTests
{
public long CatalogEpoch => 1;
public long AuthorityEpoch => 1;
public bool IsActive => true;
public bool Active { get; set; } = true;
public bool IsActive => Active;
}
internal sealed class FakeMappings(List<ProjectedMappingPlacement> current) : IProjectedConditionMappings
@@ -294,20 +577,40 @@ public sealed class GrpcDataProjectedConditionAccessTests
private readonly List<ImportedConditionUpdate> _applied = [];
private readonly List<string> _removed = [];
private readonly List<string> _stale = [];
private readonly List<string> _staleKeys = [];
private readonly HashSet<string> _live = new(StringComparer.Ordinal);
private int _refresh;
public IReadOnlyList<ImportedConditionUpdate> Applied { get { lock (_gate) return _applied.ToList(); } }
public IReadOnlyList<string> Removed { get { lock (_gate) return _removed.ToList(); } }
public IReadOnlyList<string> Stale { get { lock (_gate) return _stale.ToList(); } }
public IReadOnlyList<string> StaleKeys { get { lock (_gate) return _staleKeys.ToList(); } }
/// <summary>The keys the sink holds right now (applied minus removed).</summary>
public IReadOnlyCollection<string> Live { get { lock (_gate) return _live.ToList(); } }
public int RefreshRequired => Volatile.Read(ref _refresh);
public void ApplyConditions(IReadOnlyList<ImportedConditionUpdate> updates) { lock (_gate) _applied.AddRange(updates); }
public void RemoveConditions(string connectionId, IReadOnlyCollection<string> conditionKeys) { lock (_gate) _removed.AddRange(conditionKeys); }
/// <summary>When set, a removal blocks until released (the S3 race window, held open).</summary>
public TaskCompletionSource? RemovalGate { get; set; }
public void ApplyConditions(IReadOnlyList<ImportedConditionUpdate> updates)
{
lock (_gate) { _applied.AddRange(updates); foreach (var u in updates) _live.Add(u.State.ConditionKey); }
}
public void RemoveConditions(string connectionId, IReadOnlyCollection<string> conditionKeys)
{
RemovalGate?.Task.Wait(TimeSpan.FromSeconds(10));
lock (_gate) { _removed.AddRange(conditionKeys); foreach (var k in conditionKeys) _live.Remove(k); }
}
public void MarkConnectionStale(string connectionId) { lock (_gate) _stale.Add(connectionId); }
public void MarkConditionsStale(string connectionId, IReadOnlyCollection<string> conditionKeys) { lock (_gate) _staleKeys.AddRange(conditionKeys); }
public void RequireRefresh(string connectionId) => Interlocked.Increment(ref _refresh);
}
internal sealed class FakeConnections : IGrpcDataAdapterConnectionSource
{
public Channel<FakeStream> Streams { get; } = Channel.CreateUnbounded<FakeStream>();
/// <summary>Metadata answers Bad for these root indexes (deployed order).</summary>
public HashSet<int> MetadataFails { get; } = [];
/// <summary>The serving roles of the next streams (Primary when empty).</summary>
public Queue<string> Roles { get; } = new();
public int PrimarySubscribes;
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new Lease(new FakeConnection(this)));
@@ -319,29 +622,42 @@ public sealed class GrpcDataProjectedConditionAccessTests
}
}
private sealed class FakeConnection(FakeConnections owner) : IDataConnection
private sealed class FakeConnection(FakeConnections owner) : IDataConnection, IDataPrimarySubscriptionSource
{
public Task<IDataSubscription> SubscribePrimaryAsync(CancellationToken cancellationToken)
{
Interlocked.Increment(ref owner.PrimarySubscribes);
return SubscribeAsync(cancellationToken);
}
public DataTarget Target { get; } = new(DataTargetMode.Cluster, "origin", null);
public TimeProvider Clock => TimeProvider.System;
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(request.Views.Select(v => new DataItemResult<DataMetadata>("0", DataItemStatus.Good,
new DataMetadata(v with { Subject = v.Address.Identifier }, v.Address.Identifier, "Folder", DataValueKind.Null, -1, [], false,
Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(request.Views.Select((v, i) => owner.MetadataFails.Contains(i)
? new DataItemResult<DataMetadata>("0", DataItemStatus.Unavailable, null, null)
: new DataItemResult<DataMetadata>("0", DataItemStatus.Good, new DataMetadata(v with { Subject = v.Address.Identifier }, v.Address.Identifier, "Folder", DataValueKind.Null, -1, [], false,
DataOperations.Browse, 1, null, null, false), null)).ToArray());
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
{
var stream = new FakeStream();
string role;
lock (owner.Roles) role = owner.Roles.TryDequeue(out var next) ? next : "Primary";
var stream = new FakeStream(role);
owner.Streams.Writer.TryWrite(stream);
return Task.FromResult<IDataSubscription>(stream);
}
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
internal sealed class FakeStream : IDataSubscription
internal sealed class FakeStream(string role = "Primary") : IDataSubscription, IDataSubscriptionProvenance
{
public ServingIdentity Serving { get; } = new("origin-1", "inc-1", role, 1, 1);
public bool Disposed { get; private set; }
/// <summary>The mapping ids this stream opened items for.</summary>
public IReadOnlyList<string> Mappings => Open.Items.Select(x => x.ClientItemId).ToArray();
private readonly Channel<DataSubscriptionFrame> _frames = Channel.CreateUnbounded<DataSubscriptionFrame>();
private readonly TaskCompletionSource<OpenSubscription> _open = new(TaskCreationOptions.RunContinuationsAsynchronously);
private long _sequence;
@@ -355,7 +671,7 @@ public sealed class GrpcDataProjectedConditionAccessTests
}
public IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken);
public ValueTask DisposeAsync() { _frames.Writer.TryComplete(); return ValueTask.CompletedTask; }
public ValueTask DisposeAsync() { Disposed = true; _frames.Writer.TryComplete(); return ValueTask.CompletedTask; }
private OpenSubscription Open => _open.Task.Wait(TimeSpan.FromSeconds(10)) ? _open.Task.Result : throw new TimeoutException("no open");
@@ -365,8 +681,16 @@ public sealed class GrpcDataProjectedConditionAccessTests
return new DataItemHandle(Open.SubscriptionId, Open.StreamEpoch, (ulong)(index + 1), 1);
}
public void Ack() => _frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, "open",
Open.Items.Select(x => new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Good, HandleOf(x.ClientItemId), x.Settings, null)).ToArray()));
public void Ack(params string[] refused) => _frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, "open",
Open.Items.Select(x => refused.Contains(x.ClientItemId)
? new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Unavailable, null, x.Settings, "secondary")
: new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Good, HandleOf(x.ClientItemId), x.Settings, null)).ToArray()));
/// <summary>Snapshot record frames exactly as the A2 origin frames them (is_snapshot, no total).</summary>
public void SnapshotRecords(string mapping, params DataConditionState[] records)
{
foreach (var chunk in records.Chunk(128)) Frame(mapping, true, null, chunk, false);
}
public void Begin(string mapping, int total) => Frame(mapping, true, total, [], false);
public void Records(string mapping, params DataConditionState[] records)