Documentation
Configuration
Every field of grpcproc.Config and its default, and the order a node is built, started and stopped in.
A node is configured once, in NewNode, which fails on a bad configuration. Three fields are required: Name, Resolver and Admit. Running in production says what a deployment should set, and the API reference has each field's full comment.
Fields
| Field | Default, and what it is |
|---|---|
Name | Required. The node's name, which peers address it by. |
Resolver | Required. Turns a peer's name into an address to dial. |
Advertise | None. Where peers dial this node; published by the Registrar. |
Incarnation | The start time in nanoseconds. Must grow with each start. |
Registrar | None. Publishes the node on Start, withdraws it on Stop. |
Names | None. The store of the installation's global names, which Global targets resolve through and Process.Claim claims in. |
Metadata | None. What this start of the node tells the cluster about itself: version, zone. Published with its Member. |
Membership | None. The cluster's view of who is alive, watched from Start. |
DialOptions | None. Credentials, keepalive and interceptors for every outbound connection. |
DialOptionsFor | None. More options for the connections to one peer, after DialOptions, so they win. |
DialTimeout | 5s. Bounds a dial: resolve, connect, handshake. |
DialBackoff | 5s. The longest wait before dialing a peer again after failed dials; negative dials again at once. |
MaxQueued | None. How many envelopes the link to a peer may hold before sends and calls to it fail at once. |
MaxQueuedBytes | None. The same bound, in bytes of message bodies. |
MaxMessageSize | 4 MiB, gRPC's receive limit. The largest message, encoded, the node sends a peer, whose server must take it; larger ones fail at once with ErrTooLarge. |
Admit | Required. Runs for every inbound link: refuses it, or admits it with a Policy of what the peer may ask. AdmitTLS checks the peer's certificate; AdmitAll trusts every peer. |
Logger | slog.Default(). |
Hooks | None. The observability tap. |
CopyLocal | Off. Clone every locally delivered message. |
Identity
Name is how peers address the node: a Named address is a node name and a process name, and a PID carries the node name too. It is unique per cluster. Two instances given one name are two incarnations of one node, and the newer takes the older's place.
Advertise is the address peers dial to reach this node's gRPC server. The core only reports it, in NodeInfo and in the Hello that opens a link; a Registrar publishes it, and then it must be the address other hosts see, not a wildcard or loopback.
Incarnation distinguishes this start of the node from earlier ones, and must grow with each start: a peer that has seen an incarnation refuses links from older ones, so that an instance that was replaced, and still runs, cannot take the links of its replacement. 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. A random or hashed value would be refused whenever it came out lower than the last; a counter from a deployment system, or an etcd revision, works (Nodes and links).
Peers
Resolver maps a peer's name to an address; StaticResolver is a map, and ResolverFunc adapts a function. It is called before a dial, with a ctx bounded by DialTimeout, and must return once that ctx is done.
Registrar and Membership are optional and usually come together, from grpcproc/etcd. With Membership set, 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, even when its connection never closed (Discovery and membership).
Connections
DialOptions are used for every outbound connection: the transport credentials, keepalive, and any interceptors. Keepalive is what turns a peer that went silent into a broken link, and it takes both halves: the dial's pings end this node's link to the peer, and the server's end the peer's link to this node, whose end is what declares the peer down, firing Downs and failing calls. grpcproc sets neither. The tutorial's platform sets both:
// dialOptions are for every connection to another node: the node's links
// and the Inspector's forwarding. Keepalive is what turns a peer that went
// silent into a broken link; with the server's (newServer), into Downs and
// failed calls. Plaintext keeps the guide short; a real deployment puts mTLS
// here.
func dialOptions() []grpc.DialOption {
return []grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithKeepaliveParams(keepalive.ClientParameters{Time: 10 * time.Second, Timeout: 5 * time.Second}),
}
}func newServer(ln net.Listener) *server {
// Pings its clients, so that a peer gone silent ends its links to this
// node, which is what declares it down; and accepts the pings
// dialOptions sends.
params := keepalive.ServerParameters{Time: 10 * time.Second, Timeout: 5 * time.Second}
policy := keepalive.EnforcementPolicy{MinTime: 5 * time.Second, PermitWithoutStream: true}
return &server{grpc: grpc.NewServer(grpc.KeepaliveParams(params), grpc.KeepaliveEnforcementPolicy(policy)), ln: ln}
}The client pings every ten seconds and gives up five seconds after an unanswered ping, so a partition is a link error within fifteen seconds. The server's enforcement policy has to allow pings that often, and without an active stream, or it closes the connection for pinging too much (Failure detection).
DialTimeout bounds one dial, five seconds by default, as long as the resolver and the interceptors honour their ctx. DialBackoff is the longest the node waits before dialing a peer again after dials to it failed; meanwhile everything routed to the peer fails at once with ErrNoConnection, and a Monitor of a process there gets Down{noconnection} at once. The first wait is a 32nd of it, and each failure doubles it. A link that ends within DialTimeout of coming up counts as a failed dial, so a path that keeps breaking backs off too. Set it negative to dial again at once, as grpcproctest does.
MaxQueued and MaxQueuedBytes bound the link to each peer, which is unbounded by default. While a link holds that many envelopes not yet written, or that many bytes of message bodies, a send or a call to its peer fails at once with a *LinkError whose Err is ErrLinkBusy and whose Unsent is set: the message is still on this node, for the sender to drop or send again later. Only that peer's senders are refused. Replies, Downs, monitors and exits are queued regardless. LinkInfo.Queued and QueuedBytes show how close each link is to its bound.
MaxMessageSize is the largest message the node sends a peer, 4 MiB by default: gRPC's MaxRecvMsgSize, which every peer's server must take. A peer ends a link that sends it more, and with it every call and monitor on the link, so a node checks first: a send or a call that encodes larger, metadata included, fails at once with ErrTooLarge and is never sent, and a reply that large reaches its caller as ErrTooLarge, which Reply returns too. Local sends are not limited. Nothing tells a node its peers' limits, so to carry larger messages, raise grpc.MaxRecvMsgSize on every node's server first, and MaxMessageSize after.
Security
A link is a gRPC stream, secured as the server's other services are: TLS or mutual TLS in the server's credentials, and the matching grpc.WithTransportCredentials in DialOptions. The node's identity travels in the stream's metadata: its name, incarnation and protocol version. Nothing else checks that the certificate a peer presents belongs to the name it claims, so Admit is required. It runs for every inbound link, with the peer's transport credentials in the ctx, before the link is accepted. grpcproc.AdmitTLS admits a peer whose verified client certificate names its node, as a DNS or IP subject alternative name, so the server must verify client certificates:
srv := grpc.NewServer(grpc.Creds(credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert},
ClientCAs: pool,
ClientAuth: tls.RequireAndVerifyClientCert,
})))
node, err := grpcproc.NewNode(grpcproc.Config{
// …
Admit: grpcproc.AdmitTLS(nil), // nil: an admitted peer may ask anything
})A refused peer gets PermissionDenied, its dial fails, and it backs off like any other failed dial. grpcproc.AdmitAll admits every peer, for a network where whoever reaches the server is trusted: a demo on loopback, a test, a mesh that authenticates below gRPC. A peer it admits may claim any node name, and so stand in for a node, and exit any process.
Admit proves who dialed this node. To check the node this one dials, give each peer's TLS a ServerName of its node name in DialOptionsFor. A certificate names a node exactly: a wildcard names none. Admission has the whole set-up.
An admitted peer may ask anything of any process, Exit included, which a process cannot trap. A node of another installation, a partner's or a tenant's, gets a Policy instead: it judges every message, call, monitor and exit the peer sends over the link, by the name of the process it is for. grpcproc.Export is the usual one: the names listed, by name or PID, for sends, calls and monitors, and no exits. What a policy refuses does not exist for the peer: a call fails with ErrNoProc, a monitor gets Down{noproc}, and this node counts a dead letter with reason denied, which grpcprocctl watch shows.
Admit: func(ctx context.Context, peer grpcproc.NodeID) (grpcproc.Policy, error) {
if _, err := grpcproc.AdmitTLS(nil)(ctx, peer); err != nil {
return nil, err
}
if strings.HasPrefix(peer.Name, "partner-") {
return grpcproc.Export("quotes", "orders"), nil
}
return nil, nil
},
DialOptionsFor: func(peer string) []grpc.DialOption {
if strings.HasPrefix(peer, "partner-") { // another CA, another client certificate
return []grpc.DialOption{grpc.WithTransportCredentials(partnerCreds)}
}
return nil
},DialOptionsFor gives the connections to one peer options of their own, after DialOptions, so they win: the credentials for another installation's CA, here. Replies and Downs always pass a policy, since they answer what this node asked, so a process here can call and monitor the partner's processes whatever the partner may reach here. The Inspector, if the node serves one, is a second gRPC service on the same server and takes the same interceptors; inspect.ReadOnly() refuses its writes, for a deployment that shares the node's port without authenticating (Inspector).
Logging and hooks
Logger is the slog.Logger the node and its processes log through; p.Log() is it with the process's PID and label attached, and each process's level can be raised or lowered at runtime. Hooks is the one synchronous tap for everything the node does: spawns, exits, sends, receives, dead letters, links up and down. grpcproc/otel implements it with OpenTelemetry, and JoinHooks combines several (Observability).
CopyLocal clones every locally delivered message, so a sender can keep mutating what it sent. It is off by default: a local send shares the pointer, and the sender must not change a message after sending it.
Lifecycle
NewNodechecks the configuration and builds the node. Nothing runs yet.Registermountsgrpcproc.v1.Nodeon the gRPC server, and must come beforeServe, as any service registration does. Processes can be spawned from here on; they run before the node starts.Startpublishes the node: it begins watchingMembership, then registers with theRegistrar. Call it once the server serves, so that a peer that learns of the node can dial it.Stoptells every process to exit withshutdown, waits for them, flushes and closes the links, and withdraws the node; its ctx bounds the wait. Call it before the server stops, since the links are streams on that server.
The tutorial's platform builds the server, then the node on it, then the Inspector, then the root supervisor, and stops them in reverse:
// Module registers the node and what it stands on. They are built in this
// order, started in it and stopped in reverse: the gRPC server and its
// listener, the node served on it, the Inspector beside the node, and the
// root supervisor, which starts the node once the services run. So the
// services' trees stop first, the node closes its links after them, and the
// server stops last.
func Module(s *di.Scope) {
s.Wire[*cluster](newCluster).
// After the node, which registered in it.
OnStop(func(_ context.Context, c *cluster) error { return c.close() })
s.Wire[net.Listener](listen).
// Closed here too, for a start that fails before the server serves.
OnStop(func(_ context.Context, ln net.Listener) error { _ = ln.Close(); return nil })
s.Wire[*server](newServer).
Eager().
OnStart(func(_ context.Context, srv *server) error {
go func() {
// Serve returns nil after GracefulStop, and ErrServerStopped
// when a rollback stopped the server before it got here.
if err := srv.grpc.Serve(srv.ln); err != nil && !errors.Is(err, grpc.ErrServerStopped) {
s.Shutdown(err) // the listener died: stop the program
}
}()
return nil
}).
OnStop(func(ctx context.Context, srv *server) error {
// GracefulStop takes no context: if ctx ends first, Stop cuts
// what is left short.
stop := context.AfterFunc(ctx, srv.grpc.Stop)
srv.grpc.GracefulStop()
if !stop() {
return ctx.Err()
}
return nil
})
s.Wire[*grpcproc.Node](newNode).
Eager().
OnStop(func(ctx context.Context, n *grpcproc.Node) error { return n.Stop(ctx) })
// Built only for the services that join or read a group.
s.Wire[*groups.Scope](newScope)
s.Wire[*inspect.Server](newInspector).
Eager().
OnStop(func(_ context.Context, i *inspect.Server) error { return i.Close() })
s.Wire[*Root](newRoot).
Needs(di.AllOf[actor.ChildSpec]()).
Eager().
OnStart(func(ctx context.Context, r *Root) error { return r.start(ctx) }).
Go(func(ctx context.Context, r *Root) error { return r.wait(ctx) }).
OnStop(func(ctx context.Context, r *Root) error { return r.stop(ctx) })
}The root starts the node itself, once the services' trees run, so that with a registry the node is published only when its processes exist (Platform).