Files
UA-.NETStandard/tests/Opc.Ua.Sessions.Tests/ContinuationPointInBatchTest.cs
romanett 9b034f8291 Enable nullable reference types centrally; migrate all unset and annotations-only projects (#4700)
# Description

Nullable reference types are now enabled once, in `common.props`, and
every project in the repository builds warning-clean with them.

**Configuration**
- `<Nullable>enable</Nullable>` lives in `common.props`. All per-project
`<Nullable>` settings are removed: 178 project files (enable,
annotations, and the `disable` in the three Aot test projects).
- 419 per-file `#nullable enable`/`restore` directives and the 4
`#nullable disable` directives are removed.
- Kept on purpose:
- The 5 `<auto-generated>` schema files (`UANodeSet.cs`, `UA Type
Dictionary.cs`, `OPCBinarySchema.cs`, `SecuredApplication.cs`,
`PInvokeHelper.cs`) keep `#nullable enable`. The compiler ignores the
project setting in generated code, so the directive is required there.
- `tests/Opc.Ua.Interop.LegacyPeer` keeps `disable`. It builds against
the 1.5.378 packages and does not import the repository props.
- `docs/DeveloperGuide.md` and `.github/copilot-instructions.md` now
describe the central setting.

**Migration** (the 43 unset and 13 annotations-only projects, roughly
10k diagnostics)
- **Production code: annotated at the declarations.** Covers
`tools/Opc.Ua.SourceGeneration.Core`, `src/Opc.Ua.Lds.Server` and the
LDS sample.
- Members, parameters and returns are nullable where null actually
flows.
- Null-check helpers carry `[NotNullWhen]` (`IsNull`, `IsValidXmlName`,
`IsMethodTypeDesign`).
- `CoreUtils.Format`, `Utils.Format`, `ITemplateWriter.WriteLine` take
`params object?[]`. `Template.AddReplacement` takes `string?` (rendering
already skips null replacements).
- `IRegisteredServerStore.RegisterAsync` returns
`Task<RegistrationEntry?>`: it returns null when a registration is
removed.
- Dereferences backed by an invariant (for example, the validated model)
use `!`, so runtime behaviour is unchanged.
- **Behavioural changes in production code** (small, deliberate):
- `NodeSetToModelDesign` throws `InvalidOperationException` when the
file is not a NodeSet. Before, it threw a NullReferenceException on the
next line.
- `ModelDesignValidator` starts its lookup tables empty instead of null.
A redundant `if (m_nodes == null) return;` guard is gone.
- **Test code: minimal annotations.**
  - `?` on values that can be null, `!` where the test asserts non-null.
  - `= null!` for fixture members assigned in SetUp.
- `TryGetStructure<T>(out T? x)` where the inferred `T?` broke the
`IEncodeable` constraint.
- A few redundant `== null` checks on structs (`NodeId`, `ArrayOf<T>`)
folded into the adjacent `IsNull`/`Count` checks.

**Notes for reviewers**
- The diff is large (~1,500 files) but almost entirely mechanical: `?`,
`!` and directive removal. The non-annotation changes are listed above.
- Known follow-up, not done here:
`IModelDesign.Namespaces/TargetNamespace/NamespaceUris` stay
non-nullable even though the validator returns null before it loads a
dictionary. Making them nullable would ripple through every generator
call site.

## Related Issues

- Fixes #4439

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

The "no new warnings" box covers net10.0 and net48: full non-incremental
builds of `UA.slnx`, `tools/SourceGeneration.slnx`,
`tools/MigrationAnalyzer.slnx` and the Aot test projects finished with 0
warnings and 0 errors under the repository's warnings-as-errors
settings. net9.0 and net8.0 also had no nullable diagnostics, but they
were not rebuilt after the final fixes. Tests have not been run locally
yet.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 08:48:13 +02:00

887 lines
38 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>
/// <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"
];
}
}
}