grpcproc

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2026 License: MIT Imports: 23 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

CI Go Reference Coverage License

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

go get github.com/floatdrop/grpcproc

The full reference is on pkg.go.dev. The guide is one application, read top to bottom: a shop whose services are actors wired with golang.yandex/di, run as one program or as three nodes from the same code.

Quick start

A process is a function over a typed mailbox:

// inventory is a process whose mailbox holds *shoppb.Reserve and nothing
// else; every message is a call, answered with *shoppb.Reserved or with an
// error.
func inventory(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)
	}
}

warehouse and shop are two nodes, built as API shows. The process runs on one under a name, and the other reaches it by that name:

	if _, err := warehouse.Spawn(inventory, grpcproc.WithName("stock")); err != nil {
		log.Fatal(err)
	}

	// From shop, it 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 monitor across nodes works as one within a node does. The watcher's mailbox is untyped, proto.Message, since it expects nothing but the Down:

	// 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)
		if err := p.Exit(stock, "closing"); err != nil {
			return err
		}
		m, err := p.Receive() // the Down: nothing else is sent to this process
		if err != nil {
			return err
		}
		exited <- m.Down.Reason
		return nil
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("stock exited:", <-exited)

examples/quickstart is the whole program: each node on its own gRPC server, and a last call to the gone process, which fails with ErrNoProc. It prints:

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

API

A node is a value you construct, mount on your gRPC server, start and stop. Config needs a Name and a Resolver; DialOptions carry the credentials and keepalive for the links it opens:

node, err := grpcproc.NewNode(grpcproc.Config{Name: "shop", Resolver: peers, DialOptions: opts})
node.Register(grpcServer) // grpcproc.v1.Node, next to your services; before it serves
err = node.Start(ctx)     // publishes the node; processes spawned before it run already
err = node.Stop(ctx)      // "shutdown" to every process, waits for them (ctx bounds the wait), closes the links
Node
Spawn[M](fn func(*Process[M]) error, opts ...SpawnOption) (Addr[M], error) Runs fn as a process until it returns. M may be a concrete type, an interface, or proto.Message for an untyped process.
Send[N](ctx, to Addr[N], m N) error Queues m and returns. No such process is a dead letter, not an error.
SendTo(ctx, to Target, m proto.Message) error The same to an untyped target; the type is checked on delivery.
Call[R, N](ctx, to Addr[N], req N) (R, error) Sends and waits for the reply as R.
CallTo[R](ctx, to Target, req proto.Message) (R, error) The same to an untyped target.
Exit(ctx, to Target, reason string) error Asks a process anywhere to exit.
Whereis(name string) (PID, bool) A name registered on this node.
Processes(), Process(pid), Info(), Peers() Snapshots: every local process, one, the node with its links, the peers with a live link.
Inspect(ctx, pid) (map[string]string, error) What a local process publishes through WithInspect.
Subscribe(ctx, buffer int) <-chan Event Spawns, exits with their reasons, links up and down, dead letters.
SetLogLevel(pid, level slog.Level) error The threshold of a local process's Log().
Disconnect(peer string) bool Drops the links with a peer, as a partition would.
ID(), Name(), PID() The node's name and incarnation; the name alone; the pseudo-process (ID 0) its own sends come from.

The ctx of a Call bounds the whole call; for Send, SendTo and Exit it bounds only the wait for a first connection to a peer. Sends and calls carry the Metadata in that ctx with the message.

