test_executors 0.4.1

Simple async executors for testing.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Async runtime implementations for test executors.
//!
//! This module provides three runtime implementations that integrate with the
//! [`some_executor`] ecosystem, making them suitable for use in executor-agnostic code.
//!
//! # Available Runtimes
//!
//! - [`SpinRuntime`] - Polls futures in a busy loop (highest performance, highest CPU usage)
//! - [`SleepRuntime`] - Polls futures with sleeping between polls (balanced performance)
//! - [`SpawnRuntime`] - Spawns each future on a new OS thread (best for parallel execution)
//!
//! # Example
//!
//! ```
//! use test_executors::aruntime::SpinRuntime;
//! use some_executor::{SomeExecutor, task::{Task, Configuration}};
//!
//! # test_executors::spin_on(async {
//! let mut runtime = SpinRuntime::new();
//! let task = Task::without_notifications(
//!     "example".to_string(),
//!     Configuration::default(),
//!     async { 42 },
//! );
//! let observer = runtime.spawn(task);
//! if let some_executor::observer::FinishedObservation::Ready(value) = observer.await {
//!     assert_eq!(value, 42);
//! }
//! # });
//! ```
//!
//! # Integration with Global Executor
//!
//! You can set a runtime as the global executor using [`set_global_test_runtime`]:
//!
//! ```
//! use test_executors::aruntime;
//!
//! aruntime::set_global_test_runtime();
//! // Now some_executor::global_executor::spawn() will use SpawnRuntime
//! ```

use some_executor::observer::{Observer, ObserverNotified};
use some_executor::task::Task;
use some_executor::{
    BoxedSendObserver, BoxedSendObserverFuture, DynExecutor, ObjSafeTask, SomeExecutor,
    SomeExecutorExt,
};
use std::convert::Infallible;
use std::fmt::Display;
use std::future::Future;

/// A runtime that polls futures in a busy loop using [`crate::spin_on`].
///
/// This runtime provides the lowest latency but highest CPU usage. It continuously
/// polls futures without yielding the thread, making it ideal for CPU-bound tasks
/// or scenarios where minimal latency is critical.
///
/// # Characteristics
/// - **Latency**: Minimal - responds immediately to future readiness
/// - **CPU Usage**: Maximum - continuously burns CPU cycles
/// - **Blocking**: Yes - blocks the calling thread
/// - **Concurrency**: No - executes one future at a time
///
/// # Example
///
/// ```
/// use test_executors::aruntime::SpinRuntime;
/// use some_executor::{SomeExecutor, task::{Task, Configuration}};
///
/// # test_executors::spin_on(async {
/// let mut runtime = SpinRuntime::new();
/// let task = Task::without_notifications(
///     "example".to_string(),
///     Configuration::default(),
///     async { 42 },
/// );
/// let observer = runtime.spawn(task);
/// if let some_executor::observer::FinishedObservation::Ready(value) = observer.await {
///     assert_eq!(value, 42);
/// }
/// # });
/// ```
///
/// # When to Use
/// - For CPU-bound async tasks
/// - When you need minimal latency
/// - In tests where deterministic behavior is important
/// - For short-lived futures that complete quickly
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SpinRuntime;

impl SpinRuntime {
    /// Creates a new `SpinRuntime`.
    ///
    /// # Example
    ///
    /// ```
    /// use test_executors::aruntime::SpinRuntime;
    ///
    /// let runtime = SpinRuntime::new();
    /// ```
    pub const fn new() -> Self {
        Self
    }
}

impl SomeExecutorExt for SpinRuntime {}
impl SomeExecutor for SpinRuntime {
    type ExecutorNotifier = Infallible;

