Files
UA-.NETStandard/Libraries/Opc.Ua.PubSub/UaPubSubApplication.cs
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

503 lines
21 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 Microsoft.Extensions.Logging;
using Opc.Ua.PubSub.Configuration;
using Opc.Ua.PubSub.PublishedData;
using Opc.Ua.Security.Certificates;
using Opc.Ua.Test;
namespace Opc.Ua.PubSub
{
/// <summary>
/// A class that runs an OPC UA PubSub application.
/// </summary>
public class UaPubSubApplication : IDisposable
{
private readonly List<IUaPubSubConnection> m_uaPubSubConnections;
private readonly ITelemetryContext m_telemetry;
private readonly ILogger m_logger;
/// <summary>
/// Event that is triggered when the <see cref="UaPubSubApplication"/> receives a message via its active connections
/// </summary>
public event EventHandler<RawDataReceivedEventArgs>? RawDataReceived;
/// <summary>
/// Event that is triggered when the <see cref="UaPubSubApplication"/> receives and decodes subscribed DataSets
/// </summary>
public event EventHandler<SubscribedDataEventArgs>? DataReceived;
/// <summary>
/// Event that is triggered when the <see cref="UaPubSubApplication"/> receives and decodes subscribed DataSet MetaData
/// </summary>
public event EventHandler<SubscribedDataEventArgs>? MetaDataReceived;
/// <summary>
/// Event that is triggered when the <see cref="UaPubSubApplication"/> receives and decodes subscribed DataSet PublisherEndpoints
/// </summary>
public event EventHandler<PublisherEndpointsEventArgs>? PublisherEndpointsReceived;
/// <summary>
/// Event that is triggered before the configuration is updated with a new MetaData
/// The configuration will not be updated if <see cref="ConfigurationUpdatingEventArgs.Cancel"/> flag is set on true.
/// </summary>
public event EventHandler<ConfigurationUpdatingEventArgs>? ConfigurationUpdating;
/// <summary>
/// Event that is triggered when the <see cref="UaPubSubApplication"/> receives and decodes subscribed DataSet MetaData
/// </summary>
public event EventHandler<DataSetWriterConfigurationEventArgs>? DataSetWriterConfigurationReceived;
/// <summary>
/// Raised when the MQTT broker certificate is validated.
/// </summary>
/// <returns>
/// Returns whether the broker certificate is valid and trusted.
/// </returns>
public ValidateBrokerCertificateHandler? OnValidateBrokerCertificate;
/// <summary>
/// Initializes a new instance of the <see cref="UaPubSubApplication"/> class.
/// </summary>
/// <param name="telemetry">The telemetry context to use to create obvservability instruments</param>
/// <param name="dataStore">The current implementation of <see cref="IUaPubSubDataStore"/>
/// used by this instance of pub sub application</param>
/// <param name="applicationId"> The application id for instance.</param>
/// <param name="timeProvider">The optional <see cref="System.TimeProvider"/>
/// used for timer and duration calculations. Defaults to
/// <see cref="TimeProvider.System"/> when <c>null</c>.</param>
private UaPubSubApplication(
ITelemetryContext telemetry,
IUaPubSubDataStore? dataStore = null,
string? applicationId = null,
TimeProvider? timeProvider = null)
{
m_logger = telemetry.CreateLogger<UaPubSubApplication>();
m_uaPubSubConnections = [];
m_telemetry = telemetry;
DataStore = dataStore ?? new UaPubSubDataStore();
TimeProvider = timeProvider ?? TimeProvider.System;
if (!string.IsNullOrEmpty(applicationId))
{
ApplicationId = applicationId!;
}
else
{
ApplicationId = $"opcua:{System.Net.Dns.GetHostName()}:{RandomSource.Default.NextInt32(int.MaxValue):D10}";
}
DataCollector = new DataCollector(DataStore, m_telemetry);
UaPubSubConfigurator = new UaPubSubConfigurator(m_telemetry);
UaPubSubConfigurator.ConnectionAdded += UaPubSubConfigurator_ConnectionAdded;
UaPubSubConfigurator.ConnectionRemoved += UaPubSubConfigurator_ConnectionRemoved;
UaPubSubConfigurator.PublishedDataSetAdded
+= UaPubSubConfigurator_PublishedDataSetAdded;
UaPubSubConfigurator.PublishedDataSetRemoved
+= UaPubSubConfigurator_PublishedDataSetRemoved;
m_logger.LogInformation("An instance of UaPubSubApplication was created.");
}
/// <summary>
/// The application id associated with the UA
/// </summary>
public string ApplicationId { get; set; }
/// <summary>
/// Get the list of SupportedTransportProfiles
/// </summary>
public static string[] SupportedTransportProfiles =>
[Profiles.PubSubUdpUadpTransport, Profiles.PubSubMqttJsonTransport, Profiles
.PubSubMqttUadpTransport];
/// <summary>
/// Get reference to the associated <see cref="UaPubSubConfigurator"/> instance.
/// </summary>
public UaPubSubConfigurator UaPubSubConfigurator { get; }
/// <summary>
/// Get reference to current DataStore. Write here all node values needed to be
/// published by this PubSubApplication
/// </summary>
public IUaPubSubDataStore DataStore { get; }
/// <summary>
/// Get the read only list of <see cref="UaPubSubConnection"/> created for this
/// Application instance
/// </summary>
public ArrayOf<IUaPubSubConnection> PubSubConnections => m_uaPubSubConnections.ToArrayOf();
/// <summary>
/// Get reference to current configured DataCollector for this UaPubSubApplication
/// </summary>
internal DataCollector DataCollector { get; }
/// <summary>
/// Gets the <see cref="System.TimeProvider"/> used by this PubSub application and
/// all components it owns (connections, publishers, discovery, metadata publishers,
/// interval runners) for timer and duration calculations.
/// </summary>
public TimeProvider TimeProvider { get; }
/// <summary>
/// Creates a new <see cref="UaPubSubApplication"/> and associates it with a
/// custom implementation of <see cref="IUaPubSubDataStore"/>.
/// </summary>
/// <param name="dataStore"> The current implementation of <see cref="IUaPubSubDataStore"/>
/// used by this instance of pub sub application</param>
/// <param name="telemetry">The telemetry context to use to create obvservability instruments</param>
/// <param name="timeProvider">Optional <see cref="System.TimeProvider"/> for timer and
/// duration calculations. Defaults to <see cref="TimeProvider.System"/> when <c>null</c>.</param>
/// <returns>New instance of <see cref="UaPubSubApplication"/></returns>
public static UaPubSubApplication Create(
IUaPubSubDataStore dataStore,
ITelemetryContext telemetry,
TimeProvider? timeProvider = null)
{
return Create(
new PubSubConfigurationDataType { Enabled = true },
dataStore,
telemetry,
timeProvider);
}
/// <summary>
/// Creates a new <see cref="UaPubSubApplication"/> by loading the configuration parameters
/// from the specified path.
/// </summary>
/// <param name="configFilePath">The path of the configuration path.</param>
/// <param name="telemetry">The telemetry context to use to create obvservability instruments</param>
/// <param name="dataStore"> The current implementation of <see cref="IUaPubSubDataStore"/>
/// used by this instance of pub sub application</param>
/// <param name="timeProvider">Optional <see cref="System.TimeProvider"/> for timer and
/// duration calculations. Defaults to <see cref="TimeProvider.System"/> when <c>null</c>.</param>
/// <returns>New instance of <see cref="UaPubSubApplication"/></returns>
/// <exception cref="ArgumentNullException"><paramref name="configFilePath"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException"></exception>
public static UaPubSubApplication Create(
string configFilePath,
ITelemetryContext telemetry,
IUaPubSubDataStore? dataStore = null,
TimeProvider? timeProvider = null)
{
// validate input argument
if (configFilePath == null)
{
throw new ArgumentNullException(nameof(configFilePath));
}
if (!File.Exists(configFilePath))
{
throw new ArgumentException(
"The specified file {0} does not exist",
configFilePath);
}
PubSubConfigurationDataType pubSubConfiguration =
UaPubSubConfigurationHelper.LoadConfiguration(configFilePath, telemetry);
return Create(pubSubConfiguration, dataStore, telemetry, timeProvider);
}
/// <summary>
/// Creates a new <see cref="UaPubSubApplication"/> by loading the configuration parameters from the
/// specified <see cref="PubSubConfigurationDataType"/> parameter.
/// </summary>
/// <param name="telemetry">Telemetry context to use</param>
/// <param name="timeProvider">Optional <see cref="System.TimeProvider"/> for timer and
/// duration calculations. Defaults to <see cref="TimeProvider.System"/> when <c>null</c>.</param>
/// <returns>New instance of <see cref="UaPubSubApplication"/></returns>
public static UaPubSubApplication Create(
ITelemetryContext telemetry,
TimeProvider? timeProvider = null)
{
return Create(null!, null, telemetry, timeProvider);
}
/// <summary>
/// Creates a new <see cref="UaPubSubApplication"/> by loading the configuration parameters from the
/// specified <see cref="PubSubConfigurationDataType"/> parameter.
/// </summary>
/// <param name="pubSubConfiguration">The configuration object.</param>
/// <param name="telemetry">Telemetry context to use</param>
/// <param name="timeProvider">Optional <see cref="System.TimeProvider"/> for timer and
/// duration calculations. Defaults to <see cref="TimeProvider.System"/> when <c>null</c>.</param>
/// <returns>New instance of <see cref="UaPubSubApplication"/></returns>
public static UaPubSubApplication Create(
PubSubConfigurationDataType pubSubConfiguration,
ITelemetryContext telemetry,
TimeProvider? timeProvider = null)
{
return Create(pubSubConfiguration, null, telemetry, timeProvider);
}
/// <summary>
/// Creates a new <see cref="UaPubSubApplication"/> by loading the configuration parameters from the
/// specified <see cref="PubSubConfigurationDataType"/> parameter.
/// </summary>
/// <param name="pubSubConfiguration">The configuration object.</param>
/// <param name="dataStore"> The current implementation of <see cref="IUaPubSubDataStore"/>
/// used by this instance of pub sub application</param>
/// <param name="telemetry">Telemetry context to use</param>
/// <param name="timeProvider">Optional <see cref="System.TimeProvider"/> for timer and
/// duration calculations. Defaults to <see cref="TimeProvider.System"/> when <c>null</c>.</param>
/// <returns>New instance of <see cref="UaPubSubApplication"/></returns>
public static UaPubSubApplication Create(
PubSubConfigurationDataType pubSubConfiguration,
IUaPubSubDataStore? dataStore,
ITelemetryContext telemetry,
TimeProvider? timeProvider = null)
{
// if no argument received, start with empty configuration
pubSubConfiguration ??= new PubSubConfigurationDataType { Enabled = true };
var uaPubSubApplication = new UaPubSubApplication(
telemetry,
dataStore,
timeProvider: timeProvider);
uaPubSubApplication.UaPubSubConfigurator.LoadConfiguration(pubSubConfiguration);
return uaPubSubApplication;
}
/// <summary>
/// Start Publish/Subscribe jobs associated with this instance
/// </summary>
public void Start()
{
m_logger.LogInformation("UaPubSubApplication is starting.");
foreach (IUaPubSubConnection connection in m_uaPubSubConnections)
{
connection.Start();
}
m_logger.LogInformation("UaPubSubApplication was started.");
}
/// <summary>
/// Stop Publish/Subscribe jobs associated with this instance
/// </summary>
public void Stop()
{
m_logger.LogInformation("UaPubSubApplication is stopping.");
foreach (IUaPubSubConnection connection in m_uaPubSubConnections)
{
connection.Stop();
}
m_logger.LogInformation("UaPubSubApplication is stopped.");
}
/// <summary>
/// Raise <see cref="RawDataReceived"/> event
/// </summary>
internal void RaiseRawDataReceivedEvent(RawDataReceivedEventArgs e)
{
try
{
RawDataReceived?.Invoke(this, e);
}
catch (Exception ex)
{
m_logger.LogError(ex, "UaPubSubApplication.RaiseRawDataReceivedEvent");
}
}
/// <summary>
/// Raise DataReceived event
/// </summary>
internal void RaiseDataReceivedEvent(SubscribedDataEventArgs e)
{
try
{
DataReceived?.Invoke(this, e);
}
catch (Exception ex)
{
m_logger.LogError(ex, "UaPubSubApplication.RaiseDataReceivedEvent");
}
}
/// <summary>
/// Raise MetaDataReceived event
/// </summary>
internal void RaiseMetaDataReceivedEvent(SubscribedDataEventArgs e)
{
try
{
MetaDataReceived?.Invoke(this, e);
}
catch (Exception ex)
{
m_logger.LogError(ex, "UaPubSubApplication.RaiseMetaDataReceivedEvent");
}
}
/// <summary>
/// Raise DatasetWriterConfigurationReceived event
/// </summary>
internal void RaiseDatasetWriterConfigurationReceivedEvent(
DataSetWriterConfigurationEventArgs e)
{
try
{
DataSetWriterConfigurationReceived?.Invoke(this, e);
}
catch (Exception ex)
{
m_logger.LogError(ex, "UaPubSubApplication.DatasetWriterConfigurationReceivedEvent");
}
}
/// <summary>
/// Raise PublisherEndpointsReceived event
/// </summary>
internal void RaisePublisherEndpointsReceivedEvent(PublisherEndpointsEventArgs e)
{
try
{
PublisherEndpointsReceived?.Invoke(this, e);
}
catch (Exception ex)
{
m_logger.LogError(ex, "UaPubSubApplication.RaisePublisherEndpointsReceivedEvent");
}
}
/// <summary>
/// Raise <see cref="ConfigurationUpdating"/> event
/// </summary>
internal void RaiseConfigurationUpdatingEvent(ConfigurationUpdatingEventArgs e)
{
try
{
ConfigurationUpdating?.Invoke(this, e);
}
catch (Exception ex)
{
m_logger.LogError(ex, "UaPubSubApplication.RaiseConfigurationUpdatingEvent");
}
}
/// <summary>
/// Handler for PublishedDataSetAdded event
/// </summary>
private void UaPubSubConfigurator_PublishedDataSetAdded(
object? sender,
PublishedDataSetEventArgs e)
{
DataCollector.AddPublishedDataSet(e.PublishedDataSetDataType);
}
/// <summary>
/// Handler for PublishedDataSetRemoved event
/// </summary>
private void UaPubSubConfigurator_PublishedDataSetRemoved(
object? sender,
PublishedDataSetEventArgs e)
{
DataCollector.RemovePublishedDataSet(e.PublishedDataSetDataType);
}
/// <summary>
/// Handler for ConnectionRemoved event
/// </summary>
private void UaPubSubConfigurator_ConnectionRemoved(object? sender, ConnectionEventArgs e)
{
IUaPubSubConnection? removedUaPubSubConnection = null;
foreach (IUaPubSubConnection connection in m_uaPubSubConnections)
{
if (connection.PubSubConnectionConfiguration.Equals(e.PubSubConnectionDataType))
{
removedUaPubSubConnection = connection;
break;
}
}
if (removedUaPubSubConnection != null)
{
m_uaPubSubConnections.Remove(removedUaPubSubConnection);
removedUaPubSubConnection.Dispose();
}
}
/// <summary>
/// Handler for ConnectionAdded event
/// </summary>
private void UaPubSubConfigurator_ConnectionAdded(object? sender, ConnectionEventArgs e)
{
m_uaPubSubConnections.Add(ObjectFactory.CreateConnection(
this,
e.PubSubConnectionDataType,
m_telemetry));
}
/// <summary>
/// Releases all resources used by the current instance of the <see cref="UaPublisher"/> class.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// When overridden in a derived class, releases the unmanaged resources used by that class
/// and optionally releases the managed resources.
/// </summary>
/// <param name="disposing"> true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
UaPubSubConfigurator.ConnectionAdded -= UaPubSubConfigurator_ConnectionAdded;
UaPubSubConfigurator.ConnectionRemoved -= UaPubSubConfigurator_ConnectionRemoved;
UaPubSubConfigurator.PublishedDataSetAdded
-= UaPubSubConfigurator_PublishedDataSetAdded;
UaPubSubConfigurator.PublishedDataSetRemoved
-= UaPubSubConfigurator_PublishedDataSetRemoved;
Stop();
// free managed resources
foreach (IUaPubSubConnection connection in m_uaPubSubConnections)
{
connection.Dispose();
}
m_uaPubSubConnections.Clear();
}
}
}
/// <summary>
/// A delegate which validates the MQTT broker certificate.
/// </summary>
/// <param name="brokerCertificate">The broker certificate.</param>
/// <returns>Returns whether the broker certificate is valid and trusted.</returns>
public delegate bool ValidateBrokerCertificateHandler(Certificate brokerCertificate);
}