grpcproc

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2026 License: MIT Imports: 22 Imported by: 6 modules, 5 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.

README

grpcproc

Erlang-style processes for Go, on the gRPC server you already run.

A process is a goroutine with a mailbox and a cluster-wide PID. Send, Call, Monitor and Exit work the same whether the target is in this binary or on another node; the node-to-node traffic is one gRPC stream per direction, registered on your *grpc.Server next to your other services.

  • A library, not a framework. You bring the gRPC server, credentials, discovery, slog and lifecycle. grpcproc never opens a listener, reads env vars, installs globals or starts a goroutine outside Start/Stop.
  • Typed mailboxes. The message type lives on the address, so a send to Addr[*shoppb.Reserve] is checked by the compiler, locally and remotely. Instantiate with proto.Message for an untyped process.
  • Erlang semantics. Per-sender ordering, Down in order with messages, incarnation in the PID so a restart never resurrects a reference, unbounded mailboxes so a slow process cannot stall the link.
  • Inspectable. Every process and link keeps counters you can snapshot; a process can publish what it currently believes through WithInspect; one Hooks interface taps everything for metrics, tracing and dead letters.
  • Core depends on grpc and protobuf only.
go get github.com/floatdrop/grpcproc

Requires Go 1.27 (generic methods).

The guide is one application, read top to bottom: a shop whose services are actors wired with golang.yandex/di, run in one process or as three nodes from the same code.

Quick start

Two nodes, a typed process on one, called and monitored from the other:

// Quick start: two nodes, a typed process on one, called and monitored from
// the other. Each node is normally its own service; here both run in one
// binary, on loopback.
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"net"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/protobuf/proto"

	"github.com/floatdrop/grpcproc"
	"github.com/floatdrop/grpcproc/examples/shoppb"
)

func main() {
	ctx := context.Background()

	// Where each node's gRPC server listens: a static address book here,
	// grpcproc/etcd in a real cluster.
	warehouseLis := listen()
	shopLis := listen()
	peers := grpcproc.StaticResolver{
		"warehouse": warehouseLis.Addr().String(),
		"shop":      shopLis.Addr().String(),
	}

	warehouse, stopWarehouse := serve(ctx, "warehouse", warehouseLis, peers)
	defer stopWarehouse()
	shop, stopShop := serve(ctx, "shop", shopLis, peers)
	defer stopShop()

	// A process on warehouse. Its mailbox holds *shoppb.Reserve and
	// nothing else; it answers each call with *shoppb.Reserved.
	_, err := warehouse.Spawn(func(p *grpcproc.Process[*shoppb.Reserve]) error {
		left := map[string]int64{"apple": 3}
		for {
			m, err := p.Receive()
			if err != nil {
				return err // asked to exit, or the node is stopping
			}
			if left[m.Body.Sku] < m.Body.Qty {
				_ = p.Reply(m, nil, fmt.Errorf("only %d %s left", left[m.Body.Sku], m.Body.Sku))
				continue
			}
			left[m.Body.Sku] -= m.Body.Qty
			_ = p.Reply(m, &shoppb.Reserved{Sku: m.Body.Sku, Left: left[m.Body.Sku]}, nil)
		}
	}, grpcproc.WithName("stock"))
	if err != nil {
		log.Fatal(err)
	}

	// From shop, the process is a node name and a process name. The address
	// carries the mailbox type, so the compiler checks what is sent to it.
	stock := grpcproc.Named[*shoppb.Reserve]("warehouse", "stock")
	for range 2 {
		r, err := shop.Call[*shoppb.Reserved](ctx, stock, &shoppb.Reserve{Sku: "apple", Qty: 2})
		if err != nil {
			fmt.Println("reserve failed:", err) // the handler's error, as a *grpcproc.RemoteError
			continue
		}
		fmt.Println("reserved, left:", r.Left)
	}

	// 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. It
	// expects no messages, so its mailbox is untyped: proto.Message.
	done := make(chan grpcproc.Down)
	_, err = shop.Spawn(func(p *grpcproc.Process[proto.Message]) error {
		p.Monitor(stock)
		if err := p.Exit(stock, "closing"); err != nil {
			return err
		}
		for {
			m, err := p.Receive()
			if err != nil {
				return err
			}
			if m.Down != nil {
				done <- *m.Down
				return nil
			}
		}
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("stock exited:", (<-done).Reason)

	_, err = shop.Call[*shoppb.Reserved](ctx, stock, &shoppb.Reserve{Sku: "apple", Qty: 1})
	fmt.Println("no such process:", errors.Is(err, grpcproc.ErrNoProc))
}

func listen() net.Listener {
	lis, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		log.Fatal(err)
	}
	return lis
}

// serve runs a node on its own gRPC server, the one the service already has
// for its other APIs.
func serve(ctx context.Context, name string, lis net.Listener, peers grpcproc.Resolver) (*grpcproc.Node, func()) {
	node, err := grpcproc.NewNode(grpcproc.Config{
		Name:        name,
		Resolver:    peers,
		DialOptions: []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())},
	})
	if err != nil {
		log.Fatal(err)
	}
	srv := grpc.NewServer()
	node.Register(srv) // grpcproc.v1.Node, next to the service's own
	go func() { _ = srv.Serve(lis) }()
	if err := node.Start(ctx); err != nil {
		log.Fatal(err)
	}
	return node, func() {
		if err := node.Stop(ctx); err != nil {
			log.Println(err)
		}
		srv.GracefulStop()
	}
}

It prints:

reserved, left: 1
reserve failed: only 1 apple left
stock exited: closing
no such process: true

Actors and supervisors

grpcproc/actor adds structure on top of processes, using only the public API. An actor is a plain struct holding its dependencies, which is what a constructor or a DI container builds. Instead of a receive loop it has a method per kind of message; all but HandleMessage are optional. An actor that only answers calls embeds actor.CallsOnly[M] in place of it, which logs and drops anything sent to it without a call:

Method Runs for Its result
Init once, before the first message an error ends the actor
HandleMessage a message sent with Send an error ends the actor with it as the reason; actor.ErrStop ends it normally
HandleCall a message sent with Call the reply, a message or an error, and the actor carries on; actor.ErrNoReply answers later with p.Reply
HandleDown a Down from a monitor as for HandleMessage
Terminate once, when the actor ends, however it ends none: the exit reason is already decided

This one keeps stock. A reservation it cannot serve yet is parked and answered when a restock arrives:

// Actors: a struct with its dependencies and a method per kind of message,
// instead of a receive loop.
package main

import (
	"context"
	"errors"
	"fmt"
	"log"

	"google.golang.org/protobuf/proto"

	"github.com/floatdrop/grpcproc"
	"github.com/floatdrop/grpcproc/actor"
	"github.com/floatdrop/grpcproc/examples/shoppb"
)

// Ledger records reservations. It stands for whatever the actor depends on:
// a repository, a client, a config, built by a constructor or a DI container.
type Ledger struct{}

func (Ledger) Record(r *shoppb.Reserve) { fmt.Println("ledger:", r.Qty, r.Sku) }

// 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
}

// 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
}

// 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(p *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 {
			_ = p.Reply(c, i.reserve(res), nil)
		} else {
			i.waiting = append(i.waiting, c)
		}
	}
	return nil
}

// 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)
}

func (i *Inventory) reserve(r *shoppb.Reserve) *shoppb.Reserved {
	i.left[r.Sku] -= r.Qty
	i.ledger.Record(r)
	return &shoppb.Reserved{Sku: r.Sku, Left: i.left[r.Sku]}
}

func main() {
	ctx := context.Background()
	node, err := grpcproc.NewNode(grpcproc.Config{Name: "shop", Resolver: grpcproc.StaticResolver{}})
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = node.Stop(ctx) }()

	inventory, err := node.Spawn(actor.Run(&Inventory{ledger: &Ledger{}}), grpcproc.WithName("inventory"))
	if err != nil {
		log.Fatal(err)
	}

	// 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 := node.Call[*shoppb.Reserved](ctx, inventory, reserve("apple", 2))
		if err != nil {
			log.Fatal(err)
		}
		reserved <- r
	}()
	if err := node.Send(ctx, inventory, restock("apple", 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 = node.Call[*shoppb.Reserved](ctx, inventory, reserve("apple", -1))
	fmt.Println("reserve failed:", err)
	r, err := node.Call[*shoppb.Reserved](ctx, inventory, reserve("apple", 1))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("reserved, left:", r.Left)

	// A reservation sent without waiting for the answer breaks the
	// protocol: HandleMessage fails, and the actor exits. The call behind
	// it in the mailbox is never handled.
	if err := node.Send(ctx, inventory, reserve("apple", 1)); err != nil {
		log.Fatal(err)
	}
	_, err = node.Call[*shoppb.Reserved](ctx, inventory, reserve("apple", 1))
	fmt.Println("then:", err)
}

func reserve(sku string, qty int64) *shoppb.Stock {
	return &shoppb.Stock{Op: &shoppb.Stock_Reserve{Reserve: &shoppb.Reserve{Sku: sku, Qty: qty}}}
}

func restock(sku string, qty int64) *shoppb.Stock {
	return &shoppb.Stock{Op: &shoppb.Stock_Restock{Restock: &shoppb.Restock{Sku: sku, Qty: qty}}}
}

It prints:

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

A supervisor starts its children in order, monitors them, and restarts those that exit. Its Strategy says which: OneForOne only the child that exited, OneForAll every child, RestForOne the child and those started after it. A child's Restart says when: Permanent always, Transient after an abnormal exit only, Temporary never. A supervisor that restarts more than MaxRestarts times Within its window gives up and exits with max restarts; its own supervisor, a ChildSupervisor, then restarts it, which is how failure moves up the tree.

Here the inventory crashes on a bad message and comes back under the same name, with its state loaded from the ledger:

// Supervisors: an actor that crashes is started again, from a clean state,
// under the same name.
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"maps"
	"sync"
	"time"

	"google.golang.org/protobuf/proto"

	"github.com/floatdrop/grpcproc"
	"github.com/floatdrop/grpcproc/actor"
	"github.com/floatdrop/grpcproc/examples/shoppb"
)

// Ledger stands for a database. What must outlive a crash lives outside the
// actor, and the actor loads it when it starts.
type Ledger struct {
	mu   sync.Mutex
	left map[string]int64
}

func (l *Ledger) Load() map[string]int64 {
	l.mu.Lock()
	defer l.mu.Unlock()
	return maps.Clone(l.left)
}

func (l *Ledger) Save(sku string, left int64) {
	l.mu.Lock()
	defer l.mu.Unlock()
	l.left[sku] = left
}

// Inventory is the supervised actor.
type Inventory struct {
	ledger *Ledger
	left   map[string]int64
}

func (i *Inventory) Init(*grpcproc.Process[*shoppb.Stock]) error {
	i.left = i.ledger.Load()
	return nil
}

func (i *Inventory) HandleMessage(_ *grpcproc.Process[*shoppb.Stock], m grpcproc.Msg[*shoppb.Stock]) error {
	r := m.Body.GetRestock()
	if r.GetQty() <= 0 {
		// A bad message, or a bug: the error ends the actor with it as the
		// reason, and the supervisor starts a new one.
		return fmt.Errorf("bad restock of %d %s", r.GetQty(), r.GetSku())
	}
	i.left[r.Sku] += r.Qty
	i.ledger.Save(r.Sku, i.left[r.Sku])
	return nil
}

func (i *Inventory) HandleCall(_ *grpcproc.Process[*shoppb.Stock], m grpcproc.Msg[*shoppb.Stock]) (proto.Message, error) {
	r := m.Body.GetReserve()
	if i.left[r.GetSku()] < r.GetQty() {
		return nil, errors.New("not enough stock")
	}
	i.left[r.Sku] -= r.Qty
	i.ledger.Save(r.Sku, i.left[r.Sku])
	return &shoppb.Reserved{Sku: r.Sku, Left: i.left[r.Sku]}, nil
}

