Files
Cristi Pogacean 89c1275d9d Fix managed browse closed-channel and cancellation handling (#4774)
# Description

Fix managed browse failure reporting when the session's channel has
closed or the caller has already cancelled the operation.

- Use the existing checked `TransportChannel` accessor in
`ClientBase.MessageContext`, so a closed channel reports
`ServiceResultException(BadSecureChannelClosed)` instead of
`NullReferenceException` during `Browser` construction.
- Check cancellation at entry to
`SessionClientExtensions.ManagedBrowseAsync` and the array-based
`Browser.BrowseAsync`, before session access or request submission.
- Document failure semantics and add unit plus real client/server
regression tests for closed channels, pre-cancelled empty/non-empty
inputs, Browse/BrowseNext request failures and cancellation, and mixed
per-node results.
- Preserve existing propagation of request exceptions and the per-node
result/error contract. No dependency, analyzer configuration, or public
API signature changes.

The real-session before-fix run reproduced three failures (closed
channel, and pre-cancelled closed channel with empty/non-empty input).
All corresponding regressions pass after the fix.

## Related Issues

Fix the closed-channel and pre-cancelled managed-browse behavior
described in the linked bug report.

_If this is a relatively large or complex change, a design must have
been discussed in the related tracking issue and signed off (which
becomes the Architectural Decision Record (ADR))._

- Fixes #4773

## Checklist

_Put an `x` in the boxes that apply. You can complete these step by step
after opening the PR._

- [x] 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.
- [x] 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.
- [ ] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [ ] I have addressed **all** PR feedback received.

## Validation

Windows, .NET SDK 10.0.401. **134 targeted test cases passed**,
including existing browser and continuation-point regressions:

| Suite | net10.0 | net48 |
| --- | ---: | ---: |
| BrowserTests + BrowserAuditRegressionTests | 27 passed | 27 passed |
| ClientBaseTests | 18 passed | 18 passed |
| ContinuationPointInBatchTest managed-browse cases | 22 passed | 22
passed |
| Total | **67 passed** | **67 passed** |

Tests were added and prove the fix, but coverage percentages were not
collected; the combined tests/coverage checklist item is therefore left
unchecked. CLA status has not been independently verified.

### Exact test commands and results

Commands ran from the repository root. Test output was redirected to
local logs.

```powershell
# PASS: 27 tests.
dotnet test Tests\Opc.Ua.Client.Tests\Opc.Ua.Client.Tests.csproj --no-restore -f net10.0 -p:CustomTestTarget=net10.0 -p:NuGetAudit=false '-p:WarningsNotAsErrors=CA2000%3BCA2007' --filter "FullyQualifiedName~Opc.Ua.Client.Tests.BrowserTests|FullyQualifiedName~BrowserAuditRegressionTests" --logger "console;verbosity=normal"

# PASS: 18 tests.
dotnet test Tests\Opc.Ua.Core.Tests\Opc.Ua.Core.Tests.csproj --no-restore -f net10.0 -p:CustomTestTarget=net10.0 -p:NuGetAudit=false '-p:WarningsNotAsErrors=CA2000%3BCA2007' --filter "FullyQualifiedName~ClientBaseTests" --logger "console;verbosity=normal"

# PASS: 22 tests, using the freshly rebuilt net10.0 test binaries.
dotnet test Tests\Opc.Ua.Sessions.Tests\Opc.Ua.Sessions.Tests.csproj --no-build --no-restore -f net10.0 --filter "FullyQualifiedName~ContinuationPointInBatchTest&Name~ManagedBrowse" --logger "console;verbosity=normal"

# PASS: 27 tests.
dotnet test Tests\Opc.Ua.Client.Tests\Opc.Ua.Client.Tests.csproj -f net48 -p:CustomTestTarget=net48 -p:NuGetAudit=false '-p:WarningsNotAsErrors=CA2000%3BCA2007' --filter "FullyQualifiedName~Opc.Ua.Client.Tests.BrowserTests|FullyQualifiedName~BrowserAuditRegressionTests" --logger "console;verbosity=normal"

# PASS: 18 tests.
dotnet test Tests\Opc.Ua.Core.Tests\Opc.Ua.Core.Tests.csproj -f net48 -p:CustomTestTarget=net48 -p:NuGetAudit=false '-p:WarningsNotAsErrors=CA2000%3BCA2007' --filter "FullyQualifiedName~ClientBaseTests" --logger "console;verbosity=normal"

# PASS: 22 tests.
dotnet test Tests\Opc.Ua.Sessions.Tests\Opc.Ua.Sessions.Tests.csproj -f net48 -p:CustomTestTarget=net48 -p:NuGetAudit=false '-p:WarningsNotAsErrors=CA2000%3BCA2007' --filter "FullyQualifiedName~ContinuationPointInBatchTest&Name~ManagedBrowse" --logger "console;verbosity=normal"
```

### Production build and patch checks

```powershell
# PASS: production Client/Core dependency build, 0 warnings and 0 errors.
# Normal warnings-as-errors policy; no analyzer downgrades.
dotnet build src\Opc.Ua.Client\Opc.Ua.Client.csproj --no-restore -f net48 -p:CustomTestTarget=net48 -p:NuGetAudit=false --verbosity minimal

# PASS: no whitespace errors.
git diff --check
```

All six changed files retain CRLF line endings. No build/analyzer
diagnostics were reported in the changed files.

### Validation limitations

- Initial unmodified-policy test builds failed on unavailable NuGet
audit data (`NU1900`) and unrelated existing `CA2000`/`CA2007`
diagnostics in test code.
- The test commands use the documented offline `NuGetAudit=false` option
and command-only analyzer downgrades. TODO: remove those command-only
downgrades when the existing certificate/transport test diagnostics are
fixed. Repository build/analyzer settings are unchanged.
- An initial full `ContinuationPointInBatchTest` fixture invocation
rebuilt the net10.0 binaries but was stopped during expensive existing
node-cache traversals. It was replaced by the passing managed-browse
subset above.
- The complete `UA.slnx` suites were **not run**. Full-solution
validation, coverage measurement, and CI/CodeQL results remain
outstanding.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-14 08:43:20 +02:00

961 lines
41 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.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using NUnit.Framework;
using NUnit.Framework.Internal;
using Opc.Ua.Client;
using Opc.Ua.Client.TestFramework;
using Opc.Ua.Server.TestFramework;
using ContinuationPointPolicy = Opc.Ua.Client.ContinuationPointPolicy;
using ISession = Opc.Ua.Client.ISession;
namespace Opc.Ua.Sessions.Tests
{
public class ManagedBrowseExpectedResultValues
{
public uint InputMaxNumberOfContinuationPoints { get; set; }
public uint InputMaxNumberOfReferencesPerNode { get; set; }
public int ExpectedNumberOfPasses { get; set; }
public List<int> ExpectedNumberOfBadNoCPSCs { get; set; } = null!;
}
public class ManagedBrowseTestDataProvider : IFormattable
{
public uint MaxNumberOfContinuationPoints { get; set; }
public uint MaxNumberOfReferencesPerNode { get; set; }
public int ExpectedNumberOfPasses { get; set; }
public List<int> ExpectedNumberOfBadNoCPSCs { get; set; } = null!;
public string ToString(string? format, IFormatProvider? formatProvider)
{
return $"{MaxNumberOfContinuationPoints}:{MaxNumberOfReferencesPerNode}";
}
}
/// <summary>
/// Client tests.
/// </summary>
[TestFixture]
[Category("Client")]
[Category("ManagedBrowseWithBrowseNext")]
[SetCulture("en-us")]
[SetUICulture("en-us")]
[TestFixtureSource(nameof(CPFixtureArgs))]
[MemoryDiagnoser]
[DisassemblyDiagnoser]
public class ContinuationPointInBatchTest : ClientTestFramework
{
public static readonly object[] CPFixtureArgs = [new object[] { Utils.UriSchemeOpcTcp }];
[DatapointSource]
public IEnumerable<ManagedBrowseTestDataProvider> ManagedBrowseTestDataValues()
{
yield return new ManagedBrowseTestDataProvider
{
MaxNumberOfContinuationPoints = 2,
MaxNumberOfReferencesPerNode = 10,
ExpectedNumberOfPasses = 5,
ExpectedNumberOfBadNoCPSCs = [15, 9, 5, 3, 1]
};
yield return new ManagedBrowseTestDataProvider
{
MaxNumberOfContinuationPoints = 4,
MaxNumberOfReferencesPerNode = 10,
ExpectedNumberOfPasses = 2,
ExpectedNumberOfBadNoCPSCs = [5, 1]
};
yield return new ManagedBrowseTestDataProvider
{
MaxNumberOfContinuationPoints = 20,
MaxNumberOfReferencesPerNode = 50,
ExpectedNumberOfPasses = 1,
ExpectedNumberOfBadNoCPSCs = []
};
yield return new ManagedBrowseTestDataProvider
{
MaxNumberOfContinuationPoints = 5,
MaxNumberOfReferencesPerNode = 10,
ExpectedNumberOfPasses = 1,
ExpectedNumberOfBadNoCPSCs = []
};
}
public ReferenceServerWithLimits ReferenceServerWithLimits { get; set; } = null!;
public ServerFixture<ReferenceServerWithLimits> ServerFixtureWithLimits { get; set; } = null!;
public override async Task CreateReferenceServerFixtureAsync(
bool enableTracing,
bool disableActivityLogging,
bool securityNone)
{
// start Ref server
ServerFixtureWithLimits = new ServerFixture<ReferenceServerWithLimits>(
t => new ReferenceServerWithLimits(t),
enableTracing,
disableActivityLogging)
{
UriScheme = UriScheme,
SecurityNone = securityNone,
AutoAccept = true,
AllNodeManagers = true,
OperationLimits = true
};
await ServerFixtureWithLimits.LoadConfigurationAsync(PkiRoot).ConfigureAwait(false);
ServerFixtureWithLimits.Config.TransportQuotas!.MaxMessageSize
= TransportQuotaMaxMessageSize;
ServerFixtureWithLimits.Config.TransportQuotas.MaxByteStringLength
= ServerFixtureWithLimits
.Config
.TransportQuotas
.MaxStringLength = TransportQuotaMaxStringLength;
ServerFixtureWithLimits.Config.ServerConfiguration!.UserTokenPolicies +=
new UserTokenPolicy(UserTokenType.UserName);
ServerFixtureWithLimits.Config.ServerConfiguration.UserTokenPolicies +=
new UserTokenPolicy(UserTokenType.Certificate);
ServerFixtureWithLimits.Config.ServerConfiguration.UserTokenPolicies +=
new UserTokenPolicy(UserTokenType.IssuedToken)
{
IssuedTokenType = Profiles.JwtUserToken
};
ServerFixtureWithLimits.Config.ServerConfiguration.MaxBrowseContinuationPoints = 2;
ServerFixtureWithLimits.Config.ServerConfiguration.OperationLimits.MaxNodesPerBrowse
= 5;
ReferenceServerWithLimits = await ServerFixtureWithLimits.StartAsync()
.ConfigureAwait(false);
ReferenceServerWithLimits.TokenValidator = TokenValidator;
ReferenceServer = ReferenceServerWithLimits;
ServerFixturePort = ServerFixtureWithLimits.Port;
}
public ContinuationPointInBatchTest(string uriScheme = Utils.UriSchemeOpcTcp)
: base(uriScheme)
{
}
public ContinuationPointInBatchTest()
{
}
/// <summary>
/// Set up a Server and a Client instance.
/// </summary>
[OneTimeSetUp]
public override Task OneTimeSetUpAsync()
{
SupportsExternalServerUrl = true;
// create a new session for every test
SingleSession = false;
return OneTimeSetUpCoreAsync(false, false, false, true);
}
/// <summary>
/// Tear down the Server and the Client.
/// </summary>
[OneTimeTearDown]
public override async Task OneTimeTearDownAsync()
{
if (Session != null)
{
await Session.CloseAsync(5000, true).ConfigureAwait(false);
Session.Dispose();
Session = null!;
}
if (ServerFixtureWithLimits != null)
{
await ServerFixtureWithLimits.StopAsync().ConfigureAwait(false);
}
ClientFixture?.Dispose();
if (!string.IsNullOrEmpty(PkiRoot) && Directory.Exists(PkiRoot))
{
Directory.Delete(PkiRoot, true);
}
}
/// <summary>
/// Test setup.
/// </summary>
[SetUp]
public override async Task SetUpAsync()
{
await base.SetUpAsync().ConfigureAwait(false);
Session.NodeCache.Clear();
}
/// <summary>
/// Test teardown.
/// </summary>
[TearDown]
public override Task TearDownAsync()
{
return base.TearDownAsync();
}
/// <summary>
/// Global Setup for benchmarks.
/// </summary>
[GlobalSetup]
public override void GlobalSetup()
{
base.GlobalSetup();
}
/// <summary>
/// Global cleanup for benchmarks.
/// </summary>
[GlobalCleanup]
public override void GlobalCleanup()
{
base.GlobalCleanup();
}
/// <summary>
/// A closed channel must fail the managed browse instead of returning
/// empty references with a Good status.
/// </summary>
[Test]
public async Task ManagedBrowsePropagatesClosedChannelAsync()
{
await Session.CloseAsync(CancellationToken.None).ConfigureAwait(false);
await Assert.ThatAsync(
() => Session.ManagedBrowseAsync(
null, null, [ObjectIds.RootFolder], uint.MaxValue, BrowseDirection.Forward,
ReferenceTypeIds.HierarchicalReferences, true, 0),
Throws.TypeOf<ServiceResultException>()
.With.Property(nameof(ServiceResultException.StatusCode))
.EqualTo((StatusCode)StatusCodes.BadSecureChannelClosed)).ConfigureAwait(false);
}
/// <summary>
/// A pre-cancelled browse must report cancellation even with no nodes
/// or when the channel has already closed.
/// </summary>
[TestCase(false, false)]
[TestCase(false, true)]
[TestCase(true, false)]
[TestCase(true, true)]
public async Task ManagedBrowsePropagatesCancellationAsync(bool empty, bool closeChannel)
{
if (closeChannel)
{
await Session.CloseAsync(CancellationToken.None).ConfigureAwait(false);
}
using var cancellation = new CancellationTokenSource();
cancellation.Cancel();
ArrayOf<NodeId> nodes = empty ? [] : [ObjectIds.RootFolder];
await Assert.ThatAsync(
() => Session.ManagedBrowseAsync(
null, null, nodes, uint.MaxValue, BrowseDirection.Forward,
ReferenceTypeIds.HierarchicalReferences, true, 0, cancellation.Token),
Throws.InstanceOf<OperationCanceledException>()
.With.Property(nameof(OperationCanceledException.CancellationToken))
.EqualTo(cancellation.Token)).ConfigureAwait(false);
}
/// <summary>
/// Per-node failures remain in their original slots without failing
/// successful nodes or throwing a request-level exception.
/// </summary>
[Test]
public async Task ManagedBrowsePreservesPerNodeResultsAsync()
{
(ArrayOf<ArrayOf<ReferenceDescription>> references, ArrayOf<ServiceResult> errors) =
await Session.ManagedBrowseAsync(
null,
null,
[ObjectIds.RootFolder, new NodeId("missing-managed-browse-node", ushort.MaxValue)],
uint.MaxValue,
BrowseDirection.Forward,
ReferenceTypeIds.HierarchicalReferences,
true,
0).ConfigureAwait(false);
Assert.Multiple(() =>
{
Assert.That(references.Count, Is.EqualTo(2));
Assert.That(errors.Count, Is.EqualTo(2));
Assert.That(references[0].IsEmpty, Is.False);
Assert.That(errors[0].StatusCode, Is.EqualTo((StatusCode)StatusCodes.Good));
Assert.That(references[1].IsEmpty, Is.True);
Assert.That(errors[1].StatusCode, Is.EqualTo((StatusCode)StatusCodes.BadNodeIdUnknown));
});
}
/// <summary>
/// <para>
/// This test is taken from the node cache unit test.
/// Instead of the original test, there are now restrctions
/// on the maximum number of continuation points supported
/// by the server, and the maximum number of nodes allowed
/// in a browse service call.
/// </para>
/// <para>Browse all variables in the objects folder.</para>
/// </summary>
[Theory]
[Order(100)]
public async Task MBNodeCacheBrowseAllVariablesAsync(ManagedBrowseTestDataProvider testData)
{
ISession theSession = Session;
theSession.NodeCache.Clear();
theSession.ContinuationPointPolicy = ContinuationPointPolicy.Default;
// the ExpectedNumber* parameters are not relevant/correct for this test.
var pass1ExpectedResults = new ManagedBrowseExpectedResultValues
{
InputMaxNumberOfContinuationPoints = testData.MaxNumberOfContinuationPoints,
InputMaxNumberOfReferencesPerNode = testData.MaxNumberOfReferencesPerNode,
ExpectedNumberOfPasses = testData.ExpectedNumberOfPasses,
ExpectedNumberOfBadNoCPSCs = testData.ExpectedNumberOfBadNoCPSCs
};
var result = new List<INode>();
var nodesToBrowse = new List<ExpandedNodeId> { ObjectIds.ObjectsFolder };
await Session.FetchTypeTreeAsync(ReferenceTypeIds.References).ConfigureAwait(false);
while (nodesToBrowse.Count > 0)
{
var nextNodesToBrowse = new List<ExpandedNodeId>();
foreach (ExpandedNodeId node in nodesToBrowse)
{
try
{
ArrayOf<INode> organizers = await Session.NodeCache.FindReferencesAsync(
node,
ReferenceTypeIds.HierarchicalReferences,
false,
true).ConfigureAwait(false);
nextNodesToBrowse.AddRange(organizers.ConvertAll(n => n.NodeId));
ArrayOf<INode> objectNodes = organizers.Filter(n => n is ObjectNode);
ArrayOf<INode> variableNodes = organizers.Filter(n => n is VariableNode);
result.AddRange(variableNodes);
}
catch (ServiceResultException sre)
{
if (sre.StatusCode == StatusCodes.BadUserAccessDenied)
{
TestContext.Out.WriteLine($"Access denied: Skip node {node}.");
}
}
}
nodesToBrowse = [.. nextNodesToBrowse.Distinct()];
TestContext.Out.WriteLine(
"Found {0} duplicates",
nextNodesToBrowse.Count - nodesToBrowse.Count);
}
TestContext.Out.WriteLine("Found {0} variables", result.Count);
}
/// <summary>
/// <para>
/// For each entry in the datapoint source, the test browses some folders in the reference
/// server which have 100 subnodes each (see method getMassFolderNodesToBrowse())
/// The server is configured with a certain number of allowed nodes per browse service call
/// Depending on the number of allowed browse continuation points, the following
/// results are expected and verified:
/// i) if the number of allowed browse continuation points is less than the number
/// of nodes per browse, the ManagedBrowse method will trigger the status codes
/// BadNoContinuationPoint several times, since it uses the number of nodes per browse for
/// creating packages. It will also have to rebrowse many nodes. With an increasing number
/// of allowed browse continuation points the number of results with status code
/// BadNoContinuationPoints is reduced, as well as the number of retry attempts needed
/// to get all browse results.
/// ii) if the number of allowed browse continuation points is equal to or greater than
/// the number of nodes per browse, there will be no status codes which are bad.
/// </para>
/// <para>
/// In all cases, the browse will succeed in the end, and the test verifies that
/// the number of returned nodes from the ManagedBrowse method is correct and also that the reuslts
/// are returned in the correct sequence. This is done by comparing the results with those
/// from a plain browse service call with no limit on the max number of browse continuation
/// points.
/// </para>
/// <para>
/// No return value should have the status code BadContinuationPointInvalid, since there is
/// no attempt to allocate continuation points in parallel from more than one service call.
/// </para>
/// </summary>
[Theory]
[Order(200)]
public async Task ManagedBrowseWithManyContinuationPointsAsync(
ManagedBrowseTestDataProvider testData)
{
var theSession = (Session)Session;
await theSession.FetchOperationLimitsAsync(default).ConfigureAwait(false);
theSession.ContinuationPointPolicy = ContinuationPointPolicy.Default;
var pass1ExpectedResults = new ManagedBrowseExpectedResultValues
{
InputMaxNumberOfContinuationPoints = testData.MaxNumberOfContinuationPoints,
InputMaxNumberOfReferencesPerNode = testData.MaxNumberOfReferencesPerNode,
ExpectedNumberOfPasses = testData.ExpectedNumberOfPasses,
ExpectedNumberOfBadNoCPSCs = testData.ExpectedNumberOfBadNoCPSCs
};
var pass2ExpectedResults = new ManagedBrowseExpectedResultValues
{
InputMaxNumberOfContinuationPoints = 0,
InputMaxNumberOfReferencesPerNode = 1000,
ExpectedNumberOfPasses = 1,
ExpectedNumberOfBadNoCPSCs = []
};
ReferenceServerWithLimits.TestMaxBrowseReferencesPerNode =
pass1ExpectedResults.InputMaxNumberOfReferencesPerNode;
ReferenceServerWithLimits.SetMaxNumberOfContinuationPoints(
pass1ExpectedResults.InputMaxNumberOfContinuationPoints);
theSession.ServerCapabilities.MaxBrowseContinuationPoints = (ushort)pass1ExpectedResults
.InputMaxNumberOfContinuationPoints;
ArrayOf<NodeId> nodeIds = GetMassFolderNodesToBrowse();
// browse with test settings
(ArrayOf<ArrayOf<ReferenceDescription>> referenceDescriptionCollectionsPass1, _) = await theSession.ManagedBrowseAsync(
null,
null,
nodeIds,
0,
BrowseDirection.Forward,
ReferenceTypeIds.Organizes,
true,
0).ConfigureAwait(false);
Assert.That(referenceDescriptionCollectionsPass1.Count, Is.EqualTo(nodeIds.Count));
// now reset the server qutas to get a browse scenario without continuation points. This allows
// to verify the result from the first browse service call (with quotas in place).
ReferenceServerWithLimits.TestMaxBrowseReferencesPerNode =
pass2ExpectedResults.InputMaxNumberOfReferencesPerNode;
ReferenceServerWithLimits.SetMaxNumberOfContinuationPoints(
pass2ExpectedResults.InputMaxNumberOfContinuationPoints);
theSession.ServerCapabilities.MaxBrowseContinuationPoints = (ushort)pass2ExpectedResults
.InputMaxNumberOfContinuationPoints;
(ArrayOf<ArrayOf<ReferenceDescription>> referenceDescriptionsPass2, _) = await theSession.ManagedBrowseAsync(
null,
null,
nodeIds,
0,
BrowseDirection.Forward,
ReferenceTypeIds.Organizes,
true,
0).ConfigureAwait(false);
Assert.That(referenceDescriptionsPass2.Count, Is.EqualTo(nodeIds.Count));
// finally browse again with a simple browse service call.
(_, _, ArrayOf<ArrayOf<ReferenceDescription>> referenceDescriptionCollections2ndBrowse, _) =
await theSession.BrowseAsync(
null,
null,
nodeIds,
0,
BrowseDirection.Forward,
ReferenceTypeIds.Organizes,
true,
0).ConfigureAwait(false);
int index = 0;
foreach (
ArrayOf<ReferenceDescription> referenceDescriptionCollection in referenceDescriptionCollectionsPass1)
{
Assert.That(
referenceDescriptionCollection.Count,
Is.EqualTo(referenceDescriptionCollections2ndBrowse[index].Count));
// now verify that the type of the nodes are the same, once for each list of reference descriptions
string randomNodeName = referenceDescriptionCollection[
UnsecureRandom.Shared.Next(0, referenceDescriptionCollection.Count - 1)
]
.DisplayName
.Text!;
string suffix = GetSuffixesForMassFolders()[index];
Assert.That(randomNodeName!.StartsWith(suffix, StringComparison.Ordinal), Is.True);
int ii = UnsecureRandom.Shared.Next(0, referenceDescriptionCollection.Count - 1);
Assert.That(
referenceDescriptionCollections2ndBrowse[index].Count,
Is.EqualTo(referenceDescriptionCollection.Count));
Assert.That(
referenceDescriptionCollections2ndBrowse[index][ii].NodeId,
Is.EqualTo(referenceDescriptionCollection[ii].NodeId));
index++;
}
}
/// <summary>
/// <para>
/// For each entry in the datapoint source, the test browses some folders in the reference
/// server which have 100 subnodes each (see method getMassFolderNodesToBrowse())
/// </para>
/// <para>The server is configured with a certain number of allowed nodes per browse service call</para>
/// <para>
/// The ManagedBrowse method is called with the ContinuationPointPolicy 'Balanced'
/// which forces the method to create packages which have at most
/// min(maxBrowseContinuationPoints, maxNodesPerBrowse)
/// nodes.
/// </para>
/// <para>The following results are expected and verified:</para>
/// <para>
/// In all cases, the browse will succeed without a status code BadNoContinuationPoints
/// The test also verifies that the number of returned nodes from the ManagedBrowse method
/// is correct and also that the reuslts are returned in the correct sequence.
/// This is done by comparing the results with those
/// from a plain browse service call with no limit on the max number of browse continuation
/// points.
/// </para>
/// <para>
/// No return value should have the status code BadContinuationPointInvalid, since there is
/// no attempt to allocate continuation points in parallel from more than one service call.
/// </para>
/// </summary>
[Theory]
[Order(210)]
public async Task BalancedManagedBrowseWithManyContinuationPointsAsync(
ManagedBrowseTestDataProvider testData)
{
var theSession = (Session)Session;
theSession.ContinuationPointPolicy = ContinuationPointPolicy.Balanced;
var pass1ExpectedResults = new ManagedBrowseExpectedResultValues
{
InputMaxNumberOfContinuationPoints = testData.MaxNumberOfContinuationPoints,
InputMaxNumberOfReferencesPerNode = testData.MaxNumberOfReferencesPerNode,
ExpectedNumberOfPasses = testData.ExpectedNumberOfPasses,
ExpectedNumberOfBadNoCPSCs = testData.ExpectedNumberOfBadNoCPSCs
};
var pass2ExpectedResults = new ManagedBrowseExpectedResultValues
{
InputMaxNumberOfContinuationPoints = 0,
InputMaxNumberOfReferencesPerNode = 1000,
ExpectedNumberOfPasses = 1,
ExpectedNumberOfBadNoCPSCs = []
};
ReferenceServerWithLimits.TestMaxBrowseReferencesPerNode =
pass1ExpectedResults.InputMaxNumberOfReferencesPerNode;
ReferenceServerWithLimits.SetMaxNumberOfContinuationPoints(
pass1ExpectedResults.InputMaxNumberOfContinuationPoints);
theSession.ServerCapabilities.MaxBrowseContinuationPoints = (ushort)pass1ExpectedResults
.InputMaxNumberOfContinuationPoints;
ArrayOf<NodeId> nodeIds = GetMassFolderNodesToBrowse();
// browse with test settings
(ArrayOf<ArrayOf<ReferenceDescription>> referenceDescriptionCollectionsPass1, _) = await theSession.ManagedBrowseAsync(
null,
null,
nodeIds,
0,
BrowseDirection.Forward,
ReferenceTypeIds.Organizes,
true,
0).ConfigureAwait(false);
Assert.That(referenceDescriptionCollectionsPass1.Count, Is.EqualTo(nodeIds.Count));
// now reset the server qutas to get a browse scenario without continuation points. This allows
// to verify the result from the first browse service call (with quotas in place).
ReferenceServerWithLimits.TestMaxBrowseReferencesPerNode =
pass2ExpectedResults.InputMaxNumberOfReferencesPerNode;
ReferenceServerWithLimits.SetMaxNumberOfContinuationPoints(
pass2ExpectedResults.InputMaxNumberOfContinuationPoints);
theSession.ServerCapabilities.MaxBrowseContinuationPoints = (ushort)pass2ExpectedResults
.InputMaxNumberOfContinuationPoints;
theSession.ContinuationPointPolicy = ContinuationPointPolicy.Balanced;
(ArrayOf<ArrayOf<ReferenceDescription>> referenceDescriptionsPass2, _) = await theSession.ManagedBrowseAsync(
null,
null,
nodeIds,
0,
BrowseDirection.Forward,
ReferenceTypeIds.Organizes,
true,
0).ConfigureAwait(false);
Assert.That(referenceDescriptionsPass2.Count, Is.EqualTo(nodeIds.Count));
// finally browse again with a simple browse service call.
(_, _, ArrayOf<ArrayOf<ReferenceDescription>> referenceDescriptionCollections2ndBrowse, _) = await theSession.BrowseAsync(
null,
null,
nodeIds,
0,
BrowseDirection.Forward,
ReferenceTypeIds.Organizes,
true,
0).ConfigureAwait(false);
int index = 0;
foreach (ArrayOf<ReferenceDescription> referenceDescriptionCollection in referenceDescriptionCollectionsPass1)
{
Assert.That(
referenceDescriptionCollection.Count,
Is.EqualTo(referenceDescriptionCollections2ndBrowse[index].Count));
// now verify that the type of the nodes are the same, once for each list of reference descriptions
string randomNodeName = referenceDescriptionCollection[
UnsecureRandom.Shared.Next(0, referenceDescriptionCollection.Count - 1)
]
.DisplayName
.Text!;
string suffix = GetSuffixesForMassFolders()[index];
Assert.That(randomNodeName!.StartsWith(suffix, StringComparison.Ordinal), Is.True);
int ii = UnsecureRandom.Shared.Next(0, referenceDescriptionCollection.Count - 1);
Assert.That(
referenceDescriptionCollections2ndBrowse[index].Count,
Is.EqualTo(referenceDescriptionCollection.Count));
Assert.That(
referenceDescriptionCollections2ndBrowse[index][ii].NodeId,
Is.EqualTo(referenceDescriptionCollection[ii].NodeId));
index++;
}
}
/// <summary>
/// <para>
/// in this test the service result BadContinuationPoint invalid in (an unpredictable subset)
/// of the return values from the ManagedBrowse method call is enforced, by
/// concurrently executing the method on two sets of nodes both of which
/// require the allocation of BrowseContinuationPoints in the server
/// </para>
/// <para>
/// The following results are expected:
/// on a system which supports parallel execution of threads, at least one of the parallel calls
/// (usually all of them) to method ManagedBrowse will produce results with status code
/// BadContinuationPointInvalid
/// </para>
/// <para>
/// In the worst case the two calls to ManagedBrowse could end up in an endless loop (to prevent this
/// an upper bound for the number of rebrowse attempts would be needed, or a session wide management
/// of the continuation points the server must potentially allocate for the service calls
/// from the client).
/// </para>
/// <para>
/// The result with regards to the BadNoContinuationPoint should be similar to the one from
/// the ManagedBrowseWithManyContinuationPoints test case
/// </para>
/// </summary>
[Theory]
[Order(300)]
public async Task ParallelManagedBrowseWithManyContinuationPointsAsync(
ManagedBrowseTestDataProvider testData,
ContinuationPointPolicy policy)
{
var theSession = (Session)Session;
theSession.ContinuationPointPolicy = policy;
var pass1ExpectedResults = new ManagedBrowseExpectedResultValues
{
InputMaxNumberOfContinuationPoints = testData.MaxNumberOfContinuationPoints,
InputMaxNumberOfReferencesPerNode = testData.MaxNumberOfReferencesPerNode,
ExpectedNumberOfPasses = testData.ExpectedNumberOfPasses,
ExpectedNumberOfBadNoCPSCs = testData.ExpectedNumberOfBadNoCPSCs
};
var pass2ExpectedResults = new ManagedBrowseExpectedResultValues
{
InputMaxNumberOfContinuationPoints = 0,
InputMaxNumberOfReferencesPerNode = 1000,
ExpectedNumberOfPasses = 1,
ExpectedNumberOfBadNoCPSCs = []
};
ReferenceServerWithLimits.TestMaxBrowseReferencesPerNode =
pass1ExpectedResults.InputMaxNumberOfReferencesPerNode;
ReferenceServerWithLimits.SetMaxNumberOfContinuationPoints(
pass1ExpectedResults.InputMaxNumberOfContinuationPoints);
theSession.ServerCapabilities.MaxBrowseContinuationPoints =
(ushort)pass1ExpectedResults.InputMaxNumberOfContinuationPoints;
ArrayOf<NodeId> nodeIds = GetMassFolderNodesToBrowse();
ArrayOf<NodeId> nodeIds1 = nodeIds[..(nodeIds.Count / 2)];
ArrayOf<NodeId> nodeIds2 = nodeIds[(nodeIds.Count / 2)..];
ArrayOf<ArrayOf<ReferenceDescription>> referenceDescriptionCollectionsPass1 = [];
ArrayOf<ArrayOf<ReferenceDescription>> referenceDescriptionCollectionsPass2 = [];
ArrayOf<ServiceResult> errorsPass1 = [];
ArrayOf<ServiceResult> errorsPass2 = [];
Func<Task>[] tasks = [
async () =>
(referenceDescriptionCollectionsPass1, errorsPass1) = await theSession.ManagedBrowseAsync(
null,
null,
nodeIds1,
0,
BrowseDirection.Forward,
ReferenceTypeIds.Organizes,
true,
0).ConfigureAwait(false),
async () =>
(referenceDescriptionCollectionsPass2, errorsPass2) = await theSession.ManagedBrowseAsync(
null,
null,
nodeIds2,
0,
BrowseDirection.Forward,
ReferenceTypeIds.Organizes,
true,
0).ConfigureAwait(false)
];
await Task.WhenAll([.. tasks.Select(t => t.Invoke())]).ConfigureAwait(false);
Assert.That(referenceDescriptionCollectionsPass1.Count, Is.EqualTo(nodeIds1.Count));
Assert.That(referenceDescriptionCollectionsPass2.Count, Is.EqualTo(nodeIds2.Count));
referenceDescriptionCollectionsPass1 = ArrayOf.Combine(
referenceDescriptionCollectionsPass1,
referenceDescriptionCollectionsPass2);
errorsPass1 = ArrayOf.Combine(errorsPass1, errorsPass2);
// finally browse again with a simple browse service call.
// reset server quotas first:
ReferenceServerWithLimits.TestMaxBrowseReferencesPerNode =
pass2ExpectedResults.InputMaxNumberOfReferencesPerNode;
ReferenceServerWithLimits.SetMaxNumberOfContinuationPoints(
pass2ExpectedResults.InputMaxNumberOfContinuationPoints);
theSession.ServerCapabilities.MaxBrowseContinuationPoints = (ushort)pass2ExpectedResults
.InputMaxNumberOfContinuationPoints;
(
_,
ArrayOf<ByteString> continuationPoints2ndBrowse,
ArrayOf<ArrayOf<ReferenceDescription>> referenceDescriptionCollections2ndBrowse,
ArrayOf<ServiceResult> errors2ndBrowse
) =
await theSession.BrowseAsync(
null,
null,
nodeIds,
0,
BrowseDirection.Forward,
ReferenceTypeIds.Organizes,
true,
0).ConfigureAwait(false);
int index = 0;
foreach (ArrayOf<ReferenceDescription> referenceDescriptionCollection in referenceDescriptionCollectionsPass1)
{
Assert.That(
referenceDescriptionCollection.Count,
Is.EqualTo(referenceDescriptionCollections2ndBrowse[index].Count));
// now verify that the types of the nodes are the same, once for each list of reference descriptions
string randomNodeName = referenceDescriptionCollection[
UnsecureRandom.Shared.Next(0, referenceDescriptionCollection.Count - 1)
]
.DisplayName
.Text!;
string suffix = GetSuffixesForMassFolders()[index];
Assert.That(randomNodeName!.StartsWith(suffix, StringComparison.Ordinal), Is.True);
int ii = UnsecureRandom.Shared.Next(0, referenceDescriptionCollection.Count - 1);
Assert.That(
referenceDescriptionCollections2ndBrowse[index].Count,
Is.EqualTo(referenceDescriptionCollection.Count));
Assert.That(
referenceDescriptionCollections2ndBrowse[index][ii].NodeId,
Is.EqualTo(referenceDescriptionCollection[ii].NodeId));
index++;
}
}
/// <summary>
/// This test is taken from the node cache unit test.
/// Instead of the original test, there are now restrctions
/// on the maximum number of continuation points supported
/// by the server, and the maximum number of nodes allowed
/// in a browse service call.
/// Browse all variables in the objects folder.
/// </summary>
[Theory]
[Order(400)]
[CancelAfter(300_000)]
public async Task MBNodeCacheBrowseAllVariablesMultipleNodesAsync(
ManagedBrowseTestDataProvider testData,
ContinuationPointPolicy policy,
CancellationToken ct)
{
var theSession = (Session)Session;
theSession.NodeCache.Clear();
theSession.ContinuationPointPolicy = policy;
// the ExpectedNumber* parameters are not relevant/correct for this test.
var pass1ExpectedResults = new ManagedBrowseExpectedResultValues
{
InputMaxNumberOfContinuationPoints = testData.MaxNumberOfContinuationPoints,
InputMaxNumberOfReferencesPerNode = testData.MaxNumberOfReferencesPerNode,
ExpectedNumberOfPasses = testData.ExpectedNumberOfPasses,
ExpectedNumberOfBadNoCPSCs = testData.ExpectedNumberOfBadNoCPSCs
};
ReferenceServerWithLimits.TestMaxBrowseReferencesPerNode =
pass1ExpectedResults.InputMaxNumberOfReferencesPerNode;
ReferenceServerWithLimits.SetMaxNumberOfContinuationPoints(
pass1ExpectedResults.InputMaxNumberOfContinuationPoints);
theSession.ServerCapabilities.MaxBrowseContinuationPoints = (ushort)pass1ExpectedResults
.InputMaxNumberOfContinuationPoints;
var result = new List<INode>();
var nodesToBrowse = new List<ExpandedNodeId> { ObjectIds.ObjectsFolder };
await Session
.FetchTypeTreeAsync(ReferenceTypeIds.References, ct)
.ConfigureAwait(false);
var referenceTypeIds = new List<NodeId> { ReferenceTypeIds.HierarchicalReferences };
while (nodesToBrowse.Count > 0)
{
var nextNodesToBrowse = new List<ExpandedNodeId>();
try
{
ArrayOf<INode> organizers = await Session
.NodeCache.FindReferencesAsync(
nodesToBrowse,
referenceTypeIds,
false,
true,
ct)
.ConfigureAwait(false);
nextNodesToBrowse.AddRange(organizers.ConvertAll(n => n.NodeId));
ArrayOf<INode> objectNodes = organizers.Filter(n => n is ObjectNode);
ArrayOf<INode> variableNodes = organizers.Filter(n => n is VariableNode);
result.AddRange(variableNodes);
}
catch (ServiceResultException sre)
{
if (sre.StatusCode == StatusCodes.BadUserAccessDenied)
{
TestContext.Out.WriteLine("Access denied: Skipped node.");
}
}
nodesToBrowse = [.. nextNodesToBrowse.Distinct()];
TestContext.Out.WriteLine(
"Found {0} duplicates",
nextNodesToBrowse.Count - nodesToBrowse.Count);
}
TestContext.Out.WriteLine("Found {0} variables", result.Count);
}
private ArrayOf<NodeId> GetMassFolderNodesToBrowse()
{
const string massFolderPrefix = "Scalar_Simulation_Mass_";
var nodesToBrowse = new List<string>();
foreach (string suffix in GetSuffixesForMassFolders())
{
nodesToBrowse.Add(massFolderPrefix + suffix);
}
int nsi = Session.NamespaceUris
.GetIndex("http://opcfoundation.org/Quickstarts/ReferenceServer");
var result = new List<NodeId>();
foreach (string nodeString in nodesToBrowse)
{
result.Add(new NodeId(nodeString, (ushort)nsi));
}
return result.ToArrayOf();
}
private static List<string> GetSuffixesForMassFolders()
{
return
[
"Boolean",
"Byte",
"ByteString",
"DateTime",
"Double",
"Duration",
"Float",
"Guid",
"Int16",
"Int32",
"Int64",
"Integer",
"LocaleId",
"LocalizedText",
"NodeId",
"Number",
"QualifiedName",
"SByte",
"String",
"UInt16",
"UInt32",
"UInt64",
"UInteger",
"UtcTime",
"Variant",
"XmlElement"
];
}
}
}