Skip to main content

rocketmq_runtime/
cancellation_observer.rs

1// Copyright 2026 The RocketMQ Rust Authors
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//! Lock-free checks and waits on a [`CancellationToken`].
16
17use std::fmt;
18use std::future::Future;
19use std::pin::Pin;
20use std::sync::atomic::AtomicBool;
21use std::sync::atomic::AtomicUsize;
22use std::sync::atomic::Ordering;
23use std::sync::Arc;
24use std::sync::Weak;
25use std::task::Context;
26use std::task::Wake;
27use std::task::Waker;
28
29use tokio::sync::Notify;
30use tokio_util::sync::CancellationToken;
31use tokio_util::sync::WaitForCancellationFutureOwned;
32
33/// Waiter lists per observer. Each thread uses one of them, so waits that start on different
34/// worker threads do not share a lock.
35const WAITER_SHARDS: usize = 8;
36
37/// Observes one [`CancellationToken`] without taking its lock.
38///
39/// `CancellationToken::is_cancelled` locks the token's tree node, and every wait on the token
40/// locks it on each poll. When many tasks on different threads check one token, such as all
41/// requests of a connection, that lock moves between cores on every check. An observer reads an
42/// atomic flag instead, and its waits register in per-thread waiter lists.
43///
44/// The flag is set while the token is being cancelled: the observer registers a waker with the
45/// token, which [`CancellationToken::cancel`] calls before it returns, also when the cancellation
46/// comes from a parent token. A thread that knows a cancellation has returned therefore sees
47/// [`is_cancelled`](Self::is_cancelled) return `true`, as it would on the token itself.
48///
49/// Cloning an observer shares its flag and waiter lists.
50#[derive(Clone)]
51pub struct CancellationObserver {
52    inner: Arc<ObserverInner>,
53}
54
55struct ObserverInner {
56    cancelled: AtomicBool,
57    token: CancellationToken,
58    /// Registered with `token` and polled with a [`BridgeWaker`] until it completes.
59    bridge: parking_lot::Mutex<Pin<Box<WaitForCancellationFutureOwned>>>,
60    waiters: [WaiterShard; WAITER_SHARDS],
61}
62
63/// Keeps each waiter list on its own cache lines.
64#[repr(align(128))]
65struct WaiterShard(Notify);
66
67impl CancellationObserver {
68    /// Creates an observer of `token`.
69    pub fn new(token: CancellationToken) -> Self {
70        let inner = Arc::new(ObserverInner {
71            cancelled: AtomicBool::new(false),
72            bridge: parking_lot::Mutex::new(Box::pin(token.clone().cancelled_owned())),
73            token,
74            waiters: std::array::from_fn(|_| WaiterShard(Notify::new())),
75        });
76        let waker = Waker::from(Arc::new(BridgeWaker {
77            observer: Arc::downgrade(&inner),
78        }));
79        inner.poll_bridge(&waker);
80        Self { inner }
81    }
82
83    /// Returns whether the token is cancelled, with one atomic load.
84    #[must_use]
85    pub fn is_cancelled(&self) -> bool {
86        self.inner.cancelled.load(Ordering::Acquire)
87    }
88
89    /// Waits until the token is cancelled.
90    pub fn cancelled(&self) -> impl Future<Output = ()> + Send + '_ {
91        let inner = &*self.inner;
92        async move {
93            loop {
94                if inner.cancelled.load(Ordering::Acquire) {
95                    return;
96                }
97                let notified = inner.waiters[current_shard()].0.notified();
98                // A cancellation that sets the flag after this load notifies the shard after
99                // `notified` was created, which completes it.
100                if inner.cancelled.load(Ordering::Acquire) {
101                    return;
102                }
103                notified.await;
104            }
105        }
106    }
107
108    /// Returns the observed token.
109    pub fn token(&self) -> &CancellationToken {
110        &self.inner.token
111    }
112}
113
114impl fmt::Debug for CancellationObserver {
115    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
116        formatter
117            .debug_struct("CancellationObserver")
118            .field("is_cancelled", &self.is_cancelled())
119            .finish()
120    }
121}
122
123impl ObserverInner {
124    /// Polls the token's cancellation future and sets the flag once it completes.
125    ///
126    /// Called on creation and from the token's cancellation, which tokio-util runs after it
127    /// released the token's locks, so polling the token here cannot deadlock.
128    fn poll_bridge(&self, waker: &Waker) {
129        let mut bridge = self.bridge.lock();
130        // Set under the lock, so a completed future is not polled again.
131        if self.cancelled.load(Ordering::Relaxed) || bridge.as_mut().poll(&mut Context::from_waker(waker)).is_pending()
132        {
133            return;
134        }
135        // Stored before the waiters are notified: a waiter that misses the flag created its
136        // `Notified` before these notifications.
137        self.cancelled.store(true, Ordering::Release);
138        drop(bridge);
139        for shard in &self.waiters {
140            shard.0.notify_waiters();
141        }
142    }
143}
144
145/// The waker registered with the observed token. It holds the observer weakly, so a token that
146/// is never cancelled does not keep a dropped observer alive.
147struct BridgeWaker {
148    observer: Weak<ObserverInner>,
149}
150
151impl Wake for BridgeWaker {
152    fn wake(self: Arc<Self>) {
153        self.wake_by_ref();
154    }
155
156    fn wake_by_ref(self: &Arc<Self>) {
157        if let Some(observer) = self.observer.upgrade() {
158            observer.poll_bridge(&Waker::from(Arc::clone(self)));
159        }
160    }
161}
162
163/// Returns this thread's waiter shard.
164fn current_shard() -> usize {
165    static NEXT_SHARD: AtomicUsize = AtomicUsize::new(0);
166    thread_local! {
167        static SHARD: usize = NEXT_SHARD.fetch_add(1, Ordering::Relaxed) % WAITER_SHARDS;
168    }
169    SHARD.with(|shard| *shard)
170}
171
172#[cfg(test)]
173mod tests {
174    use std::time::Duration;
175
176    use super::*;
177
178    #[test]
179    fn a_new_observer_of_a_cancelled_token_is_cancelled() {
180        let token = CancellationToken::new();
181        token.cancel();
182        assert!(CancellationObserver::new(token).is_cancelled());
183    }
184
185    #[test]
186    fn cancelling_the_token_sets_the_flag_before_cancel_returns() {
187        let token = CancellationToken::new();
188        let observer = CancellationObserver::new(token.clone());
189        assert!(!observer.is_cancelled());
190        token.cancel();
191        assert!(observer.is_cancelled());
192    }
193
194    #[test]
195    fn cancelling_a_parent_sets_the_flag_of_an_observed_child_before_cancel_returns() {
196        let parent = CancellationToken::new();
197        let observer = CancellationObserver::new(parent.child_token().child_token());
198        assert!(!observer.is_cancelled());
199        parent.cancel();
200        assert!(observer.is_cancelled());
201        assert!(observer.token().is_cancelled());
202    }
203
204    #[test]
205    fn cancelling_a_child_does_not_cancel_an_observed_parent() {
206        let parent = CancellationToken::new();
207        let observer = CancellationObserver::new(parent.clone());
208        parent.child_token().cancel();
209        assert!(!observer.is_cancelled());
210    }
211
212    #[test]
213    fn a_dropped_observer_is_freed_while_its_token_stays_alive() {
214        let token = CancellationToken::new();
215        let observer = CancellationObserver::new(token.clone());
216        let weak = Arc::downgrade(&observer.inner);
217        drop(observer);
218        assert!(weak.upgrade().is_none());
219        // Cancelling after the observer is gone wakes no one and does not panic.
220        token.cancel();
221    }
222
223    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
224    async fn every_waiter_wakes_when_the_token_is_cancelled() {
225        let token = CancellationToken::new();
226        let observer = CancellationObserver::new(token.clone());
227        let waiters: Vec<_> = (0..64)
228            .map(|_| {
229                let observer = observer.clone();
230                tokio::spawn(async move { observer.cancelled().await })
231            })
232            .collect();
233        tokio::task::yield_now().await;
234        token.cancel();
235        for waiter in waiters {
236            tokio::time::timeout(Duration::from_secs(5), waiter)
237                .await
238                .expect("the waiter wakes")
239                .unwrap();
240        }
241        observer.cancelled().await;
242    }
243
244    #[test]
245    fn waits_that_race_the_cancellation_all_complete() {
246        // Repeats the race between a waiter that has not yet registered and the cancellation.
247        for _ in 0..200 {
248            let token = CancellationToken::new();
249            let observer = CancellationObserver::new(token.clone());
250            let waiter = std::thread::spawn({
251                let observer = observer.clone();
252                move || futures::executor::block_on(observer.cancelled())
253            });
254            token.cancel();
255            waiter.join().unwrap();
256            assert!(observer.is_cancelled());
257        }
258    }
259}