rpc

package
v0.2300.5 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2023 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package rpc provides tools for building simple RPC protocols via libp2p.

Index

Constants

View Source
const (
	// RequestWriteDeadline is the maximum amount of time that can be spent on writing a request.
	RequestWriteDeadline = 5 * time.Second
	// RequestReadDeadline is the maximum amount of time that can be spent on reading a request.
	RequestReadDeadline = 5 * time.Second
	// DefaultCallRetryInterval is the default call retry interval for calls which explicitly enable
	// retries by setting the WithMaxRetries option to a non-zero value. It can be overridden by
	// using the WithRetryInterval call option.
	DefaultCallRetryInterval = 1 * time.Second
	// DefaultParallelRequests is the default number of parallel requests that can be mande
	// when calling multiple peers.
	DefaultParallelRequests = 5
)
View Source
const (
	SuccessConnManagerPeerTagValue = 20
	ShuffledBestPeerCount          = 5
)
View Source
const (
	RequestHandleTimeout  = 60 * time.Second
	ResponseWriteDeadline = 60 * time.Second
)
View Source
const ModuleName = "p2p/rpc"

ModuleName is a unique module name for the P2P RPC module.

Variables

View Source
var (
	// ErrMethodNotSupported is an error raised when a given method is not supported.
	ErrMethodNotSupported = errors.New(ModuleName, 1, "rpc: method not supported")

	// ErrBadRequest is an error raised when a given request is malformed.
	ErrBadRequest = errors.New(ModuleName, 2, "rpc: bad request")
)

Functions

func PeerAddrInfoFromContext

func PeerAddrInfoFromContext(ctx context.Context) (peer.AddrInfo, bool)

PeerAddrInfoFromContext looks up the peer addr info value in the given context.

func PeerIDFromContext

func PeerIDFromContext(ctx context.Context) (core.PeerID, bool)

PeerIDFromContext looks up the peer ID value in the given context.

func WithPeerAddrInfo

func WithPeerAddrInfo(parent context.Context, peerAddrInfo peer.AddrInfo) context.Context

WithPeerAddrInfo creates a new context with the peer addr info value set.

Types

type AggregateFunc

type AggregateFunc func(rsp interface{}, pf PeerFeedback) bool

AggregateFunc returns a result aggregation function.

The function is passed the response and PeerFeedback instance. If the function returns true, the client will continue to call other peers. If it returns false, processing will stop.

type BestPeersOption

type BestPeersOption func(opts *BestPeersOptions)

BestPeersOption is a per-call option setter.

func WithLimitPeers

func WithLimitPeers(peers []core.PeerID) BestPeersOption

WithLimitPeers configures the peers that the call should be limited to.

type BestPeersOptions

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

BestPeersOptions are per-call options.

func NewBestPeersOptions

func NewBestPeersOptions(opts ...BestPeersOption) *BestPeersOptions

NewBestPeersOptions creates options using default and given values.

type CallMultiOption

type CallMultiOption func(opts *CallMultiOptions)

CallMultiOption is a per-multicall option setter.

func WithAggregateFn

func WithAggregateFn(fn AggregateFunc) CallMultiOption

WithAggregateFn configures the response aggregation function to use.

func WithMaxParallelRequests

func WithMaxParallelRequests(n uint) CallMultiOption

WithMaxParallelRequests configures the maximum number of parallel requests to make.

func WithMaxPeerResponseTimeMulti

func WithMaxPeerResponseTimeMulti(d time.Duration) CallMultiOption

WithMaxPeerResponseTimeMulti configures the maximum response time for a peer.

type CallMultiOptions

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

CallMultiOptions are per-multicall options.

func NewCallMultiOptions

func NewCallMultiOptions(opts ...CallMultiOption) *CallMultiOptions

NewCallMultiOptions creates options using default and given values.

type CallOption

type CallOption func(opts *CallOptions)

CallOption is a per-call option setter.

func WithMaxPeerResponseTime

func WithMaxPeerResponseTime(d time.Duration) CallOption

WithMaxPeerResponseTime configures the maximum response time for a peer.

func WithMaxRetries

