Publish to a topic
Subscribe actors on several nodes to a topic and tell all of them with one publish.
A topic tells one message to every actor subscribed to it, on any member of the cluster. pubsub::subscribe subscribes an actor of this node, and pubsub::publish tells every subscriber the receptionist knows of. There is no mediator: a topic is a key at the receptionist under another name.
The examples on this page come from two nodes. Each subscribes a listener to the topic notices before it bootstraps. The first node then publishes one notice and collects a receipt from every listener. The program plays both nodes, as in the clustered actors tutorial.
Define the message
struct Listener {
addr: SocketAddr,
}
impl Actor for Listener {
type Message = Notice;
type Timers = Untimed;
type Stash = Unstashed;
type State = ();
type Error = !;
fn init(&self, _: &ActorContext<Self::Message>) -> Result<Self::State, Self::Error> {
Ok(())
}
fn receive(
&self,
_: &ActorContext<Self::Message>,
incoming: Incoming<Self::Message>,
_: Self::State,
) -> Result<Control<Self::State>, Self::Error> {
let Incoming::Message(Notice { text, receipts }) = incoming else {
unreachable!("the listener watches no actor, hence never gets a terminated signal")
};
receipts.tell(Receipt {
addr: self.addr,
text,
});
Ok(Control::Stop)
}
}
#[derive(Clone, Serialize, Deserialize)]
struct Notice {
text: String,
receipts: ActorRef<Receipt>,
}
impl Schema for Notice {}
impl Manifest for Notice {
const MANIFEST: &'static str = "notice";
}A published message crosses the wire like any remote message: Notice derives serde's Serialize and Deserialize and implements Schema and Manifest, see Messages that travel. publish tells each subscriber of this node a clone of the message, so Notice also needs Clone. That rules out a ReplyTo in a published message, so Notice carries an ActorRef<Receipt> for the answers. The listener tells it a receipt and stops. Receipt crosses the wire as well, so it derives serde's Serialize and Deserialize and implements Schema.
Subscribe
async fn subscriber_node() -> anyhow::Result<()> {
let (addr, seeds) = node_args()?;
start_endpoint(addr)?;
let listener = ActorSystem::new(Listener { addr });
pubsub::subscribe(&Topic::new(TOPIC), listener.root()).context("subscribing to the topic")?;
bootstrap(seeds).await?;
let departure = cluster::leave_on_terminated(listener)
.await
.context("leaving the cluster")?;
anyhow::ensure!(
departure.is_acknowledged(),
"departure not acknowledged by {:?}, timed out for {:?}",
departure.unacknowledged(),
departure.timed_out()
);
Ok(())
}subscribe registers an actor of this node under the topic, so it needs a started endpoint. Both nodes subscribe before they bootstrap. There is no unsubscribe: a subscription lasts as long as its actor. An actor which should leave a topic while it keeps running subscribes a child instead, and the subscription ends with the child. A parent cannot stop a single child, so the child stops itself, for example on a message of the topic's type which asks it to. The second node waits until its listener has stopped, then leaves the cluster.
Wait for the subscriptions
A publish tells only the subscribers whose registration has reached this node. Right after bootstrap, the registrations of the other node may still be on their way:
async fn await_settled() -> anyhow::Result<()> {
let mut states = cluster::cluster_state().context("subscribing to the cluster state")?;
let settle = async {
loop {
let state = states.wait_for(|state| state.up().count() == NODES).await;
if receptionist::settled(state.version()).context("asking for the settlement")? {
return anyhow::Ok(());
}
select! {
() = states.changed() => {}
() = sleep(SETTLE_POLL_INTERVAL) => {}
}
}
};
timeout(SETTLE_TIMEOUT, settle)
.await
.context("the receptionist did not settle within the timeout")?
}receptionist::settled(version) is true when version is the current cluster state version and every other up member in that view has delivered its first set of registrations. A view in which this node is the only member up is settled, so await_settled first waits until both nodes are up. The receptionist can settle between cluster state changes, so await_settled also checks every 100 ms. Both listeners subscribed before bootstrap and are in that first delivery. Later subscriptions can still be in transit.
Publish
async fn first_node() -> anyhow::Result<()> {
let addrs = free_addrs(NODES)?;
let mut subscriber_node = spawn_node(addrs[1], &addrs)?;
let topic = Topic::new(TOPIC);
start_endpoint(addrs[0])?;
let listener = ActorSystem::new(Listener { addr: addrs[0] });
pubsub::subscribe(&topic, listener.root()).context("subscribing to the topic")?;
bootstrap(addrs.clone()).await?;
await_settled().await?;
let subscribers = receptionist::lookup(topic.key()).context("looking up the subscribers")?;
println!("Subscribers: {}", subscribers.len());
let (receipts_tx, mut receipts_rx) = mpsc::unbounded_channel();
let collector = ActorSystem::new(Collector {
receipts: receipts_tx,
});
let notice = Notice {
text: "maintenance at noon".to_string(),
receipts: collector.root().clone(),
};
let told = pubsub::publish(&topic, notice).context("publishing the notice")?;
println!("Told: {told}");
let mut receivers = Vec::new();
for _ in 0..told {
let Receipt { addr, text } = timeout(RECEIPT_TIMEOUT, receipts_rx.recv())
.await
.context("no receipt within the timeout")?
.context("the collector has stopped")?;
let node = addrs
.iter()
.position(|node| *node == addr)
.context("a receipt from an unknown node")?;
receivers.push((node + 1, text));
}
receivers.sort();
for (node, text) in receivers {
println!("Node {node} received: {text}");
}
let status = timeout(EXIT_TIMEOUT, subscriber_node.wait())
.await
.context("the subscriber node did not exit within the timeout")?
.context("awaiting the subscriber node's exit")?;
anyhow::ensure!(status.success(), "the subscriber node failed: {status}");
collector.stop();
collector
.terminated()
.await
.context("awaiting the collector's termination")?;
listener
.terminated()
.await
.context("awaiting the listener's termination")
}receptionist::lookup(topic.key()) lists the subscribers of the topic. A discovery key of the same name is a different key, so Key::new("notices") would not list them. publish tells the subscribers of this node first, each a clone. It encodes the message once per other node with subscribers, rather than once per subscriber. It answers how many subscribers it told. That is not the number of deliveries: as with tell, the message is a dead letter for a subscriber whose mailbox is full, and for every subscriber on a node which cannot be reached.
What to keep in mind
The guarantee is that of tell, per subscriber. Every subscriber gets a publish at most once. Publishes from one node reach a subscriber in the order they were made, in order with the node's direct tells to it. Concurrent publishes can reach two subscribers in different orders.
A publish fails once this node is out. On a node whose own entry is left or down, publish tells nobody and fails, rather than answer 0 as if the topic had no subscribers. It also fails if the topic has subscribers only for another message type.
A subscriber is told only while its node is up. A publish skips every subscriber on a node which is left or down in this node's view, even if the actor still runs there.
Run it
#[tokio::main]
async fn main() -> anyhow::Result<()> {
init_tracing();
match env::args().nth(1).as_deref() {
Some(SUBSCRIBER_NODE_ARG) => subscriber_node().await,
_ => first_node().await,
}
}From a clone of the tellus repository:
cargo run --quiet -p tellus --features cluster-dev --example how_to_publish_to_a_topicSubscribers: 2
Told: 2
Node 1 received: maintenance at noon
Node 2 received: maintenance at noonThe lookup on the first node lists both listeners once the receptionist has settled, and the publish tells both. The receipts arrive in any order; the first node sorts them by node before it prints them.