Interface ISession

The client session to a server or cluster of servers.

Namespace: PushTechnology.ClientInterface.Client.Session
Assembly: Diffusion.Client.dll
Syntax
public interface ISession
Remarks

A new session can be created by connecting to a server using Open(String), specifying the server URL. There is also a non-blocking variant Open(String, ISessionOpenCallback). The session factory can be configured to control the behavior of the session.

The session provides a variety of operations to the application. These are grouped into feature interfaces, such as ITopics and IMessaging, exposed to the application through various properties.


Session lifecycle

Each session is managed by a server. The server assigns the session a unique identity (ISessionId), and manages the session's topic subscriptions, security details, and session properties.

A session can be terminated using Close(). A session may also be terminated by the server because of an error or a time out, or by other privileged sessions using the IClientControl feature.

A client can become disconnected from the server, and reconnect to the server without loss of the session. Reconnection can be configured using ReconnectionStrategy(IReconnectionStrategy). The server must be configured to allow reconnection.

If a session is connected to a server that belongs to a cluster with session replication enabled, and then becomes disconnected, it will attempt to reconnect to the original server. A properly configured load balancer can detect that the original server is unavailable and re-route the reconnection request to a second server in the cluster. The second server can recover session data and continue the session. This process is known as "fail over". Unlike reconnection, in-flight messages can be lost during failover, and the application will be unsubscribed and re-subscribed to topics.

The current state of the session can be retrieved with the State property. A listener can be registered with the StateChanged event which will be notified when the session state changes.


Session Properties

For each session, the server stores a set of session properties that describe various attributes of the session.

There are two types of session property. Fixed properties are assigned by the server. User-defined properties are assigned by the application.

Many operations use session filter expressions that use session properties to select sessions.

A privileged client can monitor other sessions, including changes to their session properties, using a ISessionPropertiesListener. When registering to receive session properties, special key values of ALL_FIXED_PROPERTIES and ALL_USER_PROPERTIES can be used.

Each property is identified by a key. Most properties have a single string value. The exception is the ROLES fixed property which has a set of string values.

Fixed properties are identified by keys with a $ prefix. The available fixed session properties are:

KeyDescription
$ClientIP (CLIENT_IP) The Internet address of the client in string format.
$ClientType (CLIENT_TYPE) The client type of the session. One of ANDROID, C, DOTNET, IOS, JAVA, JAVASCRIPT_BROWSER, MQTT, PYTHON, REST, or OTHER.
$Environment (ENVIRONMENT) The environment in which the client is running. For possible values see the user manual.
$Connector (CONNECTOR) The configuration name of the server connector that the client connected to.
$Country (COUNTRY) The country code for the country where the client's Internet address was allocated (for example, NZ for New Zealand). If the country code could not be determined, this will be a zero length string.
$GatewayType (GATEWAY_TYPE) Gateway client type. Only set for gateway client sessions. If present it indicates the type of gateway client (e.g. Kafka).
$GatewayId (GATEWAY_ID) The identity of a gateway client session. Only present if the $GatewayType session property is present.
$Language (LANGUAGE) The language code for the official language of the country where the client's Internet address was allocated (for example, en for English). If the language could not be determined or is not applicable, this will be a zero length string.
$Latitude (LATITUDE) The client's latitude, if available. This will be the string representation of a floating point number and will be NaN if not available.
$Longitude (LONGITUDE) The client's longitude, if available. This will be the string representation of a floating point number and will be NaN if not available.
$MQTTClientId (MQTT_CLIENT_ID) The MQTT client identifier. Only set for MQTT sessions. If present, the value of the `$ClientType` session property will be MQTT.
$Principal (PRINCIPAL) The security principal associated with the client session.
$Roles (ROLES) Authorisation roles assigned to the session. This is a set of roles represented as quoted strings (for example, "role1","role2"). The utility method StringToRoles(String) can be used to parse the string value into a set of roles.
$ServerName (SERVER_NAME) The name of the server to which the session is connected.
$SessionId (SESSION_ID) The session identifier. Equivalent to ISessionId's ToString() output.
$StartTime (START_TIME) The session's start time in milliseconds since the epoch.
$Transport (TRANSPORT) The session transport type. One of WEBSOCKET, HTTP_LONG_POLL, TCP, or OTHER.

