grpcproc
Documentation

Supervisors

Build a supervision tree with grpcproc/actor, and add or stop children while it runs.

Supervision says which strategy to pick and where state should live; read it first if supervisors are new. The code is from examples/supervisor and the tutorial's models service.

The Spec

actor.Spec describes a supervisor: what it restarts, how often it may, how long a child has to stop, and the children themselves. actor.Supervise(node, spec, opts...) starts it on a node with its children, in order, and returns the supervisor's PID once they all run, or the first error after stopping those already started. The options are the supervisor's own: a name, a label.

examples/supervisor/main.go
// tree is the supervision tree: one child, restarted alone when it exits,
// up to 3 times a minute.
func tree(ledger *Ledger) actor.Spec {
	return actor.Spec{
		Strategy:    actor.OneForOne,
		MaxRestarts: 3,
		Within:      time.Minute,
		Children: []actor.ChildSpec{
			actor.Child("inventory", func() *Inventory { return &Inventory{ledger: ledger} }),
		},
	}
}
FieldWhat it says
StrategyWhich children restart when one exits: OneForOne, the child alone; OneForAll, every child, the others stopped first; RestForOne, the child and those started after it. The zero value is OneForOne.
MaxRestarts, WithinThe restart intensity: more than MaxRestarts restarts within Within and the supervisor gives up, exiting with ReasonMaxRestarts. Zero means 3 in 5s; a negative MaxRestarts means none.
ShutdownHow long a worker child has to exit once told to, unless its own spec says otherwise. 5s by default. A child that is a supervisor gets Infinityinstead: stopping it waits for its subtree.
AutoShutdownWhether the supervisor ends itself when its significant children end: NoAutoShutdown (the default), AnySignificant or AllSignificant.
ChildrenStarted in order, stopped in reverse. StartChild and StartChildFrom add more, after them.
FactoriesWhat StartChildFrom can ask the supervisor for, from any node, by name: see Starting a child from another node.

A spec is checked when the supervisor starts: an unknown strategy, a name used twice and a significant permanent child are errors from Supervise.

Children

A ChildSpec says how to start one child. Three functions build one:

  • actor.Child(name, newHandler) runs an actor. It takes a factory rather than a handler, and calls it at every start, so a restart begins from a fresh struct. The factory closes over the dependencies: func() *Inventory { return &Inventory{ledger: ledger} }.
  • actor.ChildFunc(name, fn) runs a plain process function, for a child that is not an actor.
  • actor.ChildSupervisor(name, spec) runs another supervisor.

The name is the child's name in the supervisor and the name it is registered under on the node, so it stays reachable with grpcproc.Named across restarts. 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.

Each builder takes spawn options for the child, a label say. LinkChild is not one of them: the supervisor does not trap exits, and would end whenever the child did. The supervisor adds LinkParent itself, so a child never outlives it.

Three methods return a copy of the spec with one field changed:

WithRestart(r)When the child is restarted: Permanent always, the default; Transient after an abnormal exit only, not after normal or shutdown; Temporary never.
WithShutdown(d)How long this child has to exit once told to, in place of the supervisor's Shutdown; actor.Infinity waits however long it takes.
WithSignificant(true)The child counts for AutoShutdown: a transient one that ends with normal or shutdown, or a temporary one that ends at all. A permanent child cannot be significant.
actor.Spec{
	Strategy:     actor.OneForOne,
	AutoShutdown: actor.AllSignificant,
	Children: []actor.ChildSpec{
		actor.Child("importer", newImporter).WithRestart(actor.Transient).WithSignificant(true),
		actor.ChildFunc("progress", progress).WithRestart(actor.Temporary).WithShutdown(time.Second),
	},
}

That tree is a job: it ends itself, with shutdown, once the importer has finished on its own. A supervisor above it restarts it only if it is a permanent child there.

Nested supervisors

ChildSupervisor is a child whose spec is another Spec, so an application can have one supervisor per service, each with its own strategy and intensity, under one root. The tutorial's models service builds its subtree in a function that takes the service's dependencies from the container:

