Namespace: messages

Session. messages

Messages Feature.

This feature provides a client session with messaging capabilities. Each message is delivered to a request stream registered with the server. Additionally, the server and other clients can send messages to be received using this feature.

Message requests are sent and received for a particular path. The message path provides a hierarchical context for the recipient.

Message paths are distinct from topic paths. A topic with the path need not exist on the server; if a topic does exist, it is unaffected by messaging. An application can use the same path to associate messages with topics, or an arbitrary path can be chosen.

A message request sent directly to another session is discarded if the receiving session is no longer connected or does not have a stream that matches the message path - an error is returned to the sending session in this case.

Handlers for receiving messages are registered for a path. Each session may register at most one handler for a given path. When dispatching a message, the server will consider all registered handlers and select one registered for the most specific path. If multiple sessions have registered a handler registered for a path, one will be chosen arbitrarily.

When registering handlers to receive messages it is also possible to indicate that certain session properties (see Session for a full description of session properties), should be delivered with each message from a client session. The current values of the named properties for the originating session will be delivered with the message.

Messages can also be sent using 'filters', (see Session for a full description of session filters), where the message is delivered to all sessions that satisfy a particular filter expression.

Messages from other clients are received via streams. Streams receive an onClose callback when unregistered and an onError callback if the session is closed.

Request-Response Messaging

Typed request-response messaging allows applications to send requests (of type T) and receive responses (of type R) in the form of a Result. Using Messaging, applications send requests to paths using sendRequest. In order to receive requests, applications must have a local request stream assigned to the specific path, using setRequestStream. When a request is received, the onRequest method on the stream is triggered, to which a response can be sent using the provided respond method call.

One-way Messaging (deprecated)

One-way messaging allows a client to send an untyped message to be sent to a path and be notified that the message has been delivered. No response is possible.

A client can listen for one-way messages for a selection of paths by adding one or more MessageStream implementations. The mapping of selectors to message streams is maintained locally in the client process. Any number of message streams for inbound messages can be added on various selectors. If a message is received on a message path that matches with no message streams, it is passed to any fallback message streams that have been registered.

Access control

A client session needs SEND_TO_MESSAGE_HANDLER permission for the message paths to which it sends messages. If a client sends messages to a message path for which it does not have permission, the message is discarded by the server.

Accessing the feature

Obtain this feature from a session as follows:

Example

// Get a reference to messaging feature
var messages = session.messages;

Classes

FilteredResponseHandler
MessageHandler
MessageStream
Registration
RequestHandler
RequestStream
Responder

Members

<static, readonly> Priority

The priority of the message. Higher priorities are delivered faster.

Properties:
Name Type Default Description
NORMAL 0

Indicates that messages should be delivered with normal priority.

HIGH 1

Indicates that messages should be delivered with high priority.

LOW 2

Indicates that messages should be delivered with low priority.

Deprecated:
  • since 6.2

    This is only used within one-way messaging, which is deprecated from this release. This enum will be removed in a future release.

Methods

addHandler(path, handler, keys) → {Result.<undefined>}

Register a MessageHandler to receive messages that were sent from other sessions for a particular path but with no specified recipient. The handler must implement the MessageHandler interface.

The provided handler will be passed messages received on the same path used for registration, or any lower branches. A session may only register a single handler for a given path at a time.

The message content is dependent on the sender. Correct parsing of the message content from a Buffer is up to the consuming handler.

Unlike Session.messages#listen, received messages provide the sender's SessionId.

Parameters:
Name Type Argument Description
path String

The message path to handle

handler Session.messages.MessageHandler

The message handler

keys Array <optional>

Message keys to register for this session

Deprecated:
  • since 6.2

    One-way messaging is deprecated in favor of request-response messaging. See sendRequest and sendRequestToFilter. This method will be removed in a future release.

Returns:

The registration Result.<undefined>

Type
Result.<undefined>
Example
// Create a message handler
var handler = {
    onMessage : function(message) {
         console.log(message); // Log the received message
    },
    onActive : function(unregister) {

    },
    onClose : function() {

    }
};

// Register the handler
session.messages.addHandler('foo/bar', handler).then(function() {
    // Registration happened successfully
}, function(error) {
    // Registration failed
});

addRequestHandler(path, handler, sessionProperties, requestType) → {Result.<Registration>}

Register a request handler to handle requests from other client sessions on a path.

Parameters:
Name Type Argument Description
path String

The request path to handle

handler Session.messages.RequestHandler

Request handler to be registered at the server

sessionProperties Array <optional>

