jrpc

package module
v0.0.0-...-5fdd8c6 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2019 License: MIT Imports: 15 Imported by: 0

README

jrpc

Documentation

Overview

Package jrpc provides JSON-RPC 2.0 compatible APIs

Index

Constants

This section is empty.

Variables

View Source
var (
	// UnknownID represents explicit but null ID. Ex) {..."id": null}
	UnknownID = ID{
				// contains filtered or unexported fields
	}

	// NoID represents omitted ID
	NoID = ID{}
)
View Source
var ErrNilData = errors.New("jrpc: Error.Data is nil")

ErrNilData is

View Source
var ErrNilParams = errors.New("jrpc: Request.Params is nil")

ErrNilParams is

View Source
var ErrNilResult = errors.New("jrpc: Response.Result is nil")

ErrNilResult is

Functions

func ServeStream

func ServeStream(ctx context.Context, stream io.ReadWriter, repository *Core) error

ServeStream is

Types

type BatchRequest

type BatchRequest []*Request

BatchRequest is

func (BatchRequest) Add

func (reqs BatchRequest) Add(req ...*Request)

Add appends

func (BatchRequest) MarshalJSON

func (reqs BatchRequest) MarshalJSON() (b []byte, err error)

MarshalJSON implements json.Marshaler

type BatchResponse

type BatchResponse []*Response

BatchResponse is

func (BatchResponse) GetFromID

func (resps BatchResponse) GetFromID(id ID) (*Response, bool)

GetFromID is

func (BatchResponse) Map

func (resps BatchResponse) Map() map[ID]*Response

Map makes without UnknownID and NoID

type Buffer

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

Buffer is a thin wrapper around a byte slice. It's intended to be pooled, so the only way to construct one is via a Pool.

func (*Buffer) AppendBool

func (b *Buffer) AppendBool(v bool)

AppendBool appends a bool to the underlying buffer.

func (*Buffer) AppendByte

func (b *Buffer) AppendByte(v byte)

AppendByte writes a single byte to the Buffer.

func (*Buffer) AppendFloat

func (b *Buffer) AppendFloat(f float64, bitSize int)

AppendFloat appends a float to the underlying buffer. It doesn't quote NaN or +/- Inf.

func (*Buffer) AppendInt

func (b *Buffer) AppendInt(i int64)

AppendInt appends an integer to the underlying buffer (assuming base 10).

func (*Buffer) AppendString

func (b *Buffer) AppendString(s string)

AppendString writes a string to the Buffer.

func (*Buffer) AppendUint

func (b *Buffer) AppendUint(i uint64)

AppendUint appends an unsigned integer to the underlying buffer (assuming base 10).

func (*Buffer) Bytes

func (b *Buffer) Bytes() []byte

Bytes returns a mutable reference to the underlying byte slice.

func (*Buffer) Free

func (b *Buffer) Free()

Free returns the Buffer to its Pool.

Callers must not retain references to the Buffer after calling Free.

func (*Buffer) Len

func (b *Buffer) Len() int

Len returns the length of the underlying byte slice.

func (*Buffer) Read

func (b *Buffer) Read(p []byte) (int, error)

Read implements io.Reader.

func (*Buffer) Reset

func (b *Buffer) Reset()

Reset resets the underlying byte slice. Subsequent writes re-use the slice's backing array.

func (*Buffer) String

func (b *Buffer) String() string

String returns a string copy of the underlying byte slice.

func (*Buffer) Write

func (b *Buffer) Write(bs []byte) (int, error)

Write implements io.Writer.

type Client

type Client struct {
	Transport ClientTransport
	// contains filtered or unexported fields
}

Client is

func NewClient

func NewClient(t ClientTransport, opts ...ClientOption) *Client

NewClient is

func (*Client) Batch

func (c *Client) Batch(ctx context.Context, registerer func(RegisterFunc), unknownErrs *[]*Error) error

Batch is result is nil -> notify jrpcErr is nil -> mere ignorant

func (*Client) Call

func (c *Client) Call(ctx context.Context, req *Request) (*Response, error)

Call is レスポンスを待つかどうか、ClientTransportの設定次第 タイムアウトは、http.Clientのものも使用できるし、contextのDeadlineでも

func (*Client) CallBatch

func (c *Client) CallBatch(ctx context.Context, reqs BatchRequest) (BatchResponse, error)

CallBatch is レスポンスを待つかどうか、ClientTransportの設定次第

func (*Client) Close

func (c *Client) Close() error

Close closing connection

func (*Client) Do

func (c *Client) Do(ctx context.Context, method string, params, result interface{}) error

Do is shorthand, use IDFactory レスポンスを待つかどうか、ClientTransportの設定次第