All listed property keys constants can be found in SessionProperty.

All user-defined property keys are non-empty strings and are case-sensitive. The characters ' ', '\t', '\r', '\n', '\"', '\'', '(', ')' are not allowed.

Session properties are initially associated with a session as follows:

  1. When a client starts a new session, it can optionally propose user-defined session properties (see Property(String, String) and Properties(IDictionary<String, String>)). Session properties proposed in this way must be accepted by the authenticator. This safeguard prevents abuse by a rogue, unprivileged client.
  2. The server allocates all fixed property values.
  3. The new session is authenticated by registered authenticators. An authenticator that accepts a session can veto or change the user-defined session properties and add new user-defined session properties. The authenticator can also change certain fixed properties.

Once a session is established, its user-defined session properties can be modified by clients with VIEW_SESSION and MODIFY_SESSION permissions using IClientControl. A privileged client can also modify its own session properties.

If a session re-authenticates (see ChangePrincipalAsync(String, ICredentials)), the authenticator that allows the re-authentication can modify the user-defined session properties and a subset of the fixed properties as mentioned above.


Session Filters

Session filters are a mechanism of addressing a set of sessions by the values of their session properties.

Session filters are specified using a Domain Specific Language (DSL). For a full and detailed description of the session filters DSL see the user manual.


Session locks

The actions of multiple sessions can be coordinated using session locks. See ISessionLock.


Note

This interface does not require user implementation and is only used to hide implementation details.

Added in 5.0.

Examples

Opening a session to localhost using the WebSocket protocol on port 8080.

var session = Diffusion.Sessions.Open( "ws://localhost:8080" );

Properties

Attributes

Gets attributes of this session.

Declaration
ISessionAttributes Attributes { get; }
Property Value
Type Description
ISessionAttributes

The attributes of this session.

Remarks

Added in 5.0.

Examples

Retrieving the session attributes.

// session is a previously obtained ISession instance.
var attributes = session.Attributes;

AuthenticationControl

Gets the authentication-control feature.

Declaration
IAuthenticationControl AuthenticationControl { get; }
Property Value
Type Description
IAuthenticationControl

The authentication-control feature.

Remarks

Added in 5.0.

Examples

Retrieving the authentication-control feature.

// session is a previously obtained ISession instance.
var authenticationControl = session.AuthenticationControl;

ClientControl

Gets the client-control feature.

Declaration
IClientControl ClientControl { get; }
Property Value
Type Description
IClientControl

The client-control feature.

Remarks

Added in 5.0.

Examples

Retrieving the client-control feature.

// session is a previously obtained ISession instance.
var clientControl = session.ClientControl;

Messaging

Gets the messaging feature.

Declaration
IMessaging Messaging { get; }
Property Value
Type Description
IMessaging

The messaging feature.

Remarks

Added in 5.0.

Examples

Retrieving the messaging feature.

// session is a previously obtained ISession instance.
var messaging = session.Messaging;

Metrics

Gets the metrics feature.

Declaration
IMetrics Metrics { get; }
Property Value
Type Description
IMetrics

The metrics feature.

Remarks

The Metrics feature allows a client to configure metric collectors.

Added in 6.7.
Examples

Retrieving the metrics feature.

// session is a previously obtained ISession instance.
var metrics = session.Metrics;

Ping

Gets the pings feature.

Declaration
IPings Ping { get; }
Property Value
Type Description
IPings

The pings feature.

Remarks

Added in 5.0.

Examples

Retrieving the pings feature.

// session is a previously obtained ISession instance.
var pings = session.Ping;

Principal

Gets the name of the security principal associated with the session.

Declaration
string Principal { get; }
Property Value
Type Description
System.String

The principal name.

Remarks

If the session was opened with no associated principal, (it is an "anonymous session"), an empty string will be returned.


