Multiple Endpoint support for WsProvider (#2234)
* Fix incorrect ws connect test cases * Make endpoint an array of endpoints * Add requirement that WsProvider endpoint arrays must not be empty * Simple endpoint increment * Add multi-endpoint test for endpoint closing its connection * Implement endpoint round robin * Revert change to mock's TEST_WS_URL * Address Lint errors * Change endpoint variable to plural in WsProvider Co-authored-by: Jaco Greeff <jacogr@gmail.com> * Review corrections to WsProvider * Grouping improvement in WsProvider connect * Correct endpoint logging to only show the specific endpoint involved * Correct ordering of endpoint increment on connect Co-authored-by: Jaco Greeff <jacogr@gmail.com>
This commit is contained in:
co-authored by
Jaco Greeff
parent
58f0df1ef0
commit
102a06b0f2
@@ -65,7 +65,7 @@ const l = logger('api-ws');
|
||||
export default class WsProvider implements WSProviderInterface {
|
||||
readonly #coder: Coder;
|
||||
|
||||
readonly #endpoint: string;
|
||||
readonly #endpoints: string[];
|
||||
|
||||
readonly #eventemitter: EventEmitter;
|
||||
|
||||
@@ -77,6 +77,8 @@ export default class WsProvider implements WSProviderInterface {
|
||||
|
||||
#autoConnectMs: number;
|
||||
|
||||
#endpointIndex: number;
|
||||
|
||||
#isConnected = false;
|
||||
|
||||
#subscriptions: Record<string, WsStateSubscription> = {};
|
||||
@@ -84,16 +86,25 @@ export default class WsProvider implements WSProviderInterface {
|
||||
#websocket: WebSocket | null;
|
||||
|
||||
/**
|
||||
* @param {string} endpoint The endpoint url. Usually `ws://ip:9944` or `wss://ip:9944`
|
||||
* @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 = defaults.WS_URL, autoConnectMs: number | false = 1000) {
|
||||
assert(/^(wss|ws):\/\//.test(endpoint), `Endpoint should start with 'ws://', received '${endpoint}'`);
|
||||
constructor (endpoint: string | string[] = defaults.WS_URL, autoConnectMs: number | false = 1000) {
|
||||
const endpoints = Array.isArray(endpoint)
|
||||
? endpoint
|
||||
: [endpoint];
|
||||
|
||||
assert(endpoints.length !== 0, 'WsProvider requires at least one Endpoint');
|
||||
|
||||
endpoints.forEach((endpoint) => {
|
||||
assert(/^(wss|ws):\/\//.test(endpoint), `Endpoint should start with 'ws://', received '${endpoint}'`);
|
||||
});
|
||||
|
||||
this.#eventemitter = new EventEmitter();
|
||||
this.#autoConnectMs = autoConnectMs || 0;
|
||||
this.#coder = new Coder();
|
||||
this.#endpoint = endpoint;
|
||||
this.#endpointIndex = -1;
|
||||
this.#endpoints = endpoints;
|
||||
this.#websocket = null;
|
||||
|
||||
if (autoConnectMs > 0) {
|
||||
@@ -112,7 +123,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
* @description Returns a clone of the object
|
||||
*/
|
||||
public clone (): WsProvider {
|
||||
return new WsProvider(this.#endpoint);
|
||||
return new WsProvider(this.#endpoints);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -122,9 +133,11 @@ export default class WsProvider implements WSProviderInterface {
|
||||
*/
|
||||
public async connect (): Promise<void> {
|
||||
try {
|
||||
this.#endpointIndex = (this.#endpointIndex + 1) % this.#endpoints.length;
|
||||
|
||||
const WS = await getWSClass();
|
||||
|
||||
this.#websocket = new WS(this.#endpoint);
|
||||
this.#websocket = new WS(this.#endpoints[this.#endpointIndex]);
|
||||
this.#websocket.onclose = this.#onSocketClose;
|
||||
this.#websocket.onerror = this.#onSocketError;
|
||||
this.#websocket.onmessage = this.#onSocketMessage;
|
||||
@@ -268,7 +281,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
|
||||
#onSocketClose = (event: CloseEvent): void => {
|
||||
if (this.#autoConnectMs > 0) {
|
||||
l.error(`disconnected from ${this.#endpoint} code: '${event.code}' reason: '${event.reason}'`);
|
||||
l.error(`disconnected from ${this.#endpoints[this.#endpointIndex]} code: '${event.code}' reason: '${event.reason}'`);
|
||||
}
|
||||
|
||||
this.#isConnected = false;
|
||||
@@ -363,7 +376,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
#onSocketOpen = (): boolean => {
|
||||
assert(!isNull(this.#websocket), 'WebSocket cannot be null in onOpen');
|
||||
|
||||
l.debug((): any[] => ['connected to', this.#endpoint]);
|
||||
l.debug((): any[] => ['connected to', this.#endpoints[this.#endpointIndex]]);
|
||||
|
||||
this.#isConnected = true;
|
||||
|
||||
|
||||
@@ -6,17 +6,23 @@ import WsProvider from './';
|
||||
import { Mock } from './../mock/types';
|
||||
import { mockWs, TEST_WS_URL } from '../../test/mockWs';
|
||||
|
||||
function sleepMs (ms = 0): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
describe('onConnect', (): void => {
|
||||
let mock: Mock;
|
||||
let mocks: Mock[];
|
||||
|
||||
beforeEach((): void => {
|
||||
mock = mockWs([]);
|
||||
mocks = [mockWs([])];
|
||||
});
|
||||
|
||||
afterEach((): void => {
|
||||
if (mock) {
|
||||
mock.done();
|
||||
}
|
||||
mocks.forEach((m) => {
|
||||
if (m) {
|
||||
m.done();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('Does not connect when autoConnect is false', (): void => {
|
||||
@@ -25,19 +31,101 @@ describe('onConnect', (): void => {
|
||||
expect(provider.isConnected()).toBe(false);
|
||||
});
|
||||
|
||||
it('Does connect when autoConnect is true', (): void => {
|
||||
it('Does connect when autoConnect is true', async () => {
|
||||
const provider: WsProvider = new WsProvider(TEST_WS_URL, 1000);
|
||||
|
||||
expect(provider.isConnected()).not.toBe(true);
|
||||
await sleepMs(10); // Hack to give the provider time to connect
|
||||
expect(provider.isConnected()).toBe(true);
|
||||
});
|
||||
|
||||
it('Creates a new WebSocket instance by calling the connect() method', (): void => {
|
||||
it('Creates a new WebSocket instance by calling the connect() method', async () => {
|
||||
const provider: WsProvider = new WsProvider(TEST_WS_URL, 0);
|
||||
|
||||
expect(provider.isConnected()).toBe(false);
|
||||
expect(mocks[0].server.clients().length).toBe(0);
|
||||
|
||||
provider.connect();
|
||||
await provider.connect();
|
||||
await sleepMs(10); // Hack to give the provider time to connect
|
||||
|
||||
expect(provider.isConnected()).not.toBe(true);
|
||||
expect(provider.isConnected()).toBe(true);
|
||||
expect(mocks[0].server.clients().length).toBe(1);
|
||||
});
|
||||
|
||||
it('Connects to first endpoint when an array is given', async () => {
|
||||
const provider: WsProvider = new WsProvider([TEST_WS_URL], 0);
|
||||
|
||||
await provider.connect();
|
||||
await sleepMs(10); // Hack to give the provider time to connect
|
||||
|
||||
expect(provider.isConnected()).toBe(true);
|
||||
});
|
||||
|
||||
it('Connects to the second endpoint when the first is unreachable', async () => {
|
||||
/* eslint-disable @typescript-eslint/no-empty-function */
|
||||
jest.spyOn(console, 'error').mockImplementation((): void => {});
|
||||
|
||||
const endpoints: string[] = ['ws://localhost:9956', TEST_WS_URL];
|
||||
const provider: WsProvider = new WsProvider(endpoints, 10);
|
||||
|
||||
await sleepMs(50); // Hack to give the provider time to connect
|
||||
|
||||
expect(provider.isConnected()).toBe(true);
|
||||
});
|
||||
|
||||
it('Connects to the second endpoint when the first is dropped', async () => {
|
||||
const endpoints: string[] = [TEST_WS_URL, 'ws://localhost:9957'];
|
||||
|
||||
mocks.push(mockWs([], endpoints[1]));
|
||||
|
||||
const provider: WsProvider = new WsProvider(endpoints, 10);
|
||||
|
||||
await sleepMs(20); // Hack to give the provider time to connect
|
||||
// Check that first server is connected
|
||||
expect(mocks[0].server.clients().length).toBe(1);
|
||||
expect(mocks[1].server.clients().length).toBe(0);
|
||||
|
||||
// Close connection from first server
|
||||
mocks[0].server.clients()[0].close();
|
||||
await sleepMs(50);
|
||||
|
||||
// Check that second server is connected
|
||||
expect(mocks[1].server.clients().length).toBe(1);
|
||||
expect(provider.isConnected()).toBe(true);
|
||||
});
|
||||
|
||||
it('Round-robin of endpoints on WsProvider', async () => {
|
||||
const rounds = 5;
|
||||
const endpoints: string[] = [
|
||||
TEST_WS_URL,
|
||||
'ws://localhost:9956',
|
||||
'ws://localhost:9957',
|
||||
'ws://invalid:9956',
|
||||
'ws://localhost:9958'
|
||||
];
|
||||
|
||||
mocks.push(mockWs([], endpoints[1]));
|
||||
mocks.push(mockWs([], endpoints[2]));
|
||||
mocks.push(mockWs([], endpoints[4]));
|
||||
|
||||
const mockNext = [
|
||||
mocks[1],
|
||||
mocks[2],
|
||||
mocks[3],
|
||||
mocks[0]
|
||||
];
|
||||
const provider: WsProvider = new WsProvider(endpoints, 10);
|
||||
|
||||
for (let round = 0; round < rounds; round++) {
|
||||
for (let index = 0; index < mocks.length; index++) {
|
||||
await sleepMs(50); // Hack to give the provider time to connect
|
||||
// Check that first server is connected and the next one isn't
|
||||
expect(mocks[index].server.clients().length).toBe(1);
|
||||
expect(mockNext[index].server.clients().length).toBe(0);
|
||||
expect(provider.isConnected()).toBe(true);
|
||||
|
||||
// Close connection from first server
|
||||
mocks[index].server.clients()[0].close();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -29,3 +29,42 @@ describe('Ws', (): void => {
|
||||
).toEqual(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Endpoint Parsing', (): void => {
|
||||
it('Succeeds when WsProvider endpoint is a valid string', () => {
|
||||
/* eslint-disable no-new */
|
||||
new WsProvider(TEST_WS_URL, 0);
|
||||
});
|
||||
|
||||
it('Throws when WsProvider endpoint is an invalid string', () => {
|
||||
expect(() => {
|
||||
/* eslint-disable no-new */
|
||||
new WsProvider('http://127.0.0.1:9955', 0);
|
||||
}).toThrowError(/^Endpoint should start with /);
|
||||
});
|
||||
|
||||
it('Succeeds when WsProvider endpoint is a valid array', () => {
|
||||
const endpoints: string[] = ['ws://127.0.0.1:9955', 'wss://testnet.io:9944', 'ws://mychain.com:9933'];
|
||||
|
||||
/* eslint-disable no-new */
|
||||
new WsProvider(endpoints, 0);
|
||||
});
|
||||
|
||||
it('Throws when WsProvider endpoint is an empty array', () => {
|
||||
const endpoints: string[] = [];
|
||||
|
||||
expect(() => {
|
||||
/* eslint-disable no-new */
|
||||
new WsProvider(endpoints, 0);
|
||||
}).toThrowError('WsProvider requires at least one Endpoint');
|
||||
});
|
||||
|
||||
it('Throws when WsProvider endpoint is an invalid array', () => {
|
||||
const endpoints: string[] = ['ws://127.0.0.1:9955', 'http://bad.co:9944', 'ws://mychain.com:9933'];
|
||||
|
||||
expect(() => {
|
||||
/* eslint-disable no-new */
|
||||
new WsProvider(endpoints, 0);
|
||||
}).toThrowError(/^Endpoint should start with /);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,8 +6,6 @@ import { Server } from 'mock-socket';
|
||||
|
||||
const TEST_WS_URL = 'ws://localhost:9955';
|
||||
|
||||
let server: Server;
|
||||
|
||||
interface Scope {
|
||||
body: { [index: string]: {} };
|
||||
requests: number;
|
||||
@@ -52,8 +50,8 @@ function createReply ({ id, reply: { result } }: ReplyDef): any {
|
||||
}
|
||||
|
||||
// scope definition returned
|
||||
function mockWs (requests: { method: string }[]): Scope {
|
||||
server = new Server(TEST_WS_URL);
|
||||
function mockWs (requests: { method: string }[], wsUrl: string = TEST_WS_URL): Scope {
|
||||
const server = new Server(wsUrl);
|
||||
|
||||
let requestCount = 0;
|
||||
const scope: Scope = {
|
||||
|
||||
Reference in New Issue
Block a user