jsonrpc

package
v0.4.11 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2024 License: Unlicense Imports: 15 Imported by: 1

Documentation

Index

Constants

View Source
const (
	ErrorCodeDefault     = -32000
	ErrorCodeApplication = -32080
	ErrorCodeJrpc        = -42000
)
View Source
const NullString = "null"
View Source
const VersionString = "2.0"

Version represents a JSON-RPC version.

Variables

View Source
var (
	ErrIllegalExtraField    = errors.New("invalid extra field")
	ErrSendAlreadyCalled    = errors.New("send already called")
	ErrCantSendNotification = errors.New("can't send to a notification")
)

Functions

func Call

func Call[T any](ctx context.Context, c Conn, method string, args ...any) (*T, error)

Call

func CallInto

func CallInto(ctx context.Context, c Conn, result any, method string, args ...any) error

CallInto

func ContextWithConn

func ContextWithConn(ctx context.Context, c Conn) context.Context

ClientFromContext retrieves the client from the context, if any. This can be used to perform 'reverse calls' in a handler method.

func Do

func Do[T any](ctx context.Context, c Conn, method string, args any) (*T, error)

Do

func IsBatchMessage

func IsBatchMessage(raw json.RawMessage) bool

isBatch returns true when the first non-whitespace characters is '['

func MarshalError added in v0.3.11

func MarshalError(err error) []byte

func MarshalMessage

func MarshalMessage(m *Message, enc *jx.Encoder) (err error)

func NewNull

func NewNull() json.RawMessage

func NewStringReader

func NewStringReader(x string) io.ReadCloser

func UnmarshalMessage

func UnmarshalMessage(m *Message, dec *jx.Decoder) error

func WrapErr

func WrapErr(data any, code int, err error) error

Types

type BatchWriter added in v0.3.17

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

func (*BatchWriter) Close added in v0.3.17

func (m *BatchWriter) Close() error

close must be called when you are done writing the batch. it releases the write lock

func (*BatchWriter) NewMessage added in v0.3.17

func (m *BatchWriter) NewMessage(ctx context.Context) (*MessageWriter, error)

Writes the next element in the batch. Note that the messagewriter is not thread safe

type ChainHandler

type ChainHandler struct {
	Endpoint Handler

	Middlewares Middlewares
	// contains filtered or unexported fields
}

ChainHandler is a Handler with support for handler composition and execution.

func (*ChainHandler) ServeRPC

func (c *ChainHandler) ServeRPC(w ResponseWriter, r *Request)

type Conn

type Conn interface {
	Doer
	Notifier

	Mounter

	io.Closer
	Closed() <-chan struct{}
}

func ConnFromContext

func ConnFromContext(ctx context.Context) (Conn, bool)

ClientFromContext retrieves the client from the context, if any. This can be used to perform 'reverse calls' in a handler method.

type DataError

type DataError interface {
	Error() string  // returns the message
	ErrorCode() int // returns the error code
	ErrorData() any // returns the error data
}

A DataError contains some data in addition to the error message.

type Doer

type Doer interface {
	Do(ctx context.Context, result any, method string, params any) error
}

type DummyClient

type DummyClient struct{}

func (*DummyClient) Close

func (d *DummyClient) Close() error

func (*DummyClient) Closed

func (d *DummyClient) Closed() <-chan struct{}

func (*DummyClient) Do

func (d *DummyClient) Do(ctx context.Context, result any, method string, params any) error

func (*DummyClient) Mount

func (d *DummyClient) Mount(_ Middleware)

func (*DummyClient) Notify

func (d *DummyClient) Notify(ctx context.Context, method string, params any) error

type Error

type Error interface {
	Error() string  // returns the message
	ErrorCode() int // returns the code
}

Error wraps RPC errors, which contain an error code in addition to the message.

type ErrorInternalError

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

unable to decode supplied params, or an invalid number of parameters

func NewInternalError

func NewInternalError(message string) *ErrorInternalError

func (*ErrorInternalError) Error

func (e *ErrorInternalError) Error() string

func (*ErrorInternalError) ErrorCode

func (e *ErrorInternalError) ErrorCode() int

type ErrorInvalidMessage

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

received message is invalid

func (*ErrorInvalidMessage) Error

func (e *ErrorInvalidMessage) Error() string

func (*ErrorInvalidMessage) ErrorCode

func (e *ErrorInvalidMessage) ErrorCode() int

type ErrorInvalidParams

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

unable to decode supplied params, or an invalid number of parameters

func NewInvalidParamsError

func NewInvalidParamsError(message string) *ErrorInvalidParams

func (*ErrorInvalidParams) Error

func (e *ErrorInvalidParams) Error() string

func (*ErrorInvalidParams) ErrorCode

func (e *ErrorInvalidParams) ErrorCode() int

type ErrorInvalidRequest

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

received message isn't a valid request

func NewInvalidRequestError

func NewInvalidRequestError(message string) *ErrorInvalidRequest

func (*ErrorInvalidRequest) Error

func (e *ErrorInvalidRequest) Error() string

