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