    fn spawn<F: Future + Send + 'static, Notifier: ObserverNotified<F::Output>>(
        &mut self,
        task: Task<F, Notifier>,
    ) -> impl Observer<Value = F::Output>
    where
        Self: Sized,
    {
        logwise::info_sync!("spawned future: {label}", label = task.label());
        while task.poll_after() > crate::sys::time::Instant::now() {
            std::hint::spin_loop()
        }
        let (spawned, observer) = task.spawn(self);
        crate::spin_on(spawned);
        observer
    }

    async fn spawn_async<F: Future + Send + 'static, Notifier: ObserverNotified<F::Output> + Send>(
        &mut self,
        task: Task<F, Notifier>,
    ) -> impl Observer<Value = F::Output>
    where
        Self: Sized,
        F::Output: Send + Unpin,
    {
        logwise::info_sync!("spawned future: {label}", label = task.label());
        let (spawned, observer) = task.spawn(self);
        while spawned.poll_after() > crate::sys::time::Instant::now() {
            std::hint::spin_loop()
        }
        crate::spin_on(spawned);
        observer
    }

    fn spawn_objsafe(&mut self, task: ObjSafeTask) -> BoxedSendObserver {
        logwise::info_sync!("spawned future: {label}", label = task.label());

        let (spawned, observer) = task.spawn_objsafe(self);
        while spawned.poll_after() > crate::sys::time::Instant::now() {
            std::hint::spin_loop()
        }
        crate::spin_on(spawned);
        Box::new(observer)
    }

    fn spawn_objsafe_async<'s>(&'s mut self, task: ObjSafeTask) -> BoxedSendObserverFuture<'s> {
        #[allow(clippy::async_yields_async)]
        Box::new(async { Self::spawn_objsafe(self, task) })
    }

    fn clone_box(&self) -> Box<DynExecutor> {
        Box::new(*self)
    }

    fn executor_notifier(&mut self) -> Option<Self::ExecutorNotifier> {
        None
    }
}

/// A runtime that polls futures with sleeping between polls using [`crate::sleep_on`].
///
/// This runtime provides a balance between responsiveness and CPU efficiency. It uses
/// a condition variable to sleep when futures return `Poll::Pending`, waking only when
/// the waker is triggered.
///
/// # Characteristics
/// - **Latency**: Moderate - wakes on waker notification
/// - **CPU Usage**: Low - sleeps when waiting
/// - **Blocking**: Yes - blocks the calling thread
/// - **Concurrency**: No - executes one future at a time
///
/// # Example
///
/// ```
/// use test_executors::aruntime::SleepRuntime;
/// use some_executor::{SomeExecutor, task::{Task, Configuration}};
///
/// # test_executors::spin_on(async {
/// let mut runtime = SleepRuntime::new();
/// let task = Task::without_notifications(
///     "io_task".to_string(),
///     Configuration::default(),
///     async { "completed".to_string() },
/// );
/// let observer = runtime.spawn(task);
/// if let some_executor::observer::FinishedObservation::Ready(value) = observer.await {
///     assert_eq!(value, "completed");
/// }
/// # });
/// ```
///
/// # When to Use
/// - For I/O-bound async tasks
/// - When you want to avoid burning CPU cycles
/// - For longer-running futures
/// - In tests that involve actual async I/O or timers
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SleepRuntime;
impl SleepRuntime {
    /// Creates a new `SleepRuntime`.
    ///
    /// # Example
    ///
    /// ```
    /// use test_executors::aruntime::SleepRuntime;
    ///
    /// let runtime = SleepRuntime::new();
    /// ```
    pub const fn new() -> Self {
        Self
    }
}
impl SomeExecutorExt for SleepRuntime {}

impl SomeExecutor for SleepRuntime {
    type ExecutorNotifier = Infallible;

