AirLibrary/Resilience/
Timeout.rs1#![allow(unused_variables, dead_code, unused_imports)]
2
3use std::time::{Duration, Instant};
15
16use crate::dev_log;
17
18pub struct TimeoutManager {
20 global_deadline:Option<Instant>,
21 operation_timeout:Duration,
22}
23
24impl TimeoutManager {
25 pub fn new(operation_timeout:Duration) -> Self { Self { global_deadline:None, operation_timeout } }
27
28 pub fn with_deadline(global_deadline:Instant, operation_timeout:Duration) -> Self {
30 Self { global_deadline:Some(global_deadline), operation_timeout }
31 }
32
33 pub fn ValidateTimeout(timeout:Duration) -> Result<(), String> {
35 if timeout.is_zero() {
36 return Err("Timeout must be greater than 0".to_string());
37 }
38 if timeout.as_secs() > 3600 {
39 return Err("Timeout cannot exceed 1 hour".to_string());
40 }
41 Ok(())
42 }
43
44 pub fn ValidateTimeoutResult(timeout:Duration) -> Result<Duration, String> {
46 if timeout.is_zero() {
47 return Err("Timeout must be greater than 0".to_string());
48 }
49 if timeout.as_secs() > 3600 {
50 return Err("Timeout cannot exceed 1 hour".to_string());
51 }
52 Ok(timeout)
53 }
54
55 pub fn remaining(&self) -> Option<Duration> {
57 self.global_deadline.map(|deadline| {
58 deadline
59 .checked_duration_since(Instant::now())
60 .unwrap_or(Duration::from_secs(0))
61 })
62 }
63
64 pub fn Remaining(&self) -> Option<Duration> {
66 std::panic::catch_unwind(|| self.remaining()).unwrap_or_else(|e| {
67 dev_log!("resilience", "error: [TimeoutManager] Panic in Remaining: {:?}", e);
68 None
69 })
70 }
71
72 pub fn effective_timeout(&self) -> Duration {
74 match self.remaining() {
75 Some(remaining) => self.operation_timeout.min(remaining),
76 None => self.operation_timeout,
77 }
78 }
79
80 pub fn EffectiveTimeout(&self) -> Duration {
82 std::panic::catch_unwind(|| {
83 let timeout = self.effective_timeout();
84 match Self::ValidateTimeoutResult(timeout) {
85 Ok(valid_timeout) => valid_timeout,
86 Err(_) => Duration::from_secs(30),
87 }
88 })
89 .unwrap_or_else(|e| {
90 dev_log!("resilience", "error: [TimeoutManager] Panic in EffectiveTimeout: {:?}", e);
91 Duration::from_secs(30)
92 })
93 }
94
95 pub fn is_exceeded(&self) -> bool { self.global_deadline.map_or(false, |deadline| Instant::now() >= deadline) }
97
98 pub fn IsExceeded(&self) -> bool {
100 std::panic::catch_unwind(|| self.is_exceeded()).unwrap_or_else(|e| {
101 dev_log!("resilience", "error: [TimeoutManager] Panic in IsExceeded: {:?}", e);
102 true
103 })
104 }
105
106 pub fn GetGlobalDeadline(&self) -> Option<Instant> { self.global_deadline }
107
108 pub fn GetOperationTimeout(&self) -> Duration { self.operation_timeout }
109}