Added in 5.0.

Examples

Retrieving the session principal.

// session is a previously obtained ISession instance.
var principal = session.Principal;

RemoteServers

Gets the remote servers feature.

Declaration
IRemoteServers RemoteServers { get; }
Property Value
Type Description
IRemoteServers

The remote servers feature.

Remarks

The Remote Servers feature allows a client session to create, remove, list and check remote servers.

Added in 6.5.
Examples

Retrieving the remote servers feature.

// session is a previously obtained ISession instance.
var remoteServers = session.RemoteServers;

Security

Gets the security feature.

Declaration
ISecurity Security { get; }
Property Value
Type Description
ISecurity

The security feature.

Remarks

Added in 5.0.

Examples

Retrieving the security feature.

// session is a previously obtained ISession instance.
var security = session.Security;

SecurityControl

Gets the security-control feature.

Declaration
ISecurityControl SecurityControl { get; }
Property Value
Type Description
ISecurityControl

The security-control feature.

Remarks

Added in 5.3.

Examples

Retrieving the security-control feature.

// session is a previously obtained ISession instance.
var securityControl = session.SecurityControl;

SessionId

Gets the unique identifier of this session.

Declaration
ISessionId SessionId { get; }
Property Value
Type Description
ISessionId

The session identifier.

Remarks

The session identifier will be assigned by the first server this session connected to.


Added in 5.0.

Examples

Retrieving the session identifier.

// session is a previously obtained ISession instance.
var sessionId = session.SessionId;

SessionTrees

Gets the session trees feature.

Declaration
ISessionTrees SessionTrees { get; }
Property Value
Type Description
ISessionTrees

The session trees feature.

Remarks

The Session Trees feature allows the creation and alteration of branch mapping tables.

Added in 6.7.
Examples

Retrieving the session trees feature.

// session is a previously obtained ISession instance.
var sessionTrees = session.SessionTrees;

State

Gets the current state of this session.

Declaration
SessionState State { get; }
Property Value
Type Description
SessionState

The current state of this session.

Remarks

Added in 5.0.

Examples

Retrieving the session state.

// session is a previously obtained ISession instance.
var state = session.State;

SubscriptionControl

Gets the subscription-control feature.

Declaration
ISubscriptionControl SubscriptionControl { get; }
Property Value
Type Description
ISubscriptionControl

The subscription-control feature.

Remarks

Added in 5.0.

Examples

Retrieving the subscription-control feature.

// session is a previously obtained ISession instance.
var subscriptionControl = session.SubscriptionControl;

SystemAuthenticationControl

Gets the system-authentication-control feature.

Declaration
ISystemAuthenticationControl SystemAuthenticationControl { get; }
Property Value
Type Description
ISystemAuthenticationControl

The system-authentication-control feature.

Remarks

Added in 5.2.

Examples

Retrieving the system-authentication-control feature.

// session is a previously obtained ISession instance.
var systemAuthenticationControl = session.SystemAuthenticationControl;

TimeSeries

Gets the time-series feature.

Declaration
ITimeSeries TimeSeries { get; }
Property Value
Type Description
ITimeSeries

The time-series feature.

Remarks

Added in 6.1.

Examples

Retrieving the time-series feature.

// session is a previously obtained ISession instance.
var timeSeries = session.TimeSeries;

TopicControl

Gets the topic-control feature.

Declaration
ITopicControl TopicControl { get; }
Property Value
Type Description
ITopicControl

The topic-control feature.

Remarks

Added in 5.0.

Examples

Retrieving the topic-control feature.

// session is a previously obtained ISession instance.
var topicControl = session.TopicControl;

TopicNotifications

Gets the topic-notifications feature.

Declaration
ITopicNotifications TopicNotifications { get; }
Property Value
Type Description
ITopicNotifications

The topic-notifications feature.

Remarks

Added in 6.1.

Examples

Retrieving the topic-notifications feature.

// session is a previously obtained ISession instance.
var topicNotifications = session.TopicNotifications;

Topics

Gets the topics feature.

