This repository has been archived by the owner on Jun 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 457
/
Copy pathws_rpc.js
226 lines (193 loc) · 6.31 KB
/
ws_rpc.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
/*
* Copyright © 2018 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*/
'use strict';
var _ = require('lodash');
var MasterWAMPServer = require('wamp-socket-cluster/MasterWAMPServer');
var scClient = require('socketcluster-client');
var WAMPClient = require('wamp-socket-cluster/WAMPClient');
var failureCodes = require('./failure_codes');
var PeerUpdateError = require('./failure_codes').PeerUpdateError;
var PromiseDefer = require('../../../helpers/promise_defer');
var System = require('../../../modules/system');
var wsServer = null;
var wsRPC = {
clientsConnectionsMap: {},
scClient: scClient,
wampClient: new WAMPClient(),
/**
* @param {MasterWAMPServer} __wsServer
*/
setServer: function (__wsServer) {
wsServer = __wsServer;
},
/**
* @throws {Error} if WS server has not been initialized yet
* @returns {MasterWAMPServer} wsServer
*/
getServer: function () {
if (!wsServer) {
throw new Error('WS server has not been initialized!');
}
return wsServer;
},
/**
* @param {string} ip
* @param {number} port
* @returns {ClientRPCStub} {[string]: function} map where keys are all procedures registered
*/
getClientRPCStub: function (ip, port) {
if (!ip || !port) {
throw new Error('RPC client needs ip and port to establish WS connection with: ' + ip + ':' + port);
}
var address = ip + ':' + port;
var connectionState = this.clientsConnectionsMap[address];
//first time init || previously rejected
if (!connectionState || connectionState.status === ConnectionState.STATUS.DISCONNECTED) {
connectionState = new ConnectionState(ip, port);
this.clientsConnectionsMap[address] = connectionState;
}
return connectionState.stub;
},
/**
* @throws {Error} if WS server has not been initialized yet
* @returns {MasterWAMPServer} wsServer
*/
getServerAuthKey: function () {
if (!wsServer) {
throw new Error('WS server has not been initialized!');
}
return wsServer.socketCluster.options.authKey;
}
};
ConnectionState.STATUS = {
NEW: 1,
PENDING: 2,
ESTABLISHED: 3,
DISCONNECTED: 4
};
function ConnectionState (ip, port) {
this.ip = ip;
this.port = +port;
this.status = ConnectionState.STATUS.NEW;
this.socketDefer = PromiseDefer();
this.stub = new ClientRPCStub(this);
}
ConnectionState.prototype.reconnect = function () {
this.status = ConnectionState.STATUS.PENDING;
this.socketDefer = PromiseDefer();
};
ConnectionState.prototype.reject = function (reason) {
this.status = ConnectionState.STATUS.DISCONNECTED;
this.socketDefer.reject(reason);
};
ConnectionState.prototype.resolve = function (socket) {
this.status = ConnectionState.STATUS.ESTABLISHED;
this.socketDefer.resolve(socket);
};
/**
* The stub of all RPC methods registered on WS server
* Example:
* methodA registered on WS server can be called by a client by simply:
* sampleClientStub.methodA(exampleArg, cb);
*
* @typedef {Object} clientStub
* @property {function} procedure - procedure that will be called with argument and callback
*/
/**
* @param {ConnectionState} connectionState
* @returns {clientStub}
*/
var ClientRPCStub = function (connectionState) {
try {
var wsServer = wsRPC.getServer();
} catch (wsServerNotInitializedException) {
return {};
}
return _.reduce(Object.assign({}, wsServer.endpoints.rpc, wsServer.endpoints.event),
function (availableCalls, procedureHandler, procedureName) {
availableCalls[procedureName] = this.sendAfterSocketReadyCb(connectionState)(procedureName);
return availableCalls;
}.bind(this), {});
};
/**
* @param {ConnectionState} connectionState
*/
ClientRPCStub.prototype.initializeNewConnection = function (connectionState) {
var options = {
hostname: connectionState.ip,
port: connectionState.port,
protocol: 'http',
autoReconnect: true,
query: System.getHeaders()
};
var clientSocket = wsRPC.scClient.connect(options);
wsRPC.wampClient.upgradeToWAMP(clientSocket);
clientSocket.on('accepted', function () {
return connectionState.resolve(clientSocket);
});
clientSocket.on('error', function () {
clientSocket.disconnect();
});
clientSocket.on('connectAbort', function () {
connectionState.reject(new PeerUpdateError(failureCodes.HANDSHAKE_ERROR, failureCodes.errorMessages[failureCodes.HANDSHAKE_ERROR]));
});
clientSocket.on('disconnect', function (code, description) {
connectionState.reject(new PeerUpdateError(code, failureCodes.errorMessages[code], description));
});
};
/**
* @param {ConnectionState} connectionState
* @returns {function} function to be called with procedure, to be then called with optional argument and/or callback
*/
ClientRPCStub.prototype.sendAfterSocketReadyCb = function (connectionState) {
return function (procedureName) {
/**
* @param {Object} data [data={}] argument passed to procedure
*/
return function (data, cb) {
cb = _.isFunction(cb) ? cb : _.isFunction(data) ? data : function () {};
data = (data && !_.isFunction(data)) ? data : {};
if (connectionState.status === ConnectionState.STATUS.NEW || connectionState.status === ConnectionState.STATUS.DISCONNECTED) {
connectionState.reconnect();
ClientRPCStub.prototype.initializeNewConnection(connectionState);
}
connectionState.socketDefer.promise.timeout(1000).then(function (socket) {
return socket.wampSend(procedureName, data)
.then(function (res) {
return setImmediate(cb, null, res);
})
.catch(function (err) {
return setImmediate(cb, err);
});
}).catch(function (err) {
if (err && err.name === 'TimeoutError') {
err = new PeerUpdateError(failureCodes.CONNECTION_TIMEOUT, failureCodes.errorMessages[failureCodes.CONNECTION_TIMEOUT]);
}
return setImmediate(cb, err);
});
};
};
};
var remoteAction = function () {
throw new Error('Function invoked on master instead of slave process');
};
var slaveRPCStub = {
updateMyself: remoteAction
};
module.exports = {
wsRPC: wsRPC,
ConnectionState: ConnectionState,
ClientRPCStub: ClientRPCStub,
slaveRPCStub: slaveRPCStub
};