actorkit

package module
v0.0.0-...-7f53d98 Latest Latest
Warning

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

Go to latest
Published: Jan 30, 2019 License: MIT Imports: 15 Imported by: 0

README

Actorkit

Go Report Card Travis Build

Actorkit is an experiement geared towards the fusion of actor based concurrency programming with different useful software architectural principles to development a flexible, viable distributable, scalable foundation for building resilient services. It takes inspirations from projects like Akka and Proto.Actor and others.

Install

go get -u github.com/gokit/actorkit

Architecture

Actor System

Actorkit is a fusion of CQRS, grains from Microsoft Orleans and actor-based message-passing principles within a a single library geared towards the creation of scalable, distributed and resilient applications built on the concept of transparent, addressable processing units or actors. It embraces the very nature of chaotic, failing system which is most transparent to the developer allowing the focus on creating systems able to resiliently function in such environments. These details become part of the architecture and not just a after development process managemeent routine.

Documentation

Index

Constants

View Source
const (

	// PackageName defines the name for the package used in relationship
	// for messages or different types.
	PackageName = "actorkit"
)

Variables

View Source
var (
	// ErrActorBusyState is returned when an actor is processing a state request when another is made.
	ErrActorBusyState = errors.New("Actor is busy with state (STOP|STOPCHILDREN|DESTROY|DESTROY)")

	// ErrActorMustBeRunning is returned when an operation is to be done and the giving actor is not started.
	ErrActorMustBeRunning = errors.New("Actor must be running")

	// ErrActorHasNoBehaviour is returned when an is to start with no attached behaviour.
	ErrActorHasNoBehaviour = errors.New("Actor must be running")

	// ErrActorHasNoDiscoveryService is returned when actor has no discovery server.
	ErrActorHasNoDiscoveryService = errors.New("Actor does not support discovery")
)
View Source
var (
	// ErrOpenedCircuit is returned when circuit breaker is in opened state.
	ErrOpenedCircuit = errors.New("Circuit is opened")

	// ErrOpAfterTimeout is returned when operation call executes longer than
	// timeout duration.
	ErrOpAfterTimeout = errors.New("operation finished after timeout")
)
View Source
var (
	ErrFutureTimeout          = errors.New("Future timed out")
	ErrFutureResolved         = errors.New("Future is resolved")
	ErrFutureEscalatedFailure = errors.New("Future failed due to escalated error")
)

errors ...

View Source
var (
	// ErrHasNoActor is returned when actor implementer has no actor underline
	// which is mostly occuring with futures.
	ErrHasNoActor = errors.New("Addr implementer has no underline actor")
)
View Source
var ErrMailboxEmpty = errors.New("mailbox is empty")

ErrMailboxEmpty is returned when mailbox is empty of pending envelopes.

View Source
var ErrPushFailed = errors.New("failed to push into mailbox")

ErrPushFailed is returned when mailbox has reached storage limit.

Functions

func AddressReference

func AddressReference(addr Addr) string

AddressReference defines a function which matches the HashingReference function type and is the default use. It simply returns the Addr() value of a Addr object.

This might not necessarily be desired as the address contains the actor's process id details which can become too specific in certain cases.

func Destroy

func Destroy(addr Addr) error

Destroy returns a error which provides a means of forceful shutdown and removal of giving actor of address from the system basically making the actor and it's children non existent.

func FormatAddr

func FormatAddr(protocol string, namespace string, id string) string

FormatAddr returns the official address format for which the actorkit package uses for representing the protocol+namespace+uuid value for a actor or it's addresses.

func FormatAddrChild

func FormatAddrChild(parentAddr string, childID string) string

FormatAddrChild returns the official address format for which the actorkit package uses for representing the parent + child address value.

func FormatAddrService

func FormatAddrService(protocol string, namespace string, id string, service string) string

FormatAddrService returns the official address format for which the actorkit package uses for formatting a actor's service address format.

func FormatNamespace

func FormatNamespace(protocol string, namespace string) string

FormatNamespace returns the official namespace format for which the actorkit package uses for representing the protocol+namespace value for a actor or it's addresses.

func FormatService

func FormatService(protocol string, namespace string, service string) string

FormatService returns the official ProtocolAddr format for which the actorkit package uses for representing the protocol+namespace+service value for a actor or it's addresses.

func FromPartialFunc

func FromPartialFunc(partial func(string, string, ...ActorOption) Actor, pre ...ActorOption) func(string, string, ...ActorOption) Actor

FromPartialFunc defines a giving function which can be supplied a function which will be called with provided ActorOption to be used for generating new actors for giving options.

func Func

func Func(fn BehaviourFunc) func(string, string, ...ActorOption) Actor

Func returns a Actor generating function which uses provided BehaviourFunc.

func Kill

func Kill(addr Addr) error

Kill returns a error which provides a means of shutdown and clearing all pending messages of giving actor through it's address. It also kills actors children.

func Poison

func Poison(addr Addr) error

Poison stops the actor referenced by giving address, this also causes a restart of actor's children.

func ProtocolAddrReference

func ProtocolAddrReference(addr Addr) string

ProtocolAddrReference defines a function which matches the HashingReference function type. It simply returns the ProtocolAddr() value of a Addr object.

func Restart

func Restart(addr Addr) error

Restart restarts giving actor through it's address, the messages are maintained and kept safe, the children of actor are also restarted.

Types

type Actor

Actor defines a entity which is the single unit of work/computation. It embodies the idea of processing, storage and communication. It is the means for work to be done.

Actors as axioms/rules which are:

1. It can receive a message and create an actor to process giving message. 2. It can send messages to actors it has addresses it has before. 3. It can designate what to do will the next message to be received.

Actors are defined by the behaviour they embody and use, their are simply the management husk for this user defined behaviour and by this behaviors all the operations a actor can perform is governed. Usually an actors behaviour is represented by it's address, which means an actor can in one instance usually have similar address with only difference be their unique id when within the same tree ancestry and only differ in the service they offer or can be be the same actor offering different services based on the behaviour it provides.

func From

func From(namespace string, protocol string, ops ...ActorOption) Actor

From returns a new spawned and not yet started Actor based on provided ActorOptions.

func FromFunc

func FromFunc(namespace string, protocol string, fn BehaviourFunc, ops ...ActorOption) Actor

FromFunc returns a new actor based on provided function.

type ActorFailureSignal

type ActorFailureSignal struct {
	// Addr of actor which signal corresponds to, usually the AccessOf produced address.
	Addr Addr

	// Err provides the attached error detailing failure for giving signal.
	Err error

	// Signal represents type of actor signal supported.
	Signal Signal

	// Optional payload attached to signal event.
	Payload interface{}
}

ActorFailureSignal defines message sent to indicate failure of transitioning to a signal state for an actor.

func (ActorFailureSignal) SystemMessage

func (ActorFailureSignal) SystemMessage()

SystemMessage identifies giving type as a system message.

type ActorImpl

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

ActorImpl implements the Actor interface.

func NewActorImpl

func NewActorImpl(namespace string, protocol string, props Prop) *ActorImpl

NewActorImpl returns a new instance of an ActorImpl assigned giving protocol and service name.

func (*ActorImpl) Addr

func (ati *ActorImpl) Addr() string

Addr returns a url-like representation of giving service by following two giving patterns:

1. If Actor is the highest ancestor then it will return address in form:

Protocol@Namespace/ID

2. If Actor is the a child of another, then it will return address in form:

		AncestorAddress/ID

   where AncestorAddress is "Protocol@Namespace/ID"

In either case, the protocol of both ancestor and parent is maintained. Namespace provides a field area which can define specific information that is specific to giving protocol e.g ip v4/v6 address.

func (*ActorImpl) Ancestor

func (ati *ActorImpl) Ancestor() Actor

Ancestor returns the root parent of giving Actor ancestral tree.

func (*ActorImpl) Children

func (ati *ActorImpl) Children() []Addr

Children returns a slice of all addresses of all child actors. All address have attached service name "access" for returned address, to indicate we are accessing this actors.

func (*ActorImpl) DeathWatch

func (ati *ActorImpl) DeathWatch(addr Addr) error

DeathWatch asks this actor sentinel to advice on behaviour or operation to be performed for the provided actor's states (i.e Stopped, Restarted, Killed, Destroyed). being watched for.

If actor has no Sentinel then an error is returned. Sentinels are required to advice on action for watched actors by watching actor.

func (*ActorImpl) Destroy

func (ati *ActorImpl) Destroy() error

Destroy stops giving actor and emits a destruction event which will remove giving actor from it's ancestry trees.

func (*ActorImpl) DestroyChildren

func (ati *ActorImpl) DestroyChildren() error

DestroyChildren immediately destroys giving children of actor.

func (*ActorImpl) Discover

func (ati *ActorImpl) Discover(service string, ancestral bool) (Addr, error)

Discover returns actor's Addr from this actor's discovery chain, else passing up the service till it reaches the actors root where no possible discovery can be done.

The returned address is not added to this actor's death watch, so user if desiring this must add it themselves.

The method will return an error if Actor is not already running.

func (*ActorImpl) Escalate

func (ati *ActorImpl) Escalate(err interface{}, addr Addr)

Escalate sends giving error that occur to actor's supervisor which can make necessary decision on actions to be done, either to escalate to parent's supervisor or restart/stop or handle giving actor as dictated by it's algorithm.

func (*ActorImpl) GetAddr

func (ati *ActorImpl) GetAddr(addr string) (Addr, error)

GetAddr returns the child of this actor which has this address string version.

This method is more specific and will not respect or handle a address which the root ID is not this actor's identification ID. It heavily relies on walking the address tree till it finds the target actor or there is found no matching actor

func (*ActorImpl) GetChild

func (ati *ActorImpl) GetChild(id string, subID ...string) (Addr, error)

GetChild returns the child of this actor which has this matching id.

If the sub is provided, then the function will drill down the provided target actor getting the child actor of that actor which matches the next string ID till it finds the last target string ID or fails to find it.

func (*ActorImpl) ID

func (ati *ActorImpl) ID() string

ID returns associated string version of id.

func (*ActorImpl) Kill

