Applies the safe / minor review feedback on PR #3852. Larger refactors
are scoped into a separate plan posted on the PR for explicit approval
before starting (merge ClientChannelManager partials, merge Channels.Stress
into Opc.Ua.Stress.Tests, move ClientChannelManagerManagedTests out of
Core.Tests, implement the ignored exhaustion-recovery integration test,
fix remaining CA2007 / CA1861 / CA5394 / CA2025 warnings without NoWarn).
Changes in this commit:
- .github/workflows/buildandtest.yml: drop "legacy" wording from the
EXCLUDE comment (Stress suite is opt-in, not legacy).
- Applications/ConsoleReferenceClient/UAClient.cs +
Applications/ConsoleReferenceClient/ClientSamples.cs: replace
Action<IList, IList>? validateResponse with Action<Array, Array>? to
(1) remove the System.Collections import that 36d67b3d had dropped
and (2) match what the call sites already pass (T[] arrays).
- Stack/Opc.Ua.Core/Stack/Client/ClientBase.cs: remove the
pragma warning disable CS0809 around AttachChannel/DetachChannel
(both interface and impl are [Obsolete] so the warning does not fire).
- Tests/Opc.Ua.Channels.Stress.Tests/*/.gitkeep: delete the seven
per-folder .gitkeep marker files; every folder now has content.
- Tests/Opc.Ua.Channels.Stress.Tests/Opc.Ua.Channels.Stress.Tests.csproj:
drop SuppressTfmSupportBuildWarnings and per-ProjectReference
AdditionalProperties=SuppressTfmSupportBuildWarnings=true (TFMs
restricted to net8/net9/net10 which fully support all Microsoft.Extensions.*
packages). Drop project-specific NoWarn extras
(CA2007;CA2000;CA2016;CA2025;CA5394;CA1861;CS1591), keep only the
common test-project NoWarn that matches Opc.Ua.Stress.Tests etc.
Restore Nullable=annotations to match the established test convention.
- Tests/Opc.Ua.Channels.Stress.Tests/Helpers/WaitForQuiescence.cs:
add ! null-forgiving on the TryFindDiagnostic out parameter.
- 17 test files (Channels.Stress, Client.Tests, Core.Tests/Stack/Client,
Sessions.Tests): move pragma warning disable directives below the
using statements per the convention noted in the review.
Verified locally: Channels.Stress.Tests, Sessions.Tests, Client.Tests,
Core.Tests all build with 0 errors on net10.0.
The buildandtest workflow only builds each test project for net10.0 via
CustomTestTarget, so three TFM-compatibility issues were masked. CodeQL
builds the whole solution for all TFMs and surfaced them:
1. Applications/ConsoleReferenceClient/UAClient.cs: regression from
36d67b3d removed 'using System.Collections;' but the file still uses
non-generic IList in the validateResponse signature. Restore the
using so the project compiles on every TFM (the error was actually
present on net10.0 too).
2. Tests/Opc.Ua.Client.Tests/Session/ManagedSessionTests.cs: the new
ManagedSessionPropagatesBudgetToChannelManagerAsync test exercises
IClientChannelManager.ReconnectAsync(channel, budget, ct), which is
a default-interface-method overload only present on netstandard2.1
and net8.0+. Guard the test body with the matching #if and Ignore
on older TFMs to keep the multi-TFM project compiling.
3. Tests/Opc.Ua.Channels.Stress.Tests/Opc.Ua.Channels.Stress.Tests.csproj:
the stress/chaos suite relies on modern primitives (3-arg Task.Delay,
RandomNumberGenerator.GetInt32, Math.Clamp, ValueTask.CompletedTask,
IClientChannelManager.ReconnectAsync(budget), Activator.CreateInstance
overloads, etc.) that simply do not exist on net48/net472. Override
TargetFrameworks to net8.0;net9.0;net10.0 so whole-solution builds
stop trying to compile it against legacy frameworks. The CI matrix
runs it under CustomTestTarget=net10.0 only, so this change is a
no-op for the standard test pipeline.
Verified locally with a full 'dotnet build UA.slnx -c Release
/p:UseSharedCompilation=false -m:1' (0 errors).
- Move all channel-related types into `Stack/Opc.Ua.Core/Stack/Client/Channels/`
subfolder (#13).
- Un-obsolete `SessionReconnectHandler` and the SessionExtensions
`ReconnectAsync(connection, ct)` / `(channel, ct)` extensions; remove
all SRH-related `#pragma warning disable CS0618` suppressions from
applications and tests. AttachChannel/DetachChannel remain obsolete (#1, #4).
- Remove the shared-budget section from MigrationGuide.md (#3).
- Mark `ManagedSession.AttachChannel`/`DetachChannel` `[Obsolete]` so the
warning surfaces all the way up the supported API surface (#9).
- Break the `<see cref=…>` line in `Session.ChannelManager.cs` to stay under
140 chars (#10).
- Move `ChannelManagerSessionFactory` from `Opc.Ua.Gds.Client.Common` into
`Opc.Ua.Client` as a public, documented session-factory option (#11).
- Audit other client classes for `IClientChannelManager`-aware overloads;
add `ISessionFactory`-accepting overloads on `GlobalDiscoveryServerClient`,
`LocalDiscoveryServerClient`, `ServerPushConfigurationClient` so any
session factory (including `ChannelManagerSessionFactory`) works (#12).
- Refactor MCP server (`OpcUaSessionManager`, `Program`) to use
`ManagedSession` + DI-resolved `IClientChannelManager`; remove
`SessionReconnectHandler` and manual keep-alive reconnect (#2).
- ConnectionStateMachine code-style fixes: use named delegate types,
collapse multi-line callback properties to single lines, swap
`timeProvider`/`maxTotalReconnectTime` constructor param order,
fix multi-line declaration (#6, #7, #8).
- HTTPS resilience: confirmed `Microsoft.Extensions.Http` and
`Microsoft.Extensions.Http.Resilience` 10.6.0 support
`net472`/`net48`/`netstandard2.1`; removed `#if NET8_0_OR_GREATER`
gating from `ManagedSessionBuilder` and `OpcUaClientBuilderExtensions`
and HTTPS csproj package refs (#5).
Verification:
- `Opc.Ua.Client` + `Opc.Ua.Core` + `Opc.Ua.Gds.Client.Common` build
clean (0 warnings, 0 errors).
- 56/56 core channel-manager / retry-budget / HTTPS factory tests pass.
- 129/129 client (ManagedSession + legacy SRH back-compat + SessionExtensions)
tests pass.
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.
# Description
Introduces a pluggable user-identity provider model covering all OPC UA
Part 6 §6.5 mechanisms (Anonymous, UserName, X509, IssuedToken/JWT) on
both client and server, with full
`Microsoft.Extensions.DependencyInjection` integration, plus the Part 12
§9 `AuthorizationService` two-phase token-request flow **including
refresh-token rotation**, the Part 12 §8 KeyCredential Push model, and a
clean provider model for OPC 10000-12 §7.2 `ApplicationSelfAdmin`. The
work is split across phase-by-phase commits so it can be reviewed
independently; nothing here changes wire-level behaviour or forces
existing applications to migrate.
### Documentation
All under `Docs/`:
- `IdentityProviders.md` — full developer guide: three-layer model,
recipes, configuration reference, "what gets auto-wired" matrix, JWS
algorithm table, identity-augmenters section, **"Implementing your own
provider"** how-to subsections for Entra / OIDC / Windows / AspNetCore
(sibling files merged in per review feedback).
- `DependencyInjection.md` — `Identity` sections with `appsettings.json`
examples, identity-extension matrix, `WithAuthorizationService` +
`WithKeyCredentialPush` + `AddIdentityAugmenter` extensions documented.
- `RoleBasedUserManagement.md` — claim-criteria callout describing
`IIdentityClaims` probe surface.
- `AuthorizationService.md` — Architecture diagram +
`IAccessTokenProvider` conceptual narrative restored from master; modern
`StartRequestToken` / `FinishRequestToken` flow leads; refresh-token
recipe added.
- `KeyCredentialService.md` — Push model + Pull vs Push vs Bridge
decision matrix + Hybrid (Push + Pull) section; explicit experimental
warning for the bridge.
- `GDS.md` — KeyCredential Push, `StartRequestToken`,
`GdsApplicationSelfAdminProvider`, **shipped Refresh-token support with
rotation policy and audit semantics** all documented.
- `MigrationGuide.md` — User Identity Providers section listing
`[Obsolete]` markers + mechanical recipes; SelfAdmin migration via
`IIdentityAugmenter`; `EnableRefreshTokens` default note.
- `README.md` index entries.
## 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.
- [x] I ran **all** tests locally using the **UA.slnx** solution against
at least .net **framework** and .net **10**, and all passed.
- [x] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [x] I have addressed **all** PR feedback received.
* New certificate and secrete abstraction with certificate infrastructure and certificate/secret stores.
* leak testing for certificate resources to validate new ref counting in every test assembly
* Migration guide updated and documentation added for all
* Remove IDisposable from Nodestate and UserIdentity.
* UserCertificateTokenHandler now just points into certificate registry/stores, no dispose required
* Fix CA2000 warnings and cleanup of other diagnostics, increase warning levels in .editorconfig
This pull request modernizes the OPC UA .NET codebase and tests, removes .NET Standard 2.0 support from certificate/security code, and updates test code to use C# 12 and .NET 8+ features for clarity and maintainability.
- Certificate and BouncyCastle interop files (e.g., CertificateBuilder.cs, X509Extensions.cs, X509SignatureFactory.cs) are refactored to drop NETSTANDARD2_0 support and use modern .NET APIs and conditional compilation.
- Test code across the codebase is updated to use default, strongly-typed Parse methods, collection expressions, and improved async/await patterns.
- Exception handling and assertions in tests are modernized, and test method naming is made consistent with Async suffixes.
- The project and build files are updated to clarify Roslynator analyzer usage and remove obsolete netstandard tags.
- General code and test cleanup includes improved null safety, type safety, and removal of deprecated or unused code.
* Enable Durable Subscriptions (#9)
* [Server] Durable Subscriptions (#2683)
* Implement a system test for DurableSubscriptions (#2839)
* Client Side
Co-authored-by: ALTERNATE-DEV\Archie <archie@dreamsandadventures.ca>
* make a static Method CalculateRevisedQueueSize
* Adress review feedback
* fix FilterRetainTests
* Add MonitoredItem Id to Queues
Use NodeIdDictionary where possible
* Added MaxChannelCount and detect and cleanup "stale" channels based on ChannelLifetime
* Add Environment.TickCount as time reference
* Set a socket backlog value to avoid socket open overflow
* Added a ChannelKeepAlive to signal when a session is still active
* Add options to console client to leak channels and run connect loop forever
Co-authored-by: Martin Regen <mregen@microsoft.com>
- Implement the reconnect and republish with async service calls.
bug fixes:
- subscription Ids should start from a random number
- the keep alive interval calculation is too short, adding +1 for the timeout
- on BadSessionIdInvalid recreate session immediately
- on a restarted server with new certificate, also reload endpoints when BadCertificateInvalid is returned
Currently, due to some internal cloning of sessions, subscriptions and monitored items it is not possible to use subclassed variants which are properly recreated after a session reconnect.
- Add a `ISessionInstantiator` interface to allow to subclass a `Session` and override virtual function.
- Add a `Subscription.CloneSubscription` and `MonitoredItem.CloneMonitoredItem` virtual method to recreate those with event handlers and client handles.
- A sample implementation with `TestableXXX` classes is provided to test the BadInvalidTimestamp fix by injecting modified timestamps in the session class.
- Remove duplicate `IDisposable` with `Session`. `IClientBase` is disposable already.
- adds `knownTypes` parameter to `Session.Load` and `Session.Save` to support save and restore of custom Subscriptions and Monitored items.
bug fixes:
- IOP: an empty DataTypeDictionary throws an exception when loaded by the complex type system, server are allowed to leave it empty to save memory.
- BadInvalidTimestamp should not be returned when the timestamp in the requestheader is out of sync. #2364
- CloseAsync still used the 'Close' synchronous function
- remove a duplicate definition of IDisposable on ISession
- reduce the log output when the server publish time is out of sync
- A few use cases were still missing from the ISessionFactory interface to make the static `Session.Create` functions completely obsolete.
- Follow naming conventions (Async) and add CancellationToken where missing.
- With exponential backoff enabled, a KeepAlive calling `BeginReconnect` could retrigger the timer in a way that a reconnect would never occur.
- Throttle `ISession.BeginPublish` on `BadTooManyOperations` error.
- Add reverse connect option to console client to test reconnect with reverse connect manager.
- null events in session on dispose to suppress spurious events.
- mark `TransferSubscription` service calls obsolete to avoid accidential use by applications.
- for reverse connection testing of session reconnect handler, add options for no security and reverse connect endpoint to console client
- Deprecate support for Nuget package support of .NET Framework 4.6.2
- Bump sample applications to 4.8
- update some copyright headers / supporting files (editorconfig etc.)
- fix a few warnings
- fix an issue with `SessionReconnectHandler`, in certain combination of reconnect period and exponential backoff the .NET sample app never reconnected.
- due to the new `MinPublishRequestCount` property publish requests are being sent after reconnect even if no subscription is active
- Improve sample code to show how to dispose the old session after reconnect
Currently the session reconnect requires to create and destroy the object and to lock the operation in the client code.
The refactored version is backward compatible but allows for a single instance to handle reconnects during the lifetime of the client. In addition no more locking is necessary in the client code.
- exponential backoff is enabled by using a constructor `new SessionReconnectHandler( true, 30000);` which would set the maxReconnectPeriod` to 30000ms. The backoff period is doubled after every unsuccessful request.
- a 10% random jitter is added to every timer update.
- The `public virtual int JitteredReconnectPeriod(int reconnectPeriod)` and `public virtual int CheckedReconnectPeriod(int reconnectPeriod, bool exponentialBackoff = false)` can be overloaded to implement custom jitter and backoff implementations.
- A new `ISession.MinPublishRequestCount` property can be set to enforce a minimum number of active publish requests. Default behavior is one publish request per subscription. It can help for low latency high frequency publish intervals.
- A new `PublishSequenceNumbersToAcknoledge` event is implemented which allows to defer ack of sequence numbers until fully processed by the client.
All new methods/properties ar not breaking changes and by default there is no behavior change, all existing code should work and compile aginst the update flawlessly.
- A bugfix in the reconnect handler, when a server changed the application certificate the reconnect ends up in an endless loop, because the `EndpointDescription` is not updated. The fix updates the endpoint from the server if a `BadSecurityChecksFailed` error os returned and then tries to reconnect with a new session.
Expose an 'ISession' interface as abstraction to ease unit testing.
Breaking changes are kept to minimal impact, but some changes maybe required to use ISession objects instead of Session.
Note: ISessionClientMethods is hand created, not yet by ModelCompiler
Improvements for complex types.
- Support to encode/decode complex type structures with multidimensional arrays.
- Perf improvements for type loader using new NodeCache fetch multiple interfaces.
- DataTypeDictionary validation when dependencies are used.
- interface for complex type resolver, to build custom types in code.
- improvements of console client to demonstrate browse/read of custom values
+++ Breaking changes +++
IDecoder interface change of the `ReadArray` method
- Return type is now `Array` for all types of arrays. Previously the method returned an array for 1-dim and a `Matrix` type for multidimensional arrays. In addition the convention in generated code is to use `Collection` for all 1-dim arrays, and so was built the `BaseComplexType`. The new convention is to expose the native `Array` type from a complex type, in all cases, hence the return type of `ReadArray` was changed to reflect that for a consistent programming model.
- `ReadArray` has a new parameter `systemType` to efficiently read encodeable types. Previously the `Type` of an encodeable was determined by the encodingid and lookup in the type factory, even when the Type is already known by the caller. The 'old' style is still supported.
- `ReadArray` supports to read encodeable type arrays which are directly encoded in structures. These arrays differ from standard encoding of arrays and they are handled when `BuiltInType.Null` is used as parameter.
- set `KeepAliveTimeout` default back to 5s, was unintentionally set to 50s in 368 release
- fix a bug that duplicate subscriptions were created after reconnect when transfer succeeds.
- add a property to enable subscription transfer in reconnect, set `Session.TransferSubscriptionsOnReconnect=true` to enable, IOP issues may not allow to use it with some servers.
- add a `SessionReconnectHandler(true)` constructor to support reconnect abort, if the connection recovers before reconnect timer called. If the new constructor is used, its a breaking change: Needs check of `Session` property in Reconnect handler callback, if aborted `Session==null`.
- Reduce warning log output if server timestamp > client time.
- Add handling when subscriptions can not be transferred, e.g. when false user credentials or no security prevent transfer.
- Improve the reconnect timer handling by using `OperationLimit` in reconnect.
- Add sample for `SessionReconnectHandler` in console client.
- Seperate session sample code from `UAClient`.
- Tested on popular demo servers of various SDK vendors.
- Fix Winforms ref client
- support for Microsoft.Extensions.Logger.ILogger in Opc.Ua.Core as the new logging interface
- backward compatible with config and TraceEvents
- new API Utils.SetLogger allows to set ILogger
- updated Console samples to demonstrate ILogger support with Serilog
- support for EventSource logging
- see Docs/Logging.md for more info
-fixes for complex types:
- a structure which contains an enum from namespace 0 can not be created. fixes#1561.
- a structure with multidimensional array may lead to a endless loop in `ComplexTypeSystem.Load`
- a malformed namespace Uri which contains a space character prevents creation of type system.
- select endpoint doesn't pick the right scheme if the default endpoint must be picked
-prep for net472 or greater and net5.0 or greater build, only build #ifdef
* Adds proper TPL usage, decouples dependencies on Console and ClientBase, and uses string interpolation versus String.Format.
* Renames private members to standard naming convention.
- The AcceptAll flag can be used to accept all suppressible errors in one call back
- Behaviour unchanged when only Accept is set, callback is invoked for all errors and all must be approved