Process[M]
Receive() (Msg[M], error) Blocks for a message, a Down or an Exited. The error is an *ExitError after Exit or the exit of a process this one is linked to, context.Canceled when the node stops.
ReceiveTimeout(d) (Msg[M], error) The same, or context.DeadlineExceeded.
Reply(m Msg[M], resp proto.Message, err error) error Answers a call. It may run later, from any goroutine.
Send[N](to Addr[N], m N) error, SendTo(to Target, m proto.Message) error As on Node, with the process as the sender and the metadata of the message it is handling.
Call[R, N](ctx, to Addr[N], req N) (R, error), CallTo[R](ctx, to Target, req proto.Message) (R, error) As on Node. Replies bypass the mailbox, so a call from a process never reorders its messages.
SendAfter[N](d, to Addr[N], m N) *Timer A send after d, as this process, cancelled if it exits first; Timer.Stop cancels it too.
Monitor(target Target) Ref, Demonitor(ref) A Down with the ref when the target exits or its node is unreachable; at once, with noproc, for a process that does not exist.
Link(target Target), Unlink(target) One way: when the target exits, this process exits too, with the target's reason, normal included; with noproc if there is no such process, noconnection if its node cannot be reached. The target is not affected by this process's exit. These are links between processes, not the links between nodes that NodeInfo.Links lists.
SetTrapExit(trap bool), TrapExit() bool Whether the exit of a process this one is linked to arrives as an Exited message instead of ending it. A request to exit, Exit, is never trapped.
Exit(to Target, reason string) error Asks another process to exit.
Spawn[N](fn, opts...) (Addr[N], error), SpawnMonitor[N](fn, opts...) (Addr[N], Ref, error) A child on the same node, with this process recorded as its parent. Neither exits with the other, unless LinkParent or LinkChild links them. The second is monitored before it runs, so no exit is missed.
Context() context.Context Cancelled when the process is asked to exit, a process it is linked to exits, or the node stops; context.Cause is then the *ExitError, or context.Canceled.
Log() *slog.Logger With pid and label attached.
Addr(), PID(), Node(), Parent() The process's typed address, its PID, its node, and the process that spawned it.
Addresses and messages
PID{Node, Incarnation, ID} A process anywhere: comparable, and travels inside messages.
Name{Node, Name} A process by the name it registered.
Addr[M] A PID or a Name plus the message type. Spawn returns one, Named[M](node, name) makes one, AddrOf[M](target) types a target.
Target What a message can go to: a PID, a Name or any Addr.
Msg[M]{From, Body, Down, Exited, Metadata} What Receive returns: a Body, a Down or an Exited, one only. IsCall() says whether a Reply is awaited; Context(parent) carries the metadata into a ctx.
Down{Ref, PID, Name, Reason} A monitored process exited, or its node is unreachable.
Exited{PID, Name, Reason} A process this one is linked to exited, or its node is unreachable. Only a process that traps exits receives one.
Metadata map[string]string carried with every message, untouched: trace context, tenant. WithMetadata(ctx, md) sets it for Node sends and every Call, MetadataFrom(ctx) reads it back.
Spawn options
WithName(name) Registers the process under name on its node until it exits; ErrNameTaken while another holds it.
WithLabel(label) The low-cardinality key metrics aggregate by. Defaults to the type of M.
WithInspect(fn func() map[string]string) What Node.Inspect and the Inspector show. fn runs on the process's goroutine, between two messages, so it reads the process's state without a lock.
LinkParent(), LinkChild() Link the child to its parent, or the parent to the child, before the child runs. Both together is Erlang's spawn_link. For Process.Spawn and SpawnMonitor: Node.Spawn has no parent.
Errors and exit reasons
ErrNoProc No such process, or a callee that exited before answering.
ErrNoConnection The peer cannot be reached. It comes as a *LinkError wrapping the transport error, which errors.Is matches. Its Unsent says the message never left this node, so sending it again cannot deliver it twice; otherwise it may have been handled.
ErrType The process does not accept this message type, or the reply is not an R.
*RemoteError The error a Call handler returned, carried back as text.
ErrNameTaken, ErrNodeStopped, ErrNotCall A Spawn under a held name; the node has stopped; a Reply to a message nobody waits on.

A process exits with a reason, a string: normal for a nil return, the error's text otherwise, panic: …, what Exit asked for, or the reason of a process it is linked to. The node stops its processes with shutdown; the Inspector's Exit defaults to killed. Only a Down or a link carries noproc, for a process that does not exist, and noconnection, for a node that cannot be reached. 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.