func (*ErrorInvalidRequest) ErrorCode

func (e *ErrorInvalidRequest) ErrorCode() int

type ErrorMethodNotFound

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

func NewMethodNotFoundError

func NewMethodNotFoundError(method string) *ErrorMethodNotFound

func (*ErrorMethodNotFound) Error

func (e *ErrorMethodNotFound) Error() string

func (*ErrorMethodNotFound) ErrorCode

func (e *ErrorMethodNotFound) ErrorCode() int

type ErrorParse

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

Invalid JSON was received by the server.

func (*ErrorParse) Error

func (e *ErrorParse) Error() string

func (*ErrorParse) ErrorCode

func (e *ErrorParse) ErrorCode() int

type ErrorSubscriptionNotFound

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

func (*ErrorSubscriptionNotFound) Error

func (e *ErrorSubscriptionNotFound) Error() string

func (*ErrorSubscriptionNotFound) ErrorCode

func (e *ErrorSubscriptionNotFound) ErrorCode() int

type HTTPError

type HTTPError struct {
	StatusCode int
	Status     string
	Body       []byte
}

HTTPError is returned by client operations when the HTTP status code of the response is not a 2xx status.

func (HTTPError) Error

func (err HTTPError) Error() string

type Handler

type Handler interface {
	ServeRPC(w ResponseWriter, r *Request)
}

http.handler, but for jrpc

func ChainMiddlewares

func ChainMiddlewares(middlewares []func(Handler) Handler, endpoint Handler) Handler

type HandlerFunc

type HandlerFunc func(w ResponseWriter, r *Request)

http.HandlerFunc,but for jrpc

func (HandlerFunc) ServeRPC

func (fn HandlerFunc) ServeRPC(w ResponseWriter, r *Request)

ServeRPC implements (jsonrpc.Handler).ServeRPC

type ID

type ID json.RawMessage

ID is a Request identifier.

alternatively, ID can be null

func NewId

func NewId(v any) *ID

func NewNullID

func NewNullID() ID

NewStringID returns a new string request ID.

func NewNullIDPtr

func NewNullIDPtr() *ID

func NewNumberID

func NewNumberID(v int64) ID

NewNumberID returns a new number request ID.

func NewNumberIDPtr

func NewNumberIDPtr(v int64) *ID

func NewStringID

func NewStringID(v string) ID

NewStringID returns a new string request ID.

func NewStringIDPtr

func NewStringIDPtr(v string) *ID

func (*ID) Format

func (i *ID) Format(f fmt.State, verb rune)

func (*ID) IsNull

func (id *ID) IsNull() bool

func (ID) MarshalJSON

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

MarshalJSON implements json.Marshaler.

func (*ID) Number

func (id *ID) Number() int

func (*ID) RawMessage

func (id *ID) RawMessage() json.RawMessage

get the raw message

func (*ID) UnmarshalJSON

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

UnmarshalJSON implements json.Unmarshaler.

type JsonError

type JsonError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
}

encapsulate json rpc error into struct

func (*JsonError) Error

func (err *JsonError) Error() string

func (*JsonError) ErrorCode

func (err *JsonError) ErrorCode() int

func (*JsonError) ErrorData

func (err *JsonError) ErrorData() any

type Listener

type Listener interface {
	Accept() (ReaderWriter, error)
	Close() error
	Addr() net.Addr
}

type Message

type Message struct {
	ID         *ID                        `json:"id,omitempty"`
	Method     string                     `json:"method,omitempty"`
	Params     json.RawMessage            `json:"params,omitempty"`
	Error      error                      `json:"error,omitempty"`
	Extensions map[string]json.RawMessage `json:"-"`

	Result io.ReadCloser `json:"result,omitempty"`
}

A value of this type can a JSON-RPC request, notification, successful response or error response. Which one it is depends on the fields.

func ParseMessage

func ParseMessage(in json.RawMessage) ([]*Message, bool)

parseMessage parses raw bytes as a (batch of) JSON-RPC message(s). There are no error checks in this function because the raw message has already been syntax-checked when it is called. Any non-JSON-RPC messages in the input return the zero value of Message.

func ReadMessage

func ReadMessage(dec *jx.Decoder) ([]*Message, bool)

parseMessage parses raw bytes as a (batch of) JSON-RPC message(s). There are no error checks in this function because the raw message has already been syntax-checked when it is called. Any non-JSON-RPC messages in the input return the zero value of Message.

func (Message) MarshalJSON

func (m Message) MarshalJSON() ([]byte, error)

func (*Message) String

func (msg *Message) String() string

func (*Message) UnmarshalJSON

func (m *Message) UnmarshalJSON(xs []byte) error

type MessageStream added in v0.3.17

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

MessageStream is a writer used to write jsonrpc message to a stream

func NewStream added in v0.3.17

func NewStream(w io.Writer) *MessageStream

func (*MessageStream) Flush added in v0.3.17

func (m *MessageStream) Flush(ctx context.Context) error

sends a flush in order to send an empty payload

