Documentation
Pub/sub
Topics that a process publishes to and any node subscribes to, with the last few events kept for late subscribers.
grpcproc/pubsub is optional, and built on the public API only. The code is from examples/pubsub.
Topics
A topic is a process that keeps its subscribers and the last Config.Buffer events, and sends each event it is given to every subscriber. It is spawned in one of two ways:
pubsub.SpawnOwned[E](p, cfg, …) | A topic owned by p, linked to it: it ends when p does, with p's reason. For events that mean something only while their producer runs. |
pubsub.Spawn[E](node, cfg, …) | A topic for the whole node, whoever publishes to it. It lasts until it is asked to exit or the node stops. |
The rest of the arguments are grpcproc.SpawnOptions: a name, a label. The example's inventory owns a topic of stock levels and publishes to it after each reservation:
// inventory reserves stock, and publishes the level after each reservation
// to a topic it owns. The topic keeps the last two levels for whoever
// subscribes later, and ends when inventory does.
func inventory(p *grpcproc.Process[*shoppb.Reserve]) error {
stock, err := pubsub.SpawnOwned[*shoppb.Reserved](p, pubsub.Config{Buffer: 2}, grpcproc.WithName("stock"))
if err != nil {
return err
}
left := map[string]int64{"apple": 10}
for {
m, err := p.Receive()
if err != nil {
return err
}
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
level := &shoppb.Reserved{Sku: m.Body.Sku, Left: left[m.Body.Sku]}
_ = stock.Publish(p.Context(), p, level)
_ = m.Reply(level, nil)
}
}Publish(ctx, from, e) is a send to the topic, from a Node or a Process, as Addr.Send is. The topic sends each event on in the order it received them, so one publisher's events arrive in the order it published them, each with the metadata it was published with, trace context included.
Topic[E] is an address that carries the event type, as Addr[M] carries a mailbox's: pubsub.Named[E](node, name) reaches a topic by its name, and pubsub.TopicOf[E](pid) by its PID. topic.Addr() is its process, to monitor, link to, or ask to exit. A topic whose E is an interface, proto.Message say, takes any message of it.
Subscribing
A process subscribes from inside its handler with topic.Subscribe(ctx, p). When it returns, the events the topic kept are already in p's mailbox, and everything published after them follows: nothing is missed between the two, and nothing arrives twice. The events are plain messages, from sub.From, so p's mailbox must accept E; Subscribe fails with ErrType when it does not, or when the topic publishes another concrete type. A topic or subscriber whose E is an interface is not checked.
// dashboard subscribes to the stock topic of another node and prints each
// level until the topic ends. Its mailbox holds the topic's events, so they
// are plain messages to it.
func dashboard(subscribed, done chan<- struct{}) func(*grpcproc.Process[*shoppb.Reserved]) error {
return func(p *grpcproc.Process[*shoppb.Reserved]) error {
defer close(done)
ctx, cancel := context.WithTimeout(p.Context(), 5*time.Second)
defer cancel()
sub, err := pubsub.Named[*shoppb.Reserved]("warehouse", "stock").Subscribe(ctx, p)
if err != nil {
return err
}
close(subscribed)
for {
m, err := p.Receive()
if err != nil {
return err
}
if m.Down != nil && m.Down.Ref == sub.Ref {
fmt.Println("stock ended:", m.Down.Reason)
return nil
}
fmt.Printf("%s left: %d\n", m.Body.Sku, m.Body.Left)
}
}
}| When | What the subscriber sees |
|---|---|
| The topic exits | The Down with sub.Ref, with the topic's reason: for an owned topic, its owner's. |
| The topic's node becomes unreachable | The same Down, with noconnection. |
sub.Cancel(p) | Its monitor of the topic stops, and the topic is told to send no more: what it sent before it heard may still arrive, and what is in the mailbox, a Down included, stays. |
| The subscriber exits | Nothing to do: the topic monitors its subscribers, and forgets one that exits. |
A subscriber that should end with the topic, rather than be told, links to it as well: p.Link(topic.Addr()). A process that subscribes twice still gets each event once, but each Subscribe monitors the topic anew, with a Ref of its own. ctx bounds the whole of Subscribe; if it ends first, Subscribe tells the topic to forget p, in case the request reached it after all.
Demand notifications
A producer whose events are costly to make can make them only while someone wants them. Config.Notify names a process the topic tells: a *pubsubv1.Demand with Subscribed true when the first subscriber comes, and false after the last one leaves, by Cancel or by exiting.
func quotes(p *grpcproc.Process[proto.Message]) error {
topic, err := pubsub.SpawnOwned[*pricespb.Quote](p, pubsub.Config{Notify: p.PID()})
if err != nil {
return err
}
polling := false
for {
m, err := p.Receive()
if err != nil {
return err
}
if d, ok := m.Body.(*pubsubv1.Demand); ok {
polling = d.GetSubscribed() // ask the exchange for quotes only while someone listens
}
…
}
}The Demand is a message like any other, so the notified process's mailbox must accept it: proto.Message here, or an interface both types implement.
Across nodes
A process that subscribes to a topic of another node subscribes through a relay on its own node: a process named pubsub:{stock@warehouse}, which the first such subscriber starts. The relay is a topic too. Its events are the upstream topic's, and it keeps as many as the upstream does, so the second subscriber on a node gets the kept events without another trip across the network. The upstream topic sends each event once to each node, however many subscribers the node has.
For the subscriber, sub.From is the relay, and the Down comes from the relay, with the topic's reason: the relay ends with the topic, for the same reason, and ends as well when its last subscriber leaves, after which the topic forgets it.
The relay subscribes to the topic while its first subscriber waits, within that subscriber's deadline: a call carries its ctx's deadline to the process called, so the relay gives up when the subscriber does. Give Subscribe a deadline, as the dashboard does: with none, the relay waits until the topic answers or its node becomes unreachable. A topic that does not exist is ErrNoProc, and a node that cannot be reached ErrNoConnection, as for a call.
Example
Two nodes in one binary, as in the quick start: inventory and its topic on warehouse, a dashboard on shop. Three reservations come before the dashboard subscribes, so it starts with the two levels the topic kept; the fourth reaches it as it is published; and when inventory is asked to exit, the dashboard is told the topic ended, and why.
// Three reservations before anyone listens: the topic keeps the last two.
for range 3 {
_, err := reserve.Call[*shoppb.Reserved](ctx, shop, &shoppb.Reserve{Sku: "apple", Qty: 1})
check(err)
}
// The dashboard subscribes from the other node, and gets those two first.
subscribed, done := make(chan struct{}), make(chan struct{})
_, err = shop.Spawn(dashboard(subscribed, done))
check(err)
<-subscribed
// What is published from now on reaches it as it happens.
_, err = reserve.Call[*shoppb.Reserved](ctx, shop, &shoppb.Reserve{Sku: "apple", Qty: 2})
check(err)
// The topic is inventory's: when inventory exits, the dashboard learns
// that the topic ended, and why.
check(warehouse.Exit(ctx, inv, "closing"))
<-doneapple left: 8
apple left: 7
apple left: 5
stock ended: closingLimits
- Delivery is at most once, as for any message. A subscriber that must not miss an event needs acknowledgements, built above this.
- Nothing pushes back on a publisher. A subscriber slower than its topic has a mailbox that grows, as any process's does.
- A node-wide topic that a supervisor restarts comes back with no subscribers. They receive a
Down, and subscribe again. - A topic addressed by its name and by its PID gets two relays on a node, one for each.