-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
Copy pathsocket_provider.ts
415 lines (357 loc) · 12.2 KB
/
socket_provider.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
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
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
import {
ConnectionEvent,
EthExecutionAPI,
JsonRpcBatchRequest,
JsonRpcBatchResponse,
JsonRpcId,
JsonRpcNotification,
JsonRpcRequest,
JsonRpcResponse,
JsonRpcResponseWithResult,
JsonRpcResult,
SocketRequestItem,
Web3APIMethod,
Web3APIPayload,
Web3APIReturnType,
Web3APISpec,
Web3ProviderEventCallback,
Web3ProviderStatus,
} from 'web3-types';
import {
ConnectionError,
ConnectionNotOpenError,
InvalidClientError,
PendingRequestsOnReconnectingError,
RequestAlreadySentError,
Web3WSProviderError,
} from 'web3-errors';
import { Eip1193Provider } from './web3_eip1193_provider';
import { ChunkResponseParser } from './chunk_response_parser';
import { isNullish } from './validation';
import { Web3DeferredPromise } from './web3_deferred_promise';
import * as jsonRpc from './json_rpc';
type ReconnectOptions = {
autoReconnect: boolean;
delay: number;
maxAttempts: number;
};
type EventType = 'message' | 'connect' | 'disconnect' | 'chainChanged' | 'accountsChanged' | string;
const NORMAL_CLOSE_CODE = 1000; // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close
export abstract class SocketProvider<
MessageEvent,
CloseEvent,
ErrorEvent,
API extends Web3APISpec = EthExecutionAPI,
> extends Eip1193Provider<API> {
protected isReconnecting: boolean;
protected readonly _socketPath: string;
protected readonly chunkResponseParser: ChunkResponseParser;
/* eslint-disable @typescript-eslint/no-explicit-any */
protected readonly _pendingRequestsQueue: Map<JsonRpcId, SocketRequestItem<any, any, any>>;
/* eslint-disable @typescript-eslint/no-explicit-any */
protected readonly _sentRequestsQueue: Map<JsonRpcId, SocketRequestItem<any, any, any>>;
protected _reconnectAttempts!: number;
protected readonly _providerOptions?: object;
protected readonly _reconnectOptions: ReconnectOptions;
protected _socketConnection?: unknown;
protected _connectionStatus: Web3ProviderStatus;
protected readonly _onMessageHandler: (event: MessageEvent) => void;
protected readonly _onOpenHandler: () => void;
protected readonly _onCloseHandler: (event: CloseEvent) => void;
protected readonly _onErrorHandler: (event: ErrorEvent) => void;
/**
* This is an abstract class for implementing a socket provider (e.g. WebSocket, IPC). It extends the EIP-1193 provider {@link EIP1193Provider}.
* @param socketPath - The path to the socket (e.g. /ipc/path or ws://localhost:8546)
* @param options - The options for the socket connection
* @param reconnectOptions - The options for the socket reconnection {@link ReconnectOptions}
*/
public constructor(socketPath: string, options?: object, reconnectOptions?: object) {
super();
this._connectionStatus = 'connecting';
this._onMessageHandler = this._onMessage.bind(this);
this._onOpenHandler = this._onConnect.bind(this);
this._onCloseHandler = this._onCloseEvent.bind(this);
this._onErrorHandler = this._onError.bind(this);
if (!this._validateProviderPath(socketPath)) throw new InvalidClientError(socketPath);
this._socketPath = socketPath;
this._providerOptions = options;
const DEFAULT_PROVIDER_RECONNECTION_OPTIONS = {
autoReconnect: true,
delay: 5000,
maxAttempts: 5,
};
this._reconnectOptions = {
...DEFAULT_PROVIDER_RECONNECTION_OPTIONS,
...(reconnectOptions ?? {}),
};
this._pendingRequestsQueue = new Map<JsonRpcId, SocketRequestItem<any, any, any>>();
this._sentRequestsQueue = new Map<JsonRpcId, SocketRequestItem<any, any, any>>();
this._init();
this.connect();
this.chunkResponseParser = new ChunkResponseParser();
this.chunkResponseParser.onError(() => {
this._clearQueues();
});
this.isReconnecting = false;
}
protected _init() {
this._reconnectAttempts = 0;
}
/**
* Try to establish a connection to the socket
*/
public connect(): void {
try {
this._openSocketConnection();
this._connectionStatus = 'connecting';
this._addSocketListeners();
} catch (e) {
if (!this.isReconnecting) {
this._connectionStatus = 'disconnected';
if (e && (e as Error).message) {
throw new ConnectionError(
`Error while connecting to ${this._socketPath}. Reason: ${
(e as Error).message
}`,
);
} else {
throw new InvalidClientError(this._socketPath);
}
} else {
setImmediate(() => {
this._reconnect();
});
}
}
}
protected abstract _openSocketConnection(): void;
protected abstract _addSocketListeners(): void;
protected abstract _removeSocketListeners(): void;
protected abstract _onCloseEvent(_event: unknown): void;
protected abstract _sendToSocket(_payload: Web3APIPayload<API, any>): void;
protected abstract _parseResponses(_event: MessageEvent): JsonRpcResponse[];
protected abstract _closeSocketConnection(_code?: number, _data?: string): void;
// eslint-disable-next-line class-methods-use-this
protected _validateProviderPath(path: string): boolean {
return !!path;
}
/**
*
* @returns `true` if the socket supports subscriptions
*/
// eslint-disable-next-line class-methods-use-this
public supportsSubscriptions(): boolean {
return true;
}
/**
* Registers a listener for the specified event type.
* @param type - The event type to listen for
* @param callback - The callback to be invoked when the event is emitted
*/
public on<T = JsonRpcResult>(type: EventType, callback: Web3ProviderEventCallback<T>): void {
this._eventEmitter.on(type, callback);
}
/**
* Registers a listener for the specified event type that will be invoked at most once.
* @param type - The event type to listen for
* @param callback - The callback to be invoked when the event is emitted
*/
public once<T = JsonRpcResult>(type: EventType, callback: Web3ProviderEventCallback<T>): void {
this._eventEmitter.once(type, callback);
}
/**
* Removes a listener for the specified event type.
* @param type - The event type to remove the listener for
* @param callback - The callback to be exetuted
*/
public removeListener(type: EventType, callback: Web3ProviderEventCallback): void {
this._eventEmitter.removeListener(type, callback);
}
protected _onDisconnect(code?: number, data?: string) {
this._connectionStatus = 'disconnected';
super._onDisconnect(code, data);
}
/**
* Disconnects the socket
* @param code - The code to be sent to the server
* @param data - The data to be sent to the server
*/
public disconnect(code?: number, data?: string): void {
const disconnectCode = code ?? NORMAL_CLOSE_CODE;
this._removeSocketListeners();
if (this.getStatus() !== 'disconnected') {
this._closeSocketConnection(disconnectCode, data);
}
this._onDisconnect(disconnectCode, data);
}
/**
* Removes all listeners for the specified event type.
* @param type - The event type to remove the listeners for
*/
public removeAllListeners(type: string): void {
this._eventEmitter.removeAllListeners(type);
}
protected _onError(event: ErrorEvent): void {
// do not emit error while trying to reconnect
if (this.isReconnecting) {
this._reconnect();
} else {
this._eventEmitter.emit('error', event);
}
}
/**
* Resets the socket, removing all listeners and pending requests
*/
public reset(): void {
this._sentRequestsQueue.clear();
this._pendingRequestsQueue.clear();
this._init();
this._removeSocketListeners();
this._addSocketListeners();
}
protected _reconnect(): void {
if (this.isReconnecting) {
return;
}
this.isReconnecting = true;
if (this._sentRequestsQueue.size > 0) {
this._sentRequestsQueue.forEach(
(request: SocketRequestItem<any, any, any>, key: JsonRpcId) => {
request.deferredPromise.reject(new PendingRequestsOnReconnectingError());
this._sentRequestsQueue.delete(key);
},
);
}
if (this._reconnectAttempts < this._reconnectOptions.maxAttempts) {
this._reconnectAttempts += 1;
setTimeout(() => {
this._removeSocketListeners();
this.connect();
this.isReconnecting = false;
}, this._reconnectOptions.delay);
} else {
this.isReconnecting = false;
this._clearQueues();
this._removeSocketListeners();
const errorMsg = `Max connection attempts exceeded (${this._reconnectOptions.maxAttempts})`;
this._eventEmitter.emit('error', errorMsg);
}
}
/**
* Creates a request object to be sent to the server
*/
public async request<
Method extends Web3APIMethod<API>,
ResultType = Web3APIReturnType<API, Method>,
>(request: Web3APIPayload<API, Method>): Promise<JsonRpcResponseWithResult<ResultType>> {
if (isNullish(this._socketConnection)) {
throw new Error('Connection is undefined');
}
// if socket disconnected - open connection
if (this.getStatus() === 'disconnected') {
this.connect();
}
const requestId = jsonRpc.isBatchRequest(request)
? (request as unknown as JsonRpcBatchRequest)[0].id
: (request as unknown as JsonRpcRequest).id;
if (!requestId) {
throw new Web3WSProviderError('Request Id not defined');
}
if (this._sentRequestsQueue.has(requestId)) {
throw new RequestAlreadySentError(requestId);
}
const deferredPromise = new Web3DeferredPromise<JsonRpcResponseWithResult<ResultType>>();
const reqItem: SocketRequestItem<API, Method, JsonRpcResponseWithResult<ResultType>> = {
payload: request,
deferredPromise,
};
if (this.getStatus() === 'connecting') {
this._pendingRequestsQueue.set(requestId, reqItem);
return reqItem.deferredPromise;
}
this._sentRequestsQueue.set(requestId, reqItem);
try {
this._sendToSocket(reqItem.payload);
} catch (error) {
this._sentRequestsQueue.delete(requestId);
throw error;
}
return deferredPromise;
}
protected _onConnect() {
this._connectionStatus = 'connected';
this._reconnectAttempts = 0;
super._onConnect();
this._sendPendingRequests();
}
private _sendPendingRequests() {
for (const [id, value] of this._pendingRequestsQueue.entries()) {
this._sendToSocket(value.payload as Web3APIPayload<API, any>);
this._pendingRequestsQueue.delete(id);
this._sentRequestsQueue.set(id, value);
}
}
protected _onMessage(event: MessageEvent): void {
const responses = this._parseResponses(event);
if (!responses) {
return;
}
for (const response of responses) {
if (
jsonRpc.isResponseWithNotification(response as JsonRpcNotification) &&
(response as JsonRpcNotification).method.endsWith('_subscription')
) {
this._eventEmitter.emit('message', undefined, response);
return;
}
const requestId = jsonRpc.isBatchResponse(response)
? (response as unknown as JsonRpcBatchResponse)[0].id
: (response as unknown as JsonRpcResponseWithResult).id;
const requestItem = this._sentRequestsQueue.get(requestId);
if (!requestItem) {
return;
}
if (
jsonRpc.isBatchResponse(response) ||
jsonRpc.isResponseWithResult(response) ||
jsonRpc.isResponseWithError(response)
) {
this._eventEmitter.emit('message', undefined, response);
requestItem.deferredPromise.resolve(response);
}
this._sentRequestsQueue.delete(requestId);
}
}
protected _clearQueues(event?: ConnectionEvent) {
if (this._pendingRequestsQueue.size > 0) {
this._pendingRequestsQueue.forEach(
(request: SocketRequestItem<any, any, any>, key: JsonRpcId) => {
request.deferredPromise.reject(new ConnectionNotOpenError(event));
this._pendingRequestsQueue.delete(key);
},
);
}
if (this._sentRequestsQueue.size > 0) {
this._sentRequestsQueue.forEach(
(request: SocketRequestItem<any, any, any>, key: JsonRpcId) => {
request.deferredPromise.reject(new ConnectionNotOpenError(event));
this._sentRequestsQueue.delete(key);
},
);
}
this._removeSocketListeners();
}
}