grpcproc

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: MIT Imports: 24 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.

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 · Getting started · 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 only. Concepts
  • Actors and supervision trees in grpcproc/actor: a struct with a method per kind of message, restarted by a supervisor when it fails. 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.
  • OpenTelemetry in grpcproc/otel, etcd membership in grpcproc/etcd, and grpcproctest, which runs a cluster inside one go test, partitions and crashes included. Testing
  • A tutorial: a shop whose services are actors, run as one program or as three nodes from the same code. The shop

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

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; 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 (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]) 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 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
	// 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.
	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 (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
}

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

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) 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, 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, 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; 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) 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) 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) 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
	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 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 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.Node().Send(ctx, p.Addr(), 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) 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. 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. 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 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
Package pubsub is publish/subscribe on grpcproc processes.
Package pubsub is publish/subscribe on grpcproc processes.
saga
postgres module
tools module

Jump to

Keyboard shortcuts

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