diff --git a/docs/DataConnections.md b/docs/DataConnections.md index ecf289f31..d11dab740 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -262,6 +262,15 @@ items or an origin is busy. per-parent child count). Removing a projected anchor, or swapping it for a root leaf, now also tombstones the anchor's own monitored node. Removing an imported condition purges only its own cached verdicts. +- **An unresolvable configured reference backs off (#1053, R-25).** `ConfiguredProjectedInterestOwner`'s shared 1 s sweep + used to re-run discovery for every desired reference with no lease, every second, for as long as the interest lasted. + A failed resolve now waits 1 s, doubling to a 30 s ceiling, before the sweep tries it again (an explicit interest change + still re-queues at once; a held lease is still re-checked every sweep). 60 s of an unreachable origin: 61 discoveries ⇒ 6. +- **Not changed, by decision (#1053, R-25):** the driver callback still publishes every value into the source hub whether + or not a gRPC consumer is subscribed. That cache is what a new subscription's first snapshot and a projected Read are + answered from (a gRPC-demanded source switches to acknowledged acquisition instead), so publishing "only with interest" + would leave a slow-changing tag with no first value. The R-3 trigger it fed is closed by the #994 re-queue above. + Perf harness: `GrpcDataWave3PerfTests` (`Category=Perf`, opt-in `OTOPCUA_GRPCDATA_PERF=1`). ### Mixed versions (X0 rollout) diff --git a/docs/DriverLifecycle.md b/docs/DriverLifecycle.md index 6a0a83ca2..ef0a01826 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -596,6 +596,10 @@ Warning / counter increment and a disable then re-enable of the same id never in holds the id in the `ChildHealthLedger` (`Forget` then `Readmit` on the next spawn), so the stopped child's late health publish cannot resurrect its diagnostics entry. +An operator **Restart** deliberately KEEPS the latch (#1053): the nodes stay in the address space, still Bad, and the +respawned incarnation is what must re-publish them. The stopped incarnation's `PostStop` comms-loss announcement re-latches +the current ref set and cancels the audit the old incarnation armed; the new incarnation's `Connected` re-arms it. + ### The connect path feeds the circuit breaker (R2-10 T10 closure) `IDriver.InitializeAsync` is routed through the capability invoker as diff --git a/docs/security.md b/docs/security.md index 5845bd3e5..7ee195ab2 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1148,6 +1148,15 @@ device folder asks once per child. Those seams go through a per-`(session, node, decision cache (`SessionAclDecisionCache`), cleared wholesale whenever the authority generation advances. +**A warm cached decision on a UNS node allocates nothing (#1053, review U-8).** The UNS placement still runs on +every call, ahead of the cache (it reads live topology), but its products are cached: the node manager keeps each UNS +folder's live id chain on the folder instance (re-verified against the live ancestry on every call, rebuilt on any +mismatch), the generation hands out one segment array per folder/equipment path, and the authorizer keys its resolved +cache keys on that array. A reference variable is keyed on its own identifier (its scope is its split, the same key a +Path-kind lookup uses), and the caller's `DataCallerIdentity` is built once per session identity. Measured warm per call: +equipment folder 416 → 0 B, folder-owned virtual tag 592 → 0 B, UNS reference variable 680 → 0 B +(`NodeManagerUnsDecisionAllocationTests`). + ⚠️ **The cache holds the grant walk, not the decision.** Grants, principals and the trie are all fixed for the life of a generation, so memoizing the walk is sound. A key's `ExpiresUtc` passes with the *clock*, not with a deployment — so revocation and expiry are re-checked on every call, outside the diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/DataPlaneAuthority.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/DataPlaneAuthority.cs index a56d38551..f0f5e8f28 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/DataPlaneAuthority.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/DataPlaneAuthority.cs @@ -137,10 +137,22 @@ public sealed class DataPlaneAuthoritySnapshot return false; } - unsSegments = path.Segments.Skip(1).ToArray(); + unsSegments = BelowRealm(path); return true; } + /// + /// 's segments below the realm, computed once per path instance (#1053 / review U-8). A + /// generation's paths are immutable and these lookups run per ACL decision on every UNS node, so the + /// Skip(1).ToArray() they used to do allocated on every warm cached decision. Callers treat the result as + /// read-only; the same instance is returned for the life of the path, which also lets the authorizer key its own + /// per-placement cache on it. + /// + private static IReadOnlyList BelowRealm(NodeAclPath path) => + BelowRealmCache.GetValue(path, static p => p.Segments.Skip(1).ToArray()); + + private static readonly System.Runtime.CompilerServices.ConditionalWeakTable BelowRealmCache = new(); + /// /// UNS folder id → (its ACL path, its folder-id chain) for every UNS Area, Line and Equipment in the /// artifact this generation was built from (Gitea #808). Keyed OrdinalIgnoreCase (identifier rule). @@ -225,7 +237,7 @@ public sealed class DataPlaneAuthoritySnapshot if (!string.Equals(scope.IdChain[i], liveIdChain[i], StringComparison.OrdinalIgnoreCase)) return false; } - unsSegments = scope.Path.Segments.Skip(1).ToArray(); + unsSegments = BelowRealm(scope.Path); return true; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index dfa68f3ce..9e9edb8ac 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -3391,7 +3391,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage // authority. Never a fallback to splitting the opaque id. var native = false; string? owner = null; - List? ownerChain = null; + IReadOnlyList? ownerChain = null; lock (Lock) { var key = MapKey(condition.NodeId); @@ -6396,8 +6396,14 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage /// /// A live hierarchy folder. /// The id chain. - private List LiveHierarchyChain(NodeState folder) + private IReadOnlyList LiveHierarchyChain(NodeState folder) { + // #1053 / review U-8: the chain is cached on the folder INSTANCE but never trusted — every call re-walks the live + // ancestry (alloc-free) and only reuses the cached array when every live id still matches it, so a re-parent, a + // rebuild that re-mints an ancestor, or a torn-down ancestor rebuilds it exactly as before. The cached array is + // also what the authorizer keys its per-placement cache on (one stable instance per placement). + if (_hierarchyChains.TryGetValue(folder, out var cached) && LiveChainMatches(folder, cached)) return cached; + var chain = new List(3); NodeState? current = folder; for (var depth = 0; current is not null && depth < MaxUnsAncestry; depth++, current = ParentOf(current)) @@ -6407,9 +6413,32 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage } chain.Reverse(); - return chain; + var built = chain.ToArray(); + _hierarchyChains.AddOrUpdate(folder, built); + return built; } + /// Whether 's live ancestry is exactly (no allocation). + private bool LiveChainMatches(NodeState folder, string[] cached) + { + var i = cached.Length - 1; + NodeState? current = folder; + for (var depth = 0; current is not null && depth < MaxUnsAncestry; depth++, current = ParentOf(current)) + { + if (LiveUnsFolderId(current) is not { } id || id.Contains('/')) break; + if (i < 0 || !string.Equals(cached[i], id, StringComparison.Ordinal)) return false; + i--; + } + + return i == -1; + } + + /// + /// The last live id chain computed per UNS folder instance (#1053 / review U-8). Weak, so a torn-down folder's entry + /// goes with it; validated against the live ancestry on every read (). + /// + private readonly ConditionalWeakTable _hierarchyChains = new(); + /// The EquipmentId the exact live is bound to, or null. Call under Lock. private string? BoundScriptedOwner(RealmKey key, ConditionState condition) => _scriptedAlarmOwners.TryGetValue(key, out var binding) @@ -6423,7 +6452,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage /// The live folder-id ancestry of the equipment folder a BOUND scripted condition hangs under (the #808 folder /// rule applied to the #797 owner), or null when unbound or no longer under that folder. Call under Lock. /// - private List? BoundScriptedOwnerChain(RealmKey key, ConditionState condition) => + private IReadOnlyList? BoundScriptedOwnerChain(RealmKey key, ConditionState condition) => BoundScriptedOwner(key, condition) is { } owner && ParentOf(condition) is FolderState parent && LiveUnsFolderId(parent) is { } parentId diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs index 663f5b457..fbdbd7b7f 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs @@ -159,8 +159,7 @@ public sealed class DataPlaneAuthorizer public bool AuthorizeProjectedAnchor(RoleCarryingUserIdentity? identity, NodeScope scope) { if (identity is null) return false; - var caller = new DataCallerIdentity(identity.Principal, identity.ApiKeyId, - identity.CredentialVersion, identity.CredentialExpiresUtc); + var caller = identity.CallerIdentity; return _policy.AuthorizeLocal(caller, OpcUaOperation.Browse, scope); } @@ -211,8 +210,7 @@ public sealed class DataPlaneAuthorizer if (operation is not (OpcUaOperation.Browse or OpcUaOperation.Read or OpcUaOperation.WriteOperate or OpcUaOperation.WriteTune or OpcUaOperation.WriteConfigure or OpcUaOperation.TransferSubscriptions or OpcUaOperation.HistoryRead)) { veto = DeniedResult; return true; } - var caller = new DataCallerIdentity(identity.Principal, identity.ApiKeyId, - identity.CredentialVersion, identity.CredentialExpiresUtc); + var caller = identity.CallerIdentity; try { veto = _policy.AuthorizeMapped(caller, operation, resolved.View, resolved.Live.Serving, @@ -358,8 +356,7 @@ public sealed class DataPlaneAuthorizer if (identity?.ApiKeyId is not { Length: > 0 } keyId) return null; var snapshot = _authority.Current; - var caller = new DataCallerIdentity(identity.Principal, identity.ApiKeyId, - identity.CredentialVersion, identity.CredentialExpiresUtc); + var caller = identity.CallerIdentity; return !_policy.IsCallerUsable(caller, allowLegacyUnversionedKey: true) || !ReferenceEquals(snapshot, _authority.Current) ? DenyRevokedKey(operation, nodeId, identity.Principal, keyId, snapshot.GenerationId, cached: false) @@ -524,27 +521,45 @@ public sealed class DataPlaneAuthorizer /// The node's s= identifier (split only for the shapes that are paths). /// The generation in force. /// The live facts the node manager reported. - /// The resolved path below the UNS realm root. + /// + /// The resolved path below the UNS realm root, or when the scope is the identifier's own + /// split (built by the caller only on a cache miss). + /// + /// The decision-cache key naming that scope. /// Why placement failed. /// when the subject is placed. private static bool TryPlaceUnsSubject( string identifier, DataPlaneAuthoritySnapshot snapshot, in UnsAclSubject subject, - out IReadOnlyList segments, + out IReadOnlyList? segments, + out string cacheKey, out string reason) { + // #1053 / review U-8: placement runs on EVERY decision, ahead of the cache, so a success here must not allocate. + // A subject whose scope IS its identifier's own split (a reference variable, a reference-shaped unknown id) is + // reported with segments == null and keyed on the identifier itself — Evaluate then builds that split only on a + // cache MISS, and the key names the same scope a Path-kind lookup of the identifier would (BuildScope = split), + // so the two can share an entry. Folder-placed subjects reuse the generation's cached segment array and the + // per-placement keys below. IReadOnlyList owner; bool owned; switch (subject.Kind) { case UnsAclSubjectKind.Unknown: - { - var split = identifier.Split('/', StringSplitOptions.RemoveEmptyEntries); - segments = split.Length == ReferenceVariableSegments ? split : [UnknownNodeSegment]; + if (CountSegments(identifier) == ReferenceVariableSegments) + { + segments = null; + cacheKey = identifier; + } + else + { + segments = UnknownSegments; + cacheKey = UnknownCacheKey; + } + reason = string.Empty; return true; - } case UnsAclSubjectKind.ReferenceVariable: { @@ -552,18 +567,18 @@ public sealed class DataPlaneAuthorizer // path is where THIS generation puts its equipment (plus one effective-name segment). An equipment // moved to another line, or an Area/Line/Equipment renamed, leaves the variable's id on the OLD names // until the address space re-points it; the old names' grants must not keep reading / writing it. - var split = identifier.Split('/', StringSplitOptions.RemoveEmptyEntries); if (subject.FolderChain is not { Count: > 0 } equipmentChain || !snapshot.TryGetUnsFolderSegments(equipmentChain[^1], equipmentChain, out var equipment) - || split.Length != equipment.Count + 1 - || !split.Take(equipment.Count).SequenceEqual(equipment, StringComparer.Ordinal)) + || !IsPlacementPlusOneName(identifier, equipment)) { - segments = []; + segments = null; + cacheKey = string.Empty; reason = $"the UNS reference variable's path does not match its equipment {subject.FolderChain?.LastOrDefault() ?? "(none)"}'s placement in generation {snapshot.GenerationId} (moved, renamed, or not yet re-pointed)"; return false; } - segments = split; + segments = null; + cacheKey = identifier; reason = string.Empty; return true; } @@ -572,7 +587,8 @@ public sealed class DataPlaneAuthorizer if (subject.FolderChain is not { Count: > 0 } chain || !snapshot.TryGetUnsFolderSegments(chain[^1], chain, out owner)) { - segments = []; + segments = null; + cacheKey = string.Empty; reason = $"the UNS folder {subject.FolderChain?.LastOrDefault() ?? "(none)"} is not placed as generation {snapshot.GenerationId} deploys it (unknown, moved, or not yet rebuilt)"; return false; } @@ -584,7 +600,8 @@ public sealed class DataPlaneAuthorizer if (!TryPlaceScriptedCondition( snapshot, subject.AlarmId, subject.OwnerEquipmentId, subject.FolderChain, out owner, out reason)) { - segments = []; + segments = null; + cacheKey = string.Empty; return false; } @@ -592,16 +609,85 @@ public sealed class DataPlaneAuthorizer break; default: - segments = []; + segments = null; + cacheKey = string.Empty; reason = "unrecognised UNS subject"; return false; } - segments = owned ? [.. owner, OwnedNodeSegment] : owner; + var placement = PlacementOf(owner); + segments = owned ? placement.OwnedSegments : owner; + cacheKey = owned ? placement.OwnedKey : placement.Key; reason = string.Empty; return true; } + /// The scope an id no live node holds is placed at (see ). + private static readonly string[] UnknownSegments = [UnknownNodeSegment]; + + /// The decision-cache key of . + private static readonly string UnknownCacheKey = ResolvedScopeCacheKey(UnknownSegments); + + /// + /// The resolved scopes and cache keys of one placement (an owner path) — the folder itself and a node it owns. + /// Built once per placement ARRAY: the generation hands out the same segment array for a path for its whole life + /// (DataPlaneAuthoritySnapshot.TryGetUnsFolderSegments / TryGetEquipmentUnsSegments), so a weak + /// table keyed on it is alloc-free on a warm hit and dies with the generation (#1053 / review U-8). + /// + private sealed class UnsPlacement + { + public UnsPlacement(IReadOnlyList owner) + { + Key = ResolvedScopeCacheKey(owner); + OwnedSegments = [.. owner, OwnedNodeSegment]; + OwnedKey = ResolvedScopeCacheKey(OwnedSegments); + } + + /// The folder's own cache key. + public string Key { get; } + + /// The scope of a node the folder owns: the owner path + . + public string[] OwnedSegments { get; } + + /// The cache key of . + public string OwnedKey { get; } + } + + private static readonly System.Runtime.CompilerServices.ConditionalWeakTable, UnsPlacement> Placements = new(); + + private static UnsPlacement PlacementOf(IReadOnlyList owner) => + Placements.GetValue(owner, static o => new UnsPlacement(o)); + + /// How many non-empty /-separated segments has (the split's length). + private static int CountSegments(string identifier) + { + var span = identifier.AsSpan(); + var count = 0; + foreach (var range in span.Split('/')) + if (!span[range].IsEmpty) count++; + return count; + } + + /// + /// Whether 's non-empty segments are exactly followed by + /// one more (the effective name) — the split + Take + SequenceEqual it replaces, without allocating. + /// + private static bool IsPlacementPlusOneName(string identifier, IReadOnlyList placement) + { + var span = identifier.AsSpan(); + var index = 0; + foreach (var range in span.Split('/')) + { + var segment = span[range]; + if (segment.IsEmpty) continue; + if (index > placement.Count) return false; + if (index < placement.Count && !segment.SequenceEqual(placement[index].AsSpan())) return false; + index++; + } + + return index == placement.Count + 1; + } + /// /// The decision-cache key for a node authorized at a RESOLVED scope rather than at its split identifier. It /// names the scope, not the node, because the cached grant walk depends only on the scope — and keying on the @@ -673,8 +759,7 @@ public sealed class DataPlaneAuthorizer // the next deploy — the generation never moves, so nothing would drop the entry. var now = _time.GetUtcNow().UtcDateTime; if (identity.ApiKeyId is { Length: > 0 } keyId - && (!_policy.IsCallerUsable(new DataCallerIdentity(identity.Principal, identity.ApiKeyId, - identity.CredentialVersion, identity.CredentialExpiresUtc), allowLegacyUnversionedKey: true) + && (!_policy.IsCallerUsable(identity.CallerIdentity, allowLegacyUnversionedKey: true) || !ReferenceEquals(snapshot, _authority.Current))) return DenyRevokedKey(operation, nodeId, identity.Principal, keyId, snapshot.GenerationId, cached); @@ -709,11 +794,11 @@ public sealed class DataPlaneAuthorizer var subject = resolve(identifier); if (subject.Kind != UnsAclSubjectKind.Path) { - if (!TryPlaceUnsSubject(identifier, snapshot, subject, out var placed, out var reason)) + if (!TryPlaceUnsSubject(identifier, snapshot, subject, out var placed, out var key, out var reason)) return Deny(operation, nodeId, identity.Principal, reason, cached); resolvedSegments = placed; - cacheIdentifier = ResolvedScopeCacheKey(placed); + cacheIdentifier = key; } } @@ -724,8 +809,7 @@ public sealed class DataPlaneAuthorizer // UserAuthorizationState. One Browse of a device folder asks this once per child. return memoized && ReferenceEquals(snapshot, _authority.Current) && (identity.ApiKeyId is not { Length: > 0 } || _policy.IsCallerUsable( - new DataCallerIdentity(identity.Principal, identity.ApiKeyId, - identity.CredentialVersion, identity.CredentialExpiresUtc), allowLegacyUnversionedKey: true)) + identity.CallerIdentity, allowLegacyUnversionedKey: true)) ? null : DenyNoGrant(operation, nodeId, identity.Principal, snapshot.GenerationId, cached); } @@ -773,8 +857,7 @@ public sealed class DataPlaneAuthorizer NodeScope scope, DateTime now) { - var caller = new DataCallerIdentity(identity.Principal, identity.ApiKeyId, - identity.CredentialVersion, identity.CredentialExpiresUtc); + var caller = identity.CallerIdentity; return _policy.AuthorizeLocal(caller, operation, scope, allowLegacyUnversionedKey: true); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/RoleCarryingUserIdentity.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/RoleCarryingUserIdentity.cs index 25fc1a4ae..da4a0afca 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/RoleCarryingUserIdentity.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/RoleCarryingUserIdentity.cs @@ -97,4 +97,15 @@ public sealed class RoleCarryingUserIdentity : RoleBasedIdentity /// Original credential expiry captured at activation. public DateTimeOffset? CredentialExpiresUtc { get; } + + private ZB.MOM.WW.OtOpcUa.Core.Authorization.DataCallerIdentity? _callerIdentity; + + /// + /// The policy-side view of this identity (principal, key id, credential version + expiry), built once per identity + /// rather than once per ACL decision (#1053 / review U-8: the cached decision path allocated it on every hit). Every + /// input is immutable, so a benign race builds two equal instances. + /// + internal ZB.MOM.WW.OtOpcUa.Core.Authorization.DataCallerIdentity CallerIdentity => + _callerIdentity ??= new ZB.MOM.WW.OtOpcUa.Core.Authorization.DataCallerIdentity( + Principal, ApiKeyId, CredentialVersion, CredentialExpiresUtc); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConfiguredProjectedInterestOwner.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConfiguredProjectedInterestOwner.cs index 29166d5f6..d1cd778d7 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConfiguredProjectedInterestOwner.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConfiguredProjectedInterestOwner.cs @@ -17,7 +17,20 @@ public sealed class ConfiguredProjectedInterestOwner : IProjectedDependencyInter internal bool Desired = true, Queued, Running; internal IConfiguredProjectionLease? Lease; internal CancellationTokenSource? InFlight; + // #1053 (R-25): consecutive failed resolves and when the sweep may try again. An explicit SetInterest re-queues + // regardless; only the shared 1 s sweep honours the backoff. + internal int Failures; + internal DateTimeOffset NextAttemptUtc; } + + /// First retry delay after a configured reference fails to resolve (#1053 / R-25). + public static readonly TimeSpan MinRetryDelay = TimeSpan.FromSeconds(1); + + /// Ceiling of that backoff: a reference whose origin comes back is resolved within this long. + public static readonly TimeSpan MaxRetryDelay = TimeSpan.FromSeconds(30); + + private static TimeSpan RetryDelay(int failures) => + TimeSpan.FromTicks(Math.Min(MaxRetryDelay.Ticks, MinRetryDelay.Ticks * (1L << Math.Min(Math.Max(failures, 1) - 1, 20)))); private readonly object _sync = new(); private readonly Dictionary _entries = new(StringComparer.Ordinal); private readonly Queue _ready = new(); @@ -106,6 +119,13 @@ public sealed class ConfiguredProjectedInterestOwner : IProjectedDependencyInter lock (_sync) { entry.Lease = acquired; entry.Running = false; + if (acquired is not null) entry.Failures = 0; + else if (operation is not null && !canceled && entry.Desired) + { + // #1053 (R-25): an unresolvable configured reference used to be rediscovered on every 1 s sweep forever. + entry.Failures++; + entry.NextAttemptUtc = _clock.GetUtcNow() + RetryDelay(entry.Failures); + } if (!entry.Desired || _disposed) { if (entry.Lease is not null) Queue(entry); @@ -120,7 +140,13 @@ public sealed class ConfiguredProjectedInterestOwner : IProjectedDependencyInter { using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1), _clock); while (await timer.WaitForNextTickAsync(_stop.Token).ConfigureAwait(false)) - lock (_sync) foreach (var entry in _entries.Values) if (entry.Desired) Queue(entry); + { + var now = _clock.GetUtcNow(); + // A held lease is re-checked every sweep (cheap: IsValid); an entry without one waits out its backoff. + lock (_sync) + foreach (var entry in _entries.Values) + if (entry.Desired && (entry.Lease is not null || now >= entry.NextAttemptUtc)) Queue(entry); + } } catch (OperationCanceledException) { } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerUnsDecisionAllocationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerUnsDecisionAllocationTests.cs new file mode 100644 index 000000000..50473a165 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerUnsDecisionAllocationTests.cs @@ -0,0 +1,228 @@ +using Microsoft.Extensions.Logging.Abstractions; +using Opc.Ua; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests; + +/// +/// lmxopcua#1053 (review 02 U-8): a WARM cached ACL decision on a UNS node used to allocate ahead of the decision +/// cache on every call — the live id-chain list, an identifier split, LINQ enumerators, the resolved segment array +/// and a string.Join cache key — about 8–12 short-lived objects per node per decision (≈10k per 1,000-node +/// UNS Read). The resolver still runs per call (it reads live topology); its products are now cached on the folder +/// instance / generation, so a warm hit allocates nothing. +/// +public sealed class NodeManagerUnsDecisionAllocationTests : IDisposable +{ + private const string Cluster = "SITE-A"; + private const string Principal = "scadabridge"; + private const string KeyId = "k-1053"; + private const string AreaId = "UA-0000000001"; + private const string LineId = "UL-0000000001"; + private const string Pump = "EQ-00000000a1b2"; + private const string Fan = "EQ-00000000c3d4"; + private const string VirtualTag = Pump + "/Temp"; + private const string Reference = "Area1/Line1/Pump/Speed"; + private const string RawTag = "Plant/Modbus/dev1/Speed"; + private const string Alarm = "scripted-pump-hi"; + private const int Calls = 2_000; + + private static readonly DateTime Start = new(2026, 12, 3, 12, 0, 0, DateTimeKind.Utc); + private static CancellationToken Ct => TestContext.Current.CancellationToken; + private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), $"otopcua-1053-{Guid.NewGuid():N}"); + + /// + /// Each UNS shape the resolver places — the equipment folder itself, a node it owns (a virtual tag), and a UNS + /// reference variable — answers a warm cached Read with zero bytes allocated on the calling thread. Positive + /// control: every verdict is an ALLOW from a narrow Equipment grant (so the placement did run), and the sibling + /// equipment the grant does not cover is a DENY. + /// + [Fact] + public async Task A_warm_cached_decision_on_a_uns_node_allocates_nothing() + { + var (host, server) = await BootAsync(); + try + { + var nm = server.NodeManager!; + Topology(nm); + var authorizer = Wire(nm); + var ns = nm.NamespaceIndexForRealm(AddressSpaceRealm.Uns); + var identity = new RoleCarryingUserIdentity( + new UserNameIdentityToken { UserName = "apikey" }, [], Principal, KeyId); + + nm.ResolveUnsAclSubject(Pump).Kind.ShouldBe(UnsAclSubjectKind.Folder); + nm.ResolveUnsAclSubject(VirtualTag).Kind.ShouldBe(UnsAclSubjectKind.Folder); + nm.ResolveUnsAclSubject(Reference).Kind.ShouldBe(UnsAclSubjectKind.ReferenceVariable); + nm.ResolveUnsAclSubject(Alarm).Kind.ShouldBe(UnsAclSubjectKind.ScriptedCondition); + authorizer.IsAllowedCached(identity, OpcUaOperation.Read, new NodeId(Fan, ns), AddressSpaceRealm.Uns) + .ShouldBeFalse("a sibling equipment the grant does not cover is denied (negative control)"); + + var measured = new List<(string Id, double PerCall)>(); + foreach (var id in new[] { Pump, VirtualTag, Reference, Alarm }) + { + var nodeId = new NodeId(id, ns); + authorizer.IsAllowedCached(identity, OpcUaOperation.Read, nodeId, AddressSpaceRealm.Uns) + .ShouldBeTrue($"{id} is covered by the Equipment grant"); + + var before = GC.GetAllocatedBytesForCurrentThread(); + var allowed = 0; + for (var i = 0; i < Calls; i++) + if (authorizer.IsAllowedCached(identity, OpcUaOperation.Read, nodeId, AddressSpaceRealm.Uns)) allowed++; + var perCall = (GC.GetAllocatedBytesForCurrentThread() - before) / (double)Calls; + + allowed.ShouldBe(Calls); + TestContext.Current.TestOutputHelper?.WriteLine($"{id}: {perCall:F3} bytes per warm decision"); + measured.Add((id, perCall)); + } + + measured.ShouldAllBe(m => m.PerCall < 1d, + "a warm cached decision must not allocate: " + string.Join(", ", measured.Select(m => $"{m.Id}={m.PerCall:F3} B/call"))); + } + finally { await host.DisposeAsync(); } + } + + /// + /// The cached chain is never trusted blindly: moving the equipment to another line (a rebuild that re-mints the + /// folder under a new parent) is re-checked against the LIVE ancestry on the next decision, and is denied until + /// the generation agrees — exactly as before the cache. + /// + [Fact] + public async Task A_cached_chain_follows_a_live_reparent() + { + var (host, server) = await BootAsync(); + try + { + var nm = server.NodeManager!; + Topology(nm); + var authorizer = Wire(nm); + var ns = nm.NamespaceIndexForRealm(AddressSpaceRealm.Uns); + var identity = new RoleCarryingUserIdentity( + new UserNameIdentityToken { UserName = "apikey" }, [], Principal, KeyId); + var pump = new NodeId(Pump, ns); + var vtag = new NodeId(VirtualTag, ns); + + authorizer.IsAllowedCached(identity, OpcUaOperation.Read, pump, AddressSpaceRealm.Uns).ShouldBeTrue(); + authorizer.IsAllowedCached(identity, OpcUaOperation.Read, vtag, AddressSpaceRealm.Uns).ShouldBeTrue(); + + // Re-parent Pump under a second line the generation does not know about: the live chain changes. + nm.RebuildAddressSpace(); + nm.EnsureFolder(AreaId, parentNodeId: null, displayName: "Area1", realm: AddressSpaceRealm.Uns); + nm.EnsureFolder(LineId, parentNodeId: AreaId, displayName: "Line1", realm: AddressSpaceRealm.Uns); + nm.EnsureFolder("UL-0000000002", parentNodeId: AreaId, displayName: "Line2", realm: AddressSpaceRealm.Uns); + nm.EnsureFolder(Pump, parentNodeId: "UL-0000000002", displayName: "Pump", realm: AddressSpaceRealm.Uns); + nm.EnsureVariable(VirtualTag, Pump, "Temp", "Double", writable: false, AddressSpaceRealm.Uns); + nm.CompleteAddressSpaceApply(); + + ((IReadOnlyList)nm.ResolveUnsAclSubject(Pump).FolderChain!).ShouldBe([AreaId, "UL-0000000002", Pump]); + authorizer.IsAllowedCached(identity, OpcUaOperation.Read, pump, AddressSpaceRealm.Uns) + .ShouldBeFalse("the live chain no longer matches the generation's placement"); + authorizer.IsAllowedCached(identity, OpcUaOperation.Read, vtag, AddressSpaceRealm.Uns).ShouldBeFalse(); + } + finally { await host.DisposeAsync(); } + } + + private static void Topology(OtOpcUaNodeManager nm) + { + nm.EnsureFolder(AreaId, parentNodeId: null, displayName: "Area1", realm: AddressSpaceRealm.Uns); + nm.EnsureFolder(LineId, parentNodeId: AreaId, displayName: "Line1", realm: AddressSpaceRealm.Uns); + nm.EnsureFolder(Pump, parentNodeId: LineId, displayName: "Pump", realm: AddressSpaceRealm.Uns); + nm.EnsureFolder(Fan, parentNodeId: LineId, displayName: "Fan", realm: AddressSpaceRealm.Uns); + nm.EnsureVariable(VirtualTag, Pump, "Temp", "Double", writable: false, AddressSpaceRealm.Uns); + nm.EnsureFolder("Plant/Modbus/dev1", parentNodeId: null, displayName: "dev1", realm: AddressSpaceRealm.Raw); + nm.EnsureVariable(RawTag, "Plant/Modbus/dev1", "Speed", "Double", writable: false, AddressSpaceRealm.Raw); + nm.EnsureVariable(Reference, Pump, "Speed", "Double", writable: false, AddressSpaceRealm.Uns); + nm.AddReference(Reference, AddressSpaceRealm.Uns, RawTag, AddressSpaceRealm.Raw, "Organizes"); + nm.MaterialiseAlarmCondition(Alarm, Pump, "hi", "AlarmCondition", 500, AddressSpaceRealm.Uns); + } + + private static AclScopePathResolver Resolver() => new( + new Dictionary(), + new Dictionary(), + new Dictionary(), + new Dictionary(), + new Dictionary(), + new Dictionary { [AreaId] = "Area1" }, + new Dictionary { [LineId] = (AreaId, "Line1") }, + new Dictionary { [Pump] = (LineId, "Pump"), [Fan] = (LineId, "Fan") }, + []); + + private static DataPlaneAuthorizer Wire(OtOpcUaNodeManager nm) + { + var resolver = Resolver(); + NodeAclPath One(NodeAclScopeKind kind, string id) => resolver.ResolveOne(kind, id).ShouldHaveSingleItem(); + var folders = new Dictionary + { + [AreaId] = new(One(NodeAclScopeKind.UnsArea, AreaId), [AreaId]), + [LineId] = new(One(NodeAclScopeKind.UnsLine, LineId), [AreaId, LineId]), + [Pump] = new(One(NodeAclScopeKind.Equipment, Pump), [AreaId, LineId, Pump]), + [Fan] = new(One(NodeAclScopeKind.Equipment, Fan), [AreaId, LineId, Fan]), + }; + var owners = new Dictionary + { + [Pump] = One(NodeAclScopeKind.Equipment, Pump), + [Fan] = One(NodeAclScopeKind.Equipment, Fan), + }; + NodeAcl[] grants = + [ + new() + { + NodeAclId = "acl-pump", ClusterId = Cluster, Principal = Principal, + ScopeKind = NodeAclScopeKind.Equipment, ScopeId = Pump, PermissionFlags = NodePermissions.ReadOnly, + }, + ]; + ApiKey[] keys = + [ + new() + { + ApiKeyId = KeyId, Name = KeyId, SecretHash = "hash", Principal = Principal, Enabled = true, + CreatedUtc = Start.AddDays(-1), + }, + ]; + var state = new DataPlaneAuthorityState(); + state.Apply(Cluster, "rev-1", keys, grants, resolver.Resolve(grants), owners, + new Dictionary { [Alarm] = Pump }, folders); + var authorizer = new DataPlaneAuthorizer( + state, new TriePermissionEvaluator(state.Tries), enabled: true, NullLogger.Instance, new FixedClock(Start)); + nm.DataPlaneAuthority = state; + nm.Authorizer = authorizer; + return authorizer; + } + + private sealed class FixedClock(DateTime utcNow) : TimeProvider + { + public override DateTimeOffset GetUtcNow() => new(utcNow, TimeSpan.Zero); + } + + private async Task<(OpcUaApplicationHost Host, OtOpcUaSdkServer Server)> BootAsync() + { + var started = await OpcUaHostStart.StartAsync( + port => new OpcUaApplicationHost( + new OpcUaApplicationHostOptions + { + ApplicationName = "OtOpcUa.UnsDecisionAllocationTest", + ApplicationUri = $"urn:OtOpcUa.UnsDecisionAllocationTest:{Guid.NewGuid():N}", + OpcUaPort = port, + PublicHostname = "localhost", + PkiStoreRoot = _pkiRoot, + }, + NullLogger.Instance), + () => new OtOpcUaSdkServer(), Ct); + return (started.Host, started.Server); + } + + /// + public void Dispose() + { + if (Directory.Exists(_pkiRoot)) + { + try { Directory.Delete(_pkiRoot, recursive: true); } + catch (IOException) { /* best effort */ } + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConfiguredInterestBackoffTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConfiguredInterestBackoffTests.cs new file mode 100644 index 000000000..bf1d258aa --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConfiguredInterestBackoffTests.cs @@ -0,0 +1,87 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// lmxopcua#1053 (review 01 R-25): ConfiguredProjectedInterestOwner.SweepAsync re-queued every desired entry +/// every second, so a configured reference that cannot be resolved (origin down, mapping gone) re-ran discovery once a +/// second for as long as the interest lasted. A failed resolve now backs off exponentially (1 s doubling, 30 s cap). +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData")] +public sealed class GrpcDataConfiguredInterestBackoffTests +{ + private static readonly string Reference = ProjectedDataIds.DependencyReference(DataRealm.Raw, + ProjectedDataIds.Identifier("mapping", new DataAddress("origin", "urn:raw", "string", "plant/unresolvable"))); + + /// + /// Sixty one-second sweeps against a reference that never resolves: one discovery per sweep before the fix (~61), + /// at most the backoff schedule's handful after it (t = 0, 1, 3, 7, 15, 31 s). Positive control: the retries do not + /// stop — once discovery succeeds, a later sweep within the 30 s cap acquires the lease. + /// + [Fact(Timeout = 60000)] + public async Task An_unresolvable_configured_reference_backs_off_instead_of_rediscovering_every_second() + { + var ct = TestContext.Current.CancellationToken; + var clock = new ManualTimeProvider(); + var discovery = new FlakyDiscovery(); + await using var owner = new ConfiguredProjectedInterestOwner(discovery, 4, clock: clock); + await clock.WaitForTimerDueAtAsync(clock.Start + TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); + + owner.SetInterest(Reference, true); + await WaitUntilAsync(() => Volatile.Read(ref discovery.Calls) >= 1, ct); + + for (var second = 0; second < 60; second++) + { + clock.Advance(TimeSpan.FromSeconds(1)); + await Task.Delay(30, ct); // let the sweep + a worker act on the tick (an upper bound is what is asserted) + } + + var failedCalls = Volatile.Read(ref discovery.Calls); + failedCalls.ShouldBeLessThanOrEqualTo(8, + $"an unresolvable reference must back off; it was rediscovered {failedCalls} times in 60 s"); + failedCalls.ShouldBeGreaterThanOrEqualTo(3, "it is still retried, just less often"); + + // Positive control: the origin comes back; a sweep within the 30 s cap resolves it. + discovery.Succeed = true; + for (var second = 0; second < 31 && discovery.Acquired == 0; second++) + { + clock.Advance(TimeSpan.FromSeconds(1)); + await Task.Delay(30, ct); + } + await WaitUntilAsync(() => Volatile.Read(ref discovery.Acquired) == 1, ct); + } + + private static async Task WaitUntilAsync(Func condition, CancellationToken ct) + { + var giveUp = DateTime.UtcNow + TimeSpan.FromSeconds(10); + while (!condition()) + { + if (DateTime.UtcNow > giveUp) throw new TimeoutException("condition not reached"); + await Task.Delay(5, ct); + } + } + + private sealed class FlakyDiscovery : IConfiguredProjectionDiscovery + { + public int Calls, Acquired; + public volatile bool Succeed; + + public Task ResolveAsync(string reference, CancellationToken cancellationToken) + { + Interlocked.Increment(ref Calls); + if (!Succeed) return Task.FromResult(null); + Interlocked.Increment(ref Acquired); + return Task.FromResult(new Lease()); + } + } + + private sealed class Lease : IConfiguredProjectionLease + { + public bool IsValid => true; + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostCommsLossRecoveryTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostCommsLossRecoveryTests.cs index 0cc882c55..91d043002 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostCommsLossRecoveryTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostCommsLossRecoveryTests.cs @@ -157,6 +157,53 @@ public sealed class DriverHostCommsLossRecoveryTests : RuntimeActorTestBase meter.SumWithTag("driver_instance", "drv-removed").ShouldBe(0); } + /// + /// #1053 (decided: KEEP). Unlike a removal (R-16, ), + /// an operator RESTART must not clear the comms latch: the nodes stay in the address space, still Bad, and the + /// respawned incarnation is what has to re-publish them — exactly what the audit checks. No host change is needed + /// for that: the stopped incarnation's PostStop comms-loss announcement re-latches the CURRENT ref set and + /// cancels the audit the old incarnation armed, and the new incarnation's Connected re-arms it. Pinned + /// here: no audit fires while the new incarnation is still connecting (well past the old window), and once it + /// connects and stays silent its OWN audit reports the kept ref. + /// + [Fact] + public void Restarting_a_comms_lost_driver_keeps_its_latch_and_audits_it_from_the_new_incarnations_reconnect() + { + var driver = new ScriptedSubscribeDriver { InstanceId = "drv-restart", InitialPush = null }; + var db = NewInMemoryDbFactory(); + var deploymentId = SeedV3Deployment(db, RevA, + rawTags: new[] { (Driver: "drv-restart", DriverName: "Modbus", Device: "dev1", Tag: "speed", DataType: "Double", Writable: false) }, + unsRefs: new[] { (Area: "filling", Line: "line1", Equip: "station1", BackingTag: "speed", Effective: (string?)null) }, + enabled: true); + var audit = TimeSpan.FromSeconds(6); + var (host, publish, _) = SpawnHostAndApply( + this, db, TestNode, deploymentId, RevA, + commsRecoveryAuditDelay: audit, driverFactory: new SingleDriverFactory(driver)); + AwaitCondition(() => driver.SubscribeCount >= 1, PresenceBudget, TestContext.Current.CancellationToken); + using var meter = new MeterRecorder("otopcua.driver.comms_latched_refs"); + + host.Tell(new ReconnectDriver("c1", "drv-restart", "test-operator", Guid.NewGuid())); + publish.FishForMessage(_ => true, ReconnectBudget, cancellationToken: TestContext.Current.CancellationToken); + // The reconnect (silent re-subscribe) arms the old incarnation's audit; restart inside its window, with the new + // incarnation's initialize held so it cannot connect (and re-arm the audit) before the old timer would fire. + AwaitCondition(() => driver.SubscribeCount >= 2, ReconnectBudget, TestContext.Current.CancellationToken); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + driver.InitializeGate = release.Task; + host.Tell(new RestartDriver("c1", "drv-restart", "test-operator", Guid.NewGuid())); + + EventFilter.Warning(contains: "still BadNoCommunication") + .Expect(0, audit + TimeSpan.FromSeconds(3), () => { }, TestContext.Current.CancellationToken); + meter.SumWithTag("driver_instance", "drv-restart").ShouldBe(0); + + // The new incarnation connects, re-subscribes silently, and its own audit reports the ref the restart kept. + EventFilter.Warning(contains: "still BadNoCommunication").ExpectOne(audit + ReconnectBudget, () => + { + driver.InitializeGate = null; + release.SetResult(); + }, TestContext.Current.CancellationToken); + AwaitCondition(() => meter.SumWithTag("driver_instance", "drv-restart") == 1, TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + } + private (IActorRef Host, Akka.TestKit.TestProbe Publish) Arrange(ScriptedSubscribeDriver driver, string driverId) { var db = NewInMemoryDbFactory(); @@ -214,7 +261,11 @@ public sealed class DriverHostCommsLossRecoveryTests : RuntimeActorTestBase public string DriverType => "Modbus"; - public Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask; + /// When set, waits on it (holds a respawned incarnation in Connecting). + public Task? InitializeGate { get; set; } + + public Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => + InitializeGate is { } gate ? gate.WaitAsync(cancellationToken) : Task.CompletedTask; public Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask;