vibesql_executor/timeout.rs
1//! Timeout context for query execution
2//!
3//! This module provides a lightweight timeout checking mechanism that can be
4//! passed to query execution functions (joins, scans, etc.) without requiring
5//! the full `SelectExecutor` reference.
6//!
7//! ## Design Rationale
8//!
9//! The `SelectExecutor` owns the timeout configuration but many query execution
10//! functions (especially joins) don't have access to it. Rather than threading
11//! the executor through all call chains, we extract just the timeout-related
12//! state into this lightweight struct.
13//!
14//! ## Usage Pattern
15//!
16//! ```text
17//! // Create from executor
18//! let timeout_ctx = TimeoutContext::from_executor(executor);
19//!
20//! // Pass to join/scan functions
21//! nested_loop_join(left, right, condition, database, &timeout_ctx)?;
22//!
23//! // Check periodically in hot loops
24//! for row in rows {
25//! if iteration % CHECK_INTERVAL == 0 {
26//! timeout_ctx.check()?;
27//! }
28//! // ... process row ...
29//! }
30//! ```
31
32use instant::Instant;
33
34use crate::errors::ExecutorError;
35use crate::limits::MAX_QUERY_EXECUTION_SECONDS;
36
37/// Recommended interval for timeout checks in hot loops.
38/// Checking every 1000 iterations balances responsiveness with overhead.
39pub const CHECK_INTERVAL: usize = 1000;
40
41/// Lightweight timeout context for query execution.
42///
43/// This struct captures the timeout configuration from `SelectExecutor` and can
44/// be passed to functions that need to check for timeouts but don't need the
45/// full executor reference.
46#[derive(Clone, Copy)]
47pub struct TimeoutContext {
48 /// When query execution started
49 start_time: Instant,
50 /// Maximum execution time in seconds
51 timeout_seconds: u64,
52}
53
54impl TimeoutContext {
55 /// Create a new timeout context with the given start time and timeout.
56 pub fn new(start_time: Instant, timeout_seconds: u64) -> Self {
57 Self { start_time, timeout_seconds }
58 }
59
60 /// Create a timeout context from a `SelectExecutor`.
61 pub fn from_executor(executor: &crate::SelectExecutor<'_>) -> Self {
62 Self { start_time: executor.start_time, timeout_seconds: executor.timeout_seconds }
63 }
64
65 /// Create a default timeout context (for use when no executor is available).
66 ///
67 /// This creates a context with the current time as start and default timeout.
68 /// Use sparingly - prefer `from_executor` when an executor is available.
69 pub fn new_default() -> Self {
70 Self { start_time: Instant::now(), timeout_seconds: MAX_QUERY_EXECUTION_SECONDS }
71 }
72
73 /// Check if the timeout has been exceeded.
74 ///
75 /// Returns `Ok(())` if within timeout, `Err(QueryTimeoutExceeded)` if exceeded.
76 ///
77 /// Call this periodically in hot loops (every `CHECK_INTERVAL` iterations).
78 #[inline]
79 pub fn check(&self) -> Result<(), ExecutorError> {
80 let elapsed = self.start_time.elapsed().as_secs();
81 if elapsed >= self.timeout_seconds {
82 return Err(ExecutorError::QueryTimeoutExceeded {
83 elapsed_seconds: elapsed,
84 max_seconds: self.timeout_seconds,
85 });
86 }
87 Ok(())
88 }
89
90 /// Get the start time for this timeout context.
91 pub fn start_time(&self) -> Instant {
92 self.start_time
93 }
94
95 /// Get the timeout in seconds for this timeout context.
96 pub fn timeout_seconds(&self) -> u64 {
97 self.timeout_seconds
98 }
99}
100
101impl Default for TimeoutContext {
102 fn default() -> Self {
103 Self::new_default()
104 }
105}
106
107#[cfg(test)]
108mod tests {
109 use super::*;
110 use std::thread::sleep;
111 use std::time::Duration;
112
113 #[test]
114 fn test_timeout_check_passes_within_limit() {
115 let ctx = TimeoutContext::new(Instant::now(), 60);
116 assert!(ctx.check().is_ok());
117 }
118
119 #[test]
120 fn test_timeout_check_fails_after_timeout() {
121 // Use a very short timeout
122 let ctx = TimeoutContext::new(Instant::now(), 0);
123 // Sleep briefly to ensure we're past the 0-second timeout
124 sleep(Duration::from_millis(10));
125 let result = ctx.check();
126 assert!(result.is_err());
127 if let Err(ExecutorError::QueryTimeoutExceeded { .. }) = result {
128 // Expected
129 } else {
130 panic!("Expected QueryTimeoutExceeded error");
131 }
132 }
133
134 #[test]
135 fn test_default_timeout_context() {
136 let ctx = TimeoutContext::default();
137 assert_eq!(ctx.timeout_seconds(), MAX_QUERY_EXECUTION_SECONDS);
138 assert!(ctx.check().is_ok());
139 }
140}