qubit_executor/task/task_slot.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026 Haixing Hu.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * Licensed under the Apache License, Version 2.0.
8 *
9 ******************************************************************************/
10use std::sync::Arc;
11
12use qubit_function::Callable;
13
14use super::{
15 TaskResult,
16 running_task_slot::RunningTaskSlot,
17 task_runner::TaskRunner,
18 task_state::TaskState,
19};
20
21/// Runner-side slot for one task submission.
22///
23/// This low-level endpoint is exposed so custom executor services built on top
24/// of `qubit-executor` can wire their own scheduling while still returning the
25/// standard [`crate::TaskHandle`]. Executor implementations should call
26/// [`Self::accept`] only after submission succeeds; this arms lifecycle hook
27/// reporting for later start and finish events. Normal callers should use
28/// [`crate::TaskHandle`] and executor/service submission methods instead.
29///
30/// Dropping an accepted slot reports [`crate::TaskExecutionError::Dropped`]
31/// because it means the runner endpoint was abandoned without making an
32/// explicit terminal decision. Executor services that intentionally discard
33/// accepted work before it starts, such as during
34/// [`crate::ExecutorService::stop`], should call [`Self::cancel_unstarted`] so
35/// callers observe [`crate::TaskExecutionError::Cancelled`] instead.
36pub struct TaskSlot<R, E> {
37 /// Shared state updated by this completion endpoint.
38 pub(crate) state: Option<Arc<TaskState<R, E>>>,
39}
40
41impl<R, E> TaskSlot<R, E> {
42 /// Returns the shared state owned by this slot.
43 ///
44 /// # Returns
45 ///
46 /// A reference to the task state. The state is always present until a
47 /// consuming runner-side API transfers it to another endpoint.
48 #[inline]
49 fn state(&self) -> &TaskState<R, E> {
50 self.state.as_deref().expect("task slot state should be present")
51 }
52
53 /// Marks this runner endpoint as accepted and arms lifecycle hook reporting.
54 ///
55 /// Calling this method emits `on_accepted` before any later `on_started` or
56 /// `on_finished` event for the same task. Executor implementations must call
57 /// it only after submission has succeeded. Dropping a slot before acceptance
58 /// still releases result waiters with `Dropped`, but does not emit lifecycle
59 /// hook events for a task that was rejected before acceptance.
60 #[inline]
61 pub fn accept(&self) {
62 let _accepted_now = self.state().accept();
63 }
64
65 /// Cancels this accepted runner endpoint before it starts running.
66 ///
67 /// This method is the runner-side service-provider API for an executor or
68 /// executor service that intentionally removes queued, scheduled, or other
69 /// unstarted accepted work. It publishes
70 /// [`crate::TaskExecutionError::Cancelled`] when this slot wins the
71 /// pending-task terminal-state race. The slot is consumed to make the
72 /// explicit cancellation decision the final runner-side action.
73 ///
74 /// If the slot has already been accepted, successful cancellation emits the
75 /// finished lifecycle hook with [`crate::TaskStatus::Cancelled`]. If it has
76 /// not been accepted, cancellation still releases result waiters but does
77 /// not emit lifecycle hook events.
78 ///
79 /// # Returns
80 ///
81 /// `true` if this call moved the task from pending to cancelled, or `false`
82 /// if another path had already started or completed the task.
83 #[inline]
84 pub fn cancel_unstarted(mut self) -> bool {
85 self.state.take().is_some_and(|state| state.try_cancel_pending())
86 }
87
88 /// Attempts to move this slot from pending into running state.
89 ///
90 /// This method consumes the pending slot. On success, it returns a
91 /// [`RunningTaskSlot`] that must be completed or dropped. On failure, the
92 /// original pending slot is returned so the caller can inspect or drop it;
93 /// the user callable must not be executed in that case.
94 ///
95 /// # Returns
96 ///
97 /// `Ok(RunningTaskSlot)` if this call won the pending-to-running race, or
98 /// `Err(TaskSlot)` if the task had already been cancelled or completed.
99 pub fn try_start(mut self) -> Result<RunningTaskSlot<R, E>, Self> {
100 if !self.start() {
101 return Err(self);
102 }
103 let state = self.state.take().expect("started task slot state should be present");
104 Ok(RunningTaskSlot::new(state))
105 }
106
107 /// Marks the task as started if it was not cancelled first.
108 ///
109 /// # Returns
110 ///
111 /// `true` if the runner should execute the task, or `false` if the task was
112 /// already completed through cancellation.
113 pub(crate) fn start(&self) -> bool {
114 self.state().try_start(self.state().is_accepted())
115 }
116
117 /// Starts the task and completes it with a lazily produced result.
118 ///
119 /// The supplied closure is executed only if this completion endpoint wins
120 /// the start race. If the handle was cancelled first, the closure is not
121 /// called and the existing cancellation result is preserved.
122 ///
123 /// # Parameters
124 ///
125 /// * `task` - Closure that runs the accepted task and returns its final
126 /// result.
127 ///
128 /// # Returns
129 ///
130 /// `true` if the closure was executed and its result was published, or
131 /// `false` if the task had already been completed by cancellation.
132 #[inline]
133 pub(crate) fn start_and_complete<F>(self, task: F) -> bool
134 where
135 F: FnOnce() -> TaskResult<R, E>,
136 {
137 let Ok(running) = self.try_start() else {
138 return false;
139 };
140 running.complete(task())
141 }
142
143 /// Starts this slot and runs a callable to completion.
144 ///
145 /// # Parameters
146 ///
147 /// * `task` - Callable to run if the task has not been cancelled.
148 ///
149 /// # Returns
150 ///
151 /// `true` if the callable ran and published a result, or `false` if the
152 /// task had already been cancelled.
153 #[inline]
154 pub fn run<C>(self, task: C) -> bool
155 where
156 C: Callable<R, E>,
157 {
158 self.start_and_complete(|| TaskRunner::new(task).call())
159 }
160}
161
162impl<R, E> Drop for TaskSlot<R, E> {
163 /// Publishes a dropped-result error when the runner endpoint is abandoned.
164 #[inline]
165 fn drop(&mut self) {
166 if let Some(state) = &self.state {
167 let _ignored = state.try_drop_unfinished(state.is_accepted());
168 }
169 }
170}