Interface Session

All Superinterfaces:
AutoCloseable

public interface Session extends AutoCloseable
A client session to a server (or cluster of servers).

A new session can be created by connecting to a server using SessionFactory.open(String), specifying the server URL. There is also a non-blocking variant SessionFactory.openAsync(String). 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 Topics and Messaging, exposed to the application through the feature(Class) method.

Session lifecycle

Each session is managed by a server. The server assigns the session a unique identity, 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 it's authentication has expired. It can also be terminated by other privileged sessions using the ClientControl feature.

A client can become disconnected from the server, and reconnect to the server without loss of the session. Reconnection can be configured using the session factory. 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 getState(). A listener can be registered with addListener(Listener) 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 getSessionProperties().

A privileged client can monitor other sessions, including changes to their session properties, using a session event listener. 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:

Key Description
$ClientIP The Internet address of the client in string format.
$ClientType The client type of the session. One of ANDROID, C, DOTNET, IOS, JAVA, JAVASCRIPT_BROWSER, MQTT, PYTHON, REST, or OTHER.
$Connector The configuration name of the server connector that the client connected to.
$Country The country code for the country where the client's Internet address was allocated (for example, NZ for New Zealand). Country codes are as defined by Locale. If the country code could not be determined, this will be a zero length string.
$Environment The environment in which the client is running. For possible values see the user manual
$ExpiryTime 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 client type. Only set for gateway client sessions. If present it indicates the type of gateway client (e.g. Kafka).
$GatewayId The identity of a gateway client session. Only present if the $GatewayType session property is present.
$Language The language code for the official language of the country where the client's Internet address was allocated (for example, en for English). Language codes are as defined by Locale. If the language could not be determined or is not applicable, this will be a zero length string.
$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 The client's longitude, if available. This will be the string representation of a floating point number and will be NaN if not available.
$MQQTClientId The MQTT client identifier. Only set for MQTT sessions. If present, the value of the $ClientType session property will be MQTT.
$Principal The security principal associated with the client session.
$Roles Authorisation roles assigned to the session. This is a set of roles represented as quoted strings (for example, "role1","role2"). The utility method Diffusion.stringToRoles(String) can be used to parse the string value into a set of roles.
$ServerName The name of the server to which the session is connected.
$SessionId The session identifier. Equivalent to SessionId.toString().
$StartTime The session's start time in milliseconds since the epoch.
$Transport The session transport type. One of WEBSOCKET, HTTP_LONG_POLL, TCP, or OTHER.

All user-defined property keys are non-empty strings. 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, it can optionally propose user-defined session properties (see SessionFactory.property(String, String) and SessionFactory.properties(Map)). Session properties proposed in this way must be accepted by the authenticator. This safeguard prevents abuse by a rogue, unprivileged client.
  2. Diffusion 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.

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

If a session re-authenticates (see reauthenticate), 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 Session.SessionLock.

