client

package
v3.10.0 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2025 License: MIT Imports: 27 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Actor

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

Actor defines a given actor name and kind. Kind is a string representation of the type within its package (e.g pkg/User)

func NewActor

func NewActor(kind string) *Actor

NewActor creates an instance of Actor

func (*Actor) Kind

func (x *Actor) Kind() string

Kind returns the actor kind

func (*Actor) Name

func (x *Actor) Name() string

Name returns the actor name

func (*Actor) WithName

func (x *Actor) WithName(name string) *Actor

WithName set the given name

type Balancer

type Balancer interface {
	// Set sets the balancer nodes pool
	Set(nodes ...*Node)
	// Next returns the appropriate weight-balanced node to use
	Next() *Node
}

Balancer helps locate the right node to channel Client request to

type BalancerStrategy

type BalancerStrategy int

BalancerStrategy defines the strategy used by the Client to determine how to distribute actors across available nodes.

These strategies are used to influence actor placement when spawning with balancing enabled, allowing for flexible and optimized load distribution.

const (
	// RoundRobinStrategy distributes actors evenly across nodes by cycling
	// through the available nodes in a round-robin fashion.
	RoundRobinStrategy BalancerStrategy = iota

	// RandomStrategy selects a node at random from the pool of available nodes.
	// This strategy can help achieve quick distribution without maintaining state.
	RandomStrategy

	// LeastLoadStrategy selects the node with the lowest current weight or load
	// at the time of actor placement. This strategy aims to optimize resource
	// utilization by placing actors on underutilized nodes.
	LeastLoadStrategy
)

type Client

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

Client provides connectivity to Go-Akt actor system nodes within a cluster.

The Client enables remote communication with Go-Akt nodes and requires remoting to be enabled on all target nodes in the cluster. It is specifically designed for interacting with Go-Akt clusters and handles the underlying networking, serialization, and actor addressing concerns.

Key capabilities:

  • Remote actor discovery and communication
  • Cluster topology awareness
  • Connection pooling and management
  • Message routing and delivery

Thread safety: Client is safe for concurrent use by multiple goroutines.

func New

func New(ctx context.Context, nodes []*Node, opts ...Option) (*Client, error)

New creates and initializes a new Client instance for interacting with a cluster of nodes.

The provided `nodes` parameter defines the initial list of cluster nodes, where each node is specified as `host:port` representing the remoting host and port of the actor system.

By default, the client uses a round-robin load-balancing strategy to distribute actor-related operations across the provided nodes. This behavior can be customized via optional parameters.

Parameters:

  • ctx: Context for initialization and potential cancellation.
  • nodes: A slice of pointers to Node, each representing a cluster node.
  • opts: Optional configuration values (e.g., custom balancer).

Returns:

  • *Client: A thread-safe client instance that can be reused across goroutines.
  • error: An error if client initialization fails (e.g., invalid nodes, config issues).

Note:

  • The returned Client is safe for concurrent use.
  • Nodes are assumed to be reachable and running a compatible actor runtime.

func (*Client) Ask

func (x *Client) Ask(ctx context.Context, actor *Actor, message proto.Message, timeout time.Duration) (reply proto.Message, err error)

Ask sends a message to the specified actor and waits for a response.

This method sends a protobuf message to the given actor and blocks until a reply is received or the timeout is reached. It is intended for request-response communication patterns.

Parameters:

  • ctx: Context used for cancellation and deadline control.
  • actor: A pointer to the target Actor instance, used to locate the actor by name.
  • message: A protobuf message to send to the actor. This must be a valid, serializable message.
  • timeout: The maximum duration to wait for a response from the actor.

Returns:

  • reply: The protobuf message returned by the actor.
  • err: Returns an error if the actor is not found, if the timeout is exceeded, or if message delivery or handling fails.

Note:

  • If the actor does not exist or is unreachable, a NOT_FOUND error is returned.
  • Ensure the actor is designed to handle the incoming message and reply appropriately.
  • For fire-and-forget messaging, use `Tell` instead of `Ask`.

func (*Client) Close

func (x *Client) Close()

Close closes the Client connection

func (*Client) Kinds

func (x *Client) Kinds(ctx context.Context) ([]string, error)

Kinds returns the list of all actor kinds currently registered in the cluster.

Actor kinds represent the different types or categories of gerrors that are available for spawning or interaction within the cluster.

Parameters:

  • ctx: Context used for cancellation and timeout control.

Returns:

  • []string: A slice of strings representing the registered actor kinds.
  • Error: An error if the request to retrieve kinds fails.