func (ati *ActorImpl) Kill() error

Kill immediately stops the actor and clears all pending messages.

func (*ActorImpl) KillChildren

func (ati *ActorImpl) KillChildren() error

KillChildren immediately kills giving children of actor.

func (*ActorImpl) Mailbox

func (ati *ActorImpl) Mailbox() Mailbox

Mailbox returns actors underline mailbox.

func (*ActorImpl) Namespace

func (ati *ActorImpl) Namespace() string

Namespace returns actor's namespace.

func (*ActorImpl) Parent

func (ati *ActorImpl) Parent() Actor

Parent returns the parent of giving Actor.

func (*ActorImpl) Protocol

func (ati *ActorImpl) Protocol() string

Protocol returns actor's protocol.

func (*ActorImpl) ProtocolAddr

func (ati *ActorImpl) ProtocolAddr() string

ProtocolAddr returns the Actors.Protocol and Actors.Namespace values in the format:

Protocol@Namespace.

func (*ActorImpl) Publish

func (ati *ActorImpl) Publish(message interface{})

Publish publishes an event into the actor event notification system.

func (*ActorImpl) Receive

func (ati *ActorImpl) Receive(a Addr, e Envelope) error

Receive adds giving Envelope into actor's mailbox.

func (*ActorImpl) Restart

func (ati *ActorImpl) Restart() error

Restart restarts the actors message processing operations. It will immediately resume operations from pending messages within mailbox. This will also restarts actors children.

func (*ActorImpl) RestartChildren

func (ati *ActorImpl) RestartChildren() error

RestartChildren restarts all children of giving actor without applying same operation to parent.

func (*ActorImpl) Spawn

func (ati *ActorImpl) Spawn(service string, prop Prop) (Addr, error)

Spawn spawns a new actor under this parents tree returning address of created actor.

The method will return an error if Actor is not already running.

func (*ActorImpl) Start

func (ati *ActorImpl) Start() error

Start starts off or resumes giving actor operations for processing received messages.

func (*ActorImpl) State

func (ati *ActorImpl) State() Signal

State returns the current state of giving actor in a safe-concurrent manner.

func (*ActorImpl) Stats

func (ati *ActorImpl) Stats() Stat

Stats returns giving actor stat associated with actor.

func (*ActorImpl) Stop

func (ati *ActorImpl) Stop() error

Stop stops the operations of the actor on processing received messages. All pending messages will be kept, so the actor can continue once started. To both stop and clear all messages, use ActorImpl.Kill().

func (*ActorImpl) StopChildren

func (ati *ActorImpl) StopChildren() error

StopChildren immediately stops all children of actor.

func (*ActorImpl) Wait

func (ati *ActorImpl) Wait()

Wait implements the Waiter interface.

func (*ActorImpl) Watch

func (ati *ActorImpl) Watch(fn func(interface{})) Subscription

Watch adds provided function as a subscriber to be called on events published by actor, it returns a subscription which can be used to end giving subscription.

type ActorOption

type ActorOption func(*Prop)

ActorOption defines a function which is runned against a pointer to a Prop which will be used for generating a actor's underline behaviour.

func UseBehaviour

func UseBehaviour(bh Behaviour) ActorOption

UseBehaviour sets the behaviour to be used by a given actor.

func UseContextLog

func UseContextLog(cl ContextLogs) ActorOption

UseContextLog sets the Logs to be used by the actor.

func UseDeadLetter

func UseDeadLetter(ml DeadLetter) ActorOption

UseDeadLetter sets giving deadletter as processor for death mails.

func UseEventStream

func UseEventStream(es EventStream) ActorOption

UseEventStream sets the event stream to be used by the actor.

func UseMailInvoker

func UseMailInvoker(mi MailInvoker) ActorOption

UseMailInvoker sets the mail invoker to be used by the actor.

func UseMailbox

func UseMailbox(m Mailbox) ActorOption

UseMailbox sets the mailbox to be used by the actor.

func UseMessageInvoker

func UseMessageInvoker(st MessageInvoker) ActorOption

UseMessageInvoker sets the message invoker to be used by the actor.

func UseSentinel

func UseSentinel(sn Sentinel) ActorOption

UseSentinel sets giving Sentinel provider for a actor.

func UseSignal

func UseSignal(signal Signals) ActorOption

UseSignal applies giving signals to be used by generated actor.

func UseStateInvoker

func UseStateInvoker(st StateInvoker) ActorOption

UseStateInvoker sets the state invoker to be used by the actor.

func UseSupervisor

func UseSupervisor(s Supervisor) ActorOption

UseSupervisor sets the supervisor to be used by the actor.

type ActorRegistry

type ActorRegistry struct {
}

type ActorSignal

type ActorSignal struct {
	// Addr of actor which signal corresponds to, usually the AccessOf produced address.
	Addr Addr

	// Signal represents type of actor signal supported.
	Signal Signal

	// Optional payload attached to signal event.
	Payload interface{}
}

ActorSignal defines message sent to indicate a state transition signal for an actor.

func (ActorSignal) SystemMessage

func (ActorSignal) SystemMessage()

SystemMessage identifies giving type as a system message.

type ActorSpawner

type ActorSpawner func(...ActorOption) Actor

ActorSpawner defines a function interface which takes a giving set of options returns a new instantiated Actor.

func FromPartial

func FromPartial(namespace string, protocol string, ops ...ActorOption) ActorSpawner

FromPartial returns a ActorSpawner which will be used for spawning new Actor using provided options both from the call to FromPartial and those passed to the returned function.

type ActorTree

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

ActorTree implements a hash/dictionary registry for giving actors. It combines internally a map and list to take advantage of quick lookup and order maintenance.

ActorTree implements the ActorRegistry interface.

ActorTree is safe for concurrent access.

func NewActorTree

func NewActorTree(initialLength int) *ActorTree

NewActorTree returns a new instance of an actor tree using the initial length as capacity to the underline slice for storing actors.

func (*ActorTree) AddActor

func (at *ActorTree) AddActor(c Actor) error

AddActor adds giving actor into tree.

func (*ActorTree) Each

func (at *ActorTree) Each(fn func(Actor) bool)

Each will call giving function on all registered actors, it concurrency safe and uses locks underneath. The handler is expected to return true/false, this indicates if we want to continue iterating in the case of true or to stop iterating in the case of false. res <- nil

func (*ActorTree) GetActor

func (at *ActorTree) GetActor(id string) (Actor, error)

GetActor returns giving actor from tree using requested id.

func (*ActorTree) GetAddr

func (at *ActorTree) GetAddr(addr string) (Actor, error)

GetAddr returns a actor from tree using requested id.

func (*ActorTree) HasActor

func (at *ActorTree) HasActor(id string) bool

HasActor returns true/false if giving actor exists.

func (*ActorTree) Length

func (at *ActorTree) Length() int

Length returns the length of actors within tree.

func (*ActorTree) RemoveActor

func (at *ActorTree) RemoveActor(c Actor) error

RemoveActor removes attached actor from tree if found.

func (*ActorTree) Reset

func (at *ActorTree) Reset()

Reset resets content of actor tree, removing all children and registry.

type AddRoute

type AddRoute struct{}

AddRoute defines a giving message delivered for adding sending address into route list.

Used by the RoundRobin, RandomRouter, HashedRouter and Broadcast Router.

type Addr

Addr represent a advertised capability and behavior which an actor provides, it is possible for one actor to exhibit ability of processing multiple operations/behaviors by being able to be expressed using different service addresses. Address simply express a reference handle by which an actor able to provide said service can be communicated with.

Interaction of one service to another is always through an address, which makes them a common concept that can be transferable between zones, distributed system and networks.

Addr by their nature can have a one-to-many and many-to-many relations with actors.

A single actor can have multiple addresses pointing to it, based on different services it can render or even based on same service type, more so one address can be a means of communicating with multiple actors in the case of clustering or distributing messaging through a proxy address.

func Ancestor

func Ancestor(protocol string, namespace string, prop Prop) (Addr, error)

Ancestor create an actor with a default DeadLetter behaviour, where this actor is the root node in a tree of actors. It is the entity by which all children spawned or discovered from it will be connected to, and allows a group control over them.

Usually you always have one root or system actor per namespace (i.e host:port, ipv6, ..etc), then build off your child actors from of it, so do ensure to minimize the use of multiple system or ancestor actor roots.

Remember all child actors spawned from an ancestor always takes its protocol and namespace.

type AddrImpl

type AddrImpl struct {
	Root Addressable
	// contains filtered or unexported fields
}

AddrImpl implements the Addr interface providing an addressable reference to an existing actor.

func AccessOf

func AccessOf(actor Actor) *AddrImpl

AccessOf returns a default "actor:access" service name, it's expected to be used when desiring a default address for an actor.

func AddressOf

func AddressOf(actor Actor, service string) *AddrImpl

AddressOf returns a new instance of AddrImpl which directly uses the provided process as it's underline target for messages.

func DeadLetters

func DeadLetters() *AddrImpl

DeadLetters returns a new instance of AddrImpl which directly delivers responses and messages to the deadletter event pipeline.

func (*AddrImpl) Actor

func (a *AddrImpl) Actor() Actor

Actor returns associated actor of Address.

func (*AddrImpl) Addr

func (a *AddrImpl) Addr() string

Addr returns the unique address which this address points to both the actor and service the address is presenting as the underline actor capability.

Address uses a format: ActorAddress/ServiceName

func (*AddrImpl) AddressOf

func (a *AddrImpl) AddressOf(service string, ancestral bool) (Addr, error)

AddressOf returns the address of giving actor matching giving service name.

func (*AddrImpl) Ancestor

func (a *AddrImpl) Ancestor() Addr

Ancestor returns the address of the root ancestor. If giving underline ancestor is the same as this address actor then we return address.

func (*AddrImpl) Children

func (a *AddrImpl) Children() []Addr

Children returns address of all children actors of this address actor.

func (*AddrImpl) DeathWatch

func (a *AddrImpl) DeathWatch(addr Addr) error

DeathWatch implements the DeathWatch interface.

func (*AddrImpl) Destroy

func (a *AddrImpl) Destroy() error

Destroy returns a error for the termination and destruction of the underline actor for giving address.

func (*AddrImpl) Escalate

func (a *AddrImpl) Escalate(v interface{})

Escalate implements the Escalator interface.

func (*AddrImpl) Forward

func (a *AddrImpl) Forward(e Envelope) error

Forward delivers provided envelope to the current process.

func (*AddrImpl) Future

func (a *AddrImpl) Future() Future

Future returns a new future instance from giving source.

func (*AddrImpl) GetAddr

func (a *AddrImpl) GetAddr(addr string) (Addr, error)

GetAddr calls the underline actor's GetAddr implementation for accessing children of actors through the provided addr string which must have it's initial ID match this address ID.

func (*AddrImpl) GetChild

func (a *AddrImpl) GetChild(id string, subID ...string) (Addr, error)

GetChild calls the underline actor's GetChild implementation for accessing children of actors through it's id and sub ids for the descendant of the retrieved actor matching the id value.

func (*AddrImpl) ID

func (a *AddrImpl) ID() string

ID returns unique identification value for underline process of Addr.

func (*AddrImpl) Kill

func (a *AddrImpl) Kill() error

Kill sends a kill signal to the underline process to stop all operations and to close immediately.

func (*AddrImpl) Namespace

func (a *AddrImpl) Namespace() string

Namespace returns address actor namespace.

func (*AddrImpl) Parent

func (a *AddrImpl) Parent() Addr

Parent returns the address of parent if giving underline actor is not the same as the actor of this address else returning this actor.

func (*AddrImpl) Protocol

func (a *AddrImpl) Protocol() string

Protocol returns address actor protocol.

func (*AddrImpl) ProtocolAddr

func (a *AddrImpl) ProtocolAddr() string

ProtocolAddr returns the Actors.ProtocolAddr() and Addr.ServiceName values in the format: Protocol@Namespace/Service.

func (*AddrImpl) Restart

func (a *AddrImpl) Restart() error

Restart returns a error for the restart of the underline actor for giving address.

func (*AddrImpl) Send

func (a *AddrImpl) Send(data interface{}, sender Addr) error

Send delivers provided raw data to this process providing destination/reply address.

func (*AddrImpl) SendWithHeader

func (a *AddrImpl) SendWithHeader(data interface{}, h Header, sender Addr) error

SendWithHeader delivers provided raw data to this process providing destination/reply address.

func (*AddrImpl) Service

func (a *AddrImpl) Service() string

Service returns the service name which the giving address represent as it's capability and functionality for giving actor.

func (*AddrImpl) Spawn

func (a *AddrImpl) Spawn(service string, prop Prop) (Addr, error)

Spawn creates a new actor based on giving service name by requesting all discovery services registered to giving underline address actor.

func (*AddrImpl) State

func (a *AddrImpl) State() Signal

State returns state of actor.

func (*AddrImpl) Stop

func (a *AddrImpl) Stop() error

Stop returns a error for the stopping of the underline actor for giving address.

func (*AddrImpl) String

func (a *AddrImpl) String() string

String returns address string of giving AddrImpl.

func (*AddrImpl) TimedFuture

func (a *AddrImpl) TimedFuture(d time.Duration) Future

TimedFuture returns a new future instance from giving source.

func (*AddrImpl) Watch

func (a *AddrImpl) Watch(fn func(interface{})) Subscription

Watch adds a giving function into the subscription listeners of giving address events.

type AddressActor

type AddressActor interface {
	Actor() Actor
}

AddressActor defines an interface which exposes a method to retrieve the actor of an Address.

type AddressService

type AddressService interface {
	AddressOf(string, bool) (Addr, error)
}

AddressService exposes a single method to locate given address for a target value, service or namespace.

type Addressable

type Addressable interface {
	Addr() string
}

Addressable defines an interface which exposes a method for retrieving associated address of implementer.

type AllForOneSupervisor

type AllForOneSupervisor struct {
	Max         int
	Decider     Decider
	PanicAction PanicAction
	Delay       DelayProvider
	Invoker     SupervisionInvoker
	// contains filtered or unexported fields
}

AllForOneSupervisor implements a one-to-one supervising strategy for giving actors.

func (*AllForOneSupervisor) Handle

func (on *AllForOneSupervisor) Handle(err interface{}, targetAddr Addr, target Actor, parent Actor)

Handle implements the Supervisor interface and provides the algorithm logic for the all-for-one monitoring strategy, where a failed actor causes the same effect to be applied to all siblings and parent.

type AncestralAddr

type AncestralAddr interface {
	Parent() Addr
	Ancestor() Addr
}

AncestralAddr defines an interface which exposes method to retrieve the address of a giving parent of an implementing type.

type Ancestry

type Ancestry interface {
	// Parent is supposed to return the immediate parent of giving
	// Actor.
	Parent() Actor

	// Ancestor is supposed to return the root parent of all actors
	// within chain.
	Ancestor() Actor
}

Ancestry defines a single method to get the parent actor of a giving actor.

type AtomicBool

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

AtomicBool implements a safe atomic boolean.

func (*AtomicBool) IsTrue

func (a *AtomicBool) IsTrue() bool

IsTrue returns true/false if giving atomic bool is in true state.

func (*AtomicBool) Off

func (a *AtomicBool) Off()

Off sets the atomic bool as false.

func (*AtomicBool) On

func (a *AtomicBool) On()

On sets the atomic bool as true.

type AtomicCounter

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

AtomicCounter implements a wrapper around a int32.

func (*AtomicCounter) Get

func (a *AtomicCounter) Get() int64

Get returns giving counter count value.

func (*AtomicCounter) GetDuration

func (a *AtomicCounter) GetDuration() time.Duration

GetDuration returns giving counter count value as a time.Duration

func (*AtomicCounter) Inc

func (a *AtomicCounter) Inc()

Inc Increment counter by one.

func (*AtomicCounter) IncBy

func (a *AtomicCounter) IncBy(c int64)

IncBy Increment counter by provided value.

func (*AtomicCounter) Set

func (a *AtomicCounter) Set(n int64)

Set sets counter to value.

func (*AtomicCounter) Swap

func (a *AtomicCounter) Swap(n int64)

Swap attempts a compare and swap operation with counter.

type Behaviour

type Behaviour interface {
	Action(Addr, Envelope)
}

Behaviour defines an interface that exposes a method that indicate a giving action to be done.

func FromBehaviourFunc

func FromBehaviourFunc(b BehaviourFunc) Behaviour

FromBehaviourFunc returns a new Behaviour from the function.

type BehaviourCircuit

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

BehaviourCircuit implements the circuit breaker pattern for execution of a implementer of the ErrorBehaviour interface which returns errors for the execution of a operation.

Usually this is suitable if the implementer only ever performs tasks are that very similar which can then be treated as the same or a implementer that ever works on the same type of task every time as the breaker once tripped will ignore all messages without a care for it's type.

func (*BehaviourCircuit) Action

func (bc *BehaviourCircuit) Action(addr Addr, msg Envelope)

Action implements the Behaviour interface.

type BehaviourFunc

type BehaviourFunc func(Addr, Envelope)

BehaviourFunc defines a function type which is wrapped by a type implementing the Behaviour interface to be used in a actor.

type BoxQueue

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

BoxQueue defines a queue implementation safe for concurrent-use across go-routines, which provides ability to requeue, pop and push new envelop messages. BoxQueue uses lock to guarantee safe concurrent use.

func BoundedBoxQueue

func BoundedBoxQueue(capped int, method Strategy, invoker MailInvoker) *BoxQueue

BoundedBoxQueue returns a new instance of a unbounded box queue. Items will be queue till the capped is reached and then old items will be dropped till queue has enough space for new item. A cap value of -1 means there will be no maximum limit of allow messages in queue.

func UnboundedBoxQueue

func UnboundedBoxQueue(invoker MailInvoker) *BoxQueue

UnboundedBoxQueue returns a new instance of a unbounded box queue. Items will be queue endlessly.

func (*BoxQueue) Cap

func (bq *BoxQueue) Cap() int

Cap returns current cap of items.

func (*BoxQueue) Clear

func (bq *BoxQueue) Clear()

Clear resets and deletes all elements pending within queue

func (*BoxQueue) IsEmpty

func (bq *BoxQueue) IsEmpty() bool

IsEmpty returns true/false if the queue is empty.

func (*BoxQueue) Pop

func (bq *BoxQueue) Pop() (Addr, Envelope, error)

Pop removes the item from the front of the queue.

Pop can be safely called from multiple goroutines.

func (*BoxQueue) Push

func (bq *BoxQueue) Push(addr Addr, env Envelope) error

Push adds the item to the back of the queue.

Push can be safely called from multiple goroutines. Based on strategy if capped, then a message will be dropped.

func (*BoxQueue) Signal

func (bq *BoxQueue) Signal()

Signal sends a signal to all listening go-routines to attempt checks for new message.

func (*BoxQueue) Total

func (bq *BoxQueue) Total() int

Total returns total of item in mailbox.

func (*BoxQueue) Unpop

func (bq *BoxQueue) Unpop(addr Addr, env Envelope)

Unpop adds back item to the font of the queue.

Unpop can be safely called from multiple goroutines. If queue is capped and max was reached, then last added message is removed to make space for message to be added back. This means strategy will be ignored since this is an attempt to re-add an item back into the top of the queue.

func (*BoxQueue) Wait

func (bq *BoxQueue) Wait()

Wait will block current goroutine till there is a message pushed into the queue, allowing you to effectively rely on it as a schedule and processing signal for when messages are in queue.

type BroadcastRouter

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

BroadcastRouter implements a router which delivers messages in a fan-out manner to all addresses.

It stores address by their Addr.Addr() which means even if two Addr are referencing same Actor, they will be respected, added and broadcasted to, as the Addr represents a unique capability.

func NewBroadcastRouter

func NewBroadcastRouter(addrs ...Addr) *BroadcastRouter

NewBroadcastRouter adds giving set of address, returning a new BroadcastRouter which will broadcast incoming messages to all addresses.

func (*BroadcastRouter) Action

