Async: futures and await
rut’s concurrency is pull-based. An async fn compiles into a
future — a cold value that runs nothing until something drives it.
There are no promises that start on creation, no microtask queue, no
implicit scheduling: the host owns time, and code progresses only when
a driving loop pumps it. The model is described in
the async model, with the full
surface in async and await and
launched futures.
async fn, async { }, and await
Calling an async fn runs nothing: it returns a cold future — a
Future<T>, the ONE async type every producer answers (an async fn
call, an async { } block, sleep, the race/completer mints). await
is the in-body suspension point, and it consumes the future:
async fn countdown(log: Logger, n: u32) {
let mut i = n;
while (i > 0) {
log.info(f"t-{i}");
await sleep(500); // park here; the loop resumes the frame
i -= 1;
}
log.info("lift-off");
}
The resume context is injected, never spelled: the weave binds cx
inside every async body (probe it with cx.cancelled() — see
async and await). And async fn is sugar over
the async { } block — the block is the primitive, an expression that
mints the frame where it stands and answers Future<T>:
let f: Future<nil> = async { // mints cold; runs when driven
log.info("later");
};
launch_future(f);
Two consume paths, and exactly one per future:
await fut— drive it from this async body. Legal only inside an async fn or async block, and only forFuture<..>values (which is every producer).launch_future(fut)— hand it to the driving loop and keep a receipt. Returns aLaunchedFutureHandle<T>, which is not a future: it cannot be awaited or re-launched. Itsabort()flags cancellation; the frame notices at its next checkpoint and runs its cleanup.
sleep(ms) is the one built-in pender — a Future<nil> that parks its
frame until the VM’s clock reaches the deadline.
Both launch_future and sleep come from the futures package:
use futures::{ launch_future, sleep };
Who drives?
You never write a driving loop — the embedder does. The rut run CLI
is an embedder: after main returns it pumps the loop — drain ready
frames, advance the virtual clock to the next timer deadline, repeat —
until nothing is pending. So a program launches work from main and
the output simply appears:
rut run countdown/ # a module dir (rut.jsonc + main.rut); main launches the countdown
t-3
t-2
t-1
lift-off
Calling an async function and awaiting it in the same body is the straight-line case; launching is for concurrency — independent work that overlaps through the loop’s interleaving.
Talking to the network: the http package
The standard http package is async-only where work actually waits.
Everything else — the client, the verbs, the builder — is sync
construction sugar:
use http::{ HttpClient };
let client = HttpClient();
let resp = await client.get(url).build().send();
The shape, step by step:
client.get(url)(orrequest(),post,put,patch,del) hands back aRequestBuilder;.method(..),.url(..),.header(k, v)(repeatable),.body(bytes)chain on it..build()freezes a re-sendableRequest..send()is the async point. It resolves at headers — the wire body is still unread.- From the
Response, take one of two readbacks:await resp.body()— drain the remaining body in one future;resp.byte_stream()thenawait stream::next()— one chunk per future,nilat end-of-stream, for bounded-memory downloads.
Errors come back as data, not traps: status 0 is reserved for
transport failure (resp.transport_error() carries the reason), any
real status — 4xx and 5xx included — is a normal response
(resp.ok() is the 2xx test), and a mid-read wire death surfaces as
nil from next() with the reason in stream::error().
A complete request handler from the repository’s GitHub-viewer example — send, then drain:
async fn do_list(client: HttpClient, owner: str, repo: str, rf: str) -> i32 {
let url = f"https://data.jsdelivr.com/v1/packages/gh/{owner}/{repo}@{rf}";
let resp = await client.get(url).build().send();
if (resp.status() == 0) {
let why: str = resp.transport_error();
eprint(f"rgh: network error: {why}");
return 1;
}
if (!resp.ok()) {
eprint(f"rgh: CDN {resp.status()}");
return 1;
}
let (tree, e) = decodeJsonBytes<Root>(await resp.body());
if (e != nil) {
let why: DecodeJsonError = e;
eprint(f"rgh: bad tree JSON at {why.at}");
return 1;
}
// ... print the tree ...
return 0;
}
The stream lane walks chunks — send, then loop:
let resp = await client.get(url).build().send();
let stream = resp.byte_stream();
while (true) {
let c = await stream.next();
if (c == nil) {
let rerr = stream.error();
if (rerr != nil) { return 1; } // failed mid-read
break; // clean end of stream
}
let chunk: bytes = c;
total += chunk.len();
}
Racing futures and the join tier
select2(a, b) races two futures and answers the first-ready side as
an Either2 (is_a()/a_value() or is_b()/b_value()); the losers
are cancelled, their drop paths running at their next checkpoint.
select_all(futs) extends the race to a cohort, answering (i, v).
Joining a launched future’s value (await handle) is still spelled in
the grammar but not in this build — the compiler gates it. See
launched futures for the race and
completer surfaces.
Parallelism
The language has none: a VM is single-threaded by construction (!Send,
one heap — the VM); async is the whole
concurrency story. A host that wants parallelism runs separate VMs —
rut defines no surface for sharing between them.
Put it together
use futures::{ launch_future, sleep };
use ink::{ Logger };
async fn countdown(log: Logger, n: u32) {
let mut i = n;
while (i > 0) {
log.info(f"t-{i}");
await sleep(500);
i -= 1;
}
log.info("lift-off");
}
entry fn main() {
let log = Logger("countdown");
launch_future(countdown(log, 3));
}
t-3
t-2
t-1
lift-off
Next: the standard library.