-
Notifications
You must be signed in to change notification settings - Fork 0
/
WebsocketRPC.go
531 lines (504 loc) · 14.4 KB
/
WebsocketRPC.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
package wsrpc
import (
"encoding/json"
"errors"
"reflect"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
)
// LowLevelRPCMethod is an RPC method that send and receive raw messages
type LowLevelRPCMethod func(rpcConn *WebsocketRPCConn, arg json.RawMessage, reply *json.RawMessage) error
type rpcMessage struct {
ID json.RawMessage `json:"id,omitempty"`
JSONRPC string `json:"jsonrpc"`
Method *string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *RPCErrorInfo `json:"error,omitempty"`
}
// WebsocketRPC represents an RPC service that run over websocket
type WebsocketRPC struct {
method map[string]LowLevelRPCMethod
}
// WebsocketRPCConn represents an RPC connection to WebsocketRPC
type WebsocketRPCConn struct {
//RPC is a pointer to the RPC service
RPC *WebsocketRPC
//Session saves the user defined session data
Session map[string]interface{}
//Timeout sets the time to wait for a response, default is 10 seconds
Timeout time.Duration
adapter MessageAdapter
seq uint64
pending sync.Map
}
var typeOfPointToRPCConn = reflect.TypeOf((*WebsocketRPCConn)(nil))
// NewWebsocketRPC will create a websocket rpc object.
func NewWebsocketRPC() *WebsocketRPC {
r := new(WebsocketRPC)
r.method = make(map[string]LowLevelRPCMethod)
return r
}
func (rpcConn *WebsocketRPCConn) allocRequestSeq(done chan *rpcMessage) json.RawMessage {
seq := atomic.AddUint64(&rpcConn.seq, 1)
rpcConn.pending.Store(seq, done)
seqBytes, _ := json.Marshal(seq)
seqRaw := json.RawMessage(seqBytes)
return seqRaw
}
// ToRPCError is a helper function to convert error to RPCErrorInfo.
// If err is a RPCErrorInfo, then return it.
// If not, then create a RPCErrorInfo with Message = err.Error()
func ToRPCError(err error) RPCErrorInfo {
var rpcErr RPCErrorInfo
rpcErr, isRPCErr := err.(RPCErrorInfo)
if !isRPCErr {
rpcErr = RPCErrorInfo{
Code: -32000,
Message: err.Error()}
}
return rpcErr
}
func (rpcConn *WebsocketRPCConn) processRequest(msg rpcMessage) *rpcMessage {
if msg.Method == nil {
return &rpcMessage{
JSONRPC: "2.0",
ID: jsonNullValue,
Error: &RPCInvalidRequestError}
}
method, methodExists := rpcConn.RPC.method[*msg.Method]
if !methodExists {
if msg.ID == nil {
return nil
}
return &rpcMessage{
JSONRPC: "2.0",
ID: msg.ID,
Error: &RPCMothedNotFoundError}
}
result := jsonNullValue
err := method(rpcConn, msg.Params, &result)
if msg.ID == nil {
return nil
}
if err != nil {
rpcError := ToRPCError(err)
return &rpcMessage{
JSONRPC: "2.0",
ID: msg.ID,
Error: &rpcError}
}
return &rpcMessage{
JSONRPC: "2.0",
ID: msg.ID,
Result: result}
}
func (rpcConn *WebsocketRPCConn) processResponse(msg rpcMessage) {
if msg.ID != nil {
var seq uint64
err := json.Unmarshal(msg.ID, &seq)
if err == nil {
if done, ok := rpcConn.pending.Load(seq); ok {
rpcConn.pending.Delete(seq)
doneChan, _ := done.(chan *rpcMessage)
doneChan <- &msg
}
}
}
}
func (rpcConn *WebsocketRPCConn) processMessage(rawMsg []byte) {
var msgs []rpcMessage
var err error
responseInArray := IsJSONArray(rawMsg)
if responseInArray {
err = json.Unmarshal(rawMsg, &msgs)
} else {
msgs = make([]rpcMessage, 1)
err = json.Unmarshal(rawMsg, &msgs[0])
}
var responses []*rpcMessage
nResponse := 0
if err != nil {
responses = make([]*rpcMessage, 1)
nResponse = 1
responseInArray = false
responses[0] = &rpcMessage{
JSONRPC: "2.0",
ID: jsonNullValue,
Error: &RPCParseError}
} else if len(msgs) == 0 {
responses = make([]*rpcMessage, 1)
nResponse = 1
responseInArray = false
responses[0] = &rpcMessage{
JSONRPC: "2.0",
ID: jsonNullValue,
Error: &RPCInvalidRequestError}
} else {
responses = make([]*rpcMessage, len(msgs))
for _, msg := range msgs {
switch {
case msg.Result != nil || msg.Error != nil:
rpcConn.processResponse(msg)
default:
responses[nResponse] = rpcConn.processRequest(msg)
if responses[nResponse] != nil {
nResponse++
}
}
}
}
if nResponse == 0 {
return
}
var resultBytes []byte
if responseInArray {
resultBytes, err = json.Marshal(responses[:nResponse])
} else {
resultBytes, err = json.Marshal(responses[0])
}
if err != nil {
return
}
_ = rpcConn.adapter.WriteMessage(resultBytes)
}
// MakeCall is used to make a proxy (as a normal function) to a remote procedure.
// The format of params and result should be matched with inCodec and outCodec.
func (rpcConn *WebsocketRPCConn) MakeCall(name string, fptr interface{}, inCodec RPCParamsCodec, outCodec RPCParamsCodec) {
fobj := reflect.ValueOf(fptr).Elem()
fType := fobj.Type()
outParamInfo := getAllOutParamInfo(fType)
nOut := len(outParamInfo)
hasErrInfo := false
if nOut > 0 && outParamInfo[nOut-1] == typeOfError {
hasErrInfo = true
nOut--
outParamInfo = outParamInfo[:nOut]
}
makeErrorResult := func(err error) []reflect.Value {
if !hasErrInfo {
panic(err)
}
result := make([]reflect.Value, nOut+1)
for i := 0; i < nOut; i++ {
pType := outParamInfo[i]
if pType.Kind() == reflect.Ptr {
result[i] = reflect.New(pType.Elem())
} else {
result[i] = reflect.New(pType).Elem()
}
}
result[nOut] = reflect.ValueOf(err)
return result
}
processorFunc := func(in []reflect.Value) []reflect.Value {
var err error
argsRaw, err := inCodec.Encode(in)
if err != nil {
return makeErrorResult(err)
}
var replyRaw json.RawMessage
err = rpcConn.CallLowLevel(name, argsRaw, &replyRaw)
if err != nil {
return makeErrorResult(err)
}
reply, err := outCodec.Decode(replyRaw, outParamInfo)
if err != nil {
return makeErrorResult(err)
}
if hasErrInfo {
reply = append(reply, reflect.Zero(reflect.TypeOf((*error)(nil)).Elem()))
}
return reply
}
// skipcq: GO-W1006
v := reflect.MakeFunc(fType, processorFunc)
fobj.Set(v)
}
// CallExplicitly provides a `net/rpc`-like way to call a remote procedure.
// In this way, the struct is defined explicitly by the caller
func (rpcConn *WebsocketRPCConn) CallExplicitly(name string, params interface{}, reply interface{}) error {
paramBytes, err := json.Marshal(params)
if err != nil {
return err
}
rawParam := json.RawMessage(paramBytes)
var rawReply json.RawMessage
err = rpcConn.CallLowLevel(name, rawParam, &rawReply)
if err != nil {
return err
}
err = json.Unmarshal(rawReply, reply)
return err
}
// CallLowLevel is used to call a remote rrocedure in low-level way (use json.RawMessage).
func (rpcConn *WebsocketRPCConn) CallLowLevel(name string, params json.RawMessage, reply *json.RawMessage) error {
msg := rpcMessage{
JSONRPC: "2.0",
Method: &name,
Params: params}
done := make(chan *rpcMessage, 1)
msg.ID = rpcConn.allocRequestSeq(done)
resultBytes, err := json.Marshal(msg)
if err != nil {
return err
}
err = rpcConn.adapter.WriteMessage(resultBytes)
if err != nil {
return err
}
var r *rpcMessage
timer := time.NewTimer(rpcConn.Timeout)
select {
case r = <-done:
timer.Stop()
case <-timer.C:
return errors.New("RPC call timed out")
}
if r.Error != nil {
return r.Error
}
if reply != nil {
*reply = r.Result
}
return nil
}
// MakeNotify is used to make a proxy (as a normal function) to send a notification.
// The format of params should be matched with inCodec.
func (rpcConn *WebsocketRPCConn) MakeNotify(name string, fptr interface{}, inCodec RPCParamsCodec) {
fobj := reflect.ValueOf(fptr).Elem()
fType := fobj.Type()
nOut := fType.NumOut()
hasErrInfo := false
switch nOut {
case 0:
// do nothing
case 1:
if fType.Out(0) == typeOfError {
hasErrInfo = true
nOut--
} else {
panic(errors.New("the function must have no return value or return an error"))
}
default:
panic(errors.New("the function must have no return value or return an error"))
}
makeErrorResult := func(err error) []reflect.Value {
if !hasErrInfo {
panic(err)
}
return []reflect.Value{reflect.ValueOf(err)}
}
processorFunc := func(in []reflect.Value) []reflect.Value {
var err error
argsRaw, err := inCodec.Encode(in)
if err != nil {
return makeErrorResult(err)
}
err = rpcConn.NotifyLowLevel(name, argsRaw)
if err != nil {
return makeErrorResult(err)
}
if hasErrInfo {
return []reflect.Value{reflect.Zero(reflect.TypeOf((*error)(nil)).Elem())}
}
return []reflect.Value{}
}
// skipcq: GO-W1006
v := reflect.MakeFunc(fType, processorFunc)
fobj.Set(v)
}
// NotifyExplicitly provides a `net/rpc`-like way to send a notification.
// In this way, the struct is defined explicitly by the caller
func (rpcConn *WebsocketRPCConn) NotifyExplicitly(name string, params interface{}) error {
paramBytes, err := json.Marshal(params)
if err != nil {
return err
}
rawParam := json.RawMessage(paramBytes)
err = rpcConn.NotifyLowLevel(name, rawParam)
return err
}
// NotifyLowLevel is used to send a notification in low-level way (use json.RawMessage).
func (rpcConn *WebsocketRPCConn) NotifyLowLevel(name string, params json.RawMessage) error {
msg := rpcMessage{
JSONRPC: "2.0",
Method: &name,
Params: params}
resultBytes, err := json.Marshal(msg)
if err != nil {
return err
}
err = rpcConn.adapter.WriteMessage(resultBytes)
return err
}
// Register is used to register a normal function for RPC.
//
// The function can have a pointer argument to receive RPC connection object
// (optional, must be the first in argument, do not provide name for this argument).
// The function can also have an error return value. (optional, must be the last out argument,
// do not provide name for this argument)
//
// The format of params and result should be matched with inCodec and outCodec.
// (not including special params described above, of course)
func (rpc *WebsocketRPC) Register(name string, fobj interface{}, inCodec RPCParamsCodec, outCodec RPCParamsCodec) {
if fobj == nil {
return
}
fValue := reflect.ValueOf(fobj)
if !fValue.IsValid() || fValue.IsZero() {
return
}
fType := reflect.TypeOf(fobj)
inParamInfo := getAllInParamInfo(fType)
nOut := fType.NumOut()
hasErrInfo := false
if nOut > 0 && fType.Out(nOut-1) == typeOfError {
hasErrInfo = true
nOut--
}
inThis := false
if len(inParamInfo) > 0 && inParamInfo[0] == typeOfPointToRPCConn {
inThis = true
inParamInfo = inParamInfo[1:]
}
fLowLevel := func(rpcConn *WebsocketRPCConn, rawArgs json.RawMessage, rawReply *json.RawMessage) error {
var err error
args, err := inCodec.Decode(rawArgs, inParamInfo)
if err != nil {
return RPCInvalidParamsError
}
var reply []reflect.Value
if inThis {
reply = fValue.Call(append([]reflect.Value{reflect.ValueOf(rpcConn)}, args...))
} else {
reply = fValue.Call(args)
}
if hasErrInfo {
errorOut := reply[nOut].Interface()
if errorOut != nil {
return errorOut.(error)
}
reply = reply[:nOut]
}
*rawReply, err = outCodec.Encode(reply)
return err
}
rpc.RegisterLowLevel(name, fLowLevel)
}
// RegisterExplicitly provides a `net/rpc`-like way to register a function.
// In this way, the struct is defined explicitly by the caller
//
// funcObj must have three in arguments. The first is a pointer to RPC connection,
// the second is used to receive the params (can be a pointer or not),
// and the third is used to send the result (must be a pointer).
// Moreover, the function can have no out parameters
// or have one out parameter to return error info.
func (rpc *WebsocketRPC) RegisterExplicitly(name string, fobj interface{}) error {
if fobj == nil {
return errors.New("nil pointer passed to RegisterExplicitly")
}
fValue := reflect.ValueOf(fobj)
if !fValue.IsValid() || fValue.IsZero() {
return errors.New("nil pointer passed to RegisterExplicitly")
}
fType := reflect.TypeOf(fobj)
hasErrInfoOut := false
nIn := fType.NumIn()
nOut := fType.NumOut()
if nIn != 3 || nOut > 1 {
return errors.New("cannot recognize the function")
}
if fType.In(0) != typeOfPointToRPCConn {
return errors.New("first in argument must be a pointer to a RPC connection")
}
argType := fType.In(1)
argIsPtr := argType.Kind() == reflect.Ptr
if argIsPtr {
argType = argType.Elem()
}
replyType := fType.In(2)
if replyType.Kind() != reflect.Ptr {
return errors.New("reply argument must be a pointer")
}
replyType = replyType.Elem()
if nOut == 1 {
if fType.Out(0) != typeOfError {
return errors.New("the function must return a void or an error")
}
hasErrInfoOut = true
}
fLowLevel := func(rpcConn *WebsocketRPCConn, rawArgs json.RawMessage, rawReply *json.RawMessage) error {
var argv reflect.Value
var err error
argv = reflect.New(argType)
err = json.Unmarshal(rawArgs, argv.Interface())
if err != nil {
return err
}
if !argIsPtr {
argv = argv.Elem()
}
replyv := reflect.New(replyType)
result := fValue.Call([]reflect.Value{reflect.ValueOf(rpcConn), argv, replyv})
if hasErrInfoOut {
targetErr := result[0].Interface()
if targetErr != nil {
return targetErr.(error)
}
}
rawReplyBytes, err := json.Marshal(replyv.Interface())
if err != nil {
return err
}
*rawReply = rawReplyBytes
return nil
}
rpc.RegisterLowLevel(name, fLowLevel)
return nil
}
// RegisterLowLevel is used to register a normal function for RPC in low-level way (use json.RawMessage).
func (rpc *WebsocketRPC) RegisterLowLevel(name string, method LowLevelRPCMethod) {
if method == nil {
return
}
rpc.method[name] = method
}
// Connect is a function to create a rpc connection binded to a websocket connection.
func (rpc *WebsocketRPC) Connect(conn *websocket.Conn) *WebsocketRPCConn {
return rpc.ConnectAdapter(NewWebsocketMessageAdapter(conn))
}
// ConnectAdapter is a function to create a rpc connection binded to an adapter.
func (rpc *WebsocketRPC) ConnectAdapter(adapter MessageAdapter) *WebsocketRPCConn {
r := WebsocketRPCConn{
RPC: rpc,
adapter: adapter,
Timeout: 10 * time.Second,
Session: make(map[string]interface{})}
return &r
}
// ServeConn is a function that you should call it at last to receive messages continuously.
// It will block until the connection is closed.
func (rpcConn *WebsocketRPCConn) ServeConn() {
for {
message, err := rpcConn.adapter.ReadMessage()
if err != nil {
break
}
go func() {
rpcConn.processMessage(message)
}()
}
// Handle all pending request
rpcConn.pending.Range(func(key interface{}, value interface{}) bool {
rpcConn.pending.Delete(key)
done, _ := value.(chan *rpcMessage)
done <- &rpcMessage{
JSONRPC: "2.0",
ID: jsonNullValue,
Error: &RPCInternalError}
return true
})
}