func (rr *BroadcastRouter) Action(addr Addr, msg Envelope)

Action implements the Behaviour interface.

type Circuit

type Circuit struct {
	// Timeout sets giving timeout duration for execution of
	// giving operation.
	Timeout time.Duration

	// MaxFailures sets giving maximum failure threshold allowed
	// before circuit enters open state.
	MaxFailures int64

	// HalfOpenSuccess sets giving minimum successfully calls to
	// circuit operation before entering closed state.
	//
	// Defaults to 1
	HalfOpenSuccess int64

	// MinCoolDown sets minimum time for circuit to be in open state
	// before we allow another attempt into half open state.
	//
	// Defaults to 15 seconds.
	MinCoolDown time.Duration

	// Maximum time to allow circuit to be in open state before
	// allowing another attempt.
	//
	// Defaults to 60 seconds.
	MaxCoolDown time.Duration

	// Now provides a function which can be used to provide
	// the next time (time.Time).
	//
	// Defaults to time.Now().
	Now func() time.Time

	// CanTrigger defines a function to be called to verify if
	// giving error falls under errors that count against
	// the circuit breaker, incrementing failure and can cause
	// circuit tripping.
	//
	// Defaults to a function that always returns true.
	CanTrigger func(error) bool

	// OnTrip sets giving callback to be called every time circuit
	// is tripped into open state.
	OnTrip func(name string, lastError error)

	// OnClose sets giving callback to be called on when
	// circuit entering closed state.
	OnClose func(name string, lastCoolDown time.Duration)

	// OnRun sets giving callback to be called on when
	// circuit is executed with function it is provided
	// with start, end time of function and possible error
	// that occurred either from function or due to time out.
	OnRun func(name string, start time.Time, end time.Time, err error)

	// OnHalfOpen sets giving callback to be called every time
	// circuit enters half open state.
	OnHalfOpen func(name string, lastCoolDown time.Duration, lastOpenedTime time.Time)
}

Circuit defines configuration values which will be used by CircuitBreaker for it's operations.

type CircuitAddr

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

CircuitAddr implements a circuit breaker Addr wrapper, which will implement a circuit breaker pattern on message delivery to a giving origin address. If giving address fails to accept messages over a certain period, this will count till a threshold is met, then all messages will be declined, till the circuit has reached

func NewCircuitAddr

func NewCircuitAddr(addr Addr, circuit Circuit, fallback func(error, Envelope) error) *CircuitAddr

NewCircuitAddr returns a new instance of a CircuitAddr.

func (*CircuitAddr) Forward

func (dm *CircuitAddr) Forward(env Envelope) error

Forward attempts to forward giving envelope to underline address. It returns an error if giving circuit is opened, hence passing envelope to fallback if provided.

func (*CircuitAddr) Send

func (dm *CircuitAddr) Send(data interface{}, addr Addr) error

Send delivers giving data as a envelope to provided underline address. It returns an error if giving circuit is opened, hence passing envelope to fallback if provided.

func (*CircuitAddr) SendWithHeader

func (dm *CircuitAddr) SendWithHeader(data interface{}, h Header, addr Addr) error

SendWithHeader delivers data as a enveloped with attached headers to underline address. It returns an error if giving circuit is opened, hence passing envelope to fallback if provided.

type CircuitBreaker

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

CircuitBreaker implements the CircuitBreaker pattern for use within actor project.

func NewCircuitBreaker

func NewCircuitBreaker(name string, circuit Circuit) *CircuitBreaker

NewCircuitBreaker returns a new instance of CircuitBreaker.

func (*CircuitBreaker) Do

func (dm *CircuitBreaker) Do(parentCtx context.Context, fn func(ctx context.Context) error, fallback func(context.Context, error) error) error

Do will attempt to execute giving function with a timed function if CircuitBreaker provides a timeout.

But the fallback if provided will be executed on the following rules:

1. The circuit is already opened, hence receiving a ErrOpenedCircuit error.

2. The function failed during execution with an error, which increases failed count and forces calling of fallback with received error.

func (*CircuitBreaker) IsOpened

func (dm *CircuitBreaker) IsOpened() bool

IsOpened returns true/false if circuit is in opened state.

type ContextLogFn

type ContextLogFn struct {
	Fn func(Actor) Logs
}

ContextLogFn implements the ContextLogs interface. It uses a provided function which returns a appropriate logger for a giving actor.

func NewContextLogFn

func NewContextLogFn(fn func(Actor) Logs) *ContextLogFn

NewContextLogFn returns a new instance of ContextLogFn

func (ContextLogFn) Get

func (c ContextLogFn) Get(a Actor) Logs

Get calls the underline function and returns the produced logger for the passed in actor.

type ContextLogs

type ContextLogs interface {
	Get(Actor) Logs
}

ContextLogs defines an interface that returns a Logs which exposes a method to return a logger which contextualizes the provided actor as a base for it's logger.

type DeadLetter

type DeadLetter interface {
	RecoverMail(DeadMail)
}

DeadLetter defines an interface which exists for the purpose of handling dead mails from terminated actors which have unprocessed mails within mailbox. It allows counter-measure to be provided to a actor's life cycle ending phase.

type DeadLetterBehaviour

type DeadLetterBehaviour struct{}

DeadLetterBehaviour implements a behaviour which forwards all messages to te deadletter mail box.

func (DeadLetterBehaviour) Action

func (DeadLetterBehaviour) Action(_ Addr, msg Envelope)

Action implements the Behaviour interface.

type DeadMail

type DeadMail struct {
	To      Addr
	Message Envelope
}

DeadMail defines the type of event triggered by the deadletters event pipeline.

type DeathWatch

type DeathWatch interface {
	DeathWatch(addr Addr) error
}

DeathWatch exposes a method to watch the state transition of a giving Addr if possible.

type Decider

type Decider func(interface{}) Directive

Decider defines a function which giving a value will return a directive.

type DelayProvider

type DelayProvider func(int) time.Duration

DelayProvider defines a function which giving a int value representing increasing attempts, will return an appropriate duration.

type Descendants

type Descendants interface {
	Children() []Addr
	GetAddr(addr string) (Addr, error)
	GetChild(id string, subID ...string) (Addr, error)
}

Descendants exposes methods which allow interaction with children of a implementing object.

type Destroyable

type Destroyable interface {
	Destroy() error
	DestroyChildren() error
}

Destroyable defines an interface that exposes methods for the total shutdown and removal of an actor from all processes.

type Directive

type Directive int

Directive defines a int type which represents a giving action to be taken for an actor.

const (
	IgnoreDirective Directive = iota
	PanicDirective
	DestroyDirective
	KillDirective
	StopDirective
	RestartDirective
	EscalateDirective
)

directive sets...

type Discovery

type Discovery interface {
	Discover(service string, ancestral bool) (Addr, error)
}

Discovery defines an interface that resolves a giving address to it's target Actor returning actor if found. It accepts a flag which can be used to indicate wiliness to search ancestral trees.

type DiscoveryChain

type DiscoveryChain interface {
	AddDiscovery(service DiscoveryService) error
}

DiscoveryChain defines a method which adds giving Discovery into underline chain else returns an error if not possible. Discovery has a very important rule, whoever has record of giving actor is parent and supervisor of said actor. Even if discovery was requested at the lowest end, if ancestral search was enabled and a higher parent provided such actor, then that parent should naturally be supervisor of that actor.

type DiscoveryService

type DiscoveryService interface {
	Discover(service string) (Addr, error)
}

DiscoveryService defines an interface which will return a giving Actor address for a desired service.

DiscoveryServices provides a great way for adding service or actor discovery the actor system where. How the underline actor's who's address is returned is up to the implementer, but by abstracting such a system by this interface we provide a simple and easy way to add better discovery functionality into actor trees.

DiscoveryServices also provide the means of templated actors, where actors with behaviors is already defined by a generating function called 'Templated Functions'. Templated functions always return a new actor when called and provide a nice means of having a guaranteed behaviour produced for a giving service namespace,

func DiscoveryFor

func DiscoveryFor(parent Addr, fn DiscoveryServiceFunction) DiscoveryService

DiscoveryFor returns a new DiscoveryService which calls giving function with service name for returning an actor suitable for handling a giving service.

type DiscoveryServiceFunction

type DiscoveryServiceFunction func(parent Addr, service string) (Addr, error)

DiscoveryServiceFunction defines a function type which will spawn a given actor using a provided parent and returns address of spawned actor. This allows us allocate management of giving actor to some parent whilst allowing others gain access to giving actor.

type DrainLog

type DrainLog struct{}

DrainLog implements the actorkit.Logs interface.

func (DrainLog) Emit

func (DrainLog) Emit(_ Level, _ LogMessage)

Emit does nothing with provided arguments, it implements actorkit.Logs Emit method.

type Envelope

type Envelope struct {
	Header
	Sender Addr
	Ref    xid.ID
	Data   interface{}
}

Envelope defines a message to be delivered to a giving target destination from another giving source with headers and data specific to giving message.

func CreateEnvelope

func CreateEnvelope(sender Addr, header Header, data interface{}) Envelope

CreateEnvelope returns a new instance of an envelope with provided arguments.

type ErrWaiter

type ErrWaiter interface {
	Wait() error
}

ErrWaiter exposes a single method which blocks till a given condition is met or an error occurs that causes it to stop blocking and will return the error encountered.

type ErrorBehaviour

type ErrorBehaviour interface {
	Action(Addr, Envelope) error
}

ErrorBehaviour defines an interface that exposes the a method which returns an error if one occurred for it's operation on a received Envelope.

type Escalatable

type Escalatable interface {
	Escalate(interface{})
}

Escalatable exposes a single method to escalate a given value up the implementers handling tree.

type EscalatedError

type EscalatedError struct {
	Err   error
	Value interface{}
}

EscalatedError defines a type which represents a escalated error and value.

It implements the error interface.

func (EscalatedError) Error

func (e EscalatedError) Error() string

Error returns the value of the internal error.

func (EscalatedError) Unwrap

func (e EscalatedError) Unwrap() error

Unwrap returns the internal error.

type Escalator