func (*Client) Notify

func (c *Client) Notify(ctx context.Context, method string, params interface{}) error

Notify is 戻り値について同様 レスポンス可能性を完全に無視する(何か返ってきていても無視する)

func (*Client) NotifyWithError

func (c *Client) NotifyWithError(ctx context.Context, method string, params interface{}) error

NotifyWithError is レスポンス可能性を積極的に拾いに行くが、最終的にはClientTransportの設定次第

type ClientOption

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

ClientOption is

func WithIDFactory

func WithIDFactory(factory IDFactory) ClientOption

WithIDFactory is

type ClientTransport

type ClientTransport interface {
	SendRequest(ctx context.Context, r io.Reader) error
	ReceivedResponse(ctx context.Context) (recv io.ReadCloser, updated, shouldClose bool, err error)
	Close() error
}

ClientTransport is

type Core

type Core struct {
	*MethodRepository
	// contains filtered or unexported fields
}

Core is

func NewRepository

func NewRepository(opts ...Option) *Core

NewRepository is

func (*Core) DoMethod

func (c *Core) DoMethod(ctx context.Context, req *Request, batch bool) (resp *Response, err error)

DoMethod is

func (*Core) Execute

func (c *Core) Execute(ctx context.Context, requests []*Request, batch bool) ([]*Response, error)

Execute is

func (*Core) Methods

func (c *Core) Methods() map[string]Metadata

Methods returns all registered method info

type Decoder

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

Decoder is

func NewDecoder

func NewDecoder(r io.Reader) *Decoder

NewDecoder is

func (*Decoder) Decode

func (d *Decoder) Decode(dst []*Request) (requests []*Request, batch bool, err error)

Decode is

func (*Decoder) DecodeContext

func (d *Decoder) DecodeContext(ctx context.Context, dst []*Request) ([]*Request, bool, error)

DecodeContext is

func (*Decoder) Err

func (d *Decoder) Err() error

Err is

func (*Decoder) Reset

func (d *Decoder) Reset(r io.Reader)

Reset not implemented yet

type EmptyClientOption

type EmptyClientOption struct{}

EmptyClientOption is xxx . It can be embedded in another structure to build custom options

type Encoder

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

Encoder is

func NewEncoder

func NewEncoder(dst io.Writer) *Encoder

NewEncoder is

func NewEncoderSize

func NewEncoderSize(dst io.Writer, bufSize int) *Encoder

NewEncoderSize is

func (*Encoder) Encode

func (enc *Encoder) Encode(resps []*Response, batch bool) error

Encode is

func (*Encoder) EncodeContext

func (enc *Encoder) EncodeContext(ctx context.Context, resps []*Response, batch bool) (err error)

EncodeContext is

func (*Encoder) Reset

func (enc *Encoder) Reset(dst io.Writer)

Reset is

type Error

type Error struct {
	Code    ErrorCode        `json:"code"`
	Message string           `json:"message"`
	Data    *json.RawMessage `json:"data"`
	// contains filtered or unexported fields
}

Error represents JSON-RPC error object. When a rpc call encounters an error, the Response Object MUST contain the error member with a value that is a Object with the following members:

code A Number that indicates the error type that occurred. This MUST be an integer.

message A String providing a short description of the error. The message SHOULD be limited to a concise single sentence.

data A Primitive or Structured value that contains additional information about the error. This may be omitted. The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.).

Either the result member or error member MUST be included, but both members MUST NOT be included.

func ErrInternal

func ErrInternal(err error) *Error

ErrInternal returns internal error.

func ErrInvalidParams

func ErrInvalidParams() *Error

ErrInvalidParams returns invalid params error.

func ErrInvalidRequest

func ErrInvalidRequest(err error) *Error

ErrInvalidRequest returns invalid request error.

func ErrMethodNotFound

func ErrMethodNotFound() *Error

ErrMethodNotFound returns method not found error.

func ErrParse

func ErrParse(err error) *Error

ErrParse returns parse error.

func FromError

func FromError(code ErrorCode, err error) *Error

FromError is

func NewError

func NewError(code ErrorCode, message string, data interface{}) (*Error, error)

NewError is

func UnmarshalParams

func UnmarshalParams(params *json.RawMessage, dst interface{}) *Error

UnmarshalParams decodes JSON-RPC Request params.

func (*Error) Cause

func (e *Error) Cause() error

Cause is

func (*Error) DecodeData

func (e *Error) DecodeData(v interface{}) error

DecodeData is

func (*Error) EncodeAndSetData

func (e *Error) EncodeAndSetData(v interface{}) error

EncodeAndSetData is

func (*Error) Error

func (e *Error) Error() string

func (*Error) MarshalJSON

