-
-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathretryOnEmpty.test.ts
788 lines (721 loc) · 25.4 KB
/
retryOnEmpty.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
import { PollingBlockTracker } from '@metamask/eth-block-tracker';
import { providerFromEngine } from '@metamask/eth-json-rpc-provider';
import type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';
import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';
import { JsonRpcEngine } from '@metamask/json-rpc-engine';
import { errorCodes, providerErrors, rpcErrors } from '@metamask/rpc-errors';
import type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';
import { createRetryOnEmptyMiddleware } from '.';
import type { ProviderRequestStub } from '../test/util/helpers';
import {
buildFinalMiddlewareWithDefaultResult,
buildMockParamsWithBlockParamAt,
buildMockParamsWithoutBlockParamAt,
buildSimpleFinalMiddleware,
buildStubForBlockNumberRequest,
expectProviderRequestNotToHaveBeenMade,
requestMatches,
stubProviderRequests,
} from '../test/util/helpers';
/**
* Objects used in each test.
*
* @property engine - The engine that holds the middleware stack, including the
* one being tested.
* @property provider - The provider that is used to make requests against
* (which the middleware being tested will react to).
* @property blockTracker - The block tracker which is used inside of the
* middleware being tested.
*/
interface Setup {
engine: JsonRpcEngine;
provider: SafeEventEmitterProvider;
blockTracker: PollingBlockTracker;
}
/**
* Options supported by `withTestSetup`.
*
* @property configureMiddleware - A function which determines which middleware
* should be added to the engine.
*/
interface WithTestSetupOptions {
configureMiddleware: (setup: Setup) => {
middlewareUnderTest: JsonRpcMiddleware<any, any>;
otherMiddleware?: JsonRpcMiddleware<any, any>[];
};
}
/**
* The function that `withTestSetup` is expected to take and will call once the
* setup objects are created.
*
* @template T - The type that the function will return, minus the promise
* wrapper.
*/
type WithTestSetupCallback<T> = (setup: Setup) => Promise<T>;
const originalSetTimeout = setTimeout;
describe('createRetryOnEmptyMiddleware', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
it('throws if not given a provider', async () => {
const promise = withTestSetup({
configureMiddleware: () => {
return {
middlewareUnderTest: createRetryOnEmptyMiddleware(),
};
},
});
await expect(promise).rejects.toThrow(
new Error(
'RetryOnEmptyMiddleware - mandatory "provider" option is missing.',
),
);
});
it('throws if not given a block tracker', async () => {
const promise = withTestSetup({
configureMiddleware: ({ provider }) => {
return {
middlewareUnderTest: createRetryOnEmptyMiddleware({ provider }),
};
},
});
await expect(promise).rejects.toThrow(
new Error(
'RetryOnEmptyMiddleware - mandatory "blockTracker" option is missing.',
),
);
});
// This list corresponds to the list in the `blockTagParamIndex` function
// within `cache.ts`
(
[
{ blockParamIndex: 0, methods: ['eth_getBlockByNumber'] },
{
blockParamIndex: 1,
methods: [
'eth_getBalance',
'eth_getCode',
'eth_getTransactionCount',
'eth_call',
],
},
{ blockParamIndex: 2, methods: ['eth_getStorageAt'] },
] as const
).forEach(({ blockParamIndex, methods }) => {
methods.forEach((method: string) => {
describe(`${method}`, () => {
it('makes a direct request through the provider, retrying it request up to 10 times and returning the response if it does not have a result of undefined', async () => {
await withTestSetup(
{
configureMiddleware: ({ provider, blockTracker }) => {
return {
middlewareUnderTest: createRetryOnEmptyMiddleware({
provider,
blockTracker,
}),
};
},
},
async ({ engine, provider }) => {
const blockNumber = '0x0';
const request: JsonRpcRequest<string[]> = {
id: 1,
jsonrpc: '2.0',
method,
params: buildMockParamsWithBlockParamAt(
blockParamIndex,
blockNumber,
),
};
const requestSpy = stubProviderRequests(provider, [
buildStubForBlockNumberRequest(blockNumber),
stubRequestThatFailsThenFinallySucceeds({
request,
numberOfTimesToFail: 9,
successfulResult: async () => 'something',
}),
]);
const promiseForResponse = engine.handle(request);
await waitForRequestToBeRetried({
requestSpy,
request,
numberOfTimes: 10,
});
expect(await promiseForResponse).toStrictEqual({
id: 1,
jsonrpc: '2.0',
result: 'something',
});
},
);
});
it('returns an error if the request is still unsuccessful after 10 retries', async () => {
await withTestSetup(
{
configureMiddleware: ({ provider, blockTracker }) => {
return {
middlewareUnderTest: createRetryOnEmptyMiddleware({
provider,
blockTracker,
}),
};
},
},
async ({ engine, provider }) => {
const blockNumber = '0x0';
const request: JsonRpcRequest<string[]> = {
id: 1,
jsonrpc: '2.0',
method,
params: buildMockParamsWithBlockParamAt(
blockParamIndex,
blockNumber,
),
};
const requestSpy = stubProviderRequests(provider, [
buildStubForBlockNumberRequest(blockNumber),
stubGenericRequest({
request,
result: () => {
throw providerErrors.custom({ code: -1, message: 'oops' });
},
remainAfterUse: true,
}),
]);
const promiseForResponse = engine.handle(request);
await waitForRequestToBeRetried({
requestSpy,
request,
numberOfTimes: 10,
});
expect(await promiseForResponse).toMatchObject({
error: expect.objectContaining({
data: expect.objectContaining({
cause: expect.objectContaining({
message: 'RetryOnEmptyMiddleware - retries exhausted',
}),
}),
}),
});
},
);
});
it('does not proceed to the next middleware after making a request through the provider', async () => {
const finalMiddleware = buildSimpleFinalMiddleware();
await withTestSetup(
{
configureMiddleware: ({ provider, blockTracker }) => {
return {
middlewareUnderTest: createRetryOnEmptyMiddleware({
provider,
blockTracker,
}),
otherMiddleware: [finalMiddleware],
};
},
},
async ({ engine, provider }) => {
const blockNumber = '0x0';
const request: JsonRpcRequest<string[]> = {
id: 1,
jsonrpc: '2.0',
method,
params: buildMockParamsWithBlockParamAt(
blockParamIndex,
blockNumber,
),
};
stubProviderRequests(provider, [
buildStubForBlockNumberRequest(blockNumber),
stubGenericRequest({
request,
result: async () => 'success',
}),
]);
await engine.handle(request);
expect(finalMiddleware).not.toHaveBeenCalled();
},
);
});
describe('if the block number in the request params is higher than the latest block number reported by the block tracker', () => {
it('does not make a direct request through the provider', async () => {
await withTestSetup(
{
configureMiddleware: ({ provider, blockTracker }) => {
return {
middlewareUnderTest: createRetryOnEmptyMiddleware({
provider,
blockTracker,
}),
};
},
},
async ({ engine, provider }) => {
const request: JsonRpcRequest<string[]> = {
id: 1,
jsonrpc: '2.0',
method,
params: buildMockParamsWithBlockParamAt(
blockParamIndex,
'0x100',
),
};
const requestSpy = stubProviderRequests(provider, [
buildStubForBlockNumberRequest('0x0'),
]);
await engine.handle(request);
expectProviderRequestNotToHaveBeenMade(requestSpy, request);
},
);
});
it('proceeds to the next middleware', async () => {
const finalMiddleware = buildSimpleFinalMiddleware();
await withTestSetup(
{
configureMiddleware: ({ provider, blockTracker }) => {
return {
middlewareUnderTest: createRetryOnEmptyMiddleware({
provider,
blockTracker,
}),
otherMiddleware: [finalMiddleware],
};
},
},
async ({ engine, provider }) => {
const request: JsonRpcRequest<string[]> = {
id: 1,
jsonrpc: '2.0',
method,
params: buildMockParamsWithBlockParamAt(
blockParamIndex,
'0x100',
),
};
stubProviderRequests(provider, [
buildStubForBlockNumberRequest('0x0'),
]);
await engine.handle(request);
expect(finalMiddleware).toHaveBeenCalled();
},
);
});
});
describe.each(['1', 'earliest', 'asdlsdfls'])(
'if the block parameter is not a 0x-prefixed hex number such as %o',
(blockParam) => {
it('does not make a direct request through the provider', async () => {
await withTestSetup(
{
configureMiddleware: ({ provider, blockTracker }) => {
return {
middlewareUnderTest: createRetryOnEmptyMiddleware({
provider,
blockTracker,
}),
};
},
},
async ({ engine, provider }) => {
const request: JsonRpcRequest<string[]> = {
id: 1,
jsonrpc: '2.0',
method,
params: buildMockParamsWithBlockParamAt(
blockParamIndex,
blockParam,
),
};
const requestSpy = stubProviderRequests(provider, [
buildStubForBlockNumberRequest('0x0'),
]);
await engine.handle(request);
expectProviderRequestNotToHaveBeenMade(requestSpy, request);
},
);
});
it('proceeds to the next middleware', async () => {
const finalMiddleware = buildSimpleFinalMiddleware();
await withTestSetup(
{
configureMiddleware: ({ provider, blockTracker }) => {
return {
middlewareUnderTest: createRetryOnEmptyMiddleware({
provider,
blockTracker,
}),
otherMiddleware: [finalMiddleware],
};
},
},
async ({ engine, provider }) => {
const request: JsonRpcRequest<string[]> = {
id: 1,
jsonrpc: '2.0',
method,
params: buildMockParamsWithBlockParamAt(
blockParamIndex,
blockParam,
),
};
stubProviderRequests(provider, [
buildStubForBlockNumberRequest('0x0'),
]);
await engine.handle(request);
expect(finalMiddleware).toHaveBeenCalled();
},
);
});
},
);
describe.each(['latest', 'pending'])(
'if the block parameter is %o',
(blockParam) => {
it('does not make a direct request through the provider', async () => {
await withTestSetup(
{
configureMiddleware: ({ provider, blockTracker }) => {
return {
middlewareUnderTest: createRetryOnEmptyMiddleware({
provider,
blockTracker,
}),
};
},
},
async ({ engine, provider }) => {
const request: JsonRpcRequest<string[]> = {
id: 1,
jsonrpc: '2.0',
method,
params: buildMockParamsWithBlockParamAt(
blockParamIndex,
blockParam,
),
};
const requestSpy = stubProviderRequests(provider, [
buildStubForBlockNumberRequest(),
]);
await engine.handle(request);
expectProviderRequestNotToHaveBeenMade(requestSpy, request);
},
);
});
it('proceeds to the next middleware', async () => {
const finalMiddleware = buildSimpleFinalMiddleware();
await withTestSetup(
{
configureMiddleware: ({ provider, blockTracker }) => {
return {
middlewareUnderTest: createRetryOnEmptyMiddleware({
provider,
blockTracker,
}),
otherMiddleware: [finalMiddleware],
};
},
},
async ({ engine, provider }) => {
const request: JsonRpcRequest<string[]> = {
id: 1,
jsonrpc: '2.0',
method,
params: buildMockParamsWithBlockParamAt(
blockParamIndex,
blockParam,
),
};
stubProviderRequests(provider, [
buildStubForBlockNumberRequest(),
]);
await engine.handle(request);
expect(finalMiddleware).toHaveBeenCalled();
},
);
});
},
);
describe('if no block parameter is given', () => {
it('does not make a direct request through the provider', async () => {
await withTestSetup(
{
configureMiddleware: ({ provider, blockTracker }) => {
return {
middlewareUnderTest: createRetryOnEmptyMiddleware({
provider,
blockTracker,
}),
};
},
},
async ({ engine, provider }) => {
const request: JsonRpcRequest<string[]> = {
id: 1,
jsonrpc: '2.0',
method,
params: buildMockParamsWithoutBlockParamAt(blockParamIndex),
};
const requestSpy = stubProviderRequests(provider, [
buildStubForBlockNumberRequest(),
]);
await engine.handle(request);
expectProviderRequestNotToHaveBeenMade(requestSpy, request);
},
);
});
it('proceeds to the next middleware', async () => {
const finalMiddleware = buildSimpleFinalMiddleware();
await withTestSetup(
{
configureMiddleware: ({ provider, blockTracker }) => {
return {
middlewareUnderTest: createRetryOnEmptyMiddleware({
provider,
blockTracker,
}),
otherMiddleware: [finalMiddleware],
};
},
},
async ({ engine, provider }) => {
const request: JsonRpcRequest<string[]> = {
id: 1,
jsonrpc: '2.0',
method,
params: buildMockParamsWithoutBlockParamAt(blockParamIndex),
};
stubProviderRequests(provider, [
buildStubForBlockNumberRequest(),
]);
await engine.handle(request);
expect(finalMiddleware).toHaveBeenCalled();
},
);
});
});
});
});
});
describe('a method that does not take a block parameter', () => {
it('does not make a direct request through the provider', async () => {
await withTestSetup(
{
configureMiddleware: ({ provider, blockTracker }) => {
return {
middlewareUnderTest: createRetryOnEmptyMiddleware({
provider,
blockTracker,
}),
};
},
},
async ({ engine, provider }) => {
const method = 'a_non_block_param_method';
const request: JsonRpcRequest<string[]> = {
id: 1,
jsonrpc: '2.0',
method,
};
const requestSpy = stubProviderRequests(provider, [
buildStubForBlockNumberRequest(),
]);
await engine.handle(request);
expectProviderRequestNotToHaveBeenMade(requestSpy, request);
},
);
});
it('proceeds to the next middleware', async () => {
const finalMiddleware = buildSimpleFinalMiddleware();
await withTestSetup(
{
configureMiddleware: ({ provider, blockTracker }) => {
return {
middlewareUnderTest: createRetryOnEmptyMiddleware({
provider,
blockTracker,
}),
otherMiddleware: [finalMiddleware],
};
},
},
async ({ engine }) => {
const method = 'a_non_block_param_method';
const request: JsonRpcRequest<string[]> = {
id: 1,
jsonrpc: '2.0',
method,
};
await engine.handle(request);
expect(finalMiddleware).toHaveBeenCalled();
},
);
});
});
describe('when provider return execution revert error', () => {
it('returns the same error to caller', async () => {
await withTestSetup(
{
configureMiddleware: ({ provider, blockTracker }) => {
return {
middlewareUnderTest: createRetryOnEmptyMiddleware({
provider,
blockTracker,
}),
};
},
},
async ({ engine, provider }) => {
const request: JsonRpcRequest<string[]> = {
id: 123,
jsonrpc: '2.0',
method: 'eth_call',
params: buildMockParamsWithBlockParamAt(1, '100'),
};
stubProviderRequests(provider, [
buildStubForBlockNumberRequest(),
{
request,
result: () => {
throw rpcErrors.invalidInput('execution reverted');
},
},
]);
const promiseForResponse = engine.handle(request);
expect(await promiseForResponse).toMatchObject({
error: expect.objectContaining({
code: errorCodes.rpc.invalidInput,
message: 'execution reverted',
}),
});
},
);
});
});
});
/**
* Calls the given function, which should represent a test of some kind, with
* data that the test can use, namely, a JsonRpcEngine instance, a provider
* object, and a block tracker.
*
* @template T - The type that the function will return, minus the promise
* wrapper.
* @param options - Options.
* @param options.configureMiddleware - A function that is called to add the
* middleware-under-test, along with any other necessary middleware, to the
* engine.
* @param callback - A function.
* @returns Whatever the function returns.
*/
async function withTestSetup<T>(
{ configureMiddleware }: WithTestSetupOptions,
callback?: WithTestSetupCallback<T>,
) {
const engine = new JsonRpcEngine();
const provider = providerFromEngine(engine);
const blockTracker = new PollingBlockTracker({
provider,
});
const {
middlewareUnderTest,
otherMiddleware = [buildFinalMiddlewareWithDefaultResult()],
} = configureMiddleware({ engine, provider, blockTracker });
for (const middleware of [middlewareUnderTest, ...otherMiddleware]) {
engine.push(middleware);
}
if (callback === undefined) {
return undefined;
}
return await callback({ engine, provider, blockTracker });
}
/**
* Builds a canned result for a request made to `provider.request`. Intended
* to be used in conjunction with `stubProviderRequests`. Although not strictly
* necessary, it helps to assign a proper type to a request/result pair.
*
* @param requestStub - The request/response pair.
* @returns The request/response pair, properly typed.
*/
function stubGenericRequest<T extends JsonRpcParams, U extends Json>(
requestStub: ProviderRequestStub<T, U>,
) {
return requestStub;
}
/**
* Builds a canned result for a request made to `provider.request` which
* will error for the first N instances and then succeed on the last instance.
* Intended to be used in conjunction with `stubProviderRequests`.
*
* @param request - The request matcher for the stub.
* @param numberOfTimesToFail - The number of times the request is expected to
* be called until it returns a successful result.
* @param successfulResult - The result that `provider.request` will
* return when called past `numberOfTimesToFail`.
* @returns The request/result pair, properly typed.
*/
function stubRequestThatFailsThenFinallySucceeds<
T extends JsonRpcParams,
U extends Json,
>({
request,
numberOfTimesToFail,
successfulResult,
}: {
request: ProviderRequestStub<T, U>['request'];
numberOfTimesToFail: number;
successfulResult: ProviderRequestStub<T, U>['result'];
}): ProviderRequestStub<T, U> {
return stubGenericRequest({
request,
result: async (callNumber) => {
if (callNumber <= numberOfTimesToFail) {
throw providerErrors.custom({ code: -1, message: 'oops' });
}
return await successfulResult(callNumber);
},
remainAfterUse: true,
});
}
/**
* The `retryOnEmpty` middleware, as its name implies, uses the provider to make
* the given request, retrying said request up to 10 times if the result is
* empty before failing. Upon retrying, it will wait a brief time using
* `setTimeout`. Because we are using Jest's fake timers, we have to manually
* trigger the callback passed to `setTimeout` atfter it is called. The problem
* is that we don't know when `setTimeout` will be called while the
* `retryOnEmpty` middleware is running, so we have to wait. We do this by
* recording how many times `provider.request` has been called with the
* request, and when that number goes up, we assume that `setTimeout` has been
* called too and advance through time. We stop the loop when
* `provider.request` has been called the given number of times.
*
* @param args - The arguments.
* @param requestSpy - The Jest spy object that represents
* `provider.request`.
* @param request - The request object.
* @param numberOfTimes - The number of times that we expect
* `provider.request` to be called with `request`.
*/
async function waitForRequestToBeRetried({
requestSpy,
request,
numberOfTimes,
}: {
requestSpy: jest.SpyInstance;
request: JsonRpcRequest;
numberOfTimes: number;
}) {
let iterationNumber = 1;
while (iterationNumber <= numberOfTimes) {
await new Promise((resolve) => originalSetTimeout(resolve, 0));
if (
requestSpy.mock.calls.filter((args) => requestMatches(args[0], request))
.length === iterationNumber
) {
jest.runAllTimers();
iterationNumber += 1;
}
}
}