mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-20 08:41:51 +08:00
87c35b84b6
## Summary
Fixes the findings of a bug audit of `Opc.Ua.Client` and
`Opc.Ua.Client.ComplexTypes`, done on master plus #4516 (now merged).
- **Audit:** 82 findings across 12 areas, each checked against the OPC
UA specification. Final severities: 2 High, 37 Medium, 43 Low.
- **Fixes:** 76 fixed, 4 partial, 2 skipped (see [Not
fixed](#not-fixed--partial)).
- **Review:** a follow-up review of the fixes found 15 more defects in
them, all fixed here.
- **Tests:** every fix has a regression test, except a few races that
cannot be reproduced deterministically; the commit messages say which.
The finding IDs (`L<area>-<n>` for the audit, `G<n>` for the review)
appear in the commit titles.
## Behaviour and user-facing changes
### Security and endpoint selection
- **Reconnect no longer drops to weaker security (L3-1, High).** When
the server rejects the configured security policy or mode during
reconnect, `SessionReconnectHandler` no longer switches to whatever
endpoint the server advertises, None included. It only picks an endpoint
at least as strong as the configured one, judged by a locally computed
security level. The server-advertised `SecurityLevel` is not trusted. If
nothing qualifies, reconnect fails with the original error (new log
event `SessionReconnectHandler + 13`) and keeps retrying with the
original settings.
- **`CoreClientUtils.SelectEndpoint(useSecurity: true)` never returns a
SecurityMode None endpoint over opc.tcp (L9-9, High).** It now returns
`null` when no secure endpoint matches.
- When the discovery URL is `https`/`opc.https`, an HTTPS endpoint with
SecurityMode None is still accepted as a last resort, because TLS
protects it (Part 6 §7.4.1) (G17).
- Endpoints with SecurityMode `Invalid` no longer count as secure.
- `GlobalDiscoveryServerClient` and `ServerPushConfigurationClient` now
throw `BadSecurityPolicyRejected` when no secure endpoint matches,
instead of passing `null` on. The ConsoleReferenceClient sample reports
this with a clear error.
- **No Bearer/Basic credentials over `http://` (L12-2).**
`WebApiClient.Create` and WebApi channel open/reconnect reject them with
`BadSecurityChecksFailed`. The public `WebApiClient(HttpClient, …)`
constructor also rejects them when the client's `BaseAddress` is not
https, and every send checks the address it actually goes to (covers a
`BaseAddress` set later).
### Session, keep-alive and identity
- **Faster detection of a silent server (L1-1).** The keep-alive Read is
now bounded by its `TimeoutHint` (2 × `KeepAliveInterval`), which is
what Part 4 §7.32 says the client should do. It then fails with
`BadNoCommunication`, so reconnect starts after about 2 ×
`KeepAliveInterval` instead of `OperationTimeout` (120 s by default).
- **Operations fail fast during a channel-manager recovery (L1-2, G9).**
`UpdateIdentityAsync`, `TransferSubscriptionsAsync` and
`ReactivateSubscriptionsAsync` fail with `BadSecureChannelClosed`
(retryable) instead of deadlocking. This covers the operation holding
the reconnect lock and any queued behind it.
- **Closing or disposing from a handler no longer waits on itself (L1-3,
G5, G6).**
- `Session` and `ManagedSession` Close/Dispose from a Notification
handler no longer wait 30 s for their own background drain.
- Disposing a `ManagedSession` from a keep-alive `PublishStatusChanged`
handler no longer deadlocks.
- Tasks spawned by a handler no longer count as "the handler" (the owner
marker is scoped to the work item).
- **Switching to an ECC user-token policy takes two ActivateSession
calls (L1-4, G4).** This follows Part 6 §6.8.2 (fetch the ephemeral key,
then activate).
- If the server returns no key, the switch fails with
`BadSecurityPolicyRejected`.
- If the second activation is rejected, the old identity stays on the
override policy with the key just fetched. Restoring the old key was
tried: against the reference server the next reconnect then failed to
decrypt the identity token.
- **`ManagedSession.ConfiguredEndpoint` follows failover (L2-6).** It
now reports the inner session's endpoint, so it changes after a failover
or network-path rotation.
- **An explicit identity update replaces the identity provider (L2-7).**
`ManagedSession.UpdateSessionAsync(identity)` stops the provider's
refresh loop and drops the provider for good. If the update fails, the
loop is restarted.
- **Reconnect waits for in-flight calls on a healthy channel (L2-3,
G8a).** Reconnect/failover on a healthy channel (certificate or
trust-list change, manual reconnect) waits for in-flight service calls.
The wait is bounded (max(`KeepAliveInterval`, 1 s)) only once the
channel is unhealthy (keep-alive stopped, channel not Ready), so a dead
channel no longer holds recovery for `OperationTimeout`.
- **Smaller fixes:**
- Restore reads the server certificate as a chain; this failed on macOS
(L1-5).
- Session recovery can no longer run twice at once (L1-6).
- Identity expiries more than 49.7 days out no longer throw (L2-2).
- Keep-alive reconnect suppression is recalculated on a lease swap
(L2-4).
### Reconnect state machine and reverse connect
- **⚠ `MaxTotalReconnectTime = 0` now means "no time limit" (L3-7).
Reviewer decision needed.** Before, 0 disabled reconnect entirely.
Negative values other than `Timeout.InfiniteTimeSpan` now throw
`ArgumentOutOfRangeException` when the state machine is constructed;
before, they crashed the worker. The XML docs of
`ReconnectPolicy`/`ReconnectPolicyOptions` are updated. If 0 should keep
meaning "no reconnect", this is a one-line revert.
- **A close racing the end of the reconnect budget is no longer lost
(L3-4).** It goes through the normal close instead of switching to
failover.
- **The "reconnect worker" marker covers one step only (L2-1).** It
lasts for a single connect/reconnect/failover/close step. Keep-alive,
publish and identity loops started in a step no longer count as the
worker afterwards.
- **Reverse-connect strategies `Undefined` and `Any` alone are removed
after the first callback (L8-1).** This matches the documentation;
before, they behaved like `Always`.
- **`AddEndpoint` for a URL that is already added disposes the replaced
listener (L8-2).**
### Service calls
- **Batched calls clean up after a failed later batch (L3-2).** When a
later batch of
`Browse`/`BrowseNext`/`HistoryRead`/`CreateMonitoredItems` fails, the
continuation points and monitored items created by earlier batches are
released or deleted before the exception is rethrown. This adds one
request. `AddNodes`/`RegisterNodes` are not undone.
- **Batched diagnostic infos point at the right strings (L3-3).** The
string-table indexes are rebased when diagnostics are padded.
- **`ReadBytesAsync` rejects oversized responses (L3-5).** It throws
`BadUnknownResponse` when the server returns more bytes than requested,
and `BadEncodingLimitsExceeded` beyond `int` range.
- **`ReadByteStringInChunksAsync` handles an unknown server limit
(L3-6).** When the server's `MaxByteStringLength` is 0 (absent) or
larger than `int`, it falls back to the client's
`MessageContext.MaxByteStringLength`. It throws only when both are
unknown.
### Browse and NodeCache
- **Empty browse pages with a continuation point are followed (L9-1,
L9-4, L9-5, G16).** Part 4 §5.9.2.1 allows a server to return an empty
page with a continuation point, so browsing keeps following it. After 10
consecutive empty rounds it gives up with `BadNoData` and releases the
continuation point.
- `BrowseAsync(NodeId)` now throws instead of silently returning a
truncated list.
- `BrowseStreamAsync` yields a `BadNoData` result for that node.
- The same cap, through one shared helper, now also protects
`RoleManagementClient.ListRolesAsync` and the FileSystem
enumerate/empty-check loops.
- **Continuation points are released on failure (L9-3).**
`BrowseAsync(NodeId)` releases them on any exception, and
`BrowseStreamAsync` releases all points of the current page when the
consumer stops early.
- **NodeCache lookups propagate cancellation (L9-6, L9-8).**
`FindAsync`, `IsKnownAsync`, `FetchNodeAsync`,
`FindReferenceTypeNameAsync`, the reference-table fill and the
type-hierarchy search now let `OperationCanceledException` through.
Before, a cancelled lookup looked like "node does not exist".
- **A NodeClass mismatch fails only that node (L9-7).** It returns
`BadNodeClassInvalid` for that node instead of throwing
`KeyNotFoundException` for the whole batch.
- **Smaller fixes:**
- `MaxNodesPerBrowse` ≥ 2^31 no longer breaks the managed browse (L9-2).
- Null discovery URLs are skipped (L9-10).
- `ModelChangeTracker` no longer cancels a joined start (L9-11).
- **Log changes:** `BrowserContinuationPointExistsButBrowse` (Browser +
0) was removed, and `BrowserServerReturnedEmptyReferencesBut` now
includes the round count.
### Subscriptions (default engine)
- **Recovery after a transfer delivers each message exactly once (L5-1,
G22).** Messages already dispatched are acknowledged instead of
republished and delivered again. Messages whose earlier republish failed
are now republished and delivered, with the Republish flag and after
newer messages, instead of being acknowledged and lost.
- **A keep-alive that proves a gap triggers republish at once (L5-5,
G23).** The dedup mark moves only past messages that were actually
recovered, so a failed republish is retried by the next data message.
- **Item changes that fail are retried with backoff (L5-3).** They are
retried on the next apply pass after the state manager's 250 ms–5 s
backoff, instead of six times back to back. The six attempts now span
about 13 s.
- **Extreme revised intervals no longer throw (L5-4, L6-1).** Very large
or NaN intervals and counts revised by the server are capped (NaN falls
back to the requested value). Before, the overflow could stop every
publish worker.
- **`SetTriggeringAsync` from a callback no longer hangs (L5-7, G21).**
While the subscription is deleted, recreated or disposed, it returns
`BadOperationAbandoned`. A cancelled reset no longer makes later calls
fail.
- **Publish responses for unknown subscription ids (L6-3, L6-4, G20).**
The client no longer re-sends acknowledgements the server already
processed. An unknown id seen while a creation is pending is left alone
instead of being deleted.
- **Smaller fixes:**
- A null and an empty `IndexRange` are treated as equal, and restored
snapshots use `null` (L5-6).
- A failed partition attach during restore is rolled back (L6-2).
- `StreamingSubscription` throws `ObjectDisposedException` after dispose
(L6-6).
### Subscriptions (classic `Subscription`)
- **Republish no longer abandons other missing messages (L7-1).** A
Republish response no longer overwrites `AvailableSequenceNumbers`, so
other missing messages are not given up while the server still holds
them.
- **Late copies are no longer delivered twice (L7-2).** Copies of
already-processed sequence numbers are ignored, and creating a new
server subscription resets the sequence state.
- **Disposing from a keep-alive handler no longer deadlocks (L7-3).**
`Dispose()` from a keep-alive `PublishStatusChanged` handler can return
while that callback is still finishing.
- **Transfer of a restored subscription (L7-4, G27).**
- It succeeds even when some saved items were never created.
- The server subscription is deleted only when this session's own
TransferSubscriptions just moved it and adoption failed definitively
(item count mismatch or a non-transient status). Transient errors and
`ReactivateSubscriptionsAsync` never delete it.
- The public `Subscription.TransferAsync` never deletes.
- **Smaller fixes:**
- Cloned items keep their triggering links (L7-5).
- `CreateAsync` clears stale server ids (L7-6).
- A `Good_SubscriptionTransferred` for the client's own transfer is
ignored (L7-7).
- An item removed while its create is in flight is deleted afterwards
(L7-8).
- The publish timeout for very long keep-alives no longer overflows
(L7-9).
- A negative `MaxMessageCount` is handled (L7-10).
- `LastMessage` tolerates a wrong notification type (L7-11).
- Pending acks exactly 2^31 away no longer throw (L4-1).
- **Log changes:** new log events `Subscription + 68..70`.
### Redundancy
- **Warm/Hot demotion (L4-2, G1, G3).**
- Without token reuse, the demoted leader closes its session and
reconnects as a fresh standby.
- With token reuse, it abandons the shared server session locally,
without CloseSession, so the new leader can reactivate it and keep its
subscriptions. This uses the new internal methods
`ManagedSession.AbandonServerSessionAsync` and
`Session.AbandonServerSession`.
- `RoleChanged(false)` is now raised before the standby connect and no
longer depends on it, so `CurrentSession` can briefly be `null`.
- Exceptions from `RoleChanged` handlers are logged and do not stop the
teardown.
- **Promotion (L4-3, G2).** A promoted standby that adopts the leader's
session first closes its own server session. A retried promotion keeps
the session it already adopted.
- **Client failover takeover (L4-4, partial).** Subscriptions the backup
prepared in advance (not yet created, `TransferId` set to the active
client's id) are moved through the session's own transfer and keep
publishing. `docs/HighAvailability.md` is updated.
- **`ShouldFailover` through the interface (L4-6).** Calling it through
`IServerRedundancyHandler` no longer fails over away from a server that
is still Healthy.
### Fluent / dependency injection
- **Shared DI session (L10-5).** The shared session from `AddClient` is
reconnected after a caller disposes it, and is disposed with the
container. After that the connect delegate throws
`ObjectDisposedException`.
- **New public API:
`ManagedSessionBuilder.WithServerRedundancyOptions(ServerRedundancyOptions)`
(L10-6).** This is additive. The `Session.ServerRedundancy` options are
now actually applied.
- **`AddDiscoveryAndConnect` rewrites the advertised address (L10-7).**
It replaces the host and port the server advertises with those of the
discovery URL (Part 4 §5.6.2.1, NAT/containers), and prefers endpoints
with the same scheme.
### State machines and role management
- **`GetSubStateMachineAsync` returns the instance's own sub-state
machine (L10-1).** Before, it returned the type's placeholder.
- **`WaitForStateAsync` reports failures with OPC UA status codes
(L10-2).** It throws `BadNotFound` when `CurrentState/Id` cannot be
resolved, and `BadInvalidState` when observation ends without reaching
the state. Before, both surfaced as `OperationCanceledException`.
- **`RoleManagementClient.ListRolesAsync` pages correctly (L10-3).** It
follows continuation points, releases them on any failure, and throws on
a Bad browse status instead of returning an empty list.
- **Role properties are read into the right fields (L10-4).** Properties
whose namespace cannot be resolved are skipped instead of shifting the
other values.
### File system, temporary files and alias names
- **Path escaping (L11-8, G12).**
- Path segments escape `:` and `/` with `&`, and `&` itself as `&&`
before those characters or at the end of a name.
- `Format` and `Parse` round-trip all names. Typed input ending in `&/`
now reads the slash as part of the name.
- A segment without a namespace prefix also matches a namespace-0 child
when nothing matches in the parent's namespace.
- **Stale path cache (L11-1).** When a cached lookup fails,
`GetInfoAsync` retries once from the server. `ExistsAsync` and
`GetFileAsync` report "not found" instead of throwing.
- **`GenerateFileForReadAsync` waits for the file (L11-2).** It waits
until the file-generation state machine reaches ReadTransfer (`Idle`
counts as not started yet), and throws `IOException` if it reports
Error. The wait is bounded only by the caller's token.
- **Non-recursive delete refuses hidden children (L11-3).** It refuses
when the directory holds children that the subtype options hide from
enumeration. Before, the server deleted them all.
- **Alias names (L11-5, L11-6, L11-7).**
- `BadMethodInvalid` maps to `NotSupportedException` for all alias
calls, so `UseVerbose` falls back to `FindAlias`.
- A duplicate alias name resolves to all its targets.
- If the refresh strategy fails to start, the resolver logs a warning
and keeps working without automatic invalidation. New log event block
`AliasNameResolver = 560`.
- **Null profile entries (L11-4).** Null `ServerProfileArray` entries no
longer crash `GetConformanceInfoAsync`.
### WebApi transport
- **Failures come back as `ServiceResultException` (L12-1).**
- A timeout becomes `BadRequestTimeout`.
- HTTP 429/503 becomes `BadServerTooBusy` with the Retry-After hint, on
every target framework. `WebApiClient` checks the status itself (reusing
`HttpsTransportChannel.CreateServerTooBusyException`), so callers of
`WebApiClient` also get a `ServiceResultException` instead of an
`HttpRequestException` for these two statuses (G15).
- An IO error becomes `BadNotConnected`.
- **Timeouts (L12-1, G14).**
- `OperationTimeout` applies to each request. When `RequestTimeout` is
unset, HttpClient's 100 s default no longer cuts off long Publish
requests.
- The GetEndpoints call at open is bounded by `OperationTimeout`, and
cancelling the open now throws.
- **Core change:** `HttpsTransportChannel.MapRequestFailure` went from
private to internal so the WebApi channel can reuse it.
### ComplexTypes
- **Out-of-range union selector (L12-3).** A union whose SwitchField is
larger than its field count now fails with `BadDecodingError` when
decoded and `BadEncodingError` when encoded (Part 6 §5.2.8).
- **Verbose JSON unions (L12-4).** They now decode their selected field
instead of `null`.
## Not fixed / partial
- **L2-5 (skipped):** an identity provider combined with a
caller-supplied reverse connection still can't connect to an
undiscovered endpoint. Fixing it means choosing the identity after
CreateSession, a design change.
- **L4-5 (skipped):** the one-time KeyCredential token needs a fresh
token on each reactivation. Today reactivation fails and the client
falls back to a new session.
- **L4-4 (partial):** only subscriptions the backup prepared in advance
survive a takeover.
- **L3-2 (partial):** `AddNodes`/`RegisterNodes` batches are not rolled
back.
- **L2-3 (partial):** service calls still hold the session lock for
their whole round trip.
- **Known from the review, not fixed here:**
- G7: the batch cleanup request can't be cancelled.
- G11: the DI session's close at host shutdown never reaches the server,
and a closed session keeps being handed out.
- G13: a file renamed by another client is still found under its old
path.
- G25: a clone-based transfer doesn't mark the original subscriptions.
- G27b: the transfer item check matches by count, not by ID.
- **Outside this PR:** the reference server ignores `ECDHPolicyUri` on
ActivateSession (`SessionSecurityPolicyHelper`), which breaks Part 6
§6.8.2. As a result, the L1-4 two-step ECC switch ends in
`BadSecurityPolicyRejected` against our own server.
## Testing
All suites on net10.0, on the branch before the master merge. Every
suite had 0 failures:
| Suite | Passed | Skipped |
|---|---|---|
| Opc.Ua.Client.Tests | 2698 | 0 |
| Opc.Ua.Redundancy.Client.Tests | 134 | 0 |
| Opc.Ua.Subscriptions.Classic.Tests | 57 | 0 |
| Opc.Ua.Bindings.Https.WebApi.Tests | 385 | 0 |
| Opc.Ua.Sessions.Tests | 782 | 379 |
| Opc.Ua.Subscriptions.Tests | 640 | 6 |
| Opc.Ua.Client.ComplexTypes.Tests | 2858 | 0 |
After merging current master (net10.0), every suite had 0 failures
except one, a flaky new test fixed in 9f52952b2:
| Suite | Passed | Skipped | Failed |
|---|---|---|---|
| Opc.Ua.Client.Tests | 2719 | 0 | 1 (the flaky test) |
| Opc.Ua.Redundancy.Client.Tests | 134 | 0 | 0 |
| Opc.Ua.Client.ComplexTypes.Tests | 2858 | 0 | 0 |
| Opc.Ua.Subscriptions.Classic.Tests | 57 | 0 | 0 |
| Opc.Ua.Bindings.Https.WebApi.Tests | 397 | 0 | 0 |
| Opc.Ua.Sessions.Tests | 790 | 379 | 0 |
| Opc.Ua.Subscriptions.Tests | 640 | 6 | 0 |
The touched test projects also build on net48 with 0 warnings.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: marcschier <11168470+marcschier@users.noreply.github.com>
Co-authored-by: Marc Schier <marcschier@users.noreply.github.com>
854 lines
33 KiB
C#
854 lines
33 KiB
C#
/* ========================================================================
|
|
* Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved.
|
|
*
|
|
* OPC Foundation MIT License 1.00
|
|
*
|
|
* Permission is hereby granted, free of charge, to any person
|
|
* obtaining a copy of this software and associated documentation
|
|
* files (the "Software"), to deal in the Software without
|
|
* restriction, including without limitation the rights to use,
|
|
* copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
* copies of the Software, and to permit persons to whom the
|
|
* Software is furnished to do so, subject to the following
|
|
* conditions:
|
|
*
|
|
* The above copyright notice and this permission notice shall be
|
|
* included in all copies or substantial portions of the Software.
|
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
|
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
|
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
|
* OTHER DEALINGS IN THE SOFTWARE.
|
|
*
|
|
* The complete license agreement can be found here:
|
|
* http://opcfoundation.org/License/MIT/1.00/
|
|
* ======================================================================*/
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Runtime.CompilerServices;
|
|
using System.Threading;
|
|
using System.Threading.Channels;
|
|
using System.Threading.Tasks;
|
|
using Moq;
|
|
using NUnit.Framework;
|
|
using Opc.Ua.Client.ModelChange;
|
|
using Opc.Ua.Client.Subscriptions;
|
|
using Opc.Ua.Client.Subscriptions.MonitoredItems;
|
|
using Opc.Ua.Client.Subscriptions.Streaming;
|
|
using MonitoringOptions = Opc.Ua.Client.Subscriptions.MonitoredItems.MonitoredItemOptions;
|
|
|
|
// Tests run on the default TaskScheduler so CA2007's sync-context
|
|
// risk does not apply. The local FakeStreamingSubscription is a
|
|
// no-op IAsyncDisposable fake with nothing to dispose; CA2000's leak
|
|
// warning does not apply.
|
|
#pragma warning disable CA2007, CA2000
|
|
|
|
namespace Opc.Ua.Client.Tests.ModelChange
|
|
{
|
|
/// <summary>
|
|
/// Unit tests for <see cref="ModelChangeTracker"/>. Drives the
|
|
/// tracker through a fake <see cref="IStreamingSubscription"/>
|
|
/// that pushes <see cref="EventNotification"/>s on demand and
|
|
/// uses a <see cref="Mock{INodeCache}"/> to observe cache
|
|
/// invalidation calls.
|
|
/// </summary>
|
|
[TestFixture]
|
|
[Category("Client")]
|
|
[Category("ModelChange")]
|
|
[Parallelizable]
|
|
public sealed class ModelChangeTrackerTests
|
|
{
|
|
[Test]
|
|
public void ConstructorWithNullStreamingThrowsArgumentNullException()
|
|
{
|
|
Assert.That(
|
|
() => new ModelChangeTracker(null!),
|
|
Throws.ArgumentNullException);
|
|
}
|
|
|
|
[Test]
|
|
public async Task IsTrackingIsFalseBeforeStartAsync()
|
|
{
|
|
var fake = new FakeStreamingSubscription();
|
|
await using var tracker = new ModelChangeTracker(fake);
|
|
|
|
Assert.That(tracker.IsTracking, Is.False);
|
|
}
|
|
|
|
[Test]
|
|
public async Task IsTrackingIsTrueAfterStartAsync()
|
|
{
|
|
var fake = new FakeStreamingSubscription();
|
|
await using var tracker = new ModelChangeTracker(fake);
|
|
|
|
await tracker.StartTrackingAsync().ConfigureAwait(false);
|
|
|
|
Assert.That(tracker.IsTracking, Is.True);
|
|
}
|
|
|
|
[Test]
|
|
public async Task StartTrackingAsyncWaitsUntilEventMonitoredItemIsCreated()
|
|
{
|
|
var fake = new FakeStreamingSubscription(eventMonitoredItemCreated: false);
|
|
await using var tracker = new ModelChangeTracker(fake);
|
|
|
|
int raised = 0;
|
|
tracker.ModelChanged += (_, _) => Interlocked.Increment(ref raised);
|
|
|
|
Task startTask = tracker.StartTrackingAsync().AsTask();
|
|
await fake.WaitForSubscribeAsync().ConfigureAwait(false);
|
|
await Task.Delay(50).ConfigureAwait(false);
|
|
|
|
Assert.That(startTask.IsCompleted, Is.False);
|
|
|
|
fake.CreateEventMonitoredItem();
|
|
await startTask.ConfigureAwait(false);
|
|
|
|
fake.Push(new EventNotification(
|
|
null,
|
|
ArrayOf.Wrapped(default, default, Variant.From("ready"))));
|
|
await fake.QuiesceAsync().ConfigureAwait(false);
|
|
|
|
Assert.That(raised, Is.EqualTo(1));
|
|
}
|
|
|
|
/// <summary>
|
|
/// L9-11: the first caller's cancelled start tore down the pump that a
|
|
/// second, uncancelled caller had joined, failing that caller too.
|
|
/// </summary>
|
|
[Test]
|
|
public async Task CancelledFirstStartDoesNotFailAJoinedStartAsync()
|
|
{
|
|
var fake = new FakeStreamingSubscription(eventMonitoredItemCreated: false);
|
|
await using var tracker = new ModelChangeTracker(fake);
|
|
|
|
using var firstCts = new CancellationTokenSource();
|
|
Task first = tracker.StartTrackingAsync(firstCts.Token).AsTask();
|
|
await fake.WaitForSubscribeAsync().ConfigureAwait(false);
|
|
Task second = tracker.StartTrackingAsync().AsTask();
|
|
|
|
firstCts.Cancel();
|
|
Assert.That(
|
|
async () => await first.ConfigureAwait(false),
|
|
Throws.InstanceOf<OperationCanceledException>());
|
|
|
|
fake.CreateEventMonitoredItem();
|
|
await second.WaitAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false);
|
|
|
|
Assert.That(tracker.IsTracking, Is.True);
|
|
Assert.That(fake.SubscribeCallCount, Is.EqualTo(1));
|
|
}
|
|
|
|
/// <summary>
|
|
/// A start abandoned by its only waiter still stops the pump.
|
|
/// </summary>
|
|
[Test]
|
|
public async Task CancelledOnlyStartStopsTrackingAsync()
|
|
{
|
|
var fake = new FakeStreamingSubscription(eventMonitoredItemCreated: false);
|
|
await using var tracker = new ModelChangeTracker(fake);
|
|
|
|
using var cts = new CancellationTokenSource();
|
|
Task start = tracker.StartTrackingAsync(cts.Token).AsTask();
|
|
await fake.WaitForSubscribeAsync().ConfigureAwait(false);
|
|
|
|
cts.Cancel();
|
|
Assert.That(
|
|
async () => await start.ConfigureAwait(false),
|
|
Throws.InstanceOf<OperationCanceledException>());
|
|
Assert.That(tracker.IsTracking, Is.False);
|
|
}
|
|
|
|
[Test]
|
|
public async Task StartTrackingAsyncIsIdempotent()
|
|
{
|
|
var fake = new FakeStreamingSubscription();
|
|
await using var tracker = new ModelChangeTracker(fake);
|
|
|
|
await tracker.StartTrackingAsync().ConfigureAwait(false);
|
|
await fake.WaitForSubscribeAsync().ConfigureAwait(false);
|
|
await tracker.StartTrackingAsync().ConfigureAwait(false);
|
|
|
|
Assert.That(tracker.IsTracking, Is.True);
|
|
|
|
// The pump task is started exactly once — a second
|
|
// call must not subscribe again.
|
|
Assert.That(fake.SubscribeCallCount, Is.EqualTo(1));
|
|
}
|
|
|
|
[Test]
|
|
public async Task StopTrackingAsyncCompletesPumpTaskAndFlipsIsTrackingToFalse()
|
|
{
|
|
var fake = new FakeStreamingSubscription();
|
|
await using var tracker = new ModelChangeTracker(fake);
|
|
|
|
await tracker.StartTrackingAsync().ConfigureAwait(false);
|
|
await fake.WaitForSubscribeAsync().ConfigureAwait(false);
|
|
await tracker.StopTrackingAsync().ConfigureAwait(false);
|
|
|
|
Assert.That(tracker.IsTracking, Is.False);
|
|
Assert.That(fake.PumpCancellationObserved, Is.True);
|
|
}
|
|
|
|
[Test]
|
|
public async Task DisposeAsyncIsIdempotent()
|
|
{
|
|
var fake = new FakeStreamingSubscription();
|
|
var tracker = new ModelChangeTracker(fake);
|
|
await tracker.StartTrackingAsync().ConfigureAwait(false);
|
|
|
|
await tracker.DisposeAsync().ConfigureAwait(false);
|
|
// Second dispose must be a no-op (does not throw).
|
|
await tracker.DisposeAsync().ConfigureAwait(false);
|
|
|
|
Assert.That(tracker.IsTracking, Is.False);
|
|
}
|
|
|
|
[Test]
|
|
public async Task DisposeAsyncCallsStopTracking()
|
|
{
|
|
var fake = new FakeStreamingSubscription();
|
|
var tracker = new ModelChangeTracker(fake);
|
|
await tracker.StartTrackingAsync().ConfigureAwait(false);
|
|
await fake.WaitForSubscribeAsync().ConfigureAwait(false);
|
|
|
|
await tracker.DisposeAsync().ConfigureAwait(false);
|
|
|
|
Assert.That(tracker.IsTracking, Is.False);
|
|
Assert.That(fake.PumpCancellationObserved, Is.True);
|
|
}
|
|
|
|
[Test]
|
|
public async Task NotificationWithFewerThanThreeFieldsDoesNotRaiseModelChanged()
|
|
{
|
|
var fake = new FakeStreamingSubscription();
|
|
var cache = new Mock<INodeCache>(MockBehavior.Strict);
|
|
await using var tracker = new ModelChangeTracker(fake, cache.Object);
|
|
|
|
int raised = 0;
|
|
tracker.ModelChanged += (_, _) => Interlocked.Increment(ref raised);
|
|
|
|
await tracker.StartTrackingAsync().ConfigureAwait(false);
|
|
await fake.WaitForSubscribeAsync().ConfigureAwait(false);
|
|
|
|
// Fields.Count < 3 — fast-path return, no event, no cache call.
|
|
fake.Push(new EventNotification(
|
|
null, ArrayOf.Wrapped<Variant>(default, default)));
|
|
|
|
await fake.QuiesceAsync().ConfigureAwait(false);
|
|
|
|
Assert.That(raised, Is.Zero);
|
|
cache.VerifyNoOtherCalls();
|
|
}
|
|
|
|
[Test]
|
|
public async Task NotificationWithMalformedFieldsTriggersFullCacheInvalidation()
|
|
{
|
|
var fake = new FakeStreamingSubscription();
|
|
var cache = new Mock<INodeCache>(MockBehavior.Loose);
|
|
await using var tracker = new ModelChangeTracker(fake, cache.Object);
|
|
|
|
ModelChangedEventArgs? observed = null;
|
|
tracker.ModelChanged += (_, e) => observed = e;
|
|
|
|
await tracker.StartTrackingAsync().ConfigureAwait(false);
|
|
await fake.WaitForSubscribeAsync().ConfigureAwait(false);
|
|
|
|
// fields[2] is a scalar string — definitively NOT an
|
|
// ExtensionObject[] of ModelChangeStructureDataType, so the
|
|
// tracker must fall back to full cache invalidation.
|
|
fake.Push(new EventNotification(
|
|
null,
|
|
ArrayOf.Wrapped(
|
|
default,
|
|
default,
|
|
Variant.From("not-an-extension-object-array"))));
|
|
|
|
await fake.QuiesceAsync().ConfigureAwait(false);
|
|
|
|
cache.Verify(c => c.Clear(), Times.Once);
|
|
cache.Verify(c => c.InvalidateNode(It.IsAny<NodeId>()), Times.Never);
|
|
|
|
Assert.That(observed, Is.Not.Null);
|
|
Assert.That(observed!.RequiresFullCacheInvalidation, Is.True);
|
|
Assert.That(observed.Changes, Is.Empty);
|
|
}
|
|
|
|
[Test]
|
|
public async Task NotificationWithNullChangesFieldTriggersFullCacheInvalidation()
|
|
{
|
|
// changesVariant.IsNull -> boxed is null -> still NOT
|
|
// ExtensionObject[] -> full invalidation path.
|
|
var fake = new FakeStreamingSubscription();
|
|
var cache = new Mock<INodeCache>(MockBehavior.Loose);
|
|
await using var tracker = new ModelChangeTracker(fake, cache.Object);
|
|
|
|
ModelChangedEventArgs? observed = null;
|
|
tracker.ModelChanged += (_, e) => observed = e;
|
|
|
|
await tracker.StartTrackingAsync().ConfigureAwait(false);
|
|
await fake.WaitForSubscribeAsync().ConfigureAwait(false);
|
|
|
|
fake.Push(new EventNotification(
|
|
null,
|
|
ArrayOf.Wrapped<Variant>(default, default, default)));
|
|
|
|
await fake.QuiesceAsync().ConfigureAwait(false);
|
|
|
|
cache.Verify(c => c.Clear(), Times.Once);
|
|
Assert.That(observed, Is.Not.Null);
|
|
Assert.That(observed!.RequiresFullCacheInvalidation, Is.True);
|
|
}
|
|
|
|
[Test]
|
|
public async Task CacheInvalidationExceptionsAreLoggedButDoNotStopTracking()
|
|
{
|
|
var fake = new FakeStreamingSubscription();
|
|
var cache = new Mock<INodeCache>();
|
|
cache.Setup(c => c.Clear())
|
|
.Throws(new InvalidOperationException("boom"));
|
|
|
|
await using var tracker = new ModelChangeTracker(fake, cache.Object);
|
|
|
|
int raised = 0;
|
|
tracker.ModelChanged += (_, _) => Interlocked.Increment(ref raised);
|
|
|
|
await tracker.StartTrackingAsync().ConfigureAwait(false);
|
|
await fake.WaitForSubscribeAsync().ConfigureAwait(false);
|
|
|
|
// First malformed notification — Clear() throws, must be swallowed,
|
|
// ModelChanged must still fire.
|
|
fake.Push(new EventNotification(
|
|
null,
|
|
ArrayOf.Wrapped(
|
|
default, default, Variant.From("garbage"))));
|
|
await fake.QuiesceAsync().ConfigureAwait(false);
|
|
|
|
// Second notification — pump must still be alive.
|
|
fake.Push(new EventNotification(
|
|
null,
|
|
ArrayOf.Wrapped(
|
|
default, default, Variant.From("garbage-2"))));
|
|
await fake.QuiesceAsync().ConfigureAwait(false);
|
|
|
|
Assert.That(raised, Is.EqualTo(2));
|
|
Assert.That(tracker.IsTracking, Is.True);
|
|
}
|
|
|
|
[Test]
|
|
public async Task SubscriberHandlerExceptionsAreSwallowed()
|
|
{
|
|
var fake = new FakeStreamingSubscription();
|
|
await using var tracker = new ModelChangeTracker(fake);
|
|
|
|
int raised = 0;
|
|
tracker.ModelChanged += (_, _) =>
|
|
{
|
|
Interlocked.Increment(ref raised);
|
|
throw new InvalidOperationException("subscriber failure");
|
|
};
|
|
|
|
await tracker.StartTrackingAsync().ConfigureAwait(false);
|
|
await fake.WaitForSubscribeAsync().ConfigureAwait(false);
|
|
|
|
fake.Push(new EventNotification(
|
|
null,
|
|
ArrayOf.Wrapped(
|
|
default, default, Variant.From("garbage-1"))));
|
|
await fake.QuiesceAsync().ConfigureAwait(false);
|
|
|
|
// Pump still alive — a second notification is delivered.
|
|
fake.Push(new EventNotification(
|
|
null,
|
|
ArrayOf.Wrapped(
|
|
default, default, Variant.From("garbage-2"))));
|
|
await fake.QuiesceAsync().ConfigureAwait(false);
|
|
|
|
Assert.That(raised, Is.EqualTo(2));
|
|
Assert.That(tracker.IsTracking, Is.True);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Regression for #4100. A server that appends a namespace uri
|
|
/// while running reports the change as a
|
|
/// <c>BaseModelChangeEvent</c> — no per-node detail — so the
|
|
/// tracker must re-read the namespace table.
|
|
/// </summary>
|
|
[Test]
|
|
public async Task UnqualifiedModelChangeRefreshesNamespaceTable()
|
|
{
|
|
var fake = new FakeStreamingSubscription();
|
|
var namespaces = new FakeNamespaceTableRefresher();
|
|
await using var tracker = new ModelChangeTracker(
|
|
fake, nodeCache: null, logger: null, namespaceTables: namespaces);
|
|
|
|
ModelChangedEventArgs? observed = null;
|
|
tracker.ModelChanged += (_, e) => observed = e;
|
|
|
|
await tracker.StartTrackingAsync().ConfigureAwait(false);
|
|
await fake.WaitForSubscribeAsync().ConfigureAwait(false);
|
|
|
|
namespaces.OnRefresh = table => table.Append("urn:live:model");
|
|
|
|
fake.Push(new EventNotification(
|
|
null, ArrayOf.Wrapped<Variant>(default, default, default)));
|
|
await fake.QuiesceAsync().ConfigureAwait(false);
|
|
|
|
Assert.That(namespaces.RefreshCount, Is.EqualTo(1));
|
|
Assert.That(observed, Is.Not.Null);
|
|
Assert.That(observed!.NamespaceTableRefreshed, Is.True);
|
|
Assert.That(namespaces.NamespaceUris.GetIndex("urn:live:model"),
|
|
Is.EqualTo(1));
|
|
}
|
|
|
|
[Test]
|
|
public async Task ResolvableModelChangeDoesNotRefreshNamespaceTable()
|
|
{
|
|
var fake = new FakeStreamingSubscription();
|
|
var namespaces = new FakeNamespaceTableRefresher("urn:one");
|
|
await using var tracker = new ModelChangeTracker(
|
|
fake, nodeCache: null, logger: null, namespaceTables: namespaces);
|
|
|
|
ModelChangedEventArgs? observed = null;
|
|
tracker.ModelChanged += (_, e) => observed = e;
|
|
|
|
await tracker.StartTrackingAsync().ConfigureAwait(false);
|
|
await fake.WaitForSubscribeAsync().ConfigureAwait(false);
|
|
|
|
fake.Push(CreateGeneralModelChangeNotification(
|
|
new NodeId(42u, 1), ObjectTypeIds.BaseObjectType));
|
|
await fake.QuiesceAsync().ConfigureAwait(false);
|
|
|
|
Assert.That(namespaces.RefreshCount, Is.Zero);
|
|
Assert.That(observed, Is.Not.Null);
|
|
Assert.That(observed!.NamespaceTableRefreshed, Is.False);
|
|
Assert.That(observed.Changes, Has.Count.EqualTo(1));
|
|
Assert.That(observed.Changes[0].AffectedNode,
|
|
Is.EqualTo(new NodeId(42u, 1)));
|
|
}
|
|
|
|
[Test]
|
|
public async Task ChangeAffectingServerNamespaceArrayRefreshesNamespaceTable()
|
|
{
|
|
var fake = new FakeStreamingSubscription();
|
|
var namespaces = new FakeNamespaceTableRefresher();
|
|
await using var tracker = new ModelChangeTracker(
|
|
fake, nodeCache: null, logger: null, namespaceTables: namespaces);
|
|
|
|
ModelChangedEventArgs? observed = null;
|
|
tracker.ModelChanged += (_, e) => observed = e;
|
|
|
|
await tracker.StartTrackingAsync().ConfigureAwait(false);
|
|
await fake.WaitForSubscribeAsync().ConfigureAwait(false);
|
|
|
|
fake.Push(CreateGeneralModelChangeNotification(
|
|
VariableIds.Server_NamespaceArray, NodeId.Null));
|
|
await fake.QuiesceAsync().ConfigureAwait(false);
|
|
|
|
Assert.That(namespaces.RefreshCount, Is.EqualTo(1));
|
|
Assert.That(observed, Is.Not.Null);
|
|
Assert.That(observed!.NamespaceTableRefreshed, Is.True);
|
|
}
|
|
|
|
[Test]
|
|
public async Task ChangeWithUnknownNamespaceIndexRefreshesNamespaceTable()
|
|
{
|
|
var fake = new FakeStreamingSubscription();
|
|
var namespaces = new FakeNamespaceTableRefresher();
|
|
await using var tracker = new ModelChangeTracker(
|
|
fake, nodeCache: null, logger: null, namespaceTables: namespaces);
|
|
|
|
ModelChangedEventArgs? observed = null;
|
|
tracker.ModelChanged += (_, e) => observed = e;
|
|
|
|
await tracker.StartTrackingAsync().ConfigureAwait(false);
|
|
await fake.WaitForSubscribeAsync().ConfigureAwait(false);
|
|
|
|
// Namespace index 3 is beyond the single known uri, so the
|
|
// client provably cannot resolve the affected node.
|
|
fake.Push(CreateGeneralModelChangeNotification(
|
|
new NodeId(42u, 3), NodeId.Null));
|
|
await fake.QuiesceAsync().ConfigureAwait(false);
|
|
|
|
Assert.That(namespaces.RefreshCount, Is.EqualTo(1));
|
|
Assert.That(observed, Is.Not.Null);
|
|
Assert.That(observed!.NamespaceTableRefreshed, Is.True);
|
|
}
|
|
|
|
[Test]
|
|
public async Task ChangeWithUnknownTypeDefinitionNamespaceRefreshesNamespaceTable()
|
|
{
|
|
var fake = new FakeStreamingSubscription();
|
|
var namespaces = new FakeNamespaceTableRefresher();
|
|
await using var tracker = new ModelChangeTracker(
|
|
fake, nodeCache: null, logger: null, namespaceTables: namespaces);
|
|
|
|
await tracker.StartTrackingAsync().ConfigureAwait(false);
|
|
await fake.WaitForSubscribeAsync().ConfigureAwait(false);
|
|
|
|
fake.Push(CreateGeneralModelChangeNotification(
|
|
new NodeId(42u), new NodeId(99u, 2)));
|
|
await fake.QuiesceAsync().ConfigureAwait(false);
|
|
|
|
Assert.That(namespaces.RefreshCount, Is.EqualTo(1));
|
|
}
|
|
|
|
[Test]
|
|
public async Task NamespaceTableIsRefreshedBeforeTheNodeCacheIsInvalidated()
|
|
{
|
|
var fake = new FakeStreamingSubscription();
|
|
var namespaces = new FakeNamespaceTableRefresher();
|
|
var order = new List<string>();
|
|
var cache = new Mock<INodeCache>(MockBehavior.Loose);
|
|
cache.Setup(c => c.Clear()).Callback(() => order.Add("clear"));
|
|
namespaces.OnRefresh = _ => order.Add("refresh");
|
|
|
|
await using var tracker = new ModelChangeTracker(
|
|
fake, cache.Object, logger: null, namespaceTables: namespaces);
|
|
|
|
tracker.ModelChanged += (_, _) => order.Add("event");
|
|
|
|
await tracker.StartTrackingAsync().ConfigureAwait(false);
|
|
await fake.WaitForSubscribeAsync().ConfigureAwait(false);
|
|
|
|
fake.Push(new EventNotification(
|
|
null, ArrayOf.Wrapped<Variant>(default, default, default)));
|
|
await fake.QuiesceAsync().ConfigureAwait(false);
|
|
|
|
Assert.That(order, Is.EqualTo(s_refreshBeforeInvalidateOrder));
|
|
}
|
|
|
|
[Test]
|
|
public async Task NamespaceTableRefreshFailureIsSwallowedAndTrackingContinues()
|
|
{
|
|
var fake = new FakeStreamingSubscription();
|
|
var namespaces = new FakeNamespaceTableRefresher
|
|
{
|
|
OnRefresh = _ => throw new ServiceResultException(
|
|
StatusCodes.BadNotConnected)
|
|
};
|
|
await using var tracker = new ModelChangeTracker(
|
|
fake, nodeCache: null, logger: null, namespaceTables: namespaces);
|
|
|
|
var observed = new List<ModelChangedEventArgs>();
|
|
tracker.ModelChanged += (_, e) => observed.Add(e);
|
|
|
|
await tracker.StartTrackingAsync().ConfigureAwait(false);
|
|
await fake.WaitForSubscribeAsync().ConfigureAwait(false);
|
|
|
|
fake.Push(new EventNotification(
|
|
null, ArrayOf.Wrapped<Variant>(default, default, default)));
|
|
await fake.QuiesceAsync().ConfigureAwait(false);
|
|
|
|
// Pump must still be alive for the next notification.
|
|
fake.Push(new EventNotification(
|
|
null, ArrayOf.Wrapped<Variant>(default, default, default)));
|
|
await fake.QuiesceAsync().ConfigureAwait(false);
|
|
|
|
Assert.That(namespaces.RefreshCount, Is.EqualTo(2));
|
|
Assert.That(observed, Has.Count.EqualTo(2));
|
|
Assert.That(observed[0].NamespaceTableRefreshed, Is.False);
|
|
Assert.That(tracker.IsTracking, Is.True);
|
|
}
|
|
|
|
[Test]
|
|
public async Task WithoutANamespaceTableRefresherNoRefreshIsAttempted()
|
|
{
|
|
var fake = new FakeStreamingSubscription();
|
|
var cache = new Mock<INodeCache>(MockBehavior.Loose);
|
|
await using var tracker = new ModelChangeTracker(fake, cache.Object);
|
|
|
|
ModelChangedEventArgs? observed = null;
|
|
tracker.ModelChanged += (_, e) => observed = e;
|
|
|
|
await tracker.StartTrackingAsync().ConfigureAwait(false);
|
|
await fake.WaitForSubscribeAsync().ConfigureAwait(false);
|
|
|
|
fake.Push(new EventNotification(
|
|
null, ArrayOf.Wrapped<Variant>(default, default, default)));
|
|
await fake.QuiesceAsync().ConfigureAwait(false);
|
|
|
|
cache.Verify(c => c.Clear(), Times.Once);
|
|
Assert.That(observed, Is.Not.Null);
|
|
Assert.That(observed!.NamespaceTableRefreshed, Is.False);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Expected call order when a model change triggers both a
|
|
/// namespace refresh and a full cache invalidation.
|
|
/// </summary>
|
|
private static readonly string[] s_refreshBeforeInvalidateOrder =
|
|
["refresh", "clear", "event"];
|
|
|
|
/// <summary>
|
|
/// Builds a <c>GeneralModelChangeEvent</c> shaped notification
|
|
/// carrying a single change entry.
|
|
/// </summary>
|
|
private static EventNotification CreateGeneralModelChangeNotification(
|
|
NodeId affected,
|
|
NodeId affectedType)
|
|
{
|
|
var change = new ModelChangeStructureDataType
|
|
{
|
|
Affected = affected,
|
|
AffectedType = affectedType,
|
|
Verb = (byte)ModelChangeVerb.NodeAdded
|
|
};
|
|
ArrayOf<ExtensionObject> changes = new ExtensionObject[]
|
|
{
|
|
new(change)
|
|
};
|
|
return new EventNotification(
|
|
null,
|
|
ArrayOf.Wrapped(default, default, Variant.From(changes)));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Hand-rolled fake for <see cref="INamespaceTableRefresher"/>.
|
|
/// Counts refresh calls and lets a test mutate the table (or
|
|
/// throw) from inside the refresh.
|
|
/// </summary>
|
|
private sealed class FakeNamespaceTableRefresher : INamespaceTableRefresher
|
|
{
|
|
public FakeNamespaceTableRefresher(params string[] additionalNamespaceUris)
|
|
{
|
|
NamespaceUris = new NamespaceTable(
|
|
new[] { Namespaces.OpcUa }.Concat(additionalNamespaceUris));
|
|
}
|
|
|
|
public NamespaceTable NamespaceUris { get; }
|
|
|
|
public int RefreshCount => Volatile.Read(ref m_refreshCount);
|
|
|
|
/// <summary>
|
|
/// Invoked on every refresh so a test can simulate the
|
|
/// server side table growing, or a failure.
|
|
/// </summary>
|
|
public Action<NamespaceTable>? OnRefresh { get; set; }
|
|
|
|
public Task FetchNamespaceTablesAsync(CancellationToken ct = default)
|
|
{
|
|
Interlocked.Increment(ref m_refreshCount);
|
|
OnRefresh?.Invoke(NamespaceUris);
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
private int m_refreshCount;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Fake streaming subscription that exposes a deterministic
|
|
/// <see cref="EventNotification"/> channel for tests. Each call
|
|
/// to <see cref="SubscribeEventsAsync"/> increments
|
|
/// <see cref="SubscribeCallCount"/>, signals
|
|
/// <see cref="WaitForSubscribeAsync"/>, and then yields every
|
|
/// notification pushed via <see cref="Push"/>. The enumerator
|
|
/// completes when <see cref="Complete"/> is called or the
|
|
/// supplied cancellation token fires.
|
|
/// </summary>
|
|
private sealed class FakeStreamingSubscription :
|
|
IStreamingSubscription,
|
|
IStreamingSubscriptionReadiness
|
|
{
|
|
private readonly Channel<EventNotification> m_channel =
|
|
Channel.CreateUnbounded<EventNotification>(
|
|
new UnboundedChannelOptions
|
|
{
|
|
SingleReader = true,
|
|
SingleWriter = false
|
|
});
|
|
|
|
private readonly TaskCompletionSource<bool> m_subscribed =
|
|
new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
|
|
private readonly FakeMonitoredItem m_eventMonitoredItem;
|
|
private int m_subscribeCallCount;
|
|
private int m_pumpCancellationObserved;
|
|
private int m_pushed;
|
|
private int m_handled;
|
|
|
|
public FakeStreamingSubscription(bool eventMonitoredItemCreated = true)
|
|
{
|
|
m_eventMonitoredItem = new FakeMonitoredItem(eventMonitoredItemCreated);
|
|
}
|
|
|
|
public int SubscribeCallCount => m_subscribeCallCount;
|
|
|
|
public bool PumpCancellationObserved =>
|
|
Volatile.Read(ref m_pumpCancellationObserved) != 0;
|
|
|
|
public void CreateEventMonitoredItem()
|
|
{
|
|
m_eventMonitoredItem.Create();
|
|
}
|
|
|
|
public void Push(EventNotification notification)
|
|
{
|
|
Interlocked.Increment(ref m_pushed);
|
|
m_channel.Writer.TryWrite(notification);
|
|
}
|
|
|
|
public void Complete()
|
|
{
|
|
m_channel.Writer.TryComplete();
|
|
}
|
|
|
|
public Task<bool> WaitForSubscribeAsync()
|
|
{
|
|
return m_subscribed.Task;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Spins briefly until every <see cref="Push"/>ed notification
|
|
/// has been observed by the production-code consumer. The
|
|
/// counter is incremented in the iterator <i>after</i> the
|
|
/// <c>yield return</c>, i.e. once the consumer's
|
|
/// <c>HandleNotification</c> call has returned and the
|
|
/// foreach loop has requested the next item.
|
|
/// </summary>
|
|
public async Task QuiesceAsync()
|
|
{
|
|
for (int i = 0; i < 400; i++)
|
|
{
|
|
if (Volatile.Read(ref m_handled) >= Volatile.Read(ref m_pushed))
|
|
{
|
|
return;
|
|
}
|
|
await Task.Delay(5).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
public IAsyncEnumerable<EventNotification> SubscribeEventsAsync(
|
|
NodeId notifierId,
|
|
EventFilter filter,
|
|
MonitoringOptions? options,
|
|
Func<IMonitoredItem, CancellationToken, ValueTask> onMonitoredItemReady,
|
|
CancellationToken ct = default)
|
|
{
|
|
return SubscribeEventsCoreAsync(onMonitoredItemReady, ct);
|
|
}
|
|
|
|
public async IAsyncEnumerable<EventNotification> SubscribeEventsAsync(
|
|
NodeId notifierId,
|
|
EventFilter filter,
|
|
MonitoringOptions? options = null,
|
|
[EnumeratorCancellation] CancellationToken ct = default)
|
|
{
|
|
await foreach (EventNotification notification in SubscribeEventsCoreAsync(null, ct)
|
|
.ConfigureAwait(false))
|
|
{
|
|
yield return notification;
|
|
}
|
|
}
|
|
|
|
private async IAsyncEnumerable<EventNotification> SubscribeEventsCoreAsync(
|
|
Func<IMonitoredItem, CancellationToken, ValueTask>? onMonitoredItemReady,
|
|
[EnumeratorCancellation] CancellationToken ct = default)
|
|
{
|
|
Interlocked.Increment(ref m_subscribeCallCount);
|
|
m_subscribed.TrySetResult(true);
|
|
if (onMonitoredItemReady != null)
|
|
{
|
|
await onMonitoredItemReady(m_eventMonitoredItem, ct).ConfigureAwait(false);
|
|
}
|
|
|
|
try
|
|
{
|
|
await foreach (EventNotification n in m_channel.Reader
|
|
.ReadAllAsync(ct).ConfigureAwait(false))
|
|
{
|
|
yield return n;
|
|
// Reached only after the consumer's
|
|
// HandleNotification returned and asked for the
|
|
// next item, so we can declare this push handled.
|
|
Interlocked.Increment(ref m_handled);
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
if (ct.IsCancellationRequested)
|
|
{
|
|
Interlocked.Exchange(ref m_pumpCancellationObserved, 1);
|
|
}
|
|
}
|
|
}
|
|
|
|
public async IAsyncEnumerable<DataValueChange> SubscribeDataChangesAsync(
|
|
NodeId nodeId,
|
|
MonitoringOptions? options = null,
|
|
[EnumeratorCancellation] CancellationToken ct = default)
|
|
{
|
|
await Task.Yield();
|
|
yield break;
|
|
}
|
|
|
|
public async IAsyncEnumerable<DataValueChange> SubscribeDataChangesAsync(
|
|
IReadOnlyList<NodeId> nodeIds,
|
|
MonitoringOptions? options = null,
|
|
[EnumeratorCancellation] CancellationToken ct = default)
|
|
{
|
|
await Task.Yield();
|
|
yield break;
|
|
}
|
|
|
|
public ValueTask DisposeAsync()
|
|
{
|
|
Complete();
|
|
return default;
|
|
}
|
|
}
|
|
|
|
private sealed class FakeMonitoredItem : IMonitoredItem, IMonitoredItemApplyState
|
|
{
|
|
private int m_created;
|
|
|
|
public FakeMonitoredItem(bool created)
|
|
{
|
|
m_created = created ? 1 : 0;
|
|
Error = ServiceResult.Good;
|
|
}
|
|
|
|
public string Name => "fake_event";
|
|
|
|
public uint Order => 0;
|
|
|
|
public uint ServerId => Created ? 1u : 0u;
|
|
|
|
public bool Created => Volatile.Read(ref m_created) != 0;
|
|
|
|
public ServiceResult Error { get; }
|
|
|
|
public bool HasPendingChanges => !Created && ServiceResult.IsGood(Error);
|
|
|
|
public MonitoringFilterResult? FilterResult => null;
|
|
|
|
public MonitoringMode CurrentMonitoringMode => MonitoringMode.Reporting;
|
|
|
|
public TimeSpan CurrentSamplingInterval => TimeSpan.Zero;
|
|
|
|
public uint CurrentQueueSize => 0;
|
|
|
|
public uint ClientHandle => 1;
|
|
|
|
public IEnumerable<IMonitoredItem> TriggeringItems => Array.Empty<IMonitoredItem>();
|
|
|
|
public IEnumerable<IMonitoredItem> TriggeredItems => Array.Empty<IMonitoredItem>();
|
|
|
|
public void Create()
|
|
{
|
|
Interlocked.Exchange(ref m_created, 1);
|
|
}
|
|
|
|
public ValueTask ConditionRefreshAsync(CancellationToken ct = default)
|
|
{
|
|
return default;
|
|
}
|
|
}
|
|
}
|
|
}
|