zu_common/interrupt.rs
1//! The handle a caller keeps on a statement that is running: whether
2//! it has been asked to stop, and how far it has got.
3//!
4//! A statement runs on the thread that asked for it, so the only way to
5//! stop one is to leave something behind that the run reads as it goes.
6//! That something is one word. The executors check it where they
7//! already have a natural boundary, which is a chunk in the pull engine
8//! and a morsel in the pipeline one, so a cancellation is answered
9//! within a vector of rows rather than at the end of the query, and the
10//! check costs a relaxed load in a place that has just done thousands
11//! of them.
12//!
13//! Nothing here is a timeout, and nothing here unwinds anything. The
14//! run notices, returns [`ZuError::Interrupted`], and the session it
15//! ran on is untouched: no plan is dropped, no reader is closed, and
16//! the next statement on it starts warm. That is the difference between
17//! cancelling a statement and killing a process, and it is the whole
18//! reason a shell wants this rather than a signal.
19//!
20//! A handle nobody armed costs one branch on a null pointer per check
21//! and never says stop, which is what every caller who did not ask for
22//! cancellation gets by default.
23
24use std::sync::Arc;
25use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
26
27use crate::{Result, ZuError};
28
29/// What the running statement and whoever is waiting for it share.
30///
31/// The two words sit together because they are read together: a caller
32/// waiting on a statement asks whether to stop it and how far it has
33/// got in the same breath, and the run touches both at the same
34/// boundary.
35#[derive(Debug, Default)]
36struct Shared {
37 stop: AtomicBool,
38 rows: AtomicU64,
39}
40
41/// A handle on a running statement.
42///
43/// Cloning is cloning the handle, not the state: every clone reads and
44/// writes the same word, which is what lets one thread hand a copy to
45/// the executor and keep one to raise. [`Interrupt::default`] is the
46/// handle nobody is holding, and it is the one that costs nothing.
47#[derive(Clone, Debug, Default)]
48pub struct Interrupt(Option<Arc<Shared>>);
49
50impl Interrupt {
51 /// A handle a caller can raise, with the word allocated for it.
52 ///
53 /// Spelled apart from [`Default`] because the two are different
54 /// things: this one can stop a statement and the default one
55 /// cannot, and a constructor that quietly returned the second when
56 /// asked for the first would be a cancellation that never arrives.
57 pub fn armed() -> Interrupt {
58 Interrupt(Some(Arc::new(Shared::default())))
59 }
60
61 /// Asks the statement to stop. Does nothing on a handle nobody
62 /// armed, which is the honest answer: there is no statement on the
63 /// other end of it.
64 pub fn stop(&self) {
65 if let Some(shared) = &self.0 {
66 shared.stop.store(true, Ordering::Relaxed);
67 }
68 }
69
70 /// Whether somebody has asked.
71 pub fn stopped(&self) -> bool {
72 self.0
73 .as_ref()
74 .is_some_and(|shared| shared.stop.load(Ordering::Relaxed))
75 }
76
77 /// The check an executor makes at a boundary: `Ok` while nobody has
78 /// asked, and the condition that ends the statement once somebody
79 /// has.
80 pub fn check(&self) -> Result<()> {
81 if self.stopped() {
82 return Err(ZuError::Interrupted);
83 }
84 Ok(())
85 }
86
87 /// Puts the flag down and the count back to zero, which is what
88 /// makes one handle serve a session rather than one statement.
89 ///
90 /// Called before a statement rather than after it, so that a stop
91 /// which arrived while nothing was running cannot end the next
92 /// thing the user types.
93 pub fn clear(&self) {
94 if let Some(shared) = &self.0 {
95 shared.stop.store(false, Ordering::Relaxed);
96 shared.rows.store(0, Ordering::Relaxed);
97 }
98 }
99
100 /// The executor reporting rows it has read out of storage.
101 ///
102 /// Rows read rather than rows answered, because the number is there
103 /// to show a person that something is happening, and a statement
104 /// that reads a hundred million rows to answer one row is exactly
105 /// the statement they are waiting on.
106 pub fn read(&self, rows: u64) {
107 if let Some(shared) = &self.0 {
108 shared.rows.fetch_add(rows, Ordering::Relaxed);
109 }
110 }
111
112 /// How many rows it has read so far.
113 pub fn rows(&self) -> u64 {
114 self.0
115 .as_ref()
116 .map_or(0, |shared| shared.rows.load(Ordering::Relaxed))
117 }
118}
119
120#[cfg(test)]
121mod tests {
122 use super::*;
123
124 #[test]
125 fn an_armed_handle_stops_and_a_default_one_never_does() {
126 let armed = Interrupt::armed();
127 assert!(!armed.stopped());
128 assert!(armed.check().is_ok());
129 armed.stop();
130 assert!(armed.stopped());
131 assert!(matches!(armed.check(), Err(ZuError::Interrupted)));
132
133 let never = Interrupt::default();
134 never.stop();
135 assert!(!never.stopped());
136 assert!(never.check().is_ok());
137 }
138
139 #[test]
140 fn every_clone_is_the_same_word() {
141 let held = Interrupt::armed();
142 let handed = held.clone();
143 handed.read(2048);
144 held.read(2048);
145 assert_eq!(held.rows(), 4096);
146 assert_eq!(handed.rows(), 4096);
147 held.stop();
148 assert!(handed.stopped(), "the executor's copy sees the ask");
149
150 // Clearing readies the same handle for the next statement, which
151 // is what a session does with it between two of them.
152 handed.clear();
153 assert!(!held.stopped());
154 assert_eq!(held.rows(), 0);
155 }
156
157 #[test]
158 fn a_default_handle_counts_nothing_and_answers_nothing() {
159 let never = Interrupt::default();
160 never.read(4096);
161 assert_eq!(never.rows(), 0);
162 }
163}