Skip to content

Commit

Permalink
fix: Add ShortID option for some WebSocket RPC which not support in…
Browse files Browse the repository at this point in the history
…t63/uint64 ID (#179)
  • Loading branch information
GoudanWoo authored Oct 10, 2024
1 parent c7a7525 commit e1dd29f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
9 changes: 7 additions & 2 deletions rpc/ws/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ type Client struct {
subscriptionByRequestID map[uint64]*Subscription
subscriptionByWSSubID map[uint64]*Subscription
reconnectOnErr bool
shortID bool
}

const (
Expand Down Expand Up @@ -76,6 +77,10 @@ func ConnectWithOptions(ctx context.Context, rpcEndpoint string, opt *Options) (
EnableCompression: true,
}

if opt != nil && opt.ShortID {
c.shortID = opt.ShortID
}

if opt != nil && opt.HandshakeTimeout > 0 {
dialer.HandshakeTimeout = opt.HandshakeTimeout
}
Expand Down Expand Up @@ -287,7 +292,7 @@ func (c *Client) closeSubscription(reqID uint64, err error) {
}

func (c *Client) unsubscribe(subID uint64, method string) error {
req := newRequest([]interface{}{subID}, method, nil)
req := newRequest([]interface{}{subID}, method, nil, c.shortID)
data, err := req.encode()
if err != nil {
return fmt.Errorf("unable to encode unsubscription message for subID %d and method %s", subID, method)
Expand All @@ -311,7 +316,7 @@ func (c *Client) subscribe(
c.lock.Lock()
defer c.lock.Unlock()

req := newRequest(params, subscriptionMethod, conf)
req := newRequest(params, subscriptionMethod, conf, c.shortID)
data, err := req.encode()
if err != nil {
return nil, fmt.Errorf("subscribe: unable to encode subsciption request: %w", err)
Expand Down
11 changes: 9 additions & 2 deletions rpc/ws/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,21 @@ type request struct {
ID uint64 `json:"id"`
}

func newRequest(params []interface{}, method string, configuration map[string]interface{}) *request {
func newRequest(params []interface{}, method string, configuration map[string]interface{}, shortID bool) *request {
if params != nil && configuration != nil {
params = append(params, configuration)
}
var ID uint64
if !shortID {
ID = uint64(rand.Int63())
} else {
ID = uint64(rand.Int31())
}
return &request{
Version: "2.0",
Method: method,
Params: params,
ID: uint64(rand.Int63()),
ID: ID,
}
}

Expand All @@ -66,6 +72,7 @@ type params struct {
type Options struct {
HttpHeader http.Header
HandshakeTimeout time.Duration
ShortID bool // some RPC do not support int63/uint64 id, so need to enable it to rand a int31/uint32 id
}

var DefaultHandshakeTimeout = 45 * time.Second

0 comments on commit e1dd29f

Please sign in to comment.