witchcraft_server/blocking/cancellation.rs
1// Copyright 2022 Palantir Technologies, Inc.
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.
14use std::sync::atomic::{AtomicBool, Ordering};
15use std::sync::Arc;
16
17/// A type tracking the cancellation state of a request.
18///
19/// This type will be added to the extensions of each request made to a blocking endpoint.
20#[derive(Clone, Debug)]
21pub struct Cancellation {
22 cancelled: Arc<AtomicBool>,
23}
24
25impl Cancellation {
26 pub(crate) fn new() -> (Cancellation, CancellationGuard) {
27 let cancelled = Arc::new(AtomicBool::new(false));
28 (
29 Cancellation {
30 cancelled: cancelled.clone(),
31 },
32 CancellationGuard { cancelled },
33 )
34 }
35
36 /// Returns `true` if the client of a request has cancelled it.
37 ///
38 /// Long running blocking endpoint handlers should periodically check this to determine if they should continue
39 /// working or not.
40 #[inline]
41 pub fn is_cancelled(&self) -> bool {
42 self.cancelled.load(Ordering::Relaxed)
43 }
44}
45
46pub struct CancellationGuard {
47 cancelled: Arc<AtomicBool>,
48}
49
50impl Drop for CancellationGuard {
51 fn drop(&mut self) {
52 self.cancelled.store(true, Ordering::Relaxed);
53 }
54}