/* ========================================================================
* 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.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Opc.Ua.Client
{
///
/// Used to handle renews of user identity tokens before reconnect.
///
public delegate IUserIdentity RenewUserIdentityEventHandler(
ISession session,
IUserIdentity identity);
///
/// The delegate used to receive keep alive notifications.
///
public delegate void KeepAliveEventHandler(ISession session, KeepAliveEventArgs e);
///
/// The delegate used to receive publish notifications.
///
public delegate void NotificationEventHandler(ISession session, NotificationEventArgs e);
///
/// The delegate used to receive publish error notifications.
///
public delegate void PublishErrorEventHandler(ISession session, PublishErrorEventArgs e);
///
/// The delegate used to modify publish response sequence numbers to acknowledge.
///
public delegate void PublishSequenceNumbersToAcknowledgeEventHandler(
ISession session,
PublishSequenceNumbersToAcknowledgeEventArgs e);
///
/// Manages a session with a server.
///
public interface ISession : ISessionClient, IAsyncDisposable
{
///
/// Raised when a keep alive arrives from the server or an error is detected.
///
///
/// Once a session is created a timer will periodically read the server state and current time.
/// If this read operation succeeds this event will be raised each time the keep alive period elapses.
/// If an error is detected (KeepAliveStopped == true) then this event will be raised as well.
///
event KeepAliveEventHandler KeepAlive;
///
/// Raised when a notification message arrives in a publish response.
///
///
/// All publish requests are managed by the Session object. When a response arrives it is
/// validated and passed to the appropriate Subscription object and this event is raised.
///
event NotificationEventHandler Notification;
///
/// Raised when an exception occurs while processing a publish response.
///
///
/// Exceptions in a publish response are not necessarily fatal and the Session will
/// attempt to recover by issuing Republish requests if missing messages are detected.
/// That said, timeout errors may be a symptom of a OperationTimeout that is too short
/// when compared to the shortest PublishingInterval/KeepAliveCount amount the current
/// Subscriptions. The OperationTimeout should be twice the minimum value for
/// PublishingInterval*KeepAliveCount.
///
event PublishErrorEventHandler PublishError;
///
/// Raised when a publish request is about to acknowledge sequence numbers.
///
///
/// If the client chooses to defer acknowledge of sequence numbers, it is responsible
/// to transfer these to the deferred list.
///
event PublishSequenceNumbersToAcknowledgeEventHandler PublishSequenceNumbersToAcknowledge;
///
/// Raised when a subscription is added or removed
///
event EventHandler SubscriptionsChanged;
///
/// Raised to indicate the session is closing.
///
event EventHandler SessionClosing;
///
/// Raised to indicate the session configuration changed.
///
///
/// An example for a session configuration change is a new user identity,
/// a new server nonce, a new locale etc.
///
event EventHandler SessionConfigurationChanged;
///
/// The factory which was used to create the session.
///
ISessionFactory SessionFactory { get; }
///
/// Gets the endpoint used to connect to the server.
///
ConfiguredEndpoint ConfiguredEndpoint { get; }
///
/// Gets the name assigned to the session.
///
string SessionName { get; }
///
/// Gets the period for wich the server will maintain the session if there
/// is no communication from the client.
///
double SessionTimeout { get; }
///
/// Gets the local handle assigned to the session.
///
object? Handle { get; }
///
/// Gets the user identity currently used for the session.
///
IUserIdentity Identity { get; }
///
/// Gets a list of user identities that can be used to connect to the server.
///
IEnumerable IdentityHistory { get; }
///
/// Gets the table of namespace uris known to the server.
///
NamespaceTable NamespaceUris { get; }
///
/// Gest the table of remote server uris known to the server.
///
StringTable ServerUris { get; }
///
/// Gets the system context for use with the session.
///
ISystemContext SystemContext { get; }
///
/// Gets the factory used to create encodeable objects that the server understands.
///
IEncodeableFactory Factory { get; }
///
/// Gets the cache of the server's type tree.
///
ITypeTable TypeTree { get; }
///
/// Gets the cache of nodes fetched from the server.
///
INodeCache NodeCache { get; }
///
/// Gets the context to use for filter operations.
///
IFilterContext FilterContext { get; }
///
/// Gets the locales that the server should use when returning localized text.
///
ArrayOf PreferredLocales { get; }
///
/// Gets the subscriptions owned by the session.
///
IEnumerable Subscriptions { get; }
///
/// Gets the number of subscriptions owned by the session.
///
int SubscriptionCount { get; }
///
/// If the subscriptions are deleted when a session is closed.
///
bool DeleteSubscriptionsOnClose { get; set; }
///
/// Gets or sets the time in milliseconds to wait for outstanding publish
/// requests to complete before canceling them during session close.
///
///
/// A value of 0 means no waiting - outstanding requests are canceled immediately.
/// A negative value means wait indefinitely for all outstanding requests to complete.
/// The default value is 5000 milliseconds (5 seconds).
///
int PublishRequestCancelDelayOnCloseSession { get; set; }
///
/// Gets or Sets the default subscription for the session.
///
Subscription DefaultSubscription { get; set; }
///
/// Gets or Sets how frequently the server is pinged to see if communication
/// is still working.
///
///
/// This interval controls how much time elaspes before a communication
/// error is detected.
/// If everything is ok the KeepAlive event will be raised each time this
/// period elapses.
///
int KeepAliveInterval { get; set; }
///
/// Returns true if the session is not receiving keep alives.
///
///
/// Set to true if the server does not respond for the KeepAliveInterval times
/// a configurable factor + a configurable guard band.
/// Set to false is communication recovers.
///
bool KeepAliveStopped { get; }
///
/// Gets the time of the last keep alive.
/// This time may not be monotonic if the system time is changed.
///
DateTime LastKeepAliveTime { get; }
///
/// Gets the monotonic timestamp (from ) of the
/// last keep alive. Use together with
/// to compute the elapsed time since the last keep alive without DateTime drift or
/// 32-bit tick wrap.
///
long LastKeepAliveTimestamp { get; }
///
/// Gets the number of outstanding publish or keep alive requests.
///
int OutstandingRequestCount { get; }
///
/// Gets the number of outstanding publish or keep alive requests which appear to be missing.
///
int DefunctRequestCount { get; }
///
/// Gets the number of good outstanding publish requests.
///
int GoodPublishRequestCount { get; }
///
/// Gets and sets the minimum number of publish requests to be used in the session.
///
int MinPublishRequestCount { get; set; }
///
/// Gets and sets the maximum number of publish requests to be used in the session.
///
int MaxPublishRequestCount { get; set; }
///
/// Whether a session is being reconnected
///
/// true if reconnected; otherwise, false.
bool Reconnecting { get; }
///
/// Stores the operation limits of a OPC UA Server.
///
OperationLimits OperationLimits { get; }
///
/// Stores the capabilities of a OPC UA server.
///
ServerCapabilities ServerCapabilities { get; }
///
/// If the subscriptions are transferred when a session is reconnected.
///
///
/// Default false, set to true if subscriptions should
/// be transferred after reconnect. Service must be supported by server.
///
bool TransferSubscriptionsOnReconnect { get; set; }
///
/// Whether the endpoint Url domain is checked in the certificate.
///
bool CheckDomain { get; }
///
/// gets or set the policy which is used to prevent the allocation of too many
/// Continuation Points in the ManagedBrowse(Async) methods
///
ContinuationPointPolicy ContinuationPointPolicy { get; set; }
///
/// Raised before a reconnect operation completes.
///
event RenewUserIdentityEventHandler RenewUserIdentity;
///
/// Reconnects to the server after a network failure using
/// a waiting connection or channel which either is provided.
/// If none is provided creates a new channel.
///
///
Task ReconnectAsync(
ITransportWaitingConnection? connection,
ITransportChannel? channel,
CancellationToken ct = default);
///
///Reload the own certificate used by the session and the issuer chain when available.
///
Task ReloadInstanceCertificateAsync(CancellationToken ct = default);
///
/// Saves a set of subscriptions to a stream.
///
///
///
///
void Save(
Stream stream,
IEnumerable subscriptions,
IEnumerable? knownTypes = null);
///
/// Load the list of subscriptions saved in a stream.
///
/// The stream.
/// Load the subscriptions for transfer
/// after load.
/// Additional known types that may be needed to
/// read the saved subscriptions.
/// The list of loaded subscriptions
IEnumerable Load(
Stream stream,
bool transferSubscriptions = false,
IEnumerable? knownTypes = null);
///
/// Returns the active session configuration and writes it to a stream.
///
SessionConfiguration SaveSessionConfiguration(Stream? stream = null);
///
/// Applies a session configuration.
/// Using a secure channel, with the session configuration a session can be reconnected.
///
bool ApplySessionConfiguration(SessionConfiguration sessionConfiguration);
///
/// Updates the local copy of the server's namespace uri and server uri tables.
///
/// The cancellation token.
Task FetchNamespaceTablesAsync(CancellationToken ct = default);
///
/// Updates the cache with the type and its subtypes.
///
///
/// This method can be used to ensure the TypeTree is populated.
///
Task FetchTypeTreeAsync(ExpandedNodeId typeId, CancellationToken ct = default);
///
/// Updates the cache with the types and its subtypes.
///
///
/// This method can be used to ensure the TypeTree is populated.
///
Task FetchTypeTreeAsync(ArrayOf typeIds, CancellationToken ct = default);
///
/// Establishes a session with the server.
///
/// The name to assign to the session.
/// The session timeout.
/// The user identity.
/// The list of preferred locales.
/// If set to true then the domain
/// in the certificate must match the endpoint used.
/// If set to true then the channel
/// is closed when the Open fails.
/// The cancellation token.
Task OpenAsync(
string sessionName,
uint sessionTimeout,
IUserIdentity identity,
ArrayOf preferredLocales,
bool checkDomain,
bool closeChannel,
CancellationToken ct = default);
///
/// Updates the user identity and/or locales used for the session.
///
/// The user identity.
/// The preferred locales.
/// The cancellation token.
Task UpdateSessionAsync(
IUserIdentity identity,
ArrayOf preferredLocales,
CancellationToken ct = default);
///
/// Changes the preferred locales used for the session.
///
/// The preferred locales.
/// The cancellation token.
Task ChangePreferredLocalesAsync(
ArrayOf preferredLocales,
CancellationToken ct = default);
///
/// Disconnects from the server and frees any network resources
/// with the specified timeout.
///
Task CloseAsync(
int timeout,
bool closeChannel,
CancellationToken ct = default);
///
/// Adds a subscription to the session.
///
/// The subscription to add.
bool AddSubscription(Subscription subscription);
///
/// Removes a transferred subscription from the session.
/// Called by the session to which the subscription
/// is transferred to obtain ownership. Internal.
///
/// The subscription to remove.
bool RemoveTransferredSubscription(Subscription subscription);
///
/// Removes a subscription from the session.
///
/// The subscription to remove.
/// The cancellation token for the request.
Task RemoveSubscriptionAsync(
Subscription subscription,
CancellationToken ct = default);
///
/// Removes a list of subscriptions from the session.
///
/// The list of subscriptions to remove.
/// The cancellation token for the request.
Task RemoveSubscriptionsAsync(
IEnumerable subscriptions,
CancellationToken ct = default);
///
/// Reactivates a list of subscriptions loaded from storage.
///
/// The list of subscriptions to reactivate.
/// Send the last value of each monitored item in the subscriptions.
/// The cancellation token for the request.
Task ReactivateSubscriptionsAsync(
SubscriptionCollection subscriptions,
bool sendInitialValues,
CancellationToken ct = default);
///
/// Transfers a list of subscriptions from another session.
///
/// The list of subscriptions to transfer.
/// Send the last value of each monitored item in the subscriptions.
/// The cancellation token for the request.
Task TransferSubscriptionsAsync(
SubscriptionCollection subscriptions,
bool sendInitialValues,
CancellationToken ct = default);
#if OPCUA_V1_CLIENT
///
/// Sends an additional publish request.
///
bool BeginPublish(int timeout);
#endif
///
/// Create the publish requests for the active subscriptions.
///
void StartPublishing(int timeout, bool fullQueue);
#if OPCUA_V1_CLIENT
///
/// Sends a republish request.
///
Task<(bool, ServiceResult)> RepublishAsync(
uint subscriptionId,
uint sequenceNumber,
CancellationToken ct = default);
#endif
}
}