actor

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2026 License: MIT Imports: 17 Imported by: 5 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package actor is optional structure on top of grpcproc processes: a handler loop in the style of gen_server, and supervisors that restart what fails. It uses only grpcproc's public API, so it can be ignored or replaced.

An actor is a plain struct holding its dependencies, built by a constructor, so it fits a DI container:

type Orders struct{ repo *Repo }

func (o *Orders) HandleMessage(p *grpcproc.Process[*orderspb.Order], m grpcproc.Msg[*orderspb.Order]) error { … }
func (o *Orders) HandleCall(p *grpcproc.Process[*orderspb.Order], m grpcproc.Msg[*orderspb.Order]) (proto.Message, error) { … }

addr, err := node.Spawn(actor.Run(&Orders{repo: repo}), grpcproc.WithName("orders"))

Index

Constants

View Source
const Infinity time.Duration = -1

Infinity, as a Shutdown, waits for a child to exit however long that takes. It is the default for a child that is itself a supervisor, which needs the time to stop its own children in order: a subtree that is still stopping must not be started again beside itself.

View Source
const ReasonMaxRestarts = "max restarts"

ReasonMaxRestarts is the exit reason of a supervisor that restarted its children more often than Spec allows. It is abnormal, so the supervisor's own supervisor restarts it: that is how failure escalates.

Variables

View Source
var (
	// ErrStop, returned from a handler, ends the actor normally. From
	// HandleCall, the reply is sent first.
	ErrStop = errors.New("actor: stop")
	// ErrNoReply, returned from HandleCall, means the actor will answer
	// later with m.Reply(…).
	ErrNoReply = errors.New("actor: reply later")
)
View Source
var ErrAlreadyStarted = errors.New("actor: StartChild: a child of that name is running already")

ErrAlreadyStarted is StartChild's error when the supervisor has a child of the spec's name running already. StartChild returns that child's PID with it.

View Source
var ErrBusy = errors.New("actor: the supervisor is waiting for a child to exit; try again")

ErrBusy is what a supervisor answers a call with, StartChild, StopChild and Children included, once it has waited past busyAfter for a child to exit: try again.

View Source
var ErrNoFactory = errors.New("actor: StartChildFrom: the supervisor has no factory of that name")

ErrNoFactory is StartChildFrom's error when the supervisor has no factory of that name.

Functions

func Run

func Run[M proto.Message](h Handler[M]) func(*grpcproc.Process[M]) error

Run turns a Handler into a process function, for Node.Spawn, Process.Spawn or Process.SpawnMonitor.

func StartChild added in v0.0.4

func StartChild(ctx context.Context, from grpcproc.Caller, sup grpcproc.Target, spec ChildSpec) (grpcproc.PID, error)

StartChild adds spec to the supervisor sup and starts the child, after the children sup has already: it returns once the child has started. from is who asks, the Node or a Process, as for grpcproc.Addr.Call, and must be on sup's node: a spec holds Go functions, which no message can carry, and sup refuses a caller of another node. The child is sup's like the others, except that once it ends for good (it is temporary, or transient and ended normally, or StopChild stopped it), sup forgets it. Anonymous children, with an empty Name, are how a supervisor keeps a pool of workers, each started as it is needed.

If sup has a child of spec's name running already, StartChild starts nothing and returns that child's PID with ErrAlreadyStarted, so a caller that means to start a named child unless it runs takes the PID either way. A child of that name that has exited, and whose exit sup has yet to handle, is waited for: sup restarts it, which is then the child that runs, or forgets it and starts spec.

The spec is checked as in Spec, and a child that fails to start is an error, which sup does not count as a restart. sup's errors come back as *grpcproc.RemoteError, which is ErrBusy to errors.Is when sup was busy. If ctx ends first, the child may still start.

From a process, pass p.Context(): a supervisor that is stopping the caller answers no call until it is done, and a caller that waits with a ctx of its own cannot exit meanwhile.

func StartChildFrom added in v0.3.0

func StartChildFrom(ctx context.Context, from grpcproc.Caller, sup grpcproc.Target, factory string, arg proto.Message, opts ...StartOption) (grpcproc.PID, grpcproc.Ref, error)

StartChildFrom asks the supervisor sup, which may run on another node, to start the child its factory named factory builds from arg (see Spec.Factories), after the children sup has already, and returns once the child has started. It is StartChild for a caller that cannot hand sup a spec, Go functions that no message carries: arg is data, and the factory, on sup's node, turns it into a spec there. The child is sup's as one StartChild added is, forgotten once it ends for good.

