kurento-jsonrpc
Advanced tools
Comparing version 6.13.0 to 6.14.0
198
Gruntfile.js
@@ -18,58 +18,80 @@ /* | ||
module.exports = function (grunt) { | ||
var DIST_DIR = "dist"; | ||
module.exports = function(grunt) | ||
{ | ||
var DIST_DIR = 'dist'; | ||
var pkg = grunt.file.readJSON("package.json"); | ||
var pkg = grunt.file.readJSON('package.json'); | ||
var bower = | ||
{ | ||
TOKEN: process.env.TOKEN, | ||
repository: 'git://github.com/Kurento/<%= pkg.name %>-bower.git' | ||
var bower = { | ||
TOKEN: process.env.TOKEN, | ||
repository: "git://github.com/Kurento/<%= pkg.name %>-bower.git" | ||
}; | ||
// Project configuration. | ||
grunt.initConfig( | ||
{ | ||
pkg: pkg, | ||
grunt.initConfig({ | ||
pkg: pkg, | ||
bower: bower, | ||
// Plugins configuration | ||
clean: | ||
{ | ||
generated_code: [DIST_DIR, 'src'], | ||
clean: { | ||
generated_code: [DIST_DIR, "src"], | ||
generated_doc: '<%= jsdoc.all.dest %>' | ||
generated_doc: "<%= jsdoc.all.dest %>" | ||
}, | ||
// Generate documentation | ||
jsdoc: | ||
{ | ||
all: | ||
{ | ||
src: ['README.md', 'lib/**/*.js', 'test/*.js'], | ||
dest: 'doc/jsdoc' | ||
jsdoc: { | ||
all: { | ||
src: ["README.md", "lib/**/*.js", "test/*.js"], | ||
dest: "doc/jsdoc" | ||
} | ||
}, | ||
jsbeautifier: { | ||
options: { | ||
js: { | ||
braceStyle: "collapse", | ||
breakChainedMethods: false, | ||
e4x: false, | ||
evalCode: false, | ||
indentChar: " ", | ||
indentLevel: 0, | ||
indentSize: 2, | ||
indentWithTabs: false, | ||
jslintHappy: true, | ||
keepArrayIndentation: false, | ||
keepFunctionIndentation: false, | ||
maxPreserveNewlines: 2, | ||
preserveNewlines: true, | ||
spaceBeforeConditional: true, | ||
spaceInParen: false, | ||
unescapeStrings: false, | ||
wrapLineLength: 80 | ||
} | ||
}, | ||
default: { | ||
src: ["lib/**/*.js", "*.js", "test/*.js", "testBrowser/*.js"] | ||
}, | ||
"git-pre-commit": { | ||
src: ["lib/**/*.js", "*.js", "test/*.js", "testBrowser/*.js"], | ||
options: { | ||
mode: "VERIFY_ONLY" | ||
} | ||
} | ||
}, | ||
// Generate browser versions and mapping debug file | ||
browserify: | ||
{ | ||
require: | ||
{ | ||
src: '<%= pkg.main %>', | ||
dest: DIST_DIR+'/<%= pkg.name %>_require.js' | ||
browserify: { | ||
require: { | ||
src: "<%= pkg.main %>", | ||
dest: DIST_DIR + "/<%= pkg.name %>_require.js" | ||
}, | ||
standalone: | ||
{ | ||
src: '<%= pkg.main %>', | ||
dest: DIST_DIR+'/<%= pkg.name %>.js', | ||
standalone: { | ||
src: "<%= pkg.main %>", | ||
dest: DIST_DIR + "/<%= pkg.name %>.js", | ||
options: | ||
{ | ||
exclude: ['ws', 'bufferutil' ], | ||
options: { | ||
exclude: ["ws", "bufferutil"], | ||
browserifyOptions: { | ||
debug: true, | ||
standalone: 'RpcBuilder' | ||
standalone: "RpcBuilder" | ||
} | ||
@@ -79,21 +101,21 @@ } | ||
'require minified': | ||
{ | ||
src: '<%= pkg.main %>', | ||
dest: DIST_DIR+'/<%= pkg.name %>_require.min.js', | ||
"require minified": { | ||
src: "<%= pkg.main %>", | ||
dest: DIST_DIR + "/<%= pkg.name %>_require.min.js", | ||
options: | ||
{ | ||
exclude: ['ws', 'bufferutil' ], | ||
options: { | ||
exclude: ["ws", "bufferutil"], | ||
debug: true, | ||
browserifyOptions: { | ||
debug: true, | ||
standalone: 'RpcBuilder' | ||
standalone: "RpcBuilder" | ||
}, | ||
plugin: [ | ||
['minifyify', | ||
{ | ||
compressPath: DIST_DIR, | ||
map: '<%= pkg.name %>.map' | ||
}] | ||
[ | ||
"minifyify", | ||
{ | ||
compressPath: DIST_DIR, | ||
map: "<%= pkg.name %>.map" | ||
} | ||
] | ||
] | ||
@@ -103,22 +125,22 @@ } | ||
'standalone minified': | ||
{ | ||
src: '<%= pkg.main %>', | ||
dest: DIST_DIR+'/<%= pkg.name %>.min.js', | ||
"standalone minified": { | ||
src: "<%= pkg.main %>", | ||
dest: DIST_DIR + "/<%= pkg.name %>.min.js", | ||
options: | ||
{ | ||
exclude: ['ws', 'bufferutil' ], | ||
options: { | ||
exclude: ["ws", "bufferutil"], | ||
debug: true, | ||
browserifyOptions: { | ||
debug: true, | ||
standalone: 'RpcBuilder' | ||
standalone: "RpcBuilder" | ||
}, | ||
plugin: [ | ||
['minifyify', | ||
{ | ||
compressPath: DIST_DIR, | ||
map: '<%= pkg.name %>.map', | ||
output: DIST_DIR+'/<%= pkg.name %>.map' | ||
}] | ||
[ | ||
"minifyify", | ||
{ | ||
compressPath: DIST_DIR, | ||
map: "<%= pkg.name %>.map", | ||
output: DIST_DIR + "/<%= pkg.name %>.map" | ||
} | ||
] | ||
] | ||
@@ -130,14 +152,17 @@ } | ||
// Generate bower.json file from package.json data | ||
sync: | ||
{ | ||
bower: | ||
{ | ||
options: | ||
{ | ||
sync: { | ||
bower: { | ||
options: { | ||
sync: [ | ||
'name', 'description', 'license', 'keywords', 'homepage', | ||
'repository' | ||
"name", | ||
"description", | ||
"license", | ||
"keywords", | ||
"homepage", | ||
"repository" | ||
], | ||
overrides: { | ||
authors: (pkg.author ? [pkg.author] : []).concat(pkg.contributors || []) | ||
authors: (pkg.author ? [pkg.author] : []).concat( | ||
pkg.contributors || [] | ||
) | ||
} | ||
@@ -149,10 +174,9 @@ } | ||
// Publish / update package info in Bower | ||
shell: | ||
{ | ||
shell: { | ||
bower: { | ||
command: [ | ||
'curl -X DELETE "https://bower.herokuapp.com/packages/<%= pkg.name %>?auth_token=<%= bower.TOKEN %>"', | ||
'node_modules/.bin/bower register <%= pkg.name %> <%= bower.repository %>', | ||
'node_modules/.bin/bower cache clean' | ||
].join('&&') | ||
"node_modules/.bin/bower register <%= pkg.name %> <%= bower.repository %>", | ||
"node_modules/.bin/bower cache clean" | ||
].join("&&") | ||
} | ||
@@ -163,11 +187,17 @@ } | ||
// Load plugins | ||
grunt.loadNpmTasks('grunt-browserify'); | ||
grunt.loadNpmTasks('grunt-contrib-clean'); | ||
grunt.loadNpmTasks('grunt-jsdoc'); | ||
grunt.loadNpmTasks('grunt-npm2bower-sync'); | ||
grunt.loadNpmTasks('grunt-shell'); | ||
grunt.loadNpmTasks("grunt-browserify"); | ||
grunt.loadNpmTasks("grunt-contrib-clean"); | ||
grunt.loadNpmTasks("grunt-jsbeautifier"); | ||
grunt.loadNpmTasks("grunt-jsdoc"); | ||
grunt.loadNpmTasks("grunt-npm2bower-sync"); | ||
grunt.loadNpmTasks("grunt-shell"); | ||
// Alias tasks | ||
grunt.registerTask('default', ['clean', 'jsdoc', 'browserify']); | ||
grunt.registerTask('bower', ['sync:bower', 'shell:bower']); | ||
grunt.registerTask("default", [ | ||
"clean", | ||
"jsdoc", | ||
"browserify", | ||
"jsbeautifier:git-pre-commit" | ||
]); | ||
grunt.registerTask("bower", ["sync:bower", "shell:bower"]); | ||
}; |
@@ -18,5 +18,4 @@ /* | ||
var JsonRpcClient = require('./jsonrpcclient'); | ||
var JsonRpcClient = require('./jsonrpcclient'); | ||
exports.JsonRpcClient = JsonRpcClient; | ||
exports.JsonRpcClient = JsonRpcClient; |
@@ -19,6 +19,7 @@ /* | ||
var RpcBuilder = require('../..'); | ||
var WebSocketWithReconnection = require('./transports/webSocketWithReconnection'); | ||
var WebSocketWithReconnection = require( | ||
'./transports/webSocketWithReconnection'); | ||
Date.now = Date.now || function() { | ||
return +new Date; | ||
Date.now = Date.now || function () { | ||
return +new Date; | ||
}; | ||
@@ -57,222 +58,231 @@ | ||
var self = this; | ||
var self = this; | ||
var wsConfig = configuration.ws; | ||
var wsConfig = configuration.ws; | ||
var notReconnectIfNumLessThan = -1; | ||
var notReconnectIfNumLessThan = -1; | ||
var pingNextNum = 0; | ||
var enabledPings = true; | ||
var pingPongStarted = false; | ||
var pingInterval; | ||
var pingNextNum = 0; | ||
var enabledPings = true; | ||
var pingPongStarted = false; | ||
var pingInterval; | ||
var status = DISCONNECTED; | ||
var status = DISCONNECTED; | ||
var onreconnecting = wsConfig.onreconnecting; | ||
var onreconnected = wsConfig.onreconnected; | ||
var onconnected = wsConfig.onconnected; | ||
var onerror = wsConfig.onerror; | ||
var onreconnecting = wsConfig.onreconnecting; | ||
var onreconnected = wsConfig.onreconnected; | ||
var onconnected = wsConfig.onconnected; | ||
var onerror = wsConfig.onerror; | ||
configuration.rpc.pull = function(params, request) { | ||
request.reply(null, "push"); | ||
configuration.rpc.pull = function (params, request) { | ||
request.reply(null, "push"); | ||
} | ||
wsConfig.onreconnecting = function () { | ||
Logger.debug("--------- ONRECONNECTING -----------"); | ||
if (status === RECONNECTING) { | ||
Logger.error( | ||
"Websocket already in RECONNECTING state when receiving a new ONRECONNECTING message. Ignoring it" | ||
); | ||
return; | ||
} | ||
wsConfig.onreconnecting = function() { | ||
Logger.debug("--------- ONRECONNECTING -----------"); | ||
if (status === RECONNECTING) { | ||
Logger.error("Websocket already in RECONNECTING state when receiving a new ONRECONNECTING message. Ignoring it"); | ||
return; | ||
} | ||
status = RECONNECTING; | ||
if (onreconnecting) { | ||
onreconnecting(); | ||
} | ||
} | ||
status = RECONNECTING; | ||
if (onreconnecting) { | ||
onreconnecting(); | ||
} | ||
wsConfig.onreconnected = function () { | ||
Logger.debug("--------- ONRECONNECTED -----------"); | ||
if (status === CONNECTED) { | ||
Logger.error( | ||
"Websocket already in CONNECTED state when receiving a new ONRECONNECTED message. Ignoring it" | ||
); | ||
return; | ||
} | ||
status = CONNECTED; | ||
wsConfig.onreconnected = function() { | ||
Logger.debug("--------- ONRECONNECTED -----------"); | ||
if (status === CONNECTED) { | ||
Logger.error("Websocket already in CONNECTED state when receiving a new ONRECONNECTED message. Ignoring it"); | ||
return; | ||
} | ||
status = CONNECTED; | ||
enabledPings = true; | ||
updateNotReconnectIfLessThan(); | ||
usePing(); | ||
enabledPings = true; | ||
updateNotReconnectIfLessThan(); | ||
usePing(); | ||
if (onreconnected) { | ||
onreconnected(); | ||
} | ||
} | ||
if (onreconnected) { | ||
onreconnected(); | ||
} | ||
wsConfig.onconnected = function () { | ||
Logger.debug("--------- ONCONNECTED -----------"); | ||
if (status === CONNECTED) { | ||
Logger.error( | ||
"Websocket already in CONNECTED state when receiving a new ONCONNECTED message. Ignoring it" | ||
); | ||
return; | ||
} | ||
status = CONNECTED; | ||
wsConfig.onconnected = function() { | ||
Logger.debug("--------- ONCONNECTED -----------"); | ||
if (status === CONNECTED) { | ||
Logger.error("Websocket already in CONNECTED state when receiving a new ONCONNECTED message. Ignoring it"); | ||
return; | ||
} | ||
status = CONNECTED; | ||
enabledPings = true; | ||
usePing(); | ||
enabledPings = true; | ||
usePing(); | ||
if (onconnected) { | ||
onconnected(); | ||
} | ||
if (onconnected) { | ||
onconnected(); | ||
} | ||
} | ||
wsConfig.onerror = function(error) { | ||
Logger.debug("--------- ONERROR -----------"); | ||
wsConfig.onerror = function (error) { | ||
Logger.debug("--------- ONERROR -----------"); | ||
status = DISCONNECTED; | ||
status = DISCONNECTED; | ||
if (onerror) { | ||
onerror(error); | ||
} | ||
if (onerror) { | ||
onerror(error); | ||
} | ||
} | ||
var ws = new WebSocketWithReconnection(wsConfig); | ||
var ws = new WebSocketWithReconnection(wsConfig); | ||
Logger.debug('Connecting websocket to URI: ' + wsConfig.uri); | ||
Logger.debug('Connecting websocket to URI: ' + wsConfig.uri); | ||
var rpcBuilderOptions = { | ||
request_timeout: configuration.rpc.requestTimeout, | ||
ping_request_timeout: configuration.rpc.heartbeatRequestTimeout | ||
}; | ||
var rpcBuilderOptions = { | ||
request_timeout: configuration.rpc.requestTimeout, | ||
ping_request_timeout: configuration.rpc.heartbeatRequestTimeout | ||
}; | ||
var rpc = new RpcBuilder(RpcBuilder.packers.JsonRPC, rpcBuilderOptions, ws, | ||
function(request) { | ||
var rpc = new RpcBuilder(RpcBuilder.packers.JsonRPC, rpcBuilderOptions, ws, | ||
function (request) { | ||
Logger.debug('Received request: ' + JSON.stringify(request)); | ||
Logger.debug('Received request: ' + JSON.stringify(request)); | ||
try { | ||
var func = configuration.rpc[request.method]; | ||
try { | ||
var func = configuration.rpc[request.method]; | ||
if (func === undefined) { | ||
Logger.error("Method " + request.method + " not registered in client"); | ||
} else { | ||
func(request.params, request); | ||
} | ||
} catch (err) { | ||
Logger.error('Exception processing request: ' + JSON.stringify(request)); | ||
Logger.error(err); | ||
} | ||
}); | ||
this.send = function(method, params, callback) { | ||
if (method !== 'ping') { | ||
Logger.debug('Request: method:' + method + " params:" + JSON.stringify(params)); | ||
if (func === undefined) { | ||
Logger.error("Method " + request.method + | ||
" not registered in client"); | ||
} else { | ||
func(request.params, request); | ||
} | ||
} catch (err) { | ||
Logger.error('Exception processing request: ' + JSON.stringify( | ||
request)); | ||
Logger.error(err); | ||
} | ||
}); | ||
var requestTime = Date.now(); | ||
rpc.encode(method, params, function(error, result) { | ||
if (error) { | ||
try { | ||
Logger.error("ERROR:" + error.message + " in Request: method:" + | ||
method + " params:" + JSON.stringify(params) + " request:" + | ||
error.request); | ||
if (error.data) { | ||
Logger.error("ERROR DATA:" + JSON.stringify(error.data)); | ||
} | ||
} catch (e) {} | ||
error.requestTime = requestTime; | ||
} | ||
if (callback) { | ||
if (result != undefined && result.value !== 'pong') { | ||
Logger.debug('Response: ' + JSON.stringify(result)); | ||
} | ||
callback(error, result); | ||
} | ||
}); | ||
this.send = function (method, params, callback) { | ||
if (method !== 'ping') { | ||
Logger.debug('Request: method:' + method + " params:" + JSON.stringify( | ||
params)); | ||
} | ||
function updateNotReconnectIfLessThan() { | ||
Logger.debug("notReconnectIfNumLessThan = " + pingNextNum + ' (old=' + | ||
notReconnectIfNumLessThan + ')'); | ||
notReconnectIfNumLessThan = pingNextNum; | ||
} | ||
var requestTime = Date.now(); | ||
function sendPing() { | ||
if (enabledPings) { | ||
var params = null; | ||
if (pingNextNum == 0 || pingNextNum == notReconnectIfNumLessThan) { | ||
params = { | ||
interval: configuration.heartbeat || PING_INTERVAL | ||
}; | ||
} | ||
pingNextNum++; | ||
self.send('ping', params, (function(pingNum) { | ||
return function(error, result) { | ||
if (error) { | ||
Logger.debug("Error in ping request #" + pingNum + " (" + | ||
error.message + ")"); | ||
if (pingNum > notReconnectIfNumLessThan) { | ||
enabledPings = false; | ||
updateNotReconnectIfLessThan(); | ||
Logger.debug("Server did not respond to ping message #" + | ||
pingNum + ". Reconnecting... "); | ||
ws.reconnectWs(); | ||
} | ||
} | ||
} | ||
})(pingNextNum)); | ||
} else { | ||
Logger.debug("Trying to send ping, but ping is not enabled"); | ||
rpc.encode(method, params, function (error, result) { | ||
if (error) { | ||
try { | ||
Logger.error("ERROR:" + error.message + " in Request: method:" + | ||
method + " params:" + JSON.stringify(params) + " request:" + | ||
error.request); | ||
if (error.data) { | ||
Logger.error("ERROR DATA:" + JSON.stringify(error.data)); | ||
} | ||
} catch (e) {} | ||
error.requestTime = requestTime; | ||
} | ||
if (callback) { | ||
if (result != undefined && result.value !== 'pong') { | ||
Logger.debug('Response: ' + JSON.stringify(result)); | ||
} | ||
} | ||
callback(error, result); | ||
} | ||
}); | ||
} | ||
/* | ||
* If configuration.hearbeat has any value, the ping-pong will work with the interval | ||
* of configuration.hearbeat | ||
*/ | ||
function usePing() { | ||
if (!pingPongStarted) { | ||
Logger.debug("Starting ping (if configured)") | ||
pingPongStarted = true; | ||
function updateNotReconnectIfLessThan() { | ||
Logger.debug("notReconnectIfNumLessThan = " + pingNextNum + ' (old=' + | ||
notReconnectIfNumLessThan + ')'); | ||
notReconnectIfNumLessThan = pingNextNum; | ||
} | ||
if (configuration.heartbeat != undefined) { | ||
pingInterval = setInterval(sendPing, configuration.heartbeat); | ||
sendPing(); | ||
function sendPing() { | ||
if (enabledPings) { | ||
var params = null; | ||
if (pingNextNum == 0 || pingNextNum == notReconnectIfNumLessThan) { | ||
params = { | ||
interval: configuration.heartbeat || PING_INTERVAL | ||
}; | ||
} | ||
pingNextNum++; | ||
self.send('ping', params, (function (pingNum) { | ||
return function (error, result) { | ||
if (error) { | ||
Logger.debug("Error in ping request #" + pingNum + " (" + | ||
error.message + ")"); | ||
if (pingNum > notReconnectIfNumLessThan) { | ||
enabledPings = false; | ||
updateNotReconnectIfLessThan(); | ||
Logger.debug("Server did not respond to ping message #" + | ||
pingNum + ". Reconnecting... "); | ||
ws.reconnectWs(); | ||
} | ||
} | ||
} | ||
})(pingNextNum)); | ||
} else { | ||
Logger.debug("Trying to send ping, but ping is not enabled"); | ||
} | ||
} | ||
this.close = function() { | ||
Logger.debug("Closing jsonRpcClient explicitly by client"); | ||
/* | ||
* If configuration.hearbeat has any value, the ping-pong will work with the interval | ||
* of configuration.hearbeat | ||
*/ | ||
function usePing() { | ||
if (!pingPongStarted) { | ||
Logger.debug("Starting ping (if configured)") | ||
pingPongStarted = true; | ||
if (pingInterval != undefined) { | ||
Logger.debug("Clearing ping interval"); | ||
clearInterval(pingInterval); | ||
} | ||
pingPongStarted = false; | ||
enabledPings = false; | ||
if (configuration.heartbeat != undefined) { | ||
pingInterval = setInterval(sendPing, configuration.heartbeat); | ||
sendPing(); | ||
} | ||
} | ||
} | ||
if (configuration.sendCloseMessage) { | ||
Logger.debug("Sending close message") | ||
this.send('closeSession', null, function(error, result) { | ||
if (error) { | ||
Logger.error("Error sending close message: " + JSON.stringify(error)); | ||
} | ||
ws.close(); | ||
}); | ||
} else { | ||
ws.close(); | ||
} | ||
this.close = function () { | ||
Logger.debug("Closing jsonRpcClient explicitly by client"); | ||
if (pingInterval != undefined) { | ||
Logger.debug("Clearing ping interval"); | ||
clearInterval(pingInterval); | ||
} | ||
pingPongStarted = false; | ||
enabledPings = false; | ||
// This method is only for testing | ||
this.forceClose = function(millis) { | ||
ws.forceClose(millis); | ||
if (configuration.sendCloseMessage) { | ||
Logger.debug("Sending close message") | ||
this.send('closeSession', null, function (error, result) { | ||
if (error) { | ||
Logger.error("Error sending close message: " + JSON.stringify( | ||
error)); | ||
} | ||
ws.close(); | ||
}); | ||
} else { | ||
ws.close(); | ||
} | ||
} | ||
this.reconnect = function() { | ||
ws.reconnectWs(); | ||
} | ||
// This method is only for testing | ||
this.forceClose = function (millis) { | ||
ws.forceClose(millis); | ||
} | ||
this.reconnect = function () { | ||
ws.reconnectWs(); | ||
} | ||
} | ||
module.exports = JsonRpcClient; |
@@ -18,5 +18,4 @@ /* | ||
var WebSocketWithReconnection = require('./webSocketWithReconnection'); | ||
var WebSocketWithReconnection = require('./webSocketWithReconnection'); | ||
exports.WebSocketWithReconnection = WebSocketWithReconnection; | ||
exports.WebSocketWithReconnection = WebSocketWithReconnection; |
@@ -31,5 +31,5 @@ /* | ||
if (!WebSocket && typeof window === 'undefined') { | ||
try { | ||
WebSocket = require('ws'); | ||
} catch (e) { } | ||
try { | ||
WebSocket = require('ws'); | ||
} catch (e) {} | ||
} | ||
@@ -59,186 +59,190 @@ | ||
var closing = false; | ||
var registerMessageHandler; | ||
var wsUri = config.uri; | ||
var useSockJS = config.useSockJS; | ||
var reconnecting = false; | ||
var closing = false; | ||
var registerMessageHandler; | ||
var wsUri = config.uri; | ||
var useSockJS = config.useSockJS; | ||
var reconnecting = false; | ||
var forcingDisconnection = false; | ||
var forcingDisconnection = false; | ||
var ws; | ||
var ws; | ||
if (useSockJS) { | ||
ws = new SockJS(wsUri); | ||
} else { | ||
ws = new WebSocket(wsUri); | ||
if (useSockJS) { | ||
ws = new SockJS(wsUri); | ||
} else { | ||
ws = new WebSocket(wsUri); | ||
} | ||
ws.onopen = function () { | ||
logConnected(ws, wsUri); | ||
if (config.onconnected) { | ||
config.onconnected(); | ||
} | ||
}; | ||
ws.onopen = function() { | ||
logConnected(ws, wsUri); | ||
if (config.onconnected) { | ||
config.onconnected(); | ||
} | ||
}; | ||
ws.onerror = function (error) { | ||
Logger.error("Could not connect to " + wsUri + | ||
" (invoking onerror if defined)", error); | ||
if (config.onerror) { | ||
config.onerror(error); | ||
} | ||
}; | ||
ws.onerror = function(error) { | ||
Logger.error("Could not connect to " + wsUri + " (invoking onerror if defined)", error); | ||
if (config.onerror) { | ||
config.onerror(error); | ||
} | ||
}; | ||
function logConnected(ws, wsUri) { | ||
try { | ||
Logger.debug("WebSocket connected to " + wsUri); | ||
} catch (e) { | ||
Logger.error(e); | ||
} | ||
} | ||
function logConnected(ws, wsUri) { | ||
try { | ||
Logger.debug("WebSocket connected to " + wsUri); | ||
} catch (e) { | ||
Logger.error(e); | ||
} | ||
var reconnectionOnClose = function () { | ||
if (ws.readyState === CLOSED) { | ||
if (closing) { | ||
Logger.debug("Connection closed by user"); | ||
} else { | ||
Logger.debug("Connection closed unexpectecly. Reconnecting..."); | ||
reconnectToSameUri(MAX_RETRIES, 1); | ||
} | ||
} else { | ||
Logger.debug("Close callback from previous websocket. Ignoring it"); | ||
} | ||
}; | ||
var reconnectionOnClose = function() { | ||
if (ws.readyState === CLOSED) { | ||
if (closing) { | ||
Logger.debug("Connection closed by user"); | ||
} else { | ||
Logger.debug("Connection closed unexpectecly. Reconnecting..."); | ||
reconnectToSameUri(MAX_RETRIES, 1); | ||
} | ||
} else { | ||
Logger.debug("Close callback from previous websocket. Ignoring it"); | ||
} | ||
}; | ||
ws.onclose = reconnectionOnClose; | ||
ws.onclose = reconnectionOnClose; | ||
function reconnectToSameUri(maxRetries, numRetries) { | ||
Logger.debug("reconnectToSameUri (attempt #" + numRetries + ", max=" + | ||
maxRetries + ")"); | ||
function reconnectToSameUri(maxRetries, numRetries) { | ||
Logger.debug("reconnectToSameUri (attempt #" + numRetries + ", max=" + maxRetries + ")"); | ||
if (numRetries === 1) { | ||
if (reconnecting) { | ||
Logger.warn( | ||
"Trying to reconnectToNewUri when reconnecting... Ignoring this reconnection." | ||
) | ||
return; | ||
} else { | ||
reconnecting = true; | ||
} | ||
if (numRetries === 1) { | ||
if (reconnecting) { | ||
Logger.warn("Trying to reconnectToNewUri when reconnecting... Ignoring this reconnection.") | ||
return; | ||
} else { | ||
reconnecting = true; | ||
} | ||
if (config.onreconnecting) { | ||
config.onreconnecting(); | ||
} | ||
} | ||
if (config.onreconnecting) { | ||
config.onreconnecting(); | ||
} | ||
} | ||
if (forcingDisconnection) { | ||
reconnectToNewUri(maxRetries, numRetries, wsUri); | ||
if (forcingDisconnection) { | ||
reconnectToNewUri(maxRetries, numRetries, wsUri); | ||
} else { | ||
if (config.newWsUriOnReconnection) { | ||
config.newWsUriOnReconnection(function (error, newWsUri) { | ||
} else { | ||
if (config.newWsUriOnReconnection) { | ||
config.newWsUriOnReconnection(function(error, newWsUri) { | ||
if (error) { | ||
Logger.debug(error); | ||
setTimeout(function() { | ||
reconnectToSameUri(maxRetries, numRetries + 1); | ||
}, RETRY_TIME_MS); | ||
} else { | ||
reconnectToNewUri(maxRetries, numRetries, newWsUri); | ||
} | ||
}) | ||
} else { | ||
reconnectToNewUri(maxRetries, numRetries, wsUri); | ||
} | ||
} | ||
if (error) { | ||
Logger.debug(error); | ||
setTimeout(function () { | ||
reconnectToSameUri(maxRetries, numRetries + 1); | ||
}, RETRY_TIME_MS); | ||
} else { | ||
reconnectToNewUri(maxRetries, numRetries, newWsUri); | ||
} | ||
}) | ||
} else { | ||
reconnectToNewUri(maxRetries, numRetries, wsUri); | ||
} | ||
} | ||
} | ||
// TODO Test retries. How to force not connection? | ||
function reconnectToNewUri(maxRetries, numRetries, reconnectWsUri) { | ||
Logger.debug("Reconnection attempt #" + numRetries); | ||
// TODO Test retries. How to force not connection? | ||
function reconnectToNewUri(maxRetries, numRetries, reconnectWsUri) { | ||
Logger.debug("Reconnection attempt #" + numRetries); | ||
ws.close(); | ||
ws.close(); | ||
wsUri = reconnectWsUri || wsUri; | ||
wsUri = reconnectWsUri || wsUri; | ||
var newWs; | ||
if (useSockJS) { | ||
newWs = new SockJS(wsUri); | ||
} else { | ||
newWs = new WebSocket(wsUri); | ||
} | ||
var newWs; | ||
if (useSockJS) { | ||
newWs = new SockJS(wsUri); | ||
} else { | ||
newWs = new WebSocket(wsUri); | ||
} | ||
newWs.onopen = function() { | ||
Logger.debug("Reconnected after " + numRetries + " attempts..."); | ||
logConnected(newWs, wsUri); | ||
reconnecting = false; | ||
registerMessageHandler(); | ||
if (config.onreconnected()) { | ||
config.onreconnected(); | ||
} | ||
newWs.onopen = function () { | ||
Logger.debug("Reconnected after " + numRetries + " attempts..."); | ||
logConnected(newWs, wsUri); | ||
reconnecting = false; | ||
registerMessageHandler(); | ||
if (config.onreconnected()) { | ||
config.onreconnected(); | ||
} | ||
newWs.onclose = reconnectionOnClose; | ||
}; | ||
newWs.onclose = reconnectionOnClose; | ||
}; | ||
var onErrorOrClose = function(error) { | ||
Logger.warn("Reconnection error: ", error); | ||
var onErrorOrClose = function (error) { | ||
Logger.warn("Reconnection error: ", error); | ||
if (numRetries === maxRetries) { | ||
if (config.ondisconnect) { | ||
config.ondisconnect(); | ||
} | ||
} else { | ||
setTimeout(function() { | ||
reconnectToSameUri(maxRetries, numRetries + 1); | ||
}, RETRY_TIME_MS); | ||
} | ||
}; | ||
if (numRetries === maxRetries) { | ||
if (config.ondisconnect) { | ||
config.ondisconnect(); | ||
} | ||
} else { | ||
setTimeout(function () { | ||
reconnectToSameUri(maxRetries, numRetries + 1); | ||
}, RETRY_TIME_MS); | ||
} | ||
}; | ||
newWs.onerror = onErrorOrClose; | ||
newWs.onerror = onErrorOrClose; | ||
ws = newWs; | ||
} | ||
ws = newWs; | ||
} | ||
this.close = function() { | ||
closing = true; | ||
ws.close(); | ||
}; | ||
this.close = function () { | ||
closing = true; | ||
ws.close(); | ||
}; | ||
// This method is only for testing | ||
this.forceClose = function (millis) { | ||
Logger.debug("Testing: Force WebSocket close"); | ||
// This method is only for testing | ||
this.forceClose = function(millis) { | ||
Logger.debug("Testing: Force WebSocket close"); | ||
if (millis) { | ||
Logger.debug("Testing: Change wsUri for " + millis + | ||
" millis to simulate net failure"); | ||
var goodWsUri = wsUri; | ||
wsUri = "wss://21.234.12.34.4:443/"; | ||
if (millis) { | ||
Logger.debug("Testing: Change wsUri for " + millis + " millis to simulate net failure"); | ||
var goodWsUri = wsUri; | ||
wsUri = "wss://21.234.12.34.4:443/"; | ||
forcingDisconnection = true; | ||
forcingDisconnection = true; | ||
setTimeout(function () { | ||
Logger.debug("Testing: Recover good wsUri " + goodWsUri); | ||
wsUri = goodWsUri; | ||
setTimeout(function() { | ||
Logger.debug("Testing: Recover good wsUri " + goodWsUri); | ||
wsUri = goodWsUri; | ||
forcingDisconnection = false; | ||
forcingDisconnection = false; | ||
}, millis); | ||
} | ||
}, millis); | ||
} | ||
ws.close(); | ||
}; | ||
ws.close(); | ||
}; | ||
this.reconnectWs = function () { | ||
Logger.debug("reconnectWs"); | ||
reconnectToSameUri(MAX_RETRIES, 1, wsUri); | ||
}; | ||
this.reconnectWs = function() { | ||
Logger.debug("reconnectWs"); | ||
reconnectToSameUri(MAX_RETRIES, 1, wsUri); | ||
}; | ||
this.send = function (message) { | ||
ws.send(message); | ||
}; | ||
this.send = function(message) { | ||
ws.send(message); | ||
this.addEventListener = function (type, callback) { | ||
registerMessageHandler = function () { | ||
ws.addEventListener(type, callback); | ||
}; | ||
this.addEventListener = function(type, callback) { | ||
registerMessageHandler = function() { | ||
ws.addEventListener(type, callback); | ||
}; | ||
registerMessageHandler(); | ||
}; | ||
registerMessageHandler(); | ||
}; | ||
} | ||
module.exports = WebSocketWithReconnection; |
481
lib/index.js
@@ -18,12 +18,7 @@ /* | ||
var defineProperty_IE8 = false | ||
if(Object.defineProperty) | ||
{ | ||
try | ||
{ | ||
if (Object.defineProperty) { | ||
try { | ||
Object.defineProperty({}, "x", {}); | ||
} | ||
catch(e) | ||
{ | ||
} catch (e) { | ||
defineProperty_IE8 = true | ||
@@ -35,18 +30,20 @@ } | ||
if (!Function.prototype.bind) { | ||
Function.prototype.bind = function(oThis) { | ||
Function.prototype.bind = function (oThis) { | ||
if (typeof this !== 'function') { | ||
// closest thing possible to the ECMAScript 5 | ||
// internal IsCallable function | ||
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); | ||
throw new TypeError( | ||
'Function.prototype.bind - what is trying to be bound is not callable' | ||
); | ||
} | ||
var aArgs = Array.prototype.slice.call(arguments, 1), | ||
fToBind = this, | ||
fNOP = function() {}, | ||
fBound = function() { | ||
return fToBind.apply(this instanceof fNOP && oThis | ||
? this | ||
: oThis, | ||
aArgs.concat(Array.prototype.slice.call(arguments))); | ||
}; | ||
var aArgs = Array.prototype.slice.call(arguments, 1), | ||
fToBind = this, | ||
fNOP = function () {}, | ||
fBound = function () { | ||
return fToBind.apply(this instanceof fNOP && oThis ? | ||
this : | ||
oThis, | ||
aArgs.concat(Array.prototype.slice.call(arguments))); | ||
}; | ||
@@ -60,3 +57,2 @@ fNOP.prototype = this.prototype; | ||
var EventEmitter = require('events').EventEmitter; | ||
@@ -69,17 +65,12 @@ | ||
var BASE_TIMEOUT = 5000; | ||
function unifyResponseMethods(responseMethods) { | ||
if (!responseMethods) return {}; | ||
function unifyResponseMethods(responseMethods) | ||
{ | ||
if(!responseMethods) return {}; | ||
for(var key in responseMethods) | ||
{ | ||
for (var key in responseMethods) { | ||
var value = responseMethods[key]; | ||
if(typeof value == 'string') | ||
responseMethods[key] = | ||
{ | ||
if (typeof value == 'string') | ||
responseMethods[key] = { | ||
response: value | ||
@@ -92,17 +83,17 @@ } | ||
function unifyTransport(transport) | ||
{ | ||
if(!transport) return; | ||
function unifyTransport(transport) { | ||
if (!transport) return; | ||
// Transport as a function | ||
if(transport instanceof Function) | ||
return {send: transport}; | ||
if (transport instanceof Function) | ||
return { | ||
send: transport | ||
}; | ||
// WebSocket & DataChannel | ||
if(transport.send instanceof Function) | ||
if (transport.send instanceof Function) | ||
return transport; | ||
// Message API (Inter-window & WebWorker) | ||
if(transport.postMessage instanceof Function) | ||
{ | ||
if (transport.postMessage instanceof Function) { | ||
transport.send = transport.postMessage; | ||
@@ -113,4 +104,3 @@ return transport; | ||
// Stream API | ||
if(transport.write instanceof Function) | ||
{ | ||
if (transport.write instanceof Function) { | ||
transport.send = transport.write; | ||
@@ -121,4 +111,4 @@ return transport; | ||
// Transports that only can receive messages, but not send | ||
if(transport.onmessage !== undefined) return; | ||
if(transport.pause instanceof Function) return; | ||
if (transport.onmessage !== undefined) return; | ||
if (transport.pause instanceof Function) return; | ||
@@ -128,3 +118,2 @@ throw new SyntaxError("Transport is not a function nor a valid object"); | ||
/** | ||
@@ -140,17 +129,18 @@ * Representation of a RPC notification | ||
*/ | ||
function RpcNotification(method, params) | ||
{ | ||
if(defineProperty_IE8) | ||
{ | ||
function RpcNotification(method, params) { | ||
if (defineProperty_IE8) { | ||
this.method = method | ||
this.params = params | ||
} else { | ||
Object.defineProperty(this, 'method', { | ||
value: method, | ||
enumerable: true | ||
}); | ||
Object.defineProperty(this, 'params', { | ||
value: params, | ||
enumerable: true | ||
}); | ||
} | ||
else | ||
{ | ||
Object.defineProperty(this, 'method', {value: method, enumerable: true}); | ||
Object.defineProperty(this, 'params', {value: params, enumerable: true}); | ||
} | ||
}; | ||
/** | ||
@@ -169,10 +159,9 @@ * @class | ||
*/ | ||
function RpcBuilder(packer, options, transport, onRequest) | ||
{ | ||
function RpcBuilder(packer, options, transport, onRequest) { | ||
var self = this; | ||
if(!packer) | ||
if (!packer) | ||
throw new SyntaxError('Packer is not defined'); | ||
if(!packer.pack || !packer.unpack) | ||
if (!packer.pack || !packer.unpack) | ||
throw new SyntaxError('Packer is invalid'); | ||
@@ -182,6 +171,4 @@ | ||
if(options instanceof Function) | ||
{ | ||
if(transport != undefined) | ||
if (options instanceof Function) { | ||
if (transport != undefined) | ||
throw new SyntaxError("There can't be parameters after onRequest"); | ||
@@ -191,8 +178,7 @@ | ||
transport = undefined; | ||
options = undefined; | ||
options = undefined; | ||
}; | ||
if(options && options.send instanceof Function) | ||
{ | ||
if(transport && !(transport instanceof Function)) | ||
if (options && options.send instanceof Function) { | ||
if (transport && !(transport instanceof Function)) | ||
throw new SyntaxError("Only a function can be after transport"); | ||
@@ -202,8 +188,7 @@ | ||
transport = options; | ||
options = undefined; | ||
options = undefined; | ||
}; | ||
if(transport instanceof Function) | ||
{ | ||
if(onRequest != undefined) | ||
if (transport instanceof Function) { | ||
if (onRequest != undefined) | ||
throw new SyntaxError("There can't be parameters after onRequest"); | ||
@@ -215,4 +200,4 @@ | ||
if(transport && transport.send instanceof Function) | ||
if(onRequest && !(onRequest instanceof Function)) | ||
if (transport && transport.send instanceof Function) | ||
if (onRequest && !(onRequest instanceof Function)) | ||
throw new SyntaxError("Only a function can be after transport"); | ||
@@ -222,37 +207,32 @@ | ||
EventEmitter.call(this); | ||
if(onRequest) | ||
if (onRequest) | ||
this.on('request', onRequest); | ||
if(defineProperty_IE8) | ||
if (defineProperty_IE8) | ||
this.peerID = options.peerID | ||
else | ||
Object.defineProperty(this, 'peerID', {value: options.peerID}); | ||
Object.defineProperty(this, 'peerID', { | ||
value: options.peerID | ||
}); | ||
var max_retries = options.max_retries || 0; | ||
function transportMessage(event) | ||
{ | ||
self.decode(event.data || event); | ||
function transportMessage(event) { | ||
self.decode(event.data || event.toString()); | ||
}; | ||
this.getTransport = function() | ||
{ | ||
this.getTransport = function () { | ||
return transport; | ||
} | ||
this.setTransport = function(value) | ||
{ | ||
this.setTransport = function (value) { | ||
// Remove listener from old transport | ||
if(transport) | ||
{ | ||
if (transport) { | ||
// W3C transports | ||
if(transport.removeEventListener) | ||
if (transport.removeEventListener) | ||
transport.removeEventListener('message', transportMessage); | ||
// Node.js Streams API | ||
else if(transport.removeListener) | ||
else if (transport.removeListener) | ||
transport.removeListener('data', transportMessage); | ||
@@ -262,10 +242,9 @@ }; | ||
// Set listener on new transport | ||
if(value) | ||
{ | ||
if (value) { | ||
// W3C transports | ||
if(value.addEventListener) | ||
if (value.addEventListener) | ||
value.addEventListener('message', transportMessage); | ||
// Node.js Streams API | ||
else if(value.addListener) | ||
else if (value.addListener) | ||
value.addListener('data', transportMessage); | ||
@@ -277,5 +256,4 @@ }; | ||
if(!defineProperty_IE8) | ||
Object.defineProperty(this, 'transport', | ||
{ | ||
if (!defineProperty_IE8) | ||
Object.defineProperty(this, 'transport', { | ||
get: this.getTransport.bind(this), | ||
@@ -287,12 +265,10 @@ set: this.setTransport.bind(this) | ||
var request_timeout = options.request_timeout || BASE_TIMEOUT; | ||
var request_timeout = options.request_timeout || BASE_TIMEOUT; | ||
var ping_request_timeout = options.ping_request_timeout || request_timeout; | ||
var response_timeout = options.response_timeout || BASE_TIMEOUT; | ||
var duplicates_timeout = options.duplicates_timeout || BASE_TIMEOUT; | ||
var response_timeout = options.response_timeout || BASE_TIMEOUT; | ||
var duplicates_timeout = options.duplicates_timeout || BASE_TIMEOUT; | ||
var requestID = 0; | ||
var requests = new Mapper(); | ||
var requests = new Mapper(); | ||
var responses = new Mapper(); | ||
@@ -303,17 +279,13 @@ var processedResponses = new Mapper(); | ||
/** | ||
* Store the response to prevent to process duplicate request later | ||
*/ | ||
function storeResponse(message, id, dest) | ||
{ | ||
var response = | ||
{ | ||
function storeResponse(message, id, dest) { | ||
var response = { | ||
message: message, | ||
/** Timeout to auto-clean old responses */ | ||
timeout: setTimeout(function() | ||
{ | ||
responses.remove(id, dest); | ||
}, | ||
response_timeout) | ||
timeout: setTimeout(function () { | ||
responses.remove(id, dest); | ||
}, | ||
response_timeout) | ||
}; | ||
@@ -327,9 +299,7 @@ | ||
*/ | ||
function storeProcessedResponse(ack, from) | ||
{ | ||
var timeout = setTimeout(function() | ||
{ | ||
processedResponses.remove(ack, from); | ||
}, | ||
duplicates_timeout); | ||
function storeProcessedResponse(ack, from) { | ||
var timeout = setTimeout(function () { | ||
processedResponses.remove(ack, from); | ||
}, | ||
duplicates_timeout); | ||
@@ -339,3 +309,2 @@ processedResponses.set(timeout, ack, from); | ||
/** | ||
@@ -354,18 +323,14 @@ * Representation of a RPC request | ||
*/ | ||
function RpcRequest(method, params, id, from, transport) | ||
{ | ||
function RpcRequest(method, params, id, from, transport) { | ||
RpcNotification.call(this, method, params); | ||
this.getTransport = function() | ||
{ | ||
this.getTransport = function () { | ||
return transport; | ||
} | ||
this.setTransport = function(value) | ||
{ | ||
this.setTransport = function (value) { | ||
transport = unifyTransport(value); | ||
} | ||
if(!defineProperty_IE8) | ||
Object.defineProperty(this, 'transport', | ||
{ | ||
if (!defineProperty_IE8) | ||
Object.defineProperty(this, 'transport', { | ||
get: this.getTransport.bind(this), | ||
@@ -380,9 +345,7 @@ set: this.setTransport.bind(this) | ||
*/ | ||
if(!(transport || self.getTransport())) | ||
{ | ||
if(defineProperty_IE8) | ||
if (!(transport || self.getTransport())) { | ||
if (defineProperty_IE8) | ||
this.duplicated = Boolean(response) | ||
else | ||
Object.defineProperty(this, 'duplicated', | ||
{ | ||
Object.defineProperty(this, 'duplicated', { | ||
value: Boolean(response) | ||
@@ -404,8 +367,7 @@ }); | ||
*/ | ||
this.reply = function(error, result, transport) | ||
{ | ||
this.reply = function (error, result, transport) { | ||
// Fix optional parameters | ||
if(error instanceof Function || error && error.send instanceof Function) | ||
{ | ||
if(result != undefined) | ||
if (error instanceof Function || error && error | ||
.send instanceof Function) { | ||
if (result != undefined) | ||
throw new SyntaxError("There can't be parameters after callback"); | ||
@@ -416,8 +378,5 @@ | ||
error = undefined; | ||
} | ||
else if(result instanceof Function | ||
|| result && result.send instanceof Function) | ||
{ | ||
if(transport != undefined) | ||
} else if (result instanceof Function || | ||
result && result.send instanceof Function) { | ||
if (transport != undefined) | ||
throw new SyntaxError("There can't be parameters after callback"); | ||
@@ -432,11 +391,10 @@ | ||
// Duplicated request, remove old response timeout | ||
if(response) | ||
if (response) | ||
clearTimeout(response.timeout); | ||
if(from != undefined) | ||
{ | ||
if(error) | ||
if (from != undefined) { | ||
if (error) | ||
error.dest = from; | ||
if(result) | ||
if (result) | ||
result.dest = from; | ||
@@ -448,7 +406,5 @@ }; | ||
// New request or overriden one, create new response with provided data | ||
if(error || result != undefined) | ||
{ | ||
if(self.peerID != undefined) | ||
{ | ||
if(error) | ||
if (error || result != undefined) { | ||
if (self.peerID != undefined) { | ||
if (error) | ||
error.from = self.peerID; | ||
@@ -460,18 +416,14 @@ else | ||
// Protocol indicates that responses has own request methods | ||
if(responseMethod) | ||
{ | ||
if(responseMethod.error == undefined && error) | ||
message = | ||
{ | ||
if (responseMethod) { | ||
if (responseMethod.error == undefined && error) | ||
message = { | ||
error: error | ||
}; | ||
else | ||
{ | ||
var method = error | ||
? responseMethod.error | ||
: responseMethod.response; | ||
else { | ||
var method = error ? | ||
responseMethod.error : | ||
responseMethod.response; | ||
message = | ||
{ | ||
message = { | ||
method: method, | ||
@@ -481,7 +433,5 @@ params: error || result | ||
} | ||
} | ||
else | ||
message = | ||
{ | ||
error: error, | ||
} else | ||
message = { | ||
error: error, | ||
result: result | ||
@@ -494,3 +444,3 @@ }; | ||
// Duplicate & not-overriden request, re-send old response | ||
else if(response) | ||
else if (response) | ||
message = response.message; | ||
@@ -500,3 +450,5 @@ | ||
else | ||
message = packer.pack({result: null}, id); | ||
message = packer.pack({ | ||
result: null | ||
}, id); | ||
@@ -509,3 +461,3 @@ // Store the response to prevent to process a duplicated request later | ||
if(transport) | ||
if (transport) | ||
return transport.send(message); | ||
@@ -518,7 +470,5 @@ | ||
function cancel(message) | ||
{ | ||
function cancel(message) { | ||
var key = message2Key[message]; | ||
if(!key) return; | ||
if (!key) return; | ||
@@ -528,3 +478,3 @@ delete message2Key[message]; | ||
var request = requests.pop(key.id, key.dest); | ||
if(!request) return; | ||
if (!request) return; | ||
@@ -542,17 +492,14 @@ clearTimeout(request.timeout); | ||
*/ | ||
this.cancel = function(message) | ||
{ | ||
if(message) return cancel(message); | ||
this.cancel = function (message) { | ||
if (message) return cancel(message); | ||
for(var message in message2Key) | ||
for (var message in message2Key) | ||
cancel(message); | ||
}; | ||
this.close = function() | ||
{ | ||
this.close = function () { | ||
// Prevent to receive new messages | ||
var transport = this.getTransport(); | ||
if(transport && transport.close) | ||
transport.close(); | ||
if (transport && transport.close) | ||
transport.close(); | ||
@@ -565,4 +512,3 @@ // Request & processed responses | ||
// Responses | ||
responses.forEach(function(response) | ||
{ | ||
responses.forEach(function (response) { | ||
clearTimeout(response.timeout); | ||
@@ -572,3 +518,2 @@ }); | ||
/** | ||
@@ -586,37 +531,28 @@ * Generates and encode a JsonRPC 2.0 message | ||
*/ | ||
this.encode = function(method, params, dest, transport, callback) | ||
{ | ||
this.encode = function (method, params, dest, transport, callback) { | ||
// Fix optional parameters | ||
if(params instanceof Function) | ||
{ | ||
if(dest != undefined) | ||
if (params instanceof Function) { | ||
if (dest != undefined) | ||
throw new SyntaxError("There can't be parameters after callback"); | ||
callback = params; | ||
callback = params; | ||
transport = undefined; | ||
dest = undefined; | ||
params = undefined; | ||
} | ||
else if(dest instanceof Function) | ||
{ | ||
if(transport != undefined) | ||
dest = undefined; | ||
params = undefined; | ||
} else if (dest instanceof Function) { | ||
if (transport != undefined) | ||
throw new SyntaxError("There can't be parameters after callback"); | ||
callback = dest; | ||
callback = dest; | ||
transport = undefined; | ||
dest = undefined; | ||
} | ||
else if(transport instanceof Function) | ||
{ | ||
if(callback != undefined) | ||
dest = undefined; | ||
} else if (transport instanceof Function) { | ||
if (callback != undefined) | ||
throw new SyntaxError("There can't be parameters after callback"); | ||
callback = transport; | ||
callback = transport; | ||
transport = undefined; | ||
}; | ||
if(self.peerID != undefined) | ||
{ | ||
if (self.peerID != undefined) { | ||
params = params || {}; | ||
@@ -627,4 +563,3 @@ | ||
if(dest != undefined) | ||
{ | ||
if (dest != undefined) { | ||
params = params || {}; | ||
@@ -636,4 +571,3 @@ | ||
// Encode message | ||
var message = | ||
{ | ||
var message = { | ||
method: method, | ||
@@ -643,4 +577,3 @@ params: params | ||
if(callback) | ||
{ | ||
if (callback) { | ||
var id = requestID++; | ||
@@ -651,4 +584,3 @@ var retried = 0; | ||
function dispatchCallback(error, result) | ||
{ | ||
function dispatchCallback(error, result) { | ||
self.cancel(message); | ||
@@ -659,6 +591,5 @@ | ||
var request = | ||
{ | ||
message: message, | ||
callback: dispatchCallback, | ||
var request = { | ||
message: message, | ||
callback: dispatchCallback, | ||
responseMethods: responseMethods[method] || {} | ||
@@ -669,11 +600,13 @@ }; | ||
function sendRequest(transport) | ||
{ | ||
function sendRequest(transport) { | ||
var rt = (method === 'ping' ? ping_request_timeout : request_timeout); | ||
request.timeout = setTimeout(timeout, rt*Math.pow(2, retried++)); | ||
message2Key[message] = {id: id, dest: dest}; | ||
request.timeout = setTimeout(timeout, rt * Math.pow(2, retried++)); | ||
message2Key[message] = { | ||
id: id, | ||
dest: dest | ||
}; | ||
requests.set(request, id, dest); | ||
transport = transport || encode_transport || self.getTransport(); | ||
if(transport) | ||
if (transport) | ||
return transport.send(message); | ||
@@ -684,7 +617,6 @@ | ||
function retry(transport) | ||
{ | ||
function retry(transport) { | ||
transport = unifyTransport(transport); | ||
console.warn(retried+' retry for request message:',message); | ||
console.warn(retried + ' retry for request message:', message); | ||
@@ -697,9 +629,8 @@ var timeout = processedResponses.pop(id, dest); | ||
function timeout() | ||
{ | ||
if(retried < max_retries) | ||
function timeout() { | ||
if (retried < max_retries) | ||
return retry(transport); | ||
var error = new Error('Request has timed out'); | ||
error.request = message; | ||
error.request = message; | ||
@@ -718,3 +649,3 @@ error.retry = retry; | ||
transport = transport || this.getTransport(); | ||
if(transport) | ||
if (transport) | ||
return transport.send(message); | ||
@@ -736,13 +667,9 @@ | ||
*/ | ||
this.decode = function(message, transport) | ||
{ | ||
if(!message) | ||
this.decode = function (message, transport) { | ||
if (!message) | ||
throw new TypeError("Message is not defined"); | ||
try | ||
{ | ||
try { | ||
message = packer.unpack(message); | ||
} | ||
catch(e) | ||
{ | ||
} catch (e) { | ||
// Ignore invalid messages | ||
@@ -752,4 +679,4 @@ return console.debug(e, message); | ||
var id = message.id; | ||
var ack = message.ack; | ||
var id = message.id; | ||
var ack = message.ack; | ||
var method = message.method; | ||
@@ -762,22 +689,18 @@ var params = message.params || {}; | ||
// Ignore messages send by us | ||
if(self.peerID != undefined && from == self.peerID) return; | ||
if (self.peerID != undefined && from == self.peerID) return; | ||
// Notification | ||
if(id == undefined && ack == undefined) | ||
{ | ||
if (id == undefined && ack == undefined) { | ||
var notification = new RpcNotification(method, params); | ||
if(self.emit('request', notification)) return; | ||
if (self.emit('request', notification)) return; | ||
return notification; | ||
}; | ||
function processRequest() | ||
{ | ||
function processRequest() { | ||
// If we have a transport and it's a duplicated request, reply inmediatly | ||
transport = unifyTransport(transport) || self.getTransport(); | ||
if(transport) | ||
{ | ||
if (transport) { | ||
var response = responses.get(id, from); | ||
if(response) | ||
if (response) | ||
return transport.send(response.message); | ||
@@ -789,13 +712,11 @@ }; | ||
if(self.emit('request', request)) return; | ||
if (self.emit('request', request)) return; | ||
return request; | ||
}; | ||
function processResponse(request, error, result) | ||
{ | ||
function processResponse(request, error, result) { | ||
request.callback(error, result); | ||
}; | ||
function duplicatedResponse(timeout) | ||
{ | ||
function duplicatedResponse(timeout) { | ||
console.warn("Response already processed", message); | ||
@@ -808,18 +729,14 @@ | ||
// Request, or response with own method | ||
if(method) | ||
{ | ||
if (method) { | ||
// Check if it's a response with own method | ||
if(dest == undefined || dest == self.peerID) | ||
{ | ||
if (dest == undefined || dest == self.peerID) { | ||
var request = requests.get(ack, from); | ||
if(request) | ||
{ | ||
if (request) { | ||
var responseMethods = request.responseMethods; | ||
if(method == responseMethods.error) | ||
if (method == responseMethods.error) | ||
return processResponse(request, params); | ||
if(method == responseMethods.response) | ||
if (method == responseMethods.response) | ||
return processResponse(request, null, params); | ||
@@ -831,3 +748,3 @@ | ||
var processed = processedResponses.get(ack, from); | ||
if(processed) | ||
if (processed) | ||
return duplicatedResponse(processed); | ||
@@ -840,18 +757,18 @@ } | ||
var error = message.error; | ||
var error = message.error; | ||
var result = message.result; | ||
// Ignore responses not send to us | ||
if(error && error.dest && error.dest != self.peerID) return; | ||
if(result && result.dest && result.dest != self.peerID) return; | ||
if (error && error.dest && error.dest != self.peerID) return; | ||
if (result && result.dest && result.dest != self.peerID) return; | ||
// Response | ||
var request = requests.get(ack, from); | ||
if(!request) | ||
{ | ||
if (!request) { | ||
var processed = processedResponses.get(ack, from); | ||
if(processed) | ||
if (processed) | ||
return duplicatedResponse(processed); | ||
return console.warn("No callback was defined for this message", message); | ||
return console.warn("No callback was defined for this message", | ||
message); | ||
}; | ||
@@ -865,6 +782,4 @@ | ||
RpcBuilder.RpcNotification = RpcNotification; | ||
module.exports = RpcBuilder; | ||
@@ -871,0 +786,0 @@ |
@@ -1,13 +0,9 @@ | ||
function Mapper() | ||
{ | ||
function Mapper() { | ||
var sources = {}; | ||
this.forEach = function(callback) | ||
{ | ||
for(var key in sources) | ||
{ | ||
this.forEach = function (callback) { | ||
for (var key in sources) { | ||
var source = sources[key]; | ||
for(var key2 in source) | ||
for (var key2 in source) | ||
callback(source[key2]); | ||
@@ -17,6 +13,5 @@ }; | ||
this.get = function(id, source) | ||
{ | ||
this.get = function (id, source) { | ||
var ids = sources[source]; | ||
if(ids == undefined) | ||
if (ids == undefined) | ||
return undefined; | ||
@@ -27,6 +22,5 @@ | ||
this.remove = function(id, source) | ||
{ | ||
this.remove = function (id, source) { | ||
var ids = sources[source]; | ||
if(ids == undefined) | ||
if (ids == undefined) | ||
return; | ||
@@ -37,3 +31,5 @@ | ||
// Check it's empty | ||
for(var i in ids){return false} | ||
for (var i in ids) { | ||
return false | ||
} | ||
@@ -43,9 +39,8 @@ delete sources[source]; | ||
this.set = function(value, id, source) | ||
{ | ||
if(value == undefined) | ||
this.set = function (value, id, source) { | ||
if (value == undefined) | ||
return this.remove(id, source); | ||
var ids = sources[source]; | ||
if(ids == undefined) | ||
if (ids == undefined) | ||
sources[source] = ids = {}; | ||
@@ -57,7 +52,5 @@ | ||
Mapper.prototype.pop = function(id, source) | ||
{ | ||
Mapper.prototype.pop = function (id, source) { | ||
var value = this.get(id, source); | ||
if(value == undefined) | ||
if (value == undefined) | ||
return undefined; | ||
@@ -70,3 +63,2 @@ | ||
module.exports = Mapper; |
var JsonRPC = require('./JsonRPC'); | ||
var XmlRPC = require('./XmlRPC'); | ||
var XmlRPC = require('./XmlRPC'); | ||
exports.JsonRPC = JsonRPC; | ||
exports.XmlRPC = XmlRPC; | ||
exports.XmlRPC = XmlRPC; |
@@ -13,6 +13,4 @@ /** | ||
*/ | ||
function pack(message, id) | ||
{ | ||
var result = | ||
{ | ||
function pack(message, id) { | ||
var result = { | ||
jsonrpc: "2.0" | ||
@@ -22,11 +20,10 @@ }; | ||
// Request | ||
if(message.method) | ||
{ | ||
if (message.method) { | ||
result.method = message.method; | ||
if(message.params) | ||
if (message.params) | ||
result.params = message.params; | ||
// Request is a notification | ||
if(id != undefined) | ||
if (id != undefined) | ||
result.id = id; | ||
@@ -36,12 +33,9 @@ } | ||
// Response | ||
else if(id != undefined) | ||
{ | ||
if(message.error) | ||
{ | ||
if(message.result !== undefined) | ||
else if (id != undefined) { | ||
if (message.error) { | ||
if (message.result !== undefined) | ||
throw new TypeError("Both result and error are defined"); | ||
result.error = message.error; | ||
} | ||
else if(message.result !== undefined) | ||
} else if (message.result !== undefined) | ||
result.result = message.result; | ||
@@ -66,7 +60,6 @@ else | ||
*/ | ||
function unpack(message) | ||
{ | ||
function unpack(message) { | ||
var result = message; | ||
if(typeof message === 'string' || message instanceof String) { | ||
if (typeof message === 'string' || message instanceof String) { | ||
result = JSON.parse(message); | ||
@@ -78,20 +71,20 @@ } | ||
var version = result.jsonrpc; | ||
if(version !== '2.0') | ||
throw new TypeError("Invalid JsonRPC version '" + version + "': " + message); | ||
if (version !== '2.0') | ||
throw new TypeError("Invalid JsonRPC version '" + version + "': " + | ||
message); | ||
// Response | ||
if(result.method == undefined) | ||
{ | ||
if(result.id == undefined) | ||
throw new TypeError("Invalid message: "+message); | ||
if (result.method == undefined) { | ||
if (result.id == undefined) | ||
throw new TypeError("Invalid message: " + message); | ||
var result_defined = result.result !== undefined; | ||
var error_defined = result.error !== undefined; | ||
var error_defined = result.error !== undefined; | ||
// Check only result or error is defined, not both or none | ||
if(result_defined && error_defined) | ||
throw new TypeError("Both result and error are defined: "+message); | ||
if (result_defined && error_defined) | ||
throw new TypeError("Both result and error are defined: " + message); | ||
if(!result_defined && !error_defined) | ||
throw new TypeError("No result or error is defined: "+message); | ||
if (!result_defined && !error_defined) | ||
throw new TypeError("No result or error is defined: " + message); | ||
@@ -106,4 +99,3 @@ result.ack = result.id; | ||
exports.pack = pack; | ||
exports.pack = pack; | ||
exports.unpack = unpack; |
@@ -1,13 +0,10 @@ | ||
function pack(message) | ||
{ | ||
function pack(message) { | ||
throw new TypeError("Not yet implemented"); | ||
}; | ||
function unpack(message) | ||
{ | ||
function unpack(message) { | ||
throw new TypeError("Not yet implemented"); | ||
}; | ||
exports.pack = pack; | ||
exports.pack = pack; | ||
exports.unpack = unpack; |
{ | ||
"name": "kurento-jsonrpc", | ||
"version": "6.13.0", | ||
"version": "6.14.0", | ||
"description": "Kurento RPC client library for Browser and Node.js", | ||
@@ -69,16 +69,17 @@ "keywords": [ | ||
"bower": "~1.8.8", | ||
"browserify": "~13.1.0", | ||
"coveralls": "~2.11.1", | ||
"eventtarget": "0.1.0", | ||
"grunt": "~1.0.1", | ||
"grunt-browserify": "~5.0.0", | ||
"grunt-browserify": "^5.3.0", | ||
"grunt-cli": "~1.2.0", | ||
"grunt-contrib-clean": "~1.0.0", | ||
"grunt-jsdoc": "~2.2.1", | ||
"grunt-jsbeautifier": "^0.2.10", | ||
"grunt-jsdoc": "^2.4.0", | ||
"grunt-npm2bower-sync": "^0.9.0", | ||
"grunt-shell": "^2.0.0", | ||
"jscoverage": "~0.6.0", | ||
"browserify": "~13.1.0", | ||
"minifyify": "~7.3.3", | ||
"nodeunit": "~0.10.2" | ||
"nodeunit": "^0.11.3" | ||
} | ||
} |
@@ -18,3 +18,2 @@ /* | ||
var nodeunit = require('nodeunit'); | ||
@@ -33,12 +32,12 @@ var EventTarget = require('eventtarget'); | ||
console.debug(err); | ||
throw(err); | ||
throw (err); | ||
}); | ||
function noop(error, result){}; | ||
function noop(error, result) {}; | ||
function connectCallback(){ | ||
function connectCallback() { | ||
connected = true; | ||
} | ||
function disconnectCallback(){ | ||
function disconnectCallback() { | ||
connected = false; | ||
@@ -51,6 +50,4 @@ } | ||
exports['encode JsonRPC 2.0'] = | ||
{ | ||
setUp: function(callback) | ||
{ | ||
exports['encode JsonRPC 2.0'] = { | ||
setUp: function (callback) { | ||
this.rpcBuilder = new RpcBuilder(packer); | ||
@@ -61,4 +58,3 @@ | ||
tearDown: function(callback) | ||
{ | ||
tearDown: function (callback) { | ||
this.rpcBuilder.close(); | ||
@@ -69,4 +65,3 @@ | ||
'notification': function(test) | ||
{ | ||
'notification': function (test) { | ||
test.expect(5); | ||
@@ -76,4 +71,3 @@ | ||
test.deepEqual(JSON.parse(notification), | ||
{ | ||
test.deepEqual(JSON.parse(notification), { | ||
jsonrpc: '2.0', | ||
@@ -95,4 +89,3 @@ method: METHOD | ||
'request': function(test) | ||
{ | ||
'request': function (test) { | ||
test.expect(5); | ||
@@ -102,4 +95,3 @@ | ||
test.deepEqual(JSON.parse(request), | ||
{ | ||
test.deepEqual(JSON.parse(request), { | ||
jsonrpc: '2.0', | ||
@@ -122,8 +114,6 @@ method: METHOD, | ||
'request timeout': function(test) | ||
{ | ||
'request timeout': function (test) { | ||
test.expect(2); | ||
var request = this.rpcBuilder.encode(METHOD, function(error, result) | ||
{ | ||
var request = this.rpcBuilder.encode(METHOD, function (error, result) { | ||
test.notEqual(error, undefined); | ||
@@ -136,4 +126,3 @@ test.deepEqual(error.request, request); | ||
'request timeout and retry': function(test) | ||
{ | ||
'request timeout and retry': function (test) { | ||
var self = this; | ||
@@ -145,6 +134,4 @@ | ||
var request = this.rpcBuilder.encode(METHOD, function(error, result) | ||
{ | ||
if(!gotError) | ||
{ | ||
var request = this.rpcBuilder.encode(METHOD, function (error, result) { | ||
if (!gotError) { | ||
gotError = true; | ||
@@ -165,6 +152,3 @@ | ||
self.rpcBuilder.decode(response); | ||
} | ||
else | ||
{ | ||
} else { | ||
test.equal(error, undefined); | ||
@@ -177,8 +161,6 @@ | ||
'cancel request': function(test) | ||
{ | ||
'cancel request': function (test) { | ||
test.expect(0); | ||
var request = this.rpcBuilder.encode(METHOD, function(error, result) | ||
{ | ||
var request = this.rpcBuilder.encode(METHOD, function (error, result) { | ||
test.ifError(error); | ||
@@ -189,10 +171,8 @@ }); | ||
setTimeout(function() | ||
{ | ||
setTimeout(function () { | ||
test.done(); | ||
}, 6*1000) | ||
}, 6 * 1000) | ||
}, | ||
'duplicated request': function(test) | ||
{ | ||
'duplicated request': function (test) { | ||
test.expect(3); | ||
@@ -218,4 +198,3 @@ | ||
'duplicated request with transport': function(test) | ||
{ | ||
'duplicated request with transport': function (test) { | ||
test.expect(2); | ||
@@ -231,4 +210,3 @@ | ||
var request2 = this.rpcBuilder.decode(request, function(reply2) | ||
{ | ||
var request2 = this.rpcBuilder.decode(request, function (reply2) { | ||
test.deepEqual(reply1, reply2); | ||
@@ -241,4 +219,3 @@ | ||
'override duplicated request': function(test) | ||
{ | ||
'override duplicated request': function (test) { | ||
test.expect(4); | ||
@@ -265,8 +242,6 @@ | ||
'response': function(test) | ||
{ | ||
'response': function (test) { | ||
test.expect(2); | ||
var request = this.rpcBuilder.encode(METHOD, function(error, result) | ||
{ | ||
var request = this.rpcBuilder.encode(METHOD, function (error, result) { | ||
test.equal(result, null); | ||
@@ -291,8 +266,6 @@ }); | ||
'duplicate response': function(test) | ||
{ | ||
'duplicate response': function (test) { | ||
test.expect(3); | ||
var request = this.rpcBuilder.encode(METHOD, function(error, result) | ||
{ | ||
var request = this.rpcBuilder.encode(METHOD, function (error, result) { | ||
test.equal(result, null); | ||
@@ -320,10 +293,10 @@ }); | ||
'request reply response': function(test) | ||
{ | ||
'request reply response': function (test) { | ||
test.expect(3); | ||
var value = {'asdf': 'qwert'}; | ||
var value = { | ||
'asdf': 'qwert' | ||
}; | ||
var request = this.rpcBuilder.encode(METHOD, function(error, result) | ||
{ | ||
var request = this.rpcBuilder.encode(METHOD, function (error, result) { | ||
test.deepEqual(result, value); | ||
@@ -338,4 +311,3 @@ }); | ||
// Test response message | ||
test.deepEqual(JSON.parse(response), | ||
{ | ||
test.deepEqual(JSON.parse(response), { | ||
jsonrpc: '2.0', | ||
@@ -354,4 +326,3 @@ result: value, | ||
'reply with transport': function(test) | ||
{ | ||
'reply with transport': function (test) { | ||
test.expect(4); | ||
@@ -361,6 +332,7 @@ | ||
var value = {'asdf': 'qwert'}; | ||
var value = { | ||
'asdf': 'qwert' | ||
}; | ||
var request = this.rpcBuilder.encode(METHOD, function(error, result) | ||
{ | ||
var request = this.rpcBuilder.encode(METHOD, function (error, result) { | ||
test.deepEqual(result, value); | ||
@@ -372,7 +344,5 @@ }); | ||
var response = request.reply(null, value, function(message) | ||
{ | ||
var response = request.reply(null, value, function (message) { | ||
// Test response message | ||
test.deepEqual(JSON.parse(message), | ||
{ | ||
test.deepEqual(JSON.parse(message), { | ||
jsonrpc: '2.0', | ||
@@ -395,4 +365,3 @@ result: value, | ||
'decode with transport': function(test) | ||
{ | ||
'decode with transport': function (test) { | ||
test.expect(4); | ||
@@ -402,6 +371,7 @@ | ||
var value = {'asdf': 'qwert'}; | ||
var value = { | ||
'asdf': 'qwert' | ||
}; | ||
var request = this.rpcBuilder.encode(METHOD, function(error, result) | ||
{ | ||
var request = this.rpcBuilder.encode(METHOD, function (error, result) { | ||
test.deepEqual(result, value); | ||
@@ -411,7 +381,5 @@ }); | ||
// Response request | ||
request = this.rpcBuilder.decode(request, function(message) | ||
{ | ||
request = this.rpcBuilder.decode(request, function (message) { | ||
// Test response message | ||
test.deepEqual(JSON.parse(message), | ||
{ | ||
test.deepEqual(JSON.parse(message), { | ||
jsonrpc: '2.0', | ||
@@ -436,4 +404,3 @@ result: value, | ||
'transport with message event': function(test) | ||
{ | ||
'transport with message event': function (test) { | ||
test.expect(2); | ||
@@ -443,28 +410,27 @@ | ||
var value = {'asdf': 'qwert'}; | ||
var value = { | ||
'asdf': 'qwert' | ||
}; | ||
var transport = new EventTarget; | ||
transport.onmessage = null; | ||
transport.send = function(message) | ||
{ | ||
message = JSON.parse(message); | ||
transport.onmessage = null; | ||
transport.send = function (message) { | ||
message = JSON.parse(message); | ||
var event = | ||
{ | ||
type: 'message', | ||
data: JSON.stringify( | ||
{ | ||
jsonrpc: '2.0', | ||
result: message.params, | ||
id: 0 | ||
}) | ||
}; | ||
var event = { | ||
type: 'message', | ||
data: JSON.stringify({ | ||
jsonrpc: '2.0', | ||
result: message.params, | ||
id: 0 | ||
}) | ||
}; | ||
this.dispatchEvent(event); | ||
}; | ||
this.dispatchEvent(event); | ||
}; | ||
this.rpcBuilder.transport = transport; | ||
var request = this.rpcBuilder.encode(METHOD, value, function(error, result) | ||
{ | ||
var request = this.rpcBuilder.encode(METHOD, value, function (error, | ||
result) { | ||
test.ifError(error); | ||
@@ -481,12 +447,10 @@ | ||
'request event': function(test) | ||
{ | ||
'request event': function (test) { | ||
test.expect(1); | ||
var transport = new EventTarget; | ||
transport.onmessage = null; | ||
transport.onmessage = null; | ||
this.rpcBuilder.transport = transport; | ||
this.rpcBuilder.on('request', function(request) | ||
{ | ||
this.rpcBuilder.on('request', function (request) { | ||
test.deepEqual(request.method, METHOD); | ||
@@ -497,7 +461,5 @@ | ||
var event = | ||
{ | ||
var event = { | ||
type: 'message', | ||
data: JSON.stringify( | ||
{ | ||
data: JSON.stringify({ | ||
jsonrpc: '2.0', | ||
@@ -509,3 +471,3 @@ method: METHOD | ||
}, | ||
// 'create JsonRpcClientWs with WS': function(test) | ||
@@ -512,0 +474,0 @@ // { |
var METHOD = 'test'; | ||
function noop(error, result) {}; | ||
function noop(error, result){}; | ||
function load() | ||
{ | ||
function load() { | ||
var packer = RpcBuilder.packers.JsonRPC; | ||
@@ -16,7 +11,7 @@ var JsonRpcClient = RpcBuilder.clients.JsonRpcClient; | ||
function connectCallback(){ | ||
connected = true; | ||
function connectCallback() { | ||
connected = true; | ||
} | ||
function disconnectCallback(){ | ||
function disconnectCallback() { | ||
connected = false; | ||
@@ -26,6 +21,4 @@ } | ||
nodeunit.run({ | ||
'encode JsonRPC 2.0': | ||
{ | ||
setUp: function(callback) | ||
{ | ||
'encode JsonRPC 2.0': { | ||
setUp: function (callback) { | ||
this.rpcBuilder = new RpcBuilder(packer); | ||
@@ -36,4 +29,3 @@ | ||
tearDown: function(callback) | ||
{ | ||
tearDown: function (callback) { | ||
this.rpcBuilder.close(); | ||
@@ -44,5 +36,3 @@ | ||
'notification': function(test) | ||
{ | ||
'notification': function (test) { | ||
test.expect(5); | ||
@@ -52,4 +42,3 @@ | ||
test.deepEqual(JSON.parse(notification), | ||
{ | ||
test.deepEqual(JSON.parse(notification), { | ||
jsonrpc: '2.0', | ||
@@ -71,4 +60,3 @@ method: METHOD | ||
'request': function(test) | ||
{ | ||
'request': function (test) { | ||
test.expect(5); | ||
@@ -78,4 +66,3 @@ | ||
test.deepEqual(JSON.parse(request), | ||
{ | ||
test.deepEqual(JSON.parse(request), { | ||
jsonrpc: '2.0', | ||
@@ -98,8 +85,7 @@ method: METHOD, | ||
'request timeout': function(test) | ||
{ | ||
'request timeout': function (test) { | ||
test.expect(2); | ||
var request = this.rpcBuilder.encode(METHOD, function(error, result) | ||
{ | ||
var request = this.rpcBuilder.encode(METHOD, function (error, | ||
result) { | ||
test.notEqual(error, undefined); | ||
@@ -112,4 +98,3 @@ test.deepEqual(error.request, request); | ||
'request timeout and retry': function(test) | ||
{ | ||
'request timeout and retry': function (test) { | ||
var self = this; | ||
@@ -121,6 +106,5 @@ | ||
var request = this.rpcBuilder.encode(METHOD, function(error, result) | ||
{ | ||
if(!gotError) | ||
{ | ||
var request = this.rpcBuilder.encode(METHOD, function (error, | ||
result) { | ||
if (!gotError) { | ||
gotError = true; | ||
@@ -141,6 +125,3 @@ | ||
self.rpcBuilder.decode(response); | ||
} | ||
else | ||
{ | ||
} else { | ||
test.equal(error, undefined); | ||
@@ -153,8 +134,7 @@ | ||
'cancel request': function(test) | ||
{ | ||
'cancel request': function (test) { | ||
test.expect(0); | ||
var request = this.rpcBuilder.encode(METHOD, function(error, result) | ||
{ | ||
var request = this.rpcBuilder.encode(METHOD, function (error, | ||
result) { | ||
test.ifError(error); | ||
@@ -165,10 +145,8 @@ }); | ||
setTimeout(function() | ||
{ | ||
setTimeout(function () { | ||
test.done(); | ||
}, 6*1000) | ||
}, 6 * 1000) | ||
}, | ||
'duplicated request': function(test) | ||
{ | ||
'duplicated request': function (test) { | ||
test.expect(3); | ||
@@ -194,4 +172,3 @@ | ||
'duplicated request with transport': function(test) | ||
{ | ||
'duplicated request with transport': function (test) { | ||
test.expect(2); | ||
@@ -207,4 +184,3 @@ | ||
var request2 = this.rpcBuilder.decode(request, function(reply2) | ||
{ | ||
var request2 = this.rpcBuilder.decode(request, function (reply2) { | ||
test.deepEqual(reply1, reply2); | ||
@@ -217,4 +193,3 @@ | ||
'override duplicated request': function(test) | ||
{ | ||
'override duplicated request': function (test) { | ||
test.expect(4); | ||
@@ -241,8 +216,7 @@ | ||
'response': function(test) | ||
{ | ||
'response': function (test) { | ||
test.expect(2); | ||
var request = this.rpcBuilder.encode(METHOD, function(error, result) | ||
{ | ||
var request = this.rpcBuilder.encode(METHOD, function (error, | ||
result) { | ||
test.equal(result, null); | ||
@@ -267,8 +241,7 @@ }); | ||
'duplicate response': function(test) | ||
{ | ||
'duplicate response': function (test) { | ||
test.expect(3); | ||
var request = this.rpcBuilder.encode(METHOD, function(error, result) | ||
{ | ||
var request = this.rpcBuilder.encode(METHOD, function (error, | ||
result) { | ||
test.equal(result, null); | ||
@@ -296,10 +269,11 @@ }); | ||
'request reply response': function(test) | ||
{ | ||
'request reply response': function (test) { | ||
test.expect(3); | ||
var value = {'asdf': 'qwert'}; | ||
var value = { | ||
'asdf': 'qwert' | ||
}; | ||
var request = this.rpcBuilder.encode(METHOD, function(error, result) | ||
{ | ||
var request = this.rpcBuilder.encode(METHOD, function (error, | ||
result) { | ||
test.deepEqual(result, value); | ||
@@ -314,4 +288,3 @@ }); | ||
// Test response message | ||
test.deepEqual(JSON.parse(response), | ||
{ | ||
test.deepEqual(JSON.parse(response), { | ||
jsonrpc: '2.0', | ||
@@ -330,4 +303,3 @@ result: value, | ||
'reply with transport': function(test) | ||
{ | ||
'reply with transport': function (test) { | ||
test.expect(4); | ||
@@ -337,6 +309,8 @@ | ||
var value = {'asdf': 'qwert'}; | ||
var value = { | ||
'asdf': 'qwert' | ||
}; | ||
var request = this.rpcBuilder.encode(METHOD, function(error, result) | ||
{ | ||
var request = this.rpcBuilder.encode(METHOD, function (error, | ||
result) { | ||
test.deepEqual(result, value); | ||
@@ -348,7 +322,5 @@ }); | ||
var response = request.reply(null, value, function(message) | ||
{ | ||
var response = request.reply(null, value, function (message) { | ||
// Test response message | ||
test.deepEqual(JSON.parse(message), | ||
{ | ||
test.deepEqual(JSON.parse(message), { | ||
jsonrpc: '2.0', | ||
@@ -371,4 +343,3 @@ result: value, | ||
'decode with transport': function(test) | ||
{ | ||
'decode with transport': function (test) { | ||
test.expect(4); | ||
@@ -378,6 +349,8 @@ | ||
var value = {'asdf': 'qwert'}; | ||
var value = { | ||
'asdf': 'qwert' | ||
}; | ||
var request = this.rpcBuilder.encode(METHOD, function(error, result) | ||
{ | ||
var request = this.rpcBuilder.encode(METHOD, function (error, | ||
result) { | ||
test.deepEqual(result, value); | ||
@@ -387,7 +360,5 @@ }); | ||
// Response request | ||
request = this.rpcBuilder.decode(request, function(message) | ||
{ | ||
request = this.rpcBuilder.decode(request, function (message) { | ||
// Test response message | ||
test.deepEqual(JSON.parse(message), | ||
{ | ||
test.deepEqual(JSON.parse(message), { | ||
jsonrpc: '2.0', | ||
@@ -412,4 +383,3 @@ result: value, | ||
'transport with message event': function(test) | ||
{ | ||
'transport with message event': function (test) { | ||
test.expect(2); | ||
@@ -419,28 +389,27 @@ | ||
var value = {'asdf': 'qwert'}; | ||
var value = { | ||
'asdf': 'qwert' | ||
}; | ||
var transport = new EventTarget; | ||
transport.onmessage = null; | ||
transport.send = function(message) | ||
{ | ||
message = JSON.parse(message); | ||
transport.onmessage = null; | ||
transport.send = function (message) { | ||
message = JSON.parse(message); | ||
var event = | ||
{ | ||
type: 'message', | ||
data: JSON.stringify( | ||
{ | ||
jsonrpc: '2.0', | ||
result: message.params, | ||
id: 0 | ||
}) | ||
}; | ||
var event = { | ||
type: 'message', | ||
data: JSON.stringify({ | ||
jsonrpc: '2.0', | ||
result: message.params, | ||
id: 0 | ||
}) | ||
}; | ||
this.dispatchEvent(event); | ||
}; | ||
this.dispatchEvent(event); | ||
}; | ||
this.rpcBuilder.setTransport(transport); | ||
var request = this.rpcBuilder.encode(METHOD, value, function(error, result) | ||
{ | ||
var request = this.rpcBuilder.encode(METHOD, value, function ( | ||
error, result) { | ||
test.ifError(error); | ||
@@ -457,12 +426,10 @@ | ||
'request event': function(test) | ||
{ | ||
'request event': function (test) { | ||
test.expect(1); | ||
var transport = new EventTarget; | ||
transport.onmessage = null; | ||
transport.onmessage = null; | ||
this.rpcBuilder.setTransport(transport); | ||
this.rpcBuilder.on('request', function(request) | ||
{ | ||
this.rpcBuilder.on('request', function (request) { | ||
test.deepEqual(request.method, METHOD); | ||
@@ -473,7 +440,5 @@ | ||
var event = | ||
{ | ||
var event = { | ||
type: 'message', | ||
data: JSON.stringify( | ||
{ | ||
data: JSON.stringify({ | ||
jsonrpc: '2.0', | ||
@@ -484,35 +449,32 @@ method: METHOD | ||
transport.dispatchEvent(event); | ||
} | ||
, | ||
}, | ||
'create JsonRpcClientWs with WS': function(test) | ||
{ | ||
test.expect(1); | ||
'create JsonRpcClientWs with WS': function (test) { | ||
test.expect(1); | ||
var configuration = { | ||
sendCloseMessage : false, | ||
ws : { | ||
uri : ws_uri, | ||
useSockJS: false, | ||
onconnected : connectCallback, | ||
ondisconnect : disconnectCallback, | ||
onreconnecting : disconnectCallback, | ||
onreconnected : connectCallback | ||
}, | ||
rpc : { | ||
requestTimeout : 15000 | ||
} | ||
}; | ||
var configuration = { | ||
sendCloseMessage: false, | ||
ws: { | ||
uri: ws_uri, | ||
useSockJS: false, | ||
onconnected: connectCallback, | ||
ondisconnect: disconnectCallback, | ||
onreconnecting: disconnectCallback, | ||
onreconnected: connectCallback | ||
}, | ||
rpc: { | ||
requestTimeout: 15000 | ||
} | ||
}; | ||
var jsonRpcClientWs = new JsonRpcClient(configuration); | ||
var jsonRpcClientWs = new JsonRpcClient(configuration); | ||
test.ok(jsonRpcClientWs instanceof JsonRpcClient); | ||
test.ok(jsonRpcClientWs instanceof JsonRpcClient); | ||
setTimeout(function() | ||
{ | ||
jsonRpcClientWs.close(); | ||
test.done(); | ||
}, 4*1000) | ||
setTimeout(function () { | ||
jsonRpcClientWs.close(); | ||
test.done(); | ||
}, 4 * 1000) | ||
} | ||
} | ||
} | ||
@@ -522,6 +484,5 @@ }); | ||
if(window.addEventListener) | ||
if (window.addEventListener) | ||
window.addEventListener('load', load, false); | ||
else if(window.attachEvent) | ||
else if (window.attachEvent) | ||
window.attachEvent('onload', load); |
91720
15
18
2045