codec

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2023 License: Unlicense Imports: 11 Imported by: 0

Documentation

Index

Constants

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

Version represents a JSON-RPC version.

Variables

View Source
var (
	ErrIllegalExtraField = errors.New("invalid extra field")
)
View Source
var Null = json.RawMessage("null")

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 EncodeError

func EncodeError(enc *jx.Encoder, err error) error

func IsBatchMessage

func IsBatchMessage(raw json.RawMessage) bool

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

func MarshalMessage

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

func NewNull

func NewNull() json.RawMessage

func UnmarshalMessage

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

func WrapErr added in v0.2.22

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

Types

type BatchCaller

type BatchCaller interface {
	BatchCall(ctx context.Context, b ...*BatchElem) error
}

type BatchElem

type BatchElem struct {
	Method string
	Params any

	IsNotification bool

	// The result is unmarshaled into this field. Result must be set to a
	// non-nil pointer value of the desired type, otherwise the response will be
	// discarded.
	Result any
	// Error is set if the server returns an error for this request, or if
	// unmarshaling into Result fails. It is not set for I/O errors.
	Error error
}

BatchElem is an element in a batch request.

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 Closeder

type Closeder interface {
	Closed() <-chan struct{}
}

type Conn

type Conn interface {
	Doer
	BatchCaller

	Mounter

	io.Closer
	Closeder
}

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) BatchCall

func (d *DummyClient) BatchCall(ctx context.Context, b ...*BatchElem) error

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 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)

type HttpInfo

type HttpInfo struct {
	// Protocol version, i.e. "HTTP/1.1". This is not set for WebSocket.
	Version string
	// Header values sent by the client.
	UserAgent string
	Origin    string
	Host      string

	Headers http.Header
}

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 Message

type Message struct {
	ID     *ID             `json:"id,omitempty"`
	Method string          `json:"method,omitempty"`
	Params json.RawMessage `json:"params,omitempty"`
	Result json.RawMessage `json:"result,omitempty"`
	Error  error           `json:"error,omitempty"`

	ExtraFields []RequestField `json:"-"`
}

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) SetExtraField

func (m *Message) SetExtraField(name string, v any) error

func (*Message) String

func (msg *Message) String() string

func (*Message) UnmarshalJSON

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

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

	// Addditional information for HTTP and WebSocket connections.
	HTTP HttpInfo
}

type Reader

type Reader interface {
	// gets the peer info
	PeerInfo() PeerInfo
	// json.RawMessage can be an array of requests. if it is, then it is a batch request
	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 {
	Peer PeerInfo `json:"-"`

	Message
	// 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 NewRequestFromMessage

func NewRequestFromMessage(ctx context.Context, message *Message) (r *Request)

func (*Request) Context

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

func (Request) MarshalJSON

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

func (*Request) Msg

func (r *Request) Msg() Message

func (*Request) ParamArray

func (r *Request) ParamArray(a ...any) error

func (*Request) Remote

func (r *Request) Remote() string

func (*Request) UnmarshalJSON

func (r *Request) UnmarshalJSON(xs []byte) error

func (*Request) WithContext

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

type RequestField

type RequestField struct {
	Name  string
	Value json.RawMessage
}

RequestField is an idea borrowed from sourcegraphs implementation.

type ResponseWriter

type ResponseWriter interface {
	Send(v any, err error) error
	Header() http.Header

	SetExtraField(k string, v any) error

	Notify(method string, v any) error
}

http.ResponseWriter interface, but for jrpc

type StreamingConn

type StreamingConn interface {
	Conn
	Notifier
}

func StreamingConnFromContext

func StreamingConnFromContext(ctx context.Context) (StreamingConn, bool)

type Writer

type Writer interface {
	// write json blob to stream
	Send(context.Context, json.RawMessage) error
	// Closed returns a channel which is closed when the connection is closed.
	Closed() <-chan struct{}
	// RemoteAddr returns the peer address of the connection.
	RemoteAddr() string
}

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