lotus/rpclib/rpc_client.go

171 lines
3.6 KiB
Go
Raw Normal View History

package rpclib
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"reflect"
"sync/atomic"
)
var (
errorType = reflect.TypeOf(new(error)).Elem()
contextType = reflect.TypeOf(new(context.Context)).Elem()
)
2019-07-02 19:08:30 +00:00
// ErrClient is an error which occurred on the client side the library
type ErrClient struct {
err error
}
func (e *ErrClient) Error() string {
return fmt.Sprintf("RPC client error: %s", e.err)
}
2019-07-02 17:45:03 +00:00
// Unwrap unwraps the actual error
func (e *ErrClient) Unwrap(err error) error {
return e.err
}
type result reflect.Value
func (r *result) UnmarshalJSON(raw []byte) error {
return json.Unmarshal(raw, reflect.Value(*r).Interface())
}
type clientResponse struct {
Jsonrpc string `json:"jsonrpc"`
Result result `json:"result"`
2019-07-02 19:08:30 +00:00
ID int64 `json:"id"`
Error *respError `json:"error,omitempty"`
}
2019-07-02 17:45:03 +00:00
// NewClient creates new josnrpc 2.0 client
//
// handler must be pointer to a struct with function fields
//
// TODO: Example
func NewClient(addr string, namespace string, handler interface{}) {
htyp := reflect.TypeOf(handler)
if htyp.Kind() != reflect.Ptr {
panic("expected handler to be a pointer")
}
typ := htyp.Elem()
if typ.Kind() != reflect.Struct {
panic("handler should be a struct")
}
val := reflect.ValueOf(handler)
var idCtr int64
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
ftyp := f.Type
if ftyp.Kind() != reflect.Func {
panic("handler field not a func")
}
valOut, errOut, nout := processFuncOut(ftyp)
2019-07-02 13:49:10 +00:00
processResponse := func(resp clientResponse, code int) []reflect.Value {
out := make([]reflect.Value, nout)
if valOut != -1 {
out[valOut] = reflect.Value(resp.Result).Elem()
}
if errOut != -1 {
out[errOut] = reflect.New(errorType).Elem()
if resp.Error != nil {
2019-07-02 13:49:10 +00:00
out[errOut].Set(reflect.ValueOf(resp.Error))
}
}
return out
}
processError := func(err error) []reflect.Value {
out := make([]reflect.Value, nout)
if valOut != -1 {
out[valOut] = reflect.New(ftyp.Out(valOut)).Elem()
}
if errOut != -1 {
out[errOut] = reflect.New(errorType).Elem()
out[errOut].Set(reflect.ValueOf(&ErrClient{err}))
}
return out
}
hasCtx := 0
if ftyp.NumIn() > 0 && ftyp.In(0) == contextType {
hasCtx = 1
}
fn := reflect.MakeFunc(ftyp, func(args []reflect.Value) (results []reflect.Value) {
id := atomic.AddInt64(&idCtr, 1)
params := make([]param, len(args)-hasCtx)
for i, arg := range args[hasCtx:] {
params[i] = param{
v: arg,
}
}
req := request{
Jsonrpc: "2.0",
2019-07-02 19:08:30 +00:00
ID: &id,
Method: namespace + "." + f.Name,
Params: params,
}
b, err := json.Marshal(&req)
if err != nil {
return processError(err)
}
// prepare / execute http request
hreq, err := http.NewRequest("POST", addr, bytes.NewReader(b))
if err != nil {
return processError(err)
}
if hasCtx == 1 {
hreq = hreq.WithContext(args[0].Interface().(context.Context))
}
hreq.Header.Set("Content-Type", "application/json")
httpResp, err := http.DefaultClient.Do(hreq)
if err != nil {
return processError(err)
}
// process response
var resp clientResponse
if valOut != -1 {
resp.Result = result(reflect.New(ftyp.Out(valOut)))
}
if err := json.NewDecoder(httpResp.Body).Decode(&resp); err != nil {
return processError(err)
}
2019-07-02 19:08:30 +00:00
if err := httpResp.Body.Close(); err != nil {
return processError(err)
}
if resp.ID != *req.ID {
return processError(errors.New("request and response id didn't match"))
}
2019-07-02 13:49:10 +00:00
return processResponse(resp, httpResp.StatusCode)
})
val.Elem().Field(i).Set(fn)
}
}