2.0.3 • Published 2 years ago

databridges-sio-client-lib v2.0.3

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
2 years ago

npm.ionpm.io

Databridges Node.js client Library

DataBridges makes it easy for connected devices and applications to communicate with each other in realtime in an efficient, fast, reliable and trust-safe manner. Databridges Node.js client library allows you to easily add realtime capabilities to your applications in record time.

Usage Overview

The following topics are covered:

Supported platforms

Node.js version 10 or newer. (The current Long Term Support (LTS) release is an ideal starting point).

Installation.

You can use NPM package manager to install the package.

npm install databridges-sio-client-lib --save

Note : Databridges library uses socket.io for websocket protocol management.

Initialization

const dbridge = require('databridges-sio-client-lib');
const dbridge = new dBridges();

Global Configuration

Required

The following is the list of required connection properties before connecting to dataBridges network.

dbridge.auth_url = 'URL';
dbridge.appkey = 'APP_KEY';

You need to replace URL and APP_KEY with the actual URL and Application Key.

PropertiesDescriptionExceptions
auth_url(string) Authentication url from dataBridges dashboard.source: DBLIB_CONNECT code: INVALID_URL
appkey(string) Application Key from dataBridges dashboard.source: DBLIB_CONNECT code: INVALID_AUTH_PARAM

Optional

The following is the list of optional connection properties before connecting to dataBridges network.

dbridge.maxReconnectionRetries = 10;
dbridge.maxReconnectionDelay = 120000; 
dbridge.minReconnectionDelay = 1000 + Math.random() * 4000;
dbridge.reconnectionDelayGrowFactor = 1.3;
dbridge.minUptime = 200 ; 
dbridge.connectionTimeout = 10000;
dbridge.autoReconnect = true; 
dbridge.cf.enable = false; 
PropertiesDefaultDescription
maxReconnectionDelay10(integer) The maximum delay between two reconnection attempts in seconds.
minReconnectionDelay1000 + Math.random() * 4000(integer) The initial delay before reconnection in milliseconds (affected by the reconnectionDelayGrowFactor value).
reconnectionDelayGrowFactor1.3(float) The randomization factor used when reconnecting (so that the clients do not reconnect at the exact same time after a server crash).
minUptime200(integer) Uptime before connected event is triggered, value in milliseconds.
connectionTimeout10000(integer) Number of milliseconds the application will wait for a connection to be established. If it fails it will emit a connection_error event.
maxReconnectionRetries10(integer) The number of reconnection attempts before giving up.
autoReconnecttrue(boolean) If false, application will not attempt reconnecting.
cf.enablefalse(boolean) Enable exposing client function for this connection. (Check Client Function section for details.)
access_tokenfunction(function) If you need custom authorization behavior for generating signatures for private/ presence/ system channels/rpc functions, you can provide your own access_token function.

Connection

Once the properties are set, use connect() function to connect to dataBridges Network.

dbridge.connect().catch((err) => {
    console.log('dBridges Connection exception..', err.source, err.code, err.message);
});

Exceptions:

SourceCodeMessageDescription
DBLIB_CONNECTINVALID_URLValue of dbridge.auth_url is not a valid dataBridges authentication URL.
DBLIB_CONNECTINVALID_AUTH_PARAMValue of dbridge.appkey is not a valid dataBridges application key.
DBLIB_CONNECTINVALID_ACCESSTOKEN_FUNCTIONIf "callback function" is not declared for authentication only while using private, presence or system channel/RPC functions. (Check Channel or RPC section for details.)
DBLIB_CONNECTHTTP_HTTP protocol reported message.HTTP Errors returned during authentication process. HTTP Error code will be concatenated with HTTP_ in the err.code. eg. HTTP_501
DBLIB_CONNECTINVALID_CLIENTFUNCTIONIf "callback function" is not declared for client function or typeof() variable defined is not a "function". This is applicable only if clientFunction is enabled. (Check Client Function section for details.)

sessionid (string)

console.log(dbridge.sessionid);

Making a connection provides the application with a new sessionid that is assigned by the server. This can be used to distinguish the application's own events. A change of state might otherwise be duplicated in the application. It is also stored within the connection, and used as a token for generating signatures for private/presence/system channels/rpc functions.

disconnect (function)

To close a connection use disconnect function. When a connection has been closed explicitly, no automatic reconnection will happen.

dbridge.disconnect();

Objects

ObjectDescription
connectionstateconnectionstate object expose properties, functions and events to monitor and manage the health of dataBridges network connection.
channelchannel object exposes trust-safe flexible Pub/Sub messaging properties, functions and events to build realtime event messaging / event driven applications at scale.
rpcrpc object exposes trust-safe properties, functions and events to provide reliable two-way messaging between multiple endpoints allowing you to build sophisticated asynchronous interactions.
cfCF (Client-function) object is a special purpose RPC implementation to build command and control applications. CF object exposes properties, functions and events for command and control server applications to send messages to devices and application using dataBridges library in trust-safe manner , build smart update configuration system and implement trust-safe actions for remote and automated management.

object:ConnectionState

Connectionstate object expose properties, functions and events to monitor and manage the health of dataBridges network connection.

Properties

The following is the list of connection state properties.

console.log(dbridge.connectionstate.state);
console.log(dbridge.connectionstate.isconnected);
console.log(dbridge.connectionstate.rttms);
console.log(dbridge.connectionstate.reconnect_attempt);
PropertyDescription
connectionstate.state(String) Current state of dataBridges network connection . List of Return Values are detailed below.
connectionstate.isconnected(Boolean) To verify if the application is still connected to the dataBridges network.
connectionstate.rttms(integer) Latency in milliseconds between your application and the dataBridges router where your application is connected.
connectionstate.reconnect_attempt(integer) Number of reconnection attempted as of now.
connectionstate.state
Return ValuesDescription
connectingYour application is now attempting to connect to dataBridges network.
connectedThe connection to dataBridges network is open and authenticated with your appkey.
connection_breakIndicates a network disconnection between application and dataBridges network. The library will initiate an automatic reconnection, if the reconnection property is set as true.
connect_errorThe dataBridges network connection was previously connected and has now errored and closed.
disconnectedThe application is now disconnected from the dataBridges network. The application will than need to initiate fresh connection attempt again.
reconnectingYour application is now attempting to reconnect to dataBridges network as per properties set for reconnection.
reconnect_errorReconnection attempt has errored.
reconnect_failedThe application will enter reconnect_failed state when all the reconnection attempts have been exhausted unsuccessfully. The application is now disconnected from the dataBridges network. The application will than need to initiate fresh connection attempt again
reconnectedThe application has successfully re-connected to the dataBridges network, This state will follow connect_error or reconnect_error.

Bind to connectionstate events

Apart from retrieveing state of a dBrige connection, application can bind to connectionstate events.

You can use the following methods on connectionstate object to bind to events.

dbridge.connectionstate.bind(eventName, () => {});
dbridge.connectionstate.unbind(eventName);
dbridge.connectionstate.unbind();

bind() on eventName has callback functions to be defined where you can write your own code as per requirement.

To stop listening to events use unbind(eventName) function.

To stop listening to all events use unbind() without eventName function.

Below are library events which can be bind to receive information about dataBridges network.

System events for connectionstate object

dbridge.connectionstate.bind("connecting", () => {
    console.log('connecting');
});
dbridge.connectionstate.bind("reconnecting", () => {
    console.log('reconnecting', "reconnect_attempt=", dbridge.connectionstate.reconnect_attempt);
});
dbridge.connectionstate.bind("disconnected", () => {
    console.log('disconnected');
});
dbridge.connectionstate.bind("reconnected", () => {
    console.log('reconnected');
}); 
dbridge.connectionstate.bind("connection_break", (payload) => {
    console.log('connection_break', payload.source, payload.code, payload.message);
});
dbridge.connectionstate.bind("state_change", (payload) => {
    console.log('state_change', dbridge.connectionstate.state, payload);
});
dbridge.connectionstate.bind("connect_error", (payload) => {
    console.log('connect_error', payload.source, payload.code, payload.message); 
});
dbridge.connectionstate.bind("reconnect_error", (payload) => {
    console.log('reconnect_error', payload.source, payload.code, payload.message);
}); 
dbridge.connectionstate.bind("reconnect_failed", (payload) => {
    console.log('reconnect_failed', payload.source, payload.code, payload.message); 
});
dbridge.connectionstate.bind("rttpong", (payload) => {
    console.log('rttpong', payload, dbridge.connectionstate.rttms);
}); 
dbridge.connectionstate.bind("connected", () => { 
    console.log('dBridges Event Bind', 'connected');
});
payload: (dberror object)
{
    "source": "DBLIB_CONNECT" , 			// (string) Error source
    "code": "RECONNECT_ATTEMPT_EXCEEDED",	// (string) Error code 
    "message": "" 							// (string) Error message if applicable.
}
EventsParametersDescription
connectingThis event is triggered when your application is attempting to connect to dataBridges network.
connectedThis event is triggered when connection to dataBridges network is open and authenticated with your appkey.
connection_breakpayload(dberror object) Indicates a network disconnection between application and dataBridges network. The library will initiate an automatic reconnection, if the reconnection property is set as true.
connect_errorpayload(dberror object) This event is triggered when the dataBridges network connection was previously connected and has now errored and closed.
disconnectedThe application is now disconnected from the dataBridges network. The application will than need to initiate fresh connection attempt again.
reconnectingThis event is triggered when application is now attempting to reconnect to dataBridges network as per properties set for reconnection.
reconnect_errorpayload(dberror object) This event is triggered when reconnection attempt has errored.
reconnect_failedpayload(dberror object) reconnect_failed event is triggered when all the reconnection attempts have been exhaused unsuccessfully. The application is now disconnected from the dataBridges network. The application will than need to initiate fresh connection attempt again.
reconnectedThis event is triggered when the connection to dataBridges network is open and reconnected after connect_error or reconnect_error.
state_changepayload with payload.previous, payload.current(dict) This event is triggered whenever there is any state changes in dataBridges network connection. Payload will have previous and current state of connection.
rttpongpayload(integer) In Response to rttping() function call to dataBridges network, payload has latency in milliseconds between your application and the dataBridges router where your application is connected.

dberror:

SourceCodeMessageDescription
DBLIB_CONNECTRECONNECT_ATTEMPT_EXCEEDEDTriggered when reconnect_failed event is raised.
DBNET_CONNECTDISCONNECT_REQUESTTriggered when connect_error event is raised.
DBNET_CONNECTRECONNECT_REQUESTTriggered when connect_error, connection_break event is raised.
DBLIB_CONNECTNETWORK_DISCONNECTEDTriggered when connect_error, reconnect_error event is raised.
DBLIB_CONNECTINVALID_URLValue of dbridge.auth_url is not a valid dataBridges authentication URL.
DBLIB_CONNECTINVALID_AUTH_PARAMValue of dbridge.appkey is not a valid dataBridges application key.
DBLIB_CONNECTINVALID_ACCESSTOKEN_FUNCTIONIf "callback function" is not declared for authentication only while using private, presence or system channel/RPC functions. (Check Channel or RPC section for details.)
DBLIB_CONNECTHTTP_HTTP protocol reported message.HTTP Errors returned during authentication process. HTTP Error code will be concatenated with HTTP_ in the err.code. eg. HTTP_501
DBLIB_CONNECTINVALID_CLIENTFUNCTIONIf "callback function" is not declared for client function or typeof() variable defined is not a "function". This is applicable only if clientFunction is enabled. (Check Client Function section for details.)

