mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-21 17:16:16 +08:00
46fa7d364a
# Description Bound managed-session recovery, preserve Publish workers and recovery ownership, and address the client, server, transport, and certificate audit findings and subsequent concurrency review. Also reduce the memory retained by exhaustive session-test diagnostics. ## Recovery and Publish ownership - Add `ManagedSessionOptions.ChannelReconnectTimeout` through direct construction, the fluent builder, and DI. The automatic duration is `max(3 * KeepAliveInterval, revised SessionTimeout, OperationTimeout)`, sampled at cycle start. Positive overrides are supported; `Timeout.InfiniteTimeSpan` explicitly opts out. Raw sessions retain their unlimited default. - Add `CreateReconnectBudget(TimeProvider)` as a required `IReconnectParticipant` member, as agreed in review. Custom participants implement it and may return null for no participant-specific bound. - Enforce the earliest participant/caller deadline through transport reconnect, activation/recreation, and subscription restoration. Late callers can shorten an active cycle but cannot extend it. - Cancel and unwind recovery, fence late responses, and release channel recovery ownership before the existing `Faulted` event hands control to the outer reconnect/failover policy. Preserve session recreate admission through final Publish cleanup and keepalive suppression until shared recovery is complete. - Treat participant budget creation/evaluation failures, including exceptions at the exact deadline, as terminal shared-recovery failures. Notify participants before exposing `Faulted`, preserve the original diagnostic, and never silently replace a finite budget with unlimited recovery. - Keep caller-supplied replacement channels, managed bindings, wrapper event subscriptions, and recovery-owner identities consistent across success, failure, and cancellation. Reject replacement during active recovery and fence retired callbacks so they cannot clear newer ownership or suppress later keepalive recovery. - Retain eligible Publish workers through temporary subscription-identifier clearing without retaining workers for never-created or removed subscriptions. Preserve cancellation, acknowledgement rollback, and drain-before-replacement ordering. - Coordinate automatic subscription updates with session recovery: cancel admitted updates, keep them paused across a failed-restoration handoff, and retry only after explicit restoration completes. This prevents competing CreateSubscription requests and updates against a retiring session, while preserving manual recreation, transfer fallback, and pending option changes. - Exercise the real ManagedSession, V2 subscription engine, and channel ready gate with scripted transports and an injected clock. Cover transfer fallback, deadline handoff, late completions, and resumed notification delivery. ## Audit and review corrections - Correct certificate/trust-list transactions, change-pump lifetimes, validation, peer revalidation, and reset/resource ownership. - Harden node admission, attribute/range/dimension validation, monitored-item sampling and lifecycle transitions, event fanout, and server shutdown. Run lifecycle readiness and compensation outside shared monitored-item admission, with stale-completion ownership checks. - Close synchronous node-manager admission before teardown and retain resources until admitted service, lifecycle, and asynchronous method work returns. Dispose the monitored-item manager outside both locks, reject late calls before they can reach it, and forward asynchronous disposal through the adapter so the master awaits the same completion. Preserve reentrant shutdown initiation, cancellation/failure unwinding, and shared cleanup-failure reporting. - Bound WSS pending-request retention using connection-local wire handles while preserving caller-visible request handles and translating Cancel targets. Safely ignore retired replies and drain admitted send/close users before resource disposal. - Clarify that the shared `ClientBase` caller-handle sequence is distinct from the non-wrapping WSS wire allocator. Existing exhaustion/reopen, late-reply, and Cancel-translation regressions verify the connection-local contract; no allocator behavior was changed by this clarification. - Preserve virtual-node validation and resolver service errors instead of converting them to cached misses. A mismatched NodeId reports `BadNodeIdInvalid`; callback type mismatches and resolver service errors keep their exact status. Per-item boundaries preserve unaffected reads, writes, history operations, method calls, browse paths, and monitored-item creation/restoration, including permission-validation paths. Caller cancellation still propagates; stored-item validation failures are logged without aborting later restores. - Correct client file/role/state-machine/streaming APIs, node-cache behavior, redundancy/failover ownership, and session configuration/identity handling. - Cancel each owned peer-discovery scope before disposing it, including when the bounded wait wins a cancellation-delivery race. Keep late results out of the endpoint cache and preserve single-flight lookup ownership. - Keep materialized alias Browse results synchronized with the live store by default, preserving explicit startup-only opt-out. Apply HistoryUpdate service results per value while retaining explicit all-or-nothing provider APIs. - Update the directly related feature documentation and add focused positive, negative, concurrency, and ownership regressions. ## Latest review-feedback corrections - Fence stale failed lease observations with a successful-confirmation generation distinct from the revocation epoch. Snapshot it before each store read, including failed-CAS revalidation, so an old failure cannot revoke or reschedule a newer lease while fresh ownership loss still revokes leadership. Preserve independent overlapping acquisitions, expiry, disposal, and late-success protections. - Isolate attributable WSS response-decoding errors to their request, including retired handles. Keep admitted socket sends connection-owned so caller timeout/cancellation cannot abort sibling requests; shutdown still cancels and drains those sends. - Restart keepalive and classic Publish replenishment after successful session reuse. Retire V2 worker demand after intentional deletion/disable without confusing that state with temporary recovery resets. - Browse virtual directories lazily across continuation pages without the 1,024-entry snapshot cap. Preserve active-page cancellation, bounded metadata retention, pushback, and exactly-once asynchronous cursor cleanup. - Apply certificate/CRL staging in last-operation order, preflight required issuer storage before writes, select actual policy-compatible RSA keys for None endpoints, frame certificate chains independently of signature OIDs, and preserve admitted validation results during rejected-writer shutdown. - Preserve base asynchronous disposal when a legacy override omits its base call; avoid double derived disposal in the adapter. Let genuinely admitted nested work finish while rejecting stale captured contexts and returning null from closed lookup APIs. - Re-park recovered monitored items if AddNodes rolls back. Give event compensation a fresh finite deadline, and preserve healthy Browse/Translate siblings at every reference/path boundary while retaining starting-node errors and caller cancellation. - Give final reconnect notifications a live, bounded shutdown-linked lifetime. Synchronize child state before parent lifecycle handlers outside the parent transition lock. - Document the accepted existing policies: direct reverse connections are single-use without a ReverseConnectManager, and multi-node stream capacity is shared rather than reserved per node. The expanded readiness controls also exposed a real generation-handoff race: an old source could finish draining after activation was deferred but before readiness tasks were collected, causing the wanted replacement to be omitted from the wait set. A deterministic test gates that exact interval; the fix keeps the replacement in the readiness wait. The original race passed 200 repetitions after the fix. A separate control now awaits both producer readiness and iterator entry under the same original deadline, rather than treating those independent signals as equivalent. Temporary logging and repetition are removed. ## CI integration contracts The History and Server CI failures exposed integration tests that still asserted the behavior intentionally changed by the audit fixes. A Windows WoT negative test raced its caller deadline against upstream retries. A subsequent Ubuntu Client failure exposed a real automatic-update versus explicit-restoration race: - History insertion collisions now verify exact per-value statuses and all persisted timestamps/values, including preservation of the existing conflicting entry. Explicit atomic-provider rollback controls remain. - Alias materialization tests wait for actual publication and verify the added node plus forward/inverse `AliasFor` references, instead of racing a startup-only snapshot expectation. Explicit refresh opt-out controls remain. - The unavailable-upstream WoT test uses an explicit finite retry policy through existing DI configuration, preserving its original four-minute guard and requiring a mapped-value service error before caller cancellation. Production retry defaults remain unchanged. - The Client fix retains the exact one-create and late-response assertions. Three deterministic real-subscription/real-manager cases cover paused creation, disposal while paused, and cancellation of an admitted create followed by explicit restoration and a pending option update. Both composed restoration-deadline cases also prove automatic updates stay blocked at the outer handoff and resume after restoration. - The merged-head net48 correction prevents lost peer-resolver cancellation and distinguishes the harness's delayed initial `Connected` event from actual outer recovery completion. A deterministic timer-order test covers both cooperative and cancellation-ignoring resolvers, cancellation before return, rejection of late cached results, and a fresh subsequent lookup. - The remaining CodeQL alert was a false content flow through `ArrayOf.Count` into an integer-only trust-list summary. Projecting the same count through `Span.Length` keeps cardinality distinct from serialized contents without allocating, dropping diagnostics, suppressing the rule, or dismissing the alert. Five log-contract cases cover null/empty/nonempty results and mixed chain-capable/fallback listeners, asserting the exact count, message, and structured properties. - Classic transfer acknowledges messages selected for asynchronous Republish only after their responses arrive. The existing locked replay-selection decision returns the immediate-acknowledgement subset to Session, preserving the public transfer API, advertised availability, and immediate acknowledgement of older gapped messages not selected for replay. A callback changing `RepublishAfterTransfer` cannot change the already-selected acknowledgement ownership. - Transfer integration tests explicitly control acknowledged versus retained origin messages. Exact assertions distinguish retained replay from requested fresh initial values by sequence number, client handles, values, status, and source timestamp. Atomic counters, observed delivery/keepalive progress, and failure-safe session/file cleanup replace timing assumptions and racy resets. - Server lifecycle tests verify the documented independent five-second compensation deadline rather than requiring a non-cancellable token. They cancel the actual request, prove compensation and unrelated monitored-item creation still proceed one tick before the deadline, preserve the original failure and ownership assertions, and verify the completed deadline is retired. - Synchronous and asynchronous directory-browser tests require the exact provider exception instead of an empty-directory success, then verify the failed cursor is not enumerated again. These correct expectations left behind by the intentional, documented provider-error propagation change; production behavior is unchanged. No tests were disabled, assertions loosened, coverage thresholds lowered, or CI checks made optional. Existing platform exclusions and Explicit debug variants remain. ## Related Issues - Fixes #4514 - Fixes #4515 - Builds on merged #4503 and retains the #4508 publishing-drain behavior. ## Validation **Lease-election review correction (`a13afa641182c70983e16bbcfebf507e666a45a5`):** The correction is based on the existing upstream merge `43079e2b851fe338a4082066f8d14abfdafb6e32`. Three deterministic stale-verdict cases fail on the original source and pass with separate confirmation fencing. Six new cases cover the initial foreign-owner verdict, failed-CAS revalidation in both invocation orders, and fresh ownership loss through both read paths, including revalidation begun after another successful confirmation. | Target and configuration | Passed | Failed | Skipped | | --- | ---: | ---: | ---: | | net10.0 Debug | 120 | 0 | 0 | | net48 Debug | 120 | 0 | 0 | The selection is the full `Opc.Ua.Core.Tests.Redundancy` namespace, including all 38 `SharedStoreLeaseElectionTests` cases and the existing expiry, clock rollback, disposal, and overlapping-success regressions. New witnesses are `StaleForeignLeaseReadDoesNotRevokeNewerAcquisitionAsync`, `StaleFailedRevalidationDoesNotRevokeNewerAcquisitionAsync`, and `FreshForeignLeaseObservationRevokesLeadershipAsync`. They assert resulting leadership, exact transitions, independent progress, and the unchanged expiry boundary. Retaining the initial generation for the fallback read independently makes the fresh-loss-after-confirmation control fail; that mutation was removed before the final rebuilt runs. The successful scoped command is `dotnet test tests\Opc.Ua.Core.Tests\Opc.Ua.Core.Tests.csproj -c Debug --no-restore --filter "FullyQualifiedName~Opc.Ua.Core.Tests.Redundancy"`, with `CustomTestTarget` and `-f` matching each row and that framework's assets restored. Both changed C# files pass formatting and analyzers through informational severity on both frameworks. These are scoped results, not a full-solution test or measured coverage-delta claim. CI monitoring is paused for this feedback-only operation; no current-head CI success is claimed. **Latest CI contract correction (`1cd1f2047bb5b50c9bf300b1ff710b0b2e935a29`):** All four failing Server shard 23 jobs in [run 36120946740](https://github.com/OPCFoundation/UA-.NETStandard/actions/runs/36120946740) reported the same six cases. Two local replays reproduced all six failures. The source changes and documentation from `cd43b831a` establish both intentional contracts: independent bounded event compensation and surfaced provider errors. Only the two test files are corrected; production code and CI policy are unchanged. | Target and configuration | Passed | Failed | Skipped | | --- | ---: | ---: | ---: | | net48 Debug | 113 | 0 | 0 | | net10.0 Release, CI Coverlet settings | 113 | 0 | 0 | The selection contains `MonitoredItemManagerLifecycleTests`, `DirectoryObjectStateTests`, `DirectoryBrowserBoundedEnumerationTests`, and `EventCompensationReadinessHasFiniteDeadlineWithInfiniteSourceTimeoutAsync`. Both changed files pass formatting and analyzers through informational severity on both frameworks. Independent mutations restoring a non-cancellable compensation token and swallowing provider errors fail all four lifecycle cases and both browser cases, respectively. Both mutations were removed before the final passing runs and commit. The scoped command is `dotnet test tests\Opc.Ua.Server.Tests\Opc.Ua.Server.Tests.csproj` with `CustomTestTarget` and `-f` set to the selected framework, `--no-restore`, and `--filter "FullyQualifiedName~MonitoredItemManagerLifecycleTests|FullyQualifiedName~DirectoryObjectStateTests|FullyQualifiedName~DirectoryBrowserBoundedEnumerationTests|FullyQualifiedName~EventCompensationReadinessHasFiniteDeadlineWithInfiniteSourceTimeoutAsync"`. The modern run additionally uses `-c Release /p:CollectCoverage=true --collect "XPlat Code Coverage" --settings tests\coverlet.runsettings.xml`. These are scoped results, not a full-solution test or measured coverage-delta claim. Hosted checks for that commit were pending at publication. The fail-fast CI watch was stopped when the requested operation switched to review feedback; no current-head CI success is claimed. **Earlier master merge (`8b15ea6ef9fc2214ac8ec886f373bb3846dd6d6f`, base `b4136d8e9bab0df680f41d9ef985f519160534b1`):** The `TcpListenerChannel` conflict preserves both lifetime responsibilities: disposal clears the retained peer-certificate chain and unregisters the quota-scoped message-assembly scheduler. Both fields and all upstream deadline handling remain intact. The only additional manual source adjustment adds the parentheses required by the existing analyzer around the session-count fallback. Master advanced during validation. The initial transport merge `80303c434ce813cf75aa7fe54a6a32fe2aeafc30` was retained, and the newer base was merged normally in `8b15ea6ef9fc2214ac8ec886f373bb3846dd6d6f`, without rewriting history. The additional recovery, fluent-pipeline, and test-framework overlaps were inspected; the branch's cancellation, validation-error, and acknowledgement ownership fixes remain alongside the upstream changes. Full `UA.slnx` builds passed on net10.0 and net48 with **0 warnings and 0 errors**. The final scoped tests rebuilt against the committed tree `2074f8efcb61d8d9c6106e7d6f76ee941940e358`: | Target | Passed | Failed | Skipped | | --- | ---: | ---: | ---: | | net10.0 | 2,653 | 0 | 0 | | net48 | 2,529 | 0 | 7 | The net48 skips are existing platform exclusions: six RSA_DH_AesGcm nonce cases and one ClientWebSocket certificate-validation case requiring .NET 7 or later. The selection covers transport cleanup, reassembly budgets/deadlines/admission, peer-chain ownership, server session binding, fluent lifecycles and source generation, reconnect and keepalive, transfer acknowledgements, Publish queues, and JSON encoding. Modern-.NET WSS transport and real-server integration cases also pass. The resolved file passed solution-relative formatting and analyzer verification through informational severity on both frameworks. These are scoped test results, not unfiltered full-suite or measured-coverage claims. Hosted CI was not monitored or repaired as part of this merge-only operation. Selected local results below are overlapping validation runs, not distinct-test totals. **Earlier review-feedback batch (`cd43b831a8f11de3f7d65c3681712a61e3c669a5`):** The final net10.0 scoped selection passed **471 tests, with no failures or skips**. The final net48 solution-root selection passed **439 tests, with no failures and one unchanged platform skip** (`ValidateServerCertificateFallsBackToTlsPolicyErrors`, which requires newer ClientWebSocket certificate-validation support). Both full nonincremental solution builds completed with **0 warnings and 0 errors**, and all **40 changed C# files** passed informational-level formatting/analyzer verification. Both frameworks validated the identical final tracked diff. The focused matrix covers every one of the 20 current review threads, including real mid-frame WSS cancellation, stale admission contexts, directory continuation ownership, multi-element Browse/Translate failures, and the readiness drain race. The net10.0 solution-root test command has a separate pre-existing runner conflict: three unrelated AOT projects reject the VSTest target under Microsoft.Testing.Platform 2.4.0 and SDK 10. Per-project net10.0 results are recorded separately; no runner migration, test exclusion, assertion relaxation, or CI-policy change is included. These are bounded selections, not unfiltered full-suite or measured coverage claims. At publication of `cd43b831a`, hosted CI was not green: the `OPCFoundation.UA-.NETStandard` check reported `ACTION_REQUIRED`, AppVeyor reported `FAILURE`, and the two signed-build jobs were in progress. No CI jobs were rerun, cancelled, approved, or repaired as part of that feedback-only operation. **Classic transfer correction (`f425376fca045794122e19aaf9cafebc4a717d91`):** The preceding head's [macOS net10.0 shard 25/30](https://github.com/OPCFoundation/UA-.NETStandard/actions/runs/35980326299/job/107570512458) failed `TransferSubscriptionTest(DisconnectedRepublish).TransferSubscriptionAsync(True,False)` at the static-node count assertion: expected 10, received 20. The trace contains a successful, explicitly requested republish of retained sequence 1 and a fresh initial-value batch at sequence 3, not duplicate dispatch of one response. Controlled lost origin acknowledgements reproduced that incorrect test expectation on both the preceding PR head and exact master base `a2539cb53dd1666cef856f33812d7a8830d68909`. The maintainer explicitly authorized correcting this existing issue in the PR. Retained replay and requested initial values are independent, as specified by [OPC UA Part 4, TransferSubscriptions](https://reference.opcfoundation.org/specs/OPC-10000-4/5.14.7). The reason that the original hosted run retained its particular origin message remains unproved. The expanded full-suite run then exposed a **real production race**, not just a count assertion: Session queued acknowledgements for all transferred available messages before the asynchronous Republish responses arrived. Publish could delete those messages first, causing `BadMessageNotAvailable`. A gated real-Session/classic-engine regression failed both replay-enabled cases on the original implementation while both no-replay controls passed. The ownership fix passes all 24 combinations of empty/consecutive/unsorted-gapped queues, replay preference, sequential delivery, and a reentrant preference change. All 40 normal real-server transfer cases pass on both frameworks. Independent mutations suppressing actual replay and duplicating observed sequence records each fail the intended assertion; both mutations were removed. The full classic suite passes on both frameworks. Hosted CI was pending when that correction was published; the earlier failed hosted job was not rerun for a lucky pass. **Local net48 caveat:** the full Client run timed out in the pre-existing fake-clock test `ReconnectAsyncSwapsFaultedLeaseEntryAsync`, which does not exercise subscription transfer. Its unchanged isolated replay passed, but that does not resolve the full-suite timeout. No unrelated code or assertions were changed, and a clean full Client net48 run is not claimed. | Scope | net10.0 | net48 | | --- | --- | --- | | Full Client.Tests after transfer acknowledgement correction | 2,549 passed | 2,552 passed, 1 timeout failure noted above, 1 existing platform skip | | Full classic-subscription project after transfer correction | 57 passed, including all 40 normal transfer cases | 57 passed, including all 40 normal transfer cases | | Gated transferred-message acknowledgement ownership | 24 passed, included above | 24 passed, included above | | Saved-session consumer of the shared subscription helper | 40 passed | 16 passed, 24 existing unsupported-security-policy skips | | Audit regression matrix | 2,339 passed | 1,934 passed, 34 existing skips | | Full Client.Tests after review follow-ups | 2,520 passed | Focused selections only | | Full Client.Tests after CI recovery correction | 2,523 passed, CI coverage collector | 2,527 passed, 1 existing platform skip | | Latest merged-head recovery/redundancy selection | 139 passed | 139 passed | | Full Client.Tests after merged-head net48 correction | Focused selection above | 2,529 passed, 1 existing platform skip | | Lifecycle and actual-dimension regressions | 146 passed | 146 passed | | Focused recovery follow-ups | 7 passed | 7 passed | | WSS-related fixtures | 93 passed | Not applicable | | CI History integration corrections | 28 passed | 28 passed | | CI alias, dispatcher, and explicit-atomic controls | 63 passed | 63 passed | | Full WoT sample project with CI coverage collector | 29 passed | Not applicable | | Trust-list effects and count-only summary contract | 22 passed | 22 passed | | Virtual-node feedback, node-manager, dispatcher, and lifecycle selections | 661 passed, 63 existing not-executed cases; all 48 virtual-node cases passed | 661 passed, 63 existing not-executed cases; all 48 virtual-node cases passed | | WSS wire-handle exhaustion, late replies, and Cancel translation | 9 passed | Not applicable | | Synchronous node-manager disposal and related service/lifecycle suites | 1,037 passed, 64 not-executed cases from existing fixture assumptions; all 93 sampling/disposal cases passed | 1,037 passed, 64 not-executed cases from existing fixture assumptions; all 93 sampling/disposal cases passed | - Full solution builds passed on net10.0 and net48 during the audit work. The subsequent full non-incremental net10.0 build also completed with zero warnings/errors. - Modified source/test formatting and analyzer checks passed through informational severity. - Original composed recovery regressions passed repeated runs on both frameworks. Independent mutations removing Publish cancellation, bypassing the recreate drain call, or ignoring ready-gate cancellation each failed the intended assertion; all mutations were restored before passing runs. - The latest recovery correction passed 100 executions of each original restoration-deadline scenario with unchanged assertions. Restoring premature update admission independently made both strengthened handoff cases fail; the correct retention behavior was restored afterward. - Startup-event and cancellation-delivery timing probes reproduced the subsequent net48 failures, then passed 100 executions of each of the three scenarios with the fixes. All timing probes and repetition were removed. The permanent timeout-order regression also went RED on the original cancellation cleanup without sleeps or scheduling amplification. - Final post-format recovery/subscription/engine checks passed all 151 selected cases on net10.0. The first local full net48 attempt aborted in `clr.dll` with native access violation `0xc0000005`; an unchanged-assembly full diagnostic rerun passed as recorded above. That native host crash has not been attributed or claimed fixed. - A minimal replay with the same CodeQL CLI and query-pack versions reproduced the custom-count alert and confirmed that the standard span-length projection is clean while direct sensitive-value and raw-identifier logging controls remain flagged. The source was already logging only a count; no identifier or certificate disclosure was established at the reported location. - The virtual-node feedback regressions first reproduced five error-preservation/cache failures; expanded service-dispatch cases exposed two additional whole-batch failures before the operation-boundary fixes. The final selections pass on both frameworks. Genuine misses remain cached, successful results remain reusable, failed validation allows same-cache retry, and request cancellation still stops the batch. - Three deterministic synchronous-manager disposal regressions reproduced early resource release and lifecycle calls reaching a manager during disposal. The fix passes direct and adapted calls, a sampling-worker join after the last operation exits, reentrant shutdown, cancellation and failure paths, repeated disposal, and exact rejection across 39 service/lifecycle entry points both during drain and after cleanup. The original outside-node-lock disposal regression remains and now requires the worker to observe closed admission. - Prior-head CI on `c985f8bded77a60449d9cd381c8a004d8590ccf6` completed with **168 passing checks, one expected release-package-publication skip, and no failures or pending checks**. All test shards, signed builds, container builds, the coverage check, and the CodeQL PR check passed. Hosted CodeQL analysis `1829262912` completed successfully and marks count-flow alert 385 fixed. This is evidence for that head, not a claim that subsequent review follow-ups have completed hosted CI. ### Session-test diagnostic memory Complete browse listings are streamed to unique NUnit attachments rather than retained in inline NUnit/VSTest output. Detached regression-test results are cleaned up without deleting runner-collected attachments. - Two covered session-suite runs each completed with 782 passed and 379 existing skips. Peak working set fell from 4.86 GiB to 2.44-2.78 GiB. - TRX output shrank from 303.1 MiB to approximately 40.7 MiB, retaining all 46 complete browse attachments. - Seven output regressions cover exact content, empty/single/large listings, disabled/enabled output, bounded inline summaries, and unique filenames. The separate Azure build-18452 VM deprovisioning cause remains unproved without provider logs. The memory measurements do not establish its cause. Unfiltered local `UA.slnx` tests, including the long stress/soak suites, have not been run on both frameworks. A local coverage delta was not collected; builds and focused tests are not substitutes for those claims. ## Checklist - [ ] I have signed the [CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf) and read the [CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md) doc. - [ ] I have added tests that prove my fix is effective or that my feature works and increased code coverage. - [x] I have added all necessary documentation. - [x] I have verified that my changes do not introduce (new) build or analyzer warnings. - [ ] I ran **all** tests locally using the **UA.slnx** solution against at least .net **framework** and .net **10**, and all passed. - [ ] All checks on the latest review-follow-up head have completed successfully; prior-head CI passed as recorded above. - [x] I have addressed **all** PR feedback received. Tests have been added and pass as recorded above; the hosted coverage check passed on the prior head identified above. The combined tests/coverage-increase checkbox remains open because no local coverage delta was measured. --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 68f26810-22b8-476f-abcd-0a8c82d6e208
1378 lines
58 KiB
C#
1378 lines
58 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/
|
|
* ======================================================================*/
|
|
|
|
#nullable enable
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Options;
|
|
using NUnit.Framework;
|
|
using Opc.Ua.Client.Subscriptions;
|
|
using Opc.Ua.Client.Subscriptions.MonitoredItems;
|
|
using Opc.Ua.Client.Subscriptions.Streaming;
|
|
|
|
namespace Opc.Ua.Subscriptions.Tests
|
|
{
|
|
/// <summary>
|
|
/// Deterministic offline unit-test coverage for
|
|
/// <see cref="StreamingSubscription"/> and
|
|
/// <see cref="StreamingSubscriptionExtensions"/>. Uses hand-rolled
|
|
/// stub implementations of the subscription interfaces (no Moq) and
|
|
/// drives notifications by invoking the captured notification
|
|
/// handler, so every assertion is data-driven and never relies on
|
|
/// wall-clock timing.
|
|
/// </summary>
|
|
[TestFixture]
|
|
[Category("Client")]
|
|
[Category("Streaming")]
|
|
[SetCulture("en-us")]
|
|
[SetUICulture("en-us")]
|
|
public sealed class StreamingSubscriptionCoverageTests
|
|
{
|
|
private static readonly TimeSpan s_safetyTimeout = TimeSpan.FromSeconds(10);
|
|
|
|
private static readonly DateTime s_publishTime =
|
|
new(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc);
|
|
|
|
private static readonly IReadOnlyList<string> s_emptyStringTable =
|
|
[];
|
|
|
|
private static readonly NodeId s_nodeA = new("SensorA", 2);
|
|
private static readonly NodeId s_nodeB = new("SensorB", 2);
|
|
private static readonly NodeId s_notifier = new("Area1", 3);
|
|
private static readonly int[] s_oneTwo = [1, 2];
|
|
private static readonly int[] s_oneTwoThree = [1, 2, 3];
|
|
|
|
private const uint GoodStatus = 0x00000000u;
|
|
private const uint UncertainStatus = 0x40920000u;
|
|
|
|
[Test]
|
|
public void ConstructorWithNullManagerThrowsArgumentNullException()
|
|
{
|
|
ArgumentNullException? ex = Assert.Throws<ArgumentNullException>(
|
|
() => _ = new StreamingSubscription(null!));
|
|
Assert.That(ex!.ParamName, Is.EqualTo("subscriptionManager"));
|
|
}
|
|
|
|
[Test]
|
|
public void SubscribeDataChangesWithNullNodeIdThrowsArgumentNullException()
|
|
{
|
|
var manager = new StubSubscriptionManager();
|
|
var subscription = new StreamingSubscription(manager);
|
|
|
|
ArgumentNullException? ex = Assert.Throws<ArgumentNullException>(
|
|
() => _ = subscription.SubscribeDataChangesAsync(NodeId.Null));
|
|
Assert.That(ex!.ParamName, Is.EqualTo("nodeId"));
|
|
}
|
|
|
|
[Test]
|
|
public void SubscribeDataChangesWithNullNodeListThrowsArgumentNullException()
|
|
{
|
|
var manager = new StubSubscriptionManager();
|
|
var subscription = new StreamingSubscription(manager);
|
|
|
|
ArgumentNullException? ex = Assert.Throws<ArgumentNullException>(
|
|
() => _ = subscription.SubscribeDataChangesAsync(null!));
|
|
Assert.That(ex!.ParamName, Is.EqualTo("nodeIds"));
|
|
}
|
|
|
|
[Test]
|
|
public void SubscribeEventsWithNullNotifierThrowsArgumentNullException()
|
|
{
|
|
var manager = new StubSubscriptionManager();
|
|
var subscription = new StreamingSubscription(manager);
|
|
|
|
ArgumentNullException? ex = Assert.Throws<ArgumentNullException>(
|
|
() => _ = subscription.SubscribeEventsAsync(NodeId.Null, new EventFilter()));
|
|
Assert.That(ex!.ParamName, Is.EqualTo("notifierId"));
|
|
}
|
|
|
|
[Test]
|
|
public void SubscribeEventsWithNullFilterThrowsArgumentNullException()
|
|
{
|
|
var manager = new StubSubscriptionManager();
|
|
var subscription = new StreamingSubscription(manager);
|
|
|
|
ArgumentNullException? ex = Assert.Throws<ArgumentNullException>(
|
|
() => _ = subscription.SubscribeEventsAsync(s_notifier, null!));
|
|
Assert.That(ex!.ParamName, Is.EqualTo("filter"));
|
|
}
|
|
|
|
[Test]
|
|
public async Task SubscribeCreatesSingleSharedSubscriptionAsync()
|
|
{
|
|
var manager = new StubSubscriptionManager();
|
|
await using var subscription = new StreamingSubscription(manager);
|
|
|
|
(IAsyncEnumerator<DataValueChange> firstEnumerator, Task<bool> firstMove) =
|
|
StartDataChanges(subscription, s_nodeA, CancellationToken.None);
|
|
(IAsyncEnumerator<DataValueChange> secondEnumerator, Task<bool> secondMove) =
|
|
StartDataChanges(subscription, s_nodeB, CancellationToken.None);
|
|
|
|
Assert.That(manager.AddCallCount, Is.EqualTo(1));
|
|
StubMonitoredItemCollection collection = manager.Subscription!.Collection;
|
|
Assert.That(collection.Count, Is.EqualTo(2u));
|
|
Assert.That(collection.Added[0].ClientHandle,
|
|
Is.Not.EqualTo(collection.Added[1].ClientHandle));
|
|
|
|
await subscription.DisposeAsync().ConfigureAwait(false);
|
|
Assert.That(await WithinTimeoutAsync(firstMove).ConfigureAwait(false), Is.False);
|
|
Assert.That(await WithinTimeoutAsync(secondMove).ConfigureAwait(false), Is.False);
|
|
await firstEnumerator.DisposeAsync().ConfigureAwait(false);
|
|
await secondEnumerator.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
[Test]
|
|
public async Task DataChangeNotificationFlowsToSubscriberAsync()
|
|
{
|
|
var manager = new StubSubscriptionManager();
|
|
await using var subscription = new StreamingSubscription(manager);
|
|
|
|
(IAsyncEnumerator<DataValueChange> enumerator, Task<bool> move) =
|
|
StartDataChanges(subscription, s_nodeA, CancellationToken.None);
|
|
|
|
Assert.That(manager.AddCallCount, Is.EqualTo(1));
|
|
StubMonitoredItem item = manager.Subscription!.Collection.Added[0];
|
|
Assert.That(item.Options.StartNodeId, Is.EqualTo(s_nodeA));
|
|
Assert.That(item.Options.AttributeId, Is.EqualTo(Attributes.Value));
|
|
Assert.That(item.Name, Is.EqualTo($"stream_data_1_{s_nodeA}"));
|
|
|
|
var change = new DataValueChange(item,
|
|
new DataValue(Variant.From(42), new StatusCode(UncertainStatus)), null);
|
|
await FireDataChangeAsync(manager, change).ConfigureAwait(false);
|
|
|
|
Assert.That(await WithinTimeoutAsync(move).ConfigureAwait(false), Is.True);
|
|
DataValueChange received = enumerator.Current;
|
|
Assert.That(received.Value.WrappedValue, Is.EqualTo(Variant.From(42)));
|
|
Assert.That(received.Value.StatusCode.Code, Is.EqualTo(UncertainStatus));
|
|
Assert.That(received.MonitoredItem, Is.SameAs(item));
|
|
|
|
await enumerator.DisposeAsync().ConfigureAwait(false);
|
|
Assert.That(manager.Subscription!.Collection.RemovedHandles,
|
|
Does.Contain(item.ClientHandle));
|
|
}
|
|
|
|
[Test]
|
|
public async Task DataChangeListOverloadAddsAllItemsAsync()
|
|
{
|
|
var manager = new StubSubscriptionManager();
|
|
await using var subscription = new StreamingSubscription(manager);
|
|
|
|
var nodes = new List<NodeId> { s_nodeA, s_nodeB };
|
|
IAsyncEnumerator<DataValueChange> enumerator =
|
|
subscription.SubscribeDataChangesAsync(nodes).GetAsyncEnumerator();
|
|
Task<bool> move = enumerator.MoveNextAsync().AsTask();
|
|
|
|
Assert.That(manager.AddCallCount, Is.EqualTo(1));
|
|
StubMonitoredItemCollection collection = manager.Subscription!.Collection;
|
|
Assert.That(collection.Count, Is.EqualTo(2u));
|
|
StubMonitoredItem second = collection.Added[1];
|
|
Assert.That(second.Options.StartNodeId, Is.EqualTo(s_nodeB));
|
|
|
|
var change = new DataValueChange(second,
|
|
new DataValue(Variant.From(99), new StatusCode(GoodStatus)), null);
|
|
await FireDataChangeAsync(manager, change).ConfigureAwait(false);
|
|
|
|
Assert.That(await WithinTimeoutAsync(move).ConfigureAwait(false), Is.True);
|
|
Assert.That(enumerator.Current.Value.WrappedValue, Is.EqualTo(Variant.From(99)));
|
|
Assert.That(enumerator.Current.MonitoredItem, Is.SameAs(second));
|
|
|
|
await enumerator.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
[Test]
|
|
public async Task EventNotificationFlowsToSubscriberAsync()
|
|
{
|
|
var manager = new StubSubscriptionManager();
|
|
await using var subscription = new StreamingSubscription(manager);
|
|
|
|
var filter = new EventFilter();
|
|
IAsyncEnumerator<EventNotification> enumerator =
|
|
subscription.SubscribeEventsAsync(s_notifier, filter).GetAsyncEnumerator();
|
|
Task<bool> move = enumerator.MoveNextAsync().AsTask();
|
|
|
|
Assert.That(manager.AddCallCount, Is.EqualTo(1));
|
|
StubMonitoredItem item = manager.Subscription!.Collection.Added[0];
|
|
Assert.That(item.Options.AttributeId, Is.EqualTo(Attributes.EventNotifier));
|
|
Assert.That(item.Options.Filter, Is.SameAs(filter));
|
|
Assert.That(item.Options.QueueSize, Is.EqualTo(10u));
|
|
Assert.That(item.Name, Is.EqualTo($"stream_event_1_{s_notifier}"));
|
|
|
|
var notification = new EventNotification(item,
|
|
ArrayOf.Wrapped(Variant.From("AlarmActive"), Variant.From(7)));
|
|
await FireEventAsync(manager, notification).ConfigureAwait(false);
|
|
|
|
Assert.That(await WithinTimeoutAsync(move).ConfigureAwait(false), Is.True);
|
|
EventNotification received = enumerator.Current;
|
|
Assert.That(received.Fields.Count, Is.EqualTo(2));
|
|
Assert.That(received.Fields[0], Is.EqualTo(Variant.From("AlarmActive")));
|
|
Assert.That(received.Fields[1], Is.EqualTo(Variant.From(7)));
|
|
Assert.That(received.MonitoredItem, Is.SameAs(item));
|
|
|
|
await enumerator.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
[Test]
|
|
public async Task EventUsesProvidedQueueSizeAsync()
|
|
{
|
|
var manager = new StubSubscriptionManager();
|
|
await using var subscription = new StreamingSubscription(manager);
|
|
|
|
var options = new MonitoredItemOptions { QueueSize = 5 };
|
|
IAsyncEnumerator<EventNotification> enumerator = subscription
|
|
.SubscribeEventsAsync(s_notifier, new EventFilter(), options)
|
|
.GetAsyncEnumerator();
|
|
Task<bool> move = enumerator.MoveNextAsync().AsTask();
|
|
|
|
StubMonitoredItem item = manager.Subscription!.Collection.Added[0];
|
|
Assert.That(item.Options.QueueSize, Is.EqualTo(5u));
|
|
|
|
await DrainAsync(subscription, enumerator, move).ConfigureAwait(false);
|
|
}
|
|
|
|
[TestCase(true, 2, 3)]
|
|
[TestCase(false, 1, 2)]
|
|
public async Task BoundedEventChannelHonorsDiscardOldestOptionAsync(
|
|
bool discardOldest,
|
|
int firstExpected,
|
|
int secondExpected)
|
|
{
|
|
var manager = new StubSubscriptionManager();
|
|
await using var subscription = new StreamingSubscription(manager);
|
|
|
|
var options = new MonitoredItemOptions
|
|
{
|
|
QueueSize = 2,
|
|
DiscardOldest = discardOldest
|
|
};
|
|
var itemReady = new TaskCompletionSource<bool>(
|
|
TaskCreationOptions.RunContinuationsAsynchronously);
|
|
var releaseItemReady = new TaskCompletionSource<bool>(
|
|
TaskCreationOptions.RunContinuationsAsynchronously);
|
|
var readiness = (IStreamingSubscriptionReadiness)subscription;
|
|
await using IAsyncEnumerator<EventNotification> enumerator = readiness
|
|
.SubscribeEventsAsync(
|
|
s_notifier,
|
|
new EventFilter(),
|
|
options,
|
|
async (_, _) =>
|
|
{
|
|
itemReady.SetResult(true);
|
|
await releaseItemReady.Task.ConfigureAwait(false);
|
|
})
|
|
.GetAsyncEnumerator();
|
|
Task<bool> move = enumerator.MoveNextAsync().AsTask();
|
|
try
|
|
{
|
|
await itemReady.Task.WaitAsync(s_safetyTimeout).ConfigureAwait(false);
|
|
StubMonitoredItem item = manager.Subscription!.Collection.Added[0];
|
|
await FireEventsAsync(
|
|
manager,
|
|
new EventNotification(item, ArrayOf.Wrapped(Variant.From(1))),
|
|
new EventNotification(item, ArrayOf.Wrapped(Variant.From(2))),
|
|
new EventNotification(item, ArrayOf.Wrapped(Variant.From(3))))
|
|
.ConfigureAwait(false);
|
|
|
|
releaseItemReady.SetResult(true);
|
|
Assert.That(await WithinTimeoutAsync(move).ConfigureAwait(false), Is.True);
|
|
Assert.That(
|
|
enumerator.Current.Fields[0],
|
|
Is.EqualTo(Variant.From(firstExpected)));
|
|
move = enumerator.MoveNextAsync().AsTask();
|
|
Assert.That(await WithinTimeoutAsync(move).ConfigureAwait(false), Is.True);
|
|
Assert.That(
|
|
enumerator.Current.Fields[0],
|
|
Is.EqualTo(Variant.From(secondExpected)));
|
|
Assert.That(subscription.DroppedNotificationCount, Is.EqualTo(1));
|
|
}
|
|
finally
|
|
{
|
|
releaseItemReady.TrySetResult(true);
|
|
await subscription.DisposeAsync().ConfigureAwait(false);
|
|
await WithinTimeoutAsync(move).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
[Test]
|
|
public async Task ConcurrentSubscribersReceiveOnlyMatchingNotificationsAsync()
|
|
{
|
|
var manager = new StubSubscriptionManager();
|
|
await using var subscription = new StreamingSubscription(manager);
|
|
|
|
(IAsyncEnumerator<DataValueChange> enumeratorA, Task<bool> moveA) =
|
|
StartDataChanges(subscription, s_nodeA, CancellationToken.None);
|
|
(IAsyncEnumerator<DataValueChange> enumeratorB, Task<bool> moveB) =
|
|
StartDataChanges(subscription, s_nodeB, CancellationToken.None);
|
|
|
|
Assert.That(manager.AddCallCount, Is.EqualTo(1));
|
|
StubMonitoredItem itemA = manager.Subscription!.Collection.Added[0];
|
|
|
|
var change = new DataValueChange(itemA,
|
|
new DataValue(Variant.From(11), new StatusCode(GoodStatus)), null);
|
|
await FireDataChangeAsync(manager, change).ConfigureAwait(false);
|
|
|
|
Assert.That(await WithinTimeoutAsync(moveA).ConfigureAwait(false), Is.True);
|
|
Assert.That(enumeratorA.Current.Value.WrappedValue, Is.EqualTo(Variant.From(11)));
|
|
Assert.That(moveB.IsCompleted, Is.False);
|
|
|
|
await enumeratorA.DisposeAsync().ConfigureAwait(false);
|
|
await subscription.DisposeAsync().ConfigureAwait(false);
|
|
Assert.That(await WithinTimeoutAsync(moveB).ConfigureAwait(false), Is.False);
|
|
await enumeratorB.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
[Test]
|
|
public async Task CancellingOneSubscriberRemovesOnlyItsMonitoredItemAsync()
|
|
{
|
|
var manager = new StubSubscriptionManager();
|
|
await using var subscription = new StreamingSubscription(manager);
|
|
using var cancelA = new CancellationTokenSource();
|
|
|
|
(IAsyncEnumerator<DataValueChange> enumeratorA, Task<bool> moveA) =
|
|
StartDataChanges(subscription, s_nodeA, cancelA.Token);
|
|
(IAsyncEnumerator<DataValueChange> enumeratorB, Task<bool> moveB) =
|
|
StartDataChanges(subscription, s_nodeB, CancellationToken.None);
|
|
|
|
StubMonitoredItemCollection collection = manager.Subscription!.Collection;
|
|
StubMonitoredItem itemA = collection.Added[0];
|
|
StubMonitoredItem itemB = collection.Added[1];
|
|
|
|
cancelA.Cancel();
|
|
await AwaitFaultAsync<OperationCanceledException>(moveA).ConfigureAwait(false);
|
|
|
|
Assert.That(collection.RemovedHandles, Does.Contain(itemA.ClientHandle));
|
|
Assert.That(collection.RemovedHandles, Does.Not.Contain(itemB.ClientHandle));
|
|
Assert.That(collection.ContainsHandle(itemB.ClientHandle), Is.True);
|
|
|
|
await enumeratorA.DisposeAsync().ConfigureAwait(false);
|
|
await subscription.DisposeAsync().ConfigureAwait(false);
|
|
Assert.That(await WithinTimeoutAsync(moveB).ConfigureAwait(false), Is.False);
|
|
await enumeratorB.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
[Test]
|
|
public async Task DisposeAsyncDisposesUnderlyingSubscriptionAndIsIdempotentAsync()
|
|
{
|
|
var manager = new StubSubscriptionManager();
|
|
var subscription = new StreamingSubscription(manager);
|
|
|
|
(IAsyncEnumerator<DataValueChange> enumerator, Task<bool> move) =
|
|
StartDataChanges(subscription, s_nodeA, CancellationToken.None);
|
|
Assert.That(manager.AddCallCount, Is.EqualTo(1));
|
|
|
|
await subscription.DisposeAsync().ConfigureAwait(false);
|
|
Assert.That(manager.Subscription!.DisposeCount, Is.EqualTo(1));
|
|
|
|
await subscription.DisposeAsync().ConfigureAwait(false);
|
|
Assert.That(manager.Subscription!.DisposeCount, Is.EqualTo(1));
|
|
|
|
Assert.That(await WithinTimeoutAsync(move).ConfigureAwait(false), Is.False);
|
|
await enumerator.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
[TestCase(true, 4)]
|
|
[TestCase(false, 1)]
|
|
public async Task DefaultDataChangeBufferBoundsSlowReadersAsync(bool discardOldest, int expected)
|
|
{
|
|
var manager = new StubSubscriptionManager();
|
|
await using var subscription = new StreamingSubscription(manager);
|
|
MonitoredItemOptions? options = discardOldest
|
|
? null
|
|
: new MonitoredItemOptions { DiscardOldest = false };
|
|
await using IAsyncEnumerator<DataValueChange> enumerator = subscription
|
|
.SubscribeDataChangesAsync(s_nodeA, options).GetAsyncEnumerator();
|
|
Task<bool> firstMove = enumerator.MoveNextAsync().AsTask();
|
|
StubMonitoredItem item = manager.Subscription!.Collection.Added[0];
|
|
await FireDataChangeAsync(manager, new DataValueChange(
|
|
item, new DataValue(Variant.From(0)), null)).ConfigureAwait(false);
|
|
Assert.That(await WithinTimeoutAsync(firstMove).ConfigureAwait(false), Is.True);
|
|
Assert.That(enumerator.Current.Value.WrappedValue, Is.EqualTo(Variant.From(0)));
|
|
Assert.That(subscription.DroppedNotificationCount, Is.Zero);
|
|
|
|
for (int value = 1; value <= 4; value++)
|
|
{
|
|
await FireDataChangeAsync(manager, new DataValueChange(
|
|
item, new DataValue(Variant.From(value)), null)).ConfigureAwait(false);
|
|
}
|
|
await subscription.DisposeAsync().ConfigureAwait(false);
|
|
|
|
Assert.That(await enumerator.MoveNextAsync().ConfigureAwait(false), Is.True);
|
|
Assert.That(enumerator.Current.Value.WrappedValue, Is.EqualTo(Variant.From(expected)));
|
|
Assert.That(await enumerator.MoveNextAsync().ConfigureAwait(false), Is.False);
|
|
Assert.That(subscription.DroppedNotificationCount, Is.EqualTo(3));
|
|
}
|
|
|
|
[TestCase(0u, true, new[] { 5, 6 })]
|
|
[TestCase(2u, true, new[] { 3, 4, 5, 6 })]
|
|
[TestCase(2u, false, new[] { 1, 2, 3, 4 })]
|
|
public async Task MultiNodeDataChangeBufferHonorsBoundAndDiscardPolicyAsync(
|
|
uint queueSize,
|
|
bool discardOldest,
|
|
int[] expected)
|
|
{
|
|
var manager = new StubSubscriptionManager();
|
|
await using var subscription = new StreamingSubscription(manager);
|
|
await using IAsyncEnumerator<DataValueChange> enumerator = subscription
|
|
.SubscribeDataChangesAsync(
|
|
[s_nodeA, s_nodeB],
|
|
new MonitoredItemOptions { QueueSize = queueSize, DiscardOldest = discardOldest })
|
|
.GetAsyncEnumerator();
|
|
Task<bool> firstMove = enumerator.MoveNextAsync().AsTask();
|
|
StubMonitoredItemCollection collection = manager.Subscription!.Collection;
|
|
Assert.That(collection.Count, Is.EqualTo(2));
|
|
await FireDataChangeAsync(manager, new DataValueChange(
|
|
collection.Added[0], new DataValue(Variant.From(0)), null)).ConfigureAwait(false);
|
|
Assert.That(await WithinTimeoutAsync(firstMove).ConfigureAwait(false), Is.True);
|
|
|
|
for (int value = 1; value <= 6; value++)
|
|
{
|
|
await FireDataChangeAsync(manager, new DataValueChange(
|
|
collection.Added[value == 1 ? 1 : 0], new DataValue(Variant.From(value)), null))
|
|
.ConfigureAwait(false);
|
|
}
|
|
await subscription.DisposeAsync().ConfigureAwait(false);
|
|
|
|
var values = new List<int>();
|
|
while (await enumerator.MoveNextAsync().ConfigureAwait(false))
|
|
{
|
|
Assert.That(enumerator.Current.Value.WrappedValue.TryGetValue(out int value), Is.True);
|
|
Assert.That(enumerator.Current.MonitoredItem,
|
|
Is.SameAs(collection.Added[value == 1 ? 1 : 0]));
|
|
values.Add(value);
|
|
}
|
|
Assert.That(values, Is.EqualTo(expected));
|
|
Assert.That(subscription.DroppedNotificationCount, Is.EqualTo(6 - expected.Length));
|
|
Assert.That(manager.Subscription.DisposeCount, Is.EqualTo(1));
|
|
}
|
|
|
|
[Test]
|
|
public async Task SubscribeAfterDisposeThrowsObjectDisposedExceptionAsync()
|
|
{
|
|
var manager = new StubSubscriptionManager();
|
|
var subscription = new StreamingSubscription(manager);
|
|
await subscription.DisposeAsync().ConfigureAwait(false);
|
|
|
|
(IAsyncEnumerator<DataValueChange> enumerator, Task<bool> move) =
|
|
StartDataChanges(subscription, s_nodeA, CancellationToken.None);
|
|
|
|
await AwaitFaultAsync<ObjectDisposedException>(move).ConfigureAwait(false);
|
|
Assert.That(manager.AddCallCount, Is.Zero);
|
|
await enumerator.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
[Test]
|
|
public async Task SubscriptionCreateFailureSurfacesToCallerAsync()
|
|
{
|
|
var manager = new StubSubscriptionManager(failAdd: true);
|
|
await using var subscription = new StreamingSubscription(manager);
|
|
|
|
(IAsyncEnumerator<DataValueChange> enumerator, Task<bool> move) =
|
|
StartDataChanges(subscription, s_nodeA, CancellationToken.None);
|
|
|
|
InvalidOperationException ex =
|
|
await AwaitFaultAsync<InvalidOperationException>(move).ConfigureAwait(false);
|
|
Assert.That(ex.Message, Is.EqualTo("subscription create failed"));
|
|
Assert.That(manager.AddCallCount, Is.EqualTo(1));
|
|
await enumerator.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
[Test]
|
|
public async Task FailedMonitoredItemAddSurfacesToCallerAsync()
|
|
{
|
|
var manager = new StubSubscriptionManager(failItemAdd: true);
|
|
await using var subscription = new StreamingSubscription(manager);
|
|
|
|
(IAsyncEnumerator<DataValueChange> enumerator, Task<bool> move) =
|
|
StartDataChanges(subscription, s_nodeA, CancellationToken.None);
|
|
|
|
InvalidOperationException ex =
|
|
await AwaitFaultAsync<InvalidOperationException>(move).ConfigureAwait(false);
|
|
Assert.That(ex.Message, Does.Contain(s_nodeA.ToString()));
|
|
Assert.That(manager.AddCallCount, Is.EqualTo(1));
|
|
StubMonitoredItemCollection collection = manager.Subscription!.Collection;
|
|
Assert.That(collection.Count, Is.Zero);
|
|
Assert.That(collection.Added, Is.Empty);
|
|
|
|
await enumerator.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
[Test]
|
|
public async Task DataChangeWithNullMonitoredItemIsIgnoredAsync()
|
|
{
|
|
var manager = new StubSubscriptionManager();
|
|
await using var subscription = new StreamingSubscription(manager);
|
|
|
|
(IAsyncEnumerator<DataValueChange> enumerator, Task<bool> move) =
|
|
StartDataChanges(subscription, s_nodeA, CancellationToken.None);
|
|
StubMonitoredItem item = manager.Subscription!.Collection.Added[0];
|
|
|
|
var ignored = new DataValueChange(null,
|
|
new DataValue(Variant.From(1), new StatusCode(GoodStatus)), null);
|
|
await FireDataChangeAsync(manager, ignored).ConfigureAwait(false);
|
|
Assert.That(move.IsCompleted, Is.False);
|
|
|
|
var delivered = new DataValueChange(item,
|
|
new DataValue(Variant.From(55), new StatusCode(GoodStatus)), null);
|
|
await FireDataChangeAsync(manager, delivered).ConfigureAwait(false);
|
|
|
|
Assert.That(await WithinTimeoutAsync(move).ConfigureAwait(false), Is.True);
|
|
Assert.That(enumerator.Current.Value.WrappedValue, Is.EqualTo(Variant.From(55)));
|
|
Assert.That(enumerator.Current.MonitoredItem, Is.SameAs(item));
|
|
|
|
await enumerator.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
[Test]
|
|
public async Task EventWithNullMonitoredItemIsIgnoredAsync()
|
|
{
|
|
var manager = new StubSubscriptionManager();
|
|
await using var subscription = new StreamingSubscription(manager);
|
|
|
|
IAsyncEnumerator<EventNotification> enumerator =
|
|
subscription.SubscribeEventsAsync(s_notifier, new EventFilter()).GetAsyncEnumerator();
|
|
Task<bool> move = enumerator.MoveNextAsync().AsTask();
|
|
StubMonitoredItem item = manager.Subscription!.Collection.Added[0];
|
|
|
|
var ignored = new EventNotification(null, ArrayOf.Wrapped(Variant.From(1)));
|
|
await FireEventAsync(manager, ignored).ConfigureAwait(false);
|
|
Assert.That(move.IsCompleted, Is.False);
|
|
|
|
var delivered = new EventNotification(item, ArrayOf.Wrapped(Variant.From("Ping")));
|
|
await FireEventAsync(manager, delivered).ConfigureAwait(false);
|
|
|
|
Assert.That(await WithinTimeoutAsync(move).ConfigureAwait(false), Is.True);
|
|
Assert.That(enumerator.Current.Fields.Count, Is.EqualTo(1));
|
|
Assert.That(enumerator.Current.Fields[0], Is.EqualTo(Variant.From("Ping")));
|
|
|
|
await enumerator.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
[Test]
|
|
public async Task KeepAliveAndStateChangeNotificationsAreNoOpsAsync()
|
|
{
|
|
var manager = new StubSubscriptionManager();
|
|
await using var subscription = new StreamingSubscription(manager);
|
|
|
|
(IAsyncEnumerator<DataValueChange> enumerator, Task<bool> move) =
|
|
StartDataChanges(subscription, s_nodeA, CancellationToken.None);
|
|
Assert.That(manager.AddCallCount, Is.EqualTo(1));
|
|
|
|
ValueTask keepAlive = manager.Handler!.OnKeepAliveNotificationAsync(
|
|
manager.Subscription!, 7u, s_publishTime, PublishState.None);
|
|
Assert.That(keepAlive.IsCompleted, Is.True);
|
|
await keepAlive.ConfigureAwait(false);
|
|
|
|
ValueTask stateChanged = manager.Handler!.OnSubscriptionStateChangedAsync(
|
|
manager.Subscription!, SubscriptionState.Created, PublishState.None);
|
|
Assert.That(stateChanged.IsCompleted, Is.True);
|
|
await stateChanged.ConfigureAwait(false);
|
|
|
|
Assert.That(move.IsCompleted, Is.False);
|
|
await DrainAsync(subscription, enumerator, move).ConfigureAwait(false);
|
|
}
|
|
|
|
[Test]
|
|
public async Task SubscriptionOptionsMonitorIsQueriedOnCreateAsync()
|
|
{
|
|
var manager = new StubSubscriptionManager();
|
|
await using var subscription = new StreamingSubscription(manager);
|
|
|
|
(IAsyncEnumerator<DataValueChange> enumerator, Task<bool> move) =
|
|
StartDataChanges(subscription, s_nodeA, CancellationToken.None);
|
|
|
|
Assert.That(manager.AddCallCount, Is.EqualTo(1));
|
|
Assert.That(manager.CapturedOptions, Is.Not.Null);
|
|
Assert.That(manager.CapturedOnChange, Is.Null);
|
|
|
|
await DrainAsync(subscription, enumerator, move).ConfigureAwait(false);
|
|
}
|
|
|
|
[Test]
|
|
public async Task DisposeAsyncSwallowsUnderlyingDisposeFailureAsync()
|
|
{
|
|
var manager = new StubSubscriptionManager(failDispose: true);
|
|
var subscription = new StreamingSubscription(manager);
|
|
|
|
(IAsyncEnumerator<DataValueChange> enumerator, Task<bool> move) =
|
|
StartDataChanges(subscription, s_nodeA, CancellationToken.None);
|
|
Assert.That(manager.AddCallCount, Is.EqualTo(1));
|
|
|
|
await subscription.DisposeAsync().ConfigureAwait(false);
|
|
Assert.That(manager.Subscription!.DisposeCount, Is.EqualTo(1));
|
|
|
|
Assert.That(await WithinTimeoutAsync(move).ConfigureAwait(false), Is.False);
|
|
await enumerator.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
[Test]
|
|
public async Task DataSubscriberFinallySwallowsRemoveFailureAsync()
|
|
{
|
|
var manager = new StubSubscriptionManager(failRemove: true);
|
|
await using var subscription = new StreamingSubscription(manager);
|
|
using var cancel = new CancellationTokenSource();
|
|
|
|
(IAsyncEnumerator<DataValueChange> enumerator, Task<bool> move) =
|
|
StartDataChanges(subscription, s_nodeA, cancel.Token);
|
|
Assert.That(manager.AddCallCount, Is.EqualTo(1));
|
|
StubMonitoredItem item = manager.Subscription!.Collection.Added[0];
|
|
|
|
cancel.Cancel();
|
|
await AwaitFaultAsync<OperationCanceledException>(move).ConfigureAwait(false);
|
|
|
|
Assert.That(manager.Subscription!.Collection.RemoveAttempts,
|
|
Does.Contain(item.ClientHandle));
|
|
await enumerator.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
[Test]
|
|
public async Task EventSubscriberFinallySwallowsRemoveFailureAsync()
|
|
{
|
|
var manager = new StubSubscriptionManager(failRemove: true);
|
|
await using var subscription = new StreamingSubscription(manager);
|
|
using var cancel = new CancellationTokenSource();
|
|
|
|
IAsyncEnumerator<EventNotification> enumerator = subscription
|
|
.SubscribeEventsAsync(s_notifier, new EventFilter(), ct: cancel.Token)
|
|
.GetAsyncEnumerator(cancel.Token);
|
|
Task<bool> move = enumerator.MoveNextAsync().AsTask();
|
|
Assert.That(manager.AddCallCount, Is.EqualTo(1));
|
|
StubMonitoredItem item = manager.Subscription!.Collection.Added[0];
|
|
|
|
cancel.Cancel();
|
|
await AwaitFaultAsync<OperationCanceledException>(move).ConfigureAwait(false);
|
|
|
|
Assert.That(manager.Subscription!.Collection.RemoveAttempts,
|
|
Does.Contain(item.ClientHandle));
|
|
await enumerator.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
[Test]
|
|
public async Task ConcurrentCreatorsShareSingleSubscriptionViaInitLockAsync()
|
|
{
|
|
using var addEntered = new SemaphoreSlim(0, 1);
|
|
using var itemsAdded = new SemaphoreSlim(0, 2);
|
|
using var releaseAdd = new ManualResetEventSlim(false);
|
|
var manager = new StubSubscriptionManager
|
|
{
|
|
OnAddEntered = () => addEntered.Release(),
|
|
AddGate = () => _ = releaseAdd.Wait(s_safetyTimeout),
|
|
OnItemAdded = () => itemsAdded.Release()
|
|
};
|
|
await using var subscription = new StreamingSubscription(manager);
|
|
|
|
// First creator acquires the init lock and blocks inside Add so the
|
|
// shared subscription is still null while a second creator queues.
|
|
IAsyncEnumerator<DataValueChange> firstEnumerator =
|
|
subscription.SubscribeDataChangesAsync(s_nodeA).GetAsyncEnumerator();
|
|
Task<bool> firstMove = Task.Run(() => firstEnumerator.MoveNextAsync().AsTask());
|
|
Assert.That(await addEntered.WaitAsync(s_safetyTimeout).ConfigureAwait(false), Is.True);
|
|
|
|
// Second creator passes the pre-lock null check then suspends on the
|
|
// held init lock; releasing the gate forces it through the
|
|
// double-check path where the subscription now already exists.
|
|
IAsyncEnumerator<DataValueChange> secondEnumerator =
|
|
subscription.SubscribeDataChangesAsync(s_nodeB).GetAsyncEnumerator();
|
|
Task<bool> secondMove = secondEnumerator.MoveNextAsync().AsTask();
|
|
|
|
releaseAdd.Set();
|
|
Assert.That(await itemsAdded.WaitAsync(s_safetyTimeout).ConfigureAwait(false), Is.True);
|
|
Assert.That(await itemsAdded.WaitAsync(s_safetyTimeout).ConfigureAwait(false), Is.True);
|
|
|
|
Assert.That(manager.AddCallCount, Is.EqualTo(1));
|
|
StubMonitoredItemCollection collection = manager.Subscription!.Collection;
|
|
Assert.That(collection.Count, Is.EqualTo(2u));
|
|
|
|
await subscription.DisposeAsync().ConfigureAwait(false);
|
|
Assert.That(await WithinTimeoutAsync(firstMove).ConfigureAwait(false), Is.False);
|
|
Assert.That(await WithinTimeoutAsync(secondMove).ConfigureAwait(false), Is.False);
|
|
await firstEnumerator.DisposeAsync().ConfigureAwait(false);
|
|
await secondEnumerator.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
[Test]
|
|
public async Task TakeUntilAsyncIsInclusiveOfMatchAsync()
|
|
{
|
|
var collected = new List<int>();
|
|
await foreach (int value in RangeAsync(1, 2, 3, 4).TakeUntilAsync(static v => v == 3))
|
|
{
|
|
collected.Add(value);
|
|
}
|
|
Assert.That(collected, Is.EqualTo(s_oneTwoThree));
|
|
}
|
|
|
|
[Test]
|
|
public void TakeUntilAsyncWithNullSourceThrowsArgumentNullException()
|
|
{
|
|
ArgumentNullException? ex = Assert.Throws<ArgumentNullException>(
|
|
() => _ = StreamingSubscriptionExtensions.TakeUntilAsync<int>(
|
|
null!, static v => true));
|
|
Assert.That(ex!.ParamName, Is.EqualTo("source"));
|
|
}
|
|
|
|
[Test]
|
|
public void TakeUntilAsyncWithNullPredicateThrowsArgumentNullException()
|
|
{
|
|
ArgumentNullException? ex = Assert.Throws<ArgumentNullException>(
|
|
() => _ = RangeAsync(1).TakeUntilAsync(null!));
|
|
Assert.That(ex!.ParamName, Is.EqualTo("predicate"));
|
|
}
|
|
|
|
[Test]
|
|
public async Task TakeAsyncYieldsExactCountAsync()
|
|
{
|
|
var collected = new List<int>();
|
|
await foreach (int value in RangeAsync(1, 2, 3, 4, 5).TakeAsync(2))
|
|
{
|
|
collected.Add(value);
|
|
}
|
|
Assert.That(collected, Is.EqualTo(s_oneTwo));
|
|
}
|
|
|
|
[Test]
|
|
public void TakeAsyncWithNonPositiveCountThrowsArgumentOutOfRangeException()
|
|
{
|
|
ArgumentOutOfRangeException? ex = Assert.Throws<ArgumentOutOfRangeException>(
|
|
() => _ = RangeAsync(1).TakeAsync(0));
|
|
Assert.That(ex!.ParamName, Is.EqualTo("count"));
|
|
}
|
|
|
|
[Test]
|
|
public void TakeAsyncWithNullSourceThrowsArgumentNullException()
|
|
{
|
|
ArgumentNullException? ex = Assert.Throws<ArgumentNullException>(
|
|
() => _ = StreamingSubscriptionExtensions.TakeAsync<int>(null!, 1));
|
|
Assert.That(ex!.ParamName, Is.EqualTo("source"));
|
|
}
|
|
|
|
[Test]
|
|
public async Task BufferedAsyncReturnsRequestedCountAsync()
|
|
{
|
|
IReadOnlyList<int> buffer = await RangeAsync(1, 2, 3, 4).BufferedAsync(3).ConfigureAwait(false);
|
|
Assert.That(buffer, Is.EqualTo(s_oneTwoThree));
|
|
}
|
|
|
|
[Test]
|
|
public async Task BufferedAsyncWithNullSourceThrowsArgumentNullExceptionAsync()
|
|
{
|
|
ArgumentNullException ex = await AwaitFaultAsync<ArgumentNullException>(
|
|
StreamingSubscriptionExtensions.BufferedAsync<int>(null!, 1).AsTask()).ConfigureAwait(false);
|
|
Assert.That(ex.ParamName, Is.EqualTo("source"));
|
|
}
|
|
|
|
[Test]
|
|
public async Task BufferedAsyncWithNonPositiveCountThrowsArgumentOutOfRangeExceptionAsync()
|
|
{
|
|
ArgumentOutOfRangeException ex = await AwaitFaultAsync<ArgumentOutOfRangeException>(
|
|
RangeAsync(1).BufferedAsync(0).AsTask()).ConfigureAwait(false);
|
|
Assert.That(ex.ParamName, Is.EqualTo("count"));
|
|
}
|
|
|
|
[Test]
|
|
public async Task TakeUntilAsyncForwardsCancellationToSourceEnumeratorAsync()
|
|
{
|
|
using var cts = new CancellationTokenSource();
|
|
var probe = new CancellationProbeEnumerable();
|
|
Task consumption = ConsumeAsync(
|
|
probe.TakeUntilAsync(static _ => false, cts.Token));
|
|
|
|
Assert.That(probe.EnumeratorCreated.Wait(s_safetyTimeout), Is.True);
|
|
cts.Cancel();
|
|
await AwaitFaultAsync<OperationCanceledException>(consumption)
|
|
.ConfigureAwait(false);
|
|
Assert.That(probe.EnumeratorCancellationObserved, Is.True);
|
|
}
|
|
|
|
[Test]
|
|
public async Task TakeAsyncForwardsCancellationToSourceEnumeratorAsync()
|
|
{
|
|
using var cts = new CancellationTokenSource();
|
|
var probe = new CancellationProbeEnumerable();
|
|
Task consumption = ConsumeAsync(probe.TakeAsync(1, cts.Token));
|
|
|
|
Assert.That(probe.EnumeratorCreated.Wait(s_safetyTimeout), Is.True);
|
|
cts.Cancel();
|
|
await AwaitFaultAsync<OperationCanceledException>(consumption)
|
|
.ConfigureAwait(false);
|
|
Assert.That(probe.EnumeratorCancellationObserved, Is.True);
|
|
}
|
|
|
|
[Test]
|
|
public async Task BufferedAsyncForwardsCancellationToSourceEnumeratorAsync()
|
|
{
|
|
using var cts = new CancellationTokenSource();
|
|
var probe = new CancellationProbeEnumerable();
|
|
Task consumption = ConsumeBufferedAsync(probe, cts.Token);
|
|
|
|
Assert.That(probe.EnumeratorCreated.Wait(s_safetyTimeout), Is.True);
|
|
cts.Cancel();
|
|
await AwaitFaultAsync<OperationCanceledException>(consumption)
|
|
.ConfigureAwait(false);
|
|
Assert.That(probe.EnumeratorCancellationObserved, Is.True);
|
|
}
|
|
|
|
[Test]
|
|
public void WithTimeoutAsyncWithNullSourceThrowsArgumentNullException()
|
|
{
|
|
ArgumentNullException? ex = Assert.Throws<ArgumentNullException>(
|
|
() => _ = StreamingSubscriptionExtensions.WithTimeoutAsync<int>(
|
|
null!, TimeSpan.FromSeconds(1)));
|
|
Assert.That(ex!.ParamName, Is.EqualTo("source"));
|
|
}
|
|
|
|
[Test]
|
|
public async Task WithTimeoutAsyncPassesThroughItemsBeforeTimeoutAsync()
|
|
{
|
|
var collected = new List<int>();
|
|
await foreach (int value in RangeAsync(1, 2, 3)
|
|
.WithTimeoutAsync(TimeSpan.FromSeconds(30)))
|
|
{
|
|
collected.Add(value);
|
|
}
|
|
Assert.That(collected, Is.EqualTo(s_oneTwoThree));
|
|
}
|
|
|
|
private static (IAsyncEnumerator<DataValueChange> Enumerator, Task<bool> Move)
|
|
StartDataChanges(StreamingSubscription subscription, NodeId nodeId, CancellationToken ct)
|
|
{
|
|
IAsyncEnumerator<DataValueChange> enumerator =
|
|
subscription.SubscribeDataChangesAsync(nodeId, ct: ct).GetAsyncEnumerator(ct);
|
|
return (enumerator, enumerator.MoveNextAsync().AsTask());
|
|
}
|
|
|
|
private static async Task FireDataChangeAsync(
|
|
StubSubscriptionManager manager, DataValueChange change)
|
|
{
|
|
await manager.Handler!.OnDataChangeNotificationAsync(
|
|
manager.Subscription!, 1u, s_publishTime,
|
|
new ReadOnlyMemory<DataValueChange>([change]),
|
|
PublishState.None, s_emptyStringTable).ConfigureAwait(false);
|
|
}
|
|
|
|
private static async Task FireEventAsync(
|
|
StubSubscriptionManager manager, EventNotification notification)
|
|
{
|
|
await manager.Handler!.OnEventDataNotificationAsync(
|
|
manager.Subscription!, 1u, s_publishTime,
|
|
new ReadOnlyMemory<EventNotification>([notification]),
|
|
PublishState.None, s_emptyStringTable).ConfigureAwait(false);
|
|
}
|
|
|
|
private static async Task FireEventsAsync(
|
|
StubSubscriptionManager manager,
|
|
params EventNotification[] notifications)
|
|
{
|
|
await manager.Handler!.OnEventDataNotificationAsync(
|
|
manager.Subscription!, 1u, s_publishTime,
|
|
new ReadOnlyMemory<EventNotification>(notifications),
|
|
PublishState.None, s_emptyStringTable).ConfigureAwait(false);
|
|
}
|
|
|
|
private static async Task DrainAsync<T>(
|
|
StreamingSubscription subscription, IAsyncEnumerator<T> enumerator, Task<bool> move)
|
|
{
|
|
await subscription.DisposeAsync().ConfigureAwait(false);
|
|
Assert.That(await WithinTimeoutAsync(move).ConfigureAwait(false), Is.False);
|
|
await enumerator.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
|
|
private static async Task<T> WithinTimeoutAsync<T>(Task<T> task)
|
|
{
|
|
using var cts = new CancellationTokenSource();
|
|
var delay = Task.Delay(s_safetyTimeout, cts.Token);
|
|
Task winner = await Task.WhenAny(task, delay).ConfigureAwait(false);
|
|
Assert.That(winner, Is.SameAs(task),
|
|
"operation did not complete within the safety timeout");
|
|
cts.Cancel();
|
|
return await task.ConfigureAwait(false);
|
|
}
|
|
|
|
private static async Task<TException> AwaitFaultAsync<TException>(Task task)
|
|
where TException : Exception
|
|
{
|
|
using var cts = new CancellationTokenSource();
|
|
var delay = Task.Delay(s_safetyTimeout, cts.Token);
|
|
Task winner = await Task.WhenAny(task, delay).ConfigureAwait(false);
|
|
Assert.That(winner, Is.SameAs(task),
|
|
"operation did not fault within the safety timeout");
|
|
cts.Cancel();
|
|
|
|
TException? caught = null;
|
|
try
|
|
{
|
|
await task.ConfigureAwait(false);
|
|
}
|
|
catch (TException ex)
|
|
{
|
|
caught = ex;
|
|
}
|
|
Assert.That(caught, Is.Not.Null, "expected exception was not thrown");
|
|
return caught!;
|
|
}
|
|
|
|
private static async Task ConsumeAsync(IAsyncEnumerable<int> source)
|
|
{
|
|
await foreach (int _ in source.ConfigureAwait(false))
|
|
{
|
|
}
|
|
}
|
|
|
|
private static async Task ConsumeBufferedAsync(
|
|
IAsyncEnumerable<int> source,
|
|
CancellationToken ct)
|
|
{
|
|
await source.BufferedAsync(1, ct).ConfigureAwait(false);
|
|
}
|
|
|
|
private static async IAsyncEnumerable<int> RangeAsync(params int[] values)
|
|
{
|
|
foreach (int value in values)
|
|
{
|
|
await Task.Yield();
|
|
yield return value;
|
|
}
|
|
}
|
|
|
|
private sealed class CancellationProbeEnumerable : IAsyncEnumerable<int>
|
|
{
|
|
public ManualResetEventSlim EnumeratorCreated { get; } = new();
|
|
|
|
public bool EnumeratorCancellationObserved { get; private set; }
|
|
|
|
public IAsyncEnumerator<int> GetAsyncEnumerator(
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
return new CancellationProbeEnumerator(this, cancellationToken);
|
|
}
|
|
|
|
private sealed class CancellationProbeEnumerator : IAsyncEnumerator<int>
|
|
{
|
|
private readonly CancellationProbeEnumerable m_owner;
|
|
private readonly CancellationToken m_ct;
|
|
|
|
public CancellationProbeEnumerator(
|
|
CancellationProbeEnumerable owner,
|
|
CancellationToken ct)
|
|
{
|
|
m_owner = owner;
|
|
m_ct = ct;
|
|
owner.EnumeratorCreated.Set();
|
|
}
|
|
|
|
public int Current => 0;
|
|
|
|
public ValueTask DisposeAsync()
|
|
{
|
|
return default;
|
|
}
|
|
|
|
public async ValueTask<bool> MoveNextAsync()
|
|
{
|
|
try
|
|
{
|
|
await Task.Delay(Timeout.Infinite, m_ct).ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
m_owner.EnumeratorCancellationObserved = true;
|
|
throw;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
|
|
private sealed class StubSubscriptionManager : ISubscriptionManager
|
|
{
|
|
private readonly bool m_failAdd;
|
|
private readonly bool m_failItemAdd;
|
|
private readonly bool m_failDispose;
|
|
private readonly bool m_failRemove;
|
|
private StubSubscription? m_subscription;
|
|
|
|
public StubSubscriptionManager(
|
|
bool failAdd = false,
|
|
bool failItemAdd = false,
|
|
bool failDispose = false,
|
|
bool failRemove = false)
|
|
{
|
|
m_failAdd = failAdd;
|
|
m_failItemAdd = failItemAdd;
|
|
m_failDispose = failDispose;
|
|
m_failRemove = failRemove;
|
|
}
|
|
|
|
public int AddCallCount { get; private set; }
|
|
|
|
public ISubscriptionNotificationHandler? Handler { get; private set; }
|
|
|
|
public StubSubscription? Subscription => m_subscription;
|
|
|
|
public SubscriptionOptions? CapturedOptions { get; private set; }
|
|
|
|
public IDisposable? CapturedOnChange { get; private set; }
|
|
|
|
public Action? OnAddEntered { get; init; }
|
|
|
|
public Action? AddGate { get; init; }
|
|
|
|
public Action? OnItemAdded { get; init; }
|
|
|
|
public ISubscription Add(
|
|
ISubscriptionNotificationHandler handler,
|
|
IOptionsMonitor<SubscriptionOptions> options)
|
|
{
|
|
AddCallCount++;
|
|
Handler = handler;
|
|
CapturedOptions = options.Get(null);
|
|
CapturedOnChange = options.OnChange(static (_, _) => { });
|
|
if (m_failAdd)
|
|
{
|
|
throw new InvalidOperationException("subscription create failed");
|
|
}
|
|
OnAddEntered?.Invoke();
|
|
AddGate?.Invoke();
|
|
m_subscription ??= new StubSubscription(
|
|
m_failItemAdd, m_failDispose, m_failRemove, OnItemAdded);
|
|
return m_subscription;
|
|
}
|
|
|
|
public DiagnosticsMasks ReturnDiagnostics
|
|
{
|
|
get => throw new NotSupportedException();
|
|
set => throw new NotSupportedException();
|
|
}
|
|
|
|
public int MaxPublishWorkerCount
|
|
{
|
|
get => throw new NotSupportedException();
|
|
set => throw new NotSupportedException();
|
|
}
|
|
|
|
public int MinPublishWorkerCount
|
|
{
|
|
get => throw new NotSupportedException();
|
|
set => throw new NotSupportedException();
|
|
}
|
|
|
|
public bool PoolNotifications
|
|
{
|
|
get => throw new NotSupportedException();
|
|
set => throw new NotSupportedException();
|
|
}
|
|
|
|
public int PublishWorkerCount => throw new NotSupportedException();
|
|
|
|
public int GoodPublishRequestCount => throw new NotSupportedException();
|
|
|
|
public int BadPublishRequestCount => throw new NotSupportedException();
|
|
|
|
public long MissingMessageCount => throw new NotSupportedException();
|
|
|
|
public long RepublishMessageCount => throw new NotSupportedException();
|
|
|
|
public int Count => throw new NotSupportedException();
|
|
|
|
public IEnumerable<ISubscription> Items => throw new NotSupportedException();
|
|
|
|
public ValueTask SaveAsync(
|
|
Stream stream,
|
|
IServiceMessageContext messageContext,
|
|
IEnumerable<ISubscription>? subscriptions = null,
|
|
CancellationToken ct = default)
|
|
{
|
|
throw new NotSupportedException();
|
|
}
|
|
|
|
public ValueTask<IReadOnlyList<ISubscription>> LoadAsync(
|
|
Stream stream,
|
|
IServiceMessageContext messageContext,
|
|
Func<string, ISubscriptionNotificationHandler> handlerFactory,
|
|
bool transferSubscriptions = false,
|
|
CancellationToken ct = default)
|
|
{
|
|
throw new NotSupportedException();
|
|
}
|
|
}
|
|
|
|
private sealed class StubSubscription : ISubscription
|
|
{
|
|
private readonly bool m_failDispose;
|
|
private int m_disposeCount;
|
|
|
|
public StubSubscription(
|
|
bool failItemAdd, bool failDispose, bool failRemove, Action? onItemAdded)
|
|
{
|
|
m_failDispose = failDispose;
|
|
Collection = new StubMonitoredItemCollection(failItemAdd, failRemove, onItemAdded);
|
|
}
|
|
|
|
public StubMonitoredItemCollection Collection { get; }
|
|
|
|
public IMonitoredItemCollection MonitoredItems => Collection;
|
|
|
|
public int DisposeCount => m_disposeCount;
|
|
|
|
public ValueTask DisposeAsync()
|
|
{
|
|
Interlocked.Increment(ref m_disposeCount);
|
|
if (m_failDispose)
|
|
{
|
|
throw new InvalidOperationException("dispose failed");
|
|
}
|
|
return default;
|
|
}
|
|
|
|
public bool Created => throw new NotSupportedException();
|
|
|
|
public TimeSpan CurrentPublishingInterval => throw new NotSupportedException();
|
|
|
|
public byte CurrentPriority => throw new NotSupportedException();
|
|
|
|
public uint CurrentLifetimeCount => throw new NotSupportedException();
|
|
|
|
public uint CurrentKeepAliveCount => throw new NotSupportedException();
|
|
|
|
public bool CurrentPublishingEnabled => throw new NotSupportedException();
|
|
|
|
public uint CurrentMaxNotificationsPerPublish => throw new NotSupportedException();
|
|
|
|
public long MissingMessageCount => throw new NotSupportedException();
|
|
|
|
public long RepublishMessageCount => throw new NotSupportedException();
|
|
|
|
public ValueTask ConditionRefreshAsync(CancellationToken ct = default)
|
|
{
|
|
throw new NotSupportedException();
|
|
}
|
|
|
|
public ValueTask RecreateAsync(CancellationToken ct = default)
|
|
{
|
|
throw new NotSupportedException();
|
|
}
|
|
|
|
public ValueTask<TimeSpan> SetAsDurableAsync(
|
|
TimeSpan lifetime, CancellationToken ct = default)
|
|
{
|
|
throw new NotSupportedException();
|
|
}
|
|
|
|
public ValueTask<SetTriggeringResult> SetTriggeringAsync(
|
|
IMonitoredItem triggeringItem,
|
|
IReadOnlyCollection<IMonitoredItem>? linksToAdd = null,
|
|
IReadOnlyCollection<IMonitoredItem>? linksToRemove = null,
|
|
CancellationToken ct = default)
|
|
{
|
|
throw new NotSupportedException();
|
|
}
|
|
}
|
|
|
|
private sealed class StubMonitoredItemCollection : IMonitoredItemCollection
|
|
{
|
|
private readonly Lock m_lock = new();
|
|
private readonly Dictionary<uint, StubMonitoredItem> m_items = [];
|
|
private readonly List<StubMonitoredItem> m_added = [];
|
|
private readonly List<uint> m_removed = [];
|
|
private readonly List<uint> m_removeAttempts = [];
|
|
private readonly bool m_failItemAdd;
|
|
private readonly bool m_failRemove;
|
|
private readonly Action? m_onItemAdded;
|
|
private uint m_nextHandle = 1000;
|
|
|
|
public StubMonitoredItemCollection(
|
|
bool failItemAdd, bool failRemove, Action? onItemAdded)
|
|
{
|
|
m_failItemAdd = failItemAdd;
|
|
m_failRemove = failRemove;
|
|
m_onItemAdded = onItemAdded;
|
|
}
|
|
|
|
public uint Count
|
|
{
|
|
get
|
|
{
|
|
lock (m_lock)
|
|
{
|
|
return (uint)m_items.Count;
|
|
}
|
|
}
|
|
}
|
|
|
|
public IEnumerable<IMonitoredItem> Items
|
|
{
|
|
get
|
|
{
|
|
lock (m_lock)
|
|
{
|
|
return [.. m_items.Values];
|
|
}
|
|
}
|
|
}
|
|
|
|
public StubMonitoredItem[] Added
|
|
{
|
|
get
|
|
{
|
|
lock (m_lock)
|
|
{
|
|
return [.. m_added];
|
|
}
|
|
}
|
|
}
|
|
|
|
public IReadOnlyList<uint> RemovedHandles
|
|
{
|
|
get
|
|
{
|
|
lock (m_lock)
|
|
{
|
|
return [.. m_removed];
|
|
}
|
|
}
|
|
}
|
|
|
|
public IReadOnlyList<uint> RemoveAttempts
|
|
{
|
|
get
|
|
{
|
|
lock (m_lock)
|
|
{
|
|
return [.. m_removeAttempts];
|
|
}
|
|
}
|
|
}
|
|
|
|
public bool ContainsHandle(uint clientHandle)
|
|
{
|
|
lock (m_lock)
|
|
{
|
|
return m_items.ContainsKey(clientHandle);
|
|
}
|
|
}
|
|
|
|
public bool TryAdd(
|
|
string name,
|
|
IOptionsMonitor<MonitoredItemOptions> options,
|
|
out IMonitoredItem? monitoredItem)
|
|
{
|
|
if (m_failItemAdd)
|
|
{
|
|
monitoredItem = null;
|
|
return false;
|
|
}
|
|
lock (m_lock)
|
|
{
|
|
var item = new StubMonitoredItem(m_nextHandle++, name, options.CurrentValue);
|
|
m_items[item.ClientHandle] = item;
|
|
m_added.Add(item);
|
|
monitoredItem = item;
|
|
}
|
|
m_onItemAdded?.Invoke();
|
|
return true;
|
|
}
|
|
|
|
public bool TryRemove(uint clientHandle)
|
|
{
|
|
lock (m_lock)
|
|
{
|
|
m_removeAttempts.Add(clientHandle);
|
|
if (m_failRemove)
|
|
{
|
|
throw new InvalidOperationException("remove failed");
|
|
}
|
|
m_removed.Add(clientHandle);
|
|
return m_items.Remove(clientHandle);
|
|
}
|
|
}
|
|
|
|
public bool TryGetMonitoredItemByClientHandle(
|
|
uint clientHandle, out IMonitoredItem? monitoredItem)
|
|
{
|
|
throw new NotSupportedException();
|
|
}
|
|
|
|
public bool TryGetMonitoredItemByName(string name, out IMonitoredItem? monitoredItem)
|
|
{
|
|
throw new NotSupportedException();
|
|
}
|
|
|
|
public IReadOnlyList<IMonitoredItem> Update(
|
|
IReadOnlyList<(string Name,
|
|
IOptionsMonitor<MonitoredItemOptions> Options)> state)
|
|
{
|
|
throw new NotSupportedException();
|
|
}
|
|
}
|
|
|
|
private sealed class StubMonitoredItem : IMonitoredItem
|
|
{
|
|
public StubMonitoredItem(uint clientHandle, string name, MonitoredItemOptions options)
|
|
{
|
|
ClientHandle = clientHandle;
|
|
Name = name;
|
|
Options = options;
|
|
}
|
|
|
|
public uint ClientHandle { get; }
|
|
|
|
public string Name { get; }
|
|
|
|
public MonitoredItemOptions Options { get; }
|
|
|
|
public uint Order => throw new NotSupportedException();
|
|
|
|
public uint ServerId => throw new NotSupportedException();
|
|
|
|
public bool Created => throw new NotSupportedException();
|
|
|
|
public ServiceResult Error => throw new NotSupportedException();
|
|
|
|
public MonitoringFilterResult? FilterResult => throw new NotSupportedException();
|
|
|
|
public MonitoringMode CurrentMonitoringMode => throw new NotSupportedException();
|
|
|
|
public TimeSpan CurrentSamplingInterval => throw new NotSupportedException();
|
|
|
|
public uint CurrentQueueSize => throw new NotSupportedException();
|
|
|
|
public IEnumerable<IMonitoredItem> TriggeringItems => throw new NotSupportedException();
|
|
|
|
public IEnumerable<IMonitoredItem> TriggeredItems => throw new NotSupportedException();
|
|
|
|
public ValueTask ConditionRefreshAsync(CancellationToken ct = default)
|
|
{
|
|
throw new NotSupportedException();
|
|
}
|
|
}
|
|
}
|
|
}
|