type Escalator interface {
	Escalate(interface{}, Addr)
}

Escalator defines an interface defines a method provided specifically for handle two cases of error:

1. Normal errors which occur as process operation life cycle 2. Critical errors which determine stability of system and ops.

Normal errors will be raised while critical errors will get escalated. this means that escalated errors will be parsed up the tree to an actors supervisor and parent.

type EventDeathMail

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

EventDeathMail implements the DeadLetter interface, where dead mails are delivered to a underline event system.

func NewEventDeathMail

func NewEventDeathMail(stream *es.EventStream) *EventDeathMail

NewEventDeathMail returns a new instance of a EventDeathMail.

func (*EventDeathMail) RecoverMail

func (em *EventDeathMail) RecoverMail(mail DeadMail)

RecoverMail implements DeadLetter interface. Sending mails into event stream.

type EventStream

type EventStream interface {
	Reset()
	Publish(interface{})
	Subscribe(Handler, Predicate) Subscription
}

EventStream defines an interface for

type EventSupervisingInvoker

type EventSupervisingInvoker struct {
	Event EventStream
}

EventSupervisingInvoker implements the SupervisorInvoker interface and simply invokes events for all invocation received.

func (*EventSupervisingInvoker) InvokedDestroy

func (es *EventSupervisingInvoker) InvokedDestroy(cause interface{}, stat Stat, addr Addr, target Actor)

InvokedDestroy emits event containing destroyed details.

func (*EventSupervisingInvoker) InvokedKill

func (es *EventSupervisingInvoker) InvokedKill(cause interface{}, stat Stat, addr Addr, target Actor)

InvokedKill emits event containing killed details.

func (*EventSupervisingInvoker) InvokedRestart

func (es *EventSupervisingInvoker) InvokedRestart(cause interface{}, stat Stat, addr Addr, target Actor)

InvokedRestart emits event containing restart details.

func (*EventSupervisingInvoker) InvokedStop

func (es *EventSupervisingInvoker) InvokedStop(cause interface{}, stat Stat, addr Addr, target Actor)

InvokedStop emits event containing stopped details.

type Eventer

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

Eventer implements the EventStream interface by decorating the gokit es event implementation.

func EventerWith

func EventerWith(em *es.EventStream) *Eventer

EventWith returns a instance of a Eventer using provided es.EventStream.

func NewEventer

func NewEventer() *Eventer

NewEventer returns a instance of a Eventer.

func (Eventer) Publish

func (e Eventer) Publish(m interface{})

Publish publishes a giving message.

func (Eventer) Reset

func (e Eventer) Reset()

Reset resets the underline event subscription list.

func (Eventer) Subscribe

func (e Eventer) Subscribe(handler Handler, predicate Predicate) Subscription

Subscribe adds a giving subscription using the provided handler and predicate.

type ExponentialBackOffSupervisor

type ExponentialBackOffSupervisor struct {
	Max     int
	Backoff time.Duration
	Invoker SupervisionInvoker
	Action  func(err interface{}, targetAddr Addr, target Actor, parent Actor) error
	// contains filtered or unexported fields
}

ExponentialBackOffSupervisor implements a supervisor which will attempt to exponentially run a giving action function continuously with an increasing backoff time, until it's maximum tries is reached.

func ExponentialBackOffRestartStrategy

func ExponentialBackOffRestartStrategy(max int, backoff time.Duration, invoker SupervisionInvoker) *ExponentialBackOffSupervisor

ExponentialBackOffRestartStrategy returns a new ExponentialBackOffSupervisor which will attempt to restart target actor where error occurred. If restart fail, it will continuously attempt till it has maxed out chances.

func ExponentialBackOffStopStrategy

func ExponentialBackOffStopStrategy(max int, backoff time.Duration, invoker SupervisionInvoker) *ExponentialBackOffSupervisor

ExponentialBackOffStopStrategy returns a new ExponentialBackOffSupervisor which will attempt to stop target actor where error occurred. If restart fail, it will continuously attempt till it has maxed out chances.

func (*ExponentialBackOffSupervisor) Handle

func (sp *ExponentialBackOffSupervisor) Handle(err interface{}, targetAddr Addr, target Actor, parent Actor)

Handle implements the exponential restart of giving target actor within giving maximum allowed runs.

type Future

type Future interface {
	Addr
	ErrWaiter

	// Pipe adds giving address as a receiver of the result
	// of giving future result or error.
	Pipe(...Addr)

	// PipeAction adds giving function as receiver of result
	// of giving future result or error.
	PipeAction(...func(Envelope))

	// Err returns an error if processing failed or if the timeout elapsed
	// or if the future was stopped.
	Err() error

	// Result returns the response received from the actors finished work.
	Result() Envelope
}

Future represents the address of a computation ongoing awaiting completion but will be completed in the future. It can be sent messages and can deliver events in accordance with it's state to all listeners. It can also be used to pipe it's resolution to other addresses.

type FutureImpl

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

FutureImpl defines an implementation the Future interface, it provides a type of address which defers the resolution of a underline result into the future and can be passed around like any address, where the result can be later retrieved using pipeTo feature.

func NewFuture

func NewFuture(parent Addr) *FutureImpl

NewFuture returns a new instance of giving future.

func TimedFuture

func TimedFuture(parent Addr, dur time.Duration) *FutureImpl

TimedFuture returns a new instance of giving future.

func (*FutureImpl) Actor

func (f *FutureImpl) Actor() Actor

Actor for a future does not exists, it is in a sense actor less, hence nil is returned.

func (*FutureImpl) Addr

func (f *FutureImpl) Addr() string

Addr returns s consistent address format representing a future addr.

func (*FutureImpl) AddressOf

func (f *FutureImpl) AddressOf(service string, ancestry bool) (Addr, error)

AddressOf requests giving service from future's parent AddressOf method.

func (*FutureImpl) Ancestor

func (f *FutureImpl) Ancestor() Addr

Ancestor returns the root parent address of the of giving Future.

func (*FutureImpl) Children

func (f *FutureImpl) Children() []Addr

Children returns an empty slice as futures can not have children actors.

func (*FutureImpl) DeathWatch

func (f *FutureImpl) DeathWatch(addr Addr) error

DeathWatch implements DeathWatch interface.

func (*FutureImpl) Err

func (f *FutureImpl) Err() error

Err returns the error for the failure of giving error.

func (*FutureImpl) Escalate

func (f *FutureImpl) Escalate(m interface{})

Escalate escalates giving value into the parent of giving future, which also fails future and resolves it as a failure.

func (*FutureImpl) Forward

func (f *FutureImpl) Forward(reply Envelope) error

Forward delivers giving envelope into Future actor which if giving future is not yet resolved will be the resolution of future.

func (*FutureImpl) Future

func (f *FutureImpl) Future() Future

Future returns a new future instance from giving source.

func (*FutureImpl) GetAddr

func (f *FutureImpl) GetAddr(addr string) (Addr, error)

GetAddr implements the Descendant interface but futures are not allowed to have children.

func (*FutureImpl) GetChild

func (f *FutureImpl) GetChild(id string, subID ...string) (Addr, error)

GetChild implements the Descendant interface but futures are not allowed to have children.

func (*FutureImpl) ID

func (f *FutureImpl) ID() string

ID returns the unique id of giving Future.

func (*FutureImpl) Namespace

func (f *FutureImpl) Namespace() string

Namespace returns future's parent namespace value.

func (*FutureImpl) Parent

func (f *FutureImpl) Parent() Addr

Parent returns the address of the parent of giving Future.

func (*FutureImpl) Pipe

func (f *FutureImpl) Pipe(addrs ...Addr)

Pipe adds giving set of address into giving Future.

func (*FutureImpl) PipeAction

func (f *FutureImpl) PipeAction(actions ...func(envelope Envelope))

PipeAction allows the addition of functions to be called with result of future.

func (*FutureImpl) Protocol

func (f *FutureImpl) Protocol() string

Protocol returns future's parent's protocol value.

func (*FutureImpl) ProtocolAddr

func (f *FutureImpl) ProtocolAddr() string

ProtocolAddr implements the ProtocolAddr interface. It always returns future@parent_namespace/service.

func (*FutureImpl) Resolve

func (f *FutureImpl) Resolve(env Envelope)

Resolve resolves giving future with envelope.

func (*FutureImpl) Result

func (f *FutureImpl) Result() Envelope

Result returns the envelope which is used to resolve the future.

func (*FutureImpl) Send

func (f *FutureImpl) Send(data interface{}, addr Addr) error

Send delivers giving data to resolve the future.

If data is a type of error then the giving future is rejected.

func (*FutureImpl) SendWithHeader

func (f *FutureImpl) SendWithHeader(data interface{}, h Header, addr Addr) error

SendWithHeader delivers giving data to Future as the resolution of said Future. The data provided will be used as the resolved value of giving future, if it's not already resolved.

If data is a type of error then the giving future is rejected.

func (*FutureImpl) Service

func (f *FutureImpl) Service() string

Service returns the "Future" as the service name of FutureImpl.

func (*FutureImpl) Spawn

func (f *FutureImpl) Spawn(service string, ops Prop) (Addr, error)

Spawn requests giving service and Receiver from future's parent Spawn method.

func (*FutureImpl) State

func (f *FutureImpl) State() Signal

State returns state of actor.

func (*FutureImpl) TimedFuture

func (f *FutureImpl) TimedFuture(d time.Duration) Future

TimedFuture returns a new future instance from giving source.

func (*FutureImpl) Wait

func (f *FutureImpl) Wait() error

Wait blocks till the giving future is resolved and returns error if occurred.

func (*FutureImpl) Watch

func (f *FutureImpl) Watch(fn func(interface{})) Subscription

Watch adds giving function into event system for future.

type FutureRejected

type FutureRejected struct {
	ID  string
	Err error
}

FutureRejected indicates the rejection of a giving future.

func (FutureRejected) Error

func (f FutureRejected) Error() string

Error implements the error interface.

func (FutureRejected) SystemMessage

func (FutureRejected) SystemMessage()

SystemMessage identifies giving type as a system message.

func (*FutureRejected) Unwrap