Exceptions:

SourceCodeDescription
DBLIB_CONNECT_BINDINVALID_EVENTNAMEInvalid Event name. Not in defined events as above.
DBLIB_CONNECT_BINDINVALID_CALLBACKIf "callback function" is not declared or typeof() variable defined is not a "function".

Functions

rttping()

This method is to understand the latency in milliseconds between your application and the dataBridges router where your application is connected. Event rttpong is triggered once response is received from dataBridges network. Bind to event:rttpong to retrieve the latency in ms.

// To get the last known Latency in milliseconds between your application and the dataBridges router where your application is connected.
// The dataBridges library exchanges rttms during the initial dataBridges network connection routine.
console.log(dbridge.connectionstate.rttms);

// To get the latest Latency in milliseconds between your application and the dataBridges router where your application is connected.
dbridge.connectionstate.rttping();

// Bind to rttpong, to get notified about the latest Latency in milliseconds between your application and the dataBridges router where your application is connected.
dbridge.connectionstate.bind("rttpong", (payload) => {
    console.log('rttpong', payload);
    //payload is an integer value is in millisecond which is same as dbridge.connectionstate.rttms.
});

Exceptions:

SourceCodeDescription
DBLIB_RTTPINGNETWORK_DISCONNECTEDConnection to dataBridges network is not active.

object:Channel

channel object exposes trust-safe flexible Pub/Sub messaging properties, functions and events to build realtime event messaging / event driven applications at scale.

Concepts

  • A message is attached to an event
  • Group similar events into a channel
  • Subscribe to a channel to receive all channel event messages.
  • Publish event message to the channel and it will be sent to all the channel subscribers who are connected to dataBridges network and online.
  • if you need to have an access controlled channel, prefix the channel name with pvt: , prs: and sys: .To subscribe to these type of channel. you will need to pass a trust-token when you subscribe to the channel. A trust-token is a JWT document created using a combination of channelname + sessionid + app.secret.
    • Use your existing access control, authorization and session identification rule-set, process and methods to create a trust-token instructing the dataBridges router to accept the pvt: prs: and sys: channel subscription, connection of from client application.
  • Trust-tokens allows you to enable secured, access controlled and compliance driven realtime event driven messaging in your existing and new initiative applications.

dataBridges library supports 4 types of channel. The namespace is the 4 characters preceding the channelName (pvt:,prs:,sys:), identifying which type of channel the application is connecting to. If the channel type is pvt:,prs:,sys:, dataBridges library will use the access_token function to get the access encrypted token and will use it for all communication with this channel.

Channel TypeChannel Name StyleDescription
PublicchannelNamePublic channel is used to send and receive messages that are to be publicly available. This channel type does not require any trust authorization token to subscribe. e.g channelName = mychannel
Privatepvt:channeNamePrivate channels is restricted channel. application will need to provide trust authorization token to subscribe and use Private channel. The dataBridges library will use the access_token function to get the trust authorization token. e.g channelName = pvt:mychannel
Presenceprs:channeNamePresence channels is a specialized private channel with additional feature of presence awareness. Subscribing to presence channel allows application to be notified of members joining / leaving the channel. Since Presence channel is a specialized version of Private channel, application will need to provide trust authorization token to subscribe and use Private channels. The dataBridges library will use the access_token function to get the trust authorization token.e.g channelName = prs:mychannel
Systemsys:channeNameSystem channel is a specialized Presence channel to build command and control applications. Using System channel to create command and control server applications to send messages to devices and application using dataBridges library in trust-safe manner , build smart update configuration system and implement trust-safe actions for remote and automated management. System channel allows application to send and receive messages with the server application (using dataBridges server library). Since System channel is a specialized version of Presence channel, application will need to provide trust authorization token to subscribe and use Private channels. The dataBridges library will use the access_token function to get the trust authorization token.e.g channelName = sys:systeminfo

dataBridges library provides 2 different ways to access any of above channel types based on usage.

Channel TypeDescription
Subscribe to Channelapplication that subscribes to a channel will receive messages and can send messages.
Connect to ChannelWhere we have use-cases where application needs to only send messages and not interested to consume / receive channel messages, should connect to channel instead of subscribing to the channel.

Subscribe to Channel

Application that subscribes to a channel will receive messages and can send messages.

subscribe()

The default method for subscribing to a channel involves invoking the channel.subscribe function of your dataBridges object:

try {
    const subscribed_channel = dbridge.channel.subscribe('mychannel');
} catch (err) {
    console.log(err.source, err.code, err.message);
}
ParameterRulesDescription
stringchannelName ORpvt:channelName ORprs:channelName ORsys:channelNamechannelName to which subscription to be done.
Return TypeDescription
objectchannel object which events and related functions can be bound to.

Application can directly work with dataBridges object without using Channel object. Using this method application cannot publish any events.

try {
    dbridge.channel.subscribe('mychannel');
} catch (err) {
    console.log(err.source, err.code, err.message);
}
Exceptions:
SourceCodeDescription
DBLIB_CHANNEL_SUBSCRIBENETWORK_DISCONNECTEDConnection to dataBridges network is not active.
DBLIB_CHANNEL_SUBSCRIBEINVALID_CHANNELNAMEApplicable for below conditions 1. channelName is not defined.2. channelName validation error, typeof() channelName is not type string3. channelName validation error, channelName fails a-zA-Z0-9\.:_- validation.
DBLIB_CHANNEL_SUBSCRIBEINVALID_CHANNELNAME_LENGTHchannelName validation error, length of channelName greater than 64
DBLIB_CHANNEL_SUBSCRIBECHANNEL_ALREADY_SUBSCRIBEDchannelName is already subscribed.

unsubscribe()

To unsubscribe from a subscribed channel, invoke the unsubscribe function of your dataBridges object. unsubscribe cannot be done on channel object.

try {
    dbridge.channel.unsubscribe('mychannel');
} catch (err) {
    console.log(err.source, err.code, err.message);
}
ParameterRulesDescription
stringchannelName ORpvt:channelName ORprs:channelName ORsys:channelNamechannelName to which un-subscription to be done.
Return TypeDescription
NA
Exceptions:
SourceCodeDescription
DBLIB_CHANNEL_UNSUBSCRIBENETWORK_DISCONNECTEDConnection to dataBridges network is not active.
DBLIB_CHANNEL_UNSUBSCRIBECHANNEL_NOT_SUBSCRIBEDchannelName is not subscribed.
DBLIB_CHANNEL_UNSUBSCRIBEINVALID_CHANNEL_TYPEchannelName is not subscribed, but it is in connected state.
DBLIB_CHANNEL_UNSUBSCRIBEUNSUBSCRIBE_ALREADY_INITIATEDunsubscription to the channel is already initiated and hence the current unsubscribe command exited with exception.

Connect to Channel

Use-cases where application needs to only send channel messages and not interested to consume / receive channel messages, should connect to channel instead of subscribing to the channel.

connect()

The default method for connecting to a channel involves invoking the channel.connect function of your dataBridges object. Application cannot publish system events for which it has connected to.

try {
    const connected_channel = dbridge.channel.connect('mychannel');
} catch (err) {
    console.log(err.source, err.code, err.message);
}
ParameterRulesDescription
stringchannelName ORpvt:channelName ORprs:channelName ORsys:channelNamechannelName to which connection to be done.
Return TypeDescription
objectchannel object which events and related functions can be bound to.
Exceptions:
SourceCodeDescription
DBLIB_CHANNEL_CONNECTNETWORK_DISCONNECTEDConnection to dataBridges network is not active.
DBLIB_CHANNEL_CONNECTCHANNEL_ALREADY_CONNECTEDchannelName is already connected.
DBLIB_CHANNEL_CONNECTINVALID_CHANNELNAMEApplicable for below conditions1. channelName is not defined.2. channelName validation error, typeof() channelName is not type string3. channelName validation error, length of channelName greater than 644. channelName validation error, channelName fails a-zA-Z0-9\.:_- validation.5. if channelName contains : and first token is not pvt,prs,sys

disconnect()

To disconnect from a connected channel, invoke the disconnect function of your dataBridges object. disconnect cannot be done on channel object.

try {
    dbridge.channel.disconnect('mychannel');
} catch (err) {
    console.log(err.source, err.code, err.message);
}
ParameterRulesDescription
stringchannelName ORpvt:channelName ORprs:channelName ORsys:channelNamechannelName to which disconnection to be done.
Return TypeDescription
NA
Exceptions:
SourceCodeDescription
DBLIB_CHANNEL_DISCONNECTNETWORK_DISCONNECTEDConnection to dataBridges network is not active.
DBLIB_CHANNEL_DISCONNECTDISCONNECT_ALREADY_INITIATEDdisconnect to the channel is already initiated and hence the current disconnect command exited with exception.
DBLIB_CHANNEL_DISCONNECTINVALID_CHANNELchannelName is not connected.
DBLIB_CHANNEL_DISCONNECTINVALID_CHANNEL_TYPEchannelName is not connected, but it is in subscribed state.

Channel Information

isOnline()

dBridgeObject as well as channelObject provides a function to check if the channel is online. The best practice is to check the channel is online before publishing any message.

const mychannel_isonline = dbridge.channel.isOnline('mychannel');
const mychannel_isonline = subscribed_channel.isOnline(); 
ParameterRulesDescription
stringchannelName ORpvt:channelName ORprs:channelName ORsys:channelNamechannelName
Return ValuesDescription
booleanIs the current status of channel online or offline.

list()

dBridgeObject provides a function to get list of successfully subscribed or connected channel.

const channels = dbridge.channel.list();
#=> [{"name":  "mychannel" , "type": "subscribed/connect" ,  "isonline": true/false }];
Return TypeDescription
array of dictArray of channels subscribed or connected.

Dictionary contains below information.

KeyDescription
name(string) channelName of subscribed or connected channel.
type(string) subscribed or connected
isonline(boolean) Is the current status of channel online or offline.

getChannelName()

channelObject provides a function to get the channelName.

const chName = channelobject.getChannelName() 
Return TypeDescription
stringchannelName of subscribed or connected channel.

Publish to Channel

Publish event-message using the publish function on an instance of the channel object.

A message is linked to an event and hence event-message. dataBridges allows you to bind to various events to create rich event driven processing flows

publish()

The default method for publishing to a channel involves invoking the channel.publish function of your channelObject.

try {
    channelObject.publish(event, payload, seqno);
} catch (err) {
    console.log(err.source, err.code, err.message);
}

// Best practice is to check the channel is online before publishing any message.
if (channelObject.isOnline()) {
    try {
        channelObject.publish(event, payload, seqno);
    } catch (err) {
        console.log(err.source, err.code, err.message);
    }
}
ParameterDescription
event(string) event Name to which the message to be sent. event Name cannot start with dbridges:
payload(string) Payload to be sent with the event.
seqno(string) optional Message sequence number. This is optional parameter. seqno can be used by applications to manage message queue processing by the subscribers.
Return ValuesDescription
NA
Exceptions:
SourceCodeDescription
DBLIB_CHANNEL_PUBLISHINVALID_SUBJECTApplicable for below conditions1. event validation error, typeof() event is not type string2. event validation error, event is not defined
DBLIB_CHANNEL_PUBLISHNETWORK_DISCONNECTEDConnection to dataBridges network is not active.

Binding to events

A message is linked to an event and hence event-message. dataBridges allows you to bind to various events to create rich event processing flows. An application needs to bind to event to process the received message.

You can use the following methods either on a channelObject, to bind to events on a particular channel; or on the dbridgeObject, to bind to events on all subscribed channels simultaneously.

bind and unbind

Bind to "event" on channel: payload and metadata is received.

//  Binding to channel events on channelObject using Anonymous function.
try {
    channelObject.bind('eventName',  (payload, metadata) => {
        console.log(payload, metadata);
    });
} catch(err){
     console.log(err.source, err.code, err.message);
}

// Binding to channel events on dbridgeObject  using Anonymous function.
try {
    dbridge.channel.bind('eventName', (payload, metadata) => {
    	console.log(payload, metadata);
	});
} catch(err){
     console.log(err.source, err.code, err.message);
}

// Binding to channel events on channelObject using user function.
const myEventHandler = (payload, metadata) =>{
	console.log(payload, metadata);
};

try {
    dbridge.channel.bind('eventName', myEventHandler);
} catch(err){
     console.log(err.source, err.code, err.message);
}
ParameterDescription
event(string) event Name to which binding to be done.
Callback parameters
payload:

(string) Payload data sent by the publisher.

metadata (dict):
{
    "channelname": "channelName" , 		// (string) channelName to which subscription is done.
    "eventname": "event",				// (string) eventName 
    "sourcesysid": "", 					// (string) Sender system identity, applicable only for presence or system channel.
    "sqnum": "1",						// (string) user defined, sent during publish function.
    "sessionid": "", 					// @Pradeep not applicable for client library
    "intime": 1645554960732  			// (string) @pradeep EPOC time when the event was received by dataBridges router for processing.
}
Exceptions:
SourceCodeDescription
DBLIB_CONNECT_BINDINVALID_EVENTNAMEeventName cannot be blank or null.
DBLIB_CONNECT_BINDINVALID_CALLBACKIf "callback function" is not declared or typeof() variable defined is not a "function".
DBLIB_CHANNEL_CONNECTINVALID_CHANNEL_TYPE_BINDINGInvalid Event name. This binding is not allowed in channel.connect.

Unbind behavior varies depending on which parameters you provide it with. For example:

// Remove just `handler` of the `event` in the subscribed/connected channel 
channelObject.unbind('eventName',handler);

// Remove all `handler` of the `event` in the subscribed/connected channel
channelObject.unbind('eventName');

//Remove all handlers for the all event in the subscribed/connected channel
channelObject.unbind();

// Remove `handler` of the `event` for all events across all subscribed/connected channels
dbridge.channel.unbind('eventName',handler);

// Remove all handlers of the `event` for all events across all subscribed/connected channels
dbridge.channel.unbind('eventName');

// Remove all handlers for all events across all subscribed/connected channels
dbridge.channel.unbind();

bind_all and unbind_all

bind_all and unbind_all work much like bind and unbind, but instead of only firing callbacks on a specific event, they fire callbacks on any event, and provide that event in the metadata to the handler along with the payload. bind_all and unbind_all is not available for connected_channel i.e. dbridge.channel.connect() object.

//  Binding to all channel events on channelObject  
try {
    channelObject.bind_all((payload, metadata) => {
        console.log(payload, metadata);
    });
} catch(err){
     console.log(err.source, err.code, err.message);
}

// Binding to all channel events on dbridgeObject 
try {
    dbridge.channel.bind_all((payload, metadata) => {
    	console.log(payload, metadata);
	});
} catch(err){
     console.log(err.source, err.code, err.message);
}

Callback out parameter payload, metadata details are explained with each event below in this document.

Exceptions:
SourceCodeDescription
DBLIB_CONNECT_BINDINVALID_CALLBACKIf "callback function" is not declared or typeof() variable defined is not a "function".

unbind_all works similarly to unbind.

// Remove just `handler` across the channel 
channelObject.unbind_all(handler);

//Remove all handlers for the all event in the subscribed/connected channel
channelObject.unbind_all();

// Remove `handler` across the subscribed/connected channels
dbridge.channel.unbind_all(handler);

// Remove all handlers for all events across all subscribed/connected channels
dbridge.channel.unbind_all();

System events for channel object

There are a number of events which are triggered internally by the library, but can also be of use elsewhere. Below are the list of all events triggered by the library.

Below syntax is same for all system events.

//  Binding to systemevent on channelObject  
try {
    channelObject.bind('dbridges:subscribe.success', (payload, metadata) => {
        console.log( payload, metadata);
    });
} catch(err) {
     console.log(err.source, err.code, err.message);
}
//  Binding to systemevent on dbridgeObject  
try {
    dbridge.channel.bind('dbridges:subscribe.success', (payload, metadata) => {
        console.log( payload, metadata);
    });
} catch(err) {
     console.log(err.source, err.code, err.message);
}

dbridges:subscribe.success

Callback parameters
payload:

null

metadata (dict):
{
    "channelname": "channelName" , 			// (string) channelName to which subscription is done.
    "eventname": "dbridges:subscribe.success",// (string) eventName 
    "sourcesysid": "", 					// (string) Sender system identity, applicable only for presence or system channel.
    "sqnum": "1",						// (string) user defined, sent during publish function.
    "sessionid": "", 					// (string) @pradeep Not applicable for client library
    "intime": 1645554960732  			// (string) @pradeep  EPOC time when the event was received by dataBridges router for processing.
}

dbridges:subscribe.fail

Callback parameters
payload: (dberror object)
{
    "source": "dberror.Source" , 		// (string) Error source, Refer dberror: for details
    "code": "dberror.Code",				// (string) Error code, Refer dberror: for details
    "message": "" 						// (string) Error message if applicable.
}
metadata (dict):
{
    "channelname": "channelName" , 		// (string) channelName to which subscription is done.
    "eventname": "dbridges:subscribe.fail",// (string) eventName 
    "sourcesysid": "", 					// (string) 
    "sqnum": "",						// (string) 
    "sessionid": "", 					// (string) 
    "intime": 	  						// (string) 
}

dbridges:channel.online

Callback parameters
payload:

null

metadata (dict):
{
    "channelname": "channelName" , 		// (string) channelName to which subscription is done.
    "eventname": "dbridges:channel.online",// (string) eventName 
    "sourcesysid": "", 					// (string) 
    "sqnum": "",						// (string) 
    "sessionid": "", 					// (string) 
    "intime": 	  						// (string) 
}

dbridges:channel.offline

Callback parameters
payload:

null

metadata (dict):
{
    "channelname": "channelName" , 		// (string) channelName to which subscription is done.
    "eventname": "dbridges:channel.offline",// (string) eventName 
    "sourcesysid": "", 					// (string) 
    "sqnum": "",						// (string) 
    "sessionid": "", 					// (string) 
    "intime": 	  						// (string) 
}

dbridges:channel.removed

Callback parameters
payload:

null

metadata (dict):
{
    "channelname": "channelName" , 		// (string) channelName to which subscription is done.
    "eventname": "dbridges:channel.removed",// (string) eventName 
    "sourcesysid": "", 					// (string) 
    "sqnum": "",						// (string) 
    "sessionid": "", 					// (string) 
    "intime": 	  						// (string) 
}

dbridges:unsubscribe.success

Callback parameters
payload:

null

metadata (dict):
{
    "channelname": "channelName" , 		// (string) channelName to which subscription is done.
    "eventname": "dbridges:unsubscribe.success",// (string) eventName 
    "sourcesysid": "", 					// (string) 
    "sqnum": "",						// (string) 
    "sessionid": "", 					// (string) 
    "intime": 	  						// (string) 
}

dbridges:unsubscribe.fail

Callback parameters
payload: (dberror object)
{
    "source": "dberror.Source" , 		// (string) Error source, Refer dberror: for details
    "code": "dberror.Code",				// (string) Error code, Refer dberror: for details
    "message": "" 						// (string) Error message if applicable.
}
metadata (dict):
{
    "channelname": "channelName" , 		// (string) channelName to which subscription is done.
    "eventname": "dbridges:unsubscribe.fail",// (string) eventName 
    "sourcesysid": "", 					// (string) 
    "sqnum": "",						// (string) 
    "sessionid": "", 					// (string) 
    "intime": 	  						// (string) 
}

dbridges:resubscribe.success

Callback parameters
payload:

null

metadata (dict):
{
    "channelname": "channelName" , 		// (string) channelName to which subscription is done.
    "eventname": "dbridges:resubscribe.success",// (string) eventName 
    "sourcesysid": "", 					// (string) 
    "sqnum": "",						// (string) 
    "sessionid": "", 					// (string) 
    "intime": 	  						// (string) 
}

dbridges:resubscribe.fail

Callback parameters
payload: (dberror object)
{
    "source": "dberror.Source" , 		// (string) Error source, Refer dberror: for details
    "code": "dberror.Code",				// (string) Error code, Refer dberror: for details
    "message": "" 						// (string) Error message if applicable.
}
metadata (dict):
{
    "channelname": "channelName" , 		// (string) channelName to which subscription is done.
    "eventname": "dbridges:resubscribe.fail",// (string) eventName 
    "sourcesysid": "", 					// (string) 
    "sqnum": "",						// (string) 
    "sessionid": "", 					// (string) 
    "intime": 	  						// (string) 
}

dbridges:participant.joined

This will be triggered only for presence (prs:) and system (sys:) channel subscription.

Callback parameters
payload: (dict)
{
  "sessionid": NA, 	// @pradeep This is not applicable for client lib. This needs to be updated across client doc
  "libtype": "nodejs", 						// (string) Library Lang of the member who has subscribed/connected to channel
  "sourceipv4": "0.0.0.0", 					// (string) IPv4 of the member who has subscribed/connected to channel
  "sourceipv6": "::1", 						// (string) Not Applicable in current version.
  "sysinfo": '{"sysid":"nameofcaller"}' 	// (string) System Info of the member who has subscribed/connected to channel
}
metadata (dict):
{
    "channelname": "prs:channelName" , 		// (string) channelName to which subscription is done.
    "eventname": "dbridges:participant.joined",// (string) eventName 
    "sourcesysid": "nameofcaller", 			// (string) Sys id of the member who has subscribed/connected to channel
    "sqnum": null,							// (string) 
    "sessionid": NA, 	// @pradeep This is not applicable for client lib. This needs to be updated across client doc
    "intime": null	  						// (string) 
}

dbridges:participant.left

This will be triggered only for presence (prs:) and system (sys:) channel subscription.

Callback parameters
payload: (dict)
{
  "sessionid": NA, 	// @pradeep This is not applicable for client lib. This needs to be updated across client doc
  "libtype": "nodejs", 						// (string) Library Lang of the member who has subscribed/connected to channel
  "sourceipv4": "0.0.0.0", 					// (string) IPv4 of the member who has subscribed/connected to channel
  "sourceipv6": "::1", 						// (string) Not Applicable in current version.
  "sysinfo": '{"sysid":"nameofcaller"}' 	// (string) System Info of the member who has subscribed/connected to channel
}
metadata (dict):
{
    "channelname": "prs:channelName" , 		// (string) channelName to which subscription is done.
    "eventname": "dbridges:participant.left",// (string) eventName 
    "sourcesysid": "nameofcaller", 			// (string) Sys id of the member who has subscribed/connected to channel
    "sqnum": null,							// (string) 
    "sessionid": NA, 	// @pradeep This is not applicable for client lib. This needs to be updated across client doc
    "intime": null	  						// (string) 
}

dbridges:connect.success

Callback parameters
payload:

null

metadata (dict):
{
    "channelname": "channelName" , 		// (string) channelName to which subscription is done.
    "eventname": "dbridges:connect.success",// (string) eventName 
    "sourcesysid": "", 					// (string) 
    "sqnum": "",						// (string) 
    "sessionid": "", 					// (string) 
    "intime": 	  						// (string) 
}

dbridges:connect.fail

Callback parameters
payload: (dberror object)
{
    "source": "dberror.Source" , 		// (string) Error source, Refer dberror: for details
    "code": "dberror.Code",				// (string) Error code, Refer dberror: for details
    "message": "" 						// (string) Error message if applicable.
}
metadata (dict):
{
    "channelname": "channelName" , 		// (string) channelName to which subscription is done.
    "eventname": "dbridges:connect.fail",// (string) eventName 
    "sourcesysid": "", 					// (string) 
    "sqnum": "",						// (string) 
    "sessionid": "", 					// (string) 
    "intime": 	  						// (string) 
}

dbridges:disconnect.success

Callback parameters
payload:

null

metadata (dict):
{
    "channelname": "channelName" , 		// (string) channelName to which subscription is done.
    "eventname": "dbridges:disconnect.success",// (string) eventName 
    "sourcesysid": "", 					// (string) 
    "sqnum": "",						// (string) 
    "sessionid": "", 					// (string) 
    "intime": 	  						// (string) 
}

dbridges:disconnect.fail

Callback parameters
payload: (dberror object)
{
    "source": "dberror.Source" , 		// (string) Error source, Refer dberror: for details
    "code": "dberror.Code",				// (string) Error code, Refer dberror: for details
    "message": "" 						// (string) Error message if applicable.
}
metadata (dict):
{
    "channelname": "channelName" , 		// (string) channelName to which subscription is done.
    "eventname": "dbridges:disconnect.fail",// (string) eventName 
    "sourcesysid": "", 					// (string) 
    "sqnum": "",						// (string) 
    "sessionid": "", 					// (string) 
    "intime": 	  						// (string) 
}

dbridges:reconnect.success

Callback parameters
payload:

null

metadata (dict):
{
    "channelname": "channelName" , 		// (string) channelName to which subscription is done.
    "eventname": "dbridges:reconnect.success",// (string) eventName 
    "sourcesysid": "", 					// (string) 
    "sqnum": "",						// (string) 
    "sessionid": "", 					// (string) 
    "intime": 	  						// (string) 
}

dbridges:reconnect.fail

Callback parameters
payload: (dberror object)
{
    "source": "dberror.Source" , 		// (string) Error source, Refer dberror: for details
    "code": "dberror.Code",				// (string) Error code, Refer dberror: for details
    "message": "" 						// (string) Error message if applicable.
}
metadata (dict):
{
    "channelname": "channelName" , 		// (string) channelName to which subscription is done.
    "eventname": "dbridges:reconnect.fail",				// (string) eventName 
    "sourcesysid": "", 					// (string) 
    "sqnum": "",						// (string) 
    "sessionid": "", 					// (string) 
    "intime": 	  						// (string) 
}

System events - payload (dberror object) - details:

SourceCodeDescription
DBNET_CHANNEL_SUBSCRIBEERR_FAIL_ERRORdataBridges network encountered error when subscribing to the channel.
DBNET_CHANNEL_SUBSCRIBEERR_ACCESS_DENIEDdBrdige network reported access violation with access_token function during subscription of this channel. Verify if appKey has sufficient publish grants. Login to management portal. Select Edit Key option and check Allow key to publish messages to public channels is selected.
DBLIB_CHANNEL_SUBSCRIBEACCESS_TOKENdbridge.access_token function returned error.
DBNET_CHANNEL_UNSUBSCRIBEERR_FAIL_ERRORdataBridges network encountered error when unsubscribing to the channel.
DBNET_CHANNEL_UNSUBSCRIBEERR_ACCESS_DENIEDdataBridges network reported access violation with access_token function during unsubscribing of this channel. Verify if appKey has sufficient publish grants. Login to management portal. Select Edit Key option and check Allow key to publish messages to public channels is selected.
DBNET_CHANNEL_CONNECTERR_FAIL_ERRORdataBridges network encountered error when subscribing to the channel.
DBNET_CHANNEL_CONNECTERR_ACCESS_DENIEDdataBridges network reported access violation with access_token function during subscription of this channel. Verify if appKey has sufficient publish grants. Login to management portal. Select Edit Key option and check Allow key to publish messages to public channels is selected.
DBLIB_CHANNEL_CONNECTACCESS_TOKENdbridge.access_token function returned error.
DBLIB_CHANNEL_DISCONNECTERR_FAIL_ERRORdataBridges network encountered error when unsubscribing to the channel..
DBLIB_CHANNEL_DISCONNECTERR_ACCESS_DENIEDdataBridges network reported access violation with access_token function during unsubscribing of this channel. Verify if appKey has sufficient publish grants. Login to management portal. Select Edit Key option and check Allow key to publish messages to public channels is selected.

