Table of Contents

Interface ISession

Namespace
PushTechnology.ClientInterface.Client.Session
Assembly
Diffusion.Client.dll

The client session to a server (or cluster of servers).

public interface ISession

Examples

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

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

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 behaviour 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, a time out, or because its authentication has expired. It can also be terminated 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 Diffusion. User-defined properties are proposed by the application, but may be changed during authentication.

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

A session may obtain its own fixed session properties using GetSessionPropertiesAsync().

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.
$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.
$Environment (ENVIRONMENT) The environment in which the client is running. For possible values see the user manual.
$ExpiryTime (EXPIRY_TIME) The time at which the session is due to expire, specified in milliseconds since the epoch. This may be set by authenticators. If not present, the session will not expire.
$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 or re-authenticates ISecurity.ReauthenticateAsync(string, DiffusionCore.Client.Types.ICredentials, System.Collections.Generic.IDictionary<string, string>), 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, such as the expiry time ISession.EXPIRY_TIME.

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 user-defined session properties.

If a session re-authenticates (see ReauthenticateAsync(string, ICredentials, IReadOnlyDictionary<string, string>)), 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.

Properties

Attributes

Gets attributes of this session.

ISessionAttributes Attributes { get; }

Property Value

ISessionAttributes

The attributes of this session.

Examples

Retrieving the session attributes.

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

Remarks

Added in 5.0.

AuthenticationControl

Gets the authentication-control feature.

IAuthenticationControl AuthenticationControl { get; }

Property Value

IAuthenticationControl

The authentication-control feature.

Examples

Retrieving the authentication-control feature.

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

Remarks

Added in 5.0.

ClientControl

Gets the client-control feature.

IClientControl ClientControl { get; }

Property Value

IClientControl

The client-control feature.

Examples

Retrieving the client-control feature.

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

Remarks

Added in 5.0.

Messaging

Gets the messaging feature.

IMessaging Messaging { get; }

Property Value

IMessaging

The messaging feature.

Examples

Retrieving the messaging feature.

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

Remarks

Added in 5.0.

Metrics

Gets the metrics feature.

IMetrics Metrics { get; }

Property Value

IMetrics

The metrics feature.

Examples

Retrieving the metrics feature.

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

Remarks

The Metrics feature allows a client to configure metric collectors.

Added in 6.7.

Ping

Gets the pings feature.

IPings Ping { get; }

Property Value

IPings

The pings feature.

Examples

Retrieving the pings feature.

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

Remarks

Added in 5.0.

Principal

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

string Principal { get; }

Property Value

string

The principal name.

Examples

Retrieving the session principal.

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

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.

RemoteServers

Gets the remote servers feature.

IRemoteServers RemoteServers { get; }

Property Value

IRemoteServers

The remote servers feature.

Examples

Retrieving the remote servers feature.

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

Remarks

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

Added in 6.5.

Security

Gets the security feature.

ISecurity Security { get; }

Property Value

ISecurity

The security feature.

Examples

Retrieving the security feature.

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

Remarks

Added in 5.0.

SecurityControl

Gets the security-control feature.

ISecurityControl SecurityControl { get; }

Property Value

ISecurityControl

The security-control feature.

Examples

Retrieving the security-control feature.

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

Remarks

Added in 5.3.

SessionId

Gets the unique identifier of this session.

ISessionId SessionId { get; }

Property Value

ISessionId

The session identifier.

Examples

Retrieving the session identifier.

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

Remarks

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


Added in 5.0.

SessionTrees

Gets the session trees feature.

ISessionTrees SessionTrees { get; }

Property Value

ISessionTrees

The session trees feature.

Examples

Retrieving the session trees feature.

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

Remarks

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

Added in 6.7.

State

Gets the current state of this session.

SessionState State { get; }

Property Value

SessionState

The current state of this session.

Examples

Retrieving the session state.

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

Remarks

Added in 5.0.

SubscriptionControl

Gets the subscription-control feature.

ISubscriptionControl SubscriptionControl { get; }

Property Value

ISubscriptionControl

The subscription-control feature.

Examples

Retrieving the subscription-control feature.

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

Remarks

Added in 5.0.

SystemAuthenticationControl

Gets the system-authentication-control feature.

ISystemAuthenticationControl SystemAuthenticationControl { get; }

Property Value

ISystemAuthenticationControl

The system-authentication-control feature.

Examples

Retrieving the system-authentication-control feature.

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

Remarks

Added in 5.2.

TimeSeries

Gets the time-series feature.

ITimeSeries TimeSeries { get; }

Property Value

ITimeSeries

The time-series feature.

Examples

Retrieving the time-series feature.

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

Remarks

Added in 6.1.

TopicControl

