2018-09-21 09:17:43 -06:00
|
|
|
// Copyright 2018 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
// Package jsonrpc2 is a minimal implementation of the JSON RPC 2 spec.
|
|
|
|
// https://www.jsonrpc.org/specification
|
|
|
|
// It is intended to be compatible with other implementations at the wire level.
|
|
|
|
package jsonrpc2
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"sync"
|
|
|
|
"sync/atomic"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Conn is a JSON RPC 2 client server connection.
|
|
|
|
// Conn is bidirectional; it does not have a designated server or client end.
|
|
|
|
type Conn struct {
|
2019-07-11 10:57:35 -06:00
|
|
|
seq int64 // must only be accessed using atomic operations
|
|
|
|
handlers []Handler
|
|
|
|
stream Stream
|
|
|
|
err error
|
|
|
|
pendingMu sync.Mutex // protects the pending map
|
2019-07-11 22:43:12 -06:00
|
|
|
pending map[ID]chan *WireResponse
|
2019-07-11 10:57:35 -06:00
|
|
|
handlingMu sync.Mutex // protects the handling map
|
|
|
|
handling map[ID]*Request
|
2019-03-29 09:13:22 -06:00
|
|
|
}
|
|
|
|
|
2019-06-24 07:16:28 -06:00
|
|
|
type requestState int
|
|
|
|
|
|
|
|
const (
|
|
|
|
requestWaiting = requestState(iota)
|
|
|
|
requestSerial
|
|
|
|
requestParallel
|
|
|
|
requestReplied
|
|
|
|
requestDone
|
|
|
|
)
|
|
|
|
|
2019-06-24 07:18:31 -06:00
|
|
|
// Request is sent to a server to represent a Call or Notify operaton.
|
|
|
|
type Request struct {
|
2019-06-24 07:16:28 -06:00
|
|
|
conn *Conn
|
|
|
|
cancel context.CancelFunc
|
|
|
|
state requestState
|
|
|
|
nextRequest chan struct{}
|
2019-06-24 07:18:31 -06:00
|
|
|
|
2019-07-11 22:43:12 -06:00
|
|
|
// The Wire values of the request.
|
|
|
|
WireRequest
|
2019-06-24 07:18:31 -06:00
|
|
|
}
|
|
|
|
|
2019-09-11 00:14:36 -06:00
|
|
|
// NewErrorf builds a Error struct for the supplied message and code.
|
2018-09-21 09:17:43 -06:00
|
|
|
// If args is not empty, message and args will be passed to Sprintf.
|
|
|
|
func NewErrorf(code int64, format string, args ...interface{}) *Error {
|
|
|
|
return &Error{
|
|
|
|
Code: code,
|
|
|
|
Message: fmt.Sprintf(format, args...),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-28 19:06:01 -06:00
|
|
|
// NewConn creates a new connection object around the supplied stream.
|
|
|
|
// You must call Run for the connection to be active.
|
|
|
|
func NewConn(s Stream) *Conn {
|
2018-09-21 09:17:43 -06:00
|
|
|
conn := &Conn{
|
2019-07-16 14:24:47 -06:00
|
|
|
handlers: []Handler{defaultHandler{}},
|
2018-09-21 09:17:43 -06:00
|
|
|
stream: s,
|
2019-07-11 22:43:12 -06:00
|
|
|
pending: make(map[ID]chan *WireResponse),
|
2019-06-24 07:16:28 -06:00
|
|
|
handling: make(map[ID]*Request),
|
2018-09-21 09:17:43 -06:00
|
|
|
}
|
|
|
|
return conn
|
|
|
|
}
|
|
|
|
|
2019-07-11 10:57:35 -06:00
|
|
|
// AddHandler adds a new handler to the set the connection will invoke.
|
|
|
|
// Handlers are invoked in the reverse order of how they were added, this
|
|
|
|
// allows the most recent addition to be the first one to attempt to handle a
|
|
|
|
// message.
|
|
|
|
func (c *Conn) AddHandler(handler Handler) {
|
|
|
|
// prepend the new handlers so we use them first
|
|
|
|
c.handlers = append([]Handler{handler}, c.handlers...)
|
|
|
|
}
|
|
|
|
|
2018-09-21 09:17:43 -06:00
|
|
|
// Cancel cancels a pending Call on the server side.
|
|
|
|
// The call is identified by its id.
|
|
|
|
// JSON RPC 2 does not specify a cancel message, so cancellation support is not
|
|
|
|
// directly wired in. This method allows a higher level protocol to choose how
|
|
|
|
// to propagate the cancel.
|
|
|
|
func (c *Conn) Cancel(id ID) {
|
|
|
|
c.handlingMu.Lock()
|
2018-11-13 20:49:07 -07:00
|
|
|
handling, found := c.handling[id]
|
2018-09-21 09:17:43 -06:00
|
|
|
c.handlingMu.Unlock()
|
2018-11-13 20:49:07 -07:00
|
|
|
if found {
|
|
|
|
handling.cancel()
|
2018-09-21 09:17:43 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Notify is called to send a notification request over the connection.
|
|
|
|
// It will return as soon as the notification has been sent, as no response is
|
|
|
|
// possible.
|
2019-06-21 14:26:30 -06:00
|
|
|
func (c *Conn) Notify(ctx context.Context, method string, params interface{}) (err error) {
|
2018-09-21 09:17:43 -06:00
|
|
|
jsonParams, err := marshalToRaw(params)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("marshalling notify parameters: %v", err)
|
|
|
|
}
|
2019-07-11 22:43:12 -06:00
|
|
|
request := &WireRequest{
|
2018-09-21 09:17:43 -06:00
|
|
|
Method: method,
|
|
|
|
Params: jsonParams,
|
|
|
|
}
|
|
|
|
data, err := json.Marshal(request)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("marshalling notify request: %v", err)
|
|
|
|
}
|
2019-07-11 10:57:35 -06:00
|
|
|
for _, h := range c.handlers {
|
2019-10-11 14:08:39 -06:00
|
|
|
ctx = h.Request(ctx, c, Send, request)
|
2019-07-11 10:57:35 -06:00
|
|
|
}
|
2019-07-11 22:43:12 -06:00
|
|
|
defer func() {
|
|
|
|
for _, h := range c.handlers {
|
|
|
|
h.Done(ctx, err)
|
|
|
|
}
|
|
|
|
}()
|
2019-06-21 14:26:30 -06:00
|
|
|
n, err := c.stream.Write(ctx, data)
|
2019-07-11 22:43:12 -06:00
|
|
|
for _, h := range c.handlers {
|
|
|
|
ctx = h.Wrote(ctx, n)
|
|
|
|
}
|
2019-06-21 14:26:30 -06:00
|
|
|
return err
|
2018-09-21 09:17:43 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
// Call sends a request over the connection and then waits for a response.
|
|
|
|
// If the response is not an error, it will be decoded into result.
|
|
|
|
// result must be of a type you an pass to json.Unmarshal.
|
2019-06-21 14:26:30 -06:00
|
|
|
func (c *Conn) Call(ctx context.Context, method string, params, result interface{}) (err error) {
|
|
|
|
// generate a new request identifier
|
|
|
|
id := ID{Number: atomic.AddInt64(&c.seq, 1)}
|
2018-09-21 09:17:43 -06:00
|
|
|
jsonParams, err := marshalToRaw(params)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("marshalling call parameters: %v", err)
|
|
|
|
}
|
2019-07-11 22:43:12 -06:00
|
|
|
request := &WireRequest{
|
2018-09-21 09:17:43 -06:00
|
|
|
ID: &id,
|
|
|
|
Method: method,
|
|
|
|
Params: jsonParams,
|
|
|
|
}
|
|
|
|
// marshal the request now it is complete
|
|
|
|
data, err := json.Marshal(request)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("marshalling call request: %v", err)
|
|
|
|
}
|
2019-07-11 22:43:12 -06:00
|
|
|
for _, h := range c.handlers {
|
2019-10-11 14:08:39 -06:00
|
|
|
ctx = h.Request(ctx, c, Send, request)
|
2019-07-11 22:43:12 -06:00
|
|
|
}
|
2018-09-21 09:17:43 -06:00
|
|
|
// we have to add ourselves to the pending map before we send, otherwise we
|
|
|
|
// are racing the response
|
2019-07-11 22:43:12 -06:00
|
|
|
rchan := make(chan *WireResponse)
|
2018-09-21 09:17:43 -06:00
|
|
|
c.pendingMu.Lock()
|
|
|
|
c.pending[id] = rchan
|
|
|
|
c.pendingMu.Unlock()
|
|
|
|
defer func() {
|
|
|
|
// clean up the pending response handler on the way out
|
|
|
|
c.pendingMu.Lock()
|
|
|
|
delete(c.pending, id)
|
|
|
|
c.pendingMu.Unlock()
|
2019-07-11 22:43:12 -06:00
|
|
|
for _, h := range c.handlers {
|
|
|
|
h.Done(ctx, err)
|
|
|
|
}
|
2018-09-21 09:17:43 -06:00
|
|
|
}()
|
|
|
|
// now we are ready to send
|
2019-07-11 22:43:12 -06:00
|
|
|
n, err := c.stream.Write(ctx, data)
|
2019-07-11 10:57:35 -06:00
|
|
|
for _, h := range c.handlers {
|
2019-07-11 22:43:12 -06:00
|
|
|
ctx = h.Wrote(ctx, n)
|
2019-07-11 10:57:35 -06:00
|
|
|
}
|
2019-06-21 14:26:30 -06:00
|
|
|
if err != nil {
|
2018-09-21 09:17:43 -06:00
|
|
|
// sending failed, we will never get a response, so don't leave it pending
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
// now wait for the response
|
|
|
|
select {
|
|
|
|
case response := <-rchan:
|
2019-07-11 10:57:35 -06:00
|
|
|
for _, h := range c.handlers {
|
2019-10-11 14:08:39 -06:00
|
|
|
ctx = h.Response(ctx, c, Receive, response)
|
2019-07-11 10:57:35 -06:00
|
|
|
}
|
2018-09-21 09:17:43 -06:00
|
|
|
// is it an error response?
|
|
|
|
if response.Error != nil {
|
|
|
|
return response.Error
|
|
|
|
}
|
|
|
|
if result == nil || response.Result == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if err := json.Unmarshal(*response.Result, result); err != nil {
|
|
|
|
return fmt.Errorf("unmarshalling result: %v", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
case <-ctx.Done():
|
|
|
|
// allow the handler to propagate the cancel
|
2019-07-11 10:57:35 -06:00
|
|
|
cancelled := false
|
|
|
|
for _, h := range c.handlers {
|
|
|
|
if h.Cancel(ctx, c, id, cancelled) {
|
|
|
|
cancelled = true
|
|
|
|
}
|
|
|
|
}
|
2018-09-21 09:17:43 -06:00
|
|
|
return ctx.Err()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-24 07:18:31 -06:00
|
|
|
// Conn returns the connection that created this request.
|
|
|
|
func (r *Request) Conn() *Conn { return r.conn }
|
|
|
|
|
|
|
|
// IsNotify returns true if this request is a notification.
|
|
|
|
func (r *Request) IsNotify() bool {
|
|
|
|
return r.ID == nil
|
|
|
|
}
|
|
|
|
|
2019-06-24 07:16:28 -06:00
|
|
|
// Parallel indicates that the system is now allowed to process other requests
|
|
|
|
// in parallel with this one.
|
|
|
|
// It is safe to call any number of times, but must only be called from the
|
|
|
|
// request handling go routine.
|
|
|
|
// It is implied by both reply and by the handler returning.
|
|
|
|
func (r *Request) Parallel() {
|
|
|
|
if r.state >= requestParallel {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
r.state = requestParallel
|
|
|
|
close(r.nextRequest)
|
|
|
|
}
|
|
|
|
|
2018-11-13 20:49:07 -07:00
|
|
|
// Reply sends a reply to the given request.
|
|
|
|
// It is an error to call this if request was not a call.
|
|
|
|
// You must call this exactly once for any given request.
|
2019-06-24 07:16:28 -06:00
|
|
|
// It should only be called from the handler go routine.
|
2018-11-13 20:49:07 -07:00
|
|
|
// If err is set then result will be ignored.
|
2019-06-26 21:36:29 -06:00
|
|
|
// If the request has not yet dropped into parallel mode
|
|
|
|
// it will be before this function returns.
|
2019-06-24 07:18:31 -06:00
|
|
|
func (r *Request) Reply(ctx context.Context, result interface{}, err error) error {
|
2019-06-24 07:16:28 -06:00
|
|
|
if r.state >= requestReplied {
|
|
|
|
return fmt.Errorf("reply invoked more than once")
|
|
|
|
}
|
2019-06-24 07:18:31 -06:00
|
|
|
if r.IsNotify() {
|
2020-01-24 14:40:38 -07:00
|
|
|
return fmt.Errorf("reply not invoked with a valid call: %v, %s", r.Method, r.Params)
|
2018-11-13 20:49:07 -07:00
|
|
|
}
|
2019-06-26 21:36:29 -06:00
|
|
|
// reply ends the handling phase of a call, so if we are not yet
|
|
|
|
// parallel we should be now. The go routine is allowed to continue
|
|
|
|
// to do work after replying, which is why it is important to unlock
|
|
|
|
// the rpc system at this point.
|
2019-06-24 07:16:28 -06:00
|
|
|
r.Parallel()
|
|
|
|
r.state = requestReplied
|
2018-11-13 20:49:07 -07:00
|
|
|
|
|
|
|
var raw *json.RawMessage
|
|
|
|
if err == nil {
|
|
|
|
raw, err = marshalToRaw(result)
|
|
|
|
}
|
2019-07-11 22:43:12 -06:00
|
|
|
response := &WireResponse{
|
2018-11-13 20:49:07 -07:00
|
|
|
Result: raw,
|
2019-06-24 07:18:31 -06:00
|
|
|
ID: r.ID,
|
2018-11-13 20:49:07 -07:00
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
if callErr, ok := err.(*Error); ok {
|
|
|
|
response.Error = callErr
|
|
|
|
} else {
|
|
|
|
response.Error = NewErrorf(0, "%s", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
data, err := json.Marshal(response)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-07-11 10:57:35 -06:00
|
|
|
for _, h := range r.conn.handlers {
|
2019-10-11 14:08:39 -06:00
|
|
|
ctx = h.Response(ctx, r.conn, Send, response)
|
2019-07-11 10:57:35 -06:00
|
|
|
}
|
2019-06-24 07:18:31 -06:00
|
|
|
n, err := r.conn.stream.Write(ctx, data)
|
2019-07-11 22:43:12 -06:00
|
|
|
for _, h := range r.conn.handlers {
|
|
|
|
ctx = h.Wrote(ctx, n)
|
|
|
|
}
|
2019-06-21 14:26:30 -06:00
|
|
|
|
|
|
|
if err != nil {
|
2018-11-13 20:49:07 -07:00
|
|
|
// TODO(iancottrell): if a stream write fails, we really need to shut down
|
|
|
|
// the whole stream
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-06-24 07:16:28 -06:00
|
|
|
func (c *Conn) setHandling(r *Request, active bool) {
|
|
|
|
if r.ID == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
r.conn.handlingMu.Lock()
|
|
|
|
defer r.conn.handlingMu.Unlock()
|
|
|
|
if active {
|
|
|
|
r.conn.handling[*r.ID] = r
|
|
|
|
} else {
|
|
|
|
delete(r.conn.handling, *r.ID)
|
|
|
|
}
|
2018-11-13 20:49:07 -07:00
|
|
|
}
|
|
|
|
|
2018-09-21 09:17:43 -06:00
|
|
|
// combined has all the fields of both Request and Response.
|
|
|
|
// We can decode this and then work out which it is.
|
|
|
|
type combined struct {
|
|
|
|
VersionTag VersionTag `json:"jsonrpc"`
|
|
|
|
ID *ID `json:"id,omitempty"`
|
|
|
|
Method string `json:"method"`
|
|
|
|
Params *json.RawMessage `json:"params,omitempty"`
|
|
|
|
Result *json.RawMessage `json:"result,omitempty"`
|
|
|
|
Error *Error `json:"error,omitempty"`
|
|
|
|
}
|
|
|
|
|
2019-03-28 19:06:01 -06:00
|
|
|
// Run blocks until the connection is terminated, and returns any error that
|
|
|
|
// caused the termination.
|
2018-09-21 09:17:43 -06:00
|
|
|
// It must be called exactly once for each Conn.
|
|
|
|
// It returns only when the reader is closed or there is an error in the stream.
|
2019-07-16 20:20:43 -06:00
|
|
|
func (c *Conn) Run(runCtx context.Context) error {
|
2019-06-26 21:36:29 -06:00
|
|
|
// we need to make the next request "lock" in an unlocked state to allow
|
|
|
|
// the first incoming request to proceed. All later requests are unlocked
|
|
|
|
// by the preceding request going to parallel mode.
|
2019-06-24 07:16:28 -06:00
|
|
|
nextRequest := make(chan struct{})
|
|
|
|
close(nextRequest)
|
2018-09-21 09:17:43 -06:00
|
|
|
for {
|
|
|
|
// get the data for a message
|
2019-07-16 20:20:43 -06:00
|
|
|
data, n, err := c.stream.Read(runCtx)
|
2018-09-21 09:17:43 -06:00
|
|
|
if err != nil {
|
|
|
|
// the stream failed, we cannot continue
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
// read a combined message
|
|
|
|
msg := &combined{}
|
|
|
|
if err := json.Unmarshal(data, msg); err != nil {
|
|
|
|
// a badly formed message arrived, log it and continue
|
|
|
|
// we trust the stream to have isolated the error to just this message
|
2019-07-11 10:57:35 -06:00
|
|
|
for _, h := range c.handlers {
|
2019-07-16 20:20:43 -06:00
|
|
|
h.Error(runCtx, fmt.Errorf("unmarshal failed: %v", err))
|
2019-07-11 10:57:35 -06:00
|
|
|
}
|
2018-09-21 09:17:43 -06:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
// work out which kind of message we have
|
|
|
|
switch {
|
|
|
|
case msg.Method != "":
|
|
|
|
// if method is set it must be a request
|
2019-07-16 20:20:43 -06:00
|
|
|
reqCtx, cancelReq := context.WithCancel(runCtx)
|
2019-06-24 07:16:28 -06:00
|
|
|
thisRequest := nextRequest
|
|
|
|
nextRequest = make(chan struct{})
|
|
|
|
req := &Request{
|
|
|
|
conn: c,
|
|
|
|
cancel: cancelReq,
|
|
|
|
nextRequest: nextRequest,
|
2019-07-11 22:43:12 -06:00
|
|
|
WireRequest: WireRequest{
|
|
|
|
VersionTag: msg.VersionTag,
|
|
|
|
Method: msg.Method,
|
|
|
|
Params: msg.Params,
|
|
|
|
ID: msg.ID,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
for _, h := range c.handlers {
|
2019-10-11 14:08:39 -06:00
|
|
|
reqCtx = h.Request(reqCtx, c, Receive, &req.WireRequest)
|
2019-07-16 20:20:43 -06:00
|
|
|
reqCtx = h.Read(reqCtx, n)
|
2018-09-21 09:17:43 -06:00
|
|
|
}
|
2019-06-24 07:16:28 -06:00
|
|
|
c.setHandling(req, true)
|
|
|
|
go func() {
|
|
|
|
<-thisRequest
|
|
|
|
req.state = requestSerial
|
|
|
|
defer func() {
|
|
|
|
c.setHandling(req, false)
|
|
|
|
if !req.IsNotify() && req.state < requestReplied {
|
2019-07-16 20:20:43 -06:00
|
|
|
req.Reply(reqCtx, nil, NewErrorf(CodeInternalError, "method %q did not reply", req.Method))
|
2019-06-24 07:16:28 -06:00
|
|
|
}
|
|
|
|
req.Parallel()
|
2019-07-11 22:43:12 -06:00
|
|
|
for _, h := range c.handlers {
|
2019-07-16 20:20:43 -06:00
|
|
|
h.Done(reqCtx, err)
|
2019-07-11 22:43:12 -06:00
|
|
|
}
|
2019-06-24 07:16:28 -06:00
|
|
|
cancelReq()
|
|
|
|
}()
|
2019-07-11 10:57:35 -06:00
|
|
|
delivered := false
|
|
|
|
for _, h := range c.handlers {
|
2019-07-16 20:20:43 -06:00
|
|
|
if h.Deliver(reqCtx, req, delivered) {
|
2019-07-11 10:57:35 -06:00
|
|
|
delivered = true
|
|
|
|
}
|
|
|
|
}
|
2019-06-24 07:16:28 -06:00
|
|
|
}()
|
2018-09-21 09:17:43 -06:00
|
|
|
case msg.ID != nil:
|
|
|
|
// we have a response, get the pending entry from the map
|
|
|
|
c.pendingMu.Lock()
|
|
|
|
rchan := c.pending[*msg.ID]
|
|
|
|
if rchan != nil {
|
|
|
|
delete(c.pending, *msg.ID)
|
|
|
|
}
|
|
|
|
c.pendingMu.Unlock()
|
|
|
|
// and send the reply to the channel
|
2019-07-11 22:43:12 -06:00
|
|
|
response := &WireResponse{
|
2018-09-21 09:17:43 -06:00
|
|
|
Result: msg.Result,
|
|
|
|
Error: msg.Error,
|
|
|
|
ID: msg.ID,
|
|
|
|
}
|
|
|
|
rchan <- response
|
|
|
|
close(rchan)
|
|
|
|
default:
|
2019-07-11 10:57:35 -06:00
|
|
|
for _, h := range c.handlers {
|
2019-07-16 20:20:43 -06:00
|
|
|
h.Error(runCtx, fmt.Errorf("message not a call, notify or response, ignoring"))
|
2019-07-11 10:57:35 -06:00
|
|
|
}
|
2018-09-21 09:17:43 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func marshalToRaw(obj interface{}) (*json.RawMessage, error) {
|
|
|
|
data, err := json.Marshal(obj)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
raw := json.RawMessage(data)
|
|
|
|
return &raw, nil
|
|
|
|
}
|