Nirvana JavaScript : Creating a Session

To interact with a Nirvana Server, the first thing to do is configure and start a Nirvana Session object, which is effectively your logical and physical connection to one or more Nirvana Realms.

Configuring a Nirvana Session Object

A Nirvana Session object (called NirvanaSession) is pre-instantiated for you when your application includes nirvana.js.

The NirvanaSession object can be started using the NirvanaSession.start() function. This function takes a configuration object (specifying at least three required keys: applicationName, sessionName and username) as a parameter, as follows:

NirvanaSession.start({
	applicationName	: "myExampleApplication",
	sessionName 	: "myExampleSession",
	username 	: "testuser"
});

The configuration object may also contain many other optional keys, as in this example:

NirvanaSession.start({
	applicationName		: "myExampleApplication",
	sessionName 		: "myExampleSession",
	username 		: "testuser",
	protocolSelection	: ["websocket","streamingcomet","longpollcomet"],
	maxStreamLength		: 50000000,
	domain			: "mycompany.com",
	realmHosts		: [ "realmhost1", "realmhost2" ],
	libPath			: "/js/nirvana/lib",
	enableDataStreams	: true,
	webSocketPort		: 443,
	webSocketAttempts	: 1,
	secure			: true,
        enableDebug             : true,
	debugLevel		: 0,
	serverLogging		: true,
	verboseKeepalives	: false,
        sessionTimeout          : 2000,
        activeDelay             : 100,
        idleTimeOut             : 60000
});

Let's take a look at each of these required and optional keys:

  • Required Configuration Key/Values

    The configuration object must contain values for the following keys:

    • applicationName - a String representing the name of your application; this is used for server side logs
    • sessionName - a String representing the name of your session
    • username - a String representing the client username

    By default, JavaScript clients will use streaming Comet communications. It is possible to force such clients to use a Comet Ajax-based LongPolling mechanism instead, or to attempt to use Web Sockets if supported - see the examples below for details.

  • Optional Configuration Key/Values

    If your application is to be served from a different web server to the Nirvana Realm, or if you intend to make use of Nirvana's server clustering features, then you will need to specify the domain and an array of realmHosts too:

    • domain - the DNS domain in which all your realm servers exist (e.g. "mycompany.com")
    • realmHosts - an array of non-fully qualified hostnames of realm servers (i.e. minus the domain part in the hostname)

    Clients will need to access the Nirvana JavaScript libraries on each of the realms in the realmHosts array. If the libraries are hosted in the same path as they are on the primary front-end webserver, then they will be located automatically. If they are located in a different path, however, you will need to specify the correct path using the following key:

    • libPath - the path where nirvana.js can be found on the realm servers (e.g. "/js/nirvana/lib")

    Clients may be located behind proxy servers that place limits on the amount of data transfered before breaking a connection. By default, streaming Comet (non-LongPoll) clients will attempt to receive 50,000,000 bytes of data before resetting their connection. This may be too large for a particular proxy configuration, so may be set explicitly if required:

    • maxStreamLength - for streaming Comet connections only: max content-length in bytes for data sent before a session reset

    Clients may optionally act as DataStreams, and receive information from DataGroups. If this behaviour is not required, it can be disabled so that resources on the server are not unnecessarily allocated:

    • enableDataStreams - true or false; determines whether the client registers with the server as a DataStream

    Clients which attempt to communicate using LongPoll can specify the delay between polls to the server by setting the following two parameters:

    • activeDelay - The time to wait between reissuing a poll while receiving events or callbacks from the server
    • idleTimeOut - The length of time to wait before reissuing a poll while no active communication is taking place between client and server

    Browsers which support HTML5 Web Sockets can attempt to use WebSocket based communications instead of Comet (falling back to Comet in the event of any problem):

    • protocolSelection - ["websocket"]; The browser will attempt to use WebSockets. If it cannot use WebSocket and the protocolSelection array has another item, it will attempt to connection using that communication mode instead.
    • webSocketPort - the Nirvana Interface Port on which WebSocket communications is enabled. Note that we strongly recommend using an SSL interface, even if the libraries are served from a non-SSL http interface, since any intermediate proxy servers are quite likely to prevent WebSocket communication unless it is SSL encrypted.
    • webSocketAttempts - 1 or greater (optional); determines how many times browser will attempt to communicate via WebSockets before falling back to Comet
    • secure - true or false; determines whether WebSocket communications use SSL or plain HTTP

    Finally, various levels of debugging information is available to developers.

    For client side debugging, the library implements a debug(msgString) function which is invoked if debugging is enabled. Note that this function can be overriden by the developer if required:

    • enableDebug - enables debugging on the client
    • debugLevel - 0 to 9; specifies the granularity of debug messages. 0 is no debug output, 9 is verbose

    Clients can also be configured to generate additional information for server-side logging:

    • serverLogging - true or false; defaults to false and determines whether client communication is logged in the server's access.log
    • verboseKeepalives - true or false; defaults to false and determines whether the client regularly logs subscription information in the server's access.log

Starting a Nirvana Session

