github.com/energicryptocurrency/go-energi@v1.1.7/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 "fmt" 22 "reflect" 23 "runtime" 24 "strings" 25 "sync" 26 "sync/atomic" 27 28 "github.com/energicryptocurrency/go-energi/log" 29 30 mapset "github.com/deckarep/golang-set" 31 ) 32 33 const MetadataApi = "rpc" 34 35 // CodecOption specifies which type of messages this codec supports 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 suports RPC notifications 43 OptionSubscriptions = 1 << iota // support pub sub 44 ) 45 46 // NewServer will create a new server instance with no registered handlers. 47 func NewServer() *Server { 48 server := &Server{ 49 services: make(serviceRegistry), 50 codecs: mapset.NewSet(), 51 run: 1, 52 } 53 54 // register a default service which will provide meta information about the RPC 55 // service such as the services and methods it offers. 56 rpcService := &RPCService{server} 57 _ = server.RegisterName(MetadataApi, rpcService) 58 59 return server 60 } 61 62 // RPCService gives meta information about the server. 63 // e.g. gives information about the loaded modules. 64 type RPCService struct { 65 server *Server 66 } 67 68 // Modules returns the list of RPC services with their version number 69 func (s *RPCService) Modules() map[string]string { 70 modules := make(map[string]string) 71 for name := range s.server.services { 72 modules[name] = "1.0" 73 } 74 return modules 75 } 76 77 // RegisterName will create a service for the given rcvr type under the given name. When no methods on the given rcvr 78 // match the criteria to be either a RPC method or a subscription an error is returned. Otherwise a new service is 79 // created and added to the service collection this server instance serves. 80 func (s *Server) RegisterName(name string, rcvr interface{}) error { 81 if s.services == nil { 82 s.services = make(serviceRegistry) 83 } 84 85 svc := new(service) 86 svc.typ = reflect.TypeOf(rcvr) 87 rcvrVal := reflect.ValueOf(rcvr) 88 89 if name == "" { 90 return fmt.Errorf("no service name for type %s", svc.typ.String()) 91 } 92 if !isExported(reflect.Indirect(rcvrVal).Type().Name()) { 93 return fmt.Errorf("%s is not exported", reflect.Indirect(rcvrVal).Type().Name()) 94 } 95 96 methods, subscriptions := suitableCallbacks(rcvrVal, svc.typ) 97 98 if len(methods) == 0 && len(subscriptions) == 0 { 99 return fmt.Errorf("Service %T doesn't have any suitable methods/subscriptions to expose", rcvr) 100 } 101 102 // already a previous service register under given name, merge methods/subscriptions 103 if regsvc, present := s.services[name]; present { 104 for _, m := range methods { 105 regsvc.callbacks[formatName(m.method.Name)] = m 106 } 107 for _, s := range subscriptions { 108 regsvc.subscriptions[formatName(s.method.Name)] = s 109 } 110 return nil 111 } 112 113 svc.name = name 114 svc.callbacks, svc.subscriptions = methods, subscriptions 115 116 s.services[svc.name] = svc 117 return nil 118 } 119 120 // serveRequest will reads requests from the codec, calls the RPC callback and 121 // writes the response to the given codec. 122 // 123 // If singleShot is true it will process a single request, otherwise it will handle 124 // requests until the codec returns an error when reading a request (in most cases 125 // an EOF). It executes requests in parallel when singleShot is false. 126 func (s *Server) serveRequest(ctx context.Context, codec ServerCodec, singleShot bool, options CodecOption) error { 127 var pend sync.WaitGroup 128 129 defer func() { 130 if err := recover(); err != nil { 131 const size = 64 << 10 132 buf := make([]byte, size) 133 buf = buf[:runtime.Stack(buf, false)] 134 log.Error(string(buf)) 135 } 136 s.codecsMu.Lock() 137 s.codecs.Remove(codec) 138 s.codecsMu.Unlock() 139 }() 140 141 // ctx, cancel := context.WithCancel(context.Background()) 142 ctx, cancel := context.WithCancel(ctx) 143 defer cancel() 144 145 // if the codec supports notification include a notifier that callbacks can use 146 // to send notification to clients. It is tied to the codec/connection. If the 147 // connection is closed the notifier will stop and cancels all active subscriptions. 148 if options&OptionSubscriptions == OptionSubscriptions { 149 ctx = context.WithValue(ctx, notifierKey{}, newNotifier(codec)) 150 } 151 s.codecsMu.Lock() 152 if atomic.LoadInt32(&s.run) != 1 { // server stopped 153 s.codecsMu.Unlock() 154 return &shutdownError{} 155 } 156 s.codecs.Add(codec) 157 s.codecsMu.Unlock() 158 159 // test if the server is ordered to stop 160 for atomic.LoadInt32(&s.run) == 1 { 161 reqs, batch, err := s.readRequest(codec) 162 if err != nil { 163 // If a parsing error occurred, send an error 164 if err.Error() != "EOF" { 165 log.Debug(fmt.Sprintf("read error %v\n", err)) 166 codec.Write(codec.CreateErrorResponse(nil, err)) 167 } 168 // Error or end of stream, wait for requests and tear down 169 pend.Wait() 170 return nil 171 } 172 173 // check if server is ordered to shutdown and return an error 174 // telling the client that his request failed. 175 if atomic.LoadInt32(&s.run) != 1 { 176 err = &shutdownError{} 177 if batch { 178 resps := make([]interface{}, len(reqs)) 179 for i, r := range reqs { 180 resps[i] = codec.CreateErrorResponse(&r.id, err) 181 } 182 codec.Write(resps) 183 } else { 184 codec.Write(codec.CreateErrorResponse(&reqs[0].id, err)) 185 } 186 return nil 187 } 188 // If a single shot request is executing, run and return immediately 189 if singleShot { 190 if batch { 191 s.execBatch(ctx, codec, reqs) 192 } else { 193 s.exec(ctx, codec, reqs[0]) 194 } 195 return nil 196 } 197 // For multi-shot connections, start a goroutine to serve and loop back 198 pend.Add(1) 199 200 go func(reqs []*serverRequest, batch bool) { 201 defer pend.Done() 202 if batch { 203 s.execBatch(ctx, codec, reqs) 204 } else { 205 s.exec(ctx, codec, reqs[0]) 206 } 207 }(reqs, batch) 208 } 209 return nil 210 } 211 212 // ServeCodec reads incoming requests from codec, calls the appropriate callback and writes the 213 // response back using the given codec. It will block until the codec is closed or the server is 214 // stopped. In either case the codec is closed. 215 func (s *Server) ServeCodec(codec ServerCodec, options CodecOption) { 216 defer codec.Close() 217 s.serveRequest(context.Background(), codec, false, options) 218 } 219 220 // ServeSingleRequest reads and processes a single RPC request from the given codec. It will not 221 // close the codec unless a non-recoverable error has occurred. Note, this method will return after 222 // a single request has been processed! 223 func (s *Server) ServeSingleRequest(ctx context.Context, codec ServerCodec, options CodecOption) { 224 s.serveRequest(ctx, codec, true, options) 225 } 226 227 // Stop will stop reading new requests, wait for stopPendingRequestTimeout to allow pending requests to finish, 228 // close all codecs which will cancel pending requests/subscriptions. 229 func (s *Server) Stop() { 230 if atomic.CompareAndSwapInt32(&s.run, 1, 0) { 231 log.Debug("RPC Server shutdown initiatied") 232 s.codecsMu.Lock() 233 defer s.codecsMu.Unlock() 234 s.codecs.Each(func(c interface{}) bool { 235 c.(ServerCodec).Close() 236 return true 237 }) 238 } 239 } 240 241 // createSubscription will call the subscription callback and returns the subscription id or error. 242 func (s *Server) createSubscription(ctx context.Context, c ServerCodec, req *serverRequest) (ID, error) { 243 // subscription have as first argument the context following optional arguments 244 args := []reflect.Value{req.callb.rcvr, reflect.ValueOf(ctx)} 245 args = append(args, req.args...) 246 reply := req.callb.method.Func.Call(args) 247 248 if !reply[1].IsNil() { // subscription creation failed 249 return "", reply[1].Interface().(error) 250 } 251 252 return reply[0].Interface().(*Subscription).ID, nil 253 } 254 255 // handle executes a request and returns the response from the callback. 256 func (s *Server) handle(ctx context.Context, codec ServerCodec, req *serverRequest) (interface{}, func()) { 257 if req.err != nil { 258 return codec.CreateErrorResponse(&req.id, req.err), nil 259 } 260 261 if req.isUnsubscribe { // cancel subscription, first param must be the subscription id 262 if len(req.args) >= 1 && req.args[0].Kind() == reflect.String { 263 notifier, supported := NotifierFromContext(ctx) 264 if !supported { // interface doesn't support subscriptions (e.g. http) 265 return codec.CreateErrorResponse(&req.id, &callbackError{ErrNotificationsUnsupported.Error()}), nil 266 } 267 268 subid := ID(req.args[0].String()) 269 if err := notifier.unsubscribe(subid); err != nil { 270 return codec.CreateErrorResponse(&req.id, &callbackError{err.Error()}), nil 271 } 272 273 return codec.CreateResponse(req.id, true), nil 274 } 275 return codec.CreateErrorResponse(&req.id, &invalidParamsError{"Expected subscription id as first argument"}), nil 276 } 277 278 if req.callb.isSubscribe { 279 subid, err := s.createSubscription(ctx, codec, req) 280 if err != nil { 281 return codec.CreateErrorResponse(&req.id, &callbackError{err.Error()}), nil 282 } 283 284 // active the subscription after the sub id was successfully sent to the client 285 activateSub := func() { 286 notifier, _ := NotifierFromContext(ctx) 287 notifier.activate(subid, req.svcname) 288 } 289 290 return codec.CreateResponse(req.id, subid), activateSub 291 } 292 293 // regular RPC call, prepare arguments 294 if len(req.args) != len(req.callb.argTypes) { 295 rpcErr := &invalidParamsError{fmt.Sprintf("%s%s%s expects %d parameters, got %d", 296 req.svcname, serviceMethodSeparator, req.callb.method.Name, 297 len(req.callb.argTypes), len(req.args))} 298 return codec.CreateErrorResponse(&req.id, rpcErr), nil 299 } 300 301 arguments := []reflect.Value{req.callb.rcvr} 302 if req.callb.hasCtx { 303 arguments = append(arguments, reflect.ValueOf(ctx)) 304 } 305 if len(req.args) > 0 { 306 arguments = append(arguments, req.args...) 307 } 308 309 // execute RPC method and return result 310 reply := req.callb.method.Func.Call(arguments) 311 if len(reply) == 0 { 312 return codec.CreateResponse(req.id, nil), nil 313 } 314 if req.callb.errPos >= 0 { // test if method returned an error 315 if !reply[req.callb.errPos].IsNil() { 316 e := reply[req.callb.errPos].Interface().(error) 317 res := codec.CreateErrorResponse(&req.id, &callbackError{e.Error()}) 318 return res, nil 319 } 320 } 321 return codec.CreateResponse(req.id, reply[0].Interface()), nil 322 } 323 324 // exec executes the given request and writes the result back using the codec. 325 func (s *Server) exec(ctx context.Context, codec ServerCodec, req *serverRequest) { 326 var response interface{} 327 var callback func() 328 if req.err != nil { 329 response = codec.CreateErrorResponse(&req.id, req.err) 330 } else { 331 response, callback = s.handle(ctx, codec, req) 332 } 333 334 if err := codec.Write(response); err != nil { 335 log.Error(fmt.Sprintf("%v\n", err)) 336 codec.Close() 337 } 338 339 // when request was a subscribe request this allows these subscriptions to be actived 340 if callback != nil { 341 callback() 342 } 343 } 344 345 // execBatch executes the given requests and writes the result back using the codec. 346 // It will only write the response back when the last request is processed. 347 func (s *Server) execBatch(ctx context.Context, codec ServerCodec, requests []*serverRequest) { 348 responses := make([]interface{}, len(requests)) 349 var callbacks []func() 350 for i, req := range requests { 351 if req.err != nil { 352 responses[i] = codec.CreateErrorResponse(&req.id, req.err) 353 } else { 354 var callback func() 355 if responses[i], callback = s.handle(ctx, codec, req); callback != nil { 356 callbacks = append(callbacks, callback) 357 } 358 } 359 } 360 361 if err := codec.Write(responses); err != nil { 362 log.Error(fmt.Sprintf("%v\n", err)) 363 codec.Close() 364 } 365 366 // when request holds one of more subscribe requests this allows these subscriptions to be activated 367 for _, c := range callbacks { 368 c() 369 } 370 } 371 372 // readRequest requests the next (batch) request from the codec. It will return the collection 373 // of requests, an indication if the request was a batch, the invalid request identifier and an 374 // error when the request could not be read/parsed. 375 func (s *Server) readRequest(codec ServerCodec) ([]*serverRequest, bool, Error) { 376 reqs, batch, err := codec.ReadRequestHeaders() 377 if err != nil { 378 return nil, batch, err 379 } 380 381 requests := make([]*serverRequest, len(reqs)) 382 383 // verify requests 384 for i, r := range reqs { 385 var ok bool 386 var svc *service 387 388 if r.err != nil { 389 requests[i] = &serverRequest{id: r.id, err: r.err} 390 continue 391 } 392 393 if r.isPubSub && strings.HasSuffix(r.method, unsubscribeMethodSuffix) { 394 requests[i] = &serverRequest{id: r.id, isUnsubscribe: true} 395 argTypes := []reflect.Type{reflect.TypeOf("")} // expect subscription id as first arg 396 if args, err := codec.ParseRequestArguments(argTypes, r.params); err == nil { 397 requests[i].args = args 398 } else { 399 requests[i].err = &invalidParamsError{err.Error()} 400 } 401 continue 402 } 403 404 if svc, ok = s.services[r.service]; !ok { // rpc method isn't available 405 requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}} 406 continue 407 } 408 409 if r.isPubSub { // eth_subscribe, r.method contains the subscription method name 410 if callb, ok := svc.subscriptions[r.method]; ok { 411 requests[i] = &serverRequest{id: r.id, svcname: svc.name, callb: callb} 412 if r.params != nil && len(callb.argTypes) > 0 { 413 argTypes := []reflect.Type{reflect.TypeOf("")} 414 argTypes = append(argTypes, callb.argTypes...) 415 if args, err := codec.ParseRequestArguments(argTypes, r.params); err == nil { 416 requests[i].args = args[1:] // first one is service.method name which isn't an actual argument 417 } else { 418 requests[i].err = &invalidParamsError{err.Error()} 419 } 420 } 421 } else { 422 requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}} 423 } 424 continue 425 } 426 427 if callb, ok := svc.callbacks[r.method]; ok { // lookup RPC method 428 requests[i] = &serverRequest{id: r.id, svcname: svc.name, callb: callb} 429 if r.params != nil && len(callb.argTypes) > 0 { 430 if args, err := codec.ParseRequestArguments(callb.argTypes, r.params); err == nil { 431 requests[i].args = args 432 } else { 433 requests[i].err = &invalidParamsError{err.Error()} 434 } 435 } 436 continue 437 } 438 439 requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}} 440 } 441 442 return requests, batch, nil 443 }