Options
All
  • Public
  • Public/Protected
  • All
Menu

Interface Messages

Messages Feature.

This feature provides a client session with request-response messaging capabilities that can be used to implement application services.

Request-response messaging allows a session to send requests to other sessions. Each receiving session provides a corresponding response, which is returned to the sending session. Each request and response carries an application provided value.

The method used to send a request determines which sessions will receive it. Each request is routed using the provided message path – an application provided string. Two addressing schemes are provided: unaddressed requests and addressed requests.

Unaddressed requests

A session can provide an application service by implementing a handler and registering it with the server. This is somewhat similar to implementing a REST service, except that interactions between the sender and receiver are asynchronous.

Unaddressed requests sent using sendRequest are routed by the server to a handler that has been pre-registered by another session, and matches the message path.

Handlers are registered with Messages.addRequestHandler. Each session may register at most one handler for a given message path. Optionally, one or more session property names can be provided (see Session for a full description of session properties), in which case the values of the session properties for each recipient session will be returned along with its response. To add a request handler, the control client session must have REGISTER_HANDLER permission. If registering to receive session property values, the session must also have VIEW_SESSION permission.

Routing works as follows:

  1. The session sends the request, providing the message path, the request value and data type, and the expected response type.
  2. The server uses the message path to apply access control. The sender must have the SEND_TO_MESSAGE_HANDLER path permission for the message path, or the request will be rejected.
  3. The server uses the message path to select a pre-registered handler and route the request to the appropriate recipient session. 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. If there is no registered handler matching the message path, the request will be rejected.
  4. Otherwise, the server forwards the request to one of the sessions registered to handle the message path. The message path is also passed to the recipient session, providing a hierarchical context.
  5. The recipient session processes the request and returns a response to the server, which forwards the response to the sending session.

Registration works across a cluster of servers. If no matching handler is registered on the server to which the sending session is connected, the request will be routed to another server in the cluster that has one.

Addressed requests

Addressed requests provide a way to perform actions on a group of sessions, or to notify sessions of one-off events (for repeating streams of events, use a topic instead).

An addressed request can be sent to a set of sessions using sendRequestToFilter. For the details of session filters, see Session. Sending a request to a filter will match zero or more sessions. Each response received will be passed to the provided callback. As a convenience, an addressed request can be sent a specific session using the overloaded variant of sendRequest that accepts a session id.

Sending an addressed request requires SEND_TO_SESSION permission.

If the sending session is connected to a server belonging to a cluster, the recipient sessions can be connected to other servers in the cluster. The filter will be evaluated against all sessions hosted by the cluster.

To receive addressed requests, a session must set up a local request stream to handle the specific message path, using setRequestStream. When a request is received for the message path, the onRequest method on the stream is triggered. The session should respond using the provided responder. Streams receive an onClose callback when unregistered and an onError callback if the session is closed.

If a request is sent to a session that does not have a matching stream for the message path, an error will be returned to the sending session.

Accessing the feature

Obtain this feature from a session as follows:

Example:

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

Hierarchy

  • Messages

Index

Methods

addRequestHandler

  • Register a request handler to handle requests from other client sessions for a branch of the message path hierarchy.

    Each control session may register a single handler for a branch. When the handler is no longer required, it may be closed using the Registration provided by the result. To change the handler for a particular branch the previous handler must first be closed.

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

    Parameters

    • path: string

      the request path to handle

    • handler: RequestHandler

      request handler to be registered at the server

    • Optional sessionProperties: string[]

      an optional array of keys of session properties that should be supplied with each request. See Session for a full list of available fixed property keys. To request all fixed properties include PropertyKeys.ALL_FIXED_PROPERTIES as a key. In this case any other fixed property keys would be ignored. To request all user properties include PropertyKeys.ALL_USER_PROPERTIES as a key. In this case any other user properties are ignored.

    • Optional requestType: DataType<any, any, any>

      an optional request data type

    Returns Result<Registration>

    the registration Result that resolves when the handler has been registered, returning a Registration which can be used to unregister the handler.

    Otherwise, the Result will fail with an error. Common reasons for failure include:

    • the session is closed;
    • the session has already registered a handler for this message path;
    • the session does not have REGISTER_HANDLER permission to register a request handler on the server;
    • the session does not have VIEW_SESSION permission to access the client's session properties.

removeRequestStream

  • Remove the request stream at a particular path.

    Parameters

    • path: string

      the path at which to remove the request stream

    Returns RequestStream | undefined

    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), undefined will be returned instead.

sendRequest

  • Send a request. If a target is supplied, the request will be sent to the target session only.

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

    Example:

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

    Example:

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

    Example:

    // 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']
    });

    Parameters

    • path: string

      the path to send the request to

    • request: any

      the request to send

    • target: SessionId | string

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

    • Optional requestType: DataType<any, any, any> | TopicType | object | string

      an optional request DataType

    • Optional responseType: DataType<any, any, any> | TopicType | object | string

      an optional response DataType

    Returns Result<any>

    A Result that resolves with the response when a response has been received by the session if the task completes successfully.

    Otherwise, the Result will fail with an Error. Common reasons for failure include:

    • the session does not exist on the server;
    • the recipient session does not have a local request stream registered for this path;
    • the request is not compatible with the datatype bound to the handler's message path;
    • the response is not compatible with the specified response type;
    • the request has been rejected by the recipient session calling Responder.reject(message);
    • the session is closed;
    • the session does not have SEND_TO_SESSION permission;

  • Parameters

    • path: string
    • request: any
    • Optional requestType: DataType<any, any, any> | TopicType | object | string
    • Optional responseType: DataType<any, any, any> | TopicType | object | string

    Returns Result<any>

sendRequestToFilter

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

    Example:

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

    Example:

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

    Parameters

    • filter: string

      the session filter expression. See Session for a full description of filter expressions.

    • path: string

      message path used by the recipient to select an appropriate handler

    • request: any

      the request to send

    • callback: FilteredResponseHandler

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

    • Optional reqType: DataType<any, any, any> | TopicType | object
    • Optional respType: DataType<any, any, any> | TopicType | object

    Returns Result<number>

    a Result that resolves when the server has dispatched all the requests.

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

    Otherwise, the Result will fail with an Error. Common reasons for failure include:

    • the filter parameter could not be parsed;
    • the calling session does not have SEND_TO_SESSION and VIEW_SESSION permissions;
    • the calling session is closed.

setRequestStream

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

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

    Parameters

    • path: string

      the path to receive request on

    • stream: RequestStream

      the request stream to handle requests to this path

    • Optional reqType: DataType<any, any, any> | TopicType | object
    • Optional resType: DataType<any, any, any> | TopicType | object

    Returns RequestStream | undefined

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