gitlab.com/aquachain/aquachain@v1.17.16-rc3.0.20221018032414-e3ddf1e1c055/rpc/server.go (about) 1 // Copyright 2018 The aquachain Authors 2 // This file is part of the aquachain library. 3 // 4 // The aquachain 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 aquachain 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 aquachain 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 set "github.com/deckarep/golang-set" 29 "gitlab.com/aquachain/aquachain/common/log" 30 ) 31 32 const MetadataApi = "rpc" 33 34 // CodecOption specifies which type of messages this codec supports 35 type CodecOption int 36 37 const ( 38 // OptionMethodInvocation is an indication that the codec supports RPC method calls 39 OptionMethodInvocation CodecOption = 1 << iota 40 41 // OptionSubscriptions is an indication that the codec suports RPC notifications 42 OptionSubscriptions = 1 << iota // support pub sub 43 ) 44 45 // NewServer will create a new server instance with no registered handlers. 46 func NewServer() *Server { 47 server := &Server{ 48 services: make(serviceRegistry), 49 codecs: set.NewSet(), 50 run: 1, 51 } 52 53 // register a default service which will provide meta information about the RPC service such as the services and 54 // methods it offers. 55 rpcService := &RPCService{server} 56 server.RegisterName(MetadataApi, rpcService) 57 58 return server 59 } 60 61 // RPCService gives meta information about the server. 62 // e.g. gives information about the loaded modules. 63 type RPCService struct { 64 server *Server 65 } 66 67 // Modules returns the list of RPC services with their version number 68 func (s *RPCService) Modules() map[string]string { 69 modules := make(map[string]string) 70 for name := range s.server.services { 71 modules[name] = "1.0" 72 } 73 return modules 74 } 75 76 // RegisterName will create a service for the given rcvr type under the given name. When no methods on the given rcvr 77 // match the criteria to be either a RPC method or a subscription an error is returned. Otherwise a new service is 78 // created and added to the service collection this server instance serves. 79 func (s *Server) RegisterName(name string, rcvr interface{}) error { 80 if s.services == nil { 81 s.services = make(serviceRegistry) 82 } 83 84 svc := new(service) 85 svc.typ = reflect.TypeOf(rcvr) 86 rcvrVal := reflect.ValueOf(rcvr) 87 88 if name == "" { 89 return fmt.Errorf("no service name for type %s", svc.typ.String()) 90 } 91 if !isExported(reflect.Indirect(rcvrVal).Type().Name()) { 92 return fmt.Errorf("%s is not exported", reflect.Indirect(rcvrVal).Type().Name()) 93 } 94 95 methods, subscriptions := suitableCallbacks(rcvrVal, svc.typ) 96 97 if len(methods) == 0 && len(subscriptions) == 0 { 98 return fmt.Errorf("Service %T doesn't have any suitable methods/subscriptions to expose", rcvr) 99 } 100 101 // already a previous service register under given name, merge methods/subscriptions 102 if regsvc, present := s.services[name]; present { 103 for _, m := range methods { 104 regsvc.callbacks[formatName(m.method.Name)] = m 105 } 106 for _, s := range subscriptions { 107 regsvc.subscriptions[formatName(s.method.Name)] = s 108 } 109 return nil 110 } 111 112 svc.name = name 113 svc.callbacks, svc.subscriptions = methods, subscriptions 114 115 s.services[svc.name] = svc 116 return nil 117 } 118 119 // serveRequest will reads requests from the codec, calls the RPC callback and 120 // writes the response to the given codec. 121 // 122 // If singleShot is true it will process a single request, otherwise it will handle 123 // requests until the codec returns an error when reading a request (in most cases 124 // an EOF). It executes requests in parallel when singleShot is false. 125 func (s *Server) serveRequest(codec ServerCodec, singleShot bool, options CodecOption) error { 126 var pend sync.WaitGroup 127 128 defer func() { 129 if err := recover(); err != nil { 130 const size = 64 << 10 131 buf := make([]byte, size) 132 buf = buf[:runtime.Stack(buf, false)] 133 log.Error(string(buf)) 134 } 135 if s.codecs != nil { 136 s.codecsMu.Lock() 137 s.codecs.Remove(codec) 138 s.codecsMu.Unlock() 139 } 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.Warn("parsing rpc request", "error", 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 { // aqua_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.service, 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 }