The above discussed parameters are used to define various mechanisms for connecting to the Nirvana Realm Server. The following examples demonstrate their use.

The Basics

As explained earlier, all invocations of the NirvanaSession.start() call must contain a configuration object with values for - at minimum - the keys applicationName, sessionName and username.

Session for Channels, Queues and P2P:

This example shows how to use a basic configuration object to start a NirvanaSession:

NirvanaSession.start({
	applicationName	: "myExampleApplication",
	sessionName 	: "myExampleSession",
	username 	: "testuser"
});

Session for DataGroups, Channels, Queues and P2P:

Configuring a session to become a DataStream, thus receiving events from any DataGroups of which it is a member, is easy:

NirvanaSession.start({
	applicationName  : "myExampleApplication",
	sessionName      : "myExampleSession",
	username         : "testuser",
	enableDataGroups : true
});

Comet and WebSocket Communication Modes

The following examples demonstrate how to start a NirvanaSession and control whether the client uses Streaming Comet, Long-Polling Comet or Web Sockets. For simplicity, these examples assume your application is deployed entirely on a Realm File Plugin:

Streaming Comet Session:

Streaming Comet is the default communication mode for a JavaScript client:

NirvanaSession.start({
	applicationName	: "myExampleApplication",
	sessionName 	: "myExampleSession",
	username 	: "testuser"
});

Long-Polling Comet Session:

NirvanaSession.start({
	applicationName	: "myExampleApplication",
	sessionName 	: "myExampleSession",
	username 	: "testuser",
	protocolSelection : ["longpollcomet"]
});

Web Socket Session (with Streaming Comet for browsers without WebSocket support):

NirvanaSession.start({
	applicationName	: "myExampleApplication",
	sessionName 	: "myExampleSession",
	username 	: "testuser",
	protocolSelection : ["websocket","streamingcomet"],
    	webSocketPort 	: 443,
    	secure		: true
});

Web Socket Session (with Long-Polling Comet for browsers without WebSocket support):

NirvanaSession.start({
	applicationName	: "myExampleApplication",
	sessionName 	: "myExampleSession",
	username 	: "testuser",
	protocolSelection : ["websocket","longpollcomet"],
	webSocketPort 	: 443,
	secure		: true,
});

Note that when using WebSocket, while specifying the webSocketPort and secure keys is optional, we strongly recommend they are used to configure the client to communicate via WebSockets to a Nirvana Interface that is SSL-encrypted and using the standard HTTPS port, 443. This will ensure that clients using arbitrary proxy infrastructure will have the greatest chance of successful WebSocket communication.

If WebSocket is being used in an environment where no client requests are proxied, then it is quite safe to use non-SSL encrypted WebSocket communication, typically to the same Nirvana Interface that hosts the file plugin from which the libraries are served. In this case, there would be no need to set the webSocketPort and secure keys.

Applications Deployed on a Third Party Web Server

The following example demonstrates how to start a NirvanaSession when your application is deployed on a third party web server, and when the Realm (at realmhost1.mydomain.com) is only used to host Nirvana JavaScript libraries and provide the HTTP/HTTPS interface for JavaScript communcations:

NirvanaSession.start({
	applicationName : "myExampleApplication",
	sessionName     : "myExampleSession",
	username        : "testuser",
	domain          : "mydomain.com",
	realmHosts      : [ "realmhost1" ]
});

For more information, please see Serving Applications from Another Webserver.

Applications Deployed across a Cluster of Nirvana Realms

The following example demonstrates how to configure a client to make use of multiple possible realms in a cluster (in this example, realmhost1.mydomain.com, realmhost2.mydomain.com and realmhost3.mydomain.com). It is identical to deploying an application on a third party web server, except for the addition of extra hosts in the realmNames array:

NirvanaSession.start({
        applicationName : "myExampleApplication",
        sessionName     : "myExampleSession",
        username        : "testuser",
	domain          : "mydomain.com",
	realmHosts      : [ "realmhost1", "realmhost2", "realmhost" ]
});

Since the configuration is very similar, you may find Serving Applications from Another Webserver worth a read.

NirvanaSession.onInit

When a Nirvana Session is successfully started following a call to NirvanaSession.start(), an asynchronous callback function, NirvanaSession.onInit(sessionID). will be fired. At this stage, it is possible to create NirvanaChannel objects, NirvanaQueue objects, nConsumeEvent objects and nEventProperties objects.

You should implement the Nirvana.onInit(sessionID) function, and include your application-specific business logic within it:

NirvanaSession.onInit = function(nirvanaSessionID) {
	// At this stage it is possible to subscribe to channels, queues or services, or publish events
}

NirvanaSession.onData

If a Nirvana Session is initialised with a configuration object specifying enableDataGroups : true, then whenever it receives an event from a DataGroup of which it has been assigned membership, the event will be passed as a parameter to the NirvanaSession.onData callback function.

You should, in this case, implement the Nirvana.onData(event) function, and include your application-specific business logic within it:

NirvanaSession.onData = function(event) {
	// process the event
}