grpcproc
Documentation

Monitors and links

How a process learns that another is gone: a monitor delivers the exit as a message, a link makes it an exit of its own.

Monitors

p.Monitor(target) watches a process. When the target exits, p receives a message with Down set, through the same Receive as everything else. The target can be a PID, a name on some node, or a typed address; it can run on this node or on any other, and the watcher's code is the same.

ref := p.Monitor(grpcproc.Named[*shoppb.Reserve]("warehouse", "stock"))

m, err := p.Receive()
if err != nil {
	return err
}
if m.Down != nil && m.Down.Ref == ref {
	p.Log().Info("stock is gone", "reason", m.Down.Reason)
}

Monitor returns a Ref, and the Down carries it back, so a process that watches several targets tells their notices apart. The Down also carries the PID that exited, the Name the monitor was placed by, if it was, and the Reason. Demonitor(ref) stops watching; a Down already in the mailbox stays there.

Two cases need no exit at all. A monitor on a process that does not exist, because it never did or already went, answers at once with reason noproc. A monitor on a process whose node cannot be reached, now or later, answers with noconnection, the moment the node is declared down. In both the watcher gets exactly one Down.

Ordering

A process's Down arrives after every message that process sent to the watcher. When a worker sends its result and then exits, the watcher sees the result, then the Down, and after the Down nothing more comes.

Within a node it holds because the Down is queued in the watcher's mailbox like a message, by the same code, behind what came before. Across nodes it holds because everything one node sends to another travels on one gRPC stream, in order: messages, replies, monitor notices. Nodes and links has the link in detail.

The quick start's watcher monitors the stock, asks it to exit, and next receives the Down, with the reason it asked for:

examples/quickstart/main.go
// A monitor across nodes works as one within a node does. A process on
// shop monitors stock, then asks it to exit; the Down arrives with the
// reason, as it would for a crash or a lost node.
exited := make(chan string)
_, err = shop.Spawn(func(p *grpcproc.Process[proto.Message]) error {
	p.Monitor(stock)
	check(p.Exit(stock, "closing"))
	m, err := p.Receive() // the Down: nothing else is sent to this process
	if err != nil {
		return err
	}
	exited <- m.Down.Reason
	return nil
})
check(err)
fmt.Println("stock exited:", <-exited)

Spawning monitored

There is a gap between Spawn returning an address and Monitor being called on it. A child that exits inside that gap is reported as noproc, and its real reason is lost: a supervisor would take a transient child's clean, immediate exit for a crash and restart it in a loop.

p.SpawnMonitor(fn) closes the gap: it spawns the child and monitors it in one step, inside the section that admits the child, so the monitor exists before the child runs. However soon the child exits, the Down has its real reason. It is Erlang's spawn_monitor, and it is how supervisors start every child.

child, ref, err := p.SpawnMonitor(worker, grpcproc.WithLabel("worker"))
if err != nil {
	return err
}
// A Down with ref arrives when child exits, with its reason, even
// if it exits before this line runs.

A child of another node has the same gap, wider: the process that starts it is there, answering a call. The caller asks for the monitor with the call, with addr.CallMonitor, and the callee spawns with grpcproc.WatchedBy(m), which places it on the child inside the same critical section, before the child runs. The answer names the child, and a Down that came before it waits for it, so it comes after the answer with its real reason. Only a successful answer brings the monitor: a call that fails leaves none, so a spawn that failed is an error and a child that started and died is a Down. addr.CallLink links the caller instead, as LinkChild does, and m.Watch(pid) places either on a process that runs already.

// On the caller's node.
placed, ref, err := placer.CallMonitor[*roomspb.Placed](ctx, p, &roomspb.Place{Peer: id})

// On the callee's: the placer, answering the call m.
peer, err := p.Spawn(runPeer, grpcproc.WatchedBy(m))
if err != nil {
	return m.Reply(nil, err)
}
return m.Reply(&roomspb.Placed{Peer: peer.PID().Proto()}, nil)

