PubNub FunctionsIntro to Function Types

PubNub Functions behave differently depending on their type and the type of a Function determines when and in response to what external event it will be triggered.

A Function can be one of the 4 types below:

  • Before Publish or Fire
  • After Publish or Fire
  • After Presence
  • On Request

When an Function is triggered, the message processing can be defined as either asynchronous (non-blocking) or synchronous (blocking), depending on the selected Function Type.

When a synchronous Function Type is used, messages are processed by the Function code before they are forwarded on to subscribers of the channel.

Since the logic of the Function must complete before the message is released to continue it's trip to the subscribers, a delivery delay (from microseconds for simple arithmetic, to potentially tens or thousands of milliseconds if interacting with a 3rd-party REST service) may be incurred.

Synchronous Event Handlers process messages (events) inline
 

Any mutations made to a message from within a synchronous Function are irreversible! Once the message has been mutated and passed through, the original message data is not recoverable (unless programatically preserved in a new message attribute, the KV store, etc.)

When a Before Publish or Fire Function Type is chosen, the message is:

  1. Published by the sender.
  2. Received by the PubNub Data Stream Network.
  3. Routed to PubNub Functions for Function processing.
  4. Upon completion of Function processing, globally replicated and distributed to awaiting subscribers.

Due to the store, process, and forward characteristics of this Function Type, it is critical that all Function logic performed is quick and efficient to minimize message delivery delays.

If you need to mutate a message inflight (add a new attribute or modify an existing attribute) Before Publish or Fire is the proper Function Type to use.

Some applications of Before Publish or Fire include:

  • Translating a message from one language to another.
  • Conversion of values from Imperial to Metric.
  • Detecting (and censoring) profanity.
  • Detecting (and normalization) of missing or illegal values.

When an asynchronous Function Type is used, messages are delivered to subscribers in parallel to Function code running against the message -- because of this, there is no delay incurred from the perspective of the subscribing clients.

Asynchronous Event Handlers process messages (events) in parallel
 

Since a message cannot be mutated from within an Asynchronous Function Type, the message received by the client is always identical to the message that triggered the Function.

When an After Publish or Fire Function Type is chosen, the message is received by the PubNub Data Stream Network and replicated (as-is, without any sort of mutation) across all global PoPs and awaiting subscribers. Simultaneously, a copy of the same message is made available to the associated PubNub Functions Function for further processing.

Note that relative to the awaiting subscribing clients, this operation is asynchronous, and as such, results in no observable message delivery delay.

If you need to pass the original message through the PubNub Data Stream Network intact, without mutating it by any means, however using it as a trigger to execute other logic (logging, message teeing, etc.,) After Publish or Fire is the Function Type to use.

Some applications of After Publish or Fire include:

  • Asynchronous Message Logging via REST (ElasticSearch).
  • Mention, Keyword, Slash Command, or other String Triggers.
  • Message Teeing / Forwarding.

Message-based Function Type(s) (such as Before/After Publish or Fire) execute their associated Function(s) via message-based triggers. In comparison, the Presence-based Function Type, After Presence, triggers it's associated Function(s) via PubNub subscriber presence events.

When an After Presence Function Type is chosen, in parallel with the triggering presence event, a copy of the same presence event is made available to the associated Function for further processing.

Note that relative to the awaiting subscribing clients, this operation is asynchronous, and there is no presence event delivery delay.

If you need to pass the presence event through the PubNub Data Stream Network intact, without mutating it by any means, however using it as a trigger to execute other logic (logging, message teeing, etc.,) After Presence is the Function Type to use.

Some use cases for After Presence include:

  • Send an SMS to an offline user when you see a member of his priority buddy-list come online.
  • Update an on-hold wait time KV store as JOIN and LEAVE events occur.
  • Monitor a user's online/offline time card as they JOIN and LEAVE an app.
Example of jsonParsing a POST body and responding with a 301 redirect

export default (request, response) => {
    return request.json().then(jsonParsedBody => {
        console.log('jsonParsedBody', jsonParsedBody);
        response.headers.location = 'http://www.pubnub.com';
        response.status = '301';
        return response.send();
    });
}

Here are examples of possible properties on the request object:

request.verb = 'rest';
request.version = 'v1';
request.pubkey = 'demo'
request.subkey = 'demo'
request.path = 'examplePath';
request.method = 'POST';
request.body = '%22hello%22';
request.headers = {
    'foo': 'bar'
};
request.params = {
    'bar': 'baz'
};
request.meta = {
    'clientip': '127.0.0.1',
    'origin': 'ps.pndsn.com'
    'useragent': 'Mozilla',
};
 If no query string variables are passed that, request.params will be an empty dictionary and if no headers are passed that, request.headers will be an empty dictionary.

To summarize:

Before Publish or Fire Function TypeAfter Publish or Fire Function TypeAfter Presence Function Type
PubNub Client Trigger
fire() or publish()
fire() or publish()
Subscriber Presence events
Sync or Async
Synchronous
Asynchronous
Asynchronous
Triggering Message can be mutated
Yes
No
No
Example
Translating a message from English to another language
Mention, Keyword, Slash Command, or other String Triggers
Send an SMS to an offline when buddy-list member goes online.

Regardless of the Function Type selected, all Function(s) can read/write to the KV DB, utilize 3rd Party API(s) via REST calls, add/remove/mutate attributes, etc.

It's important to keep in mind some basic rules on how channels, Functions  Function(s), Function Type(s), and PubNub Functions can be combined and associated with one another:

  • A Module may have many Functions contained within it.
  • A Function can only belong to one Module (unless you clone it.)
  • A Function can be bound to a single channel, a first level wildcard (foo.), or a top level wildcard.
  • If a Function is bound to a first level wildcard, other Functions for that key cannot be bound to overlapping channels, for example if you register a Function to foo.* you cannot also register another Function of the same type to foo.bar.
  • If a Function is bound to a top level wildcard (""), it must be the only Function registered of that event type for the key. For example, if you register a Function of type On Before Publish or Fire to "", you cannot register any other Function of the same type in any Module in the key.
  • For any given channel, only one of each unique Functions may be bound to it, and therefore, for any given channel, only three Functions may be bound to it.

For example, channel public-lobby can have up to three Functions assigned to it; one of each Before Publish or Fire, After Publish or Fire, and After Presence.

 
PubNub Functions provides a rich set of tools, and this documentation does not cover all of the potential situations you may encounter. If you need help with a situation not covered by the documentation, please contact PubNub Support.