1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
mod handle;
mod outcome;
mod promise;
use promise::AbortablePromise;
use crate::{Promise, PromiseRejection};
pub use handle::AbortHandle;
pub use outcome::{PromiseAborted, PromiseSettled};
impl<T, E> Promise<T, E>
where
T: Send + 'static,
E: PromiseRejection,
{
/// Wraps this [`Promise`] with an external abort handle.
///
/// Returns the wrapped promise alongside an [`AbortHandle`]. Aborting is a
/// suggestion, not a command: it takes effect only while the promise is
/// still pending and is observed on a subsequent poll. When an abort is
/// visible on a poll, it takes precedence, so the promise rejects even if
/// the underlying promise is simultaneously settled; but an abort that
/// arrives after the promise has already settled simply has no effect. On
/// abort the promise rejects with
/// [`TaskFailure::Aborted`](crate::TaskFailure::Aborted), mapped through
/// [`PromiseRejection::task_failed`]. The handle is cloneable, so any clone
/// may abort, and [`AbortHandle::abort`]'s return value is only a hint, as
/// described on that method. Dropping every handle without aborting has no
/// effect: the underlying promise simply runs to completion.
///
/// # Cancellation
///
/// Aborting drops the underlying future, which does not preempt running
/// code. What an abort actually stops therefore depends on how
/// the underlying promise is driven:
///
/// - A poll-driven promise (the default, such as [`Promise::lazy`]) makes
/// progress only while polled, so dropping it halts the work at its last
/// `.await`. This is genuine cancellation.
/// - An eager promise (`eager_with_tokio` or `eager_with_smol`) holds a
/// detached task. Aborting abandons the result, but the spawned future
/// runs to completion; the work is not stopped.
/// - [`Promise::unblock`] runs a blocking closure on a thread pool. A
/// closure that has already started cannot be interrupted, so aborting
/// abandons the result while the closure runs to completion.
pub fn abortable(self) -> (Self, AbortHandle) {
let (sender, receiver) = async_channel::bounded(1);
let promise = AbortablePromise::new(self, receiver).into();
let handle = AbortHandle { sender };
(promise, handle)
}
}
#[cfg(test)]
mod tests {
use std::{
future::Future,
pin::Pin,
sync::{
atomic::{AtomicBool, AtomicUsize, Ordering},
Arc,
},
task::{Context, Poll, Wake, Waker},
};
use super::{PromiseAborted, PromiseSettled};
use crate::{Promise, PromiseRejection, TaskFailure};
#[derive(Debug, PartialEq)]
enum E {
Aborted,
AlreadyConsumed,
TaskFailed,
}
impl PromiseRejection for E {
fn already_consumed() -> Self {
Self::AlreadyConsumed
}
fn task_failed(failure: TaskFailure) -> Self {
match failure {
TaskFailure::Aborted => Self::Aborted,
_ => Self::TaskFailed,
}
}
}
fn cx() -> Context<'static> {
Context::from_waker(Waker::noop())
}
fn pending_promise() -> Promise<i32, E> {
Promise::<i32, E>::lazy(std::future::pending::<Result<i32, E>>())
}
/// Counts how many times it is woken, so a test can observe that an abort
/// arriving while the promise is pending wakes the parked task.
struct CountingWaker(AtomicUsize);
impl Wake for CountingWaker {
fn wake(self: Arc<Self>) {
self.wake_by_ref();
}
fn wake_by_ref(self: &Arc<Self>) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
/// Sets a shared flag when dropped, so a test can observe whether the
/// future holding it was dropped.
struct DropFlag(Arc<AtomicBool>);
impl Drop for DropFlag {
fn drop(&mut self) {
self.0.store(true, Ordering::SeqCst);
}
}
/// A future that never resolves and carries a [`DropFlag`], standing in
/// for in-flight work that should be cancelled on abort.
struct NeverReady {
_flag: DropFlag,
}
impl Future for NeverReady {
type Output = Result<i32, E>;
fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
Poll::Pending
}
}
#[test]
fn abort_rejects_pending_promise() {
let (mut promise, handle) = pending_promise().abortable();
assert!(promise.poll_pending(&mut cx()));
assert_eq!(handle.abort(), Ok(PromiseAborted));
assert!(promise.poll_settled(&mut cx()));
assert_eq!(promise.consume(), Some(Err(E::Aborted)));
}
/// A redundant abort, before the first one is observed, still reports the
/// promise as aborted: a still-queued request reads as live.
#[test]
fn redundant_abort_still_reports_aborted() {
let (mut promise, handle) = pending_promise().abortable();
assert_eq!(handle.abort(), Ok(PromiseAborted));
assert_eq!(handle.abort(), Ok(PromiseAborted));
assert!(promise.poll_settled(&mut cx()));
assert_eq!(promise.consume(), Some(Err(E::Aborted)));
}
#[test]
fn resolves_when_not_aborted() {
let (mut promise, _handle) = Promise::<i32, E>::resolve(42).abortable();
assert!(promise.poll_settled(&mut cx()));
assert_eq!(promise.consume(), Some(Ok(42)));
}
#[test]
fn dropping_handle_leaves_pending_promise_pending() {
let (mut promise, handle) = pending_promise().abortable();
drop(handle);
assert!(promise.poll_pending(&mut cx()));
assert!(promise.poll_pending(&mut cx()));
}
#[test]
fn clone_can_abort_after_original_is_dropped() {
let (mut promise, handle) = pending_promise().abortable();
let clone = handle.clone();
drop(handle);
assert_eq!(clone.abort(), Ok(PromiseAborted));
assert!(promise.poll_settled(&mut cx()));
assert_eq!(promise.consume(), Some(Err(E::Aborted)));
}
/// Once the underlying promise has settled and been observed, a later
/// abort is too late: it reports [`PromiseSettled`] and the resolved value
/// stands.
#[test]
fn settlement_wins_over_later_abort() {
let (mut promise, handle) = Promise::<i32, E>::resolve(5).abortable();
assert!(promise.poll_settled(&mut cx()));
assert_eq!(handle.abort(), Err(PromiseSettled));
assert_eq!(promise.consume(), Some(Ok(5)));
}
/// A pending abort takes precedence over an underlying promise that is
/// already resolvable: aborting before the first poll rejects, rather than
/// surfacing the settled value. This is the imperative `AbortController`
/// semantic, where `abort` commands cancellation rather than racing.
#[test]
fn abort_wins_over_settled_inner() {
let (mut promise, handle) = Promise::<i32, E>::resolve(5).abortable();
assert_eq!(handle.abort(), Ok(PromiseAborted));
assert!(promise.poll_settled(&mut cx()));
assert_eq!(promise.consume(), Some(Err(E::Aborted)));
}
/// Aborting drops the underlying future, cancelling poll-driven work.
#[test]
fn abort_drops_the_underlying_future() {
let dropped = Arc::new(AtomicBool::new(false));
let inner = Promise::<i32, E>::lazy(NeverReady {
_flag: DropFlag(dropped.clone()),
});
let (mut promise, handle) = inner.abortable();
assert!(promise.poll_pending(&mut cx()));
assert!(!dropped.load(Ordering::SeqCst));
assert_eq!(handle.abort(), Ok(PromiseAborted));
assert!(promise.poll_settled(&mut cx()));
assert!(
dropped.load(Ordering::SeqCst),
"aborting must drop the underlying future"
);
}
#[test]
fn aborted_error_message() {
assert_eq!(TaskFailure::Aborted.to_string(), "promise aborted");
}
/// An abort arriving while the promise is pending wakes the parked task,
/// so a real executor would re-poll and observe the rejection.
#[test]
fn abort_wakes_a_pending_promise() {
let waker = Arc::new(CountingWaker(AtomicUsize::new(0)));
let raw = Waker::from(waker.clone());
let mut cx = Context::from_waker(&raw);
let (mut promise, handle) = pending_promise().abortable();
assert!(promise.poll_pending(&mut cx));
assert_eq!(waker.0.load(Ordering::SeqCst), 0);
assert_eq!(handle.abort(), Ok(PromiseAborted));
assert!(
waker.0.load(Ordering::SeqCst) >= 1,
"aborting a pending promise must wake the parked task"
);
assert!(promise.poll_settled(&mut cx));
assert_eq!(promise.consume(), Some(Err(E::Aborted)));
}
/// Once an abort has been observed and the promise has rejected, a later
/// abort is too late: the promise is no longer abortable.
#[test]
fn abort_after_rejection_reports_settled() {
let (mut promise, handle) = pending_promise().abortable();
assert_eq!(handle.abort(), Ok(PromiseAborted));
assert!(promise.poll_settled(&mut cx()));
assert_eq!(promise.consume(), Some(Err(E::Aborted)));
assert_eq!(handle.abort(), Err(PromiseSettled));
}
/// Dropping the wrapped promise leaves nothing to abort, so a later abort
/// reports the promise as settled.
#[test]
fn abort_after_dropping_the_promise_reports_settled() {
let (promise, handle) = pending_promise().abortable();
drop(promise);
assert_eq!(handle.abort(), Err(PromiseSettled));
}
}