-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathrpc-callback.js
67 lines (54 loc) · 1.69 KB
/
rpc-callback.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const LusterRPCCallbackError = require('./errors').LusterRPCCallbackError;
const RPCCallback = {
_storage: {},
_counter: 0,
/**
* @param {ClusterProcess} proc
* @param {String} command
* @param {Function} callback
* @param {Number} [timeout=10000] in milliseconds
* @returns {String} callbackId
*/
setCallback(proc, command, callback, timeout) {
const storage = this._storage;
if ( ! timeout) {
timeout = 10000;
}
const callbackId = proc.wid + '_' + this._counter++;
storage[callbackId] = {
callback,
timeout:
setTimeout(() => {
storage[callbackId].callback(
proc,
LusterRPCCallbackError.createError(
LusterRPCCallbackError.CODES.REMOTE_CALL_WITH_CALLBACK_TIMEOUT,
{ command }));
this.removeCallback(callbackId);
}, timeout)
};
return callbackId;
},
/**
* @param {ClusterProcess} proc
* @param {String} callbackId
* @param {*} [data] provided in callback
*/
processCallback(proc, callbackId, data) {
const stored = this._storage[callbackId];
if ( ! stored) {
return;
}
setImmediate(() => stored.callback(proc, null, data));
this.removeCallback(callbackId);
},
/**
* @param {String} callbackId
*/
removeCallback(callbackId) {
const timeout = this._storage[callbackId].timeout;
clearTimeout(timeout);
delete this._storage[callbackId];
}
};
module.exports = RPCCallback;