Files
Marc Schier dbc09b8e22 Adopt System.TimeProvider across the stack (fixes #2458) (#3829)
# Description

Adopt
[`System.TimeProvider`](https://learn.microsoft.com/dotnet/api/system.timeprovider)
across the stack so that every place that creates timers, runs duration
math, or schedules periodic work is mockable, deterministic in tests,
and immune to wall-clock changes.

The migration touches Core, Core.Types, Server, Client, PubSub,
Configuration, Gds (server + client), Lds, and the Quickstarts/Console
reference apps. Per-component changes follow the same pattern:

1. Add a `private readonly TimeProvider m_timeProvider;` field.
2. Accept a nullable `TimeProvider? timeProvider = null` as the **last**
constructor parameter (new overload; legacy constructor stays for binary
compatibility and delegates with `timeProvider: null`).
3. Initialise the field with `m_timeProvider = timeProvider ??=
TimeProvider.System;`.
4. Replace `new Timer(...)`, `Stopwatch`, `HiResClock.*`,
`DateTime.UtcNow`-based duration math, and `Task.Delay(delay, ct)` in
timing loops with the matching `m_timeProvider` API (`CreateTimer`,
`GetTimestamp` / `GetElapsedTime`, `GetUtcNow().UtcDateTime`,
`Task.Delay(delay, m_timeProvider, ct)`).
5. Wire the provider through DI: `AddOpcUaServerBuilder` /
`AddOpcUaClientBuilder` register `TimeProvider.System` via
`TryAddSingleton<TimeProvider>()` so tests can swap in
`Microsoft.Extensions.Time.Testing.FakeTimeProvider`.

`HiResClock` itself is kept (so the
`ApplicationConfiguration.DisableHiResClock` schema flag still
round-trips), but **every public member** is now `[Obsolete]` with a
single shared message pointing to the new migration-guide section. The
few internal call sites that still need to set/read `HiResClock` are
wrapped with `#pragma warning disable CS0618`.

### Highlights per component

- **Core / Stack** — `Opc.Ua.Core`, `Opc.Ua.Core.Types`, channel
pipeline (`UaSCBinaryClientChannel`, `ChannelToken`,
`UaSCBinaryChannel`), `ApplicationConfiguration`, certificate
validators, `JwksIssuerKeyResolver`, `TimeProviderExtensions` polyfills
(`GetTimestampMilliseconds`, `GetTickCount`,
`CancellationTokenSource(timeout, timeProvider)`, `Task.Delay(delay,
provider, ct)` polyfill for older TFMs).
- **Server** — session lockout, subscription pipeline
(publish/sample/keep-alive/lifetime), `MonitoredItemQueue`, alarm
sampling rate, `IntervalRunner`, server diagnostics, configuration state
machines, hosted services.
- **Client** — `Session`, managed/V2 subscription engines, reconnect
handlers, channel keep-alive, periodic publishing, complex-type
discovery polling.
- **PubSub** — `IntervalRunner` pipeline, message-receive timers,
MQTT/UDP keep-alive, publishers/readers.
- **Gds / Lds** — `LdsServer`, `LinqApplicationsDatabase` expiry
housekeeping, GDS clients (push, pull), `DirectoryCertificateStore`,
`ConnectionStateMachine`, classic subscription engine.
- **Quickstarts / Console samples** — `SampleNodeManager`,
`ReferenceNodeManager`, `AlarmNodeManager`, `BoilerState`,
`MemoryBufferState`, `PublishedValuesWrites`. Samples resolve via
`(Server as ITimeProviderProvider)?.TimeProvider ?? TimeProvider.System`
so existing ctor signatures stay binary-compatible.
- **Tests** — `Opc.Ua.PubSub.Tests` adds `IntervalRunnerTests`; existing
`SubscriptionTests`, `UaPublisherTests`, and `TestDataSystem` move off
`HiResClock`. Added `Microsoft.Extensions.TimeProvider.Testing` package
for `FakeTimeProvider` (project-load warning surfaces on net48/net472
only — runtime is .NET 8+).

### Migration guide

New section [**Time and Timer abstraction
(`TimeProvider`)**](Docs/MigrationGuide.md#time-and-timer-abstraction-timeprovider)
documents:

- The canonical replacement table (`HiResClock.UtcNow` →
`timeProvider.GetUtcNow().UtcDateTime`, `HiResClock.TickCount64` →
`timeProvider.GetTimestamp()`, `new Timer` → `timeProvider.CreateTimer`,
`Task.Delay(delay, ct)` → `Task.Delay(delay, timeProvider, ct)`, …).
- The `TimeProvider? timeProvider = null` + `??=` constructor pattern.
- DI wiring and how to swap in `FakeTimeProvider` in tests.
- Before/after snippets for `HiResClock.TickCount64`,
`HiResClock.UtcNow`, and `new Timer(...)`.

## Related Issues

- Fixes #2458

## Checklist

- [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.
2026-06-03 22:38:32 +02:00

537 lines
20 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.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Opc.Ua.Server
{
/// <summary>
/// Reverse connection states.
/// </summary>
public enum ReverseConnectState
{
/// <summary>
/// The connection is closed.
/// </summary>
Closed = 0,
/// <summary>
/// The server is connecting.
/// </summary>
Connecting = 1,
/// <summary>
/// The server is connected with a client.
/// </summary>
Connected = 2,
/// <summary>
/// The client rejected the connection with the server.
/// </summary>
Rejected = 3,
/// <summary>
/// An error occurred connecting with the client.
/// </summary>
Errored = 4
}
/// <summary>
/// Describes the properties of a server reverse connection.
/// </summary>
public class ReverseConnectProperty
{
/// <summary>
/// Initialize a reverse connect server property.
/// </summary>
/// <param name="clientUrl">The Url of the reverse connect client.</param>
/// <param name="timeout">The timeout to use for a reverse connect attempt.</param>
/// <param name="maxSessionCount">The maximum number of sessions allowed to the client.</param>
/// <param name="configEntry">If this is an application configuration entry.</param>
/// <param name="enabled">If the connection is enabled.</param>
public ReverseConnectProperty(
Uri clientUrl,
int timeout,
int maxSessionCount,
bool configEntry,
bool enabled = true)
{
ClientUrl = clientUrl;
Timeout = timeout > 0 ? timeout : ReverseConnectServer.DefaultReverseConnectTimeout;
MaxSessionCount = maxSessionCount;
ConfigEntry = configEntry;
Enabled = enabled;
}
/// <summary>
/// The Url of the reverse connect client.
/// </summary>
public readonly Uri ClientUrl;
/// <summary>
/// The timeout to use for a reverse connect attempt.
/// </summary>
public readonly int Timeout;
/// <summary>
/// If this is an application configuration entry.
/// </summary>
public readonly bool ConfigEntry;
/// <summary>
/// The service result of the last connection attempt.
/// </summary>
public ServiceResult? ServiceResult;
/// <summary>
/// The last state of the reverse connection.
/// </summary>
public ReverseConnectState LastState = ReverseConnectState.Closed;
/// <summary>
/// The maximum number of sessions allowed to the client.
/// </summary>
public int MaxSessionCount;
/// <summary>
/// If the connection is enabled.
/// </summary>
public bool Enabled;
/// <summary>
/// The time when the connection was rejected.
/// </summary>
public DateTime RejectTime;
}
/// <summary>
/// The standard implementation of a UA server with reverse connect.
/// </summary>
public class ReverseConnectServer : StandardServer
{
/// <summary>
/// The default reverse connect interval.
/// </summary>
public static int DefaultReverseConnectInterval => 15000;
/// <summary>
/// The default reverse connect timeout.
/// </summary>
public static int DefaultReverseConnectTimeout => 30000;
/// <summary>
/// The default timeout after a rejected connection attempt.
/// </summary>
public static int DefaultReverseConnectRejectTimeout => 60000;
/// <summary>
/// Creates a reverse connect server based on a StandardServer.
/// </summary>
public ReverseConnectServer(ITelemetryContext telemetry)
: this(telemetry, null)
{
}
/// <summary>
/// Creates a reverse connect server with an explicit
/// <see cref="TimeProvider"/> so the reverse-connect timer and
/// expiry logic can be mocked in tests.
/// </summary>
/// <param name="telemetry">The telemetry context.</param>
/// <param name="timeProvider">The time provider used for all
/// time / duration calculations, or <c>null</c> to use
/// <see cref="TimeProvider.System"/>.</param>
public ReverseConnectServer(ITelemetryContext telemetry, TimeProvider? timeProvider)
: base(telemetry, timeProvider)
{
m_connectInterval = DefaultReverseConnectInterval;
m_connectTimeout = DefaultReverseConnectTimeout;
m_rejectTimeout = DefaultReverseConnectRejectTimeout;
m_connections = [];
}
/// <inheritdoc/>
protected override void OnServerStarted(IServerInternal server)
{
base.OnServerStarted(server);
UpdateConfiguration(Configuration!);
StartTimer(true);
}
/// <inheritdoc />
protected override async ValueTask OnUpdateConfigurationAsync(ApplicationConfiguration configuration, CancellationToken cancellationToken = default)
{
await base.OnUpdateConfigurationAsync(configuration, cancellationToken)
.ConfigureAwait(false);
UpdateConfiguration(configuration);
}
/// <inheritdoc />
protected override ValueTask OnServerStoppingAsync(CancellationToken cancellationToken = default)
{
DisposeTimer();
return base.OnServerStoppingAsync(cancellationToken);
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
if (disposing)
{
m_reverseConnectTimer?.Dispose();
m_reverseConnectTimer = null;
}
base.Dispose(disposing);
}
/// <summary>
/// Add a reverse connection url.
/// </summary>
/// <exception cref="ArgumentException"></exception>
public virtual void AddReverseConnection(
Uri url,
int timeout = 0,
int maxSessionCount = 0,
bool enabled = true)
{
if (m_connections.ContainsKey(url))
{
throw new ArgumentException(
"Connection for specified clientUrl is already configured",
nameof(url));
}
var reverseConnection = new ReverseConnectProperty(
url,
timeout,
maxSessionCount,
false,
enabled);
lock (m_connectionsLock)
{
m_connections[url] = reverseConnection;
m_logger.LogInformation("Reverse Connection added for EndpointUrl: {Url}.", url);
StartTimer(false);
}
}
/// <summary>
/// Remove a reverse connection url.
/// </summary>
/// <returns>true if the reverse connection is found and removed</returns>
/// <exception cref="ArgumentNullException"><paramref name="url"/> is <c>null</c>.</exception>
public virtual bool RemoveReverseConnection(Uri url)
{
if (url == null)
{
throw new ArgumentNullException(nameof(url));
}
lock (m_connectionsLock)
{
bool connectionRemoved = m_connections.Remove(url);
if (connectionRemoved)
{
m_logger.LogInformation("Reverse Connection removed for EndpointUrl: {Url}.", url);
}
if (m_connections.Count == 0)
{
DisposeTimer();
}
return connectionRemoved;
}
}
/// <summary>
/// Return a dictionary of configured reverse connection Urls.
/// </summary>
public virtual ReadOnlyDictionary<Uri, ReverseConnectProperty> GetReverseConnections()
{
lock (m_connectionsLock)
{
return new ReadOnlyDictionary<Uri, ReverseConnectProperty>(m_connections);
}
}
/// <summary>
/// Timer callback to establish new reverse connections.
/// </summary>
private void OnReverseConnect(object? state)
{
try
{
lock (m_connectionsLock)
{
foreach (ReverseConnectProperty reverseConnection in m_connections.Values)
{
// recharge a rejected connection after timeout
if (reverseConnection.LastState == ReverseConnectState.Rejected &&
reverseConnection.RejectTime +
TimeSpan.FromMilliseconds(m_rejectTimeout) <
TimeProvider.GetUtcNow().UtcDateTime)
{
reverseConnection.LastState = ReverseConnectState.Closed;
}
// try the reverse connect
if (reverseConnection.Enabled &&
(
reverseConnection.MaxSessionCount == 0 ||
(
reverseConnection.MaxSessionCount == 1 &&
reverseConnection.LastState == ReverseConnectState.Closed
) ||
reverseConnection.MaxSessionCount > ServerInternal.SessionManager
.GetSessions()
.Count))
{
try
{
reverseConnection.LastState = ReverseConnectState.Connecting;
CreateConnection(
reverseConnection.ClientUrl,
reverseConnection.Timeout > 0
? reverseConnection.Timeout
: m_connectTimeout);
m_logger.LogInformation(
"Create Connection! [{LastState}][{ClientUrl}]",
reverseConnection.LastState,
reverseConnection.ClientUrl);
}
catch (Exception e)
{
reverseConnection.LastState = ReverseConnectState.Errored;
reverseConnection.ServiceResult = new ServiceResult(e);
m_logger.LogError(
"Create Connection failed! [{LastState}][{ClientUrl}]",
reverseConnection.LastState,
reverseConnection.ClientUrl);
}
}
}
}
}
catch (Exception ex)
{
m_logger.LogError(ex, "OnReverseConnect unexpected error");
}
finally
{
StartTimer(true);
}
}
/// <summary>
/// Track reverse connection status.
/// </summary>
protected override void OnConnectionStatusChanged(
object? sender,
ConnectionStatusEventArgs e)
{
lock (m_connectionsLock)
{
if (m_connections.TryGetValue(
e.EndpointUrl,
out ReverseConnectProperty? reverseConnection))
{
if (ServiceResult.IsBad(e.ChannelStatus))
{
reverseConnection.ServiceResult = e.ChannelStatus;
if (e.ChannelStatus.Code == StatusCodes.BadTcpMessageTypeInvalid)
{
reverseConnection.LastState = ReverseConnectState.Rejected;
reverseConnection.RejectTime = TimeProvider.GetUtcNow().UtcDateTime;
m_logger.LogWarning(
"Client Rejected Connection! [{LastState}][{EndpointUrl}]",
reverseConnection.LastState,
e.EndpointUrl);
return;
}
reverseConnection.LastState = ReverseConnectState.Closed;
m_logger.LogError(
"Connection Error! [{LastState}][{EndpointUrl}]",
reverseConnection.LastState,
e.EndpointUrl);
return;
}
reverseConnection.LastState = e.Closed
? ReverseConnectState.Closed
: ReverseConnectState.Connected;
m_logger.LogInformation(
"New Connection State! [{LastState}][{EndpointUrl}]",
reverseConnection.LastState,
e.EndpointUrl);
}
else
{
m_logger.LogWarning(
"Warning: Status changed for unknown reverse connection: [{ChannelStatus}][{EndpointUrl}]",
e.ChannelStatus,
e.EndpointUrl);
}
}
base.OnConnectionStatusChanged(sender, e);
}
/// <summary>
/// Restart the timer.
/// </summary>
private void StartTimer(bool forceRestart)
{
if (forceRestart)
{
DisposeTimer();
}
lock (m_connectionsLock)
{
if (m_connectInterval > 0 &&
m_connections.Count > 0 &&
m_reverseConnectTimer == null)
{
m_reverseConnectTimer = TimeProvider.CreateTimer(
OnReverseConnect,
this,
TimeSpan.FromMilliseconds(forceRestart ? m_connectInterval : 1000),
Timeout.InfiniteTimeSpan);
}
}
}
/// <summary>
/// Dispose the current timer.
/// </summary>
private void DisposeTimer()
{
// start registration timer.
lock (m_connectionsLock)
{
m_reverseConnectTimer?.Dispose();
m_reverseConnectTimer = null;
}
}
/// <summary>
/// Remove a reverse connection url.
/// </summary>
private void ClearConnections(bool configEntry)
{
lock (m_connectionsLock)
{
foreach (
KeyValuePair<Uri, ReverseConnectProperty> entry in m_connections.Where(r =>
r.Value.ConfigEntry == configEntry))
{
m_connections.Remove(entry.Key);
}
}
}
/// <summary>
/// Update the reverse connect configuration from the application configuration.
/// </summary>
private void UpdateConfiguration(ApplicationConfiguration configuration)
{
ClearConnections(true);
// get the configuration for the reverse connections.
ReverseConnectServerConfiguration? reverseConnect = configuration?.ServerConfiguration?
.ReverseConnect;
// add configuration reverse client connection properties.
if (reverseConnect != null)
{
lock (m_connectionsLock)
{
m_connectInterval =
reverseConnect.ConnectInterval > 0
? reverseConnect.ConnectInterval
: DefaultReverseConnectInterval;
m_connectTimeout =
reverseConnect.ConnectTimeout > 0
? reverseConnect.ConnectTimeout
: DefaultReverseConnectTimeout;
m_rejectTimeout =
reverseConnect.RejectTimeout > 0
? reverseConnect.RejectTimeout
: DefaultReverseConnectRejectTimeout;
if (!reverseConnect.Clients.IsEmpty)
{
foreach (ReverseConnectClient client in reverseConnect.Clients)
{
Uri? uri = Utils.ParseUri(client.EndpointUrl);
if (uri != null)
{
if (m_connections.ContainsKey(uri))
{
m_logger.LogWarning(
"Warning: ServerConfiguration.ReverseConnect contains duplicate EndpointUrl: {Uri}.",
uri);
}
else
{
m_connections[uri] = new ReverseConnectProperty(
uri,
client.Timeout,
client.MaxSessionCount,
true,
client.Enabled);
m_logger.LogInformation(
"Reverse Connection added for EndpointUrl: {Uri}.",
uri);
}
}
}
}
}
}
}
private ITimer? m_reverseConnectTimer;
private int m_connectInterval;
private int m_connectTimeout;
private int m_rejectTimeout;
private readonly Dictionary<Uri, ReverseConnectProperty> m_connections;
private readonly Lock m_connectionsLock = new();
}
}