#[allow(unused_variables)]
fn timeout_new_inner<A: TimerAccess>(access: A, duration: Duration) -> Timeout<A> {
let min_positive = Duration::from_millis(1);
if duration.is_zero() {
return Timeout {
access,
duration,
registration: None,
initial_error: None,
phase: TimeoutPhase::Zero,
zero: YieldOnce::new(),
};
}
if duration < min_positive {
return Timeout {
access,
duration,
registration: None,
initial_error: Some(TimerError::InvalidDuration {
value: duration,
min_positive,
max: None,
}),
phase: TimeoutPhase::Prepared,
zero: YieldOnce::new(),
};
}
let (registration, initial_error) = match access.prepare_registration(TimerRegistrationKind::Wait) {
Ok(registration) => (Some(registration), None),
Err(error) => (None, Some(error)),
};
Timeout {
access,
duration,
registration,
initial_error,
phase: TimeoutPhase::Prepared,
zero: YieldOnce::new(),
}
}
#[allow(unused_variables)]
fn timeout_control_inner<A: TimerAccess>(this: &Timeout<A>) -> TimeoutControl<A> {
let usable = this.initial_error.is_none()
&& matches!(this.phase, TimeoutPhase::Prepared | TimeoutPhase::Registered);
TimeoutControl {
access: this.access.clone(),
registration: if usable { this.registration.clone() } else { None },
}
}
#[allow(unused_variables)]
fn timeout_poll_inner<A: TimerAccess>(
this: Pin<&mut Timeout<A>>,
cx: &mut Context<'_>,
) -> Poll<pi_result::RawResult<(), TimerError>> {
let this = this.get_mut();
assert!(!matches!(this.phase, TimeoutPhase::Done),
"已完成的计时等待不能再次轮询(timeout polled after completion)");
if let Some(error) = this.initial_error.take() {
this.phase = TimeoutPhase::Done;
return Poll::Ready(Err(error));
}
match this.phase {
TimeoutPhase::Zero => return match Pin::new(&mut this.zero).poll(cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(()) => {
this.phase = TimeoutPhase::Done;
Poll::Ready(Ok(()))
}
},
TimeoutPhase::Prepared => {
let registration = match this.registration.as_ref() {
Some(registration) => registration,
None => {
this.phase = TimeoutPhase::Done;
return Poll::Ready(Err(TimerError::ServiceClosed));
}
};
let mut guard = RegistrationGuard {
access: this.access.clone(),
registration: registration.clone(),
armed: false,
};
let entry_registration = registration.clone();
let target = registration.as_ref();
if !target.begin() {
this.phase = TimeoutPhase::Done;
target.close_interest();
target.finish(RegistrationEnd::Cancelled);
return Poll::Ready(Err(TimerError::Cancelled));
}
guard.armed = true;
let deadline = match this.access.deadline_after(this.duration) {
Ok(deadline) => deadline,
Err(error) => {
this.phase = TimeoutPhase::Done;
guard.armed = false;
target.finish(RegistrationEnd::DirectFailure);
return Poll::Ready(Err(error));
}
};
let entry = TimerEntry::signal(entry_registration);
match this.access.try_register(deadline, entry) {
Ok(key) => {
let already_recorded = target.publish_key(key);
guard.armed = false;
this.phase = TimeoutPhase::Registered;
if already_recorded {
let _ = request_registration_cancel(&this.access, registration, CancelMode::KeyPublished);
}
}
Err(submit_error) => {
let pi_async_task_queue::timer::TimerSubmitError { item, cause } = submit_error;
let _ = item.recover();
target.finish(RegistrationEnd::DirectFailure);
guard.armed = false;
this.phase = TimeoutPhase::Done;
return Poll::Ready(Err(TimerError::Queue(cause)));
}
}
}
TimeoutPhase::Registered => {}
TimeoutPhase::Done => unreachable!(),
}
let Some(registration) = this.registration.as_ref() else {
this.phase = TimeoutPhase::Done;
return Poll::Ready(Err(TimerError::ServiceClosed));
};
let Poll::Ready(end) = registration.as_ref().poll(cx) else {
return Poll::Pending;
};
this.phase = TimeoutPhase::Done;
Poll::Ready(match end {
RegistrationEnd::Elapsed => Ok(()),
RegistrationEnd::Cancelled => Err(TimerError::Cancelled),
RegistrationEnd::Removed => Err(TimerError::RegistrationRemoved),
RegistrationEnd::DirectFailure => Err(TimerError::ServiceClosed),
})
}
fn timeout_drop_inner<A: TimerAccess>(this: &mut Timeout<A>) {
if let Some(registration) = this.registration.as_ref() {
if matches!(this.phase, TimeoutPhase::Prepared | TimeoutPhase::Registered) {
registration.as_ref().close_interest();
}
if matches!(this.phase, TimeoutPhase::Registered) {
let _ = request_registration_cancel(&this.access, registration, CancelMode::Detached);
}
}
this.phase = TimeoutPhase::Done;
}
#[allow(unused_variables)]
fn timeout_cancel_inner<A: TimerAccess>(
this: &TimeoutControl<A>,
) -> pi_result::RawResult<bool, TimerError> {
let Some(registration) = this.registration.as_ref() else {
return Ok(false);
};
match request_registration_cancel(&this.access, registration, CancelMode::WaitControl) {
Ok(recorded) => Ok(recorded),
Err(error) => Err(TimerError::Queue(error)),
}
}
fn timeout_control_clone_inner<A: TimerAccess>(this: &TimeoutControl<A>) -> TimeoutControl<A> {
TimeoutControl {
access: this.access.clone(),
registration: this.registration.clone(),
}
}
#[allow(unused_variables)]
fn timer_resume_inner<A: TimerAccess>(access: &A, registration: A::Registration) {
let _ = request_registration_cancel(access, ®istration, CancelMode::Resume);
}
#[allow(unused_variables)]
fn registration_guard_drop_inner<A: TimerAccess>(this: &mut RegistrationGuard<A>) {
if !this.armed {
return;
}
this.armed = false;
let _ = request_registration_cancel(&this.access, &this.registration, CancelMode::Detached);
}
#[allow(unused_variables)]
fn forward_guard_drop_inner<'a, A: TimerAccess>(
this: &mut ForwardGuard<'a, A>,
) -> Option<(A::Registration, Confirmation<'a, A::Key>)> {
this.pending.take()
}
#[cfg(test)]
#[path = "timeout_inner_test.rs"]
mod timeout_inner_test;
#[cfg(test)]
#[path = "timeout_construct_inner_test.rs"]
mod timeout_construct_inner_test;
fn registration_cancel_forward_inner<A: TimerAccess>(
access: &A,
registration: &A::Registration,
mode: CancelMode,
) -> pi_result::RawResult<bool, TimerQueueError> {
let prepared = registration.clone();
let target = registration.as_ref();
if !std::ptr::eq(prepared.as_ref(), target) {
return Err(TimerQueueError::WrongQueue);
}
let access_for_guard = access.clone();
let recorded = match mode {
CancelMode::WaitControl => target.request_wait_cancel(),
CancelMode::Detached => target.request_cancel(),
CancelMode::Resume | CancelMode::KeyPublished => true,
};
if !recorded {
return Ok(false);
}
let deferred = matches!(mode, CancelMode::Resume);
let Some(confirmation) = target.claim_forwarding(deferred) else {
return Ok(matches!(mode, CancelMode::WaitControl));
};
let mut guard = ForwardGuard {
access: access_for_guard,
pending: Some((prepared, confirmation)),
error: None,
};
let attempt = {
let key = target.key().expect("取得转交资格(forwarding)时键(key)已就绪");
access.request_cancel(key)
};
match attempt {
Ok(outcome) => {
let (prepared, confirmation) = match forward_guard_drop_inner(&mut guard) {
Some(pair) => pair,
None => return Ok(false),
};
confirmation.finish_request(outcome);
drop(prepared);
Ok(true)
}
Err(error) => {
if matches!(mode, CancelMode::WaitControl) {
Err(error)
} else {
guard.error = Some(error);
Ok(true)
}
}
}
}
fn spawn_timed_task_inner<S, N, A, F, M>(
factory: &crate::task::TaskFactory<S, N>,
access: A,
future: F,
delay: Duration,
config: crate::task::TaskConfig<M>,
) -> pi_result::RawResult<
crate::task::TaskHandle<super::task_notify::TimedTaskNotifier<N, A>, F::Output, M>,
crate::task::SpawnError<F, super::task_notify::TimedTaskNotifier<N, A>, M>,
>
where
S: pi_async_task::Schedule + Clone,
N: crate::task::TaskNotifier,
A: TimerAccess,
F: Future + Send + 'static,
F::Output: Send + 'static,
M: Send + Sync + 'static,
{
use crate::definitions::{CreateErrorKind, SubmitErrorKind};
use crate::task::{CreateError, SpawnError, SubmissionMode};
use pi_async_task_queue::timer::TimerSubmitError;
if factory.runtime_id() != access.runtime_id() {
return Err(SpawnError::Create(CreateError {
future,
config,
cause: CreateErrorKind::Timer(TimerError::Queue(TimerQueueError::WrongQueue)),
}));
}
let min_positive = Duration::from_millis(1);
if !delay.is_zero() && delay < min_positive {
return Err(SpawnError::Create(CreateError {
future,
config,
cause: CreateErrorKind::Timer(TimerError::InvalidDuration {
value: delay,
min_positive,
max: None,
}),
}));
}
let deadline = match access.deadline_after(delay) {
Ok(deadline) => deadline,
Err(error) => {
return Err(SpawnError::Create(CreateError {
future,
config,
cause: CreateErrorKind::Timer(error),
}));
}
};
let registration = match access.prepare_registration(TimerRegistrationKind::Task) {
Ok(registration) => registration,
Err(error) => {
return Err(SpawnError::Create(CreateError {
future,
config,
cause: CreateErrorKind::Timer(error),
}));
}
};
let timed_notifier = super::task_notify::TimedTaskNotifier::new(
factory.notifier().clone(),
access.clone(),
registration.clone(),
);
let timed_factory = factory.with_notifier(timed_notifier);
let (unsubmitted, handle) = timed_factory
.create(future, config)
.map_err(SpawnError::Create)?;
let mut guard = RegistrationGuard {
access: access.clone(),
registration: registration.clone(),
armed: false,
};
let submit_result = factory.submit(unsubmitted, SubmissionMode::Ordinary, |runnable| {
if !registration.as_ref().begin() {
registration.as_ref().finish(RegistrationEnd::DirectFailure);
return Err((runnable, SubmitErrorKind::Timer(TimerQueueError::Closed)));
}
guard.armed = true;
let entry = TimerEntry::task(runnable, registration.clone());
match access.try_register(deadline, entry) {
Ok(key) => {
let already_recorded = registration.as_ref().publish_key(key);
if already_recorded {
let _ = request_registration_cancel(
&access,
®istration,
CancelMode::KeyPublished,
);
}
Ok(())
}
Err(TimerSubmitError { item, cause }) => {
let runnable = item
.recover()
.expect("刚构造的任务定时入口(TimerEntry::task)必须保有原Runnable");
registration.as_ref().finish(RegistrationEnd::DirectFailure);
guard.armed = false;
Err((runnable, SubmitErrorKind::Timer(cause)))
}
}
});
match submit_result {
Ok(()) => {
guard.armed = false;
Ok(handle)
}
Err(error) => {
guard.armed = false;
Err(SpawnError::Submit { error, handle })
}
}
}
fn spawn_timed_local_task_inner<S, N, A, F, M>(
factory: &crate::task::TaskFactory<S, N>,
owner: &pi_async_task::TaskThread,
access: A,
future: F,
delay: Duration,
config: crate::task::TaskConfig<M>,
) -> pi_result::RawResult<
crate::task::TaskHandle<
super::task_notify::TimedTaskNotifier<N, A>,
F::Output,
M,
pi_async_task::LocalOutput,
>,
crate::task::SpawnError<
F,
super::task_notify::TimedTaskNotifier<N, A>,
M,
pi_async_task::LocalOutput,
>,
>
where
S: pi_async_task::Schedule + Clone,
N: crate::task::TaskNotifier,
A: TimerAccess,
F: Future + 'static,
F::Output: 'static,
M: Send + Sync + 'static,
{
use crate::definitions::{CreateErrorKind, SubmitErrorKind};
use crate::task::{CreateError, SpawnError, SubmissionMode};
use pi_async_task_queue::timer::TimerSubmitError;
if factory.runtime_id() != access.runtime_id() {
return Err(SpawnError::Create(CreateError {
future,
config,
cause: CreateErrorKind::Timer(TimerError::Queue(TimerQueueError::WrongQueue)),
}));
}
let min_positive = Duration::from_millis(1);
if !delay.is_zero() && delay < min_positive {
return Err(SpawnError::Create(CreateError {
future,
config,
cause: CreateErrorKind::Timer(TimerError::InvalidDuration {
value: delay,
min_positive,
max: None,
}),
}));
}
let deadline = match access.deadline_after(delay) {
Ok(deadline) => deadline,
Err(error) => {
return Err(SpawnError::Create(CreateError {
future,
config,
cause: CreateErrorKind::Timer(error),
}));
}
};
let registration = match access.prepare_registration(TimerRegistrationKind::Task) {
Ok(registration) => registration,
Err(error) => {
return Err(SpawnError::Create(CreateError {
future,
config,
cause: CreateErrorKind::Timer(error),
}));
}
};
let timed_notifier = super::task_notify::TimedTaskNotifier::new(
factory.notifier().clone(),
access.clone(),
registration.clone(),
);
let timed_factory = factory.with_notifier(timed_notifier);
let (unsubmitted, handle) = timed_factory
.create_local(owner, future, config)
.map_err(SpawnError::Create)?;
let mut guard = RegistrationGuard {
access: access.clone(),
registration: registration.clone(),
armed: false,
};
let submit_result = factory.submit(unsubmitted, SubmissionMode::Local(owner.id()), |runnable| {
if !registration.as_ref().begin() {
registration.as_ref().finish(RegistrationEnd::DirectFailure);
return Err((runnable, SubmitErrorKind::Timer(TimerQueueError::Closed)));
}
guard.armed = true;
let entry = TimerEntry::task(runnable, registration.clone());
match access.try_register_local(deadline, entry) {
Ok(key) => {
let already_recorded = registration.as_ref().publish_key(key);
if already_recorded {
let _ = request_registration_cancel(
&access,
®istration,
CancelMode::KeyPublished,
);
}
Ok(())
}
Err(TimerSubmitError { item, cause }) => {
let runnable = item
.recover()
.expect("刚构造的本地任务定时入口(TimerEntry::task)必须保有原Runnable");
registration.as_ref().finish(RegistrationEnd::DirectFailure);
guard.armed = false;
Err((runnable, SubmitErrorKind::Timer(cause)))
}
}
});
match submit_result {
Ok(()) => {
guard.armed = false;
Ok(handle)
}
Err(error) => {
guard.armed = false;
Err(SpawnError::Submit { error, handle })
}
}
}