use crate::definitions::*;
use pi_async_task::control::{CancelWait, ExternalWaiter};
use pi_async_task::definitions::{
CancellationOutcome, QueueSupport, TaskId, TaskOwnerId, TaskSnapshot,
};
use pi_async_task::join::{JoinHandle, LocalOutput, OutputMode, SendOutput};
use pi_async_task::{ControlHandle, Runnable, Schedule, TaskThread};
use pi_async_task_queue::notify::QueueNotifier;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll, Waker};
pub trait TaskNotifier: QueueNotifier + Clone {
fn notify_cancel(&self, _snapshot: impl FnOnce() -> TaskSnapshot) {
self.notify();
}
}
pub struct TaskConfig<M = ()> {
pub metadata: M,
pub capture_panic_backtrace: bool,
#[cfg(feature = "observe")]
pub observer: Option<std::sync::Arc<dyn pi_async_task::task::TaskObserver>>,
}
impl<M> TaskConfig<M> {
pub fn new(metadata: M) -> Self {
task_config_new_inner(metadata)
}
}
impl<M: Default> Default for TaskConfig<M> {
fn default() -> Self {
Self::new(M::default())
}
}
#[must_use = "提交回原服务,或释放以按原任务机制放弃"]
pub struct UnsubmittedTask {
pub(crate) runnable: Runnable,
pub(crate) runtime_id: RuntimeId,
pub(crate) local_owner: Option<TaskOwnerId>,
}
impl UnsubmittedTask {
pub fn id(&self) -> TaskId {
self.runnable.id()
}
pub fn snapshot(&self) -> TaskSnapshot {
self.runnable.snapshot()
}
}
pub struct TaskControl<N: TaskNotifier> {
control: ControlHandle,
notifier: N,
}
impl<N: TaskNotifier> TaskControl<N> {
pub fn query_handle(&self) -> TaskQuery {
TaskQuery {
control: self.control.clone(),
}
}
pub fn id(&self) -> TaskId {
self.control.id()
}
pub fn snapshot(&self) -> TaskSnapshot {
self.control.snapshot()
}
pub fn cancel(&self) {
task_control_cancel_inner(self)
}
pub fn wake(&self) {
self.control.wake();
}
pub fn waker(&self) -> Waker {
self.control.waker()
}
pub fn cancel_and_wait(&self) -> TaskCancelWait<N> {
task_control_wait_inner(self, None)
}
pub fn cancel_and_wait_from(&self, waiter: &ExternalWaiter) -> TaskCancelWait<N> {
task_control_wait_inner(self, Some(waiter))
}
}
pub struct TaskQuery {
control: ControlHandle,
}
impl TaskQuery {
pub fn id(&self) -> TaskId {
self.control.id()
}
pub fn snapshot(&self) -> TaskSnapshot {
self.control.snapshot()
}
pub fn is_waiting_for_wake(&self) -> bool {
self.control.is_waiting_for_wake()
}
}
impl Clone for TaskQuery {
fn clone(&self) -> Self {
Self {
control: self.control.clone(),
}
}
}
impl<N: TaskNotifier> Clone for TaskControl<N> {
fn clone(&self) -> Self {
task_control_clone_inner(self)
}
}
#[must_use = "等待领取结果,或释放以放弃结果兴趣;释放不自动取消"]
pub struct TaskHandle<N: TaskNotifier, T, M: Send + Sync + 'static = (), K: OutputMode = SendOutput>
{
join: JoinHandle<T, M, K>,
control: TaskControl<N>,
}
impl<N: TaskNotifier, T, M: Send + Sync + 'static, K: OutputMode> Unpin for TaskHandle<N, T, M, K> {}
impl<N: TaskNotifier, T, M: Send + Sync + 'static, K: OutputMode> TaskHandle<N, T, M, K> {
pub fn id(&self) -> TaskId {
self.join.id()
}
pub fn snapshot(&self) -> TaskSnapshot {
self.join.snapshot()
}
pub fn metadata(&self) -> &M {
self.join.metadata()
}
pub fn control_handle(&self) -> TaskControl<N> {
self.control.clone()
}
pub fn query_handle(&self) -> TaskQuery {
self.control.query_handle()
}
}
impl<N: TaskNotifier, T, M: Send + Sync + 'static, K: OutputMode> Future
for TaskHandle<N, T, M, K>
{
type Output = pi_result::RawResult<T, pi_async_task::TaskError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
task_handle_poll_inner(self, cx)
}
}
pub struct TaskCancelWait<N: TaskNotifier> {
wait: CancelWait,
probe: ControlHandle,
notifier: N,
notified: bool,
}
impl<N: TaskNotifier> Unpin for TaskCancelWait<N> {}
impl<N: TaskNotifier> Future for TaskCancelWait<N> {
type Output = CancellationOutcome;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut();
let mut guard = CancelWaitNotifyGuard {
probe: &this.probe,
notifier: &this.notifier,
notified: &mut this.notified,
armed: false,
};
let outcome = task_cancel_wait_poll_inner(Pin::new(&mut this.wait), cx, &mut guard);
guard.armed = false;
if outcome.is_pending() && !*guard.notified {
*guard.notified = true;
guard.notifier.notify_cancel(|| guard.probe.snapshot());
}
outcome
}
}
pub struct TaskFactory<S: Schedule, N: TaskNotifier> {
runtime_id: RuntimeId,
schedule: S,
notifier: N,
queue_support: QueueSupport,
}
impl<S: Schedule, N: TaskNotifier> TaskFactory<S, N> {
pub fn try_new(
schedule: S,
notifier: N,
queue_support: QueueSupport,
) -> pi_result::Result<Self> {
task_factory_new_inner(schedule, notifier, queue_support)
}
pub fn runtime_id(&self) -> RuntimeId {
self.runtime_id
}
pub(crate) fn notifier(&self) -> &N {
&self.notifier
}
pub fn submit(
&self,
task: UnsubmittedTask,
mode: SubmissionMode,
push: impl FnOnce(Runnable) -> pi_result::RawResult<(), (Runnable, SubmitErrorKind)>,
) -> pi_result::RawResult<(), SubmitError> {
task_factory_submit_inner(self, task, mode, push)
}
}
impl<S: Schedule + Clone, N: TaskNotifier> TaskFactory<S, N> {
pub fn create<F, M>(
&self,
future: F,
config: TaskConfig<M>,
) -> pi_result::RawResult<(UnsubmittedTask, TaskHandle<N, F::Output, M>), CreateError<F, M>>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
M: Send + Sync + 'static,
{
task_factory_create_inner(self, future, config)
}
pub fn create_local<F, M>(
&self,
owner: &TaskThread,
future: F,
config: TaskConfig<M>,
) -> pi_result::RawResult<
(UnsubmittedTask, TaskHandle<N, F::Output, M, LocalOutput>),
CreateError<F, M>,
>
where
F: Future + 'static,
F::Output: 'static,
M: Send + Sync + 'static,
{
task_factory_create_local_inner(self, owner, future, config)
}
pub fn with_notifier<N2: TaskNotifier>(&self, notifier: N2) -> TaskFactory<S, N2> {
task_factory_notifier_inner(self, notifier)
}
}
impl<S: Schedule + Clone, N: TaskNotifier> Clone for TaskFactory<S, N> {
fn clone(&self) -> Self {
task_factory_clone_inner(self)
}
}
#[derive(Clone, Copy)]
pub enum SubmissionMode {
Ordinary,
Local(TaskOwnerId),
Idle,
}
pub struct CreateError<F, M> {
pub future: F,
pub config: TaskConfig<M>,
pub cause: CreateErrorKind,
}
impl<F, M> CreateError<F, M> {
pub fn into_parts(self) -> (F, TaskConfig<M>, CreateErrorKind) {
(self.future, self.config, self.cause)
}
}
pub struct SubmitError {
pub task: UnsubmittedTask,
pub cause: SubmitErrorKind,
}
impl SubmitError {
pub fn into_parts(self) -> (UnsubmittedTask, SubmitErrorKind) {
(self.task, self.cause)
}
}
pub enum SpawnError<
F: Future,
N: TaskNotifier,
M: Send + Sync + 'static = (),
K: OutputMode = SendOutput,
> {
Create(CreateError<F, M>),
Submit {
error: SubmitError,
handle: TaskHandle<N, F::Output, M, K>,
},
}
impl<F, M> std::fmt::Debug for CreateError<F, M> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CreateError")
.field("cause", &self.cause)
.finish_non_exhaustive()
}
}
impl std::fmt::Debug for SubmitError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SubmitError")
.field("task_id", &self.task.id())
.field("cause", &self.cause)
.finish()
}
}
impl<F: Future, N: TaskNotifier, M: Send + Sync + 'static, K: OutputMode> std::fmt::Debug
for SpawnError<F, N, M, K>
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Create(error) => f.debug_tuple("Create").field(error).finish(),
Self::Submit { error, .. } => f.debug_tuple("Submit").field(error).finish(),
}
}
}
struct CancelNotifyGuard<'a, N: TaskNotifier> {
target: &'a TaskControl<N>,
armed: bool,
}
impl<N: TaskNotifier> Drop for CancelNotifyGuard<'_, N> {
fn drop(&mut self) {
cancel_notify_drop_inner(self)
}
}
struct CancelWaitNotifyGuard<'a, N: TaskNotifier> {
probe: &'a ControlHandle,
notifier: &'a N,
notified: &'a mut bool,
armed: bool,
}
impl<N: TaskNotifier> Drop for CancelWaitNotifyGuard<'_, N> {
fn drop(&mut self) {
if !self.armed {
return;
}
if let Some(snapshot) = cancel_wait_notify_drop_inner(self) {
self.notifier.notify_cancel(move || snapshot);
}
}
}
include!("task_inner.rs");