Declaration
ITopics Topics { get; }
Property Value
Type Description
ITopics

The topics feature.

Remarks

Added in 5.0.

Examples

Retrieving the topics feature.

// session is a previously obtained ISession instance.
var topics = session.Topics;

TopicUpdate

Gets the topic-update feature.

Declaration
ITopicUpdate TopicUpdate { get; }
Property Value
Type Description
ITopicUpdate

The topic-update feature.

Remarks

Added in 6.2.

Examples

Retrieving the topic-update feature.

// session is a previously obtained ISession instance.
var topicUpdate = session.TopicUpdate;

TopicViews

Gets the topic-views feature.

Declaration
ITopicViews TopicViews { get; }
Property Value
Type Description
ITopicViews

The topic-views feature.

Remarks

Added in 6.3.

Examples

Retrieving the topic-views feature.

// session is a previously obtained ISession instance.
var topicViews = session.TopicViews;

Methods

Close()

Closes the session.

Declaration
void Close()
Remarks

Has no effect if the session is already closed.


Added in 5.0.

Examples

Closing an active session.

// session is a previously obtained ISession instance.
session.Close();

LockAsync(String)

Attempts to acquire a ISessionLock.

Declaration
Task<ISessionLock> LockAsync(string lockName)
Parameters
Type Name Description
System.String lockName

The name of the session lock.

Returns
Type Description
Task<ISessionLock>

The Task representing the current operation.

Remarks

If the operation completes successfully, the Task result will be the requested ISessionLock assigned to the calling session by the server. The session owns the returned lock and is responsible for unlocking it.

Acquiring the lock can take an arbitrarily long time if other sessions are competing for the lock. The server will retain the session's request for the lock until it is assigned to the session, the session is closed.

A session can call this method multiple times. If the lock is acquired, all calls will complete successfully with equal ISessionLock.

A session that acquires a lock will remain its owner until it is unlocked (via UnlockAsync()) or the session closes. The LockAsync(String, SessionLockScope) variant of this method takes a scope argument that provides the further option of releasing the lock when the session loses its connection to the server.


Access control

To allow fine-grained access control, lock names are interpreted as path names, controlled with the ACQUIRE_LOCK topic permission. This allows permission to be granted to a session to acquire the lock update-topic/a while preventing the session from acquiring the lock update-topic/b, for example.

This method is the same as calling LockAsync(String, CancellationToken) with System.Threading.CancellationToken.None.


Added in 6.2.

Examples

Acquiring a session lock.

try {
    // session is a previously obtained ISession instance.
    var sessionLock = await session.LockAsync( "lock name" );
    Console.WriteLine( $"Lock {sessionLock.Name} acquired." );
} catch ( SessionSecurityException ex ) {
    Console.WriteLine( $"Acquiring lock failed because of security reasons: {ex}" );
} catch ( SessionClosedException ex ) {
    Console.WriteLine( "Acquiring lock failed because the session is closed." );
}
Exceptions
Type Condition
SessionSecurityException

The calling session does not have ACQUIRE_LOCK permission for lockName. Thrown by the returned Task.

SessionClosedException

The calling session is closed. Thrown by the returned Task.

See Also
LockAsync(String, CancellationToken)
ISessionLock

LockAsync(String, CancellationToken)

Attempts to acquire a ISessionLock.

Declaration
Task<ISessionLock> LockAsync(string lockName, CancellationToken cancellationToken)
Parameters
Type Name Description
System.String lockName

The name of the session lock.

CancellationToken cancellationToken

The cancellation token used to cancel the current operation.

Returns
Type Description
Task<ISessionLock>

The Task representing the current operation.

Remarks

If the operation completes successfully, the Task result will be the requested ISessionLock assigned to the calling session by the server. The session owns the returned lock and is responsible for unlocking it.

Acquiring the lock can take an arbitrarily long time if other sessions are competing for the lock. The server will retain the session's request for the lock until it is assigned to the session, the session is closed, or the session cancels the Task.

