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