grpcproc

package module
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: MIT Imports: 30 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 Awesome Go

Erlang-style processes for Go over gRPC.

A process is a goroutine with a typed mailbox and an address any node in the cluster can use. Send, Call, Monitor and Exit work the same whether the process runs in this binary or on another node, and supervisors restart what fails.

go get github.com/floatdrop/grpcproc

Documentation · Quick start · Concepts · API reference

A quick look

Two nodes, each on its own gRPC server. A process on one, a call and a monitor from the other:

// inventory is a process: a goroutine with a mailbox. The mailbox holds
// *shoppb.Reserve and nothing else, and every message is a call, answered
// with a *shoppb.Reserved or 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 {
			_ = m.Reply(nil, fmt.Errorf("only %d %s left", left[m.Body.Sku], m.Body.Sku))
			continue
		}
		left[m.Body.Sku] -= m.Body.Qty
		_ = m.Reply(&shoppb.Reserved{Sku: m.Body.Sku, Left: left[m.Body.Sku]}, nil)
	}
}

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

	// Two nodes, each on its own gRPC server; see node() below.
	warehouse, shop := node(ctx, "warehouse"), node(ctx, "shop")

	// The process runs on warehouse, under a name.
	_, err := warehouse.Spawn(inventory, grpcproc.WithName("stock"))
	check(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 := stock.Call[*shoppb.Reserved](ctx, shop, &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. A process on
	// shop monitors stock, then asks it to exit; the Down arrives with the
	// reason, as it would for a crash or a lost node.
	exited := make(chan string)
	_, err = shop.Spawn(func(p *grpcproc.Process[proto.Message]) error {
		p.Monitor(stock)
		check(p.Exit(stock, "closing"))
		m, err := p.Receive() // the Down: nothing else is sent to this process
		if err != nil {
			return err
		}
		exited <- m.Down.Reason
		return nil
	})
	check(err)
	fmt.Println("stock exited:", <-exited)

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

	check(shop.Stop(ctx))
	check(warehouse.Stop(ctx))
}
reserved, left: 1
reserve failed: only 1 apple left
stock exited: closing
no such process: true

examples/quickstart is the whole program, node() included: a grpcproc.Node is a value you construct, register on your *grpc.Server next to your other services, start and stop.

What is in the box

  • Processes with typed mailboxes, Send and Call, monitors and links, exit reasons: the core, which depends on gRPC and protobuf, and on fsm, which has no dependencies of its own. Concepts
  • Actors and supervision trees in grpcproc/actor: a struct with a method per kind of message, restarted by a supervisor when it fails, and started from any node, monitored from before it runs. Supervision
  • Pub/sub in grpcproc/pubsub: topics a process publishes to and any node subscribes to, with the last few events kept for whoever comes late, and each event sent once to each node. Guide
  • An Inspector and grpcprocctl: every process, its mailbox and what it says about itself, from a terminal or an AI agent over MCP. Guide
  • Cron and leader election in grpcproc/cron and grpcproc/leader: jobs on crontab schedules, every run a process of its own; and a singleton that runs on the elected leader and carries its state to the next, so a job can run once in a cluster.
  • Sagas in grpcproc/saga: work that spans services and outlasts a process, as an fsm machine and its data per run, kept in a store, with retries, durable timers and signals; Sequence for steps with what undoes each. Guide
  • OpenTelemetry in grpcproc/otel, etcd membership in grpcproc/etcd, sagas kept in PostgreSQL in grpcproc/saga/postgres, and grpcproctest, which runs a cluster inside one go test, partitions and crashes included. Testing
  • A tutorial: an AI agent runtime, with a process per conversation, the model on GPU nodes, tools on a sandbox node and tokens streamed to the browser, run as one program or as a program per node from the same code. An agent runtime

docs/DESIGN.md has the wire protocol and the reasons behind the choices; benchmarks measures it against GoAkt, Hollywood, Proto.Actor and Ergo.

License

MIT, see LICENSE.

Documentation

Overview

Package grpcproc gives goroutines Erlang-style network transparency over gRPC. 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"
	ReasonGoexit       = "goexit" // the process's function called runtime.Goexit
	ReasonType         = "type"
	ReasonDenied       = "denied"        // a dead letter a peer's Policy refused
	ReasonMailboxFull  = "mailbox full"  // a dead letter a full mailbox refused (see WithMailboxLimit)
	ReasonNameLost     = "name lost"     // a global name's claim was lost (see Process.Claim)
	ReasonNameConflict = "name conflict" // a KeepOnLoss claim found its name taken (see KeepOnLoss)
)

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

