use pi_async_executor::{
routing::LocalReadySubmit,
timer::{DefaultTimerItem, LocalTimerSubmit},
AdmissionRule, AdmissionState, DefaultExecutor, DefaultIdlePolicy, DefaultTimerDriver,
ExecutorClock, ExecutorOptions, NoHooks, NoIdleQueue, NoTimerQueue, ThreadNotifier,
};
use pi_async_runtime_core::{
block_on::block_on_root, CloseState, RuntimeControl, RuntimeId, RuntimeQuery, RuntimeStatus,
TaskConfig,
};
use pi_async_task::{Runnable, TaskError};
use pi_async_task_queue::{
CancelTimerKey, CancelTimerOptions, ExternalQueueManager, ExternalTaskQueue, MpscIdleTaskQueue,
MpscQueueOptions, MpscTaskQueue, MpscTaskQueueHandle, QueueCleanupProgress, TimerQueueError,
TimerSubmitError,
};
use pi_clock_manual::global::GlobalManualInstant;
use std::{
alloc::{GlobalAlloc, Layout, System},
cell::Cell,
future::ready,
rc::Rc,
sync::atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed},
sync::Arc,
time::Duration,
};
struct ObservedAllocator;
#[global_allocator]
static ALLOCATOR: ObservedAllocator = ObservedAllocator;
thread_local! {
static PI_ASYNC_EXECUTOR_TEST_ALLOCATIONS: Cell<Option<usize>> = const { Cell::new(None) };
}
unsafe impl GlobalAlloc for ObservedAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let _ = PI_ASYNC_EXECUTOR_TEST_ALLOCATIONS.try_with(|current| {
if let Some(count) = current.get() {
current.set(Some(count.saturating_add(1)));
}
});
unsafe { System.alloc(layout) }
}
unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
unsafe { System.dealloc(pointer, layout) };
}
}
struct AdmitAll;
impl AdmissionRule for AdmitAll {
fn admits_external(&self, _: &AdmissionState) -> bool {
true
}
}
struct NoLocalBinding;
impl LocalReadySubmit for NoLocalBinding {
fn try_push_local(_: RuntimeId, task: Runnable) -> Result<(), Runnable> {
Err(task)
}
}
impl LocalTimerSubmit<DefaultTimerItem<TestClock, Self>> for NoLocalBinding {
fn try_push_local(
_: RuntimeId,
_: GlobalManualInstant,
item: DefaultTimerItem<TestClock, Self>,
) -> Result<CancelTimerKey, TimerSubmitError<DefaultTimerItem<TestClock, Self>>> {
Err(TimerSubmitError {
item,
cause: TimerQueueError::WrongOwner,
})
}
}
type Timer = DefaultTimerDriver<TestClock, NoLocalBinding>;
type TimedAndIdle =
DefaultExecutor<TestClock, MpscTaskQueue, MpscIdleTaskQueue, Timer, NoLocalBinding>;
type TimedOnly = DefaultExecutor<TestClock, MpscTaskQueue, NoIdleQueue, Timer, NoLocalBinding>;
type IdleOnly = DefaultExecutor<
UnusedClock,
MpscTaskQueue,
MpscIdleTaskQueue,
NoTimerQueue<()>,
NoLocalBinding,
>;
type Neither =
DefaultExecutor<UnusedClock, MpscTaskQueue, NoIdleQueue, NoTimerQueue<()>, NoLocalBinding>;
fn external() -> MpscTaskQueue {
MpscTaskQueue::new(MpscQueueOptions::default()).unwrap()
}
fn idle() -> MpscIdleTaskQueue {
MpscIdleTaskQueue::new(MpscQueueOptions::default()).unwrap()
}
fn make_timer(
id: RuntimeId,
clock: &TestClock,
notifier: ThreadNotifier,
) -> pi_result::Result<Timer> {
Timer::new(id, clock.clone(), notifier, CancelTimerOptions::default())
}
#[derive(Clone)]
struct TestClock(Arc<AtomicUsize>);
impl ExecutorClock for TestClock {
type Instant = GlobalManualInstant;
fn now(&self) -> pi_result::Result<GlobalManualInstant> {
GlobalManualInstant::ZERO.try_add(Duration::from_millis(self.0.load(Relaxed) as u64))
}
fn checked_add(
&self,
now: &Self::Instant,
duration: Duration,
) -> pi_result::Result<Self::Instant> {
now.try_add(duration)
}
fn remaining(
&self,
now: &Self::Instant,
deadline: &Self::Instant,
) -> pi_result::Result<Duration> {
if deadline <= now {
Ok(Duration::ZERO)
} else {
deadline.try_duration_since(*now)
}
}
}
#[derive(Clone, Copy)]
struct UnusedClock;
impl ExecutorClock for UnusedClock {
type Instant = ();
fn now(&self) -> pi_result::Result<()> {
panic!("省略定时任务队列后不得取时");
}
fn checked_add(&self, _: &(), _: Duration) -> pi_result::Result<()> {
panic!("省略定时任务队列后不得计算截止时间");
}
fn remaining(&self, _: &(), _: &()) -> pi_result::Result<Duration> {
panic!("省略定时任务队列后不得重查截止时间");
}
}
#[test]
fn four_queue_combinations_drive_and_close_in_one_process() {
let clock = TestClock(Arc::new(AtomicUsize::new(0)));
let options = ExecutorOptions::default();
let mut both =
TimedAndIdle::with_queues(clock.clone(), external(), idle(), options, make_timer).unwrap();
let mut timed =
TimedOnly::with_queues(clock.clone(), external(), NoIdleQueue, options, make_timer)
.unwrap();
let mut idle_only = IdleOnly::with_queues(
UnusedClock,
external(),
idle(),
options,
NoTimerQueue::default(),
)
.unwrap();
let mut neither = Neither::with_queue_factories(
UnusedClock,
external(),
NoIdleQueue,
|context| Ok(context.task_queue()),
options,
NoTimerQueue::default(),
)
.unwrap();
let both_handle = both.handle();
let timed_handle = timed.handle();
let idle_handle = idle_only.handle();
let neither_handle = neither.handle();
let (both_idle_task, both_idle_result) = both_handle
.create(ready(11), TaskConfig::<()>::default())
.unwrap();
both_handle.submit_idle(both_idle_task).unwrap();
let (idle_only_task, idle_only_result) = idle_handle
.create(ready(22), TaskConfig::<()>::default())
.unwrap();
idle_handle.submit_idle(idle_only_task).unwrap();
let (ordinary, ordinary_result) = neither_handle
.create(ready(33), TaskConfig::<()>::default())
.unwrap();
neither_handle.submit(ordinary).unwrap();
let both_timed_result = both_handle
.spawn_timing(ready(44), Duration::ZERO, TaskConfig::<()>::default())
.unwrap();
let timed_result = timed_handle
.spawn_timing(ready(55), Duration::ZERO, TaskConfig::<()>::default())
.unwrap();
assert_eq!(both_handle.timer_registration_count(), 1);
assert_eq!(timed_handle.timer_registration_count(), 1);
assert_eq!(both_handle.idle_task_count(), 1);
assert_eq!(idle_handle.idle_task_count(), 1);
assert_eq!(timed_handle.idle_task_count(), 0);
assert_eq!(idle_handle.timer_registration_count(), 0);
assert_eq!(neither_handle.timer_registration_count(), 0);
assert_eq!(neither_handle.idle_task_count(), 0);
clock.0.store(1000, Relaxed);
for _ in 0..8 {
both.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks)
.unwrap();
timed
.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks)
.unwrap();
idle_only
.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks)
.unwrap();
neither
.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks)
.unwrap();
}
let mut lease = neither.begin_drive();
let last = neither
.turn_with_lease(&mut lease, &AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks)
.unwrap();
assert!(last.sleep_for.is_some());
assert!(!last.immediate_work);
neither
.park_with_lease(&mut lease, &AdmitAll, &last, None)
.unwrap();
drop(lease);
assert_eq!(both_handle.in_flight_task_count(), 0);
assert_eq!(timed_handle.in_flight_task_count(), 0);
assert_eq!(idle_handle.in_flight_task_count(), 0);
assert_eq!(neither_handle.in_flight_task_count(), 0);
assert_eq!(both_handle.timer_registration_count(), 0);
assert_eq!(timed_handle.timer_registration_count(), 0);
assert_eq!(both_handle.idle_task_count(), 0);
assert_eq!(idle_handle.idle_task_count(), 0);
assert_eq!(neither_handle.external_task_count(), 0);
assert_eq!(block_on_root(both_idle_result).unwrap(), 11);
assert_eq!(block_on_root(idle_only_result).unwrap(), 22);
assert_eq!(block_on_root(ordinary_result).unwrap(), 33);
assert_eq!(block_on_root(both_timed_result).unwrap(), 44);
assert_eq!(block_on_root(timed_result).unwrap(), 55);
both_handle.request_close();
timed_handle.request_close();
idle_handle.request_close();
neither_handle.request_close();
assert!(
both.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks)
.unwrap()
.service_closed
);
assert!(
timed
.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks)
.unwrap()
.service_closed
);
assert!(
idle_only
.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks)
.unwrap()
.service_closed
);
assert!(
neither
.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks)
.unwrap()
.service_closed
);
assert_eq!(both_handle.close_state(), CloseState::Completed);
assert_eq!(timed_handle.close_state(), CloseState::Completed);
assert_eq!(idle_handle.close_state(), CloseState::Completed);
assert_eq!(neither_handle.close_state(), CloseState::Completed);
}
#[test]
fn dropping_executor_without_optional_queues_cleans_pending_ordinary_tasks() {
struct CountDrop(Arc<AtomicUsize>);
impl Drop for CountDrop {
fn drop(&mut self) {
self.0.fetch_add(1, Relaxed);
}
}
let executor = Neither::with_queues(
UnusedClock,
external(),
NoIdleQueue,
ExecutorOptions::default(),
NoTimerQueue::default(),
)
.unwrap();
let handle = executor.handle();
let drops = Arc::new(AtomicUsize::new(0));
let ownership = CountDrop(Arc::clone(&drops));
let (task, _result) = handle
.create(async move { drop(ownership) }, TaskConfig::<()>::default())
.unwrap();
handle.submit(task).unwrap();
drop(executor);
assert_eq!(drops.load(Relaxed), 1);
assert_eq!(handle.status(), RuntimeStatus::Closed);
assert_eq!(handle.close_state(), CloseState::Completed);
assert_eq!(handle.external_task_count(), 0);
}
#[test]
fn single_external_import_does_not_allocate_a_batch() {
let mut executor = Neither::with_queues(
UnusedClock,
external(),
NoIdleQueue,
ExecutorOptions::default(),
NoTimerQueue::default(),
)
.unwrap();
let handle = executor.handle();
let (warm, warmed) = handle.create(ready(1), TaskConfig::<()>::default()).unwrap();
handle.submit(warm).unwrap();
executor.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks).unwrap();
assert_eq!(block_on_root(warmed).unwrap(), 1);
let polls = Arc::new(AtomicUsize::new(0));
let observed = Arc::clone(&polls);
let (single, result) = handle
.create(async move { observed.fetch_add(1, Relaxed) }, TaskConfig::<()>::default())
.unwrap();
handle.submit(single).unwrap();
result.control_handle().cancel();
assert_eq!(handle.external_task_count(), 1);
PI_ASYNC_EXECUTOR_TEST_ALLOCATIONS.with(|count| count.set(Some(0)));
let turn = executor.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks);
let allocations = PI_ASYNC_EXECUTOR_TEST_ALLOCATIONS.with(|count| count.take().unwrap());
turn.unwrap();
assert_eq!(handle.external_task_count(), 0);
assert_eq!(handle.in_flight_task_count(), 0);
assert_eq!(polls.load(Relaxed), 0);
assert!(matches!(block_on_root(result), Err(TaskError::Cancelled)));
assert_eq!(allocations, 0);
let order = Arc::new(AtomicUsize::new(0));
let mut results = Vec::with_capacity(2);
for _ in 0..2 {
let order = Arc::clone(&order);
let (task, result) = handle
.create(async move { order.fetch_add(1, Relaxed) }, TaskConfig::<()>::default())
.unwrap();
handle.submit(task).unwrap();
results.push(result);
}
assert_eq!(handle.external_task_count(), 2);
executor.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks).unwrap();
assert_eq!(handle.external_task_count(), 0);
assert_eq!(order.load(Relaxed), 1);
executor.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks).unwrap();
assert_eq!(order.load(Relaxed), 2);
for (expected, result) in results.into_iter().enumerate() {
assert_eq!(block_on_root(result).unwrap(), expected);
}
executor.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks).unwrap();
assert_eq!(handle.in_flight_task_count(), 0);
}
struct ExternalCloseAfterTaskExit {
queue: MpscTaskQueue,
task_exited: Arc<AtomicBool>,
close_attempts: Arc<AtomicUsize>,
final_error: Option<pi_result::Error>,
}
impl ExternalQueueManager for ExternalCloseAfterTaskExit {
type Handle = MpscTaskQueueHandle;
fn handle(&self) -> Self::Handle {
self.queue.handle()
}
fn clear(&mut self) -> pi_result::Result<QueueCleanupProgress> {
self.queue.clear()
}
fn close(&mut self) -> pi_result::Result<QueueCleanupProgress> {
self.close_attempts.fetch_add(1, Relaxed);
let progress = self.queue.close()?;
if !self.task_exited.load(Relaxed) || matches!(progress, QueueCleanupProgress::MoreWork) {
return Ok(QueueCleanupProgress::MoreWork);
}
match self.final_error.take() {
Some(error) => Err(error),
None => Ok(QueueCleanupProgress::Complete),
}
}
}
#[test]
fn close_revisits_external_source_after_local_task_exits() {
assert_external_close_after_task_exit(ExternalCloseCall::Direct);
}
#[test]
fn close_keeps_pending_external_source_across_owner_borrow() {
assert_external_close_after_task_exit(ExternalCloseCall::AfterBorrow);
}
#[test]
fn close_can_finish_source_after_reporting_unconfirmed() {
assert_external_close_after_task_exit(ExternalCloseCall::SuccessAfterBorrow);
}
#[test]
fn drop_finishes_the_pending_external_source_after_owner_borrow() {
assert_external_close_after_task_exit(ExternalCloseCall::DropAfterBorrow);
}
enum ExternalCloseCall {
Direct,
AfterBorrow,
DropAfterBorrow,
SuccessAfterBorrow,
}
fn assert_external_close_after_task_exit(call: ExternalCloseCall) {
struct SetOnExit(Arc<AtomicBool>);
impl Drop for SetOnExit {
fn drop(&mut self) {
self.0.store(true, Relaxed);
}
}
let task_exited = Arc::new(AtomicBool::new(false));
let close_attempts = Arc::new(AtomicUsize::new(0));
let reports_error = !matches!(call, ExternalCloseCall::SuccessAfterBorrow);
let queue = ExternalCloseAfterTaskExit {
queue: external(),
task_exited: Arc::clone(&task_exited),
close_attempts: Arc::clone(&close_attempts),
final_error: reports_error.then(|| pi_result::Error::new(pi_result::ErrorKind::Unsupported)
.attach("外部任务退出后的原关闭错误")),
};
let mut executor = DefaultExecutor::<_, _, _, _, NoLocalBinding>::with_queues(
UnusedClock,
queue,
NoIdleQueue,
ExecutorOptions::default(),
NoTimerQueue::default(),
)
.unwrap();
let handle = executor.handle();
let exit = SetOnExit(Arc::clone(&task_exited));
let (task, result) = handle
.create(
async move {
let _exit = exit;
std::future::pending::<()>().await
},
TaskConfig::<()>::default(),
)
.unwrap();
handle.submit(task).unwrap();
assert_eq!(executor.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks).unwrap().runs, 1);
assert_eq!(handle.in_flight_task_count(), 1);
assert!(!task_exited.load(Relaxed));
handle.request_close();
if !matches!(call, ExternalCloseCall::Direct) {
let local = Rc::clone(executor.local());
local
.with_owner(|_| {
for _ in 0..2 {
let error = executor.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks)
.expect_err("借用归还前无法确认关闭");
assert_eq!(error.current_context(), &pi_result::ErrorKind::InvalidState);
assert_eq!(handle.status(), RuntimeStatus::Closing);
assert_eq!(close_attempts.load(Relaxed), 1);
assert!(!task_exited.load(Relaxed));
}
})
.unwrap();
assert!(task_exited.load(Relaxed));
assert_eq!(close_attempts.load(Relaxed), 1);
}
if matches!(call, ExternalCloseCall::DropAfterBorrow) {
drop(executor);
} else {
let turn = executor.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks);
if reports_error {
let error = turn.expect_err("必须取得来源实际关闭错误");
assert_eq!(error.current_context(), &pi_result::ErrorKind::Unsupported);
assert_eq!(error.downcast_ref::<&'static str>(), Some(&"外部任务退出后的原关闭错误"));
} else {
assert!(turn.expect("来源后来确实完成清理").service_closed);
}
}
assert!(task_exited.load(Relaxed));
assert!(matches!(block_on_root(result), Err(TaskError::Cancelled)));
assert_eq!(close_attempts.load(Relaxed), 2);
assert_eq!(handle.status(), RuntimeStatus::Closed);
assert_eq!(handle.close_state(), CloseState::Requested);
}
#[test]
fn close_drains_a_bounded_external_source_before_reporting_complete() {
let queue = MpscTaskQueue::new(MpscQueueOptions {
cleanup_batch_size: std::num::NonZeroUsize::MIN,
..MpscQueueOptions::default()
})
.unwrap();
let mut executor = Neither::with_queues(
UnusedClock,
queue,
NoIdleQueue,
ExecutorOptions::default(),
NoTimerQueue::default(),
)
.unwrap();
let handle = executor.handle();
let mut results = Vec::new();
for value in 0..3 {
let (task, result) = handle.create(ready(value), TaskConfig::<()>::default()).unwrap();
handle.submit(task).unwrap();
results.push(result);
}
assert_eq!(handle.external_task_count(), 3);
handle.request_close();
let closed = executor.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks).unwrap();
assert!(closed.service_closed);
assert_eq!(closed.runs, 0);
assert_eq!(handle.external_task_count(), 0);
assert_eq!(handle.status(), RuntimeStatus::Closed);
assert_eq!(handle.close_state(), CloseState::Completed);
for result in results {
assert!(matches!(block_on_root(result), Err(TaskError::Abandoned)));
}
}
#[test]
fn close_drains_tasks_after_a_pending_external_clear_endpoint() {
struct NeverSchedule;
impl pi_async_task::Schedule for NeverSchedule {
fn schedule(&self, _: Runnable) {
panic!("关闭只能清理原任务");
}
}
let mut queue = MpscTaskQueue::new(MpscQueueOptions {
cleanup_batch_size: std::num::NonZeroUsize::MIN,
..MpscQueueOptions::default()
}).unwrap();
let queue_handle = queue.handle();
let mut results = Vec::new();
for value in 0..3 {
if value == 2 {
assert!(matches!(queue.clear().unwrap(), QueueCleanupProgress::MoreWork));
assert_eq!(queue_handle.len(), 1);
}
let task = pi_async_task::create(
ready(value), NeverSchedule, (), pi_async_task::TaskOptions::intrusive_mpsc(),
).unwrap_or_else(|_| panic!("原任务应可创建"));
queue_handle.try_push(task.runnable).unwrap_or_else(|_| panic!("原任务应可入队"));
results.push(task.join);
}
let mut executor = Neither::with_queues(
UnusedClock, queue, NoIdleQueue, ExecutorOptions::default(), NoTimerQueue::default(),
).unwrap();
let handle = executor.handle();
assert_eq!(handle.external_task_count(), 2);
handle.request_close();
let report = executor.run_once(&AdmitAll, &mut DefaultIdlePolicy, &mut NoHooks).unwrap();
assert!(report.service_closed);
assert_eq!(handle.close_state(), CloseState::Completed);
assert_eq!(queue_handle.len(), 0);
for result in results {
assert!(matches!(block_on_root(result), Err(TaskError::Abandoned)));
}
}