Options
All
  • Public
  • Public/Protected
  • All
Menu

Interface Session

A client session to a server or cluster of servers.

A new session can be created by connecting to a server using diffusion.connect, specifying the server URL. The session factory can be configured to control the behavior the session.

The session provides a variety of operations to the application. These are grouped into feature interfaces, such as Topics and Messages, exposed to the application through properties on the Session object.

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 or a time out, or 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 options. 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 isClosed and isConnected. Listeners can be registered with on 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 (see section Session Filters) that use session properties to select sessions.

A privileged client can monitor other sessions, including changes to their session properties, using a session properties 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, 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). If the country code could not be determined, this will be a zero length string.
$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). 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.
$MQTTClientId 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 stringToRoles 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 Session.sessionID.
$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 and are case-sensitve. 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 Options.properties). 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 ClientControl.setSessionProperties. A privileged client can also modify its own session properties.

If a session re-authenticates (see changePrincipal), 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 query expressions for session properties. They can be used to address a set of sessions based on their session properties. For example, it is possible to send a message to all sessions that satisfy a specified filter. Session filters are parsed and evaluated at the server.

A session filter expression consists of either a single clause, or multiple clauses connected by the binary operators and and or. The and operator takes precedence over or but parentheses can be used to override the precedence. For example:

  • Department is "Accounts"
  • hasRoles ["operator" "trading desk"]
  • Department is "Payroll" and Status is "Closed"}
  • (Department is "Accounts" or Department is "Payroll") and Status is "Closed"}

The boolean not operator may be used to negate the following clause or an expression within parentheses:

  • not Department is "Payroll"
  • not (Department is "Payroll" or Department is "Accounts")

An equality clause has the form key operator value where key is the name of a session property and value is the property value. The supported operators are is or eq, both of which mean "equals", and ne which means "does not equal". Values are strings enclosed within single or double quotes. Special characters (", ' or \) can be included within the value by preceding with the escape character \. The utility method escape can be used to insert escape characters into a value.

The all operator matches all sessions.

The has operator checks if a property is present. This is useful for determining whether a user-defined property or an optional fixed property has been set for a session.

hasRoles is a special operator for querying the $Roles session property. A hasRoles clause has the form hasRoles ["role1" "role2" ... "roleN"]. The clause will match sessions that have all the specified authorisation roles. Each role is a string enclosed within either single or double quotes. Roles can be space or comma separated.

The in operator allows for the querying of a specific session property to see if it exists in a defined set. An example of this would to be filter all sessions from a set of countries, say Germany, France, and the UK. The query would be $Country in 'UK','DE','FR'.

The lists provided to in and hasRoles can optionally use square brackets and commas as delimiters. For example $Country in ['UK','DE','FR'].

The $Roles session property can also be queried with an equality clause, for example, $Roles eq '"admin","client"', but the hasRoles clause is usually more convenient. An equality clause will match sessions that have exactly the listed roles. In contrast, a hasRoles clause will match any sessions with the listed roles, regardless of whether they have other roles. The equality clause requires the value to be in the canonical form produced by the rolesToString utility method. Supported operators are as follows:

Operator Description
is or eq equals
ne not equals

All operators are case insensitive.

The following are examples of valid expressions:

  • $Principal is "Alice"
  • Department is "Accounts" and $Country ne "US"
  • $Language EQ "en" and $Country NE "US"
  • not (Department is "Accounts" or
  • "Department is "Payroll") and $Country is "FR"
  • Text is "xyz\"\\"
  • hasRoles ["operator"]}
  • hasRoles "operator"}
  • $Transport is "wss" and hasRoles ["accountancy" "administrator"]
  • hasRoles ["operator"] and not hasRoles ["administrator"]
  • $Version in {"6","7","8"}
  • $Country in ['UK','DE','FR']
  • has Department
  • all

Example:

// Establish a session
diffusion.connect('diffusion.example.com').then(function(session) {
    // Attach state listeners
    session.on({
        disconnect : function() {
            console.log('Disconnected!');
        },
        reconnect : function() {
            console.log('Phew, reconnected!');
        },
        error : function(error) {
             console.log('Session error', error);
        },
        close : function(reason) {
            console.log('Session closed', reason);
        }
    });

    // Do something with session...
});

Events

disconnect

Emitted when a connected session has lost connection to the server, and Options reconnect is enabled. The provided reason will contain the specific cause of the session disconnect.

Parameters:

reason: CloseReason - the cause of the session disconnect

reconnect

Emitted when a disconnected session has successfully reconnected.

close

Emitted when a session is closed. This can occur because it was closed by the user, closed by the server, failed to connect, or the session encountered an error. The provided close reason will contain the specific cause of the session close.

