-
Notifications
You must be signed in to change notification settings - Fork 220
/
client-with-ratelimit.go
65 lines (54 loc) · 1.49 KB
/
client-with-ratelimit.go
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
package rpc
import (
"context"
"io"
"net/http"
"github.com/gagliardetto/solana-go/rpc/jsonrpc"
"go.uber.org/ratelimit"
)
var _ JSONRPCClient = &clientWithRateLimiting{}
type clientWithRateLimiting struct {
rpcClient jsonrpc.RPCClient
rateLimiter ratelimit.Limiter
}
// NewWithRateLimit creates a new rate-limitted Solana RPC client.
func NewWithRateLimit(
rpcEndpoint string,
rps int, // requests per second
) JSONRPCClient {
opts := &jsonrpc.RPCClientOpts{
HTTPClient: newHTTP(),
}
rpcClient := jsonrpc.NewClientWithOpts(rpcEndpoint, opts)
return &clientWithRateLimiting{
rpcClient: rpcClient,
rateLimiter: ratelimit.New(rps),
}
}
func (wr *clientWithRateLimiting) CallForInto(ctx context.Context, out interface{}, method string, params []interface{}) error {
wr.rateLimiter.Take()
return wr.rpcClient.CallForInto(ctx, &out, method, params)
}
func (wr *clientWithRateLimiting) CallWithCallback(
ctx context.Context,
method string,
params []interface{},
callback func(*http.Request, *http.Response) error,
) error {
wr.rateLimiter.Take()
return wr.rpcClient.CallWithCallback(ctx, method, params, callback)
}
func (wr *clientWithRateLimiting) CallBatch(
ctx context.Context,
requests jsonrpc.RPCRequests,
) (jsonrpc.RPCResponses, error) {
wr.rateLimiter.Take()
return wr.rpcClient.CallBatch(ctx, requests)
}
// Close closes clientWithRateLimiting.
func (cl *clientWithRateLimiting) Close() error {
if c, ok := cl.rpcClient.(io.Closer); ok {
return c.Close()
}
return nil
}