1use crate::definitions::*;
3use pi_async_task::control::{CancelWait, ExternalWaiter};
4use pi_async_task::definitions::{
5 CancellationOutcome, QueueSupport, TaskId, TaskOwnerId, TaskSnapshot,
6};
7use pi_async_task::join::{JoinHandle, LocalOutput, OutputMode, SendOutput};
8use pi_async_task::{ControlHandle, Runnable, Schedule, TaskThread};
9use pi_async_task_queue::notify::QueueNotifier;
10use std::future::Future;
11use std::pin::Pin;
12use std::task::{Context, Poll, Waker};
13
14pub trait TaskNotifier: QueueNotifier + Clone {
17 fn notify_cancel(&self, _snapshot: impl FnOnce() -> TaskSnapshot) {
19 self.notify();
20 }
21}
22
23pub struct TaskConfig<M = ()> {
26 pub metadata: M,
28 pub capture_panic_backtrace: bool,
30 #[cfg(feature = "observe")]
32 pub observer: Option<std::sync::Arc<dyn pi_async_task::task::TaskObserver>>,
33}
34impl<M> TaskConfig<M> {
35 pub fn new(metadata: M) -> Self {
36 task_config_new_inner(metadata)
37 }
38}
39impl<M: Default> Default for TaskConfig<M> {
40 fn default() -> Self {
41 Self::new(M::default())
42 }
43}
44
45#[must_use = "提交回原服务,或释放以按原任务机制放弃"]
48pub struct UnsubmittedTask {
50 pub(crate) runnable: Runnable,
51 pub(crate) runtime_id: RuntimeId,
52 pub(crate) local_owner: Option<TaskOwnerId>,
53}
54impl UnsubmittedTask {
55 pub fn id(&self) -> TaskId {
57 self.runnable.id()
58 }
59 pub fn snapshot(&self) -> TaskSnapshot {
61 self.runnable.snapshot()
62 }
63}
64
65pub struct TaskControl<N: TaskNotifier> {
68 control: ControlHandle,
69 notifier: N,
70}
71impl<N: TaskNotifier> TaskControl<N> {
72 pub fn query_handle(&self) -> TaskQuery {
75 TaskQuery {
76 control: self.control.clone(),
77 }
78 }
79 pub fn id(&self) -> TaskId {
81 self.control.id()
82 }
83 pub fn snapshot(&self) -> TaskSnapshot {
85 self.control.snapshot()
86 }
87 pub fn cancel(&self) {
89 task_control_cancel_inner(self)
90 }
91 pub fn wake(&self) {
93 self.control.wake();
94 }
95 pub fn waker(&self) -> Waker {
98 self.control.waker()
99 }
100 pub fn cancel_and_wait(&self) -> TaskCancelWait<N> {
102 task_control_wait_inner(self, None)
103 }
104 pub fn cancel_and_wait_from(&self, waiter: &ExternalWaiter) -> TaskCancelWait<N> {
109 task_control_wait_inner(self, Some(waiter))
110 }
111}
112
113pub struct TaskQuery {
116 control: ControlHandle,
117}
118impl TaskQuery {
119 pub fn id(&self) -> TaskId {
121 self.control.id()
122 }
123 pub fn snapshot(&self) -> TaskSnapshot {
125 self.control.snapshot()
126 }
127 pub fn is_waiting_for_wake(&self) -> bool {
130 self.control.is_waiting_for_wake()
131 }
132}
133impl Clone for TaskQuery {
134 fn clone(&self) -> Self {
135 Self {
136 control: self.control.clone(),
137 }
138 }
139}
140impl<N: TaskNotifier> Clone for TaskControl<N> {
141 fn clone(&self) -> Self {
142 task_control_clone_inner(self)
143 }
144}
145
146#[must_use = "等待领取结果,或释放以放弃结果兴趣;释放不自动取消"]
148pub struct TaskHandle<N: TaskNotifier, T, M: Send + Sync + 'static = (), K: OutputMode = SendOutput>
153{
154 join: JoinHandle<T, M, K>,
155 control: TaskControl<N>,
156}
157impl<N: TaskNotifier, T, M: Send + Sync + 'static, K: OutputMode> Unpin for TaskHandle<N, T, M, K> {}
159impl<N: TaskNotifier, T, M: Send + Sync + 'static, K: OutputMode> TaskHandle<N, T, M, K> {
160 pub fn id(&self) -> TaskId {
162 self.join.id()
163 }
164 pub fn snapshot(&self) -> TaskSnapshot {
166 self.join.snapshot()
167 }
168 pub fn metadata(&self) -> &M {
170 self.join.metadata()
171 }
172 pub fn control_handle(&self) -> TaskControl<N> {
174 self.control.clone()
175 }
176 pub fn query_handle(&self) -> TaskQuery {
178 self.control.query_handle()
179 }
180}
181impl<N: TaskNotifier, T, M: Send + Sync + 'static, K: OutputMode> Future
182 for TaskHandle<N, T, M, K>
183{
184 type Output = pi_result::RawResult<T, pi_async_task::TaskError>;
185 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
186 task_handle_poll_inner(self, cx)
187 }
188}
189
190pub struct TaskCancelWait<N: TaskNotifier> {
196 wait: CancelWait,
197 probe: ControlHandle,
198 notifier: N,
199 notified: bool,
200}
201impl<N: TaskNotifier> Unpin for TaskCancelWait<N> {}
202impl<N: TaskNotifier> Future for TaskCancelWait<N> {
203 type Output = CancellationOutcome;
204 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
205 task_cancel_wait_poll_inner(self, cx)
206 }
207}
208
209pub struct TaskFactory<S: Schedule, N: TaskNotifier> {
213 runtime_id: RuntimeId,
214 schedule: S,
215 notifier: N,
216 queue_support: QueueSupport,
217}
218impl<S: Schedule, N: TaskNotifier> TaskFactory<S, N> {
219 pub fn try_new(
222 schedule: S,
223 notifier: N,
224 queue_support: QueueSupport,
225 ) -> pi_result::Result<Self> {
226 task_factory_new_inner(schedule, notifier, queue_support)
227 }
228 pub fn runtime_id(&self) -> RuntimeId {
230 self.runtime_id
231 }
232 pub fn submit(
235 &self,
236 task: UnsubmittedTask,
237 mode: SubmissionMode,
238 push: impl FnOnce(Runnable) -> pi_result::RawResult<(), (Runnable, SubmitErrorKind)>,
239 ) -> pi_result::RawResult<(), SubmitError> {
240 task_factory_submit_inner(self, task, mode, push)
241 }
242}
243impl<S: Schedule + Clone, N: TaskNotifier> TaskFactory<S, N> {
244 pub fn create<F, M>(
246 &self,
247 future: F,
248 config: TaskConfig<M>,
249 ) -> pi_result::RawResult<(UnsubmittedTask, TaskHandle<N, F::Output, M>), CreateError<F, M>>
250 where
251 F: Future + Send + 'static,
252 F::Output: Send + 'static,
253 M: Send + Sync + 'static,
254 {
255 task_factory_create_inner(self, future, config)
256 }
257 pub fn create_local<F, M>(
259 &self,
260 owner: &TaskThread,
261 future: F,
262 config: TaskConfig<M>,
263 ) -> pi_result::RawResult<
264 (UnsubmittedTask, TaskHandle<N, F::Output, M, LocalOutput>),
265 CreateError<F, M>,
266 >
267 where
268 F: Future + 'static,
269 F::Output: 'static,
270 M: Send + Sync + 'static,
271 {
272 task_factory_create_local_inner(self, owner, future, config)
273 }
274 pub fn with_notifier<N2: TaskNotifier>(&self, notifier: N2) -> TaskFactory<S, N2> {
276 task_factory_notifier_inner(self, notifier)
277 }
278}
279impl<S: Schedule + Clone, N: TaskNotifier> Clone for TaskFactory<S, N> {
280 fn clone(&self) -> Self {
281 task_factory_clone_inner(self)
282 }
283}
284
285#[derive(Clone, Copy)]
287pub enum SubmissionMode {
288 Ordinary,
290 Local(TaskOwnerId),
292 Idle,
294}
295
296pub struct CreateError<F, M> {
298 pub future: F,
299 pub config: TaskConfig<M>,
300 pub cause: CreateErrorKind,
301}
302impl<F, M> CreateError<F, M> {
303 pub fn into_parts(self) -> (F, TaskConfig<M>, CreateErrorKind) {
305 (self.future, self.config, self.cause)
306 }
307}
308pub struct SubmitError {
310 pub task: UnsubmittedTask,
311 pub cause: SubmitErrorKind,
312}
313impl SubmitError {
314 pub fn into_parts(self) -> (UnsubmittedTask, SubmitErrorKind) {
316 (self.task, self.cause)
317 }
318}
319pub enum SpawnError<
321 F: Future,
322 N: TaskNotifier,
323 M: Send + Sync + 'static = (),
324 K: OutputMode = SendOutput,
325> {
326 Create(CreateError<F, M>),
327 Submit {
328 error: SubmitError,
329 handle: TaskHandle<N, F::Output, M, K>,
330 },
331}
332
333impl<F, M> std::fmt::Debug for CreateError<F, M> {
334 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
335 f.debug_struct("CreateError")
336 .field("cause", &self.cause)
337 .finish_non_exhaustive()
338 }
339}
340impl std::fmt::Debug for SubmitError {
341 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
342 f.debug_struct("SubmitError")
343 .field("task_id", &self.task.id())
344 .field("cause", &self.cause)
345 .finish()
346 }
347}
348impl<F: Future, N: TaskNotifier, M: Send + Sync + 'static, K: OutputMode> std::fmt::Debug
349 for SpawnError<F, N, M, K>
350{
351 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
352 match self {
353 Self::Create(error) => f.debug_tuple("Create").field(error).finish(),
354 Self::Submit { error, .. } => f.debug_tuple("Submit").field(error).finish(),
355 }
356 }
357}
358
359struct CancelNotifyGuard<'a, N: TaskNotifier> {
362 target: &'a TaskControl<N>,
363 armed: bool,
364}
365impl<N: TaskNotifier> Drop for CancelNotifyGuard<'_, N> {
366 fn drop(&mut self) {
367 cancel_notify_drop_inner(self)
368 }
369}
370include!("task_inner.rs");