jsonrpc2

package module
Version: v0.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 22, 2022 License: BSD-3-Clause Imports: 15 Imported by: 19

README

jsonrpc2

CircleCI pkg.go.dev Go module codecov.io GA

Package jsonrpc2 is an implementation of the JSON-RPC 2 specification for Go.

Documentation

Overview

Package jsonrpc2 is an implementation of the JSON-RPC 2 specification for Go.

https://www.jsonrpc.org/specification

Index

Constants

View Source
const (
	// HdrContentLength is the HTTP header name of the length of the content part in bytes. This header is required.
	// This entity header indicates the size of the entity-body, in bytes, sent to the recipient.
	//
	// RFC 7230, section 3.3.2: Content-Length:
	//  https://tools.ietf.org/html/rfc7230#section-3.3.2
	HdrContentLength = "Content-Length"

	// HeaderContentType is the mime type of the content part. Defaults to "application/vscode-jsonrpc; charset=utf-8".
	// This entity header is used to indicate the media type of the resource.
	//
	// RFC 7231, section 3.1.1.5: Content-Type:
	//  https://tools.ietf.org/html/rfc7231#section-3.1.1.5
	HdrContentType = "Content-Type"

	// HeaderContentSeparator is the header and content part separator.
	HdrContentSeparator = "\r\n\r\n"
)
View Source
const (
	// ErrIdleTimeout is returned when serving timed out waiting for new connections.
	ErrIdleTimeout = constErr("timed out waiting for new connections")
)
View Source
const Version = "2.0"

Version represents a JSON-RPC version.

Variables

View Source
var (
	// ErrUnknown should be used for all non coded errors.
	ErrUnknown = NewError(UnknownError, "JSON-RPC unknown error")

	// ErrParse is used when invalid JSON was received by the server.
	ErrParse = NewError(ParseError, "JSON-RPC parse error")

	// ErrInvalidRequest is used when the JSON sent is not a valid Request object.
	ErrInvalidRequest = NewError(InvalidRequest, "JSON-RPC invalid request")

	// ErrMethodNotFound should be returned by the handler when the method does
	// not exist / is not available.
	ErrMethodNotFound = NewError(MethodNotFound, "JSON-RPC method not found")

	// ErrInvalidParams should be returned by the handler when method
	// parameter(s) were invalid.
	ErrInvalidParams = NewError(InvalidParams, "JSON-RPC invalid params")

	// ErrInternal is not currently returned but defined for completeness.
	ErrInternal = NewError(InternalError, "JSON-RPC internal error")
)

This file contains the Go forms of the wire specification.

See http://www.jsonrpc.org/specification for details.

list of JSON-RPC errors.

Functions

func ListenAndServe added in v0.7.0

func ListenAndServe(ctx context.Context, network, addr string, server StreamServer, idleTimeout time.Duration) error

ListenAndServe starts an jsonrpc2 server on the given address.

If idleTimeout is non-zero, ListenAndServe exits after there are no clients for this duration, otherwise it exits only on error.

func MethodNotFoundHandler added in v0.7.0

func MethodNotFoundHandler(ctx context.Context, reply Replier, req Request) error

MethodNotFoundHandler is a Handler that replies to all call requests with the standard method not found response.

This should normally be the final handler in a chain.

func Serve added in v0.7.0

func Serve(ctx context.Context, ln net.Listener, server StreamServer, idleTimeout time.Duration) error

Serve accepts incoming connections from the network, and handles them using the provided server. If idleTimeout is non-zero, ListenAndServe exits after there are no clients for this duration, otherwise it exits only on error.

Types

type Call added in v0.7.0

type Call struct {
	// contains filtered or unexported fields
}

Call is a request that expects a response.

The response will have a matching ID.

func NewCall added in v0.7.0

func NewCall(id ID, method string, params interface{}) (*Call, error)

NewCall constructs a new Call message for the supplied ID, method and parameters.

func (*Call) ID added in v0.7.0

func (c *Call) ID() ID

ID returns the current call id.

func (Call) MarshalJSON added in v0.7.0

func (c Call) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Call) Method added in v0.7.0

func (c *Call) Method() string

Method implements Request.

func (*Call) Params added in v0.7.0

func (c *Call) Params() json.RawMessage

Params implements Request.

func (*Call) UnmarshalJSON added in v0.7.0

func (c *Call) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Code

type Code int32

Code is an error code as defined in the JSON-RPC spec.

