Merge #922: a lapsed projected metadata lease renews on demand (retryable status, never BadUserAccessDenied for a lapse); own renewal pool, bounded HistoryRead wait; review fixes
This commit is contained in:
@@ -90,6 +90,40 @@ reply cannot lengthen it. Renewal grants no parent or sibling visibility, Browse
|
||||
local Browse privilege. Missing capability, denied Metadata or an invalid lease leaves the item
|
||||
unavailable until valid authority can be established.
|
||||
|
||||
**A lapsed lease is not an access denial (#922).** A projected node idle longer than its mapping's
|
||||
`MetadataLeaseMilliseconds` keeps its retained proof; the lease is only *lapsed* when its time ran
|
||||
out or its route was replaced while the local catalog authority, mapping binding and cache
|
||||
generation are all still current and nothing revoked it. On a refused value Read / attribute Read /
|
||||
HistoryRead of such a node, the consumer first authorizes the caller against the lapsed subject
|
||||
(local grant + mapping bit, everything but the lease). A caller without the grant is still
|
||||
`BadUserAccessDenied` and nothing is sent to the origin. A granted caller gets the same exact
|
||||
`GetMetadata` renewal as above, for the operation it is performing (Read / HistoryRead bit, not
|
||||
Subscribe), one per node and operation at a time, with a 250 ms back-off after a failure. On-demand
|
||||
renewals never touch the unary budget (cold reads, writes) or the browse/subscription-renewal fetch
|
||||
slots: they queue (at most 64) for their own pool of `max(1, maxConcurrentFetches / 2)` origin calls,
|
||||
reserve 256 KiB each, and have 3 s end to end, so a batch of N lapsed nodes renews all N:
|
||||
|
||||
- **Value Read** answers `BadWaitingForInitialData` (as a cold read does) while the renewal runs off
|
||||
the request thread; once it commits, a read is scheduled so the client's retry is served from the
|
||||
fresh sample. `BadResourceUnavailable` while a renewal cannot be started (capacity, back-off).
|
||||
A non-Value attribute of a lapsed node answers `BadResourceUnavailable` while it renews.
|
||||
- **HistoryRead** renews within the request and is then served. The wait (one per batch, at most 4 s
|
||||
and never past `HistoryReadDeadline`, no node-manager `Lock` held, the request's cancellation
|
||||
honoured) takes one of the non-local history batch slots first. A batch that finds none free does
|
||||
not wait. A renewal that cannot complete (origin unreachable or silent, no slot) answers
|
||||
`BadResourceUnavailable`. A renewal that succeeded while the node manager's ACL veto still refuses
|
||||
answers `BadUserAccessDenied`.
|
||||
- **Browse:** a cached page past half its lease is served as is *and* refreshed in the background
|
||||
(one refresh per page key), so a re-browse renews the leases of the nodes it lists.
|
||||
|
||||
An origin that stopped granting the operation fails the renewal; the consumer then keeps answering
|
||||
the retryable status (it cannot tell that from an unreachable origin).
|
||||
|
||||
Not covered yet: a **Write** or **CreateMonitoredItems** on a lapsed node is still refused
|
||||
`BadUserAccessDenied` (neither starts a renewal; a re-browse, a Read or a HistoryRead of the node
|
||||
renews it, after which they succeed). A lease that was revoked (`Invalidate`), a removed mapping and a
|
||||
retired node are refusals, not lapses, and are never renewed.
|
||||
|
||||
An authorized logical monitored-item request can survive a physical stream expiry and seek a new
|
||||
pinned binding with bounded retries. The old binding and any queued sample evidence remain tied to
|
||||
their original authority and serving generation. The same item needs a fresh, complete baseline
|
||||
|
||||
@@ -139,7 +139,7 @@ while held, 0 after the session closed; `down` ⇒ 0/0/0/0 for both runs.
|
||||
**Found on the re-run (pre-existing v1 projection behaviour, not an H3 defect — for a follow-up):** an idle projected node's
|
||||
authority lapses with its 15 s `MetadataLeaseMilliseconds`; any read after that is `BadUserAccessDenied` — a value Read exactly as a
|
||||
HistoryRead (reproduced in the Runtime harness) — and a re-browse served from the still-cached browse page does not renew it
|
||||
(live: the H06 rebuild leg denied right after a re-browse). The gate now starts each held leg right after a deploy + re-browse.
|
||||
(live: the H06 rebuild leg denied right after a re-browse). The gate now starts each held leg right after a deploy + re-browse. **Fixed by #922** (`fu922.md`): a lapsed lease now renews on demand. The gate no longer re-browses before H04's resume, and H06(c) idles past the lease on purpose.
|
||||
|
||||
## Review round 3 (approve-with-changes) — fixes
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
# #922 — a lapsed projected metadata lease is not an access denial
|
||||
|
||||
Found in the H3 live gate (`H3.md` §"Found on the re-run"). Pre-existing v1 projection behaviour (95c5e484).
|
||||
|
||||
## Root cause
|
||||
|
||||
A projected node's authority is its catalog proof, bound to a `BoundProjectionLease` whose remote `MetadataAuthorityLease` lasts
|
||||
`MetadataLeaseMilliseconds` (15 s on the rig) from the browse that fetched it. Only a **subscription** ever renewed it
|
||||
(`RemoteNamespaceResolver.RenewExactAsync`, Subscribe only). After the lease lapsed:
|
||||
|
||||
- `ProjectedCatalogCache.TryResolveProjected` / `Valid` required `Lease.IsValid`, so `ProjectedDataAccess.TryAcquire` returned
|
||||
`false`, and the node manager's Read pre-loop mapped **every** `false` to `BadUserAccessDenied`. A lapse looked the same as an
|
||||
ACL denial.
|
||||
- HistoryRead: `AuthorizeHistoryRead` → `DataPlaneAuthorizer` → `MappedSubjectResolver` (`TryResolveProjected`) returned
|
||||
`Deny` ⇒ `BadUserAccessDenied`.
|
||||
- Re-browse: a cached parent page is served while its own lease holds, and nothing renews on a cache hit. A re-browse just
|
||||
before the page's lease ran out therefore renewed nothing, and the nodes lapsed seconds later (the H06 observation).
|
||||
|
||||
## Fix
|
||||
|
||||
| Piece | Change |
|
||||
|---|---|
|
||||
| `BoundProjectionLease.Renewable` | the lease is invalid ONLY because it is transient: the remote time ran out or the route was replaced, while the local catalog authority, mapping binding and cache generation are current and nothing called `Invalidate` |
|
||||
| `ProjectedCatalogCache.TryResolveForRenewal` | the retained, non-retired proof that is valid or `Renewable` (every `ValidCore` fence except the lease) |
|
||||
| `OtOpcUaNodeManager.TryResolveForRenewal` (+ `IProjectedNodeLookup`, sinks) | the committed live definition without the authority check (lock-free snapshot), so the renewal commits against the exact SDK node |
|
||||
| `DataOperationPolicy.AuthorizeMappedSubject` | `AuthorizeMapped` minus the lease checks. Classifies a refusal only and serves nothing |
|
||||
| `IProjectedDataAccess.RenewLapsed` → `ProjectedLapseOutcome {Denied, Renewing, Unavailable}` | `Denied` unless the node is lapsed-renewable AND the caller holds the grant for the operation (local grant + mapping bit + op-specific checks). Otherwise starts ONE exact renewal per node (`RenewExactAsync` generalised to `authorizeAs`/`required` = Read or HistoryRead; the subscription default is unchanged), off the request thread, inside the unary budget, with a 250 ms back-off after a failure. A successful Read renewal then schedules a read so the retry is served from cache |
|
||||
| Read pre-loop | `Denied` ⇒ `BadUserAccessDenied` (unchanged); `Renewing` ⇒ `BadWaitingForInitialData` (as for a cold read); `Unavailable` ⇒ `BadResourceUnavailable`. A non-Value attribute of a lapsed node ⇒ `BadResourceUnavailable` |
|
||||
| `AuthorizeHistoryRead` | renews lapsed projected handles within the request (one block-bridged wait per batch, ≤ 5 s, no `Lock` held — the SDK released it before dispatching, as H3 recorded), re-authorizes, then serves. A renewal that does not complete ⇒ `BadResourceUnavailable` |
|
||||
| `ProjectedBrowseAccess` | an initial cached page past half its lease is served AND refreshed in the background (one in flight per page key) |
|
||||
|
||||
The node-manager `Lock` is never held across a network renewal. The Read path only starts the task. The renewal commits
|
||||
through `IProjectedNamespacePageSink.TryRenewExact`, which takes `Lock` briefly and performs no I/O.
|
||||
|
||||
## Red / green (Runtime harness, `GrpcDataLeaseLapseWireTests`, `Trait Issue=922`, real consumer SDK session + projection stack)
|
||||
|
||||
| Test | master (`05f431f5d` src) | fix |
|
||||
|---|---|---|
|
||||
| value Read after the lease lapses ⇒ retryable, renews on demand without a browse (twice), attribute read not denied | **FAIL** (`BadUserAccessDenied`) | pass |
|
||||
| no local Read grant ⇒ still `BadUserAccessDenied` after the lapse; no metadata/read call; renewal counter 0 (counted synchronously at admission) | pass | pass |
|
||||
| HistoryRead after the lapse ⇒ renewed in the request, Good, 3 values | **FAIL** (`BadUserAccessDenied`) | pass |
|
||||
| lapsed HistoryRead with the origin unreachable ⇒ `BadResourceUnavailable`, nothing read; Good after recovery | **FAIL** (`BadUserAccessDenied`) | pass |
|
||||
| no local HistoryRead grant ⇒ still `BadUserAccessDenied` after the lapse, unsent | pass | pass |
|
||||
| re-browse of a cached page past half its lease renews (origin browse call, lease holds at t0+20 s) | **FAIL** (no origin call) | pass |
|
||||
|
||||
Real ACL denial and lease lapse are tested both ways. The lapse cases are red on master and the ACL-denial controls are green on
|
||||
both. 8 consecutive green runs of the six tests after the final assertion fix.
|
||||
Harness note: the fixture origin observes its single sample once, so the sample's origin age grows with the manual clock. The
|
||||
value tests use a stale timeout and client maxAge longer than the idle gaps, so that age stays out of the result under test.
|
||||
|
||||
## Gates
|
||||
|
||||
`dotnet build -c Release` (solution) 0 errors. Runtime.Tests 2096 passed / 3 skipped / **2 failed** under machine load average
|
||||
100–150: `VirtualTagActorTimerTests.Ticks_during_a_slow_run_coalesce_instead_of_piling_up` and
|
||||
`GrpcDataConfiguredDiscoveryWireTests.Failed_sdk_item_construction_releases_candidate_and_fanout_ownership` (its first
|
||||
subscription publish was not Good, and it calls no code path changed here). Once load dropped, both passed 12/12 on master `src`
|
||||
and 12/12 on the fix. Cause not established, so this is recorded as load-correlated, not as a flake. OpcUaServer.Tests 1460 passed
|
||||
(+2 skips). Host.Tests 497 passed, including `GrpcDataV1CompatibilityTests` (goldens untouched). Core.Tests 385 passed (+1 skip).
|
||||
|
||||
## Live (grpc-data rig, OrbStack, run `f922a-sqlserver`, `--history --history-backend sqlserver`)
|
||||
|
||||
`history_gate.py` with the workaround removed: H04 no longer re-browses before its resume, and H06(c) now deliberately idles
|
||||
`LEASE_LAPSE_SECONDS = 20` (> the 15 s lease) after its restore before the held read. **H01–H06 all PASS** (47/34/35/44/58/238
|
||||
assertions).
|
||||
|
||||
Value-Read probe (one browse, then never again; Client CLI `read --max-age 10000` on CONSUMER, raw/counter and uns/scalar):
|
||||
the fresh-lease control and both idle legs (20 s and 40 s, i.e. past the lease) answer `BadWaitingForInitialData` then Good on
|
||||
the next read, with **no `BadUserAccessDenied` anywhere**. With the CLI's default `--max-age 0`, every projected read (lapsed or
|
||||
not) stays `BadWaitingForInitialData`, because the v1 Read path never serves `maxAge = 0` from cache. That is separate from this
|
||||
fix and is filed as a follow-up. `rig.py down` ⇒ 0 containers / volumes / networks / images.
|
||||
|
||||
## Security review round 1 (no auth bypass; two availability findings + lows) — fixes
|
||||
|
||||
Merged local master first (incl. #916/#917, DataConnections), clean, build 0 errors.
|
||||
|
||||
| # | Finding | Resolution | Red/green |
|
||||
|---|---|---|---|
|
||||
| 1 | A renewal reserved `MaxUnaryBytes` in the unary budget: (A) a batch of N lapsed nodes renewed only the first, (B) while one ran, every cold read / write / subscription renewal was refused | renewals left the unary budget: own resolver pool `max(1, maxConcurrentFetches/2)` (never `_fetchSlots`), a bounded queue (64), 256 KiB each, 3 s end to end including the pool wait | `A_read_batch_of_several_lapsed_nodes_renews_every_node…`, `A_history_batch_of_several_lapsed_nodes…`, `A_renewal_in_flight_does_not_crowd_out_a_cold_read…`: all **red** on the pre-review fix, green now |
|
||||
| 2 | `AuthorizeHistoryRead` waited 5 s before the history batch limiter and ignored the request token, so concurrent HistoryReads against a slow origin pinned SDK threads past the 16-batch cap. The wait also equalled the renewal budget | the wait first takes a non-local history slot with `Wait(0)` (none free ⇒ no wait, retryable), honours `OperationContext.CancellationToken`, and lasts 4 s (≤ `HistoryReadDeadline`) against a 3 s renewal | `Concurrent_history_reads_against_a_slow_origin…`: 24 reads against a silent origin, ≥ 24 − RemoteSlots answer in < 2.5 s, all `BadResourceUnavailable`, origin untouched, Good after release. **Red** on the pre-review fix (all 24 waited ~5 s) |
|
||||
| 3 | Two authorities (policy classifies, `DataPlaneAuthorizer` vetoes) | a renewal that completed `true` and is still vetoed ⇒ `BadUserAccessDenied` | by construction; the grant-revoked test below covers the revoked case |
|
||||
| 4 | Renewals keyed by node only, though each requests its operation's bit | keyed by (realm, id, operation), back-off too | — |
|
||||
| 5 | Back-off map cleared wholesale at 4096; browse refresh deduped per (caller, MaxResults) | expired entries are evicted first, otherwise the one expiring first; one background refresh per parent node | — |
|
||||
| 6 | Write / CreateMonitoredItems on a lapsed node | documented in `docs/DataConnections.md` as not covered (still `BadUserAccessDenied` until a read/browse renews); reported as a follow-up | — |
|
||||
|
||||
New safety controls, green on both the pre-review fix and now: an `Invalidate`d lease ⇒ `BadUserAccessDenied`, no renewal, no origin
|
||||
call. A grant revoked while the renewal is parked at the origin ⇒ nothing served, the renewal never commits, then
|
||||
`BadUserAccessDenied`. A mapping removed while renewing ⇒ not revived, not answered as a lapse. 13 #922 tests, 5 consecutive green
|
||||
runs.
|
||||
@@ -24,6 +24,8 @@ NODE_PERMISSIONS_ADMIN = 4095 # NodePermissions.Admin = bits 0..11 (HistoryUpda
|
||||
NODE_PERMISSIONS_HISTORY_READ = 1 << 3
|
||||
NODE_PERMISSIONS_BROWSE = 1 << 0
|
||||
EXPORT_WITHOUT_HISTORY = 31 # Browse | Metadata | Read | Write | Subscribe
|
||||
# #922: longer than the rig mappings' 15 s MetadataLeaseMilliseconds, so a projected node idles past its lease.
|
||||
LEASE_LAPSE_SECONDS = 20
|
||||
|
||||
|
||||
def _iso(moment):
|
||||
@@ -266,9 +268,8 @@ class HistoryGate:
|
||||
with self.runner.stopped(source):
|
||||
observed["new_primary"] = self.runner.wait_primary("source", exclude=source)
|
||||
self.runner.wait_connection_ready(consumer, "raw")
|
||||
# Resume INSIDE the stop window: the issuing endpoint is down, the pinned resume cannot move. Re-browse first so
|
||||
# the node's projection authority is current (it lapses with the 15 s metadata lease, as for a value Read).
|
||||
self.rebrowse()
|
||||
# Resume INSIDE the stop window: the issuing endpoint is down, the pinned resume cannot move. No re-browse: a
|
||||
# projected node whose 15 s metadata lease lapsed renews on demand within the HistoryRead (#922).
|
||||
self.held_resume_now()
|
||||
self.runner.wait_pair_topology("source")
|
||||
|
||||
@@ -374,10 +375,11 @@ class HistoryGate:
|
||||
self.runner.check(any(l.startswith("Page 2: BadContinuationPointInvalid") for l in lines), "resume after the origin rebuild is invalid")
|
||||
self.runner.check(any(l.startswith("Fresh: Good") for l in lines), "a fresh read after the rebuild succeeds")
|
||||
report["rebuild"] = lines
|
||||
# (c) a consumer session close releases the origin continuation. Each held read starts right after a deploy + re-browse:
|
||||
# an idle projected node's authority lapses with its 15 s metadata lease and a re-browse served from the cached page
|
||||
# does not renew it (a value Read is refused the same way — pre-existing v1 projection behaviour, reported).
|
||||
# (c) a consumer session close releases the origin continuation. The restore's deploy retires cold projected nodes, so it
|
||||
# re-browses; the held read then deliberately starts only after the node's 15 s metadata lease has LAPSED (#922: it
|
||||
# renews on demand within the HistoryRead instead of answering BadUserAccessDenied).
|
||||
self.restore()
|
||||
time.sleep(LEASE_LAPSE_SECONDS)
|
||||
consumer = self.runner.primary("consumer")
|
||||
self.runner.check(self.origin_state() == 0, "no origin continuation open before")
|
||||
counts = {}
|
||||
|
||||
@@ -73,6 +73,29 @@ public sealed class DataOperationPolicy
|
||||
&& CredentialUsable(snapshot, caller, false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #922: would <paramref name="caller"/> be granted <paramref name="operation"/> on this mapped subject, judged on
|
||||
/// everything EXCEPT the remote lease's validity? Used only to classify a refusal of a node whose lease lapsed — a caller
|
||||
/// this answers false for is refused <c>BadUserAccessDenied</c> exactly as before; one it answers true for gets a retryable
|
||||
/// status while the lease is renewed. It never authorizes serving anything: every served read still passes
|
||||
/// <see cref="AuthorizeMapped"/> against a renewed, valid lease.
|
||||
/// </summary>
|
||||
public bool AuthorizeMappedSubject(DataCallerIdentity caller, OpcUaOperation operation, DataView requested,
|
||||
ServingIdentity serving, MappedNamespaceSubject live, MappedSubjectResolver resolver)
|
||||
{
|
||||
if (resolver is null || serving is null || caller is null) return false;
|
||||
var snapshot = _authority.Current;
|
||||
if (!CatalogIsCurrent(resolver.LocalAuthority, snapshot)) return false;
|
||||
var resolved = resolver.Resolve(requested, live);
|
||||
if (resolved.Kind != MappedSubjectResolutionKind.Mapped || resolved.Subject is not { } subject
|
||||
|| subject.Serving != serving || serving.CatalogEpoch <= 0 || serving.AuthorityEpoch <= 0
|
||||
|| string.IsNullOrWhiteSpace(serving.NodeId) || string.IsNullOrWhiteSpace(serving.Incarnation)
|
||||
|| !AllowsMappedOperation(subject, operation)) return false;
|
||||
return Authorize(snapshot, caller, operation, subject.Scope, false, subject, false)
|
||||
&& CatalogIsCurrent(resolver.LocalAuthority, snapshot) && ReferenceEquals(snapshot, _authority.Current)
|
||||
&& CredentialUsable(snapshot, caller, false);
|
||||
}
|
||||
|
||||
private static bool CatalogIsCurrent(IDataMappedCatalogAuthority catalog, DataPlaneAuthoritySnapshot snapshot) =>
|
||||
catalog.IsActive && catalog.CatalogEpoch > 0 && catalog.AuthorityEpoch == snapshot.GenerationId
|
||||
&& snapshot.HasArtifact;
|
||||
|
||||
@@ -11,6 +11,11 @@ public sealed class DeferredProjectedNodeAccess(DeferredAddressSpaceSink deferre
|
||||
definition = null;
|
||||
return deferred.GetCapability<IProjectedNodeLookup>()?.TryResolve(nodeId, out definition) == true;
|
||||
}
|
||||
public bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition)
|
||||
{
|
||||
definition = null;
|
||||
return deferred.GetCapability<IProjectedNodeLookup>()?.TryResolveForRenewal(nodeId, out definition) == true;
|
||||
}
|
||||
public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId)
|
||||
{
|
||||
nodeId = null;
|
||||
|
||||
@@ -18,6 +18,20 @@ public interface IProjectedDemandLease : IDisposable
|
||||
bool IsValid { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #922: how a refused <see cref="IProjectedDataAccess.TryAcquire"/> of a projected node is classified. A lapsed metadata
|
||||
/// lease is NOT an authorization failure: only <see cref="Denied"/> is answered <c>BadUserAccessDenied</c>.
|
||||
/// </summary>
|
||||
public enum ProjectedLapseOutcome
|
||||
{
|
||||
/// <summary>Not a lapse the caller may wait out (no grant, not a lapse at all, or a revoked authority).</summary>
|
||||
Denied,
|
||||
/// <summary>The caller is granted the subject; its lapsed lease is being renewed (the task completes with the outcome).</summary>
|
||||
Renewing,
|
||||
/// <summary>The caller is granted the subject, but no renewal can run right now (capacity, a recent failure): retry later.</summary>
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
/// <summary>Nonblocking local admission and bounded scheduling for projected data.</summary>
|
||||
public interface IProjectedDataAccess
|
||||
{
|
||||
@@ -30,6 +44,17 @@ public interface IProjectedDataAccess
|
||||
bool StartSubscription(IProjectedDemandLease demand, TimeSpan publishingInterval);
|
||||
/// <summary>Requests a coalesced fresh authenticated snapshot without changing caller ownership.</summary>
|
||||
bool RequestFreshSnapshot(IProjectedDemandLease demand) => false;
|
||||
/// <summary>
|
||||
/// #922: classifies a refused acquire of <paramref name="nodeId"/> for <paramref name="operation"/> (Read or HistoryRead) and,
|
||||
/// when the only reason is a lapsed lease the caller would otherwise be granted, starts (or joins) ONE bounded asynchronous
|
||||
/// exact renewal. Nonblocking and lock-free with respect to the caller: never call it, or wait on the task, under the
|
||||
/// node-manager <c>Lock</c> — the renewal commits through the SDK sink, which takes it.
|
||||
/// </summary>
|
||||
ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out Task<bool>? renewal)
|
||||
{
|
||||
renewal = null;
|
||||
return ProjectedLapseOutcome.Denied;
|
||||
}
|
||||
/// <summary>True while a demand or physically retained operation still owns this projection.</summary>
|
||||
bool HasLiveDemand(DataRealm realm, string localIdentifier) => true;
|
||||
}
|
||||
|
||||
@@ -13,6 +13,12 @@ public interface IProjectedNodeLookup
|
||||
{
|
||||
bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition);
|
||||
bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId);
|
||||
/// <summary>
|
||||
/// #922: the committed, still-live definition of a projected node WHETHER OR NOT its authority is current — used only to
|
||||
/// renew a lapsed lease in place (the renewal re-proves authority at the origin and commits against this exact definition).
|
||||
/// Confers nothing; never use it to serve.
|
||||
/// </summary>
|
||||
bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition) { definition = null; return false; }
|
||||
}
|
||||
|
||||
/// <summary>Installs and retires locally authorized mapping anchors.</summary>
|
||||
|
||||
@@ -4414,6 +4414,23 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #922: like <see cref="TryResolve"/> but WITHOUT the authority check, so a node whose metadata lease lapsed can be renewed
|
||||
/// in place. Lock-free (committed snapshot), confers nothing.
|
||||
/// </summary>
|
||||
public bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition)
|
||||
{
|
||||
var committed = Volatile.Read(ref _committedProjectedDefinitions);
|
||||
if (!_disposing && committed.TryGetValue(nodeId, out var current) && current.Lifetime.IsActive &&
|
||||
Volatile.Read(ref _committedProjectedDefinitions).TryGetValue(nodeId, out var latest) && ReferenceEquals(current, latest))
|
||||
{
|
||||
definition = current;
|
||||
return true;
|
||||
}
|
||||
definition = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
private int _maxProjectedNodes = 4096;
|
||||
private long _maxProjectedNodeBytes = 16 * 1024 * 1024;
|
||||
private long _projectedNodeBytes;
|
||||
@@ -6293,8 +6310,18 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
if (identity is null || access is null || !access.TryAcquire(projected.NodeId, identity, DataOperations.Read, out demand) ||
|
||||
demand is null || !demand.IsValid)
|
||||
{
|
||||
errors[ii] = StatusCodes.BadUserAccessDenied;
|
||||
values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied);
|
||||
demand?.Dispose(); demand = null;
|
||||
// #922: a lapsed metadata lease is not an authorization failure. A caller granted the node gets the same
|
||||
// retryable answer as a cold read while the lease renews on demand (off this thread, no Lock held).
|
||||
var lapse = identity is null || access is null ? ProjectedLapseOutcome.Denied
|
||||
: access.RenewLapsed(projected.NodeId, identity, DataOperations.Read, out _);
|
||||
if (lapse == ProjectedLapseOutcome.Denied)
|
||||
{
|
||||
errors[ii] = StatusCodes.BadUserAccessDenied;
|
||||
values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied);
|
||||
}
|
||||
else values[ii] = new DataValue(Variant.Null, lapse == ProjectedLapseOutcome.Renewing
|
||||
? StatusCodes.BadWaitingForInitialData : StatusCodes.BadResourceUnavailable);
|
||||
continue;
|
||||
}
|
||||
ProjectedValueWrite? cached;
|
||||
@@ -6335,6 +6362,13 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
if (Permits(identity, OpcUaOperation.Read, nodeToRead.NodeId)) continue;
|
||||
|
||||
nodeToRead.Processed = true;
|
||||
// #922: an attribute of a projected node whose lease lapsed — retryable while it renews, never access-denied.
|
||||
if (identity is not null && IsProjectedDescendant(nodeToRead.NodeId) && ProjectedDataAccess is { } lapsedAccess &&
|
||||
ClassifyProjectedLapse(lapsedAccess, nodeToRead.NodeId, identity, DataOperations.Read) != ProjectedLapseOutcome.Denied)
|
||||
{
|
||||
values[ii] = new DataValue(Variant.Null, StatusCodes.BadResourceUnavailable);
|
||||
continue;
|
||||
}
|
||||
errors[ii] = StatusCodes.BadUserAccessDenied;
|
||||
values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied);
|
||||
denied++;
|
||||
@@ -8921,18 +8955,75 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
var identity = (context as ISessionOperationContext)?.UserIdentity as RoleCarryingUserIdentity
|
||||
?? context.OperationContext?.UserIdentity as RoleCarryingUserIdentity;
|
||||
|
||||
var allowed = new List<NodeHandle>(nodesToProcess.Count);
|
||||
foreach (var handle in nodesToProcess)
|
||||
{
|
||||
var veto = _authorizer?.AuthorizeIfRequired(
|
||||
ServiceResult? Veto(NodeHandle handle) => _authorizer?.AuthorizeIfRequired(
|
||||
identity, OpcUaOperation.HistoryRead, handle.NodeId, RealmOf(handle.NodeId), cached: false)
|
||||
?? (_authorizer is null && _mappedSubjectResolver is not null ? new ServiceResult(StatusCodes.BadUserAccessDenied) : null);
|
||||
?? (_authorizer is null && _mappedSubjectResolver is not null ? new ServiceResult(StatusCodes.BadUserAccessDenied) : null);
|
||||
|
||||
var vetoes = new ServiceResult?[nodesToProcess.Count];
|
||||
var lapses = new ProjectedLapseOutcome?[nodesToProcess.Count];
|
||||
var renewalTasks = new Task<bool>?[nodesToProcess.Count];
|
||||
List<Task<bool>>? renewals = null;
|
||||
var access = ProjectedDataAccess;
|
||||
for (var i = 0; i < nodesToProcess.Count; i++)
|
||||
{
|
||||
var handle = nodesToProcess[i];
|
||||
vetoes[i] = Veto(handle);
|
||||
// #922: a projected node refused only because its metadata lease lapsed is renewed within this request — never
|
||||
// answered access-denied for the lapse. A caller without the grant is classified Denied and never reaches the origin.
|
||||
if (vetoes[i] is null || identity is null || access is null || !IsProjectedDescendant(handle.NodeId)) continue;
|
||||
Task<bool>? renewal = null;
|
||||
try { lapses[i] = access.RenewLapsed(handle.NodeId, identity, DataOperations.HistoryRead, out renewal); }
|
||||
catch (Exception) { lapses[i] = ProjectedLapseOutcome.Denied; renewal = null; }
|
||||
renewalTasks[i] = renewal;
|
||||
if (renewal is not null) (renewals ??= []).Add(renewal);
|
||||
}
|
||||
if (renewals is not null)
|
||||
{
|
||||
// Block-bridged once per batch, like the projected history read itself; the SDK released Lock before dispatching.
|
||||
// #922 review: the wait holds an SDK request thread, so it takes one of the SAME non-local history slots a projected
|
||||
// read takes (never waiting for one — none free ⇒ the lapsed nodes are simply retryable), honours the request's
|
||||
// cancellation, and is clearly longer than the renewal's own budget so a renewal that completes is never answered late.
|
||||
var slots = GetNonLocalHistoryLimiter();
|
||||
if (slots.Wait(0))
|
||||
{
|
||||
try
|
||||
{
|
||||
var wait = HistoryReadDeadline > TimeSpan.Zero && HistoryReadDeadline < ProjectedLapseRenewalWait
|
||||
? HistoryReadDeadline : ProjectedLapseRenewalWait;
|
||||
Task.WhenAll(renewals).Wait((int)wait.TotalMilliseconds,
|
||||
context.OperationContext?.CancellationToken ?? CancellationToken.None);
|
||||
}
|
||||
catch (AggregateException) { }
|
||||
catch (OperationCanceledException) { }
|
||||
finally { slots.Release(); }
|
||||
}
|
||||
for (var i = 0; i < nodesToProcess.Count; i++)
|
||||
if (lapses[i] is ProjectedLapseOutcome.Renewing) vetoes[i] = Veto(nodesToProcess[i]);
|
||||
}
|
||||
|
||||
var allowed = new List<NodeHandle>(nodesToProcess.Count);
|
||||
for (var i = 0; i < nodesToProcess.Count; i++)
|
||||
{
|
||||
var handle = nodesToProcess[i];
|
||||
var veto = vetoes[i];
|
||||
if (veto is null)
|
||||
{
|
||||
allowed.Add(handle);
|
||||
continue;
|
||||
}
|
||||
|
||||
// #922 review: the lapse classification and the veto are two authorities (DataOperationPolicy / DataPlaneAuthorizer).
|
||||
// A renewal that SUCCEEDED and is still vetoed is a real refusal, never a retryable one.
|
||||
if (lapses[i] is ProjectedLapseOutcome.Renewing && renewalTasks[i] is { IsCompletedSuccessfully: true, Result: true })
|
||||
lapses[i] = ProjectedLapseOutcome.Denied;
|
||||
if (lapses[i] is ProjectedLapseOutcome.Renewing or ProjectedLapseOutcome.Unavailable)
|
||||
{
|
||||
// Granted, but the lease could not be renewed in time (origin unreachable, capacity): retryable.
|
||||
errors[handle.Index] = new ServiceResult(StatusCodes.BadResourceUnavailable);
|
||||
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadResourceUnavailable };
|
||||
continue;
|
||||
}
|
||||
|
||||
// Set both slots explicitly rather than relying on the base's pre-seeded
|
||||
// BadHistoryOperationUnsupported — "unsupported" would tell the client the node has no history,
|
||||
// which is a different fact from "you may not read it" and sends them debugging the wrong thing.
|
||||
@@ -8943,6 +9034,20 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
return allowed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #922: the longest a HistoryRead waits for the on-demand renewal of lapsed projected leases (one wait per batch, capped by
|
||||
/// <see cref="HistoryReadDeadline"/>) — longer than the renewal's own budget (3 s), so a completed renewal is always seen.
|
||||
/// </summary>
|
||||
internal static readonly TimeSpan ProjectedLapseRenewalWait = TimeSpan.FromSeconds(4);
|
||||
|
||||
/// <summary>#922: classifies (and, when it is a lapse, starts renewing) a refused projected node; total — a fault is Denied.</summary>
|
||||
private static ProjectedLapseOutcome ClassifyProjectedLapse(IProjectedDataAccess access, NodeId nodeId,
|
||||
RoleCarryingUserIdentity identity, DataOperations operation)
|
||||
{
|
||||
try { return access.RenewLapsed(nodeId, identity, operation, out _); }
|
||||
catch (Exception) { return ProjectedLapseOutcome.Denied; }
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <remarks>A thin adapter over the history port (<see cref="ReadHistory"/>): authorize, then serve (H3: projected handles go remote).</remarks>
|
||||
protected override void HistoryReadRawModified(
|
||||
|
||||
@@ -51,6 +51,9 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre
|
||||
/// <inheritdoc />
|
||||
public bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition) => _nodeManager.TryResolve(nodeId, out definition);
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition) => _nodeManager.TryResolveForRenewal(nodeId, out definition);
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId) => _nodeManager.TryGetNodeId(namespaceUri, identifier, out nodeId);
|
||||
|
||||
|
||||
@@ -13,11 +13,18 @@ internal sealed class BoundProjectionLease(MetadataAuthorityLease remote, Cancel
|
||||
internal DataTarget? Target => target;
|
||||
internal object? BindingIdentity => bindingIdentity;
|
||||
internal TimeSpan Remaining => remote.Remaining;
|
||||
internal MetadataAuthorityLease Remote => remote;
|
||||
internal TimeSpan UsableDuration => remote.UsableDuration;
|
||||
private bool RouteAlive => !route.IsCancellationRequested && (routeCurrent?.Invoke() ?? true);
|
||||
internal bool LiveContext => RouteAlive && local.IsActive && bindingCurrent() && cache.IsCurrentGeneration(mapping, generation);
|
||||
internal bool ExpiredNaturally => remote.ExpiredNaturally && LiveContext;
|
||||
public bool IsValid => LiveContext && remote.IsValid;
|
||||
/// <summary>
|
||||
/// #922: the authority is gone ONLY because it is transient — the remote lease's time ran out or its route was
|
||||
/// replaced — while the local catalog authority, the mapping binding and the cache generation are all still current
|
||||
/// and nothing revoked it. Such a lapse is renewed by an exact metadata refresh, never answered as an access denial.
|
||||
/// </summary>
|
||||
internal bool Renewable => !remote.Invalidated && local.IsActive && bindingCurrent() && cache.IsCurrentGeneration(mapping, generation);
|
||||
internal ProjectionLeaseDiagnostics CaptureDiagnostics() => new(RouteAlive, local.IsActive,
|
||||
remote.IsValid, bindingCurrent(), cache.IsCurrentGeneration(mapping, generation));
|
||||
}
|
||||
|
||||
@@ -47,6 +47,8 @@ public sealed class MetadataAuthorityLease : IDataAuthorizationLease
|
||||
}
|
||||
}
|
||||
internal TimeSpan UsableDuration => _usableDuration;
|
||||
/// <summary>True once <see cref="Invalidate"/> ran: a revocation, never renewable (#922).</summary>
|
||||
internal bool Invalidated => Volatile.Read(ref _invalidated) != 0;
|
||||
internal bool ExpiredNaturally => Volatile.Read(ref _invalidated) == 0 &&
|
||||
_clock.GetElapsedTime(_requestStart, _clock.GetTimestamp()) >= _usableDuration;
|
||||
public bool IsValid
|
||||
|
||||
@@ -22,6 +22,9 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
|
||||
private readonly object _anchorGate = new();
|
||||
private readonly ConcurrentDictionary<string, Installed> _installed = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly ConcurrentDictionary<WorkKey, TaskCompletionSource> _inflight = new();
|
||||
// #922 review: background refreshes of cached pages, keyed by the parent NODE (not caller / MaxResults), so varying the
|
||||
// browse parameters cannot multiply origin browses of one parent.
|
||||
private readonly ConcurrentDictionary<NodeId, byte> _refreshing = new();
|
||||
private readonly record struct Failure(ProjectionPageStatus Status, long Until);
|
||||
private readonly object _resultGate = new();
|
||||
private readonly Dictionary<WorkKey, Failure> _failures = new();
|
||||
@@ -176,15 +179,26 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
|
||||
if (!guard.IsCurrent()) return Empty(ProjectedBrowseReadiness.Unavailable);
|
||||
var retainedBytes = checked(sourceGuard.RetainedBytes + 2048L + 2L * (snapshot.Continuation?.Length ?? 0) +
|
||||
expectedIds.Sum(node => 128L + 2L * node.IdentifierAsString.Length));
|
||||
// #922: a re-browse served from a cached page must still renew a lease that is running out — otherwise a client that
|
||||
// re-browses to refresh a node it reads gets nothing until the page itself lapses. Past half its life an initial page
|
||||
// is served as is AND refreshed in the background (at most one in flight per page key; a fresh page is untouched).
|
||||
if (input.Cursor is null && lease is BoundProjectionLease bound && bound.Remaining < bound.UsableDuration / 2)
|
||||
_ = TrySchedule(new WorkKey(input.Parent, identity, input.Cursor, maximum), request, anchor, input.Parent, refresh: true);
|
||||
return new(ProjectedBrowseReadiness.Ready, Array.AsReadOnly(expectedIds), snapshot.Continuation, snapshot.Complete,
|
||||
guard.IsCurrent, retainedBytes);
|
||||
}
|
||||
if (snapshot.Status == ProjectionPageStatus.InvalidContinuation) return Empty(ProjectedBrowseReadiness.InvalidContinuation);
|
||||
var key = new WorkKey(input.Parent, identity, input.Cursor, maximum);
|
||||
return TrySchedule(new WorkKey(input.Parent, identity, input.Cursor, maximum), request, anchor, input.Parent, refresh: false);
|
||||
}
|
||||
|
||||
private ProjectedBrowsePage TrySchedule(WorkKey key, ProjectedBrowseRequest request, Installed anchor, NodeId exactParent, bool refresh)
|
||||
{
|
||||
lock (_resultGate)
|
||||
{
|
||||
var now = _catalog.Clock.GetTimestamp();
|
||||
foreach (var expired in _failures.Where(x => x.Value.Until <= now).Select(x => x.Key).ToArray()) _failures.Remove(expired);
|
||||
if (refresh && (_failures.ContainsKey(key) || _inflight.ContainsKey(key) || !_refreshing.TryAdd(exactParent, 0)))
|
||||
return Empty(ProjectedBrowseReadiness.Pending);
|
||||
if (_failures.TryGetValue(key, out var failure))
|
||||
return Empty(failure.Status switch
|
||||
{
|
||||
@@ -193,11 +207,14 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
|
||||
_ => ProjectedBrowseReadiness.Unavailable
|
||||
});
|
||||
if (_inflight.ContainsKey(key)) return Empty(ProjectedBrowseReadiness.Pending);
|
||||
if (_failures.Count + _pending >= _maxPending) return Empty(ProjectedBrowseReadiness.Unavailable);
|
||||
if (!_inflight.TryAdd(key, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously))) return Empty(ProjectedBrowseReadiness.Pending);
|
||||
if (_failures.Count + _pending >= _maxPending ||
|
||||
!_inflight.TryAdd(key, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)))
|
||||
{
|
||||
if (refresh) _refreshing.TryRemove(exactParent, out _);
|
||||
return Empty(_failures.Count + _pending >= _maxPending ? ProjectedBrowseReadiness.Unavailable : ProjectedBrowseReadiness.Pending);
|
||||
}
|
||||
_pending++;
|
||||
}
|
||||
var exactParent = input.Parent;
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
var result = ProjectionPageStatus.Unavailable;
|
||||
@@ -208,6 +225,7 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable
|
||||
lock (_resultGate)
|
||||
{
|
||||
_inflight.TryRemove(key, out var completed);
|
||||
if (refresh) _refreshing.TryRemove(exactParent, out _);
|
||||
_pending--;
|
||||
if (result != ProjectionPageStatus.Ready && !_stop.IsCancellationRequested)
|
||||
{
|
||||
|
||||
@@ -106,7 +106,8 @@ public sealed class ProjectedCatalogCache
|
||||
private static ParentKey Key(ProjectedBrowseRequest request) => new(request.MappingId.ToUpperInvariant(), request.Parent,
|
||||
request.Filter, request.Continuation, request.Caller, request.ConfiguredCapability);
|
||||
private static (string Mapping, DataView Parent) Parent(string mapping, DataView parent) => (mapping.ToUpperInvariant(), parent);
|
||||
private bool ValidCore(ProjectedNodeProof proof) => proof.Generation > 0 && proof.Lease.IsValid && proof.Lease.Serving.ServingGeneration > 0 &&
|
||||
private bool ValidCore(ProjectedNodeProof proof, bool requireLease = true) => proof.Generation > 0 &&
|
||||
(requireLease ? proof.Lease.IsValid : proof.Lease is BoundProjectionLease { Renewable: true }) && proof.Lease.Serving.ServingGeneration > 0 &&
|
||||
proof.Subject.Serving == proof.Lease.Serving && proof.Metadata.View == proof.Subject.View &&
|
||||
proof.Metadata.Serving == proof.Lease.Serving && proof.OriginMetadata.Serving == proof.Lease.Serving &&
|
||||
proof.OriginMetadata.View.MappingId is null && proof.OriginMetadata.View.MappingRevision == 0 &&
|
||||
@@ -488,6 +489,26 @@ public sealed class ProjectedCatalogCache
|
||||
proof = null; return false;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// #922: the retained, non-retired proof of a node whose authority may be refreshed by an exact renewal — a valid one,
|
||||
/// or one that is invalid ONLY because its lease lapsed (time, or a replaced route) while every local fence still holds
|
||||
/// (<see cref="BoundProjectionLease.Renewable"/>). Never an authorization: the caller still authorizes the subject and
|
||||
/// the renewal re-proves everything at the origin before anything is served.
|
||||
/// </summary>
|
||||
internal bool TryResolveForRenewal(DataRealm realm, string localId, out ProjectedNodeProof? proof)
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
if (_nodes.TryGetValue((realm, localId), out var entry) && !entry.Retired && (Valid(entry.Proof) || Renewable(entry.Proof)))
|
||||
{ proof = entry.Proof; return true; }
|
||||
proof = null; return false;
|
||||
}
|
||||
}
|
||||
private bool Renewable(ProjectedNodeProof proof)
|
||||
{
|
||||
try { return ValidCore(proof, requireLease: false); }
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or NullReferenceException) { return false; }
|
||||
}
|
||||
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin)
|
||||
{
|
||||
lock (_sync)
|
||||
|
||||
@@ -201,6 +201,123 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireException); return false; }
|
||||
}
|
||||
// #922: at most one on-demand renewal per projected node AND operation (each requests its own bit at the origin); a failed
|
||||
// one is not retried for a short back-off so a client polling a node whose origin is unreachable cannot turn every Read into
|
||||
// a metadata call. Renewals never use the unary budget (that would starve cold reads, writes and subscription renewals):
|
||||
// they queue — at most MaxQueuedLapseRenewals — for the resolver's own on-demand pool, so a batch of N lapsed nodes renews
|
||||
// them all, a few at a time.
|
||||
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), Task<bool>> _lapseRenewals = new();
|
||||
private readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), long> _lapseRenewalBackoff = new();
|
||||
private const int MaxLapseRenewalBackoffEntries = 4096;
|
||||
internal const int MaxQueuedLapseRenewals = 64;
|
||||
internal static readonly TimeSpan LapseRenewalBackoff = TimeSpan.FromMilliseconds(250);
|
||||
/// <summary>The whole on-demand renewal, pool wait included; clearly shorter than the longest a HistoryRead waits for it.</summary>
|
||||
internal static readonly TimeSpan LapseRenewalTimeout = TimeSpan.FromSeconds(3);
|
||||
/// <summary>One metadata item and its capability probe: never a multi-MiB unary reservation.</summary>
|
||||
internal const long LapseRenewalBytes = 256 * 1024;
|
||||
internal int LapseRenewalsStartedForTests => Volatile.Read(ref _lapseRenewalsStarted);
|
||||
private int _lapseRenewalsStarted;
|
||||
|
||||
/// <inheritdoc />
|
||||
public ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out Task<bool>? renewal)
|
||||
{
|
||||
renewal = null;
|
||||
if (caller is null || operation is not (DataOperations.Read or DataOperations.HistoryRead) || _renewalSink is not { } sink ||
|
||||
_catalog is not RemoteNamespaceResolver resolver) return ProjectedLapseOutcome.Denied;
|
||||
try
|
||||
{
|
||||
// The SDK node must still be live, and either it or its catalog proof must have lapsed — a refusal of a node whose
|
||||
// authority is fully current was a real refusal (grant, capacity…), never a lapse.
|
||||
if (!_nodes.TryResolveForRenewal(nodeId, out var definition) || definition is null || !definition.Lifetime.IsActive ||
|
||||
!resolver.TryResolveForRenewal(definition.Realm, definition.LocalIdentifier, out var proof) || proof is null ||
|
||||
definition.AuthorityIsCurrent() && _catalog.IsUsableProof(proof) ||
|
||||
proof.Generation != definition.ProjectionGeneration || !MetadataMatches(proof.Metadata, definition.Metadata) ||
|
||||
proof.Metadata.View.MappingId is not { } mapping || _connectionForMapping(mapping) is not { Length: > 0 } ||
|
||||
(operation == DataOperations.Read && proof.MaximumSampleAge <= TimeSpan.Zero) ||
|
||||
(operation == DataOperations.HistoryRead && (!definition.Historizing || !ProjectedHistoryAccess.Advertises(proof))))
|
||||
return ProjectedLapseOutcome.Denied;
|
||||
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
|
||||
// The same grant the served operation needs, judged on everything but the lapsed lease: a caller without it is
|
||||
// refused exactly as before, and never causes an origin call.
|
||||
if (!_policy.AuthorizeMappedSubject(identity, Operation(operation), proof.Metadata.View, proof.Lease.Serving, proof.Subject, proof.Resolver))
|
||||
return ProjectedLapseOutcome.Denied;
|
||||
var key = (definition.Realm, definition.LocalIdentifier, operation);
|
||||
var budget = new DataBudget(LapseRenewalTimeout, 1, Math.Min(LapseRenewalBytes, _limits.MaxUnaryBytes));
|
||||
TaskCompletionSource<bool> started;
|
||||
lock (_sync)
|
||||
{
|
||||
if (_disposed) return ProjectedLapseOutcome.Unavailable;
|
||||
if (_lapseRenewals.TryGetValue(key, out var running)) { renewal = running; return ProjectedLapseOutcome.Renewing; }
|
||||
var now = Clock.GetTimestamp();
|
||||
if (_lapseRenewalBackoff.TryGetValue(key, out var until))
|
||||
{
|
||||
if (now < until) return ProjectedLapseOutcome.Unavailable;
|
||||
_lapseRenewalBackoff.Remove(key);
|
||||
}
|
||||
if (_lapseRenewals.Count >= MaxQueuedLapseRenewals) return ProjectedLapseOutcome.Unavailable;
|
||||
started = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_lapseRenewals.Add(key, started.Task);
|
||||
}
|
||||
Interlocked.Increment(ref _lapseRenewalsStarted);
|
||||
// Never on the caller's thread: the renewal awaits the origin and commits through the SDK sink (node-manager Lock).
|
||||
_ = Task.Run(() => RunLapseRenewalAsync(resolver, sink, key, proof, definition, nodeId, caller, identity, operation, budget, started));
|
||||
renewal = started.Task;
|
||||
return ProjectedLapseOutcome.Renewing;
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return ProjectedLapseOutcome.Denied; }
|
||||
}
|
||||
|
||||
private async Task RunLapseRenewalAsync(RemoteNamespaceResolver resolver, IProjectedNamespacePageSink sink,
|
||||
(DataRealm Realm, string LocalIdentifier, DataOperations Operation) key, ProjectedNodeProof proof, ProjectedVariableDefinition definition, NodeId nodeId,
|
||||
RoleCarryingUserIdentity caller, DataCallerIdentity identity, DataOperations operation, DataBudget budget, TaskCompletionSource<bool> completion)
|
||||
{
|
||||
var renewed = false;
|
||||
try
|
||||
{
|
||||
renewed = await resolver.RenewExactAsync(proof, definition, nodeId, identity, null, sink, budget,
|
||||
() => { lock (_sync) return !_disposed; }, CancellationToken.None, overlap: false,
|
||||
authorizeAs: Operation(operation), required: operation, onDemand: true).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException) { renewed = false; }
|
||||
finally
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
_lapseRenewals.Remove(key);
|
||||
if (!renewed && !_disposed)
|
||||
{
|
||||
if (_lapseRenewalBackoff.Count >= MaxLapseRenewalBackoffEntries) EvictLapseBackoffLocked();
|
||||
var delay = (long)(LapseRenewalBackoff.TotalSeconds * Clock.TimestampFrequency);
|
||||
_lapseRenewalBackoff[key] = Clock.GetTimestamp() + Math.Max(1, delay);
|
||||
}
|
||||
}
|
||||
}
|
||||
// A Read answered retryable while the lease renewed: fetch the value now, through the ordinary authorized path, so the
|
||||
// client's retry is served from the fresh sample instead of starting another cold read.
|
||||
if (renewed && operation == DataOperations.Read)
|
||||
{
|
||||
IProjectedDemandLease? demand = null;
|
||||
try
|
||||
{
|
||||
if (TryAcquire(nodeId, caller, DataOperations.Read, out demand) && demand is not null &&
|
||||
ScheduleRead(demand, new DataBudget(LapseRenewalTimeout, 1, ProjectedReadBytes), Clock.GetTimestamp())) demand = null;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException) { }
|
||||
finally { demand?.Dispose(); }
|
||||
}
|
||||
completion.TrySetResult(renewed);
|
||||
}
|
||||
// Full map (rare): drop the expired entries; if none expired, the one that expires first — never the whole map, which would
|
||||
// let every node's back-off lapse at once.
|
||||
private void EvictLapseBackoffLocked()
|
||||
{
|
||||
var now = Clock.GetTimestamp();
|
||||
var expired = _lapseRenewalBackoff.Where(entry => entry.Value <= now).Select(entry => entry.Key).ToArray();
|
||||
foreach (var key in expired) _lapseRenewalBackoff.Remove(key);
|
||||
if (expired.Length == 0) _lapseRenewalBackoff.Remove(_lapseRenewalBackoff.MinBy(entry => entry.Value).Key);
|
||||
}
|
||||
/// <summary>The per-read byte budget the SDK Read path schedules a cold projected read with.</summary>
|
||||
internal const long ProjectedReadBytes = 4 * 1024 * 1024;
|
||||
internal bool TryAcquireConfigured(NodeId nodeId, ConfiguredProjectionCapability capability, out IProjectedDemandLease? demand)
|
||||
{
|
||||
demand = null;
|
||||
|
||||
@@ -22,6 +22,10 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
private readonly DataOperationPolicy _policy;
|
||||
private readonly int _maxMappings;
|
||||
private readonly SemaphoreSlim _fetchSlots;
|
||||
// #922 review: on-demand renewals of lapsed nodes (a Read / HistoryRead) run on their OWN small pool, never on _fetchSlots,
|
||||
// so a burst of them cannot crowd out browse pages or the subscription renewals that keep live items from lapsing.
|
||||
private readonly SemaphoreSlim _onDemandSlots;
|
||||
internal int OnDemandRenewalSlots { get; }
|
||||
private readonly int _maximumWaiters;
|
||||
private readonly Func<CancellationToken, Task>? _beforeFetch;
|
||||
private int _waiterCount;
|
||||
@@ -44,6 +48,8 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
_source = source ?? throw new ArgumentNullException(nameof(source)); _policy = policy ?? throw new ArgumentNullException(nameof(policy));
|
||||
if (maxMappings <= 0 || maxConcurrentFetches <= 0) throw new ArgumentOutOfRangeException(nameof(maxMappings));
|
||||
_maxMappings = maxMappings; _fetchSlots = new(maxConcurrentFetches, maxConcurrentFetches);
|
||||
OnDemandRenewalSlots = Math.Max(1, maxConcurrentFetches / 2);
|
||||
_onDemandSlots = new(OnDemandRenewalSlots, OnDemandRenewalSlots);
|
||||
_maximumWaiters = checked(maxConcurrentFetches * 16);
|
||||
_cache.Invalidated += OnInvalidated;
|
||||
}
|
||||
@@ -98,6 +104,8 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) => _cache.TryResolveProjected(realm, localId, out proof);
|
||||
public bool IsUsableProof(ProjectedNodeProof proof) => _cache.IsUsableProof(proof);
|
||||
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) => _cache.TryPinProjected(realm, localId, out pin);
|
||||
internal bool TryResolveForRenewal(DataRealm realm, string localId, out ProjectedNodeProof? proof) =>
|
||||
_cache.TryResolveForRenewal(realm, localId, out proof);
|
||||
internal bool TryPinExpiredRecoveryPair(ProjectedNodeProof previous, ProjectedNodeProof successor, out IDisposable? pin) =>
|
||||
_cache.TryPinExpiredRecoveryPair(previous, successor, out pin);
|
||||
public async Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken)
|
||||
@@ -301,8 +309,14 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
// page, cursor or sibling visibility and does not create a physical subscription.
|
||||
internal async Task<bool> RenewExactAsync(ProjectedNodeProof previous, ProjectedVariableDefinition definition,
|
||||
NodeId nodeId, DataCallerIdentity? caller, ConfiguredProjectionCapability? configured,
|
||||
IProjectedNamespacePageSink sink, DataBudget budget, Func<bool> demandActive, CancellationToken cancellationToken, bool overlap = false)
|
||||
IProjectedNamespacePageSink sink, DataBudget budget, Func<bool> demandActive, CancellationToken cancellationToken, bool overlap = false,
|
||||
OpcUaOperation authorizeAs = OpcUaOperation.CreateMonitoredItems, DataOperations required = DataOperations.Subscribe,
|
||||
bool onDemand = false)
|
||||
{
|
||||
// #922: a subscription renews for CreateMonitoredItems/Subscribe (the default); an on-demand renewal of a lapsed node
|
||||
// renews for the operation the caller is performing (Read / HistoryRead) and requires exactly that bit at the origin.
|
||||
if (authorizeAs is not (OpcUaOperation.CreateMonitoredItems or OpcUaOperation.Read or OpcUaOperation.HistoryRead) ||
|
||||
required is not (DataOperations.Subscribe or DataOperations.Read or DataOperations.HistoryRead)) return false;
|
||||
var mapping = previous.Metadata.View.MappingId;
|
||||
if (mapping is null || previous.Subject.Scope.Segments.Count == 0) return false;
|
||||
ProjectedMappingBinding binding;
|
||||
@@ -313,7 +327,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
bool CallerAllowed() => demandActive() && (configured is not null
|
||||
? configured.Matches(mapping, previous.Metadata.View, binding.LocalAuthority)
|
||||
: caller is not null && _policy.IsCallerUsable(caller) &&
|
||||
_policy.AuthorizeLocal(caller, OpcUaOperation.CreateMonitoredItems, previous.Subject.Scope));
|
||||
_policy.AuthorizeLocal(caller, authorizeAs, previous.Subject.Scope));
|
||||
if (!IsCurrent(binding) || !binding.LocalAuthority.IsActive || !CallerAllowed() ||
|
||||
previous.Metadata.View.MappingRevision != binding.Mapping.Revision || previous.Metadata.View.Realm != binding.Mapping.Realm ||
|
||||
previous.OriginMetadata.View.MappingId is not null ||
|
||||
@@ -322,7 +336,17 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
previous.Subject.Scope.Segments.Count < binding.LocalScope.Segments.Count ||
|
||||
!previous.Subject.Scope.Segments.Take(binding.LocalScope.Segments.Count).SequenceEqual(binding.LocalScope.Segments, StringComparer.Ordinal) ||
|
||||
!previous.Subject.LocalAncestry.SequenceEqual(binding.LocalAncestry, StringComparer.OrdinalIgnoreCase)) return false;
|
||||
if (!await _fetchSlots.WaitAsync(0, cancellationToken).ConfigureAwait(false)) return false;
|
||||
// A subscription renewal never queues (it retries on its own cadence); an on-demand renewal waits for its own pool within
|
||||
// its budget, and the wait is charged to that budget.
|
||||
var slots = onDemand ? _onDemandSlots : _fetchSlots;
|
||||
var queued = System.Diagnostics.Stopwatch.GetTimestamp();
|
||||
if (!await slots.WaitAsync(onDemand ? budget.Timeout : TimeSpan.Zero, cancellationToken).ConfigureAwait(false)) return false;
|
||||
if (onDemand)
|
||||
{
|
||||
var left = budget.Timeout - System.Diagnostics.Stopwatch.GetElapsedTime(queued);
|
||||
if (left <= TimeSpan.Zero) { slots.Release(); return false; }
|
||||
budget = budget with { Timeout = left };
|
||||
}
|
||||
IGrpcDataAdapterConnectionLease? connection = null;
|
||||
try
|
||||
{
|
||||
@@ -356,7 +380,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
metadata.ValueKind != previous.OriginMetadata.ValueKind || metadata.ValueRank != previous.OriginMetadata.ValueRank ||
|
||||
metadata.ArrayElementKind != previous.OriginMetadata.ArrayElementKind ||
|
||||
!metadata.Dimensions.SequenceEqual(previous.OriginMetadata.Dimensions) ||
|
||||
(metadata.AllowedOperations & binding.Mapping.AllowedOperations & DataOperations.Subscribe) == 0 ||
|
||||
(metadata.AllowedOperations & binding.Mapping.AllowedOperations & required) == 0 ||
|
||||
!IsCurrent(binding) || !CallerAllowed() || connection.CancellationToken.IsCancellationRequested) return false;
|
||||
metadata.Validate(); remoteLease.Validate();
|
||||
var generation = _cache.CaptureGeneration(mapping);
|
||||
@@ -377,7 +401,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
var renewed = new ProjectedNodeProof(previous.LocalIdentifier, mapped, subject, resolver, lease, generation, metadata,
|
||||
TimeSpan.FromMilliseconds(binding.Mapping.StaleTimeoutMilliseconds));
|
||||
var guard = new ExactAuthority(renewed);
|
||||
if (!guard.IsCurrent() || caller is not null && !_policy.AuthorizeMapped(caller, OpcUaOperation.CreateMonitoredItems,
|
||||
if (!guard.IsCurrent() || caller is not null && !_policy.AuthorizeMapped(caller, authorizeAs,
|
||||
mapped.View, serving, subject, resolver, lease)) return false;
|
||||
var newDefinition = new ProjectedVariableDefinition(definition.Realm, definition.LocalIdentifier, definition.Parent,
|
||||
mapped, generation, guard.IsCurrent) { Lifetime = definition.Lifetime, Historizing = ProjectedHistoryAccess.Advertises(renewed) };
|
||||
@@ -400,7 +424,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
{
|
||||
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
|
||||
catch (Exception) { }
|
||||
finally { _fetchSlots.Release(); }
|
||||
finally { slots.Release(); }
|
||||
}
|
||||
}
|
||||
public void Dispose()
|
||||
|
||||
+276
@@ -0,0 +1,276 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using DataBrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest;
|
||||
using DataReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest;
|
||||
using DataReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
/// <summary>
|
||||
/// #922 security-review round 1: on-demand renewal admission must not starve the unary budget (cold reads, writes, subscription
|
||||
/// renewals), a batch of N lapsed nodes renews all N, a slow origin cannot pin SDK threads, and every refusal that is not a
|
||||
/// lapse (a revoked lease, a revoked grant, a removed node) stays a refusal.
|
||||
/// </summary>
|
||||
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
{
|
||||
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
||||
public async Task A_read_batch_of_several_lapsed_nodes_renews_every_node_not_only_the_first()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1);
|
||||
var connections = new GatedConnections(origin);
|
||||
await WithComposedServer(origin, origin.Root, async (session, _, resolver, _, access, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
|
||||
children.Length.ShouldBe(3);
|
||||
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
||||
var ids = children.Select(c => c.IdentifierAsString).ToArray();
|
||||
ids.Count(id => resolver.TryResolveProjected(DataRealm.Raw, id, out var _1)).ShouldBe(0);
|
||||
|
||||
var read = await client.ReadAsync(new RequestHeader(), LongMaxAge, TimestampsToReturn.Both,
|
||||
children.Select(c => new ReadValueId { NodeId = c, AttributeId = Attributes.Value }).ToArray(), ct);
|
||||
read.Results.ToArray()!.ShouldAllBe(r => r.StatusCode.Code == StatusCodes.BadWaitingForInitialData.Code);
|
||||
access.LapseRenewalsStartedForTests.ShouldBe(3, "every lapsed node in the batch is admitted for renewal");
|
||||
for (var i = 0; i < 400 && !ids.All(id => resolver.TryResolveProjected(DataRealm.Raw, id, out _)); i++) await Task.Delay(25, ct);
|
||||
ids.Count(id => resolver.TryResolveProjected(DataRealm.Raw, id, out var _2)).ShouldBe(3, "all three renewed, with no re-browse");
|
||||
connections.BrowseCalls.ShouldBe(1);
|
||||
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
|
||||
}
|
||||
|
||||
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
||||
public async Task A_history_batch_of_several_lapsed_nodes_renews_and_serves_every_node()
|
||||
{
|
||||
await using var originServer = await HistoryOrigin.StartAsync(7, extra: 2);
|
||||
using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, history: originServer.Port);
|
||||
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
|
||||
children.Length.ShouldBe(3);
|
||||
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
||||
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false,
|
||||
children.Select(c => new HistoryReadValueId { NodeId = c }).ToArray(), TestContext.Current.CancellationToken);
|
||||
var results = response.Results.ToArray()!;
|
||||
results.ShouldAllBe(r => StatusCode.IsGood(r.StatusCode), string.Join(", ", results.Select(r => r.StatusCode.ToString())));
|
||||
results.ShouldAllBe(r => Values(r).Count == 3);
|
||||
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin));
|
||||
}
|
||||
|
||||
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
||||
public async Task A_renewal_in_flight_does_not_crowd_out_a_cold_read_of_another_node()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1);
|
||||
var connections = new GatedConnections(origin);
|
||||
await WithComposedServer(origin, origin.Root, async (session, _, _, _, access, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
|
||||
var (a, b) = (children[0], children[1]);
|
||||
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
||||
connections.HoldMetadataFor = a.IdentifierAsString;
|
||||
(await ReadValue(client, a, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadWaitingForInitialData.Code);
|
||||
await connections.Held.Task.WaitAsync(TimeSpan.FromSeconds(10), ct); // A's renewal is now parked at the origin
|
||||
|
||||
// Re-browse renews B (and A) by page; B's cold read must still be dispatched while A's renewal is in flight.
|
||||
await BrowseAll(client, anchor, 10);
|
||||
var reads = connections.ReadCalls;
|
||||
(await ReadValue(client, b, ct)).StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code);
|
||||
for (var i = 0; i < 200 && connections.ReadCalls == reads; i++) await Task.Delay(25, ct);
|
||||
connections.ReadCalls.ShouldBeGreaterThan(reads, "an on-demand renewal holds no unary capacity");
|
||||
connections.Release();
|
||||
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
|
||||
}
|
||||
|
||||
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
||||
public async Task An_invalidated_lease_is_a_refusal_not_a_lapse_and_never_reaches_the_origin()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1);
|
||||
origin.Publish(42);
|
||||
var connections = new GatedConnections(origin);
|
||||
await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, access, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
await BrowseAll(client, anchor, 1);
|
||||
(await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
|
||||
resolver.TryResolveProjected(DataRealm.Raw, anchor.IdentifierAsString, out var proof).ShouldBeTrue();
|
||||
((BoundProjectionLease)proof!.Lease).Remote.Invalidate();
|
||||
var metadata = connections.MetadataCalls;
|
||||
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
|
||||
access.LapseRenewalsStartedForTests.ShouldBe(0, "a revoked lease is never renewed");
|
||||
connections.MetadataCalls.ShouldBe(metadata);
|
||||
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
|
||||
}
|
||||
|
||||
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
||||
public async Task A_grant_revoked_while_the_renewal_is_at_the_origin_is_not_committed_and_the_read_is_denied()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1);
|
||||
origin.Publish(42);
|
||||
var connections = new GatedConnections(origin);
|
||||
LocalCatalogCoordinator? coordinator = null;
|
||||
await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, access, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
await BrowseAll(client, anchor, 1);
|
||||
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
||||
connections.HoldMetadataFor = anchor.IdentifierAsString;
|
||||
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadWaitingForInitialData.Code);
|
||||
await connections.Held.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
|
||||
Prepare(coordinator!, localPermissions: BrowseOnlyGrant); // the caller's Read grant is gone from now on
|
||||
connections.Release();
|
||||
for (var i = 0; i < 40; i++)
|
||||
{
|
||||
var value = await ReadValue(client, anchor, ct);
|
||||
StatusCode.IsGood(value.StatusCode).ShouldBeFalse("nothing is served after the grant was revoked");
|
||||
if (value.StatusCode.Code == StatusCodes.BadUserAccessDenied.Code) break;
|
||||
await Task.Delay(50, ct);
|
||||
}
|
||||
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
|
||||
resolver.TryResolveProjected(DataRealm.Raw, anchor.IdentifierAsString, out _).ShouldBeFalse("the renewal never committed");
|
||||
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale, onCoordinator: value => coordinator = value);
|
||||
}
|
||||
|
||||
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
||||
public async Task A_node_whose_mapping_is_removed_while_it_renews_is_not_revived()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1);
|
||||
origin.Publish(42);
|
||||
var connections = new GatedConnections(origin);
|
||||
await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, _, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
await BrowseAll(client, anchor, 1);
|
||||
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
||||
connections.HoldMetadataFor = anchor.IdentifierAsString;
|
||||
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadWaitingForInitialData.Code);
|
||||
await connections.Held.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
|
||||
resolver.ApplyMappings([]); // the mapping goes away mid-renewal
|
||||
connections.Release();
|
||||
await Task.Delay(300, ct);
|
||||
resolver.TryResolveProjected(DataRealm.Raw, anchor.IdentifierAsString, out _).ShouldBeFalse();
|
||||
resolver.TryResolveForRenewal(DataRealm.Raw, anchor.IdentifierAsString, out _).ShouldBeFalse();
|
||||
var value = await ReadValue(client, anchor, ct);
|
||||
StatusCode.IsGood(value.StatusCode).ShouldBeFalse();
|
||||
value.StatusCode.Code.ShouldNotBe(StatusCodes.BadWaitingForInitialData.Code, "a removed node is not a lapse");
|
||||
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
|
||||
}
|
||||
|
||||
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
||||
public async Task Concurrent_history_reads_against_a_slow_origin_are_bounded_and_retryable_and_recover()
|
||||
{
|
||||
await using var originServer = await HistoryOrigin.StartAsync(7);
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
|
||||
var connections = new GatedConnections(origin);
|
||||
OtOpcUaNodeManager? manager = null;
|
||||
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
await BrowseAll(client, anchor, 1);
|
||||
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
||||
connections.HoldMetadataFor = anchor.IdentifierAsString; // the origin never answers the renewal until released
|
||||
var clock = System.Diagnostics.Stopwatch.StartNew();
|
||||
async Task<(Opc.Ua.HistoryReadResult Result, TimeSpan Took)> Timed()
|
||||
{
|
||||
var each = System.Diagnostics.Stopwatch.StartNew();
|
||||
var result = await RawHistory(client, anchor, 3, default);
|
||||
return (result, each.Elapsed);
|
||||
}
|
||||
var reads = Enumerable.Range(0, 24).Select(_ => Timed()).ToArray();
|
||||
var all = Task.WhenAll(reads);
|
||||
// Every waiter is bounded (a non-local history slot, then at most the lapse wait) — none is pinned until the origin
|
||||
// answers, which it never does while held.
|
||||
(await Task.WhenAny(all, Task.Delay(TimeSpan.FromSeconds(30), TestContext.Current.CancellationToken))).ShouldBe(all,
|
||||
"every concurrent HistoryRead returned while the origin was still silent");
|
||||
clock.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(30));
|
||||
var statuses = all.Result.Select(r => r.Result.StatusCode.Code).ToArray();
|
||||
// Waiters are capped by the non-local history slots: the reads that found none answer at once instead of each pinning
|
||||
// an SDK thread for the whole lapse wait (the pre-review code made all 24 wait it out).
|
||||
var slots = OriginHistoryPort.RemoteSlots(manager!.MaxConcurrentHistoryReadBatches);
|
||||
all.Result.Count(r => r.Took < TimeSpan.FromSeconds(2.5)).ShouldBeGreaterThanOrEqualTo(24 - slots,
|
||||
string.Join(", ", all.Result.Select(r => r.Took.TotalMilliseconds.ToString("0"))));
|
||||
statuses.ShouldAllBe(code => code == StatusCodes.BadResourceUnavailable.Code, "granted + lapsed + silent origin ⇒ retryable");
|
||||
originServer.Source.Calls.ShouldBe(0);
|
||||
|
||||
connections.Release();
|
||||
Opc.Ua.HistoryReadResult? served = null;
|
||||
for (var i = 0; i < 40; i++)
|
||||
{
|
||||
served = await RawHistory(client, anchor, 3, default);
|
||||
if (StatusCode.IsGood(served.StatusCode)) break;
|
||||
origin.Clock.Advance(ProjectedDataAccess.LapseRenewalBackoff + TimeSpan.FromMilliseconds(1));
|
||||
await Task.Delay(50, TestContext.Current.CancellationToken);
|
||||
}
|
||||
StatusCode.IsGood(served!.StatusCode).ShouldBeTrue(served.StatusCode.ToString());
|
||||
}, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (_, nm) => manager = nm);
|
||||
}
|
||||
|
||||
/// <summary>One persistent origin connection whose metadata call for one node can be parked; counts browse/metadata/read calls.</summary>
|
||||
private sealed class GatedConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource
|
||||
{
|
||||
private IDataConnection? _inner;
|
||||
private readonly object _gate = new();
|
||||
private readonly object _route = new();
|
||||
private int _browse, _metadata, _read;
|
||||
private TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public int BrowseCalls => Volatile.Read(ref _browse);
|
||||
public int MetadataCalls => Volatile.Read(ref _metadata);
|
||||
public int ReadCalls => Volatile.Read(ref _read);
|
||||
/// <summary>The projected local identifier whose origin metadata call is parked until <see cref="Release"/>.</summary>
|
||||
public volatile string? HoldMetadataFor;
|
||||
public TaskCompletionSource Held { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public void Release() { HoldMetadataFor = null; _release.TrySetResult(); }
|
||||
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (connectionId != "link") return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(null);
|
||||
lock (_gate) _inner ??= peer.Connection();
|
||||
return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new Borrowed(new Gate(_inner, this), _route));
|
||||
}
|
||||
private sealed class Borrowed(IDataConnection connection, object route) : IGrpcDataAdapterConnectionLease
|
||||
{
|
||||
public IDataConnection Connection => connection;
|
||||
public CancellationToken CancellationToken => CancellationToken.None;
|
||||
public object? RouteIdentity => route;
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
}
|
||||
private sealed class Gate(IDataConnection inner, GatedConnections owner) : IDataConnection, IDataHistoryService
|
||||
{
|
||||
public DataTarget Target => inner.Target;
|
||||
public TimeProvider Clock => inner.Clock;
|
||||
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken);
|
||||
public Task<DataBrowseBranch> BrowseAsync(DataBrowseRequest request, CancellationToken cancellationToken)
|
||||
{ Interlocked.Increment(ref owner._browse); return inner.BrowseAsync(request, cancellationToken); }
|
||||
public async Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
Interlocked.Increment(ref owner._metadata);
|
||||
if (owner.HoldMetadataFor is { } held && request.Views.Any(view =>
|
||||
ProjectedDataIds.Identifier("map", view.Address) == held))
|
||||
{
|
||||
owner.Held.TrySetResult();
|
||||
await owner._release.Task.WaitAsync(cancellationToken);
|
||||
}
|
||||
return await inner.GetMetadataAsync(request, cancellationToken);
|
||||
}
|
||||
public Task<IReadOnlyList<DataReadResult>> ReadAsync(DataReadRequest request, CancellationToken cancellationToken)
|
||||
{ Interlocked.Increment(ref owner._read); return inner.ReadAsync(request, cancellationToken); }
|
||||
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken);
|
||||
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken);
|
||||
public Task<IReadOnlyList<DataHistoryReadResult>> ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) =>
|
||||
((IDataHistoryService)inner).ReadAsync(request, cancellationToken);
|
||||
public Task ReleaseAsync(IReadOnlyList<byte[]> continuations, CancellationToken cancellationToken) =>
|
||||
((IDataHistoryService)inner).ReleaseAsync(continuations, cancellationToken);
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
+250
@@ -0,0 +1,250 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using DataBrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest;
|
||||
using DataReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest;
|
||||
using DataReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
/// <summary>
|
||||
/// #922 — a projected node idle longer than its <c>MetadataLeaseMilliseconds</c> (15 s here) is a LAPSE, not an
|
||||
/// authorization failure: a value Read answers a retryable status and renews the lease on demand (no re-browse), a
|
||||
/// HistoryRead renews it within the request's deadline and is served, and a re-browse served from a still-cached page
|
||||
/// renews a lease that is past half its life. A real ACL denial stays <c>BadUserAccessDenied</c> after a lapse too, and
|
||||
/// never reaches the origin.
|
||||
/// </summary>
|
||||
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
{
|
||||
private const int BrowseOnlyGrant = 1;
|
||||
// The fixture origin observes its one sample at t0 and never again, so the sample's ORIGIN age grows with the manual clock:
|
||||
// a stale timeout and a client maxAge longer than the test's idle gaps keep that age out of what is under test (the lease).
|
||||
private const int LongStale = 120_000;
|
||||
private const double LongMaxAge = 120_000;
|
||||
|
||||
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
||||
public async Task A_value_read_after_the_metadata_lease_lapses_is_retryable_and_renews_on_demand_without_a_browse()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1);
|
||||
origin.Publish(42);
|
||||
var connections = new CountingConnections(origin);
|
||||
await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, _, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
await BrowseAll(client, anchor, 1);
|
||||
(await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
|
||||
var browses = connections.BrowseCalls;
|
||||
var metadata = connections.MetadataCalls;
|
||||
|
||||
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
||||
var id = ProjectedDataIds.Identifier("map", origin.Raw.Address);
|
||||
resolver.TryResolveProjected(DataRealm.Raw, id, out _).ShouldBeFalse("precondition: the lease has lapsed");
|
||||
|
||||
// A non-Value attribute of the lapsed node is not access-denied either (retryable while the lease renews).
|
||||
var name = (await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Neither,
|
||||
[new ReadValueId { NodeId = anchor, AttributeId = Attributes.DisplayName }], ct)).Results[0];
|
||||
name.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code);
|
||||
var lapsed = await ReadValue(client, anchor, ct);
|
||||
lapsed.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code, "a lease lapse is not an authorization failure");
|
||||
// The attribute read above already started the renewal, which may have finished (and fetched the value) by now.
|
||||
(StatusCode.IsGood(lapsed.StatusCode) || lapsed.StatusCode.Code == StatusCodes.BadWaitingForInitialData.Code ||
|
||||
lapsed.StatusCode.Code == StatusCodes.BadResourceUnavailable.Code).ShouldBeTrue(lapsed.StatusCode.ToString());
|
||||
(await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
|
||||
resolver.TryResolveProjected(DataRealm.Raw, id, out _).ShouldBeTrue("the read renewed the node's authority");
|
||||
connections.BrowseCalls.ShouldBe(browses, "the renewal is an exact metadata refresh, not a re-browse");
|
||||
connections.MetadataCalls.ShouldBeGreaterThan(metadata, "renewed by an exact metadata call");
|
||||
|
||||
// And again: every idle gap longer than the lease renews the same way.
|
||||
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
||||
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadWaitingForInitialData.Code);
|
||||
(await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
|
||||
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
|
||||
}
|
||||
|
||||
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
||||
public async Task Without_the_local_read_grant_a_lapsed_value_read_is_still_BadUserAccessDenied_and_never_renews()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1);
|
||||
origin.Publish(42);
|
||||
var connections = new CountingConnections(origin);
|
||||
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, access, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
await BrowseAll(client, anchor, 1);
|
||||
// Positive control: before the lapse the same caller is refused for the ACL, not the lease.
|
||||
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
|
||||
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
||||
var metadata = connections.MetadataCalls;
|
||||
for (var i = 0; i < 3; i++)
|
||||
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
|
||||
await Task.Delay(200, ct);
|
||||
connections.MetadataCalls.ShouldBe(metadata, "an unauthorized caller never triggers a renewal at the origin");
|
||||
connections.ReadCalls.ShouldBe(0);
|
||||
// Counted synchronously when a renewal is admitted, so this absence is not a race with a background task.
|
||||
access.LapseRenewalsStartedForTests.ShouldBe(0);
|
||||
}, connectionSource: connections, localPermissions: BrowseOnlyGrant);
|
||||
}
|
||||
|
||||
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
||||
public async Task A_history_read_after_the_metadata_lease_lapses_renews_within_the_request_and_is_served()
|
||||
{
|
||||
await using var originServer = await HistoryOrigin.StartAsync(7);
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
|
||||
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
await BrowseAll(client, anchor, 1);
|
||||
StatusCode.IsGood((await RawHistory(client, anchor, 3, default)).StatusCode).ShouldBeTrue();
|
||||
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
||||
|
||||
var lapsed = await RawHistory(client, anchor, 3, default);
|
||||
lapsed.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code, "a lease lapse is not an authorization failure");
|
||||
StatusCode.IsGood(lapsed.StatusCode).ShouldBeTrue(lapsed.StatusCode.ToString());
|
||||
Values(lapsed).Count.ShouldBe(3);
|
||||
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin));
|
||||
}
|
||||
|
||||
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
||||
public async Task A_lapsed_history_read_whose_renewal_cannot_reach_the_origin_is_retryable_not_denied_and_recovers()
|
||||
{
|
||||
await using var originServer = await HistoryOrigin.StartAsync(7);
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
|
||||
var connections = new DownableConnections(new PersistentConnections(origin));
|
||||
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
await BrowseAll(client, anchor, 1);
|
||||
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
||||
connections.Down = true;
|
||||
var calls = originServer.Source.Calls;
|
||||
var down = await RawHistory(client, anchor, 3, default);
|
||||
down.StatusCode.Code.ShouldBe(StatusCodes.BadResourceUnavailable.Code, "granted, lapsed, origin unreachable: retryable");
|
||||
originServer.Source.Calls.ShouldBe(calls, "nothing is read under a lapsed lease");
|
||||
|
||||
connections.Down = false;
|
||||
origin.Clock.Advance(ProjectedDataAccess.LapseRenewalBackoff + TimeSpan.FromMilliseconds(1)); // past the failure back-off
|
||||
var recovered = await RawHistory(client, anchor, 3, default);
|
||||
StatusCode.IsGood(recovered.StatusCode).ShouldBeTrue(recovered.StatusCode.ToString());
|
||||
}, localPermissions: 15, allowHistory: true, connectionSource: connections);
|
||||
}
|
||||
|
||||
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
||||
public async Task Without_the_local_history_grant_a_lapsed_history_read_is_still_BadUserAccessDenied_and_unsent()
|
||||
{
|
||||
await using var originServer = await HistoryOrigin.StartAsync(7);
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
|
||||
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
await BrowseAll(client, anchor, 1);
|
||||
origin.Clock.Advance(TimeSpan.FromSeconds(16));
|
||||
var result = await RawHistory(client, anchor, 3, default);
|
||||
result.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
|
||||
result.ContinuationPoint.IsEmpty.ShouldBeTrue();
|
||||
originServer.Source.Calls.ShouldBe(0);
|
||||
}, localPermissions: 7, allowHistory: true, connectionSource: new PersistentConnections(origin));
|
||||
}
|
||||
|
||||
[Fact(Timeout = 90000), Trait("Issue", "922")]
|
||||
public async Task A_rebrowse_served_from_a_cached_page_past_half_its_lease_renews_the_lease()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1);
|
||||
origin.Publish(42);
|
||||
var connections = new CountingConnections(origin);
|
||||
await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, _, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
var id = ProjectedDataIds.Identifier("map", origin.Raw.Address);
|
||||
await BrowseAll(client, anchor, 1);
|
||||
var browses = connections.BrowseCalls;
|
||||
|
||||
// Inside the first half the cached page is served as is (no origin call).
|
||||
origin.Clock.Advance(TimeSpan.FromSeconds(5));
|
||||
await BrowseAll(client, anchor, 1);
|
||||
await Task.Delay(200, ct);
|
||||
connections.BrowseCalls.ShouldBe(browses, "a fresh cached page is served without an origin call");
|
||||
|
||||
// Past half its life the cached page is still served, and the re-browse refreshes it in the background.
|
||||
origin.Clock.Advance(TimeSpan.FromSeconds(5));
|
||||
await BrowseAll(client, anchor, 1);
|
||||
for (var i = 0; i < 200 && connections.BrowseCalls == browses; i++) await Task.Delay(25, ct);
|
||||
connections.BrowseCalls.ShouldBeGreaterThan(browses, "the re-browse refreshed the cached page");
|
||||
|
||||
// The original lease (t0 + 15 s) is gone; the renewed one still holds at t0 + 20 s.
|
||||
ProjectedNodeProof? renewed = null;
|
||||
for (var i = 0; i < 200; i++)
|
||||
{
|
||||
if (resolver.TryResolveProjected(DataRealm.Raw, id, out renewed) && renewed is not null &&
|
||||
((BoundProjectionLease)renewed.Lease).Remaining > TimeSpan.FromSeconds(10)) break;
|
||||
await Task.Delay(25, ct);
|
||||
}
|
||||
origin.Clock.Advance(TimeSpan.FromSeconds(10));
|
||||
resolver.TryResolveProjected(DataRealm.Raw, id, out _).ShouldBeTrue("the re-browse renewed the node's lease");
|
||||
(await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
|
||||
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
|
||||
}
|
||||
|
||||
private static async Task<Opc.Ua.DataValue> ReadValue(SessionClient client, NodeId node, CancellationToken ct) =>
|
||||
(await client.ReadAsync(new RequestHeader(), LongMaxAge, TimestampsToReturn.Both,
|
||||
[new ReadValueId { NodeId = node, AttributeId = Attributes.Value }], ct)).Results[0];
|
||||
|
||||
private static async Task<object?> ReadUntilGood(SessionClient client, NodeId node, CancellationToken ct)
|
||||
{
|
||||
var deadline = DateTime.UtcNow.AddSeconds(10);
|
||||
Opc.Ua.DataValue value;
|
||||
do
|
||||
{
|
||||
value = await ReadValue(client, node, ct);
|
||||
if (StatusCode.IsGood(value.StatusCode)) return value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy);
|
||||
value.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code);
|
||||
await Task.Delay(25, ct);
|
||||
} while (DateTime.UtcNow < deadline);
|
||||
throw new ShouldAssertException($"the projected read never became Good (last {value.StatusCode})");
|
||||
}
|
||||
|
||||
/// <summary>A connection source that can be switched to "no connection" (an unreachable origin / undeployed route).</summary>
|
||||
private sealed class DownableConnections(IGrpcDataAdapterConnectionSource inner) : IGrpcDataAdapterConnectionSource
|
||||
{
|
||||
public volatile bool Down;
|
||||
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
|
||||
Down ? ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(null) : inner.AcquireAsync(connectionId, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Like <c>FakeConnections</c>, counting browse, metadata and read calls separately.</summary>
|
||||
private sealed class CountingConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource
|
||||
{
|
||||
private int _browse, _metadata, _read;
|
||||
public int BrowseCalls => Volatile.Read(ref _browse);
|
||||
public int MetadataCalls => Volatile.Read(ref _metadata);
|
||||
public int ReadCalls => Volatile.Read(ref _read);
|
||||
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
|
||||
ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(connectionId == "link" ? new Lease(new Connection(peer.Connection(), this)) : null);
|
||||
private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease
|
||||
{
|
||||
public IDataConnection Connection => connection;
|
||||
public CancellationToken CancellationToken => CancellationToken.None;
|
||||
public ValueTask DisposeAsync() => connection.DisposeAsync();
|
||||
}
|
||||
private sealed class Connection(IDataConnection inner, CountingConnections owner) : IDataConnection
|
||||
{
|
||||
public DataTarget Target => inner.Target;
|
||||
public TimeProvider Clock => inner.Clock;
|
||||
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken);
|
||||
public Task<DataBrowseBranch> BrowseAsync(DataBrowseRequest request, CancellationToken cancellationToken)
|
||||
{ Interlocked.Increment(ref owner._browse); return inner.BrowseAsync(request, cancellationToken); }
|
||||
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
|
||||
{ Interlocked.Increment(ref owner._metadata); return inner.GetMetadataAsync(request, cancellationToken); }
|
||||
public Task<IReadOnlyList<DataReadResult>> ReadAsync(DataReadRequest request, CancellationToken cancellationToken)
|
||||
{ Interlocked.Increment(ref owner._read); return inner.ReadAsync(request, cancellationToken); }
|
||||
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken);
|
||||
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken);
|
||||
public ValueTask DisposeAsync() => inner.DisposeAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user