Files
Marc Schier 36d67b3d3a [Client] Central channel manager with shared, ref-counted transport channels (#3288)
Introduces `IClientChannelManager` as the central registry for client-side
transport channels. Sessions and discovery clients now share ref-counted
managed channels per (endpoint, reverse-connect identity); reconnect is
coalesced and notified to attached participants via a new
`IReconnectParticipant` callback interface; service calls are gated by a
three-state lifecycle (`TransportReconnecting` -> `TransportConnectedSessionReactivating`
-> `Ready`) until reactivation completes.

New types in `Stack/Opc.Ua.Core/Stack/Client/`:
- `ManagedChannelKey`, `ChannelState`, `ChannelStateChange`, `ParticipantReconnectResult`
- `IReconnectParticipant`, `IManagedTransportChannel`, `IClientChannelManager`
- `IChannelReconnectPolicy` + `ExponentialBackoffChannelReconnectPolicy`
- `IRetryBudget` + `RetryBudget` (shared retry deadline across the two layers)
- `ClientChannelManager.Managed/Entry/Lease/Metrics/Diagnostics/CertRotation.cs`
  partials with refcount, coalesced reconnect, IMeter instruments, ActivitySource
  + EventSource, and automatic ReconnectAllAsync on certificate rotation.

Session integration (Libraries/Opc.Ua.Client):
- `Session.CreateAsync(IClientChannelManager, ...)` overload constructs a
  Session that shares its channel with co-located participants.
- `Session` implements `IReconnectParticipant`; reactivation handler
  distinguishes Reactivated / RequiresSessionRecreate / TransientFailure /
  FatalForParticipant / FatalForChannel.
- `Session.ReconnectAsync(ct)` automatically delegates to the channel
  manager when wired.
- `Session.RecreateInPlaceAsync` swaps managed-channel leases for
  failover-to-different-endpoint; same-key recreates delegate to manager
  reconnect; explicit channel/connection callers retain legacy behavior.
- KA failure routes through `IClientChannelManager.ReconnectAsync(channel)`.

ManagedSession integration:
- `WithChannelManager(...)` builder + ctor param.
- Two-level retry: channel-mgr handles transparent reconnect; outer
  `ConnectionStateMachine` + `IReconnectPolicy` only triggers on terminal
  channel `Faulted`. Outer-state churn suppressed during channel-mgr
  cycles via `_channelReconnectInProgress` flag wired through
  `IManagedTransportChannel.StateChanged`.
- New `ManagedSession.ChannelStateChanged` event surfaces transparent
  reconnects to UI / health dashboards.
- `ConnectionStateChangedEventArgs.UnderlyingChannelState` populated when
  outer reconnect was triggered by a channel fault.
- Shared `IRetryBudget` propagated to channel-mgr so the two layers
  enforce a single max-total-time instead of compounding multiplicatively.

Discovery/Registration/GDS:
- Channel-manager-aware `CreateAsync` overloads on `DiscoveryClient`,
  `RegistrationClient`, `ServerPushConfigurationClient`,
  `LocalDiscoveryServerClient`, `GlobalDiscoveryServerClient`. Each
  registers a minimal `IReconnectParticipant`; co-located sessions and
  discovery probes targeting the same endpoint share a channel.

HTTPS transport (`Stack/Opc.Ua.Bindings.Https/`):
- New `IOpcUaHttpClientFactory` abstraction.
- HTTPS / OPC-HTTPS channels migrated to `IHttpClientFactory` +
  `Microsoft.Extensions.Http.Resilience` (10.6.0, AOT-compatible on net10
  via source generators; legacy direct-HTTP path retained for older TFMs
  / no-DI consumers).

DI:
- `AddOpcUa().AddClient(...)` registers `IClientChannelManager` and the
  named HTTPS HttpClient + standard resilience handler automatically.
- `ManagedSessionBuilder` resolves the manager from DI when present.

Obsoletions (functional, `[Obsolete]` with guidance):
- `IClientBase.AttachChannel`/`DetachChannel`
- `SessionReconnectHandler`
- `SessionExtensions.ReconnectAsync(connection, ct)` and `(channel, ct)`
  legacy overloads

Tests (~70 new unit + 4 live-server integration fixtures):
- Core: `ClientChannelManagerManagedTests`, `ClientChannelManagerCertRotationTests`,
  `RetryBudgetTests`, `OpcUaHttpClientFactoryTests` (56/56 pass).
- Client: `ManagedSession*Tests` updated (129/129 pass) + back-compat
  suites pass with `#pragma warning disable CS0618`.
- Sessions integration: `ChannelManagerSharing/TransparentReconnect/SessionLifecycle/CertRotation`
  (6 pass, 2 skipped with documented blockers for faulted-entry reset and
  RequiresSessionRecreate end-to-end plumbing).

Builds clean (0 warnings / 0 errors) across all six TFMs (net472, net48,
netstandard2.1, net8.0, net9.0, net10.0).

Docs:
- `Docs/Sessions.md` new section 4 documents the channel manager,
  three-state gating, two-level retry with shared `IRetryBudget`, and
  HTTPS resilience layering.
- `Docs/MigrationGuide.md` migration recipes for the four obsoleted API
  groups.
- `Docs/DependencyInjection.md` channel-manager and HTTPS factory
  registration.
2026-06-05 15:37:23 +02:00

167 lines
5.6 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;
namespace Opc.Ua.Client
{
/// <summary>
/// Backoff strategy for reconnection delays.
/// </summary>
public enum BackoffStrategy
{
/// <summary>
/// Constant delay between attempts.
/// </summary>
Constant,
/// <summary>
/// Linearly increasing delay.
/// </summary>
Linear,
/// <summary>
/// Exponentially increasing delay.
/// </summary>
Exponential
}
/// <summary>
/// Default reconnect policy with configurable backoff,
/// jitter, and retry limits.
/// </summary>
public class ReconnectPolicy : IReconnectPolicy
{
/// <summary>
/// Default initial delay (1 second).
/// </summary>
public static readonly TimeSpan DefaultInitialDelay = TimeSpan.FromSeconds(1);
/// <summary>
/// Default max delay (30 seconds).
/// </summary>
public static readonly TimeSpan DefaultMaxDelay = TimeSpan.FromSeconds(30);
/// <summary>
/// Default maximum total reconnect time (5 minutes).
/// </summary>
public static readonly TimeSpan DefaultMaxTotalReconnectTime = TimeSpan.FromMinutes(5);
/// <summary>
/// Initialize a reconnect policy with default options.
/// </summary>
public ReconnectPolicy()
: this(new ReconnectPolicyOptions())
{
}
/// <summary>
/// Initialize a reconnect policy from an options snapshot.
/// </summary>
public ReconnectPolicy(ReconnectPolicyOptions options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
InitialDelay = options.InitialDelay;
MaxDelay = options.MaxDelay;
MaxRetries = options.MaxRetries;
Strategy = options.Strategy;
JitterFactor = options.JitterFactor;
MaxTotalReconnectTime = options.MaxTotalReconnectTime;
}
/// <summary>
/// Initial delay between reconnect attempts.
/// </summary>
public TimeSpan InitialDelay { get; set; } = DefaultInitialDelay;
/// <summary>
/// Maximum delay between attempts.
/// </summary>
public TimeSpan MaxDelay { get; set; } = DefaultMaxDelay;
/// <summary>
/// Maximum number of retries (0 = unlimited).
/// </summary>
public int MaxRetries { get; set; }
/// <summary>
/// Backoff strategy.
/// </summary>
public BackoffStrategy Strategy { get; set; } = BackoffStrategy.Exponential;
/// <summary>
/// Jitter factor (0.0 = no jitter, 0.1 = ±10%).
/// </summary>
public double JitterFactor { get; set; } = 0.1;
/// <summary>
/// Maximum total elapsed time for one reconnect cycle across
/// outer ManagedSession retries and channel-manager retries.
/// </summary>
public TimeSpan MaxTotalReconnectTime { get; set; } = DefaultMaxTotalReconnectTime;
/// <inheritdoc/>
public TimeSpan? GetNextDelay(int attempt, CancellationToken ct = default)
{
if (MaxRetries > 0 && attempt >= MaxRetries)
{
return null;
}
double delayMs = Strategy switch
{
BackoffStrategy.Constant => InitialDelay.TotalMilliseconds,
BackoffStrategy.Linear => InitialDelay.TotalMilliseconds * (attempt + 1),
BackoffStrategy.Exponential => InitialDelay.TotalMilliseconds * Math.Pow(2, attempt),
_ => InitialDelay.TotalMilliseconds
};
delayMs = Math.Min(delayMs, MaxDelay.TotalMilliseconds);
if (JitterFactor > 0)
{
int jitter = (int)(delayMs * JitterFactor);
delayMs += UnsecureRandom.Shared.Next(-jitter, jitter + 1);
}
return TimeSpan.FromMilliseconds(Math.Max(delayMs, 0));
}
/// <inheritdoc/>
public void Reset()
{
// Stateless — no internal state to reset.
}
}
}