github.com/theQRL/go-zond@v0.1.1/rpc/server.go (about) 1 // Copyright 2015 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 "io" 22 "sync" 23 "sync/atomic" 24 25 "github.com/theQRL/go-zond/log" 26 ) 27 28 const MetadataApi = "rpc" 29 const EngineApi = "engine" 30 31 // CodecOption specifies which type of messages a codec supports. 32 // 33 // Deprecated: this option is no longer honored by Server. 34 type CodecOption int 35 36 const ( 37 // OptionMethodInvocation is an indication that the codec supports RPC method calls 38 OptionMethodInvocation CodecOption = 1 << iota 39 40 // OptionSubscriptions is an indication that the codec supports RPC notifications 41 OptionSubscriptions = 1 << iota // support pub sub 42 ) 43 44 // Server is an RPC server. 45 type Server struct { 46 services serviceRegistry 47 idgen func() ID 48 49 mutex sync.Mutex 50 codecs map[ServerCodec]struct{} 51 run atomic.Bool 52 batchItemLimit int 53 batchResponseLimit int 54 } 55 56 // NewServer creates a new server instance with no registered handlers. 57 func NewServer() *Server { 58 server := &Server{ 59 idgen: randomIDGenerator(), 60 codecs: make(map[ServerCodec]struct{}), 61 } 62 server.run.Store(true) 63 // Register the default service providing meta information about the RPC service such 64 // as the services and methods it offers. 65 rpcService := &RPCService{server} 66 server.RegisterName(MetadataApi, rpcService) 67 return server 68 } 69 70 // SetBatchLimits sets limits applied to batch requests. There are two limits: 'itemLimit' 71 // is the maximum number of items in a batch. 'maxResponseSize' is the maximum number of 72 // response bytes across all requests in a batch. 73 // 74 // This method should be called before processing any requests via ServeCodec, ServeHTTP, 75 // ServeListener etc. 76 func (s *Server) SetBatchLimits(itemLimit, maxResponseSize int) { 77 s.batchItemLimit = itemLimit 78 s.batchResponseLimit = maxResponseSize 79 } 80 81 // RegisterName creates a service for the given receiver type under the given name. When no 82 // methods on the given receiver match the criteria to be either a RPC method or a 83 // subscription an error is returned. Otherwise a new service is created and added to the 84 // service collection this server provides to clients. 85 func (s *Server) RegisterName(name string, receiver interface{}) error { 86 return s.services.registerName(name, receiver) 87 } 88 89 // ServeCodec reads incoming requests from codec, calls the appropriate callback and writes 90 // the response back using the given codec. It will block until the codec is closed or the 91 // server is stopped. In either case the codec is closed. 92 // 93 // Note that codec options are no longer supported. 94 func (s *Server) ServeCodec(codec ServerCodec, options CodecOption) { 95 defer codec.close() 96 97 if !s.trackCodec(codec) { 98 return 99 } 100 defer s.untrackCodec(codec) 101 102 cfg := &clientConfig{ 103 idgen: s.idgen, 104 batchItemLimit: s.batchItemLimit, 105 batchResponseLimit: s.batchResponseLimit, 106 } 107 c := initClient(codec, &s.services, cfg) 108 <-codec.closed() 109 c.Close() 110 } 111 112 func (s *Server) trackCodec(codec ServerCodec) bool { 113 s.mutex.Lock() 114 defer s.mutex.Unlock() 115 116 if !s.run.Load() { 117 return false // Don't serve if server is stopped. 118 } 119 s.codecs[codec] = struct{}{} 120 return true 121 } 122 123 func (s *Server) untrackCodec(codec ServerCodec) { 124 s.mutex.Lock() 125 defer s.mutex.Unlock() 126 127 delete(s.codecs, codec) 128 } 129 130 // serveSingleRequest reads and processes a single RPC request from the given codec. This 131 // is used to serve HTTP connections. Subscriptions and reverse calls are not allowed in 132 // this mode. 133 func (s *Server) serveSingleRequest(ctx context.Context, codec ServerCodec) { 134 // Don't serve if server is stopped. 135 if !s.run.Load() { 136 return 137 } 138 139 h := newHandler(ctx, codec, s.idgen, &s.services, s.batchItemLimit, s.batchResponseLimit) 140 h.allowSubscribe = false 141 defer h.close(io.EOF, nil) 142 143 reqs, batch, err := codec.readBatch() 144 if err != nil { 145 if err != io.EOF { 146 resp := errorMessage(&invalidMessageError{"parse error"}) 147 codec.writeJSON(ctx, resp, true) 148 } 149 return 150 } 151 if batch { 152 h.handleBatch(reqs) 153 } else { 154 h.handleMsg(reqs[0]) 155 } 156 } 157 158 // Stop stops reading new requests, waits for stopPendingRequestTimeout to allow pending 159 // requests to finish, then closes all codecs which will cancel pending requests and 160 // subscriptions. 161 func (s *Server) Stop() { 162 s.mutex.Lock() 163 defer s.mutex.Unlock() 164 165 if s.run.CompareAndSwap(true, false) { 166 log.Debug("RPC server shutting down") 167 for codec := range s.codecs { 168 codec.close() 169 } 170 } 171 } 172 173 // RPCService gives meta information about the server. 174 // e.g. gives information about the loaded modules. 175 type RPCService struct { 176 server *Server 177 } 178 179 // Modules returns the list of RPC services with their version number 180 func (s *RPCService) Modules() map[string]string { 181 s.server.services.mu.Lock() 182 defer s.server.services.mu.Unlock() 183 184 modules := make(map[string]string) 185 for name := range s.server.services.services { 186 modules[name] = "1.0" 187 } 188 return modules 189 } 190 191 // PeerInfo contains information about the remote end of the network connection. 192 // 193 // This is available within RPC method handlers through the context. Call 194 // PeerInfoFromContext to get information about the client connection related to 195 // the current method call. 196 type PeerInfo struct { 197 // Transport is name of the protocol used by the client. 198 // This can be "http", "ws" or "ipc". 199 Transport string 200 201 // Address of client. This will usually contain the IP address and port. 202 RemoteAddr string 203 204 // Additional information for HTTP and WebSocket connections. 205 HTTP struct { 206 // Protocol version, i.e. "HTTP/1.1". This is not set for WebSocket. 207 Version string 208 // Header values sent by the client. 209 UserAgent string 210 Origin string 211 Host string 212 } 213 } 214 215 type peerInfoContextKey struct{} 216 217 // PeerInfoFromContext returns information about the client's network connection. 218 // Use this with the context passed to RPC method handler functions. 219 // 220 // The zero value is returned if no connection info is present in ctx. 221 func PeerInfoFromContext(ctx context.Context) PeerInfo { 222 info, _ := ctx.Value(peerInfoContextKey{}).(PeerInfo) 223 return info 224 }