func (f *FutureRejected) Unwrap() error

Unwrap returns the original error for giving rejection, unravelling any further FutureRejected struct if gets.

type FutureResolved

type FutureResolved struct {
	ID   string
	Data interface{}
}

FutureResolved indicates the resolution of a giving future.

func (FutureResolved) SystemMessage

func (FutureResolved) SystemMessage()

SystemMessage identifies giving type as a system message.

type Futures

type Futures interface {
	// Future returns a new future instance from giving source.
	Future() Future

	// TimedFuture returns a new timed future instance from giving source.
	TimedFuture(time.Duration) Future
}

Futures defines an interface which exposes methods creating futures from a source

type Handler

type Handler func(interface{})

Handler defines a function type which is to be passed to a EventStream subscriber function.

type Hashed

type Hashed interface {
	Hash() string
}

Hashed defines a interface where it's implementers must expose a method which returns a string hash used for routing purposes.

type HashedRouter

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

HashedRouter implements a router which delivers messages to giving address based on hash value from message to possible address.

It stores address by their Addr.Addr() which means even if two Addr are referencing same Actor, they will be respected, added and broadcasted to, as the Addr represents a unique capability.

func NewHashedRouter

func NewHashedRouter(ref HashingReference, addrs ...Addr) *HashedRouter

NewHashedRouter returns a new instance of a HashedRouter.

func (*HashedRouter) Action

func (rr *HashedRouter) Action(addr Addr, msg Envelope)

Action implements the Behaviour interface.

type HashedSet

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

HashedSet implements a giving set which is unique in that it has a hash ring underline which is encoded to return specific keys for specific hash strings. It allows consistently retrieving same key for same hash.

func NewHashedSet

func NewHashedSet(set []string) *HashedSet

NewHashedSet returns a new instance of HashedSet.

func (*HashedSet) Add

func (hs *HashedSet) Add(n string)

Add adds giving item into set.

func (*HashedSet) Get

func (hs *HashedSet) Get(hashed string) (string, bool)

Get returns a giving item for provided hash value.

func (*HashedSet) Has

func (hs *HashedSet) Has(n string) bool

Has returns true/false if giving item is in set.

func (*HashedSet) Remove

func (hs *HashedSet) Remove(n string)

Remove removes giving item from set.

type HashingReference

type HashingReference func(Addr) string

HashingReference defines a function which is provided to the HashRouter which will return a string from a adderess. This allows custom values based of giving Addr to be returned as hashing input value.

type Header map[string]string

Header defines a map type to hold meta information associated with a Envelope.

func (Header) Get

func (m Header) Get(n string) string

Get returns the associated value from the map within the map.

func (Header) Has

func (m Header) Has(n string) bool

Has returns true/false value if key is present.

func (Header) Len

func (m Header) Len() int

Len returns the length of records within the meta.

func (Header) Map

func (m Header) Map() map[string]string

Map returns a map with contents of header.

type IDSet

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

IDSet implements a grouping of giving actor addresses using sets based on the Addr.ID(). It allows indexing, checking availability of giving address within set.

This is not safe for concurrent access.

func NewIDSet

func NewIDSet() *IDSet

NewIDSet returns a new instance of a IDSet.

func (*IDSet) Add

func (ad *IDSet) Add(addr Addr) bool

Add adds giving address into address set.

func (*IDSet) ForEach

func (ad *IDSet) ForEach(fx func(Addr, int) bool)

ForEach iterates through all available address against provided function. It expects the function to return true if it wishes to continue iteration or to stop by returning false.

func (*IDSet) Get

func (ad *IDSet) Get(service string) (Addr, bool)

Get returns giving Addr for a giving service string if in set.

func (*IDSet) Has

func (ad *IDSet) Has(id string) bool

Has returns true/false if giving underline address (string version) already exists in set.

func (*IDSet) HasAddr

func (ad *IDSet) HasAddr(addr Addr) bool

HasAddr returns true/false if giving underline address already exists in set.

func (*IDSet) Index

func (ad *IDSet) Index(id string) int

Index returns giving index of address (string version) if within set else returns -1.

func (*IDSet) IndexOf

func (ad *IDSet) IndexOf(addr Addr) int

IndexOf returns the giving index of address if in set else returns -1.

func (*IDSet) Remove

func (ad *IDSet) Remove(id string) bool

Remove removes giving address (string version from underline set).

func (*IDSet) RemoveAddr

func (ad *IDSet) RemoveAddr(addr Addr) bool

RemoveAddr removes giving address from set.

func (*IDSet) Set

func (ad *IDSet) Set() []Addr

Set exposes the provided underline list of Addr, this slice is only valid for use until the next call to Add or Remove. Hence you must be adequately careful here.

type Identity

type Identity interface {
	ID() string
}

Identity provides a method to return the ID of a process.

type Killable

type Killable interface {
	Kill() error
	KillChildren() error
}

Killable defines an interface that provides set of method to abruptly stop and end the operation of an actor ungracefully.

type Level

type Level uint8

Level defines different level warnings for giving log events.

const (
	INFO Level = 1 << iota
	DEBUG
	WARN
	ERROR
	PANIC
)

constants of log levels this package respect. They are capitalize to ensure no naming conflict.

func (Level) String

func (l Level) String() string

String implements the Stringer interface.

type LogEvent

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

*LogEvent implements a efficient zero or near zero-allocation as much as possible, using a underline non-strict json format to transform log key-value pairs into a LogMessage.

Each *LogEvent iss retrieved from a pool and will panic if after release/write it is used.

func LogMsg

func LogMsg(message string, inherits ...func(event *LogEvent)) *LogEvent

LogMsg requests allocation for a *LogEvent from the internal pool returning a *LogEvent for use which must be have it's Write() method called once done.

func LogMsgWithContext

func LogMsgWithContext(message string, ctx string, hook func(*LogEvent), inherits ...func(event *LogEvent)) *LogEvent

LogMsgWithContext requests allocation for a *LogEvent from the internal pool returning a *LogEvent for use. It packs the field into a internal map with the key for that map set to the value of ctx. which must be have it's Write() method called once done.

If a hook is provided then the hook is used to add field key-value pairs to the root of the returned json.

func (*LogEvent) Bool

func (l *LogEvent) Bool(name string, value bool) *LogEvent

Bool adds a field name with bool value.

func (*LogEvent) Buf

func (l *LogEvent) Buf() []byte

Buf returns the current content of the *LogEvent.

func (*LogEvent) Bytes

func (l *LogEvent) Bytes(name string, value []byte) *LogEvent

Bytes adds a field name with bytes value. The byte is expected to be valid JSON, no checks are made to ensure this, you can mess up your JSON if you do not use this correctly.

func (*LogEvent) Float64

func (l *LogEvent) Float64(name string, value float64) *LogEvent

Float64 adds a field name with float64 value.

func (*LogEvent) Int

func (l *LogEvent) Int(name string, value int) *LogEvent

Int adds a field name with int value.

func (*LogEvent) Int64

func (l *LogEvent) Int64(name string, value int64) *LogEvent

In64 adds a field name with int64 value.

func (*LogEvent) Message

func (l *LogEvent) Message() string

Message returns the generated JSON of giving *LogEvent.

func (*LogEvent) Object

func (l *LogEvent) Object(name string, handler func(event *LogEvent)) *LogEvent

Object adds a field name with object value.

func (*LogEvent) ObjectJSON

func (l *LogEvent) ObjectJSON(name string, value interface{}) *LogEvent

ObjectJSON adds a field name with object value.

func (*LogEvent) QBytes

func (l *LogEvent) QBytes(name string, value []byte) *LogEvent

QBytes adds a field name with bytes value. The byte is expected to be will be wrapped with quotation.

func (*LogEvent) String

func (l *LogEvent) String(name string, value string) *LogEvent

String adds a field name with string value.

func (*LogEvent) With

func (l *LogEvent) With(handler func(event *LogEvent)) *LogEvent

With applies giving function to the log event object.

func (*LogEvent) Write

func (l *LogEvent) Write(ll Level, lg Logs)

Write writes giving event into Logs using provided log level.

func (*LogEvent) WriteDebug

func (l *LogEvent) WriteDebug(lg Logs)

WriteDEBUG writes the underline logEvent into provided log as a DEBUG log level.

func (*LogEvent) WriteError

func (l *LogEvent) WriteError(lg Logs)

WriteError writes the underline logEvent into provided log as a ERROR log level.

func (*LogEvent) WriteInfo

func (l *LogEvent) WriteInfo(lg Logs)

WriteInfo writes the underline logEvent into provided log as a INFO log level.

func (*LogEvent) WritePanic

func (l *LogEvent) WritePanic(lg Logs)

WritePanic writes the underline logEvent into provided log as a PANIC log level.

func (*LogEvent) WriteWarn

func (l *LogEvent) WriteWarn(lg Logs)

WriteWARN writes the underline logEvent into provided log as a WARNING log level.

type LogMessage

type LogMessage interface {
	Message() string
}

LogMessage defines an interface which exposes a method for retrieving log details for giving log item.

type Logs

type Logs interface {
	Emit(Level, LogMessage)
}

Logs defines a acceptable logging interface which all elements and sub packages will respect and use to deliver logs for different parts and ops, this frees this package from specifying or locking a giving implementation and contaminating import paths. Implement this and pass in to elements that provide for it.

type MailInvoker

type MailInvoker interface {
	InvokedFull()
	InvokedEmpty()
	InvokedDropped(Addr, Envelope)
	InvokedReceived(Addr, Envelope)
	InvokedDispatched(Addr, Envelope)
}

MailInvoker defines an interface that exposes methods to signal status of a mailbox.

type Mailbox

type Mailbox interface {
	// Wait will block till a message or set of messages are available.
	Wait()

	// Clear resets and empties all pending elements of queue.
	Clear()

	// Signal will broadcast to all listeners to attempt checking for
	// new messages from blocking state.
	Signal()

	// Cap should returns maximum capacity for mailbox else -1 if unbounded.
	Cap() int

	// Total should return current total message counts in mailbox.
	Total() int

	// IsEmpty should return true/false if mailbox is empty.
	IsEmpty() bool

	// Unpop should add giving addr and envelope to head/start of mailbox
	// ensuring next retrieved message is this added envelope and address.
	Unpop(Addr, Envelope)

	// Push adds giving address and envelope to the end of the mailbox.
	Push(Addr, Envelope) error

	// Pop gets next messages from the top of the mailbox, freeing space
	// for more messages.
	Pop() (Addr, Envelope, error)
}

