protoactor-go: github.com/AsynkronIT/protoactor-go/actor Index | Examples | Files | Directories

package actor

import "github.com/AsynkronIT/protoactor-go/actor"

Package actor declares the types used to represent actors in the Actor Model.

The actors model provide a high level abstraction for writing concurrent and distributed systems. This approach simplifies the burden imposed on engineers, such as explicit locks and concurrent access to shared state, as actors receive messages synchronously.

The following quote from Wikipedia distills the definition of an actor down to its essence

In response to a message that it receives, an actor can: make local decisions, create more actors,
send more messages, and determine how to respond to the next message received.

Creating Actors

Props provide the building blocks for declaring how actors should be created. The following example defines an actor using a function literal to process messages:

var props Props = actor.FromFunc(func(c Context) {
	// process messages
})

Alternatively, a type which conforms to the Actor interface, by defining a single Receive method, can be used.

type MyActor struct {}

func (a *MyActor) Receive(c Context) {
	// process messages
}

var props Props = actor.FromInstance(&MyActor{})

Spawn and SpawnNamed use the given props to create a running instances of an actor. Once spawned, the actor is ready to process incoming messages. To spawn an actor with a unique name, use

pid := actor.Spawn(props)

The result of calling Spawn is a unique PID or process identifier.

Each time an actor is spawned, a new mailbox is created and associated with the PID. Messages are sent to the mailbox and then forwarded to the actor to process.

Processing Messages

An actor processes messages via its Receive handler. The signature of this function is:

Receive(c actor.Context)

The actor system guarantees that this method is called synchronously, therefore there is no requirement to protect shared state inside calls to this function. See the caution above

CAUTION: whilst spawning multiple actors from the same Props will have their own private mailbox, using FromInstance or FromFunc will reference the same instance or function and therefore should not modify shared state. Use FromProducer, which accepts a function that produces new Actor instances:

var props Props = actor.FromProducer(func() actor.Actor { return &MyActor{} })

Communicating With Actors

A PID is the primary interface for sending messages to actors. The PID.Tell method is used to send an asynchronous message to the actor associated with the PID:

pid.Tell("Hello World")

Depending on the requirements, communication between actors can take place synchronously or asynchronously. Regardless of the circumstances, actors always communicate via a PID.

When sending a message using PID.Request or PID.RequestFuture, the actor which receives the message will respond using the Context.Sender method, which returns the PID of of the sender.

For synchronous communication, an actor will use a Future and wait for the result before continuing. To send a message to an actor and wait for a response, use the RequestFuture method, which returns a Future:

f := actor.RequestFuture(pid,"Hello", 50 * time.Millisecond)
res, err := f.Result() // waits for pid to reply

Package actor is a generated protocol buffer package.

It is generated from these files:

protos.proto

It has these top-level messages:

PID
PoisonPill
Watch
Unwatch
Terminated
Stop

Demonstrates how to create an actor using a function literal and how to send a message asynchronously

Code:

var props *actor.Props = actor.FromFunc(func(c actor.Context) {
    if msg, ok := c.Message().(string); ok {
        fmt.Println(msg) // outputs "Hello World"
    }
})

pid := actor.Spawn(props)

pid.Tell("Hello World")
pid.GracefulStop() // wait for the actor to stop

Output:

Hello World

Demonstrates how to send a message from one actor to another and for the caller to wait for a response before proceeding

Code:

var wg sync.WaitGroup
wg.Add(1)

// callee will wait for the PING message
callee := actor.Spawn(actor.FromFunc(func(c actor.Context) {
    if msg, ok := c.Message().(string); ok {
        fmt.Println(msg) // outputs PING
        c.Respond("PONG")
    }
}))

// caller will send a PING message and wait for the PONG
caller := actor.Spawn(actor.FromFunc(func(c actor.Context) {
    switch msg := c.Message().(type) {
    // the first message an actor receives after it has started
    case *actor.Started:
        // send a PING to the callee, and specify the response
        // is sent to Self, which is this actor's PID
        c.Request(callee, "PING")

    case string:
        fmt.Println(msg) // PONG
        wg.Done()
    }
}))

wg.Wait()
callee.GracefulStop()
caller.GracefulStop()

Output:

PING
PONG

Index

Examples

Package Files

