Extract a scheduler crate from GPUI to enable unified integration testing of client and server code (#37326)
Extracts and cleans up GPUI's scheduler code into a new `scheduler` crate, making it pluggable by external runtimes. This will enable deterministic integration testing with cloud components by providing a unified test scheduler across Zed and backend code. In Zed, it will replace the existing GPUI scheduler for consistent async task management across platforms. ## Changes - **Core Implementation**: `TestScheduler` with seed-based randomization, session tracking (`SessionId`), and foreground/background task separation for reproducible testing. - **Executors**: `ForegroundExecutor` (!Send, thread-local) and `BackgroundExecutor` (Send, with blocking/timeout support) as GPUI-compatible wrappers. - **Clock and Timer**: Controllable `TestClock` and future-based `Timer` for time-sensitive tests. - **Testing APIs**: `once()`, `with_seed()`, and `many()` methods for configurable test runs. - **Dependencies**: Added `async-task`, `chrono`, `futures`, etc., with updates to `Cargo.toml` and lock file. ## Benefits - **Integration Testing**: Facilitates reliable async tests involving cloud sessions, reducing flakiness via deterministic execution. - **Pluggability**: Trait-based design (`Scheduler`) allows easy integration into non-GPUI runtimes while maintaining GPUI compatibility. - **Cleanup**: Refactors GPUI scheduler logic for clarity, correctness (no `unwrap()`, proper error handling), and extensibility. Follows Rust guidelines; run `./script/clippy` for verification. - [x] Define and test a core scheduler that we think can power our cloud code and GPUI - [ ] Replace GPUI's scheduler Release Notes: - N/A --------- Co-authored-by: Antonio Scandurra <me@as-cii.com>
This commit is contained in:
co-authored by
Antonio Scandurra
parent
a05f86f97b
commit
1ae326432e
@@ -0,0 +1,34 @@
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use parking_lot::Mutex;
|
||||
|
||||
pub trait Clock {
|
||||
fn now(&self) -> DateTime<Utc>;
|
||||
}
|
||||
|
||||
pub struct TestClock {
|
||||
now: Mutex<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
impl TestClock {
|
||||
pub fn new() -> Self {
|
||||
const START_TIME: &str = "2025-07-01T23:59:58-00:00";
|
||||
let now = DateTime::parse_from_rfc3339(START_TIME).unwrap().to_utc();
|
||||
Self {
|
||||
now: Mutex::new(now),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_now(&self, now: DateTime<Utc>) {
|
||||
*self.now.lock() = now;
|
||||
}
|
||||
|
||||
pub fn advance(&self, duration: Duration) {
|
||||
*self.now.lock() += duration;
|
||||
}
|
||||
}
|
||||
|
||||
impl Clock for TestClock {
|
||||
fn now(&self) -> DateTime<Utc> {
|
||||
*self.now.lock()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
use crate::{Scheduler, SessionId, Timer};
|
||||
use std::{
|
||||
future::Future,
|
||||
marker::PhantomData,
|
||||
pin::Pin,
|
||||
rc::Rc,
|
||||
sync::Arc,
|
||||
task::{Context, Poll},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ForegroundExecutor {
|
||||
session_id: SessionId,
|
||||
scheduler: Arc<dyn Scheduler>,
|
||||
not_send: PhantomData<Rc<()>>,
|
||||
}
|
||||
|
||||
impl ForegroundExecutor {
|
||||
pub fn spawn<F>(&self, future: F) -> Task<F::Output>
|
||||
where
|
||||
F: Future + 'static,
|
||||
F::Output: 'static,
|
||||
{
|
||||
let session_id = self.session_id;
|
||||
let scheduler = Arc::clone(&self.scheduler);
|
||||
let (runnable, task) = async_task::spawn_local(future, move |runnable| {
|
||||
scheduler.schedule_foreground(session_id, runnable);
|
||||
});
|
||||
runnable.schedule();
|
||||
Task(TaskState::Spawned(task))
|
||||
}
|
||||
|
||||
pub fn timer(&self, duration: Duration) -> Timer {
|
||||
self.scheduler.timer(duration)
|
||||
}
|
||||
}
|
||||
|
||||
impl ForegroundExecutor {
|
||||
pub fn new(session_id: SessionId, scheduler: Arc<dyn Scheduler>) -> Self {
|
||||
assert!(
|
||||
scheduler.is_main_thread(),
|
||||
"ForegroundExecutor must be created on the same thread as the Scheduler"
|
||||
);
|
||||
Self {
|
||||
session_id,
|
||||
scheduler,
|
||||
not_send: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BackgroundExecutor {
|
||||
pub fn new(scheduler: Arc<dyn Scheduler>) -> Self {
|
||||
Self { scheduler }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BackgroundExecutor {
|
||||
scheduler: Arc<dyn Scheduler>,
|
||||
}
|
||||
|
||||
impl BackgroundExecutor {
|
||||
pub fn spawn<F>(&self, future: F) -> Task<F::Output>
|
||||
where
|
||||
F: Future + Send + 'static,
|
||||
F::Output: Send + 'static,
|
||||
{
|
||||
let scheduler = Arc::clone(&self.scheduler);
|
||||
let (runnable, task) = async_task::spawn(future, move |runnable| {
|
||||
scheduler.schedule_background(runnable);
|
||||
});
|
||||
runnable.schedule();
|
||||
Task(TaskState::Spawned(task))
|
||||
}
|
||||
|
||||
pub fn block_on<Fut: Future>(&self, future: Fut) -> Fut::Output {
|
||||
self.scheduler.block_on(future)
|
||||
}
|
||||
|
||||
pub fn block_with_timeout<Fut: Unpin + Future>(
|
||||
&self,
|
||||
future: &mut Fut,
|
||||
timeout: Duration,
|
||||
) -> Option<Fut::Output> {
|
||||
self.scheduler.block_with_timeout(future, timeout)
|
||||
}
|
||||
|
||||
pub fn timer(&self, duration: Duration) -> Timer {
|
||||
self.scheduler.timer(duration)
|
||||
}
|
||||
}
|
||||
|
||||
/// Task is a primitive that allows work to happen in the background.
|
||||
///
|
||||
/// It implements [`Future`] so you can `.await` on it.
|
||||
///
|
||||
/// If you drop a task it will be cancelled immediately. Calling [`Task::detach`] allows
|
||||
/// the task to continue running, but with no way to return a value.
|
||||
#[must_use]
|
||||
#[derive(Debug)]
|
||||
pub struct Task<T>(TaskState<T>);
|
||||
|
||||
#[derive(Debug)]
|
||||
enum TaskState<T> {
|
||||
/// A task that is ready to return a value
|
||||
Ready(Option<T>),
|
||||
|
||||
/// A task that is currently running.
|
||||
Spawned(async_task::Task<T>),
|
||||
}
|
||||
|
||||
impl<T> Task<T> {
|
||||
/// Creates a new task that will resolve with the value
|
||||
pub fn ready(val: T) -> Self {
|
||||
Task(TaskState::Ready(Some(val)))
|
||||
}
|
||||
|
||||
/// Detaching a task runs it to completion in the background
|
||||
pub fn detach(self) {
|
||||
match self {
|
||||
Task(TaskState::Ready(_)) => {}
|
||||
Task(TaskState::Spawned(task)) => task.detach(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Future for Task<T> {
|
||||
type Output = T;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
|
||||
match unsafe { self.get_unchecked_mut() } {
|
||||
Task(TaskState::Ready(val)) => Poll::Ready(val.take().unwrap()),
|
||||
Task(TaskState::Spawned(task)) => Pin::new(task).poll(cx),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
mod clock;
|
||||
mod executor;
|
||||
mod test_scheduler;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub use clock::*;
|
||||
pub use executor::*;
|
||||
pub use test_scheduler::*;
|
||||
|
||||
use async_task::Runnable;
|
||||
use futures::{FutureExt as _, channel::oneshot, future::LocalBoxFuture};
|
||||
use std::{
|
||||
future::Future,
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
pub trait Scheduler: Send + Sync {
|
||||
fn block(&self, future: LocalBoxFuture<()>, timeout: Option<Duration>);
|
||||
fn schedule_foreground(&self, session_id: SessionId, runnable: Runnable);
|
||||
fn schedule_background(&self, runnable: Runnable);
|
||||
fn timer(&self, timeout: Duration) -> Timer;
|
||||
fn is_main_thread(&self) -> bool;
|
||||
}
|
||||
|
||||
impl dyn Scheduler {
|
||||
pub fn block_on<Fut: Future>(&self, future: Fut) -> Fut::Output {
|
||||
let mut output = None;
|
||||
self.block(async { output = Some(future.await) }.boxed_local(), None);
|
||||
output.unwrap()
|
||||
}
|
||||
|
||||
pub fn block_with_timeout<Fut: Unpin + Future>(
|
||||
&self,
|
||||
future: &mut Fut,
|
||||
timeout: Duration,
|
||||
) -> Option<Fut::Output> {
|
||||
let mut output = None;
|
||||
self.block(
|
||||
async { output = Some(future.await) }.boxed_local(),
|
||||
Some(timeout),
|
||||
);
|
||||
output
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
pub struct SessionId(u16);
|
||||
|
||||
pub struct Timer(oneshot::Receiver<()>);
|
||||
|
||||
impl Future for Timer {
|
||||
type Output = ();
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> {
|
||||
match self.0.poll_unpin(cx) {
|
||||
Poll::Ready(_) => Poll::Ready(()),
|
||||
Poll::Pending => Poll::Pending,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
use crate::{
|
||||
BackgroundExecutor, Clock as _, ForegroundExecutor, Scheduler, SessionId, TestClock, Timer,
|
||||
};
|
||||
use async_task::Runnable;
|
||||
use chrono::{DateTime, Duration as ChronoDuration, Utc};
|
||||
use futures::{FutureExt as _, channel::oneshot, future::LocalBoxFuture};
|
||||
use parking_lot::Mutex;
|
||||
use rand::prelude::*;
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
future::Future,
|
||||
panic::{self, AssertUnwindSafe},
|
||||
pin::Pin,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering::SeqCst},
|
||||
},
|
||||
task::{Context, Poll, Wake, Waker},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
pub struct TestScheduler {
|
||||
clock: Arc<TestClock>,
|
||||
rng: Arc<Mutex<StdRng>>,
|
||||
state: Mutex<SchedulerState>,
|
||||
pub thread_id: thread::ThreadId,
|
||||
pub config: SchedulerConfig,
|
||||
}
|
||||
|
||||
impl TestScheduler {
|
||||
/// Run a test once with default configuration (seed 0)
|
||||
pub fn once<R>(f: impl AsyncFnOnce(Arc<TestScheduler>) -> R) -> R {
|
||||
Self::with_seed(0, f)
|
||||
}
|
||||
|
||||
/// Run a test multiple times with sequential seeds (0, 1, 2, ...)
|
||||
pub fn many<R>(iterations: usize, mut f: impl AsyncFnMut(Arc<TestScheduler>) -> R) -> Vec<R> {
|
||||
(0..iterations as u64)
|
||||
.map(|seed| {
|
||||
let mut unwind_safe_f = AssertUnwindSafe(&mut f);
|
||||
match panic::catch_unwind(move || Self::with_seed(seed, &mut *unwind_safe_f)) {
|
||||
Ok(result) => result,
|
||||
Err(error) => {
|
||||
eprintln!("Failing Seed: {seed}");
|
||||
panic::resume_unwind(error);
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Run a test once with a specific seed
|
||||
pub fn with_seed<R>(seed: u64, f: impl AsyncFnOnce(Arc<TestScheduler>) -> R) -> R {
|
||||
let scheduler = Arc::new(TestScheduler::new(SchedulerConfig::with_seed(seed)));
|
||||
let future = f(scheduler.clone());
|
||||
let result = scheduler.block_on(future);
|
||||
scheduler.run();
|
||||
result
|
||||
}
|
||||
|
||||
pub fn new(config: SchedulerConfig) -> Self {
|
||||
Self {
|
||||
rng: Arc::new(Mutex::new(StdRng::seed_from_u64(config.seed))),
|
||||
state: Mutex::new(SchedulerState {
|
||||
runnables: VecDeque::new(),
|
||||
timers: Vec::new(),
|
||||
randomize_order: config.randomize_order,
|
||||
allow_parking: config.allow_parking,
|
||||
next_session_id: SessionId(0),
|
||||
}),
|
||||
thread_id: thread::current().id(),
|
||||
clock: Arc::new(TestClock::new()),
|
||||
config,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clock(&self) -> Arc<TestClock> {
|
||||
self.clock.clone()
|
||||
}
|
||||
|
||||
pub fn rng(&self) -> Arc<Mutex<StdRng>> {
|
||||
self.rng.clone()
|
||||
}
|
||||
|
||||
/// Create a foreground executor for this scheduler
|
||||
pub fn foreground(self: &Arc<Self>) -> ForegroundExecutor {
|
||||
let session_id = {
|
||||
let mut state = self.state.lock();
|
||||
state.next_session_id.0 += 1;
|
||||
state.next_session_id
|
||||
};
|
||||
ForegroundExecutor::new(session_id, self.clone())
|
||||
}
|
||||
|
||||
/// Create a background executor for this scheduler
|
||||
pub fn background(self: &Arc<Self>) -> BackgroundExecutor {
|
||||
BackgroundExecutor::new(self.clone())
|
||||
}
|
||||
|
||||
pub fn block_on<Fut: Future>(&self, future: Fut) -> Fut::Output {
|
||||
(self as &dyn Scheduler).block_on(future)
|
||||
}
|
||||
|
||||
pub fn yield_random(&self) -> Yield {
|
||||
Yield(self.rng.lock().random_range(0..20))
|
||||
}
|
||||
|
||||
pub fn run(&self) {
|
||||
while self.step() || self.advance_clock() {
|
||||
// Continue until no work remains
|
||||
}
|
||||
}
|
||||
|
||||
fn step(&self) -> bool {
|
||||
let elapsed_timers = {
|
||||
let mut state = self.state.lock();
|
||||
let end_ix = state
|
||||
.timers
|
||||
.partition_point(|timer| timer.expiration <= self.clock.now());
|
||||
state.timers.drain(..end_ix).collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
if !elapsed_timers.is_empty() {
|
||||
return true;
|
||||
}
|
||||
|
||||
let runnable = self.state.lock().runnables.pop_front();
|
||||
if let Some(runnable) = runnable {
|
||||
runnable.run();
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
fn advance_clock(&self) -> bool {
|
||||
if let Some(timer) = self.state.lock().timers.first() {
|
||||
self.clock.set_now(timer.expiration);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Scheduler for TestScheduler {
|
||||
fn is_main_thread(&self) -> bool {
|
||||
thread::current().id() == self.thread_id
|
||||
}
|
||||
|
||||
fn schedule_foreground(&self, session_id: SessionId, runnable: Runnable) {
|
||||
let mut state = self.state.lock();
|
||||
let ix = if state.randomize_order {
|
||||
let start_ix = state
|
||||
.runnables
|
||||
.iter()
|
||||
.rposition(|task| task.session_id == Some(session_id))
|
||||
.map_or(0, |ix| ix + 1);
|
||||
self.rng
|
||||
.lock()
|
||||
.random_range(start_ix..=state.runnables.len())
|
||||
} else {
|
||||
state.runnables.len()
|
||||
};
|
||||
state.runnables.insert(
|
||||
ix,
|
||||
ScheduledRunnable {
|
||||
session_id: Some(session_id),
|
||||
runnable,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn schedule_background(&self, runnable: Runnable) {
|
||||
let mut state = self.state.lock();
|
||||
let ix = if state.randomize_order {
|
||||
self.rng.lock().random_range(0..=state.runnables.len())
|
||||
} else {
|
||||
state.runnables.len()
|
||||
};
|
||||
state.runnables.insert(
|
||||
ix,
|
||||
ScheduledRunnable {
|
||||
session_id: None,
|
||||
runnable,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn timer(&self, duration: Duration) -> Timer {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
let expiration = self.clock.now() + ChronoDuration::from_std(duration).unwrap();
|
||||
let state = &mut *self.state.lock();
|
||||
state.timers.push(ScheduledTimer {
|
||||
expiration,
|
||||
_notify: tx,
|
||||
});
|
||||
state.timers.sort_by_key(|timer| timer.expiration);
|
||||
Timer(rx)
|
||||
}
|
||||
|
||||
/// Block until the given future completes, with an optional timeout. If the
|
||||
/// future is unable to make progress at any moment before the timeout and
|
||||
/// no other tasks or timers remain, we panic unless parking is allowed. If
|
||||
/// parking is allowed, we block up to the timeout or indefinitely if none
|
||||
/// is provided. This is to allow testing a mix of deterministic and
|
||||
/// non-deterministic async behavior, such as when interacting with I/O in
|
||||
/// an otherwise deterministic test.
|
||||
fn block(&self, mut future: LocalBoxFuture<()>, timeout: Option<Duration>) {
|
||||
let (parker, unparker) = parking::pair();
|
||||
let deadline = timeout.map(|timeout| Instant::now() + timeout);
|
||||
let awoken = Arc::new(AtomicBool::new(false));
|
||||
let waker = Waker::from(Arc::new(WakerFn::new({
|
||||
let awoken = awoken.clone();
|
||||
move || {
|
||||
awoken.store(true, SeqCst);
|
||||
unparker.unpark();
|
||||
}
|
||||
})));
|
||||
let max_ticks = if timeout.is_some() {
|
||||
self.rng
|
||||
.lock()
|
||||
.random_range(0..=self.config.max_timeout_ticks)
|
||||
} else {
|
||||
usize::MAX
|
||||
};
|
||||
let mut cx = Context::from_waker(&waker);
|
||||
|
||||
for _ in 0..max_ticks {
|
||||
let Poll::Pending = future.poll_unpin(&mut cx) else {
|
||||
break;
|
||||
};
|
||||
|
||||
let mut stepped = None;
|
||||
while self.rng.lock().random() && stepped.unwrap_or(true) {
|
||||
*stepped.get_or_insert(false) |= self.step();
|
||||
}
|
||||
|
||||
let stepped = stepped.unwrap_or(true);
|
||||
let awoken = awoken.swap(false, SeqCst);
|
||||
if !stepped && !awoken && !self.advance_clock() {
|
||||
if self.state.lock().allow_parking {
|
||||
if !park(&parker, deadline) {
|
||||
break;
|
||||
}
|
||||
} else if deadline.is_some() {
|
||||
break;
|
||||
} else {
|
||||
panic!("Parking forbidden");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SchedulerConfig {
|
||||
pub seed: u64,
|
||||
pub randomize_order: bool,
|
||||
pub allow_parking: bool,
|
||||
pub max_timeout_ticks: usize,
|
||||
}
|
||||
|
||||
impl SchedulerConfig {
|
||||
pub fn with_seed(seed: u64) -> Self {
|
||||
Self {
|
||||
seed,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for SchedulerConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
seed: 0,
|
||||
randomize_order: true,
|
||||
allow_parking: false,
|
||||
max_timeout_ticks: 1000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ScheduledRunnable {
|
||||
session_id: Option<SessionId>,
|
||||
runnable: Runnable,
|
||||
}
|
||||
|
||||
impl ScheduledRunnable {
|
||||
fn run(self) {
|
||||
self.runnable.run();
|
||||
}
|
||||
}
|
||||
|
||||
struct ScheduledTimer {
|
||||
expiration: DateTime<Utc>,
|
||||
_notify: oneshot::Sender<()>,
|
||||
}
|
||||
|
||||
struct SchedulerState {
|
||||
runnables: VecDeque<ScheduledRunnable>,
|
||||
timers: Vec<ScheduledTimer>,
|
||||
randomize_order: bool,
|
||||
allow_parking: bool,
|
||||
next_session_id: SessionId,
|
||||
}
|
||||
|
||||
struct WakerFn<F> {
|
||||
f: F,
|
||||
}
|
||||
|
||||
impl<F: Fn()> WakerFn<F> {
|
||||
fn new(f: F) -> Self {
|
||||
Self { f }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F: Fn()> Wake for WakerFn<F> {
|
||||
fn wake(self: Arc<Self>) {
|
||||
(self.f)();
|
||||
}
|
||||
|
||||
fn wake_by_ref(self: &Arc<Self>) {
|
||||
(self.f)();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Yield(usize);
|
||||
|
||||
impl Future for Yield {
|
||||
type Output = ();
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
|
||||
if self.0 == 0 {
|
||||
Poll::Ready(())
|
||||
} else {
|
||||
self.0 -= 1;
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn park(parker: &parking::Parker, deadline: Option<Instant>) -> bool {
|
||||
if let Some(deadline) = deadline {
|
||||
parker.park_deadline(deadline)
|
||||
} else {
|
||||
parker.park();
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
use super::*;
|
||||
use futures::{
|
||||
FutureExt,
|
||||
channel::{mpsc, oneshot},
|
||||
executor::block_on,
|
||||
future,
|
||||
sink::SinkExt,
|
||||
stream::{FuturesUnordered, StreamExt},
|
||||
};
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
collections::{BTreeSet, HashSet},
|
||||
pin::Pin,
|
||||
rc::Rc,
|
||||
sync::Arc,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn test_foreground_executor_spawn() {
|
||||
let result = TestScheduler::once(async |scheduler| {
|
||||
let task = scheduler.foreground().spawn(async move { 42 });
|
||||
task.await
|
||||
});
|
||||
assert_eq!(result, 42);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_background_executor_spawn() {
|
||||
TestScheduler::once(async |scheduler| {
|
||||
let task = scheduler.background().spawn(async move { 42 });
|
||||
let result = task.await;
|
||||
assert_eq!(result, 42);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_foreground_ordering() {
|
||||
let mut traces = HashSet::new();
|
||||
|
||||
TestScheduler::many(100, async |scheduler| {
|
||||
#[derive(Hash, PartialEq, Eq)]
|
||||
struct TraceEntry {
|
||||
session: usize,
|
||||
task: usize,
|
||||
}
|
||||
|
||||
let trace = Rc::new(RefCell::new(Vec::new()));
|
||||
|
||||
let foreground_1 = scheduler.foreground();
|
||||
for task in 0..10 {
|
||||
foreground_1
|
||||
.spawn({
|
||||
let trace = trace.clone();
|
||||
async move {
|
||||
trace.borrow_mut().push(TraceEntry { session: 0, task });
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
let foreground_2 = scheduler.foreground();
|
||||
for task in 0..10 {
|
||||
foreground_2
|
||||
.spawn({
|
||||
let trace = trace.clone();
|
||||
async move {
|
||||
trace.borrow_mut().push(TraceEntry { session: 1, task });
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
scheduler.run();
|
||||
|
||||
assert_eq!(
|
||||
trace
|
||||
.borrow()
|
||||
.iter()
|
||||
.filter(|entry| entry.session == 0)
|
||||
.map(|entry| entry.task)
|
||||
.collect::<Vec<_>>(),
|
||||
(0..10).collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(
|
||||
trace
|
||||
.borrow()
|
||||
.iter()
|
||||
.filter(|entry| entry.session == 1)
|
||||
.map(|entry| entry.task)
|
||||
.collect::<Vec<_>>(),
|
||||
(0..10).collect::<Vec<_>>()
|
||||
);
|
||||
|
||||
traces.insert(trace.take());
|
||||
});
|
||||
|
||||
assert!(traces.len() > 1, "Expected at least two traces");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_timer_ordering() {
|
||||
TestScheduler::many(1, async |scheduler| {
|
||||
let background = scheduler.background();
|
||||
let futures = FuturesUnordered::new();
|
||||
futures.push(
|
||||
async {
|
||||
background.timer(Duration::from_millis(100)).await;
|
||||
2
|
||||
}
|
||||
.boxed(),
|
||||
);
|
||||
futures.push(
|
||||
async {
|
||||
background.timer(Duration::from_millis(50)).await;
|
||||
1
|
||||
}
|
||||
.boxed(),
|
||||
);
|
||||
futures.push(
|
||||
async {
|
||||
background.timer(Duration::from_millis(150)).await;
|
||||
3
|
||||
}
|
||||
.boxed(),
|
||||
);
|
||||
assert_eq!(futures.collect::<Vec<_>>().await, vec![1, 2, 3]);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_send_from_bg_to_fg() {
|
||||
TestScheduler::once(async |scheduler| {
|
||||
let foreground = scheduler.foreground();
|
||||
let background = scheduler.background();
|
||||
|
||||
let (sender, receiver) = oneshot::channel::<i32>();
|
||||
|
||||
background
|
||||
.spawn(async move {
|
||||
sender.send(42).unwrap();
|
||||
})
|
||||
.detach();
|
||||
|
||||
let task = foreground.spawn(async move { receiver.await.unwrap() });
|
||||
let result = task.await;
|
||||
assert_eq!(result, 42);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_randomize_order() {
|
||||
// Test deterministic mode: different seeds should produce same execution order
|
||||
let mut deterministic_results = HashSet::new();
|
||||
for seed in 0..10 {
|
||||
let config = SchedulerConfig {
|
||||
seed,
|
||||
randomize_order: false,
|
||||
..Default::default()
|
||||
};
|
||||
let order = block_on(capture_execution_order(config));
|
||||
assert_eq!(order.len(), 6);
|
||||
deterministic_results.insert(order);
|
||||
}
|
||||
|
||||
// All deterministic runs should produce the same result
|
||||
assert_eq!(
|
||||
deterministic_results.len(),
|
||||
1,
|
||||
"Deterministic mode should always produce same execution order"
|
||||
);
|
||||
|
||||
// Test randomized mode: different seeds can produce different execution orders
|
||||
let mut randomized_results = HashSet::new();
|
||||
for seed in 0..20 {
|
||||
let config = SchedulerConfig::with_seed(seed);
|
||||
let order = block_on(capture_execution_order(config));
|
||||
assert_eq!(order.len(), 6);
|
||||
randomized_results.insert(order);
|
||||
}
|
||||
|
||||
// Randomized mode should produce multiple different execution orders
|
||||
assert!(
|
||||
randomized_results.len() > 1,
|
||||
"Randomized mode should produce multiple different orders"
|
||||
);
|
||||
}
|
||||
|
||||
async fn capture_execution_order(config: SchedulerConfig) -> Vec<String> {
|
||||
let scheduler = Arc::new(TestScheduler::new(config));
|
||||
let foreground = scheduler.foreground();
|
||||
let background = scheduler.background();
|
||||
|
||||
let (sender, receiver) = mpsc::unbounded::<String>();
|
||||
|
||||
// Spawn foreground tasks
|
||||
for i in 0..3 {
|
||||
let mut sender = sender.clone();
|
||||
foreground
|
||||
.spawn(async move {
|
||||
sender.send(format!("fg-{}", i)).await.ok();
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
// Spawn background tasks
|
||||
for i in 0..3 {
|
||||
let mut sender = sender.clone();
|
||||
background
|
||||
.spawn(async move {
|
||||
sender.send(format!("bg-{}", i)).await.ok();
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
drop(sender); // Close sender to signal no more messages
|
||||
scheduler.run();
|
||||
|
||||
receiver.collect().await
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_block() {
|
||||
let scheduler = Arc::new(TestScheduler::new(SchedulerConfig::default()));
|
||||
let executor = BackgroundExecutor::new(scheduler);
|
||||
let (tx, rx) = oneshot::channel();
|
||||
|
||||
// Spawn background task to send value
|
||||
let _ = executor
|
||||
.spawn(async move {
|
||||
tx.send(42).unwrap();
|
||||
})
|
||||
.detach();
|
||||
|
||||
// Block on receiving the value
|
||||
let result = executor.block_on(async { rx.await.unwrap() });
|
||||
assert_eq!(result, 42);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "Parking forbidden")]
|
||||
fn test_parking_panics() {
|
||||
let scheduler = Arc::new(TestScheduler::new(SchedulerConfig::default()));
|
||||
let executor = BackgroundExecutor::new(scheduler);
|
||||
executor.block_on(future::pending::<()>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_block_with_parking() {
|
||||
let config = SchedulerConfig {
|
||||
allow_parking: true,
|
||||
..Default::default()
|
||||
};
|
||||
let scheduler = Arc::new(TestScheduler::new(config));
|
||||
let executor = BackgroundExecutor::new(scheduler);
|
||||
let (tx, rx) = oneshot::channel();
|
||||
|
||||
// Spawn background task to send value
|
||||
let _ = executor
|
||||
.spawn(async move {
|
||||
tx.send(42).unwrap();
|
||||
})
|
||||
.detach();
|
||||
|
||||
// Block on receiving the value (will park if needed)
|
||||
let result = executor.block_on(async { rx.await.unwrap() });
|
||||
assert_eq!(result, 42);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_helper_methods() {
|
||||
// Test the once method
|
||||
let result = TestScheduler::once(async |scheduler: Arc<TestScheduler>| {
|
||||
let background = scheduler.background();
|
||||
background.spawn(async { 42 }).await
|
||||
});
|
||||
assert_eq!(result, 42);
|
||||
|
||||
// Test the many method
|
||||
let results = TestScheduler::many(3, async |scheduler: Arc<TestScheduler>| {
|
||||
let background = scheduler.background();
|
||||
background.spawn(async { 10 }).await
|
||||
});
|
||||
assert_eq!(results, vec![10, 10, 10]);
|
||||
|
||||
// Test the with_seed method
|
||||
let result = TestScheduler::with_seed(123, async |scheduler: Arc<TestScheduler>| {
|
||||
let background = scheduler.background();
|
||||
|
||||
// Spawn a background task and wait for its result
|
||||
let task = background.spawn(async { 99 });
|
||||
task.await
|
||||
});
|
||||
assert_eq!(result, 99);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_block_with_timeout() {
|
||||
// Test case: future completes within timeout
|
||||
TestScheduler::once(async |scheduler| {
|
||||
let background = scheduler.background();
|
||||
let mut future = future::ready(42);
|
||||
let output = background.block_with_timeout(&mut future, Duration::from_millis(100));
|
||||
assert_eq!(output, Some(42));
|
||||
});
|
||||
|
||||
// Test case: future times out
|
||||
TestScheduler::once(async |scheduler| {
|
||||
let background = scheduler.background();
|
||||
let mut future = future::pending::<()>();
|
||||
let output = background.block_with_timeout(&mut future, Duration::from_millis(50));
|
||||
assert_eq!(output, None);
|
||||
});
|
||||
|
||||
// Test case: future makes progress via timer but still times out
|
||||
let mut results = BTreeSet::new();
|
||||
TestScheduler::many(100, async |scheduler| {
|
||||
let background = scheduler.background();
|
||||
let mut task = background.spawn(async move {
|
||||
Yield { polls: 10 }.await;
|
||||
42
|
||||
});
|
||||
let output = background.block_with_timeout(&mut task, Duration::from_millis(50));
|
||||
results.insert(output);
|
||||
});
|
||||
assert_eq!(
|
||||
results.into_iter().collect::<Vec<_>>(),
|
||||
vec![None, Some(42)]
|
||||
);
|
||||
}
|
||||
|
||||
struct Yield {
|
||||
polls: usize,
|
||||
}
|
||||
|
||||
impl Future for Yield {
|
||||
type Output = ();
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
self.polls -= 1;
|
||||
if self.polls == 0 {
|
||||
Poll::Ready(())
|
||||
} else {
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user