Variables

View Source
var (
	// ErrTaken is the error of a claim of a name another process holds; the
	// error itself is a *TakenError, which says which. Across the wire only
	// its text travels, which errors.Is still matches.
	ErrTaken = errors.New("grpcproc: name taken")
	// ErrNoNames is the error of a claim on a node without Config.Names.
	ErrNoNames = errors.New("grpcproc: no Config.Names")
)

Errors of global names.

View Source
var (
	ErrNoProc       = errors.New("grpcproc: no such process")
	ErrNoConnection = errors.New("grpcproc: no connection to node")
	ErrLinkBusy     = errors.New("grpcproc: link queue full")   // see Config.MaxQueued
	ErrMailboxFull  = errors.New("grpcproc: mailbox full")      // see WithMailboxLimit
	ErrTooLarge     = errors.New("grpcproc: message too large") // see Config.MaxMessageSize
	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")
	ErrNoQuery      = errors.New("grpcproc: process answers no queries") // see WithQuery
)

Functions

func AdmitTLS added in v0.8.0

func AdmitTLS(pol Policy) func(ctx context.Context, peer NodeID) (Policy, error)

AdmitTLS is a Config.Admit that admits a peer whose verified TLS client certificate names the node it claims to be, and judges it by pol, nil for no Policy. The name is a DNS subject alternative name equal to the node's, or an IP one of the address the node's name is; a wildcard names no node, since a node name is a name, not a host to match. The server's credentials must verify client certificates (tls.RequireAndVerifyClientCert), or no peer is admitted.

It proves who dialed this node. That the node this one dials is the one it meant is for the dial's own credentials: DialOptionsFor can give each peer's TLS a ServerName of the peer's node name.

func WithMetadata

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

WithMetadata returns a context carrying md, merged over any metadata already in ctx. Every send and call made with ctx propagates it with the message, merged, from a process, over what the process inherited.

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. An Addr of a Global stays one: each send resolves the name afresh.

func Named

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

Named addresses the process registered as name on node.

func (Addr[M]) Call added in v0.1.0

func (a Addr[M]) Call[R proto.Message](ctx context.Context, from Caller, req M) (R, error)

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

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

from is who calls: the Node, or a Process from inside its handler, whose call carries the metadata of the message it is handling with ctx's merged over it. Replies do not pass through the mailbox, so calling from inside a process never reorders its messages. The callee sees ctx's deadline as the call's (Msg.Deadline).

A reply of another type is ErrType; a handler error is a *RemoteError; a callee that is gone, or exits before answering, is ErrNoProc; one whose mailbox is full (see WithMailboxLimit) is ErrMailboxFull, and never saw req; 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.

It lets a contract package write its protocol once, as a method per operation on its own address type, which names R so callers do not:

type StockAddr struct{ grpcproc.Addr[*Command] }

func (s StockAddr) Reserve(ctx context.Context, from grpcproc.Caller, r *Reserve) (*Reserved, error) {
	return s.Call[*Reserved](ctx, from, &Command{Op: &Command_Reserve{Reserve: r}})
}

and then, from a node or from inside a process alike:

reserved, err := stock.Reserve(ctx, p, &Reserve{Sku: "apple", Qty: 2})
func (a Addr[M]) CallLink[R proto.Message](ctx context.Context, from Caller, req M) (R, error)

CallLink is CallMonitor with a link for the monitor: once it returns without an error, from is linked to the process the callee answers with, as LinkChild links a parent, and that process's exit ends from, with its reason, or reaches it as an Exited if from traps exits (see Process.SetTrapExit). A link to it already is the same link.

func (Addr[M]) CallMonitor added in v0.3.0

func (a Addr[M]) CallMonitor[R proto.Message](ctx context.Context, from Caller, req M) (R, Ref, error)