examples/guide/internal/models/models.go
// tree is the service's supervision tree. The scheduler's dependencies come
// from the container; Child builds a fresh actor around them at every start.
func tree(model Model, slots Slots, scope *groups.Scope) actor.ChildSpec {
	return actor.ChildSupervisor(modelsv1.Service+"-sup", actor.Spec{
		Children: []actor.ChildSpec{
			actor.Child(modelsv1.SchedulerProcess, func() *scheduler {
				return &scheduler{model: model, slots: slots, scope: scope, running: map[grpcproc.Ref]grpcproc.Msg[proto.Message]{}}
			}, grpcproc.WithLabel("scheduler")),
		},
	})
}

The root, in the tutorial's platform, is a OneForOne supervisor whose children are every service's tree. A service that gives up, past its own intensity, exits with max restarts, an abnormal reason; the root restarts that subtree alone, and the others carry on. A root that gives up ends the program, for whatever runs it to start again.

A supervisor told to exit stops its children in reverse order, and a child supervisor has as long as it takes, Infinity, to stop its own. grpcproc cannot kill a goroutine, so a worker that outlives its Shutdown is logged and left behind; a named one keeps its name until it exits, and the supervisor starts it again, or ends, only once it has.

Adding and stopping children

actor.StartChild(ctx, from, sup, spec) adds a child to a running supervisor and starts it, after the children it already has; it returns the child's PID once it runs. from is who asks, the node or a process from inside its handler, as for an address's Call, and sup is a PID or a name. The child is the supervisor's like the others, with one difference: once it ends for good, because it is temporary, or transient and ended normally, or StopChild stopped it, the supervisor forgets it. So a pool of workers, a OneForOne supervisor with anonymous children added as they are needed, does not grow with every worker that ever ran.

worker, err := actor.StartChild(ctx, node, pool, actor.ChildFunc("", handle(job)).WithRestart(actor.Temporary))

A spec holds Go functions, which no message can carry, so StartChild works only from the supervisor's own node, which the supervisor checks: it registers the spec locally and calls the supervisor with its id. A child that fails to start is an error, and the supervisor does not count it as a restart. StartChild is refused while a restart waits on a stuck child, since the new one would start before those owed a start.

A name belongs to one child. StartChild of a name the supervisor runs a child under starts nothing, and returns that child's PID with actor.ErrAlreadyStarted, whether the supervisor started it from its spec or an earlier StartChild did, and whether or not it has been restarted since. So code that starts a child per key keeps no map of its own, which the first restart would leave pointing at a process that is gone:

room, err := actor.StartChild(ctx, node, rooms, actor.Child("room:"+id, newRoom).WithRestart(actor.Transient))
if err != nil && !errors.Is(err, actor.ErrAlreadyStarted) {
	return err
}
// room runs, started now or before.

A child of that name that has just exited, and whose exit the supervisor has yet to handle, has freed the name already. The call waits for the supervisor to handle it, and gets the child's restart, or, if the supervisor forgets the child, a fresh start of the spec.

actor.StopChild(ctx, from, sup, child) stops a child for good: it is not restarted, whatever its Restart, and a strategy no longer counts it, until the supervisor itself is started again from its Spec. It carries a PID, so the supervisor may be on another node. A significant child stopped this way does not end its supervisor; only a child that ends by itself does.

Starting a child from another node

A supervisor that other nodes ask for children declares what they may ask for, since a spec cannot travel: Spec.Factories, a factory per name, each built with actor.ChildFactory from a function that takes an argument, a protobuf message, and returns the spec to start. The functions, and the dependencies they close over, stay on the supervisor's node; only the name and the argument travel.

rooms, err := actor.Supervise(node, actor.Spec{Factories: map[string]actor.Factory{
	"peer": actor.ChildFactory(func(j *roomspb.Join) (actor.ChildSpec, error) {
		if media.Full() {
			return actor.ChildSpec{}, ErrFull
		}
		return actor.Child("peer:"+j.GetPeer(), func() *Peer { return &Peer{join: j, media: media} }).
			WithRestart(actor.Temporary), nil
	}),
}}, grpcproc.WithName("rooms"))

actor.StartChildFrom(ctx, from, sup, factory, arg, opts...) asks for one, from any node, and returns the child's PID once it runs. The child is the supervisor's as one StartChild added is. The factory is where admission goes: what it refuses with is StartChildFrom's error, as it returned it, so errors.Is tells a full node, worth trying elsewhere, from a request that is wrong everywhere. actor.ErrNoFactory is a name the supervisor has no factory for.

sup := grpcproc.Name{Node: pick(), Name: "rooms"}
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.

