use std::collections::VecDeque;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::task::{Context, Poll, Wake, Waker};
use crate::compute::{Ambient, Fabric};
use crate::failure::Cause;
use crate::kernel::{AnyBox, AnyEnv, AnyExit, Effect, Instr, erase, succeed, unbox};
use crate::runtime::{BoxFuture, FiberCell, FiberContext, spawn_fiber};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Concurrency {
Sequential,
Bounded(usize),
Unbounded,
Inherit,
}
pub trait Admission: Send + Sync {
fn admit(&self, weight: u32) -> BoxFuture<'static, AdmissionPermit>;
}
pub struct AdmissionPermit {
_guard: Option<Box<dyn std::any::Any + Send + Sync>>,
}
impl AdmissionPermit {
pub fn new(guard: impl Send + Sync + 'static) -> Self {
Self {
_guard: Some(Box::new(guard)),
}
}
pub fn unlimited() -> Self {
Self { _guard: None }
}
}
impl std::fmt::Debug for AdmissionPermit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AdmissionPermit").finish_non_exhaustive()
}
}
pub fn fork_all<A, E, R>(effects: Vec<Effect<A, E, R>>, c: Concurrency) -> Effect<Vec<A>, E, R>
where
A: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
let limit = match c {
Concurrency::Sequential => {
return effects.into_iter().fold(succeed(Vec::new()), |acc, e| {
acc.flat_map(move |mut v| {
e.map(move |a| {
v.push(a);
v
})
})
});
}
Concurrency::Bounded(n) => n.max(1),
Concurrency::Unbounded | Concurrency::Inherit => usize::MAX,
};
let instrs: VecDeque<(usize, Instr)> = effects
.into_iter()
.map(Effect::into_instr)
.enumerate()
.collect();
let inherit = c == Concurrency::Inherit;
Effect::from_instr(Instr::FlatMap(
Box::new(Instr::WithFiber(Box::new(move |env, fiber| {
let ambient = if inherit { Ambient::of(fiber) } else { None };
Instr::Future(Box::pin(AllFut::new(
Arc::clone(fiber),
Arc::clone(env),
instrs,
limit,
ambient,
)))
}))),
Box::new(|v| {
let vals: Vec<A> = unbox::<Vec<AnyBox>>(v)
.into_iter()
.map(unbox::<A>)
.collect();
Instr::Pure(Ok(erase(vals)))
}),
))
}
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 AllFut {
parent: Arc<FiberContext>,
env: AnyEnv,
queue: VecDeque<(usize, Instr)>,
limit: usize,
kids: Vec<Option<Kid>>,
in_flight: usize,
ready: Arc<Ready>,
results: Vec<Option<AnyBox>>,
failure: Option<Cause<AnyBox>>,
fabric: Option<Fabric>,
lend: bool,
lent: Option<usize>,
pending: Option<BoxFuture<'static, AdmissionPermit>>,
}
impl AllFut {
fn new(
parent: Arc<FiberContext>,
env: AnyEnv,
queue: VecDeque<(usize, Instr)>,
limit: usize,
ambient: Option<Ambient>,
) -> Self {
let n = queue.len();
let (fabric, lend) = match ambient {
Some(a) => (Some(a.fabric), a.admitted),
None => (None, false),
};
Self {
parent,
env,
queue,
limit,
kids: (0..n).map(|_| None).collect(),
in_flight: 0,
ready: Arc::new(Ready::default()),
results: (0..n).map(|_| None).collect(),
failure: None,
fabric,
lend,
lent: None,
pending: None,
}
}
fn admit_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<AdmissionPermit>> {
let Some(fabric) = self.fabric.as_ref() else {
return Poll::Ready(None);
};
if self.lend && self.lent.is_none() {
return Poll::Ready(None);
}
let fut = self.pending.get_or_insert_with(|| fabric.admit(1));
match fut.as_mut().poll(cx) {
Poll::Ready(p) => {
self.pending = None;
Poll::Ready(Some(p))
}
Poll::Pending => Poll::Pending,
}
}
fn start_up_to_limit(&mut self, cx: &mut Context<'_>) {
if self.failure.is_some() {
self.queue.clear();
self.pending = None;
return;
}
while self.in_flight < self.limit {
if self.queue.is_empty() {
self.pending = None;
return;
}
let Poll::Ready(permit) = self.admit_next(cx) else {
return;
};
let Some((i, instr)) = self.queue.pop_front() else {
return;
};
let ctx = FiberContext::new_child(&self.parent);
let instr = match (permit, self.fabric.as_ref()) {
(Some(permit), Some(fabric)) => {
Ambient::mark_admitted(&ctx, fabric);
Instr::Fold(
Box::new(instr),
Box::new(move |exit| {
drop(permit);
Instr::Pure(exit)
}),
)
}
(None, Some(_)) => {
self.lent = Some(i);
instr
}
(_, None) => instr,
};
let cell = spawn_fiber(&ctx, instr, Arc::clone(&self.env));
let waker = Waker::from(Arc::new(KidWaker {
slot: i,
ready: Arc::clone(&self.ready),
}));
self.kids[i] = Some(Kid { ctx, cell, waker });
self.in_flight += 1;
lock(&self.ready.slots).push(i);
}
}
fn record(&mut self, i: usize, exit: AnyExit) {
match exit {
Ok(v) => self.results[i] = Some(v),
Err(c) => match self.failure.take() {
None => {
self.failure = Some(c);
self.queue.clear();
for kid in self.kids.iter().flatten() {
kid.ctx.request_interrupt();
}
}
Some(first) => {
self.failure = Some(match without_interrupts(c) {
Some(more) => Cause::Both(Box::new(first), Box::new(more)),
None => first,
});
}
},
}
}
}
fn without_interrupts<E>(c: Cause<E>) -> Option<Cause<E>> {
match c {
Cause::Interrupt(_) => None,
Cause::Both(l, r) => join(without_interrupts(*l), without_interrupts(*r), Cause::Both),
Cause::Then(l, r) => join(without_interrupts(*l), without_interrupts(*r), Cause::Then),
leaf => Some(leaf),
}
}
fn join<E>(
l: Option<Cause<E>>,
r: Option<Cause<E>>,
both: fn(Box<Cause<E>>, Box<Cause<E>>) -> Cause<E>,
) -> Option<Cause<E>> {
match (l, r) {
(Some(l), Some(r)) => Some(both(Box::new(l), Box::new(r))),
(one, None) | (None, one) => one,
}
}
impl Future for AllFut {
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 {
this.start_up_to_limit(cx);
let slots = std::mem::take(&mut *lock(&this.ready.slots));
if slots.is_empty() && !(this.in_flight == 0 && this.queue.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;
if this.lent == Some(i) {
this.lent = None;
}
this.record(i, exit);
}
}
if this.in_flight == 0 && this.queue.is_empty() {
if let Some(c) = this.failure.take() {
return Poll::Ready(Err(c));
}
let vals: Vec<AnyBox> = this
.results
.iter_mut()
.map(|r| {
r.take()
.expect("id_effect: fork_all child result missing (kernel bug)")
})
.collect();
return Poll::Ready(Ok(erase(vals)));
}
}
}
}
impl Drop for AllFut {
fn drop(&mut self) {
for kid in self.kids.iter().flatten() {
kid.ctx.request_interrupt();
}
}
}