-
-
Notifications
You must be signed in to change notification settings - Fork 283
/
Copy pathjson-rpc.ts
131 lines (109 loc) · 3.36 KB
/
json-rpc.ts
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
import { EventEmitter } from 'events';
import { throwError } from '@trezor/utils';
import type { ISocket } from '../sockets/interface';
type Callback = (error: any, result?: any) => void;
type CallbackMessageQueue = Record<number, Callback>;
export type JsonRpcClientOptions = {
debug?: boolean;
};
export class JsonRpcClient {
private id = 0;
private buffer = '';
private emitter = new EventEmitter();
protected callbacks: CallbackMessageQueue = {};
protected socket?: ISocket;
protected debug = false;
async connect(socket: ISocket, options?: JsonRpcClientOptions) {
if (this.socket) return;
this.debug = options?.debug || false;
try {
this.socket = socket;
await this.socket.connect(this);
} catch (err) {
this.socket = undefined;
throw new Error(`JSON RPC connection failed: [${err}]`);
}
}
isConnected() {
return !!this.socket;
}
close() {
this.socket?.close();
this.socket = undefined;
this.onClose();
}
request(method: string, ...params: any[]) {
return new Promise<any>((resolve, reject) => {
const id = ++this.id;
const request = JSON.stringify({
jsonrpc: '2.0',
method,
params,
id,
});
this.callbacks[id] = (err, result) => {
if (err) reject(err);
else resolve(result);
};
this.send(request);
});
}
on(event: string, listener: (...args: any[]) => void) {
this.emitter.on(event, listener);
}
off(event: string, listener: (...args: any[]) => void) {
this.emitter.off(event, listener);
}
protected send(message: string) {
const socket = this.socket || throwError('Connection not established');
this.log('SENDING:', message);
socket.send(`${message}\n`);
}
protected response(response: any) {
const { id, method, params, result, error } = response;
if (!id) {
// Notification
this.emitter.emit(method, params);
} else {
// Response
const callback = this.callbacks[id];
if (callback) {
delete this.callbacks[id];
callback(error, result);
} else {
this.log(`Can't get callback for ${id}`);
}
}
}
protected onMessage(body: string) {
const msg = JSON.parse(body);
this.log('RECEIVED:', msg);
this.response(msg);
}
onConnect() {
this.log('onConnect');
}
onReceive(chunk: string) {
const msgs = (this.buffer + chunk).split('\n');
this.buffer = msgs.pop() || '';
msgs.filter(msg => !!msg).forEach(this.onMessage, this);
}
onEnd(e: unknown) {
this.log(`onEnd: [${e}]`);
}
onError(error: unknown) {
this.log(`onError: [${error}]`);
}
onClose() {
this.log('onClose');
Object.values(this.callbacks).forEach(cb => cb(new Error('Connection closed')));
this.callbacks = {};
this.emitter.removeAllListeners();
}
protected log(...data: any[]) {
if (this.debug) {
// eslint-disable-next-line no-console
console.log(...data);
}
}
}