A session can call this method multiple times. If the lock is acquired, all calls will complete successfully with equal ISessionLock.

Canceling the returned Task has no effect on other pending lock calls made by the session.

A session that acquires a lock will remain its owner until it is unlocked (via UnlockAsync(CancellationToken)) or the session closes. The LockAsync(String, SessionLockScope, CancellationToken) variant of this method takes a scope argument that provides the further option of releasing the lock when the session loses its connection to the server.


Access control

To allow fine-grained access control, lock names are interpreted as path names, controlled with the ACQUIRE_LOCK topic permission. This allows permission to be granted to a session to acquire the lock update-topic/a while preventing the session from acquiring the lock update-topic/b, for example.


Added in 6.2.

Examples

Acquiring a session lock.

var cancellationTokenSource = new CancellationTokenSource();
var token = cancellationTokenSource.Token;

try {
    // session is a previously obtained ISession instance.
    var sessionLock = await session.LockAsync( "lock name", token );
    Console.WriteLine( $"Lock {sessionLock.Name} acquired." );
} catch ( SessionSecurityException ex ) {
    Console.WriteLine( $"Acquiring lock failed because of security reasons: {ex}" );
} catch ( SessionClosedException ex ) {
    Console.WriteLine( "Acquiring lock failed because the session is closed." );
}
Exceptions
Type Condition
SessionSecurityException

The calling session does not have ACQUIRE_LOCK permission for lockName. Thrown by the returned Task.

SessionClosedException

The calling session is closed. Thrown by the returned Task.

See Also
ISessionLock

LockAsync(String, SessionLockScope)

Attempts to acquire a ISessionLock with a given scope.

Declaration
Task<ISessionLock> LockAsync(string lockName, SessionLockScope scope)
Parameters
Type Name Description
System.String lockName

The name of the session lock.

SessionLockScope scope

The scope of the session lock.

Returns
Type Description
Task<ISessionLock>

The Task representing the current operation.

Remarks

If the operation completes successfully, the Task result will be the requested ISessionLock assigned to the calling session by the server. The session owns the returned lock and is responsible for unlocking it.

Acquiring the lock can take an arbitrarily long time if other sessions are competing for the lock. The server will retain the session's request for the lock until it is assigned to the session, the session is closed.

A session can call this method multiple times. If the lock is acquired, all calls will complete successfully with equal ISessionLock.

A session that acquires a lock will remain its owner until it is unlocked (via UnlockAsync()) or the session closes.

If called with a scope of UNLOCK_ON_SESSION_LOSS, this method behaves exactly like LockAsync(String).

If called with a scope of UNLOCK_ON_CONNECTION_LOSS, any lock that is returned will be unlocked if the session loses its connection to the server. This is useful to allow another session to take ownership of the lock while this session is reconnecting.

If a session makes multiple requests for a lock using different scopes, and the server assigns the lock to the session fulfilling the requests, the lock will be given the weakest scope (UNLOCK_ON_CONNECTION_LOSS).


Access control

To allow fine-grained access control, lock names are interpreted as path names, controlled with the ACQUIRE_LOCK topic permission. This allows permission to be granted to a session to acquire the lock update-topic/a while preventing the session from acquiring the lock update-topic/b, for example.

This method is the same as calling LockAsync(String, SessionLockScope, CancellationToken) with System.Threading.CancellationToken.None.


Added in 6.2.

Examples

Acquiring a session lock.

var scope = SessionLockScope.UNLOCK_ON_CONNECTION_LOSS;

try {
    // session is a previously obtained ISession instance.
    var sessionLock = await session.LockAsync( "lock name", scope );
    Console.WriteLine( $"Lock {sessionLock.Name} acquired." );
} catch ( SessionSecurityException ex ) {
    Console.WriteLine( $"Acquiring lock failed because of security reasons: {ex}" );
} catch ( SessionClosedException ex ) {
    Console.WriteLine( "Acquiring lock failed because the session is closed." );
}
Exceptions
Type Condition
SessionSecurityException

The calling session does not have ACQUIRE_LOCK permission for lockName. Thrown by the returned Task.