Config
Name, Resolver Required: the node's name, and what turns a peer's name into an address. StaticResolver is a map.
DialOptions For every outbound link: credentials, keepalive, interceptors. Keepalive is what turns a silent partition into a link error, so set it.
Advertise, Registrar, Membership Where peers dial this node, what publishes it, and the cluster's view of who is alive; see Discovery.
Authorize func(ctx, peer NodeID) error Runs for every inbound link, with the peer's transport credentials in ctx.
Hooks, Logger The observability tap, and the logger (slog.Default()).
DialTimeout, DialBackoff How long a dial may take (5s). How long, at most, the node waits before dialing a peer again after dials to it failed (5s); meanwhile sends to it fail at once.
Incarnation, CopyLocal This start of the node (the time, by default); whether local messages are cloned rather than shared (off).

Actors and supervisors

grpcproc/actor is optional structure on top of processes, built on the public API only. An actor is a struct holding its dependencies, which is what a constructor or a DI container builds, with a method per kind of message instead of a receive loop. All but HandleMessage are optional:

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
HandleExited an Exited from a link, when the actor traps exits; one from its parent ends the actor instead as for HandleMessage
Terminate once, when the actor ends, however it ends none: the exit reason is already decided

actor.Run(h) turns an actor into a process function for Spawn. An actor that only answers calls embeds actor.CallsOnly[M] in place of HandleMessage: a plain send to it is logged and dropped.

This inventory records reservations in a Ledger, its dependency, parks one it cannot serve yet, and answers it from HandleMessage when a restock arrives:

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

examples/actors spawns it with node.Spawn(actor.Run(&Inventory{…}), grpcproc.WithName("inventory")), then breaks its protocol with a reservation that is sent rather than called, which ends it. 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 from before they run, and restarts those that exit. Its children are also linked to it, a safeguard beside the orderly stop it makes when it ends. 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. More than MaxRestarts restarts Within the window (3 in 5s by default) and the supervisor exits with max restarts; its own supervisor, a ChildSupervisor, then restarts it, which is how failure moves up the tree.

A worker told to exit has Shutdown (5s) to do so, or its own WithShutdown(d). A child supervisor has as long as it takes (actor.Infinity) to stop its subtree in order. 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 its supervisor starts it again, or ends, only once it has, handling its mailbox meanwhile: nothing is ever started under a name an old process still holds.

ChildFunc("", fn) An anonymous child: registered under no name, known by its PID. A supervisor can have any number.
actor.StartChild(ctx, node, sup, spec) (PID, error) Adds a child to a running supervisor on node and starts it. Once it ends for good, the supervisor forgets it: a pool of workers is anonymous children added as they are needed.
actor.StopChild(ctx, node, sup, child) error Stops a child, which is not restarted until the supervisor itself starts again from its Spec. sup may be on another node.
Spec.AutoShutdown, WithSignificant(true) A supervisor that ends itself, with shutdown, when any or all of its significant children end by themselves: a job's subtree that is done.

A supervisor that waits more than 100ms for a child to exit answers calls, these included, with actor.ErrBusy until it is done; from a process, call it with p.Context().

actor.Child builds the handler afresh at every start, so a restart never sees the state that crashed; ChildFunc runs a plain process function. What must outlive a crash lives outside the actor, here in a Ledger that Init loads:

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

actor.Supervise(node, tree(ledger), grpcproc.WithName("supervisor")) starts it. In examples/supervisor the inventory crashes on a bad message and comes back under the same name, with its state loaded from the ledger; the supervisor reports its restarts through WithInspect. It prints:

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

Observability

A ProcessInfo has the state, mailbox depth and oldest wait, messages sent and received, calls in flight, last message type, watchers, monitors and log level; a LinkInfo its messages, bytes, reconnects and envelopes waiting to be written, and for a peer whose dials fail, when it will be dialed again. node.Inspect adds what the process says about itself: a process busy in a handler answers when it next receives, and 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 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 (the 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. A watch holds a buffer of up to 4096 events, about 1.7 MB, so limit how many streams a client may open, with grpc.MaxConcurrentStreams or an interceptor.

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, partition and crash included, is a plain go test:

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}. The cluster's nodes dial again at once after a failed dial, so the call right after Heal reaches the peer; with the default DialBackoff, sends would fail fast for a while instead. grpcproctest.WithServices registers extra services (an Inspector) on every node, and c.Conn(name) dials one.