Parameters:

reason: CloseReason - the cause of the session close

error

Emitted when a session error has occurred. A session error occurs when the client cannot parse communication from the server. This occurs if a component between the two - for example, a proxy or load balancer - alters the communication.

Parameters:

error: any - the error that occurred

Hierarchy

Index

Properties

clients

clients: ClientControl

Exposes client control capabilities via ClientControl

messages

messages: Messages

Exposes messaging capabilities via Session.messages

metrics

metrics: Metrics

Exposes metric collector management capabilities via Metrics

notifications

notifications: TopicNotifications

Exposes topic notification capabilities via Session.notifications

options

options: Options

The connection options used to establish this session

remoteServers

remoteServers: RemoteServers

Exposes remote servers capabilities via Session.remoteServers

security

security: Security

Exposes system authentication capabilities via a Session.security

sessionID

sessionID: string

The unique id assigned to this session by the server.

deprecated

since 6.5 replaced by sessionId

sessionId

sessionId: SessionId

The unique id assigned to this session by the server.

sessionTrees

sessionTrees: SessionTrees

Exposes session trees capabilities via Session.sessionTrees

timeseries

timeseries: TimeSeries

Exposes time series capabilities via Session.timeseries

topicUpdate

topicUpdate: TopicUpdate

Exposes topic update capabilities via Session.topicUpdate

topicViews

topicViews: TopicViews

Exposes topic views capabilities via Session.topicViews

topics

topics: TopicControl

Exposes topic control capabilities via Session.topics

Methods

addFallbackStream

  • This adds a value stream for a given Data Type without a selector which will be a fallback stream to receive all events that do not have a stream registered.

    Example:

    // Produce a fallback value stream for receiving JSON values.
    var json = diffusion.datatypes.json();
    
    session.addFallbackStream(json).on('value', function(topic, specification, newValue, oldValue) {
          console.log('New value ', newValue.get());
    });

    Parameters

    Returns ValueStream

    a fallback stream

addStream

  • Create a ValueStream to receive updates from topics that match the provided topic selector.

    This method will not cause the server to send any topic updates unless already subscribed. This allows the registration of listeners prior to subscribing via Session.select, or to add/remove listeners independently of subscriptions on the server.

    The values as specific types, use the Streams will only receive values from topics for which the specified Data Type is compatible. Passing AnyDataType as second argument will create a polymorphic value stream that receives all data types. It is then up to the value handler to interpret the incoming data.

    The first argument of this function can be a string, a TopicSelector, or a non-empty array of strings and TopicSelectors.

    Example:

    // Produce a value stream for receiving JSON values.
    var json = diffusion.datatypes.json();
    
    session.addStream(topic, json).on('value', function(topic, specification, newValue, oldValue) {
          console.log('New value ', newValue.get());
    });

    Parameters

    Returns ValueStream

    a new ValueStream for the provided data type

close

  • Close this session's connection to the server.

    Calling this repeatedly will have no effect.

    Returns Session

    this session

closeSession

  • Close this session's connection to the server and return a Result that will completes when the session is closed.

    Returns Result<CloseReason>

    a Result that completes with the close reason returned by the server. Only the Result of the first call to closeSession is guaranteed to complete. The Result will not resolve if the session is already closed.

fetchRequest

  • Creates an unconfigured fetch request.

    The returned request can be invoked with fetch. The server will evaluate the query and return a fetch result that provides the paths and types of the matching topics which the session has permission to read.

    You will usually want to restrict the query to a subset of the topic tree, and to retrieve the topic values and/or properties. This is achieved by applying one or more of the fluent builder methods provided by FetchRequest to produce more refined requests.

    Example:

    // Create and send a fetch request. Then pass the results to a resultHandler
    session.fetchRequest()
           .withValues(diffusion.datatypes.StringDataType)
           .fetch("*A/B//")
           .then(resultHandler);
    see

    diffusion.topics.FetchRequest

    since

    6.2

    Returns FetchRequest

    a new unconfigured fetch request

getPrincipal

  • getPrincipal(): string
  • Returns the principal name that this session is associated with.

    Returns string

    the principal for this session

isClosed

  • isClosed(): boolean
  • Indicates if this session is currently closed, or in the process of closing.

    This will not return true if the session is disconnected but attempting to reconnect.

    Returns boolean

    whether the session is currently closed.

isConnected

  • isConnected(): boolean
  • Indicates if this session is currently connected.

    This is orthogonal to Session.isClosed, as a session may be disconnected and attempting to reconnect.

    Returns boolean

    whether the session is currently connected or not.