    fn spawn<F: Future + Send + 'static, Notifier: ObserverNotified<F::Output>>(
        &mut self,
        task: Task<F, Notifier>,
    ) -> impl Observer<Value = F::Output>
    where
        Self: Sized,
        F::Output: Send,
    {
        logwise::info_sync!("spawned future: {label}", label = task.label());
        let (spawned, observer) = task.spawn(self);
        let now = crate::sys::time::Instant::now();
        if spawned.poll_after() > now {
            let dur = now.duration_since(spawned.poll_after());
            std::thread::sleep(dur);
        }
        crate::sleep_on(spawned);
        observer
    }

    async fn spawn_async<F: Future + Send + 'static, Notifier: ObserverNotified<F::Output> + Send>(
        &mut self,
        task: Task<F, Notifier>,
    ) -> impl Observer<Value = F::Output>
    where
        Self: Sized,
        F::Output: Send + Unpin,
    {
        logwise::info_sync!("spawned future: {label}", label = task.label());
        let (spawned, observer) = task.spawn(self);
        let now = crate::sys::time::Instant::now();
        if spawned.poll_after() > now {
            let dur = spawned.poll_after() - now;
            std::thread::sleep(dur);
        }
        crate::sleep_on(spawned);
        observer
    }

    fn spawn_objsafe(&mut self, task: ObjSafeTask) -> BoxedSendObserver {
        logwise::info_sync!("spawned future: {label}", label = task.label());
        let (spawned, observer) = task.spawn_objsafe(self);
        let now = crate::sys::time::Instant::now();
        if spawned.poll_after() > now {
            let dur = now.duration_since(spawned.poll_after());
            std::thread::sleep(dur);
        }
        crate::sleep_on(spawned);
        Box::new(observer)
    }

    fn spawn_objsafe_async<'s>(&'s mut self, task: ObjSafeTask) -> BoxedSendObserverFuture<'s> {
        #[allow(clippy::async_yields_async)]
        Box::new(async { Self::spawn_objsafe(self, task) })
    }

    fn clone_box(&self) -> Box<DynExecutor> {
        Box::new(*self)
    }

    fn executor_notifier(&mut self) -> Option<Self::ExecutorNotifier> {
        None
    }
}

/// A runtime that spawns each future on a new OS thread using [`crate::spawn_on`].
///
/// This runtime provides true parallelism by running each future on its own thread.
/// It returns immediately after spawning, making it suitable for fire-and-forget tasks
/// or when you need parallel execution.
///
/// # Characteristics
/// - **Latency**: Low - returns immediately after spawning
/// - **CPU Usage**: Efficient - only uses CPU when futures are ready
/// - **Blocking**: No - doesn't block the calling thread
/// - **Concurrency**: Yes - can run multiple futures in parallel
///
/// # Example
///
/// ```
/// use test_executors::aruntime::SpawnRuntime;
/// use some_executor::{SomeExecutor, task::{Task, Configuration}};
/// use std::sync::{Arc, Mutex};
///
/// # test_executors::spin_on(async {
/// let mut runtime = SpawnRuntime::new();
/// let results = Arc::new(Mutex::new(Vec::new()));
/// let results_clone = results.clone();
///
/// let task = Task::without_notifications(
///     "parallel_task".to_string(),
///     Configuration::default(),
///     async move {
///         results_clone.lock().unwrap().push(42);
///     },
/// );
/// let observer = runtime.spawn(task);
///
/// // The task runs in parallel
/// observer.await;
/// assert_eq!(results.lock().unwrap().len(), 1);
/// # });
/// ```
///
/// # When to Use
/// - For tasks that should run in parallel
/// - When you don't want to block the calling thread
/// - For fire-and-forget operations
/// - When you need true concurrency
///
/// # Thread Safety
/// The futures spawned must be `Send` since they will be moved to another thread.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SpawnRuntime;
impl SpawnRuntime {
    /// Creates a new `SpawnRuntime`.
    ///
    /// # Example
    ///
    /// ```
    /// use test_executors::aruntime::SpawnRuntime;
    ///
    /// let runtime = SpawnRuntime::new();
    /// ```
    pub const fn new() -> Self {
        Self
    }
}
impl SomeExecutorExt for SpawnRuntime {}

impl SomeExecutor for SpawnRuntime {
    type ExecutorNotifier = Infallible;