An optional array containing session properties that should be included with each request

requestType function <optional>

An optional request DataType

Returns:

The registration Result.<Registration>

Type
Result.<Registration>
Example
// Create a request handler that handles strings
var handler = {
      onRequest: function(request, context, responder) {
          console.log(request); // Log the request
          responder.respond('something');
      },
      onError: function() {},
      onClose: function() {}
  };

// Register the handler
control.messages.addRequestHandler('test/topic', handler).then(function() {
    // Registration happened successfully
}, function(error) {
    // Registration failed
});

listen(path, listener) → {Session.messages.MessageStream}

Listen to a stream of messages sent to this Session for a particular path. Messages will be received as message instances.

The message content is dependent on the sender. Correct parsing of the message content from a Buffer is up to the consuming session.

Received messages do not indicate which session sent them; if sender information is required then this should be included within the message content.

Parameters:
Name Type Argument Description
path String

The message path

listener function <optional>

The default listener

Deprecated:
  • since 6.2

    One-way messaging is deprecated in favor of request-response messaging. See sendRequest and sendRequestToFilter. This method will be removed in a future release.

Returns:

A stream providing messages received on the specific path

Type
Session.messages.MessageStream
Examples
// Create with a default listener function
session.messages.listen('foo', function(message) {
    // Do something with the message
});
// Create a message stream and consume from it
var stream = session.messages.listen('foo');

stream.on('message', function(message) {
     // Do something with the message
});

removeRequestStream(path) → {Session.messages.RequestStream}

Remove the request stream at a particular path.

Parameters:
Name Type Description
path String

The path at which to remove the request stream

Returns:

stream - The request stream that was removed from the path. If the path does not have a request stream assigned (or the path does not exist), null will be returned instead.

Type
Session.messages.RequestStream

send(path, message, options, target) → {Result.<Session.messages.MessageSendResult>}

Send an arbitrary message to either the server or another session, on a particular path.

The path does not need to correspond to an existing topic; however the use of / as a hierarchical delimiter allows for other sessions to listen to messages from specific paths.

The message content may be of any type that can be used for topic updates. It is up to any receiving session to de-serialize it as appropriate.

An optional argument may be provided to target a specific session or a collection of sessions that satisfy a given filter string. Messages sent will be received if that session has established a MessageStream for the same message path. The ability to send messages to specific sessions or via a filter is determined by permissions assigned to the sender.

If no session ID or filter is given, the message will be sent to the server and dispatched to a control client that has registered a MessageHandler for the same, or higher, path. There is no guarantee that a MessageHandler will have been established for the path that the message is sent on.

If no recipient is specified, a successful result will resolve with a single object containing the path that the message was sent to.

If a session ID was used as the recipient, then the result will resolve with an object containing both path and recipient fields. The result will only resolve when the message has been successfully received by the intended recipient.

If a session filter was used to send the message, then the result will contain path, recipient, sent and errors fields. The sent field specifies the number of sessions that the filter resolved and successfully sent the message to. The errors field contains an array of errors for any session that could not receive the message.

Parameters:
Name Type Argument Description
path String

The message path

message Object

The message value

options Session.messages.SendOptions <optional>

The optional message send options

target String | Object <optional>

The target recipient's session ID (as a string or Session ID object) or a session property filter string.

Deprecated:
  • since 6.2

    One-way messaging is deprecated in favor of request-response messaging. Use sendRequest instead. This method will be removed in a future release.

Returns:

The Result<Session.messages.MessageSendResult> of the send operation

Type
Result.<Session.messages.MessageSendResult>
Examples
// Send a message to be received by the server and passed to a MessageHandler
session.messages.send('foo', 123);
// Send a message to a specific session
session.messages.send('bar', 'hello', sessionID);
// Send a message with a filter
session.messages.send('baz', 'world', '$Principal is "john"');

sendRequest(path, request, target, requestType, responseType) → {Result}

Send a request.

A response is returned when the {Result} is complete.

Parameters:
Name Type Argument Description
path String

The path to send the request to

request Object

The request to send

target String | Object <optional>

The target recipient's session ID (as a string or Session ID object)

requestType function <optional>

An optional request DataType

responseType function <optional>

An optional response DataType

Returns:

A {Result} containing the response

Type
Result
Examples
// Send a string request to be received by the server and passed to a
// {Session.messages.RequestHandler} registered on the supplied topic
session.messages.sendRequest('test/topic', 'string request');
// Send a JSON request to be received by the server and passed to a
// {Session.messages.RequestHandler} registered on the supplied topic
session.messages.sendRequest('test/topic', diffusion.datatypes.json()
     .from({ "foo": "bar"}), diffusion.datatypes.json());
