uqa_engine/session/
terminations.rs1use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
10use std::sync::Arc;
11use std::time::Duration;
12
13use parking_lot::Mutex;
14use uqa_core::{CancellationReason, ScheduledAction};
15
16use super::Engine;
17
18pub(crate) struct SessionTerminations {
20 tracks_idle: bool,
22 gate_depth: AtomicUsize,
24 busy_epoch: Arc<AtomicU64>,
26 idle: Mutex<Option<ScheduledAction>>,
27 transaction: Mutex<Option<(i64, ScheduledAction)>>,
29}
30
31impl SessionTerminations {
32 pub(crate) fn new(tracks_idle: bool) -> Self {
33 Self {
34 tracks_idle,
35 gate_depth: AtomicUsize::new(0),
36 busy_epoch: Arc::new(AtomicU64::new(0)),
37 idle: Mutex::new(None),
38 transaction: Mutex::new(None),
39 }
40 }
41
42 pub(crate) fn enter_gate(&self) -> bool {
44 self.tracks_idle && self.gate_depth.fetch_add(1, Ordering::AcqRel) == 0
45 }
46
47 pub(crate) fn leave_gate(&self) -> bool {
49 self.tracks_idle && self.gate_depth.fetch_sub(1, Ordering::AcqRel) == 1
50 }
51
52 pub(crate) fn is_idle(&self) -> bool {
54 self.gate_depth.load(Ordering::Acquire) == 0
55 }
56
57 pub(crate) fn disarm(&self) {
59 *self.idle.lock() = None;
60 *self.transaction.lock() = None;
61 }
62}
63
64enum TerminationScope {
66 IdlePeriod {
68 epoch: Arc<AtomicU64>,
69 expected: u64,
70 },
71 Transaction { started: i64, explicit: bool },
73}
74
75fn timeout(engine: &Engine, name: &str) -> Option<Duration> {
77 let milliseconds = engine.session.setting(name).parse::<u64>().ok()?;
78 (milliseconds != 0).then(|| Duration::from_millis(milliseconds))
79}
80
81impl Engine {
82 pub(crate) fn session_became_busy(&self) {
84 let terminations = &self.runtime.terminations;
85 terminations.busy_epoch.fetch_add(1, Ordering::AcqRel);
86 *terminations.idle.lock() = None;
87 if self.transaction_depth() == 0 {
88 self.schedule_transaction_termination(uqa_sql::expr::clock_timestamp_micros());
89 }
90 }
91
92 pub(crate) fn session_became_idle(&self) {
94 if self.runtime.cancellation.termination().is_some() {
95 self.session_terminator_engine()
96 .finish_session_termination();
97 return;
98 }
99 let transaction_start = self
100 .session
101 .transactions
102 .lock()
103 .first()
104 .map(|frame| frame.started_at_micros);
105 let (name, reason) = if let Some(started) = transaction_start {
106 self.schedule_transaction_termination(started);
107 (
108 "idle_in_transaction_session_timeout",
109 CancellationReason::IdleInTransactionSessionTimeout,
110 )
111 } else {
112 *self.runtime.terminations.transaction.lock() = None;
113 (
114 "idle_session_timeout",
115 CancellationReason::IdleSessionTimeout,
116 )
117 };
118 let Some(after) = timeout(self, name) else {
119 return;
120 };
121 let epoch = Arc::clone(&self.runtime.terminations.busy_epoch);
122 let expected = epoch.load(Ordering::Acquire);
123 let action =
124 self.termination_action(reason, TerminationScope::IdlePeriod { epoch, expected });
125 *self.runtime.terminations.idle.lock() = Some(uqa_core::cancel::schedule(after, action));
126 }
127
128 fn schedule_transaction_termination(&self, started: i64) {
130 let mut scheduled = self.runtime.terminations.transaction.lock();
131 if scheduled
132 .as_ref()
133 .is_some_and(|(start, _)| *start == started)
134 {
135 return;
136 }
137 *scheduled = None;
138 let Some(limit) = timeout(self, "transaction_timeout") else {
139 return;
140 };
141 let elapsed = uqa_sql::expr::clock_timestamp_micros().saturating_sub(started);
142 let elapsed = Duration::from_micros(u64::try_from(elapsed).unwrap_or(0));
143 let explicit = self.transaction_depth() != 0;
144 let action = self.termination_action(
145 CancellationReason::TransactionTimeout,
146 TerminationScope::Transaction { started, explicit },
147 );
148 *scheduled = Some((
149 started,
150 uqa_core::cancel::schedule(limit.saturating_sub(elapsed), action),
151 ));
152 }
153
154 fn termination_action(
156 &self,
157 reason: CancellationReason,
158 scope: TerminationScope,
159 ) -> impl FnOnce() + Send + 'static {
160 let token = self.runtime.cancellation.clone();
161 let terminator = self.session_terminator_engine();
162 move || {
163 let applies = match &scope {
164 TerminationScope::IdlePeriod { epoch, expected } => {
165 epoch.load(Ordering::Acquire) == *expected
166 }
167 TerminationScope::Transaction { started, explicit } => {
168 !*explicit
169 || terminator
170 .session
171 .transactions
172 .lock()
173 .first()
174 .is_some_and(|frame| frame.started_at_micros == *started)
175 }
176 };
177 if !applies {
178 return;
179 }
180 token.cancel_with(reason);
181 let _ = std::thread::Builder::new()
183 .name("uqa-session-termination".into())
184 .spawn(move || terminator.terminate_idle_session());
185 }
186 }
187
188 fn terminate_idle_session(&self) {
190 let Some(_statement) = self.runtime.statement_gate.try_lock() else {
191 return;
192 };
193 self.finish_session_termination();
194 }
195
196 fn finish_session_termination(&self) {
198 if self
199 .session
200 .termination_finished
201 .swap(true, Ordering::AcqRel)
202 {
203 return;
204 }
205 while self.transaction_depth() != 0 {
206 if self.rollback().is_err() {
207 break;
208 }
209 }
210 if let Some(cache) = self.session.regex_cache.lock().take() {
211 cache.clear();
212 }
213 let _ = self.clear_notification_listener_without_transaction();
214 self.release_automatic_statistics_client();
215 }
216
217 fn session_terminator_engine(&self) -> Engine {
219 let mut epochs = crate::EpochCoordinator::new();
220 epochs.share_published_from(&self.epochs);
221 let mut runtime = crate::QueryRuntime::new(
222 self.sql_function_depth_limit(),
223 self.session.state.client_level(),
224 );
225 runtime.diagnostics = self.runtime.diagnostics.fork();
226 runtime.statement_gate = Arc::clone(&self.runtime.statement_gate);
227 runtime.notices = Arc::clone(&self.runtime.notices);
228 runtime.notifications = Arc::clone(&self.runtime.notifications);
229 runtime.terminations = SessionTerminations::new(false);
230 Engine {
231 storage: crate::StorageContext::shared_from(&self.storage),
232 durable: Arc::clone(&self.durable),
233 session: Arc::clone(&self.session),
234 extensions: crate::RuntimeExtensions::shared_from(&self.extensions),
235 epochs,
236 runtime,
237 row_locks: Arc::clone(&self.row_locks),
238 statistics: Arc::clone(&self.statistics),
239 notification_hub: Arc::clone(&self.notification_hub),
240 session_id: self.session_id,
241 owns_session_registration: false,
242 query_table_snapshots: None,
243 query_view_snapshots: None,
244 query_sql_function_snapshots: None,
245 query_catalog_snapshot: None,
246 query_transaction_overlay: None,
247 query_transaction_origin: None,
248 }
249 }
250
251 pub fn session_termination(&self) -> Option<uqa_sql::SQLError> {
253 self.runtime
254 .cancellation
255 .termination()
256 .map(|reason| uqa_core::QueryCancelled::new(reason).into())
257 }
258}