const (
	// ParseError is the invalid JSON was received by the server.
	// An error occurred on the server while parsing the JSON text.
	ParseError Code = -32700

	// InvalidRequest is the JSON sent is not a valid Request object.
	InvalidRequest Code = -32600

	// MethodNotFound is the method does not exist / is not available.
	MethodNotFound Code = -32601

	// InvalidParams is the invalid method parameter(s).
	InvalidParams Code = -32602

	// InternalError is the internal JSON-RPC error.
	InternalError Code = -32603

	// JSONRPCReservedErrorRangeStart is the start range of JSON RPC reserved error codes.
	//
	// It doesn't denote a real error code. No LSP error codes should
	// be defined between the start and end range. For backwards
	// compatibility the "ServerNotInitialized" and the "UnknownErrorCode"
	// are left in the range.
	//
	// @since 3.16.0.
	JSONRPCReservedErrorRangeStart Code = -32099

	// CodeServerErrorStart reserved for implementation-defined server-errors.
	//
	// Deprecated: Use JSONRPCReservedErrorRangeStart instead.
	CodeServerErrorStart = JSONRPCReservedErrorRangeStart

	// ServerNotInitialized is the error of server not initialized.
	ServerNotInitialized Code = -32002

	// UnknownError should be used for all non coded errors.
	UnknownError Code = -32001

	// JSONRPCReservedErrorRangeEnd is the start range of JSON RPC reserved error codes.
	//
	// It doesn't denote a real error code.
	//
	// @since 3.16.0.
	JSONRPCReservedErrorRangeEnd Code = -32000

	// CodeServerErrorEnd reserved for implementation-defined server-errors.
	//
	// Deprecated: Use JSONRPCReservedErrorRangeEnd instead.
	CodeServerErrorEnd = JSONRPCReservedErrorRangeEnd
)

list of JSON-RPC error codes.

type Conn

type Conn interface {
	// Call invokes the target method and waits for a response.
	//
	// The params will be marshaled to JSON before sending over the wire, and will
	// be handed to the method invoked.
	//
	// The response will be unmarshaled from JSON into the result.
	//
	// The id returned will be unique from this connection, and can be used for
	// logging or tracking.
	Call(ctx context.Context, method string, params, result interface{}) (ID, error)

	// Notify invokes the target method but does not wait for a response.
	//
	// The params will be marshaled to JSON before sending over the wire, and will
	// be handed to the method invoked.
	Notify(ctx context.Context, method string, params interface{}) error

	// Go starts a goroutine to handle the connection.
	//
	// It must be called exactly once for each Conn. It returns immediately.
	// Must block on Done() to wait for the connection to shut down.
	//
	// This is a temporary measure, this should be started automatically in the
	// future.
	Go(ctx context.Context, handler Handler)

	// Close closes the connection and it's underlying stream.
	//
	// It does not wait for the close to complete, use the Done() channel for
	// that.
	Close() error

	// Done returns a channel that will be closed when the processing goroutine
	// has terminated, which will happen if Close() is called or an underlying
	// stream is closed.
	Done() <-chan struct{}

	// Err returns an error if there was one from within the processing goroutine.
	//
	// If err returns non nil, the connection will be already closed or closing.
	Err() error
}

Conn is the common interface to jsonrpc clients and servers.

Conn is bidirectional; it does not have a designated server or client end. It manages the jsonrpc2 protocol, connecting responses back to their calls.

func NewConn

func NewConn(s Stream) Conn

NewConn creates a new connection object around the supplied stream.

type Error

type Error struct {
	// Code a number indicating the error type that occurred.
	Code Code `json:"code"`

	// Message a string providing a short description of the error.
	Message string `json:"message"`

	// Data a Primitive or Structured value that contains additional
	// information about the error. Can be omitted.
	Data *json.RawMessage `json:"data,omitempty"`
}

Error represents a JSON-RPC error.

func Errorf

func Errorf(c Code, format string, args ...interface{}) *Error

Errorf builds a Error struct for the suppied code, format and args.

func NewError

func NewError(c Code, message string) *Error

NewError builds a Error struct for the suppied code and message.

func (*Error) Error

func (e *Error) Error() string

Error implements error.Error.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap implements errors.Unwrap.

Returns the error underlying the receiver, which may be nil.

type Framer added in v0.7.0

type Framer func(conn io.ReadWriteCloser) Stream

Framer wraps a network connection up into a Stream.

It is responsible for the framing and encoding of messages into wire form. NewRawStream and NewStream are implementations of a Framer.

type Handler

type Handler func(ctx context.Context, reply Replier, req Request) error

Handler is invoked to handle incoming requests.

The Replier sends a reply to the request and must be called exactly once.

func AsyncHandler added in v0.7.0

func AsyncHandler(handler Handler) (h Handler)

AsyncHandler returns a handler that processes each request goes in its own goroutine.

The handler returns immediately, without the request being processed. Each request then waits for the previous request to finish before it starts.

This allows the stream to unblock at the cost of unbounded goroutines all stalled on the previous one.

func CancelHandler added in v0.7.0

func CancelHandler(handler Handler) (h Handler, canceller func(id ID))

CancelHandler returns a handler that supports cancellation, and a function that can be used to trigger canceling in progress requests.

func ReplyHandler added in v0.7.0

func ReplyHandler(handler Handler) (h Handler)

ReplyHandler creates a Handler that panics if the wrapped handler does not call Reply for every request that it is passed.

type ID

type ID struct {
	// contains filtered or unexported fields
}

ID is a Request identifier.

Only one of either the Name or Number members will be set, using the number form if the Name is the empty string.

