forked from royaltm/node-zmq-raft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzmq_rpc_socket.js
360 lines (303 loc) · 9.4 KB
/
zmq_rpc_socket.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/*
* Copyright (c) 2016-2017 Rafał Michalski <[email protected]>
*/
"use strict";
const isArray = Array.isArray
, isBuffer = Buffer.isBuffer
, identity = (a) => a;
const assert = require('assert');
const zmq = require('zeromq');
const { ZMQ_LINGER, ZMQ_SNDHWM } = zmq;
const { ZmqDealerSocket } = require('../utils/zmqsocket');
const DEFAULT_RPC_TIMEOUT = 50;
const { allocBufUIntLE: encodeRequestId, readBufUIntLE: decodeRequestId } = require('../utils/bufconv');
const REQUEST_ID_BYTES = 3;
const REQUEST_ID_MASK = (1 << (REQUEST_ID_BYTES*8)) - 1;
const requestIdIsValid = (id) => {
const len = id.length;
return len > 0 && len <= REQUEST_ID_BYTES;
}
const handler$ = Symbol.for('handler');
const pending$ = Symbol.for('pending');
const connected$ = Symbol.for('connected');
const sockopts$ = Symbol.for('sockopts');
const lastReqId$ = Symbol.for('lastReqId');
const nextRequestId$ = Symbol.for('nextRequestId');
const disconnect$ = Symbol.for('disconnect');
const debug = require('debug')('zmq-raft:rpc-socket');
function RpcCancelError(message) {
Error.captureStackTrace(this, RpcCancelError);
this.name = 'RpcCancelError';
this.message = message || 'request cancelled';
}
RpcCancelError.prototype = Object.create(Error.prototype);
RpcCancelError.prototype.constructor = RpcCancelError;
RpcCancelError.prototype.isCancel = true;
/*
ZmqRpcSocket is a handy wrapper for zmq DEALER socket that implements RPC pattern.
ZmqRpcSocket waits forever for reply re-sending request every `timeout` milliseconds if needed.
ZmqRpcSocket guarantees that only one unique request may be sent at a time (the request may be repeated though).
Pending requests may be canceled any time.
The response is handled using promises.
example:
rpc = new ZmqRpcSocket('tcp://127.0.0.1:1234', {timeout: 100});
rpc.request('foo')
// handle response
.then(resp => console.log(resp))
// handle timeout or close error
.catch(err => console.error(err));
To cancel pending request invoke reset(), e.g.:
rpc.reset().request('another request')
*/
class ZmqRpcSocket {
/**
* Create ZmqRpcSocket
*
* `options` may be one of:
*
* - `timeout` {number}: default repeat request timeout in milliseconds
* - `sockopts` {Object}: specify zmq socket options as object e.g.: {ZMQ_IPV4ONLY: true}
*
* @param {string} url
* @param {Object} options
* @return {ZmqRpcSocket}
**/
constructor(url, options) {
options || (options = {});
var sockopts = options.sockopts || {};
if ('object' !== typeof sockopts)
throw TypeError('ZmqRpcSocket: sockopts must be an object');
if ('string' !== typeof url)
throw TypeError('ZmqRpcSocket: url must be a string');
this.url = url;
this.options = Object.assign({}, options);
this[sockopts$] = Object.keys(sockopts).filter(opt => sockopts.hasOwnProperty(opt))
.reduce((map, opt) => {
map.set(toZmqOpt(opt), sockopts[opt]);
return map;
}, new Map());
this.timeoutMs = (options.timeout|0) || DEFAULT_RPC_TIMEOUT;
if (this.timeoutMs <= 0)
throw TypeError('ZmqRpcSocket: timeout must be > 0');
this.socket = null;
this[connected$] = false;
this[pending$] = null;
this[handler$] = null;
this[lastReqId$] = 0;
}
toString() {
return this.url;
}
/**
* @property pending {Promise|null}
**/
get pending() {
return this[pending$];
}
/**
* @property connected {boolean}
**/
get connected() {
return this[connected$];
}
/**
* Send request
*
* @param {Array|primitive} req
* @param {number} [timeoutMs]
* @return {Promise}
**/
request(req, timeoutMs) {
if (this[pending$]) return Promise.reject(new Error('ZmqRpcSocket: another request pending'));
return (this[pending$] = new Promise((resolve, reject) => {
if (!this[connected$]) this.connect();
const socket = this.socket;
const requestId = this[nextRequestId$]();
var handler = this[handler$] = {requestId: requestId};
const payload = [encodeRequestId(requestId)].concat(req);
if (timeoutMs === undefined) timeoutMs = this.timeoutMs;
var drain, timeout;
const cleanup = () => {
if (timeout !== undefined) clearTimeout(timeout);
if (drain !== undefined) {
socket.cancelSend();
socket.removeListener('drain', drain);
}
this[handler$] = handler = null;
}
const send = () => {
var sentok = socket.send(payload);
/* send may invoke 'frames' or 'error' event, which might clear this request */
if (!handler) {
if (!sentok) socket.cancelSend();
debug("rpc.request already gone: %s", this);
}
else if (sentok) {
timeout = setTimeout(send, timeoutMs);
}
else {
timeout = undefined;
debug("rpc.request queue full: %s", this);
drain = () => {
drain = undefined;
debug("rpc.request drain: %s", this);
socket.cancelSend();
timeout = setTimeout(send, timeoutMs);
}
socket.once('drain', drain);
}
};
handler.reject = (err) => {
cleanup();
reject(err);
};
handler.resolve = (arg) => {
cleanup();
resolve(arg);
};
send();
}));
}
/**
* Reset socket for another request, optionally disconnecting socket and rejecting pending requests
*
* @return {ZmqRpcSocket}
**/
reset() {
if (this[pending$]) this[disconnect$]();
return this;
}
/**
* Disconnect, close socket and reject pending request
*
* @return {ZmqRpcSocket}
**/
close() {
this[disconnect$]();
var socket = this.socket;
if (socket) {
debug("rpc.close: %s", this);
socket.close();
this.socket = null;
}
return this;
}
/**
* Disconnect, close socket, reject all pending requests and prevent further ones
**/
destroy() {
debug("rpc.destroy: %s", this);
this.close();
this.request = destroyed;
this.connect = destroyed;
}
/**
* Connect socket
*
* Use it only to eagerly connect, request() will ensure connect() is being invoked before sending request.
*
* @return {ZmqRpcSocket}
**/
connect() {
if (this[connected$]) return this;
var socket = this.socket || (this.socket = new ZmqDealerSocket());
/* makes sure socket is really closed when close() is called */
socket.setsockopt(ZMQ_LINGER, 0);
for(let [opt, val] of this[sockopts$]) {
socket.setsockopt(opt, val);
}
/* one request a time */
socket.setsockopt(ZMQ_SNDHWM, 1);
var url = this.url;
debug("rpc.connect: %s", url);
socket.connect(url);
this[connected$] = true;
/* error handler */
socket.on('error', err => {
var handler = this[handler$];
if (handler) handler.reject(err);
});
/* frames handler */
socket.on('frames', (args) => {
var requestId = args.shift();
if (!requestId || !requestIdIsValid(requestId)) {
debug("rpc.recv: invalid request id");
return; /* ignore */
}
requestId = decodeRequestId(requestId);
/* now get the handler associated with requestId */
var handler = this[handler$];
if (!handler || handler.requestId !== requestId) {
debug("rpc.recv: received requestId: %s doesn't match pending response handler", requestId);
return;
}
/* resolve handler promise */
handler.resolve(args);
/* cleanup pending only on success
on error user must reset() socket */
this[pending$] = null;
});
return this;
}
/**
* Get zmq socket option from the underlaying socket
*
* @param {string} opt
* @return {*}
**/
getsockopt(opt) {
return this[sockopts$].get(toZmqOpt(opt));
}
/**
* Set zmq socket option on the underlaying socket
*
* @param {string} opt
* @param {*} value
* @return {RpcCancelError}
**/
setsockopt(opt, value) {
opt = toZmqOpt(opt);
this[sockopts$].set(opt, value);
if (this.socket) this.socket.setsockopt(opt, value);
return this;
}
[nextRequestId$]() {
var id = (this[lastReqId$] + 1) & REQUEST_ID_MASK;
this[lastReqId$] = id;
return id;
}
[disconnect$]() {
var cancel = new RpcCancelError();
var handler = this[handler$];
if (handler) handler.reject(cancel);
this[pending$] = null;
if (this[connected$]) {
let socket = this.socket
, url = this.url;
socket.removeAllListeners('error');
socket.removeAllListeners('frames');
debug("rpc.disconnect: %s", url);
socket.disconnect(url);
this[connected$] = false;
}
}
}
function destroyed() {
throw new Error('ZmqRpcSocket: socket destroyed');
}
function toZmqOpt(opt) {
var value = ('string' === typeof opt) ? zmq[opt] : opt;
if ('number' !== typeof value || !isFinite(value)) {
throw TypeError(`ZmqRpcSocket: invalid socket option: ${opt}`);
}
return value;
}
ZmqRpcSocket.encodeRequestId = encodeRequestId;
ZmqRpcSocket.decodeRequestId = decodeRequestId;
ZmqRpcSocket.requestIdIsValid = requestIdIsValid;
ZmqRpcSocket.prototype.encodeRequestId = encodeRequestId;
ZmqRpcSocket.prototype.decodeRequestId = decodeRequestId;
ZmqRpcSocket.prototype.requestIdIsValid = requestIdIsValid;
ZmqRpcSocket.ZmqRpcSocket = ZmqRpcSocket;
ZmqRpcSocket.RpcCancelError = RpcCancelError;
module.exports = exports = ZmqRpcSocket;