mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-22 01:26:20 +08:00
dbc09b8e22
# 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.
251 lines
9.3 KiB
C#
251 lines
9.3 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.Security.Certificates;
|
|
|
|
namespace Opc.Ua.Server
|
|
{
|
|
/// <summary>
|
|
/// A generic session manager object for a server.
|
|
/// </summary>
|
|
public interface ISession : IDisposable
|
|
{
|
|
/// <summary>
|
|
/// Whether the session has been activated.
|
|
/// </summary>
|
|
bool Activated { get; }
|
|
|
|
/// <summary>
|
|
/// The server application instance certificate used by this session.
|
|
/// </summary>
|
|
Certificate ServerCertificate { get; }
|
|
|
|
/// <summary>
|
|
/// The application instance certificate associated with the client.
|
|
/// </summary>
|
|
Certificate ClientCertificate { get; }
|
|
|
|
/// <summary>
|
|
/// The last time the session was contacted by the client.
|
|
/// </summary>
|
|
DateTime ClientLastContactTime { get; }
|
|
|
|
/// <summary>
|
|
/// The monotonic tick count (milliseconds) at the last client contact.
|
|
/// Used for timeout calculations that are immune to system time changes.
|
|
/// </summary>
|
|
long LastContactTickCount { get; }
|
|
|
|
/// <summary>
|
|
/// The client Nonce associated with the session.
|
|
/// </summary>
|
|
ByteString ClientNonce { get; }
|
|
|
|
/// <summary>
|
|
/// A lock which must be acquired before accessing the diagnostics.
|
|
/// </summary>
|
|
object DiagnosticsLock { get; }
|
|
|
|
/// <summary>
|
|
/// The application defined mapping for user identity provided by the client.
|
|
/// </summary>
|
|
IUserIdentity EffectiveIdentity { get; }
|
|
|
|
/// <summary>
|
|
/// Whether the session's <see cref="EffectiveIdentity"/> has been
|
|
/// invalidated by a configuration change (e.g. Role identity-mapping
|
|
/// rules) and should be recomputed on the next request.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// The flag is set by <see cref="MarkIdentityStale"/> and cleared by
|
|
/// <see cref="RefreshEffectiveIdentity"/>. Per OPC UA Part 18 §4.4.1
|
|
/// role grants must reflect the live RoleSet without forcing the
|
|
/// client to re-activate.
|
|
/// </remarks>
|
|
bool IsIdentityStale { get; }
|
|
|
|
/// <summary>
|
|
/// Marks the session's <see cref="EffectiveIdentity"/> as stale so
|
|
/// the next request triggers a re-evaluation of the role mapping.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Safe to call from any thread. Multiple concurrent calls are
|
|
/// idempotent — the flag is sticky until a refresh clears it.
|
|
/// </remarks>
|
|
void MarkIdentityStale();
|
|
|
|
/// <summary>
|
|
/// Atomically replaces the session's <see cref="EffectiveIdentity"/>
|
|
/// with the supplied value and clears the
|
|
/// <see cref="IsIdentityStale"/> flag.
|
|
/// </summary>
|
|
/// <param name="effectiveIdentity">
|
|
/// The newly resolved effective identity (including any roles layered
|
|
/// on by mandatory-role assignment and the live RoleSet).
|
|
/// </param>
|
|
void RefreshEffectiveIdentity(IUserIdentity effectiveIdentity);
|
|
|
|
/// <summary>
|
|
/// Returns the session's endpoint
|
|
/// </summary>
|
|
EndpointDescription EndpointDescription { get; }
|
|
|
|
/// <summary>
|
|
/// Whether the session timeout has elapsed since the last communication from the client.
|
|
/// </summary>
|
|
bool HasExpired { get; }
|
|
|
|
/// <summary>
|
|
/// Gets the identifier assigned to the session when it was created.
|
|
/// </summary>
|
|
NodeId Id { get; }
|
|
|
|
/// <summary>
|
|
/// The user identity provided by the client.
|
|
/// </summary>
|
|
IUserIdentity Identity { get; }
|
|
|
|
/// <summary>
|
|
/// The user identity token provided by the client wrapped into a handler.
|
|
/// </summary>
|
|
IUserIdentityTokenHandler IdentityToken { get; }
|
|
|
|
/// <summary>
|
|
/// The locales requested when the session was created.
|
|
/// </summary>
|
|
string[] PreferredLocales { get; }
|
|
|
|
/// <summary>
|
|
/// Returns the session's SecureChannelId
|
|
/// </summary>
|
|
string SecureChannelId { get; }
|
|
|
|
/// <summary>
|
|
/// The diagnostics associated with the session.
|
|
/// </summary>
|
|
SessionDiagnosticsDataType SessionDiagnostics { get; }
|
|
|
|
/// <summary>
|
|
/// Activates the session and binds it to the current secure channel.
|
|
/// </summary>
|
|
bool Activate(
|
|
OperationContext context,
|
|
IUserIdentityTokenHandler identityToken,
|
|
IUserIdentity identity,
|
|
IUserIdentity effectiveIdentity,
|
|
ArrayOf<string> localeIds,
|
|
Nonce serverNonce);
|
|
|
|
/// <summary>
|
|
/// Closes a session and removes itself from the address space.
|
|
/// </summary>
|
|
ValueTask CloseAsync(CancellationToken cancellationToken = default);
|
|
|
|
/// <summary>
|
|
/// Create new ECC ephemeral key
|
|
/// </summary>
|
|
/// <returns>A new ephemeral key</returns>
|
|
EphemeralKeyType? GetNewEphemeralKey();
|
|
|
|
/// <summary>
|
|
/// Checks if the secure channel is currently valid.
|
|
/// </summary>
|
|
bool IsSecureChannelValid(string secureChannelId);
|
|
|
|
/// <summary>
|
|
/// Restores a continuation point for a session.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// The caller is responsible for disposing the continuation point returned.
|
|
/// </remarks>
|
|
ContinuationPoint? RestoreContinuationPoint(ByteString continuationPoint);
|
|
|
|
/// <summary>
|
|
/// Restores a previously saves history continuation point.
|
|
/// </summary>
|
|
/// <param name="continuationPoint">The identifier for the continuation point.</param>
|
|
/// <returns>The save continuation point. null if not found.</returns>
|
|
object? RestoreHistoryContinuationPoint(ByteString continuationPoint);
|
|
|
|
/// <summary>
|
|
/// Saves a continuation point for a session.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// If the session has too many continuation points the oldest one is dropped.
|
|
/// </remarks>
|
|
void SaveContinuationPoint(ContinuationPoint continuationPoint);
|
|
|
|
/// <summary>
|
|
/// Saves a continuation point used for historical reads.
|
|
/// </summary>
|
|
/// <param name="id">The identifier for the continuation point.</param>
|
|
/// <param name="continuationPoint">The continuation point.</param>
|
|
/// <remarks>
|
|
/// If the continuationPoint implements IDisposable it will be disposed when
|
|
/// the Session is closed or discarded.
|
|
/// </remarks>
|
|
void SaveHistoryContinuationPoint(Guid id, object continuationPoint);
|
|
|
|
/// <summary>
|
|
/// Set the ECC security policy URI
|
|
/// </summary>
|
|
void SetUserTokenSecurityPolicy(string securityPolicyUri);
|
|
|
|
/// <summary>
|
|
/// Updates the requested locale ids.
|
|
/// </summary>
|
|
/// <returns>true if the new locale ids are different from the old locale ids.</returns>
|
|
bool UpdateLocaleIds(ArrayOf<string> localeIds);
|
|
|
|
/// <summary>
|
|
/// Activates the session and binds it to the current secure channel.
|
|
/// </summary>
|
|
void ValidateBeforeActivate(
|
|
OperationContext context,
|
|
SignatureData clientSignature,
|
|
ExtensionObject userIdentityToken,
|
|
SignatureData userTokenSignature,
|
|
out IUserIdentityTokenHandler? identityToken,
|
|
out UserTokenPolicy? userTokenPolicy);
|
|
|
|
/// <summary>
|
|
/// Validate the diagnostic info.
|
|
/// </summary>
|
|
void ValidateDiagnosticInfo(RequestHeader requestHeader);
|
|
|
|
/// <summary>
|
|
/// Validates the request.
|
|
/// </summary>
|
|
void ValidateRequest(RequestHeader requestHeader, SecureChannelContext secureChannelContext, RequestType requestType);
|
|
}
|
|
}
|