github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/rpc/server.go (about) 1 // Copyright 2015 The Spectrum Authors 2 // This file is part of the Spectrum library. 3 // 4 // The Spectrum 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 Spectrum 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 Spectrum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package rpc 18 19 import ( 20 "context" 21 "fmt" 22 "github.com/SmartMeshFoundation/Spectrum/log" 23 mapset "github.com/deckarep/golang-set" 24 "reflect" 25 "runtime" 26 "strings" 27 "sync" 28 "sync/atomic" 29 ) 30 31 const MetadataApi = "rpc" 32 33 // CodecOption specifies which type of messages this codec supports 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 suports RPC notifications 41 OptionSubscriptions = 1 << iota // support pub sub 42 ) 43 44 // NewServer will create a new server instance with no registered handlers. 45 func NewServer() *Server { 46 server := &Server{ 47 services: make(serviceRegistry), 48 codecs: mapset.NewSet(), 49 run: 1, 50 } 51 52 // register a default service which will provide meta information about the RPC service such as the services and 53 // methods it offers. 54 rpcService := &RPCService{server} 55 server.RegisterName(MetadataApi, rpcService) 56 57 return server 58 } 59 60 // RPCService gives meta information about the server. 61 // e.g. gives information about the loaded modules. 62 type RPCService struct { 63 server *Server 64 } 65 66 // Modules returns the list of RPC services with their version number 67 func (s *RPCService) Modules() map[string]string { 68 modules := make(map[string]string) 69 for name := range s.server.services { 70 modules[name] = "1.0" 71 } 72 return modules 73 } 74 75 // RegisterName will create a service for the given rcvr type under the given name. When no methods on the given rcvr 76 // match the criteria to be either a RPC method or a subscription an error is returned. Otherwise a new service is 77 // created and added to the service collection this server instance serves. 78 func (s *Server) RegisterName(name string, rcvr interface{}) error { 79 if s.services == nil { 80 s.services = make(serviceRegistry) 81 } 82 83 svc := new(service) 84 svc.typ = reflect.TypeOf(rcvr) 85 rcvrVal := reflect.ValueOf(rcvr) 86 87 if name == "" { 88 return fmt.Errorf("no service name for type %s", svc.typ.String()) 89 } 90 if !isExported(reflect.Indirect(rcvrVal).Type().Name()) { 91 return fmt.Errorf("%s is not exported", reflect.Indirect(rcvrVal).Type().Name()) 92 } 93 94 methods, subscriptions := suitableCallbacks(rcvrVal, svc.typ) 95 96 // already a previous service register under given sname, merge methods/subscriptions 97 if regsvc, present := s.services[name]; present { 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 for _, m := range methods { 102 regsvc.callbacks[formatName(m.method.Name)] = m 103 } 104 for _, s := range subscriptions { 105 regsvc.subscriptions[formatName(s.method.Name)] = s 106 } 107 return nil 108 } 109 110 svc.name = name 111 svc.callbacks, svc.subscriptions = methods, subscriptions 112 113 if len(svc.callbacks) == 0 && len(svc.subscriptions) == 0 { 114 return fmt.Errorf("Service %T doesn't have any suitable methods/subscriptions to expose", rcvr) 115 } 116 117 s.services[svc.name] = svc 118 return nil 119 } 120 121 // serveRequest will reads requests from the codec, calls the RPC callback and 122 // writes the response to the given codec. 123 // 124 // If singleShot is true it will process a single request, otherwise it will handle 125 // requests until the codec returns an error when reading a request (in most cases 126 // an EOF). It executes requests in parallel when singleShot is false. 127 func (s *Server) serveRequest(codec ServerCodec, singleShot bool, options CodecOption) error { 128 var pend sync.WaitGroup 129 130 defer func() { 131 if err := recover(); err != nil { 132 const size = 64 << 10 133 buf := make([]byte, size) 134 buf = buf[:runtime.Stack(buf, false)] 135 log.Error(string(buf)) 136 } 137 s.codecsMu.Lock() 138 s.codecs.Remove(codec) 139 s.codecsMu.Unlock() 140 }() 141 142 ctx, cancel := context.WithCancel(context.Background()) 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 thight 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(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(codec ServerCodec, options CodecOption) { 224 s.serveRequest(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 315 if req.callb.errPos >= 0 { // test if method returned an error 316 if !reply[req.callb.errPos].IsNil() { 317 e := reply[req.callb.errPos].Interface().(error) 318 res := codec.CreateErrorResponse(&req.id, &callbackError{e.Error()}) 319 return res, nil 320 } 321 } 322 return codec.CreateResponse(req.id, reply[0].Interface()), nil 323 } 324 325 // exec executes the given request and writes the result back using the codec. 326 func (s *Server) exec(ctx context.Context, codec ServerCodec, req *serverRequest) { 327 var response interface{} 328 var callback func() 329 if req.err != nil { 330 response = codec.CreateErrorResponse(&req.id, req.err) 331 } else { 332 response, callback = s.handle(ctx, codec, req) 333 } 334 335 if err := codec.Write(response); err != nil { 336 log.Error(fmt.Sprintf("%v\n", err)) 337 codec.Close() 338 } 339 340 // when request was a subscribe request this allows these subscriptions to be actived 341 if callback != nil { 342 callback() 343 } 344 } 345 346 // execBatch executes the given requests and writes the result back using the codec. 347 // It will only write the response back when the last request is processed. 348 func (s *Server) execBatch(ctx context.Context, codec ServerCodec, requests []*serverRequest) { 349 responses := make([]interface{}, len(requests)) 350 var callbacks []func() 351 for i, req := range requests { 352 if req.err != nil { 353 responses[i] = codec.CreateErrorResponse(&req.id, req.err) 354 } else { 355 var callback func() 356 if responses[i], callback = s.handle(ctx, codec, req); callback != nil { 357 callbacks = append(callbacks, callback) 358 } 359 } 360 } 361 362 if err := codec.Write(responses); err != nil { 363 log.Error(fmt.Sprintf("%v\n", err)) 364 codec.Close() 365 } 366 367 // when request holds one of more subscribe requests this allows these subscriptions to be activated 368 for _, c := range callbacks { 369 c() 370 } 371 } 372 373 // readRequest requests the next (batch) request from the codec. It will return the collection 374 // of requests, an indication if the request was a batch, the invalid request identifier and an 375 // error when the request could not be read/parsed. 376 func (s *Server) readRequest(codec ServerCodec) ([]*serverRequest, bool, Error) { 377 reqs, batch, err := codec.ReadRequestHeaders() 378 if err != nil { 379 return nil, batch, err 380 } 381 382 requests := make([]*serverRequest, len(reqs)) 383 384 // verify requests 385 for i, r := range reqs { 386 var ok bool 387 var svc *service 388 389 if r.err != nil { 390 requests[i] = &serverRequest{id: r.id, err: r.err} 391 continue 392 } 393 394 if r.isPubSub && strings.HasSuffix(r.method, unsubscribeMethodSuffix) { 395 requests[i] = &serverRequest{id: r.id, isUnsubscribe: true} 396 argTypes := []reflect.Type{reflect.TypeOf("")} // expect subscription id as first arg 397 if args, err := codec.ParseRequestArguments(argTypes, r.params); err == nil { 398 requests[i].args = args 399 } else { 400 requests[i].err = &invalidParamsError{err.Error()} 401 } 402 continue 403 } 404 405 if svc, ok = s.services[r.service]; !ok { // rpc method isn't available 406 requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}} 407 continue 408 } 409 410 if r.isPubSub { // eth_subscribe, r.method contains the subscription method name 411 if callb, ok := svc.subscriptions[r.method]; ok { 412 requests[i] = &serverRequest{id: r.id, svcname: svc.name, callb: callb} 413 if r.params != nil && len(callb.argTypes) > 0 { 414 argTypes := []reflect.Type{reflect.TypeOf("")} 415 argTypes = append(argTypes, callb.argTypes...) 416 if args, err := codec.ParseRequestArguments(argTypes, r.params); err == nil { 417 requests[i].args = args[1:] // first one is service.method name which isn't an actual argument 418 } else { 419 requests[i].err = &invalidParamsError{err.Error()} 420 } 421 } 422 } else { 423 requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.method, r.method}} 424 } 425 continue 426 } 427 428 if callb, ok := svc.callbacks[r.method]; ok { // lookup RPC method 429 requests[i] = &serverRequest{id: r.id, svcname: svc.name, callb: callb} 430 if r.params != nil && len(callb.argTypes) > 0 { 431 if args, err := codec.ParseRequestArguments(callb.argTypes, r.params); err == nil { 432 requests[i].args = args 433 } else { 434 requests[i].err = &invalidParamsError{err.Error()} 435 } 436 } 437 continue 438 } 439 440 requests[i] = &serverRequest{id: r.id, err: &methodNotFoundError{r.service, r.method}} 441 } 442 443 return requests, batch, nil 444 }