github.com/klaytn/klaytn@v1.10.2/networks/rpc/server.go (about)

     1  // Modifications Copyright 2018 The klaytn Authors
     2  // Copyright 2015 The go-ethereum Authors
     3  // This file is part of the go-ethereum library.
     4  //
     5  // The go-ethereum library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The go-ethereum library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    17  //
    18  // This file is derived from rpc/server.go (2018/06/04).
    19  // Modified and improved for the klaytn development.
    20  
    21  package rpc
    22  
    23  import (
    24  	"context"
    25  	"io"
    26  	"sync/atomic"
    27  
    28  	mapset "github.com/deckarep/golang-set"
    29  )
    30  
    31  const MetadataApi = "rpc"
    32  
    33  // CodecOption specifies which type of messages a codec supports.
    34  //
    35  // Deprecated: this option is no longer honored by Server.
    36  type CodecOption int
    37  
    38  const (
    39  	// OptionMethodInvocation is an indication that the codec supports RPC method calls
    40  	OptionMethodInvocation CodecOption = 1 << iota
    41  
    42  	// OptionSubscriptions is an indication that the codec supports RPC notifications
    43  	OptionSubscriptions = 1 << iota // support pub sub
    44  
    45  	// pendingRequestLimit is a limit for concurrent RPC method calls
    46  	pendingRequestLimit = 200000
    47  )
    48  
    49  var (
    50  	// ConcurrencyLimit is a limit for the number of concurrency connection for RPC servers.
    51  	// It can be overwritten by rpc.concurrencylimit flag
    52  	ConcurrencyLimit = 3000
    53  
    54  	// pendingRequestCount is a total number of concurrent RPC method calls
    55  	pendingRequestCount int64 = 0
    56  
    57  	// TODO-Klaytn: move websocket configurations to Config struct in /network/rpc/server.go
    58  	// MaxSubscriptionPerWSConn is a maximum number of subscription for a websocket connection
    59  	MaxSubscriptionPerWSConn int32 = 3000
    60  
    61  	// WebsocketReadDeadline is the read deadline on the underlying network connection in seconds. 0 means read will not timeout
    62  	WebsocketReadDeadline int64 = 0
    63  
    64  	// WebsocketWriteDeadline is the write deadline on the underlying network connection in seconds. 0 means write will not timeout
    65  	WebsocketWriteDeadline int64 = 0
    66  
    67  	// MaxWebsocketConnections is a maximum number of websocket connections
    68  	MaxWebsocketConnections int32 = 3000
    69  
    70  	// NonEthCompatible is a bool value that determines whether to use return formatting of the eth namespace API  provided for compatibility.
    71  	// It can be overwritten by rpc.eth.noncompatible flag
    72  	NonEthCompatible = false
    73  )
    74  
    75  // Server is an RPC server.
    76  type Server struct {
    77  	services    serviceRegistry
    78  	idgen       func() ID
    79  	codecs      mapset.Set
    80  	run         int32
    81  	wsConnCount int32
    82  }
    83  
    84  // NewServer creates a new server instance with no registered handlers.
    85  func NewServer() *Server {
    86  	server := &Server{idgen: randomIDGenerator(), codecs: mapset.NewSet(), run: 1, wsConnCount: 0}
    87  	// Register the default service providing meta information about the RPC service such
    88  	// as the services and methods it offers.
    89  	rpcService := &RPCService{server}
    90  	server.RegisterName(MetadataApi, rpcService)
    91  	return server
    92  }
    93  
    94  // RPCService gives meta information about the server.
    95  // e.g. gives information about the loaded modules.
    96  type RPCService struct {
    97  	server *Server
    98  }
    99  
   100  // Modules returns the list of RPC services with their version number
   101  func (s *RPCService) Modules() map[string]string {
   102  	s.server.services.mu.Lock()
   103  	defer s.server.services.mu.Unlock()
   104  
   105  	modules := make(map[string]string)
   106  	for name := range s.server.services.services {
   107  		modules[name] = "1.0"
   108  	}
   109  	return modules
   110  }
   111  
   112  func (s *Server) GetServices() map[string]service {
   113  	return s.services.services
   114  }
   115  
   116  // RegisterName creates a service for the given receiver type under the given name. When no
   117  // methods on the given receiver match the criteria to be either a RPC method or a
   118  // subscription an error is returned. Otherwise a new service is created and added to the
   119  // service collection this server provides to clients.
   120  func (s *Server) RegisterName(name string, rcvr interface{}) error {
   121  	return s.services.registerName(name, rcvr)
   122  }
   123  
   124  func GetNullServices() service {
   125  	return service{}
   126  }
   127  
   128  // ServeCodec reads incoming requests from codec, calls the appropriate callback and writes
   129  // the response back using the given codec. It will block until the codec is closed or the
   130  // server is stopped. In either case the codec is closed.
   131  //
   132  // Note that codec options are no longer supported.
   133  func (s *Server) ServeCodec(codec ServerCodec, options CodecOption) {
   134  	defer codec.close()
   135  
   136  	// Don't serve if server is stopped.
   137  	if atomic.LoadInt32(&s.run) == 0 {
   138  		return
   139  	}
   140  
   141  	// Add the codec to the set so it can be closed by Stop.
   142  	s.codecs.Add(codec)
   143  	defer s.codecs.Remove(codec)
   144  
   145  	c := initClient(codec, s.idgen, &s.services)
   146  	<-codec.closed()
   147  	c.Close()
   148  }
   149  
   150  // ServeSingleRequest reads and processes a single RPC request from the given codec. This
   151  // is used to serve HTTP connections. Subscriptions and reverse calls are not allowed in
   152  // this mode.
   153  func (s *Server) ServeSingleRequest(ctx context.Context, codec ServerCodec) {
   154  	// Don't serve if server is stopped.
   155  	if atomic.LoadInt32(&s.run) == 0 {
   156  		return
   157  	}
   158  	h := newHandler(ctx, codec, s.idgen, &s.services)
   159  	h.allowSubscribe = false
   160  	defer h.close(io.EOF, nil)
   161  
   162  	reqs, batch, err := codec.readBatch()
   163  	if err != nil {
   164  		if err != io.EOF {
   165  			rpcErrorResponsesCounter.Inc(int64(len(reqs)))
   166  			codec.writeJSON(ctx, errorMessage(&invalidMessageError{"parse error"}))
   167  		}
   168  		return
   169  	}
   170  	if batch {
   171  		h.handleBatch(reqs)
   172  	} else {
   173  		h.handleMsg(reqs[0])
   174  	}
   175  }
   176  
   177  // Stop stops reading new requests, waits for stopPendingRequestTimeout to allow pending
   178  // requests to finish, then closes all codecs which will cancel pending requests and
   179  // subscriptions.
   180  func (s *Server) Stop() {
   181  	if atomic.CompareAndSwapInt32(&s.run, 1, 0) {
   182  		logger.Debug("RPC Server shutdown initiatied")
   183  		s.codecs.Each(func(c interface{}) bool {
   184  			c.(ServerCodec).close()
   185  			return true
   186  		})
   187  	}
   188  }