Since:
5.0
Author:
DiffusionData Limited
  • Field Details

    • ANONYMOUS

      static final String ANONYMOUS
      Value returned by getPrincipal() if no principal name is associated with the session.
      See Also:
    • ALL_FIXED_PROPERTIES

      static final String ALL_FIXED_PROPERTIES
      This constant can be used instead of a property key in requests for session property values to indicate that all fixed session properties are required.
      Since:
      5.6
      See Also:
    • ALL_USER_PROPERTIES

      static final String ALL_USER_PROPERTIES
      This constant can be used instead of a property key in requests for session property values to indicate that all user defined session properties are required.
      Since:
      5.6
      See Also:
    • SESSION_ID

      static final String SESSION_ID
      Session property key for session identifier.
      Since:
      6.2
      See Also:
    • PRINCIPAL

      static final String PRINCIPAL
      Session property key for principal.
      Since:
      6.2
      See Also:
    • CONNECTOR

      static final String CONNECTOR
      Session property key for connector name.
      Since:
      6.2
      See Also:
    • TRANSPORT

      static final String TRANSPORT
      Session property key for transport.
      Since:
      6.2
      See Also:
    • CLIENT_TYPE

      static final String CLIENT_TYPE
      Session property key for client type.
      Since:
      6.2
      See Also:
    • COUNTRY

      static final String COUNTRY
      Session property key for country code.
      Since:
      6.2
      See Also:
    • LANGUAGE

      static final String LANGUAGE
      Session property key for language code.
      Since:
      6.2
      See Also:
    • SERVER_NAME

      static final String SERVER_NAME
      Session property key for server name.
      Since:
      6.2
      See Also:
    • CLIENT_IP

      static final String CLIENT_IP
      Session property key for client IP address.
      Since:
      6.2
      See Also:
    • LATITUDE

      static final String LATITUDE
      Session property key for client latitude.
      Since:
      6.2
      See Also:
    • LONGITUDE

      static final String LONGITUDE
      Session property key for client longitude.
      Since:
      6.2
      See Also:
    • START_TIME

      static final String START_TIME
      Session property key for client start time.
      Since:
      6.2
      See Also:
    • EXPIRY_TIME

      static final String EXPIRY_TIME
      Session property key for client session expiry time.
      Since:
      6.12
      See Also:
    • ROLES

      static final String ROLES
      Session property key for session roles.
      Since:
      6.2
      See Also:
    • MQTT_CLIENT_ID

      static final String MQTT_CLIENT_ID
      Session property key for MQTT client identifier.
      Since:
      6.6
      See Also:
    • GATEWAY_TYPE

      static final String GATEWAY_TYPE
      Session property key for gateway client type.
      Since:
      6.6
      See Also:
    • GATEWAY_ID

      static final String GATEWAY_ID
      Session property key for gateway client identifier.
      Since:
      6.6
      See Also:
    • ENVIRONMENT

      static final String ENVIRONMENT
      Session property key for client environment.
      Since:
      6.11
      See Also:
  • Method Details

    • getSessionId

      SessionId getSessionId()
      Returns the unique identifier for the session as assigned by the (first) server it connects to.
      Returns:
      the session identifier
    • getPrincipal

      String getPrincipal()
      Returns the name of the security principal requested when opening the session.
      Returns:
      the principal name. If the session was opened with no associated principal, (it is an "anonymous session"), the empty string ( ANONYMOUS) will be returned
    • getAttributes

      SessionAttributes getAttributes()
      Returns the session attributes.
      Returns:
      session attributes
    • getState

      Session.State getState()
      Returns the current state of the session.
      Returns:
      the current session state
    • close

      void close()
      Close the session.

      Has no effect if the session is already closed

      Specified by:
      close in interface AutoCloseable
    • feature

      <T extends Feature> T feature(Class<T> featureInterface) throws IllegalArgumentException, UnsupportedOperationException
      Obtain a feature.

      This can be used to get any feature. It will automatically instantiate the feature the first time it is called.

      Type Parameters:
      T - feature type
      Parameters:
      featureInterface - the feature interface
      Returns:
      the feature
      Throws:
      IllegalArgumentException - if featureInterface is not an interface
      UnsupportedOperationException - if no implementation of the feature is supported or found
    • addListener

      void addListener(Session.Listener listener)
      Add a session listener.
      Parameters:
      listener - the listener
      Since:
      5.1
    • removeListener

      void removeListener(Session.Listener listener)
      Remove a session listener. All session listeners equal to listener will be removed.
      Parameters:
      listener - the listener
      Since:
      5.1
    • getSessionProperties

      CompletableFuture<Map<String,String>> getSessionProperties()
      Returns the values of the session's fixed session properties.

      All current fixed property values are returned, except the value of the ROLES property. User-defined session properties are not returned.

      Returns:
      a CompletableFuture that completes when a response is received from the server.

      If the CompletableFuture completes normally, a map of the current fixed session properties will be returned (excluding the value of the ROLES property).

      Otherwise, the CompletableFuture will complete exceptionally with a CompletionException. Common reasons for failure, listed by the exception reported as the cause, include:

      Since:
      6.12
    • lock

      Attempt to acquire a session lock.

      This method returns a CompletableFuture that will complete normally if the server assigns the requested lock to the session. Otherwise, the CompletableFuture will complete exceptionally with an exception indicating why the lock could not be acquired.

      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 CompletableFuture.

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

      Canceling the returned CompletableFuture has no effect on other pending calls to lock(...} made by the session.

      If the CompletableFuture completes normally, the session owns the lock and is responsible for unlocking it. When canceling a CompletableFuture, take care that it has not already completed by checking the return value. The following code releases the lock if the request could not be canceled.

       CompletableFuture result = session.lock("my-lock");
      
       // ..
      
       if (!result.cancel(true)) {
           // The session acquired the lock. Release it.
           SessionLock lock = result.get();
           lock.unlock();
       }
       

      A session that acquires a lock will remain its owner until it is unlocked or the session closes. The lock(String, SessionLockScope) variant of this method takes a scope parameter 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 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.

      Parameters:
      lockName - the name of the session lock
      Returns:
      a CompletableFuture that completes when a response is received from the server.

      If this session has successfully acquired the session lock, or this session already owns the session lock, the CompletableFuture will complete normally with a SessionLock result.

      If the CompletableFuture completes exceptionally, this session does not own the session lock. Common reasons for failure, indicated by the exception reported as the cause, include:

      Since:
      6.1
      See Also:
    • lock

      Variant of lock(String) that provides control over when a lock will be released.

      If called with UNLOCK_ON_SESSION_LOSS, this method behaves exactly like lock(String).

      If called with 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.

      Parameters:
      lockName - the name of the session lock
      scope - preferred scope. The scope of a lock controls when it will be released automatically. 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).
      Returns:
      a CompletableFuture that completes when a response is received from the server. See lock(String).