With WithMonitor, the caller monitors the child from before it runs, as Process.SpawnMonitor does a child of its own node: however soon the child exits, its Down comes after StartChildFrom returns, with the Ref it returned and the real reason, never noproc. WithLink links the caller to the child instead, as grpcproc.LinkChild does. Either needs from to be a process, the only kind of caller a Down or an exit reaches. A start that fails leaves no monitor or link behind, and no Down comes of it: the error says it failed, which a Down never does. Once StartChildFrom has returned the child, a link to sup's node that breaks is its Down, with noconnection.

As with StartChild, a child of the spec's name that runs already is not started again: StartChildFrom returns its PID with ErrAlreadyStarted, and the monitor or link, on that child. So when an answer is lost, a link that broke or a ctx that ended, a named child may have started unwatched, and starting it again finds it, with a watch. An anonymous child has no name to be found by: sup lists it (Children), and it runs until it ends. The watch is of the child's process: a restart sup makes is a new one, which StartChildFrom of the name watches again.

pid, ref, err := actor.StartChildFrom(p.Context(), p, sup, "peer", &roomspb.Join{Peer: id}, actor.WithMonitor())
switch {
case errors.Is(err, ErrFull):
	// try another node
case err != nil && !errors.Is(err, actor.ErrAlreadyStarted):
	return err
}
// A Down with ref comes when pid exits, however soon.

The factory's refusal is the error, as the factory returned it, which errors.Is tells apart; ErrNoFactory when sup has no factory of that name. The other errors are StartChild's.

func StopChild added in v0.0.4

func StopChild(ctx context.Context, from grpcproc.Caller, sup grpcproc.Target, child grpcproc.PID) error

StopChild stops child, a running child of the supervisor sup, and makes sup forget it: it is not restarted, whatever its Restart, and a strategy no longer counts it, until sup itself is started again from its Spec. A significant child stopped this way does not end sup. sup may run on another node. from is who asks, as for StartChild; from a process, pass p.Context() as StartChild says.

func Supervise

func Supervise(n *grpcproc.Node, spec Spec, opts ...grpcproc.SpawnOption) (grpcproc.PID, error)

Supervise starts a supervisor on n and its children, in order. It returns once they have all started, or with the first error, after stopping those already started. opts apply to the supervisor itself (a name, a label).

Types

type AutoShutdown added in v0.0.4

type AutoShutdown uint8

AutoShutdown says whether a supervisor ends itself when its significant children end (see ChildSpec.Significant). It then exits with reason "shutdown", after stopping its other children: a supervisor above it restarts it only if it is a permanent child there.

const (
	// NoAutoShutdown: the supervisor has no significant children.
	NoAutoShutdown AutoShutdown = iota
	// AnySignificant: the supervisor ends when any significant child does.
	AnySignificant
	// AllSignificant: the supervisor ends when all its significant children
	// have.
	AllSignificant
)

func (AutoShutdown) String added in v0.0.4

func (a AutoShutdown) String() string

type CallHandler

type CallHandler[M proto.Message] interface {
	HandleCall(p *grpcproc.Process[M], m grpcproc.Msg[M]) (proto.Message, error)
}

CallHandler answers calls: the returned message, or error, is the reply, and the actor carries on. Return ErrNoReply to answer later with m.Reply(…), from any goroutine; ErrStop to reply and then stop.

Without it, a call is answered with an error.

type CallsOnly

type CallsOnly[M proto.Message] struct{}

CallsOnly provides HandleMessage for an actor that only answers calls; embed it by value. A message sent to the actor with Send is logged at Warn and dropped, and the actor carries on, as gen_server's default handle_info does: a stray sender cannot crash it.

type Pricer struct {
	actor.CallsOnly[*pricespb.Quote]
	table *Table
}

func (pr *Pricer) HandleCall(p *grpcproc.Process[*pricespb.Quote], m grpcproc.Msg[*pricespb.Quote]) (proto.Message, error) { … }

addr, err := node.Spawn(actor.Run(&Pricer{table: table}))

Run panics for an actor that embeds CallsOnly but has no HandleCall, which is what spawning Pricer{} rather than &Pricer{} gives.

func (CallsOnly[M]) HandleMessage

func (CallsOnly[M]) HandleMessage(p *grpcproc.Process[M], m grpcproc.Msg[M]) error

HandleMessage logs m and drops it.

type ChildInfo added in v0.2.0

