Files
UA-.NETStandard/Libraries/Opc.Ua.Client/Fluent/ManagedSessionBuilder.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

443 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 System.Threading;
using System.Threading.Tasks;
using Opc.Ua.Identity;
namespace Opc.Ua.Client
{
/// <summary>
/// Fluent builder for constructing a <see cref="ManagedSession"/>. The
/// builder accumulates an immutable <see cref="ManagedSessionOptions"/>
/// snapshot via <c>With*</c>/<c>Use*</c>/<c>Configure</c> methods. Call
/// <see cref="Build"/> to obtain the snapshot, or
/// <see cref="ConnectAsync"/> to construct and open the session in one
/// step.
/// </summary>
/// <example>
/// <code>
/// var session = await new ManagedSessionBuilder(configuration, telemetry)
/// .UseEndpoint(endpoint)
/// .WithSessionName("My App")
/// .WithReconnectPolicy(p =&gt; p with { Strategy = BackoffStrategy.Linear })
/// .ConnectAsync(ct);
/// </code>
/// </example>
public sealed class ManagedSessionBuilder
{
private readonly ApplicationConfiguration m_configuration;
private readonly ITelemetryContext m_telemetry;
private ManagedSessionOptions m_options = new();
private IReconnectPolicy? m_reconnectPolicy;
private IServerRedundancyHandler? m_redundancyHandler;
private ISessionFactory? m_sessionFactory;
/// <summary>
/// Initializes a new builder.
/// </summary>
public ManagedSessionBuilder(
ApplicationConfiguration configuration,
ITelemetryContext telemetry)
{
m_configuration = configuration
?? throw new ArgumentNullException(nameof(configuration));
m_telemetry = telemetry
?? throw new ArgumentNullException(nameof(telemetry));
}
/// <summary>
/// Use the supplied configured endpoint.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="endpoint"/> is <c>null</c>.</exception>
public ManagedSessionBuilder UseEndpoint(ConfiguredEndpoint endpoint)
{
if (endpoint == null)
{
throw new ArgumentNullException(nameof(endpoint));
}
m_options = m_options with { Endpoint = endpoint };
return this;
}
/// <summary>
/// Use a discovery endpoint URL with optional security mode/policy.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="url"/> is <c>null</c>.</exception>
public ManagedSessionBuilder UseEndpoint(
string url,
MessageSecurityMode securityMode = MessageSecurityMode.SignAndEncrypt,
string securityPolicyUri = SecurityPolicies.Basic256Sha256)
{
if (url == null)
{
throw new ArgumentNullException(nameof(url));
}
var endpointDescription = new EndpointDescription
{
EndpointUrl = url,
SecurityMode = securityMode,
SecurityPolicyUri = securityPolicyUri
};
return UseEndpoint(new ConfiguredEndpoint(null, endpointDescription, null));
}
/// <summary>
/// Set the user identity used when activating the session.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="identity"/> is <c>null</c>.</exception>
public ManagedSessionBuilder WithUserIdentity(IUserIdentity identity)
{
if (identity == null)
{
throw new ArgumentNullException(nameof(identity));
}
#pragma warning disable CS0618 // Legacy eager identity remains supported for compatibility.
m_options = m_options with { Identity = identity };
#pragma warning restore CS0618
return this;
}
/// <summary>
/// Set the lazy identity provider used to refresh identities after connect.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="provider"/> is <c>null</c>.</exception>
public ManagedSessionBuilder WithIdentityProvider(IClientIdentityProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException(nameof(provider));
}
m_options = m_options with { IdentityProvider = provider };
return this;
}
/// <summary>
/// Set the time provider used by proactive identity refresh.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="timeProvider"/> is <c>null</c>.</exception>
public ManagedSessionBuilder WithTimeProvider(TimeProvider timeProvider)
{
if (timeProvider == null)
{
throw new ArgumentNullException(nameof(timeProvider));
}
m_options = m_options with { TimeProvider = timeProvider };
return this;
}
/// <summary>
/// Set the session display name.
/// </summary>
/// <exception cref="ArgumentException"></exception>
public ManagedSessionBuilder WithSessionName(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException("Value required", nameof(name));
}
m_options = m_options with { SessionName = name };
return this;
}
/// <summary>
/// Set the requested session timeout.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public ManagedSessionBuilder WithSessionTimeout(TimeSpan timeout)
{
if (timeout <= TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(timeout));
}
m_options = m_options with { SessionTimeout = timeout };
return this;
}
/// <summary>
/// Set the preferred locales for the session.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="locales"/> is <c>null</c>.</exception>
public ManagedSessionBuilder WithPreferredLocales(params string[] locales)
{
if (locales == null)
{
throw new ArgumentNullException(nameof(locales));
}
m_options = m_options with { PreferredLocales = locales };
return this;
}
/// <summary>
/// Enable or disable server-certificate domain validation.
/// </summary>
public ManagedSessionBuilder WithCheckDomain(bool checkDomain = true)
{
m_options = m_options with { CheckDomain = checkDomain };
return this;
}
/// <summary>
/// Configure the reconnect policy via a transformation of the
/// underlying <see cref="ReconnectPolicyOptions"/> record.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="configure"/> is <c>null</c>.</exception>
public ManagedSessionBuilder WithReconnectPolicy(
Func<ReconnectPolicyOptions, ReconnectPolicyOptions> configure)
{
if (configure == null)
{
throw new ArgumentNullException(nameof(configure));
}
m_options = m_options with
{
ReconnectPolicy = configure(m_options.ReconnectPolicy)
};
m_reconnectPolicy = null;
return this;
}
/// <summary>
/// Use the supplied <see cref="IReconnectPolicy"/> directly. Overrides
/// any options-based reconnect configuration.
/// </summary>
/// <exception cref="ArgumentNullException"></exception>
public ManagedSessionBuilder WithReconnectPolicy(IReconnectPolicy policy)
{
m_reconnectPolicy = policy
?? throw new ArgumentNullException(nameof(policy));
return this;
}
/// <summary>
/// Enable server redundancy with a default handler.
/// </summary>
public ManagedSessionBuilder WithServerRedundancy()
{
m_options = m_options with { EnableServerRedundancy = true };
m_redundancyHandler = null;
return this;
}
/// <summary>
/// Enable server redundancy with the supplied handler.
/// </summary>
/// <exception cref="ArgumentNullException"></exception>
public ManagedSessionBuilder WithServerRedundancy(IServerRedundancyHandler handler)
{
m_redundancyHandler = handler
?? throw new ArgumentNullException(nameof(handler));
m_options = m_options with { EnableServerRedundancy = true };
return this;
}
/// <summary>
/// Use a specific subscription engine factory. Defaults to the V2
/// engine when not specified.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="factory"/> is <c>null</c>.</exception>
public ManagedSessionBuilder UseSubscriptionEngine(ISubscriptionEngineFactory factory)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
m_options = m_options with { SubscriptionEngineFactory = factory };
return this;
}
/// <summary>
/// Opt the V2 subscription engine into transfer-on-recreate.
/// When enabled, the V2 <c>SubscriptionManager</c> attempts to
/// transfer existing server-side subscriptions from the
/// previous session to the new one on each session re-create
/// (e.g. failover via
/// <see cref="Session.RecreateInPlaceAsync"/>) and falls back
/// to per-subscription recreate when transfer is not
/// available. Disabled by default — recreate is the
/// universal, server-agnostic fallback; transfer requires
/// server support.
/// </summary>
/// <remarks>
/// Has no effect when the classic subscription engine is in
/// use; the classic engine drives recreate through the
/// <see cref="Session"/>'s template-based path.
/// </remarks>
public ManagedSessionBuilder WithTransferSubscriptionsOnRecreate(
bool transferOnRecreate = true)
{
m_options = m_options with
{
TransferSubscriptionsOnRecreate = transferOnRecreate
};
return this;
}
/// <summary>
/// Enable activator-level pooling of V2 subscription
/// notification payload instances. When enabled, the V2
/// subscription dispatcher calls
/// <see cref="IPooledEncodeable.Reuse"/> on notification
/// payload objects (such as <c>MonitoredItemNotification</c>)
/// after each handler dispatch, releasing them back to their
/// activator's pool for reuse on the next publish. Handlers
/// that retain values past the dispatch call must copy them.
/// Disabled by default.
/// </summary>
/// <remarks>
/// Has no effect when the classic subscription engine is in
/// use; this option only applies to the V2
/// <see cref="Subscriptions.ISubscriptionManager"/>.
/// </remarks>
public ManagedSessionBuilder WithPoolNotifications(
bool poolNotifications = true)
{
m_options = m_options with
{
PoolNotifications = poolNotifications
};
return this;
}
/// <summary>
/// Enables address-space model change tracking. The session
/// auto-starts a <see cref="ModelChange.IModelChangeTracker"/>
/// after connect that invalidates the node cache and exposes
/// changes via <see cref="ManagedSession.ModelChange"/>.
/// Disabled by default.
/// </summary>
public ManagedSessionBuilder WithModelChangeTracking(
bool enabled = true)
{
m_options = m_options with
{
ModelChangeTracking = enabled
};
return this;
}
/// <summary>
/// Use a specific session factory. By default, the builder
/// creates a new <see cref="DefaultSessionFactory"/> configured with
/// the V2 subscription engine.
/// </summary>
/// <exception cref="ArgumentNullException"></exception>
public ManagedSessionBuilder UseSessionFactory(ISessionFactory factory)
{
m_sessionFactory = factory
?? throw new ArgumentNullException(nameof(factory));
return this;
}
/// <summary>
/// Returns the immutable options snapshot accumulated so far.
/// </summary>
public ManagedSessionOptions Build()
{
return m_options;
}
/// <summary>
/// Construct and connect a <see cref="ManagedSession"/> using the
/// accumulated options.
/// </summary>
/// <exception cref="InvalidOperationException"></exception>
public async Task<ManagedSession> ConnectAsync(CancellationToken ct = default)
{
ManagedSessionOptions opts = m_options;
if (opts.Endpoint == null)
{
throw new InvalidOperationException(
"ManagedSessionBuilder.UseEndpoint must be called before ConnectAsync.");
}
ISubscriptionEngineFactory engineFactory =
opts.SubscriptionEngineFactory ?? (opts.TimeProvider == null
? DefaultSubscriptionEngineFactory.Instance
: new DefaultSubscriptionEngineFactory(opts.TimeProvider));
ISessionFactory sessionFactory = m_sessionFactory ??
new DefaultSessionFactory(m_telemetry)
{
SubscriptionEngineFactory = engineFactory,
TimeProvider = opts.TimeProvider
};
IReconnectPolicy reconnect =
m_reconnectPolicy ?? new ReconnectPolicy(opts.ReconnectPolicy);
IServerRedundancyHandler? redundancy = m_redundancyHandler ??
(opts.EnableServerRedundancy
? new DefaultServerRedundancyHandler()
: null);
ArrayOf<string> preferredLocales = default;
if (opts.PreferredLocales is { Count: > 0 } locales)
{
string[] arr = new string[locales.Count];
for (int i = 0; i < locales.Count; i++)
{
arr[i] = locales[i];
}
preferredLocales = new ArrayOf<string>(arr);
}
#pragma warning disable CS0618 // Legacy eager identity remains supported when no provider is configured.
IUserIdentity? identity = opts.Identity;
#pragma warning restore CS0618
ManagedSession session = await ManagedSession.CreateAsync(
m_configuration,
opts.Endpoint,
sessionFactory,
identity,
reconnect,
redundancy,
m_telemetry,
opts.SessionName,
(uint)opts.SessionTimeout.TotalMilliseconds,
preferredLocales,
opts.CheckDomain,
engineFactory,
opts.TransferSubscriptionsOnRecreate,
opts.PoolNotifications,
opts.IdentityProvider,
opts.TimeProvider,
ct).ConfigureAwait(false);
if (opts.ModelChangeTracking)
{
await session.EnableModelChangeTrackingAsync(ct).ConfigureAwait(false);
}
return session;
}
}
}