CallMonitor is Call, from a process that monitors the process the callee answers with: one the callee spawns to answer, which it monitors from before that process runs (see WatchedBy), or one that runs (Msg.Watch). It is the remote spawn_monitor: however soon that process exits, from receives its Down, with the returned Ref and the real reason, never noproc, after the answer and in order with what that process sent it. A callee that places no monitor answers with none, and the Down comes at once, with noproc.

Only an answer that is not an error brings the monitor. A call that fails, the callee's error, a ctx that ends, a link that breaks, leaves from monitoring nothing, and no Down comes of it, whatever the callee spawned: so that error, a RemoteError say, tells a spawn that failed from a process that started and exited, which is a Down. If the link to the callee's node breaks once the answer has come, the Down comes, with noconnection.

from must be a process, which can receive a Down; from the Node, the call is not made, and the error says why. A process that has exited calls nothing: the error is ErrNoProc.

func (Addr[M]) Name

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

Name returns the registered name, or "" for a PID address. For an address of a Global, it is the global name.

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]) Send added in v0.1.0

func (a Addr[M]) Send(ctx context.Context, from Caller, m M) error

Send delivers m to the address, local or remote, from the Node or a Process, and returns once m is queued. From a process, m carries the metadata of the message it is handling with ctx's merged over it; from the node, ctx's. ctx bounds only the wait for a connection to a peer the 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 (Addr[M]) String

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

type Caller added in v0.1.0

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

Caller is who sends or calls through Addr.Call and Addr.Send: a *Node, or a *Process from inside its handler. Only this package implements it.

type Claim added in v0.4.0

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

Claim is a global name a process holds: from Process.Claim until the process exits, Release is called, or the claim is lost.

func (*Claim) Held added in v0.4.0

func (c *Claim) Held() bool

Held reports whether the claim holds its name: false while a claim made with KeepOnLoss is lost, and once it is over.

func (*Claim) Name added in v0.4.0

func (c *Claim) Name() string

Name returns the global name.

func (*Claim) Release added in v0.4.0

func (c *Claim) Release(ctx context.Context) error

Release gives the name up, while the process goes on.

func (*Claim) Revision added in v0.4.0

func (c *Claim) Revision() int64

Revision returns the claim's fencing token: a new one each time a claim made with KeepOnLoss holds the name again.

type ClaimEvent added in v0.4.0

type ClaimEvent struct {
	Kind     ClaimEventKind
	Revision int64 // the new one, for ClaimRegained
}

ClaimEvent is what a Names store tells of a claim it made.

type ClaimEventKind added in v0.4.0

type ClaimEventKind uint8

ClaimEventKind is what became of a claim.

const (
	// ClaimLost: the store can no longer vouch for the claim (an etcd lease
	// that ended, or will have by the time another node could claim the
	// name). Without KeepOnLoss, the claim is over.
	ClaimLost ClaimEventKind = iota + 1
	// ClaimRegained: a claim made with KeepOnLoss holds the name again, with
	// a new Revision.
	ClaimRegained
	// ClaimConflict: a claim made with KeepOnLoss found the name held by
	// another process when it could claim again. The claim is over.
	ClaimConflict
)

type ClaimOption added in v0.4.0

type ClaimOption func(*ClaimOptions)

ClaimOption configures Process.Claim.

func KeepOnLoss added in v0.4.0

func KeepOnLoss() ClaimOption

KeepOnLoss keeps the holder running when its claim is lost, rather than end it with reason ReasonNameLost, and claims the name again once the store can. Meanwhile Held is false, and another process may claim the name and run beside it; if one did, the holder the store has wins, and this one ends with reason ReasonNameConflict. It is for a process whose duplicate is a nuisance and whose absence is an outage: a teleconference room, whose calls go on while etcd is out of reach.

func WaitForName added in v0.4.0

func WaitForName() ClaimOption

WaitForName makes Claim wait, until its ctx is done, for a name that is held to be free, and claim it then: a standby, with the same process on other nodes, that takes over when the holder exits or its node goes.

type ClaimOptions added in v0.4.0

type ClaimOptions struct {
	Wait       bool // wait for a name that is held to be free (WaitForName)
	KeepOnLoss bool // claim again once the store can, rather than give up (KeepOnLoss)
}