func NewNumberID added in v0.7.0

func NewNumberID(v int32) ID

NewNumberID returns a new number request ID.

func NewStringID added in v0.6.2

func NewStringID(v string) ID

NewStringID returns a new string request ID.

func (ID) Format added in v0.6.2

func (id ID) Format(f fmt.State, r rune)

Format writes the ID to the formatter.

If the rune is q the representation is non ambiguous, string forms are quoted, number forms are preceded by a #.

func (*ID) MarshalJSON

func (id *ID) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*ID) UnmarshalJSON

func (id *ID) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Message added in v0.7.0

type Message interface {
	// contains filtered or unexported methods
}

Message is the interface to all JSON-RPC message types.

They share no common functionality, but are a closed set of concrete types that are allowed to implement this interface.

The message types are *Call, *Response and *Notification.

func DecodeMessage added in v0.7.0

func DecodeMessage(data []byte) (Message, error)

DecodeMessage decodes data to Message.

type Notification added in v0.7.0

type Notification struct {
	// contains filtered or unexported fields
}

Notification is a request for which a response cannot occur, and as such it has not ID.

func NewNotification added in v0.7.0

func NewNotification(method string, params interface{}) (*Notification, error)

NewNotification constructs a new Notification message for the supplied method and parameters.

func (Notification) MarshalJSON added in v0.7.0

func (n Notification) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Notification) Method added in v0.7.0

func (n *Notification) Method() string

Method implements Request.

func (*Notification) Params added in v0.7.0

func (n *Notification) Params() json.RawMessage

Params implements Request.

func (*Notification) UnmarshalJSON added in v0.7.0

func (n *Notification) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Replier added in v0.7.0

type Replier func(ctx context.Context, result interface{}, err error) error

Replier is passed to handlers to allow them to reply to the request.

If err is set then result will be ignored.

type Request

type Request interface {
	Message

	// Method is a string containing the method name to invoke.
	Method() string
	// Params is either a struct or an array with the parameters of the method.
	Params() json.RawMessage
	// contains filtered or unexported methods
}

Request is the shared interface to jsonrpc2 messages that request a method be invoked.

The request types are a closed set of *Call and *Notification.

type Response added in v0.7.0

type Response struct {
	// contains filtered or unexported fields
}

Response is a reply to a Request.

It will have the same ID as the call it is a response to.

func NewResponse added in v0.7.0

func NewResponse(id ID, result interface{}, err error) (*Response, error)

NewResponse constructs a new Response message that is a reply to the supplied. If err is set result may be ignored.

func (*Response) Err added in v0.7.0

func (r *Response) Err() error

Err returns the Response error.

func (*Response) ID added in v0.7.0

func (r *Response) ID() ID

ID returns the current response id.

func (Response) MarshalJSON added in v0.7.0

func (r Response) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Response) Result added in v0.7.0

func (r *Response) Result() json.RawMessage

Result returns the Response result.

func (*Response) UnmarshalJSON added in v0.7.0

func (r *Response) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type ServerFunc added in v0.7.0

type ServerFunc func(context.Context, Conn) error

ServerFunc is an adapter that implements the StreamServer interface using an ordinary function.

func (ServerFunc) ServeStream added in v0.7.0

func (f ServerFunc) ServeStream(ctx context.Context, c Conn) error

ServeStream implements StreamServer.

ServeStream calls f(ctx, s).

type Stream

type Stream interface {
	// Read gets the next message from the stream.
	Read(context.Context) (Message, int64, error)

	// Write sends a message to the stream.
	Write(context.Context, Message) (int64, error)

	// Close closes the connection.
	// Any blocked Read or Write operations will be unblocked and return errors.
	Close() error
}

Stream abstracts the transport mechanics from the JSON RPC protocol.

A Conn reads and writes messages using the stream it was provided on construction, and assumes that each call to Read or Write fully transfers a single message, or returns an error.

A stream is not safe for concurrent use, it is expected it will be used by a single Conn in a safe manner.

func NewRawStream added in v0.7.0

func NewRawStream(conn io.ReadWriteCloser) Stream

NewRawStream returns a Stream built on top of a io.ReadWriteCloser.

The messages are sent with no wrapping, and rely on json decode consistency to determine message boundaries.

func NewStream

func NewStream(conn io.ReadWriteCloser) Stream

NewStream returns a Stream built on top of a io.ReadWriteCloser.

The messages are sent with HTTP content length and MIME type headers. This is the format used by LSP and others.

type StreamServer added in v0.7.0

type StreamServer interface {
	ServeStream(context.Context, Conn) error
}

StreamServer is used to serve incoming jsonrpc2 clients communicating over a newly created connection.

func HandlerServer added in v0.7.0

func HandlerServer(h Handler) StreamServer

HandlerServer returns a StreamServer that handles incoming streams using the provided handler.

Directories

Path Synopsis
Package fake provides utilities for running tests against a remote LSP server.
Package fake provides utilities for running tests against a remote LSP server.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL