github.com/ava-labs/subnet-evm@v0.6.4/rpc/server.go (about)

     1  // (c) 2019-2020, Ava Labs, Inc.
     2  //
     3  // This file is a derived work, based on the go-ethereum library whose original
     4  // notices appear below.
     5  //
     6  // It is distributed under a license compatible with the licensing terms of the
     7  // original code from which it is derived.
     8  //
     9  // Much love to the original authors for their work.
    10  // **********
    11  // Copyright 2015 The go-ethereum Authors
    12  // This file is part of the go-ethereum library.
    13  //
    14  // The go-ethereum library is free software: you can redistribute it and/or modify
    15  // it under the terms of the GNU Lesser General Public License as published by
    16  // the Free Software Foundation, either version 3 of the License, or
    17  // (at your option) any later version.
    18  //
    19  // The go-ethereum library is distributed in the hope that it will be useful,
    20  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    21  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    22  // GNU Lesser General Public License for more details.
    23  //
    24  // You should have received a copy of the GNU Lesser General Public License
    25  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    26  
    27  package rpc
    28  
    29  import (
    30  	"context"
    31  	"io"
    32  	"sync"
    33  	"sync/atomic"
    34  	"time"
    35  
    36  	"github.com/ethereum/go-ethereum/log"
    37  )
    38  
    39  const MetadataApi = "rpc"
    40  
    41  // CodecOption specifies which type of messages a codec supports.
    42  //
    43  // Deprecated: this option is no longer honored by Server.
    44  type CodecOption int
    45  
    46  const (
    47  	// OptionMethodInvocation is an indication that the codec supports RPC method calls
    48  	OptionMethodInvocation CodecOption = 1 << iota
    49  
    50  	// OptionSubscriptions is an indication that the codec supports RPC notifications
    51  	OptionSubscriptions = 1 << iota // support pub sub
    52  )
    53  
    54  // Server is an RPC server.
    55  type Server struct {
    56  	services        serviceRegistry
    57  	idgen           func() ID
    58  	maximumDuration time.Duration
    59  
    60  	mutex              sync.Mutex
    61  	codecs             map[ServerCodec]struct{}
    62  	run                atomic.Bool
    63  	batchItemLimit     int
    64  	batchResponseLimit int
    65  }
    66  
    67  // NewServer creates a new server instance with no registered handlers.
    68  //
    69  // If [maximumDuration] > 0, the deadline of incoming requests is
    70  // [maximumDuration] in the future. Otherwise, no deadline is assigned to
    71  // incoming requests.
    72  func NewServer(maximumDuration time.Duration) *Server {
    73  	server := &Server{
    74  		idgen:           randomIDGenerator(),
    75  		codecs:          make(map[ServerCodec]struct{}),
    76  		maximumDuration: maximumDuration,
    77  	}
    78  	server.run.Store(true)
    79  	// Register the default service providing meta information about the RPC service such
    80  	// as the services and methods it offers.
    81  	rpcService := &RPCService{server}
    82  	server.RegisterName(MetadataApi, rpcService)
    83  	return server
    84  }
    85  
    86  // SetBatchLimits sets limits applied to batch requests. There are two limits: 'itemLimit'
    87  // is the maximum number of items in a batch. 'maxResponseSize' is the maximum number of
    88  // response bytes across all requests in a batch.
    89  //
    90  // This method should be called before processing any requests via ServeCodec, ServeHTTP,
    91  // ServeListener etc.
    92  func (s *Server) SetBatchLimits(itemLimit, maxResponseSize int) {
    93  	s.batchItemLimit = itemLimit
    94  	s.batchResponseLimit = maxResponseSize
    95  }
    96  
    97  // RegisterName creates a service for the given receiver type under the given name. When no
    98  // methods on the given receiver match the criteria to be either a RPC method or a
    99  // subscription an error is returned. Otherwise a new service is created and added to the
   100  // service collection this server provides to clients.
   101  func (s *Server) RegisterName(name string, receiver interface{}) error {
   102  	return s.services.registerName(name, receiver)
   103  }
   104  
   105  // ServeCodec reads incoming requests from codec, calls the appropriate callback and writes
   106  // the response back using the given codec. It will block until the codec is closed or the
   107  // server is stopped. In either case the codec is closed.
   108  //
   109  // Note that codec options are no longer supported.
   110  func (s *Server) ServeCodec(codec ServerCodec, options CodecOption, apiMaxDuration, refillRate, maxStored time.Duration) {
   111  	defer codec.close()
   112  
   113  	if !s.trackCodec(codec) {
   114  		return
   115  	}
   116  	defer s.untrackCodec(codec)
   117  
   118  	cfg := &clientConfig{
   119  		idgen:              s.idgen,
   120  		batchItemLimit:     s.batchItemLimit,
   121  		batchResponseLimit: s.batchResponseLimit,
   122  	}
   123  	c := initClient(codec, &s.services, cfg, apiMaxDuration, refillRate, maxStored)
   124  	<-codec.closed()
   125  	c.Close()
   126  }
   127  
   128  func (s *Server) trackCodec(codec ServerCodec) bool {
   129  	s.mutex.Lock()
   130  	defer s.mutex.Unlock()
   131  
   132  	if !s.run.Load() {
   133  		return false // Don't serve if server is stopped.
   134  	}
   135  	s.codecs[codec] = struct{}{}
   136  	return true
   137  }
   138  
   139  func (s *Server) untrackCodec(codec ServerCodec) {
   140  	s.mutex.Lock()
   141  	defer s.mutex.Unlock()
   142  
   143  	delete(s.codecs, codec)
   144  }
   145  
   146  // serveSingleRequest reads and processes a single RPC request from the given codec. This
   147  // is used to serve HTTP connections. Subscriptions and reverse calls are not allowed in
   148  // this mode.
   149  func (s *Server) serveSingleRequest(ctx context.Context, codec ServerCodec) {
   150  	// Don't serve if server is stopped.
   151  	if !s.run.Load() {
   152  		return
   153  	}
   154  
   155  	h := newHandler(ctx, codec, s.idgen, &s.services, s.batchItemLimit, s.batchResponseLimit)
   156  	h.deadlineContext = s.maximumDuration
   157  	h.allowSubscribe = false
   158  	defer h.close(io.EOF, nil)
   159  
   160  	reqs, batch, err := codec.readBatch()
   161  	if err != nil {
   162  		if err != io.EOF {
   163  			resp := errorMessage(&invalidMessageError{"parse error"})
   164  			codec.writeJSON(ctx, resp, true)
   165  		}
   166  		return
   167  	}
   168  	if batch {
   169  		h.handleBatch(reqs)
   170  	} else {
   171  		h.handleMsg(reqs[0])
   172  	}
   173  }
   174  
   175  // Stop stops reading new requests, waits for stopPendingRequestTimeout to allow pending
   176  // requests to finish, then closes all codecs which will cancel pending requests and
   177  // subscriptions.
   178  func (s *Server) Stop() {
   179  	s.mutex.Lock()
   180  	defer s.mutex.Unlock()
   181  
   182  	if s.run.CompareAndSwap(true, false) {
   183  		log.Debug("RPC server shutting down")
   184  		for codec := range s.codecs {
   185  			codec.close()
   186  		}
   187  	}
   188  }
   189  
   190  // RPCService gives meta information about the server.
   191  // e.g. gives information about the loaded modules.
   192  type RPCService struct {
   193  	server *Server
   194  }
   195  
   196  // Modules returns the list of RPC services with their version number
   197  func (s *RPCService) Modules() map[string]string {
   198  	s.server.services.mu.Lock()
   199  	defer s.server.services.mu.Unlock()
   200  
   201  	modules := make(map[string]string)
   202  	for name := range s.server.services.services {
   203  		modules[name] = "1.0"
   204  	}
   205  	return modules
   206  }
   207  
   208  // PeerInfo contains information about the remote end of the network connection.
   209  //
   210  // This is available within RPC method handlers through the context. Call
   211  // PeerInfoFromContext to get information about the client connection related to
   212  // the current method call.
   213  type PeerInfo struct {
   214  	// Transport is name of the protocol used by the client.
   215  	// This can be "http", "ws" or "ipc".
   216  	Transport string
   217  
   218  	// Address of client. This will usually contain the IP address and port.
   219  	RemoteAddr string
   220  
   221  	// Additional information for HTTP and WebSocket connections.
   222  	HTTP struct {
   223  		// Protocol version, i.e. "HTTP/1.1". This is not set for WebSocket.
   224  		Version string
   225  		// Header values sent by the client.
   226  		UserAgent string
   227  		Origin    string
   228  		Host      string
   229  	}
   230  }
   231  
   232  type peerInfoContextKey struct{}
   233  
   234  // PeerInfoFromContext returns information about the client's network connection.
   235  // Use this with the context passed to RPC method handler functions.
   236  //
   237  // The zero value is returned if no connection info is present in ctx.
   238  func PeerInfoFromContext(ctx context.Context) PeerInfo {
   239  	info, _ := ctx.Value(peerInfoContextKey{}).(PeerInfo)
   240  	return info
   241  }