func WithMaxRetries(maxRetries uint64) CallOption

WithMaxRetries configures the maximum number of retries to use for the call.

func WithRetryInterval

func WithRetryInterval(retryInterval time.Duration) CallOption

WithRetryInterval configures the retry interval to use for the call.

func WithValidationFn

func WithValidationFn(fn ValidationFunc) CallOption

WithValidationFn configures the response validation function to use for the call.

When the function is called, the decoded response value will be set.

type CallOptions

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

CallOptions are per-call options.

func NewCallOptions

func NewCallOptions(opts ...CallOption) *CallOptions

NewCallOptions creates options using default and given values.

type Client

type Client interface {
	// Call attempts to route the given RPC method call to the given peer. It's up to the caller
	// to provide only connected peers that support the protocol.
	//
	// On success it returns a PeerFeedback instance that should be used by the caller to provide
	// deferred feedback on whether the peer is any good or not. This will help guide later choices
	// when routing calls.
	Call(
		ctx context.Context,
		peer core.PeerID,
		method string,
		body, rsp interface{},
		opts ...CallOption,
	) (PeerFeedback, error)

	// CallOne attempts to route the given RPC method call to one of the peers in the list in
	// a sequential order. It's up to the caller to prioritize peers and to provide only
	// connected peers that support the protocol.
	//
	// On success it returns a PeerFeedback instance that should be used by the caller to provide
	// deferred feedback on whether the peer is any good or not. This will help guide later choices
	// when routing calls.
	CallOne(
		ctx context.Context,
		peers []core.PeerID,
		method string,
		body, rsp interface{},
		opts ...CallOption,
	) (PeerFeedback, error)

	// CallMulti routes the given RPC method call to multiple (possibly all) peers in the list in
	// a sequential order. It's up to the caller to prioritize peers and use only peers that support
	// the protocol.
	//
	// It returns all successfully retrieved results and their corresponding PeerFeedback instances.
	CallMulti(
		ctx context.Context,
		peers []core.PeerID,
		method string,
		body, rspTyp interface{},
		opts ...CallMultiOption,
	) ([]interface{}, []PeerFeedback, error)

	// Close closes all connections to the given peer.
	Close(peerID core.PeerID) error

	// RegisterListener subscribes the listener to the client notification events.
	// If the listener is already registered this is a noop operation.
	RegisterListener(l ClientListener)

	// UnregisterListener unsubscribes the listener from the client notification events.
	// If the listener is not registered this is a noop operation.
	UnregisterListener(l ClientListener)
}

Client is an RPC client for a given protocol.

func NewClient

func NewClient(h host.Host, p protocol.ID) Client

NewClient creates a new RPC client for the given protocol.

type ClientListener

type ClientListener interface {
	// RecordSuccess is called on a successful protocol interaction with a peer.
	RecordSuccess(peerID core.PeerID, latency time.Duration)

	// RecordFailure is called on an unsuccessful protocol interaction with a peer.
	RecordFailure(peerID core.PeerID, latency time.Duration)

	// RecordBadPeer is called when a malicious protocol interaction with a peer is detected.
	RecordBadPeer(peerID core.PeerID)
}

ClientListener is an interface for an object wishing to receive notifications from the client.

type Error

type Error struct {
	Module  string `json:"module,omitempty"`
	Code    uint32 `json:"code,omitempty"`
	Message string `json:"message,omitempty"`
}

Error is a message body representing an error.

func (Error) String

func (e Error) String() string

String returns a string representation of this error.

type P2P

type P2P interface {
	// BlockPeer blocks a specific peer from being used by the local node.
	BlockPeer(peerID core.PeerID)

	// RegisterProtocol starts tracking and managing peers that support given protocol.
	RegisterProtocol(p core.ProtocolID, min int, total int)

	// Host returns the P2P host.
	Host() core.Host
}

P2P is a P2P interface that the RPC protocols need.

type PeerAdded

type PeerAdded struct{}

PeerAdded is an event emitted when a new peer is added.

type PeerFeedback