A supervisor does this for a child it builds from a factory, with actor.StartChildFrom: see Starting a child from another node.

Exit requests

p.Exit(target, reason) asks a process anywhere to stop, with a reason of the caller's choosing; node.Exit(ctx, target, reason) does the same from outside a process, and node.Wait(ctx, target) returns the exit reason of a process of this node once it is gone. The target's context is cancelled with the reason as its cause, its next Receive returns an *ExitError, and it returns. Its watchers get a Down with that reason, its supervisor decides from the reason whether to start it again, and the node stops its processes this way, with shutdown.

m, err := p.Receive()
if err != nil {
	// After Exit: err is an *ExitError, and context.Cause(p.Context())
	// is the same value. Return it, and the reason is the process's.
	return err
}

A goroutine cannot be killed from outside, so the request is delivered as the error above and the process is expected to return. Trapping exits does not turn it into a message: if it could, a process could keep running through the node's shutdown. A process that needs to clean up does so after Receive returns, or in an actor's Terminate.

Spawning linked

A link placed after Spawn has the same gap a monitor has, so links to a child are made at spawn, by option. LinkParent() links the child to the process that spawns it: when the parent exits, the child does too. LinkChild() links the parent to the child: when the child exits, the parent does. Both together are Erlang's spawn_link, a link both ways.

// A helper that must not outlive p, and whose failure must not end p.
helper, err := p.Spawn(fetch, grpcproc.LinkParent())

// A pair that live and die together.
twin, err := p.Spawn(other, grpcproc.LinkParent(), grpcproc.LinkChild())

Both options need a parent, so they are for Process.Spawn and SpawnMonitor; Node.Spawn, which no process calls, refuses them. A supervisor spawns each child with LinkParent, so a supervisor that is gone takes its children with it even if the orderly stop it makes when it ends did not reach them.

Trapping exits

A process that wants to know when a linked process exits, and do something other than exit, calls p.SetTrapExit(true). From then on, the exit of a process it is linked to arrives as a message with Exited set, in order with the rest, instead of ending it. Exited carries the PID, the Name the link was placed by, if it was, and the Reason; p.TrapExit() reports the setting.

p.SetTrapExit(true)
for {
	m, err := p.Receive()
	if err != nil {
		return err // an Exit request: still not a message
	}
	if m.Exited != nil {
		p.Log().Warn("a linked process exited", "pid", m.Exited.PID, "reason", m.Exited.Reason)
		continue
	}
	// …
}

Trapping applies to links only. An Exit request still ends the process. And an actor run by actor.Run still ends when its parent exits, whether it traps or not, as a gen_server does; that rule lives in the actor loop, and a raw process that traps exits decides for itself.

Exit reasons

A Down and an Exited carry a reason, a string, which a supervisor reads to decide whether an exit was normal. These are the ones grpcproc sets; Exit sets whatever the caller asked for.

ReasonWhat happened
normalThe process function returned nil.
the error’s textThe function returned an error, and this is err.Error(). Abnormal.
panic: …The function panicked; the message follows, and the stack goes to the log. Abnormal.
goexitThe function called runtime.Goexit, as t.FailNow does. Abnormal.
shutdownAn orderly stop: the node is stopping, or a supervisor stopped the child. Not abnormal.
killedThe default reason of the Inspector’s Exit, from grpcprocctl or an agent.
noprocThe process monitored or linked to does not exist: it never did, or it exited before the monitor was placed.
noconnectionThe node the process runs on cannot be reached: its link broke, or the cluster declared it gone. The process may still run there.
max restartsA supervisor gave up: more restarts than its Spec allows within the window. Abnormal, so its own supervisor restarts it.

Errors and exit reasons has the errors a sender sees for the same events: ErrNoProc and ErrNoConnection are the caller's side of noproc and noconnection.