lemma/evaluator/
timeout.rs

1//! Timeout tracking for evaluation
2//!
3//! Provides platform-specific timeout tracking. On native targets, uses std::time::Instant
4//! to track elapsed time. On WASM, timeout checking is a no-op since std::time::Instant
5//! is not available in the wasm32 target.
6
7use crate::{LemmaError, ResourceLimits};
8
9#[cfg(not(target_arch = "wasm32"))]
10use std::time::Instant;
11
12/// Timeout tracker for evaluation
13///
14/// On native platforms, tracks actual elapsed time using Instant.
15/// On WASM, this is a zero-cost abstraction with no-op timeout checks.
16pub struct TimeoutTracker {
17    #[cfg(not(target_arch = "wasm32"))]
18    start_time: Instant,
19}
20
21impl TimeoutTracker {
22    /// Create a new timeout tracker
23    #[cfg(not(target_arch = "wasm32"))]
24    pub fn new() -> Self {
25        Self {
26            start_time: Instant::now(),
27        }
28    }
29
30    /// Create a new timeout tracker (WASM version)
31    #[cfg(target_arch = "wasm32")]
32    pub fn new() -> Self {
33        Self {}
34    }
35
36    /// Check if evaluation has exceeded the timeout limit
37    ///
38    /// On native platforms, returns an error if elapsed time exceeds max_evaluation_time_ms.
39    /// On WASM, always returns Ok (timeout checking not available).
40    #[cfg(not(target_arch = "wasm32"))]
41    pub fn check_timeout(&self, limits: &ResourceLimits) -> Result<(), LemmaError> {
42        let elapsed_ms = self.start_time.elapsed().as_millis() as u64;
43        if elapsed_ms > limits.max_evaluation_time_ms {
44            return Err(LemmaError::ResourceLimitExceeded {
45                limit_name: "max_evaluation_time_ms".to_string(),
46                limit_value: limits.max_evaluation_time_ms.to_string(),
47                actual_value: elapsed_ms.to_string(),
48                suggestion: format!(
49                    "Evaluation took {}ms, exceeding the limit of {}ms. Simplify the document or increase the timeout.",
50                    elapsed_ms, limits.max_evaluation_time_ms
51                ),
52            });
53        }
54        Ok(())
55    }
56
57    /// Check if evaluation has exceeded the timeout limit (WASM version - no-op)
58    #[cfg(target_arch = "wasm32")]
59    pub fn check_timeout(&self, _limits: &ResourceLimits) -> Result<(), LemmaError> {
60        // Timeout checking not available on WASM (no std::time::Instant)
61        Ok(())
62    }
63}
64
65impl Default for TimeoutTracker {
66    fn default() -> Self {
67        Self::new()
68    }
69}