type ChildInfo struct {
	// Name is the child's name in the supervisor, and on the node; empty
	// for an anonymous child.
	Name string
	// PID is the child's process while it runs, and zero while it does not:
	// it has ended for good, or it is Restarting.
	PID grpcproc.PID
	// Restarting reports that a restart owes the child a start, which waits
	// for a previous process, the child's own or an earlier child's, to exit.
	Restarting bool
	Restart    Restart
	// Restarts is how many times the supervisor has restarted the child.
	Restarts int
	// Supervisor reports that the child is a supervisor itself.
	Supervisor bool
}

ChildInfo is one of a supervisor's children, as Children reports it.

func Children added in v0.2.0

func Children(ctx context.Context, from grpcproc.Caller, sup grpcproc.Target) ([]ChildInfo, error)

Children asks the supervisor sup which children it has, in the order it starts them: those of its Spec, then those StartChild added, until they end for good. It reports them as sup knows them when it answers, so a child that has just exited may still be listed as running until sup has handled its exit, and the list is out of date as soon as it is taken: to start a named child unless it runs, call StartChild, which answers ErrAlreadyStarted with the running child's PID. sup may run on another node. from is who asks, as for StartChild; from a process, pass p.Context() as StartChild says.

type ChildSpec

type ChildSpec struct {
	// Name is the child's name in the supervisor, and the name it is
	// registered under on the node, so it stays reachable across restarts
	// with grpcproc.Named; it must be unique on the node. An empty Name
	// registers nothing: the child is anonymous, known by its PID, and a
	// supervisor can have any number of those.
	Name    string
	Restart Restart
	// Shutdown is how long the child has to exit once told to: 0 means the
	// supervisor's Spec.Shutdown for a worker, and Infinity for a child
	// that is a supervisor.
	Shutdown time.Duration
	// Significant children end their supervisor, as its Spec.AutoShutdown
	// says, when they end by themselves for good: a transient one that
	// exits with reason normal or shutdown, a temporary one that exits. A
	// permanent child cannot be significant, nor can the child of a
	// supervisor whose AutoShutdown is NoAutoShutdown.
	Significant bool
	// contains filtered or unexported fields
}

ChildSpec says how to start one child. Build it with Child, ChildFunc or ChildSupervisor.

func Child

func Child[M proto.Message, H Handler[M]](name string, newHandler func() H, opts ...grpcproc.SpawnOption) ChildSpec

Child is a child that runs a Handler, built afresh by newHandler at every start so a restart begins from a clean state:

actor.Child("orders", func() *Orders { return &Orders{repo: repo} })

func ChildFunc

func ChildFunc[M proto.Message](name string, fn func(*grpcproc.Process[M]) error, opts ...grpcproc.SpawnOption) ChildSpec

ChildFunc is a child that runs fn, registered as name unless name is empty. opts are for the child; grpcproc.LinkChild is not one of them.

func ChildSupervisor

func ChildSupervisor(name string, spec Spec, opts ...grpcproc.SpawnOption) ChildSpec

ChildSupervisor is a child that is itself a supervisor. Its Shutdown is Infinity unless set: stopping it waits for its whole subtree.

func (ChildSpec) WithRestart

func (c ChildSpec) WithRestart(r Restart) ChildSpec

WithRestart returns a copy of c with restart policy r.

func (ChildSpec) WithShutdown added in v0.0.4

func (c ChildSpec) WithShutdown(d time.Duration) ChildSpec

WithShutdown returns a copy of c that has d to exit once told to, or as long as it takes with Infinity.

func (ChildSpec) WithSignificant added in v0.0.4

func (c ChildSpec) WithSignificant(significant bool) ChildSpec

WithSignificant returns a copy of c that is significant, or not.

type DownHandler

type DownHandler[M proto.Message] interface {
	HandleDown(p *grpcproc.Process[M], d grpcproc.Down) error
}

DownHandler is told when a process the actor monitors exits. Without it, Downs are ignored.

type ExitedHandler added in v0.0.4

type ExitedHandler[M proto.Message] interface {
	HandleExited(p *grpcproc.Process[M], e grpcproc.Exited) error
}

ExitedHandler is told when a process the actor is linked to exits, if the actor traps exits (p.SetTrapExit(true), in Init, say). Without it, those Exiteds are ignored. One from the actor's parent ends the actor all the same, with the parent's reason, as it ends a gen_server: an actor spawned with grpcproc.LinkParent never outlives its parent.

type Factory added in v0.3.0

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

Factory builds a child spec from an argument, on the supervisor's node, for StartChildFrom. Build it with ChildFactory, and name it in Spec.Factories.

