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

250 lines
9.1 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.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Opc.Ua.PubSub
{
/// <summary>
/// component that is specialized in calculating and executing a routine for a given interval
/// </summary>
public class IntervalRunner : IDisposable
{
private const int kMinInterval = 10;
private readonly Lock m_lock = new();
private readonly ILogger m_logger;
private readonly TimeProvider m_timeProvider;
private double m_interval = kMinInterval;
private double m_nextPublishTick;
/// <summary>
/// event used to cancel run
/// </summary>
private CancellationTokenSource? m_cancellationToken = new();
/// <summary>
/// Create new instance of <see cref="IntervalRunner"/>.
/// </summary>
public IntervalRunner(
object? id,
double interval,
Func<bool> canExecuteFunc,
Func<Task> intervalActionAsync,
ITelemetryContext telemetry,
TimeProvider? timeProvider = null)
{
m_logger = telemetry.CreateLogger<IntervalRunner>();
Id = id;
Interval = interval;
CanExecuteFunc = canExecuteFunc;
IntervalActionAsync = intervalActionAsync;
m_timeProvider = timeProvider ?? TimeProvider.System;
}
/// <summary>
/// Identifier of current IntervalRunner
/// </summary>
public object? Id { get; }
/// <summary>
/// Get/set the Interval between Runs in milliseconds
/// </summary>
public double Interval
{
get => m_interval;
set
{
lock (m_lock)
{
if (value < kMinInterval)
{
value = kMinInterval;
}
m_interval = value;
}
}
}
/// <summary>
/// Get the function that decides if the configured action can be executed when the Interval elapses
/// </summary>
public Func<bool> CanExecuteFunc { get; }
/// <summary>
/// Get the async action that will be executed at each interval
/// </summary>
public Func<Task> IntervalActionAsync { get; }
/// <summary>
/// Starts the IntervalRunner and makes it ready to execute the code.
/// </summary>
public void Start()
{
lock (m_lock)
{
// m_cancellationToken is only null after Dispose; the existing contract
// assumes Start is not called after Dispose (latent NRE preserved).
// TODO: Consider adding ObjectDisposedException check after Dispose.
if (m_cancellationToken!.IsCancellationRequested)
{
m_cancellationToken.Dispose();
m_cancellationToken = new CancellationTokenSource();
}
}
Task.Run(ProcessAsync).ConfigureAwait(false);
m_logger.LogInformation("IntervalRunner with id: {Id} was started.", Id);
}
/// <summary>
/// Stop the publishing thread.
/// </summary>
public virtual void Stop()
{
lock (m_lock)
{
m_cancellationToken?.Cancel();
}
m_logger.LogInformation("IntervalRunner with id: {Id} was stopped.", Id);
}
/// <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)
{
Stop();
m_cancellationToken?.Dispose();
m_cancellationToken = null;
}
}
/// <summary>
/// Periodically executes the .
/// </summary>
private async Task ProcessAsync()
{
bool isSystemProvider = ReferenceEquals(m_timeProvider, TimeProvider.System);
long ticksPerMs = Math.Max(1L, m_timeProvider.TimestampFrequency / 1000L);
lock (m_lock)
{
m_nextPublishTick = m_timeProvider.GetTimestamp();
}
// m_cancellationToken is only null after Dispose; ProcessAsync is started
// by Start before Dispose can be reached in normal usage.
while (!m_cancellationToken!.IsCancellationRequested)
{
long nowTick = m_timeProvider.GetTimestamp();
double nextPublishTick = 0;
lock (m_lock)
{
nextPublishTick = m_nextPublishTick;
}
double sleepCycle = (nextPublishTick - nowTick) / ticksPerMs;
if (sleepCycle > 16)
{
// Use Task.Delay if sleep cycle is larger
await m_timeProvider.Delay(
TimeSpan.FromMilliseconds(sleepCycle),
m_cancellationToken.Token)
.ConfigureAwait(false);
// Still ticks to consume (spurious wakeup too early), improbable
nowTick = m_timeProvider.GetTimestamp();
if (nowTick < nextPublishTick)
{
if (isSystemProvider)
{
SpinWait.SpinUntil(() => m_timeProvider.GetTimestamp() >= nextPublishTick);
}
else
{
double remainingMs = (nextPublishTick - nowTick) / ticksPerMs;
if (remainingMs > 0)
{
await m_timeProvider.Delay(
TimeSpan.FromMilliseconds(remainingMs),
m_cancellationToken.Token)
.ConfigureAwait(false);
}
}
}
}
else if (sleepCycle is >= 0 and <= 16)
{
if (isSystemProvider)
{
SpinWait.SpinUntil(() => m_timeProvider.GetTimestamp() >= nextPublishTick);
}
else if (sleepCycle > 0)
{
await m_timeProvider.Delay(
TimeSpan.FromMilliseconds(sleepCycle),
m_cancellationToken.Token)
.ConfigureAwait(false);
}
}
lock (m_lock)
{
double nextCycle = (long)m_interval * ticksPerMs;
m_nextPublishTick += nextCycle;
if (IntervalActionAsync != null && CanExecuteFunc != null && CanExecuteFunc())
{
// call on a new task without blocking the thread pool
_ = Task.Run(IntervalActionAsync);
}
}
}
}
}
}