actor.go behaviorstack.go child_restart_stats.go context.go deadletter.go directive.go directive_string.go doc.go future.go local_context.go local_process.go log.go mailbox.go message_envelope.go message_producer.go messages.go middleware_chain.go options.go pid.go pidset.go process.go process_registry.go props.go protos.pb.go root_supervisor.go spawn.go strategy_all_for_one.go strategy_exponential_backoff.go strategy_one_for_one.go strategy_restarting.go supervision.go supervision_event.go

Variables

var (
    ErrInvalidLengthProtos = fmt.Errorf("proto: negative length found during unmarshaling")
    ErrIntOverflowProtos   = fmt.Errorf("proto: integer overflow")
)
var ErrNameExists = errors.New("spawn: name exists")

ErrNameExists is the error used when an existing name is used for spawning an actor.

var ErrTimeout = errors.New("future: timeout")

ErrTimeout is the error used when a future times out before receiving a result.

var ProcessRegistry = &ProcessRegistryValue{
    Address:   localAddress,
    LocalPIDs: cmap.New(),
}

ProcessRegistry is a registry of all active processes.

NOTE: This should only be used for advanced scenarios

func SetLogLevel Uses

func SetLogLevel(level log.Level)

SetLogLevel sets the log level for the logger.

SetLogLevel is safe to call concurrently

func SetOptions Uses

func SetOptions(opts ...optionFn)

SetOptions is used to configure the actor system

func UnwrapEnvelope Uses

func UnwrapEnvelope(message interface{}) (interface{}, *PID)

func WithDeadLetterSubscriber Uses

func WithDeadLetterSubscriber(fn func(evt interface{})) optionFn

WithDeadLetterSubscriber option replaces the default DeadLetterEvent event subscriber with fn.

fn will only receive *DeadLetterEvent messages

Specifying nil will clear the existing.

func WithSupervisorSubscriber Uses

func WithSupervisorSubscriber(fn func(evt interface{})) optionFn

WithSupervisorSubscriber option replaces the default SupervisorEvent event subscriber with fn.

fn will only receive *SupervisorEvent messages

Specifying nil will clear the existing.

type Actor Uses

type Actor interface {
    Receive(c Context)
}

Actor is the interface that defines the Receive method.

Receive is sent messages to be processed from the mailbox associated with the instance of the actor

type ActorFunc Uses

type ActorFunc func(c Context)

The ActorFunc type is an adapter to allow the use of ordinary functions as actors to process messages

func (ActorFunc) Receive Uses

func (f ActorFunc) Receive(c Context)

Receive calls f(c)

type AddressResolver Uses

type AddressResolver func(*PID) (Process, bool)

An AddressResolver is used to resolve remote actors

type AutoReceiveMessage Uses

type AutoReceiveMessage interface {
    AutoReceiveMessage()
}

An AutoReceiveMessage is a special kind of user message that will be handled in some way automatially by the actor

type Context Uses

type Context interface {
    // Watch registers the actor as a monitor for the specified PID
    Watch(pid *PID)

    // Unwatch unregisters the actor as a monitor for the specified PID
    Unwatch(pid *PID)

    // Message returns the current message to be processed
    Message() interface{}

    // Sender returns the PID of actor that sent currently processed message
    Sender() *PID

    //MessageHeader returns the meta information for the currently processed message
    MessageHeader() ReadonlyMessageHeader

    //Tell sends a message to the given PID
    Tell(pid *PID, message interface{})

    //Request sends a message to the given PID and also provides a Sender PID
    Request(pid *PID, message interface{})

    // RequestFuture sends a message to a given PID and returns a Future
    RequestFuture(pid *PID, message interface{}, timeout time.Duration) *Future

    // SetReceiveTimeout sets the inactivity timeout, after which a ReceiveTimeout message will be sent to the actor.
    // A duration of less than 1ms will disable the inactivity timer.
    //
    // If a message is received before the duration d, the timer will be reset. If the message conforms to
    // the NotInfluenceReceiveTimeout interface, the timer will not be reset
    SetReceiveTimeout(d time.Duration)

    // ReceiveTimeout returns the current timeout
    ReceiveTimeout() time.Duration

    // SetBehavior replaces the actors current behavior stack with the new behavior
    SetBehavior(behavior ActorFunc)

    // PushBehavior pushes the current behavior on the stack and sets the current Receive handler to the new behavior
    PushBehavior(behavior ActorFunc)

    // PopBehavior reverts to the previous Receive handler
    PopBehavior()

    // Self returns the PID for the current actor
    Self() *PID

    // Parent returns the PID for the current actors parent
    Parent() *PID

    // Spawn starts a new child actor based on props and named with a unique id
    Spawn(props *Props) *PID

    // SpawnPrefix starts a new child actor based on props and named using a prefix followed by a unique id
    SpawnPrefix(props *Props, prefix string) *PID

    // SpawnNamed starts a new child actor based on props and named using the specified name
    //
    // ErrNameExists will be returned if id already exists
    SpawnNamed(props *Props, id string) (*PID, error)

    // Returns a slice of the actors children
    Children() []*PID

    // Stash stashes the current message on a stack for reprocessing when the actor restarts
    Stash()

    // Respond sends a response to the to the current `Sender`
    //
    // If the Sender is nil, the actor will panic
    Respond(response interface{})

    // Actor returns the actor associated with this context
    Actor() Actor

    AwaitFuture(f *Future, continuation func(res interface{}, err error))
}

