Skip to main content

id_effect/
race.rs

1//! Racing and timeouts on fibers: [`Effect::race`], [`race_all`], [`Effect::race_first`],
2//! [`Effect::timeout`] and [`Effect::timeout_fail`].
3//!
4//! Every racer runs as a child fiber of the racing fiber (so the racer's interruption reaches
5//! them, and its exit awaits them). Semantics follow Effect.ts:
6//!
7//! - **`race` / `race_all`** (`Effect.race`, `Effect.raceAll`): the first *success* wins. The
8//!   other racers are interrupted and awaited, so their finalizers have run before the result is
9//!   returned. A failure does not end the race; when every racer fails, the race fails with all
10//!   the causes combined by `Cause::Both` in input order (`race(a, b)` fails with
11//!   `Both(cause_a, cause_b)`, like Effect.ts `Cause.parallel`). Effect.ts `raceAll` keeps only
12//!   the last failure; here `race_all` keeps every one, so `race_all([a, b])` and `a.race(b)`
13//!   agree.
14//! - **`race_first`** (`Effect.raceFirst`): the first racer to *complete* wins, success or
15//!   failure, and the other is interrupted and awaited.
16//! - **`timeout`** (`Effect.timeout`) is `race_first` against a sleep on the fiber's executor
17//!   clock (virtual time on `TestExecutor`). The Rust shape returns `Option<A>`: `Some(a)` when
18//!   the effect finished first, `None` when the deadline passed. The Effect.ts 3.x
19//!   `TimeoutException` error channel is the separate [`Effect::timeout_fail`], which fails with
20//!   an error built by the caller instead. A failure of the effect before the deadline is
21//!   re-raised as is. Because the interrupted racer is awaited, an uninterruptible (masked)
22//!   effect delays the timeout until it completes; the result is still `None`.
23//!
24//! `race_all` of no effects dies (as Effect.ts `raceAll` of an empty iterable does).
25
26use std::future::Future;
27use std::pin::Pin;
28use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
29use std::task::{Context, Poll, Wake, Waker};
30use std::time::Duration;
31
32use crate::failure::Cause;
33use crate::kernel::{AnyBox, AnyExit, Effect, Instr, die, fail, sleep, succeed};
34use crate::runtime::{FiberCell, FiberContext, spawn_fiber};
35
36/// Which outcome ends a race.
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38enum Mode {
39  /// The first success wins; failures are collected (`race`, `race_all`).
40  FirstSuccess,
41  /// The first completion wins, success or failure (`race_first`, `timeout`).
42  FirstExit,
43}
44
45impl<A, E, R> Effect<A, E, R>
46where
47  A: Send + 'static,
48  E: Send + 'static,
49  R: Send + Sync + 'static,
50{
51  /// Races this effect against `that` (Effect.ts `Effect.race`): the first success wins, and the
52  /// loser is interrupted and awaited (its finalizers have run) before the result is returned.
53  /// When both fail, the race fails with `Cause::Both(self_cause, that_cause)`.
54  ///
55  /// ```
56  /// use std::time::Duration;
57  ///
58  /// use id_effect::Exit;
59  /// use id_effect::{Effect, sleep, succeed};
60  ///
61  /// let slow: Effect<&str> = sleep(Duration::from_secs(3600)).map(|()| "slow");
62  /// let fast: Effect<&str> = succeed("fast");
63  /// assert_eq!(slow.race(fast).block_on(), Exit::succeed("fast"));
64  /// ```
65  pub fn race(self, that: Effect<A, E, R>) -> Effect<A, E, R> {
66    race_with(vec![self, that], Mode::FirstSuccess)
67  }
68
69  /// Races this effect against `that` (Effect.ts `Effect.raceFirst`): the first to complete
70  /// wins, whether it succeeded or failed, and the other is interrupted and awaited.
71  pub fn race_first(self, that: Effect<A, E, R>) -> Effect<A, E, R> {
72    race_with(vec![self, that], Mode::FirstExit)
73  }
74
75  /// Bounds this effect by `d` on the fiber's executor clock (Effect.ts `Effect.timeout`):
76  /// `Some(a)` when it finished in time, `None` once `d` has passed (the effect is then
77  /// interrupted and awaited, so a masked effect delays the `None`). A failure before the
78  /// deadline is re-raised.
79  ///
80  /// On a [`TestExecutor`](crate::TestExecutor) the deadline is virtual time:
81  ///
82  /// ```
83  /// use std::sync::Arc;
84  /// use std::time::Duration;
85  ///
86  /// use id_effect::{Effect, TestExecutor, sleep};
87  ///
88  /// let exec = TestExecutor::new();
89  /// let slow: Effect<u8> = sleep(Duration::from_secs(60)).map(|()| 1);
90  /// let h = slow
91  ///   .timeout(Duration::from_secs(10))
92  ///   .fork_root(Arc::new(exec.clone()));
93  /// exec.advance(Duration::from_secs(9));
94  /// assert!(!h.is_done());
95  /// exec.advance(Duration::from_secs(1));
96  /// assert!(h.is_done(), "timed out at virtual 10 s");
97  /// ```
98  pub fn timeout(self, d: Duration) -> Effect<Option<A>, E, R> {
99    let timer: Effect<Option<A>, E, R> = sleep(d).map(|()| None);
100    race_with(vec![self.map(Some), timer], Mode::FirstExit)
101  }
102
103  /// Like [`timeout`](Effect::timeout), but fails with `on_timeout()` once `d` has passed
104  /// (Effect.ts `Effect.timeoutFail`).
105  pub fn timeout_fail(
106    self,
107    d: Duration,
108    on_timeout: impl FnOnce() -> E + Send + 'static,
109  ) -> Effect<A, E, R> {
110    self.timeout(d).flat_map(move |o| match o {
111      Some(a) => succeed(a),
112      None => fail(on_timeout()),
113    })
114  }
115}
116
117/// Races every effect (Effect.ts `Effect.raceAll`): the first success wins, and the others are
118/// interrupted and awaited (their finalizers have run) before the result is returned. When every
119/// effect fails, the race fails with all the causes combined by `Cause::Both` in input order.
120/// An empty input dies.
121pub fn race_all<A, E, R>(effects: impl IntoIterator<Item = Effect<A, E, R>>) -> Effect<A, E, R>
122where
123  A: Send + 'static,
124  E: Send + 'static,
125  R: Send + Sync + 'static,
126{
127  let effects: Vec<_> = effects.into_iter().collect();
128  if effects.is_empty() {
129    return die("id_effect: race_all of no effects");
130  }
131  race_with(effects, Mode::FirstSuccess)
132}
133
134/// Forks every effect as a child of the current fiber when the step runs, and awaits the race.
135fn race_with<A, E, R>(effects: Vec<Effect<A, E, R>>, mode: Mode) -> Effect<A, E, R>
136where
137  A: Send + 'static,
138  E: Send + 'static,
139  R: Send + Sync + 'static,
140{
141  let instrs: Vec<Instr> = effects.into_iter().map(Effect::into_instr).collect();
142  Effect::from_instr(Instr::WithFiber(Box::new(move |env, fiber| {
143    let ready = Arc::new(Ready::default());
144    let kids: Vec<Option<Kid>> = instrs
145      .into_iter()
146      .enumerate()
147      .map(|(i, instr)| {
148        let ctx = FiberContext::new_child(fiber);
149        let cell = spawn_fiber(&ctx, instr, Arc::clone(env));
150        let waker = Waker::from(Arc::new(KidWaker {
151          slot: i,
152          ready: Arc::clone(&ready),
153        }));
154        // Marked ready, so the first poll registers the kid's waker.
155        lock(&ready.slots).push(i);
156        Some(Kid { ctx, cell, waker })
157      })
158      .collect();
159    let n = kids.len();
160    Instr::Future(Box::pin(RaceFut {
161      in_flight: n,
162      kids,
163      ready,
164      mode,
165      winner: None,
166      failures: (0..n).map(|_| None).collect(),
167    }))
168  })))
169}
170
171/// A started racer: its context, its exit slot, and the waker that marks it ready.
172struct Kid {
173  ctx: Arc<FiberContext>,
174  cell: FiberCell,
175  waker: Waker,
176}
177
178/// Which racers woke since the last poll, and the waker of the task awaiting the race.
179#[derive(Default)]
180struct Ready {
181  slots: Mutex<Vec<usize>>,
182  parent: Mutex<Option<Waker>>,
183}
184
185/// Wakes the race for one racer: records its slot, then wakes the awaiting task.
186struct KidWaker {
187  slot: usize,
188  ready: Arc<Ready>,
189}
190
191impl Wake for KidWaker {
192  fn wake(self: Arc<Self>) {
193    self.wake_by_ref();
194  }
195
196  fn wake_by_ref(self: &Arc<Self>) {
197    lock(&self.ready.slots).push(self.slot);
198    let w = lock(&self.ready.parent).clone();
199    if let Some(w) = w {
200      w.wake();
201    }
202  }
203}
204
205fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
206  m.lock().unwrap_or_else(PoisonError::into_inner)
207}
208
209/// Awaits the racers: once a winner is decided the rest are interrupted, and the race completes
210/// only when every racer has completed.
211struct RaceFut {
212  /// Racers not yet completed, by input index.
213  kids: Vec<Option<Kid>>,
214  in_flight: usize,
215  ready: Arc<Ready>,
216  mode: Mode,
217  winner: Option<AnyExit>,
218  /// Failure causes by input index (`Mode::FirstSuccess`, until a winner is decided).
219  failures: Vec<Option<Cause<AnyBox>>>,
220}
221
222impl RaceFut {
223  fn record(&mut self, i: usize, exit: AnyExit) {
224    if self.winner.is_some() {
225      // A loser finishing after the decision (usually interrupted): its outcome is dropped.
226      return;
227    }
228    match (self.mode, exit) {
229      (Mode::FirstSuccess, Err(c)) => self.failures[i] = Some(c),
230      (_, exit) => {
231        self.winner = Some(exit);
232        self.failures.clear();
233        for kid in self.kids.iter().flatten() {
234          kid.ctx.request_interrupt();
235        }
236      }
237    }
238  }
239
240  /// The race's exit once every racer has completed.
241  fn finish(&mut self) -> AnyExit {
242    if let Some(exit) = self.winner.take() {
243      return exit;
244    }
245    let cause = std::mem::take(&mut self.failures)
246      .into_iter()
247      .flatten()
248      .reduce(Cause::both)
249      .expect("id_effect: race with no racers (kernel bug)");
250    Err(cause)
251  }
252}
253
254impl Future for RaceFut {
255  type Output = AnyExit;
256
257  fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<AnyExit> {
258    let this = self.get_mut();
259    // Stored before draining the ready list, so a racer completing meanwhile still wakes us.
260    {
261      let mut parent = lock(&this.ready.parent);
262      match parent.as_ref() {
263        Some(w) if w.will_wake(cx.waker()) => {}
264        _ => *parent = Some(cx.waker().clone()),
265      }
266    }
267    loop {
268      if this.in_flight == 0 {
269        return Poll::Ready(this.finish());
270      }
271      let slots = std::mem::take(&mut *lock(&this.ready.slots));
272      if slots.is_empty() {
273        return Poll::Pending;
274      }
275      for i in slots {
276        let Some(kid) = this.kids[i].as_ref() else {
277          continue;
278        };
279        let mut kcx = Context::from_waker(&kid.waker);
280        if let Poll::Ready(exit) = kid.cell.poll_take(&mut kcx) {
281          this.kids[i] = None;
282          this.in_flight -= 1;
283          this.record(i, exit);
284        }
285      }
286    }
287  }
288}
289
290impl Drop for RaceFut {
291  /// Dropped early (the racing fiber was interrupted): interrupt the racers still running. The
292  /// racing fiber's own exit then awaits them as its children.
293  fn drop(&mut self) {
294    for kid in self.kids.iter().flatten() {
295      kid.ctx.request_interrupt();
296    }
297  }
298}