-
Notifications
You must be signed in to change notification settings - Fork 13
/
rpcClient.go
263 lines (222 loc) · 6.37 KB
/
rpcClient.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
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
package bitcoin
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptrace"
"net/http/httputil"
"os"
"time"
)
const (
rpcClientTimeoutSecondsDefault = 120
)
var (
ErrTimeout = errors.New("Timeout reading data from server")
debugHttpDumpBody = os.Getenv("debug_http_dump_body")
debugHttp = os.Getenv("debug_http")
)
// A rpcClient represents a JSON RPC client (over HTTP(s)).
type rpcClient struct {
serverAddr string
user string
passwd string
httpClient *http.Client
logger Logger
rpcClientTimeout time.Duration
}
// rpcRequest represent a RCP request
type rpcRequest struct {
Method string `json:"method"`
Params interface{} `json:"params"`
ID int64 `json:"id"`
JSONRpc string `json:"jsonrpc"`
}
// rpcError represents a RCP error
/*type rpcError struct {
Code int16 `json:"code"`
Message string `json:"message"`
}*/
// rpcResponse represents a RCP response
type rpcResponse struct {
ID int64 `json:"id"`
Result json.RawMessage `json:"result"`
Err interface{} `json:"error"`
}
func (c *rpcClient) debug(data []byte, err error) {
if err == nil {
c.logger.Infof("%s\n\n", data)
} else {
c.logger.Errorf("ERROR: %s\n\n", err)
}
}
func WithTimeoutDuration(d time.Duration) func(*rpcClient) {
return func(p *rpcClient) {
p.rpcClientTimeout = d
}
}
func WithOptionalLogger(l Logger) func(*rpcClient) {
return func(p *rpcClient) {
p.logger = l
}
}
type Option func(f *rpcClient)
func newClient(host string, port int, user, passwd string, useSSL bool, opts ...Option) (c *rpcClient, err error) {
if len(host) == 0 {
err = errors.New("Bad call missing argument host")
return
}
var serverAddr string
var httpClient *http.Client
if useSSL {
serverAddr = "https://"
t := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
httpClient = &http.Client{Transport: t}
} else {
serverAddr = "http://"
httpClient = &http.Client{}
}
c = &rpcClient{
serverAddr: fmt.Sprintf("%s%s:%d", serverAddr, host, port),
user: user,
passwd: passwd,
httpClient: httpClient,
logger: &DefaultLogger{},
rpcClientTimeout: rpcClientTimeoutSecondsDefault * time.Second,
}
// apply options to client
for _, opt := range opts {
opt(c)
}
return
}
// doTimeoutRequest process a HTTP request with timeout
func (c *rpcClient) doTimeoutRequest(timer *time.Timer, req *http.Request) (*http.Response, error) {
type result struct {
resp *http.Response
err error
}
done := make(chan result, 1)
go func() {
if debugHttp == "true" {
c.debug(httputil.DumpRequestOut(req, debugHttpDumpBody == "true"))
}
resp, err := c.httpClient.Do(req)
done <- result{resp, err}
}()
// Wait for the read or the timeout
select {
case r := <-done:
if debugHttp == "true" {
c.debug(httputil.DumpResponse(r.resp, debugHttpDumpBody == "true"))
}
return r.resp, r.err
case <-timer.C:
return nil, ErrTimeout
}
}
// call prepare & exec the request
func (c *rpcClient) call(method string, params interface{}) (rpcResponse, error) {
connectTimer := time.NewTimer(c.rpcClientTimeout)
rpcR := rpcRequest{method, params, time.Now().UnixNano(), "1.0"}
payloadBuffer := &bytes.Buffer{}
jsonEncoder := json.NewEncoder(payloadBuffer)
err := jsonEncoder.Encode(rpcR)
if err != nil {
return rpcResponse{}, fmt.Errorf("failed to encode rpc request: %w", err)
}
req, err := http.NewRequest("POST", c.serverAddr, payloadBuffer)
if err != nil {
return rpcResponse{}, fmt.Errorf("failed to create new http request: %w", err)
}
if os.Getenv("HTTP_TRACE") == "TRUE" {
trace := &httptrace.ClientTrace{
DNSDone: func(dnsInfo httptrace.DNSDoneInfo) {
c.logger.Debugf("HTTP_TRACE - DNS: %+v\n", dnsInfo)
},
GotConn: func(connInfo httptrace.GotConnInfo) {
c.logger.Debugf("HTTP_TRACE - Conn: %+v\n", connInfo)
}}
ctxTrace := httptrace.WithClientTrace(req.Context(), trace)
req = req.WithContext(ctxTrace)
}
req.Header.Add("Content-Type", "application/json;charset=utf-8")
req.Header.Add("Accept", "application/json")
// Auth ?
if len(c.user) > 0 || len(c.passwd) > 0 {
req.SetBasicAuth(c.user, c.passwd)
}
resp, err := c.doTimeoutRequest(connectTimer, req)
if err != nil {
return rpcResponse{}, fmt.Errorf("failed to do request: %w", err)
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return rpcResponse{}, fmt.Errorf("failed to read response: %w", err)
}
var rr rpcResponse
if resp.StatusCode != 200 {
_ = json.Unmarshal(data, &rr)
v, ok := rr.Err.(map[string]interface{})
if ok {
err = errors.New(v["message"].(string))
} else {
err = errors.New("HTTP error: " + resp.Status)
}
return rr, fmt.Errorf("unexpected response code %d: %w", resp.StatusCode, err)
}
err = json.Unmarshal(data, &rr)
if err != nil {
return rr, fmt.Errorf("failed to unmarshal response: %w", err)
}
return rr, nil
}
// call prepare & exec the request
func (c *rpcClient) read(method string, params interface{}) (io.ReadCloser, error) {
connectTimer := time.NewTimer(c.rpcClientTimeout)
rpcR := rpcRequest{method, params, time.Now().UnixNano(), "1.0"}
payloadBuffer := &bytes.Buffer{}
jsonEncoder := json.NewEncoder(payloadBuffer)
err := jsonEncoder.Encode(rpcR)
if err != nil {
return nil, fmt.Errorf("failed to encode rpc request: %w", err)
}
req, err := http.NewRequest("POST", c.serverAddr, payloadBuffer)
if err != nil {
return nil, fmt.Errorf("failed to create new http request: %w", err)
}
req.Header.Add("Content-Type", "application/json;charset=utf-8")
req.Header.Add("Accept", "application/json")
// Auth ?
if len(c.user) > 0 || len(c.passwd) > 0 {
req.SetBasicAuth(c.user, c.passwd)
}
resp, err := c.doTimeoutRequest(connectTimer, req)
if err != nil {
return nil, fmt.Errorf("failed to do request: %w", err)
}
if resp.StatusCode != 200 {
defer resp.Body.Close()
var rr rpcResponse
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
_ = json.Unmarshal(data, &rr)
v, ok := rr.Err.(map[string]interface{})
if ok {
err = errors.New(v["message"].(string))
} else {
err = errors.New("HTTP error: " + resp.Status)
}
return nil, fmt.Errorf("unexpected response code %d: %w", resp.StatusCode, err)
}
return resp.Body, nil
}