2021-02-20 23:05:36 +00:00
|
|
|
use anyhow::{anyhow, Result};
|
|
|
|
use async_task::Runnable;
|
2021-04-02 17:02:09 +00:00
|
|
|
pub use async_task::Task;
|
2021-07-13 10:31:36 +00:00
|
|
|
use backtrace::{Backtrace, BacktraceFmt, BytesOrWideString};
|
2021-07-08 19:03:00 +00:00
|
|
|
use parking_lot::Mutex;
|
2021-09-08 16:58:59 +00:00
|
|
|
use postage::{barrier, prelude::Stream as _};
|
2021-07-08 19:03:00 +00:00
|
|
|
use rand::prelude::*;
|
2021-09-08 16:58:59 +00:00
|
|
|
use smol::{channel, prelude::*, Executor, Timer};
|
2021-07-09 13:00:51 +00:00
|
|
|
use std::{
|
2021-07-13 10:31:36 +00:00
|
|
|
fmt::{self, Debug},
|
2021-07-09 13:00:51 +00:00
|
|
|
marker::PhantomData,
|
|
|
|
mem,
|
2021-07-20 22:05:28 +00:00
|
|
|
ops::RangeInclusive,
|
2021-07-09 13:00:51 +00:00
|
|
|
pin::Pin,
|
|
|
|
rc::Rc,
|
2021-07-11 09:26:06 +00:00
|
|
|
sync::{
|
|
|
|
atomic::{AtomicBool, Ordering::SeqCst},
|
|
|
|
Arc,
|
|
|
|
},
|
2021-07-20 17:20:50 +00:00
|
|
|
task::{Context, Poll},
|
2021-07-09 13:00:51 +00:00
|
|
|
thread,
|
2021-09-08 16:58:59 +00:00
|
|
|
time::{Duration, Instant},
|
2021-07-09 13:00:51 +00:00
|
|
|
};
|
2021-07-20 18:22:02 +00:00
|
|
|
use waker_fn::waker_fn;
|
2021-02-20 23:05:36 +00:00
|
|
|
|
2021-07-20 17:20:50 +00:00
|
|
|
use crate::{platform, util};
|
2021-02-20 23:05:36 +00:00
|
|
|
|
|
|
|
pub enum Foreground {
|
|
|
|
Platform {
|
|
|
|
dispatcher: Arc<dyn platform::Dispatcher>,
|
|
|
|
_not_send_or_sync: PhantomData<Rc<()>>,
|
|
|
|
},
|
|
|
|
Test(smol::LocalExecutor<'static>),
|
2021-07-08 19:03:00 +00:00
|
|
|
Deterministic(Arc<Deterministic>),
|
2021-02-20 23:05:36 +00:00
|
|
|
}
|
|
|
|
|
2021-07-08 19:03:00 +00:00
|
|
|
pub enum Background {
|
|
|
|
Deterministic(Arc<Deterministic>),
|
|
|
|
Production {
|
|
|
|
executor: Arc<smol::Executor<'static>>,
|
|
|
|
_stop: channel::Sender<()>,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2021-07-11 09:26:06 +00:00
|
|
|
struct DeterministicState {
|
|
|
|
rng: StdRng,
|
|
|
|
seed: u64,
|
2021-07-23 09:54:43 +00:00
|
|
|
scheduled_from_foreground: Vec<(Runnable, Backtrace)>,
|
|
|
|
scheduled_from_background: Vec<(Runnable, Backtrace)>,
|
2021-07-13 10:31:36 +00:00
|
|
|
spawned_from_foreground: Vec<(Runnable, Backtrace)>,
|
2021-07-20 18:22:02 +00:00
|
|
|
forbid_parking: bool,
|
2021-07-20 22:05:28 +00:00
|
|
|
block_on_ticks: RangeInclusive<usize>,
|
2021-09-08 16:58:59 +00:00
|
|
|
now: Instant,
|
2021-09-09 13:34:46 +00:00
|
|
|
pending_timers: Vec<(Instant, barrier::Sender)>,
|
2021-07-09 16:55:42 +00:00
|
|
|
}
|
|
|
|
|
2021-07-20 18:22:02 +00:00
|
|
|
pub struct Deterministic {
|
|
|
|
state: Arc<Mutex<DeterministicState>>,
|
|
|
|
parker: Mutex<parking::Parker>,
|
|
|
|
}
|
2021-07-08 19:03:00 +00:00
|
|
|
|
|
|
|
impl Deterministic {
|
|
|
|
fn new(seed: u64) -> Self {
|
2021-07-20 18:22:02 +00:00
|
|
|
Self {
|
|
|
|
state: Arc::new(Mutex::new(DeterministicState {
|
|
|
|
rng: StdRng::seed_from_u64(seed),
|
|
|
|
seed,
|
2021-07-23 09:54:43 +00:00
|
|
|
scheduled_from_foreground: Default::default(),
|
|
|
|
scheduled_from_background: Default::default(),
|
2021-07-20 18:22:02 +00:00
|
|
|
spawned_from_foreground: Default::default(),
|
|
|
|
forbid_parking: false,
|
2021-07-20 22:05:28 +00:00
|
|
|
block_on_ticks: 0..=1000,
|
2021-09-08 16:58:59 +00:00
|
|
|
now: Instant::now(),
|
2021-09-09 13:34:46 +00:00
|
|
|
pending_timers: Default::default(),
|
2021-07-20 18:22:02 +00:00
|
|
|
})),
|
|
|
|
parker: Default::default(),
|
|
|
|
}
|
2021-07-08 19:03:00 +00:00
|
|
|
}
|
|
|
|
|
2021-07-09 16:55:42 +00:00
|
|
|
pub fn spawn_from_foreground<F, T>(&self, future: F) -> Task<T>
|
2021-07-08 19:03:00 +00:00
|
|
|
where
|
|
|
|
T: 'static,
|
|
|
|
F: Future<Output = T> + 'static,
|
|
|
|
{
|
2021-07-13 10:31:36 +00:00
|
|
|
let backtrace = Backtrace::new_unresolved();
|
2021-07-11 09:26:06 +00:00
|
|
|
let scheduled_once = AtomicBool::new(false);
|
2021-07-20 18:22:02 +00:00
|
|
|
let state = self.state.clone();
|
|
|
|
let unparker = self.parker.lock().unparker();
|
2021-07-08 19:03:00 +00:00
|
|
|
let (runnable, task) = async_task::spawn_local(future, move |runnable| {
|
2021-07-11 09:26:06 +00:00
|
|
|
let mut state = state.lock();
|
2021-07-13 10:31:36 +00:00
|
|
|
let backtrace = backtrace.clone();
|
2021-07-11 09:26:06 +00:00
|
|
|
if scheduled_once.fetch_or(true, SeqCst) {
|
2021-07-23 09:54:43 +00:00
|
|
|
state.scheduled_from_foreground.push((runnable, backtrace));
|
2021-07-09 16:55:42 +00:00
|
|
|
} else {
|
2021-07-13 10:31:36 +00:00
|
|
|
state.spawned_from_foreground.push((runnable, backtrace));
|
2021-07-09 16:55:42 +00:00
|
|
|
}
|
2021-07-20 18:22:02 +00:00
|
|
|
unparker.unpark();
|
2021-07-08 19:03:00 +00:00
|
|
|
});
|
|
|
|
runnable.schedule();
|
|
|
|
task
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn spawn<F, T>(&self, future: F) -> Task<T>
|
|
|
|
where
|
|
|
|
T: 'static + Send,
|
|
|
|
F: 'static + Send + Future<Output = T>,
|
|
|
|
{
|
2021-07-13 10:31:36 +00:00
|
|
|
let backtrace = Backtrace::new_unresolved();
|
2021-07-20 18:22:02 +00:00
|
|
|
let state = self.state.clone();
|
|
|
|
let unparker = self.parker.lock().unparker();
|
2021-07-08 19:03:00 +00:00
|
|
|
let (runnable, task) = async_task::spawn(future, move |runnable| {
|
2021-07-20 18:22:02 +00:00
|
|
|
let mut state = state.lock();
|
2021-07-23 09:54:43 +00:00
|
|
|
state
|
|
|
|
.scheduled_from_background
|
|
|
|
.push((runnable, backtrace.clone()));
|
2021-07-20 18:22:02 +00:00
|
|
|
unparker.unpark();
|
2021-07-08 19:03:00 +00:00
|
|
|
});
|
|
|
|
runnable.schedule();
|
|
|
|
task
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn run<F, T>(&self, future: F) -> T
|
|
|
|
where
|
|
|
|
T: 'static,
|
|
|
|
F: Future<Output = T> + 'static,
|
|
|
|
{
|
2021-09-08 18:24:27 +00:00
|
|
|
let woken = Arc::new(AtomicBool::new(false));
|
|
|
|
let mut future = Box::pin(future);
|
|
|
|
loop {
|
|
|
|
if let Some(result) = self.run_internal(woken.clone(), &mut future) {
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
if !woken.load(SeqCst) && self.state.lock().forbid_parking {
|
|
|
|
panic!("deterministic executor parked after a call to forbid_parking");
|
|
|
|
}
|
|
|
|
|
|
|
|
woken.store(false, SeqCst);
|
|
|
|
self.parker.lock().park();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn run_until_parked(&self) {
|
|
|
|
let woken = Arc::new(AtomicBool::new(false));
|
|
|
|
let future = std::future::pending::<()>();
|
2021-07-23 09:54:43 +00:00
|
|
|
smol::pin!(future);
|
2021-09-08 18:24:27 +00:00
|
|
|
self.run_internal(woken, future);
|
|
|
|
}
|
2021-07-23 09:54:43 +00:00
|
|
|
|
2021-09-08 18:24:27 +00:00
|
|
|
pub fn run_internal<F, T>(&self, woken: Arc<AtomicBool>, mut future: F) -> Option<T>
|
|
|
|
where
|
|
|
|
T: 'static,
|
|
|
|
F: Future<Output = T> + Unpin,
|
|
|
|
{
|
2021-07-23 09:54:43 +00:00
|
|
|
let unparker = self.parker.lock().unparker();
|
2021-09-08 18:24:27 +00:00
|
|
|
let waker = waker_fn(move || {
|
|
|
|
woken.store(true, SeqCst);
|
|
|
|
unparker.unpark();
|
|
|
|
});
|
2021-07-23 09:54:43 +00:00
|
|
|
|
|
|
|
let mut cx = Context::from_waker(&waker);
|
|
|
|
let mut trace = Trace::default();
|
|
|
|
loop {
|
|
|
|
let mut state = self.state.lock();
|
|
|
|
let runnable_count = state.scheduled_from_foreground.len()
|
|
|
|
+ state.scheduled_from_background.len()
|
|
|
|
+ state.spawned_from_foreground.len();
|
|
|
|
|
|
|
|
let ix = state.rng.gen_range(0..=runnable_count);
|
|
|
|
if ix < state.scheduled_from_foreground.len() {
|
|
|
|
let (_, backtrace) = &state.scheduled_from_foreground[ix];
|
|
|
|
trace.record(&state, backtrace.clone());
|
|
|
|
let runnable = state.scheduled_from_foreground.remove(ix).0;
|
|
|
|
drop(state);
|
|
|
|
runnable.run();
|
|
|
|
} else if ix - state.scheduled_from_foreground.len()
|
|
|
|
< state.scheduled_from_background.len()
|
|
|
|
{
|
|
|
|
let ix = ix - state.scheduled_from_foreground.len();
|
|
|
|
let (_, backtrace) = &state.scheduled_from_background[ix];
|
|
|
|
trace.record(&state, backtrace.clone());
|
|
|
|
let runnable = state.scheduled_from_background.remove(ix).0;
|
|
|
|
drop(state);
|
|
|
|
runnable.run();
|
|
|
|
} else if ix < runnable_count {
|
|
|
|
let (_, backtrace) = &state.spawned_from_foreground[0];
|
|
|
|
trace.record(&state, backtrace.clone());
|
|
|
|
let runnable = state.spawned_from_foreground.remove(0).0;
|
|
|
|
drop(state);
|
|
|
|
runnable.run();
|
|
|
|
} else {
|
|
|
|
drop(state);
|
2021-09-08 18:24:27 +00:00
|
|
|
if let Poll::Ready(result) = future.poll(&mut cx) {
|
|
|
|
return Some(result);
|
2021-07-23 09:54:43 +00:00
|
|
|
}
|
2021-09-08 18:24:27 +00:00
|
|
|
|
2021-07-23 09:54:43 +00:00
|
|
|
let state = self.state.lock();
|
|
|
|
if state.scheduled_from_foreground.is_empty()
|
|
|
|
&& state.scheduled_from_background.is_empty()
|
|
|
|
&& state.spawned_from_foreground.is_empty()
|
|
|
|
{
|
2021-09-08 18:24:27 +00:00
|
|
|
return None;
|
2021-07-23 09:54:43 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-07-20 17:20:50 +00:00
|
|
|
}
|
2021-07-08 19:03:00 +00:00
|
|
|
|
2021-07-23 09:54:43 +00:00
|
|
|
pub fn block_on<F, T>(&self, future: F) -> Option<T>
|
2021-07-20 17:20:50 +00:00
|
|
|
where
|
|
|
|
T: 'static,
|
|
|
|
F: Future<Output = T>,
|
|
|
|
{
|
|
|
|
smol::pin!(future);
|
2021-07-08 19:03:00 +00:00
|
|
|
|
2021-07-20 18:22:02 +00:00
|
|
|
let unparker = self.parker.lock().unparker();
|
|
|
|
let waker = waker_fn(move || {
|
|
|
|
unparker.unpark();
|
|
|
|
});
|
2021-07-23 09:54:43 +00:00
|
|
|
let max_ticks = {
|
|
|
|
let mut state = self.state.lock();
|
|
|
|
let range = state.block_on_ticks.clone();
|
|
|
|
state.rng.gen_range(range)
|
|
|
|
};
|
2021-07-20 18:22:02 +00:00
|
|
|
|
2021-07-20 17:20:50 +00:00
|
|
|
let mut cx = Context::from_waker(&waker);
|
2021-07-13 10:31:36 +00:00
|
|
|
let mut trace = Trace::default();
|
2021-07-20 17:20:50 +00:00
|
|
|
for _ in 0..max_ticks {
|
2021-07-20 18:22:02 +00:00
|
|
|
let mut state = self.state.lock();
|
2021-07-23 09:54:43 +00:00
|
|
|
let runnable_count = state.scheduled_from_background.len();
|
2021-07-20 18:22:02 +00:00
|
|
|
let ix = state.rng.gen_range(0..=runnable_count);
|
2021-07-23 09:54:43 +00:00
|
|
|
if ix < state.scheduled_from_background.len() {
|
|
|
|
let (_, backtrace) = &state.scheduled_from_background[ix];
|
2021-07-20 18:22:02 +00:00
|
|
|
trace.record(&state, backtrace.clone());
|
2021-07-23 09:54:43 +00:00
|
|
|
let runnable = state.scheduled_from_background.remove(ix).0;
|
2021-07-20 18:22:02 +00:00
|
|
|
drop(state);
|
|
|
|
runnable.run();
|
|
|
|
} else {
|
|
|
|
drop(state);
|
|
|
|
if let Poll::Ready(result) = future.as_mut().poll(&mut cx) {
|
|
|
|
return Some(result);
|
|
|
|
}
|
2021-07-20 18:37:02 +00:00
|
|
|
let state = self.state.lock();
|
2021-07-23 09:54:43 +00:00
|
|
|
if state.scheduled_from_background.is_empty() {
|
2021-07-20 18:22:02 +00:00
|
|
|
if state.forbid_parking {
|
|
|
|
panic!("deterministic executor parked after a call to forbid_parking");
|
2021-07-20 17:20:50 +00:00
|
|
|
}
|
2021-07-20 18:22:02 +00:00
|
|
|
drop(state);
|
|
|
|
self.parker.lock().park();
|
2021-07-09 16:55:42 +00:00
|
|
|
}
|
2021-07-08 19:03:00 +00:00
|
|
|
|
2021-07-20 18:22:02 +00:00
|
|
|
continue;
|
|
|
|
}
|
2021-07-08 19:03:00 +00:00
|
|
|
}
|
2021-07-20 17:20:50 +00:00
|
|
|
|
|
|
|
None
|
2021-07-08 19:03:00 +00:00
|
|
|
}
|
2021-02-20 23:05:36 +00:00
|
|
|
}
|
|
|
|
|
2021-07-13 10:31:36 +00:00
|
|
|
#[derive(Default)]
|
|
|
|
struct Trace {
|
|
|
|
executed: Vec<Backtrace>,
|
|
|
|
scheduled: Vec<Vec<Backtrace>>,
|
|
|
|
spawned_from_foreground: Vec<Vec<Backtrace>>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Trace {
|
|
|
|
fn record(&mut self, state: &DeterministicState, executed: Backtrace) {
|
|
|
|
self.scheduled.push(
|
|
|
|
state
|
2021-07-23 09:54:43 +00:00
|
|
|
.scheduled_from_foreground
|
2021-07-13 10:31:36 +00:00
|
|
|
.iter()
|
|
|
|
.map(|(_, backtrace)| backtrace.clone())
|
|
|
|
.collect(),
|
|
|
|
);
|
|
|
|
self.spawned_from_foreground.push(
|
|
|
|
state
|
|
|
|
.spawned_from_foreground
|
|
|
|
.iter()
|
|
|
|
.map(|(_, backtrace)| backtrace.clone())
|
|
|
|
.collect(),
|
|
|
|
);
|
|
|
|
self.executed.push(executed);
|
|
|
|
}
|
|
|
|
|
|
|
|
fn resolve(&mut self) {
|
|
|
|
for backtrace in &mut self.executed {
|
|
|
|
backtrace.resolve();
|
|
|
|
}
|
|
|
|
|
|
|
|
for backtraces in &mut self.scheduled {
|
|
|
|
for backtrace in backtraces {
|
|
|
|
backtrace.resolve();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for backtraces in &mut self.spawned_from_foreground {
|
|
|
|
for backtrace in backtraces {
|
|
|
|
backtrace.resolve();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Debug for Trace {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
|
struct FirstCwdFrameInBacktrace<'a>(&'a Backtrace);
|
|
|
|
|
|
|
|
impl<'a> Debug for FirstCwdFrameInBacktrace<'a> {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
let cwd = std::env::current_dir().unwrap();
|
|
|
|
let mut print_path = |fmt: &mut fmt::Formatter<'_>, path: BytesOrWideString<'_>| {
|
|
|
|
fmt::Display::fmt(&path, fmt)
|
|
|
|
};
|
|
|
|
let mut fmt = BacktraceFmt::new(f, backtrace::PrintFmt::Full, &mut print_path);
|
|
|
|
for frame in self.0.frames() {
|
|
|
|
let mut formatted_frame = fmt.frame();
|
|
|
|
if frame
|
|
|
|
.symbols()
|
|
|
|
.iter()
|
|
|
|
.any(|s| s.filename().map_or(false, |f| f.starts_with(&cwd)))
|
|
|
|
{
|
|
|
|
formatted_frame.backtrace_frame(frame)?;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
fmt.finish()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for ((backtrace, scheduled), spawned_from_foreground) in self
|
|
|
|
.executed
|
|
|
|
.iter()
|
|
|
|
.zip(&self.scheduled)
|
|
|
|
.zip(&self.spawned_from_foreground)
|
|
|
|
{
|
|
|
|
writeln!(f, "Scheduled")?;
|
|
|
|
for backtrace in scheduled {
|
|
|
|
writeln!(f, "- {:?}", FirstCwdFrameInBacktrace(backtrace))?;
|
|
|
|
}
|
|
|
|
if scheduled.is_empty() {
|
|
|
|
writeln!(f, "None")?;
|
|
|
|
}
|
|
|
|
writeln!(f, "==========")?;
|
|
|
|
|
|
|
|
writeln!(f, "Spawned from foreground")?;
|
|
|
|
for backtrace in spawned_from_foreground {
|
|
|
|
writeln!(f, "- {:?}", FirstCwdFrameInBacktrace(backtrace))?;
|
|
|
|
}
|
|
|
|
if spawned_from_foreground.is_empty() {
|
|
|
|
writeln!(f, "None")?;
|
|
|
|
}
|
|
|
|
writeln!(f, "==========")?;
|
|
|
|
|
|
|
|
writeln!(f, "Run: {:?}", FirstCwdFrameInBacktrace(backtrace))?;
|
|
|
|
writeln!(f, "+++++++++++++++++++")?;
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for Trace {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
let trace_on_panic = if let Ok(trace_on_panic) = std::env::var("EXECUTOR_TRACE_ON_PANIC") {
|
|
|
|
trace_on_panic == "1" || trace_on_panic == "true"
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
};
|
|
|
|
let trace_always = if let Ok(trace_always) = std::env::var("EXECUTOR_TRACE_ALWAYS") {
|
|
|
|
trace_always == "1" || trace_always == "true"
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
};
|
|
|
|
|
|
|
|
if trace_always || (trace_on_panic && thread::panicking()) {
|
|
|
|
self.resolve();
|
|
|
|
dbg!(self);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-20 23:05:36 +00:00
|
|
|
impl Foreground {
|
|
|
|
pub fn platform(dispatcher: Arc<dyn platform::Dispatcher>) -> Result<Self> {
|
|
|
|
if dispatcher.is_main_thread() {
|
|
|
|
Ok(Self::Platform {
|
|
|
|
dispatcher,
|
|
|
|
_not_send_or_sync: PhantomData,
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
Err(anyhow!("must be constructed on main thread"))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn test() -> Self {
|
|
|
|
Self::Test(smol::LocalExecutor::new())
|
|
|
|
}
|
|
|
|
|
2021-04-02 17:02:09 +00:00
|
|
|
pub fn spawn<T: 'static>(&self, future: impl Future<Output = T> + 'static) -> Task<T> {
|
2021-02-20 23:05:36 +00:00
|
|
|
match self {
|
|
|
|
Self::Platform { dispatcher, .. } => {
|
|
|
|
let dispatcher = dispatcher.clone();
|
|
|
|
let schedule = move |runnable: Runnable| dispatcher.run_on_main_thread(runnable);
|
|
|
|
let (runnable, task) = async_task::spawn_local(future, schedule);
|
|
|
|
runnable.schedule();
|
2021-04-02 17:02:09 +00:00
|
|
|
task
|
2021-02-20 23:05:36 +00:00
|
|
|
}
|
2021-04-02 17:02:09 +00:00
|
|
|
Self::Test(executor) => executor.spawn(future),
|
2021-07-09 16:55:42 +00:00
|
|
|
Self::Deterministic(executor) => executor.spawn_from_foreground(future),
|
2021-02-20 23:05:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-08 19:03:00 +00:00
|
|
|
pub fn run<T: 'static>(&self, future: impl 'static + Future<Output = T>) -> T {
|
2021-02-20 23:05:36 +00:00
|
|
|
match self {
|
|
|
|
Self::Platform { .. } => panic!("you can't call run on a platform foreground executor"),
|
2021-07-08 19:03:00 +00:00
|
|
|
Self::Test(executor) => smol::block_on(executor.run(future)),
|
|
|
|
Self::Deterministic(executor) => executor.run(future),
|
2021-02-20 23:05:36 +00:00
|
|
|
}
|
|
|
|
}
|
2021-07-11 09:26:06 +00:00
|
|
|
|
2021-07-20 18:22:02 +00:00
|
|
|
pub fn forbid_parking(&self) {
|
|
|
|
match self {
|
|
|
|
Self::Deterministic(executor) => {
|
2021-07-20 18:28:04 +00:00
|
|
|
let mut state = executor.state.lock();
|
|
|
|
state.forbid_parking = true;
|
|
|
|
state.rng = StdRng::seed_from_u64(state.seed);
|
2021-07-20 18:22:02 +00:00
|
|
|
}
|
2021-07-20 22:05:28 +00:00
|
|
|
_ => panic!("this method can only be called on a deterministic executor"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-09 13:34:46 +00:00
|
|
|
pub async fn timer(&self, duration: Duration) {
|
2021-09-08 16:58:59 +00:00
|
|
|
match self {
|
|
|
|
Self::Deterministic(executor) => {
|
|
|
|
let (tx, mut rx) = barrier::channel();
|
|
|
|
{
|
|
|
|
let mut state = executor.state.lock();
|
|
|
|
let wakeup_at = state.now + duration;
|
2021-09-09 13:34:46 +00:00
|
|
|
state.pending_timers.push((wakeup_at, tx));
|
2021-09-08 16:58:59 +00:00
|
|
|
}
|
|
|
|
rx.recv().await;
|
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
Timer::after(duration).await;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn advance_clock(&self, duration: Duration) {
|
|
|
|
match self {
|
|
|
|
Self::Deterministic(executor) => {
|
2021-09-08 18:24:27 +00:00
|
|
|
executor.run_until_parked();
|
|
|
|
|
2021-09-08 16:58:59 +00:00
|
|
|
let mut state = executor.state.lock();
|
|
|
|
state.now += duration;
|
|
|
|
let now = state.now;
|
2021-09-09 13:34:46 +00:00
|
|
|
let mut pending_timers = mem::take(&mut state.pending_timers);
|
2021-09-08 18:24:27 +00:00
|
|
|
drop(state);
|
|
|
|
|
2021-09-09 13:34:46 +00:00
|
|
|
pending_timers.retain(|(wakeup, _)| *wakeup > now);
|
|
|
|
executor.state.lock().pending_timers.extend(pending_timers);
|
2021-09-08 16:58:59 +00:00
|
|
|
}
|
|
|
|
_ => panic!("this method can only be called on a deterministic executor"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-20 22:05:28 +00:00
|
|
|
pub fn set_block_on_ticks(&self, range: RangeInclusive<usize>) {
|
|
|
|
match self {
|
|
|
|
Self::Deterministic(executor) => executor.state.lock().block_on_ticks = range,
|
|
|
|
_ => panic!("this method can only be called on a deterministic executor"),
|
2021-07-20 18:22:02 +00:00
|
|
|
}
|
|
|
|
}
|
2021-02-20 23:05:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Background {
|
|
|
|
pub fn new() -> Self {
|
|
|
|
let executor = Arc::new(Executor::new());
|
|
|
|
let stop = channel::unbounded::<()>();
|
|
|
|
|
2021-07-13 16:13:25 +00:00
|
|
|
for i in 0..2 * num_cpus::get() {
|
2021-02-20 23:05:36 +00:00
|
|
|
let executor = executor.clone();
|
|
|
|
let stop = stop.1.clone();
|
|
|
|
thread::Builder::new()
|
|
|
|
.name(format!("background-executor-{}", i))
|
|
|
|
.spawn(move || smol::block_on(executor.run(stop.recv())))
|
|
|
|
.unwrap();
|
|
|
|
}
|
|
|
|
|
2021-07-08 19:03:00 +00:00
|
|
|
Self::Production {
|
2021-02-20 23:05:36 +00:00
|
|
|
executor,
|
|
|
|
_stop: stop.0,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-13 16:13:25 +00:00
|
|
|
pub fn num_cpus(&self) -> usize {
|
|
|
|
num_cpus::get()
|
2021-07-09 13:00:51 +00:00
|
|
|
}
|
|
|
|
|
2021-06-11 17:28:00 +00:00
|
|
|
pub fn spawn<T, F>(&self, future: F) -> Task<T>
|
2021-02-20 23:05:36 +00:00
|
|
|
where
|
|
|
|
T: 'static + Send,
|
2021-06-11 17:28:00 +00:00
|
|
|
F: Send + Future<Output = T> + 'static,
|
2021-02-20 23:05:36 +00:00
|
|
|
{
|
2021-07-08 19:03:00 +00:00
|
|
|
match self {
|
|
|
|
Self::Production { executor, .. } => executor.spawn(future),
|
|
|
|
Self::Deterministic(executor) => executor.spawn(future),
|
|
|
|
}
|
2021-02-20 23:05:36 +00:00
|
|
|
}
|
2021-07-09 13:00:51 +00:00
|
|
|
|
2021-07-22 20:16:42 +00:00
|
|
|
pub fn block_with_timeout<F, T>(&self, timeout: Duration, mut future: F) -> Result<T, F>
|
2021-07-20 17:20:50 +00:00
|
|
|
where
|
|
|
|
T: 'static,
|
2021-07-22 20:16:42 +00:00
|
|
|
F: 'static + Unpin + Future<Output = T>,
|
2021-07-20 17:20:50 +00:00
|
|
|
{
|
2021-09-07 23:23:49 +00:00
|
|
|
if !timeout.is_zero() {
|
|
|
|
let output = match self {
|
|
|
|
Self::Production { .. } => {
|
|
|
|
smol::block_on(util::timeout(timeout, Pin::new(&mut future))).ok()
|
|
|
|
}
|
|
|
|
Self::Deterministic(executor) => executor.block_on(Pin::new(&mut future)),
|
|
|
|
};
|
|
|
|
if let Some(output) = output {
|
|
|
|
return Ok(output);
|
2021-07-20 17:20:50 +00:00
|
|
|
}
|
|
|
|
}
|
2021-09-07 23:23:49 +00:00
|
|
|
Err(future)
|
2021-07-20 17:20:50 +00:00
|
|
|
}
|
|
|
|
|
2021-07-09 13:00:51 +00:00
|
|
|
pub async fn scoped<'scope, F>(&self, scheduler: F)
|
|
|
|
where
|
|
|
|
F: FnOnce(&mut Scope<'scope>),
|
|
|
|
{
|
|
|
|
let mut scope = Scope {
|
|
|
|
futures: Default::default(),
|
|
|
|
_phantom: PhantomData,
|
|
|
|
};
|
|
|
|
(scheduler)(&mut scope);
|
2021-07-09 16:32:57 +00:00
|
|
|
let spawned = scope
|
|
|
|
.futures
|
|
|
|
.into_iter()
|
|
|
|
.map(|f| self.spawn(f))
|
|
|
|
.collect::<Vec<_>>();
|
|
|
|
for task in spawned {
|
|
|
|
task.await;
|
2021-07-09 13:00:51 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct Scope<'a> {
|
|
|
|
futures: Vec<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>,
|
|
|
|
_phantom: PhantomData<&'a ()>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> Scope<'a> {
|
|
|
|
pub fn spawn<F>(&mut self, f: F)
|
|
|
|
where
|
|
|
|
F: Future<Output = ()> + Send + 'a,
|
|
|
|
{
|
|
|
|
let f = unsafe {
|
|
|
|
mem::transmute::<
|
|
|
|
Pin<Box<dyn Future<Output = ()> + Send + 'a>>,
|
|
|
|
Pin<Box<dyn Future<Output = ()> + Send + 'static>>,
|
|
|
|
>(Box::pin(f))
|
|
|
|
};
|
|
|
|
self.futures.push(f);
|
|
|
|
}
|
2021-02-20 23:05:36 +00:00
|
|
|
}
|
2021-07-08 19:03:00 +00:00
|
|
|
|
|
|
|
pub fn deterministic(seed: u64) -> (Rc<Foreground>, Arc<Background>) {
|
|
|
|
let executor = Arc::new(Deterministic::new(seed));
|
|
|
|
(
|
|
|
|
Rc::new(Foreground::Deterministic(executor.clone())),
|
|
|
|
Arc::new(Background::Deterministic(executor)),
|
|
|
|
)
|
|
|
|
}
|