Mailbox defines a underline queue which provides the ability to adequately push and release a envelope received for later processing. Usually a mailbox is associated with a actor and managed by a distributor.

type MailboxOwner

type MailboxOwner interface {
	Mailbox() Mailbox
}

MailboxOwner exposes a single method to retrieve an implementer's Mailbox.

type Message

type Message string

Message defines a giving error string for use as a detail.

func (Message) Message

func (m Message) Message() string

Message implements the actorkit.LogEvent interface.

type MessageInvoker

type MessageInvoker interface {
	InvokedRequest(Addr, Envelope)
	InvokedProcessed(Addr, Envelope)
	InvokedProcessing(Addr, Envelope)
}

MessageInvoker defines a interface that exposes methods to signal different state of a process for external systems to plugin.

type Namespace

type Namespace interface {
	Namespace() string
}

Namespace exposes a self named method to get a giving value for namespace of implementer.

type OneForOneSupervisor

type OneForOneSupervisor struct {
	Max         int
	Delay       DelayProvider
	Decider     Decider
	PanicAction PanicAction
	Invoker     SupervisionInvoker
	// contains filtered or unexported fields
}

OneForOneSupervisor implements a one-to-one supervising strategy for giving actors.

func (*OneForOneSupervisor) Handle

func (on *OneForOneSupervisor) Handle(err interface{}, targetAddr Addr, target Actor, parent Actor)

Handle implements the Supervisor interface and provides the algorithm logic for the one-for-one monitoring strategy, where a failed actor is dealt with singularly without affecting it's siblings.

type OpMessage

type OpMessage struct {
	Detail string
	Data   interface{}
}

OpMessage defines a giving default type for containing data related to an operation detail.

func (OpMessage) Message

func (m OpMessage) Message() string

Message implements the LogEvent interface.

type PanicAction

type PanicAction func(interface{}, Addr, Actor)

PanicAction defines a function type which embodies the action to be done with panic'ed value.

type PanicEvent

type PanicEvent struct {
	Addr  Addr
	ID    string
	Panic interface{}
	Stack []byte

	CulpritAddr Addr
	CulpritMsg  Envelope
}

PanicEvent is sent when a actor internal routine panics due to message processor or some other error.

func (PanicEvent) SystemMessage

func (PanicEvent) SystemMessage()

SystemMessage identifies giving type as a system message.

type PostDestroy

type PostDestroy interface {
	PostDestroy(Addr)
}

PostDestroy defines a function to be called after the destruction of an actor. It is called after stopping routine.

type PostRestart

type PostRestart interface {
	PostRestart(Addr) error
}

PostRestart exposes a method which gets called after the restart of an actor.

If any error is returned, it will cause the actor to stop and shutdown.

type PostStart

type PostStart interface {
	PostStart(Addr) error
}

PostStart exposes a method which gets called after the start of an actor.

If any error is returned, it will cause the actor to stop and shutdown.

type PostStop

type PostStop interface {
	PostStop(Addr)
}

PostStop defines a function to be called after the stopping of an actor. It is called after stopping routine.

type PreDestroy

type PreDestroy interface {
	PreDestroy(Addr)
}

PreDestroy defines a function to be called after the destruction of an actor. It is called after stopping routine.

type PreRestart

type PreRestart interface {
	PreRestart(Addr) error
}

PreRestart exposes a method which gets called before the restart of an actor.

If any error is returned, it will cause the actor to stop and shutdown.

type PreStart

type PreStart interface {
	PreStart(Addr) error
}

PreStart exposes a method which gets called before the start of an actor.

If any error is returned, it will cause the actor to stop and shutdown.

type PreStop

type PreStop interface {
	PreStop(Addr)
}

PreStop defines a function to be called before the stopping of an actor. It is called before initiating the stop routine.

type Predicate

type Predicate func(interface{}) bool

Predicate defines a function for filtering by returning true/false for a giving value.

type Prop

type Prop struct {
	// ContextLog sets the context logger provider, which will be
	// if set to create a Logger which will be used by the actor
	// for logging, it's operations.
	//
	// It's expected child actors will inherit parent's Prop.ContextLogs
	// if they are provided none for use in creating Logs instance in
	// implementations.
	ContextLogs ContextLogs

	// Behaviour defines the behaviour to be used for handling
	// and processing incoming messages.
	Behaviour Behaviour

	// Event represent the local events coming from the
	// actor. Usually good to isolate events for actor
	// only and is what is bounded to by Actor.Watch.
	Event EventStream

	// Mailbox is the actors's mailbox to be used for queuing
	// incoming messages.
	Mailbox Mailbox

	// Signals is only ever accepted by a root actor who has
	// no parent, but instead parent's pass down their own signal
	// provider to their children/descendants. It provides a good
	// and easy way of accepting signal indicators for a giving
	// actor as it transitions between states.
	Signals Signals

	// Sentinel provides a advisor of behaviours to be performed
	// for actors being watched by owner of this prop. This allows
	// behaviours to be implemented or optionally provided. You can
	// also implement the Sentinel interface on the Behaviour implementer
	// instead.
	Sentinel Sentinel

	// DeadLetters provides a means of receiving dead mails i.e mails which
	// could not be processed by actor due to termination.
	DeadLetters DeadLetter

	// Supervisor defines the supervisor which the actor is to use for managing
	// it's state errors and child state errors.
	Supervisor Supervisor

	// StateInvoker defines the invoker called for update metrics or other uses cases
	// for different states of the actor.
	StateInvoker StateInvoker

	// MessageInvoker defines the invoker called for updating metrics on status of incoming
	// messages.
	MessageInvoker MessageInvoker

	// Discovery provides a overriding discovery service to be used for spawned actor
	// instead of inheriting from parent, if parent has any.
	Discovery DiscoveryService

	// MailInvoker defines the invoker called for updating metrics on mailbox usage.
	MailInvoker MailInvoker
}

Prop defines underline actor operation which are used to generate said handlers for an instantiated actor.

type Protocol

type Protocol interface {
	Protocol() string
}

Protocol exposes a self named method to get a giving value for procol of implementer.

type ProtocolAddr

type ProtocolAddr interface {
	ProtocolAddr() string
}

ProtocolAddr defines a self named function which returns a giving value representing it's protocol address.

type RandomRouter

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

RandomRouter implements a router which delivers messages to giving address based on one randomly chosen address from it's set of known addresses.

It stores address by their Addr.Addr() which means even if two Addr are referencing same Actor, they will be respected, added and broadcasted to, as the Addr represents a unique capability.

func NewRandomRouter

func NewRandomRouter(addrs ...Addr) *RandomRouter

NewRandomRouter returns a new instance of a RandomRouter.

func (*RandomRouter) Action

func (rr *RandomRouter) Action(addr Addr, msg Envelope)

Action implements the Behaviour interface.

type RandomSet

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

RandomSet implements a element set which returns a random item on every call to it's Get() method. It uses the internal random package, which is not truly random.

func NewRandomSet

func NewRandomSet() *RandomSet

NewRandomSet returns a new instance of RandomSet.

func (*RandomSet) Add

func (p *RandomSet) Add(proc string)

Add adds giving item into set.

func (*RandomSet) Get

func (p *RandomSet) Get() string

Get will return the next Process in a round-robin random fashion, allowing some form of distributed calls for different process to handle messages.

func (*RandomSet) Has

func (p *RandomSet) Has(s string) bool

Has returns true/false if giving item is in set.

func (*RandomSet) Remove

func (p *RandomSet) Remove(proc string)

Remove removes giving item from set.

func (*RandomSet) Total

func (p *RandomSet) Total() int

Total returns current total of items in round robin.

type Receiver

type Receiver interface {
	Receive(Addr, Envelope) error
}

Receiver defines an interface that exposes methods to receive envelopes and it's own used address.

type RemoveRoute

type RemoveRoute struct{}

RemoveRoute defines a giving message delivered for removing sending address from route list.

Used by the RoundRobin, RandomRouter, HashedRouter and Broadcast Router.

type Resolvable

type Resolvable interface {
	Resolve(Envelope)
}

Resolvable defines an interface which exposes a method for resolving the implementer.

type Restartable

type Restartable interface {
	Restart() error
	RestartChildren() error
}

Restartable defines an interface that exposes a method which returns a ErrWaiter to indicate completion of restart.

type RestartingSupervisor

type RestartingSupervisor struct {
	Delay   DelayProvider
	Invoker SupervisionInvoker
	// contains filtered or unexported fields
}

RestartingSupervisor implements a one-to-one supervising strategy for giving actors.

func (*RestartingSupervisor) Handle

func (sp *RestartingSupervisor) Handle(err interface{}, targetAddr Addr, target Actor, parent Actor)

Handle implements a restarting supervision strategy where any escalated error will lead to a restart of actor.

type RoundRobinRouter

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

RoundRobinRouter implements a router which delivers messages to giving address in a round robin manner. The router uses the Address.Addr() value to allow distinct addresses regardless if underline serving actor is the same to maintain address uniqueness and logic.

It stores address by their Addr.Addr() which means even if two Addr are referencing same Actor, they will be respected, added and broadcasted to, as the Addr represents a unique capability.

func NewRoundRobinRouter

func NewRoundRobinRouter(addrs ...Addr) *RoundRobinRouter

NewRoundRobinRouter returns a new instance of a RoundRobinRouter using provided address list if any to setup.

func (*RoundRobinRouter) Action

func (rr *RoundRobinRouter) Action(addr Addr, msg Envelope)

Action implements the Behaviour interface.

type RoundRobinSet

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

RoundRobinSet defines a process set/group which are processes offering the same service contract and will randomly based on index be provided when a process is needed for communication.

func NewRoundRobinSet