func ChildFactory added in v0.3.0

func ChildFactory[A proto.Message](fn func(A) (ChildSpec, error)) Factory

ChildFactory is a Factory whose argument is an A: fn builds the spec of the child to start from it, as Child, ChildFunc or ChildSupervisor would, or refuses with an error. StartChildFrom returns that error as its own, a *grpcproc.RemoteError that is fn's error to errors.Is, so fn is where admission goes, with an error per reason a caller tells apart:

actor.Spec{Factories: map[string]actor.Factory{
	"peer": actor.ChildFactory(func(j *roomspb.Join) (actor.ChildSpec, error) {
		if media.Full() {
			return actor.ChildSpec{}, ErrFull // the caller tries another node
		}
		return actor.Child("peer:"+j.GetPeer(), func() *Peer { return &Peer{join: j, media: media} }).
			WithRestart(actor.Temporary), nil
	}),
}}

An argument of another type is refused.

type Handler

type Handler[M proto.Message] interface {
	HandleMessage(p *grpcproc.Process[M], m grpcproc.Msg[M]) error
}

Handler handles the messages sent to an actor whose mailbox holds M. Returning an error ends the actor with that error as its exit reason; ErrStop ends it normally.

type Initializer

type Initializer[M proto.Message] interface {
	Init(p *grpcproc.Process[M]) error
}

Initializer runs before the first message. An error ends the actor before it handles anything, and Terminate is not called.

type Restart

type Restart uint8

Restart says when a child is restarted.

const (
	// Permanent children are always restarted.
	Permanent Restart = iota
	// Transient children are restarted only after an abnormal exit: not
	// after "normal" or "shutdown".
	Transient
	// Temporary children are never restarted.
	Temporary
)

func (Restart) String

func (r Restart) String() string

type Spec

type Spec struct {
	Strategy Strategy
	// MaxRestarts within Within is how many restarts the supervisor makes
	// before giving up and exiting with ReasonMaxRestarts. Zero means 3;
	// a negative value means none.
	MaxRestarts int
	// Within defaults to 5s.
	Within time.Duration
	// Shutdown is how long a worker child has to exit once told to, unless
	// its ChildSpec says otherwise; a child supervisor waits for its
	// subtree. Default 5s, or Infinity. grpcproc cannot kill a goroutine: a
	// child that outlives its Shutdown is reported and left behind, and a
	// named one keeps its name until it exits. The supervisor starts it
	// again, or ends, only once it has, so that nothing started under that
	// name meets it.
	Shutdown time.Duration
	// AutoShutdown says whether the supervisor ends itself when its
	// significant children end.
	AutoShutdown AutoShutdown
	// Children start in order and stop in reverse order. StartChild and
	// StartChildFrom add more, after them.
	Children []ChildSpec
	// Factories are the children StartChildFrom can ask the supervisor for,
	// from any node, by name: each builds a child spec from an argument that
	// crossed the wire, with Go functions and dependencies of this node. They
	// are part of the Spec so that what a supervisor can be asked to start is
	// declared where what it starts is, and outlasts restarts of either node
	// as the Spec does.
	Factories map[string]Factory
}

Spec describes a supervisor.

type StartOption added in v0.3.0

type StartOption func(*startOpts)

StartOption configures StartChildFrom.

func WithLink() StartOption

WithLink links the caller of StartChildFrom to the child from before it runs, as grpcproc.LinkChild links a parent: the child's exit ends the caller, with its reason, or reaches it as an Exited if it traps exits.

func WithMonitor added in v0.3.0

func WithMonitor() StartOption

WithMonitor has the caller of StartChildFrom monitor the child from before it runs: StartChildFrom returns the monitor's Ref.

type Strategy

type Strategy uint8

Strategy says which children a supervisor restarts when one exits.

const (
	// OneForOne restarts only the child that exited.
	OneForOne Strategy = iota
	// OneForAll stops every other child and restarts them all.
	OneForAll
	// RestForOne restarts the child and every child started after it.
	RestForOne
)

func (Strategy) String

func (s Strategy) String() string

type Terminator

type Terminator[M proto.Message] interface {
	Terminate(p *grpcproc.Process[M], err error)
}

Terminator runs when the actor ends, however it ends: err is nil after ErrStop, the handler's error, an *grpcproc.ExitError after Exit or the exit of a process it is linked to, context.Canceled when the node stops, or "panic: …" (after which the panic continues, and grpcproc reports it).

Jump to

Keyboard shortcuts

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