Class: Session


new Session()

Diffusion Session. Handles a connection to Diffusion and exposes API features. Sessions can subscribe, add, remove and update topics, as well as perform remote operations on the server.

A session represents a single connection to a single Diffusion server. A session begins connected and will remain so until until it is explicitly closed via Session#close or there is a connection error.

When a connected session loses its connection to the server, it will close if Session.Options reconnect is not enabled. If reconnect is enabled then the session will enter a disconnected state. Once disconnected, any API methods that involve the server will automatically fail. It is possible for a session to lose messages while disconnected.

The session will attempt to reconnect to the server on a regular basis. This will continue until the server responds; at which point the session will attempt to recover its previous connection.

If the reconnection is succesful the session will become connected again and emit a reconnect event. Any prior subscriptions will continue to receive data.

If the server rejects the reconnection, the session will be closed.

Sessions emit events to notify listeners of changes in state. Certain events will provide arguments to any callback functions that have been registered.

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. See ClientLocation.address.
$ClientType The client type of the session. One of ANDROID, C, DOTNET, IOS, JAVA, JAVASCRIPT_BROWSER, or OTHER. Equivalent to ClientSummary.clientType.
$Connector The configuration name of the server connector that the client connected to. See SessionDetails.connector.
$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. See
$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. See ClientLocation.details.language.
$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. See ClientLocation.coordinates.latitude.
$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. See ClientLocation.coordinates.longitude.
$Principal The security principal associated with the client session. Equivalent to ClientSummary.principal
$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 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. See SessionDetails.server.
$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, or OTHER. Equivalent to ClientSummary.transportType.

All user-defined property keys must be alphanumeric, starting with an alphabetic character, and are case sensitive. Embedded whitespace is 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 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 diffusion#escape can be used to insert escape characters into a value.

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 $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 diffusion#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"]}
  • $Transport is "wss" and hasRoles ["accountancy" "administrator"]
  • hasRoles ["operator"] and not hasRoles ["administrator"]
Name Type Description

Exposes system authentication capabilities via a

topics Session.topics

Exposes topic control capabilities via Session.topics.

topicUpdate Session.topicUpdate

Exposes topic update capabilities via Session.topicUpdate.

messages Session.messages

Exposes messaging capabilities via Session.messages.

notifications Session.notifications

Exposes topic notification capabilities via Session.notifications.

clients Session.clients

Exposes client control capabilities via Session.clients.

options Session.Options

The options used when connecting.

sessionID String

The unique id assigned to this session by the server.

