grpcproc
Documentation

Actors

Write a process as a struct with a method per kind of message, using the grpcproc/actor package.

grpcproc/actor is optional, and built on the public API only. Its other half is Supervisors. The code is from examples/actors.

Why actors

A process is a receive loop with a switch in it, which suits one that does one thing. For a service, the switch grows a case per operation. An actor is a struct holding its dependencies and its state, with a method per kind of message: one for messages, one for calls, one for the exit of something it watches. A constructor builds the struct, so a DI container can, and actor.Run is the loop.

type Orders struct{ repo *Repo }

func NewOrders(repo *Repo) *Orders { return &Orders{repo: repo} }

func (o *Orders) HandleMessage(p *grpcproc.Process[*orderspb.Order], m grpcproc.Msg[*orderspb.Order]) error {
	return o.repo.Save(p.Context(), m.Body)
}

addr, err := node.Spawn(actor.Run(NewOrders(repo)), grpcproc.WithName("orders"))

Run turns the handler into a process function, the one Spawn takes, so an actor is spawned, named, monitored and addressed like any process.

Handler methods

One method is required, HandleMessage: it is the Handler[M] interface. The rest are optional interfaces that Run looks for once, by type assertion, when the actor starts.

MethodRuns for, and what its result means
Init(p) errorOnce, on the actor's goroutine, before the first message. An error ends the actor before it handles anything, and Terminate does not run.
HandleMessage(p, m) errorA message sent with Send. An error ends the actor with the error as its exit reason; actor.ErrStop ends it normally.
HandleCall(p, m) (proto.Message, error)A message sent with Call. What it returns, a message or an error, is the reply, and the actor carries on either way. actor.ErrNoReply means the answer comes later, through m.Reply. Without this method, every call is answered with an error.
HandleDown(p, d) errorA Down from a process the actor monitors. As for HandleMessage. Without it, Downs are ignored.
HandleExited(p, e) errorAn Exited from a process the actor is linked to, when it traps exits. As for HandleMessage. One from the actor's parent ends the actor instead, whatever this method would say.
Terminate(p, err)Once, when the actor ends, however it ends. The exit reason is already decided: err is nil after ErrStop, the handler's error, an *ExitError after Exit, context.Canceled when the node stops, or goexit when a handler called runtime.Goexit.

The interfaces are Initializer, CallHandler, DownHandler, ExitedHandler and Terminator, each with one method.

All of them run on the actor's goroutine, one at a time, in the order the messages arrived, so its fields need no lock. A call it makes from a handler holds the actor until the reply comes; the next message waits in the mailbox meanwhile.

Errors: a reply, or an exit reason

From HandleCall, an error is the answer: the caller gets it as a *RemoteError, and the actor goes on to the next message. Use it for a refused reservation or a bad quantity, which are not the actor's failure.

From HandleMessage, HandleDown and HandleExited, an error is the exit reason: nobody waits for an answer to a send, so the error goes to the actor's supervisor, which sees a crash and starts a fresh actor. So keep what must survive outside the actor, in the dependency the constructor takes, and load it in Init.

Two sentinel errors are exceptions. actor.ErrStop from any handler ends the actor with reason normal; from HandleCall, the reply is sent first, so a caller that asked the actor to stop gets its answer. actor.ErrNoReply from HandleCall sends nothing: the actor keeps the message and answers later with m.Reply(resp, err), from a later handler or from any goroutine. The caller waits until then, or until its context ends; m.Deadline() says when that is, so an answer nobody waits for any more need not be worked out.

Call-only actors

An actor that only answers calls, a pricer or a lookup, has no use for HandleMessage, but the interface requires it. actor.CallsOnly[M], embedded by value, provides one: a message sent without a call is logged at Warn and dropped, and the actor carries on.

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) {
	return &pricespb.Price{Cents: pr.table.Lookup(m.Body.Sku)}, nil
}

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

The message was delivered, so it is not a dead letter, and a stray sender on another node is no reason to end this actor: gen_server's default handle_info drops it too. The log line names the sender and the type.

Run panics for an actor that embeds CallsOnly and has no HandleCall. The usual way to get there is to spawn Pricer{} where HandleCall has a pointer receiver: the value has the embedded method and not the real one. The panic happens at spawn, with a message saying so, rather than at the first call.

Example: an inventory

The example's actor holds a stock and records reservations in a Ledger, its one dependency. Its mailbox holds *shoppb.Stock, a oneof of a reservation and a restock:

examples/actors/main.go
// Inventory is an actor whose mailbox holds *shoppb.Stock. It implements
// actor.Handler, and whichever of the optional interfaces it needs:
// CallHandler, DownHandler, Initializer, Terminator.
type Inventory struct {
	ledger  *Ledger
	left    map[string]int64
	waiting []grpcproc.Msg[*shoppb.Stock] // reservations parked until a restock
}

// Init runs on the actor's goroutine before the first message.
func (i *Inventory) Init(*grpcproc.Process[*shoppb.Stock]) error {
	i.left = map[string]int64{}
	return nil
}

A reservation is a call. When there is not enough stock, the actor parks the message and returns ErrNoReply; the caller waits, and gets its answer when a restock arrives:

examples/actors/main.go
// 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
}

A restock is a send. HandleMessage adds the stock and answers the parked calls it now can, each with its own Reply. A reservation that arrives as a send breaks the protocol, and the returned error ends the actor:

examples/actors/main.go
// HandleMessage gets what was sent with Send; nobody waits for an answer.
// An error ends the actor, with the error as its exit reason, and
// actor.ErrStop ends it normally.
func (i *Inventory) HandleMessage(_ *grpcproc.Process[*shoppb.Stock], m grpcproc.Msg[*shoppb.Stock]) error {
	r := m.Body.GetRestock()
	if r == nil {
		return errors.New("a reservation must be a call")
	}
	i.left[r.Sku] += r.Qty
	parked := i.waiting
	i.waiting = nil
	for _, c := range parked {
		if res := c.Body.GetReserve(); i.left[res.Sku] >= res.Qty {
			_ = c.Reply(i.reserve(res), nil)
		} else {
			i.waiting = append(i.waiting, c)
		}
	}
	return nil
}

Terminate runs however the actor ends. The calls it never answered need no handling here: a caller whose callee exits gets ErrNoProc on its own.

examples/actors/main.go
// Terminate runs however the actor ends. Calls it never answered fail with
// grpcproc.ErrNoProc on their own.
func (*Inventory) Terminate(_ *grpcproc.Process[*shoppb.Stock], err error) {
	fmt.Println("inventory stopped:", err)
}

The program spawns the actor under a name and calls it through a shoppb.StockAddr, whose methods are its protocol (an address with its protocol). It parks a reservation until a restock, gets a refusal back as an error, then breaks the protocol with a raw Stock that the address's methods would not send:

examples/actors/main.go
addr, err := node.Spawn(actor.Run(&Inventory{ledger: &Ledger{}}), grpcproc.WithName("inventory"))
if err != nil {
	log.Fatal(err)
}
// The address with the protocol as methods.
inventory := shoppb.StockAddr{Addr: addr}

// Nothing is in stock, so this call is parked in the actor until the
// restock below arrives.
reserved := make(chan *shoppb.Reserved)
go func() {
	r, err := inventory.Reserve(ctx, node, &shoppb.Reserve{Sku: "apple", Qty: 2})
	if err != nil {
		log.Fatal(err)
	}
	reserved <- r
}()
if err := inventory.Restock(ctx, node, &shoppb.Restock{Sku: "apple", Qty: 5}); err != nil {
	log.Fatal(err)
}
fmt.Println("reserved, left:", (<-reserved).Left)

// A handler's error goes back to the caller; the actor carries on.
_, err = inventory.Reserve(ctx, node, &shoppb.Reserve{Sku: "apple", Qty: -1})
fmt.Println("reserve failed:", err)
r, err := inventory.Reserve(ctx, node, &shoppb.Reserve{Sku: "apple", Qty: 1})
if err != nil {
	log.Fatal(err)
}
fmt.Println("reserved, left:", r.Left)

// A reservation sent without waiting for the answer breaks the
// protocol. The address's methods keep to it, so this one is sent as a
// raw Stock: HandleMessage fails, and the actor exits. The call behind
// it in the mailbox is never handled.
sent := &shoppb.Stock{Op: &shoppb.Stock_Reserve{Reserve: &shoppb.Reserve{Sku: "apple", Qty: 1}}}
if err := inventory.Send(ctx, node, sent); err != nil {
	log.Fatal(err)
}
_, err = inventory.Reserve(ctx, node, &shoppb.Reserve{Sku: "apple", Qty: 1})
fmt.Println("then:", err)
output
ledger: 2 apple
reserved, left: 3
reserve failed: cannot reserve -1
ledger: 1 apple
reserved, left: 2
inventory stopped: a reservation must be a call
then: grpcproc: no such process

The last line is the reservation queued behind the one that was sent: the actor had exited by the time it was next in the mailbox, so the call failed with ErrNoProc. Under a supervisor, a new actor would be running by then, under the same name, with a fresh state; Supervisors shows that.

Slow answers on workers

An actor handles one message at a time, so a call that takes long to answer, a report rendered or a query run, holds up every message behind it, the writes included. actor.Workers answers such a call from a worker, a process started for it, and the actor goes on with its mailbox at once. The tutorial's tool runner runs each tool that way, running of them at most, on the actor.NewWorkers(running) its constructor makes:

examples/guide/internal/tools/tools.go
// runner is the actor. It hands each call to a worker, a process started
// for it, and is free again at once; the worker's answer is the call's. A
// tool that failed is part of the answer, since the model is told of it,
// and so is one that panicked: the worker answers with the panic.
type runner struct {
	actor.CallsOnly[proto.Message]
	tools   Tools
	workers *actor.Workers
}

// HandleCall hands a call to the Runner service's method for it: Run.
func (r *runner) HandleCall(p *grpcproc.Process[proto.Message], m grpcproc.Msg[proto.Message]) (proto.Message, error) {
	return toolsv1.HandleRunnerCall(r, p, m)
}