func (*Client) ReSpawn

func (x *Client) ReSpawn(ctx context.Context, actor *Actor) (err error)

ReSpawn restarts a previously spawned actor.

This method stops the given actor (if running) and starts a new instance of it, preserving its identity. It is typically used in scenarios where the actor has failed or needs to be re-initialized due to updated state or configuration.

Parameters:

  • ctx: Context used for cancellation and timeout control.
  • actor: A pointer to the Actor instance to be restarted.

Returns:

  • err: An error if the actor could not be stopped, restarted, or re-registered.

Note:

  • ReSpawn does not guarantee preservation of the in-memory state unless the actor is designed to persist and recover it (e.g., via snapshotting or event sourcing).

func (*Client) Reinstate

func (x *Client) Reinstate(ctx context.Context, actor *Actor) error

Reinstate transitions a previously suspended actor back to an active state.

Upon reinstatement, the actor resumes processing incoming messages from its mailbox, continuing with the internal state it held before suspension.

Important notes:

  • The actor’s state is preserved; no state reset occurs during reinstatement.
  • Messages processing resumed after reinstatement.
  • If the actor cannot be reinstated (e.g., if it no longer exists or is in a terminal state), an error will be returned.
  • Reinstate should be used cautiously in distributed systems to avoid race conditions or inconsistent actor states.

Parameters:

  • ctx: Context for cancellation and deadlines.
  • actor: Pointer to the Actor instance to be reinstated.

Returns:

  • error: Non-nil if the operation fails due to invalid state, internal issues. In case the actor is not found it will return no error.

func (*Client) Spawn

func (x *Client) Spawn(ctx context.Context, actor *Actor, singleton, relocatable bool) (err error)

Spawn creates and starts an actor using the default balancing strategy.

This method initializes the provided actor and places it on an available node using the default balancing strategy configured in the Client. It supports singleton enforcement and relocatability.

Parameters:

  • ctx: Context for cancellation and timeout control.
  • actor: A pointer to the Actor instance to be spawned.
  • singleton: If true, ensures only one instance of the actor exists across the system.
  • relocatable: If true, allows the actor to be relocated to another node if needed.

Returns:

  • err: An error if actor creation or placement fails.

Note:

  • If you require custom balancing logic, use SpawnBalanced instead.

func (*Client) SpawnBalanced

func (x *Client) SpawnBalanced(ctx context.Context, actor *Actor, singleton, relocatable bool, strategy BalancerStrategy) (err error)

SpawnBalanced creates and starts an actor with the specified balancing strategy.

This method spawns the given actor across a cluster or local node using a provided `BalancerStrategy` to determine optimal placement. It supports singleton enforcement and relocatability of the actor.

Parameters:

  • ctx: Context used for cancellation and timeout control.
  • actor: A pointer to the Actor instance to be spawned.
  • singleton: If true, ensures only one instance of the actor exists across the system.
  • relocatable: If true, allows the actor to be relocated by the balancer when necessary.
  • strategy: Defines the balancing strategy (e.g., round-robin, least-loaded) to use for actor placement.

Returns:

  • err: Non-nil if spawning the actor fails (e.g., invalid actor, placement error, etc.)

Example:

err := client.SpawnBalanced(ctx, myActor, true, false, RoundRobinStrategy)
if err != nil {
    log.Fatalf("Failed to spawn actor: %v", err)
}

func (*Client) Stop

func (x *Client) Stop(ctx context.Context, actor *Actor) error

Stop gracefully stops or forcefully terminates the specified actor.

This method instructs the Client to stop the given actor, releasing any resources associated with it. Depending on the actor’s design and internal state, it may perform cleanup logic before termination.

Parameters:

  • ctx: Context used for cancellation and timeout control.
  • actor: A pointer to the Actor instance to be stopped.

Returns:

  • error: Returns an error if the actor could not be found, or if stopping it fails.

Note:

  • If the actor is not running or found, no error is returned.
  • Graceful shutdown behavior depends on the actor implementation (e.g., handling termination signals).

func (*Client) Tell

func (x *Client) Tell(ctx context.Context, actor *Actor, message proto.Message) error

Tell sends a message to the specified actor.

This method delivers the given protobuf message to the target actor. If the actor is not currently running or registered in the system, a NOT_FOUND error is returned.

Parameters:

  • ctx: Context used for cancellation and timeout control.
  • actor: A pointer to the target Actor instance, used to locate the actor by name.
  • Message: A protobuf message to send to the actor. This must be a valid, serializable message.