object: rpc (Remote Procedure Call)

rpc object exposes trust-safe properties, functions and events to provide reliable two-way messaging (request-response) between multiple endpoints allowing you to build sophisticated asynchronous interactions.

Concepts

  • Client application allows you to execute RPC functions exposed by server applications.
  • Client application is called CALLEE and the server application is called CALLER.
  • Client application will execute a remote function by passing IN.paramter, and a timeout
    • The server application's corresponding function will be invoked with the IN.parameter and it will respond with response() or exception() which will be delivered back to the CALLEE client application by dataBridges network completing the request-response communication.
  • Client application need not be aware about RPC servers identity and will only interact with RPC server namespace. The dataBridges network will intelligently route and load balance RPC call() to the RPC server application. The dataBridges network will automatically load balance multiple instance of server application exposing the same RPC endpoints.
  • Trust-tokens are supported by RPC as well. You will need to pass a trust-token when you connect to the access controlled RPC endpoint. A trust-token is a JWT document created using a combination of rpc server endpoint / server name + sessionid + app.secret.
    • Use your existing access control, authorization and session identification rule-set, process and methods to create a trust-token instructing the dataBridges router to accept the pvt: prs: rpc endpoint/server connection of from client application.
  • Trust-tokens allows you to enable secured, access controlled and compliance driven reliable two-way messaging (request-response) in your existing and new initiative applications.

Connect to Server

To use rpc functions, the application has to connect to the rpc endpoint/server. This is done using connect() function explained below.

connect()

The default method for connecting to a rpc endpoint/server involves invoking the rpc.connect function of your dataBridges object.

try {
    const rpcClient = dbridge.rpc.connect('rpcServer');
} catch (err) {
    console.log(err.source, err.code, err.message);
}
ParameterRulesDescription
stringserverName ORpvt:serverName ORprs:serverNameserverName to which connection to be done.
Return TypeDescription
objectrpcObject which events and related functions can be bound to.
Exceptions:
SourceCodeMessageDescription
DBLIB_RPC_CONNECTINVALID_SERVERNAMEApplicable for below conditions 1. serverName is not defined.2. serverName validation error, length of serverName greater than 643. serverName validation error, serverName fails a-zA-Z0-9\.:_- validation.4. serverName contains : and first token is not pvt,prs.
DBLIB_RPC_CONNECTNETWORK_DISCONNECTEDConnection to dataBridges network is not active.
DBNET_RPC_CONNECTERR_FAIL_ERRORdataBridges network encountered error during current operation.
DBNET_RPC_CONNECTERR_ACCESS_DENIEDdataBridges network reported access violation with access_token function during current operation.Verify if appKey has sufficient publish grants. Login to management portal. Select Edit Key option and check Allow key to access RPC functions is selected.

Server Information

isOnline()

rpcObject provides a function to check if the channel is online.

const rpcClient_isonline = rpcClient.isOnline(); 
ParameterRulesDescription
stringserverName ORpvt:serverName ORprs:serverNameserverName to which subscription to be done.
Return ValuesDescription
booleanIs the current status of server connection online or offline.

getServerName()

rpcObject provides a function to get the serverName.

const rpcServerName = rpcClient.getServerName() 
Return TypeDescription
stringserverName of connected rpcServer.

Execute Remote Procedure Call

call()

rpcObject call() function allows you to execute a remote function hosted by RPC endpoint / server using dataBridges server library

  • passing function parameter as parameter
  • while setting an time to live (TTL) for the response

The RPC call() functions supports multipart response (where the RPC function can send back multiple responses to a single RPC function call) along with exception routine.

rpcClient.call(functionName, parameter, ttlms, (response) => {
    console.log('multipart response',response)
}).then((response) => {
    console.log('end response', response);
}).catch((err) => {
    console.log('exception',err.source, err.code, err.message);
});

//Below example how a client can connect to a RPC endpoint / Server called mathServer and use add, multiply functions.
try {
    const myMathServer = dbridge.rpc.connect('mathServer');
} catch (err) {
    console.log(err.source, err.code, err.message);
}

let obj = { "num1":44.5, "num2":30};
let inparam = JSON.stringify(obj);

myMathServer.call(add, inparam, ttlms, (response) => {
}).then((response) => {
    console.log('response: ', JSON.parse(response));
}).catch((err) => {
    console.log('exception',err.source, err.code, err.message);
});

myMathServer.call(multiply, inparam, ttlms, (response) => {
}).then((response) => {
    console.log('response: ', JSON.parse(response));
}).catch((err) => {
    console.log('exception',err.source, err.code, err.message);
});
ParameterExpected ValueDescription
functionNamefunctionname(string) Function name as defined in rpc endpoint/ Server . Note - RPC endpoint / server can expose multiple rpc functions.
parameterfunction parameter(string) if multiple parameters to be passed, This can be done by putting it into array or json and stringify the object.
ttlms1000(integer) Time to live in millisecond, timeout value before the call() function throws error timeout.
Return ValuesDescription
stringMultipart or final response. in case of error, dberror object is returned.
Exceptions:
SourceCodeDescription
DBNET_RPC_CALLNETWORK_DISCONNECTEDConnection to dataBridges network is not active.
DBNET_RPC_CALLRESPONSE_TIMEOUTcall() response not received within defined ttlms.
DBLIB_RPC_CALLID_GENERATION_FAILEDInternal Library error.
DBNET_RPC_CALLERR_ACCESS_DENIEDdataBridges network reported access violation with access_token function during cur