Documentation
Platform
What every program of the runtime runs: configuration, a gRPC server with the node and the Inspector on it, what each peer may ask, and the root supervisor.
Configuration
Every program runs the same platform. It starts from the configuration, the one thing the programs of a deployment differ in: which node this is, where it listens, where the other nodes are, as a list or in etcd, which node runs each service it does not, and what its peers may ask of it. Where is what the conversations and the front ask. The nodes that run a model are not placed: the conversations find them in a process group.
package platform
import (
"cmp"
"fmt"
"os"
"strings"
)
// Config is what a program is told: which node it is, where it listens, and
// where the services it does not run are. Services address each other
// through Where, so moving a service to another node changes which entry
// point composes it and what the programs are told, and no service.
type Config struct {
// Node is the node's name. NODE, "local" by default.
Node string
// Listen is where its gRPC server listens. LISTEN.
Listen string
// HTTP is where the web front listens, when the program runs it. HTTP.
HTTP string
// Peers are the gRPC addresses of the nodes it talks to, and of those
// that talk to it: a reply travels back on the replier's own link.
// PEERS, as node=addr,node=addr. Not read with Etcd.
Peers map[string]string
// Etcd is the etcd cluster the nodes find each other in, instead of
// Peers: each node registers its name and Listen there, and learns of
// the others as they come and go. ETCD, as host:port,host:port.
Etcd []string
// Placement names the node of each service that does not run here, or
// its nodes, for one that runs on several. PLACEMENT, as
// service=node,service=node+node.
Placement map[string]string
// Export names the processes this node offers its peers: they may send
// to, call and monitor those, and the node's groups scope, and nothing
// else. With none, they may ask anything. EXPORT, as name,name.
Export []string
// Untrusted names the peers that may ask nothing of this node: they
// answer what it asks them. UNTRUSTED, as node,node.
Untrusted []string
}
// Where is the node that runs service: the one Placement names, the first
// if it names several, or this one.
func (c Config) Where(service string) string { return c.All(service)[0] }
// All is the nodes that run service: those Placement names, or this one.
func (c Config) All(service string) []string {
return strings.Split(cmp.Or(c.Placement[service], c.Node), "+")
}
// Load reads the configuration from the environment. With none set, it is
// the local deployment: one node, every service on it.
func Load() (Config, error) {
etcd := list("ETCD")
var peers map[string]string
if len(etcd) == 0 {
var err error
if peers, err = pairs("PEERS"); err != nil {
return Config{}, err
}
}
placement, err := pairs("PLACEMENT")
if err != nil {
return Config{}, err
}
cfg := Config{
Node: env("NODE", "local"),
Listen: env("LISTEN", "127.0.0.1:9100"),
HTTP: env("HTTP", "127.0.0.1:8080"),
Peers: peers,
Etcd: etcd,
Placement: placement,
Export: list("EXPORT"),
Untrusted: list("UNTRUSTED"),
}
// A service placed on a node nobody can dial fails every call to it;
// better to fail here. With etcd, a node is dialable once registered.
if len(cfg.Etcd) > 0 {
return cfg, nil
}
for service := range cfg.Placement {
for _, node := range cfg.All(service) {
if node != cfg.Node && cfg.Peers[node] == "" {
return Config{}, fmt.Errorf("platform: PLACEMENT puts %s on %s, which PEERS does not name", service, node)
}
}
}
return cfg, nil
}
// list parses name,name.
func list(key string) []string {
var out []string
for name := range strings.SplitSeq(os.Getenv(key), ",") {
if name = strings.TrimSpace(name); name != "" {
out = append(out, name)
}
}
return out
}
func env(key, fallback string) string { return cmp.Or(os.Getenv(key), fallback) }
// pairs parses key=value,key=value.
func pairs(key string) (map[string]string, error) {
out := map[string]string{}
for pair := range strings.SplitSeq(os.Getenv(key), ",") {
if pair = strings.TrimSpace(pair); pair == "" {
continue
}
k, v, ok := strings.Cut(pair, "=")
k, v = strings.TrimSpace(k), strings.TrimSpace(v)
switch {
case !ok || k == "" || v == "":
return nil, fmt.Errorf("platform: %s: %q is not name=value", key, pair)
case out[k] != "":
return nil, fmt.Errorf("platform: %s names %s twice", key, k)
}
out[k] = v
}
return out, nil
}The node and the server
Then it builds a gRPC server, the node registered on it, the Inspector beside the node, and the root supervisor. grpcprocctl talks to the Inspector. The node is a dependency like any other: a constructor that needs it takes it as a parameter.
The server serves from its own start hook, before the node and the services start, and not once the whole start has succeeded, as digrpc.Serve would have it: an answer to a call that a starting service makes to another node comes back over that peer's link into this server. The web front's server has no such need, and is run by dihttp.Serve.
// Package platform is what every program of the runtime runs, whichever
// services it hosts: its node, the gRPC server the node is served on, the
// Inspector beside it, and the root of its supervision tree. The services'
// packages know none of it but the node and the configuration.
package platform
import (
"context"
"errors"
"log/slog"
"net"
"slices"
"time"
"golang.yandex/di"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/keepalive"
"github.com/floatdrop/grpcproc"
"github.com/floatdrop/grpcproc/actor"
"github.com/floatdrop/grpcproc/groups"
"github.com/floatdrop/grpcproc/inspect"
)
// 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) })
}
// listen binds the gRPC port when the program starts, so a busy one fails
// the start rather than the first peer's dial.
func listen(cfg Config) (net.Listener, error) { return net.Listen("tcp", cfg.Listen) }
// 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}),
}
}
// server is the program's gRPC server and the listener it serves. The node
// and the Inspector register on it when they are built, before it serves.
type server struct {
grpc *grpc.Server
ln net.Listener
}
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}
}
func newNode(cfg Config, c *cluster, srv *server, log *slog.Logger) (*grpcproc.Node, error) {
n, err := grpcproc.NewNode(grpcproc.Config{
Admit: admit(cfg),
Name: cfg.Node,
Advertise: cfg.Listen,
Resolver: c.resolver,
Registrar: c.registrar,
Membership: c.membership,
DialOptions: dialOptions(),
Logger: log,
})
if err != nil {
return nil, err
}
n.Register(srv.grpc)
return n, nil
}
// admit says what each peer may ask of this node, from the configuration:
// an untrusted peer nothing, so that it only answers what this node asks
// it; any other the processes this node exports, and its groups' scope, or
// anything if it names none. Nothing here checks who a peer is, so a peer is whoever it says it
// is: plaintext keeps the guide short. A real deployment first checks that
// the peer's certificate names its node, as grpcproc.AdmitTLS does.
func admit(cfg Config) func(context.Context, grpcproc.NodeID) (grpcproc.Policy, error) {
exported := grpcproc.Export(append(slices.Clone(cfg.Export), groups.ScopeName(scope))...)
return func(_ context.Context, peer grpcproc.NodeID) (grpcproc.Policy, error) {
switch {
case slices.Contains(cfg.Untrusted, peer.Name):
return grpcproc.Export(), nil
case len(cfg.Export) > 0:
return exported, nil
}
return nil, nil
}
}
// newInspector serves the node to grpcprocctl, and reaches the other nodes'
// Inspectors the way the node reaches the nodes, which it does by default.
// It is read-only, since it shares the node's port and nothing here
// authenticates: exit and loglevel are refused. A deployment that wants them
// puts the Inspector behind the interceptors that guard its other services.
func newInspector(n *grpcproc.Node, srv *server) *inspect.Server {
i := inspect.New(n, inspect.ReadOnly())
i.Register(srv.grpc)
return i
}What a peer may ask
A node decides once per link what the peer on it may do: Config.Admit refuses the link, or returns the policy that judges every send, call and monitor that arrives on it. The platform makes it from the configuration. A peer named untrusted gets grpcproc.Export() with no names, which allows nothing; any other peer may reach the processes this node exports, and the scope of its process groups, or all of them if it names none.
// admit says what each peer may ask of this node, from the configuration:
// an untrusted peer nothing, so that it only answers what this node asks
// it; any other the processes this node exports, and its groups' scope, or
// anything if it names none. Nothing here checks who a peer is, so a peer is whoever it says it
// is: plaintext keeps the guide short. A real deployment first checks that
// the peer's certificate names its node, as grpcproc.AdmitTLS does.
func admit(cfg Config) func(context.Context, grpcproc.NodeID) (grpcproc.Policy, error) {
exported := grpcproc.Export(append(slices.Clone(cfg.Export), groups.ScopeName(scope))...)
return func(_ context.Context, peer grpcproc.NodeID) (grpcproc.Policy, error) {
switch {
case slices.Contains(cfg.Untrusted, peer.Name):
return grpcproc.Export(), nil
case len(cfg.Export) > 0:
return exported, nil
}
return nil, nil
}
}Answers are never judged: a reply, or the Down of a monitor the node placed itself, always comes back. So the gateway, which does not trust the sandbox, still calls its tools and gets their results, while a sandbox that tries to call a conversation is told ErrNoProc, as for a process that does not exist. The GPU nodes name the sandbox untrusted too: a scheduler publishes to whatever topic a request names, so it takes requests from the gateway only.
All of this rests on a peer being who it says it is, and here nothing checks: the links are plaintext, to keep the tutorial short, and a sandbox could call itself gpu-1. A real deployment uses mutual TLS and admits a peer only under the node name its certificate carries, as grpcproc.AdmitTLS does; then what a tool that takes over the sandbox's node can do through grpcproc is answer the calls made to it.
Start and stop order
The container builds eager services in registration order and starts them in build order, so the node and the Inspector are registered on the server before it serves. Stopping runs the other way: the root stops the trees first, then the node closes its links, and the server goes last.
Keepalive, in the dial options and on the server, is what turns a silent peer into a broken link, and so into Downs and failed calls. The Inspector is read-only, since it shares the node's port and nothing here checks who calls it.
The root supervisor
The root is built from the group the service modules add their trees to: one supervisor per node, actor.OneForOne, so a service whose supervisor gives up is restarted without the others. It starts the node once the services run, which with a registry is when peers learn of the node. A worker watches it: a root that exits on its own, past its restart limit, means the services have given up, and the worker's error stops the program for whatever runs it to start again.
package platform
import (
"context"
"errors"
"fmt"
"time"
"github.com/floatdrop/grpcproc"
"github.com/floatdrop/grpcproc/actor"
)
// Root is the node's top supervisor. Its children are the services' trees,
// which the services' modules add to the group of actor.ChildSpec: a
// program runs the services its entry point composes, and nothing here
// knows which those are.
type Root struct {
node *grpcproc.Node
spec actor.Spec
pid grpcproc.PID
gone chan struct{} // closed once the root has exited
reason string // why it did; read after gone is closed
cancel context.CancelFunc
}
func newRoot(n *grpcproc.Node, trees []actor.ChildSpec) *Root {
return &Root{node: n, spec: actor.Spec{Strategy: actor.OneForOne, Children: trees}}
}
// start runs the trees, in the order their modules were composed, and only
// then starts the node: with a registry, that is when peers learn of it, so
// none routes to a service that does not exist yet.
func (r *Root) start(ctx context.Context) error {
// Subscribed before the root exists, so its exit cannot be missed.
watch, cancel := context.WithCancel(context.Background())
events := r.node.Subscribe(watch, 64)
pid, err := actor.Supervise(r.node, r.spec, grpcproc.WithName("root"))
if err != nil {
cancel()
return err
}
r.pid, r.gone, r.cancel = pid, make(chan struct{}), cancel
go r.watch(events)
if err := r.node.Start(ctx); err != nil {
// No stop hook runs for a start that failed: stop the trees here.
return errors.Join(err, r.stop(ctx))
}
return nil
}
// watch closes gone when the root exits, with the reason.
func (r *Root) watch(events <-chan grpcproc.Event) {
defer close(r.gone)
tick := time.NewTicker(time.Second)
defer tick.Stop()
for {
select {
case e, ok := <-events:
if !ok {
r.reason = grpcproc.ReasonShutdown // the node stopped
return
}
if e.Kind == grpcproc.EventExit && e.Process.PID == r.pid {
r.reason = e.Reason
return
}
case <-tick.C:
// A node busy enough to drop events may drop this one, and if
// nothing follows it no later event says so. A root that is gone
// with nothing left to read went unreported.
if _, running := r.node.Process(r.pid); !running && len(events) == 0 {
r.reason = "exited"
return
}
}
}
}
// wait is the root's worker: it returns when the root exits. The container
// cancels it before stopping the root, so an exit it sees is the node's
// services giving up, and its error stops the program, for whatever runs it
// to start again.
func (r *Root) wait(ctx context.Context) error {
select {
case <-r.gone:
return fmt.Errorf("platform: the root supervisor exited: %s", r.reason)
case <-ctx.Done():
return nil
}
}
// stop asks the root to exit and waits until it has. A supervisor stops
// its children first, in reverse order, so every service is down before the
// node is stopped under it.
func (r *Root) stop(ctx context.Context) error {
defer r.cancel()
if err := r.node.Exit(ctx, r.pid, grpcproc.ReasonShutdown); err != nil {
return err
}
select {
case <-r.gone:
return nil
case <-ctx.Done():
return ctx.Err()
}
}Run and Compose
Run is every entry point's main: it loads the configuration, composes the platform with the services, validates the graph before building anything, and runs until a signal arrives or a worker fails. Compose is the part the tests use.
package platform
import (
"context"
"log/slog"
"os"
"time"
"golang.yandex/di"
"golang.yandex/di/dislog"
)
// Run is a program's main: it composes the platform with the services'
// modules, checks the graph, and runs until a signal arrives. The entry
// points differ only in the modules they pass.
func Run(services ...di.Module) {
log := slog.New(slog.NewTextHandler(os.Stderr, nil))
cfg, err := Load()
if err != nil {
log.Error("configuration", "err", err)
os.Exit(2)
}
app := di.New()
// dislog logs what the container does: each constructor and hook, so
// the program says what it builds, starts and stops, in order.
app.Observe(dislog.New(log.With("node", cfg.Node)))
Compose(app, cfg, log, services...)
// Nothing is built yet; the constructors declared their dependencies,
// so a service that needs what no module provides fails here.
if err := app.Validate().Err(); err != nil {
log.Error("invalid wiring", "err", err)
os.Exit(1)
}
if err := app.Run(context.Background(), di.StopTimeout(10*time.Second)); err != nil {
log.Error("stopped with failures", "err", err)
os.Exit(1)
}
}
// Compose registers what a program is: its configuration and logger, the
// platform, and the services it runs. Tests compose the same way.
func Compose(app *di.Scope, cfg Config, log *slog.Logger, services ...di.Module) {
app.Value(cfg)
app.Value(log) // the node adds its name to what it logs
app.Use(Module)
app.Use(services...)
}Each module declares what it provides and what its constructors need, so the container can report a composition without building it. This is cmd/local's, as the tests compose it; another test checks that each main passes the modules its test composes.
registered directly
provides platform.Config, *slog.Logger
platform.Module
provides *platform.cluster, net.Listener, *platform.server, *grpcproc.Node, *groups.Scope, *inspect.Server, *platform.Root
needs platform.Config ← registered directly
*slog.Logger ← registered directly
all of actor.ChildSpec
models.Module
provides models.Model, models.Pace, models.Slots, actor.ChildSpec
needs *groups.Scope ← platform.Module
tools.Module
provides tools.Tools, actor.ChildSpec
conversations.Module
provides conversations.History, conversations.Limits, actor.ChildSpec
needs platform.Config ← registered directly
*groups.Scope ← platform.Module
web.Module
provides *web.front, *http.Server
needs *grpcproc.Node ← platform.Module
platform.Config ← registered directly
*slog.Logger ← registered directly