@pezkuwi/rpc-provider 16.5.5 → 16.5.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +10 -10
- package/bizinikiwi-connect/Health.js +259 -0
- package/{build/substrate-connect → bizinikiwi-connect}/index.d.ts +3 -3
- package/bizinikiwi-connect/index.js +319 -0
- package/{build/bundle.d.ts → bundle.d.ts} +1 -1
- package/{src/bundle.ts → bundle.js} +1 -4
- package/cjs/bizinikiwi-connect/Health.d.ts +7 -0
- package/cjs/bizinikiwi-connect/Health.js +264 -0
- package/cjs/bizinikiwi-connect/index.d.ts +22 -0
- package/cjs/bizinikiwi-connect/index.js +323 -0
- package/cjs/bizinikiwi-connect/types.d.ts +12 -0
- package/cjs/bizinikiwi-connect/types.js +2 -0
- package/cjs/bundle.d.ts +5 -0
- package/cjs/bundle.js +14 -0
- package/cjs/coder/error.js +53 -0
- package/cjs/coder/index.js +63 -0
- package/cjs/defaults.js +8 -0
- package/{build → cjs}/http/index.d.ts +1 -1
- package/cjs/http/index.js +196 -0
- package/cjs/http/types.js +2 -0
- package/cjs/index.js +5 -0
- package/cjs/lru.js +150 -0
- package/cjs/mock/index.js +196 -0
- package/cjs/mock/mockHttp.js +17 -0
- package/cjs/mock/mockWs.js +47 -0
- package/cjs/mock/types.js +2 -0
- package/cjs/package.json +3 -0
- package/cjs/packageDetect.d.ts +1 -0
- package/cjs/packageDetect.js +6 -0
- package/cjs/packageInfo.js +4 -0
- package/cjs/types.js +2 -0
- package/cjs/ws/errors.js +41 -0
- package/{build → cjs}/ws/index.d.ts +1 -1
- package/cjs/ws/index.js +529 -0
- package/coder/error.d.ts +29 -0
- package/coder/error.js +50 -0
- package/coder/index.d.ts +8 -0
- package/coder/index.js +58 -0
- package/defaults.d.ts +5 -0
- package/defaults.js +6 -0
- package/http/index.d.ts +81 -0
- package/http/index.js +191 -0
- package/http/types.d.ts +7 -0
- package/http/types.js +1 -0
- package/index.d.ts +2 -0
- package/index.js +2 -0
- package/lru.d.ts +15 -0
- package/lru.js +146 -0
- package/mock/index.d.ts +35 -0
- package/mock/index.js +191 -0
- package/mock/mockHttp.d.ts +9 -0
- package/mock/mockHttp.js +12 -0
- package/mock/mockWs.d.ts +26 -0
- package/mock/mockWs.js +43 -0
- package/mock/types.d.ts +23 -0
- package/mock/types.js +1 -0
- package/package.json +316 -15
- package/packageDetect.d.ts +1 -0
- package/packageDetect.js +4 -0
- package/packageInfo.d.ts +6 -0
- package/packageInfo.js +1 -0
- package/types.d.ts +85 -0
- package/types.js +1 -0
- package/ws/errors.d.ts +1 -0
- package/ws/errors.js +38 -0
- package/ws/index.d.ts +121 -0
- package/ws/index.js +524 -0
- package/src/coder/decodeResponse.spec.ts +0 -70
- package/src/coder/encodeJson.spec.ts +0 -20
- package/src/coder/encodeObject.spec.ts +0 -25
- package/src/coder/error.spec.ts +0 -111
- package/src/coder/error.ts +0 -66
- package/src/coder/index.ts +0 -88
- package/src/defaults.ts +0 -10
- package/src/http/index.spec.ts +0 -72
- package/src/http/index.ts +0 -238
- package/src/http/send.spec.ts +0 -61
- package/src/http/types.ts +0 -11
- package/src/index.ts +0 -6
- package/src/lru.spec.ts +0 -74
- package/src/lru.ts +0 -197
- package/src/mock/index.ts +0 -259
- package/src/mock/mockHttp.ts +0 -35
- package/src/mock/mockWs.ts +0 -92
- package/src/mock/on.spec.ts +0 -43
- package/src/mock/send.spec.ts +0 -38
- package/src/mock/subscribe.spec.ts +0 -81
- package/src/mock/types.ts +0 -36
- package/src/mock/unsubscribe.spec.ts +0 -57
- package/src/mod.ts +0 -4
- package/src/packageDetect.ts +0 -12
- package/src/packageInfo.ts +0 -6
- package/src/substrate-connect/Health.ts +0 -325
- package/src/substrate-connect/index.spec.ts +0 -638
- package/src/substrate-connect/index.ts +0 -415
- package/src/substrate-connect/types.ts +0 -16
- package/src/types.ts +0 -101
- package/src/ws/connect.spec.ts +0 -167
- package/src/ws/errors.ts +0 -41
- package/src/ws/index.spec.ts +0 -97
- package/src/ws/index.ts +0 -652
- package/src/ws/send.spec.ts +0 -126
- package/src/ws/state.spec.ts +0 -20
- package/src/ws/subscribe.spec.ts +0 -68
- package/src/ws/unsubscribe.spec.ts +0 -100
- package/tsconfig.build.json +0 -17
- package/tsconfig.build.tsbuildinfo +0 -1
- package/tsconfig.spec.json +0 -18
- /package/{build/substrate-connect → bizinikiwi-connect}/Health.d.ts +0 -0
- /package/{build/substrate-connect → bizinikiwi-connect}/types.d.ts +0 -0
- /package/{build/packageDetect.d.ts → bizinikiwi-connect/types.js} +0 -0
- /package/{build → cjs}/coder/error.d.ts +0 -0
- /package/{build → cjs}/coder/index.d.ts +0 -0
- /package/{build → cjs}/defaults.d.ts +0 -0
- /package/{build → cjs}/http/types.d.ts +0 -0
- /package/{build → cjs}/index.d.ts +0 -0
- /package/{build → cjs}/lru.d.ts +0 -0
- /package/{build → cjs}/mock/index.d.ts +0 -0
- /package/{build → cjs}/mock/mockHttp.d.ts +0 -0
- /package/{build → cjs}/mock/mockWs.d.ts +0 -0
- /package/{build → cjs}/mock/types.d.ts +0 -0
- /package/{build → cjs}/packageInfo.d.ts +0 -0
- /package/{build → cjs}/types.d.ts +0 -0
- /package/{build → cjs}/ws/errors.d.ts +0 -0
package/src/ws/index.ts
DELETED
|
@@ -1,652 +0,0 @@
|
|
|
1
|
-
// Copyright 2017-2025 @polkadot/rpc-provider authors & contributors
|
|
2
|
-
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
-
|
|
4
|
-
import type { Class } from '@pezkuwi/util/types';
|
|
5
|
-
import type RpcError from '../coder/error.js';
|
|
6
|
-
import type { EndpointStats, JsonRpcResponse, ProviderInterface, ProviderInterfaceCallback, ProviderInterfaceEmitCb, ProviderInterfaceEmitted, ProviderStats } from '../types.js';
|
|
7
|
-
|
|
8
|
-
import { EventEmitter } from 'eventemitter3';
|
|
9
|
-
|
|
10
|
-
import { isChildClass, isNull, isUndefined, logger, noop, objectSpread, stringify } from '@pezkuwi/util';
|
|
11
|
-
import { xglobal } from '@pezkuwi/x-global';
|
|
12
|
-
import { WebSocket } from '@pezkuwi/x-ws';
|
|
13
|
-
|
|
14
|
-
import { RpcCoder } from '../coder/index.js';
|
|
15
|
-
import defaults from '../defaults.js';
|
|
16
|
-
import { DEFAULT_CAPACITY, DEFAULT_TTL, LRUCache } from '../lru.js';
|
|
17
|
-
import { getWSErrorString } from './errors.js';
|
|
18
|
-
|
|
19
|
-
interface SubscriptionHandler {
|
|
20
|
-
callback: ProviderInterfaceCallback;
|
|
21
|
-
type: string;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
interface WsStateAwaiting {
|
|
25
|
-
callback: ProviderInterfaceCallback;
|
|
26
|
-
method: string;
|
|
27
|
-
params: unknown[];
|
|
28
|
-
start: number;
|
|
29
|
-
subscription?: SubscriptionHandler | undefined;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
interface WsStateSubscription extends SubscriptionHandler {
|
|
33
|
-
method: string;
|
|
34
|
-
params: unknown[];
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
const ALIASES: Record<string, string> = {
|
|
38
|
-
chain_finalisedHead: 'chain_finalizedHead',
|
|
39
|
-
chain_subscribeFinalisedHeads: 'chain_subscribeFinalizedHeads',
|
|
40
|
-
chain_unsubscribeFinalisedHeads: 'chain_unsubscribeFinalizedHeads'
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
const RETRY_DELAY = 2_500;
|
|
44
|
-
|
|
45
|
-
const DEFAULT_TIMEOUT_MS = 60 * 1000;
|
|
46
|
-
const TIMEOUT_INTERVAL = 5_000;
|
|
47
|
-
|
|
48
|
-
const l = logger('api-ws');
|
|
49
|
-
|
|
50
|
-
/** @internal Clears a Record<*> of all keys, optionally with all callback on clear */
|
|
51
|
-
function eraseRecord<T> (record: Record<string, T>, cb?: (item: T) => void): void {
|
|
52
|
-
Object.keys(record).forEach((key): void => {
|
|
53
|
-
if (cb) {
|
|
54
|
-
cb(record[key]);
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
delete record[key];
|
|
58
|
-
});
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/** @internal Creates a default/empty stats object */
|
|
62
|
-
function defaultEndpointStats (): EndpointStats {
|
|
63
|
-
return { bytesRecv: 0, bytesSent: 0, cached: 0, errors: 0, requests: 0, subscriptions: 0, timeout: 0 };
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* # @polkadot/rpc-provider/ws
|
|
68
|
-
*
|
|
69
|
-
* @name WsProvider
|
|
70
|
-
*
|
|
71
|
-
* @description The WebSocket Provider allows sending requests using WebSocket to a WebSocket RPC server TCP port. Unlike the [[HttpProvider]], it does support subscriptions and allows listening to events such as new blocks or balance changes.
|
|
72
|
-
*
|
|
73
|
-
* @example
|
|
74
|
-
* <BR>
|
|
75
|
-
*
|
|
76
|
-
* ```javascript
|
|
77
|
-
* import Api from '@pezkuwi/api/promise';
|
|
78
|
-
* import { WsProvider } from '@pezkuwi/rpc-provider/ws';
|
|
79
|
-
*
|
|
80
|
-
* const provider = new WsProvider('ws://127.0.0.1:9944');
|
|
81
|
-
* const api = new Api(provider);
|
|
82
|
-
* ```
|
|
83
|
-
*
|
|
84
|
-
* @see [[HttpProvider]]
|
|
85
|
-
*/
|
|
86
|
-
export class WsProvider implements ProviderInterface {
|
|
87
|
-
readonly #callCache: LRUCache;
|
|
88
|
-
readonly #coder: RpcCoder;
|
|
89
|
-
readonly #endpoints: string[];
|
|
90
|
-
readonly #headers: Record<string, string>;
|
|
91
|
-
readonly #eventemitter: EventEmitter;
|
|
92
|
-
readonly #handlers: Record<string, WsStateAwaiting> = {};
|
|
93
|
-
readonly #isReadyPromise: Promise<WsProvider>;
|
|
94
|
-
readonly #stats: ProviderStats;
|
|
95
|
-
readonly #waitingForId: Record<string, JsonRpcResponse<unknown>> = {};
|
|
96
|
-
readonly #cacheCapacity: number;
|
|
97
|
-
readonly #ttl: number | null | undefined;
|
|
98
|
-
|
|
99
|
-
#autoConnectMs: number;
|
|
100
|
-
#endpointIndex: number;
|
|
101
|
-
#endpointStats: EndpointStats;
|
|
102
|
-
#isConnected = false;
|
|
103
|
-
#subscriptions: Record<string, WsStateSubscription> = {};
|
|
104
|
-
#timeoutId?: ReturnType<typeof setInterval> | null = null;
|
|
105
|
-
#websocket: WebSocket | null;
|
|
106
|
-
#timeout: number;
|
|
107
|
-
|
|
108
|
-
/**
|
|
109
|
-
* @param {string | string[]} endpoint The endpoint url. Usually `ws://ip:9944` or `wss://ip:9944`, may provide an array of endpoint strings.
|
|
110
|
-
* @param {number | false} autoConnectMs Whether to connect automatically or not (default). Provided value is used as a delay between retries.
|
|
111
|
-
* @param {Record<string, string>} headers The headers provided to the underlying WebSocket
|
|
112
|
-
* @param {number} [timeout] Custom timeout value used per request . Defaults to `DEFAULT_TIMEOUT_MS`
|
|
113
|
-
* @param {number} [cacheCapacity] Custom size of the WsProvider LRUCache. Defaults to `DEFAULT_CAPACITY` (1024)
|
|
114
|
-
* @param {number} [cacheTtl] Custom TTL of the WsProvider LRUCache. Determines how long an object can live in the cache. Defaults to DEFAULT_TTL` (30000)
|
|
115
|
-
*/
|
|
116
|
-
constructor (endpoint: string | string[] = defaults.WS_URL, autoConnectMs: number | false = RETRY_DELAY, headers: Record<string, string> = {}, timeout?: number, cacheCapacity?: number, cacheTtl?: number | null) {
|
|
117
|
-
const endpoints = Array.isArray(endpoint)
|
|
118
|
-
? endpoint
|
|
119
|
-
: [endpoint];
|
|
120
|
-
|
|
121
|
-
if (endpoints.length === 0) {
|
|
122
|
-
throw new Error('WsProvider requires at least one Endpoint');
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
endpoints.forEach((endpoint) => {
|
|
126
|
-
if (!/^(wss|ws):\/\//.test(endpoint)) {
|
|
127
|
-
throw new Error(`Endpoint should start with 'ws://', received '${endpoint}'`);
|
|
128
|
-
}
|
|
129
|
-
});
|
|
130
|
-
const ttl = cacheTtl === undefined ? DEFAULT_TTL : cacheTtl;
|
|
131
|
-
|
|
132
|
-
this.#callCache = new LRUCache(cacheCapacity === 0 ? 0 : cacheCapacity || DEFAULT_CAPACITY, ttl);
|
|
133
|
-
this.#ttl = cacheTtl;
|
|
134
|
-
this.#cacheCapacity = cacheCapacity || DEFAULT_CAPACITY;
|
|
135
|
-
this.#eventemitter = new EventEmitter();
|
|
136
|
-
this.#autoConnectMs = autoConnectMs || 0;
|
|
137
|
-
this.#coder = new RpcCoder();
|
|
138
|
-
this.#endpointIndex = -1;
|
|
139
|
-
this.#endpoints = endpoints;
|
|
140
|
-
this.#headers = headers;
|
|
141
|
-
this.#websocket = null;
|
|
142
|
-
this.#stats = {
|
|
143
|
-
active: { requests: 0, subscriptions: 0 },
|
|
144
|
-
total: defaultEndpointStats()
|
|
145
|
-
};
|
|
146
|
-
this.#endpointStats = defaultEndpointStats();
|
|
147
|
-
this.#timeout = timeout || DEFAULT_TIMEOUT_MS;
|
|
148
|
-
|
|
149
|
-
if (autoConnectMs && autoConnectMs > 0) {
|
|
150
|
-
this.connectWithRetry().catch(noop);
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
this.#isReadyPromise = new Promise((resolve): void => {
|
|
154
|
-
this.#eventemitter.once('connected', (): void => {
|
|
155
|
-
resolve(this);
|
|
156
|
-
});
|
|
157
|
-
});
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
/**
|
|
161
|
-
* @summary `true` when this provider supports subscriptions
|
|
162
|
-
*/
|
|
163
|
-
public get hasSubscriptions (): boolean {
|
|
164
|
-
return !!true;
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
/**
|
|
168
|
-
* @summary `true` when this provider supports clone()
|
|
169
|
-
*/
|
|
170
|
-
public get isClonable (): boolean {
|
|
171
|
-
return !!true;
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
/**
|
|
175
|
-
* @summary Whether the node is connected or not.
|
|
176
|
-
* @return {boolean} true if connected
|
|
177
|
-
*/
|
|
178
|
-
public get isConnected (): boolean {
|
|
179
|
-
return this.#isConnected;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
/**
|
|
183
|
-
* @description Promise that resolves the first time we are connected and loaded
|
|
184
|
-
*/
|
|
185
|
-
public get isReady (): Promise<WsProvider> {
|
|
186
|
-
return this.#isReadyPromise;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
public get endpoint (): string {
|
|
190
|
-
return this.#endpoints[this.#endpointIndex];
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
/**
|
|
194
|
-
* @description Returns a clone of the object
|
|
195
|
-
*/
|
|
196
|
-
public clone (): WsProvider {
|
|
197
|
-
return new WsProvider(this.#endpoints);
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
protected selectEndpointIndex (endpoints: string[]): number {
|
|
201
|
-
return (this.#endpointIndex + 1) % endpoints.length;
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
/**
|
|
205
|
-
* @summary Manually connect
|
|
206
|
-
* @description The [[WsProvider]] connects automatically by default, however if you decided otherwise, you may
|
|
207
|
-
* connect manually using this method.
|
|
208
|
-
*/
|
|
209
|
-
// eslint-disable-next-line @typescript-eslint/require-await
|
|
210
|
-
public async connect (): Promise<void> {
|
|
211
|
-
if (this.#websocket) {
|
|
212
|
-
throw new Error('WebSocket is already connected');
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
try {
|
|
216
|
-
this.#endpointIndex = this.selectEndpointIndex(this.#endpoints);
|
|
217
|
-
|
|
218
|
-
// the as here is Deno-specific - not available on the globalThis
|
|
219
|
-
this.#websocket = typeof xglobal.WebSocket !== 'undefined' && isChildClass(xglobal.WebSocket as unknown as Class<WebSocket>, WebSocket)
|
|
220
|
-
? new WebSocket(this.endpoint)
|
|
221
|
-
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
222
|
-
// @ts-ignore - WS may be an instance of ws, which supports options
|
|
223
|
-
: new WebSocket(this.endpoint, undefined, {
|
|
224
|
-
headers: this.#headers
|
|
225
|
-
});
|
|
226
|
-
|
|
227
|
-
if (this.#websocket) {
|
|
228
|
-
this.#websocket.onclose = this.#onSocketClose;
|
|
229
|
-
this.#websocket.onerror = this.#onSocketError;
|
|
230
|
-
this.#websocket.onmessage = this.#onSocketMessage;
|
|
231
|
-
this.#websocket.onopen = this.#onSocketOpen;
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
// timeout any handlers that have not had a response
|
|
235
|
-
this.#timeoutId = setInterval(() => this.#timeoutHandlers(), TIMEOUT_INTERVAL);
|
|
236
|
-
} catch (error) {
|
|
237
|
-
l.error(error);
|
|
238
|
-
|
|
239
|
-
this.#emit('error', error);
|
|
240
|
-
|
|
241
|
-
throw error;
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
/**
|
|
246
|
-
* @description Connect, never throwing an error, but rather forcing a retry
|
|
247
|
-
*/
|
|
248
|
-
public async connectWithRetry (): Promise<void> {
|
|
249
|
-
if (this.#autoConnectMs > 0) {
|
|
250
|
-
try {
|
|
251
|
-
await this.connect();
|
|
252
|
-
} catch {
|
|
253
|
-
setTimeout((): void => {
|
|
254
|
-
this.connectWithRetry().catch(noop);
|
|
255
|
-
}, this.#autoConnectMs);
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
/**
|
|
261
|
-
* @description Manually disconnect from the connection, clearing auto-connect logic
|
|
262
|
-
*/
|
|
263
|
-
// eslint-disable-next-line @typescript-eslint/require-await
|
|
264
|
-
public async disconnect (): Promise<void> {
|
|
265
|
-
// switch off autoConnect, we are in manual mode now
|
|
266
|
-
this.#autoConnectMs = 0;
|
|
267
|
-
|
|
268
|
-
try {
|
|
269
|
-
if (this.#websocket) {
|
|
270
|
-
// 1000 - Normal closure; the connection successfully completed
|
|
271
|
-
this.#websocket.close(1000);
|
|
272
|
-
}
|
|
273
|
-
} catch (error) {
|
|
274
|
-
l.error(error);
|
|
275
|
-
|
|
276
|
-
this.#emit('error', error);
|
|
277
|
-
|
|
278
|
-
throw error;
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
/**
|
|
283
|
-
* @description Returns the connection stats
|
|
284
|
-
*/
|
|
285
|
-
public get stats (): ProviderStats {
|
|
286
|
-
return {
|
|
287
|
-
active: {
|
|
288
|
-
requests: Object.keys(this.#handlers).length,
|
|
289
|
-
subscriptions: Object.keys(this.#subscriptions).length
|
|
290
|
-
},
|
|
291
|
-
total: this.#stats.total
|
|
292
|
-
};
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
/**
|
|
296
|
-
* @description Returns the connection stats
|
|
297
|
-
*/
|
|
298
|
-
public get ttl (): number | null | undefined {
|
|
299
|
-
return this.#ttl;
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
public get endpointStats (): EndpointStats {
|
|
303
|
-
return this.#endpointStats;
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
/**
|
|
307
|
-
* @summary Listens on events after having subscribed using the [[subscribe]] function.
|
|
308
|
-
* @param {ProviderInterfaceEmitted} type Event
|
|
309
|
-
* @param {ProviderInterfaceEmitCb} sub Callback
|
|
310
|
-
* @return unsubscribe function
|
|
311
|
-
*/
|
|
312
|
-
public on (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): () => void {
|
|
313
|
-
this.#eventemitter.on(type, sub);
|
|
314
|
-
|
|
315
|
-
return (): void => {
|
|
316
|
-
this.#eventemitter.removeListener(type, sub);
|
|
317
|
-
};
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
/**
|
|
321
|
-
* @summary Send JSON data using WebSockets to configured HTTP Endpoint or queue.
|
|
322
|
-
* @param method The RPC methods to execute
|
|
323
|
-
* @param params Encoded parameters as applicable for the method
|
|
324
|
-
* @param subscription Subscription details (internally used)
|
|
325
|
-
*/
|
|
326
|
-
public send <T = any> (method: string, params: unknown[], isCacheable?: boolean, subscription?: SubscriptionHandler): Promise<T> {
|
|
327
|
-
this.#endpointStats.requests++;
|
|
328
|
-
this.#stats.total.requests++;
|
|
329
|
-
|
|
330
|
-
const [id, body] = this.#coder.encodeJson(method, params);
|
|
331
|
-
|
|
332
|
-
if (this.#cacheCapacity === 0) {
|
|
333
|
-
return this.#send(id, body, method, params, subscription);
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
const cacheKey = isCacheable ? `${method}::${stringify(params)}` : '';
|
|
337
|
-
let resultPromise: Promise<T> | null = isCacheable
|
|
338
|
-
? this.#callCache.get(cacheKey)
|
|
339
|
-
: null;
|
|
340
|
-
|
|
341
|
-
if (!resultPromise) {
|
|
342
|
-
resultPromise = this.#send(id, body, method, params, subscription);
|
|
343
|
-
|
|
344
|
-
if (isCacheable) {
|
|
345
|
-
this.#callCache.set(cacheKey, resultPromise);
|
|
346
|
-
}
|
|
347
|
-
} else {
|
|
348
|
-
this.#endpointStats.cached++;
|
|
349
|
-
this.#stats.total.cached++;
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
return resultPromise;
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
async #send <T> (id: number, body: string, method: string, params: unknown[], subscription?: SubscriptionHandler): Promise<T> {
|
|
356
|
-
return new Promise<T>((resolve, reject): void => {
|
|
357
|
-
try {
|
|
358
|
-
if (!this.isConnected || this.#websocket === null) {
|
|
359
|
-
throw new Error('WebSocket is not connected');
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
const callback = (error?: Error | null, result?: T): void => {
|
|
363
|
-
error
|
|
364
|
-
? reject(error)
|
|
365
|
-
: resolve(result as T);
|
|
366
|
-
};
|
|
367
|
-
|
|
368
|
-
l.debug(() => ['calling', method, body]);
|
|
369
|
-
|
|
370
|
-
this.#handlers[id] = {
|
|
371
|
-
callback,
|
|
372
|
-
method,
|
|
373
|
-
params,
|
|
374
|
-
start: Date.now(),
|
|
375
|
-
subscription
|
|
376
|
-
};
|
|
377
|
-
|
|
378
|
-
const bytesSent = body.length;
|
|
379
|
-
|
|
380
|
-
this.#endpointStats.bytesSent += bytesSent;
|
|
381
|
-
this.#stats.total.bytesSent += bytesSent;
|
|
382
|
-
|
|
383
|
-
this.#websocket.send(body);
|
|
384
|
-
} catch (error) {
|
|
385
|
-
this.#endpointStats.errors++;
|
|
386
|
-
this.#stats.total.errors++;
|
|
387
|
-
|
|
388
|
-
const rpcError: RpcError = error as RpcError;
|
|
389
|
-
const failedRequest = `\nFailed WS Request: ${JSON.stringify({ method, params })}`;
|
|
390
|
-
|
|
391
|
-
// Provide WS Request alongside the error
|
|
392
|
-
rpcError.message = `${rpcError.message}${failedRequest}`;
|
|
393
|
-
reject(rpcError);
|
|
394
|
-
}
|
|
395
|
-
});
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
/**
|
|
399
|
-
* @name subscribe
|
|
400
|
-
* @summary Allows subscribing to a specific event.
|
|
401
|
-
*
|
|
402
|
-
* @example
|
|
403
|
-
* <BR>
|
|
404
|
-
*
|
|
405
|
-
* ```javascript
|
|
406
|
-
* const provider = new WsProvider('ws://127.0.0.1:9944');
|
|
407
|
-
* const rpc = new Rpc(provider);
|
|
408
|
-
*
|
|
409
|
-
* rpc.state.subscribeStorage([[storage.system.account, <Address>]], (_, values) => {
|
|
410
|
-
* console.log(values)
|
|
411
|
-
* }).then((subscriptionId) => {
|
|
412
|
-
* console.log('balance changes subscription id: ', subscriptionId)
|
|
413
|
-
* })
|
|
414
|
-
* ```
|
|
415
|
-
*/
|
|
416
|
-
public subscribe (type: string, method: string, params: unknown[], callback: ProviderInterfaceCallback): Promise<number | string> {
|
|
417
|
-
this.#endpointStats.subscriptions++;
|
|
418
|
-
this.#stats.total.subscriptions++;
|
|
419
|
-
|
|
420
|
-
// subscriptions are not cached, LRU applies to .at(<blockHash>) only
|
|
421
|
-
return this.send<number | string>(method, params, false, { callback, type });
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
/**
|
|
425
|
-
* @summary Allows unsubscribing to subscriptions made with [[subscribe]].
|
|
426
|
-
*/
|
|
427
|
-
public async unsubscribe (type: string, method: string, id: number | string): Promise<boolean> {
|
|
428
|
-
const subscription = `${type}::${id}`;
|
|
429
|
-
|
|
430
|
-
// FIXME This now could happen with re-subscriptions. The issue is that with a re-sub
|
|
431
|
-
// the assigned id now does not match what the API user originally received. It has
|
|
432
|
-
// a slight complication in solving - since we cannot rely on the send id, but rather
|
|
433
|
-
// need to find the actual subscription id to map it
|
|
434
|
-
if (isUndefined(this.#subscriptions[subscription])) {
|
|
435
|
-
l.debug(() => `Unable to find active subscription=${subscription}`);
|
|
436
|
-
|
|
437
|
-
return false;
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
delete this.#subscriptions[subscription];
|
|
441
|
-
|
|
442
|
-
try {
|
|
443
|
-
return this.isConnected && !isNull(this.#websocket)
|
|
444
|
-
? this.send<boolean>(method, [id])
|
|
445
|
-
: true;
|
|
446
|
-
} catch {
|
|
447
|
-
return false;
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
#emit = (type: ProviderInterfaceEmitted, ...args: unknown[]): void => {
|
|
452
|
-
this.#eventemitter.emit(type, ...args);
|
|
453
|
-
};
|
|
454
|
-
|
|
455
|
-
#onSocketClose = (event: CloseEvent): void => {
|
|
456
|
-
const error = new Error(`disconnected from ${this.endpoint}: ${event.code}:: ${event.reason || getWSErrorString(event.code)}`);
|
|
457
|
-
|
|
458
|
-
if (this.#autoConnectMs > 0) {
|
|
459
|
-
l.error(error.message);
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
this.#isConnected = false;
|
|
463
|
-
|
|
464
|
-
if (this.#websocket) {
|
|
465
|
-
this.#websocket.onclose = null;
|
|
466
|
-
this.#websocket.onerror = null;
|
|
467
|
-
this.#websocket.onmessage = null;
|
|
468
|
-
this.#websocket.onopen = null;
|
|
469
|
-
this.#websocket = null;
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
if (this.#timeoutId) {
|
|
473
|
-
clearInterval(this.#timeoutId);
|
|
474
|
-
this.#timeoutId = null;
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
// reject all hanging requests
|
|
478
|
-
eraseRecord(this.#handlers, (h) => {
|
|
479
|
-
try {
|
|
480
|
-
h.callback(error, undefined);
|
|
481
|
-
} catch (err) {
|
|
482
|
-
// does not throw
|
|
483
|
-
l.error(err);
|
|
484
|
-
}
|
|
485
|
-
});
|
|
486
|
-
eraseRecord(this.#waitingForId);
|
|
487
|
-
|
|
488
|
-
// Reset stats for active endpoint
|
|
489
|
-
this.#endpointStats = defaultEndpointStats();
|
|
490
|
-
|
|
491
|
-
this.#emit('disconnected');
|
|
492
|
-
|
|
493
|
-
if (this.#autoConnectMs > 0) {
|
|
494
|
-
setTimeout((): void => {
|
|
495
|
-
this.connectWithRetry().catch(noop);
|
|
496
|
-
}, this.#autoConnectMs);
|
|
497
|
-
}
|
|
498
|
-
};
|
|
499
|
-
|
|
500
|
-
#onSocketError = (error: Event): void => {
|
|
501
|
-
l.debug(() => ['socket error', error]);
|
|
502
|
-
this.#emit('error', error);
|
|
503
|
-
};
|
|
504
|
-
|
|
505
|
-
#onSocketMessage = (message: MessageEvent<string>): void => {
|
|
506
|
-
l.debug(() => ['received', message.data]);
|
|
507
|
-
|
|
508
|
-
const bytesRecv = message.data.length;
|
|
509
|
-
|
|
510
|
-
this.#endpointStats.bytesRecv += bytesRecv;
|
|
511
|
-
this.#stats.total.bytesRecv += bytesRecv;
|
|
512
|
-
|
|
513
|
-
const response = JSON.parse(message.data) as JsonRpcResponse<string>;
|
|
514
|
-
|
|
515
|
-
return isUndefined(response.method)
|
|
516
|
-
? this.#onSocketMessageResult(response)
|
|
517
|
-
: this.#onSocketMessageSubscribe(response);
|
|
518
|
-
};
|
|
519
|
-
|
|
520
|
-
#onSocketMessageResult = (response: JsonRpcResponse<string>): void => {
|
|
521
|
-
const handler = this.#handlers[response.id];
|
|
522
|
-
|
|
523
|
-
if (!handler) {
|
|
524
|
-
l.debug(() => `Unable to find handler for id=${response.id}`);
|
|
525
|
-
|
|
526
|
-
return;
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
try {
|
|
530
|
-
const { method, params, subscription } = handler;
|
|
531
|
-
const result = this.#coder.decodeResponse<string>(response);
|
|
532
|
-
|
|
533
|
-
// first send the result - in case of subs, we may have an update
|
|
534
|
-
// immediately if we have some queued results already
|
|
535
|
-
handler.callback(null, result);
|
|
536
|
-
|
|
537
|
-
if (subscription) {
|
|
538
|
-
const subId = `${subscription.type}::${result}`;
|
|
539
|
-
|
|
540
|
-
this.#subscriptions[subId] = objectSpread({}, subscription, {
|
|
541
|
-
method,
|
|
542
|
-
params
|
|
543
|
-
});
|
|
544
|
-
|
|
545
|
-
// if we have a result waiting for this subscription already
|
|
546
|
-
if (this.#waitingForId[subId]) {
|
|
547
|
-
this.#onSocketMessageSubscribe(this.#waitingForId[subId]);
|
|
548
|
-
}
|
|
549
|
-
}
|
|
550
|
-
} catch (error) {
|
|
551
|
-
this.#endpointStats.errors++;
|
|
552
|
-
this.#stats.total.errors++;
|
|
553
|
-
|
|
554
|
-
handler.callback(error as Error, undefined);
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
delete this.#handlers[response.id];
|
|
558
|
-
};
|
|
559
|
-
|
|
560
|
-
#onSocketMessageSubscribe = (response: JsonRpcResponse<unknown>): void => {
|
|
561
|
-
if (!response.method) {
|
|
562
|
-
throw new Error('No method found in JSONRPC response');
|
|
563
|
-
}
|
|
564
|
-
|
|
565
|
-
const method = ALIASES[response.method] || response.method;
|
|
566
|
-
const subId = `${method}::${response.params.subscription}`;
|
|
567
|
-
const handler = this.#subscriptions[subId];
|
|
568
|
-
|
|
569
|
-
if (!handler) {
|
|
570
|
-
// store the JSON, we could have out-of-order subid coming in
|
|
571
|
-
this.#waitingForId[subId] = response;
|
|
572
|
-
|
|
573
|
-
l.debug(() => `Unable to find handler for subscription=${subId}`);
|
|
574
|
-
|
|
575
|
-
return;
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
// housekeeping
|
|
579
|
-
delete this.#waitingForId[subId];
|
|
580
|
-
|
|
581
|
-
try {
|
|
582
|
-
const result = this.#coder.decodeResponse(response);
|
|
583
|
-
|
|
584
|
-
handler.callback(null, result);
|
|
585
|
-
} catch (error) {
|
|
586
|
-
this.#endpointStats.errors++;
|
|
587
|
-
this.#stats.total.errors++;
|
|
588
|
-
|
|
589
|
-
handler.callback(error as Error, undefined);
|
|
590
|
-
}
|
|
591
|
-
};
|
|
592
|
-
|
|
593
|
-
#onSocketOpen = (): boolean => {
|
|
594
|
-
if (this.#websocket === null) {
|
|
595
|
-
throw new Error('WebSocket cannot be null in onOpen');
|
|
596
|
-
}
|
|
597
|
-
|
|
598
|
-
l.debug(() => ['connected to', this.endpoint]);
|
|
599
|
-
|
|
600
|
-
this.#isConnected = true;
|
|
601
|
-
|
|
602
|
-
this.#resubscribe();
|
|
603
|
-
|
|
604
|
-
this.#emit('connected');
|
|
605
|
-
|
|
606
|
-
return true;
|
|
607
|
-
};
|
|
608
|
-
|
|
609
|
-
#resubscribe = (): void => {
|
|
610
|
-
const subscriptions = this.#subscriptions;
|
|
611
|
-
|
|
612
|
-
this.#subscriptions = {};
|
|
613
|
-
|
|
614
|
-
Promise.all(Object.keys(subscriptions).map(async (id): Promise<void> => {
|
|
615
|
-
const { callback, method, params, type } = subscriptions[id];
|
|
616
|
-
|
|
617
|
-
// only re-create subscriptions which are not in author (only area where
|
|
618
|
-
// transactions are created, i.e. submissions such as 'author_submitAndWatchExtrinsic'
|
|
619
|
-
// are not included (and will not be re-broadcast)
|
|
620
|
-
if (type.startsWith('author_')) {
|
|
621
|
-
return;
|
|
622
|
-
}
|
|
623
|
-
|
|
624
|
-
try {
|
|
625
|
-
await this.subscribe(type, method, params, callback);
|
|
626
|
-
} catch (error) {
|
|
627
|
-
l.error(error);
|
|
628
|
-
}
|
|
629
|
-
})).catch(l.error);
|
|
630
|
-
};
|
|
631
|
-
|
|
632
|
-
#timeoutHandlers = (): void => {
|
|
633
|
-
const now = Date.now();
|
|
634
|
-
const ids = Object.keys(this.#handlers);
|
|
635
|
-
|
|
636
|
-
for (let i = 0, count = ids.length; i < count; i++) {
|
|
637
|
-
const handler = this.#handlers[ids[i]];
|
|
638
|
-
|
|
639
|
-
if ((now - handler.start) > this.#timeout) {
|
|
640
|
-
try {
|
|
641
|
-
handler.callback(new Error(`No response received from RPC endpoint in ${this.#timeout / 1000}s`), undefined);
|
|
642
|
-
} catch {
|
|
643
|
-
// ignore
|
|
644
|
-
}
|
|
645
|
-
|
|
646
|
-
this.#endpointStats.timeout++;
|
|
647
|
-
this.#stats.total.timeout++;
|
|
648
|
-
delete this.#handlers[ids[i]];
|
|
649
|
-
}
|
|
650
|
-
}
|
|
651
|
-
};
|
|
652
|
-
}
|