Examples

The code above is from examples, a module of its own: whole programs, of which this README shows the parts that matter. CI runs each one, compares what it prints with its output.txt, and checks that the 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, Proto.Actor and Ergo on the same machine (Apple M3 Max), remote over TCP on loopback for all; see benchmarks for the method, why Ergo runs with its keepalive off, and how to read it:

grpcproc GoAkt Hollywood Proto.Actor Ergo
Local send 96 ns 95 ns 59 ns 200 ns 198 ns
Local request 761 ns 568 ns 2362 ns 2451 ns 3200 ns
Remote send 382 ns 520 ns 197 ns 340 ns 551 ns
Remote request 44.8 µs 35.9 µs 37.6 µs 60.7 µs 49.6 µs
Remote request, 14 in parallel 7.5 µs 10.1 µs 5.0 µs 7.0 µs 6.5 µ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, Link 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 a dial: resolving the peer, connecting, and the
	// handshake. A send that waits for a dial waits at most this long, as
	// long as the Resolver and any interceptors in DialOptions honour their
	// ctx. Default 5s.
	DialTimeout time.Duration
	// DialBackoff is the longest a node waits before dialing a peer again
	// once dials to it have failed. Meanwhile everything routed to the peer
	// fails at once with ErrNoConnection rather than wait for a dial that
	// would likely fail too: sends, calls, exits, replies, Downs; a Monitor
	// gets Down{noconnection} at once. The first send after the wait dials
	// again, and the others keep failing while it does. The first wait is a
	// 32nd of DialBackoff, up to a fifth less for jitter. Each further failure
	// doubles it, unless the peer was left alone for longer than DialBackoff,
	// and a dial that succeeds starts over. A link the peer opens lets the
	// next send dial at once, without starting over, since it shows the peer
	// is up but not that this node can reach it. Membership reporting the peer
	// up, or Disconnect, ends the wait. Default 5s; negative dials again at
	// once.
	DialBackoff 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, when no
	// process held the name or its node became unreachable, which process
	// it would have been 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, or a process it is linked to exited.

func (*ExitError) Error

func (e *ExitError) Error() string

type Exited added in v0.0.4

type Exited struct {
	// PID is the process that exited. For a link placed by name, when no
	// process held the name or its node became unreachable, which process
	// it would have been is not known: PID has only its Node, and Name says
	// what was linked to.
	PID    PID
	Name   string // the registered name, when the link was placed by name
	Reason string
}

Exited is what a process that traps exits (see Process.SetTrapExit) receives when a process it is linked to exits, or that process's node becomes unreachable; a process that does not trap exits ends instead. See Process.Link.

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), or queued on a link
	// that broke before or while writing it (ReasonNoConnection). A message
	// that could not be sent at all is not one: its sender gets the error.
	// 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
	// Unsent reports that the message never left this node, so sending it
	// again cannot deliver it twice: the peer could not be reached, or dials
	// to it are backed off. Otherwise it may have been handled: a Call whose
	// link broke while it waited for the reply.
	Unsent bool
}

LinkError reports that a link to a peer closed or could not open; Err says why.

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
	Queued        int    // outbound: envelopes waiting to be written
	LastError     string // why dials to the peer failed; set with RetryAt
	// RetryAt is set on an outbound link that is down because dials to the
	// peer failed: sends to the peer fail at once until then, and the first
	// send after it dials again (Config.DialBackoff). It may be in the past:
	// nothing has been sent since, or that dial is under way. Such a link's
	// Peer has no Incarnation, which only a dial that succeeds learns.
	RetryAt time.Time
}

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
	Exited   *Exited
	Metadata Metadata
	// contains filtered or unexported fields
}