func (r *runner) Run(p *grpcproc.Process[proto.Message], m grpcproc.Msg[proto.Message], run *toolsv1.Run) (*toolsv1.Ran, error) {
	tool, ok := r.tools[run.Name]
	if !ok {
		return &toolsv1.Ran{Failed: "no tool named " + run.Name}, nil
	}
	return nil, r.workers.Label("tool:"+run.Name).ReplyLater(p, m, func(ctx context.Context, _ *grpcproc.Process[proto.Message]) (*toolsv1.Ran, error) {
		// The caller's deadline is the tool's. A goroutine cannot be
		// killed: a tool that does not watch ctx runs on after it, in its
		// worker's place.
		out, err := tool(ctx, run.Args)
		if err != nil {
			return &toolsv1.Ran{Failed: err.Error()}, nil
		}
		return &toolsv1.Ran{Output: out}, nil
	})
}

// running is how many tools the runner runs at once; a call beyond them is
// answered actor.ErrWorkersBusy.
const running = 16

What fn returns is the reply, as HandleCall's would be. Its context carries the caller's deadline and metadata, and ends when the actor does, since the worker is linked to it. Its second argument is the worker, to send and call from; the actor's own p belongs to the actor's goroutine.

fn runs beside the actor, so it must not touch the actor's state: nothing stops it, and the race is yours. Hand it a copy made in HandleCall, as the inventory above would with left := maps.Clone(i.left), or a value the actor replaces and never changes. Then neither needs a lock: each read sees the state as its call found it, while the actor goes on with the writes.

At most n calls are being answered at once; a worker gives its place back as it answers, a moment before its process ends. With all n busy, ReplyLater returns actor.ErrWorkersBusy without running fn, and HandleCall returning it answers the caller at once; making the call again cannot run it twice. Waiting for a worker would hold up the actor instead, and deadlock it when a worker calls the actor back. The error spawning a worker, on a stopping node, is answered the same way. A panic in fn answers the call with panic: …, and a runtime.Goexit with actor: the worker ended without answering; either way the worker ends and the actor carries on.

The call still belongs to the actor. If the actor ends while fn runs, the caller gets ErrNoProc at once, as for any call it left unanswered, and what fn returns afterwards is dropped.

Label returns a copy whose workers carry another label, which the Inspector and metrics tell them apart by; the copies share the original's n places. A label is a metrics key, so it comes from a small set, as the runner's tool names do, never from what a caller sends.

The parent link

An actor spawned from another process with p.Spawn records that process as its parent, and a supervisor spawns its children with LinkParent: the child is linked to the supervisor, one way, so when the supervisor exits the child does too. That link can be trapped, as any link can, with p.SetTrapExit(true) in Init, after which a linked process's exit arrives as an Exited message.

An Exited from the actor's own parent is the exception: it ends the actor, with the parent's reason, before HandleExited sees it, as a gen_server ends when its parent does, so no subtree outlives its supervisor. That rule is in actor.Run, not in the core; a plain process that traps exits decides for itself. Monitors and links has the details.

Testing an actor

An actor is a process, so a test spawns it on a node and talks to it. A node with no peers needs a name, an empty resolver and AdmitAll, and stops when the test ends. Run inside Go's testing/synctest, the test needs no timeout to tell a parked call from a slow one: synctest.Wait returns once every process waits, so a reservation not answered by then is parked, and one answered after the restock was answered by it:

examples/actors/inventory_test.go
// A reservation with nothing in stock waits for a restock. Inside a
// synctest bubble the test can say so without a timeout: synctest.Wait
// returns once every process waits, so a call not answered by then is
// parked, not slow.
func TestReservationWaitsForRestock(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		node, err := grpcproc.NewNode(grpcproc.Config{Admit: grpcproc.AdmitAll, Name: "test", Resolver: grpcproc.StaticResolver{}})
		if err != nil {
			t.Fatal(err)
		}
		t.Cleanup(func() { _ = node.Stop(context.Background()) })
		addr, err := node.Spawn(actor.Run(&Inventory{ledger: &Ledger{}}))
		if err != nil {
			t.Fatal(err)
		}
		inventory := shoppb.StockAddr{Addr: addr}

		reserved := make(chan *shoppb.Reserved, 1)
		go func() {
			r, err := inventory.Reserve(t.Context(), node, &shoppb.Reserve{Sku: "apple", Qty: 2})
			if err != nil {
				t.Error(err)
				return
			}
			reserved <- r
		}()
		synctest.Wait()
		if len(reserved) != 0 {
			t.Fatal("a reservation was answered with nothing in stock")
		}

		if err := inventory.Restock(t.Context(), node, &shoppb.Restock{Sku: "apple", Qty: 5}); err != nil {
			t.Fatal(err)
		}
		synctest.Wait()
		if r := <-reserved; r.Left != 3 {
			t.Fatalf("left %d after the restock, want 3", r.Left)
		}
	})
}

An actor that calls other actors takes their addresses as dependencies, and a test puts fakes behind them: plain process functions registered under the same names. Testing shows that with the tutorial's conversations, grpcproctest for anything that needs more than one node, and deterministic tests for timers and restarts.