func main() {
	ctx := context.Background()
	node, err := grpcproc.NewNode(grpcproc.Config{Name: "shop", Resolver: grpcproc.StaticResolver{}})
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = node.Stop(ctx) }()

	ledger := &Ledger{left: map[string]int64{}}
	sup, err := actor.Supervise(node, actor.Spec{
		// Restart only the child that exited. OneForAll restarts every
		// child; RestForOne, the child and those started after it.
		Strategy: actor.OneForOne,
		// More restarts than this and the supervisor gives up: it exits
		// with "max restarts", and its own supervisor, if any, restarts it.
		MaxRestarts: 3,
		Within:      time.Minute,
		Children: []actor.ChildSpec{
			// A child is registered under its name. Child builds a new
			// handler for every start, so a restart never sees the state
			// that crashed. ChildFunc runs a plain process function, and
			// ChildSupervisor nests another Spec.
			actor.Child("inventory", func() *Inventory { return &Inventory{ledger: ledger} }),
		},
	}, grpcproc.WithName("supervisor"))
	if err != nil {
		log.Fatal(err)
	}

	// The name reaches whichever process currently runs the child.
	inventory := grpcproc.Named[*shoppb.Stock]("shop", "inventory")
	if err := node.Send(ctx, inventory, restock("apple", 5)); err != nil {
		log.Fatal(err)
	}
	r, err := node.Call[*shoppb.Reserved](ctx, inventory, reserve("apple", 2))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("reserved, left:", r.Left)

	// Crash it, and follow what the supervisor does through node events.
	events := node.Subscribe(ctx, 16)
	if err := node.Send(ctx, inventory, restock("apple", 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
		}
	}

	// Same name, new process, state loaded back from the ledger.
	r, err = node.Call[*shoppb.Reserved](ctx, inventory, reserve("apple", 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"])
}

func reserve(sku string, qty int64) *shoppb.Stock {
	return &shoppb.Stock{Op: &shoppb.Stock_Reserve{Reserve: &shoppb.Reserve{Sku: sku, Qty: qty}}}
}

func restock(sku string, qty int64) *shoppb.Stock {
	return &shoppb.Stock{Op: &shoppb.Stock_Restock{Restock: &shoppb.Restock{Sku: sku, Qty: qty}}}
}

It prints:

reserved, left: 3
inventory exited: bad restock of 0 apple
inventory started again
reserved, left: 2
supervisor restarts: 1/3 in 1m0s

Children are monitored from before they run (p.SpawnMonitor), so no exit is missed. A supervisor publishes its children and restart counts through WithInspect, so the Inspector shows the supervision tree's state.

What a process sees

ref := p.Monitor(stock)                  // Down{Ref: ref} when it exits or its node is unreachable
err := p.Send(stock, &shoppb.Reserve{…}) // compile-time typed
r, err := p.Call[*shoppb.Reserved](ctx, stock, &shoppb.Reserve{…})
err = p.SendTo(m.From, &shoppb.Restock{…}) // untyped: a PID from a message
a, err := p.CallTo[*shoppb.Reserved](ctx, m.From, &shoppb.Reserve{…})

// Node has the same four, and each takes a ctx: its metadata goes with the
// message. It bounds a whole Call, but for Send only the first connection.
// Node.Exit takes a ctx too, for the first connection only.
Call Returns
p.Receive() Msg[M]{From, Body, Down, Metadata}; error when asked to exit
p.ReceiveTimeout(d) the same, or context.DeadlineExceeded
p.Send(to Addr[N], m N) / p.SendTo(Target, proto.Message) typed / untyped asynchronous send
p.Call[R](ctx, to Addr[N], req N) / p.CallTo[R](ctx, Target, proto.Message) the reply as R, *RemoteError, ErrNoProc (also when the callee exits before answering), ErrType or ErrNoConnection
p.Reply(m, resp, err) answers a call; may be deferred to another goroutine
p.Monitor(target) / p.Demonitor(ref) a Down with the ref when the target exits: normal, the returned error, panic: …, killed, noproc, noconnection, shutdown
p.Exit(target, reason) asks another process to exit; its Receive returns an *ExitError
p.Log() *slog.Logger with pid and label; threshold settable at runtime
p.SendAfter(d, to, m) a *Timer; cancelled if the process exits first; carries the metadata of when it was scheduled
p.Spawn[N](fn, …) / p.SpawnMonitor[N](fn, …) a child on the same node, with p as its parent; the second monitored before it runs

Exit reasons and the type check on delivery are the whole error model: a message of the wrong type is a dead letter with reason type (and ErrType to a caller), never a panic in the process.

Observability

node.Processes()            // []ProcessInfo: state, mailbox depth and oldest age, sent/received,
                            // calls in flight, last message type, watchers, monitors, log level
node.Process(pid)
node.Info()                 // NodeInfo: incarnation, uptime, counts, per-link messages/bytes/reconnects
node.Inspect(ctx, pid)      // the map the process's WithInspect returns, produced on its own goroutine
node.SetLogLevel(pid, slog.LevelDebug)

WithInspect runs between two messages, inside Receive, so it reads the process's state without a lock. A process busy in a handler answers when it next receives; one that never does reports busy for 12s, which is the diagnosis. With a state machine that is one line:

grpcproc.WithInspect(func() map[string]string { return map[string]string{"state": rec.state.String()} })

node.Subscribe(ctx, buffer) streams what happens on the node: spawns, exits with their reasons, links up and down, dead letters. It never blocks the node; a subscriber that falls behind loses events and is told how many in the next one's Missed.

Config.Hooks is the synchronous tap for everything else: OnSpawn, OnExit, OnSend, OnReceive, OnDeadLetter, OnLinkUp, OnLinkDown. OnSend and OnReceive return the metadata to use and a Done that closes what they started, which is all a tracer needs. A process's sends inherit the metadata of the message it is handling, so trace chains form without threading a context through handlers. grpcproc.JoinHooks combines several.

grpcproc/otel implements them with OpenTelemetry: spans for every send, call and handled message, chained across nodes, and metrics by process label (throughput, mailbox wait and depth, handling and call latency, exits by reason class, dead letters, link traffic).

Inspector

grpcproc/inspect serves all of the above over gRPC, on the same server:

node.Register(grpcServer)
insp := inspect.New(node, inspect.WithResolver(resolver, dialOptions...)) // reaches other nodes' Inspectors
insp.Register(grpcServer)
defer insp.Close()

grpcproc.inspect.v1.Inspector has GetNode, ListProcesses (filter by name, label, state, mailbox depth), GetProcess (snapshot plus what the process publishes through WithInspect), SetLogLevel, Send, Exit and Watch. Every request names a node; one that is not this node is forwarded to that node's Inspector, so one endpoint inspects the whole cluster. inspect.ReadOnly() refuses the three writes; anything finer is the job of the interceptors that guard your other services.

grpcprocctl is its command line, and serves it to AI agents over MCP:

grpcprocctl --plaintext ps --sort mailbox        # who is falling behind
grpcprocctl --plaintext inspect ledger-writer    # what it believes, or that it is busy
grpcprocctl --plaintext dot --cluster | dot -Tsvg -o processes.svg
claude mcp add grpcproc -- grpcprocctl --plaintext --addr 10.0.0.5:9000 mcp

It is a plain gRPC service, so grpcurl works on it too.

Discovery

Config.Resolver is all a node needs to reach peers; grpcproc.StaticResolver is a map. Config.Registrar publishes the node on Start and withdraws it on Stop, and Config.Membership is the cluster's view of who is alive: a peer that leaves, or comes back as a new incarnation, has its links dropped, so monitors fire and pending calls fail even when its connection never closed. grpcproc/etcd implements all three on etcd leases.

Testing a cluster

grpcproctest runs nodes over in-memory connections, so a multi-node scenario is a plain go test:

package shop

import (
	"errors"
	"testing"

	"github.com/floatdrop/grpcproc"
	"github.com/floatdrop/grpcproc/examples/shoppb"
	"github.com/floatdrop/grpcproc/grpcproctest"
)

func TestReserveAcrossNodes(t *testing.T) {
	// Two nodes over in-memory gRPC connections, stopped when the test ends.
	c := grpcproctest.New(t, "shop", "warehouse")
	shop := c.Node("shop")
	if _, err := c.Node("warehouse").Spawn(Stock(map[string]int64{"apple": 3}), grpcproc.WithName("stock")); err != nil {
		t.Fatal(err)
	}
	stock := grpcproc.Named[*shoppb.Reserve]("warehouse", "stock")
	apple := &shoppb.Reserve{Sku: "apple", Qty: 1}

	if r, err := shop.Call[*shoppb.Reserved](t.Context(), stock, apple); err != nil || r.Left != 2 {
		t.Fatal(r, err)
	}

	// A partition fails calls, and fires monitors with Down{noconnection},
	// until it heals.
	c.Partition("shop", "warehouse")
	if _, err := shop.Call[*shoppb.Reserved](t.Context(), stock, apple); !errors.Is(err, grpcproc.ErrNoConnection) {
		t.Fatal(err)
	}
	c.Heal("shop", "warehouse")
	if r, err := shop.Call[*shoppb.Reserved](t.Context(), stock, apple); err != nil || r.Left != 1 {
		t.Fatal(r, err)
	}

	// A crash, and a restart: same node name, new incarnation, and none of
	// the processes the old one ran.
	c.Kill("warehouse")
	c.Restart("warehouse")
	if _, err := shop.Call[*shoppb.Reserved](t.Context(), stock, apple); !errors.Is(err, grpcproc.ErrNoProc) {
		t.Fatal(err)
	}
}

c.Stop(name) stops a node gracefully, so watchers get Down{shutdown}. grpcproctest.WithServices registers extra services (an Inspector) on every node, and c.Conn(name) dials one.

Examples

The programs above are in examples, a module of its own. CI runs each one and compares what it prints with its output.txt, and checks that this README embeds the current code, with embedmd. After editing an example:

cd examples && go test ./quickstart ./actors ./supervisor -update
cd .. && gofmt -w examples && go run github.com/campoy/embedmd@v1.0.0 -w README.md

examples/guide is the application the guide shows, from site/. Its tests run it in both deployments and pin the output the page prints; go test ./guide -update refreshes it.

Design

docs/DESIGN.md has the wire protocol, the reasons behind the choices (and what was rejected), what the observability surface is copied from, and what is left: releases, a cluster-wide name registry.

Performance

Against GoAkt, Hollywood and Proto.Actor on the same machine (Apple M3 Max), remote over TCP on loopback for all; see benchmarks for the method and how to read it:

grpcproc GoAkt Hollywood Proto.Actor
Local send 99 ns 96 ns 58 ns 191 ns
Local request 738 ns 565 ns 2265 ns 2354 ns
Remote send 368 ns 514 ns 205 ns 315 ns
Remote request 44.4 µs 34.5 µs 36.4 µs 58.6 µs
Remote request, 14 in parallel 7.5 µs 10.2 µs 4.9 µs 7.1 µs

A mailbox that keeps up, and a local send, allocate nothing.

License

MIT, see LICENSE.

Documentation

Overview

Package grpcproc gives goroutines Erlang-style network transparency on top of the gRPC server a service already runs. A process is addressed by a PID or a name; Send, Call, Monitor and Exit work the same whether the target lives in this binary or on another node.

Index

Constants

View Source
const (
	ReasonNormal       = "normal"
	ReasonNoProc       = "noproc"
	ReasonNoConnection = "noconnection"
	ReasonShutdown     = "shutdown"
	ReasonKilled       = "killed"
	ReasonType         = "type"
)

Exit reasons used by grpcproc itself. Applications use any string.

Variables

View Source
var (
	ErrNoProc       = errors.New("grpcproc: no such process")
	ErrNoConnection = errors.New("grpcproc: no connection to node")
	ErrNameTaken    = errors.New("grpcproc: name already registered")
	ErrNotLocal     = errors.New("grpcproc: pid does not belong to this node")
	ErrNodeStopped  = errors.New("grpcproc: node stopped")
	ErrNotCall      = errors.New("grpcproc: message is not a call")
	ErrType         = errors.New("grpcproc: process does not accept this message type")
)

Functions

func WithMetadata

func WithMetadata(ctx context.Context, md Metadata) context.Context

WithMetadata returns a context carrying md, merged over any metadata already in ctx. Node.Send, Node.SendTo and every Call propagate it with the message.

Types

type Addr

type Addr[M proto.Message] struct {
	// contains filtered or unexported fields
}

Addr is a typed address: a PID or a Name plus the message type M the process behind it accepts. The type is checked at compile time for local and remote sends alike; it is verified again on delivery, because types do not cross the wire.

func AddrOf

func AddrOf[M proto.Message](t Target) Addr[M]

AddrOf types an untyped target. Nothing checks that the process behind it really accepts M until a message is delivered.

func Named

func Named[M proto.Message](node, name string) Addr[M]

Named addresses the process registered as name on node.

func (Addr[M]) Name

func (a Addr[M]) Name() string

Name returns the registered name, or "" for a PID address.

func (Addr[M]) Node

func (a Addr[M]) Node() string

Node returns the node the address points at.

func (Addr[M]) PID

func (a Addr[M]) PID() PID

PID returns the address's PID; it is zero but for Node when the address is a name.

func (Addr[M]) String

func (a Addr[M]) String() string

type Config

type Config struct {
	// Name is the node's logical name; peers address it by this.
	Name string
	// Advertise is the address peers dial to reach this node's gRPC server.
	// It is only informational to the core (NodeInfo, Hello); a Registrar
	// publishes it.
	Advertise string
	// Incarnation distinguishes this start of the node from earlier ones.
	// Zero picks the current Unix time in nanoseconds.
	Incarnation uint64
	// Resolver maps peer names to addresses.
	Resolver Resolver
	// Registrar, if set, publishes the node on Start and withdraws it on Stop.
	Registrar Registrar
	// Membership, if set, is watched from Start: a peer that leaves the
	// cluster, or comes back as a new incarnation, has its links dropped,
	// which fires Down{noconnection} for monitors across them and fails
	// pending calls.
	Membership Membership
	// DialOptions are used for every outbound connection: credentials,
	// keepalive, interceptors. Keepalive is what turns a silent partition
	// into a link error; set it.
	DialOptions []grpc.DialOption
	// Authorize, if set, runs for every inbound link with the peer's
	// transport credentials in ctx (grpc/peer) and the identity it claims.
	Authorize func(ctx context.Context, peer NodeID) error
	// Logger defaults to slog.Default().
	Logger *slog.Logger
	// Hooks is the observability tap; nil means none.
	Hooks Hooks
	// CopyLocal clones every locally delivered message, so a sender can keep
	// mutating what it sent. Off by default: the pointer is shared.
	CopyLocal bool
	// DialTimeout bounds the connect + handshake of a link. Default 5s.
	DialTimeout time.Duration
}

Config configures a Node. Name and Resolver are required.

type Done

type Done func(err error)

Done ends what a hook started. For a send it runs once the message is handed to delivery, with the error Send returns; for a call, once the call returns, with its error; for a received message, when the process next calls Receive (nil) or exits (nil if normally, else its reason).

type Down

type Down struct {
	Ref Ref
	// PID is the process that exited. For a monitor placed by name on a
	// node that became unreachable, which process held the name is not
	// known: PID has only its Node, and Name says what was monitored.
	PID    PID
	Name   string // the registered name, when the monitor was placed by name
	Reason string
}

Down is delivered to a watcher when the process it monitors exits, or when that process's node becomes unreachable.

type Event

type Event struct {
	Kind    EventKind
	Time    time.Time
	Process ProcessInfo
	Reason  string
	Peer    NodeID
	Err     string
	From    PID
	To      PID
	Type    string
	// Missed is how many events this subscriber lost, because its buffer
	// was full, since the event before this one.
	Missed uint64
}

Event is something that happened on a node. Which fields are set depends on Kind:

EventSpawn       Process
EventExit        Process, Reason
EventLinkUp      Peer
EventLinkDown    Peer, Err
EventDeadLetter  From, To, Type (proto full name), Reason

type EventKind

type EventKind uint8

EventKind says what an Event reports.

const (
	EventSpawn EventKind = iota + 1
	EventExit
	EventLinkUp
	EventLinkDown
	EventDeadLetter
)

func (EventKind) String

func (k EventKind) String() string

type ExitError

type ExitError struct{ Reason string }

ExitError is the cause of a process's context when it was asked to exit.

func (*ExitError) Error

func (e *ExitError) Error() string

type Hooks

type Hooks interface {
	OnSpawn(ProcessInfo)
	OnExit(info ProcessInfo, reason string)
	OnSend(s SendInfo, md Metadata) (Metadata, Done)
	OnReceive(r ReceiveInfo, md Metadata) (Metadata, Done)
	// OnDeadLetter runs when a message could not be delivered: no such
	// process (ReasonNoProc), wrong type (ReasonType), node unreachable
	// (ReasonNoConnection). body is nil for a message that could not be
	// decoded.
	OnDeadLetter(from, to PID, body proto.Message, reason string)
	OnLinkUp(peer NodeID)
	OnLinkDown(peer NodeID, err error)
}

Hooks is the single tap for observability. Every method is called synchronously on the goroutine doing the work, so implementations must be cheap and must not call back into the node. Embed NopHooks and override what you need; combine several with JoinHooks.

OnSend and OnReceive return the metadata to use from then on, which is how trace context is propagated: OnSend may add to what leaves, and what OnReceive returns is what the process's own sends inherit while it handles the message. They must not modify md, which may be shared; return a copy to change it.

func JoinHooks

func JoinHooks(hs ...Hooks) Hooks

JoinHooks combines several Hooks into one. Metadata passes through them in order, each seeing what the previous returned; Done functions run in reverse order, so the first hook's span encloses the others'. Nil entries are skipped; JoinHooks of none is nil.

type LinkError

type LinkError struct {
	Peer string
	Err  error
}

LinkError wraps the transport error that closed a link to a peer.

func (*LinkError) Error

func (e *LinkError) Error() string

func (*LinkError) Is

func (*LinkError) Is(target error) bool

Is reports true for ErrNoConnection: every link failure is one.

func (*LinkError) Unwrap

func (e *LinkError) Unwrap() error

type LinkInfo

type LinkInfo struct {
	Peer          NodeID
	Outbound      bool // this node opened the stream
	State         LinkState
	EstablishedAt time.Time
	Reconnects    uint64
	Messages      uint64 // envelopes: messages, calls, replies, monitors, downs
	Bytes         uint64 // message bodies carried, not counting framing
	LastError     string
}

LinkInfo describes one direction of traffic with a peer.

type LinkState

type LinkState uint8

LinkState is the state of a link to a peer.

const (
	LinkConnecting LinkState = iota
	LinkUp
	LinkDown
)

func (LinkState) String

func (s LinkState) String() string

type MailboxInfo

type MailboxInfo struct {
	Depth int
	Peak  int
	// OldestAge is how long the oldest queued message has waited, 0 when
	// empty. It is read from when its batch started queueing: exact for the
	// first message of a burst, an upper bound for later ones.
	OldestAge time.Duration
}

MailboxInfo is a snapshot of a mailbox.

type Member

type Member struct {
	Name        string
	Incarnation uint64
	Addr        string // where peers dial it: its Config.Advertise
}

Member is one incarnation of a node, as the cluster knows it.

type MemberEvent

type MemberEvent struct {
	Member Member
	Up     bool
}

MemberEvent is a member joining (Up) or leaving the cluster. A leaving member with Incarnation 0 means whichever incarnation it was.

type Membership

type Membership interface {
	// Watch reports members joining and leaving until ctx is done, then
	// closes the channel.
	Watch(ctx context.Context) (<-chan MemberEvent, error)
}

Membership is the cluster's authoritative view of which nodes are alive. Links notice a dead peer by themselves, but only as fast as keepalive allows and not at all behind a half-open connection; Membership (an etcd lease expiring, say) settles it.

type Metadata

type Metadata map[string]string

Metadata is propagated with every message, unchanged by grpcproc: trace context, tenant, anything the application's interceptors would carry.

func MetadataFrom

func MetadataFrom(ctx context.Context) Metadata

MetadataFrom returns the metadata carried by ctx, or nil.

type Msg

type Msg[M proto.Message] struct {
	From     PID
	Body     M
	Down     *Down
	Metadata Metadata
	// contains filtered or unexported fields
}

Msg is what Receive returns: a message (Body) or a Down, never both.

func (Msg[M]) Context

func (m Msg[M]) Context(parent context.Context) context.Context

Context returns a context carrying the message's metadata, for Node.Send, a Call, or any code taking a ctx, run on behalf of the message.

func (Msg[M]) IsCall

func (m Msg[M]) IsCall() bool

IsCall reports whether the sender waits for a Reply.

type Name

type Name struct {
	Node string
	Name string
}

Name addresses a process by the name it registered on a node.

func (Name) String

func (n Name) String() string

type Node

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

Node hosts processes and links to peers. It is a plain value the application constructs, registers on its gRPC server, starts and stops.

func NewNode

func NewNode(cfg Config) (*Node, error)

NewNode validates cfg and returns a node that is not yet started.

func (*Node) Call

func (n *Node) Call[R, N proto.Message](ctx context.Context, to Addr[N], req N) (R, error)

Call sends req to a typed address and waits for the reply, typed as R:

resp, err := node.Call[*orderspb.Reserved](ctx, addr, &orderspb.Order{…})

A reply of another type is ErrType; a handler error is a *RemoteError; a callee that is gone, or exits before answering, is ErrNoProc.

func (*Node) CallTo

func (n *Node) CallTo[R proto.Message](ctx context.Context, to Target, req proto.Message) (R, error)

CallTo is Call to an untyped target.

func (*Node) Disconnect

func (n *Node) Disconnect(peer string) bool

Disconnect drops every link with peer, as if the network had. Monitors across it fire Down{noconnection} and pending calls fail; the next send dials again. It reports whether there was a link to drop.

func (*Node) Exit

func (n *Node) Exit(ctx context.Context, to Target, reason string) error

Exit asks a process anywhere to terminate with reason. As for Send, ctx bounds only the wait for a connection to a peer this node has no link to yet.

func (*Node) ID

func (n *Node) ID() NodeID

ID is the node's name and incarnation.

func (*Node) Info

func (n *Node) Info() NodeInfo

Info snapshots the node.

func (*Node) Inspect

func (n *Node) Inspect(ctx context.Context, pid PID) (map[string]string, error)

Inspect asks a local process what it currently believes: the map its WithInspect function returns, produced on the process's own goroutine between two messages. A process busy in a handler answers when it next calls Receive; ctx bounds the wait.

func (*Node) Name

func (n *Node) Name() string

Name is the node's logical name.

func (*Node) PID

func (n *Node) PID() PID

PID is the node's own pseudo-process (ID 0): the sender of messages sent from outside any process.

func (*Node) Peers

func (n *Node) Peers() []string

Peers lists nodes with a live link in either direction.

func (*Node) Process

func (n *Node) Process(pid PID) (ProcessInfo, bool)

Process snapshots one local process.

func (*Node) Processes

func (n *Node) Processes() []ProcessInfo

Processes snapshots every local process, ordered by PID.

func (*Node) Register

func (n *Node) Register(s grpc.ServiceRegistrar)

Register mounts the grpcproc.v1.Node service on s. Call it before the server starts serving.

func (*Node) Send

func (n *Node) Send[N proto.Message](ctx context.Context, to Addr[N], m N) error

Send delivers m to a typed address, local or remote, with the node as sender and the metadata carried by ctx. It returns once m is queued; ctx bounds only the wait for a connection to a peer this node has no link to yet. Sending to a process that does not exist is not an error (it is a dead letter); an error means m could not be encoded, the node could not be reached, or ctx ended first.

func (*Node) SendTo

func (n *Node) SendTo(ctx context.Context, to Target, m proto.Message) error

SendTo delivers m to an untyped target: a PID, a Name, or an Addr of another type. The target's type is checked on delivery only.

func (*Node) SetLogLevel

func (n *Node) SetLogLevel(pid PID, level slog.Level) error

SetLogLevel sets the threshold of a local process's Log() at runtime.

func (*Node) Spawn

func (n *Node) Spawn[M proto.Message](fn func(*Process[M]) error, opts ...SpawnOption) (Addr[M], error)

Spawn starts fn as a process that accepts messages of type M. The process ends when fn returns; nil means exit reason "normal", otherwise the error text is the reason. A panic is recovered, logged with its stack, and becomes reason "panic: …".

M may be a concrete type (one contract per process), an interface the accepted types implement, or proto.Message for an untyped process.

func (*Node) Start

func (n *Node) Start(ctx context.Context) error

Start watches Membership and publishes the node with its Registrar, when configured. Processes may be spawned before Start and run immediately; Start only makes the node known. A second call does nothing.

func (*Node) Stop

func (n *Node) Stop(ctx context.Context) error

Stop asks every process to exit (Receive returns ReasonShutdown), waits for them until ctx is done, then closes every link. Watchers of this node's processes receive Down{shutdown} while the links are still up. A dial in flight completes within Config.DialTimeout and its link is discarded; Stop waits for it too, until ctx is done.

func (*Node) Subscribe

func (n *Node) Subscribe(ctx context.Context, buffer int) <-chan Event

Subscribe streams the node's events until ctx is done or the node stops, then closes the channel. Publishing never blocks the node: when the channel's buffer is full the event is dropped, and the next event this subscriber receives carries the count in Missed.

func (*Node) Whereis

func (n *Node) Whereis(name string) (PID, bool)

Whereis resolves a name registered on this node.

type NodeID

type NodeID struct {
	Name        string
	Incarnation uint64
}

NodeID names one incarnation of a node.

func (NodeID) String

func (n NodeID) String() string

type NodeInfo

type NodeInfo struct {
	ID          NodeID
	Advertise   string
	StartedAt   time.Time
	Processes   int
	Spawned     uint64
	Exited      uint64
	DeadLetters uint64
	Links       []LinkInfo // ordered by peer name, outbound before inbound
}

NodeInfo is a snapshot of the node.

type NopHooks

type NopHooks struct{}

NopHooks implements Hooks with no-ops, for embedding.

func (NopHooks) OnDeadLetter

func (NopHooks) OnDeadLetter(PID, PID, proto.Message, string)

func (NopHooks) OnExit

func (NopHooks) OnExit(ProcessInfo, string)

func (NopHooks) OnLinkDown

func (NopHooks) OnLinkDown(NodeID, error)

func (NopHooks) OnLinkUp

func (NopHooks) OnLinkUp(NodeID)

func (NopHooks) OnReceive

func (NopHooks) OnReceive(_ ReceiveInfo, md Metadata) (Metadata, Done)

func (NopHooks) OnSend

func (NopHooks) OnSend(_ SendInfo, md Metadata) (Metadata, Done)

func (NopHooks) OnSpawn

func (NopHooks) OnSpawn(ProcessInfo)

type PID

type PID struct {
	Node        string
	Incarnation uint64
	ID          uint64
}

PID identifies a process anywhere in the cluster. It is a plain comparable value that can travel inside messages.

func (PID) IsZero

func (p PID) IsZero() bool

IsZero reports whether p is the zero PID.

func (PID) String

func (p PID) String() string

type Process

type Process[M proto.Message] struct {
	// contains filtered or unexported fields
}

Process is a goroutine with a mailbox of M and a cluster-wide PID.

func (*Process[M]) Addr

func (p *Process[M]) Addr() Addr[M]

Addr returns the process's typed address.

func (*Process[M]) Call

func (p *Process[M]) Call[R, N proto.Message](ctx context.Context, to Addr[N], req N) (R, error)

Call sends req and waits for the Reply, typed as R:

resp, err := p.Call[*orderspb.Reserved](ctx, addr, &orderspb.Order{…})

Replies do not pass through the mailbox, so calling from inside a process never reorders its messages. Errors are as for Node.Call.

func (*Process[M]) CallTo

func (p *Process[M]) CallTo[R proto.Message](ctx context.Context, to Target, req proto.Message) (R, error)

CallTo is Call to an untyped target, such as a Msg's From.

func (Process) Context

func (p Process) Context() context.Context

Context is cancelled when the process is asked to exit or its node stops. context.Cause is an *ExitError after Exit.

func (Process) Demonitor

func (p Process) Demonitor(ref Ref)

Demonitor stops a monitor. A Down already in the mailbox stays there.

func (Process) Exit

func (p Process) Exit(to Target, reason string) error

Exit asks another process, anywhere, to terminate with reason. A first exit to a node with no link yet waits for the dial, up to Config.DialTimeout.

func (Process) Log

func (p Process) Log() *slog.Logger

Log returns a logger with the process's pid and label attached. Its threshold can be changed at runtime with Node.SetLogLevel.

func (Process) Monitor

func (p Process) Monitor(target Target) Ref

Monitor watches target. When it exits, or its node becomes unreachable, this process receives a Msg with Down set and the returned Ref. Monitoring a process that does not exist yields Down{Reason: "noproc"}.

func (Process) Node

func (p Process) Node() *Node

Node returns the node hosting the process.

func (Process) PID

func (p Process) PID() PID

PID returns the process's PID.

func (*Process[M]) Receive

func (p *Process[M]) Receive() (Msg[M], error)

Receive blocks until a message or a Down arrives, or the process is told to exit. The error is then context.Canceled (node stop) or an *ExitError.

func (*Process[M]) ReceiveTimeout

func (p *Process[M]) ReceiveTimeout(d time.Duration) (Msg[M], error)

ReceiveTimeout is Receive with a deadline; context.DeadlineExceeded on timeout.

func (*Process[M]) Reply

func (p *Process[M]) Reply(m Msg[M], resp proto.Message, err error) error

Reply answers a message for which IsCall is true. It may be called later and from any goroutine (a deferred reply).

func (*Process[M]) Send

func (p *Process[M]) Send[N proto.Message](to Addr[N], m N) error

Send delivers m to a typed address, local or remote. It carries the metadata of the message the process is handling. A first send to a node with no link yet waits for the dial, up to Config.DialTimeout. See Node.Send.

func (*Process[M]) SendAfter

func (p *Process[M]) SendAfter[N proto.Message](d time.Duration, to Addr[N], m N) *Timer

SendAfter sends m to a typed address after d, as this process. The timer belongs to the process: it is cancelled if the process exits first. The message carries the metadata the process holds now, when it is scheduled, not whatever it is handling when the timer fires.

func (Process) SendTo

func (p Process) SendTo(to Target, msg proto.Message) error

SendTo delivers msg to an untyped target such as a Msg's From. The target's type is checked on delivery only.

func (*Process[M]) Spawn

func (p *Process[M]) Spawn[N proto.Message](fn func(*Process[N]) error, opts ...SpawnOption) (Addr[N], error)

Spawn starts fn as a process on p's node, like Node.Spawn, with p recorded as its parent. That is for inspection only: p does not monitor the child, and neither exits when the other does. A process that has exited spawns nothing: the error is ErrNoProc.

func (*Process[M]) SpawnMonitor

func (p *Process[M]) SpawnMonitor[N proto.Message](fn func(*Process[N]) error, opts ...SpawnOption) (Addr[N], Ref, error)

SpawnMonitor is Spawn, with the child monitored from p before it runs: however soon the child exits, p receives its Down with the real reason, never noproc. It is Erlang's spawn_monitor, and what a supervisor needs. A process that has exited spawns nothing: the error is ErrNoProc.

type ProcessInfo

type ProcessInfo struct {
	PID           PID
	Name          string // WithName; "" for an unnamed process
	Label         string // WithLabel; the low-cardinality key for metrics
	Type          string // the Go type of M, for display
	Parent        PID    // the spawning process, for Process.Spawn and SpawnMonitor; zero for Node.Spawn
	State         ProcessState
	StartedAt     time.Time
	Mailbox       MailboxInfo
	Received      uint64
	Sent          uint64
	CallsInFlight uint32
	LastMessage   string // proto full name of the last body taken from the mailbox
	Monitors      int    // held by this process
	Watchers      int    // processes monitoring this one
	Wakeups       uint64 // Receive returns
	LogLevel      slog.Level
}

ProcessInfo is a snapshot of one process, the same for local inspection, the Inspector service and any tool built on either.

type ProcessState

type ProcessState uint8

ProcessState is where a process is in its loop.

const (
	StateIdle         ProcessState = iota // blocked in Receive
	StateRunning                          // between Receive calls
	StateWaitingReply                     // blocked in Call
	StateExiting
)

func (ProcessState) String

func (s ProcessState) String() string

type ReceiveInfo

type ReceiveInfo struct {
	PID    PID
	Label  string
	From   PID
	Body   proto.Message // nil for a Down
	Down   *Down
	Call   bool // the sender waits for a Reply
	Waited time.Duration
}

ReceiveInfo describes a message a process has just taken from its mailbox.

type Ref

type Ref struct {
	Node string
	ID   uint64
}

Ref identifies a monitor. It is unique per watching node.

func (Ref) String

func (r Ref) String() string

type Registrar

type Registrar interface {
	// Register returns once self is published, and keeps it published
	// until withdraw is called. Start calls Register; Stop calls withdraw
	// last, after the node's processes have exited and their Down notices
	// have reached its peers.
	Register(ctx context.Context, self Member) (withdraw func(context.Context) error, err error)
}

Registrar publishes a node to the cluster, so that peers resolve it and Membership reports it.

type RemoteError

type RemoteError struct{ Msg string }

RemoteError is the error a Call handler returned, carried back to the caller.

func (*RemoteError) Error

func (e *RemoteError) Error() string

type Resolver

type Resolver interface {
	Resolve(ctx context.Context, node string) (addr string, err error)
}

Resolver turns a node name into an address grpc can dial.

type ResolverFunc

type ResolverFunc func(ctx context.Context, node string) (string, error)

ResolverFunc adapts a function to Resolver.

func (ResolverFunc) Resolve

func (f ResolverFunc) Resolve(ctx context.Context, node string) (string, error)

type SendInfo

type SendInfo struct {
	From      PID
	FromLabel string // "" when sent from outside any process
	To        PID    // To.ID is 0 when the target is a name
	ToName    string
	Body      proto.Message
	Call      bool // a Call, which ends when answered
	Remote    bool // the target is on another node
}

SendInfo describes a message or call about to leave its sender.

type SpawnOption

type SpawnOption func(*spawnOpts)

SpawnOption configures Node.Spawn, Process.Spawn and Process.SpawnMonitor.

func WithInspect

func WithInspect(fn func() map[string]string) SpawnOption

WithInspect lets the process publish what it currently believes. fn runs on the process's own goroutine, inside Receive, so it may read the process's state without locking. See Node.Inspect.

func WithLabel

func WithLabel(label string) SpawnOption

WithLabel tags the process with a low-cardinality label, the key metrics aggregate by. Defaults to the type of M.

func WithName

func WithName(name string) SpawnOption

WithName registers the process under name on its node before it runs. The name is held until the process exits; while another process holds it, spawning fails with ErrNameTaken.

type StaticResolver

type StaticResolver map[string]string

StaticResolver is a fixed node -> address map.

func (StaticResolver) Resolve

func (s StaticResolver) Resolve(_ context.Context, node string) (string, error)

type Target

type Target interface {
	// contains filtered or unexported methods
}

Target is anything a message can be addressed to: a PID, a Name, or an Addr.

type Timer

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

Timer is a message scheduled with SendAfter.

func (*Timer) Stop

func (t *Timer) Stop() bool

Stop cancels the send. It reports whether it did: false if the message was already sent, or the process has exited.

Directories

Path Synopsis
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.
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.
cron module
etcd module
Package grpcproctest runs a grpcproc cluster inside one test binary.
Package grpcproctest runs a grpcproc cluster inside one test binary.
Package inspect serves grpcproc.inspect.v1.Inspector: a node's processes, links and events over gRPC, for tools and for people.
Package inspect serves grpcproc.inspect.v1.Inspector: a node's processes, links and events over gRPC, for tools and for people.
internal
leader module
otel module
proto
saga
postgres module
tools module

Jump to

Keyboard shortcuts

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