Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: extract request with retry to a stateless function #170

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fetchMock from 'jest-fetch-mock';
import { createRpcClient } from '../../../../src/services/ownership/backend/backendUtils';
import { requestWithRetries } from '../../../../src/services/ownership/backend/request';

describe('refetch', () => {
beforeAll(() => {
Expand All @@ -11,9 +11,7 @@ describe('refetch', () => {
it('should refetch when first request fails', async () => {
fetchMock.mockRejectOnce(new Error('some error'));
fetchMock.mockResponse(JSON.stringify({ result: 'some result' }));
const { request } = createRpcClient('');
await request('some_method', {});

await requestWithRetries(() => fetch('http://dummy'));
expect(fetch).toBeCalledTimes(2);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ import { asserts } from '@nexus-wallet/utils';
import { ScriptConfig } from '@ckb-lumos/config-manager';
import { JSONRPCRequest, JSONRPCResponse } from 'json-rpc-2.0';
import { RPC as RpcType } from '@ckb-lumos/rpc/lib/types/rpc';
import { RequestOptions, requestWithRetries } from './request';
import { NexusCommonErrors } from '../../../errors';
import pTimeout from './thirdpartyLib/p-timeout';
import pRetry from './thirdpartyLib/p-retry';

type Order = 'asc' | 'desc';
type Limit = HexNumber;
Expand Down Expand Up @@ -91,39 +90,22 @@ type RpcClient = {
batchRequest: <Result = unknown, Params = unknown>(method: string, batchParams: Params[]) => Promise<Result[]>;
};

type RpcClientOptions = {
timeout?: number; // in milliseconds
maxRetries?: number;
};

function createRpcClient(url: string, options?: RpcClientOptions): RpcClient {
function createRpcClient(url: string, options?: RequestOptions): RpcClient {
// auto-increment id
let jsonRpcId = 0;

async function _request(body: JSONRPCRequest | JSONRPCRequest[]): Promise<JSONRPCResponse | JSONRPCResponse[]> {
++jsonRpcId;
const retryRunner = async () => {
const res = await fetch(url, {
const fetchProvider = () =>
fetch(url, {
method: 'POST',
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json',
},
});
// Abort retrying if the resource doesn't exist
if (res.status >= 300) {
/* istanbul ignore next */
throw NexusCommonErrors.RequestCkbFailed(res);
}
return res.json();
};

const retryPromise = pRetry(retryRunner, { retries: options?.maxRetries || 5 });
const res = await pTimeout(retryPromise, {
milliseconds: options?.timeout || 5_000,
});

return res as Promise<JSONRPCResponse | JSONRPCResponse[]>;
return requestWithRetries(fetchProvider, options);
}

async function request<Result = unknown, Params = unknown>(method: string, params: Params): Promise<Result> {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { JSONRPCResponse } from 'json-rpc-2.0';
import { NexusCommonErrors } from '../../../errors';
import pRetry from './thirdpartyLib/p-retry';
import pTimeout from './thirdpartyLib/p-timeout';

export type RequestOptions = {
timeout?: number; // in milliseconds
maxRetries?: number;
};

export const requestWithRetries = async (
promiseCtor: () => Promise<Response>,
options?: RequestOptions,
): Promise<JSONRPCResponse | JSONRPCResponse[]> => {
const retryRunner = async () => {
const res = await promiseCtor();
// Abort retrying if the resource doesn't exist
if (res.status >= 300) {
/* istanbul ignore next */
throw NexusCommonErrors.RequestCkbFailed(res);
}
return res.json();
};

const retryPromise = pRetry(retryRunner, { retries: options?.maxRetries || 5 });
const res = await pTimeout(retryPromise, {
milliseconds: options?.timeout || 5_000,
});

return res as Promise<JSONRPCResponse | JSONRPCResponse[]>;
};