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