Documentation
Processes and messages
What a process can do: spawn, receive, send, call, reply, and exit.
A process is a function func(p *grpcproc.Process[M]) error, run on its own goroutine until it returns. M is the type of message its mailbox holds.
Spawning
Node.Spawn starts a process from outside any process, and returns its typed address. A process starts another with p.Spawn, which records p as the child's parent; the parent is for inspection, and neither exits when the other does unless the spawn asks for a link.
addr, err := node.Spawn(inventory, grpcproc.WithName("stock"))
// From inside a process: the child's parent is p.
child, err := p.Spawn(worker)
// Monitored from before it runs, so no exit is missed: Erlang's spawn_monitor.
child, ref, err := p.SpawnMonitor(worker)SpawnMonitor places the monitor before the child's first line runs. A supervisor that monitored after spawning could miss a child that exits at once, and would then read its instant normal exit as noproc. Processes may be spawned before the node is started; they run immediately, and Start only makes the node known to its peers.
Receiving
Receive blocks until something arrives, and returns a Msg[M]. It holds one of three things: a Body of type M, a Down from a monitor, or an Exited from a link when the process traps exits. From is the sender's PID, Metadata what travelled with the message, and IsCall says whether the sender waits for a Reply.
for {
m, err := p.Receive()
if err != nil {
return err // asked to exit, linked process gone, or the node stops
}
switch {
case m.Down != nil:
p.Log().Info("watched process gone", "pid", m.Down.PID, "reason", m.Down.Reason)
case m.IsCall():
_ = m.Reply(answer(m.Body), nil)
default:
apply(m.Body)
}
}The error tells the process to stop, and the process returns it: an *ExitError carrying the reason after Exit or a linked process's exit, context.Canceled when the node stops. ReceiveTimeout is the same with a deadline, and returns context.DeadlineExceeded when nothing came.
Messages come out in the order they went in, per sender, and a Down comes after the last message of the process it reports on. The mailbox has no priorities and no selective receive; what a process cannot handle now, it keeps in a variable, as the actor in Actors does with reservations it cannot yet serve.
The mailbox type
M must be a proto.Message, and it is one of three things:
| M | Use |
|---|---|
*shoppb.Stock | A generated message with a oneof: one contract per process, visible in the .proto, and the type every send through its address takes. The examples use this. |
StockMsg | Your own interface, interface{ proto.Message; stockMsg() }, implemented by several generated types with one extra method each. The address takes any of them as it is, addr.Send(ctx, p, &shoppb.Reserve{}), with no wrapper. |
proto.Message | Anything at all: the untyped process, for one that expects only a Down, or takes what a tool sends it. SendTo and CallTo reach it. |
The type lives on the address, so a remote sender is checked by its compiler, and the receiving node checks again on delivery, because types do not cross the wire. A message of the wrong type never reaches the process: it is a dead letter with reason type, counted and reported, and a caller gets ErrType.
Send and Call
Send queues a message and returns; nobody waits for an answer, and a process that does not exist is a dead letter, not an error. Call sends and waits for the reply, typed by what the caller asks for, under the context's deadline. Both are methods of the address, and take the sender: p from inside a process, or the node for code outside any.
err := stock.Send(ctx, p, &shoppb.Stock{Op: &shoppb.Stock_Restock{Restock: restock}})
r, err := stock.Call[*shoppb.Reserved](ctx, p, &shoppb.Stock{Op: &shoppb.Stock_Reserve{Reserve: reserve}})The oneof and the reply type are the protocol. The package that owns the process writes each operation once, as a method on an address type of its own, which takes the sender, p or the node, as an argument. The examples' shoppb.StockAddr does, and Addresses shows how:
inventory := shoppb.StockAddr{Addr: stock}
err := inventory.Restock(ctx, p, restock)
r, err := inventory.Reserve(ctx, p, reserve)A call is answered with the message's Reply: a message, or an error, which the caller gets back as a *RemoteError. The reply does not go through the caller's mailbox. A process that calls another waits on the reply alone, and the messages queued behind it stay in order. The message holds all a reply takes, so it can be kept and answered later, from any goroutine, or by another process it was handed to.
// HandleCall gets what was sent with Call. The returned message, or error,
// is the reply, and the actor carries on either way.
func (i *Inventory) HandleCall(_ *grpcproc.Process[*shoppb.Stock], m grpcproc.Msg[*shoppb.Stock]) (proto.Message, error) {
r := m.Body.GetReserve()
switch {
case r == nil:
return nil, errors.New("only reservations are calls")
case r.Qty <= 0:
return nil, fmt.Errorf("cannot reserve %d", r.Qty)
case i.left[r.Sku] < r.Qty:
// Not enough yet: keep the call and answer it from HandleMessage,
// when stock arrives. The caller just waits.
i.waiting = append(i.waiting, m)
return nil, actor.ErrNoReply
}
return i.reserve(r), nil
}The caller's deadline travels with the call. m.Deadline() says when the caller stops waiting, and m.Context(parent) gives a context that ends then, so work for a caller that gave up can stop. Between nodes it travels as the time left, as gRPC's does, so clocks need not agree, and counts from when the call arrives. It is not applied to the callee's own sends and calls unless it passes that context on, since a callee may have to finish what it started. Only the deadline travels, not the caller's cancellation.
ctx, cancel := m.Context(p.Context())
defer cancel()
rows, err := db.QueryContext(ctx, query) // ends when nobody waits for the answerA callee that exits before answering fails the call with ErrNoProc; a peer that cannot be reached fails it with a *LinkError, which says whether the request ever left the node. Errors and exit reasons lists them all.
Timers, context and logging
SendAfter schedules a send from the process after a delay. The timer belongs to the process: it is cancelled if the process exits first, and Stop cancels it by hand. The message carries the metadata the process holds when the timer is set, not whatever it is handling when the timer fires.
t := p.SendAfter(30*time.Second, p.Addr(), &shoppb.Stock{Op: tick})
// …
if t.Stop() {
// the tick had not fired yet
}p.Context() is cancelled when the process is asked to exit, when a process it is linked to exits, or when the node stops. Hand it to whatever the process calls, a database or another process, so that a request to exit interrupts the work; context.Cause is then the *ExitError.
p.Log() is a *slog.Logger with the process's PID and label attached. Its threshold can be changed at runtime, per process, with Node.SetLogLevel or from the Inspector, without restarting anything.
Spawn options
WithName(name) | Registers the process under name on its node until it exits, so that Named reaches it. While another process holds the name, the spawn fails with ErrNameTaken. |
WithLabel(label) | A low-cardinality tag, the key that metrics aggregate by. It defaults to the type of M. |
WithInspect(fn) | What the process publishes about itself: a map[string]string the Inspector shows. fn runs on the process's own goroutine, between two messages, so it reads the process's state without a lock. |
WithQuery(fn) | What the process answers when asked a question, through Node.Query and the Inspector, without its mailbox: fn runs on the asker's goroutine, with the asker's ctx, and must change nothing, since a read-only Inspector serves it. |
WithMailboxLimit(n) | Bounds the mailbox: while it holds n items, a message to the process is a dead letter with reason mailbox full, and a call fails with ErrMailboxFull, never handled. Downs and Exiteds always get in. Zero, the default, is no bound. |
LinkParent(), LinkChild() | Link the child to its parent, or the parent to the child, before the child runs. Both together are Erlang's spawn_link. Only for p.Spawn and p.SpawnMonitor: a Node.Spawn has no parent. |
WatchedBy(m) | Place the monitor or link the caller of the call m asked for on the child, before the child runs: the caller may be on another node. See Monitoring from before the start. |
Exit reasons
A process ends when its function returns, and it ends with a reason, a string that travels to whoever monitors it:
normalfor anilreturn, the error's text for any other.panic: …for a panic, which is recovered, logged with its stack, and reported like an error. The node keeps running.goexitfor a function that calledruntime.Goexit, ast.FailNowdoes.- What
Exitasked for: a request to exit reaches the process as an error fromReceive, and the reason is the one the request carried. The node stops its processes withshutdown, and the Inspector'sExitdefaults tokilled. - The reason of a process it was linked to, when it does not trap exits.
A process cannot be killed: a goroutine has no such operation. Exit is a request the process sees at its next Receive, and one that is busy in a handler ends when the handler returns. So long work takes p.Context(), and a supervisor gives a child a shutdown timeout rather than a guarantee.
// 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)Delivery guarantees
- At most once. A message is delivered once or not at all, never twice. Nothing is retried, since a retry could deliver a message a second time; what failed is reported instead, and a
*LinkErrorwhoseUnsentis set is the one case where sending again is known to be safe. - In order per sender. Two messages from one process to another arrive in the order they were sent, on one node or across a link, and a
Downarrives after the last message of the process it reports on. Calls travel on the same link as messages, so they cannot overtake or be overtaken. - Mailboxes that never block. A send never waits for the receiver. All the processes of a node share its link to a peer, so one mailbox that made it wait would stall every other process behind it. Mailboxes are unbounded by default;
WithMailboxLimitbounds one, which then refuses what it has no room for. The depth and the age of the oldest message are in every process's snapshot, for the application to act on. - Local sends share the pointer. Within a node a message is not encoded, and the receiver gets the value the sender built; the sender must not change it after sending.
Config.CopyLocalclones every local message instead.