This repository has been archived by the owner on Jul 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
rpc_core.go
175 lines (161 loc) · 4.04 KB
/
rpc_core.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
package deribit
import (
"fmt"
"strings"
"time"
"github.com/adampointer/go-deribit/client/operations"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
)
type composite struct {
RPCNotification
RPCResponse
}
// Submit satisfies the runtime.ClientTransport interface
func (e *Exchange) Submit(operation *runtime.ClientOperation) (interface{}, error) {
method := operation.PathPattern
// Strip leading slashes
method = strings.TrimPrefix(method, "/")
req := NewRPCRequest(method)
if err := operation.Params.WriteToRequest(req, strfmt.Default); err != nil {
return nil, err
}
// Add auth
if strings.HasPrefix(method, "private/") && e.auth != nil {
req.Params["access_token"] = e.auth.AccessToken
}
res, err := e.rpcRequest(req)
if err != nil {
return nil, err
}
return operation.Reader.ReadResponse(res, runtime.JSONConsumer())
}
// Client returns an initialised API client
func (e *Exchange) Client() *operations.Client {
if e.client == nil {
e.client = operations.New(e, strfmt.Default)
}
return e.client
}
func (e *Exchange) rpcRequest(req *RPCRequest) (*RPCResponse, error) {
call := NewRPCCall(req)
// Create a new request ID
e.mutex.Lock()
id := e.counter
e.counter++
req.ID = id
e.pending[id] = call
// Send
if err := e.conn.WriteJSON(&req); err != nil {
delete(e.pending, id)
e.mutex.Unlock()
return nil, err
}
e.mutex.Unlock()
// Wait for response or timeout
select {
case <-call.Done:
case <-time.After(10 * time.Second):
call.Error = fmt.Errorf("request %d timed out", id)
}
if call.Error != nil {
return nil, call.Error
}
if call.Res.Error != nil {
return nil, fmt.Errorf("request failed with code (%d): %s", call.Res.Error.Code, call.Res.Error.Message)
}
return call.Res, nil
}
// read takes messages off the websocket and deals with them accordingly
func (e *Exchange) read() {
var resErr error
Loop:
for {
select {
case <-e.stop:
break Loop
default:
var raw composite
if err := e.conn.ReadJSON(&raw); err != nil {
if isTemporary(err) {
continue
}
e.mutex.Lock()
isClosed := e.isClosed
e.mutex.Unlock()
if isClosed { // fix for `use of closed network connection`
break Loop
}
// stop reading if the client initiated a closure
if isClosed && websocket.IsCloseError(err, websocket.CloseNormalClosure) {
break Loop
}
if f := e.OnDisconnect; f != nil { // reconnect
f(e)
}
break Loop
}
if raw.ID != 0 || raw.Error != nil {
res := &RPCResponse{
JsonRpc: rpcVersion,
ID: raw.ID,
Result: raw.Result,
Error: raw.Error,
}
if len(res.Result) <= 2 && res.Error == nil {
res.Error = &RPCError{Code: 10001, Message: "empty result"}
}
e.mutex.Lock()
call := e.pending[res.ID]
e.mutex.Unlock()
if res.Error != nil && res.Error.Code != 0 {
resErr = fmt.Errorf("request failed with code (%d): %s", res.Error.Code, res.Error.Message)
break Loop
} else {
if call == nil {
resErr = fmt.Errorf("no pending request found for response ID %d", res.ID)
break Loop
}
call.Res = res
call.Done <- true
e.mutex.Lock()
delete(e.pending, res.ID)
e.mutex.Unlock()
}
} else if raw.Method == "subscription" {
res := &RPCNotification{
JsonRpc: rpcVersion,
Method: raw.Method,
Params: raw.Params,
}
e.mutex.Lock()
sub := e.subscriptions[res.Params.Channel]
e.mutex.Unlock()
if sub == nil {
// Send error to main error channel
e.errors <- fmt.Errorf("no subscription found for %s", res.Params.Channel)
}
// Send the notification to the right channel
sub.Data <- res
}
}
}
if resErr != nil {
e.mutex.Lock()
for _, call := range e.pending {
call.Error = resErr
call.Done <- true
}
e.mutex.Unlock()
}
}
type temporary interface {
Temporary() bool
}
// returns true if network err is temporary.
func isTemporary(err error) bool {
te, ok := errors.Cause(err).(temporary)
return ok && te.Temporary()
}