github.com/stafiprotocol/go-substrate-rpc-client@v1.4.7/pkg/gethrpc/handler.go (about)

     1  // Copyright 2019 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package rpc
    18  
    19  import (
    20  	"context"
    21  	"encoding/json"
    22  	"fmt"
    23  	"reflect"
    24  	"strconv"
    25  	"sync"
    26  	"time"
    27  
    28  	"github.com/ethereum/go-ethereum/log"
    29  )
    30  
    31  // handler handles JSON-RPC messages. There is one handler per connection. Note that
    32  // handler is not safe for concurrent use. Message handling never blocks indefinitely
    33  // because RPCs are processed on background goroutines launched by handler.
    34  //
    35  // The entry points for incoming messages are:
    36  //
    37  //	h.handleMsg(message)
    38  //	h.handleBatch(message)
    39  //
    40  // Outgoing calls use the requestOp struct. Register the request before sending it
    41  // on the connection:
    42  //
    43  //	op := &requestOp{ids: ...}
    44  //	h.addRequestOp(op)
    45  //
    46  // Now send the request, then wait for the reply to be delivered through handleMsg:
    47  //
    48  //	if err := op.wait(...); err != nil {
    49  //	    h.removeRequestOp(op) // timeout, etc.
    50  //	}
    51  type handler struct {
    52  	reg            *serviceRegistry
    53  	unsubscribeCb  *callback
    54  	idgen          func() ID                      // subscription ID generator
    55  	respWait       map[string]*requestOp          // active client requests
    56  	clientSubs     map[string]*ClientSubscription // active client subscriptions
    57  	callWG         sync.WaitGroup                 // pending call goroutines
    58  	rootCtx        context.Context                // canceled by close()
    59  	cancelRoot     func()                         // cancel function for rootCtx
    60  	conn           jsonWriter                     // where responses will be sent
    61  	log            log.Logger
    62  	allowSubscribe bool
    63  
    64  	subLock    sync.Mutex
    65  	serverSubs map[ID]*Subscription
    66  }
    67  
    68  type callProc struct {
    69  	ctx       context.Context
    70  	notifiers []*Notifier
    71  }
    72  
    73  func newHandler(connCtx context.Context, conn jsonWriter, idgen func() ID, reg *serviceRegistry) *handler {
    74  	rootCtx, cancelRoot := context.WithCancel(connCtx)
    75  	h := &handler{
    76  		reg:            reg,
    77  		idgen:          idgen,
    78  		conn:           conn,
    79  		respWait:       make(map[string]*requestOp),
    80  		clientSubs:     make(map[string]*ClientSubscription),
    81  		rootCtx:        rootCtx,
    82  		cancelRoot:     cancelRoot,
    83  		allowSubscribe: true,
    84  		serverSubs:     make(map[ID]*Subscription),
    85  		log:            log.Root(),
    86  	}
    87  	if conn.RemoteAddr() != "" {
    88  		h.log = h.log.New("conn", conn.RemoteAddr())
    89  	}
    90  	h.unsubscribeCb = newCallback(reflect.Value{}, reflect.ValueOf(h.unsubscribe))
    91  	return h
    92  }
    93  
    94  // handleBatch executes all messages in a batch and returns the responses.
    95  func (h *handler) handleBatch(msgs []*jsonrpcMessage) {
    96  	// Emit error response for empty batches:
    97  	if len(msgs) == 0 {
    98  		h.startCallProc(func(cp *callProc) {
    99  			h.conn.Write(cp.ctx, errorMessage(&invalidRequestError{"empty batch"}))
   100  		})
   101  		return
   102  	}
   103  
   104  	// Handle non-call messages first:
   105  	calls := make([]*jsonrpcMessage, 0, len(msgs))
   106  	for _, msg := range msgs {
   107  		if handled := h.handleImmediate(msg); !handled {
   108  			calls = append(calls, msg)
   109  		}
   110  	}
   111  	if len(calls) == 0 {
   112  		return
   113  	}
   114  	// Process calls on a goroutine because they may block indefinitely:
   115  	h.startCallProc(func(cp *callProc) {
   116  		answers := make([]*jsonrpcMessage, 0, len(msgs))
   117  		for _, msg := range calls {
   118  			if answer := h.handleCallMsg(cp, msg); answer != nil {
   119  				answers = append(answers, answer)
   120  			}
   121  		}
   122  		h.addSubscriptions(cp.notifiers)
   123  		if len(answers) > 0 {
   124  			h.conn.Write(cp.ctx, answers)
   125  		}
   126  		for _, n := range cp.notifiers {
   127  			n.activate()
   128  		}
   129  	})
   130  }
   131  
   132  // handleMsg handles a single message.
   133  func (h *handler) handleMsg(msg *jsonrpcMessage) {
   134  	if ok := h.handleImmediate(msg); ok {
   135  		return
   136  	}
   137  	h.startCallProc(func(cp *callProc) {
   138  		answer := h.handleCallMsg(cp, msg)
   139  		h.addSubscriptions(cp.notifiers)
   140  		if answer != nil {
   141  			h.conn.Write(cp.ctx, answer)
   142  		}
   143  		for _, n := range cp.notifiers {
   144  			n.activate()
   145  		}
   146  	})
   147  }
   148  
   149  // close cancels all requests except for inflightReq and waits for
   150  // call goroutines to shut down.
   151  func (h *handler) close(err error, inflightReq *requestOp) {
   152  	h.cancelAllRequests(err, inflightReq)
   153  	h.callWG.Wait()
   154  	h.cancelRoot()
   155  	h.cancelServerSubscriptions(err)
   156  }
   157  
   158  // addRequestOp registers a request operation.
   159  func (h *handler) addRequestOp(op *requestOp) {
   160  	for _, id := range op.ids {
   161  		h.respWait[string(id)] = op
   162  	}
   163  }
   164  
   165  // removeRequestOps stops waiting for the given request IDs.
   166  func (h *handler) removeRequestOp(op *requestOp) {
   167  	for _, id := range op.ids {
   168  		delete(h.respWait, string(id))
   169  	}
   170  }
   171  
   172  // cancelAllRequests unblocks and removes pending requests and active subscriptions.
   173  func (h *handler) cancelAllRequests(err error, inflightReq *requestOp) {
   174  	didClose := make(map[*requestOp]bool)
   175  	if inflightReq != nil {
   176  		didClose[inflightReq] = true
   177  	}
   178  
   179  	for id, op := range h.respWait {
   180  		// Remove the op so that later calls will not close op.resp again.
   181  		delete(h.respWait, id)
   182  
   183  		if !didClose[op] {
   184  			op.err = err
   185  			close(op.resp)
   186  			didClose[op] = true
   187  		}
   188  	}
   189  	for id, sub := range h.clientSubs {
   190  		delete(h.clientSubs, id)
   191  		sub.quitWithError(err, false)
   192  	}
   193  }
   194  
   195  func (h *handler) addSubscriptions(nn []*Notifier) {
   196  	h.subLock.Lock()
   197  	defer h.subLock.Unlock()
   198  
   199  	for _, n := range nn {
   200  		if sub := n.takeSubscription(); sub != nil {
   201  			h.serverSubs[sub.ID] = sub
   202  		}
   203  	}
   204  }
   205  
   206  // cancelServerSubscriptions removes all subscriptions and closes their error channels.
   207  func (h *handler) cancelServerSubscriptions(err error) {
   208  	h.subLock.Lock()
   209  	defer h.subLock.Unlock()
   210  
   211  	for id, s := range h.serverSubs {
   212  		s.err <- err
   213  		close(s.err)
   214  		delete(h.serverSubs, id)
   215  	}
   216  }
   217  
   218  // startCallProc runs fn in a new goroutine and starts tracking it in the h.calls wait group.
   219  func (h *handler) startCallProc(fn func(*callProc)) {
   220  	h.callWG.Add(1)
   221  	go func() {
   222  		ctx, cancel := context.WithCancel(h.rootCtx)
   223  		defer h.callWG.Done()
   224  		defer cancel()
   225  		fn(&callProc{ctx: ctx})
   226  	}()
   227  }
   228  
   229  // handleImmediate executes non-call messages. It returns false if the message is a
   230  // call or requires a reply.
   231  func (h *handler) handleImmediate(msg *jsonrpcMessage) bool {
   232  	start := time.Now()
   233  	switch {
   234  	case msg.isNotification():
   235  		// TODO find better way to perform this check
   236  		// if strings.HasSuffix(msg.Method, notificationMethodSuffix) {
   237  		h.handleSubscriptionResult(msg)
   238  		return true
   239  		// }
   240  		// return false
   241  	case msg.isResponse():
   242  		h.handleResponse(msg)
   243  		h.log.Trace("Handled RPC response", "reqid", idForLog{msg.ID}, "t", time.Since(start))
   244  		return true
   245  	default:
   246  		return false
   247  	}
   248  }
   249  
   250  // handleSubscriptionResult processes subscription notifications.
   251  func (h *handler) handleSubscriptionResult(msg *jsonrpcMessage) {
   252  	var result subscriptionResult
   253  	if err := json.Unmarshal(msg.Params, &result); err != nil {
   254  		h.log.Debug("Dropping invalid subscription message")
   255  		return
   256  	}
   257  	resultID := fmt.Sprint(result.ID)
   258  	if h.clientSubs[resultID] != nil {
   259  		h.clientSubs[resultID].deliver(result.Result)
   260  	}
   261  }
   262  
   263  // handleResponse processes method call responses.
   264  func (h *handler) handleResponse(msg *jsonrpcMessage) {
   265  	op := h.respWait[string(msg.ID)]
   266  	if op == nil {
   267  		h.log.Debug("Unsolicited RPC response", "reqid", idForLog{msg.ID})
   268  		return
   269  	}
   270  	delete(h.respWait, string(msg.ID))
   271  	// For normal responses, just forward the reply to Call/BatchCall.
   272  	if op.sub == nil {
   273  		op.resp <- msg
   274  		return
   275  	}
   276  	// For subscription responses, start the subscription if the server
   277  	// indicates success. EthSubscribe gets unblocked in either case through
   278  	// the op.resp channel.
   279  	defer close(op.resp)
   280  	if msg.Error != nil {
   281  		op.err = msg.Error
   282  		return
   283  	}
   284  	var subID string
   285  	if op.err = json.Unmarshal(msg.Result, &subID); op.err == nil {
   286  		op.sub.subid = subID
   287  		go op.sub.start()
   288  		h.clientSubs[op.sub.subid] = op.sub
   289  	}
   290  }
   291  
   292  // handleCallMsg executes a call message and returns the answer.
   293  func (h *handler) handleCallMsg(ctx *callProc, msg *jsonrpcMessage) *jsonrpcMessage {
   294  	start := time.Now()
   295  	switch {
   296  	case msg.isNotification():
   297  		h.handleCall(ctx, msg)
   298  		h.log.Debug("Served "+msg.Method, "t", time.Since(start))
   299  		return nil
   300  	case msg.isCall():
   301  		resp := h.handleCall(ctx, msg)
   302  		if resp.Error != nil {
   303  			h.log.Warn("Served "+msg.Method, "reqid", idForLog{msg.ID}, "t", time.Since(start), "err", resp.Error.Message)
   304  		} else {
   305  			h.log.Debug("Served "+msg.Method, "reqid", idForLog{msg.ID}, "t", time.Since(start))
   306  		}
   307  		return resp
   308  	case msg.hasValidID():
   309  		return msg.errorResponse(&invalidRequestError{"invalid request"})
   310  	default:
   311  		return errorMessage(&invalidRequestError{"invalid request"})
   312  	}
   313  }
   314  
   315  // handleCall processes method calls.
   316  func (h *handler) handleCall(cp *callProc, msg *jsonrpcMessage) *jsonrpcMessage {
   317  	// if msg.isSubscribe() {
   318  	// 	return h.handleSubscribe(cp, msg)
   319  	// }
   320  	var callb *callback
   321  	// if msg.isUnsubscribe() {
   322  	// callb = h.unsubscribeCb
   323  	// } else {
   324  	callb = h.reg.callback(msg.Method)
   325  	// }
   326  	if callb == nil {
   327  		return msg.errorResponse(&methodNotFoundError{method: msg.Method})
   328  	}
   329  	args, err := parsePositionalArguments(msg.Params, callb.argTypes)
   330  	if err != nil {
   331  		return msg.errorResponse(&invalidParamsError{err.Error()})
   332  	}
   333  
   334  	return h.runMethod(cp.ctx, msg, callb, args)
   335  }
   336  
   337  // handleSubscribe processes *_subscribe method calls.
   338  // func (h *handler) handleSubscribe(cp *callProc, msg *jsonrpcMessage) *jsonrpcMessage {
   339  // 	if !h.allowSubscribe {
   340  // 		return msg.errorResponse(ErrNotificationsUnsupported)
   341  // 	}
   342  
   343  // 	// Subscription method name is first argument.
   344  // 	name, err := parseSubscriptionName(msg.Params)
   345  // 	if err != nil {
   346  // 		return msg.errorResponse(&invalidParamsError{err.Error()})
   347  // 	}
   348  // 	namespace := msg.namespace()
   349  // 	callb := h.reg.subscription(namespace, name)
   350  // 	if callb == nil {
   351  // 		return msg.errorResponse(&subscriptionNotFoundError{namespace, name})
   352  // 	}
   353  
   354  // 	// Parse subscription name arg too, but remove it before calling the callback.
   355  // 	argTypes := append([]reflect.Type{stringType}, callb.argTypes...)
   356  // 	args, err := parsePositionalArguments(msg.Params, argTypes)
   357  // 	if err != nil {
   358  // 		return msg.errorResponse(&invalidParamsError{err.Error()})
   359  // 	}
   360  // 	args = args[1:]
   361  
   362  // 	// Install notifier in context so the subscription handler can find it.
   363  // 	n := &Notifier{h: h, namespace: namespace}
   364  // 	cp.notifiers = append(cp.notifiers, n)
   365  // 	ctx := context.WithValue(cp.ctx, notifierKey{}, n)
   366  
   367  // 	return h.runMethod(ctx, msg, callb, args)
   368  // }
   369  
   370  // runMethod runs the Go callback for an RPC method.
   371  func (h *handler) runMethod(ctx context.Context, msg *jsonrpcMessage, callb *callback, args []reflect.Value) *jsonrpcMessage {
   372  	result, err := callb.call(ctx, msg.Method, args)
   373  	if err != nil {
   374  		return msg.errorResponse(err)
   375  	}
   376  	return msg.response(result)
   377  }
   378  
   379  // unsubscribe is the callback function for all *_unsubscribe calls.
   380  func (h *handler) unsubscribe(ctx context.Context, id ID) (bool, error) {
   381  	h.subLock.Lock()
   382  	defer h.subLock.Unlock()
   383  
   384  	s := h.serverSubs[id]
   385  	if s == nil {
   386  		return false, ErrSubscriptionNotFound
   387  	}
   388  	close(s.err)
   389  	delete(h.serverSubs, id)
   390  	return true, nil
   391  }
   392  
   393  type idForLog struct{ json.RawMessage }
   394  
   395  func (id idForLog) String() string {
   396  	if s, err := strconv.Unquote(string(id.RawMessage)); err == nil {
   397  		return s
   398  	}
   399  	return string(id.RawMessage)
   400  }