Bound how long a call may take
Goal: stop a handler waiting on a slow dependency for longer than it can afford, and say what it does instead.
Write within
Section titled “Write within”Add .within(d) to any effect. The result is a Result that is Err(TimedOut) when
the deadline passes first:
context shop.quote
consumes bynk
capability Pricing { fn quote(id: Int) -> Effect[Int]}
service quotes { on call(id: Int) -> Effect[String] by Caller given Pricing { let r <- Pricing.quote(id).within(2.seconds) match r { Ok(q) => Effect.pure("quoted \(q)"), Err(TimedOut { after, .. }) => Effect.pure("the quote is taking too long"), } }}TimedOut belongs to bynk, so the context needs consumes bynk (or consumes bynk { TimedOut }). within works on any
Effect, so it needs no support from the capability behind it.
If the effect already returns a Result, you get one more layer, and you unwrap both:
let r <- Pricing.tryQuote(id).within(3.seconds)match r { Ok(Ok(q)) => Effect.pure(true) Ok(Err(why)) => Effect.pure(false) Err(late) => Effect.pure(false)}Bound several calls at once
Section titled “Bound several calls at once”A lambda written in the handler can use within, and a par block bounds each of its
bindings alone:
let rs <- ids.parTraverseAll((id) => Pricing.quote(id).within(1.second))Where it is allowed
Section titled “Where it is allowed”In a service handler’s body, lambdas included, and in a function that a handler calls: the helper that knows a call is slow can bound it itself. The compiler passes the handler’s execution context down to the function, so nothing changes at the call site.
fn bounded(quote: Effect[Int]) -> Effect[Result[Int, TimedOut]] { quote.within(2.seconds)}An agent handler is refused (bynk.within.in_agent_handler), and so are a provider
operation and a WebSocket handler (bynk.within.outside_handler): they have no execution
context to hand a late effect to. Calling a function that uses within from one of those
is refused too (bynk.exec.unavailable), with a note that names the chain of calls down to
the within.
Test the timeout
Section titled “Test the timeout”A test runs within on virtual time, so it never sleeps. A stub can take time, or never
finish:
suite shop.quote { case "a slow quote times out" { stub Pricing.quote(_) returns 7 after 3.seconds let r <- quotes.call(1) expect r == "the quote is taking too long" }
case "a quote that never arrives times out" { stub Pricing.quote(_) never let r <- quotes.call(1) expect r == "the quote is taking too long" }}The harness moves its clock to the deadline for you, but only while every call in flight
is a stub waiting on after or never; a call into a real provider is waited for. See
testing.
For what a timeout does and does not stop, read what a timeout stops.