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

515 lines
16 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 Microsoft.Extensions.Logging;
namespace Opc.Ua.Server
{
/// <summary>
/// The interface that a server exposes to objects that it contains.
/// </summary>
public static partial class ServerUtils
{
private enum EventType
{
WriteValue,
CreateItem,
ModifyItem,
QueueValue,
FilterValue,
DiscardValue,
PublishValue
}
private class Event
{
public DateTime Timestamp;
public EventType EventType;
public NodeId NodeId;
public uint ServerHandle;
public DataValue Value;
public MonitoringParameters? Parameters;
public MonitoringMode MonitoringMode;
}
private static readonly Queue<Event> s_events = new();
private static bool s_eventsEnabled;
/// <summary>
/// Whether event queuing is enabled.
/// </summary>
public static bool EventsEnabled
{
get => s_eventsEnabled;
set
{
if (s_eventsEnabled != value && !value)
{
lock (s_events)
{
s_events.Clear();
}
}
s_eventsEnabled = value;
}
}
/// <summary>
/// Reports a value written.
/// </summary>
public static void ReportWriteValue(NodeId nodeId, DataValue value, StatusCode error)
{
if (!s_eventsEnabled)
{
return;
}
lock (s_events)
{
var e = new Event
{
EventType = EventType.WriteValue,
NodeId = nodeId,
ServerHandle = 0,
Timestamp = DateTime.UtcNow,
Value = value,
Parameters = null,
MonitoringMode = MonitoringMode.Disabled
};
if (StatusCode.IsBad(error))
{
e.Value = new DataValue(value.WrappedValue, error);
}
s_events.Enqueue(e);
}
}
/// <summary>
/// Reports a value queued.
/// </summary>
public static void ReportQueuedValue(NodeId nodeId, uint serverHandle, DataValue value)
{
if (!s_eventsEnabled)
{
return;
}
lock (s_events)
{
var e = new Event
{
EventType = EventType.QueueValue,
NodeId = nodeId,
ServerHandle = serverHandle,
Timestamp = DateTime.UtcNow,
Value = value,
Parameters = null,
MonitoringMode = MonitoringMode.Disabled
};
s_events.Enqueue(e);
}
}
/// <summary>
/// Reports a value excluded by the filter.
/// </summary>
public static void ReportFilteredValue(NodeId nodeId, uint serverHandle, DataValue value)
{
if (!s_eventsEnabled)
{
return;
}
lock (s_events)
{
var e = new Event
{
EventType = EventType.FilterValue,
NodeId = nodeId,
ServerHandle = serverHandle,
Timestamp = DateTime.UtcNow,
Value = value,
Parameters = null,
MonitoringMode = MonitoringMode.Disabled
};
s_events.Enqueue(e);
}
}
/// <summary>
/// Reports a value discarded because of queue overflow.
/// </summary>
public static void ReportDiscardedValue(NodeId nodeId, uint serverHandle, DataValue value)
{
if (!s_eventsEnabled)
{
return;
}
lock (s_events)
{
var e = new Event
{
EventType = EventType.DiscardValue,
NodeId = nodeId,
ServerHandle = serverHandle,
Timestamp = DateTime.UtcNow,
Value = value,
Parameters = null,
MonitoringMode = MonitoringMode.Disabled
};
s_events.Enqueue(e);
}
}
/// <summary>
/// Reports a value published.
/// </summary>
public static void ReportPublishValue(NodeId nodeId, uint serverHandle, DataValue value)
{
if (!s_eventsEnabled)
{
return;
}
lock (s_events)
{
var e = new Event
{
EventType = EventType.PublishValue,
NodeId = nodeId,
ServerHandle = serverHandle,
Timestamp = DateTime.UtcNow,
Value = value,
Parameters = null,
MonitoringMode = MonitoringMode.Disabled
};
s_events.Enqueue(e);
}
}
/// <summary>
/// Reports a new monitored item.
/// </summary>
public static void ReportCreateMonitoredItem(
NodeId nodeId,
uint serverHandle,
double samplingInterval,
uint queueSize,
bool discardOldest,
MonitoringFilter filter,
MonitoringMode monitoringMode)
{
if (!s_eventsEnabled)
{
return;
}
lock (s_events)
{
var e = new Event
{
EventType = EventType.CreateItem,
NodeId = nodeId,
ServerHandle = serverHandle,
Timestamp = DateTime.UtcNow,
Value = default,
Parameters = new MonitoringParameters
{
SamplingInterval = samplingInterval,
QueueSize = queueSize,
DiscardOldest = discardOldest,
Filter = new ExtensionObject(filter)
},
MonitoringMode = monitoringMode
};
s_events.Enqueue(e);
}
}
/// <summary>
/// Reports a modified monitored item.
/// </summary>
public static void ReportModifyMonitoredItem(
NodeId nodeId,
uint serverHandle,
double samplingInterval,
uint queueSize,
bool discardOldest,
MonitoringFilter filter,
MonitoringMode monitoringMode)
{
if (!s_eventsEnabled)
{
return;
}
lock (s_events)
{
var e = new Event
{
EventType = EventType.ModifyItem,
NodeId = nodeId,
ServerHandle = serverHandle,
Timestamp = DateTime.UtcNow,
Value = default,
Parameters = new MonitoringParameters
{
SamplingInterval = samplingInterval,
QueueSize = queueSize,
DiscardOldest = discardOldest,
Filter = new ExtensionObject(filter)
},
MonitoringMode = monitoringMode
};
s_events.Enqueue(e);
}
}
/// <summary>
/// Fills in the diagnostic information after an error.
/// </summary>
public static uint CreateError(
uint code,
OperationContext context,
List<DiagnosticInfo> diagnosticInfos,
int index,
ILogger logger)
{
var error = new ServiceResult(code);
if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0)
{
diagnosticInfos[index] = new DiagnosticInfo(
error,
context.DiagnosticsMask,
false,
context.StringTable,
logger);
}
return error.Code;
}
/// <summary>
/// Fills in the diagnostic information after an error.
/// </summary>
public static bool CreateError(
uint code,
List<StatusCode> results,
List<DiagnosticInfo> diagnosticInfos,
OperationContext context,
ILogger logger)
{
var error = new ServiceResult(code);
results.Add(error.Code);
if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0)
{
diagnosticInfos.Add(
new DiagnosticInfo(error, context.DiagnosticsMask, false, context.StringTable, logger));
return true;
}
return false;
}
/// <summary>
/// Fills in the diagnostic information after an error.
/// </summary>
public static bool CreateError(
uint code,
List<StatusCode> results,
List<DiagnosticInfo> diagnosticInfos,
int index,
OperationContext context,
ILogger logger)
{
var error = new ServiceResult(code);
results[index] = error.Code;
if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0)
{
diagnosticInfos[index] = new DiagnosticInfo(
error,
context.DiagnosticsMask,
false,
context.StringTable,
logger);
return true;
}
return false;
}
/// <summary>
/// Creates a place holder in the lists for the results.
/// </summary>
public static void CreateSuccess(
List<StatusCode> results,
List<DiagnosticInfo> diagnosticInfos,
OperationContext context)
{
results.Add(StatusCodes.Good);
if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0)
{
diagnosticInfos.Add(null!);
}
}
/// <summary>
/// Creates a collection of diagnostics from a set of errors.
/// </summary>
public static List<DiagnosticInfo>? CreateDiagnosticInfoCollection(
OperationContext context,
IList<ServiceResult> errors,
ILogger logger)
{
// all done if no diagnostics requested.
if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) == 0)
{
return null;
}
// create diagnostics.
var results = new List<DiagnosticInfo>(errors.Count);
foreach (ServiceResult error in errors)
{
if (ServiceResult.IsBad(error))
{
results.Add(new DiagnosticInfo(
error,
context.DiagnosticsMask,
false,
context.StringTable,
logger));
}
else
{
results.Add(null!);
}
}
return results;
}
/// <summary>
/// Creates a collection of status codes and diagnostics from a set of errors.
/// </summary>
public static List<StatusCode> CreateStatusCodeCollection(
OperationContext context,
IList<ServiceResult> errors,
out List<DiagnosticInfo> diagnosticInfos,
ILogger logger)
{
diagnosticInfos = null!;
bool noErrors = true;
var results = new List<StatusCode>(errors.Count);
foreach (ServiceResult error in errors)
{
if (ServiceResult.IsBad(error))
{
results.Add(error.Code);
noErrors = false;
}
else
{
results.Add(StatusCodes.Good);
}
}
// only generate diagnostics if errors exist.
if (noErrors)
{
diagnosticInfos = CreateDiagnosticInfoCollection(context, errors, logger)!;
}
return results;
}
/// <summary>
/// Creates the diagnostic info and translates any strings.
/// </summary>
[Obsolete("Use CreateDiagnosticInfo with ILogger")]
public static DiagnosticInfo CreateDiagnosticInfo(
IServerInternal server,
OperationContext context,
ServiceResult error)
{
ILogger logger = AmbientMessageContext.Telemetry.CreateLogger("ServerUtils");
return CreateDiagnosticInfo(server, context, error, logger)!;
}
/// <summary>
/// Creates the diagnostic info and translates any strings.
/// </summary>
/// <param name="server">The server.</param>
/// <param name="context">The context containing the string stable.</param>
/// <param name="error">The error to translate.</param>
/// <param name="logger">A contextual logger to log to</param>
/// <returns>The diagnostics with references to the strings in the context string table.</returns>
public static DiagnosticInfo? CreateDiagnosticInfo(
IServerInternal server,
OperationContext context,
ServiceResult error,
ILogger logger)
{
if (error == null)
{
return null;
}
ServiceResult? translatedError = error;
// Only translate if ServiceLocalizedText is set, as DiagnosticInfo only uses
// the translation for ServiceLocalizedText, not OperationLocalizedText
if ((context.DiagnosticsMask & DiagnosticsMasks.ServiceLocalizedText) != 0)
{
translatedError = server.ResourceManager.Translate(context.PreferredLocales, error);
}
return new DiagnosticInfo(
translatedError!,
context.DiagnosticsMask,
false,
context.StringTable,
logger);
}
}
}