rpc: golint comments

This commit is contained in:
Kiel barry 2018-06-05 15:22:23 -07:00
parent 580b598525
commit 97ae8b5c5c
9 changed files with 63 additions and 46 deletions

View file

@ -36,6 +36,7 @@ import (
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
) )
// Vars hardcodes custom error messages.
var ( var (
ErrClientQuit = errors.New("client is closed") ErrClientQuit = errors.New("client is closed")
ErrNoResult = errors.New("no result in JSON-RPC response") ErrNoResult = errors.New("no result in JSON-RPC response")
@ -191,29 +192,37 @@ func (io StdIOConn) Write(b []byte) (n int, err error) {
return os.Stdout.Write(b) return os.Stdout.Write(b)
} }
// Close is a noop.
func (io StdIOConn) Close() error { func (io StdIOConn) Close() error {
return nil return nil
} }
// LocalAddr sets the address of a Unix domain socket end point.
func (io StdIOConn) LocalAddr() net.Addr { func (io StdIOConn) LocalAddr() net.Addr {
return &net.UnixAddr{Name: "stdio", Net: "stdio"} return &net.UnixAddr{Name: "stdio", Net: "stdio"}
} }
// RemoteAddr sets the remote address of a Unix domain socket end point.
func (io StdIOConn) RemoteAddr() net.Addr { func (io StdIOConn) RemoteAddr() net.Addr {
return &net.UnixAddr{Name: "stdio", Net: "stdio"} return &net.UnixAddr{Name: "stdio", Net: "stdio"}
} }
// SetDeadline sets the operation, network type, and address of an error.
func (io StdIOConn) SetDeadline(t time.Time) error { func (io StdIOConn) SetDeadline(t time.Time) error {
return &net.OpError{Op: "set", Net: "stdio", Source: nil, Addr: nil, Err: errors.New("deadline not supported")} return &net.OpError{Op: "set", Net: "stdio", Source: nil, Addr: nil, Err: errors.New("deadline not supported")}
} }
// SetReadDeadline sets the operation, network type, and address of an error.
func (io StdIOConn) SetReadDeadline(t time.Time) error { func (io StdIOConn) SetReadDeadline(t time.Time) error {
return &net.OpError{Op: "set", Net: "stdio", Source: nil, Addr: nil, Err: errors.New("deadline not supported")} return &net.OpError{Op: "set", Net: "stdio", Source: nil, Addr: nil, Err: errors.New("deadline not supported")}
} }
// SetWriteDeadline sets the operation, network type, and address of an error.
func (io StdIOConn) SetWriteDeadline(t time.Time) error { func (io StdIOConn) SetWriteDeadline(t time.Time) error {
return &net.OpError{Op: "set", Net: "stdio", Source: nil, Addr: nil, Err: errors.New("deadline not supported")} return &net.OpError{Op: "set", Net: "stdio", Source: nil, Addr: nil, Err: errors.New("deadline not supported")}
} }
// DialStdIO returns a new client instance with ctx values.
func DialStdIO(ctx context.Context) (*Client, error) { func DialStdIO(ctx context.Context) (*Client, error) {
return newClient(ctx, func(_ context.Context) (net.Conn, error) { return newClient(ctx, func(_ context.Context) (net.Conn, error) {
return StdIOConn{}, nil return StdIOConn{}, nil
@ -329,7 +338,7 @@ func (c *Client) BatchCall(b []BatchElem) error {
return c.BatchCallContext(ctx, b) return c.BatchCallContext(ctx, b)
} }
// BatchCall sends all given requests as a single batch and waits for the server // BatchCallContext sends all given requests as a single batch and waits for the server
// to return a response for all of them. The wait duration is bounded by the // to return a response for all of them. The wait duration is bounded by the
// context's deadline. // context's deadline.
// //
@ -781,7 +790,7 @@ func (sub *ClientSubscription) start() {
sub.quitWithError(sub.forward()) sub.quitWithError(sub.forward())
} }
func (sub *ClientSubscription) forward() (err error, unsubscribeServer bool) { func (sub *ClientSubscription) forward() (unsubscribeServer bool, err error) {
cases := []reflect.SelectCase{ cases := []reflect.SelectCase{
{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(sub.quit)}, {Dir: reflect.SelectRecv, Chan: reflect.ValueOf(sub.quit)},
{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(sub.in)}, {Dir: reflect.SelectRecv, Chan: reflect.ValueOf(sub.in)},
@ -803,14 +812,14 @@ func (sub *ClientSubscription) forward() (err error, unsubscribeServer bool) {
switch chosen { switch chosen {
case 0: // <-sub.quit case 0: // <-sub.quit
return nil, false return false, nil
case 1: // <-sub.in case 1: // <-sub.in
val, err := sub.unmarshal(recv.Interface().(json.RawMessage)) val, err := sub.unmarshal(recv.Interface().(json.RawMessage))
if err != nil { if err != nil {
return err, true return true, err
} }
if buffer.Len() == maxClientSubscriptionBuffer { if buffer.Len() == maxClientSubscriptionBuffer {
return ErrSubscriptionQueueOverflow, true return true, ErrSubscriptionQueueOverflow
} }
buffer.PushBack(val) buffer.PushBack(val)
case 2: // sub.channel<- case 2: // sub.channel<-

View file

@ -173,6 +173,11 @@ func NewHTTPServer(cors []string, vhosts []string, srv *Server) *http.Server {
} }
} }
type contextKey string
func contextString(c contextKey) string {
return string(c)
}
// ServeHTTP serves JSON-RPC requests over HTTP. // ServeHTTP serves JSON-RPC requests over HTTP.
func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Permit dumb empty requests for remote health-checks (AWS) // Permit dumb empty requests for remote health-checks (AWS)
@ -183,13 +188,16 @@ func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), code) http.Error(w, err.Error(), code)
return return
} }
rem, sch, loc := contextKey("remote"), contextKey("scheme"), contextKey("local")
// All checks passed, create a codec that reads direct from the request body // All checks passed, create a codec that reads direct from the request body
// untilEOF and writes the response to w and order the server to process a // untilEOF and writes the response to w and order the server to process a
// single request. // single request.
ctx := r.Context() ctx := r.Context()
ctx = context.WithValue(ctx, "remote", r.RemoteAddr) ctx = context.WithValue(ctx, remote, r.RemoteAddr)
ctx = context.WithValue(ctx, "scheme", r.Proto) ctx = context.WithValue(ctx, sch, r.Proto)
ctx = context.WithValue(ctx, "local", r.Host) ctx = context.WithValue(ctx, loc, r.Host)
body := io.LimitReader(r.Body, maxRequestContentLength) body := io.LimitReader(r.Body, maxRequestContentLength)
codec := NewJSONCodec(&httpReadWriteNopCloser{body, w}) codec := NewJSONCodec(&httpReadWriteNopCloser{body, w})

View file

@ -40,13 +40,13 @@ const (
type jsonRequest struct { type jsonRequest struct {
Method string `json:"method"` Method string `json:"method"`
Version string `json:"jsonrpc"` Version string `json:"jsonrpc"`
Id json.RawMessage `json:"id,omitempty"` ID json.RawMessage `json:"id,omitempty"`
Payload json.RawMessage `json:"params,omitempty"` Payload json.RawMessage `json:"params,omitempty"`
} }
type jsonSuccessResponse struct { type jsonSuccessResponse struct {
Version string `json:"jsonrpc"` Version string `json:"jsonrpc"`
Id interface{} `json:"id,omitempty"` ID interface{} `json:"id,omitempty"`
Result interface{} `json:"result"` Result interface{} `json:"result"`
} }
@ -58,7 +58,7 @@ type jsonError struct {
type jsonErrResponse struct { type jsonErrResponse struct {
Version string `json:"jsonrpc"` Version string `json:"jsonrpc"`
Id interface{} `json:"id,omitempty"` ID interface{} `json:"id,omitempty"`
Error jsonError `json:"error"` Error jsonError `json:"error"`
} }
@ -150,17 +150,17 @@ func (c *jsonCodec) ReadRequestHeaders() ([]rpcRequest, bool, Error) {
return parseRequest(incomingMsg) return parseRequest(incomingMsg)
} }
// checkReqId returns an error when the given reqId isn't valid for RPC method calls. // checkReqID returns an error when the given reqID isn't valid for RPC method calls.
// valid id's are strings, numbers or null // valid id's are strings, numbers or null
func checkReqId(reqId json.RawMessage) error { func checkReqID(reqID json.RawMessage) error {
if len(reqId) == 0 { if len(reqID) == 0 {
return fmt.Errorf("missing request id") return fmt.Errorf("missing request id")
} }
if _, err := strconv.ParseFloat(string(reqId), 64); err == nil { if _, err := strconv.ParseFloat(string(reqID), 64); err == nil {
return nil return nil
} }
var str string var str string
if err := json.Unmarshal(reqId, &str); err == nil { if err := json.Unmarshal(reqID, &str); err == nil {
return nil return nil
} }
return fmt.Errorf("invalid request id") return fmt.Errorf("invalid request id")
@ -175,13 +175,13 @@ func parseRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) {
return nil, false, &invalidMessageError{err.Error()} return nil, false, &invalidMessageError{err.Error()}
} }
if err := checkReqId(in.Id); err != nil { if err := checkReqID(in.ID); err != nil {
return nil, false, &invalidMessageError{err.Error()} return nil, false, &invalidMessageError{err.Error()}
} }
// subscribe are special, they will always use `subscribeMethod` as first param in the payload // subscribe are special, they will always use `subscribeMethod` as first param in the payload
if strings.HasSuffix(in.Method, subscribeMethodSuffix) { if strings.HasSuffix(in.Method, subscribeMethodSuffix) {
reqs := []rpcRequest{{id: &in.Id, isPubSub: true}} reqs := []rpcRequest{{id: &in.ID, isPubSub: true}}
if len(in.Payload) > 0 { if len(in.Payload) > 0 {
// first param must be subscription name // first param must be subscription name
var subscribeMethod [1]string var subscribeMethod [1]string
@ -198,7 +198,7 @@ func parseRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) {
} }
if strings.HasSuffix(in.Method, unsubscribeMethodSuffix) { if strings.HasSuffix(in.Method, unsubscribeMethodSuffix) {
return []rpcRequest{{id: &in.Id, isPubSub: true, return []rpcRequest{{id: &in.ID, isPubSub: true,
method: in.Method, params: in.Payload}}, false, nil method: in.Method, params: in.Payload}}, false, nil
} }
@ -209,10 +209,10 @@ func parseRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) {
// regular RPC call // regular RPC call
if len(in.Payload) == 0 { if len(in.Payload) == 0 {
return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id}}, false, nil return []rpcRequest{{service: elems[0], method: elems[1], id: &in.ID}}, false, nil
} }
return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id, params: in.Payload}}, false, nil return []rpcRequest{{service: elems[0], method: elems[1], id: &in.ID, params: in.Payload}}, false, nil
} }
// parseBatchRequest will parse a batch request into a collection of requests from the given RawMessage, an indication // parseBatchRequest will parse a batch request into a collection of requests from the given RawMessage, an indication
@ -225,11 +225,11 @@ func parseBatchRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error)
requests := make([]rpcRequest, len(in)) requests := make([]rpcRequest, len(in))
for i, r := range in { for i, r := range in {
if err := checkReqId(r.Id); err != nil { if err := checkReqID(r.ID); err != nil {
return nil, false, &invalidMessageError{err.Error()} return nil, false, &invalidMessageError{err.Error()}
} }
id := &in[i].Id id := &in[i].ID
// subscribe are special, they will always use `subscriptionMethod` as first param in the payload // subscribe are special, they will always use `subscriptionMethod` as first param in the payload
if strings.HasSuffix(r.Method, subscribeMethodSuffix) { if strings.HasSuffix(r.Method, subscribeMethodSuffix) {
@ -275,9 +275,8 @@ func parseBatchRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error)
func (c *jsonCodec) ParseRequestArguments(argTypes []reflect.Type, params interface{}) ([]reflect.Value, Error) { func (c *jsonCodec) ParseRequestArguments(argTypes []reflect.Type, params interface{}) ([]reflect.Value, Error) {
if args, ok := params.(json.RawMessage); !ok { if args, ok := params.(json.RawMessage); !ok {
return nil, &invalidParamsError{"Invalid params supplied"} return nil, &invalidParamsError{"Invalid params supplied"}
} else {
return parsePositionalArguments(args, argTypes)
} }
return parsePositionalArguments(args, argTypes)
} }
// parsePositionalArguments tries to parse the given args to an array of values with the // parsePositionalArguments tries to parse the given args to an array of values with the
@ -321,20 +320,20 @@ func parsePositionalArguments(rawArgs json.RawMessage, types []reflect.Type) ([]
// CreateResponse will create a JSON-RPC success response with the given id and reply as result. // CreateResponse will create a JSON-RPC success response with the given id and reply as result.
func (c *jsonCodec) CreateResponse(id interface{}, reply interface{}) interface{} { func (c *jsonCodec) CreateResponse(id interface{}, reply interface{}) interface{} {
if isHexNum(reflect.TypeOf(reply)) { if isHexNum(reflect.TypeOf(reply)) {
return &jsonSuccessResponse{Version: jsonrpcVersion, Id: id, Result: fmt.Sprintf(`%#x`, reply)} return &jsonSuccessResponse{Version: jsonrpcVersion, ID: id, Result: fmt.Sprintf(`%#x`, reply)}
} }
return &jsonSuccessResponse{Version: jsonrpcVersion, Id: id, Result: reply} return &jsonSuccessResponse{Version: jsonrpcVersion, ID: id, Result: reply}
} }
// CreateErrorResponse will create a JSON-RPC error response with the given id and error. // CreateErrorResponse will create a JSON-RPC error response with the given id and error.
func (c *jsonCodec) CreateErrorResponse(id interface{}, err Error) interface{} { func (c *jsonCodec) CreateErrorResponse(id interface{}, err Error) interface{} {
return &jsonErrResponse{Version: jsonrpcVersion, Id: id, Error: jsonError{Code: err.ErrorCode(), Message: err.Error()}} return &jsonErrResponse{Version: jsonrpcVersion, ID: id, Error: jsonError{Code: err.ErrorCode(), Message: err.Error()}}
} }
// CreateErrorResponseWithInfo will create a JSON-RPC error response with the given id and error. // CreateErrorResponseWithInfo will create a JSON-RPC error response with the given id and error.
// info is optional and contains additional information about the error. When an empty string is passed it is ignored. // info is optional and contains additional information about the error. When an empty string is passed it is ignored.
func (c *jsonCodec) CreateErrorResponseWithInfo(id interface{}, err Error, info interface{}) interface{} { func (c *jsonCodec) CreateErrorResponseWithInfo(id interface{}, err Error, info interface{}) interface{} {
return &jsonErrResponse{Version: jsonrpcVersion, Id: id, return &jsonErrResponse{Version: jsonrpcVersion, ID: id,
Error: jsonError{Code: err.ErrorCode(), Message: err.Error(), Data: info}} Error: jsonError{Code: err.ErrorCode(), Message: err.Error(), Data: info}}
} }

View file

@ -69,8 +69,8 @@ func TestJSONRequestParsing(t *testing.T) {
t.Fatalf("Expected method 'Add' but got '%s'", requests[0].method) t.Fatalf("Expected method 'Add' but got '%s'", requests[0].method)
} }
if rawId, ok := requests[0].id.(*json.RawMessage); ok { if rawID, ok := requests[0].id.(*json.RawMessage); ok {
id, e := strconv.ParseInt(string(*rawId), 0, 64) id, e := strconv.ParseInt(string(*rawID), 0, 64)
if e != nil { if e != nil {
t.Fatalf("%v", e) t.Fatalf("%v", e)
} }

View file

@ -29,7 +29,7 @@ import (
"gopkg.in/fatih/set.v0" "gopkg.in/fatih/set.v0"
) )
const MetadataApi = "rpc" const MetadataAPI = "rpc"
// CodecOption specifies which type of messages this codec supports // CodecOption specifies which type of messages this codec supports
type CodecOption int type CodecOption int
@ -52,20 +52,20 @@ func NewServer() *Server {
// register a default service which will provide meta information about the RPC service such as the services and // register a default service which will provide meta information about the RPC service such as the services and
// methods it offers. // methods it offers.
rpcService := &RPCService{server} rpcService := &Service{server}
server.RegisterName(MetadataApi, rpcService) server.RegisterName(MetadataAPI, rpcService)
return server return server
} }
// RPCService gives meta information about the server. // Service gives meta information about the server.
// e.g. gives information about the loaded modules. // e.g. gives information about the loaded modules.
type RPCService struct { type Service struct {
server *Server server *Server
} }
// Modules returns the list of RPC services with their version number // Modules returns the list of RPC services with their version number
func (s *RPCService) Modules() map[string]string { func (s *Service) Modules() map[string]string {
modules := make(map[string]string) modules := make(map[string]string)
for name := range s.server.services { for name := range s.server.services {
modules[name] = "1.0" modules[name] = "1.0"

View file

@ -59,8 +59,8 @@ func (s *Service) Rets() (string, error) {
return "", nil return "", nil
} }
func (s *Service) InvalidRets1() (error, string) { func (s *Service) InvalidRets1() (string, error) {
return nil, "" return "", nil
} }
func (s *Service) InvalidRets2() (string, string) { func (s *Service) InvalidRets2() (string, string) {

View file

@ -25,14 +25,14 @@ import (
var ( var (
// ErrNotificationsUnsupported is returned when the connection doesn't support notifications // ErrNotificationsUnsupported is returned when the connection doesn't support notifications
ErrNotificationsUnsupported = errors.New("notifications not supported") ErrNotificationsUnsupported = errors.New("notifications not supported")
// ErrNotificationNotFound is returned when the notification for the given id is not found // ErrSubscriptionNotFound is returned when the notification for the given id is not found
ErrSubscriptionNotFound = errors.New("subscription not found") ErrSubscriptionNotFound = errors.New("subscription not found")
) )
// ID defines a pseudo random number that is used to identify RPC subscriptions. // ID defines a pseudo random number that is used to identify RPC subscriptions.
type ID string type ID string
// a Subscription is created by a notifier and tight to that notifier. The client can use // Subscription is created by a notifier and tight to that notifier. The client can use
// this subscription to wait for an unsubscribe request for the client, see Err(). // this subscription to wait for an unsubscribe request for the client, see Err().
type Subscription struct { type Subscription struct {
ID ID ID ID

View file

@ -160,6 +160,7 @@ func (bn *BlockNumber) UnmarshalJSON(data []byte) error {
return nil return nil
} }
// Int64 casts the bn into int64.
func (bn BlockNumber) Int64() int64 { func (bn BlockNumber) Int64() int64 {
return (int64)(bn) return (int64)(bn)
} }

View file

@ -230,12 +230,12 @@ func NewID() ID {
} }
} }
rpcId := hex.EncodeToString(id) rpcID := hex.EncodeToString(id)
// rpc ID's are RPC quantities, no leading zero's and 0 is 0x0 // rpc ID's are RPC quantities, no leading zero's and 0 is 0x0
rpcId = strings.TrimLeft(rpcId, "0") rpcID = strings.TrimLeft(rpcID, "0")
if rpcId == "" { if rpcID == "" {
rpcId = "0" rpcID = "0"
} }
return ID("0x" + rpcId) return ID("0x" + rpcID)
} }