Context contains contextual information for actors

SetBehavior allows an actor to change its Receive handler, providing basic support for state machines

Code:

package main

import (
    "fmt"
    "sync"

    "github.com/AsynkronIT/protoactor-go/actor"
)

type setBehaviorActor struct {
    sync.WaitGroup
}

// Receive is the default message handler when an actor is started
func (f *setBehaviorActor) Receive(context actor.Context) {
    if msg, ok := context.Message().(string); ok && msg == "other" {
        // Change actor's receive message handler to Other
        context.SetBehavior(f.Other)
    }
}

func (f *setBehaviorActor) Other(context actor.Context) {
    if msg, ok := context.Message().(string); ok && msg == "foo" {
        fmt.Println(msg)
        f.Done()
    }
}

// SetBehavior allows an actor to change its Receive handler, providing basic support for state machines
func main() {
    a := &setBehaviorActor{}
    a.Add(1)
    pid := actor.Spawn(actor.FromInstance(a))
    defer pid.GracefulStop()

    pid.Tell("other")
    pid.Tell("foo")
    a.Wait()

}

SetReceiveTimeout allows an actor to be notified repeatedly if it does not receive any messages for a specified duration

Code:

package main

import (
    "fmt"
    "sync"
    "time"

    "github.com/AsynkronIT/protoactor-go/actor"
)

type setReceiveTimeoutActor struct {
    sync.WaitGroup
}

// Receive is the default message handler when an actor is started
func (f *setReceiveTimeoutActor) Receive(context actor.Context) {
    switch context.Message().(type) {

    case *actor.Started:
        // when the actor starts, set the receive timeout to 10 milliseconds.
        //
        // the system will send an *actor.ReceiveTimeout message every time the timeout
        // expires until SetReceiveTimeout is called again with a duration < 1 ms
        context.SetReceiveTimeout(10 * time.Millisecond)

    case *actor.ReceiveTimeout:
        fmt.Println("timed out")
        f.Done()
    }
}

// SetReceiveTimeout allows an actor to be notified repeatedly if it does not receive any messages
// for a specified duration
func main() {
    a := &setReceiveTimeoutActor{}
    a.Add(1)

    pid := actor.Spawn(actor.FromInstance(a))
    defer pid.GracefulStop()

    a.Wait() // wait for the ReceiveTimeout message

}

type DeadLetterEvent Uses

type DeadLetterEvent struct {
    PID     *PID        // The invalid process, to which the message was sent
    Message interface{} // The message that could not be delivered
    Sender  *PID        // the process that sent the Message
}

A DeadLetterEvent is published via event.Publish when a message is sent to a nonexistent PID

type DeciderFunc Uses

type DeciderFunc func(reason interface{}) Directive

DeciderFunc is a function which is called by a SupervisorStrategy

type Directive Uses

type Directive int

Directive is an enum for supervision actions

const (
    // ResumeDirective instructs the supervisor to resume the actor and continue processing messages
    ResumeDirective Directive = iota

    // RestartDirective instructs the supervisor to discard the actor, replacing it with a new instance,
    // before processing additional messages
    RestartDirective

    // StopDirective instructs the supervisor to stop the actor
    StopDirective

    // EscalateDirective instructs the supervisor to escalate handling of the failure to the actor's parent supervisor
    EscalateDirective
)

Directive determines how a supervisor should handle a faulting actor

func DefaultDecider Uses

func DefaultDecider(_ interface{}) Directive

DefaultDecider is a decider that will always restart the failing child actor

func (Directive) String Uses

func (i Directive) String() string

