Learning question: When several tasks need the same mutable state, what is the alternative to sharing it?
Some state can only be used by one caller at a time, and a server has many callers. This article reads tower::buffer, which solves that for any tower Service: a handle you can clone, a channel, and one worker task that owns the service.
Scope. We read tower/src/buffer/service.rs, worker.rs and message.rs at commit df06d70 [S8]. We do not cover Pin, poll or how futures are driven; where a signature mentions them, read past it. You need closures, move, and the Commands and Typed results articles. Actor is the name Hewitt, Bishop and Steiger gave in 1973 to the single kind of object in their formalism, which has one kind of behaviour: sending messages to actors [S11]. This article uses the name for a unit that owns its state and is reached only by messages; "owns its state" is this article's wording and is not in the paper. The Rust patterns book's architectural advice, that data flow one way and that a reply travel on its own separate channel, describes the same shape [S2, ch. 9, "Data flows downward"].
A counter with two owners
Example 1 gives one counter to two threads.
Example 1. Compiles, with four warnings (compile-fail/cf10_actor.rs, lines 3 to 14)
struct Counter {
seen: u32,
}
fn main() {
let mut counter = Counter { seen: 0 };
let a = thread::spawn(move || counter.seen += 1);
let b = thread::spawn(move || counter.seen += 1);
a.join().unwrap();
b.join().unwrap();
println!("requests seen: {}", counter.seen);
}
The program had one counter and two threads, and it gave the counter to each of them with the word move, as a man might promise the same calf to two neighbours. Each thread added one. The program waited politely for both and then read the total. It compiled. It printed:
requests seen: 0Predict
Two increments, and the answer is zero, and the compiler accepted it. Before reading on: u32 is a Copy type. What do you think each closure captured?
The first warning tells you:
warning: value captured by `counter.seen` is never read
--> cf10_actor.rs:10:35
|
10 | let b = thread::spawn(move || counter.seen += 1);
| ^^^^^^^^^^^^
|
= help: did you mean to capture by reference instead?
= note: `#[warn(unused_assignments)]` (part of `#[warn(unused)]`) on by defaultEach closure captured its own copy of the one field it mentions, incremented the copy, and threw it away.¹ There were three counters. This is the footgun to remember from this article: move plus a Copy field can compile into a program that shares nothing.
Name the parts
| Role | In tower | Where [S8] |
|---|---|---|
| Handle | Buffer<Req, F> |
buffer/service.rs line 19 |
| Mailbox | mpsc::channel(bound) |
service.rs line 73 |
| Message | Message { request, tx, span } |
buffer/message.rs line 6 |
| Owner | Worker<T, Request>, holding service: T |
buffer/worker.rs line 23 |
| Reply path | a oneshot channel per request |
service.rs line 120; worker.rs line 177 |
Who owns the service?
Sharing mutable state between tasks means a lock around every use, and a lock held across an .await is its own category of trouble: std's own attribute on MutexGuard lists deadlocks, delays and futures that are not Send [S3, mutex.rs lines 271 to 273]. Thankfully, there's another arrangement: give the state to one task and send it requests. Take a look at Example 2.
Example 2. The message, the owner, and the handle (buffer/message.rs lines 6 to 10; buffer/worker.rs lines 23 to 33; buffer/service.rs lines 19 to 22, visibility removed, the pin_project! wrapper around Worker (worker.rs line 14) not shown, and the alias Tx<Fut> (message.rs line 13) written out [S8])
struct Message<Request, Fut> {
request: Request,
tx: oneshot::Sender<Result<Fut, ServiceError>>,
span: tracing::Span,
}
pub struct Worker<T, Request>
where
T: Service<Request>,
{
current_message: Option<Message<Request, T::Future>>,
rx: mpsc::Receiver<Message<Request, T::Future>>,
service: T,
finish: bool,
failed: Option<ServiceError>,
handle: Handle,
}
pub struct Buffer<Req, F> {
tx: PollSender<Message<Req, F>>,
handle: Handle,
}
There are three structs and one fact to take from each. Worker has the field service: T: the service itself, owned, with no lock around it. Buffer has no service at all; it has tx, the sending half of a channel. And Message carries the request together with tx, a one-use sender for the reply, so each request brings its own return envelope.
The worker's loop takes one message at a time (
poll_recv, worker.rs line 94) and, once self.service.poll_ready at line 167 reports ready, does two things with it: self.service.call(msg.request) at line 170, then msg.tx.send(Ok(response)) at line 177. A text search for .call( in the seven files of tower/src/buffer/ at the pinned commit finds that line and one other match, which is inside a doc comment (mod.rs line 30).
The channel is bounded. The documentation on Buffer::new says bound is the number of requests that can queue before backpressure is applied to callers [S8, service.rs lines 30 to 31]. A full mailbox is how the owner says it is behind.
What transfers, and what does not
A queue worker that pulls jobs one at a time is the PHP-shaped version, and the reasoning transfers: one consumer, so no two jobs touch the state together. What does not transfer is where the guarantee comes from. In PHP it comes from the deployment: you run one worker. Here it comes from ownership. service is a field of Worker, Worker is moved into one spawned task, and no other code has a name for it.
What did you give up?
So nothing is shared and nothing is locked. Every call to the service is now a message, a channel send, a wake-up of the worker task and a reply on a second channel, where a method call on a shared reference would have been a method call, and every request waits behind the ones before it whether or not they would have conflicted, which suits state that truly admits one user and does not suit a map that is read a thousand times for every write. Does the state behind your handle need one user at a time, or did it only need a lock around the writes?
Practice tier: judgment, with a lint-shaped trap on the way in. The compiler accepted Example 1; only the unused_assignments warnings pointed at the mistake.
Testing
The claim is that many handles reach one owned service and no request is lost or duplicated. Example 3 uses a service whose state is a plain u32, with no lock and no Clone. The second argument to Buffer::pair, 8, is bound: pair passes it to mpsc::channel (service.rs lines 66 and 73).
Example 3. Three handles, one counter (tests/p10_actor_tower_buffer.rs, abridged)
let (handle, worker) = Buffer::pair(Counter { seen: 0 }, 8);
tokio::spawn(worker); // the worker task now owns the Counter
let mut replies = Vec::new();
for name in ["a", "b", "c"] {
let mut h = handle.clone(); // cloning the handle clones a sender, not the Counter
replies.push(tokio::spawn(async move {
h.ready().await.unwrap().call(name).await.unwrap()
}));
}
// collect the three replies, sort them
assert_eq!(counts, vec![1, 2, 3]);
Three tasks, three replies, and the counter reached exactly 3. It passed against the pinned commit on rustc 1.100.0. With Example 1's arrangement the same assertion could not be written at all: there was no single counter to ask.
Retrieve
- Which struct has the field
service: T, and which has none? - What did each closure in Example 1 capture, and why did the total stay at zero?
The RAII article reads the arrangement this one avoided: a Mutex, and the guard value that releases it.
TL;DR
tower::buffer splits a service into a Buffer handle, which holds only a channel sender and can be cloned, and a Worker, which owns the service and runs as one task. Requests travel as Message values through a bounded channel, each with a oneshot sender for its reply. The service is used by one task, so it needs no lock; the cost is a message per call and a queue.
¹ Since the 2021 edition, a closure captures the individual fields it uses and not the whole struct. The Rust Edition Guide's words: "Starting in Rust 2021, closures captures are more precise. Typically they will only capture the fields they use" [S12]. Example 1 was built as edition 2021, the edition in the example crate's Cargo.toml. Built with no edition flag, rustc 1.100.0 rejects the second closure with E0382, use of moved value (evidence/ev10_default_edition.stderr, beside this article).