ClaimOptions are what Process.Claim passes to Names.Claim.

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,
	// and must grow with each start: a peer that has seen an incarnation of
	// the node refuses links from older ones, so that an instance that was
	// replaced, and still runs, cannot take the links of its replacement.
	// The peer refuses them until Membership reports the newer one gone, or
	// it calls Disconnect: a random or hashed Incarnation would be refused
	// whenever it came out lower than the last one. Zero picks the current
	// Unix time in nanoseconds, which grows as long as the clocks of the
	// hosts the node starts on agree to within the time between two starts,
	// or one more than the last incarnation picked in this program, if the
	// clock has not moved since: a coarse clock, or a testing/synctest
	// bubble, whose clock stands still until every goroutine in it waits.
	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
	// Names, if set, is the store of the installation's global names, which
	// Global targets resolve through and Process.Claim claims in. Start
	// watches it before the Registrar; grpcproc/etcd keeps it in etcd.
	Names Names
	// Metadata describes this start of the node to the cluster: the
	// application's version, its zone, whatever placement or a rolling
	// deploy decides by. grpcproc reads none of it. It is published with the
	// node's Member through the Registrar, so peers find it in their
	// Membership (Node.Members), and NodeInfo and the Inspector show it. It
	// is fixed for the node's life, so a change is a new start.
	Metadata map[string]string
	// Membership, if set, is watched from Start: a peer that leaves the
	// cluster, or comes back as a newer incarnation, has its links dropped,
	// which fires Down{noconnection} for monitors across them and fails
	// pending calls. An older incarnation reported up is ignored.
	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 here and on the server, whose pings end a
	// silent peer's link to this node, which is what declares it down.
	DialOptions []grpc.DialOption
	// DialOptionsFor, if set, gives more options for the connections to one
	// peer, its link's and Dial's. They come after DialOptions, so they
	// override them: the credentials of another installation, whose nodes
	// present certificates of another CA, say.
	DialOptionsFor func(peer string) []grpc.DialOption
	// Admit runs for every inbound link before it is accepted, with the
	// peer's transport credentials in ctx (grpc/peer) and the identity it
	// claims. An error refuses the link: the peer's dial fails with
	// PermissionDenied. Otherwise the Policy it returns judges everything the
	// peer asks over the link, for as long as the link lasts: messages,
	// calls, monitors and links, exits; a nil Policy lets everything through.
	//
	// It is required, since a peer that is let in may exit any process, and
	// claim any node name: AdmitTLS admits a peer whose verified certificate
	// names its node, and AdmitAll every peer, for a network where whoever
	// reaches the server is trusted.
	Admit func(ctx context.Context, peer NodeID) (Policy, 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 that ends within
	// DialTimeout of coming up counts as a dial that failed, after the wait
	// its dial came after: a path that keeps breaking backs off as one that
	// cannot be dialed does. 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 (not as an older incarnation than this node has seen), or
	// Disconnect, ends the wait. Default 5s; negative dials again at once.
	DialBackoff time.Duration
	// MaxQueued bounds the link to each peer: while it holds this many
	// envelopes not yet written (LinkInfo.Queued), a message or a call to
	// the peer fails at once with a *LinkError whose Err is ErrLinkBusy and
	// whose Unsent is set, so sending it again later cannot deliver it
	// twice. Each peer has a link of its own, so a peer that cannot keep up
	// refuses only what is sent to it. Replies, Downs, monitors and exits
	// are queued regardless, and count: the peer waits for a reply or a
	// Down, and a refused one would have to cut its link to this node. Zero,
	// the default, is no bound: a send never fails for a slow peer, and the
	// link holds whatever the peer has not yet taken.
	MaxQueued int
	// MaxMessageSize is the largest message this node sends a peer, encoded,
	// metadata included. Every peer's server must take it, through its
	// grpc.MaxRecvMsgSize, or it ends the link the message came on, and with
	// it every call and monitor there. A message or a call that encodes
	// larger fails at once with ErrTooLarge, and is never sent; a reply that
	// large reaches its caller as ErrTooLarge instead. Local sends are not
	// limited. Default 4 MiB, gRPC's own limit; at least 64 KiB. To raise it,
	// raise grpc.MaxRecvMsgSize on every node's server first.
	MaxMessageSize int
	// MaxQueuedBytes bounds the link to each peer as MaxQueued does, by the
	// bytes of the message bodies it holds (LinkInfo.QueuedBytes, counted as
	// Bytes is): a message or a call fails while they come to this much, so
	// the last one taken can carry the link past it. Zero, the default, is no
	// bound.
	MaxQueuedBytes int
}

