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 scheduled: Arc<ScheduledTerminations>,
27}
28
29#[derive(Default)]
30struct ScheduledTerminations {
31 idle: Mutex<Option<ScheduledAction>>,
32 transaction: Mutex<Option<(i64, ScheduledAction)>>,
34}
35
36impl SessionTerminations {
37 pub(crate) fn new(tracks_idle: bool) -> Self {
38 Self {
39 tracks_idle,
40 gate_depth: AtomicUsize::new(0),
41 busy_epoch: Arc::new(AtomicU64::new(0)),
42 scheduled: Arc::new(ScheduledTerminations::default()),
43 }
44 }
45
46 fn for_termination(&self) -> Self {
48 Self {
49 tracks_idle: false,
50 gate_depth: AtomicUsize::new(0),
51 busy_epoch: Arc::clone(&self.busy_epoch),
52 scheduled: Arc::clone(&self.scheduled),
53 }
54 }
55
56 pub(crate) fn enter_gate(&self) -> bool {
58 self.tracks_idle && self.gate_depth.fetch_add(1, Ordering::AcqRel) == 0
59 }
60
61 pub(crate) fn leave_gate(&self) -> bool {
63 self.tracks_idle && self.gate_depth.fetch_sub(1, Ordering::AcqRel) == 1
64 }
65
66 pub(crate) fn is_idle(&self) -> bool {
68 self.gate_depth.load(Ordering::Acquire) == 0
69 }
70
71 pub(crate) fn disarm(&self) {
73 *self.scheduled.idle.lock() = None;
74 *self.scheduled.transaction.lock() = None;
75 }
76}
77
78enum TerminationScope {
80 IdlePeriod {
82 epoch: Arc<AtomicU64>,
83 expected: u64,
84 },
85 Transaction { started: i64, explicit: bool },
87}
88
89fn timeout(engine: &Engine, name: &str) -> Option<Duration> {
91 let milliseconds = engine.session.setting(name).parse::<u64>().ok()?;
92 (milliseconds != 0).then(|| Duration::from_millis(milliseconds))
93}
94
95impl Engine {
96 pub(crate) fn session_became_busy(&self) {
98 if !self.session.closure.is_open() {
99 return;
100 }
101 let terminations = &self.runtime.terminations;
102 terminations.busy_epoch.fetch_add(1, Ordering::AcqRel);
103 *terminations.scheduled.idle.lock() = None;
104 if self.transaction_depth() == 0 {
105 self.schedule_transaction_termination(uqa_sql::expr::clock_timestamp_micros());
106 }
107 }
108
109 pub(crate) fn session_became_idle(&self) {
111 if !self.session.closure.is_open() {
112 return;
113 }
114 if self.runtime.cancellation.termination().is_some() {
115 self.session_terminator_engine()
116 .finish_session_termination();
117 return;
118 }
119 let transaction_start = self
120 .session
121 .transactions
122 .lock()
123 .first()
124 .map(|frame| frame.started_at_micros);
125 let (name, reason) = if let Some(started) = transaction_start {
126 self.schedule_transaction_termination(started);
127 (
128 "idle_in_transaction_session_timeout",
129 CancellationReason::IdleInTransactionSessionTimeout,
130 )
131 } else {
132 *self.runtime.terminations.scheduled.transaction.lock() = None;
133 (
134 "idle_session_timeout",
135 CancellationReason::IdleSessionTimeout,
136 )
137 };
138 let Some(after) = timeout(self, name) else {
139 return;
140 };
141 let epoch = Arc::clone(&self.runtime.terminations.busy_epoch);
142 let expected = epoch.load(Ordering::Acquire);
143 let action =
144 self.termination_action(reason, TerminationScope::IdlePeriod { epoch, expected });
145 *self.runtime.terminations.scheduled.idle.lock() =
146 Some(self.runtime.cancellation.schedule(after, action));
147 }
148
149 fn schedule_transaction_termination(&self, started: i64) {
151 let mut scheduled = self.runtime.terminations.scheduled.transaction.lock();
152 if scheduled
153 .as_ref()
154 .is_some_and(|(start, _)| *start == started)
155 {
156 return;
157 }
158 *scheduled = None;
159 let Some(limit) = timeout(self, "transaction_timeout") else {
160 return;
161 };
162 let elapsed = uqa_sql::expr::clock_timestamp_micros().saturating_sub(started);
163 let elapsed = Duration::from_micros(u64::try_from(elapsed).unwrap_or(0));
164 let explicit = self.transaction_depth() != 0;
165 let action = self.termination_action(
166 CancellationReason::TransactionTimeout,
167 TerminationScope::Transaction { started, explicit },
168 );
169 *scheduled = Some((
170 started,
171 self.runtime
172 .cancellation
173 .schedule(limit.saturating_sub(elapsed), action),
174 ));
175 }
176
177 fn termination_action(
179 &self,
180 reason: CancellationReason,
181 scope: TerminationScope,
182 ) -> impl FnOnce() + Send + 'static {
183 let token = self.runtime.cancellation.clone();
184 let terminator = self.session_terminator_engine();
185 move || {
186 if !terminator.session.closure.is_open() {
187 return;
188 }
189 let applies = match &scope {
190 TerminationScope::IdlePeriod { epoch, expected } => {
191 epoch.load(Ordering::Acquire) == *expected
192 }
193 TerminationScope::Transaction { started, explicit } => {
194 !*explicit
195 || terminator
196 .session
197 .transactions
198 .lock()
199 .first()
200 .is_some_and(|frame| frame.started_at_micros == *started)
201 }
202 };
203 if !applies {
204 return;
205 }
206 token.cancel_with(reason);
207 let _ = std::thread::Builder::new()
209 .name("uqa-session-termination".into())
210 .spawn(move || terminator.terminate_idle_session());
211 }
212 }
213
214 fn terminate_idle_session(&self) {
216 let Some(_statement) = self.runtime.statement_gate.try_lock() else {
217 return;
218 };
219 self.finish_session_termination();
220 }
221
222 fn finish_session_termination(&self) {
224 let _ = self.close_terminated_session();
225 }
226
227 fn session_terminator_engine(&self) -> Engine {
229 let mut runtime = crate::QueryRuntime::with_cancellation(
230 self.sql_function_depth_limit(),
231 self.runtime.cancellation.clone(),
232 self.session.state.client_level(),
233 self.session.state.io_timing(),
234 );
235 runtime.function_context = std::sync::Arc::clone(&self.runtime.function_context);
236 runtime.diagnostics = self.runtime.diagnostics.fork();
237 runtime.statement_gate = Arc::clone(&self.runtime.statement_gate);
238 runtime.notices = Arc::clone(&self.runtime.notices);
239 runtime.notifications = Arc::clone(&self.runtime.notifications);
240 runtime.notification_wake = Arc::clone(&self.runtime.notification_wake);
241 runtime.terminations = self.runtime.terminations.for_termination();
242 Engine {
243 storage: crate::StorageContext::shared_from(&self.storage),
244 durable: Arc::clone(&self.durable),
245 session: Arc::clone(&self.session),
246 extensions: crate::RuntimeExtensions::shared_from(&self.extensions),
247 epochs: Arc::clone(&self.epochs),
248 runtime,
249 row_locks: Arc::clone(&self.row_locks),
250 statistics: Arc::clone(&self.statistics),
251 notification_hub: Arc::clone(&self.notification_hub),
252 session_id: self.session_id,
253 owns_session_registration: false,
254 query_table_snapshots: None,
255 query_view_snapshots: None,
256 query_sql_function_snapshots: None,
257 query_catalog_snapshot: None,
258 query_transaction_overlay: None,
259 query_transaction_origin: None,
260 }
261 }
262
263 pub fn session_termination(&self) -> Option<uqa_sql::SQLError> {
265 self.runtime
266 .cancellation
267 .termination()
268 .map(|reason| uqa_core::QueryCancelled::new(reason).into())
269 }
270}