// Send an implicit JSON request to be received by the server and passed to a
// {Session.messages.RequestHandler} registered on the supplied topic
session.messages.sendRequest('test/topic', {
      dwarfs: ['sneezy', 'sleepy','dopey',
          'doc', 'happy', 'bashful',
          'grumpy']
  });

sendRequestToFilter(filter, path, request, callback, requestType, responseType) → {Result}

Send a request to all sessions that satisfy a given session filter.

Parameters:
Name Type Argument Description
filter String

The session filter expression

path String

Message path used by the recipient to select an appropriate handler

request Object

The request to send

callback Session.messages.FilteredResponseHandler

The handler to receive notification of responses (or errors) from sessions

requestType function <optional>

An optional request DataType

responseType function <optional>

An optional response DataType

Returns:

If the server successfully evaluated the filter, the result contains the number of sessions the request was sent to. Failure to send a request to a particular matching session is reported to the handler.

Type
Result
Examples
// Send a string request to be received by the server and passed to sessions matching the filter.
session.messages.sendRequestToFilter('$Principal NE "control"', 'test/topic', 'string request', {
          onResponse : function(sessionID, response) {
              console.log(response); // Log the response
          },
          onResponseError : function() {},
          onError : function() {},
          onClose : function() {}});
// Send a JSON request to be received by the server and passed to sessions matching the filter.
session.messages.sendRequestToFilter('$Principal NE "control"', 'test/topic',
     { dwarfs: ['sneezy', 'sleepy','dopey' ] },
     {
          onResponse : function(sessionID, response) {
              console.log(response.get()); // Log the response
          },
          onResponseError : function() {},
          onError : function() {},
          onClose : function() {}}, diffusion.datatypes.json(), diffusion.datatypes.json());

setRequestStream(path, stream, requestType, responseType) → {Session.messages.RequestStream}

Set a request stream to handle requests to a specified path.

Parameters:
Name Type Argument Description
path String

The path to receive request on

stream Session.messages.RequestStream

The request stream to handle requests to this path

requestType function <optional>

An optional request DataType

responseType function <optional>

An optional response DataType

Returns:

Null if the request stream is the first stream to be set to the path, otherwise this method will return the previously set request stream.

Type
Session.messages.RequestStream
Example
// Set a request stream handler to handle string requests to 'test/topic'
var handler = {
      onRequest: function (path, request, responder) {
          console.log(request);
          responder.respond('hello');
      },
      onError: function() {}
  };

control.messages.setRequestStream('test/topic', handler,
                                     diffusion.datatypes.string(), diffusion.datatypes.string());

Type Definitions

Message

Type:
  • Object
Properties:
Name Type Description
path String

The path that this message was sent on

content Buffer

The message's value as a binary buffer

Deprecated:
  • since 6.2

    One-way messaging is deprecated in favor of request-response messaging. See sendRequest and sendRequestToFilter. This interface will be removed in a future release.

Example
// Read message content as a JSON DataType value
var jsonObj = diffusion.datatypes.json().readValue(message.content).get();

MessageSendResult

Type:
  • Object
Properties:
Name Type Argument Description
path String

topic path

recipient String

session filter or SessionID of the recipient

sent Number <optional>

the number of sessions the message has been sent to using a filter string

errors Array.<ErrorReport> <optional>

errors from sending to sessions using a filter string

Deprecated:
  • since 6.2

    One-way messaging is deprecated in favor of request-response messaging. See sendRequest and sendRequestToFilter. This interface will be removed in a future release.

RequestContext

Type:
  • Object
Properties:
Name Type Description
sessionId SessionId

SessionId of the session that sent the request

path String

the message path of the request

properties Object

the session properties

SendOptions

Type:
  • Object
Properties:
Name Type Argument Default Description
priority Session.messages.Priority <optional>
Session.messages.Priority.NORMAL

The message priority

headers Array.<String> <optional>
[]

The message headers as an array of strings

Deprecated:
  • since 6.2

    This is only used within one-way messaging, which is deprecated from this release. This interface will be removed in a future release.

SessionMessage

Type:
  • Object
Properties:
Name Type Description
path String

The path that this message was sent on

content Buffer

The message's value as a binary buffer

session String

The session that sent this message

Deprecated:
  • since 6.2

    One-way messaging is deprecated in favor of request-response messaging. See sendRequest and sendRequestToFilter. This interface will be removed in a future release.