type PeerFeedback interface {
	// RecordSuccess records a successful protocol interaction with the given peer.
	RecordSuccess()

	// RecordFailure records an unsuccessful protocol interaction with the given peer.
	RecordFailure()

	// RecordBadPeer records a malicious protocol interaction with the given peer.
	//
	// The peer will be ignored during peer selection.
	RecordBadPeer()

	// PeerID returns the id of the peer.
	PeerID() core.PeerID
}

PeerFeedback is an interface for providing deferred peer feedback after an outcome is known.

func NewNopPeerFeedback

func NewNopPeerFeedback() PeerFeedback

NewNopPeerFeedback creates a no-op peer feedback instance.

type PeerManager

type PeerManager interface {
	// AddPeer tries to add the given peer to the peer manager.
	//
	// Peer is only added in case it supports the specified protocol.
	AddPeer(peerID core.PeerID)

	// RemovePeer unconditionally removes the peer from the peer manager.
	RemovePeer(peerID core.PeerID)

	// RecordSuccess records a successful protocol interaction with the given peer.
	RecordSuccess(peerID core.PeerID, latency time.Duration)

	// RecordFailure records an unsuccessful protocol interaction with the given peer.
	RecordFailure(peerID core.PeerID, latency time.Duration)

	// RecordBadPeer records a malicious protocol interaction with the given peer.
	//
	// The peer will be ignored during peer selection.
	RecordBadPeer(peerID core.PeerID)

	// GetBestPeers returns a set of peers sorted by the probability that they will be able to
	// answer our requests the fastest with some randomization.
	GetBestPeers(opts ...BestPeersOption) []core.PeerID

	// WatchUpdates returns a channel that produces a stream of messages on peer updates.
	WatchUpdates() (<-chan *PeerUpdate, pubsub.ClosableSubscription, error)
}

PeerManager is an interface for keeping track of peer statistics in order to guide peer selection when performing RPC requests.

func NewPeerManager

func NewPeerManager(p2p P2P, protocolID protocol.ID, opts ...PeerManagerOption) PeerManager

NewPeerManager creates a new peer manager for the given protocol.

type PeerManagerOption

type PeerManagerOption func(opts *PeerManagerOptions)

PeerManagerOption is a peer manager option setter.

func WithStickyPeers

func WithStickyPeers(enabled bool) PeerManagerOption

WithStickyPeers configures the sticky peers feature.

When enabled, the last successful peer will be stuck and reused on subsequent selections of the best peers until the peer is deemed bad.

type PeerManagerOptions

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

PeerManagerOptions are peer manager options.

type PeerRemoved

type PeerRemoved struct {
	// BadPeer indicates that the peer was removed due to being recorded as a bad peer.
	BadPeer bool
}

PeerRemoved is an event emitted when a peer is removed.

type PeerUpdate

type PeerUpdate struct {
	ID core.PeerID

	PeerAdded   *PeerAdded
	PeerRemoved *PeerRemoved
}

PeerUpdate is a peer update event.

type Request

type Request struct {
	// Method is the name of the method.
	Method string `json:"method"`
	// Body is the method-specific body.
	Body cbor.RawMessage `json:"body"`
}

Request is a request sent by the client.

type Response

type Response struct {
	// Ok is the method-specific response in case of success.
	Ok cbor.RawMessage `json:"ok,omitempty"`
	// Error is an error response in case of failure.
	Error *Error `json:"error,omitempty"`
}

Response is a response to a previously sent request.

type Server

type Server interface {
	// Protocol returns the unique protocol identifier.
	Protocol() protocol.ID

	// HandleStream handles an incoming stream.
	HandleStream(stream network.Stream)
}

Server is an RPC server for the given protocol.

func NewServer

func NewServer(protocolID protocol.ID, srv Service) Server

NewServer creates a new RPC server for the given protocol.

type Service

type Service interface {
	// HandleRequest handles an incoming RPC request.
	HandleRequest(ctx context.Context, method string, body cbor.RawMessage) (interface{}, error)
}

Service is an RPC service implementation.

type ValidationFunc

type ValidationFunc func(pf PeerFeedback) error

ValidationFunc is a call response validation function.

Jump to

Keyboard shortcuts

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