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 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, or OTHER.
$Environment The environment in which the client is running. For possible values see the user manual. The browser name and version are determined by the UA-Parser library.
$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 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.

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: 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());
    });
    throws

    an IllegalArgumentError if dataType is not a valid data type

    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());
    });
    throws

    an IllegalArgumentError if dataType is not a valid data type or if the selector could not be parsed

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

    an IllegalArgumentError if the selector could not be parsed

    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/.*');
    throws

    an IllegalArgumentError if the selector could not be parsed

    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