type Failure Uses

type Failure struct {
    Who          *PID
    Reason       interface{}
    RestartStats *RestartStatistics
    Message      interface{}
}

func (*Failure) SystemMessage Uses

func (*Failure) SystemMessage()

type Future Uses

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

func NewFuture Uses

func NewFuture(d time.Duration) *Future

NewFuture creates and returns a new actor.Future with a timeout of duration d

func (*Future) PID Uses

func (f *Future) PID() *PID

PID to the backing actor for the Future result

func (*Future) PipeTo Uses

func (f *Future) PipeTo(pids ...*PID)

PipeTo forwards the result or error of the future to the specified pids

Code:

var wg sync.WaitGroup
wg.Add(1)

// test actor that will be the target of the future PipeTo
pid := actor.Spawn(actor.FromFunc(func(ctx actor.Context) {
    // check if the message is a string and therefore
    // the "hello world" message piped from the future
    if m, ok := ctx.Message().(string); ok {
        fmt.Println(m)
        wg.Done()
    }
}))

f := actor.NewFuture(50 * time.Millisecond)
f.PipeTo(pid)
// resolve the future and pipe to waiting actor
f.PID().Tell("hello world")
wg.Wait()

Output:

hello world

func (*Future) Result Uses

func (f *Future) Result() (interface{}, error)

Result waits for the future to resolve

func (*Future) Wait Uses

func (f *Future) Wait() error

type InboundMiddleware Uses

type InboundMiddleware func(next ActorFunc) ActorFunc

type MessageEnvelope Uses

type MessageEnvelope struct {
    Header  messageHeader
    Message interface{}
    Sender  *PID
}

type MessageProducer Uses

type MessageProducer interface {
    // Tell sends a messages asynchronously to the PID
    Tell(pid *PID, message interface{})

    // Request sends a messages asynchronously to the PID. The actor may send a response back via respondTo, which is
    // available to the receiving actor via Context.Sender
    Request(pid *PID, message interface{}, respondTo *PID)

    // RequestFuture sends a message to a given PID and returns a Future
    RequestFuture(pid *PID, message interface{}, timeout time.Duration) *Future
}
var (
    EmptyContext MessageProducer = &rootMessageProducer{}
)

type NotInfluenceReceiveTimeout Uses

type NotInfluenceReceiveTimeout interface {
    NotInfluenceReceiveTimeout()
}

NotInfluenceReceiveTimeout messages will not reset the ReceiveTimeout timer of an actor that receives the message

type OutboundMiddleware Uses

type OutboundMiddleware func(next SenderFunc) SenderFunc

type PID Uses

type PID struct {
    Address string `protobuf:"bytes,1,opt,name=Address,proto3" json:"Address,omitempty"`
    Id      string `protobuf:"bytes,2,opt,name=Id,proto3" json:"Id,omitempty"`
    // contains filtered or unexported fields
}

func NewLocalPID Uses

func NewLocalPID(id string) *PID

NewLocalPID returns a new instance of the PID struct with the address preset

func NewPID Uses

func NewPID(address, id string) *PID

NewPID returns a new instance of the PID struct

func Spawn Uses

func Spawn(props *Props) *PID

Spawn starts a new actor based on props and named with a unique id

Spawn creates instances of actors, similar to 'new' or 'make' but for actors.

Code:

var wg sync.WaitGroup
wg.Add(1)

//define the actor props
//props define the creation process of an actor
props := actor.FromFunc(func(ctx actor.Context) {
    // check if the message is a *actor.Started message
    // this is the first message all actors get
    // actor.Started is received async and can be used
    // to initialize your actors initial state
    if _, ok := ctx.Message().(*actor.Started); ok {
        fmt.Println("hello world")
        wg.Done()
    }
})

// spawn the actor based on the props
actor.Spawn(props)
wg.Wait()

Output:

hello world

func SpawnNamed Uses

func SpawnNamed(props *Props, name string) (*PID, error)

SpawnNamed starts a new actor based on props and named using the specified name

If name exists, error will be ErrNameExists

Spawn creates instances of actors, similar to 'new' or 'make' but for actors.

Code:

var wg sync.WaitGroup
wg.Add(1)

//define the actor props
//props define the creation process of an actor
props := actor.FromFunc(func(ctx actor.Context) {
    // check if the message is a *actor.Started message
    // this is the first message all actors get
    // actor.Started is received async and can be used
    // to initialize your actors initial state
    if _, ok := ctx.Message().(*actor.Started); ok {
        fmt.Println("hello world")
        wg.Done()
    }
})

