forked from st3v/go-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
211 lines (191 loc) · 5.34 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
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
package jsonrpc2
import (
"encoding/json"
"errors"
"io"
"math"
"reflect"
"sync"
"github.com/micro/go-micro/codec"
)
const seqNotify = math.MaxUint64
type clientCodec struct {
dec *json.Decoder // for reading JSON values
enc *json.Encoder // for writing JSON values
c io.Closer
// temporary work space
resp clientResponse
// JSON-RPC responses include the request id but not the request method.
// Package rpc expects both.
// We save the request method in pending when sending a request
// and then look it up by request ID when filling out the rpc Response.
mutex sync.Mutex // protects pending
pending map[uint64]string // map request id to method name
}
func newClientCodec(conn io.ReadWriteCloser) *clientCodec {
return &clientCodec{
dec: json.NewDecoder(conn),
enc: json.NewEncoder(conn),
c: conn,
pending: make(map[uint64]string),
}
}
type clientRequest struct {
Version string `json:"jsonrpc"`
Method string `json:"method"`
Params interface{} `json:"params,omitempty"`
ID *uint64 `json:"id,omitempty"`
}
func (c *clientCodec) Write(m *codec.Message, b interface{}) error {
// If return error: it will be returned as is for this call.
// Allow param to be only Array, Slice, Map or Struct.
// When param is nil or uninitialized Map or Slice - omit "params".
if b != nil {
switch k := reflect.TypeOf(b).Kind(); k {
case reflect.Map:
if reflect.TypeOf(b).Key().Kind() == reflect.String {
if reflect.ValueOf(b).IsNil() {
b = nil
}
}
case reflect.Slice:
if reflect.ValueOf(b).IsNil() {
b = nil
}
case reflect.Array, reflect.Struct:
case reflect.Ptr:
switch k := reflect.TypeOf(b).Elem().Kind(); k {
case reflect.Map:
if reflect.TypeOf(b).Elem().Key().Kind() == reflect.String {
if reflect.ValueOf(b).Elem().IsNil() {
b = nil
}
}
case reflect.Slice:
if reflect.ValueOf(b).Elem().IsNil() {
b = nil
}
case reflect.Array, reflect.Struct:
default:
return NewError(errInternal.Code, "unsupported param type: Ptr to "+k.String())
}
default:
return NewError(errInternal.Code, "unsupported param type: "+k.String())
}
}
var req clientRequest
if m.Id != seqNotify {
c.mutex.Lock()
c.pending[m.Id] = m.Method
c.mutex.Unlock()
req.ID = &m.Id
}
req.Version = "2.0"
req.Method = m.Method
req.Params = b
if err := c.enc.Encode(&req); err != nil {
return NewError(errInternal.Code, err.Error())
}
return nil
}
type clientResponse struct {
Version string `json:"jsonrpc"`
ID *uint64 `json:"id"`
Result *json.RawMessage `json:"result,omitempty"`
Error *Error `json:"error,omitempty"`
}
func (r *clientResponse) reset() {
r.Version = ""
r.ID = nil
r.Result = nil
r.Error = nil
}
func (r *clientResponse) UnmarshalJSON(raw []byte) error {
r.reset()
type resp *clientResponse
if err := json.Unmarshal(raw, resp(r)); err != nil {
return errors.New("bad response: " + string(raw))
}
var o = make(map[string]*json.RawMessage)
if err := json.Unmarshal(raw, &o); err != nil {
return errors.New("bad response: " + string(raw))
}
_, okVer := o["jsonrpc"]
_, okID := o["id"]
_, okRes := o["result"]
_, okErr := o["error"]
if !okVer || !okID || !(okRes || okErr) || (okRes && okErr) || len(o) > 3 {
return errors.New("bad response: " + string(raw))
}
if r.Version != "2.0" {
return errors.New("bad response: " + string(raw))
}
if okRes && r.Result == nil {
r.Result = &null
}
if okErr {
if o["error"] == nil {
return errors.New("bad response: " + string(raw))
}
oe := make(map[string]*json.RawMessage)
if err := json.Unmarshal(*o["error"], &oe); err != nil {
return errors.New("bad response: " + string(raw))
}
if oe["code"] == nil || oe["message"] == nil {
return errors.New("bad response: " + string(raw))
}
if _, ok := oe["data"]; (!ok && len(oe) > 2) || len(oe) > 3 {
return errors.New("bad response: " + string(raw))
}
}
if o["id"] == nil && !okErr {
return errors.New("bad response: " + string(raw))
}
return nil
}
func (c *clientCodec) ReadHeader(m *codec.Message) error {
// If return err:
// - io.EOF will became ErrShutdown or io.ErrUnexpectedEOF
// - it will be returned as is for all pending calls
// - client will be shutdown
// So, return io.EOF as is, return *Error for all other errors.
c.resp.reset()
if err := c.dec.Decode(&c.resp); err != nil {
if err == io.EOF {
return err
}
return NewError(errInternal.Code, err.Error())
}
if c.resp.ID == nil {
return c.resp.Error
}
c.mutex.Lock()
m.Method = c.pending[*c.resp.ID]
delete(c.pending, *c.resp.ID)
c.mutex.Unlock()
m.Error = ""
m.Id = *c.resp.ID
if c.resp.Error != nil {
m.Error = c.resp.Error.Error()
}
return nil
}
func (c *clientCodec) ReadBody(x interface{}) error {
// If x!=nil and return error e:
// - this call get e.Error() appended to "reading body "
// - other pending calls get error as is XXX actually other calls
// shouldn't be affected by this error at all, so let's at least
// provide different error message for other calls
if x == nil {
return nil
}
if err := json.Unmarshal(*c.resp.Result, x); err != nil {
e := NewError(errInternal.Code, err.Error())
e.Data = NewError(errInternal.Code, "some other Call failed to unmarshal Reply")
return e
}
return nil
}
func (c *clientCodec) Close() error {
return c.c.Close()
}