Config configures a Node. Name, Resolver and Admit 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 or global name, when the monitor was placed by one
	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: a session with it began (see Hooks.OnLinkUp)
EventLinkDown    Peer, Err: the session ended, the peer declared down
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 or global name, when the link was placed by one
	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 Global added in v0.4.0

type Global struct{ Name string }

Global addresses whichever process holds Name among the installation's global names (Config.Names), wherever it runs. The sender's node looks the name up, and the message goes to the PID it finds, as if addressed by it: nothing on the wire changes. A name no one holds, or a node without Names, is a process that does not exist: a call fails with ErrNoProc, a monitor or a link gets Down{noproc} with Name set to the global name, and a message is a dead letter.

The node's copy of the names lags the store by a moment, so a message sent just after a holder moved may reach the old one: noproc once it has exited, noconnection if its node is gone. Names.Resolve asks the store itself, where that matters.

func (Global) String added in v0.4.0

func (g Global) String() string

type GlobalName added in v0.4.0

type GlobalName struct {
	Name string
	PID  PID
}

GlobalName is a global name and the process that holds it.

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), refused by a peer's
	// Policy (ReasonDenied) or a full mailbox (ReasonMailboxFull), 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 runs when a session with peer begins: its first link, either
	// way, comes up. OnLinkDown runs when the session ends: the peer is
	// declared down, and err says why. Each session's OnLinkUp comes before
	// its OnLinkDown, and a link that breaks and comes back while the other
	// way stays up is neither.
	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, dials to
	// it are backed off, or its link was full (ErrLinkBusy). 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, a full link's included.

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
	QueuedBytes   int    // outbound: their bodies' bytes, as Bytes counts them
	LastError     string // why dials to the peer failed, or its link ended young; set with RetryAt
	// Sessions counts the sessions with the peer that have ended: each time
	// this node declared it down, or learned that the peer had declared this
	// node down. One that keeps growing is a peer whose links keep breaking.
	// It counts from 0 for each incarnation of the peer.
	Sessions uint64
	// RetryAt is set on an outbound link that is down because dials to the
	// peer failed, or its last link ended within DialTimeout of coming up:
	// 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
	Limit     int // WithMailboxLimit; 0 is none
}

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
	Metadata    map[string]string // its Config.Metadata; not to be modified
}

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; a joining one, an incarnation not known.

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.CancelFunc)

Context returns a context for code run on behalf of the message: it carries the message's metadata, for a send, a call, or any code taking a ctx, and for a call with a Deadline it ends then, when nobody waits for the reply any more. Call cancel once that code is done, as with context.WithDeadline.

func (Msg[M]) Deadline added in v0.1.0

func (m Msg[M]) Deadline() (deadline time.Time, ok bool)

Deadline reports when the caller of a call stops waiting for its Reply: the deadline of the context it called with. ok is false for a plain message and for a call whose context had no deadline. A remote call carries the time its caller had left, so its deadline counts from when it reached this node, a little after the caller's own; clocks need not agree.

func (Msg[M]) IsCall

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

IsCall reports whether the sender waits for a Reply.

func (Msg[M]) Reply added in v0.1.0

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

Reply answers the message, if IsCall is true. The message holds all it takes, so a reply can wait: m can be kept, or handed to another goroutine or process, and answered from there. A call is answered once: a second Reply is dropped, and so is one after the process that received m exited (which answers ErrNoProc) or its node's Stop gave up on it (ErrNodeStopped). An error answer takes back the watch the caller asked for, if it was placed (see WatchedBy).

The error says what became of the answer, which is given either way: a reply to a peer's caller that does not encode, or is larger than Config.MaxMessageSize (ErrTooLarge), reaches the caller as that error instead, and a reply that cannot be routed cuts the link the call came by, failing the caller with ErrNoConnection.

func (Msg[M]) Watch added in v0.3.0

func (m Msg[M]) Watch(pid PID) error

Watch places the watch m's caller asked for, a monitor or a link (see Addr.CallMonitor and Addr.CallLink), on pid, a process of this node that runs: for a call answered with a process that was running already, as WatchedBy places it on one spawned for the call. From then on, the caller hears of pid's exit, if the answer to m is not an error. For a caller that asked for none, Watch does nothing.

