JSONRPC request/response handler opts (#4722)
* JSONRPC request/response handler opts * Fix test * CHANGELOG
This commit is contained in:
@@ -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 => {
|
||||
|
||||
@@ -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"]}']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
}]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,7 +122,7 @@ export class HttpProvider implements ProviderInterface {
|
||||
public async send <T> (method: string, params: unknown[], isCacheable?: boolean): Promise<T> {
|
||||
this.#stats.total.requests++;
|
||||
|
||||
const body = this.#coder.encodeJson(method, params);
|
||||
const [, body] = this.#coder.encodeJson(method, params);
|
||||
let resultPromise: Promise<T> | null = isCacheable
|
||||
? this.#callCache.get(body) as Promise<T>
|
||||
: null;
|
||||
|
||||
@@ -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<T = any> (method: string, params: unknown[]): Promise<T> {
|
||||
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<T>((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 }]);
|
||||
|
||||
|
||||
@@ -295,13 +295,13 @@ export class WsProvider implements ProviderInterface {
|
||||
public send <T = any> (method: string, params: unknown[], isCacheable?: boolean, subscription?: SubscriptionHandler): Promise<T> {
|
||||
this.#stats.total.requests++;
|
||||
|
||||
const body = this.#coder.encodeJson(method, params);
|
||||
const [id, body] = this.#coder.encodeJson(method, params);
|
||||
let resultPromise: Promise<T> | null = isCacheable
|
||||
? this.#callCache.get(body) as Promise<T>
|
||||
: 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 <T> (json: string, method: string, params: unknown[], subscription?: SubscriptionHandler): Promise<T> {
|
||||
async #send <T> (id: number, body: string, method: string, params: unknown[], subscription?: SubscriptionHandler): Promise<T> {
|
||||
return new Promise<T>((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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user