async/await became stable in Rust 1.39 on 7 November 2019. I waited for the libraries to catch up. Tokio 0.2, released on 26 November, is the first Tokio built on the new syntax, so now I tried it on a real small task.
The task: I have a list of devices on the home network (Pis, cameras, the MQTT broker), and I want a quick check of which ones answer on their port. Doing it one by one with a timeout is slow when several devices are off. This is a good fit for async: many network waits, almost no CPU.
What the language gives you, and what it does not
The language gives you async fn, async blocks and .await. An async fn returns a future, and a future does nothing until something polls it. The standard library has no runtime to run futures. You pick one: Tokio or async-std are the main choices now. I took Tokio because most network crates I use are built on it.
Cargo.toml
[package]
name = "portcheck"
version = "0.1.0"
edition = "2018"
[dependencies]
tokio = { version = "0.2", features = ["full"] }
futures = "0.3"
Tokio 0.2 has many feature flags and almost nothing is on by default. full turns everything on. For a small tool it is fine. For a library I would pick only the features I need.
The code
use std::time::Duration;
use futures::future::join_all;
use tokio::net::TcpStream;
use tokio::time::timeout;
async fn check(addr: &str) -> (String, bool) {
let ok = match timeout(Duration::from_secs(2), TcpStream::connect(addr)).await {
Ok(Ok(_stream)) => true,
_ => false, // timeout or connection error
};
(addr.to_string(), ok)
}
#[tokio::main]
async fn main() {
let hosts = vec![
"192.168.1.10:1883",
"192.168.1.21:22",
"192.168.1.22:22",
"192.168.1.30:554",
];
let results = join_all(hosts.iter().map(|h| check(h))).await;
for (addr, ok) in results {
println!("{:<22} {}", addr, if ok { "up" } else { "DOWN" });
}
}
#[tokio::main] creates the runtime and runs main on it. join_all runs all the checks at the same time and waits for all of them. The whole run takes about as long as the slowest check, which is the 2-second timeout when a device is off.
What confused me
Nothing happens without .await. I first wrote check(h); in a loop and got only a compiler warning that a future was unused. Coming from JavaScript, where a promise starts running when you create it, this was surprising. In Rust, a future is lazy.
Two Results from timeout. The outer one is the timeout, the inner one is the connection. Ok(Ok(_)) reads a bit odd, but the match makes both cases visible.
Blocking calls inside async code. std::thread::sleep or a blocking file read inside an async function blocks the whole worker thread, and other tasks wait. Use tokio::time::delay_for instead of sleep. For blocking work, Tokio has tokio::task::spawn_blocking.
Old crates. Many crates still use futures 0.1 and Tokio 0.1. They do not work directly with the new futures. I checked each dependency before I started. Within a month or two this should be better.
Error messages. When a borrowed value does not live long enough inside an async block, the compiler message is long and harder to read than in normal code. async move fixed it in my case, but I did not fully understand why at first.
One thing to know about tokio::spawn
tokio::spawn needs futures that are Send and 'static. That changes how data is passed around: a spawned
task gets owned values or an Arc, not references to local variables. Code that compiles fine with join!
can fail to compile once the same future goes into spawn.