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

87 lines
3.2 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;
namespace Opc.Ua.Client
{
/// <summary>
/// Connection states for a ManagedSession, following OPC UA
/// client connectivity guidance.
/// </summary>
public enum ConnectionState
{
/// <summary>Session is not connected and not attempting to connect.</summary>
Disconnected,
/// <summary>Session is attempting initial connection.</summary>
Connecting,
/// <summary>Session is connected and operational.</summary>
Connected,
/// <summary>Connection lost, attempting to reconnect to the same server.</summary>
Reconnecting,
/// <summary>Reconnect failed, attempting failover to a redundant server.</summary>
Failover,
/// <summary>Session is closing.</summary>
Closing,
/// <summary>Session is closed and disposed.</summary>
Closed
}
/// <summary>
/// Event args for connection state changes.
/// </summary>
public sealed class ConnectionStateChangedEventArgs : EventArgs
{
/// <summary>The previous state.</summary>
public ConnectionState PreviousState { get; init; }
/// <summary>The new state.</summary>
public ConnectionState NewState { get; init; }
/// <summary>Service result if the transition was due to an error.</summary>
public ServiceResult? Error { get; init; }
/// <summary>The reconnect attempt number (0 when not reconnecting).</summary>
public int ReconnectAttempt { get; init; }
/// <summary>
/// Underlying managed-channel state transition that caused this
/// outer state transition, or <c>null</c> when no channel-manager
/// state was involved.
/// </summary>
public ChannelStateChange? UnderlyingChannelState { get; init; }
}
}