It is ErrNotCall for a message that is not a call, and ErrNoProc when pid has exited, or is not of the node that holds m. A call answered already, or whose watch is placed already, is an error too.

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 NameClaim added in v0.4.0

type NameClaim interface {
	// Revision is the claim's fencing token: it grows with each claim of a
	// name, so a write fenced by it refuses a holder that lost the name.
	Revision() int64
	// Release gives the name up, if this claim still holds it, and stops a
	// claim made with KeepOnLoss from being made again.
	Release(ctx context.Context) error
}

NameClaim is a claim a Names store made.

type NameLister added in v0.4.0

type NameLister interface {
	// List returns the names with prefix, ordered by name, at most limit of
	// them unless limit is 0.
	List(prefix string, limit int) []GlobalName
}

NameLister is a Names that can list its names: one that keeps them all, as the etcd and in-memory stores do. The Inspector lists global names only through it.

type Names added in v0.4.0

type Names interface {
	// Watch begins keeping this node's copy of the names, until ctx is done.
	// Start calls it before the Registrar, and it returns once the copy holds
	// every name, so a node that has started finds every name claimed before.
	Watch(ctx context.Context) error
	// Lookup returns the process that holds name, as this node's copy has
	// it. It must not block: a process's SendTo, which resolves through it,
	// takes no ctx.
	Lookup(name string) (PID, bool)
	// Resolve asks the store itself, for when Lookup's lag matters: before
	// starting what another node may have started a moment ago, or after
	// losing a race to start it.
	Resolve(ctx context.Context, name string) (PID, bool, error)
	// Claim makes holder the holder of name, unless another process holds it:
	// then it fails with a *TakenError, or, with opts.Wait, waits until ctx
	// is done for the name to be free. notify, which must not block, is told
	// what becomes of the claim (see ClaimEvent). Process.Claim calls it, and
	// releases the claim when its process exits.
	Claim(ctx context.Context, name string, holder PID, opts ClaimOptions, notify func(ClaimEvent)) (NameClaim, error)
}

Names is a store of global names: the names of the installation, each held by one process at a time. The core resolves Global targets through it and ties each claim to its process; the store keeps the names, and says when it can no longer vouch for a claim. grpcproc/etcd keeps them in etcd; grpcproctest keeps them in memory.

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) CallTo

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

CallTo calls an untyped target from the node, as Addr.Call does a typed one, and types the reply as R.

func (*Node) Dial added in v0.1.0

func (n *Node) Dial(ctx context.Context, peer string) (*grpc.ClientConn, error)

Dial opens a connection to peer's gRPC server as the node reaches it, through Config.Resolver and with Config.DialOptions and DialOptionsFor, credentials and all: for a service registered there beside grpcproc's own, the peer's Inspector say. ctx bounds resolving peer's address. The connection is the caller's to close; the node's links do not use it.

func (*Node) Disconnect

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

Disconnect drops every link with peer, and a dial to it under way, as if the network had, and forgets that dials to it failed (Config.DialBackoff) and which incarnation of it this node has seen, so that none is refused (see Config.Incarnation). Monitors across it fire Down{noconnection} and pending calls fail, as do sends waiting for the dial; 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 SendTo, 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) Member added in v0.4.0

func (n *Node) Member(name string) (Member, bool)

Member returns the member named name, as Members has it.

func (*Node) Members added in v0.4.0

func (n *Node) Members() []Member

Members lists the nodes Config.Membership reports up, this one among them once it reports it, ordered by name, each as the newest incarnation reported and with the Metadata it registered: what placement chooses among, by version or zone say. It is this node's view, as current as the Membership's events, and empty without a Membership. The Metadata maps are shared: do not modify them.

func (*Node) Membership added in v0.1.0

func (n *Node) Membership() Membership

Membership returns Config.Membership, or nil: for a component that follows the cluster as the node does, grpcproc/leader say.

func (*Node) Name

func (n *Node) Name() string

Name is the node's logical name.

func (*Node) Names added in v0.4.0

func (n *Node) Names() Names

Names returns Config.Names, or nil: for a component that resolves names itself, through Resolve.

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) Query added in v0.10.0

