1use crate::Error;
2use std::sync::atomic::AtomicI64;
3use std::sync::{Arc, Mutex};
4use tokio::sync::watch;
5use tokio_util::sync::CancellationToken;
6
7pub type CancelCause = Arc<dyn std::error::Error + Send + Sync>;
8
9#[derive(Clone, Debug, Default)]
11pub struct Context {
12 token: CancellationToken,
13 pub(crate) deadline: Option<tokio::time::Instant>,
14}
15
16impl Context {
17 pub fn new() -> Self {
18 Self::default()
19 }
20
21 pub fn with_deadline(self, deadline: tokio::time::Instant) -> Self {
22 let deadline = self.deadline.map_or(deadline, |prior| prior.min(deadline));
23 Self {
24 deadline: Some(deadline),
25 ..self
26 }
27 }
28
29 pub fn with_timeout(self, timeout: std::time::Duration) -> Self {
30 let Some(deadline) = tokio::time::Instant::now().checked_add(timeout) else {
31 return self;
32 };
33 self.with_deadline(deadline)
34 }
35
36 pub fn cancel(&self) {
37 self.token.cancel();
38 }
39
40 pub(crate) fn token(&self) -> &CancellationToken {
41 &self.token
42 }
43
44 pub(crate) fn error(&self) -> Option<Error> {
45 if self.token.is_cancelled() {
46 Some(Error::ContextCancelled("context canceled".into()))
47 } else if self
48 .deadline
49 .is_some_and(|at| tokio::time::Instant::now() >= at)
50 {
51 Some(Error::DeadlineExceeded)
52 } else {
53 None
54 }
55 }
56
57 pub async fn done(&self) -> Error {
58 if let Some(err) = self.error() {
59 return err;
60 }
61 if let Some(at) = self.deadline {
62 tokio::select! {
63 biased;
64 _ = self.token.cancelled() => Error::ContextCancelled("context canceled".into()),
65 _ = tokio::time::sleep_until(at) => Error::DeadlineExceeded,
66 }
67 } else {
68 self.token.cancelled().await;
69 Error::ContextCancelled("context canceled".into())
70 }
71 }
72}
73
74impl From<CancellationToken> for Context {
75 fn from(token: CancellationToken) -> Self {
76 Self {
77 token,
78 deadline: None,
79 }
80 }
81}
82
83#[derive(Clone)]
84pub struct CancelOption(CancelCause);
85
86pub fn with_cause(cause: CancelCause) -> CancelOption {
87 CancelOption(cause)
88}
89
90pub(crate) fn cause_of(options: &[CancelOption]) -> Option<CancelCause> {
91 options.last().map(|option| option.0.clone())
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub enum CancelKind {
96 Task,
97 Run,
98 Parent,
99 TaskDone,
100}
101
102#[derive(Debug, Clone)]
103pub struct CancelReason {
104 pub kind: CancelKind,
105 pub source: Option<CancelCause>,
106}
107
108impl CancelReason {
109 pub(crate) fn new(kind: CancelKind, source: Option<CancelCause>) -> Self {
110 Self { kind, source }
111 }
112}
113
114#[derive(Clone)]
115pub struct TaskContext {
116 token: CancellationToken,
117 control: Arc<TaskControl>,
118 parent: Context,
119}
120
121impl TaskContext {
122 pub async fn cancelled(&self) {
123 self.token.cancelled().await;
124 }
125
126 pub fn is_cancelled(&self) -> bool {
127 self.token.is_cancelled()
128 }
129
130 pub fn cause(&self) -> Option<CancelReason> {
131 if !self.is_cancelled() {
132 return None;
133 }
134 Some(self.control.reason().unwrap_or_else(|| {
135 CancelReason::new(
136 CancelKind::Parent,
137 self.parent.error().map(|err| Arc::new(err) as CancelCause),
138 )
139 }))
140 }
141
142 pub(crate) fn release_on_drop(&self) -> impl Drop {
143 struct Release(Arc<TaskControl>);
144 impl Drop for Release {
145 fn drop(&mut self) {
146 let mut state = self.0.state.lock().unwrap();
147 if !state.token.is_cancelled() {
148 state.reason = Some(CancelReason::new(CancelKind::TaskDone, None));
149 state.token.cancel();
150 }
151 }
152 }
153 Release(self.control.clone())
154 }
155
156 pub(crate) fn token(&self) -> &CancellationToken {
157 &self.token
158 }
159
160 pub(crate) fn control(&self) -> &Arc<TaskControl> {
161 &self.control
162 }
163
164 pub(crate) fn cancellation_error(&self, underlying: Option<Error>) -> Error {
165 match self.cause().map(|reason| reason.kind) {
166 Some(CancelKind::Task) => Error::TaskCanceled {
167 task: self.control.name.clone(),
168 reason: self.cause().unwrap(),
169 last: underlying.map(Box::new),
170 },
171 Some(CancelKind::Run) => Error::RunCanceled {
172 reason: self.cause().unwrap(),
173 last: underlying.map(Box::new),
174 },
175 _ => match (self.parent.error(), underlying) {
176 (Some(Error::DeadlineExceeded), Some(Error::RetryInterrupted { last })) => {
177 Error::DeadlineInterrupted { last }
178 }
179 (Some(Error::DeadlineExceeded), _) => Error::DeadlineExceeded,
180 (_, underlying) => underlying
181 .unwrap_or_else(|| Error::ContextCancelled("parent context canceled".into())),
182 },
183 }
184 }
185}
186
187struct ControlState {
188 token: CancellationToken,
189 reason: Option<CancelReason>,
190 task_suspended: bool,
191 run_suspended: bool,
192}
193
194pub(crate) struct TaskControl {
195 name: String,
196 state: Mutex<ControlState>,
197 paused: watch::Sender<bool>,
198 pub(crate) attempts: AtomicI64,
199}
200
201impl TaskControl {
202 pub(crate) fn new(name: String) -> Self {
203 let (paused, _) = watch::channel(false);
204 Self {
205 name,
206 state: Mutex::new(ControlState {
207 token: CancellationToken::new(),
208 reason: None,
209 task_suspended: false,
210 run_suspended: false,
211 }),
212 paused,
213 attempts: AtomicI64::new(0),
214 }
215 }
216
217 pub(crate) fn bind(
218 self: &Arc<Self>,
219 token: &CancellationToken,
220 parent: &Context,
221 ) -> TaskContext {
222 let token = token.child_token();
223 let mut state = self.state.lock().unwrap();
224 if state.reason.is_some() {
225 token.cancel();
226 }
227 state.token = token.clone();
228 TaskContext {
229 token,
230 control: self.clone(),
231 parent: parent.clone(),
232 }
233 }
234
235 pub(crate) fn cancel(&self, requested: CancelReason) {
236 let mut state = self.state.lock().unwrap();
237 if state.reason.is_none() && !state.token.is_cancelled() {
238 state.reason = Some(requested);
239 }
240 state.token.cancel();
241 }
242
243 pub(crate) fn reason(&self) -> Option<CancelReason> {
244 self.state.lock().unwrap().reason.clone()
245 }
246
247 pub(crate) fn set_task_suspended(&self, suspended: bool) {
248 let mut state = self.state.lock().unwrap();
249 if state.task_suspended != suspended {
250 state.task_suspended = suspended;
251 self.paused
252 .send_replace(state.task_suspended || state.run_suspended);
253 }
254 }
255
256 pub(crate) fn set_run_suspended(&self, suspended: bool) {
257 let mut state = self.state.lock().unwrap();
258 if state.run_suspended != suspended {
259 state.run_suspended = suspended;
260 self.paused
261 .send_replace(state.task_suspended || state.run_suspended);
262 }
263 }
264
265 pub(crate) fn suspended(&self) -> bool {
266 *self.paused.borrow()
267 }
268
269 pub(crate) async fn wait(&self, token: &CancellationToken) -> Result<(), Error> {
270 let mut paused = self.paused.subscribe();
271 loop {
272 if token.is_cancelled() {
273 return Err(Error::ContextCancelled("canceled while suspended".into()));
274 }
275 if !*paused.borrow_and_update() {
276 return Ok(());
277 }
278 tokio::select! {
279 _ = token.cancelled() => return Err(Error::ContextCancelled("canceled while suspended".into())),
280 result = paused.changed() => {
281 if result.is_err() {
282 return Err(Error::TaskExecution("suspension gate closed".into()));
283 }
284 }
285 }
286 }
287 }
288}