use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::task::{Context, Poll, Wake, Waker};
use std::time::Duration;
use crate::failure::Cause;
use crate::kernel::{AnyBox, AnyExit, Effect, Instr, die, fail, sleep, succeed};
use crate::runtime::{FiberCell, FiberContext, spawn_fiber};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Mode {
FirstSuccess,
FirstExit,
}
impl<A, E, R> Effect<A, E, R>
where
A: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
pub fn race(self, that: Effect<A, E, R>) -> Effect<A, E, R> {
race_with(vec![self, that], Mode::FirstSuccess)
}
pub fn race_first(self, that: Effect<A, E, R>) -> Effect<A, E, R> {
race_with(vec![self, that], Mode::FirstExit)
}
pub fn timeout(self, d: Duration) -> Effect<Option<A>, E, R> {
let timer: Effect<Option<A>, E, R> = sleep(d).map(|()| None);
race_with(vec![self.map(Some), timer], Mode::FirstExit)
}
pub fn timeout_fail(
self,
d: Duration,
on_timeout: impl FnOnce() -> E + Send + 'static,
) -> Effect<A, E, R> {
self.timeout(d).flat_map(move |o| match o {
Some(a) => succeed(a),
None => fail(on_timeout()),
})
}
}
pub fn race_all<A, E, R>(effects: impl IntoIterator<Item = Effect<A, E, R>>) -> Effect<A, E, R>
where
A: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
let effects: Vec<_> = effects.into_iter().collect();
if effects.is_empty() {
return die("id_effect: race_all of no effects");
}
race_with(effects, Mode::FirstSuccess)
}
fn race_with<A, E, R>(effects: Vec<Effect<A, E, R>>, mode: Mode) -> Effect<A, E, R>
where
A: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
let instrs: Vec<Instr> = effects.into_iter().map(Effect::into_instr).collect();
Effect::from_instr(Instr::WithFiber(Box::new(move |env, fiber| {
let ready = Arc::new(Ready::default());
let kids: Vec<Option<Kid>> = instrs
.into_iter()
.enumerate()
.map(|(i, instr)| {
let ctx = FiberContext::new_child(fiber);
let cell = spawn_fiber(&ctx, instr, Arc::clone(env));
let waker = Waker::from(Arc::new(KidWaker {
slot: i,
ready: Arc::clone(&ready),
}));
lock(&ready.slots).push(i);
Some(Kid { ctx, cell, waker })
})
.collect();
let n = kids.len();
Instr::Future(Box::pin(RaceFut {
in_flight: n,
kids,
ready,
mode,
winner: None,
failures: (0..n).map(|_| None).collect(),
}))
})))
}
struct Kid {
ctx: Arc<FiberContext>,
cell: FiberCell,
waker: Waker,
}
#[derive(Default)]
struct Ready {
slots: Mutex<Vec<usize>>,
parent: Mutex<Option<Waker>>,
}
struct KidWaker {
slot: usize,
ready: Arc<Ready>,
}
impl Wake for KidWaker {
fn wake(self: Arc<Self>) {
self.wake_by_ref();
}
fn wake_by_ref(self: &Arc<Self>) {
lock(&self.ready.slots).push(self.slot);
let w = lock(&self.ready.parent).clone();
if let Some(w) = w {
w.wake();
}
}
}
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(PoisonError::into_inner)
}
struct RaceFut {
kids: Vec<Option<Kid>>,
in_flight: usize,
ready: Arc<Ready>,
mode: Mode,
winner: Option<AnyExit>,
failures: Vec<Option<Cause<AnyBox>>>,
}
impl RaceFut {
fn record(&mut self, i: usize, exit: AnyExit) {
if self.winner.is_some() {
return;
}
match (self.mode, exit) {
(Mode::FirstSuccess, Err(c)) => self.failures[i] = Some(c),
(_, exit) => {
self.winner = Some(exit);
self.failures.clear();
for kid in self.kids.iter().flatten() {
kid.ctx.request_interrupt();
}
}
}
}
fn finish(&mut self) -> AnyExit {
if let Some(exit) = self.winner.take() {
return exit;
}
let cause = std::mem::take(&mut self.failures)
.into_iter()
.flatten()
.reduce(Cause::both)
.expect("id_effect: race with no racers (kernel bug)");
Err(cause)
}
}
impl Future for RaceFut {
type Output = AnyExit;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<AnyExit> {
let this = self.get_mut();
{
let mut parent = lock(&this.ready.parent);
match parent.as_ref() {
Some(w) if w.will_wake(cx.waker()) => {}
_ => *parent = Some(cx.waker().clone()),
}
}
loop {
if this.in_flight == 0 {
return Poll::Ready(this.finish());
}
let slots = std::mem::take(&mut *lock(&this.ready.slots));
if slots.is_empty() {
return Poll::Pending;
}
for i in slots {
let Some(kid) = this.kids[i].as_ref() else {
continue;
};
let mut kcx = Context::from_waker(&kid.waker);
if let Poll::Ready(exit) = kid.cell.poll_take(&mut kcx) {
this.kids[i] = None;
this.in_flight -= 1;
this.record(i, exit);
}
}
}
}
}
impl Drop for RaceFut {
fn drop(&mut self) {
for kid in self.kids.iter().flatten() {
kid.ctx.request_interrupt();
}
}
}