#[allow(unused_variables)]
fn local_owner_inner<T: ExecutorTimer + 'static, R>(
this: &ExecutorLocal<T>,
action: impl FnOnce(&TaskThread) -> R,
) -> pi_result::Result<R> {
let activity = LocalActivityGuard { local: this };
let borrowed = match this.owner.try_borrow() {
Ok(borrowed) => borrowed,
Err(_) => {
drop(activity);
return Err(pi_result::Error::new(pi_result::ErrorKind::InvalidState)
.attach("所属域(owner)正在被使用"));
}
};
let Some(owner) = borrowed.as_ref() else {
drop(borrowed);
drop(activity);
return Err(pi_result::Error::new(pi_result::ErrorKind::InvalidState)
.attach("所属域(owner)已经退出"));
};
let result = action(owner);
drop(borrowed);
drop(activity);
Ok(result)
}
fn local_push_inner<T: ExecutorTimer + 'static>(
this: &ExecutorLocal<T>,
task: Runnable,
front: bool,
) -> pi_result::RawResult<(), QueuePushError> {
if this.state.status() != pi_async_runtime_core::definitions::RuntimeStatus::Open {
return Err(QueuePushError { task, cause: pi_async_task_queue::local::QueuePushErrorKind::Closed });
}
let mut ready = match this.ready.try_borrow_mut() {
Ok(ready) => ready,
Err(_) => panic!("本地就绪队列(ready queue)不得在借用内重入"),
};
let Some(queue) = ready.as_mut() else {
return Err(QueuePushError { task, cause: pi_async_task_queue::local::QueuePushErrorKind::Closed });
};
let result = if front {
this.state.push_front(queue, task)
} else {
this.state.push_back(queue, task)
};
drop(ready);
if result.is_ok() {
pi_async_task_queue::notify::QueueNotifier::notify(&this.notifier);
}
result
}
fn local_timer_push_inner<T: ExecutorTimer + 'static>(
this: &ExecutorLocal<T>,
deadline: T::Instant,
item: T::Item,
) -> pi_result::RawResult<T::Key, TimerSubmitError<T::Item>> {
use pi_async_task_queue::timer::TimerQueueError;
if this.state.status() != pi_async_runtime_core::definitions::RuntimeStatus::Open {
return Err(TimerSubmitError { item, cause: TimerQueueError::Closed });
}
let mut timer = match this.timer.try_borrow_mut() {
Ok(timer) => timer,
Err(_) => return Err(TimerSubmitError { item, cause: TimerQueueError::Busy }),
};
let Some(timer) = timer.as_mut() else {
return Err(TimerSubmitError { item, cause: TimerQueueError::Closed });
};
pi_async_task_queue::timer::TimerTaskQueue::try_push_local(timer, deadline, item)
}
fn local_selected_inner<T: ExecutorTimer + 'static>(
this: &ExecutorLocal<T>,
task: Runnable,
) -> pi_result::Result<PreparedTask> {
use pi_async_task::definitions::{CancelRequestStatus, ExecutionStatus, TaskPhase};
use std::sync::atomic::Ordering::Release;
let missing = || {
pi_result::Error::new(pi_result::ErrorKind::InvalidState)
.attach("本地任务选择(local selection)缺少有效登记")
};
let snapshot = task.snapshot();
if matches!(snapshot.owner, Some(owner) if owner != this.owner_id) {
return Err(missing());
}
if snapshot.phase == TaskPhase::Ended
|| snapshot.execution == ExecutionStatus::CleanupUnconfirmed
{
return Ok(PreparedTask::Settled(task));
}
if this.register_pool_tasks && snapshot.owner.is_none() && !snapshot.admitted {
this.register_selected_member_task(&task)?;
}
let registered = this.registry.borrow_mut().as_mut()
.is_some_and(|registry| registry.query(snapshot.id).is_some());
if !registered {
return Err(missing());
}
if snapshot.cancellation == CancelRequestStatus::Recorded || snapshot.phase == TaskPhase::Exiting {
return Ok(PreparedTask::Cleanup(task));
}
if snapshot.admitted {
let existing = {
let active = this.active.borrow();
match active.get(&snapshot.id) {
Some(ActiveRecord::Registered(registration)) => Some(std::rc::Rc::clone(registration)),
_ => None,
}
};
return match existing {
Some(registration) => Ok(PreparedTask::Business(task, registration)),
None => Ok(PreparedTask::Cleanup(task)),
};
}
this.active.borrow_mut().reserve(1);
this.active_order.borrow_mut().reserve(1);
let id = snapshot.id;
let outcome = {
let borrowed = this.owner.borrow();
let Some(owner) = borrowed.as_ref() else {
return Err(missing());
};
let mut attempt = AdmissionAttemptGuard { local: this, task: &task, armed: true };
let outcome = task.admit(owner);
attempt.armed = false;
drop(attempt);
outcome
};
match outcome {
Ok(registration) => {
let registration = std::rc::Rc::new(registration);
this.active
.borrow_mut()
.insert(id, ActiveRecord::Registered(std::rc::Rc::clone(®istration)));
this.active_order.borrow_mut().push_back(id);
this.state.in_flight.fetch_add(1, Release);
Ok(PreparedTask::Business(task, registration))
}
Err(pi_async_task::definitions::AdmissionError::AlreadyEnded) => {
let again = task.snapshot();
if again.cancellation == CancelRequestStatus::Recorded
|| matches!(again.phase, TaskPhase::Exiting | TaskPhase::Ended)
{
Ok(PreparedTask::Cleanup(task))
} else {
Err(missing())
}
}
Err(_) => Err(missing()),
}
}
fn local_maintain_inner<T: ExecutorTimer + 'static>(this: &ExecutorLocal<T>, max_nodes: usize) {
use pi_async_task::definitions::{FutureDropStatus, TaskPhase};
use std::sync::atomic::Ordering::Release;
let rounds = max_nodes.min(this.active_order.borrow().len());
for _ in 0..rounds {
let Some(id) = this.active_order.borrow_mut().pop_front() else {
break;
};
let Some(finished) = ({
let active = this.active.borrow();
active.get(&id).map(|record| {
let snapshot = record.snapshot();
snapshot.phase == TaskPhase::Ended
&& snapshot.future_drop == FutureDropStatus::Confirmed
})
}) else {
continue;
};
if finished {
let removed = this.active.borrow_mut().remove(&id);
this.state.in_flight.fetch_sub(1, Release);
drop(removed);
} else {
this.active_order.borrow_mut().push_back(id);
}
}
struct RestoreRegistry<'a> {
slot: &'a RefCell<Option<TaskRegistry>>,
registry: Option<TaskRegistry>,
}
impl Drop for RestoreRegistry<'_> {
fn drop(&mut self) {
*self.slot.borrow_mut() = self.registry.take();
}
}
let registry = this.registry.borrow_mut().take();
let mut restore = RestoreRegistry { slot: &this.registry, registry };
if let Some(registry) = restore.registry.as_mut() {
registry.maintain(max_nodes);
}
}
fn local_finish_exit_inner<T: ExecutorTimer + 'static>(
this: &ExecutorLocal<T>,
source_failed: bool,
) -> bool {
this.exit_requested.set(true);
if source_failed {
this.source_failed.set(true);
}
if this.exit_finished.get() {
return true;
}
if this.exit_running.get() {
return false;
}
if this.owner.try_borrow_mut().is_err() {
return false;
}
this.exit_running.set(true);
let mut guard = LocalExitGuard {
local: this,
phase: LocalExitPhase::Owner,
current_failed: false,
failed: false,
domain_unconfirmed: 0,
admitted_unconfirmed: 0,
};
local_exit_drain_inner(&mut guard);
guard.phase = LocalExitPhase::Done;
drop(guard);
this.exit_finished.get()
}
fn local_drop_inner<T: ExecutorTimer + 'static>(this: &mut ExecutorLocal<T>) {
if local_finish_exit_inner(this, false) {
return;
}
let mut guard = LocalExitGuard {
local: this,
phase: LocalExitPhase::Owner,
current_failed: false,
failed: true,
domain_unconfirmed: 0,
admitted_unconfirmed: 0,
};
local_exit_drain_inner(&mut guard);
guard.phase = LocalExitPhase::Done;
drop(guard);
}
fn local_exit_drain_inner<T: ExecutorTimer + 'static>(guard: &mut LocalExitGuard<'_, T>) {
let local = guard.local;
if matches!(guard.phase, LocalExitPhase::Owner) {
guard.phase = LocalExitPhase::Ready;
guard.current_failed = true;
let owner = local.owner.borrow_mut().take();
drop(owner);
guard.current_failed = false;
}
if matches!(guard.phase, LocalExitPhase::Ready) {
if let Ok(borrowed) = local.registry.try_borrow() {
if let Some(registry) = borrowed.as_ref() {
let (domain, admitted) = registry.unconfirmed_counts(local.owner_id);
guard.domain_unconfirmed = domain;
guard.admitted_unconfirmed = admitted;
}
}
guard.phase = LocalExitPhase::Timer;
guard.current_failed = true;
let ready = local.ready.borrow_mut().take();
if let Some(queue) = ready {
let release = ReadyReleaseGuard { state: &local.state, count: queue.len() };
drop(queue);
drop(release);
}
guard.current_failed = false;
}
if matches!(guard.phase, LocalExitPhase::Timer) {
guard.phase = LocalExitPhase::Returns;
guard.current_failed = true;
let timer = local.timer.borrow_mut().take();
drop(timer);
guard.current_failed = false;
}
if matches!(guard.phase, LocalExitPhase::Returns) {
guard.phase = LocalExitPhase::Active;
guard.current_failed = true;
let returns = local.returns.borrow_mut().take();
if let Some(mut returns) = returns {
let _ = returns.close_after_owner();
drop(returns);
}
guard.current_failed = false;
}
if matches!(guard.phase, LocalExitPhase::Active) {
loop {
let removed = {
let mut active = local.active.borrow_mut();
match active.keys().next().copied() {
Some(id) => active.remove(&id),
None => None,
}
};
match removed {
Some(record) => {
guard.current_failed = true;
drop(record);
guard.current_failed = false;
}
None => break,
}
}
drop(std::mem::take(&mut *local.active.borrow_mut()));
drop(std::mem::take(&mut *local.active_order.borrow_mut()));
guard.phase = LocalExitPhase::Registry;
}
if matches!(guard.phase, LocalExitPhase::Registry) {
guard.phase = LocalExitPhase::Finish;
guard.current_failed = true;
let registry = local.registry.borrow_mut().take();
drop(registry);
guard.current_failed = false;
}
if matches!(guard.phase, LocalExitPhase::Finish) {
guard.phase = LocalExitPhase::Done;
let cleanup_failed = guard.failed || local.source_failed.get() || guard.domain_unconfirmed != 0;
local.state.finish_owner(guard.admitted_unconfirmed, cleanup_failed);
local.exit_finished.set(true);
local.exit_running.set(false);
}
}
fn local_exit_drop_inner<T: ExecutorTimer + 'static>(guard: &mut LocalExitGuard<'_, T>) {
if matches!(guard.phase, LocalExitPhase::Done) {
return;
}
if guard.current_failed {
guard.current_failed = false;
guard.failed = true;
}
local_exit_drain_inner(guard);
}
fn local_activity_drop_inner<T: ExecutorTimer + 'static>(guard: &mut LocalActivityGuard<'_, T>) {
let local = guard.local;
if !local.exit_requested.get() || local.exit_finished.get() || local.exit_running.get() {
return;
}
let _ = local_finish_exit_inner(local, false);
}
fn ready_release_inner(guard: &mut ReadyReleaseGuard<'_>) {
let count = std::mem::take(&mut guard.count);
if count != 0 {
guard.state.internal.fetch_sub(count, std::sync::atomic::Ordering::Release);
}
}
#[allow(unused_variables)]
fn local_new_inner<T: ExecutorTimer + 'static>(
runtime: RuntimeId,
owner: TaskThread,
ready: TaskQueue,
timer: T,
returns: ReturnQueue,
registry: TaskRegistry,
state: Arc<ExecutorState>,
notifier: ThreadNotifier,
) -> ExecutorLocal<T> {
let owner_id = owner.id();
ExecutorLocal {
runtime,
owner_id,
owner: std::cell::RefCell::new(Some(owner)),
ready: std::cell::RefCell::new(Some(ready)),
timer: std::cell::RefCell::new(Some(timer)),
returns: std::cell::RefCell::new(Some(returns)),
registry: std::cell::RefCell::new(Some(registry)),
active: std::cell::RefCell::new(std::collections::HashMap::new()),
active_order: std::cell::RefCell::new(std::collections::VecDeque::new()),
state,
notifier,
register_pool_tasks: false,
exit_requested: std::cell::Cell::new(false),
exit_running: std::cell::Cell::new(false),
source_failed: std::cell::Cell::new(false),
exit_finished: std::cell::Cell::new(false),
}
}
fn admission_attempt_drop_inner<T: ExecutorTimer + 'static>(
guard: &mut AdmissionAttemptGuard<'_, T>,
) {
use pi_async_task::definitions::FutureDropStatus;
use std::sync::atomic::Ordering::Release;
if !guard.armed {
return;
}
guard.armed = false;
let snapshot = guard.task.snapshot();
let local = guard.local;
if snapshot.owner != Some(local.owner_id)
|| !snapshot.admitted
|| snapshot.future_drop != FutureDropStatus::Unconfirmed
{
return;
}
let id = snapshot.id;
if local.active.borrow().contains_key(&id) {
return;
}
let query = {
let Ok(mut borrowed) = local.registry.try_borrow_mut() else {
return;
};
let Some(registry) = borrowed.as_mut() else {
return;
};
registry.query(id).cloned()
};
let Some(query) = query else {
return;
};
{
let mut active = local.active.borrow_mut();
if active.contains_key(&id) {
return;
}
active.insert(id, ActiveRecord::Interrupted(query));
}
local.active_order.borrow_mut().push_back(id);
local.state.in_flight.fetch_add(1, Release);
}