func NewRoundRobinSet() *RoundRobinSet

NewRoundRobinSet returns a new instance of RoundRobinSet.

func (*RoundRobinSet) Add

func (p *RoundRobinSet) Add(proc string)

Add adds giving item into set.

func (*RoundRobinSet) Get

func (p *RoundRobinSet) Get() string

Get will return the next Process in a round-robin random fashion, allowing some form of distributed calls for different process to handle messages.

func (*RoundRobinSet) Has

func (p *RoundRobinSet) Has(s string) bool

Has returns true/false if giving item is in set.

func (*RoundRobinSet) Remove

func (p *RoundRobinSet) Remove(proc string)

Remove removes giving item from set.

func (*RoundRobinSet) Total

func (p *RoundRobinSet) Total() int

Total returns current total of items in round robin.

type Sender

type Sender interface {
	// Forward forwards giving envelope to actor.
	Forward(Envelope) error

	// Send will deliver a message to the underline actor
	// with Addr set as sender .
	Send(interface{}, Addr) error

	// SendWithHeader will deliver a message to the underline actor
	// with Addr set as sender with a Header.
	SendWithHeader(interface{}, Header, Addr) error
}

Sender defines an interface that exposes methods to sending messages.

type Sentinel

type Sentinel interface {
	Advice(Addr, SystemMessage)
}

Sentinel exposes a method which handles necessarily logic for advising an action to be done for a watched actor. It allows notifications about said actor be handled and responded to.

Whilst Sentinel and Signals seem similar, sentinel are mainly for the purpose of taking actions against the calls of when a Addr is asked to watch another address. It allows you to provide a structure which sits to provide a means of executing sets of behaviours for when a actor wishes to work or act on a giving state of another actor which has no parent and child relationship with it, which means such an actor does not rely on it's supervisory strategy.

Sentinels will generally be inherited by child actors from parents if they do not provide their own, that is their general idea.

type Service

type Service interface {
	Service() string
}

Service defines an interface which exposes a method for retrieving service name.

type ServiceSet

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

ServiceSet implements a grouping of giving addresses using sets based on their service offered which is represented by the Addr.Addr(). It allows indexing, checking availability of giving address within set.

This is not safe for concurrent access.

func NewServiceSet

func NewServiceSet() *ServiceSet

NewServiceSet returns a new instance of a ServiceSet.

func (*ServiceSet) Add

func (ad *ServiceSet) Add(addr Addr) bool

Add adds giving address into address set.

func (*ServiceSet) ForEach

func (ad *ServiceSet) ForEach(fx func(Addr, int) bool)

ForEach iterates through all available address against provided function. It expects the function to return true if it wishes to continue iteration or to stop by returning false.

func (*ServiceSet) Get

func (ad *ServiceSet) Get(service string) (Addr, bool)

Get returns giving Addr for a giving service string if in set.

func (*ServiceSet) Has

func (ad *ServiceSet) Has(addr string) bool

Has returns true/false if giving underline address (string version) already exists in set.

func (*ServiceSet) HasAddr

func (ad *ServiceSet) HasAddr(addr Addr) bool

HasAddr returns true/false if giving underline address already exists in set.

func (*ServiceSet) Index

func (ad *ServiceSet) Index(addr string) int

Index returns giving index of address (string version) if within set else returns -1.

func (*ServiceSet) IndexOf

func (ad *ServiceSet) IndexOf(addr Addr) int

IndexOf returns the giving index of address if in set else returns -1.

func (*ServiceSet) Remove

func (ad *ServiceSet) Remove(service string) bool

Remove removes giving address (string version from underline set).

func (*ServiceSet) RemoveAddr

func (ad *ServiceSet) RemoveAddr(addr Addr) bool

RemoveAddr removes giving address from set.

func (*ServiceSet) Set

func (ad *ServiceSet) Set() []Addr

Set exposes the provided underline list of Addr, this slice is only valid for use until the next call to Add or Remove. Hence you must be adequately careful here.

type Signal

type Signal uint32

Signal represent a series of transitioning state which an actor runs through, it also provides a efficient means of checking actor's state.

const (
	INACTIVE Signal = 1 << iota
	STARTING
	RUNNING
	RESTARTING
	RESTARTED
	STOPPING
	STOPPED
	KILLING
	KILLED
	DESTRUCTING
	DESTROYED
	PANICED
	REJECTED
	RESOLVED
)

constants of different actor states transition used for signaling purposes.

func (Signal) String

func (s Signal) String() string

String returns a text version of state.

type Signals

type Signals interface {
	SignalState(Addr, Signal)
}

Signals defines a interesting interface which exposes a method for the reception of a current state of an actor. Useful for service discovery purposes and more.

type Spawner

type Spawner interface {
	Spawn(service string, props Prop) (Addr, error)
}

Spawner exposes a single method to spawn an underline actor returning the address for spawned actor.

Note: Children actors always get their global registry from their parents so if your root actor has no registry, then the kids won't get access to any.

type Startable

type Startable interface {
	Start() error
}

Startable defines an interface that exposes a method which returns a ErrWaiter to indicate completion of start process.

type Stat

type Stat struct {
	Death          time.Time
	Creation       time.Time
	Killed         int64
	Stopped        int64
	Delivered      int64
	Processed      int64
	Restarted      int64
	FailedRestarts int64
	FailedDelivery int64
}

Stat holds count and time details for a giving target or holder of stat.

type State

type State interface {
	State() Signal
}

State defines a function which returns the current state of it's implementer.

type StateInvoker

type StateInvoker interface {
	InvokedDestroyed(interface{})
	InvokedStarted(interface{})
	InvokedStopped(interface{})
	InvokedKilled(interface{})
	InvokedRestarted(interface{})
	InvokedPanic(Addr, PanicEvent)
}

StateInvoker defines an interface which signals an invocation of state of it's implementer.

type Stats

type Stats interface {
	Stats() Stat
}

Stats exposes a method which returns a giving Signal entity for it's implementer.

type Stoppable

type Stoppable interface {
	Stop() error
	StopChildren() error
}

Stoppable defines an interface that provides sets of method to gracefully stop the operation of a actor.

type Strategy

type Strategy int

Strategy defines a int type to represent a giving strategy.

const (
	DropNew Strategy = iota
	DropOld
)

constants.

type Subscription

type Subscription interface {
	Stop() error
}

Subscription defines a method which exposes a single method to remove giving subscription.

type SupervisionInvoker

type SupervisionInvoker interface {
	InvokedStop(cause interface{}, stat Stat, addr Addr, target Actor)
	InvokedKill(cause interface{}, stat Stat, addr Addr, target Actor)
	InvokedDestroy(cause interface{}, stat Stat, addr Addr, target Actor)
	InvokedRestart(cause interface{}, stat Stat, addr Addr, target Actor)
}

SupervisionInvoker defines a invocation watcher, which reports giving action taken for a giving error.

type Supervisor

type Supervisor interface {
	Handle(err interface{}, targetAddr Addr, target Actor, parent Actor)
}

Supervisor defines a single method which takes an occurred error with addr and actor which are related to error and also the parent of giving actor which then handles the error based on giving criteria and criticality.

type SupervisorEvent

type SupervisorEvent struct {
	Stat      Stat
	Addr      Addr
	Actor     string
	Time      time.Time
	Directive Directive
	Cause     interface{}
}

SupervisorEvent defines an event type which is published by the EventSupervisingInvoker.

type SwitchImpl

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

SwitchImpl implements a thread-safe switching mechanism, which swaps between a on and off state.

func NewSwitch

func NewSwitch() *SwitchImpl

NewSwitch returns a new instance of a SwitchImpl.

func (*SwitchImpl) IsOn

func (s *SwitchImpl) IsOn() bool

IsOn returns true/false if giving switch is on. Must be called only.

func (*SwitchImpl) Off

func (s *SwitchImpl) Off()

Off will flips switch into off state.

func (*SwitchImpl) On

func (s *SwitchImpl) On()

On will flips switch into on state.

func (*SwitchImpl) Wait

func (s *SwitchImpl) Wait()

Wait blocks till it receives signal that the switch has changed state, this can be used to await switch change.

type SystemMessage

type SystemMessage interface {
	SystemMessage()
}

SystemMessage defines a type to identify giving message data as a system message.

type Waiter

type Waiter interface {
	Wait()
}

Waiter exposes a single method which blocks till a given condition is met.

type WaiterImpl

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

WaiterImpl implements the ErrorWaiter interface.

func NewWaiterImpl

func NewWaiterImpl(err error) *WaiterImpl

NewWaiterImpl returns a new instance of WaiterImpl.

func (*WaiterImpl) Wait

func (w *WaiterImpl) Wait() error

Wait returns giving error associated with instance.

type Watchable

type Watchable interface {
	Watch(func(interface{})) Subscription
}

Watchable defines a interface that exposes methods to add functions to be called on some status change of the implementing instance.

Directories

Path Synopsis
examples
Package pubsubs implements remote communication in actorkit using message queues and pubsub services.
Package pubsubs implements remote communication in actorkit using message queues and pubsub services.
kafka
Package kafka provides 2 subpackages each implementing pubsub on top of kafka through the librdkafka c library and using the pure go implementation Samsara from Shopify.
Package kafka provides 2 subpackages each implementing pubsub on top of kafka through the librdkafka c library and using the pure go implementation Samsara from Shopify.
nats
Package nats implements different actor constructs for communicating with actor clusters and GNATS/NATS(https://github.com/nats-io/gnatsd/) cloud related services using actorkit and the actor paradigm.
Package nats implements different actor constructs for communicating with actor clusters and GNATS/NATS(https://github.com/nats-io/gnatsd/) cloud related services using actorkit and the actor paradigm.
redispb
Package redis implements pubsub communication over redis pubsub system for use in the actor framework.
Package redis implements pubsub communication over redis pubsub system for use in the actor framework.
Package runtimes implements different management runtime which connects to different communication channels to initiate and distribute work for a deployed actorkit system.
Package runtimes implements different management runtime which connects to different communication channels to initiate and distribute work for a deployed actorkit system.

Jump to

Keyboard shortcuts

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