func (e *Error) MarshalJSON() (b []byte, err error)

MarshalJSON implements json.Marshaler

type ErrorCode

type ErrorCode int

ErrorCode is

const (
	// ErrorCodeParse Invalid JSON was received by the server.
	// An error occurred on the server while parsing the JSON text.
	ErrorCodeParse ErrorCode = -32700
	// ErrorCodeInvalidRequest The JSON sent is not a valid Request object.
	ErrorCodeInvalidRequest ErrorCode = -32600
	// ErrorCodeMethodNotFound The method does not exist / is not available.
	ErrorCodeMethodNotFound ErrorCode = -32601
	// ErrorCodeInvalidParams Invalid method parameter(s).
	ErrorCodeInvalidParams ErrorCode = -32602
	// ErrorCodeInternal Internal JSON-RPC error.
	ErrorCodeInternal ErrorCode = -32603
)

type Handler

type Handler interface {
	ServeJSONRPC(ctx context.Context, params *json.RawMessage) (interface{}, *Error)
}

Handler is

type HandlerFunc

type HandlerFunc func(context.Context, *json.RawMessage) (interface{}, *Error)

HandlerFunc is

func (HandlerFunc) ServeJSONRPC

func (f HandlerFunc) ServeJSONRPC(ctx context.Context, params *json.RawMessage) (interface{}, *Error)

ServeJSONRPC is

type ID

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

ID represents "id" member of JSON-RPC object. An identifier established by the Client that MUST contain a String, Number, or NULL value if included. If it is not included it is assumed to be a notification. The value SHOULD normally not be Null and Numbers SHOULD NOT contain fractional parts

The Server MUST reply with the same value in the Response object if included. This member is used to correlate the context between the two objects.

func NewID

func NewID(v interface{}) ID

NewID is NoID is zero value

func (ID) Equals

func (id ID) Equals(v interface{}) bool

Equals is

func (ID) Float32

func (id ID) Float32() (float32, error)

Float32 is

func (ID) Float64

func (id ID) Float64() (float64, error)

Float64 is

func (ID) Int

func (id ID) Int() (int, error)

Int is

func (ID) Int64

func (id ID) Int64() (int64, error)

Int64 is

func (ID) MarshalJSON

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

MarshalJSON implements json.Marshaler

func (ID) String

func (id ID) String() string

String is

func (ID) Type

func (id ID) Type() string

Type returns number, string or unknown

func (ID) Uint

func (id ID) Uint() (uint, error)

Uint is

func (ID) Uint64

func (id ID) Uint64() (uint64, error)

Uint64 is

func (*ID) UnmarshalJSON

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

UnmarshalJSON implements json.Unmarshaler

type IDFactory

type IDFactory interface {
	CreateID() ID
	BatchIDFactory() IDFactory
}

IDFactory is

type Interceptor

type Interceptor func(context.Context, *json.RawMessage, *RequestInfo, Handler) (interface{}, *Error)

Interceptor is

type Interceptors

type Interceptors []Interceptor

Interceptors is

type Metadata

type Metadata struct {
	Handler          Handler     // raw handler
	InterceptorChain Interceptor // interceptor stack
	Params           interface{}
	Result           interface{}
}

Metadata is

type MethodRepository

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

MethodRepository is

func (*MethodRepository) Interceptors

func (mr *MethodRepository) Interceptors() Interceptors

Interceptors is

func (*MethodRepository) Namespace

func (mr *MethodRepository) Namespace(namespace string, assignFunc func(Repository))

Namespace is

func (*MethodRepository) Register

func (mr *MethodRepository) Register(method string, handler Handler, params, result interface{}) error

Register is

func (*MethodRepository) With

func (mr *MethodRepository) With(interceptors ...Interceptor)

With is

type Option

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

Option is

func WithDisableConcurrentCall

func WithDisableConcurrentCall() Option

WithDisableConcurrentCall is

func WithNamespaceSeparator

func WithNamespaceSeparator(sep byte) Option

WithNamespaceSeparator is namespaceSeparator used for join namespace. Default is comma.

func WithPanicHandler

func WithPanicHandler(panicHandler func(req *Request, recovered interface{})) Option

WithPanicHandler register panic handler function. Core always return Response object with Internal Error when panic occurred during call of JSON-RPC method. You can get detailed information of panic in your panicHandler. If you allow concurrent call of JSON-RPC method, panicHandler must be concurrent-safe.

type Pool

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

A Pool is a type-safe wrapper around a sync.Pool.

func NewPool

func NewPool() Pool

NewPool constructs a new Pool.

func (Pool) Get

func (p Pool) Get() *Buffer

Get retrieves a Buffer from the pool, creating one if necessary.

