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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
|
import assert from 'assert';
import log from 'electron-log';
import { EventEmitter } from 'events';
import jsonrpc from 'jsonrpc-lite';
import * as net from 'net';
import StreamValues from 'stream-json/streamers/StreamValues';
import * as uuid from 'uuid';
export interface IUnansweredRequest {
resolve: (value: any) => void;
reject: (value: any) => void;
timerId: NodeJS.Timeout;
message: object;
}
export interface IJsonRpcErrorResponse {
type: 'error';
payload: {
id: string;
error: {
code: number;
message: string;
};
};
}
export interface IJsonRpcNotification {
type: 'notification';
payload: {
method: string;
params: {
subscription: string;
result: any;
};
};
}
export interface IJsonRpcSuccess {
type: 'success';
payload: {
id: string;
result: any;
};
}
export type JsonRpcMessage = IJsonRpcErrorResponse | IJsonRpcNotification | IJsonRpcSuccess;
export class RemoteError extends Error {
constructor(private codeValue: number, private detailsValue: string) {
super(`Remote JSON-RPC error ${codeValue}: ${detailsValue}`);
}
get code(): number {
return this.codeValue;
}
get details(): string {
return this.detailsValue;
}
}
export class TimeOutError extends Error {
constructor(private jsonRpcMessageValue: object) {
super('Request timed out');
}
get jsonRpcMessage(): object {
return this.jsonRpcMessageValue;
}
}
export class SubscriptionError extends Error {
constructor(message: string, private replyValue: any) {
super(`${message}: ${JSON.stringify(replyValue)}`);
}
get reply(): any {
return this.replyValue;
}
}
export class WebSocketError extends Error {
get code(): number {
return this.codeValue;
}
private static reason(code: number): string {
switch (code) {
case 1006:
return 'Abnormal closure';
case 1011:
return 'Internal error';
case 1012:
return 'Service restart';
case 1014:
return 'Bad gateway';
default:
return `Unknown (${code})`;
}
}
constructor(private codeValue: number) {
super(WebSocketError.reason(codeValue));
}
}
export class TransportError extends Error {}
const DEFAULT_TIMEOUT_MILLIS = 5000;
export default class JsonRpcClient<T> extends EventEmitter {
private unansweredRequests: Map<string, IUnansweredRequest> = new Map();
private subscriptions: Map<string | number, (value: any) => void> = new Map();
private transport: ITransport<T>;
constructor(transport: ITransport<T>) {
super();
this.transport = transport;
}
/// Connect websocket
public connect(connectionParams: T): Promise<void> {
return new Promise((resolve, reject) => {
this.disconnect();
log.info('Connecting to transport with params', connectionParams);
// A flag used to determine if Promise was resolved.
let isPromiseResolved = false;
const transport = this.transport;
transport.onOpen = () => {
log.info('Transport is connected');
this.emit('open');
// Resolve the Promise
resolve();
isPromiseResolved = true;
};
transport.onMessage = (obj) => {
this.onMessage(obj);
};
transport.onClose = (error?: Error) => {
// Remove all subscriptions since they are connection based
this.subscriptions.clear();
this.emit('close', error);
// Prevent rejecting a previously resolved Promise.
if (!isPromiseResolved) {
reject(error);
}
};
transport.connect(connectionParams);
this.transport = transport;
});
}
public disconnect() {
if (this.transport) {
this.transport.close();
}
}
public async subscribe(event: string, listener: (value: any) => void): Promise<void> {
log.silly(`Adding a listener for ${event}`);
try {
const subscriptionId = await this.send(`${event}_subscribe`);
if (typeof subscriptionId === 'string' || typeof subscriptionId === 'number') {
this.subscriptions.set(subscriptionId, listener);
} else {
throw new SubscriptionError(
'The subscription id was not a string or a number',
subscriptionId,
);
}
} catch (e) {
log.error(`Failed adding listener to ${event}: ${e.message}`);
throw e;
}
}
public send(action: string, data?: any, timeout: number = DEFAULT_TIMEOUT_MILLIS): Promise<any> {
return new Promise((resolve, reject) => {
const transport = this.transport;
if (!transport) {
reject(new Error('RPC client transport is not connected.'));
return;
}
const id = uuid.v4();
const payload = this.prepareParams(data);
const timerId = global.setTimeout(() => this.onTimeout(id), timeout);
const message = jsonrpc.request(id, action, payload);
this.unansweredRequests.set(id, {
resolve,
reject,
timerId,
message,
});
try {
log.silly('Sending message', id, action);
transport.send(JSON.stringify(message));
} catch (error) {
log.error(`Failed sending RPC message "${action}": ${error.message}`);
// clean up on error
this.unansweredRequests.delete(id);
clearTimeout(timerId);
throw error;
}
});
}
private prepareParams(data?: any): any[] | object {
// JSONRPC only accepts arrays and objects as params, but
// this isn't very nice to use, so this method wraps other
// types in an array. The choice of array is based on try-and-error
if (data === undefined) {
return [];
} else if (data === null) {
return [null];
} else if (Array.isArray(data) || typeof data === 'object') {
return data;
} else {
return [data];
}
}
private onTimeout(requestId: string) {
const request = this.unansweredRequests.get(requestId);
this.unansweredRequests.delete(requestId);
if (request) {
log.warn(`Request ${requestId} timed out: `, request.message);
request.reject(new TimeOutError(request.message));
} else {
log.warn(`Request ${requestId} timed out but it seems to already have been answered`);
}
}
private onMessage(obj: object) {
let message: ReturnType<typeof jsonrpc.parseObject>;
try {
message = jsonrpc.parseObject(obj);
} catch (error) {
log.error(`Failed to parse JSON-RPC message: ${error} for object`);
return;
}
if (message.type === 'notification') {
this.onNotification(message as IJsonRpcNotification);
} else {
this.onReply(message as (IJsonRpcErrorResponse | IJsonRpcSuccess));
}
}
private onNotification(message: IJsonRpcNotification) {
const subscriptionId = message.payload.params.subscription;
const listener = this.subscriptions.get(subscriptionId);
if (listener) {
log.silly(`Got notification for ${message.payload.method}`);
listener(message.payload.params.result);
} else {
log.warn(`Got notification for ${message.payload.method} but no one is listening for it`);
}
}
private onReply(message: IJsonRpcErrorResponse | IJsonRpcSuccess) {
const id = message.payload.id;
const request = this.unansweredRequests.get(id);
this.unansweredRequests.delete(id);
if (request) {
log.silly('Got answer to', id, message.type);
clearTimeout(request.timerId);
if (message.type === 'error') {
const error = message.payload.error;
request.reject(new RemoteError(error.code, error.message));
} else {
const reply = message.payload.result;
request.resolve(reply);
}
} else {
log.warn(`Got reply to ${id} but no one was waiting for it`);
}
}
}
export interface ITransport<T> {
onOpen: () => void;
onMessage: (data: object) => void;
onClose: (error?: Error) => void;
close(): void;
send(message: string): void;
connect(params: T): void;
}
// Given the correct parameters, this transport supports named pipes/unix
// domain sockets, and also TCP/UDP sockets
export class SocketTransport implements ITransport<{ path: string }> {
private connection?: net.Socket;
private jsonStream?: NodeJS.ReadWriteStream;
private socketReady = false;
private lastError?: Error;
public onMessage = (_message: object) => {
// no-op
};
public onClose = (_error?: Error) => {
// no-op
};
public onOpen = () => {
// no-op
};
public connect(options: { path: string }) {
assert(!this.connection, 'Make sure to close the existing socket');
const jsonStream = StreamValues.withParser()
.on('data', this.onJsonStreamData)
.once('error', this.onJsonStreamError);
const connection = new net.Socket()
.once('ready', this.onSocketReady)
.once('error', this.onSocketError)
.once('close', this.onSocketClose);
this.connection = connection;
this.jsonStream = jsonStream;
this.socketReady = false;
this.lastError = undefined;
log.debug('Connect socket');
connection.pipe(jsonStream);
connection.connect(options);
}
public close() {
if (this.connection) {
log.debug('Close socket');
// closing socket is not synchronous, so remove all of the event handlers first
this.connection
.removeListener('ready', this.onSocketReady)
.removeListener('error', this.onSocketError)
.removeListener('close', this.onSocketClose);
this.jsonStream!.removeListener('data', this.onJsonStreamData).removeListener(
'error',
this.onJsonStreamError,
);
try {
this.connection.end();
} catch (error) {
log.error('Failed to close the socket: ', error);
}
this.connection = undefined;
this.jsonStream = undefined;
this.onClose();
}
}
public send(msg: string) {
if (this.socketReady && this.connection) {
this.connection.write(msg);
} else {
throw new TransportError('Socket not connected');
}
}
private onSocketReady = () => {
this.socketReady = true;
log.debug('Socket is ready');
this.onOpen();
};
private onSocketError = (error: Error) => {
this.lastError = error;
log.error('Socket error: ', error);
};
private onSocketClose = (hadError: boolean) => {
if (hadError) {
log.debug(`Socket was closed due to an error: `, this.lastError);
this.onClose(this.lastError);
} else {
log.debug(`Socket was closed by peer`);
this.onClose(new TransportError('Socket was closed by peer'));
}
};
private onJsonStreamData = (data: { key: number; value: any }) => {
this.onMessage(data.value);
};
private onJsonStreamError = (error: Error) => {
log.error('Socket JSON stream error: ', error);
if (this.connection) {
// This will destroy the socket and emit "error" and "close" events
this.connection.destroy(error);
}
};
}
|