Safe, secure, reliable

A deadline for every wait

The problem
A program that waits for another service waits as long as that service takes. When the service is slow or gone, the answer the program owes its own callers is late too, and under load the waiting requests pile up.
An example
A page shows a price from a pricing service. The service stops answering, and every page that shows a price hangs with it.
What Nikaia checks
A task can be started with a deadline, async(within: d), and a handle can be waited for with one, join(within: d). When the time runs out, the task is cancelled at its next pause and ends with task::TimedOut. That is a failure like any other, so the compiler asks for it to be handled where the value is first needed, and a fallback written with catch stands in for it there. A handle that is still live where a join(within:) timed out is refused (NK2109), so a task is not left behind by accident.
The limit
The deadline is a protection while the program runs. The compiler checks that a timeout is handled, not that the time chosen is right. A task is cancelled where it pauses; a long calculation that never pauses runs to its next pause first. A limit on how many tasks of one group run at once is written async(limit: n) { … }, and the tasks over it wait, unstarted, until one ends.
Show the program and what Nikaia says
use std::time

fn lookup() -> String {
    time::sleep(2.seconds())
    return "fresh price"
}

fn render() -> String {
    let price = async(within: 100.millis()) lookup()
    let page = "the page"
    return f"{page} with the {price}"
}

fn main() throws {
    println(render())
}
$ nikaia check main.nika
error[NK2605]: This function can fail, because the deadline of `within:` can run out.
  --> main.nika:9:5
   |
 9 |     let price = async(within: 100.millis()) lookup()
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: When the deadline runs out, the task is cancelled and ends with `task::TimedOut` (ADR-async-v7 D16).
   = help: Add `throws` to `render`, or write a fallback: `async(within: d) … catch { … }`.

With a fallback, the page is rendered with the price the program already has:

use std::time

fn lookup() -> String {
    time::sleep(2.seconds())
    return "fresh price"
}

fn render() -> String {
    let price = async(within: 100.millis()) lookup() catch { "cached price" }
    let page = "the page"
    return f"{page} with the {price}"
}

fn main() throws {
    println(render())
}
$ nikaia run main.nika
the page with the cached price

More under Safe, secure, reliable: Errors that go unhandledData from outsideCalls that break a function's contractTwo tasks changing the same valueTasks that get stuckA memory budget for every task