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