func (Pool) GetForBufferSlice

func (p Pool) GetForBufferSlice() *Buffer

GetForBufferSlice retrieves a Buffer from the pool and grow length up to its capacity.

type RandomIDFactory

type RandomIDFactory struct {
	Prefix            string
	Digits            int
	BatchPrefixDigits int
}

RandomIDFactory is

func (*RandomIDFactory) BatchIDFactory

func (rif *RandomIDFactory) BatchIDFactory() IDFactory

BatchIDFactory is

func (*RandomIDFactory) CreateID

func (rif *RandomIDFactory) CreateID() ID

CreateID makes

type RecoveredError

type RecoveredError struct {
	Request   *Request
	Recovered interface{}
}

RecoveredError is

func (*RecoveredError) Error

func (re *RecoveredError) Error() string

type RegisterFunc

type RegisterFunc func(method string, params, result interface{}, jrpcErr **Error) error

RegisterFunc is

type Repository

type Repository interface {
	Register(method string, handler Handler, params, result interface{}) error
	With(interceptors ...Interceptor)
	Interceptors() Interceptors
	Namespace(namespace string, fn func(Repository))
	// contains filtered or unexported methods
}

Repository is

type Request

type Request struct {
	Version string           `json:"jsonrpc"`
	Method  string           `json:"method"`
	Params  *json.RawMessage `json:"params"`
	ID      ID               `json:"id"`
	// contains filtered or unexported fields
}

Request represents JSON-RPC Request object. A rpc call is represented by sending a Request object to a Server. The Request object has the following members:

jsonrpc A String specifying the version of the JSON-RPC protocol. MUST be exactly "2.0".

method A String containing the name of the method to be invoked. Method names that begin with the word rpc followed by a period character (U+002E or ASCII 46) are reserved for rpc-internal methods and extensions and MUST NOT be used for anything else.

params A Structured value that holds the parameter values to be used during the invocation of the method. This member MAY be omitted.

id An identifier established by the Client that MUST contain a String, Number, or NULL value if included. If it is not included it is assumed to be a notification. The value SHOULD normally not be Null and Numbers SHOULD NOT contain fractional parts

The Server MUST reply with the same value in the Response object if included. This member is used to correlate the context between the two objects.

func Calibrate

func Calibrate(requests []*Request, capacity int) []*Request

Calibrate is utility

func NewRequest

func NewRequest(method string, params interface{}, id ID) (*Request, error)

NewRequest is

func (*Request) DecodeParams

func (req *Request) DecodeParams(v interface{}) error

DecodeParams is

func (*Request) EncodeAndSetParams

func (req *Request) EncodeAndSetParams(v interface{}) error

EncodeAndSetParams is

func (*Request) MarshalJSON

func (req *Request) MarshalJSON() (b []byte, err error)

MarshalJSON implements json.Marshaler

func (*Request) Reader

func (req *Request) Reader() (io.Reader, error)

Reader is.

type RequestInfo

type RequestInfo struct {
	MethodFullName string // 機能を定義する側は、自身がどうマウントされたのかは知り得ないため、有用
	IsBatch        bool   // バッチリクエストかどうかの情報が、何に使えるのか。ロギング?
	ID             ID

} // params は、json.Compactを使おう

RequestInfo is

type Response

type Response struct {
	Version string           `json:"jsonrpc"`
	Result  *json.RawMessage `json:"result"`
	Error   *Error           `json:"error"`
	ID      ID               `json:"id"`
}

Response represents JSON-RPC Response object. When a rpc call is made, the Server MUST reply with a Response, except for in the case of Notifications. The Response is expressed as a single JSON Object, with the following members:

jsonrpc A String specifying the version of the JSON-RPC protocol. MUST be exactly "2.0".

result This member is REQUIRED on success. This member MUST NOT exist if there was an error invoking the method. The value of this member is determined by the method invoked on the Server.

error This member is REQUIRED on error. This member MUST NOT exist if there was no error triggered during invocation. The value for this member MUST be an Object as defined in section 5.1.

id This member is REQUIRED. It MUST be the same as the value of the id member in the Request Object. If there was an error in detecting the id in the Request object (e.g. Parse error/Invalid Request), it MUST be Null.

Either the result member or error member MUST be included, but both members MUST NOT be included.

func (*Response) DecodeResult

func (resp *Response) DecodeResult(v interface{}) error

DecodeResult is

func (*Response) EncodeAndSetResult

func (resp *Response) EncodeAndSetResult(v interface{}) error

EncodeAndSetResult is

func (*Response) MarshalJSON

func (resp *Response) MarshalJSON() (b []byte, err error)

MarshalJSON implements json.Marshaler

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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