// spawn the actor based on the props
_, err := actor.SpawnNamed(props, "my-actor")
if err != nil {
    log.Fatal("The actor name is already in use")
}
wg.Wait()

Output:

hello world

func SpawnPrefix Uses

func SpawnPrefix(props *Props, prefix string) (*PID, error)

SpawnPrefix starts a new actor based on props and named using a prefix followed by a unique id

func (*PID) Descriptor Uses

func (*PID) Descriptor() ([]byte, []int)

func (*PID) Equal Uses

func (this *PID) Equal(that interface{}) bool

func (*PID) GetAddress Uses

func (m *PID) GetAddress() string

func (*PID) GetId Uses

func (m *PID) GetId() string

func (*PID) GracefulStop Uses

func (pid *PID) GracefulStop()

func (*PID) Marshal Uses

func (m *PID) Marshal() (dAtA []byte, err error)

func (*PID) MarshalTo Uses

func (m *PID) MarshalTo(dAtA []byte) (int, error)

func (*PID) ProtoMessage Uses

func (*PID) ProtoMessage()

func (*PID) Request Uses

func (pid *PID) Request(message interface{}, respondTo *PID)

Request sends a messages asynchronously to the PID. The actor may send a response back via respondTo, which is available to the receiving actor via Context.Sender

func (*PID) RequestFuture Uses

func (pid *PID) RequestFuture(message interface{}, timeout time.Duration) *Future

RequestFuture sends a message to a given PID and returns a Future

func (*PID) Reset Uses

func (m *PID) Reset()

func (*PID) Size Uses

func (m *PID) Size() (n int)

func (*PID) Stop Uses

func (pid *PID) Stop()

Stop the given PID

func (*PID) StopFuture Uses

func (pid *PID) StopFuture() *Future

func (*PID) String Uses

func (pid *PID) String() string

func (*PID) Tell Uses

func (pid *PID) Tell(message interface{})

Tell sends a messages asynchronously to the PID

func (*PID) Unmarshal Uses

func (m *PID) Unmarshal(dAtA []byte) error

type PIDSet Uses

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

func NewPIDSet Uses

func NewPIDSet(pids ...*PID) *PIDSet

NewPIDSet returns a new PIDSet with the given pids.

func (*PIDSet) Add Uses

func (p *PIDSet) Add(v *PID)

Add adds the element v to the set

func (*PIDSet) Clear Uses

func (p *PIDSet) Clear()

Clear removes all the elements in the set

func (*PIDSet) Contains Uses

func (p *PIDSet) Contains(v *PID) bool

Contains reports whether v is an element of the set

func (*PIDSet) Empty Uses

func (p *PIDSet) Empty() bool

Empty reports whether the set is empty

func (*PIDSet) ForEach Uses

func (p *PIDSet) ForEach(f func(i int, pid PID))

ForEach invokes f for every element of the set

func (*PIDSet) Len Uses

func (p *PIDSet) Len() int

Len returns the number of elements in the set

func (*PIDSet) Remove Uses

func (p *PIDSet) Remove(v *PID) bool

Remove removes v from the set and returns true if them element existed

func (*PIDSet) Values Uses

func (p *PIDSet) Values() []PID

Values returns all the elements of the set as a slice

type PoisonPill Uses

type PoisonPill struct {
}

user messages

func (*PoisonPill) AutoReceiveMessage Uses

func (*PoisonPill) AutoReceiveMessage()

func (*PoisonPill) Descriptor Uses

func (*PoisonPill) Descriptor() ([]byte, []int)

func (*PoisonPill) Equal Uses

func (this *PoisonPill) Equal(that interface{}) bool

func (*PoisonPill) Marshal Uses

func (m *PoisonPill) Marshal() (dAtA []byte, err error)

func (*PoisonPill) MarshalTo Uses

func (m *PoisonPill) MarshalTo(dAtA []byte) (int, error)

func (*PoisonPill) ProtoMessage Uses

func (*PoisonPill) ProtoMessage()

func (*PoisonPill) Reset Uses

func (m *PoisonPill) Reset()

func (*PoisonPill) Size Uses

func (m *PoisonPill) Size() (n int)

func (*PoisonPill) String Uses

func (this *PoisonPill) String() string

func (*PoisonPill) Unmarshal Uses