Returns:

  • error: Returns nil on success. Returns a NOT_FOUND error if the actor is not available.

Note:

  • This method is asynchronous; it does not wait for a response.
  • For request-response patterns, consider using `Ask` instead of `Tell`.

func (*Client) Whereis

func (x *Client) Whereis(ctx context.Context, actor *Actor) (*address.Address, error)

Whereis looks up the location of the specified actor and returns its address.

This method queries the system to find the current network or logical address of the given actor. It can be used to inspect actor placement or route messages manually.

Parameters:

  • ctx: Context used for cancellation and timeout control.
  • actor: A pointer to the Actor instance whose address is being queried.

Returns:

  • *address.Address: The resolved address of the actor if found.
  • error: Returns a NOT_FOUND error if the actor does not exist or is not currently registered.

Note:

  • This method does not send a message or interact with the actor directly.
  • Use this for diagnostic, routing, or debugging purposes.

type LeastLoad

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

LeastLoad uses the LeastLoadStrategy to pick the next available node in the pool

func NewLeastLoad

func NewLeastLoad() *LeastLoad

NewLeastLoad creates an instance of LeastLoad

func (*LeastLoad) Next

func (x *LeastLoad) Next() *Node

Next returns the next node in the pool

func (*LeastLoad) Set

func (x *LeastLoad) Set(nodes ...*Node)

Set sets the balancer nodes pool

type Node

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

Node represents the node in the cluster

func NewNode

func NewNode(address string, opts ...NodeOption) *Node

NewNode creates an instance of Node nolint

func (*Node) Address

func (n *Node) Address() string

Address returns the node address

func (*Node) Free

func (n *Node) Free()

Free closes the underlying http client connection of the given node

func (*Node) HTTPClient

func (n *Node) HTTPClient() *nethttp.Client

HTTPClient returns the underlying http client for the given node

func (*Node) HTTPEndPoint

func (n *Node) HTTPEndPoint() string

HTTPEndPoint returns the node remote endpoint

func (*Node) HostAndPort

func (n *Node) HostAndPort() (string, int)

HostAndPort returns the node host and port

func (*Node) Remoting

func (n *Node) Remoting() remote.Remoting

Remoting returns the remoting instance

func (*Node) SetWeight

func (n *Node) SetWeight(weight float64)

SetWeight sets the node weight. This is thread safe

func (*Node) Validate

func (n *Node) Validate() error

func (*Node) Weight

func (n *Node) Weight() float64

Weight returns the node weight

type NodeOption

type NodeOption func(*Node)

func WithTLS

func WithTLS(config *tls.Config) NodeOption

WithTLS configures the node to use a secure connection for communication with the specified remote node. This requires a TLS client configuration to enable secure interactions with the remote actor system.

Ensure that the actor cluster is configured with TLS enabled and capable of completing a successful handshake. It is recommended that both systems share the same root Certificate Authority (CA) for mutual trust and secure communication.

func WithWeight

func WithWeight(weight float64) NodeOption

WithWeight set the node weight

type Option

type Option interface {
	// Apply sets the Option value of a config.
	Apply(cl *Client)
}

Option is the interface that applies a configuration option.

func WithBalancerStrategy

func WithBalancerStrategy(strategy BalancerStrategy) Option

WithBalancerStrategy sets the Client weight balancer strategy

func WithRefresh

func WithRefresh(interval time.Duration) Option

WithRefresh sets a refresh interval. This help check the nodes state time to time. This help remove dead nodes from the pool

type OptionFunc

type OptionFunc func(*Client)

OptionFunc implements the Option interface.

func (OptionFunc) Apply

func (f OptionFunc) Apply(c *Client)

type Random

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

Random helps pick a node at random

func NewRandom

func NewRandom() *Random

NewRandom creates an instance of Random balancer

func (*Random) Next

func (x *Random) Next() *Node

Next returns the next node in the pool

func (*Random) Set

func (x *Random) Set(nodes ...*Node)

Set sets the balancer nodes pool

type RoundRobin

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

RoundRobin implements the round-robin algorithm to pick a particular nodes in the cluster

func NewRoundRobin

func NewRoundRobin() *RoundRobin

NewRoundRobin creates an instance of RoundRobin

func (*RoundRobin) Next

func (x *RoundRobin) Next() *Node

Next returns the next node in the pool

func (*RoundRobin) Set

func (x *RoundRobin) Set(nodes ...*Node)

Set sets the balancer nodes pool

Jump to

Keyboard shortcuts

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