Gets the topic-control feature.

ITopicControl TopicControl { get; }

Property Value

ITopicControl

The topic-control feature.

Examples

Retrieving the topic-control feature.

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

Remarks

Added in 5.0.

TopicNotifications

Gets the topic-notifications feature.

ITopicNotifications TopicNotifications { get; }

Property Value

ITopicNotifications

The topic-notifications feature.

Examples

Retrieving the topic-notifications feature.

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

Remarks

Added in 6.1.

TopicUpdate

Gets the topic-update feature.

ITopicUpdate TopicUpdate { get; }

Property Value

ITopicUpdate

The topic-update feature.

Examples

Retrieving the topic-update feature.

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

Remarks

Added in 6.2.

TopicViews

Gets the topic-views feature.

ITopicViews TopicViews { get; }

Property Value

ITopicViews

The topic-views feature.

Examples

Retrieving the topic-views feature.

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

Remarks

Added in 6.3.

Topics

Gets the topics feature.

ITopics Topics { get; }

Property Value

ITopics

The topics feature.

Examples

Retrieving the topics feature.

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

Remarks

Added in 5.0.

Methods

Close()

Closes the session.

void Close()

Examples

Closing an active session.

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

Remarks

Has no effect if the session is already closed.


Added in 5.0.

GetSessionPropertiesAsync()

Returns the values of the session's fixed session properties.

Task<IReadOnlyDictionary<string, string>> GetSessionPropertiesAsync()

Returns

Task<IReadOnlyDictionary<string, string>>

A Task that completes when a response is received from the server by returning a dictionary of the current fixed session properties (excluding the value of the ROLES property).

Remarks

All current fixed property values are returned, except the value of the ROLES property.

This method is the same as calling GetSessionPropertiesAsync(CancellationToken) with System.Threading.CancellationToken.None.

Since 6.12.

Exceptions

SessionClosedException

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

GetSessionPropertiesAsync(CancellationToken)

Returns the values of the session's fixed session properties.

Task<IReadOnlyDictionary<string, string>> GetSessionPropertiesAsync(CancellationToken cancellationToken)

Parameters

cancellationToken CancellationToken

The cancellation token used to cancel the current operation.

Returns

Task<IReadOnlyDictionary<string, string>>

A Task that completes when a response is received from the server by returning a dictionary of the current fixed session properties (excluding the value of the ROLES property).

Remarks

All current fixed property values are returned, except the value of the ROLES property.

Since 6.12

Exceptions

SessionClosedException

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

LockAsync(string)

Attempts to acquire a ISessionLock.

Task<ISessionLock> LockAsync(string lockName)

Parameters

lockName string

The name of the session lock.

Returns

Task<ISessionLock>

The Task representing the current operation.

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." );
}

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.

Exceptions

ArgumentNullException

The lockName is null.

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)

Attempts to acquire a ISessionLock with a given scope.

Task<ISessionLock> LockAsync(string lockName, SessionLockScope scope)

Parameters

lockName string

The name of the session lock.

scope SessionLockScope

The scope of the session lock.

Returns

Task<ISessionLock>

The Task representing the current operation.

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." );
}

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.

Exceptions

ArgumentNullException

The lockName is null.

ArgumentException

The scope is invalid.

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)

Attempts to acquire a ISessionLock with a given scope.

Task<ISessionLock> LockAsync(string lockName, SessionLockScope scope, CancellationToken cancellationToken)

Parameters

lockName string

The name of the session lock.

scope SessionLockScope

The scope of the session lock.

cancellationToken CancellationToken

The cancellation token used to cancel the current operation.

Returns

Task<ISessionLock>

The Task representing the current operation.

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." );
}

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.

Exceptions

ArgumentNullException

The lockName is null.

ArgumentException

The scope is invalid.

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)

Attempts to acquire a ISessionLock.

Task<ISessionLock> LockAsync(string lockName, CancellationToken cancellationToken)

Parameters

lockName string

The name of the session lock.

cancellationToken CancellationToken

The cancellation token used to cancel the current operation.

Returns

Task<ISessionLock>

The Task representing the current operation.

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." );
}

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.

Exceptions

ArgumentNullException

The lockName is null.

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

Events

ErrorNotified

The event for session errors.

event EventHandler<SessionErrorHandlerEventArgs> ErrorNotified

Event Type

EventHandler<SessionErrorHandlerEventArgs>

The event for session errors.

Examples

Subscribe to the event.

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

Remarks

Added in 5.0.

StateChanged

The event for session state changes.

event EventHandler<SessionListenerEventArgs> StateChanged

Event Type

EventHandler<SessionListenerEventArgs>

The event for session state changes.

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}." );
};

Remarks

Added in 5.0.