openvidu/openvidu-browser/src/OpenViduInternal/KurentoUtils/kurento-jsonrpc/index.js

754 lines
19 KiB
JavaScript
Raw Normal View History

/*
* (C) Copyright 2014 Kurento (http://kurento.org/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
var defineProperty_IE8 = false
2021-03-22 12:14:38 +01:00
if (Object.defineProperty) {
try {
Object.defineProperty({}, "x", {});
2021-03-22 12:14:38 +01:00
} catch (e) {
defineProperty_IE8 = true
}
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
if (!Function.prototype.bind) {
2021-03-22 12:14:38 +01:00
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');
}
2021-03-22 12:14:38 +01:00
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)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
var EventEmitter = require('events').EventEmitter;
var inherits = require('inherits');
var packers = require('./packers');
var Mapper = require('./Mapper');
var BASE_TIMEOUT = 5000;
2021-03-22 12:14:38 +01:00
function unifyResponseMethods(responseMethods) {
if (!responseMethods) return {};
2021-03-22 12:14:38 +01:00
for (var key in responseMethods) {
var value = responseMethods[key];
2021-03-22 12:14:38 +01:00
if (typeof value == 'string')
responseMethods[key] = {
response: value
}
};
return responseMethods;
};
2021-03-22 12:14:38 +01:00
function unifyTransport(transport) {
if (!transport) return;
// Transport as a function
2021-03-22 12:14:38 +01:00
if (transport instanceof Function)
return {
send: transport
};
// WebSocket & DataChannel
2021-03-22 12:14:38 +01:00
if (transport.send instanceof Function)
return transport;
// Message API (Inter-window & WebWorker)
2021-03-22 12:14:38 +01:00
if (transport.postMessage instanceof Function) {
transport.send = transport.postMessage;
return transport;
}
// Stream API
2021-03-22 12:14:38 +01:00
if (transport.write instanceof Function) {
transport.send = transport.write;
return transport;
}
// Transports that only can receive messages, but not send
2021-03-22 12:14:38 +01:00
if (transport.onmessage !== undefined) return;
if (transport.pause instanceof Function) return;
throw new SyntaxError("Transport is not a function nor a valid object");
};
/**
* Representation of a RPC notification
*
* @class
*
* @constructor
*
* @param {String} method -method of the notification
* @param params - parameters of the notification
*/
2021-03-22 12:14:38 +01:00
function RpcNotification(method, params) {
if (defineProperty_IE8) {
this.method = method
this.params = params
2021-03-22 12:14:38 +01:00
} else {
Object.defineProperty(this, 'method', {
value: method,
enumerable: true
});
Object.defineProperty(this, 'params', {
value: params,
enumerable: true
});
}
};
/**
* @class
*
* @constructor
*
* @param {object} packer
*
* @param {object} [options]
*
* @param {object} [transport]
*
* @param {Function} [onRequest]
*/
2021-03-22 12:14:38 +01:00
function RpcBuilder(packer, options, transport, onRequest) {
var self = this;
2021-03-22 12:14:38 +01:00
if (!packer)
throw new SyntaxError('Packer is not defined');
2021-03-22 12:14:38 +01:00
if (!packer.pack || !packer.unpack)
throw new SyntaxError('Packer is invalid');
var responseMethods = unifyResponseMethods(packer.responseMethods);
2021-03-22 12:14:38 +01:00
if (options instanceof Function) {
if (transport != undefined)
throw new SyntaxError("There can't be parameters after onRequest");
onRequest = options;
transport = undefined;
2021-03-22 12:14:38 +01:00
options = undefined;
};
2021-03-22 12:14:38 +01:00
if (options && options.send instanceof Function) {
if (transport && !(transport instanceof Function))
throw new SyntaxError("Only a function can be after transport");
onRequest = transport;
transport = options;
2021-03-22 12:14:38 +01:00
options = undefined;
};
2021-03-22 12:14:38 +01:00
if (transport instanceof Function) {
if (onRequest != undefined)
throw new SyntaxError("There can't be parameters after onRequest");
onRequest = transport;
transport = undefined;
};
2021-03-22 12:14:38 +01:00
if (transport && transport.send instanceof Function)
if (onRequest && !(onRequest instanceof Function))
throw new SyntaxError("Only a function can be after transport");
options = options || {};
EventEmitter.call(this);
2021-03-22 12:14:38 +01:00
if (onRequest)
this.on('request', onRequest);
2021-03-22 12:14:38 +01:00
if (defineProperty_IE8)
this.peerID = options.peerID
else
2021-03-22 12:14:38 +01:00
Object.defineProperty(this, 'peerID', {
value: options.peerID
});
var max_retries = options.max_retries || 0;
2021-03-22 12:14:38 +01:00
function transportMessage(event) {
self.decode(event.data || event);
};
2021-03-22 12:14:38 +01:00
this.getTransport = function () {
return transport;
}
2021-03-22 12:14:38 +01:00
this.setTransport = function (value) {
// Remove listener from old transport
2021-03-22 12:14:38 +01:00
if (transport) {
// W3C transports
2021-03-22 12:14:38 +01:00
if (transport.removeEventListener)
transport.removeEventListener('message', transportMessage);
// Node.js Streams API
2021-03-22 12:14:38 +01:00
else if (transport.removeListener)
transport.removeListener('data', transportMessage);
};
// Set listener on new transport
2021-03-22 12:14:38 +01:00
if (value) {
// W3C transports
2021-03-22 12:14:38 +01:00
if (value.addEventListener)
value.addEventListener('message', transportMessage);
// Node.js Streams API
2021-03-22 12:14:38 +01:00
else if (value.addListener)
value.addListener('data', transportMessage);
};
transport = unifyTransport(value);
}
2021-03-22 12:14:38 +01:00
if (!defineProperty_IE8)
Object.defineProperty(this, 'transport', {
get: this.getTransport.bind(this),
set: this.setTransport.bind(this)
})
this.setTransport(transport);
2021-03-22 12:14:38 +01:00
var request_timeout = options.request_timeout || BASE_TIMEOUT;
var ping_request_timeout = options.ping_request_timeout || request_timeout;
2021-03-22 12:14:38 +01:00
var response_timeout = options.response_timeout || BASE_TIMEOUT;
var duplicates_timeout = options.duplicates_timeout || BASE_TIMEOUT;
var requestID = 0;
2021-03-22 12:14:38 +01:00
var requests = new Mapper();
var responses = new Mapper();
var processedResponses = new Mapper();
var message2Key = {};
/**
* Store the response to prevent to process duplicate request later
*/
2021-03-22 12:14:38 +01:00
function storeResponse(message, id, dest) {
var response = {
message: message,
/** Timeout to auto-clean old responses */
2021-03-22 12:14:38 +01:00
timeout: setTimeout(function () {
responses.remove(id, dest);
},
response_timeout)
};
responses.set(response, id, dest);
};
/**
* Store the response to ignore duplicated messages later
*/
2021-03-22 12:14:38 +01:00
function storeProcessedResponse(ack, from) {
var timeout = setTimeout(function () {
processedResponses.remove(ack, from);
},
duplicates_timeout);
processedResponses.set(timeout, ack, from);
};
/**
* Representation of a RPC request
*
* @class
* @extends RpcNotification
*
* @constructor
*
* @param {String} method -method of the notification
* @param params - parameters of the notification
* @param {Integer} id - identifier of the request
* @param [from] - source of the notification
*/
2021-03-22 12:14:38 +01:00
function RpcRequest(method, params, id, from, transport) {
RpcNotification.call(this, method, params);
2021-03-22 12:14:38 +01:00
this.getTransport = function () {
return transport;
}
2021-03-22 12:14:38 +01:00
this.setTransport = function (value) {
transport = unifyTransport(value);
}
2021-03-22 12:14:38 +01:00
if (!defineProperty_IE8)
Object.defineProperty(this, 'transport', {
get: this.getTransport.bind(this),
set: this.setTransport.bind(this)
})
var response = responses.get(id, from);
/**
* @constant {Boolean} duplicated
*/
2021-03-22 12:14:38 +01:00
if (!(transport || self.getTransport())) {
if (defineProperty_IE8)
this.duplicated = Boolean(response)
else
2021-03-22 12:14:38 +01:00
Object.defineProperty(this, 'duplicated', {
value: Boolean(response)
});
}
var responseMethod = responseMethods[method];
this.pack = packer.pack.bind(packer, this, id)
/**
* Generate a response to this request
*
* @param {Error} [error]
* @param {*} [result]
*
* @returns {string}
*/
2021-03-22 12:14:38 +01:00
this.reply = function (error, result, transport) {
// Fix optional parameters
2021-03-22 12:14:38 +01:00
if (error instanceof Function || error && error.send instanceof Function) {
if (result != undefined)
throw new SyntaxError("There can't be parameters after callback");
transport = error;
result = null;
error = undefined;
2021-03-22 12:14:38 +01:00
} else if (result instanceof Function ||
result && result.send instanceof Function) {
if (transport != undefined)
throw new SyntaxError("There can't be parameters after callback");
transport = result;
result = null;
};
transport = unifyTransport(transport);
// Duplicated request, remove old response timeout
2021-03-22 12:14:38 +01:00
if (response)
clearTimeout(response.timeout);
2021-03-22 12:14:38 +01:00
if (from != undefined) {
if (error)
error.dest = from;
2021-03-22 12:14:38 +01:00
if (result)
result.dest = from;
};
var message;
// New request or overriden one, create new response with provided data
2021-03-22 12:14:38 +01:00
if (error || result != undefined) {
if (self.peerID != undefined) {
if (error)
error.from = self.peerID;
else
result.from = self.peerID;
}
// Protocol indicates that responses has own request methods
2021-03-22 12:14:38 +01:00
if (responseMethod) {
if (responseMethod.error == undefined && error)
message = {
error: error
};
2021-03-22 12:14:38 +01:00
else {
var method = error ?
responseMethod.error :
responseMethod.response;
2021-03-22 12:14:38 +01:00
message = {
method: method,
params: error || result
};
}
2021-03-22 12:14:38 +01:00
} else
message = {
error: error,
result: result
};
message = packer.pack(message, id);
}
// Duplicate & not-overriden request, re-send old response
2021-03-22 12:14:38 +01:00
else if (response)
message = response.message;
// New empty reply, response null value
else
2021-03-22 12:14:38 +01:00
message = packer.pack({
result: null
}, id);
// Store the response to prevent to process a duplicated request later
storeResponse(message, id, from);
// Return the stored response so it can be directly send back
transport = transport || this.getTransport() || self.getTransport();
2021-03-22 12:14:38 +01:00
if (transport)
return transport.send(message);
return message;
}
};
inherits(RpcRequest, RpcNotification);
2021-03-22 12:14:38 +01:00
function cancel(message) {
var key = message2Key[message];
2021-03-22 12:14:38 +01:00
if (!key) return;
delete message2Key[message];
var request = requests.pop(key.id, key.dest);
2021-03-22 12:14:38 +01:00
if (!request) return;
clearTimeout(request.timeout);
// Start duplicated responses timeout
storeProcessedResponse(key.id, key.dest);
};
/**
* Allow to cancel a request and don't wait for a response
*
* If `message` is not given, cancel all the request
*/
2021-03-22 12:14:38 +01:00
this.cancel = function (message) {
if (message) return cancel(message);
2021-03-22 12:14:38 +01:00
for (var message in message2Key)
cancel(message);
};
2021-03-22 12:14:38 +01:00
this.close = function () {
// Prevent to receive new messages
var transport = this.getTransport();
2021-03-22 12:14:38 +01:00
if (transport && transport.close)
transport.close(4003, "Cancel request");
// Request & processed responses
this.cancel();
processedResponses.forEach(clearTimeout);
// Responses
2021-03-22 12:14:38 +01:00
responses.forEach(function (response) {
clearTimeout(response.timeout);
});
};
/**
* Generates and encode a JsonRPC 2.0 message
*
* @param {String} method -method of the notification
* @param params - parameters of the notification
* @param [dest] - destination of the notification
* @param {object} [transport] - transport where to send the message
* @param [callback] - function called when a response to this request is
* received. If not defined, a notification will be send instead
*
* @returns {string} A raw JsonRPC 2.0 request or notification string
*/
2021-03-22 12:14:38 +01:00
this.encode = function (method, params, dest, transport, callback) {
// Fix optional parameters
2021-03-22 12:14:38 +01:00
if (params instanceof Function) {
if (dest != undefined)
throw new SyntaxError("There can't be parameters after callback");
2021-03-22 12:14:38 +01:00
callback = params;
transport = undefined;
2021-03-22 12:14:38 +01:00
dest = undefined;
params = undefined;
} else if (dest instanceof Function) {
if (transport != undefined)
throw new SyntaxError("There can't be parameters after callback");
2021-03-22 12:14:38 +01:00
callback = dest;
transport = undefined;
2021-03-22 12:14:38 +01:00
dest = undefined;
} else if (transport instanceof Function) {
if (callback != undefined)
throw new SyntaxError("There can't be parameters after callback");
2021-03-22 12:14:38 +01:00
callback = transport;
transport = undefined;
};
2021-03-22 12:14:38 +01:00
if (self.peerID != undefined) {
params = params || {};
params.from = self.peerID;
};
2021-03-22 12:14:38 +01:00
if (dest != undefined) {
params = params || {};
params.dest = dest;
};
// Encode message
2021-03-22 12:14:38 +01:00
var message = {
method: method,
params: params
};
2021-03-22 12:14:38 +01:00
if (callback) {
var id = requestID++;
var retried = 0;
message = packer.pack(message, id);
2021-03-22 12:14:38 +01:00
function dispatchCallback(error, result) {
self.cancel(message);
callback(error, result);
};
2021-03-22 12:14:38 +01:00
var request = {
message: message,
callback: dispatchCallback,
responseMethods: responseMethods[method] || {}
};
var encode_transport = unifyTransport(transport);
2021-03-22 12:14:38 +01:00
function sendRequest(transport) {
var rt = (method === 'ping' ? ping_request_timeout : request_timeout);
2021-03-22 12:14:38 +01:00
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();
2021-03-22 12:14:38 +01:00
if (transport)
return transport.send(message);
return message;
};
2021-03-22 12:14:38 +01:00
function retry(transport) {
transport = unifyTransport(transport);
2021-03-22 12:14:38 +01:00
console.warn(retried + ' retry for request message:', message);
var timeout = processedResponses.pop(id, dest);
clearTimeout(timeout);
return sendRequest(transport);
};
2021-03-22 12:14:38 +01:00
function timeout() {
if (retried < max_retries)
return retry(transport);
var error = new Error('Request has timed out');
2021-03-22 12:14:38 +01:00
error.request = message;
error.retry = retry;
dispatchCallback(error)
};
return sendRequest(transport);
};
// Return the packed message
message = packer.pack(message);
transport = transport || this.getTransport();
2021-03-22 12:14:38 +01:00
if (transport)
return transport.send(message);
return message;
};
/**
* Decode and process a JsonRPC 2.0 message
*
* @param {string} message - string with the content of the message
*
* @returns {RpcNotification|RpcRequest|undefined} - the representation of the
* notification or the request. If a response was processed, it will return
* `undefined` to notify that it was processed
*
* @throws {TypeError} - Message is not defined
*/
2021-03-22 12:14:38 +01:00
this.decode = function (message, transport) {
if (!message)
throw new TypeError("Message is not defined");
2021-03-22 12:14:38 +01:00
try {
message = packer.unpack(message);
2021-03-22 12:14:38 +01:00
} catch (e) {
// Ignore invalid messages
return console.debug(e, message);
};
2021-03-22 12:14:38 +01:00
var id = message.id;
var ack = message.ack;
var method = message.method;
var params = message.params || {};
var from = params.from;
var dest = params.dest;
// Ignore messages send by us
2021-03-22 12:14:38 +01:00
if (self.peerID != undefined && from == self.peerID) return;
// Notification
2021-03-22 12:14:38 +01:00
if (id == undefined && ack == undefined) {
var notification = new RpcNotification(method, params);
2021-03-22 12:14:38 +01:00
if (self.emit('request', notification)) return;
return notification;
};
2021-03-22 12:14:38 +01:00
function processRequest() {
// If we have a transport and it's a duplicated request, reply inmediatly
transport = unifyTransport(transport) || self.getTransport();
2021-03-22 12:14:38 +01:00
if (transport) {
var response = responses.get(id, from);
2021-03-22 12:14:38 +01:00
if (response)
return transport.send(response.message);
};
var idAck = (id != undefined) ? id : ack;
var request = new RpcRequest(method, params, idAck, from, transport);
2021-03-22 12:14:38 +01:00
if (self.emit('request', request)) return;
return request;
};
2021-03-22 12:14:38 +01:00
function processResponse(request, error, result) {
request.callback(error, result);
};
2021-03-22 12:14:38 +01:00
function duplicatedResponse(timeout) {
console.warn("Response already processed", message);
// Update duplicated responses timeout
clearTimeout(timeout);
storeProcessedResponse(ack, from);
};
// Request, or response with own method
2021-03-22 12:14:38 +01:00
if (method) {
// Check if it's a response with own method
2021-03-22 12:14:38 +01:00
if (dest == undefined || dest == self.peerID) {
var request = requests.get(ack, from);
2021-03-22 12:14:38 +01:00
if (request) {
var responseMethods = request.responseMethods;
2021-03-22 12:14:38 +01:00
if (method == responseMethods.error)
return processResponse(request, params);
2021-03-22 12:14:38 +01:00
if (method == responseMethods.response)
return processResponse(request, null, params);
return processRequest();
}
var processed = processedResponses.get(ack, from);
2021-03-22 12:14:38 +01:00
if (processed)
return duplicatedResponse(processed);
}
// Request
return processRequest();
};
2021-03-22 12:14:38 +01:00
var error = message.error;
var result = message.result;
// Ignore responses not send to us
2021-03-22 12:14:38 +01:00
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);
2021-03-22 12:14:38 +01:00
if (!request) {
var processed = processedResponses.get(ack, from);
2021-03-22 12:14:38 +01:00
if (processed)
return duplicatedResponse(processed);
return console.warn("No callback was defined for this message", message);
};
// Process response
processResponse(request, error, result);
};
};
inherits(RpcBuilder, EventEmitter);
RpcBuilder.RpcNotification = RpcNotification;
module.exports = RpcBuilder;
var clients = require('./clients');
var transports = require('./clients/transports');
RpcBuilder.clients = clients;
RpcBuilder.clients.transports = transports;
2021-03-22 12:14:38 +01:00
RpcBuilder.packers = packers;