-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
128 lines (117 loc) · 2.49 KB
/
client.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
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
package continuum
import (
"context"
"fmt"
"log"
"net/url"
"sync"
"time"
rpc "github.com/qlcchain/jsonrpc2"
)
type Client struct {
client *rpc.Client
Account *AccountApi
Contract *ContractApi
Ledger *LedgerApi
Mintage *MintageApi
Pledge *PledgeApi
Rewards *RewardsApi
Network *NetApi
Util *UtilApi
Destroy *DestroyApi
Debug *DebugApi
Pov *PovApi
Miner *MinerApi
Rep *RepApi
ctx context.Context
cancel context.CancelFunc
endpoint string
isWsConnected bool
mutex sync.RWMutex
}
func (c *Client) Close() error {
if c != nil && c.client != nil {
c.cancel()
c.client.Close()
c.Ledger.Stop()
}
return nil
}
// NewClient creates a new client
func NewClient(endpoint string) (*Client, error) {
client, err := rpc.Dial(endpoint)
if err != nil {
return nil, fmt.Errorf("dial: %s", err)
}
ctx, cancel := context.WithCancel(context.Background())
c := &Client{
client: client,
ctx: ctx,
cancel: cancel,
endpoint: endpoint,
isWsConnected: isWsConnected(endpoint),
mutex: sync.RWMutex{},
}
c.Account = NewAccountAPI(c)
c.Ledger = NewLedgerAPI(endpoint, c)
c.Contract = NewContractAPI(c)
c.Mintage = NewMintageAPI(c)
c.Pledge = NewPledgeAPI(c)
c.Rewards = NewRewardAPI(c)
c.Network = NewNetAPI(c)
c.Util = NewUtilAPI(c)
c.Destroy = NewDestroyAPI(c)
c.Debug = NewDebugAPI(c)
c.Pov = NewPovAPI(endpoint, c)
c.Miner = NewMinerAPI(c)
c.Rep = NewRepAPI(c)
c.wsConnected()
return c, nil
}
// Version returns version for sdk
//func (c *Client) Version() string {
// return fmt.Sprintf("%s.%s.%s", VERSION, GITREV, BUILDTIME)
//}
func (c *Client) wsConnected() {
if c.isWsConnected {
go func() {
cTicker := time.NewTicker(5 * time.Second)
for {
select {
case <-cTicker.C:
_, err := c.Ledger.ChainToken()
if err != nil {
c.mutex.Lock()
c.client.Close()
client, err := rpc.Dial(c.endpoint)
if err == nil {
c.client = client
}
c.mutex.Unlock()
}
case <-c.ctx.Done():
return
}
}
}()
}
}
func (c *Client) getClient() *rpc.Client {
if c.isWsConnected {
c.mutex.RLock()
defer c.mutex.RUnlock()
return c.client
} else {
return c.client
}
}
func isWsConnected(endpoint string) bool {
u, err := url.Parse(endpoint)
if err != nil {
log.Fatal(err)
}
if u.Scheme == "ws" || u.Scheme == "wss" {
return true
}
return false
}