From 5af98cc89ebd3d12d752c58017652be66b9da6af Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Sat, 5 Sep 2020 14:30:55 +0200 Subject: [PATCH] Retry WS on initial connection failures (#2585) --- packages/rpc-provider/src/ws/Provider.ts | 28 ++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/packages/rpc-provider/src/ws/Provider.ts b/packages/rpc-provider/src/ws/Provider.ts index 3a384ad614..252f22bf0e 100644 --- a/packages/rpc-provider/src/ws/Provider.ts +++ b/packages/rpc-provider/src/ws/Provider.ts @@ -36,6 +36,8 @@ const ALIASSES: { [index: string]: string } = { chain_unsubscribeFinalisedHeads: 'chain_unsubscribeFinalizedHeads' }; +const RETRY_DELAY = 1000; + const l = logger('api-ws'); /** @@ -87,7 +89,7 @@ export default class WsProvider implements ProviderInterface { * @param {string | string[]} endpoint The endpoint url. Usually `ws://ip:9944` or `wss://ip:9944`, may provide an array of endpoint strings. * @param {boolean} autoConnect Whether to connect automatically or not. */ - constructor (endpoint: string | string[] = defaults.WS_URL, autoConnectMs: number | false = 1000, headers: Record = {}) { + constructor (endpoint: string | string[] = defaults.WS_URL, autoConnectMs: number | false = RETRY_DELAY, headers: Record = {}) { const endpoints = Array.isArray(endpoint) ? endpoint : [endpoint]; @@ -107,8 +109,9 @@ export default class WsProvider implements ProviderInterface { this.#websocket = null; if (autoConnectMs > 0) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - this.connect(); + this.connectWithRetry().catch((): void => { + // does not throw + }); } } @@ -163,6 +166,21 @@ export default class WsProvider implements ProviderInterface { } } + /** + * @description Connect, never throwing an error, but rather forcing a retry + */ + public async connectWithRetry (): Promise { + try { + await this.connect(); + } catch (error) { + setTimeout((): void => { + this.connectWithRetry().catch((): void => { + // does not throw + }); + }, this.#autoConnectMs || RETRY_DELAY); + } + } + /** * @description Manually disconnect from the connection, clearing autoconnect logic */ @@ -304,7 +322,9 @@ export default class WsProvider implements ProviderInterface { if (this.#autoConnectMs > 0) { setTimeout((): void => { - this.connect().catch(() => { /* noop */ }); + this.connectWithRetry().catch(() => { + // does not throw + }); }, this.#autoConnectMs); } }