@@ -15,12 +15,14 @@ import (
15
15
"time"
16
16
17
17
"encoding/json"
18
+ "golang.org/x/sync/semaphore"
18
19
)
19
20
20
21
const (
21
22
jsonrpcVersion = "2.0"
22
23
timeout = 70 * time .Second
23
24
httpTimeout = 60 * time .Second
25
+ maxConcurrentRequests = int64 (350 )
24
26
)
25
27
26
28
// RPCClient sends JSON-RPC requests over HTTP to the provided JSON-RPC backend.
@@ -246,6 +248,7 @@ type rpcClient struct {
246
248
endpoint string
247
249
httpClient * http.Client
248
250
customHeaders map [string ]string
251
+ sem * semaphore.Weighted
249
252
}
250
253
251
254
// RPCClientOpts can be provided to NewClientWithOpts() to change configuration of RPCClient.
@@ -320,6 +323,7 @@ func NewClientWithOpts(endpoint string, opts *RPCClientOpts) RPCClient {
320
323
IdleConnTimeout : 60 * time .Second ,
321
324
},
322
325
},
326
+ sem : semaphore .NewWeighted (maxConcurrentRequests ),
323
327
customHeaders : make (map [string ]string ),
324
328
}
325
329
@@ -449,6 +453,11 @@ func (client *rpcClient) newRequest(ctx context.Context, req interface{}) (*http
449
453
}
450
454
451
455
func (client * rpcClient ) doCall (cctx context.Context , RPCRequest * RPCRequest ) (* RPCResponse , error ) {
456
+ if err := client .sem .Acquire (cctx , 1 ); err != nil {
457
+ return nil , fmt .Errorf ("waiting for semaphore on rpc call on %v" , err .Error ())
458
+ }
459
+ defer client .sem .Release (1 )
460
+
452
461
ctx , cancel := context .WithTimeout (cctx , timeout )
453
462
defer cancel ()
454
463
@@ -497,11 +506,16 @@ func (client *rpcClient) doCall(cctx context.Context, RPCRequest *RPCRequest) (*
497
506
}
498
507
499
508
func (client * rpcClient ) doBatchCall (rpcRequest []* RPCRequest ) ([]* RPCResponse , error ) {
509
+ if err := client .sem .Acquire (context .Background (), 1 ); err != nil {
510
+ return nil , fmt .Errorf ("waiting for semaphore on rpc batch call on %v" , err .Error ())
511
+ }
512
+ defer client .sem .Release (1 )
513
+
500
514
httpRequest , err := client .newRequest (context .Background (), rpcRequest )
501
515
if err != nil {
502
516
return nil , fmt .Errorf ("rpc batch call on %v: %v" , client .endpoint , err .Error ())
503
517
}
504
-
518
+
505
519
httpResponse , err := client .httpClient .Do (httpRequest )
506
520
if err != nil {
507
521
return nil , fmt .Errorf ("rpc batch call on %v: %v" , httpRequest .URL .String (), err .Error ())
0 commit comments