func (m *PoisonPill) Unmarshal(dAtA []byte) error

type Process Uses

type Process interface {
    SendUserMessage(pid *PID, message interface{})
    SendSystemMessage(pid *PID, message interface{})
    Stop(pid *PID)
}

A Process is an interface that defines the base contract for interaction of actors

type ProcessRegistryValue Uses

type ProcessRegistryValue struct {
    Address        string
    LocalPIDs      cmap.ConcurrentMap
    RemoteHandlers []AddressResolver
    SequenceID     uint64
}

func (*ProcessRegistryValue) Add Uses

func (pr *ProcessRegistryValue) Add(process Process, id string) (*PID, bool)

func (*ProcessRegistryValue) Get Uses

func (pr *ProcessRegistryValue) Get(pid *PID) (Process, bool)

func (*ProcessRegistryValue) GetLocal Uses

func (pr *ProcessRegistryValue) GetLocal(id string) (Process, bool)

func (*ProcessRegistryValue) NextId Uses

func (pr *ProcessRegistryValue) NextId() string

func (*ProcessRegistryValue) RegisterAddressResolver Uses

func (pr *ProcessRegistryValue) RegisterAddressResolver(handler AddressResolver)

func (*ProcessRegistryValue) Remove Uses

func (pr *ProcessRegistryValue) Remove(pid *PID)

type Producer Uses

type Producer func() Actor

The Producer type is a function that creates a new actor

type Props Uses

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

Props represents configuration to define how an actor should be created

func FromFunc Uses

func FromFunc(f ActorFunc) *Props

FromFunc creates a props with the given receive func assigned as the actor producer

func FromInstance Uses

func FromInstance(template Actor) *Props

FromInstance creates a props with the given instance assigned as the actor producer

func FromProducer Uses

func FromProducer(actorProducer Producer) *Props

FromProducer creates a props with the given actor producer assigned

func FromSpawnFunc Uses

func FromSpawnFunc(spawn SpawnFunc) *Props

func (*Props) WithDispatcher Uses

func (props *Props) WithDispatcher(dispatcher mailbox.Dispatcher) *Props

WithDispatcher assigns a dispatcher to the props

func (*Props) WithFunc Uses

func (props *Props) WithFunc(f ActorFunc) *Props

WithFunc assigns a receive func to the props

func (*Props) WithInstance Uses

func (props *Props) WithInstance(a Actor) *Props

WithInstance creates a custom actor producer from a given instance and assigns it to the props

func (*Props) WithMailbox Uses

func (props *Props) WithMailbox(mailbox mailbox.Producer) *Props

WithMailbox assigns the desired mailbox producer to the props

func (*Props) WithMiddleware Uses

func (props *Props) WithMiddleware(middleware ...InboundMiddleware) *Props

Assign one or more middlewares to the props

func (*Props) WithOutboundMiddleware Uses

func (props *Props) WithOutboundMiddleware(middleware ...OutboundMiddleware) *Props

func (*Props) WithProducer Uses

func (props *Props) WithProducer(p Producer) *Props

WithProducer assigns a actor producer to the props

func (*Props) WithSpawnFunc Uses

func (props *Props) WithSpawnFunc(spawn SpawnFunc) *Props

WithSpawnFunc assigns a custom spawn func to the props, this is mainly for internal usage

func (*Props) WithSupervisor Uses

func (props *Props) WithSupervisor(supervisor SupervisorStrategy) *Props

WithSupervisor assigns a supervision strategy to the props

type ReadonlyMessageHeader Uses

type ReadonlyMessageHeader interface {
    Get(key string) string
    Keys() []string
}

type ReceiveTimeout Uses

type ReceiveTimeout struct{}

A ReceiveTimeout message is sent to an actor after the Context.ReceiveTimeout duration has expired

type Restart Uses

type Restart struct{}

Restart is message sent by the actor system to control the lifecycle of an actor

func (*Restart) SystemMessage Uses

func (*Restart) SystemMessage()

type RestartStatistics Uses

type RestartStatistics struct {
    FailureCount    int
    LastFailureTime time.Time
}

RestartStatistics keeps track of how many times an actor have restarted and when

func (*RestartStatistics) Fail Uses

func (rs *RestartStatistics) Fail()

Fail increases the associated actors failure count

func (*RestartStatistics) IsWithinDuration Uses

func (rs *RestartStatistics) IsWithinDuration(withinDuration time.Duration) bool

