new Session()
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
Every session has a number of fixed properties associated with it and may also have additional user-defined properties assigned to it by authentication handlers.Properties are essentially key/value pairs. A property is identified by its key. All property keys must be alphanumeric, starting with an alphabetic and are case sensitive. Embedded whitespace is not allowed.
All fixed properties are identified by a '$' prefix. The currently available fixed session properties are:
Fixed Property Key | Property Description |
$SessionId | The session identifier. Equivalent to Session.sessionID |
$Principal | The session principal. Equivalent to ClientSummary.principal . |
$ClientType | The client type of the session. Equivalent to ClientSummary.clientType. |
$Transport | The session transport type. Equivalent to ClientSummary.transportType. |
$Connector | The name of the connector on which the client connected. See SessionDetails.connector. |
$Country | The session's country code. See ClientLocation.details.country. |
$Language | The session's language code. See ClientLocation.details.language. |
$ServerName | The name of the session's server. See SessionDetails.server. |
$ClientIP | The session's address. See ClientLocation.address. |
$Latitude | The session's latitude, if available. See ClientLocation.coordinates.latitude. |
$Longitude | The session's longitude, if available. See ClientLocation.coordinates.longitude. |
$StartTime | The session's start time in milliseconds since the epoch. |
When registering to receive session properties special key values of diffusion.clients.PropertyKeys.ALL_FIXED_PROPERTIES and diffusion.clients.PropertyKeys.ALL_USER_PROPERTIES may be used.
Session filters
Session filters are a mechanism for accessing sessions by means of a query expression. For example, it is possible to send a message to all sessions that satisfy a specified filter. Filters are parsed and evaluated at the server.A session filter query consists of either a single search clause (example 1) or multiple search clauses connected by boolean operators (example 2):
1. Department is "Accounts"
2. Department is "Payroll" and Status is "Closed"
Search clauses may be linked by the boolean operators and or or. 'and' takes precedence over 'or' but parentheses may be used to override the precedence as follows:
(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:
1. not Department is "Payroll"
2. not (Department is "Payroll" or Department is "Accounts")
A search clause takes the form:
key operator value
Where key is the name of a session property and value is the property value. Only string values are currently supported and must be enclosed within either single or double quotes.
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"
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. |
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. |
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
Methods
-
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.
Parameters:
Name Type Description datatype
DataType The data type to produce a stream for. Returns:
- a fallback stream- Type
- FallbackStream
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()); });
-
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.
Parameters:
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. Returns:
A new ValueStream for the provided data type- Type
- ValueStream
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()); });
-
close() → {Session}
-
Close this session's connection to the server.
Calling this repeatedly will have no effect.
Returns:
This session- Type
- Session
-
getPrincipal() → {String}
-
Returns the principal name that this session is associated with.
Returns:
The principal for this session- Type
- String
-
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() { ... } });
-
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.
Returns:
a result that completes when a response is received from the server.- Type
- Result.<Session.PingDetails>
Example
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.
Parameters:
Name Type Description selector
String | TopicSelector | Array.<String> The topic selector to subscribe to. Returns:
for this operation- Type
- Result
Example
// Subscribe to a topic foo session.select("foo").then(function() { // Successfully subscribed }, function(err) { // There was an error with subscribing to topic "foo" });
-
stream(selector, callback) → {Subscription}
-
Create a Subscription stream 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#subscribe, or to add/remove listeners independently of subscriptions on the server.
By default, values are received as
Buffer
instances. To receive values as specific types, use the Subscription#asType method to specify a Data Type. Streams will only receive values from topics for which the specified data type is compatible.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 is not explicitly aware of.
An optional callback function may be provided, which will be automatically bound to the returned Subscription's
update
event.Deprecation notice
As of 6.0, Subscription is deprecated. In future versions, Session#stream will return a ValueStream. Preferred Session#addStream.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').asType(diffusion.datatypes.string()).on('value', function(path, spec, value) { console.log(value); }); // Once subscribed, the listener established above will receive topic updates session.subscribe('foo');
// Maintain a single listener independently of subscriptions/unsubscriptions session.stream('?foo/.*').asType(diffusion.datatypes.json()).on('value', function(path, spec, value) { console.log('Received an update for : ' + path, value.get()); }); // 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().asType(diffusion.datatypes.binary()).on({ value : function(topic, specification, value) { console.log('Update from: ', topic, value.get()); }, subscribe : function(topic, specification) { console.log('Subscribed to: ', topic); }, unsubscribe : function(topic, specification, reason) { 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.
Deprecation notice
As of 6.0, Subscription is deprecated. Preferred Session#select.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 selector session.subscribe("foo");
// Subscribe to a regex selector session.subscribe('?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.
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>
Examples
// Unsubscribe from a single topic session.unsubscribe('foo');
// Unsubscribe from multiple topics session.unsubscribe('?foo/.*');
-
view(selector, callback) → {View}
-
Deprecated
As of 6.0, this method is deprecated.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. - Deprecated:
-
- Yes
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
or443
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
orhttps
.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
andabort
- these are functions to be called within the strategy. Thereconnect
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:
Thetransports
property configures how the session should connect. It can be set to either astring
, or anarray
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 notransports
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 | 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>
true Reconnection options. transports
String | Array <optional>
["WEBSOCKET"] The transports to be used for connection establishment. maxMessageSize
Number <optional>
2147483647 The maximum size of messages that may be received from the server. -
PingDetails
-
Type:
- Object
Properties:
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
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.