Class: Session

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.

Properties:
Name Type Description
security Session.security Exposes system authentication capabilities via a Session.security.
topics Session.topics Exposes topic control capabilities via Session.topics.
messages Session.messages Exposes messaging capabilities via Session.messages.
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.
Fires:
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...
});

Extends

Namespaces

clients
messages
security
topics

Methods

close() → {Session}

Close this session's connection to the server.

Calling this repeatedly will have no effect.

Returns:
This session
Type
Session

fetch(selector) → {FetchStream}

Fetch the current state of one or more topics.

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

Parameters:
Name Type Description
selector String | TopicSelector The topic selector to fetch
Returns:
A FetchStream that will emit the fetched values.
Type
FetchStream
Examples
// 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
session.fetch("?foo/bar.*").on({
    value : function(value, path) { ... },
    error : function(error) { ... },
    close : function() { ... }
});

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:
Whether the session is currently closed.
Type
boolean

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:
Whether the session is currently connected or not.
Type
boolean

off(event, listener) → {Stream}

Remove a listener from a specified event.
Parameters:
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:
Returns:
This stream.
Type
Stream
Examples
// Bind a single listener to the 'foo' event and then deregister it
var listener = function() {};
stream.on('foo', listener);
stream.off('foo', listener);
// Bind a listener to the 'foo' event and deregister all listeners
var listener = function() {};
stream.on('foo', listener);
stream.off('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.

Parameters:
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:
Returns:
This stream.
Type
Stream
Examples
// 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
stream.on({
    foo : function() { ... },
    bar : function() { ... },
    baz : function() { ... }
});

stream(selector, callback) → {Subscription}

Create a Subscription stream to receive updates from topics that match the provided topic selector.

This method operates in a similar way to Session#subscribe, except it will not cause the server to send any topic updates unless already subscribed. This allows the registration of listeners prior to actually subscribing, or to add/remove listeners independently of subscriptions on the server.

If no selector is provided, the Subscription stream created will receive all topic events that have not been handled by other subscription streams registered to specific selectors. This allows the handling of topic events for topics that this session has been subscribed to by other control sessions.

An optional callback function may be provided, which will be automatically bound to the returned Subscription's update event.

Parameters:
Name Type Argument Description
selector String <optional>
The topic selector to receive updates for
callback function <optional>
An optional callback for update events
Returns:
A representation of the subscription stream
Type
Subscription
Examples
// Establish a listener, but will not receive updates immediately
session.stream('foo', function(update, topic) {
    console.log('Received an update for : ' + topic, update);
});

// Once subscribed, the listener established above will receive topic updates
session.subscribe('foo');
// Maintain a single listener independently of subscriptions/unsubscriptions
session.stream('?foo/.*').on('update', function(update, topic) {
    console.log('Received an update for : ' + topic, update);
});

// The session can subscribe and unsubscribe from specific selectors separately from receiving updates.
session.subscribe('foo/bar');
session.unsubscribe('foo/baz');
// Receive topic events for topics that aren't handled by any other listeners
session.stream().on({
    update : function(value, topic) {
        console.log('Update from: ', topic, value);
    },
    subscribe : function(details, topic) {
        console.log('Subscribed to: ', topic);
    },
    unsubscribe : function(reason, topic) {
        console.log('Unsubscribed from: ', topic);
    }
});

subscribe(selector, callback) → {Subscription}

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

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.

An optional callback function may be provided, which will be automatically bound to the returned Subscription's update event.

A Subscription will emit all topic events that match the provided selector. Documentation of these events is available on the Subscription page.

When calling Session#subscribe, a Subscription object is returned to bind event listeners to. This object may be closed via Subscription#close, which will remove all event listeners and emit no further events. Closing a Subscription object is different to unsubscribing via Session#unsubscribe as it is a purely client-side operation that only affects the single Subscription returned from the initial Session#subscribe call.

Parameters:
Name Type Argument Description
selector String The topic selector to subscribe to.
callback function <optional>
An optional callback for update events
Returns:
A representation of this session's subscription
Type
Subscription
Examples
// Subscribe to a single topic with a callback function for updates
session.subscribe('foo/bar', function(update) {
    console.log('Update : ' + update);
});
// Subscribe to multiple topics and handle subscription events
session.subscribe('?foo/.*').on({
    open : function(subscription) {
        console.log('Opened subscription for: ' + subscription.selector);
    },
    update : function(value, topic) {
        console.log('Update for ' + topic + ' : ' + value);
    },
    subscribe : function(details, topic) {
        console.log('Subscribed to : ' + topic);
    },
    unsubscribe : function(reason, topic) {
        console.log('Unsubscribed from : ' + topic);
    }
});
// Assign subscription and bind multiple listeners
var subscription = session.subscribe('?foo/.*');

subscription.on('update', callback1);
subscription.on('update', callback2);

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.

Each topic that this session is unsubscribed from will cause any associated Subscriptions to emit 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.

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.

Parameters:
Name Type Description
selector String | TopicSelector | Array.<String> The topic selector to unsubscribe from.
Returns:
A Result.<undefined> for this operation
Type
Result.<undefined>
Example
session.unsubscribe('foo');

view(selector, callback) → {View}

Produce a View of multiple topics from a topic selector.

A view is a subscription, but instead of an update being issued for each topic in a selector set, the view presents all participating topics in a single structure when any of them are updated.

If the topic selector matches a topic which is subsequently added or removed, the update is also fired.

Update events will still be emitted by the View.

Parameters:
Name Type Argument Description
selector String The topic selector to subscribe topics for the view.
callback function <optional>
An optional callback that is invoked when the view is updated.
Returns:
A View instance bound to the provided selector
Type
View
Example
// For an existing topic tree containing foo/bar and foo/baz,
// create a view to show updates to foo and below.
var view = session.view('?foo//');

// Log the current value of the topic 'foo'.
console.log(view.foo);

// Log the current value of the topic 'foo/bar'.
console.log(view.foo.bar);

// Log the current value of the topic 'foo/baz'.
console.log(view.foo.baz);

// Convert the value of foo/bar to a String and log it.
view.on('update', function(data) {
  console.log(String(data.foo.bar));
});

Type Definitions

Options

Provide Session configuration options.

Connection:
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:
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);
}
}
An object containing both the timeout and strategy options as specified above, allowing both to be set together.

Transports:
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.

Type:
  • object
Properties:
Name Type Argument Default Description
host String <optional>
localhost The hostname to connect to
port Number | String <optional>
443 The port to connect to.
path String <optional>
/diffusion The request path used for connections
secure Boolean <optional>
true Whether to use secure connections
principal String <optional>
The principal name this session should connect with. Used for authentication.
credentials String | Buffer <optional>
A password string to authenticate with, or a buffer containing custom credentials in binary format.
reconnect Boolean | Number | function | Object <optional>
true Reconnection options.
transports String | Array <optional>
["WEBSOCKET"] The transports to be used for connection establishment.

Events

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.
Properties:
Name Type Description
reason diffusion.clients.CloseReason the cause of the session close.

disconnect

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.
Properties:
Name Type Description
reason diffusion.clients.CloseReason the cause of the session disconnect.

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.
Properties:
Name Type Description
error Error the error that occured.

reconnect

Emitted when a disconnected session has successfully reconnected.