IsWithinDuration checks if a given duration is within the timespan from now to the last falure timestamp

func (*RestartStatistics) Reset Uses

func (rs *RestartStatistics) Reset()

Reset the associated actors failure count

func (*RestartStatistics) Restart Uses

func (rs *RestartStatistics) Restart()

Restart sets the last failure timestamp for the associated actor

type Restarting Uses

type Restarting struct{}

A Restarting message is sent to an actor when the actor is being restarted by the system due to a failure

func (*Restarting) AutoReceiveMessage Uses

func (*Restarting) AutoReceiveMessage()

type SenderFunc Uses

type SenderFunc func(c Context, target *PID, envelope *MessageEnvelope)

type SpawnFunc Uses

type SpawnFunc func(id string, props *Props, parent *PID) (*PID, error)
var DefaultSpawner SpawnFunc = spawn

DefaultSpawner conforms to Spawner and is used to spawn a local actor

type Started Uses

type Started struct{}

A Started message is sent to an actor once it has been started and ready to begin receiving messages.

func (*Started) SystemMessage Uses

func (*Started) SystemMessage()

type Stop Uses

type Stop struct {
}

func (*Stop) Descriptor Uses

func (*Stop) Descriptor() ([]byte, []int)

func (*Stop) Equal Uses

func (this *Stop) Equal(that interface{}) bool

func (*Stop) Marshal Uses

func (m *Stop) Marshal() (dAtA []byte, err error)

func (*Stop) MarshalTo Uses

func (m *Stop) MarshalTo(dAtA []byte) (int, error)

func (*Stop) ProtoMessage Uses

func (*Stop) ProtoMessage()

func (*Stop) Reset Uses

func (m *Stop) Reset()

func (*Stop) Size Uses

func (m *Stop) Size() (n int)

func (*Stop) String Uses

func (this *Stop) String() string

func (*Stop) SystemMessage Uses

func (*Stop) SystemMessage()

func (*Stop) Unmarshal Uses

func (m *Stop) Unmarshal(dAtA []byte) error

type Stopped Uses

type Stopped struct{}

A Stopped message is sent to the actor once it has been stopped. A stopped actor will receive no further messages

func (*Stopped) AutoReceiveMessage Uses

func (*Stopped) AutoReceiveMessage()

type Stopping Uses

type Stopping struct{}

A Stopping message is sent to an actor prior to the actor being stopped

func (*Stopping) AutoReceiveMessage Uses

func (*Stopping) AutoReceiveMessage()

type Supervisor Uses

type Supervisor interface {
    Children() []*PID
    EscalateFailure(reason interface{}, message interface{})
    RestartChildren(pids ...*PID)
    StopChildren(pids ...*PID)
    ResumeChildren(pids ...*PID)
}

Supervisor is an interface that is used by the SupervisorStrategy to manage child actor lifecycle

type SupervisorEvent Uses

type SupervisorEvent struct {
    Child     *PID
    Reason    interface{}
    Directive Directive
}

SupervisorEvent is sent on the EventStream when a supervisor have applied a directive to a failing child actor

type SupervisorStrategy Uses

type SupervisorStrategy interface {
    HandleFailure(supervisor Supervisor, child *PID, rs *RestartStatistics, reason interface{}, message interface{})
}

SupervisorStrategy is an interface that decides how to handle failing child actors

func DefaultSupervisorStrategy Uses

func DefaultSupervisorStrategy() SupervisorStrategy

func NewAllForOneStrategy Uses

func NewAllForOneStrategy(maxNrOfRetries int, withinDuration time.Duration, decider DeciderFunc) SupervisorStrategy

NewAllForOneStrategy returns a new SupervisorStrategy which applies the given fault Directive from the decider to the failing child and all its children.

This strategy is appropriate when the children have a strong dependency, such that and any single one failing would place them all into a potentially invalid state.

func NewExponentialBackoffStrategy Uses

func NewExponentialBackoffStrategy(backoffWindow time.Duration, initialBackoff time.Duration) SupervisorStrategy

NewExponentialBackoffStrategy creates a new Supervisor strategy that restarts a faulting child using an exponential back off algorithm:

delay =

func NewOneForOneStrategy Uses

func NewOneForOneStrategy(maxNrOfRetries int, withinDuration time.Duration, decider DeciderFunc) SupervisorStrategy

NewOneForOneStrategy returns a new Supervisor strategy which applies the fault Directive from the decider to the failing child process.