    fn spawn<F: Future + Send + 'static, Notifier: ObserverNotified<F::Output> + Send>(
        &mut self,
        task: Task<F, Notifier>,
    ) -> impl Observer<Value = F::Output>
    where
        Self: Sized,
        F::Output: Send,
    {
        logwise::info_sync!("spawned future: {label}", label = task.label());
        let (spawned, observer) = task.spawn(self);
        std::thread::spawn(move || {
            if spawned.poll_after() > crate::sys::time::Instant::now() {
                let dur = crate::sys::time::Instant::now().duration_since(spawned.poll_after());
                std::thread::sleep(dur);
            }
            crate::sleep_on(spawned);
        });
        observer
    }

    fn spawn_async<'s, F: Future + Send + 'static, Notifier: ObserverNotified<F::Output> + Send>(
        &'s mut self,
        task: Task<F, Notifier>,
    ) -> impl Future<Output = impl Observer<Value = F::Output>> + Send + 's
    where
        Self: Sized,
        F::Output: Send + Unpin,
    {
        logwise::info_sync!("spawned future: {label}", label = task.label());
        #[allow(clippy::async_yields_async)]
        async move {
            let (spawned, observer) = task.spawn(self);
            std::thread::spawn(move || {
                if spawned.poll_after() > crate::sys::time::Instant::now() {
                    let dur = spawned.poll_after() - crate::sys::time::Instant::now();
                    std::thread::sleep(dur);
                }
                crate::sleep_on(spawned);
            });
            observer
        }
    }

    fn spawn_objsafe(&mut self, task: ObjSafeTask) -> BoxedSendObserver {
        logwise::info_sync!("spawned future: {label}", label = task.label());
        let (spawned, observer) = task.spawn_objsafe(self);
        std::thread::spawn(move || {
            if spawned.poll_after() > crate::sys::time::Instant::now() {
                let dur = crate::sys::time::Instant::now().duration_since(spawned.poll_after());
                std::thread::sleep(dur);
            }
            crate::sleep_on(spawned);
        });
        Box::new(observer)
    }

    fn spawn_objsafe_async<'s>(&'s mut self, task: ObjSafeTask) -> BoxedSendObserverFuture<'s> {
        #[allow(clippy::async_yields_async)]
        Box::new(async { Self::spawn_objsafe(self, task) })
    }

    fn clone_box(&self) -> Box<DynExecutor> {
        Box::new(*self)
    }

    fn executor_notifier(&mut self) -> Option<Self::ExecutorNotifier> {
        None
    }
}

//boilerplate

impl Display for SpinRuntime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "SpinRuntime")
    }
}

impl Display for SleepRuntime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "SleepRuntime")
    }
}

impl Display for SpawnRuntime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "SpawnRuntime")
    }
}

impl Default for SpinRuntime {
    fn default() -> Self {
        Self::new()
    }
}

impl Default for SleepRuntime {
    fn default() -> Self {
        Self::new()
    }
}

impl Default for SpawnRuntime {
    fn default() -> Self {
        Self::new()
    }
}

/// Sets a [`SpawnRuntime`] as the global executor for the `some_executor` ecosystem.
///
/// This function configures a `SpawnRuntime` instance as the global executor,
/// allowing code that uses `some_executor::global_executor::spawn()` to automatically
/// use this runtime for task execution.
///
/// # Example
///
/// ```
/// use test_executors::aruntime;
///
/// // Set the global runtime
/// aruntime::set_global_test_runtime();
///
/// // Now the global executor is available for use
/// // via some_executor::global_executor::global_executor()
/// ```
///
/// # Note
/// This function uses `SpawnRuntime`, which creates a new thread for each spawned
/// future. This provides good parallelism but may have higher overhead for many
/// small tasks.
pub fn set_global_test_runtime() {
    let as_dyn = Box::new(SpawnRuntime) as Box<DynExecutor>;
    some_executor::global_executor::set_global_executor(as_dyn)
}
#[cfg(test)]
mod test {
    #[test]
    fn assert_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<super::SpinRuntime>();
        assert_send_sync::<super::SleepRuntime>();
        assert_send_sync::<super::SpawnRuntime>();
    }
}