SessionClosedException

The calling session is closed. Thrown by the returned Task.

See Also
LockAsync(String, SessionLockScope, CancellationToken)
ISessionLock

LockAsync(String, SessionLockScope, CancellationToken)

Attempts to acquire a ISessionLock with a given scope.

Declaration
Task<ISessionLock> LockAsync(string lockName, SessionLockScope scope, CancellationToken cancellationToken)
Parameters
Type Name Description
System.String lockName

The name of the session lock.

SessionLockScope scope

The scope of the session lock.

CancellationToken cancellationToken

The cancellation token used to cancel the current operation.

Returns
Type Description
Task<ISessionLock>

The Task representing the current operation.

Remarks

If the operation completes successfully, the Task result will be the requested ISessionLock assigned to the calling session by the server. The session owns the returned lock and is responsible for unlocking it.

Acquiring the lock can take an arbitrarily long time if other sessions are competing for the lock. The server will retain the session's request for the lock until it is assigned to the session, the session is closed, or the session cancels the Task.

A session can call this method multiple times. If the lock is acquired, all calls will complete successfully with equal ISessionLock.

Canceling the returned Task has no effect on other pending lock calls made by the session.

A session that acquires a lock will remain its owner until it is unlocked (by calling UnlockAsync(CancellationToken)) or the session closes.

If called with a scope of UNLOCK_ON_SESSION_LOSS, this method behaves exactly like LockAsync(String).

If called with a scope of UNLOCK_ON_CONNECTION_LOSS, any lock that is returned will be unlocked if the session loses its connection to the server. This is useful to allow another session to take ownership of the lock while this session is reconnecting.

If a session makes multiple requests for a lock using different scopes, and the server assigns the lock to the session fulfilling the requests, the lock will be given the weakest scope (UNLOCK_ON_CONNECTION_LOSS).


Access control

To allow fine-grained access control, lock names are interpreted as path names, controlled with the ACQUIRE_LOCK topic permission. This allows permission to be granted to a session to acquire the lock update-topic/a while preventing the session from acquiring the lock update-topic/b, for example.


Added in 6.2.

Examples

Acquiring a session lock.

var cancellationTokenSource = new CancellationTokenSource();
var token = cancellationTokenSource.Token;
var scope = SessionLockScope.UNLOCK_ON_CONNECTION_LOSS;

try {
    // session is a previously obtained ISession instance.
    var sessionLock = await session.LockAsync( "lock name", scope, token );
    Console.WriteLine( $"Lock {sessionLock.Name} acquired." );
} catch ( SessionSecurityException ex ) {
    Console.WriteLine( $"Acquiring lock failed because of security reasons: {ex}" );
} catch ( SessionClosedException ex ) {
    Console.WriteLine( "Acquiring lock failed because the session is closed." );
}
Exceptions
Type Condition
SessionSecurityException

The calling session does not have ACQUIRE_LOCK permission for lockName. Thrown by the returned Task.

SessionClosedException

The calling session is closed. Thrown by the returned Task.

See Also
ISessionLock

Events

ErrorNotified

The event for session errors.

Declaration
event EventHandler<SessionErrorHandlerEventArgs> ErrorNotified
Event Type
Type Description
EventHandler<SessionErrorHandlerEventArgs>

The event for session errors.

Remarks

Added in 5.0.

Examples

Subscribe to the event.

// session is a previously obtained ISession instance.
session.ErrorNotified += ( sender, e ) => {
    Console.WriteLine( $"Session Error: {e.Error}." );
};

StateChanged

The event for session state changes.

Declaration
event EventHandler<SessionListenerEventArgs> StateChanged
Event Type
Type Description
EventHandler<SessionListenerEventArgs>

The event for session state changes.

Remarks

Added in 5.0.

Examples

Subscribe to the event.

// session is a previously obtained ISession instance.
session.StateChanged += ( sender, e ) => {
    Console.WriteLine( $"{e.Session.SessionId} state changed from {e.OldState} to {e.NewState}." );
};
Back to top