rpc

package
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: Apache-2.0 Imports: 15 Imported by: 1

Documentation

Index

Constants

View Source
const (

	// Standard JSON-RPC 2.0 Codes
	ParseError     = -32700
	InvalidRequest = -32600
	MethodNotFound = -32601
	InvalidParams  = -32602
	InternalError  = -32603
)

Standard JSON-RPC 2.0 Error Codes

Variables

View Source
var ErrMethodNotFound = &JsonRPCerror{
	Code:    MethodNotFound,
	Message: "Method not found",
}
View Source
var ErrUnhandledMethod = errors.New(
	errors.UnhandledMethodErr,
	"unhandled method",
	"p2p.rpc.delegate",
)
View Source
var StdError = map[int]string{
	ParseError:     "Parse error",
	InvalidRequest: "Invalid Request",
	MethodNotFound: "Method not found",
	InvalidParams:  "Invalid params",
	InternalError:  "Internal error",
}

Functions

This section is empty.

Types

type AuthParams

type AuthParams struct {
	Username string `json:"username,omitempty"`
	Password string `json:"password,omitempty"`
	Token    string `json:"token,omitempty"`
}

type AuthResult

type AuthResult struct {
	Status   string `json:"status"`
	Token    string `json:"token,omitempty"`
	Username string `json:"username,omitempty"`
}

type BatchItem added in v1.0.2

type BatchItem struct {
	Method string
	Params any
	Result any // Pointer to the target struct for the result
}

BatchItem represents a single call within a batch.

type DefaultNexDelegate added in v1.0.2

type DefaultNexDelegate struct {
	Authenticator UserAuthenticator
	// contains filtered or unexported fields
}

DefaultNexDelegate provides a base implementation. Custom delegates can embed this struct and only need to override the required methods.

func (*DefaultNexDelegate) OnError added in v1.0.2

func (d *DefaultNexDelegate) OnError(peer *Peer, err error)

func (*DefaultNexDelegate) OnNotification added in v1.0.2

func (d *DefaultNexDelegate) OnNotification(ctx context.Context, peer *Peer, method string, params []byte)

func (*DefaultNexDelegate) OnPeerConnected added in v1.0.2

func (d *DefaultNexDelegate) OnPeerConnected(peer *Peer)

func (*DefaultNexDelegate) OnPeerDisconnected added in v1.0.2

func (d *DefaultNexDelegate) OnPeerDisconnected(peer *Peer, err error)

func (*DefaultNexDelegate) OnRequest added in v1.0.2

func (d *DefaultNexDelegate) OnRequest(ctx context.Context, peer *Peer, method string, params []byte) (any, error)

func (*DefaultNexDelegate) SetAuthenticator added in v1.0.4

func (d *DefaultNexDelegate) SetAuthenticator(auth UserAuthenticator)

func (*DefaultNexDelegate) ValidatePeer added in v1.0.2

func (d *DefaultNexDelegate) ValidatePeer(peer *Peer) bool

type DummyAuthenticator

type DummyAuthenticator struct{}

Default/Fallback Provider (for Demos or Tests)

func (*DummyAuthenticator) Authenticate

func (d *DummyAuthenticator) Authenticate(ctx context.Context, username, password string) bool

type JsonRPCerror

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

func NewRPCErrorFromNexError

func NewRPCErrorFromNexError(code int, nexErr *errors.Error) *JsonRPCerror

NewRPCErrorFromNexError converts a nexutils/errors.Error into a JsonRPCerror. The nexutils error object is cleanly included in the 'Data' field.

func (*JsonRPCerror) Error added in v1.0.2

func (e *JsonRPCerror) Error() string

type JsonRPCrequest

type JsonRPCrequest struct {
	JSONRPC string          `json:"jsonrpc"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
	ID      json.RawMessage `json:"id,omitempty"`
}

func (*JsonRPCrequest) IsResponse

func (req *JsonRPCrequest) IsResponse() bool

IsResponse checks whether it is a JSON-RPC response to a request of its own.

func (*JsonRPCrequest) UnmarshalParams

func (req *JsonRPCrequest) UnmarshalParams(v any) error

UnmarshalParams is a convenient helper method for parsing JSON-RPC parameters directly into a target struct or variable.

type JsonRPCresponse

type JsonRPCresponse struct {
	JSONRPC string          `json:"jsonrpc"`
	Result  any             `json:"result,omitempty"`
	Error   *JsonRPCerror   `json:"error,omitempty"`
	Method  string          `json:"method,omitempty"`
	ID      json.RawMessage `json:"id,omitempty"`
}

type ManagedClient

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

ManagedClient manages a P2P connection, including auto-reconnect and session handling.

func NewManagedClient

func NewManagedClient(node *Node, targetURL string, cfg ReconnectConfig) *ManagedClient

func (*ManagedClient) Call

func (mc *ManagedClient) Call(ctx context.Context, method string, params any, resultTarget any) *JsonRPCerror

Call forwards calls only when the connection is fully ready.

func (*ManagedClient) CallBatch added in v1.0.2

func (mc *ManagedClient) CallBatch(ctx context.Context, items []BatchItem) []*JsonRPCerror

CallBatch executes multiple RPC calls as a bundled batch via the ManagedClient.

func (*ManagedClient) Close

func (mc *ManagedClient) Close()

Close closes permanently terminates the client.

func (*ManagedClient) GetPeer

func (mc *ManagedClient) GetPeer() *Peer

GetPeer returns the current peer (or nil).

func (*ManagedClient) IsClosed

func (mc *ManagedClient) IsClosed() bool

func (*ManagedClient) IsReady

func (mc *ManagedClient) IsReady() bool

func (*ManagedClient) SetCredentials

func (mc *ManagedClient) SetCredentials(username, password string)

SetCredentials stores access credentials for automatic login and re-authentication processes.

func (*ManagedClient) Start

func (mc *ManagedClient) Start()

"Start" initiates the connection and the monitoring loop in the background.

type NexDelegate added in v1.0.2

type NexDelegate interface {
	// --- Lifecycle Hooks ---
	// ValidatePeer is called during the incoming handshake.
	// Returns false to reject the connection immediately (e.g., auth error).
	ValidatePeer(peer *Peer) bool

	//OnPeerConnected is called after a successful handshake.
	OnPeerConnected(peer *Peer)

	// OnPeerDisconnected is called when the connection is disconnected.
	OnPeerDisconnected(peer *Peer, err error)

	// --- Message / RPC Handling ---
	// OnRequest processes incoming RPC requests.
	OnRequest(ctx context.Context, peer *Peer, method string, params []byte) (any, error)

	// OnNotification processes incoming one-way messages (without a response).
	OnNotification(ctx context.Context, peer *Peer, method string, params []byte)

	// --- Error Handling ---
	// OnError catches protocol or transport errors.
	OnError(peer *Peer, err error)
}

P2PDelegate defines the behavior and hooks for a P2P node.

type Node

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

func NewNode

func NewNode(opts Options) *Node

NewNode creates a node with the specified options.

func (*Node) Broadcast

func (n *Node) Broadcast(method string, params any)

Broadcast sends a notification signal to ALL connected peers.

func (*Node) BroadcastAuthorized

func (n *Node) BroadcastAuthorized(method string, params any)

BroadcastAuthorized sends a notification signal ONLY to authenticated peers.

func (*Node) BroadcastFilter

func (n *Node) BroadcastFilter(method string, params any, filter PeerFilter)

BroadcastFilter sends a notification signal to all peers to which the filter applies.

func (*Node) BroadcastToUsers

func (n *Node) BroadcastToUsers(method string, params any, usernames []string)

BroadcastToUsers sends a notification signal to a specific list of usernames.

func (*Node) ConnectToPeer

func (n *Node) ConnectToPeer(targetURL string) (*Peer, error)

func (*Node) ConnectWithAutoReconnect

func (n *Node) ConnectWithAutoReconnect(targetURL string, cfg ReconnectConfig) *ManagedClient

ConnectWithAutoReconnect creates a ManagedClient that autonomously connects, authenticates, and manages reconnections in the background.

func (*Node) Start

func (n *Node) Start() error

func (*Node) Stop

func (n *Node) Stop() error

type Options

type Options struct {
	Addr              string
	HeartbeatInterval time.Duration
	ShutdownDelay     time.Duration
	WriteReadLimit    int64
	Delegate          NexDelegate
}

type Peer

type Peer struct {
	ID   string
	Role PeerRole
	// contains filtered or unexported fields
}

func NewPeer

func NewPeer(conn *websocket.Conn, remoteAddr string) *Peer

func (*Peer) Call

func (p *Peer) Call(ctx context.Context, method string, params any, resultTarget any) *JsonRPCerror

Call sends a request to the peer and waits synchronously for the response.

func (*Peer) CallBatch added in v1.0.2

func (p *Peer) CallBatch(ctx context.Context, items []BatchItem) []*JsonRPCerror

CallBatch sends multiple RPC calls as a single JSON array.

func (*Peer) Close

func (p *Peer) Close()

func (*Peer) IsAuthorized

func (p *Peer) IsAuthorized() bool

func (*Peer) Notify

func (p *Peer) Notify(method string, params any) error

Notify sends a message without an ID to the peer (fire-and-forget; no response expected).

func (*Peer) RemoteAddr

func (p *Peer) RemoteAddr() string

func (*Peer) Send

func (p *Peer) Send(msg any)

--- Helper & State ---

func (*Peer) SetAuth

func (p *Peer) SetAuth(username, token string, ttl time.Duration)

func (*Peer) Start

func (p *Peer) Start()

func (*Peer) Username

func (p *Peer) Username() string

type PeerFilter

type PeerFilter func(p *Peer) bool

Broadcast functionality PeerFilter is a function that determines whether a peer should receiv e a signal.

type PeerRole

type PeerRole int
const (
	RoleInbound PeerRole = iota
	RoleOutbound
)

type ReconnectConfig

type ReconnectConfig struct {
	InitialInterval time.Duration
	MaxInterval     time.Duration
	Multiplier      float64
	MaxRetries      int // 0 = infinite
}

type SessionData

type SessionData struct {
	Username string
	Expires  time.Time
}

type UserAuthenticator

type UserAuthenticator interface {
	// Authenticate checks the username and password.
	// Returns true if the credentials are correct.
	Authenticate(ctx context.Context, username, password string) bool
}

UserAuthenticator must be implemented by every user management system.

Jump to

Keyboard shortcuts

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