mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-20 08:41:51 +08:00
9b034f8291
# 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>
434 lines
17 KiB
C#
434 lines
17 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 Microsoft.Extensions.Time.Testing;
|
|
using Moq;
|
|
using NUnit.Framework;
|
|
using Opc.Ua.Tests;
|
|
|
|
#pragma warning disable CA2000, CA2007
|
|
|
|
namespace Opc.Ua.Client.Tests
|
|
{
|
|
/// <summary>
|
|
/// Tests for the keep alive liveness bookkeeping of <see cref="Session"/>.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Regression coverage for
|
|
/// https://github.com/OPCFoundation/UA-.NETStandard/issues/4317:
|
|
/// <see cref="Session.RequestCompleted"/> defers the keep alive read on every
|
|
/// good service response, so under steady request traffic the read never
|
|
/// fires. The freshness timestamp <see cref="Session.KeepAliveStopped"/> is
|
|
/// judged against therefore has to be refreshed by those responses as well,
|
|
/// otherwise the first pause in traffic reports BadNoCommunication on a
|
|
/// perfectly healthy session.
|
|
/// </remarks>
|
|
[TestFixture]
|
|
[Parallelizable]
|
|
[Category("Client")]
|
|
[Category("Session")]
|
|
[Category("KeepAlive")]
|
|
public sealed class SessionKeepAliveTests
|
|
{
|
|
private const int kKeepAliveInterval = 5_000;
|
|
|
|
/// <summary>
|
|
/// KeepAliveInterval * m_keepAliveIntervalFactor (1) + m_keepAliveGuardBand (1000).
|
|
/// </summary>
|
|
private static readonly TimeSpan s_pastKeepAliveThreshold =
|
|
TimeSpan.FromMilliseconds(kKeepAliveInterval + 1_000 + 1);
|
|
|
|
[Test]
|
|
public void KeepAliveStoppedTripsWhenNothingIsHeardFromTheServer()
|
|
{
|
|
var timeProvider = new FakeTimeProvider();
|
|
using KeepAliveTestSession session = CreateSession(timeProvider);
|
|
|
|
Assert.That(session.KeepAliveStopped, Is.False);
|
|
|
|
timeProvider.Advance(s_pastKeepAliveThreshold);
|
|
|
|
Assert.That(session.KeepAliveStopped, Is.True);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Steady traffic keeps the session alive even though the keep alive read
|
|
/// is deferred by every response and consequently never fires.
|
|
/// </summary>
|
|
[Test]
|
|
public void GoodResponsesKeepTheSessionAliveWhileTheKeepAliveReadIsDeferred()
|
|
{
|
|
var timeProvider = new FakeTimeProvider();
|
|
using KeepAliveTestSession session = CreateSession(timeProvider);
|
|
|
|
long initialTimestamp = session.LastKeepAliveTimestamp;
|
|
|
|
// a request every 2 s for 20 s - each response defers the keep alive
|
|
// read by a full interval, so no keep alive read is ever sent.
|
|
for (int ii = 0; ii < 10; ii++)
|
|
{
|
|
timeProvider.Advance(TimeSpan.FromSeconds(2));
|
|
session.CompleteRequest(StatusCodes.Good);
|
|
|
|
Assert.That(
|
|
session.KeepAliveStopped,
|
|
Is.False,
|
|
$"the server answered 2000 ms ago (iteration {ii})");
|
|
}
|
|
|
|
Assert.Multiple(() =>
|
|
{
|
|
Assert.That(session.KeepAliveStopped, Is.False);
|
|
Assert.That(session.LastKeepAliveTimestamp, Is.GreaterThan(initialTimestamp));
|
|
});
|
|
|
|
// once the traffic stops the session must still detect the silence.
|
|
timeProvider.Advance(s_pastKeepAliveThreshold);
|
|
|
|
Assert.That(session.KeepAliveStopped, Is.True);
|
|
}
|
|
|
|
/// <summary>
|
|
/// A good response also revives a timestamp that already went stale but
|
|
/// has not been reported as an error yet - the keep alive read is still
|
|
/// in flight, the worker is skipping while reconnecting, or its tick is
|
|
/// late. Without this no traffic could rescue the session from the
|
|
/// spurious BadNoCommunication the worker is about to raise.
|
|
/// </summary>
|
|
[Test]
|
|
public void GoodResponseRevivesAStaleTimestampWhenNoErrorIsLatched()
|
|
{
|
|
var timeProvider = new FakeTimeProvider();
|
|
using KeepAliveTestSession session = CreateSession(timeProvider);
|
|
|
|
timeProvider.Advance(s_pastKeepAliveThreshold);
|
|
Assert.That(session.KeepAliveStopped, Is.True);
|
|
|
|
session.CompleteRequest(StatusCodes.Good);
|
|
|
|
Assert.That(
|
|
session.KeepAliveStopped,
|
|
Is.False,
|
|
"a good response must count as proof of liveness");
|
|
}
|
|
|
|
[Test]
|
|
public void BadResponsesDoNotRefreshTheKeepAliveTimestamp()
|
|
{
|
|
var timeProvider = new FakeTimeProvider();
|
|
using KeepAliveTestSession session = CreateSession(timeProvider);
|
|
|
|
long initialTimestamp = session.LastKeepAliveTimestamp;
|
|
|
|
timeProvider.Advance(TimeSpan.FromMilliseconds(3_000));
|
|
session.CompleteRequest(StatusCodes.BadTimeout);
|
|
|
|
Assert.That(session.LastKeepAliveTimestamp, Is.EqualTo(initialTimestamp));
|
|
|
|
timeProvider.Advance(s_pastKeepAliveThreshold - TimeSpan.FromMilliseconds(3_000));
|
|
|
|
Assert.That(session.KeepAliveStopped, Is.True);
|
|
}
|
|
|
|
/// <summary>
|
|
/// A latched keep alive error is only cleared by an actual keep alive
|
|
/// response, never by unrelated traffic.
|
|
/// </summary>
|
|
[Test]
|
|
public void LatchedKeepAliveErrorIsNotClearedByAGoodResponse()
|
|
{
|
|
var timeProvider = new FakeTimeProvider();
|
|
using KeepAliveTestSession session = CreateSession(timeProvider);
|
|
|
|
session.RaiseKeepAliveError(StatusCodes.BadTimeout);
|
|
Assert.That(session.KeepAliveStopped, Is.True);
|
|
|
|
session.CompleteRequest(StatusCodes.Good);
|
|
|
|
Assert.That(session.KeepAliveStopped, Is.True);
|
|
}
|
|
|
|
/// <summary>
|
|
/// After BadNoCommunication was reported the recovery branch of
|
|
/// OnKeepAlive must still run, i.e. good responses arriving before the
|
|
/// keep alive read completes must not silently mark the session as
|
|
/// healthy again.
|
|
/// </summary>
|
|
[Test]
|
|
public void RecoveryAfterBadNoCommunicationIsHandledByTheKeepAliveResponse()
|
|
{
|
|
var timeProvider = new FakeTimeProvider();
|
|
using KeepAliveTestSession session = CreateSession(timeProvider);
|
|
|
|
timeProvider.Advance(s_pastKeepAliveThreshold);
|
|
session.RaiseKeepAliveError(StatusCodes.BadNoCommunication);
|
|
|
|
// the keep alive read itself completes as a good response first.
|
|
session.CompleteRequest(StatusCodes.Good);
|
|
Assert.That(
|
|
session.KeepAliveStopped,
|
|
Is.True,
|
|
"the keep alive error must survive until OnKeepAlive handled it");
|
|
|
|
session.RaiseKeepAlive();
|
|
|
|
Assert.Multiple(() =>
|
|
{
|
|
Assert.That(
|
|
session.KeepAliveStoppedOnEnteringOnKeepAlive,
|
|
Is.True,
|
|
"OnKeepAlive must take the recovery branch");
|
|
Assert.That(session.KeepAliveStopped, Is.False);
|
|
});
|
|
}
|
|
|
|
/// <summary>
|
|
/// Once the transport channel is detached the keep alive read fails with
|
|
/// BadSecureChannelClosed, which the keep alive worker reports through
|
|
/// OnKeepAliveError, and the next tick reports BadNoCommunication.
|
|
/// Neither report may dereference the missing channel: the endpoint url
|
|
/// in the log comes from the configured endpoint, not from the channel.
|
|
/// </summary>
|
|
[Test]
|
|
public void KeepAliveReadFailureIsReportedAfterTheChannelIsDetached()
|
|
{
|
|
AssertKeepAliveErrorIsReportedAfterTheChannelIsDetached(
|
|
StatusCodes.BadSecureChannelClosed);
|
|
}
|
|
|
|
/// <summary>
|
|
/// See <see cref="KeepAliveReadFailureIsReportedAfterTheChannelIsDetached"/>;
|
|
/// BadNoCommunication additionally logs KEEP ALIVE LATE with the endpoint url.
|
|
/// </summary>
|
|
[Test]
|
|
public void KeepAliveLateIsReportedAfterTheChannelIsDetached()
|
|
{
|
|
AssertKeepAliveErrorIsReportedAfterTheChannelIsDetached(
|
|
StatusCodes.BadNoCommunication);
|
|
}
|
|
|
|
private static void AssertKeepAliveErrorIsReportedAfterTheChannelIsDetached(
|
|
StatusCode statusCode)
|
|
{
|
|
var timeProvider = new FakeTimeProvider();
|
|
using KeepAliveTestSession session = CreateSession(timeProvider);
|
|
StatusCode reported = StatusCodes.Good;
|
|
session.KeepAlive += (_, e) => reported = e.Status?.StatusCode ?? StatusCodes.Good;
|
|
|
|
#pragma warning disable CS0618 // DetachChannel is obsolete
|
|
session.DetachChannel();
|
|
#pragma warning restore CS0618
|
|
|
|
timeProvider.Advance(s_pastKeepAliveThreshold);
|
|
Assert.DoesNotThrow(() => session.RaiseKeepAliveError(statusCode));
|
|
|
|
Assert.Multiple(() =>
|
|
{
|
|
Assert.That(reported, Is.EqualTo(statusCode));
|
|
Assert.That(session.KeepAliveStopped, Is.True);
|
|
});
|
|
}
|
|
|
|
/// <summary>
|
|
/// The keep alive read on a detached channel fails with a service error
|
|
/// the keep alive worker handles, not with an unexpected exception.
|
|
/// </summary>
|
|
[Test]
|
|
public void KeepAliveReadAfterTheChannelIsDetachedFailsWithBadSecureChannelClosed()
|
|
{
|
|
using KeepAliveTestSession session = CreateSession(new FakeTimeProvider());
|
|
|
|
#pragma warning disable CS0618 // DetachChannel is obsolete
|
|
session.DetachChannel();
|
|
#pragma warning restore CS0618
|
|
|
|
ServiceResultException sre = Assert.ThrowsAsync<ServiceResultException>(
|
|
async () => await session.ReadAsync(
|
|
new RequestHeader(),
|
|
0,
|
|
TimestampsToReturn.Neither,
|
|
new[]
|
|
{
|
|
new ReadValueId
|
|
{
|
|
NodeId = VariableIds.Server_ServerStatus_State,
|
|
AttributeId = Attributes.Value
|
|
}
|
|
}.ToArrayOf(),
|
|
default).ConfigureAwait(false));
|
|
|
|
Assert.That(sre.StatusCode, Is.EqualTo(StatusCodes.BadSecureChannelClosed));
|
|
}
|
|
|
|
private static KeepAliveTestSession CreateSession(TimeProvider timeProvider)
|
|
{
|
|
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
|
|
ApplicationConfiguration configuration = CreateClientConfiguration(telemetry);
|
|
IServiceMessageContext messageContext = configuration.CreateMessageContext();
|
|
var channel = new Mock<ITransportChannel>();
|
|
channel.SetupGet(c => c.MessageContext).Returns(messageContext);
|
|
|
|
var session = new KeepAliveTestSession(
|
|
channel.Object,
|
|
configuration,
|
|
CreateEndpoint(),
|
|
timeProvider)
|
|
{
|
|
KeepAliveInterval = kKeepAliveInterval
|
|
};
|
|
|
|
// establish the initial liveness baseline the keep alive timer start
|
|
// would normally provide, then forget what that call observed.
|
|
session.RaiseKeepAlive();
|
|
session.ResetKeepAliveObservation();
|
|
|
|
return session;
|
|
}
|
|
|
|
private static ApplicationConfiguration CreateClientConfiguration(
|
|
ITelemetryContext telemetry)
|
|
{
|
|
return new ApplicationConfiguration(telemetry)
|
|
{
|
|
ApplicationName = "SessionKeepAliveTests",
|
|
ApplicationType = ApplicationType.Client,
|
|
ApplicationUri = "urn:localhost:SessionKeepAliveTests",
|
|
ProductUri = "urn:localhost:SessionKeepAliveTests",
|
|
ClientConfiguration = new ClientConfiguration
|
|
{
|
|
DefaultSessionTimeout = 60000,
|
|
MinSubscriptionLifetime = 10000
|
|
},
|
|
SecurityConfiguration = new SecurityConfiguration
|
|
{
|
|
ApplicationCertificate = new CertificateIdentifier()
|
|
},
|
|
TransportQuotas = new TransportQuotas { OperationTimeout = 6000 }
|
|
};
|
|
}
|
|
|
|
private static ConfiguredEndpoint CreateEndpoint()
|
|
{
|
|
var description = new EndpointDescription
|
|
{
|
|
EndpointUrl = "opc.tcp://localhost:4840",
|
|
SecurityMode = MessageSecurityMode.None,
|
|
SecurityPolicyUri = SecurityPolicies.None,
|
|
TransportProfileUri = Profiles.UaTcpTransport,
|
|
UserIdentityTokens =
|
|
[
|
|
new UserTokenPolicy
|
|
{
|
|
PolicyId = "anonymous",
|
|
TokenType = UserTokenType.Anonymous,
|
|
SecurityPolicyUri = SecurityPolicies.None
|
|
}
|
|
]
|
|
};
|
|
description.Server.ApplicationUri = description.EndpointUrl;
|
|
description.Server.ApplicationType = ApplicationType.Server;
|
|
|
|
return new ConfiguredEndpoint(
|
|
null,
|
|
description,
|
|
new EndpointConfiguration { OperationTimeout = 6000 })
|
|
{
|
|
UpdateBeforeConnect = false
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// Exposes the protected keep alive hooks so the handling of service
|
|
/// responses can be driven without a server.
|
|
/// </summary>
|
|
private sealed class KeepAliveTestSession : Session
|
|
{
|
|
public KeepAliveTestSession(
|
|
ITransportChannel channel,
|
|
ApplicationConfiguration configuration,
|
|
ConfiguredEndpoint endpoint,
|
|
TimeProvider timeProvider)
|
|
: base(channel, configuration, endpoint, timeProvider: timeProvider)
|
|
{
|
|
}
|
|
|
|
/// <summary>
|
|
/// The value of <see cref="Session.KeepAliveStopped"/> observed when
|
|
/// <see cref="OnKeepAlive"/> was entered the last time.
|
|
/// </summary>
|
|
public bool? KeepAliveStoppedOnEnteringOnKeepAlive { get; private set; }
|
|
|
|
/// <summary>
|
|
/// Discards what <see cref="OnKeepAlive"/> observed so far.
|
|
/// </summary>
|
|
public void ResetKeepAliveObservation()
|
|
{
|
|
KeepAliveStoppedOnEnteringOnKeepAlive = null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Simulates a completed service call with the given service result.
|
|
/// </summary>
|
|
public void CompleteRequest(StatusCode serviceResult)
|
|
{
|
|
RequestCompleted(
|
|
new ReadRequest { RequestHeader = new RequestHeader() },
|
|
new ReadResponse
|
|
{
|
|
ResponseHeader = new ResponseHeader { ServiceResult = serviceResult }
|
|
},
|
|
nameof(Read));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Simulates a successful keep alive read response.
|
|
/// </summary>
|
|
public void RaiseKeepAlive()
|
|
{
|
|
OnKeepAlive(ServerState.Running, DateTime.UtcNow);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Simulates a failed keep alive read.
|
|
/// </summary>
|
|
public void RaiseKeepAliveError(StatusCode statusCode)
|
|
{
|
|
OnKeepAliveError(new ServiceResult(statusCode));
|
|
}
|
|
|
|
protected override void OnKeepAlive(ServerState currentState, DateTime currentTime)
|
|
{
|
|
KeepAliveStoppedOnEnteringOnKeepAlive = KeepAliveStopped;
|
|
base.OnKeepAlive(currentState, currentTime);
|
|
}
|
|
}
|
|
}
|
|
}
|