github.com/v2fly/tools@v0.100.0/internal/jsonrpc2_v2/conn.go (about)

     1  // Copyright 2018 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package jsonrpc2
     6  
     7  import (
     8  	"context"
     9  	"encoding/json"
    10  	"fmt"
    11  	"io"
    12  	"sync/atomic"
    13  
    14  	"github.com/v2fly/tools/internal/event"
    15  	"github.com/v2fly/tools/internal/event/label"
    16  	"github.com/v2fly/tools/internal/lsp/debug/tag"
    17  	errors "golang.org/x/xerrors"
    18  )
    19  
    20  // Binder builds a connection configuration.
    21  // This may be used in servers to generate a new configuration per connection.
    22  // ConnectionOptions itself implements Binder returning itself unmodified, to
    23  // allow for the simple cases where no per connection information is needed.
    24  type Binder interface {
    25  	// Bind is invoked when creating a new connection.
    26  	// The connection is not ready to use when Bind is called.
    27  	Bind(context.Context, *Connection) (ConnectionOptions, error)
    28  }
    29  
    30  // ConnectionOptions holds the options for new connections.
    31  type ConnectionOptions struct {
    32  	// Framer allows control over the message framing and encoding.
    33  	// If nil, HeaderFramer will be used.
    34  	Framer Framer
    35  	// Preempter allows registration of a pre-queue message handler.
    36  	// If nil, no messages will be preempted.
    37  	Preempter Preempter
    38  	// Handler is used as the queued message handler for inbound messages.
    39  	// If nil, all responses will be ErrNotHandled.
    40  	Handler Handler
    41  }
    42  
    43  // Connection manages the jsonrpc2 protocol, connecting responses back to their
    44  // calls.
    45  // Connection is bidirectional; it does not have a designated server or client
    46  // end.
    47  type Connection struct {
    48  	seq         int64 // must only be accessed using atomic operations
    49  	closer      io.Closer
    50  	writerBox   chan Writer
    51  	outgoingBox chan map[ID]chan<- *Response
    52  	incomingBox chan map[ID]*incoming
    53  	async       async
    54  }
    55  
    56  type AsyncCall struct {
    57  	id        ID
    58  	response  chan *Response // the channel a response will be delivered on
    59  	resultBox chan asyncResult
    60  	endSpan   func() // close the tracing span when all processing for the message is complete
    61  }
    62  
    63  type asyncResult struct {
    64  	result []byte
    65  	err    error
    66  }
    67  
    68  // incoming is used to track an incoming request as it is being handled
    69  type incoming struct {
    70  	request   *Request        // the request being processed
    71  	baseCtx   context.Context // a base context for the message processing
    72  	done      func()          // a function called when all processing for the message is complete
    73  	handleCtx context.Context // the context for handling the message, child of baseCtx
    74  	cancel    func()          // a function that cancels the handling context
    75  }
    76  
    77  // Bind returns the options unmodified.
    78  func (o ConnectionOptions) Bind(context.Context, *Connection) (ConnectionOptions, error) {
    79  	return o, nil
    80  }
    81  
    82  // newConnection creates a new connection and runs it.
    83  // This is used by the Dial and Serve functions to build the actual connection.
    84  func newConnection(ctx context.Context, rwc io.ReadWriteCloser, binder Binder) (*Connection, error) {
    85  	c := &Connection{
    86  		closer:      rwc,
    87  		writerBox:   make(chan Writer, 1),
    88  		outgoingBox: make(chan map[ID]chan<- *Response, 1),
    89  		incomingBox: make(chan map[ID]*incoming, 1),
    90  	}
    91  
    92  	options, err := binder.Bind(ctx, c)
    93  	if err != nil {
    94  		return nil, err
    95  	}
    96  	if options.Framer == nil {
    97  		options.Framer = HeaderFramer()
    98  	}
    99  	if options.Preempter == nil {
   100  		options.Preempter = defaultHandler{}
   101  	}
   102  	if options.Handler == nil {
   103  		options.Handler = defaultHandler{}
   104  	}
   105  	c.outgoingBox <- make(map[ID]chan<- *Response)
   106  	c.incomingBox <- make(map[ID]*incoming)
   107  	c.async.init()
   108  	// the goroutines started here will continue until the underlying stream is closed
   109  	reader := options.Framer.Reader(rwc)
   110  	readToQueue := make(chan *incoming)
   111  	queueToDeliver := make(chan *incoming)
   112  	go c.readIncoming(ctx, reader, readToQueue)
   113  	go c.manageQueue(ctx, options.Preempter, readToQueue, queueToDeliver)
   114  	go c.deliverMessages(ctx, options.Handler, queueToDeliver)
   115  	// releaseing the writer must be the last thing we do in case any requests
   116  	// are blocked waiting for the connection to be ready
   117  	c.writerBox <- options.Framer.Writer(rwc)
   118  	return c, nil
   119  }
   120  
   121  // Notify invokes the target method but does not wait for a response.
   122  // The params will be marshaled to JSON before sending over the wire, and will
   123  // be handed to the method invoked.
   124  func (c *Connection) Notify(ctx context.Context, method string, params interface{}) error {
   125  	notify, err := NewNotification(method, params)
   126  	if err != nil {
   127  		return errors.Errorf("marshaling notify parameters: %v", err)
   128  	}
   129  	ctx, done := event.Start(ctx, method,
   130  		tag.Method.Of(method),
   131  		tag.RPCDirection.Of(tag.Outbound),
   132  	)
   133  	event.Metric(ctx, tag.Started.Of(1))
   134  	err = c.write(ctx, notify)
   135  	switch {
   136  	case err != nil:
   137  		event.Label(ctx, tag.StatusCode.Of("ERROR"))
   138  	default:
   139  		event.Label(ctx, tag.StatusCode.Of("OK"))
   140  	}
   141  	done()
   142  	return err
   143  }
   144  
   145  // Call invokes the target method and returns an object that can be used to await the response.
   146  // The params will be marshaled to JSON before sending over the wire, and will
   147  // be handed to the method invoked.
   148  // You do not have to wait for the response, it can just be ignored if not needed.
   149  // If sending the call failed, the response will be ready and have the error in it.
   150  func (c *Connection) Call(ctx context.Context, method string, params interface{}) *AsyncCall {
   151  	result := &AsyncCall{
   152  		id:        Int64ID(atomic.AddInt64(&c.seq, 1)),
   153  		resultBox: make(chan asyncResult, 1),
   154  	}
   155  	// generate a new request identifier
   156  	call, err := NewCall(result.id, method, params)
   157  	if err != nil {
   158  		//set the result to failed
   159  		result.resultBox <- asyncResult{err: errors.Errorf("marshaling call parameters: %w", err)}
   160  		return result
   161  	}
   162  	ctx, endSpan := event.Start(ctx, method,
   163  		tag.Method.Of(method),
   164  		tag.RPCDirection.Of(tag.Outbound),
   165  		tag.RPCID.Of(fmt.Sprintf("%q", result.id)),
   166  	)
   167  	result.endSpan = endSpan
   168  	event.Metric(ctx, tag.Started.Of(1))
   169  	// We have to add ourselves to the pending map before we send, otherwise we
   170  	// are racing the response.
   171  	// rchan is buffered in case the response arrives without a listener.
   172  	result.response = make(chan *Response, 1)
   173  	pending := <-c.outgoingBox
   174  	pending[result.id] = result.response
   175  	c.outgoingBox <- pending
   176  	// now we are ready to send
   177  	if err := c.write(ctx, call); err != nil {
   178  		// sending failed, we will never get a response, so deliver a fake one
   179  		r, _ := NewResponse(result.id, nil, err)
   180  		c.incomingResponse(r)
   181  	}
   182  	return result
   183  }
   184  
   185  // ID used for this call.
   186  // This can be used to cancel the call if needed.
   187  func (a *AsyncCall) ID() ID { return a.id }
   188  
   189  // IsReady can be used to check if the result is already prepared.
   190  // This is guaranteed to return true on a result for which Await has already
   191  // returned, or a call that failed to send in the first place.
   192  func (a *AsyncCall) IsReady() bool {
   193  	select {
   194  	case r := <-a.resultBox:
   195  		a.resultBox <- r
   196  		return true
   197  	default:
   198  		return false
   199  	}
   200  }
   201  
   202  // Await the results of a Call.
   203  // The response will be unmarshaled from JSON into the result.
   204  func (a *AsyncCall) Await(ctx context.Context, result interface{}) error {
   205  	defer a.endSpan()
   206  	var r asyncResult
   207  	select {
   208  	case response := <-a.response:
   209  		// response just arrived, prepare the result
   210  		switch {
   211  		case response.Error != nil:
   212  			r.err = response.Error
   213  			event.Label(ctx, tag.StatusCode.Of("ERROR"))
   214  		default:
   215  			r.result = response.Result
   216  			event.Label(ctx, tag.StatusCode.Of("OK"))
   217  		}
   218  	case r = <-a.resultBox:
   219  		// result already available
   220  	case <-ctx.Done():
   221  		event.Label(ctx, tag.StatusCode.Of("CANCELLED"))
   222  		return ctx.Err()
   223  	}
   224  	// refill the box for the next caller
   225  	a.resultBox <- r
   226  	// and unpack the result
   227  	if r.err != nil {
   228  		return r.err
   229  	}
   230  	if result == nil || len(r.result) == 0 {
   231  		return nil
   232  	}
   233  	return json.Unmarshal(r.result, result)
   234  }
   235  
   236  // Respond deliverers a response to an incoming Call.
   237  // It is an error to not call this exactly once for any message for which a
   238  // handler has previously returned ErrAsyncResponse. It is also an error to
   239  // call this for any other message.
   240  func (c *Connection) Respond(id ID, result interface{}, rerr error) error {
   241  	pending := <-c.incomingBox
   242  	defer func() { c.incomingBox <- pending }()
   243  	entry, found := pending[id]
   244  	if !found {
   245  		return nil
   246  	}
   247  	delete(pending, id)
   248  	return c.respond(entry, result, rerr)
   249  }
   250  
   251  // Cancel is used to cancel an inbound message by ID, it does not cancel
   252  // outgoing messages.
   253  // This is only used inside a message handler that is layering a
   254  // cancellation protocol on top of JSON RPC 2.
   255  // It will not complain if the ID is not a currently active message, and it will
   256  // not cause any messages that have not arrived yet with that ID to be
   257  // cancelled.
   258  func (c *Connection) Cancel(id ID) {
   259  	pending := <-c.incomingBox
   260  	defer func() { c.incomingBox <- pending }()
   261  	if entry, found := pending[id]; found && entry.cancel != nil {
   262  		entry.cancel()
   263  		entry.cancel = nil
   264  	}
   265  }
   266  
   267  // Wait blocks until the connection is fully closed, but does not close it.
   268  func (c *Connection) Wait() error {
   269  	return c.async.wait()
   270  }
   271  
   272  // Close can be used to close the underlying stream, and then wait for the connection to
   273  // fully shut down.
   274  // This does not cancel in flight requests, but waits for them to gracefully complete.
   275  func (c *Connection) Close() error {
   276  	// close the underlying stream
   277  	if err := c.closer.Close(); err != nil && !isClosingError(err) {
   278  		return err
   279  	}
   280  	// and then wait for it to cause the connection to close
   281  	if err := c.Wait(); err != nil && !isClosingError(err) {
   282  		return err
   283  	}
   284  	return nil
   285  }
   286  
   287  // readIncoming collects inbound messages from the reader and delivers them, either responding
   288  // to outgoing calls or feeding requests to the queue.
   289  func (c *Connection) readIncoming(ctx context.Context, reader Reader, toQueue chan<- *incoming) {
   290  	defer close(toQueue)
   291  	for {
   292  		// get the next message
   293  		// no lock is needed, this is the only reader
   294  		msg, n, err := reader.Read(ctx)
   295  		if err != nil {
   296  			// The stream failed, we cannot continue
   297  			c.async.setError(err)
   298  			return
   299  		}
   300  		switch msg := msg.(type) {
   301  		case *Request:
   302  			entry := &incoming{
   303  				request: msg,
   304  			}
   305  			// add a span to the context for this request
   306  			labels := append(make([]label.Label, 0, 3), // make space for the id if present
   307  				tag.Method.Of(msg.Method),
   308  				tag.RPCDirection.Of(tag.Inbound),
   309  			)
   310  			if msg.IsCall() {
   311  				labels = append(labels, tag.RPCID.Of(fmt.Sprintf("%q", msg.ID)))
   312  			}
   313  			entry.baseCtx, entry.done = event.Start(ctx, msg.Method, labels...)
   314  			event.Metric(entry.baseCtx,
   315  				tag.Started.Of(1),
   316  				tag.ReceivedBytes.Of(n))
   317  			// in theory notifications cannot be cancelled, but we build them a cancel context anyway
   318  			entry.handleCtx, entry.cancel = context.WithCancel(entry.baseCtx)
   319  			// if the request is a call, add it to the incoming map so it can be
   320  			// cancelled by id
   321  			if msg.IsCall() {
   322  				pending := <-c.incomingBox
   323  				c.incomingBox <- pending
   324  				pending[msg.ID] = entry
   325  			}
   326  			// send the message to the incoming queue
   327  			toQueue <- entry
   328  		case *Response:
   329  			// If method is not set, this should be a response, in which case we must
   330  			// have an id to send the response back to the caller.
   331  			c.incomingResponse(msg)
   332  		}
   333  	}
   334  }
   335  
   336  func (c *Connection) incomingResponse(msg *Response) {
   337  	pending := <-c.outgoingBox
   338  	response, ok := pending[msg.ID]
   339  	if ok {
   340  		delete(pending, msg.ID)
   341  	}
   342  	c.outgoingBox <- pending
   343  	if response != nil {
   344  		response <- msg
   345  	}
   346  }
   347  
   348  // manageQueue reads incoming requests, attempts to proccess them with the preempter, or queue them
   349  // up for normal handling.
   350  func (c *Connection) manageQueue(ctx context.Context, preempter Preempter, fromRead <-chan *incoming, toDeliver chan<- *incoming) {
   351  	defer close(toDeliver)
   352  	q := []*incoming{}
   353  	ok := true
   354  	for {
   355  		var nextReq *incoming
   356  		if len(q) == 0 {
   357  			// no messages in the queue
   358  			// if we were closing, then we are done
   359  			if !ok {
   360  				return
   361  			}
   362  			// not closing, but nothing in the queue, so just block waiting for a read
   363  			nextReq, ok = <-fromRead
   364  		} else {
   365  			// we have a non empty queue, so pick whichever of reading or delivering
   366  			// that we can make progress on
   367  			select {
   368  			case nextReq, ok = <-fromRead:
   369  			case toDeliver <- q[0]:
   370  				//TODO: this causes a lot of shuffling, should we use a growing ring buffer? compaction?
   371  				q = q[1:]
   372  			}
   373  		}
   374  		if nextReq != nil {
   375  			// TODO: should we allow to limit the queue size?
   376  			var result interface{}
   377  			rerr := nextReq.handleCtx.Err()
   378  			if rerr == nil {
   379  				// only preempt if not already cancelled
   380  				result, rerr = preempter.Preempt(nextReq.handleCtx, nextReq.request)
   381  			}
   382  			switch {
   383  			case rerr == ErrNotHandled:
   384  				// message not handled, add it to the queue for the main handler
   385  				q = append(q, nextReq)
   386  			case rerr == ErrAsyncResponse:
   387  				// message handled but the response will come later
   388  			default:
   389  				// anything else means the message is fully handled
   390  				c.reply(nextReq, result, rerr)
   391  			}
   392  		}
   393  	}
   394  }
   395  
   396  func (c *Connection) deliverMessages(ctx context.Context, handler Handler, fromQueue <-chan *incoming) {
   397  	defer c.async.done()
   398  	for entry := range fromQueue {
   399  		// cancel any messages in the queue that we have a pending cancel for
   400  		var result interface{}
   401  		rerr := entry.handleCtx.Err()
   402  		if rerr == nil {
   403  			// only deliver if not already cancelled
   404  			result, rerr = handler.Handle(entry.handleCtx, entry.request)
   405  		}
   406  		switch {
   407  		case rerr == ErrNotHandled:
   408  			// message not handled, report it back to the caller as an error
   409  			c.reply(entry, nil, errors.Errorf("%w: %q", ErrMethodNotFound, entry.request.Method))
   410  		case rerr == ErrAsyncResponse:
   411  			// message handled but the response will come later
   412  		default:
   413  			c.reply(entry, result, rerr)
   414  		}
   415  	}
   416  }
   417  
   418  // reply is used to reply to an incoming request that has just been handled
   419  func (c *Connection) reply(entry *incoming, result interface{}, rerr error) {
   420  	if entry.request.IsCall() {
   421  		// we have a call finishing, remove it from the incoming map
   422  		pending := <-c.incomingBox
   423  		defer func() { c.incomingBox <- pending }()
   424  		delete(pending, entry.request.ID)
   425  	}
   426  	if err := c.respond(entry, result, rerr); err != nil {
   427  		// no way to propagate this error
   428  		//TODO: should we do more than just log it?
   429  		event.Error(entry.baseCtx, "jsonrpc2 message delivery failed", err)
   430  	}
   431  }
   432  
   433  // respond sends a response.
   434  // This is the code shared between reply and SendResponse.
   435  func (c *Connection) respond(entry *incoming, result interface{}, rerr error) error {
   436  	var err error
   437  	if entry.request.IsCall() {
   438  		// send the response
   439  		if result == nil && rerr == nil {
   440  			// call with no response, send an error anyway
   441  			rerr = errors.Errorf("%w: %q produced no response", ErrInternal, entry.request.Method)
   442  		}
   443  		var response *Response
   444  		response, err = NewResponse(entry.request.ID, result, rerr)
   445  		if err == nil {
   446  			// we write the response with the base context, in case the message was cancelled
   447  			err = c.write(entry.baseCtx, response)
   448  		}
   449  	} else {
   450  		switch {
   451  		case rerr != nil:
   452  			// notification failed
   453  			err = errors.Errorf("%w: %q notification failed: %v", ErrInternal, entry.request.Method, rerr)
   454  			rerr = nil
   455  		case result != nil:
   456  			//notification produced a response, which is an error
   457  			err = errors.Errorf("%w: %q produced unwanted response", ErrInternal, entry.request.Method)
   458  		default:
   459  			// normal notification finish
   460  		}
   461  	}
   462  	switch {
   463  	case rerr != nil || err != nil:
   464  		event.Label(entry.baseCtx, tag.StatusCode.Of("ERROR"))
   465  	default:
   466  		event.Label(entry.baseCtx, tag.StatusCode.Of("OK"))
   467  	}
   468  	// and just to be clean, invoke and clear the cancel if needed
   469  	if entry.cancel != nil {
   470  		entry.cancel()
   471  		entry.cancel = nil
   472  	}
   473  	// mark the entire request processing as done
   474  	entry.done()
   475  	return err
   476  }
   477  
   478  // write is used by all things that write outgoing messages, including replies.
   479  // it makes sure that writes are atomic
   480  func (c *Connection) write(ctx context.Context, msg Message) error {
   481  	writer := <-c.writerBox
   482  	defer func() { c.writerBox <- writer }()
   483  	n, err := writer.Write(ctx, msg)
   484  	event.Metric(ctx, tag.SentBytes.Of(n))
   485  	return err
   486  }