Files
UA-.NETStandard/tests/Opc.Ua.Server.Tests/Hosting/OpcUaServerHostedServiceCoverageTests.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

726 lines
31 KiB
C#

/* ========================================================================
* Copyright (c) 2005-2026 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.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Moq;
using NUnit.Framework;
using Opc.Ua.Bindings;
using Opc.Ua.Configuration;
using Opc.Ua.Identity;
using Opc.Ua.Server.AliasNames;
using Opc.Ua.Server.Historian;
using Opc.Ua.Server.Hosting;
using Opc.Ua.Server.TestFramework;
using Opc.Ua.Server.UserDatabase;
using Opc.Ua.Server.UserManagement;
using Opc.Ua.Tests;
namespace Opc.Ua.Server.Tests.Hosting
{
/// <summary>
/// Directly exercises <see cref="OpcUaServerHostedService"/> paths that
/// are not reached by the broader fluent-API hosting tests: the
/// constructor's null-argument guards, early historian and alias
/// alias registry wiring on a plain
/// (non dependency-injection-aware) <see cref="StandardServer"/>, and
/// the matched-authenticator branches of <c>HasMatchingAuthenticator</c>
/// for <see cref="UserTokenType.Certificate"/> and
/// <see cref="UserTokenType.IssuedToken"/>.
/// </summary>
[TestFixture]
[Category("Server")]
[Category("Hosting")]
[NonParallelizable]
public sealed class OpcUaServerHostedServiceCoverageTests
{
/// <summary>
/// Verifies that the default certificate store root is a per-user
/// application-data directory and not the shared temporary directory.
/// </summary>
[Test]
public void DefaultPkiRootIsNotInTempDirectory()
{
string pkiRoot = DefaultPkiRoot.Get("DefaultPkiApp");
string appData = Environment.GetFolderPath(
Environment.SpecialFolder.LocalApplicationData,
Environment.SpecialFolderOption.DoNotVerify);
Assert.That(
pkiRoot,
Is.EqualTo(System.IO.Path.Combine(appData, "OPC Foundation", "DefaultPkiApp", "pki")));
Assert.That(
pkiRoot,
Does.Not.StartWith(System.IO.Path.GetTempPath()));
}
/// <summary>
/// Verifies that hosted-service construction rejects null options.
/// </summary>
[Test]
public void ConstructorThrowsForNullOptions()
{
Assert.That(
() => new OpcUaServerHostedService(
null!,
NUnitTelemetryContext.Create(isServer: true),
Mock.Of<IApplicationInstanceFactory>(),
[],
[],
[],
[],
Mock.Of<IServiceProvider>(),
Mock.Of<IOpcUaServerFactory>(),
new HostedNodeManagerLifecycle(),
NullLogger<OpcUaServerHostedService>.Instance),
Throws.ArgumentNullException.With.Property(nameof(ArgumentNullException.ParamName))
.EqualTo("options"));
}
/// <summary>
/// Verifies that hosted-service construction rejects null configuration providers.
/// </summary>
[Test]
public void ConstructorThrowsForNullConfigurationProviders()
{
Assert.That(
() => new OpcUaServerHostedService(
Options.Create(new OpcUaServerOptions()),
NUnitTelemetryContext.Create(isServer: true),
Mock.Of<IApplicationInstanceFactory>(),
null!,
[],
[],
[],
Mock.Of<IServiceProvider>(),
Mock.Of<IOpcUaServerFactory>(),
new HostedNodeManagerLifecycle(),
NullLogger<OpcUaServerHostedService>.Instance),
Throws.ArgumentNullException.With.Property(nameof(ArgumentNullException.ParamName))
.EqualTo("configurationProviders"));
}
/// <summary>
/// Verifies that hosted startup wires historian and alias stores on an ordinary server.
/// </summary>
[Test]
public async Task HostedStartupWiresHistorianAndAliasStoresOnPlainServerAsync()
{
RegistryCaptureServer.Reset();
var historian = new Mock<IHistorianProvider>();
var directStore = new Mock<IAliasNameStore>();
directStore.SetupGet(s => s.RootCategories).Returns([]);
var registrySourcedStore = new Mock<IAliasNameStore>();
registrySourcedStore.SetupGet(s => s.RootCategories).Returns([]);
var sourceRegistry = new Mock<IAliasNameStoreRegistry>();
sourceRegistry.SetupGet(r => r.Stores).Returns([registrySourcedStore.Object]);
IHistoryContinuationPointStore continuationStore =
Mock.Of<IHistoryContinuationPointStore>();
var loggerProvider = new CapturingLoggerProvider();
await using HostedServerFixture fixture = await HostedServerFixture.StartAsync(
services =>
{
services.AddLogging(builder => builder.AddProvider(loggerProvider));
services.AddSingleton(continuationStore);
services.AddOpcUa()
.AddServer<RegistryCaptureServer>(o => ConfigureHostedOptions(o, "EarlyRegistries"))
.AddHistorian(historian.Object)
.AddAliasNameStore(directStore.Object)
.AddAliasNameStoreRegistry(sourceRegistry.Object);
}).ConfigureAwait(false);
Assert.That(
await WaitForAsync(
() => RegistryCaptureServer.StartedServer != null,
TimeSpan.FromSeconds(60)).ConfigureAwait(false),
Is.True,
"Hosted service registry wiring did not complete.");
IServerInternal server = RegistryCaptureServer.StartedServer ??
throw new InvalidOperationException("The server did not start.");
var historianRegistryProvider = (IHistorianRegistryProvider)server;
var aliasRegistryProvider = (IAliasNameStoreRegistryProvider)server;
Assert.That(
await WaitForAsync(
() =>
historianRegistryProvider.HistorianRegistry.Providers.Contains(
historian.Object) &&
aliasRegistryProvider.AliasNameStoreRegistry.Stores.Contains(
directStore.Object) &&
aliasRegistryProvider.AliasNameStoreRegistry.Stores.Contains(
registrySourcedStore.Object),
TimeSpan.FromSeconds(60)).ConfigureAwait(false),
Is.True);
Assert.That(
historianRegistryProvider.HistorianRegistry.Providers.Contains(
historian.Object),
Is.True);
Assert.That(
RegistryCaptureServer.StartedInstance?
.HistoryContinuationPointStore,
Is.SameAs(continuationStore));
Assert.That(
aliasRegistryProvider.AliasNameStoreRegistry.Stores,
Has.Member(directStore.Object));
Assert.That(
aliasRegistryProvider.AliasNameStoreRegistry.Stores,
Has.Member(registrySourcedStore.Object));
}
/// <summary>
/// Verifies that matching certificate and issued-token policies do not produce unmatched-authenticator
/// warnings.
/// </summary>
[Test]
public async Task MatchingCertificateAndIssuedTokenPoliciesDoNotLogUnmatchedWarningAsync()
{
using var rsa = RSA.Create(2048);
RSAParameters parameters = rsa.ExportParameters(false);
var loggerProvider = new CapturingLoggerProvider();
await using HostedServerFixture fixture = await HostedServerFixture.StartAsync(
services =>
{
services.AddLogging(builder => builder.AddProvider(loggerProvider));
services.AddSingleton(Mock.Of<ICertificateValidatorEx>());
services.AddOpcUa().AddServer(o =>
{
ConfigureHostedOptions(o, "MatchedAuthenticators");
o.UserTokenPolicies.Clear();
o.UserTokenPolicies.Add(
new OpcUaUserTokenPolicy { TokenType = UserTokenType.Certificate });
o.UserTokenPolicies.Add(
new OpcUaUserTokenPolicy { TokenType = UserTokenType.IssuedToken });
o.Identity.Defaults.EnableAnonymous = false;
o.Identity.Defaults.EnableUserNamePassword = false;
o.Identity.Defaults.EnableX509 = true;
o.Identity.Defaults.EnableJwt = true;
o.Identity.Defaults.ExpectedAudience = "urn:opcua:test-server";
o.Identity.Issuers.Add(new JwtIssuerOptions
{
IssuerUri = "https://issuer.example.test",
StaticKeys =
{
new JwtStaticKeyOptions
{
Kid = "kid-rsa",
Algorithm = "RS256",
RsaModulus = Base64UrlEncode(parameters.Modulus!),
RsaExponent = Base64UrlEncode(parameters.Exponent!)
}
}
});
});
}).ConfigureAwait(false);
Assert.That(
await WaitForAsync(
() => loggerProvider.Messages.Any(
message => message.Contains("OPC UA server listening", StringComparison.Ordinal)),
TimeSpan.FromSeconds(30)).ConfigureAwait(false),
Is.True);
Assert.That(
loggerProvider.Messages.Any(
message => message.Contains(
"without a matching identity authenticator", StringComparison.Ordinal)),
Is.False);
}
/// <summary>
/// Verifies that hosted startup wires optional features and matches the username authentication policy.
/// </summary>
[Test]
public async Task HostedServiceWiresOptionalFeaturesAndMatchesUserNamePolicyAsync()
{
RegistryCaptureServer.Reset();
var augmenter = new Mock<IIdentityAugmenter>();
var loggerProvider = new CapturingLoggerProvider();
bool rateLimitsConfigured = false;
await using HostedServerFixture fixture = await HostedServerFixture.StartAsync(
services =>
{
services.AddLogging(builder => builder.AddProvider(loggerProvider));
services.AddSingleton<ITransportBindingRegistry>(TestTransportBindings.WithAllSchemes());
services.AddSingleton(new ServerComplexTypeOptions { Enabled = false });
services.AddSingleton(Mock.Of<IUserDatabase>());
services.AddSingleton(Mock.Of<IUserManagement>());
services.AddOpcUa()
.AddServer<RegistryCaptureServer>(o =>
{
ConfigureHostedOptions(o, "OptionalFeatures");
o.UserTokenPolicies.Clear();
o.UserTokenPolicies.Add(
new OpcUaUserTokenPolicy { TokenType = UserTokenType.UserName });
o.Identity.Defaults.EnableAnonymous = false;
o.Identity.Defaults.EnableUserNamePassword = true;
o.ConfigureRateLimits = _ => rateLimitsConfigured = true;
})
.AddIdentityAugmenter(_ => augmenter.Object);
}).ConfigureAwait(false);
Assert.That(
await WaitForAsync(
() => RegistryCaptureServer.StartedServer != null,
TimeSpan.FromSeconds(60)).ConfigureAwait(false),
Is.True);
IServerInternal server = RegistryCaptureServer.StartedServer ??
throw new InvalidOperationException("The server did not start.");
Assert.That(RegistryCaptureServer.StartedInstance, Is.Not.Null);
Assert.That(RegistryCaptureServer.StartedInstance!.LoadComplexTypes, Is.False);
Assert.That(RegistryCaptureServer.StartedInstance.TransportBindings, Is.Not.Null);
Assert.That(rateLimitsConfigured, Is.True);
Assert.That(
loggerProvider.Messages.Any(
message => message.Contains(
"without a matching identity authenticator", StringComparison.Ordinal)),
Is.False);
// The augmenter is registered during the hosted service's post-start
// phase (RegisterIdentityAugmenters), which runs after OnServerStarted
// sets StartedServer. Poll UnregisterAugmenter (which returns false
// until the augmenter is present, then true once, removing it) so the
// assertion does not race that background registration.
Assert.That(
await WaitForAsync(
() => server.IdentityRegistry.UnregisterAugmenter(augmenter.Object),
TimeSpan.FromSeconds(60)).ConfigureAwait(false),
Is.True);
}
/// <summary>
/// Verifies that an identity configuration that disables anonymous access but yields no
/// authenticator (UserName enabled without a user database) does not re-enable anonymous
/// logins: anonymous tokens are rejected instead of falling back to acceptance.
/// </summary>
[Test]
public async Task HostedServiceRejectsAnonymousWhenDisabledAndNoAuthenticatorIsCreatedAsync()
{
RegistryCaptureServer.Reset();
await using HostedServerFixture fixture = await HostedServerFixture.StartAsync(
services =>
{
services.AddLogging();
services.AddSingleton<ITransportBindingRegistry>(TestTransportBindings.WithAllSchemes());
services.AddSingleton(new ServerComplexTypeOptions { Enabled = false });
services.AddOpcUa()
.AddServer<RegistryCaptureServer>(o =>
{
ConfigureHostedOptions(o, "AnonymousDisabled");
o.Identity.Defaults.EnableAnonymous = false;
o.Identity.Defaults.EnableUserNamePassword = true;
o.Identity.Defaults.EnableX509 = false;
o.Identity.Defaults.EnableJwt = false;
});
}).ConfigureAwait(false);
Assert.That(
await WaitForAsync(
() => RegistryCaptureServer.StartedServer != null,
TimeSpan.FromSeconds(60)).ConfigureAwait(false),
Is.True);
IServerInternal server = RegistryCaptureServer.StartedServer ??
throw new InvalidOperationException("The server did not start.");
var context = new AuthenticationContext(
new AnonymousIdentityTokenHandler(),
new UserTokenPolicy { TokenType = UserTokenType.Anonymous },
new EndpointDescription { SecurityMode = MessageSecurityMode.SignAndEncrypt },
ServiceMessageContext.CreateEmpty(NUnitTelemetryContext.Create()));
// the authenticators are registered after the server started; poll until they are.
AuthenticationResult result = AuthenticationResult.NotHandled;
DateTime deadline = DateTime.UtcNow.AddSeconds(60);
while (result.Outcome == AuthenticationOutcome.NotHandled && DateTime.UtcNow < deadline)
{
result = await server.IdentityRegistry.AuthenticateAsync(context).ConfigureAwait(false);
if (result.Outcome == AuthenticationOutcome.NotHandled)
{
await Task.Delay(50).ConfigureAwait(false);
}
}
Assert.That(result.Outcome, Is.EqualTo(AuthenticationOutcome.Rejected));
Assert.That(result.Error!.StatusCode, Is.EqualTo(StatusCodes.BadIdentityTokenRejected));
}
/// <summary>
/// Verifies that disabling anonymous access without explicit UserTokenPolicies does not
/// advertise the implicit Anonymous policy: endpoints list the user identity tokens the
/// server accepts (Part 4 7.14, 7.41), here the UserName token of the default authenticator.
/// </summary>
[Test]
public async Task HostedServiceDoesNotAdvertiseAnonymousWhenDisabledByDefaultsAsync()
{
RegistryCaptureServer.Reset();
await using HostedServerFixture fixture = await HostedServerFixture.StartAsync(
services =>
{
services.AddLogging();
services.AddSingleton<ITransportBindingRegistry>(TestTransportBindings.WithAllSchemes());
services.AddSingleton(new ServerComplexTypeOptions { Enabled = false });
services.AddSingleton(Mock.Of<IUserDatabase>());
services.AddSingleton(Mock.Of<IUserManagement>());
services.AddOpcUa()
.AddServer<RegistryCaptureServer>(o =>
{
ConfigureHostedOptions(o, "AnonymousNotAdvertised");
o.Identity.Defaults.EnableAnonymous = false;
o.Identity.Defaults.EnableUserNamePassword = true;
o.Identity.Defaults.EnableX509 = false;
o.Identity.Defaults.EnableJwt = false;
});
}).ConfigureAwait(false);
Assert.That(
await WaitForAsync(
() => RegistryCaptureServer.StartedServer != null,
TimeSpan.FromSeconds(60)).ConfigureAwait(false),
Is.True);
EndpointDescription[] endpoints = [.. RegistryCaptureServer.StartedInstance!.GetEndpoints()];
Assert.That(endpoints, Is.Not.Empty);
foreach (EndpointDescription endpoint in endpoints)
{
UserTokenPolicy[] policies = [.. endpoint.UserIdentityTokens];
UserTokenType[] tokenTypes = [.. policies.Select(p => p.TokenType)];
Assert.That(tokenTypes, Does.Not.Contain(UserTokenType.Anonymous));
Assert.That(tokenTypes, Does.Contain(UserTokenType.UserName));
}
}
/// <summary>
/// Verifies that the budget registered through the fluent builder is the
/// one the hosted server bounds incomplete messages with.
/// </summary>
[TestCase(false)]
[TestCase(true)]
public async Task HostedServiceAppliesTheRegisteredChunkReassemblyBudgetAsync(bool explicitShare)
{
RegistryCaptureServer.Reset();
const long maxBytes = 48L * 1024 * 1024;
await using HostedServerFixture fixture = await HostedServerFixture.StartAsync(
services =>
{
services.AddLogging();
services.AddSingleton<ITransportBindingRegistry>(TestTransportBindings.WithAllSchemes());
services.AddSingleton(new ServerComplexTypeOptions { Enabled = false });
IOpcUaServerBuilder builder = services.AddOpcUa()
.AddServer<RegistryCaptureServer>(o => ConfigureHostedOptions(o, "ChunkReassemblyBudget"));
if (explicitShare)
{
builder.WithChunkReassemblyBudget(maxBytes, maxBytes / 4);
}
else
{
builder.WithChunkReassemblyBudget(maxBytes);
}
}).ConfigureAwait(false);
Assert.That(
await WaitForAsync(
() => RegistryCaptureServer.StartedServer != null,
TimeSpan.FromSeconds(60)).ConfigureAwait(false),
Is.True);
ChunkReassemblyBudget? budget = RegistryCaptureServer.StartedInstance?.ChunkReassemblyBudget;
Assert.That(budget, Is.Not.Null);
Assert.That(budget!.MaxBytes, Is.EqualTo(maxBytes));
Assert.That(budget.MaxBytesWithoutSession, Is.EqualTo(maxBytes / (explicitShare ? 4 : 2)));
}
[Test]
public async Task HostedServiceAppliesTheRegisteredSessionBindingProviderAsync()
{
RegistryCaptureServer.Reset();
ISessionBindingProvider configured = Mock.Of<ISessionBindingProvider>();
await using HostedServerFixture fixture = await HostedServerFixture.StartAsync(
services =>
{
services.AddLogging();
services.AddSingleton(configured);
services.AddSingleton<ITransportBindingRegistry>(TestTransportBindings.WithAllSchemes());
services.AddSingleton(new ServerComplexTypeOptions { Enabled = false });
services.AddOpcUa().AddServer<RegistryCaptureServer>(
options => ConfigureHostedOptions(options, "SessionBindings"));
}).ConfigureAwait(false);
Assert.That(
await WaitForAsync(
() => RegistryCaptureServer.StartedInstance != null,
TimeSpan.FromSeconds(60)).ConfigureAwait(false),
Is.True);
Assert.That(RegistryCaptureServer.StartedInstance!.SessionBindingProvider, Is.SameAs(configured));
}
/// <summary>
/// Verifies that the fluent builder rejects a budget that is not positive.
/// </summary>
[Test]
public void WithChunkReassemblyBudgetRejectsABudgetThatIsNotPositive()
{
IOpcUaServerBuilder builder = new ServiceCollection().AddOpcUa().AddServer(_ => { });
Assert.That(
() => builder.WithChunkReassemblyBudget(0),
Throws.TypeOf<ArgumentOutOfRangeException>());
Assert.That(
() => ((IOpcUaServerBuilder)null!).WithChunkReassemblyBudget(1),
Throws.ArgumentNullException);
}
[TestCase(0, 0)]
[TestCase(1024, -1)]
[TestCase(1024, 1025)]
public void ExplicitChunkBudgetShareIsValidatedDuringRegistration(long maxBytes, long sessionlessBytes)
{
IOpcUaServerBuilder builder = new ServiceCollection().AddOpcUa().AddServer(_ => { });
Assert.That(
() => builder.WithChunkReassemblyBudget(maxBytes, sessionlessBytes),
Throws.TypeOf<ArgumentOutOfRangeException>());
}
private static void ConfigureHostedOptions(OpcUaServerOptions options, string applicationName)
{
string testRoot = System.IO.Path.Combine(
TestContext.CurrentContext.WorkDirectory,
nameof(OpcUaServerHostedServiceCoverageTests),
applicationName,
Guid.NewGuid().ToString("N"));
options.ApplicationName = applicationName;
options.ApplicationUri = "urn:localhost:" + applicationName;
options.ProductUri = "urn:localhost:" + applicationName + ":product";
options.PkiRoot = System.IO.Path.Combine(testRoot, "pki");
options.AutoAcceptUntrustedCertificates = true;
options.IncludeUnsecurePolicyNone = true;
options.EndpointUrls.Clear();
options.EndpointUrls.Add(
"opc.tcp://localhost:" +
GetAvailablePort().ToString(CultureInfo.InvariantCulture) +
"/" +
applicationName);
}
private static int GetAvailablePort()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
try
{
return ((IPEndPoint)listener.LocalEndpoint).Port;
}
finally
{
listener.Stop();
}
}
private static async Task<bool> WaitForAsync(Func<bool> condition, TimeSpan timeout)
{
DateTime deadline = DateTime.UtcNow + timeout;
while (DateTime.UtcNow < deadline)
{
if (condition())
{
return true;
}
await Task.Delay(100).ConfigureAwait(false);
}
return condition();
}
private static string Base64UrlEncode(byte[] bytes)
{
return Convert.ToBase64String(bytes)
.TrimEnd('=')
.Replace('+', '-')
.Replace('/', '_');
}
/// <summary>
/// A plain <see cref="StandardServer"/> (i.e. not a
/// <see cref="DependencyInjectionStandardServer"/>) whose
/// <c>CurrentInstance</c> is the stock <c>ServerInternalData</c>,
/// which implements <see cref="IHistorianRegistryProvider"/> and
/// <see cref="IAliasNameStoreRegistryProvider"/>. The hosted service
/// stages both registries before this server's node managers start.
/// </summary>
[SuppressMessage(
"Performance",
"CA1812:Avoid uninstantiated internal classes",
Justification = "Instantiated by the DI container through AddServer<TServer>.")]
private sealed class RegistryCaptureServer : StandardServer
{
public RegistryCaptureServer(ITelemetryContext telemetry, TimeProvider timeProvider)
: base(telemetry, timeProvider)
{
StartedInstance = this;
}
public static IServerInternal? StartedServer { get; private set; }
public static RegistryCaptureServer? StartedInstance { get; private set; }
public static void Reset()
{
StartedServer = null;
StartedInstance = null;
}
protected override void OnServerStarted(IServerInternal server)
{
StartedServer = server;
base.OnServerStarted(server);
}
}
private sealed class HostedServerFixture : IAsyncDisposable
{
private HostedServerFixture(ServiceProvider provider, IHostedService hostedService)
{
m_provider = provider;
m_hostedService = hostedService;
}
public static async ValueTask<HostedServerFixture> StartAsync(
Action<IServiceCollection> configureServices)
{
var services = new ServiceCollection();
configureServices(services);
ServiceProvider provider = services.BuildServiceProvider();
IHostedService hostedService = provider.GetServices<IHostedService>().Single();
try
{
await hostedService.StartAsync(CancellationToken.None).ConfigureAwait(false);
return new HostedServerFixture(provider, hostedService);
}
catch
{
await provider.DisposeAsync().ConfigureAwait(false);
throw;
}
}
public async ValueTask DisposeAsync()
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
try
{
await m_hostedService.StopAsync(cts.Token).ConfigureAwait(false);
}
finally
{
await m_provider.DisposeAsync().ConfigureAwait(false);
}
}
private readonly ServiceProvider m_provider;
private readonly IHostedService m_hostedService;
}
private sealed class CapturingLoggerProvider : ILoggerProvider
{
public ConcurrentBag<string> Messages { get; } = [];
public ILogger CreateLogger(string categoryName)
{
return new CapturingLogger(Messages);
}
public void Dispose()
{
}
}
private sealed class CapturingLogger : ILogger
{
public CapturingLogger(ConcurrentBag<string> messages)
{
m_messages = messages;
}
public IDisposable BeginScope<TState>(TState state)
where TState : notnull
{
return NoopDisposable.Instance;
}
public bool IsEnabled(LogLevel logLevel)
{
return true;
}
public void Log<TState>(
LogLevel logLevel,
EventId eventId,
TState state,
Exception? exception,
Func<TState, Exception?, string> formatter)
{
m_messages.Add(formatter(state, exception));
}
private readonly ConcurrentBag<string> m_messages;
}
private sealed class NoopDisposable : IDisposable
{
public static readonly NoopDisposable Instance = new();
public void Dispose()
{
}
}
}
}