func (n *Node) Query(ctx context.Context, pid PID, q proto.Message) (answer proto.Message, err error)

Query asks a local process q, through the function it was spawned with WithQuery, and returns its answer, google.protobuf.Empty for none: ErrNoProc itself if it does not run here, ErrNoQuery itself if it answers no queries, or the function's error as it returned it.

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) SendTo

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

SendTo delivers m from the node to an untyped target: a PID, a Name, or an Addr of another type, as Addr.Send does to a typed one. 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
	Metadata    map[string]string // Config.Metadata
	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 Op added in v0.4.0

type Op uint8

Op is what a peer asks of a process on this node, as a Policy sees it.

const (
	OpSend    Op = iota + 1 // a message
	OpCall                  // a call
	OpMonitor               // a monitor, or a link, which travels as one
	OpExit                  // a request to exit
)

The requests a Policy judges. Replies, Downs and demonitors are not among them: they answer, or take back, what was asked, and always pass.

func (Op) String added in v0.4.0

func (o Op) String() string

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 PIDFromProto added in v0.1.0

func PIDFromProto(p *grpcprocv1.PID) PID

PIDFromProto returns the PID a grpcproc.v1.PID holds: the zero PID for nil.

func (PID) IsZero

func (p PID) IsZero() bool

IsZero reports whether p is the zero PID.

func (PID) Proto added in v0.1.0

func (p PID) Proto() *grpcprocv1.PID

Proto returns p as a grpcproc.v1.PID, for a PID that travels inside an application's own messages; nil for the zero PID.

func (PID) String

func (p PID) String() string

type Policy added in v0.4.0

type Policy func(op Op, name string) bool

Policy says what a peer may ask of this node's processes: op of the process registered under name, or, for one the peer addresses by PID, under the name it was spawned with, "" if none. Config.Admit returns one per inbound link, which judges everything the peer sends over it for as long as it lasts. A request it refuses is answered as if the process did not exist: a call fails with ErrNoProc, a monitor or a link gets Down{noproc}, and a message or an exit is dropped. This node counts each as a dead letter with reason ReasonDenied.

It runs on the goroutine that reads the link, for every request on it, so it should not block.

func AdmitAll added in v0.8.0

func AdmitAll(context.Context, NodeID) (Policy, error)

AdmitAll is a Config.Admit that admits every peer, with no Policy: for a network where whoever can reach the node's gRPC server is trusted, since such a peer may claim any node name and exit any process.

func Export added in v0.4.0

func Export(names ...string) Policy

Export is the Policy of a peer that may send to, call and monitor the processes registered under names, by name or by PID, and nothing else: no process without a name, and no exits. It suits a node of another installation, which reaches the services this one offers it and is not trusted to stop them.

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.

Receive and ReceiveTimeout belong to the process's own goroutine. Other goroutines may send and call as the process, ask another process to exit, and use its PID, Addr, Node, Context and Log; a message's Reply works from anywhere. A send from another goroutine inherits the metadata of whatever message the process is handling at that moment, and a Call made there shows the process as waiting on a reply, so a goroutine that feeds a process, one blocked on a read say, sends to it as the node instead:

_ = p.Addr().Send(ctx, p.Node(), m)

func (*Process[M]) Addr

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

Addr returns the process's typed address.

func (*Process[M]) CallTo

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

CallTo calls an untyped target, such as a Msg's From, from the process, as Addr.Call does a typed one, and types the reply as R.

func (Process) Claim added in v0.4.0

func (p Process) Claim(ctx context.Context, name string, opts ...ClaimOption) (*Claim, error)

Claim makes p the holder of a global name, until p exits or the claim is released: the name is p's to all the installation's nodes, whose Global targets reach p. A name another process holds fails with a *TakenError, which says which (errors.Is matches ErrTaken), unless WaitForName waits for it. A node without Config.Names fails with ErrNoNames.

A claim the store loses, an etcd lease that ended, ends p with reason ReasonNameLost, before another process can claim the name, unless it was made with KeepOnLoss. Its Revision is the fencing token for what clocks cannot promise.

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 SendTo does, and, as SendTo, it takes no ctx. 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]) 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 from the process to an untyped target, such as a Msg's From, as Addr.Send does to a typed one, carrying 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). The target's type is checked on delivery only.

