From ba188dcc0d3bc75585900e4c4ae93a4bd0b26665 Mon Sep 17 00:00:00 2001 From: Jaco Date: Fri, 8 Apr 2022 07:51:44 +0200 Subject: [PATCH] JSONRPC request/response handler opts (#4722) * JSONRPC request/response handler opts * Fix test * CHANGELOG --- CHANGELOG.md | 6 +++ .../src/coder/decodeResponse.spec.ts | 2 +- .../rpc-provider/src/coder/encodeJson.spec.ts | 2 +- .../src/coder/encodeObject.spec.ts | 9 +--- packages/rpc-provider/src/coder/index.ts | 52 +++++++++---------- packages/rpc-provider/src/http/index.ts | 2 +- .../src/substrate-connect/ScProvider.ts | 32 +++++++----- packages/rpc-provider/src/ws/index.ts | 14 +++-- 8 files changed, 59 insertions(+), 60 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ec704d387..73a27deb07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,14 @@ ## master +Contributed: + +- Improve `rpc-provider` README (Thanks to https://github.com/josepot) +- Add handling for `Vec<[;]>` in typegen (Thanks to https://github.com/zannis) + Changes: +- Optimize JSONRPC requests/response handling - Add latest Polkadot 9180 upgrade block diff --git a/packages/rpc-provider/src/coder/decodeResponse.spec.ts b/packages/rpc-provider/src/coder/decodeResponse.spec.ts index ac66cd10c7..aafe48aaab 100644 --- a/packages/rpc-provider/src/coder/decodeResponse.spec.ts +++ b/packages/rpc-provider/src/coder/decodeResponse.spec.ts @@ -15,7 +15,7 @@ describe('decodeResponse', (): void => { it('expects a non-empty input object', (): void => { expect( () => coder.decodeResponse(undefined as unknown as JsonRpcResponse) - ).toThrow(/Empty response/); + ).toThrow(/Invalid jsonrpc/); }); it('expects a valid jsonrpc field', (): void => { diff --git a/packages/rpc-provider/src/coder/encodeJson.spec.ts b/packages/rpc-provider/src/coder/encodeJson.spec.ts index 49a7bbee3d..616059c0bf 100644 --- a/packages/rpc-provider/src/coder/encodeJson.spec.ts +++ b/packages/rpc-provider/src/coder/encodeJson.spec.ts @@ -13,6 +13,6 @@ describe('encodeJson', (): void => { it('encodes a valid JsonRPC JSON string', (): void => { expect( coder.encodeJson('method', ['params']) - ).toEqual('{"id":1,"jsonrpc":"2.0","method":"method","params":["params"]}'); + ).toEqual([1, '{"id":1,"jsonrpc":"2.0","method":"method","params":["params"]}']); }); }); diff --git a/packages/rpc-provider/src/coder/encodeObject.spec.ts b/packages/rpc-provider/src/coder/encodeObject.spec.ts index 5f3380e0b1..4094c67d40 100644 --- a/packages/rpc-provider/src/coder/encodeObject.spec.ts +++ b/packages/rpc-provider/src/coder/encodeObject.spec.ts @@ -10,19 +10,14 @@ describe('encodeObject', (): void => { coder = new RpcCoder(); }); - it('starts with id === 0 (nothing sent)', (): void => { - expect(coder.getId()).toEqual(0); - }); - it('encodes a valid JsonRPC object', (): void => { expect( coder.encodeObject('method', ['a', 'b']) - ).toEqual({ + ).toEqual([1, { id: 1, jsonrpc: '2.0', method: 'method', params: ['a', 'b'] - }); - expect(coder.getId()).toEqual(1); + }]); }); }); diff --git a/packages/rpc-provider/src/coder/index.ts b/packages/rpc-provider/src/coder/index.ts index df75ade11d..9dcab156c0 100644 --- a/packages/rpc-provider/src/coder/index.ts +++ b/packages/rpc-provider/src/coder/index.ts @@ -20,27 +20,34 @@ function formatErrorData (data?: string | number): string { // very nested, pick a number and trim the result display to it return formatted.length <= 256 ? formatted - : `${formatted.substr(0, 255)}…`; + : `${formatted.substring(0, 255)}…`; +} + +function checkError (error?: JsonRpcResponseBaseError): void { + if (error) { + const { code, data, message } = error; + + throw new RpcError(`${code}: ${message}${formatErrorData(data)}`, code, data); + } } /** @internal */ export class RpcCoder { #id = 0; - public decodeResponse (response: JsonRpcResponse): unknown { - assert(response, 'Empty response object received'); - assert(response.jsonrpc === '2.0', 'Invalid jsonrpc field in decoded object'); + public decodeResponse (response?: JsonRpcResponse): unknown { + assert(response && response.jsonrpc === '2.0', 'Invalid jsonrpc field in decoded object'); const isSubscription = !isUndefined(response.params) && !isUndefined(response.method); assert(isNumber(response.id) || (isSubscription && (isNumber(response.params.subscription) || isString(response.params.subscription))), 'Invalid id field in decoded object'); - this._checkError(response.error); + checkError(response.error); - assert(!isUndefined(response.result) || isSubscription, 'No result found in JsonRpc response'); + assert(!isUndefined(response.result) || isSubscription, 'No result found in jsonrpc response'); if (isSubscription) { - this._checkError(response.params.error); + checkError(response.params.error); return response.params.result; } @@ -48,31 +55,20 @@ export class RpcCoder { return response.result; } - public encodeJson (method: string, params: unknown[]): string { - return stringify( - this.encodeObject(method, params) - ); + public encodeJson (method: string, params: unknown[]): [number, string] { + const [id, data] = this.encodeObject(method, params); + + return [id, stringify(data)]; } - public encodeObject (method: string, params: unknown[]): JsonRpcRequest { - return { - id: ++this.#id, + public encodeObject (method: string, params: unknown[]): [number, JsonRpcRequest] { + const id = ++this.#id; + + return [id, { + id, jsonrpc: '2.0', method, params - }; - } - - public getId (): number { - return this.#id; - } - - private _checkError (error?: JsonRpcResponseBaseError): void { - if (error) { - const { code, data, message } = error; - const fmtMessage = `${code}: ${message}${formatErrorData(data)}`; - - throw new RpcError(fmtMessage, code, data); - } + }]; } } diff --git a/packages/rpc-provider/src/http/index.ts b/packages/rpc-provider/src/http/index.ts index 6dac380bb1..e51bd39931 100644 --- a/packages/rpc-provider/src/http/index.ts +++ b/packages/rpc-provider/src/http/index.ts @@ -122,7 +122,7 @@ export class HttpProvider implements ProviderInterface { public async send (method: string, params: unknown[], isCacheable?: boolean): Promise { this.#stats.total.requests++; - const body = this.#coder.encodeJson(method, params); + const [, body] = this.#coder.encodeJson(method, params); let resultPromise: Promise | null = isCacheable ? this.#callCache.get(body) as Promise : null; diff --git a/packages/rpc-provider/src/substrate-connect/ScProvider.ts b/packages/rpc-provider/src/substrate-connect/ScProvider.ts index 10817fe07c..ad80c8a9f3 100644 --- a/packages/rpc-provider/src/substrate-connect/ScProvider.ts +++ b/packages/rpc-provider/src/substrate-connect/ScProvider.ts @@ -151,14 +151,19 @@ export class ScProvider implements ProviderInterface { return; } - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const { id, unsubscribeMethod } = staleSubscriptions.pop()!; + const stale = staleSubscriptions.pop(); - // eslint-disable-next-line @typescript-eslint/no-floating-promises - Promise.race([ - this.send(unsubscribeMethod, [id]).catch(Function.prototype as () => void), - new Promise((resolve) => setTimeout(resolve, 500)) - ]).then(killStaleSubscriptions); + assert(stale, 'Unable to get stale subscription'); + + const { id, unsubscribeMethod } = stale; + + Promise + .race([ + this.send(unsubscribeMethod, [id]).catch(() => undefined), + new Promise((resolve) => setTimeout(resolve, 500)) + ]) + .then(killStaleSubscriptions) + .catch(() => undefined); }; hc.start((health) => { @@ -256,12 +261,10 @@ export class ScProvider implements ProviderInterface { } public async send (method: string, params: unknown[]): Promise { - assert(this.isConnected, 'Provider is not connected'); + assert(this.isConnected && this.#chain, 'Provider is not connected'); - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const chain = await this.#chain!; - const json = this.#coder.encodeJson(method, params); - const id = this.#coder.getId(); + const chain = await this.#chain; + const [id, json] = this.#coder.encodeJson(method, params); const result = new Promise((resolve, reject): void => { this.#requests.set(id, (response) => { @@ -312,8 +315,9 @@ export class ScProvider implements ProviderInterface { } }; - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const unsubscribeMethod = subscriptionUnsubscriptionMethods.get(method)!; + const unsubscribeMethod = subscriptionUnsubscriptionMethods.get(method); + + assert(unsubscribeMethod, 'Invalid unsubscribe method found'); this.#subscriptions.set(subscriptionId, [cb, { id, unsubscribeMethod }]); diff --git a/packages/rpc-provider/src/ws/index.ts b/packages/rpc-provider/src/ws/index.ts index b3f84bf59e..9edd47ee26 100644 --- a/packages/rpc-provider/src/ws/index.ts +++ b/packages/rpc-provider/src/ws/index.ts @@ -295,13 +295,13 @@ export class WsProvider implements ProviderInterface { public send (method: string, params: unknown[], isCacheable?: boolean, subscription?: SubscriptionHandler): Promise { this.#stats.total.requests++; - const body = this.#coder.encodeJson(method, params); + const [id, body] = this.#coder.encodeJson(method, params); let resultPromise: Promise | null = isCacheable ? this.#callCache.get(body) as Promise : null; if (!resultPromise) { - resultPromise = this.#send(body, method, params, subscription); + resultPromise = this.#send(id, body, method, params, subscription); if (isCacheable) { this.#callCache.set(body, resultPromise); @@ -313,20 +313,18 @@ export class WsProvider implements ProviderInterface { return resultPromise; } - async #send (json: string, method: string, params: unknown[], subscription?: SubscriptionHandler): Promise { + async #send (id: number, body: string, method: string, params: unknown[], subscription?: SubscriptionHandler): Promise { return new Promise((resolve, reject): void => { try { assert(this.isConnected && !isNull(this.#websocket), 'WebSocket is not connected'); - const id = this.#coder.getId(); - const callback = (error?: Error | null, result?: T): void => { error ? reject(error) : resolve(result as T); }; - l.debug(() => ['calling', method, json]); + l.debug(() => ['calling', method, body]); this.#handlers[id] = { callback, @@ -335,8 +333,8 @@ export class WsProvider implements ProviderInterface { start: Date.now(), subscription }; - this.#stats.total.bytesSent += json.length; - this.#websocket.send(json); + this.#stats.total.bytesSent += body.length; + this.#websocket.send(body); } catch (error) { reject(error); }