github.com/theQRL/go-zond@v0.1.1/rpc/client.go (about) 1 // Copyright 2016 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 "encoding/json" 22 "errors" 23 "fmt" 24 "net/url" 25 "os" 26 "reflect" 27 "strconv" 28 "sync/atomic" 29 "time" 30 31 "github.com/theQRL/go-zond/log" 32 ) 33 34 var ( 35 ErrBadResult = errors.New("bad result in JSON-RPC response") 36 ErrClientQuit = errors.New("client is closed") 37 ErrNoResult = errors.New("JSON-RPC response has no result") 38 ErrMissingBatchResponse = errors.New("response batch did not contain a response to this call") 39 ErrSubscriptionQueueOverflow = errors.New("subscription queue overflow") 40 errClientReconnected = errors.New("client reconnected") 41 errDead = errors.New("connection lost") 42 ) 43 44 // Timeouts 45 const ( 46 defaultDialTimeout = 10 * time.Second // used if context has no deadline 47 subscribeTimeout = 10 * time.Second // overall timeout eth_subscribe, rpc_modules calls 48 ) 49 50 const ( 51 // Subscriptions are removed when the subscriber cannot keep up. 52 // 53 // This can be worked around by supplying a channel with sufficiently sized buffer, 54 // but this can be inconvenient and hard to explain in the docs. Another issue with 55 // buffered channels is that the buffer is static even though it might not be needed 56 // most of the time. 57 // 58 // The approach taken here is to maintain a per-subscription linked list buffer 59 // shrinks on demand. If the buffer reaches the size below, the subscription is 60 // dropped. 61 maxClientSubscriptionBuffer = 20000 62 ) 63 64 // BatchElem is an element in a batch request. 65 type BatchElem struct { 66 Method string 67 Args []interface{} 68 // The result is unmarshaled into this field. Result must be set to a 69 // non-nil pointer value of the desired type, otherwise the response will be 70 // discarded. 71 Result interface{} 72 // Error is set if the server returns an error for this request, or if 73 // unmarshaling into Result fails. It is not set for I/O errors. 74 Error error 75 } 76 77 // Client represents a connection to an RPC server. 78 type Client struct { 79 idgen func() ID // for subscriptions 80 isHTTP bool // connection type: http, ws or ipc 81 services *serviceRegistry 82 83 idCounter atomic.Uint32 84 85 // This function, if non-nil, is called when the connection is lost. 86 reconnectFunc reconnectFunc 87 88 // config fields 89 batchItemLimit int 90 batchResponseMaxSize int 91 92 // writeConn is used for writing to the connection on the caller's goroutine. It should 93 // only be accessed outside of dispatch, with the write lock held. The write lock is 94 // taken by sending on reqInit and released by sending on reqSent. 95 writeConn jsonWriter 96 97 // for dispatch 98 close chan struct{} 99 closing chan struct{} // closed when client is quitting 100 didClose chan struct{} // closed when client quits 101 reconnected chan ServerCodec // where write/reconnect sends the new connection 102 readOp chan readOp // read messages 103 readErr chan error // errors from read 104 reqInit chan *requestOp // register response IDs, takes write lock 105 reqSent chan error // signals write completion, releases write lock 106 reqTimeout chan *requestOp // removes response IDs when call timeout expires 107 } 108 109 type reconnectFunc func(context.Context) (ServerCodec, error) 110 111 type clientContextKey struct{} 112 113 type clientConn struct { 114 codec ServerCodec 115 handler *handler 116 } 117 118 func (c *Client) newClientConn(conn ServerCodec) *clientConn { 119 ctx := context.Background() 120 ctx = context.WithValue(ctx, clientContextKey{}, c) 121 ctx = context.WithValue(ctx, peerInfoContextKey{}, conn.peerInfo()) 122 handler := newHandler(ctx, conn, c.idgen, c.services, c.batchItemLimit, c.batchResponseMaxSize) 123 return &clientConn{conn, handler} 124 } 125 126 func (cc *clientConn) close(err error, inflightReq *requestOp) { 127 cc.handler.close(err, inflightReq) 128 cc.codec.close() 129 } 130 131 type readOp struct { 132 msgs []*jsonrpcMessage 133 batch bool 134 } 135 136 // requestOp represents a pending request. This is used for both batch and non-batch 137 // requests. 138 type requestOp struct { 139 ids []json.RawMessage 140 err error 141 resp chan []*jsonrpcMessage // the response goes here 142 sub *ClientSubscription // set for Subscribe requests. 143 hadResponse bool // true when the request was responded to 144 } 145 146 func (op *requestOp) wait(ctx context.Context, c *Client) ([]*jsonrpcMessage, error) { 147 select { 148 case <-ctx.Done(): 149 // Send the timeout to dispatch so it can remove the request IDs. 150 if !c.isHTTP { 151 select { 152 case c.reqTimeout <- op: 153 case <-c.closing: 154 } 155 } 156 return nil, ctx.Err() 157 case resp := <-op.resp: 158 return resp, op.err 159 } 160 } 161 162 // Dial creates a new client for the given URL. 163 // 164 // The currently supported URL schemes are "http", "https", "ws" and "wss". If rawurl is a 165 // file name with no URL scheme, a local socket connection is established using UNIX 166 // domain sockets on supported platforms and named pipes on Windows. 167 // 168 // If you want to further configure the transport, use DialOptions instead of this 169 // function. 170 // 171 // For websocket connections, the origin is set to the local host name. 172 // 173 // The client reconnects automatically when the connection is lost. 174 func Dial(rawurl string) (*Client, error) { 175 return DialOptions(context.Background(), rawurl) 176 } 177 178 // DialContext creates a new RPC client, just like Dial. 179 // 180 // The context is used to cancel or time out the initial connection establishment. It does 181 // not affect subsequent interactions with the client. 182 func DialContext(ctx context.Context, rawurl string) (*Client, error) { 183 return DialOptions(ctx, rawurl) 184 } 185 186 // DialOptions creates a new RPC client for the given URL. You can supply any of the 187 // pre-defined client options to configure the underlying transport. 188 // 189 // The context is used to cancel or time out the initial connection establishment. It does 190 // not affect subsequent interactions with the client. 191 // 192 // The client reconnects automatically when the connection is lost. 193 func DialOptions(ctx context.Context, rawurl string, options ...ClientOption) (*Client, error) { 194 u, err := url.Parse(rawurl) 195 if err != nil { 196 return nil, err 197 } 198 199 cfg := new(clientConfig) 200 for _, opt := range options { 201 opt.applyOption(cfg) 202 } 203 204 var reconnect reconnectFunc 205 switch u.Scheme { 206 case "http", "https": 207 reconnect = newClientTransportHTTP(rawurl, cfg) 208 case "ws", "wss": 209 rc, err := newClientTransportWS(rawurl, cfg) 210 if err != nil { 211 return nil, err 212 } 213 reconnect = rc 214 case "stdio": 215 reconnect = newClientTransportIO(os.Stdin, os.Stdout) 216 case "": 217 reconnect = newClientTransportIPC(rawurl) 218 default: 219 return nil, fmt.Errorf("no known transport for URL scheme %q", u.Scheme) 220 } 221 222 return newClient(ctx, cfg, reconnect) 223 } 224 225 // ClientFromContext retrieves the client from the context, if any. This can be used to perform 226 // 'reverse calls' in a handler method. 227 func ClientFromContext(ctx context.Context) (*Client, bool) { 228 client, ok := ctx.Value(clientContextKey{}).(*Client) 229 return client, ok 230 } 231 232 func newClient(initctx context.Context, cfg *clientConfig, connect reconnectFunc) (*Client, error) { 233 conn, err := connect(initctx) 234 if err != nil { 235 return nil, err 236 } 237 c := initClient(conn, new(serviceRegistry), cfg) 238 c.reconnectFunc = connect 239 return c, nil 240 } 241 242 func initClient(conn ServerCodec, services *serviceRegistry, cfg *clientConfig) *Client { 243 _, isHTTP := conn.(*httpConn) 244 c := &Client{ 245 isHTTP: isHTTP, 246 services: services, 247 idgen: cfg.idgen, 248 batchItemLimit: cfg.batchItemLimit, 249 batchResponseMaxSize: cfg.batchResponseLimit, 250 writeConn: conn, 251 close: make(chan struct{}), 252 closing: make(chan struct{}), 253 didClose: make(chan struct{}), 254 reconnected: make(chan ServerCodec), 255 readOp: make(chan readOp), 256 readErr: make(chan error), 257 reqInit: make(chan *requestOp), 258 reqSent: make(chan error, 1), 259 reqTimeout: make(chan *requestOp), 260 } 261 262 // Set defaults. 263 if c.idgen == nil { 264 c.idgen = randomIDGenerator() 265 } 266 267 // Launch the main loop. 268 if !isHTTP { 269 go c.dispatch(conn) 270 } 271 return c 272 } 273 274 // RegisterName creates a service for the given receiver type under the given name. When no 275 // methods on the given receiver match the criteria to be either a RPC method or a 276 // subscription an error is returned. Otherwise a new service is created and added to the 277 // service collection this client provides to the server. 278 func (c *Client) RegisterName(name string, receiver interface{}) error { 279 return c.services.registerName(name, receiver) 280 } 281 282 func (c *Client) nextID() json.RawMessage { 283 id := c.idCounter.Add(1) 284 return strconv.AppendUint(nil, uint64(id), 10) 285 } 286 287 // SupportedModules calls the rpc_modules method, retrieving the list of 288 // APIs that are available on the server. 289 func (c *Client) SupportedModules() (map[string]string, error) { 290 var result map[string]string 291 ctx, cancel := context.WithTimeout(context.Background(), subscribeTimeout) 292 defer cancel() 293 err := c.CallContext(ctx, &result, "rpc_modules") 294 return result, err 295 } 296 297 // Close closes the client, aborting any in-flight requests. 298 func (c *Client) Close() { 299 if c.isHTTP { 300 return 301 } 302 select { 303 case c.close <- struct{}{}: 304 <-c.didClose 305 case <-c.didClose: 306 } 307 } 308 309 // SetHeader adds a custom HTTP header to the client's requests. 310 // This method only works for clients using HTTP, it doesn't have 311 // any effect for clients using another transport. 312 func (c *Client) SetHeader(key, value string) { 313 if !c.isHTTP { 314 return 315 } 316 conn := c.writeConn.(*httpConn) 317 conn.mu.Lock() 318 conn.headers.Set(key, value) 319 conn.mu.Unlock() 320 } 321 322 // Call performs a JSON-RPC call with the given arguments and unmarshals into 323 // result if no error occurred. 324 // 325 // The result must be a pointer so that package json can unmarshal into it. You 326 // can also pass nil, in which case the result is ignored. 327 func (c *Client) Call(result interface{}, method string, args ...interface{}) error { 328 ctx := context.Background() 329 return c.CallContext(ctx, result, method, args...) 330 } 331 332 // CallContext performs a JSON-RPC call with the given arguments. If the context is 333 // canceled before the call has successfully returned, CallContext returns immediately. 334 // 335 // The result must be a pointer so that package json can unmarshal into it. You 336 // can also pass nil, in which case the result is ignored. 337 func (c *Client) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error { 338 if result != nil && reflect.TypeOf(result).Kind() != reflect.Ptr { 339 return fmt.Errorf("call result parameter must be pointer or nil interface: %v", result) 340 } 341 msg, err := c.newMessage(method, args...) 342 if err != nil { 343 return err 344 } 345 op := &requestOp{ 346 ids: []json.RawMessage{msg.ID}, 347 resp: make(chan []*jsonrpcMessage, 1), 348 } 349 350 if c.isHTTP { 351 err = c.sendHTTP(ctx, op, msg) 352 } else { 353 err = c.send(ctx, op, msg) 354 } 355 if err != nil { 356 return err 357 } 358 359 // dispatch has accepted the request and will close the channel when it quits. 360 batchresp, err := op.wait(ctx, c) 361 if err != nil { 362 return err 363 } 364 resp := batchresp[0] 365 switch { 366 case resp.Error != nil: 367 return resp.Error 368 case len(resp.Result) == 0: 369 return ErrNoResult 370 default: 371 if result == nil { 372 return nil 373 } 374 return json.Unmarshal(resp.Result, result) 375 } 376 } 377 378 // BatchCall sends all given requests as a single batch and waits for the server 379 // to return a response for all of them. 380 // 381 // In contrast to Call, BatchCall only returns I/O errors. Any error specific to 382 // a request is reported through the Error field of the corresponding BatchElem. 383 // 384 // Note that batch calls may not be executed atomically on the server side. 385 func (c *Client) BatchCall(b []BatchElem) error { 386 ctx := context.Background() 387 return c.BatchCallContext(ctx, b) 388 } 389 390 // BatchCallContext sends all given requests as a single batch and waits for the server 391 // to return a response for all of them. The wait duration is bounded by the 392 // context's deadline. 393 // 394 // In contrast to CallContext, BatchCallContext only returns errors that have occurred 395 // while sending the request. Any error specific to a request is reported through the 396 // Error field of the corresponding BatchElem. 397 // 398 // Note that batch calls may not be executed atomically on the server side. 399 func (c *Client) BatchCallContext(ctx context.Context, b []BatchElem) error { 400 var ( 401 msgs = make([]*jsonrpcMessage, len(b)) 402 byID = make(map[string]int, len(b)) 403 ) 404 op := &requestOp{ 405 ids: make([]json.RawMessage, len(b)), 406 resp: make(chan []*jsonrpcMessage, 1), 407 } 408 for i, elem := range b { 409 msg, err := c.newMessage(elem.Method, elem.Args...) 410 if err != nil { 411 return err 412 } 413 msgs[i] = msg 414 op.ids[i] = msg.ID 415 byID[string(msg.ID)] = i 416 } 417 418 var err error 419 if c.isHTTP { 420 err = c.sendBatchHTTP(ctx, op, msgs) 421 } else { 422 err = c.send(ctx, op, msgs) 423 } 424 if err != nil { 425 return err 426 } 427 428 batchresp, err := op.wait(ctx, c) 429 if err != nil { 430 return err 431 } 432 433 // Wait for all responses to come back. 434 for n := 0; n < len(batchresp) && err == nil; n++ { 435 resp := batchresp[n] 436 if resp == nil { 437 // Ignore null responses. These can happen for batches sent via HTTP. 438 continue 439 } 440 441 // Find the element corresponding to this response. 442 index, ok := byID[string(resp.ID)] 443 if !ok { 444 continue 445 } 446 delete(byID, string(resp.ID)) 447 448 // Assign result and error. 449 elem := &b[index] 450 switch { 451 case resp.Error != nil: 452 elem.Error = resp.Error 453 case resp.Result == nil: 454 elem.Error = ErrNoResult 455 default: 456 elem.Error = json.Unmarshal(resp.Result, elem.Result) 457 } 458 } 459 460 // Check that all expected responses have been received. 461 for _, index := range byID { 462 elem := &b[index] 463 elem.Error = ErrMissingBatchResponse 464 } 465 466 return err 467 } 468 469 // Notify sends a notification, i.e. a method call that doesn't expect a response. 470 func (c *Client) Notify(ctx context.Context, method string, args ...interface{}) error { 471 op := new(requestOp) 472 msg, err := c.newMessage(method, args...) 473 if err != nil { 474 return err 475 } 476 msg.ID = nil 477 478 if c.isHTTP { 479 return c.sendHTTP(ctx, op, msg) 480 } 481 return c.send(ctx, op, msg) 482 } 483 484 // EthSubscribe registers a subscription under the "eth" namespace. 485 func (c *Client) EthSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error) { 486 return c.Subscribe(ctx, "eth", channel, args...) 487 } 488 489 // ShhSubscribe registers a subscription under the "shh" namespace. 490 // Deprecated: use Subscribe(ctx, "shh", ...). 491 func (c *Client) ShhSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error) { 492 return c.Subscribe(ctx, "shh", channel, args...) 493 } 494 495 // Subscribe calls the "<namespace>_subscribe" method with the given arguments, 496 // registering a subscription. Server notifications for the subscription are 497 // sent to the given channel. The element type of the channel must match the 498 // expected type of content returned by the subscription. 499 // 500 // The context argument cancels the RPC request that sets up the subscription but has no 501 // effect on the subscription after Subscribe has returned. 502 // 503 // Slow subscribers will be dropped eventually. Client buffers up to 20000 notifications 504 // before considering the subscriber dead. The subscription Err channel will receive 505 // ErrSubscriptionQueueOverflow. Use a sufficiently large buffer on the channel or ensure 506 // that the channel usually has at least one reader to prevent this issue. 507 func (c *Client) Subscribe(ctx context.Context, namespace string, channel interface{}, args ...interface{}) (*ClientSubscription, error) { 508 // Check type of channel first. 509 chanVal := reflect.ValueOf(channel) 510 if chanVal.Kind() != reflect.Chan || chanVal.Type().ChanDir()&reflect.SendDir == 0 { 511 panic(fmt.Sprintf("channel argument of Subscribe has type %T, need writable channel", channel)) 512 } 513 if chanVal.IsNil() { 514 panic("channel given to Subscribe must not be nil") 515 } 516 if c.isHTTP { 517 return nil, ErrNotificationsUnsupported 518 } 519 520 msg, err := c.newMessage(namespace+subscribeMethodSuffix, args...) 521 if err != nil { 522 return nil, err 523 } 524 op := &requestOp{ 525 ids: []json.RawMessage{msg.ID}, 526 resp: make(chan []*jsonrpcMessage, 1), 527 sub: newClientSubscription(c, namespace, chanVal), 528 } 529 530 // Send the subscription request. 531 // The arrival and validity of the response is signaled on sub.quit. 532 if err := c.send(ctx, op, msg); err != nil { 533 return nil, err 534 } 535 if _, err := op.wait(ctx, c); err != nil { 536 return nil, err 537 } 538 return op.sub, nil 539 } 540 541 // SupportsSubscriptions reports whether subscriptions are supported by the client 542 // transport. When this returns false, Subscribe and related methods will return 543 // ErrNotificationsUnsupported. 544 func (c *Client) SupportsSubscriptions() bool { 545 return !c.isHTTP 546 } 547 548 func (c *Client) newMessage(method string, paramsIn ...interface{}) (*jsonrpcMessage, error) { 549 msg := &jsonrpcMessage{Version: vsn, ID: c.nextID(), Method: method} 550 if paramsIn != nil { // prevent sending "params":null 551 var err error 552 if msg.Params, err = json.Marshal(paramsIn); err != nil { 553 return nil, err 554 } 555 } 556 return msg, nil 557 } 558 559 // send registers op with the dispatch loop, then sends msg on the connection. 560 // if sending fails, op is deregistered. 561 func (c *Client) send(ctx context.Context, op *requestOp, msg interface{}) error { 562 select { 563 case c.reqInit <- op: 564 err := c.write(ctx, msg, false) 565 c.reqSent <- err 566 return err 567 case <-ctx.Done(): 568 // This can happen if the client is overloaded or unable to keep up with 569 // subscription notifications. 570 return ctx.Err() 571 case <-c.closing: 572 return ErrClientQuit 573 } 574 } 575 576 func (c *Client) write(ctx context.Context, msg interface{}, retry bool) error { 577 if c.writeConn == nil { 578 // The previous write failed. Try to establish a new connection. 579 if err := c.reconnect(ctx); err != nil { 580 return err 581 } 582 } 583 err := c.writeConn.writeJSON(ctx, msg, false) 584 if err != nil { 585 c.writeConn = nil 586 if !retry { 587 return c.write(ctx, msg, true) 588 } 589 } 590 return err 591 } 592 593 func (c *Client) reconnect(ctx context.Context) error { 594 if c.reconnectFunc == nil { 595 return errDead 596 } 597 598 if _, ok := ctx.Deadline(); !ok { 599 var cancel func() 600 ctx, cancel = context.WithTimeout(ctx, defaultDialTimeout) 601 defer cancel() 602 } 603 newconn, err := c.reconnectFunc(ctx) 604 if err != nil { 605 log.Trace("RPC client reconnect failed", "err", err) 606 return err 607 } 608 select { 609 case c.reconnected <- newconn: 610 c.writeConn = newconn 611 return nil 612 case <-c.didClose: 613 newconn.close() 614 return ErrClientQuit 615 } 616 } 617 618 // dispatch is the main loop of the client. 619 // It sends read messages to waiting calls to Call and BatchCall 620 // and subscription notifications to registered subscriptions. 621 func (c *Client) dispatch(codec ServerCodec) { 622 var ( 623 lastOp *requestOp // tracks last send operation 624 reqInitLock = c.reqInit // nil while the send lock is held 625 conn = c.newClientConn(codec) 626 reading = true 627 ) 628 defer func() { 629 close(c.closing) 630 if reading { 631 conn.close(ErrClientQuit, nil) 632 c.drainRead() 633 } 634 close(c.didClose) 635 }() 636 637 // Spawn the initial read loop. 638 go c.read(codec) 639 640 for { 641 select { 642 case <-c.close: 643 return 644 645 // Read path: 646 case op := <-c.readOp: 647 if op.batch { 648 conn.handler.handleBatch(op.msgs) 649 } else { 650 conn.handler.handleMsg(op.msgs[0]) 651 } 652 653 case err := <-c.readErr: 654 conn.handler.log.Debug("RPC connection read error", "err", err) 655 conn.close(err, lastOp) 656 reading = false 657 658 // Reconnect: 659 case newcodec := <-c.reconnected: 660 log.Debug("RPC client reconnected", "reading", reading, "conn", newcodec.remoteAddr()) 661 if reading { 662 // Wait for the previous read loop to exit. This is a rare case which 663 // happens if this loop isn't notified in time after the connection breaks. 664 // In those cases the caller will notice first and reconnect. Closing the 665 // handler terminates all waiting requests (closing op.resp) except for 666 // lastOp, which will be transferred to the new handler. 667 conn.close(errClientReconnected, lastOp) 668 c.drainRead() 669 } 670 go c.read(newcodec) 671 reading = true 672 conn = c.newClientConn(newcodec) 673 // Re-register the in-flight request on the new handler 674 // because that's where it will be sent. 675 conn.handler.addRequestOp(lastOp) 676 677 // Send path: 678 case op := <-reqInitLock: 679 // Stop listening for further requests until the current one has been sent. 680 reqInitLock = nil 681 lastOp = op 682 conn.handler.addRequestOp(op) 683 684 case err := <-c.reqSent: 685 if err != nil { 686 // Remove response handlers for the last send. When the read loop 687 // goes down, it will signal all other current operations. 688 conn.handler.removeRequestOp(lastOp) 689 } 690 // Let the next request in. 691 reqInitLock = c.reqInit 692 lastOp = nil 693 694 case op := <-c.reqTimeout: 695 conn.handler.removeRequestOp(op) 696 } 697 } 698 } 699 700 // drainRead drops read messages until an error occurs. 701 func (c *Client) drainRead() { 702 for { 703 select { 704 case <-c.readOp: 705 case <-c.readErr: 706 return 707 } 708 } 709 } 710 711 // read decodes RPC messages from a codec, feeding them into dispatch. 712 func (c *Client) read(codec ServerCodec) { 713 for { 714 msgs, batch, err := codec.readBatch() 715 if _, ok := err.(*json.SyntaxError); ok { 716 msg := errorMessage(&parseError{err.Error()}) 717 codec.writeJSON(context.Background(), msg, true) 718 } 719 if err != nil { 720 c.readErr <- err 721 return 722 } 723 c.readOp <- readOp{msgs, batch} 724 } 725 }