github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/rpc/json.go (about) 1 // This file is part of the go-sberex library. The go-sberex library is 2 // free software: you can redistribute it and/or modify it under the terms 3 // of the GNU Lesser General Public License as published by the Free 4 // Software Foundation, either version 3 of the License, or (at your option) 5 // any later version. 6 // 7 // The go-sberex library is distributed in the hope that it will be useful, 8 // but WITHOUT ANY WARRANTY; without even the implied warranty of 9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 10 // General Public License <http://www.gnu.org/licenses/> for more details. 11 12 package rpc 13 14 import ( 15 "bytes" 16 "encoding/json" 17 "fmt" 18 "io" 19 "reflect" 20 "strconv" 21 "strings" 22 "sync" 23 24 "github.com/Sberex/go-sberex/log" 25 ) 26 27 const ( 28 jsonrpcVersion = "2.0" 29 serviceMethodSeparator = "_" 30 subscribeMethodSuffix = "_subscribe" 31 unsubscribeMethodSuffix = "_unsubscribe" 32 notificationMethodSuffix = "_subscription" 33 ) 34 35 type jsonRequest struct { 36 Method string `json:"method"` 37 Version string `json:"jsonrpc"` 38 Id json.RawMessage `json:"id,omitempty"` 39 Payload json.RawMessage `json:"params,omitempty"` 40 } 41 42 type jsonSuccessResponse struct { 43 Version string `json:"jsonrpc"` 44 Id interface{} `json:"id,omitempty"` 45 Result interface{} `json:"result"` 46 } 47 48 type jsonError struct { 49 Code int `json:"code"` 50 Message string `json:"message"` 51 Data interface{} `json:"data,omitempty"` 52 } 53 54 type jsonErrResponse struct { 55 Version string `json:"jsonrpc"` 56 Id interface{} `json:"id,omitempty"` 57 Error jsonError `json:"error"` 58 } 59 60 type jsonSubscription struct { 61 Subscription string `json:"subscription"` 62 Result interface{} `json:"result,omitempty"` 63 } 64 65 type jsonNotification struct { 66 Version string `json:"jsonrpc"` 67 Method string `json:"method"` 68 Params jsonSubscription `json:"params"` 69 } 70 71 // jsonCodec reads and writes JSON-RPC messages to the underlying connection. It 72 // also has support for parsing arguments and serializing (result) objects. 73 type jsonCodec struct { 74 closer sync.Once // close closed channel once 75 closed chan interface{} // closed on Close 76 decMu sync.Mutex // guards d 77 d *json.Decoder // decodes incoming requests 78 encMu sync.Mutex // guards e 79 e *json.Encoder // encodes responses 80 rw io.ReadWriteCloser // connection 81 } 82 83 func (err *jsonError) Error() string { 84 if err.Message == "" { 85 return fmt.Sprintf("json-rpc error %d", err.Code) 86 } 87 return err.Message 88 } 89 90 func (err *jsonError) ErrorCode() int { 91 return err.Code 92 } 93 94 // NewJSONCodec creates a new RPC server codec with support for JSON-RPC 2.0 95 func NewJSONCodec(rwc io.ReadWriteCloser) ServerCodec { 96 d := json.NewDecoder(rwc) 97 d.UseNumber() 98 return &jsonCodec{closed: make(chan interface{}), d: d, e: json.NewEncoder(rwc), rw: rwc} 99 } 100 101 // isBatch returns true when the first non-whitespace characters is '[' 102 func isBatch(msg json.RawMessage) bool { 103 for _, c := range msg { 104 // skip insignificant whitespace (http://www.ietf.org/rfc/rfc4627.txt) 105 if c == 0x20 || c == 0x09 || c == 0x0a || c == 0x0d { 106 continue 107 } 108 return c == '[' 109 } 110 return false 111 } 112 113 // ReadRequestHeaders will read new requests without parsing the arguments. It will 114 // return a collection of requests, an indication if these requests are in batch 115 // form or an error when the incoming message could not be read/parsed. 116 func (c *jsonCodec) ReadRequestHeaders() ([]rpcRequest, bool, Error) { 117 c.decMu.Lock() 118 defer c.decMu.Unlock() 119 120 var incomingMsg json.RawMessage 121 if err := c.d.Decode(&incomingMsg); err != nil { 122 return nil, false, &invalidRequestError{err.Error()} 123 } 124 125 if isBatch(incomingMsg) { 126 return parseBatchRequest(incomingMsg) 127 } 128 129 return parseRequest(incomingMsg) 130 } 131 132 // checkReqId returns an error when the given reqId isn't valid for RPC method calls. 133 // valid id's are strings, numbers or null 134 func checkReqId(reqId json.RawMessage) error { 135 if len(reqId) == 0 { 136 return fmt.Errorf("missing request id") 137 } 138 if _, err := strconv.ParseFloat(string(reqId), 64); err == nil { 139 return nil 140 } 141 var str string 142 if err := json.Unmarshal(reqId, &str); err == nil { 143 return nil 144 } 145 return fmt.Errorf("invalid request id") 146 } 147 148 // parseRequest will parse a single request from the given RawMessage. It will return 149 // the parsed request, an indication if the request was a batch or an error when 150 // the request could not be parsed. 151 func parseRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) { 152 var in jsonRequest 153 if err := json.Unmarshal(incomingMsg, &in); err != nil { 154 return nil, false, &invalidMessageError{err.Error()} 155 } 156 157 if err := checkReqId(in.Id); err != nil { 158 return nil, false, &invalidMessageError{err.Error()} 159 } 160 161 // subscribe are special, they will always use `subscribeMethod` as first param in the payload 162 if strings.HasSuffix(in.Method, subscribeMethodSuffix) { 163 reqs := []rpcRequest{{id: &in.Id, isPubSub: true}} 164 if len(in.Payload) > 0 { 165 // first param must be subscription name 166 var subscribeMethod [1]string 167 if err := json.Unmarshal(in.Payload, &subscribeMethod); err != nil { 168 log.Debug(fmt.Sprintf("Unable to parse subscription method: %v\n", err)) 169 return nil, false, &invalidRequestError{"Unable to parse subscription request"} 170 } 171 172 reqs[0].service, reqs[0].method = strings.TrimSuffix(in.Method, subscribeMethodSuffix), subscribeMethod[0] 173 reqs[0].params = in.Payload 174 return reqs, false, nil 175 } 176 return nil, false, &invalidRequestError{"Unable to parse subscription request"} 177 } 178 179 if strings.HasSuffix(in.Method, unsubscribeMethodSuffix) { 180 return []rpcRequest{{id: &in.Id, isPubSub: true, 181 method: in.Method, params: in.Payload}}, false, nil 182 } 183 184 elems := strings.Split(in.Method, serviceMethodSeparator) 185 if len(elems) != 2 { 186 return nil, false, &methodNotFoundError{in.Method, ""} 187 } 188 189 // regular RPC call 190 if len(in.Payload) == 0 { 191 return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id}}, false, nil 192 } 193 194 return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id, params: in.Payload}}, false, nil 195 } 196 197 // parseBatchRequest will parse a batch request into a collection of requests from the given RawMessage, an indication 198 // if the request was a batch or an error when the request could not be read. 199 func parseBatchRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) { 200 var in []jsonRequest 201 if err := json.Unmarshal(incomingMsg, &in); err != nil { 202 return nil, false, &invalidMessageError{err.Error()} 203 } 204 205 requests := make([]rpcRequest, len(in)) 206 for i, r := range in { 207 if err := checkReqId(r.Id); err != nil { 208 return nil, false, &invalidMessageError{err.Error()} 209 } 210 211 id := &in[i].Id 212 213 // subscribe are special, they will always use `subscriptionMethod` as first param in the payload 214 if strings.HasSuffix(r.Method, subscribeMethodSuffix) { 215 requests[i] = rpcRequest{id: id, isPubSub: true} 216 if len(r.Payload) > 0 { 217 // first param must be subscription name 218 var subscribeMethod [1]string 219 if err := json.Unmarshal(r.Payload, &subscribeMethod); err != nil { 220 log.Debug(fmt.Sprintf("Unable to parse subscription method: %v\n", err)) 221 return nil, false, &invalidRequestError{"Unable to parse subscription request"} 222 } 223 224 requests[i].service, requests[i].method = strings.TrimSuffix(r.Method, subscribeMethodSuffix), subscribeMethod[0] 225 requests[i].params = r.Payload 226 continue 227 } 228 229 return nil, true, &invalidRequestError{"Unable to parse (un)subscribe request arguments"} 230 } 231 232 if strings.HasSuffix(r.Method, unsubscribeMethodSuffix) { 233 requests[i] = rpcRequest{id: id, isPubSub: true, method: r.Method, params: r.Payload} 234 continue 235 } 236 237 if len(r.Payload) == 0 { 238 requests[i] = rpcRequest{id: id, params: nil} 239 } else { 240 requests[i] = rpcRequest{id: id, params: r.Payload} 241 } 242 if elem := strings.Split(r.Method, serviceMethodSeparator); len(elem) == 2 { 243 requests[i].service, requests[i].method = elem[0], elem[1] 244 } else { 245 requests[i].err = &methodNotFoundError{r.Method, ""} 246 } 247 } 248 249 return requests, true, nil 250 } 251 252 // ParseRequestArguments tries to parse the given params (json.RawMessage) with the given 253 // types. It returns the parsed values or an error when the parsing failed. 254 func (c *jsonCodec) ParseRequestArguments(argTypes []reflect.Type, params interface{}) ([]reflect.Value, Error) { 255 if args, ok := params.(json.RawMessage); !ok { 256 return nil, &invalidParamsError{"Invalid params supplied"} 257 } else { 258 return parsePositionalArguments(args, argTypes) 259 } 260 } 261 262 // parsePositionalArguments tries to parse the given args to an array of values with the 263 // given types. It returns the parsed values or an error when the args could not be 264 // parsed. Missing optional arguments are returned as reflect.Zero values. 265 func parsePositionalArguments(rawArgs json.RawMessage, types []reflect.Type) ([]reflect.Value, Error) { 266 // Read beginning of the args array. 267 dec := json.NewDecoder(bytes.NewReader(rawArgs)) 268 if tok, _ := dec.Token(); tok != json.Delim('[') { 269 return nil, &invalidParamsError{"non-array args"} 270 } 271 // Read args. 272 args := make([]reflect.Value, 0, len(types)) 273 for i := 0; dec.More(); i++ { 274 if i >= len(types) { 275 return nil, &invalidParamsError{fmt.Sprintf("too many arguments, want at most %d", len(types))} 276 } 277 argval := reflect.New(types[i]) 278 if err := dec.Decode(argval.Interface()); err != nil { 279 return nil, &invalidParamsError{fmt.Sprintf("invalid argument %d: %v", i, err)} 280 } 281 if argval.IsNil() && types[i].Kind() != reflect.Ptr { 282 return nil, &invalidParamsError{fmt.Sprintf("missing value for required argument %d", i)} 283 } 284 args = append(args, argval.Elem()) 285 } 286 // Read end of args array. 287 if _, err := dec.Token(); err != nil { 288 return nil, &invalidParamsError{err.Error()} 289 } 290 // Set any missing args to nil. 291 for i := len(args); i < len(types); i++ { 292 if types[i].Kind() != reflect.Ptr { 293 return nil, &invalidParamsError{fmt.Sprintf("missing value for required argument %d", i)} 294 } 295 args = append(args, reflect.Zero(types[i])) 296 } 297 return args, nil 298 } 299 300 // CreateResponse will create a JSON-RPC success response with the given id and reply as result. 301 func (c *jsonCodec) CreateResponse(id interface{}, reply interface{}) interface{} { 302 if isHexNum(reflect.TypeOf(reply)) { 303 return &jsonSuccessResponse{Version: jsonrpcVersion, Id: id, Result: fmt.Sprintf(`%#x`, reply)} 304 } 305 return &jsonSuccessResponse{Version: jsonrpcVersion, Id: id, Result: reply} 306 } 307 308 // CreateErrorResponse will create a JSON-RPC error response with the given id and error. 309 func (c *jsonCodec) CreateErrorResponse(id interface{}, err Error) interface{} { 310 return &jsonErrResponse{Version: jsonrpcVersion, Id: id, Error: jsonError{Code: err.ErrorCode(), Message: err.Error()}} 311 } 312 313 // CreateErrorResponseWithInfo will create a JSON-RPC error response with the given id and error. 314 // info is optional and contains additional information about the error. When an empty string is passed it is ignored. 315 func (c *jsonCodec) CreateErrorResponseWithInfo(id interface{}, err Error, info interface{}) interface{} { 316 return &jsonErrResponse{Version: jsonrpcVersion, Id: id, 317 Error: jsonError{Code: err.ErrorCode(), Message: err.Error(), Data: info}} 318 } 319 320 // CreateNotification will create a JSON-RPC notification with the given subscription id and event as params. 321 func (c *jsonCodec) CreateNotification(subid, namespace string, event interface{}) interface{} { 322 if isHexNum(reflect.TypeOf(event)) { 323 return &jsonNotification{Version: jsonrpcVersion, Method: namespace + notificationMethodSuffix, 324 Params: jsonSubscription{Subscription: subid, Result: fmt.Sprintf(`%#x`, event)}} 325 } 326 327 return &jsonNotification{Version: jsonrpcVersion, Method: namespace + notificationMethodSuffix, 328 Params: jsonSubscription{Subscription: subid, Result: event}} 329 } 330 331 // Write message to client 332 func (c *jsonCodec) Write(res interface{}) error { 333 c.encMu.Lock() 334 defer c.encMu.Unlock() 335 336 return c.e.Encode(res) 337 } 338 339 // Close the underlying connection 340 func (c *jsonCodec) Close() { 341 c.closer.Do(func() { 342 close(c.closed) 343 c.rw.Close() 344 }) 345 } 346 347 // Closed returns a channel which will be closed when Close is called 348 func (c *jsonCodec) Closed() <-chan interface{} { 349 return c.closed 350 }