Skip to main content

uqa_sql/expr/
statement_cancellation.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! The cancellation of the statement the current thread runs. Work inside one scalar evaluation that can run long checks it as `PostgreSQL`'s `CHECK_FOR_INTERRUPTS` observes a cancel request or `statement_timeout`, without receiving a production control from its caller.
8
9use std::{cell::RefCell, marker::PhantomData, rc::Rc};
10use uqa_core::{CancellationToken, QueryCancelled};
11
12thread_local! {
13    /// The cancellation token of the statement the current thread runs while a [`StatementCancellationScope`] is entered.
14    static STATEMENT_CANCELLATION: RefCell<Option<CancellationToken>> = const { RefCell::new(None) };
15}
16
17/// The running statement's cancellation token, which a thread dispatching part of the statement to a worker captures for the worker to enter; `None` outside any statement.
18#[must_use]
19pub fn statement_cancellation() -> Option<CancellationToken> {
20    STATEMENT_CANCELLATION.with_borrow(Clone::clone)
21}
22
23/// Report the running statement's cancellation with the reason its token was canceled for, or `Ok` while it may continue. Work outside any statement has no cancellation to observe and continues.
24pub fn check_statement_cancellation() -> Result<(), QueryCancelled> {
25    STATEMENT_CANCELLATION
26        .with_borrow(|token| token.as_ref().map_or(Ok(()), CancellationToken::check))
27}
28
29/// Runs the current thread under one statement's cancellation until it drops, restoring the enclosing statement's so nested statements and workers return to their caller's.
30pub struct StatementCancellationScope {
31    previous: Option<CancellationToken>,
32    thread: PhantomData<Rc<()>>,
33}
34
35impl StatementCancellationScope {
36    /// Enter `token` as the running statement's cancellation. Entering `None` runs the thread outside any statement, as a worker does for work dispatched from outside one, so it never observes the cancellation of a statement whose work it ran before.
37    #[must_use]
38    pub fn enter(token: impl Into<Option<CancellationToken>>) -> Self {
39        Self {
40            previous: STATEMENT_CANCELLATION.replace(token.into()),
41            thread: PhantomData,
42        }
43    }
44}
45
46impl Drop for StatementCancellationScope {
47    fn drop(&mut self) {
48        STATEMENT_CANCELLATION.set(self.previous.take());
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55    use uqa_core::CancellationReason;
56
57    #[test]
58    fn work_outside_a_statement_continues_without_a_token() {
59        assert!(statement_cancellation().is_none());
60        assert_eq!(check_statement_cancellation(), Ok(()));
61    }
62
63    #[test]
64    fn a_statement_observes_its_token_with_the_reason_it_was_canceled_for() {
65        let token = CancellationToken::new();
66        let _statement = StatementCancellationScope::enter(token.clone());
67        assert!(statement_cancellation().is_some_and(|current| current.shares_signal(&token)));
68        assert_eq!(check_statement_cancellation(), Ok(()));
69        token.cancel_with(CancellationReason::StatementTimeout);
70        let cancelled = check_statement_cancellation().unwrap_err();
71        assert_eq!(
72            cancelled,
73            QueryCancelled::new(CancellationReason::StatementTimeout)
74        );
75        assert_eq!(cancelled.sqlstate(), "57014");
76        assert_eq!(
77            cancelled.to_string(),
78            "canceling statement due to statement timeout"
79        );
80        token.reset();
81        assert_eq!(check_statement_cancellation(), Ok(()));
82    }
83
84    #[test]
85    fn nested_statements_restore_the_enclosing_cancellation_on_every_exit() {
86        let outer = CancellationToken::new();
87        let inner = CancellationToken::new();
88        inner.cancel();
89        let _outer = StatementCancellationScope::enter(outer.clone());
90        {
91            let _inner = StatementCancellationScope::enter(inner.clone());
92            assert!(statement_cancellation().is_some_and(|current| current.shares_signal(&inner)));
93            assert_eq!(
94                check_statement_cancellation(),
95                Err(QueryCancelled::USER_REQUEST)
96            );
97            {
98                let _detached = StatementCancellationScope::enter(None);
99                assert!(statement_cancellation().is_none());
100                assert_eq!(check_statement_cancellation(), Ok(()));
101            }
102            assert!(statement_cancellation().is_some_and(|current| current.shares_signal(&inner)));
103        }
104        assert!(statement_cancellation().is_some_and(|current| current.shares_signal(&outer)));
105        assert_eq!(check_statement_cancellation(), Ok(()));
106        let failed = std::panic::catch_unwind(|| {
107            let _failing = StatementCancellationScope::enter(inner.clone());
108            panic!("the statement fails inside its scope");
109        });
110        assert!(failed.is_err());
111        assert!(statement_cancellation().is_some_and(|current| current.shares_signal(&outer)));
112    }
113
114    #[test]
115    fn another_thread_runs_outside_the_statement_until_it_enters_the_token() {
116        let token = CancellationToken::new();
117        token.cancel();
118        let _statement = StatementCancellationScope::enter(token.clone());
119        let captured = statement_cancellation();
120        std::thread::spawn(move || {
121            assert_eq!(check_statement_cancellation(), Ok(()));
122            let _worker = StatementCancellationScope::enter(captured);
123            assert_eq!(
124                check_statement_cancellation(),
125                Err(QueryCancelled::USER_REQUEST)
126            );
127        })
128        .join()
129        .unwrap();
130    }
131}