// Establish a session
diffusion.connect('').then(function(session) {
    // Attach state listeners
        disconnect : function() {
        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...





addFallbackStream(datatype) → {FallbackStream}

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.

Name Type Description
datatype DataType

The data type to produce a stream for.

  • a fallback stream
// 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());

addStream(selector, datatype) → {ValueStream}

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.topics#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.

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

Name Type Description
selector String | TopicSelector | Array.<String>
  • The topic selector to receive updates for
datatype DataType

The data type to produce a stream for.


A new ValueStream for the provided data type

// 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());

close() → {Session}

Close this session's connection to the server.

Calling this repeatedly will have no effect.


This session


fetch(selector) → {FetchStream}

Fetch the current state of one or more topics.

Fetching a topic will provide its current value without subscribing this client to that topic. The returned FetchStream will emit value events for each topic that is matched for which a fetch request can be satisfied. Once complete, the FetchStream will be closed.

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.

Name Type Description
selector String | TopicSelector | Array.<String>

The topic selector to fetch

  • since 6.2

    Prefer the use of #fetchRequest() instead. Unlike this method fetchRequest supports additional query constraints, returns type-safe values, and optionally allows topic properties to be retrieved. This will be removed in a future release.


A FetchStream that will emit the fetched values.

// Fetch a topic's value
session.fetch("foo").on('value', function(value, path) {
    console.log("Value for topic '" + path + "' is: " + value);
// Fetch multiple topics, handling possible errors
    value : function(value, path) { ... },
    error : function(error) { ... },
    close : function() { ... }

fetchRequest() → {diffusion.topics.FetchRequest}

Creates an unconfigured fetch request.

If the request is invoked by calling fetch, the fetch result will provide the paths and types of all of the topics which the session has permission to read.

Usually the query should be restricted to a subset of the topic tree, and should retrieve the topic values and/or properties. This is achieved by applying one or more of the fluent builder methods to produce more refined requests.

  • 6.2

a new unconfigured fetch request

// Create and send a fetch request. Then pass the results to a resultHandler

getPrincipal() → {String}

Returns the principal name that this session is associated with.


The principal for this session


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.


Whether the session is currently closed.


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.


Whether the session is currently connected or not.


lock(lockName, scope)

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.

Name Type Description
lockName String

the name of the session lock

scope diffusion.locks.SessionLockScope

(optional) 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).

  • 6.2

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(event, listener) → {Stream}

Remove a listener from a specified event.

Name Type Argument Description
event String

The event to remove listeners from

listener function <optional>

The listener to remove. All listeners for the event are removed if this is not specified

Inherited From:

This stream.

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

on(events, listener) → {Stream}

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 an object, mapping event names to listener functions.

Name Type Argument Description
events String | Object

The event name or object mapping event names to listeners

listener function <optional>

The listener to bind to the event, if passed as string.

Inherited From:

This stream.

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

pingServer() → {Result.<Session.PingDetails>}

Send a ping request to the server.

The main purpose of a ping is to test, at a very basic level, the current network conditions that exist between the client session and the server it is connected to. The ping response includes the time taken to make a round-trip call to the server.

There are no permission requirements associated with this feature.


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

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

select(selector) → {Result}

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.

Name Type Description
selector String | TopicSelector | Array.<String>

The topic selector to subscribe to.


for this operation

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

unsubscribe(selector) → {Result.<undefined>}

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 Subscription objects produced from Session#subscribe or Session#stream will remain open, and will continue to emit updates for topics that the session has not been unsubscribed from.

The returned result will complete normally if the session has been unsubscribed. It will fail 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.

Name Type Description
selector String | TopicSelector | Array.<String>

The topic selector to unsubscribe from.


A Result.<undefined> for this operation

// Unsubscribe from a single topic
// Unsubscribe from multiple topics

Type Definitions


Provide Session configuration options.

There are several option values that can be configured to change how Diffusion establishes a connection. These options are used to derive a connection URL in the format: {protocol}://{host}:{port}/{path}. The protocol used is determined by the chosen transports and whether secure connections are enabled.

Option Default value Description
host localhost The hostname to connect to.
port 80 or 443 The port to connect to. The default value depends on whether secure connections are enabled, or if the client is being run in a page served via http or https.
path /diffusion The URL path to apply after the hostname/port. This allows additional context to be provided, such as might be used by load balancers.
secure true Determines if secure transports will be used. If no port option is specified, this will also determine the port to use.

Reconnection is enabled by default, and accepts several different option values.

Option type Default value Description
boolean true Enables or disables reconnection. If set to true, reconnection will be enabled using the default timeout value and a periodic back-off strategy.
number 60000 Passing a number will enable reconnection with the default strategy and the reconnection timeout set to the specified value. The reconnection timeout determines how long, in milliseconds, the client will remain in a disconnected state before the client is closed.
function function(reconnect, abort) {
setTimeout(reconnect, 5000);
A strategy function that will be called when the client enters a disconnected state, and subsequently if attempts to reconnect fail. Two arguments are provided, reconnect and abort

  • these are functions to be called within the strategy. The reconnect argument will initiate a reconnect attempt. abort may be called to abort reconnection, in which case the client will be closed.
timeout : <number>,
strategy : <function>
timeout : 60000,
strategy : function(reconnect, abort) {
  setTimeout(reconnect, 5000);</br>
An object containing both the timeout and strategy options as specified above, allowing both to be set together.

The transports property configures how the session should connect. It can be set to either a string, or an array of strings to provide a transport cascading capability.
Transport key Description
ws, WS, WEBSOCKET The WebSocket transport. A single, long-lived WebSocket connection will be used to send and receive data.
xhr, XHR, HTTP_POLLING An XHR-based polling transport. Data will be queued on the client and server, and sent in batches.
The client will use the transports in the order provided, for example: transports: ['WS', 'XHR'] indicates that the client will attempt to connect with the WebSocket transport, and if the connection fails, the client will attempt to connect with the HTTP Polling transport. When no transports value is provided the client will default to using the WebSocket transport. Any string values that do not have an associated transport will be ignored.


Supplied session properties will be provided to the server when a session is created using this session factory. The supplied properties will be validated during authentication and may be discarded or changed.

The specified properties will be added to any existing properties set for this session factory. If any of the keys have been previously declared then they will be overwritten with the new values.

For details of how session properties are used see Session.

  • object
Name Type Argument Default Description
host String <optional>

The hostname to connect to

port Number | String <optional>

The port to connect to.

path String <optional>

The request path used for connections

secure Boolean <optional>

Whether to use secure connections

principal String <optional>

The principal name this session should connect with. Used for authentication.

credentials String | Buffer | TypedArray | Array <optional>

A password string to authenticate with, a buffer containing custom credentials in binary format, a typed array i.e. Uint8Array or a regular array of octets.

reconnect Boolean | Number | function | Object <optional>

Reconnection options.

transports String | Array <optional>

The transports to be used for connection establishment.

maxMessageSize Number <optional>

The maximum size of messages that may be received from the server.

properties Object

An object of key-value pairs that define the user-defined session properties


  • Object
Name Type Description
timestamp Number

The timestamp when the ping was sent, represented as milliseconds since epoch

rtt Number

The round-trip time in milliseconds from when the ping was sent to the time the response was received



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.

Name Type Description
reason diffusion.clients.CloseReason

the cause of the session close.


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

Name Type Description
reason diffusion.clients.CloseReason

the cause of the session disconnect.


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.

Name Type Description
error Error

the error that occured.


Emitted when a disconnected session has successfully reconnected.