This strategy is applicable if it is safe to handle a single child in isolation from its peers or dependents

func NewRestartingStrategy Uses

func NewRestartingStrategy() SupervisorStrategy

func RestartingSupervisorStrategy Uses

func RestartingSupervisorStrategy() SupervisorStrategy

type SystemMessage Uses

type SystemMessage interface {
    SystemMessage()
}

A SystemMessage message is reserved for specific lifecycle messages used by the actor system

type Terminated Uses

type Terminated struct {
    Who               *PID `protobuf:"bytes,1,opt,name=who" json:"who,omitempty"`
    AddressTerminated bool `protobuf:"varint,2,opt,name=address_terminated,json=addressTerminated,proto3" json:"address_terminated,omitempty"`
}

func (*Terminated) Descriptor Uses

func (*Terminated) Descriptor() ([]byte, []int)

func (*Terminated) Equal Uses

func (this *Terminated) Equal(that interface{}) bool

func (*Terminated) GetAddressTerminated Uses

func (m *Terminated) GetAddressTerminated() bool

func (*Terminated) GetWho Uses

func (m *Terminated) GetWho() *PID

func (*Terminated) Marshal Uses

func (m *Terminated) Marshal() (dAtA []byte, err error)

func (*Terminated) MarshalTo Uses

func (m *Terminated) MarshalTo(dAtA []byte) (int, error)

func (*Terminated) ProtoMessage Uses

func (*Terminated) ProtoMessage()

func (*Terminated) Reset Uses

func (m *Terminated) Reset()

func (*Terminated) Size Uses

func (m *Terminated) Size() (n int)

func (*Terminated) String Uses

func (this *Terminated) String() string

func (*Terminated) SystemMessage Uses

func (*Terminated) SystemMessage()

func (*Terminated) Unmarshal Uses

func (m *Terminated) Unmarshal(dAtA []byte) error

type Unwatch Uses

type Unwatch struct {
    Watcher *PID `protobuf:"bytes,1,opt,name=watcher" json:"watcher,omitempty"`
}

func (*Unwatch) Descriptor Uses

func (*Unwatch) Descriptor() ([]byte, []int)

func (*Unwatch) Equal Uses

func (this *Unwatch) Equal(that interface{}) bool

func (*Unwatch) GetWatcher Uses

func (m *Unwatch) GetWatcher() *PID

func (*Unwatch) Marshal Uses

func (m *Unwatch) Marshal() (dAtA []byte, err error)

func (*Unwatch) MarshalTo Uses

func (m *Unwatch) MarshalTo(dAtA []byte) (int, error)

func (*Unwatch) ProtoMessage Uses

func (*Unwatch) ProtoMessage()

func (*Unwatch) Reset Uses

func (m *Unwatch) Reset()

func (*Unwatch) Size Uses

func (m *Unwatch) Size() (n int)

func (*Unwatch) String Uses

func (this *Unwatch) String() string

func (*Unwatch) SystemMessage Uses

func (*Unwatch) SystemMessage()

func (*Unwatch) Unmarshal Uses

func (m *Unwatch) Unmarshal(dAtA []byte) error

type Watch Uses

type Watch struct {
    Watcher *PID `protobuf:"bytes,1,opt,name=watcher" json:"watcher,omitempty"`
}

system messages

func (*Watch) Descriptor Uses

func (*Watch) Descriptor() ([]byte, []int)

func (*Watch) Equal Uses

func (this *Watch) Equal(that interface{}) bool

func (*Watch) GetWatcher Uses

func (m *Watch) GetWatcher() *PID

func (*Watch) Marshal Uses

func (m *Watch) Marshal() (dAtA []byte, err error)

func (*Watch) MarshalTo Uses

func (m *Watch) MarshalTo(dAtA []byte) (int, error)

func (*Watch) ProtoMessage Uses

func (*Watch) ProtoMessage()

func (*Watch) Reset Uses

func (m *Watch) Reset()

func (*Watch) Size Uses

func (m *Watch) Size() (n int)

func (*Watch) String Uses

func (this *Watch) String() string

func (*Watch) SystemMessage Uses

func (*Watch) SystemMessage()

func (*Watch) Unmarshal Uses

func (m *Watch) Unmarshal(dAtA []byte) error

Directories

PathSynopsis
middleware
middleware/protozip

Package actor imports 18 packages (graph) and is imported by 14 packages. Updated 2017-10-18. Refresh now. Tools for package owners.