Skip to content
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
55 changes: 55 additions & 0 deletions __tests__/utils/batchClient.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { BatchClient } from '../../src/utils/batch';
import { RPC } from '../../src/types';
import { RpcChannel } from '../../src/channel';
import { RpcError } from '../../src/utils/errors';

const createBatchClient = (request: jest.Mock) =>
new BatchClient<RPC.Methods>({
nodeUrl: 'http://127.0.0.1:0',
headers: {},
interval: 0,
baseFetch: jest.fn() as any,
transport: { request } as any,
rpcMethods: {} as RPC.Methods,
});

describe('BatchClient without a node', () => {
test('hands a batch-level error reply to every caller', async () => {
// JSON-RPC 2.0: a batch the server rejects as a whole gets a single response object.
const reply = { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Batch too large' } };
const client = createBatchClient(jest.fn(async () => reply));

const [first, second] = await Promise.all([
client.fetch('starknet_blockNumber'),
client.fetch('starknet_chainId'),
]);

expect(first.error).toEqual(reply.error);
expect(second.error).toEqual(reply.error);
});

test('the channel turns a batch-level error reply into an RpcError', async () => {
const channel = new RpcChannel({ nodeUrl: 'http://127.0.0.1:0', batch: 0 });
jest.spyOn((channel as any).transport, 'request').mockResolvedValue({
jsonrpc: '2.0',
id: null,
error: { code: -32005, message: 'Rate limit exceeded' },
});

const failure = channel.getBlockNumber();
await expect(failure).rejects.toThrow(RpcError);
await expect(failure).rejects.toThrow('Rate limit exceeded');
});

test('forgets the batch once it has failed', async () => {
const client = createBatchClient(jest.fn().mockRejectedValue(new Error('network down')));

const results = await Promise.allSettled([
client.fetch('starknet_blockNumber'),
client.fetch('starknet_chainId'),
]);

expect(results.map((r) => r.status)).toEqual(['rejected', 'rejected']);
expect((client as any).batchPromises).toEqual({});
});
});
16 changes: 14 additions & 2 deletions src/utils/batch/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,20 @@ export class BatchClient<T extends { [key: string]: { params?: any; result?: any
});
}

const results = await this.batchPromises[requestId];
delete this.batchPromises[requestId];
let results: JRPC.ResponseBody[];
try {
results = await this.batchPromises[requestId];
} finally {
delete this.batchPromises[requestId];
}

// JSON-RPC 2.0: a batch rejected as a whole (size limit, rate limit...) gets a single
// response object. Every caller of that batch gets its error.
Comment on lines +141 to +142

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The JSON-RPC 2.0 spec does not say this. Section 6 (Batch) asks for a single response object only when the batch itself is invalid:

If the batch rpc call itself fails to be recognized as an valid JSON or as an Array with at least one value, the response from the Server MUST be a single Response object.

BatchClient never sends such a batch. A size or rate limit is a choice of the node, not a rule of the spec. Could you reword the comment, for example:

Suggested change
// JSON-RPC 2.0: a batch rejected as a whole (size limit, rate limit...) gets a single
// response object. Every caller of that batch gets its error.
// A node can reject the whole batch, for example when it is too large.
// It then answers with a single error object instead of an array.
// Every caller of the batch gets this error.

if (!Array.isArray(results)) {
const reply = results as { error?: JRPC.Error } | undefined;
if (reply?.error) return reply as TResponse;
throw new Error(`Unexpected reply to a batch request. Method: ${String(method)}`);
}

// Find this request in the results and return it
const result = results.find((res: any) => res.id === requestId);
Expand Down