Skip to main content

common_base/
cancellation.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! [CancellationHandle] is used to compose with manual implementation of [futures::future::Future]
16//! or [futures::stream::Stream] to facilitate cancellation.
17//! See example in [frontend::stream_wrapper::CancellableStreamWrapper] and [CancellableFuture].
18
19use std::fmt::{Debug, Display, Formatter};
20use std::future::Future;
21use std::pin::Pin;
22use std::sync::Arc;
23use std::sync::atomic::{AtomicBool, Ordering};
24use std::task::{Context, Poll};
25
26use futures::task::AtomicWaker;
27use pin_project::pin_project;
28
29#[derive(Default)]
30pub struct CancellationHandle {
31    waker: AtomicWaker,
32    cancelled: AtomicBool,
33}
34
35impl Debug for CancellationHandle {
36    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
37        f.debug_struct("CancellationHandle")
38            .field("cancelled", &self.is_cancelled())
39            .finish()
40    }
41}
42
43impl CancellationHandle {
44    pub fn waker(&self) -> &AtomicWaker {
45        &self.waker
46    }
47
48    /// Cancels a future or stream.
49    pub fn cancel(&self) {
50        if self
51            .cancelled
52            .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
53            .is_ok()
54        {
55            self.waker.wake();
56        }
57    }
58
59    /// Is this handle cancelled.
60    pub fn is_cancelled(&self) -> bool {
61        self.cancelled.load(Ordering::Relaxed)
62    }
63}
64
65#[pin_project]
66#[derive(Debug, Clone)]
67pub struct CancellableFuture<T> {
68    #[pin]
69    fut: T,
70    handle: Arc<CancellationHandle>,
71}
72
73impl<T> CancellableFuture<T> {
74    pub fn new(fut: T, handle: Arc<CancellationHandle>) -> Self {
75        Self { fut, handle }
76    }
77}
78
79impl<T> Future for CancellableFuture<T>
80where
81    T: Future,
82{
83    type Output = Result<T::Output, Cancelled>;
84
85    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
86        let this = self.as_mut().project();
87        // Check if the task has been aborted
88        if this.handle.is_cancelled() {
89            return Poll::Ready(Err(Cancelled));
90        }
91
92        if let Poll::Ready(x) = this.fut.poll(cx) {
93            return Poll::Ready(Ok(x));
94        }
95
96        this.handle.waker().register(cx.waker());
97        if this.handle.is_cancelled() {
98            return Poll::Ready(Err(Cancelled));
99        }
100        Poll::Pending
101    }
102}
103
104#[derive(Copy, Clone, Debug)]
105pub struct Cancelled;
106
107impl std::error::Error for Cancelled {}
108
109impl Display for Cancelled {
110    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
111        write!(f, "Future has been cancelled")
112    }
113}
114
115#[cfg(test)]
116mod tests {
117    use std::sync::Arc;
118    use std::time::Duration;
119
120    use tokio::time::{sleep, timeout};
121
122    use crate::cancellation::{CancellableFuture, CancellationHandle, Cancelled};
123
124    #[tokio::test]
125    async fn test_cancellable_future_completes_normally() {
126        let handle = Arc::new(CancellationHandle::default());
127        let future = async { 42 };
128        let cancellable = CancellableFuture::new(future, handle);
129
130        let result = cancellable.await;
131        assert!(result.is_ok());
132        assert_eq!(result.unwrap(), 42);
133    }
134
135    #[tokio::test]
136    async fn test_cancellable_future_cancelled_before_start() {
137        let handle = Arc::new(CancellationHandle::default());
138        handle.cancel();
139
140        let future = async { 42 };
141        let cancellable = CancellableFuture::new(future, handle);
142
143        let result = cancellable.await;
144        assert!(result.is_err());
145        assert!(matches!(result.unwrap_err(), Cancelled));
146    }
147
148    #[tokio::test]
149    async fn test_cancellable_future_cancelled_during_execution() {
150        let handle = Arc::new(CancellationHandle::default());
151        let handle_clone = handle.clone();
152
153        // Create a future that sleeps for a long time
154        let future = async {
155            sleep(Duration::from_secs(10)).await;
156            42
157        };
158        let cancellable = CancellableFuture::new(future, handle);
159
160        // Cancel the future after a short delay
161        tokio::spawn(async move {
162            sleep(Duration::from_millis(50)).await;
163            handle_clone.cancel();
164        });
165
166        let result = cancellable.await;
167        assert!(result.is_err());
168        assert!(matches!(result.unwrap_err(), Cancelled));
169    }
170
171    #[tokio::test]
172    async fn test_cancellable_future_completes_before_cancellation() {
173        let handle = Arc::new(CancellationHandle::default());
174        let handle_clone = handle.clone();
175
176        // Create a future that completes quickly
177        let future = async {
178            sleep(Duration::from_millis(10)).await;
179            42
180        };
181        let cancellable = CancellableFuture::new(future, handle);
182
183        // Try to cancel after the future should have completed
184        tokio::spawn(async move {
185            sleep(Duration::from_millis(100)).await;
186            handle_clone.cancel();
187        });
188
189        let result = cancellable.await;
190        assert!(result.is_ok());
191        assert_eq!(result.unwrap(), 42);
192    }
193
194    #[tokio::test]
195    async fn test_cancellation_handle_is_cancelled() {
196        let handle = CancellationHandle::default();
197        assert!(!handle.is_cancelled());
198
199        handle.cancel();
200        assert!(handle.is_cancelled());
201    }
202
203    #[tokio::test]
204    async fn test_multiple_cancellable_futures_with_same_handle() {
205        let handle = Arc::new(CancellationHandle::default());
206
207        let future1 = CancellableFuture::new(async { 1 }, handle.clone());
208        let future2 = CancellableFuture::new(async { 2 }, handle.clone());
209
210        // Cancel before starting
211        handle.cancel();
212
213        let (result1, result2) = tokio::join!(future1, future2);
214
215        assert!(result1.is_err());
216        assert!(result2.is_err());
217        assert!(matches!(result1.unwrap_err(), Cancelled));
218        assert!(matches!(result2.unwrap_err(), Cancelled));
219    }
220
221    #[tokio::test]
222    async fn test_cancellable_future_with_timeout() {
223        let handle = Arc::new(CancellationHandle::default());
224        let future = async {
225            sleep(Duration::from_secs(1)).await;
226            42
227        };
228        let cancellable = CancellableFuture::new(future, handle.clone());
229
230        // Use timeout to ensure the test doesn't hang
231        let result = timeout(Duration::from_millis(100), cancellable).await;
232
233        // Should timeout because the future takes 1 second but we timeout after 100ms
234        assert!(result.is_err());
235    }
236
237    #[tokio::test]
238    async fn test_cancelled_display() {
239        let cancelled = Cancelled;
240        assert_eq!(format!("{}", cancelled), "Future has been cancelled");
241    }
242}