It takes no ctx, as Exit takes none: a process carries its own, the metadata it inherits and the node's DialTimeout. Its own Context would be no better, since it ends as the process is asked to exit, when a process may still have a send to make. For a ctx of its own, a process sends through the address: AddrOf[proto.Message](to).Send(ctx, p, msg).

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. A global name is not looked up again: the links placed by it go, whichever process it led to, since the name may have moved on since. 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
	Globals       []string // the global names it holds (Process.Claim), ordered
	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. Only its text crosses the wire, so errors.Is matches it by its text: a handler that answers with a sentinel error, one of grpcproc's or its own, gives the caller an error that is that sentinel to errors.Is.

func (*RemoteError) Error

func (e *RemoteError) Error() string

func (*RemoteError) Is added in v0.1.0

func (e *RemoteError) Is(target error) bool

Is reports whether target has the error's text; see RemoteError.

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 WatchedBy added in v0.3.0

func WatchedBy[M proto.Message](m Msg[M]) SpawnOption

WatchedBy places the watch m's caller asked for, a monitor or a link (see Addr.CallMonitor and Addr.CallLink), on the child, before it runs, as SpawnMonitor places its monitor: however soon the child exits, the caller hears of it with the real reason, never noproc. The answer to m names the child to the caller, and brings the watch only if it is not an error: a call that fails leaves no watch behind. For a caller that asked for none, WatchedBy does nothing.

m must be a call a process of the spawning node holds and has not answered yet, whose watch is not placed yet (see Msg.Watch); otherwise the spawn fails, with ErrNotCall for a message that is not a call.

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 WithMailboxLimit added in v0.7.0

func WithMailboxLimit(n int) SpawnOption

WithMailboxLimit bounds the process's mailbox: while it holds n items, a message sent to the process is a dead letter with reason ReasonMailboxFull, and a call to it fails with ErrMailboxFull, never handled, so making it again cannot run it twice. Both hold whether the sender runs on this node or another: Send's error still means only that the message could not leave, so a sender that must know calls. Downs and Exiteds always get in, and count. Zero, the default, is no bound; a negative n makes the spawn fail.

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. A name must be valid UTF-8 and at most 16 KiB, so that peers can address it.

func WithQuery added in v0.10.0

func WithQuery(fn func(ctx context.Context, q proto.Message) (proto.Message, error)) SpawnOption

WithQuery lets the process be asked questions that WithInspect cannot answer, because they take an argument or read what the process does not hold, such as a store: fn answers q, a question its author defined. See Node.Query, which a read-only Inspector serves. fn runs on the asker's goroutine, not the process's, for as long as the process runs, and must change nothing; its ctx is the asker's. A panic in it is the asker's error, not the process's.

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 TakenError added in v0.4.0

type TakenError struct {
	Name   string
	Holder PID
}

TakenError is the error of a claim of a name another process holds.

func (*TakenError) Error added in v0.4.0

func (*TakenError) Error() string

Error is ErrTaken's text, so that the error matches ErrTaken on another node too, where it arrives as its text alone.

func (*TakenError) Is added in v0.4.0

func (*TakenError) Is(target error) bool

Is reports whether target is ErrTaken.

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.
Package cron runs jobs on schedules written in crontab syntax, from a grpcproc process the application starts:
Package cron runs jobs on schedules written in crontab syntax, from a grpcproc process the application starts:
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
Package leader elects one node of a cluster to run a singleton: a child spec that runs on the leader only, started when its node wins an election and told to exit when it loses.
Package leader elects one node of a cluster to run a singleton: a child spec that runs on the leader only, started when its node wins an election and told to exit when it loses.
otel module
proto
Package pubsub is publish/subscribe on grpcproc processes.
Package pubsub is publish/subscribe on grpcproc processes.
Package saga runs sagas that outlast a process: work that spans services, kept in a Store, so that a crash, a restart or a lost node is followed by the run going on from where it was.
Package saga runs sagas that outlast a process: work that spans services, kept in a Store, so that a crash, a restart or a lost node is followed by the run going on from where it was.
sagatest
Package sagatest checks a saga.Store: what every implementation must do for an engine to be right on it.
Package sagatest checks a saga.Store: what every implementation must do for an engine to be right on it.
postgres module
tools module

Jump to

Keyboard shortcuts

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