Msg is what Receive returns: a message (Body), a Down or an Exited, one of them only.

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; a peer that cannot be reached is a *LinkError, whose Unsent says that req never left. If ctx ends first, Call returns its error, and req may have been handled; a ctx already done sends nothing.

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, and forgets that dials to it failed (Config.DialBackoff). 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, and the error then wraps ctx.Err(). A process that is gone, or exits before answering (its inspect function panicked), is ErrNoProc.

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, and while dials to the peer are failing it does not wait at all (see Config.DialBackoff). 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. ctx bounds it. A call after one that succeeded does nothing; after one that failed, Start tries again; concurrent calls wait for the one in progress; after Stop began, Start fails with ErrNodeStopped.

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: every outbound link flushes, and is waited on until its peer ends it, or ctx is done. A dial in flight completes within Config.DialTimeout and its link is discarded; Stop waits for it too, until ctx is done. If ctx cuts any of these waits short, Stop returns its error. The Registrar's withdraw comes last, and gets a second of its own if ctx is done by then.

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, a process it is linked to exits, or its node stops. context.Cause is then an *ExitError, or context.Canceled.

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 as Send does. It is not trapped: a process that traps exits ends all the same.

func (p Process) Link(target Target)

Link links p to target, one way: when target exits, p exits too, with target's reason, whatever it is, normal included. If p traps exits (see SetTrapExit), it receives a Msg with Exited set instead. A target that does not exist ends p with noproc, and one whose node cannot be reached, now or later, with noconnection. p's own exit does not affect target, which can link to p for that.

A second link to the same target is the same link. Linking to itself, or from a process that has exited, does nothing.

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) Parent added in v0.0.4

func (p Process) Parent() PID

Parent returns the process that spawned p with Process.Spawn or SpawnMonitor, or the zero PID.

func (*Process[M]) Receive

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

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

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 (*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, from any goroutine (a deferred reply), and on another process than the one that received m. A call is answered once: a second Reply is dropped, and so is one after the receiving process exited (which answers ErrNoProc) or its node's Stop gave up on it (ErrNodeStopped).

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, unless dials to it are failing (Config.DialBackoff). 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) SetTrapExit added in v0.0.4

func (p Process) SetTrapExit(trap bool)

SetTrapExit sets whether p traps exits: whether the exit of a process it is linked to reaches it as a Msg with Exited set, rather than ending it. It takes effect for exits that arrive from then on. A request to exit, Process.Exit or Node.Exit, is never trapped.

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. By itself that is for inspection: p does not monitor the child, and neither exits when the other does, unless LinkParent or LinkChild links them. 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.

func (Process) TrapExit added in v0.0.4

func (p Process) TrapExit() bool

TrapExit reports whether p traps exits.

func (p Process) Unlink(target Target)

Unlink removes p's link to target. An Exited already in the mailbox stays there.

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
	Links         int    // process links held by this one: whose exits end it, or reach it as an Exited
	Watchers      int    // processes monitoring or linked to this one
	Wakeups       uint64 // Receive returns
	LogLevel      slog.Level
	TrapExit      bool // see Process.SetTrapExit
}

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 or an Exited
	Down   *Down
	Exited *Exited
	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. An error must leave self unpublished: Start
	// may call Register again.
	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. Resolve must return once ctx is done: that is what bounds a dial by Config.DialTimeout.

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 LinkChild added in v0.0.4

func LinkChild() SpawnOption

LinkChild links the spawning process to the child, before the child runs: when the child exits, the parent does too, with the child's reason, or receives an Exited if it traps exits. With LinkParent as well, the two are linked both ways, as Erlang's spawn_link does. Node.Spawn refuses it.

func LinkParent added in v0.0.4

func LinkParent() SpawnOption

LinkParent links the child to the process that spawns it, before the child runs: when the parent exits, the child does too, with the parent's reason, or receives an Exited if it traps exits. See Process.Link. It is for Process.Spawn and SpawnMonitor: Node.Spawn, which has no parent, refuses it.

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. A panic in fn is the process's own: it exits with reason "panic: …", and Inspect returns ErrNoProc. 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