lock

  • Attempt to acquire a session lock.

    This method returns a Promise that will resolve normally if the server assigns the requested lock to the session. Otherwise, the Promise will fail with an error indicating why the lock could not be acquired.

    since

    6.2

    Parameters

    • lockName: string

      the name of the session lock

    • Optional scope: SessionLockScope

      preferred scope, defaults to UNLOCK_ON_SESSION_LOSS . 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_SESSION_LOSS ).

    Returns Result<SessionLock>

    a Promise that resolves 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 Promise will resolve normally with a SessionLock result.

    If the Promise resolves with an error, this session does not own the session lock.

off

  • Remove a listener from a specified event.

    Example:

    // Bind a single listener to the 'foo' event and then deregister it
    var listener = function() {};
    stream.on('foo', listener);
    stream.off('foo', listener);

    Example:

    // Bind a listener to the 'foo' event and deregister all listeners
    var listener = function() {};
    stream.on('foo', listener);
    stream.off('foo');

    Parameters

    • events: string | CallbackMap
    • Optional listener: StreamCallback

      the listener to remove. All listeners for the event are removed if this is not specified. This argument is ignored if the first argument is a CallbackMap.

    Returns Stream

    this stream.

on

  • Register listeners against events.

    A single listener may be bound to an event by passing the event name and listener function.

    Multiple listeners may be bound by passing in a CallbackMap, mapping event names to listener functions.

    Example:

    // Bind a single listener to the 'foo' event
    stream.on('foo', function(arg1, arg2) {
        console.log("Called for 'foo' event", arg1, arg2);
    });

    Example:

    // Bind multiple listeners
    stream.on({
        foo : function() { ... },
        bar : function() { ... },
        baz : function() { ... }
    });

    Parameters

    • events: string | CallbackMap

      the event name or CallbackMap mapping event names to listeners

    • Optional listener: StreamCallback

      the listener to bind to the event, if passed as string. This argument is ignored if the first argument is a CallbackMap.

    Returns Stream

    this stream.

pingServer

  • Send a ping request to the server.

    Example:

    session.pingServer().then(function(pingDetails) {
        console.log("Round-trip call to server took: " + pingDetails.rtt + " milliseconds");
    });

    Returns Result<PingDetails>

    a result that completes when a response is received from the server.

select

  • Subscribe the session to a topic selector in order to receive updates and subscription events.

    Subscription causes the server to establish a subscription for this session to any topic that matches the specified selector, including topics that are added after the initial call to Session.select.

    If the provided selector string does not begin with one of the prefixes defined by TopicSelectors, it will be treated as a direct topic path.

    This function can take any number of arguments. Each argument can be a string or a TopicSelector. Alternatively, an array of strings and TopicSelectors can be passed as a single argument. At least one valid selector has to be specified.

    The session will become subscribed to each existing topic matching the selector unless the session is already subscribed to the topic, or the session does not have READ_TOPIC permission for the topic path. For each topic to which the session becomes subscribed, a subscription notification and initial value (if any) will be delivered to registered value streams before the returned promise completes.

    The subscription request is also retained at the server and the session will be automatically subscribed to newly created topics that match the selector (unless a subsequent unsubscription cancels the request).

    Example:

    // Subscribe to a topic foo
    session.select("foo").then(function() {
        // Successfully subscribed
    }, function(err) {
        // There was an error with subscribing to topic "foo"
    });

    Parameters

    • selector: Array<string | TopicSelector>

      the topic selector to subscribe to.

    Returns Result<void>

    a result that completes when this operation succeeds

  • Parameters

    Returns Result<void>

unsubscribe

  • Unsubscribe the client from a given topic selector.

    No more updates will be received from the server for any topics matched by the selector. If no topics exist that match the selector, the server will do nothing.

    Each topic that this session is unsubscribed from will cause an unsubscribe event. Any ValueStream objects produced from Session.addStream will remain open, and will continue to emit updates for topics that the session has not been unsubscribed from.

    The returned result will resolve normally when the session has been unsubscribed. It will resolve with an error if the session is unable to unsubscribe, for instance due to security constraints.

    This function can take any number of arguments. Each argument can be a string or a TopicSelector. Alternatively, an array of strings and TopicSelectors can be passed as a single argument. At least one valid selector has to be specified.

    Example:

    // Unsubscribe from a single topic
    session.unsubscribe('foo');

    Example:

    // Unsubscribe from multiple topics
    session.unsubscribe('?foo/.*');

    Parameters

    • selector: Array<string | TopicSelector>

      the topic selector to unsubscribe from.

    Returns Result<void>

    a Result for this operation

  • Parameters

    Returns Result<void>

updateFeatures

  • updateFeatures(): void
  • Updates the session with missing features that may have been loaded asynchronously. This method only has an effect when running the client as a modular client in the browser.

    Returns void