github.com/klaytn/klaytn@v1.12.1/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 // UpstreamArchiveEN is the upstream archive mode EN endpoint 75 UpstreamArchiveEN string 76 ) 77 78 // Server is an RPC server. 79 type Server struct { 80 services serviceRegistry 81 idgen func() ID 82 codecs mapset.Set 83 run int32 84 wsConnCount int32 85 } 86 87 // NewServer creates a new server instance with no registered handlers. 88 func NewServer() *Server { 89 server := &Server{idgen: randomIDGenerator(), codecs: mapset.NewSet(), run: 1, wsConnCount: 0} 90 // Register the default service providing meta information about the RPC service such 91 // as the services and methods it offers. 92 rpcService := &RPCService{server} 93 server.RegisterName(MetadataApi, rpcService) 94 return server 95 } 96 97 // RPCService gives meta information about the server. 98 // e.g. gives information about the loaded modules. 99 type RPCService struct { 100 server *Server 101 } 102 103 // Modules returns the list of RPC services with their version number 104 func (s *RPCService) Modules() map[string]string { 105 s.server.services.mu.Lock() 106 defer s.server.services.mu.Unlock() 107 108 modules := make(map[string]string) 109 for name := range s.server.services.services { 110 modules[name] = "1.0" 111 } 112 return modules 113 } 114 115 func (s *Server) GetServices() map[string]service { 116 return s.services.services 117 } 118 119 // RegisterName creates a service for the given receiver type under the given name. When no 120 // methods on the given receiver match the criteria to be either a RPC method or a 121 // subscription an error is returned. Otherwise a new service is created and added to the 122 // service collection this server provides to clients. 123 func (s *Server) RegisterName(name string, rcvr interface{}) error { 124 return s.services.registerName(name, rcvr) 125 } 126 127 func GetNullServices() service { 128 return service{} 129 } 130 131 // ServeCodec reads incoming requests from codec, calls the appropriate callback and writes 132 // the response back using the given codec. It will block until the codec is closed or the 133 // server is stopped. In either case the codec is closed. 134 // 135 // Note that codec options are no longer supported. 136 func (s *Server) ServeCodec(codec ServerCodec, options CodecOption) { 137 defer codec.close() 138 139 // Don't serve if server is stopped. 140 if atomic.LoadInt32(&s.run) == 0 { 141 return 142 } 143 144 // Add the codec to the set so it can be closed by Stop. 145 s.codecs.Add(codec) 146 defer s.codecs.Remove(codec) 147 148 c := initClient(codec, s.idgen, &s.services) 149 <-codec.closed() 150 c.Close() 151 } 152 153 // ServeSingleRequest reads and processes a single RPC request from the given codec. This 154 // is used to serve HTTP connections. Subscriptions and reverse calls are not allowed in 155 // this mode. 156 func (s *Server) ServeSingleRequest(ctx context.Context, codec ServerCodec) { 157 // Don't serve if server is stopped. 158 if atomic.LoadInt32(&s.run) == 0 { 159 return 160 } 161 h := newHandler(ctx, codec, s.idgen, &s.services) 162 h.allowSubscribe = false 163 defer h.close(io.EOF, nil) 164 165 reqs, batch, err := codec.readBatch() 166 if err != nil { 167 if err != io.EOF { 168 rpcErrorResponsesCounter.Inc(int64(len(reqs))) 169 codec.writeJSON(ctx, errorMessage(&invalidMessageError{"parse error"})) 170 } 171 return 172 } 173 if batch { 174 h.handleBatch(reqs) 175 } else { 176 h.handleMsg(reqs[0]) 177 } 178 } 179 180 // Stop stops reading new requests, waits for stopPendingRequestTimeout to allow pending 181 // requests to finish, then closes all codecs which will cancel pending requests and 182 // subscriptions. 183 func (s *Server) Stop() { 184 if atomic.CompareAndSwapInt32(&s.run, 1, 0) { 185 logger.Debug("RPC Server shutdown initiatied") 186 s.codecs.Each(func(c interface{}) bool { 187 c.(ServerCodec).close() 188 return true 189 }) 190 } 191 }