actor.WithMonitor() has the caller monitor the child from before it runs, as SpawnMonitor does on one node: a child that exits at once is a Down with its reason, after StartChildFrom returns, never noproc. A start that fails leaves no monitor, and no Down comes of it, so an error means nothing started, or nothing the caller will hear of. actor.WithLink() links the caller to the child instead. Either needs the caller to be a process.

A call is answered at most once, and an answer can be lost: a link that breaks, a context that ends. The child may have started then, unwatched. A named child is found again: StartChildFrom of its name answers ErrAlreadyStarted with its PID and the monitor, as StartChild does. An anonymous one runs until it ends, and actor.Children lists it. The monitor is of the child's process: a restart the supervisor makes is a new one, which StartChildFrom of the name monitors again.

Calling a busy supervisor

A supervisor waits for a child to exit outside its receive loop, and so does every supervisor above it, each waiting for its subtree. A child that calls its supervisor while it is being stopped, from Terminate say, would hold the whole chain until the call gave up. So a supervisor that has waited more than 100ms answers the calls queued meanwhile, StartChild and StopChild among them, with actor.ErrBusy, and handles the rest once the wait is over.

From a process, call a supervisor with p.Context(). A supervisor that is stopping the caller answers no call until it is done, and a caller waiting with a context of its own could not exit meanwhile. p.Context() ends when the process is told to, and so does the call.

Inspecting a supervisor

Every supervisor publishes its state through WithInspect: its strategy, its restarts against the intensity, the names of its factories, and each child with its PID or stopped, its restart policy and how many times it has been restarted. A child the supervisor is waiting on shows as waiting with the PID it waits for. node.Inspect reads it, and so does grpcprocctl through the Inspector:

grpcprocctl inspect orders-sup
name:                  orders-sup
label:                 supervisor
monitors:              2
  child.payments:      <orders-1.1718.3> permanent restarts=0
  child.reservations:  <orders-1.1718.2> permanent restarts=0
  restarts:            0/3 in 5s
  strategy:            one_for_one

A program asks with actor.Children(ctx, from, sup), which answers the same as data, from any node: the children in the order the supervisor starts them, each with its name, its PID while it runs, whether a restart owes it a start, its restart policy and its restarts, and whether it is a supervisor. It is what the supervisor knows when it answers, and out of date as soon as it is taken; to start a child unless it runs, call StartChild.

Watch the restarts: a count that keeps climbing without reaching the limit is a child that fails, waits out the window and fails again, and never escalates.

Example: a crash and a restart

The example's inventory keeps its levels in a Ledger, outside the actor, and loads them in Init. A restock of zero is a bug, and the error ends the actor; the program follows what the supervisor does through the node's events:

examples/supervisor/main.go
// Crash it, and follow what the supervisor does through node events.
events := node.Subscribe(ctx, 16)
if err := inventory.Restock(ctx, node, &shoppb.Restock{Sku: "apple", Qty: 0}); err != nil {
	log.Fatal(err)
}
for e := range events {
	if e.Process.Name != "inventory" {
		continue
	}
	if e.Kind == grpcproc.EventExit {
		fmt.Println("inventory exited:", e.Reason)
	}
	if e.Kind == grpcproc.EventSpawn {
		fmt.Println("inventory started again")
		break
		}
	}

The name reaches whichever process currently runs the child, so the next call after the restart goes to the new actor, whose state came from the ledger. The supervisor's own count is read with node.Inspect:

examples/supervisor/main.go
// Same name, new process, state loaded back from the ledger.
r, err = inventory.Reserve(ctx, node, &shoppb.Reserve{Sku: "apple", Qty: 1})
if err != nil {
	log.Fatal(err)
}
fmt.Println("reserved, left:", r.Left)

// The supervisor publishes its state through WithInspect, which is what
// the Inspector and grpcprocctl show.
state, err := node.Inspect(ctx, sup)
if err != nil {
	log.Fatal(err)
}
fmt.Println("supervisor restarts:", state["restarts"])
output
reserved, left: 3
inventory exited: bad restock of 0 apple
inventory started again
reserved, left: 2
supervisor restarts: 1/3 in 1m0s

One restart of three within the minute. A fourth crash in that window would end the supervisor with max restarts, and with it, in this program, the tree; in the tutorial, the root would start the service again.