Unreleased. Packages are not on crates.io, npm or opam yet. Use commit-pinned source.
Guide · 6
Timeouts and retries
Timers as Services, requests that wait with deadlines, retries whose late answers are stale, and timeout tests that never sleep.
A request sent over a network may be answered late, twice, or never. Code that waits for it usually needs a callback for the answer, a timer for the timeout, a flag they share to decide which came first, and a retry that must not be confused by the first attempt's answer when it finally arrives. Each piece runs on its own schedule, and the races between them are where the bugs are.
In causet a timeout is an Event, like the answer. A reducer asks the timer Service for one, pinned to the request it times out; the answer and the timer then reach the same reducer, one at a time, in the order the Store runs them. Whichever arrives first ends the request. The other finds nothing and is stale, and the reducer ignores it. A retry is a new request with a new ID, so a late answer to the old one is stale too.
This page covers the timer Service, a timeout per request, retries,
testing a timeout without waiting for it, keeping requests in Pending,
and one timer for many deadlines.
The timer Service
TimerCauset.TimerTimer is a Service like any other. An
Effect handler arms it with a delay, a reply and a request ID:
timer.after(delay, reply, request), where the delay is a DurationTimer.after timer ~delay reply request, where the delay is in nanosecondstimer.after(delay, reply, request), where the delay is in nanoseconds.
When the delay has passed, it sends
TimerFired { request }a Timer.fired, { request }a TimerFired, { kind: "causet.timer_fired", request },
of Event type causet.timer_fired, through the reply, into the worker
lane. It reaches the mount whose Effect made the reply, so one timer can
serve several mounts. Timers due at the same instant fire in the order they
were set. Arming never blocks.
The request is whatever the reducer pinned the timer to, usually the ID of the request it times out. Nothing cancels a timer once it is set: when the answer comes first, the timer's Event finds its request no longer pending and is stale. That is how a timeout is cancelled.
A component adapts the Event as it adapts any other:
it registers it with r.event::<TimerFired>() and implements Adapts<TimerFired>it registers Timer.fired with Registrar.eventit registers timerFired with r.event(timerFired, adapt),
turning it into one of its own Actions.
On native targets, Timer::new() starts a thread that waitsTimer.create () starts a thread that waitsTimer.create() makes one that waits, through setTimeout,
for the deadlines on its own monotonic clock, not on the Store's.
Services may keep their own clocks for their I/O; reducers only ever see
the Event, and read the time from the execution, as always
(the clock). When the worker lane is full,
the thread waits for roomthe thread waits for roomthe timer waits for room, 10 ms at a time,
and the timers due after it wait too.
Dropping the Timer, with the Services that own it, stops the thread and drops the timers that have not fired.Timer.stop stops the thread, and the timers that have not fired never will; after it, after sets nothing. Native socket wakeups work on Unix and Windows without a descriptor-number limit.timer.stop() clears its setTimeout, so it keeps nothing alive, and the timers that have not fired never will; after it, after sets nothing.
Timers driven by the host
A host with its own event loop can use
Timer::driven(clock)Timer.driven clockTimer.driven(clock)
with any clock. It returns the same timer Service and a control, without
starting a thread or arranging a callback. The host reads
control.next_deadline()Timer.Control.next_deadline controlcontrol.nextDeadline(),
arranges its own wakeup, and calls
control.fire_due()Timer.Control.fire_due controlcontrol.fireDue()
on the driver when due. Those calls publish Events through the worker
lane; only draining the Store runs their transitions.
use causet::{SystemClock, Timer};
let (timer, control) = Timer::driven(SystemClock::new());
// Put `timer` in Services. After each root input, arm the host's wakeup for:
let next = control.next_deadline();
// When the host wakes, publish due Events, then drain the Store as usual:
control.fire_due();open Causet
let () =
let timer, control = Timer.driven (Clock.system ()) in
(* Put [timer] in Services. After each root input, arm the host's wakeup for: *)
let next = Timer.Control.next_deadline control in
(* When the host wakes, publish due Events, then drain the Store as usual: *)
ignore (Timer.Control.fire_due control);
assert (next = None);
Timer.stop timerimport assert from "node:assert/strict";
import { systemClock, Timer } from "causet";
const clock = systemClock();
const { timer, control } = Timer.driven(clock);
// Put `timer` in Services. After each root input, arm the host's wakeup for
// the next deadline: nanoseconds on the timer's clock, as milliseconds, at
// most what setTimeout can wait. Waking early, the host finds nothing due.
const waitMs = (deadline: number): number =>
Math.min(2 ** 31 - 1, Math.max(0, (deadline - clock.now()) / 1e6));
const next = control.nextDeadline();
// When the host wakes, publish due Events, then drain the Store as usual:
control.fireDue();
assert.equal(next, undefined);
assert.equal(waitMs(clock.now() + 30 * 86_400e9), 2 ** 31 - 1);
timer.stop();Recheck the deadline after every root input, since it may have armed an
earlier timer. Use the timer clock's time to compute the host's wait; clocks
with different origins cannot have their deadlines compared directly.
Deadlines are nanoseconds, and setTimeout takes milliseconds, at most
2^31 - 1 (about 24.8 days): a longer delay overflows to 1 ms, so cap the
wait, and on waking early find nothing due and arm the next.
When the worker lane is full, the due timer and those after it stay pending
in deadline order. Drain some Events before retrying, so an overdue timer
does not make the driver spin.
The simulated timer below uses this same mechanism with a manual clock.
WebAssembly hosts use Timer::driven, since the threaded timer is
unavailable there.
A timeout per request
This component asks a supplier for a price. In the same reducer it makes a
request ID, keeps the request in a Pending table, and emits two Effects:
one sends the request, the other arms a timer pinned to it. The answer and
the timer each become an Action, and each tries to take the request:
use std::time::Duration;
use causet::*;
/// How long to wait for an answer, and how many times to ask.
const TIMEOUT: Duration = Duration::from_millis(100);
const ATTEMPTS: u32 = 2;
/// A supplier's answer.
#[derive(Debug, Event)]
#[causet(type = "quote.answer")]
struct Quoted {
request: RequestId,
price: u64,
}
/// Anything that can quote a price and answer later, from any thread.
trait Supplier: Send {
fn ask(&mut self, request: RequestId, item: String, reply: Reply<Quoted>);
}
struct QuoteServices {
supplier: Box<dyn Supplier>,
timer: Timer,
}
/// What an answer needs: the item asked about, and which attempt this is.
#[derive(Debug)]
struct Attempt {
item: String,
attempt: u32,
}
#[derive(Debug, Default)]
struct QuoteState {
waiting: Pending<Attempt>,
prices: Vec<(String, u64)>,
gave_up: Vec<String>,
/// Answers and timers for requests no longer pending.
stale: u32,
}
#[derive(Debug, Action)]
#[causet(type = "quote.action")]
enum QuoteAction {
Ask { item: String },
Answered { request: RequestId, price: u64 },
TimedOut { request: RequestId },
}
#[derive(Debug, Effect)]
#[causet(type = "quote.effect")]
enum QuoteEffect {
/// Sends the request to the supplier.
Send { request: RequestId, item: String },
/// Arms a timer pinned to the same request.
Arm { request: RequestId },
}
struct Quotes;
impl Component for Quotes {
type State = QuoteState;
type Service = QuoteServices;
type Action = QuoteAction;
type Effect = QuoteEffect;
type Output = Never;
fn reduce(mut ctx: ComponentContext<'_, Self>, action: QuoteAction, _: &ActionMeta) {
let (item, attempt) = match action {
QuoteAction::Ask { item } => (item, 1),
QuoteAction::Answered { request, price } => {
let state = ctx.state_mut();
match state.waiting.take(request) {
Some(Attempt { item, .. }) => state.prices.push((item, price)),
// Too late: it timed out, and was asked again.
None => state.stale += 1,
}
return;
}
QuoteAction::TimedOut { request } => {
let state = ctx.state_mut();
match state.waiting.take(request) {
Some(Attempt { item, attempt }) if attempt < ATTEMPTS => (item, attempt + 1),
Some(Attempt { item, .. }) => {
state.gave_up.push(item);
return;
}
// Answered in time: the timer is stale.
None => {
state.stale += 1;
return;
}
}
}
};
// Every attempt is a new request: an answer to an earlier one is stale.
let request = ctx.new_request();
ctx.state_mut().waiting.insert(request, Attempt { item: item.clone(), attempt });
let mut out = ctx.into_emitter();
out.emit_effect(QuoteEffect::Send { request, item });
out.emit_effect(QuoteEffect::Arm { request });
}
fn handle(mut ctx: EffectContext<'_, Self>, effect: QuoteEffect, _: &EffectMeta) {
match effect {
QuoteEffect::Send { request, item } => {
let reply = ctx.reply::<Quoted>();
ctx.service().supplier.ask(request, item, reply);
}
QuoteEffect::Arm { request } => {
let reply = ctx.reply::<TimerFired>();
ctx.service().timer.after(TIMEOUT, reply, request);
}
}
}
fn register(r: &mut ComponentRegistry<'_, Self>) {
r.event::<Quoted>();
r.event::<TimerFired>();
}
}
impl Adapts<Quoted> for Quotes {
fn adapt(Quoted { request, price }: Quoted, port: &mut ActionPort<'_, Self>) {
port.emit_action(QuoteAction::Answered { request, price });
}
}
impl Adapts<TimerFired> for Quotes {
fn adapt(fired: TimerFired, port: &mut ActionPort<'_, Self>) {
port.emit_action(QuoteAction::TimedOut { request: fired.request });
}
}(* How long to wait for an answer, in nanoseconds, and how many times to ask. *)
let quote_timeout = 100_000_000
let quote_attempts = 2
(* A supplier's answer. *)
type quoted = Quoted of { request : Request_id.t; price : int }
[@@deriving message ~name:"quote.answer"]
(* Anything that can quote a price and answer later, from any thread. *)
type supplier = { ask : Request_id.t -> string -> quoted reply -> unit }
type quote_services = { supplier : supplier; timer : Timer.t }
(* What an answer needs: the item asked about, and which attempt this is. *)
type quote_attempt = { item : string; attempt : int }
type quote_state = {
waiting : quote_attempt Pending.t;
prices : (string * int) list;
gave_up : string list;
stale : int; (** Answers and timers for requests no longer pending. *)
}
type quote_action =
| Ask_quote of { item : string }
| Quote_answered of { request : Request_id.t; price : int }
| Quote_timed_out of { request : Request_id.t }
[@@deriving message ~name:"quote.action"]
type quote_effect =
| Request_quote of { request : Request_id.t; item : string }
(** Sends the request to the supplier. *)
| Arm_quote_timer of { request : Request_id.t }
(** Arms a timer pinned to the same request. *)
[@@deriving message ~name:"quote.effect"]
(* Every attempt is a new request: an answer to an earlier one is stale. *)
let ask_again ctx item attempt =
let request = Ctx.new_request ctx in
Ctx.update ctx (fun s ->
{ s with waiting = Pending.add request { item; attempt } s.waiting });
Ctx.emit_effect ctx (Request_quote { request; item });
Ctx.emit_effect ctx (Arm_quote_timer { request })
let quotes : (quote_state, quote_services, quote_action, quote_effect, never) Component.t
=
Component.make ~name:"quotes" ~actions:quote_action_message
~effects:quote_effect_message ~outputs:Message.never
~reduce:(fun ctx action _ ->
let s = Ctx.state ctx in
match action with
| Ask_quote { item } -> ask_again ctx item 1
| Quote_answered { request; price } -> (
match Pending.take request s.waiting with
| Some ({ item; _ }, waiting) ->
Ctx.set_state ctx { s with waiting; prices = s.prices @ [ (item, price) ] }
(* Too late: it timed out, and was asked again. *)
| None -> Ctx.set_state ctx { s with stale = s.stale + 1 })
| Quote_timed_out { request } -> (
match Pending.take request s.waiting with
| Some ({ item; attempt }, waiting) when attempt < quote_attempts ->
Ctx.set_state ctx { s with waiting };
ask_again ctx item (attempt + 1)
| Some ({ item; _ }, waiting) ->
Ctx.set_state ctx { s with waiting; gave_up = s.gave_up @ [ item ] }
(* Answered in time: the timer is stale. *)
| None -> Ctx.set_state ctx { s with stale = s.stale + 1 }))
~handle:(fun ctx eff _ ->
let services = Effect_ctx.service ctx in
match eff with
| Request_quote { request; item } ->
services.supplier.ask request item (Effect_ctx.reply ctx quoted_message)
| Arm_quote_timer { request } ->
let reply = Effect_ctx.reply ctx Timer.fired in
Timer.after services.timer ~delay:quote_timeout reply request)
~register:(fun r ->
Registrar.event r quoted_message (fun (Quoted { request; price }) port ->
Port.emit_action port (Quote_answered { request; price }));
Registrar.event r Timer.fired (fun (fired : Timer.fired) port ->
Port.emit_action port (Quote_timed_out { request = fired.request })))
()import {
type Ctx,
component,
message,
type Pending,
type Reply,
type RequestId,
type Timer,
timerFired,
} from "causet";
/** How long to wait for an answer, in nanoseconds, and how many times to ask. */
const quoteTimeout = 100_000_000;
const quoteAttempts = 2;
/** A supplier's answer. */
type Quoted = {
readonly kind: "quote.answer";
readonly request: RequestId;
readonly price: number;
};
const quoted = message<Quoted>("quote.answer");
/** Anything that can quote a price and answer later, through the reply. */
interface Supplier {
ask(request: RequestId, item: string, reply: Reply<Quoted>): void;
}
interface QuoteServices {
readonly supplier: Supplier;
readonly timer: Timer;
}
/** What an answer needs: the item asked about, and which attempt this is. */
interface Attempt {
readonly item: string;
readonly attempt: number;
}
interface QuoteState {
readonly waiting: Pending<Attempt>;
readonly prices: ReadonlyArray<readonly [string, number]>;
readonly gaveUp: readonly string[];
/** Answers and timers for requests no longer pending. */
readonly stale: number;
}
type QuoteAction =
| { readonly kind: "quote.ask"; readonly item: string }
| { readonly kind: "quote.answered"; readonly request: RequestId; readonly price: number }
| { readonly kind: "quote.timed_out"; readonly request: RequestId };
const quoteAction = message<QuoteAction>("quote.action");
type QuoteEffect =
/** Sends the request to the supplier. */
| { readonly kind: "quote.send"; readonly request: RequestId; readonly item: string }
/** Arms a timer pinned to the same request. */
| { readonly kind: "quote.arm"; readonly request: RequestId };
const quoteEffect = message<QuoteEffect>("quote.effect");
type QuoteCtx = Ctx<QuoteState, QuoteServices, QuoteAction, QuoteEffect, never>;
// Every attempt is a new request: an answer to an earlier one is stale.
function askAgain(ctx: QuoteCtx, item: string, attempt: number): void {
const request = ctx.newRequest();
ctx.update((s) => ({ ...s, waiting: s.waiting.add(request, { item, attempt }) }));
ctx.emitEffect({ kind: "quote.send", request, item });
ctx.emitEffect({ kind: "quote.arm", request });
}
const quotes = component<QuoteState, QuoteServices>()({
name: "quotes",
actions: quoteAction,
effects: quoteEffect,
reduce(ctx, action) {
const s = ctx.state;
switch (action.kind) {
case "quote.ask":
askAgain(ctx, action.item, 1);
break;
case "quote.answered": {
const taken = s.waiting.take(action.request);
if (taken === undefined) {
// Too late: it timed out, and was asked again.
ctx.set({ ...s, stale: s.stale + 1 });
break;
}
const [{ item }, waiting] = taken;
ctx.set({ ...s, waiting, prices: [...s.prices, [item, action.price]] });
break;
}
case "quote.timed_out": {
const taken = s.waiting.take(action.request);
if (taken === undefined) {
// Answered in time: the timer is stale.
ctx.set({ ...s, stale: s.stale + 1 });
break;
}
const [{ item, attempt }, waiting] = taken;
if (attempt < quoteAttempts) {
ctx.set({ ...s, waiting });
askAgain(ctx, item, attempt + 1);
} else {
ctx.set({ ...s, waiting, gaveUp: [...s.gaveUp, item] });
}
break;
}
}
},
handle(ctx, effect) {
switch (effect.kind) {
case "quote.send":
ctx.service.supplier.ask(effect.request, effect.item, ctx.reply(quoted));
break;
case "quote.arm":
ctx.service.timer.after(quoteTimeout, ctx.reply(timerFired), effect.request);
break;
}
},
register(r) {
r.event(quoted, ({ request, price }, port) => {
port.emitAction({ kind: "quote.answered", request, price });
});
r.event(timerFired, (fired, port) => {
port.emitAction({ kind: "quote.timed_out", request: fired.request });
});
},
});The stale count is there for the test below to read. A component usually
ignores a stale input and keeps no count of it.
Retries
When the timer takes the request and attempts are left, the reducer asks again: a new request, with a new ID and a timer of its own. The first attempt's answer may still arrive. Its request is no longer pending, so it is stale, and it cannot be mistaken for the second attempt's answer, as it would be if the retry reused the first ID. After the last attempt, the component gives up.
The delay is the Effect's to choose, so a backoff is a delay that grows
with the attempt number. A failure answer can be retried the same way as a
timeout.
examples/downloads.rs does both: it retries a failure or a timeout once, then gives up, and ignores duplicate answers, late answers, and the timers of requests already answered.
Testing a timeout without waiting
A test should not sleep for a timeout to pass. The timer has a simulated
form, Timer::simulated(&clock)Timer.simulated clockTimer.simulated(clock),
with the same API, on a manual clock. It returns the timer, for the
Services, and its control, which the test hands to a
test node with
with_timerNode.with_timerwithTimer. A simulated timer's
deadline is the clock's time when it was armed plus the delay, and time
moves only when the test moves the clock.
fire_timersNode.fire_timersfireTimers fires the timers the clock
has reached, and their Events are held like any other until the test
delivers them; next_deadlineNode.next_deadlinenextDeadline says
when the next one is due.
The test decides whether the answer or the timer comes first. Here the supplier answers at once, the node holds the answer, and the timer fires before the answer is delivered:
use causet_test::Node;
const MS: u64 = 1_000_000;
/// Answers at once. A test node holds every Event until the test delivers
/// it, so the test decides when the answer arrives.
struct AtOnce;
impl Supplier for AtOnce {
fn ask(&mut self, request: RequestId, _item: String, reply: Reply<Quoted>) {
reply.try_send_as_worker(Quoted { request, price: 7 }).expect("held");
}
}
let clock = ManualClock::new(1_000 * MS);
let (timer, control) = Timer::simulated(&clock);
let services = QuoteServices { supplier: Box::new(AtOnce), timer };
let mut node = Node::new::<Quotes>("quotes", QuoteState::default(), services, SessionId(1), &clock)
.with_timer(control);
let quotes = node.mount(&root::<Quotes>());
node.dispatch("es, QuoteAction::Ask { item: "tea".into() });
assert_eq!(node.next_deadline(), Some(1_100 * MS));
// 100 ms pass before the answer is delivered: the timer fires first.
clock.advance(100 * MS);
assert_eq!(node.fire_timers(), 1);
assert!(node.deliver_where::<TimerFired>(|_| true));
// It asked again, as a new request with a timer of its own.
assert_eq!(node.state().waiting.values().map(|a| a.attempt).collect::<Vec<_>>(), [2]);
assert_eq!(node.next_deadline(), Some(1_200 * MS));
// The first answer arrives late, and is stale. The second is taken.
node.deliver_next();
assert_eq!(node.state().stale, 1);
node.deliver_next();
assert_eq!(node.state().prices, [("tea".to_string(), 7)]);
// The second timer fires after its answer, and finds nothing.
clock.advance(100 * MS);
assert_eq!(node.fire_timers(), 1);
node.deliver_next();
assert_eq!(node.state().stale, 2);
assert!(node.state().waiting.is_empty());open Causet
open Causet_test
let ms = 1_000_000
(* Answers at once. A test node holds every Event until the test delivers it,
so the test decides when the answer arrives. *)
let at_once =
{
ask =
(fun request _item reply ->
match Reply.try_send_as_worker reply (Quoted { request; price = 7 }) with
| Ok () -> ()
| Error _ -> failwith "held");
}
let () =
let clock = Clock.Manual.create (1_000 * ms) in
let timer, control = Timer.simulated clock in
let state = { waiting = Pending.empty; prices = []; gave_up = []; stale = 0 } in
let node =
Node.create ~name:"quotes" quotes ~state ~services:{ supplier = at_once; timer }
~session:1 clock
in
let node = Node.with_timer node control in
let m = Node.mount node (Path.root quotes) in
ignore (Node.dispatch node m (Ask_quote { item = "tea" }));
assert (Node.next_deadline node = Some (1_100 * ms));
(* 100 ms pass before the answer is delivered: the timer fires first. *)
Clock.Manual.advance clock (100 * ms);
assert (Node.fire_timers node = 1);
assert (Node.deliver_where node Timer.fired (fun _ -> true));
(* It asked again, as a new request with a timer of its own. *)
let attempts s = List.map (fun a -> a.attempt) (Pending.values s.waiting) in
assert (attempts (Node.state node) = [ 2 ]);
assert (Node.next_deadline node = Some (1_200 * ms));
(* The first answer arrives late, and is stale. The second is taken. *)
ignore (Node.deliver_next node);
assert ((Node.state node).stale = 1);
ignore (Node.deliver_next node);
assert ((Node.state node).prices = [ ("tea", 7) ]);
(* The second timer fires after its answer, and finds nothing. *)
Clock.Manual.advance clock (100 * ms);
assert (Node.fire_timers node = 1);
ignore (Node.deliver_next node);
assert ((Node.state node).stale = 2);
assert (Pending.is_empty (Node.state node).waiting)import assert from "node:assert/strict";
import { ManualClock, Pending, rootPath, Timer, timerFired } from "causet";
import { Node } from "causet/test";
const ms = 1_000_000;
// Answers at once. A test node holds every Event until the test delivers it,
// so the test decides when the answer arrives.
const atOnce: Supplier = {
ask(request, _item, reply) {
const sent = reply.trySendAsWorker({ kind: "quote.answer", request, price: 7 });
if (!sent.ok) throw new Error("held");
},
};
const clock = new ManualClock(1_000 * ms);
const { timer, control } = Timer.simulated(clock);
const state: QuoteState = { waiting: Pending.empty(), prices: [], gaveUp: [], stale: 0 };
const node = Node.create("quotes", quotes, {
state,
services: { supplier: atOnce, timer },
session: 1,
clock,
}).withTimer(control);
const m = node.mount(rootPath(quotes));
node.dispatch(m, { kind: "quote.ask", item: "tea" });
assert.equal(node.nextDeadline(), 1_100 * ms);
// 100 ms pass before the answer is delivered: the timer fires first.
clock.advance(100 * ms);
assert.equal(node.fireTimers(), 1);
assert.ok(node.deliverWhere(timerFired, () => true));
// It asked again, as a new request with a timer of its own.
assert.deepEqual(
node.state.waiting.values().map((a) => a.attempt),
[2],
);
assert.equal(node.nextDeadline(), 1_200 * ms);
// The first answer arrives late, and is stale. The second is taken.
node.deliverNext();
assert.equal(node.state.stale, 1);
node.deliverNext();
assert.deepEqual(node.state.prices, [["tea", 7]]);
// The second timer fires after its answer, and finds nothing.
clock.advance(100 * ms);
assert.equal(node.fireTimers(), 1);
node.deliverNext();
assert.equal(node.state.stale, 2);
assert.ok(node.state.waiting.isEmpty());A scenario does the same for several nodes: when nothing is held, it moves the clock to the next timer deadline and fires the timers that are due.
Keeping requests: Pending
Pending holds the requests a component waits on, in its State: for
each, what the reducer needs to handle the answer, and an optional
deadline. The examples on this page keep their requests in it, and so do
the shop's payments, their charges
(one checkout, step by step).
Its methods change it in place.A table is a value, like the rest of State: each change returns a new one.A table is a value, like the rest of State: each change returns a new one.
Requests are kept in ID order, the order they were made in a Store's run.
insert(request, value)Pending.add request valueadd(request, value)waits on a request, andinsert_until(request, value, deadline)Pending.add ~deadline request valueadd(request, value, deadline)waits on it until a deadline as well.take(request)Pending.take requesttake(request)is what the answer and a timer pinned to the request call. The first gets the value, and the request is no longer waited on; the second gets nothing.cancel(request)Pending.cancel requestcancel(request)stops waiting without an answer. The answer, when it comes, is stale.retain(keep)Pending.retain keepretain(keep)stops waiting on every requestkeeprejects, such as every request of a piece of work that has ended.clear()Pending.clearclear()stops waiting on all of them, such as when a new request replaces the one in flight: clear, then wait on the new one, and the old answer is stale.
use causet::{ExecutionId, Pending, RequestId, SessionId};
// Request IDs as a reducer's `new_request` makes them.
let request = |index| RequestId { session: SessionId(1), execution: ExecutionId(1), index };
let mut pending = Pending::new();
// The first of the answer and the timer takes the request; the second is stale.
pending.insert(request(0), "tea");
assert_eq!(pending.take(request(0)), Some("tea"));
assert_eq!(pending.take(request(0)), None);
// Cancelled: its answer, when it comes, is stale.
pending.insert(request(1), "coffee");
pending.cancel(request(1));
assert_eq!(pending.take(request(1)), None);
// Order 7 ended: so did every request made for it.
pending.insert(request(2), "order 7");
pending.insert(request(3), "order 8");
pending.retain(|_, work| *work != "order 7");
assert_eq!(pending.take(request(2)), None);
// A new search replaces the one in flight.
pending.insert(request(4), "first search");
pending.clear();
pending.insert(request(5), "second search");
assert_eq!(pending.take(request(4)), None);
assert_eq!(pending.len(), 1);let () =
(* Request IDs as a reducer's [Ctx.new_request] makes them. *)
let request index = { Request_id.session = 1; execution = 1; index } in
let stale r pending = Option.is_none (Pending.take r pending) in
(* The first of the answer and the timer takes the request; the second is stale. *)
let pending = Pending.add (request 0) "tea" Pending.empty in
let pending =
match Pending.take (request 0) pending with
| Some ("tea", pending) -> pending
| _ -> assert false
in
assert (stale (request 0) pending);
(* Cancelled: its answer, when it comes, is stale. *)
let pending = Pending.add (request 1) "coffee" pending |> Pending.cancel (request 1) in
assert (stale (request 1) pending);
(* Order 7 ended: so did every request made for it. *)
let pending =
pending
|> Pending.add (request 2) "order 7"
|> Pending.add (request 3) "order 8"
|> Pending.retain (fun _ work -> work <> "order 7")
in
assert (stale (request 2) pending);
(* A new search replaces the one in flight. *)
let pending =
pending
|> Pending.add (request 4) "first search"
|> Pending.clear
|> Pending.add (request 5) "second search"
in
assert (stale (request 4) pending);
assert (Pending.cardinal pending = 1)import assert from "node:assert/strict";
import { Pending, RequestId } from "causet";
// Request IDs as a reducer's `ctx.newRequest()` makes them.
const request = (index: number) => new RequestId(1, 1, index);
const stale = (pending: Pending<string>, r: RequestId) => pending.take(r) === undefined;
// The first of the answer and the timer takes the request; the second is stale.
let pending = Pending.empty<string>().add(request(0), "tea");
const [value, rest] = pending.take(request(0)) ?? assert.fail("tea is pending");
assert.equal(value, "tea");
pending = rest;
assert.ok(stale(pending, request(0)));
// Cancelled: its answer, when it comes, is stale.
pending = pending.add(request(1), "coffee").cancel(request(1));
assert.ok(stale(pending, request(1)));
// Order 7 ended: so did every request made for it.
pending = pending
.add(request(2), "order 7")
.add(request(3), "order 8")
.retain((_, work) => work !== "order 7");
assert.ok(stale(pending, request(2)));
// A new search replaces the one in flight.
pending = pending.add(request(4), "first search").clear().add(request(5), "second search");
assert.ok(stale(pending, request(4)));
assert.equal(pending.size, 1);With causet's serde feature, Pending serializes, as a list of pairs,
with the rest of a State that derives serde.
Pending keeps its requests in a private field, which
assert.deepStrictEqual and JSON.stringify do not see: two tables
compare with equals, and one is saved through entries() and
deadline(request).
Why take does not look at the time
take does not compare the time a timer fired with the request's deadline.
A threaded timer keeps its own monotonic clock, and the Store's clock can
move apart from it: the Store's clock takes corrections and notices a
device's sleep, which a monotonic clock may not. If take refused a timer
that arrived before the deadline by the Store's clock, the timeout would be
dropped, and nothing would ever end the request. So the timer pinned to a
request ends it, whenever it arrives.
The deadlines kept in Pending are read only by
next_deadline and expirePending.next_deadline and Pending.expirenextDeadline and expire,
for one timer that serves many requests.
One timer for the earliest deadline
A component that waits on many requests can keep one timer instead of one
each. Each request is kept with its deadline, and the timer is armed for
the earliest, next_deadline()Pending.next_deadlinenextDeadline().
When it fires, expire(now)Pending.expire nowexpire(now) takes
every request whose deadline has come by the execution's time, in deadline
order and then request order, and the timer is armed again for what is
left.
The timer is pinned to a request ID of its own, kept in State with the deadline it is armed for. When a new request's deadline comes before that one, the component arms a new timer, and the old one, when it fires, finds a different ID and is stale.
expire does compare deadlines with the time, the execution's. If a
threaded timer fires early by the Store's clock, nothing is due yet; the
component arms again for the earliest deadline, which is still there, and
the next timer expires it.
use std::time::Duration;
use causet::*;
const MS: Timestamp = 1_000_000;
/// The directory's answer.
#[derive(Debug, Event)]
#[causet(type = "lookup.answer")]
struct Listing {
request: RequestId,
number: u64,
}
/// Anything that can look a name up and answer later, from any thread.
trait Directory: Send {
fn find(&mut self, request: RequestId, name: String, reply: Reply<Listing>);
}
struct LookupServices {
directory: Box<dyn Directory>,
timer: Timer,
}
#[derive(Debug, Default)]
struct LookupState {
/// Each lookup's name, until its deadline.
lookups: Pending<String>,
/// The one timer armed: its own request, and the deadline it is for.
armed: Option<(RequestId, Timestamp)>,
found: Vec<(String, u64)>,
expired: Vec<String>,
}
#[derive(Debug, Action)]
#[causet(type = "lookup.action")]
enum LookupAction {
Find { name: String, wait_ms: u64 },
Answered { request: RequestId, number: u64 },
Sweep { timer: RequestId },
}
#[derive(Debug, Effect)]
#[causet(type = "lookup.effect")]
enum LookupEffect {
Ask { request: RequestId, name: String },
/// Arms the one timer, `delay` nanoseconds from now.
Arm { timer: RequestId, delay: Timestamp },
}
struct Lookups;
impl Component for Lookups {
type State = LookupState;
type Service = LookupServices;
type Action = LookupAction;
type Effect = LookupEffect;
type Output = Never;
fn reduce(mut ctx: ComponentContext<'_, Self>, action: LookupAction, meta: &ActionMeta) {
let now = meta.time;
let mut ask = None;
match action {
LookupAction::Find { name, wait_ms } => {
let request = ctx.new_request();
ctx.state_mut().lookups.insert_until(request, name.clone(), now + wait_ms * MS);
ask = Some(LookupEffect::Ask { request, name });
}
LookupAction::Answered { request, number } => {
let state = ctx.state_mut();
// Stale once expired: the deadline came first.
if let Some(name) = state.lookups.take(request) {
state.found.push((name, number));
}
}
LookupAction::Sweep { timer } => {
let state = ctx.state_mut();
// A timer replaced by an earlier one is stale.
if state.armed.is_some_and(|(armed, _)| armed == timer) {
state.armed = None;
let due = state.lookups.expire(now);
state.expired.extend(due.into_iter().map(|(_, name)| name));
}
}
}
// One timer, for the earliest deadline: armed when none is, or when
// a deadline comes before the one it is armed for.
let earliest = ctx.state().lookups.next_deadline();
let arm = match (earliest, ctx.state().armed) {
(Some(at), None) => Some(at),
(Some(at), Some((_, armed_at))) if at < armed_at => Some(at),
_ => None,
};
let arm = arm.map(|at| {
let timer = ctx.new_request();
ctx.state_mut().armed = Some((timer, at));
LookupEffect::Arm { timer, delay: at.saturating_sub(now) }
});
let mut out = ctx.into_emitter();
for effect in ask.into_iter().chain(arm) {
out.emit_effect(effect);
}
}
fn handle(mut ctx: EffectContext<'_, Self>, effect: LookupEffect, _: &EffectMeta) {
match effect {
LookupEffect::Ask { request, name } => {
let reply = ctx.reply::<Listing>();
ctx.service().directory.find(request, name, reply);
}
LookupEffect::Arm { timer, delay } => {
let reply = ctx.reply::<TimerFired>();
ctx.service().timer.after(Duration::from_nanos(delay), reply, timer);
}
}
}
fn register(r: &mut ComponentRegistry<'_, Self>) {
r.event::<Listing>();
r.event::<TimerFired>();
}
}
impl Adapts<Listing> for Lookups {
fn adapt(Listing { request, number }: Listing, port: &mut ActionPort<'_, Self>) {
port.emit_action(LookupAction::Answered { request, number });
}
}
impl Adapts<TimerFired> for Lookups {
fn adapt(fired: TimerFired, port: &mut ActionPort<'_, Self>) {
port.emit_action(LookupAction::Sweep { timer: fired.request });
}
}(* The directory's answer. *)
type listing = Listing of { request : Request_id.t; number : int }
[@@deriving message ~name:"lookup.answer"]
(* Anything that can look a name up and answer later, from any thread. *)
type directory = { find : Request_id.t -> string -> listing reply -> unit }
type lookup_services = { directory : directory; timer : Timer.t }
type lookup_state = {
lookups : string Pending.t; (** Each lookup's name, until its deadline. *)
armed : (Request_id.t * int) option;
(** The one timer armed: its own request, and the deadline it is for. *)
found : (string * int) list;
expired : string list;
}
type lookup_action =
| Look_up of { name : string; wait_ms : int }
| Listed of { request : Request_id.t; number : int }
| Sweep of { timer : Request_id.t }
[@@deriving message ~name:"lookup.action"]
type lookup_effect =
| Query of { request : Request_id.t; name : string }
| Arm_sweep of { timer : Request_id.t; delay : int }
(** Arms the one timer, [delay] nanoseconds from now. *)
[@@deriving message ~name:"lookup.effect"]
let lookup_ms = 1_000_000
(* One timer, for the earliest deadline: armed when none is, or when a deadline
comes before the one it is armed for. *)
let arm_earliest ctx now =
let s = Ctx.state ctx in
let arm_at at =
let timer = Ctx.new_request ctx in
Ctx.set_state ctx { s with armed = Some (timer, at) };
Some (Arm_sweep { timer; delay = at - now })
in
match (Pending.next_deadline s.lookups, s.armed) with
| Some at, None -> arm_at at
| Some at, Some (_, armed_at) when at < armed_at -> arm_at at
| _ -> None
let lookups :
(lookup_state, lookup_services, lookup_action, lookup_effect, never) Component.t =
Component.make ~name:"lookups" ~actions:lookup_action_message
~effects:lookup_effect_message ~outputs:Message.never
~reduce:(fun ctx action (meta : Meta.t) ->
let now = meta.time in
let s = Ctx.state ctx in
let ask =
match action with
| Look_up { name; wait_ms } ->
let request = Ctx.new_request ctx in
let deadline = now + (wait_ms * lookup_ms) in
Ctx.set_state ctx
{ s with lookups = Pending.add ~deadline request name s.lookups };
Some (Query { request; name })
| Listed { request; number } ->
(* Stale once expired: the deadline came first. *)
(match Pending.take request s.lookups with
| Some (name, lookups) ->
Ctx.set_state ctx { s with lookups; found = s.found @ [ (name, number) ] }
| None -> ());
None
| Sweep { timer } ->
(* A timer replaced by an earlier one is stale. *)
(match s.armed with
| Some (armed, _) when armed = timer ->
let due, lookups = Pending.expire now s.lookups in
Ctx.set_state ctx
{ s with lookups; armed = None; expired = s.expired @ List.map snd due }
| _ -> ());
None
in
let arm = arm_earliest ctx now in
Option.iter (Ctx.emit_effect ctx) ask;
Option.iter (Ctx.emit_effect ctx) arm)
~handle:(fun ctx eff _ ->
let services = Effect_ctx.service ctx in
match eff with
| Query { request; name } ->
services.directory.find request name (Effect_ctx.reply ctx listing_message)
| Arm_sweep { timer; delay } ->
Timer.after services.timer ~delay (Effect_ctx.reply ctx Timer.fired) timer)
~register:(fun r ->
Registrar.event r listing_message (fun (Listing { request; number }) port ->
Port.emit_action port (Listed { request; number }));
Registrar.event r Timer.fired (fun (fired : Timer.fired) port ->
Port.emit_action port (Sweep { timer = fired.request })))
()import {
component,
message,
type Pending,
type Reply,
type RequestId,
type Timer,
type Timestamp,
timerFired,
} from "causet";
const ms = 1_000_000;
/** The directory's answer. */
type Listing = {
readonly kind: "lookup.answer";
readonly request: RequestId;
readonly number: number;
};
const listing = message<Listing>("lookup.answer");
/** Anything that can look a name up and answer later, through the reply. */
interface Directory {
find(request: RequestId, name: string, reply: Reply<Listing>): void;
}
interface LookupServices {
readonly directory: Directory;
readonly timer: Timer;
}
interface LookupState {
/** Each lookup's name, until its deadline. */
readonly lookups: Pending<string>;
/** The one timer armed: its own request, and the deadline it is for. */
readonly armed: { readonly timer: RequestId; readonly at: Timestamp } | undefined;
readonly found: ReadonlyArray<readonly [string, number]>;
readonly expired: readonly string[];
}
type LookupAction =
| { readonly kind: "lookup.find"; readonly name: string; readonly waitMs: number }
| { readonly kind: "lookup.answered"; readonly request: RequestId; readonly number: number }
| { readonly kind: "lookup.sweep"; readonly timer: RequestId };
const lookupAction = message<LookupAction>("lookup.action");
type LookupEffect =
| { readonly kind: "lookup.ask"; readonly request: RequestId; readonly name: string }
/** Arms the one timer, `delay` nanoseconds from now. */
| { readonly kind: "lookup.arm"; readonly timer: RequestId; readonly delay: number };
const lookupEffect = message<LookupEffect>("lookup.effect");
const lookups = component<LookupState, LookupServices>()({
name: "lookups",
actions: lookupAction,
effects: lookupEffect,
reduce(ctx, action, meta) {
const now = meta.time;
let ask: LookupEffect | undefined;
switch (action.kind) {
case "lookup.find": {
const request = ctx.newRequest();
const deadline = now + action.waitMs * ms;
ctx.update((s) => ({ ...s, lookups: s.lookups.add(request, action.name, deadline) }));
ask = { kind: "lookup.ask", request, name: action.name };
break;
}
case "lookup.answered": {
const s = ctx.state;
// Stale once expired: the deadline came first.
const taken = s.lookups.take(action.request);
if (taken !== undefined) {
const [name, lookups] = taken;
ctx.set({ ...s, lookups, found: [...s.found, [name, action.number]] });
}
break;
}
case "lookup.sweep": {
const s = ctx.state;
// A timer replaced by an earlier one is stale.
if (s.armed?.timer.equals(action.timer)) {
const [due, lookups] = s.lookups.expire(now);
const expired = [...s.expired, ...due.map(([, name]) => name)];
ctx.set({ ...s, lookups, armed: undefined, expired });
}
break;
}
}
// One timer, for the earliest deadline: armed when none is, or when a
// deadline comes before the one it is armed for.
const s = ctx.state;
const at = s.lookups.nextDeadline();
let arm: LookupEffect | undefined;
if (at !== undefined && (s.armed === undefined || at < s.armed.at)) {
const timer = ctx.newRequest();
ctx.set({ ...s, armed: { timer, at } });
arm = { kind: "lookup.arm", timer, delay: Math.max(0, at - now) };
}
if (ask !== undefined) ctx.emitEffect(ask);
if (arm !== undefined) ctx.emitEffect(arm);
},
handle(ctx, effect) {
switch (effect.kind) {
case "lookup.ask":
ctx.service.directory.find(effect.request, effect.name, ctx.reply(listing));
break;
case "lookup.arm":
ctx.service.timer.after(effect.delay, ctx.reply(timerFired), effect.timer);
break;
}
},
register(r) {
r.event(listing, ({ request, number }, port) => {
port.emitAction({ kind: "lookup.answered", request, number });
});
r.event(timerFired, (fired, port) => {
port.emitAction({ kind: "lookup.sweep", timer: fired.request });
});
},
});Three lookups wait 300, 100 and 200 ms; one answer arrives in time, and the other two requests expire in deadline order:
use causet_test::Node;
/// Answers at once; the test node holds the answers.
struct AtOnce;
impl Directory for AtOnce {
fn find(&mut self, request: RequestId, name: String, reply: Reply<Listing>) {
let number = name.len() as u64;
reply.try_send_as_worker(Listing { request, number }).expect("held");
}
}
let clock = ManualClock::new(1_000 * MS);
let (timer, control) = Timer::simulated(&clock);
let services = LookupServices { directory: Box::new(AtOnce), timer };
let mut node = Node::new::<Lookups>("lookups", LookupState::default(), services, SessionId(1), &clock)
.with_timer(control);
let lookups = node.mount(&root::<Lookups>());
node.dispatch(&lookups, LookupAction::Find { name: "ada".into(), wait_ms: 300 });
assert_eq!(node.next_deadline(), Some(1_300 * MS));
// An earlier deadline: a new timer, and the first one is stale.
node.dispatch(&lookups, LookupAction::Find { name: "bob".into(), wait_ms: 100 });
node.dispatch(&lookups, LookupAction::Find { name: "cy".into(), wait_ms: 200 });
assert_eq!(node.next_deadline(), Some(1_100 * MS));
// Only cy's answer arrives in time.
let answers = node.held();
node.deliver(answers[2].id);
assert_eq!(node.state().found, [("cy".to_string(), 2)]);
// At 1,100 ms bob expires, and the timer is armed again, for ada.
clock.advance(100 * MS);
assert_eq!(node.fire_timers(), 1);
assert!(node.deliver_where::<TimerFired>(|_| true));
assert_eq!(node.state().expired, ["bob"]);
assert_eq!(node.next_deadline(), Some(1_300 * MS));
// At 1,300 ms two timers fire: the stale first one finds nothing.
clock.advance(200 * MS);
assert_eq!(node.fire_timers(), 2);
while node.deliver_where::<TimerFired>(|_| true) {}
assert_eq!(node.state().expired, ["bob", "ada"]);
// The answers for ada and bob arrive late, and are stale.
node.deliver(answers[0].id);
node.deliver(answers[1].id);
assert_eq!(node.state().found, [("cy".to_string(), 2)]);
assert!(node.state().lookups.is_empty());(* Answers at once; the test node holds the answers. *)
let at_once =
{
find =
(fun request name reply ->
let number = String.length name in
match Reply.try_send_as_worker reply (Listing { request; number }) with
| Ok () -> ()
| Error _ -> failwith "held");
}
let () =
let clock = Clock.Manual.create (1_000 * ms) in
let timer, control = Timer.simulated clock in
let state = { lookups = Pending.empty; armed = None; found = []; expired = [] } in
let node =
Node.create ~name:"lookups" lookups ~state ~services:{ directory = at_once; timer }
~session:1 clock
in
let node = Node.with_timer node control in
let m = Node.mount node (Path.root lookups) in
ignore (Node.dispatch node m (Look_up { name = "ada"; wait_ms = 300 }));
assert (Node.next_deadline node = Some (1_300 * ms));
(* An earlier deadline: a new timer, and the first one is stale. *)
ignore (Node.dispatch node m (Look_up { name = "bob"; wait_ms = 100 }));
ignore (Node.dispatch node m (Look_up { name = "cy"; wait_ms = 200 }));
assert (Node.next_deadline node = Some (1_100 * ms));
(* Only cy's answer arrives in time. *)
let answers = List.map (fun (e : held_event) -> e.held_id) (Node.held node) in
Node.deliver node (List.nth answers 2);
assert ((Node.state node).found = [ ("cy", 2) ]);
(* At 1,100 ms bob expires, and the timer is armed again, for ada. *)
Clock.Manual.advance clock (100 * ms);
assert (Node.fire_timers node = 1);
assert (Node.deliver_where node Timer.fired (fun _ -> true));
assert ((Node.state node).expired = [ "bob" ]);
assert (Node.next_deadline node = Some (1_300 * ms));
(* At 1,300 ms two timers fire: the stale first one finds nothing. *)
Clock.Manual.advance clock (200 * ms);
assert (Node.fire_timers node = 2);
while Node.deliver_where node Timer.fired (fun _ -> true) do () done;
assert ((Node.state node).expired = [ "bob"; "ada" ]);
(* The answers for ada and bob arrive late, and are stale. *)
Node.deliver node (List.nth answers 0);
Node.deliver node (List.nth answers 1);
assert ((Node.state node).found = [ ("cy", 2) ]);
assert (Pending.is_empty (Node.state node).lookups)import assert from "node:assert/strict";
import { ManualClock, Pending, rootPath, Timer, timerFired } from "causet";
import { Node } from "causet/test";
// Answers at once; the test node holds the answers.
const atOnce: Directory = {
find(request, name, reply) {
const sent = reply.trySendAsWorker({ kind: "lookup.answer", request, number: name.length });
if (!sent.ok) throw new Error("held");
},
};
const clock = new ManualClock(1_000 * ms);
const { timer, control } = Timer.simulated(clock);
const state: LookupState = { lookups: Pending.empty(), armed: undefined, found: [], expired: [] };
const node = Node.create("lookups", lookups, {
state,
services: { directory: atOnce, timer },
session: 1,
clock,
}).withTimer(control);
const m = node.mount(rootPath(lookups));
node.dispatch(m, { kind: "lookup.find", name: "ada", waitMs: 300 });
assert.equal(node.nextDeadline(), 1_300 * ms);
// An earlier deadline: a new timer, and the first one is stale.
node.dispatch(m, { kind: "lookup.find", name: "bob", waitMs: 100 });
node.dispatch(m, { kind: "lookup.find", name: "cy", waitMs: 200 });
assert.equal(node.nextDeadline(), 1_100 * ms);
// Only cy's answer arrives in time.
const [ada, bob, cy] = node.held().map((e) => e.id) as [number, number, number];
node.deliver(cy);
assert.deepEqual(node.state.found, [["cy", 2]]);
// At 1,100 ms bob expires, and the timer is armed again, for ada.
clock.advance(100 * ms);
assert.equal(node.fireTimers(), 1);
assert.ok(node.deliverWhere(timerFired, () => true));
assert.deepEqual(node.state.expired, ["bob"]);
assert.equal(node.nextDeadline(), 1_300 * ms);
// At 1,300 ms two timers fire: the stale first one finds nothing.
clock.advance(200 * ms);
assert.equal(node.fireTimers(), 2);
while (node.deliverWhere(timerFired, () => true)) {}
assert.deepEqual(node.state.expired, ["bob", "ada"]);
// The answers for ada and bob arrive late, and are stale.
node.deliver(ada);
node.deliver(bob);
assert.deepEqual(node.state.found, [["cy", 2]]);
assert.ok(node.state.lookups.isEmpty());A timer per request is the simpler of the two: its Event names the request it ends. One timer for the earliest deadline keeps a single timer armed however many requests wait, and keeps every deadline in State, where an invariant or a test can read it.
NextDeterminismWhat application code must do so a run can be repeated.