use pi_async_runtime::{
CloseState, ConcurrentRuntime, DefaultIdlePolicy, LocalTaskDispatch, ManualClock, NoHooks,
RuntimeBlockOn, RuntimeControl, RuntimeOptions, RuntimeQuery, RuntimeQueues, RuntimeTime,
SerialRuntime, TaskDispatch,
};
use pi_async_task::{definitions::TaskOwnerId, Runnable};
use pi_async_task_queue::{InternalTaskQueue, QueueCleanupProgress, QueuePushError, TaskQueue};
use std::{
cell::Cell,
future::{poll_fn, Future},
panic::{catch_unwind, panic_any, AssertUnwindSafe},
pin::pin,
rc::Rc,
sync::{atomic::{AtomicUsize, Ordering}, Arc},
task::Poll,
time::Duration,
};
struct WrappedReadyQueue(TaskQueue);
impl InternalTaskQueue for WrappedReadyQueue {
fn try_push_internal_front(&mut self, task: Runnable) -> Result<(), QueuePushError> {
self.0.try_push_internal_front(task)
}
fn try_push_internal_back(&mut self, task: Runnable) -> Result<(), QueuePushError> {
self.0.try_push_internal_back(task)
}
fn pop_internal_front(&mut self) -> Option<Runnable> {
self.0.pop_internal_front()
}
fn internal_len(&self) -> usize {
self.0.internal_len()
}
fn is_internal_closed(&self) -> bool {
self.0.is_internal_closed()
}
fn internal_owner_id(&self) -> Option<TaskOwnerId> {
self.0.internal_owner_id()
}
fn clear_internal(&mut self) -> pi_result::Result<QueueCleanupProgress> {
self.0.clear_internal()
}
fn close_internal(&mut self) -> pi_result::Result<QueueCleanupProgress> {
self.0.close_internal()
}
}
fn spawn_and_time_local<R: RuntimeBlockOn + LocalTaskDispatch + RuntimeTime + RuntimeQuery>(
runtime: &R,
) {
runtime.block_on(async {
let local = Rc::new(40_u32);
let result = R::spawn_local(async move { *local + 2 }).unwrap();
let mut sleep = pin!(R::sleep_local(Duration::from_millis(1)).unwrap());
poll_fn(|cx| {
assert!(sleep.as_mut().poll(cx).is_pending());
assert_eq!(runtime.timer_registration_count(), 1);
Poll::Ready(())
})
.await;
sleep.await.unwrap();
assert_eq!(result.await.unwrap(), 42);
});
}
#[test]
fn internal_queue_factory_keeps_local_timer_and_admission() {
let options = RuntimeOptions::default();
let calls = Cell::new(0);
let invalid = RuntimeQueues::default().with_internal_factory(|context| {
calls.set(calls.get() + 1);
Ok(WrappedReadyQueue(context.task_queue()))
});
let error = SerialRuntime::with_queues(options, invalid).err().unwrap();
assert_eq!(*error.current_context(), pi_result::ErrorKind::InvalidInput);
assert!(format!("{error:?}").contains("内部任务队列"));
assert_eq!(calls.get(), 0);
let invalid = RuntimeQueues::default()
.without_timer()
.with_internal_factory(|context| {
calls.set(calls.get() + 1);
Ok(WrappedReadyQueue(context.task_queue()))
});
let explicit_error = SerialRuntime::with_components_and_queues(
ManualClock,
DefaultIdlePolicy,
NoHooks,
options,
invalid,
)
.err()
.unwrap();
assert_eq!(
*explicit_error.current_context(),
pi_result::ErrorKind::InvalidInput
);
assert!(format!("{explicit_error:?}").contains("内部任务队列"));
assert_eq!(calls.get(), 0);
pi_clock_manual::global::try_init().unwrap();
let mut runtime = ConcurrentRuntime::with_queues(
options,
RuntimeQueues::default().with_internal_factory(|context| {
calls.set(calls.get() + 1);
Ok(WrappedReadyQueue(context.task_queue()))
}),
)
.unwrap();
assert_eq!(calls.get(), 1);
let result = runtime.spawn(async { "原普通任务" }).unwrap();
assert_eq!(runtime.block_on(result).unwrap(), "原普通任务");
spawn_and_time_local(&runtime);
runtime.request_close();
assert!(runtime.run_once().unwrap().service_closed);
assert_eq!(runtime.close_state(), CloseState::Completed);
}
#[derive(Default)]
struct UnboundReadyQueue {
owned: std::collections::VecDeque<Runnable>,
closed: bool,
events: Rc<Cell<(usize, usize, usize)>>,
push_panic: Option<Arc<u32>>,
}
impl InternalTaskQueue for UnboundReadyQueue {
fn try_push_internal_front(&mut self, task: Runnable) -> Result<(), QueuePushError> {
if self.closed {
return Err(QueuePushError {
task,
cause: pi_async_task_queue::QueuePushErrorKind::Closed,
});
}
self.owned.push_front(task);
Ok(())
}
fn try_push_internal_back(&mut self, task: Runnable) -> Result<(), QueuePushError> {
if self.closed {
return Err(QueuePushError {
task,
cause: pi_async_task_queue::QueuePushErrorKind::Closed,
});
}
if let Some(payload) = self.push_panic.take() {
panic_any(payload);
}
let (pushed, popped, closed) = self.events.get();
self.events.set((pushed + 1, popped, closed));
self.owned.push_back(task);
Ok(())
}
fn pop_internal_front(&mut self) -> Option<Runnable> {
if let Some(task) = self.owned.pop_front() {
let (pushed, popped, closed) = self.events.get();
self.events.set((pushed, popped + 1, closed));
Some(task)
} else {
None
}
}
fn internal_len(&self) -> usize {
self.owned.len()
}
fn internal_owner_id(&self) -> Option<TaskOwnerId> {
None
}
fn is_internal_closed(&self) -> bool {
self.closed
}
fn clear_internal(&mut self) -> pi_result::Result<QueueCleanupProgress> {
self.owned.clear();
Ok(QueueCleanupProgress::Complete)
}
fn close_internal(&mut self) -> pi_result::Result<QueueCleanupProgress> {
self.closed = true;
let (pushed, popped, closed) = self.events.get();
self.events.set((pushed, popped, closed + 1));
self.clear_internal()
}
}
#[test]
fn internal_queue_by_value_composes_with_omitted_sources() {
let events = Rc::new(Cell::new((0, 0, 0)));
let queue = UnboundReadyQueue {
events: Rc::clone(&events),
..UnboundReadyQueue::default()
};
let mut runtime = ConcurrentRuntime::with_queues(
RuntimeOptions::default(),
RuntimeQueues::default()
.without_timer()
.with_internal(queue)
.without_idle(),
)
.unwrap();
let result = runtime.spawn(async move { 201 }).unwrap();
assert_eq!(runtime.block_on(result).unwrap(), 201);
assert_eq!(events.get(), (1, 1, 0));
runtime.request_close();
assert!(runtime.run_once().unwrap().service_closed);
assert_eq!(runtime.close_state(), CloseState::Completed);
assert_eq!(events.get(), (1, 1, 1));
}
struct ObserveFutureDrop(Arc<AtomicUsize>);
impl Drop for ObserveFutureDrop {
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::Relaxed);
}
}
#[test]
fn test_internal_queue_push_panic_returns_original_payload() {
let payload = Arc::new(31_u32);
let queue = UnboundReadyQueue {
push_panic: Some(Arc::clone(&payload)),
..UnboundReadyQueue::default()
};
let mut runtime = ConcurrentRuntime::with_queues(
RuntimeOptions::default(),
RuntimeQueues::default().without_timer().without_idle().with_internal(queue),
)
.unwrap();
let dropped = Arc::new(AtomicUsize::new(0));
let observe = ObserveFutureDrop(Arc::clone(&dropped));
let result = runtime
.spawn(async move {
let _observe = observe;
panic!("原任务尚未入队,不可被轮询");
})
.unwrap();
assert_eq!(runtime.external_task_count(), 1);
let panic = catch_unwind(AssertUnwindSafe(|| runtime.run_once()))
.expect_err("本轮推进须传播原队列的恐慌");
assert!(Arc::ptr_eq(panic.downcast_ref::<Arc<u32>>().unwrap(), &payload));
assert_eq!(runtime.external_task_count(), 0);
assert_eq!(runtime.internal_task_count(), 1);
assert_eq!(runtime.in_flight_task_count(), 1);
assert_eq!(dropped.load(Ordering::Relaxed), 0);
assert!(runtime.block_on(result).is_err());
runtime.request_close();
assert!(runtime.run_once().unwrap().service_closed);
assert_eq!(runtime.close_state(), CloseState::Completed);
assert_eq!(runtime.internal_task_count(), 0);
assert_eq!(runtime.in_flight_task_count(), 0);
assert_eq!(dropped.load(Ordering::Relaxed), 1);
}