func (*MessageStream) NewBatch added in v0.3.17

func (m *MessageStream) NewBatch(ctx context.Context) (*BatchWriter, error)

Start writing a batch to the stream. this function acquires the lock caller MUST call Close() on the BatchWriter iff err == nil

func (*MessageStream) NewMessage added in v0.3.17

func (m *MessageStream) NewMessage(ctx context.Context) (*MessageWriter, error)

NewMessage starts a new message and acquires the write lock. to free the write lock, you must call *MessageWriter.Close() the lock MUST be closed if and only if err == nil

func (*MessageStream) ReadFrom added in v0.3.17

func (m *MessageStream) ReadFrom(ctx context.Context, r io.Reader) error

ReadFrom calls io.Copy within the semaphore, then calls flush

type MessageStreamer added in v0.3.17

type MessageStreamer interface {
	NewMessage(ctx context.Context) (*MessageWriter, error)
}

type MessageWriter added in v0.3.17

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

func (*MessageWriter) Close added in v0.3.17

func (m *MessageWriter) Close() error

close must be called when you are done writing the message. it releases the write lock

func (*MessageWriter) Field added in v0.3.17

func (m *MessageWriter) Field(name string, value json.RawMessage) error

func (*MessageWriter) Params added in v0.3.17

func (m *MessageWriter) Params() (io.Writer, error)

Params returns a writer that writes to a params field

func (*MessageWriter) Result added in v0.3.17

func (m *MessageWriter) Result() (io.WriteCloser, error)

Result returns a writer that writes to a result field

type Middleware

type Middleware = func(Handler) Handler

type Middlewares

type Middlewares []Middleware

Middlewares type is a slice of standard middleware handlers with methods to compose middleware chains and Handler's.

func Chain

func Chain(middlewares ...func(Handler) Handler) Middlewares

Chain returns a Middlewares type from a slice of middleware handlers.

func (Middlewares) Handler

func (mws Middlewares) Handler(h Handler) Handler

Handler builds and returns a Handler from the chain of middlewares, with `h Handler` as the final handler.

func (Middlewares) HandlerFunc

func (mws Middlewares) HandlerFunc(h HandlerFunc) Handler

HandlerFunc builds and returns a Handler from the chain of middlewares, with `h Handler` as the final handler.

type Mounter

type Mounter interface {
	Mount(Middleware)
}

type Notifier

type Notifier interface {
	Notify(ctx context.Context, method string, params any) error
}

type PeerInfo

type PeerInfo struct {
	// Transport is name of the protocol used by the client.
	Transport string

	// Address of client. This will usually contain the IP address and port.
	RemoteAddr string

	// Additional information for HTTP and WebSocket connections.
	HTTP *http.Request `json:"-"`
}

type Reader

type Reader interface {
	// gets the peer info
	PeerInfo() PeerInfo
	// reads a batch of messages
	ReadBatch(ctx context.Context) (msgs []*Message, batch bool, err error)
	// closes the connection
	Close() error
}

Reader can write JSON messages to its underlying connection Implementations must be safe for concurrent use

type ReaderWriter

type ReaderWriter interface {
	Reader
	Writer
}

ReaderWriter represents a single stream this stream can be used to send/receive an arbitrary amount of requests and notifications

type Request

type Request struct {
	ID         *ID                        `json:"id,omitempty"`
	Method     string                     `json:"method,omitempty"`
	Params     json.RawMessage            `json:"params,omitempty"`
	Peer       PeerInfo                   `json:"-"`
	Extensions map[string]json.RawMessage `json:"-"`
	// contains filtered or unexported fields
}

func NewRawRequest

func NewRawRequest(ctx context.Context, id *ID, method string, params json.RawMessage) (r *Request)

func NewRequest

func NewRequest(ctx context.Context, id *ID, method string, params any) (r *Request, err error)

NewRequest makes a new request

func (*Request) Context

func (r *Request) Context() context.Context

func (Request) MarshalJSON added in v0.3.18

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

func (*Request) WithContext

func (r *Request) WithContext(ctx context.Context) *Request

type ResponseWriter

type ResponseWriter interface {
	Send(v any, err error) error
	Notify(method string, v any) error
}

http.ResponseWriter interface, but for jrpc

type ResultWriter added in v0.3.17

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

func (*ResultWriter) Close added in v0.3.17

func (m *ResultWriter) Close() error

func (*ResultWriter) Write added in v0.3.17

func (m *ResultWriter) Write(p []byte) (n int, err error)

type StreamingResponseWriter added in v0.3.17

type StreamingResponseWriter interface {
	ResponseWriter
	SendStream(func(MessageStreamer) error) error
	NotifyStream(func(MessageStreamer) error) error
}

type Writer

type Writer interface {
	// write json blob to stream
	io.Writer
	Flush() error
	// Closed returns a channel which is closed when the connection is closed.
	Closed() <-chan struct{}
}

Writer can write bytes messages to their underlying connection. Implementations must be safe for concurrent use.

Jump to

Keyboard shortcuts

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