1use std::sync::Arc;
27use std::sync::atomic::{AtomicU64, Ordering};
28use std::time::Duration;
29
30use crate::error::{GraphError, Result};
31use crate::node::{Node, NodeContext, NodeOutput};
32
33#[derive(Debug, Clone, Default)]
35pub enum OnTimeout {
36 #[default]
38 Fail,
39 Retry { max_attempts: usize },
41 Skip,
43}
44
45#[derive(Debug, Clone, Default)]
60pub struct TimeoutPolicy {
61 pub run_timeout: Option<Duration>,
63 pub idle_timeout: Option<Duration>,
65 pub on_timeout: OnTimeout,
67}
68
69#[derive(Debug, Clone)]
75pub struct ProgressHandle {
76 last_progress_ms: Arc<AtomicU64>,
77}
78
79impl ProgressHandle {
80 pub fn new() -> Self {
82 let now_ms = current_time_ms();
83 Self { last_progress_ms: Arc::new(AtomicU64::new(now_ms)) }
84 }
85
86 pub fn report_progress(&self) {
88 let now_ms = current_time_ms();
89 self.last_progress_ms.store(now_ms, Ordering::Release);
90 }
91
92 pub(crate) fn last_progress_ms(&self) -> u64 {
94 self.last_progress_ms.load(Ordering::Acquire)
95 }
96}
97
98impl Default for ProgressHandle {
99 fn default() -> Self {
100 Self::new()
101 }
102}
103
104pub async fn execute_with_timeout(
136 node: &dyn Node,
137 ctx: &NodeContext,
138 policy: &TimeoutPolicy,
139) -> Result<NodeOutput> {
140 if policy.run_timeout.is_none() && policy.idle_timeout.is_none() {
142 return node.execute(ctx).await;
143 }
144
145 let mut attempts = 0;
146
147 loop {
148 attempts += 1;
149 crate::executor::begin_attempt(ctx);
150 let result = execute_once_with_timeout(node, ctx, policy).await;
151
152 match result {
153 Ok(output) => return Ok(output),
154 Err(GraphError::NodeTimedOut { ref node, ref elapsed }) => {
155 match &policy.on_timeout {
156 OnTimeout::Fail => {
157 tracing::warn!(
158 node = %node,
159 elapsed_ms = elapsed.as_millis(),
160 action = "fail",
161 "node timed out, failing execution"
162 );
163 return result;
164 }
165 OnTimeout::Retry { max_attempts } => {
166 if attempts >= *max_attempts {
167 tracing::warn!(
168 node = %node,
169 elapsed_ms = elapsed.as_millis(),
170 attempts = attempts,
171 action = "fail_after_retries",
172 "node timed out after all retry attempts exhausted"
173 );
174 return result;
175 }
176 tracing::warn!(
177 node = %node,
178 elapsed_ms = elapsed.as_millis(),
179 attempt = attempts,
180 max_attempts = *max_attempts,
181 action = "retry",
182 "node timed out, retrying"
183 );
184 }
186 OnTimeout::Skip => {
187 tracing::warn!(
188 node = %node,
189 elapsed_ms = elapsed.as_millis(),
190 action = "skip",
191 "node timed out, skipping with empty output"
192 );
193 return Ok(NodeOutput::new());
194 }
195 }
196 }
197 Err(other) => return Err(other),
198 }
199 }
200}
201
202async fn execute_once_with_timeout(
204 node: &dyn Node,
205 ctx: &NodeContext,
206 policy: &TimeoutPolicy,
207) -> Result<NodeOutput> {
208 let node_name = node.name().to_string();
209 let progress_handle = ProgressHandle::new();
210
211 let mut timeout_ctx = ctx.clone();
215 timeout_ctx.set_progress_handle(progress_handle.clone());
216
217 tokio::select! {
218 result = node.execute(&timeout_ctx) => {
219 result
220 }
221 elapsed = wait_for_run_timeout(policy.run_timeout) => {
222 Err(GraphError::NodeTimedOut {
223 node: node_name,
224 elapsed,
225 })
226 }
227 elapsed = wait_for_idle_timeout(policy.idle_timeout, &progress_handle) => {
228 Err(GraphError::NodeTimedOut {
229 node: node_name,
230 elapsed,
231 })
232 }
233 }
234}
235
236async fn wait_for_run_timeout(run_timeout: Option<Duration>) -> Duration {
239 match run_timeout {
240 Some(duration) => {
241 tokio::time::sleep(duration).await;
242 duration
243 }
244 None => {
245 std::future::pending::<()>().await;
247 unreachable!()
248 }
249 }
250}
251
252async fn wait_for_idle_timeout(
256 idle_timeout: Option<Duration>,
257 progress_handle: &ProgressHandle,
258) -> Duration {
259 match idle_timeout {
260 Some(idle_duration) => {
261 let start_ms = current_time_ms();
262 let idle_ms = idle_duration.as_millis() as u64;
263 let poll_interval = Duration::from_millis(100);
264
265 loop {
266 tokio::time::sleep(poll_interval).await;
267 let now_ms = current_time_ms();
268 let last_progress = progress_handle.last_progress_ms();
269 let idle_elapsed = now_ms.saturating_sub(last_progress);
270
271 if idle_elapsed >= idle_ms {
272 let total_elapsed_ms = now_ms.saturating_sub(start_ms);
273 return Duration::from_millis(total_elapsed_ms);
274 }
275 }
276 }
277 None => {
278 std::future::pending::<()>().await;
280 unreachable!()
281 }
282 }
283}
284
285fn current_time_ms() -> u64 {
287 std::time::SystemTime::now()
288 .duration_since(std::time::UNIX_EPOCH)
289 .unwrap_or_default()
290 .as_millis() as u64
291}
292
293pub fn item_timeout_budget(policy: &TimeoutPolicy, elapsed: Duration) -> Option<Duration> {
300 let remaining_run = policy.run_timeout.map(|limit| limit.saturating_sub(elapsed));
301 match (remaining_run, policy.idle_timeout) {
302 (Some(run), Some(idle)) => Some(run.min(idle)),
303 (Some(run), None) => Some(run),
304 (None, Some(idle)) => Some(idle),
305 (None, None) => None,
306 }
307}
308
309#[cfg(test)]
310mod tests {
311 use super::*;
312 use crate::node::{ExecutionConfig, FunctionNode, NodeContext, NodeOutput};
313 use crate::state::State;
314
315 #[tokio::test]
316 async fn test_no_timeout_executes_normally() {
317 let node = FunctionNode::new("fast", |_ctx| async {
318 Ok(NodeOutput::new().with_update("done", serde_json::json!(true)))
319 });
320
321 let ctx = NodeContext::new(State::new(), ExecutionConfig::default(), 0);
322 let policy = TimeoutPolicy::default();
323
324 let result = execute_with_timeout(&node, &ctx, &policy).await;
325 assert!(result.is_ok());
326 let output = result.unwrap();
327 assert_eq!(output.updates.get("done"), Some(&serde_json::json!(true)));
328 }
329
330 #[tokio::test]
331 async fn test_run_timeout_fires_on_slow_node() {
332 let node = FunctionNode::new("slow", |_ctx| async {
333 tokio::time::sleep(Duration::from_secs(10)).await;
334 Ok(NodeOutput::new())
335 });
336
337 let ctx = NodeContext::new(State::new(), ExecutionConfig::default(), 0);
338 let policy = TimeoutPolicy {
339 run_timeout: Some(Duration::from_millis(100)),
340 idle_timeout: None,
341 on_timeout: OnTimeout::Fail,
342 };
343
344 let result = execute_with_timeout(&node, &ctx, &policy).await;
345 assert!(result.is_err());
346 match result {
347 Err(GraphError::NodeTimedOut { node, .. }) => {
348 assert_eq!(node, "slow");
349 }
350 Err(other) => panic!("expected NodeTimedOut, got: {other:?}"),
351 Ok(_) => panic!("expected error, got Ok"),
352 }
353 }
354
355 #[tokio::test]
356 async fn test_skip_returns_empty_output() {
357 let node = FunctionNode::new("slow", |_ctx| async {
358 tokio::time::sleep(Duration::from_secs(10)).await;
359 Ok(NodeOutput::new().with_update("should_not_appear", serde_json::json!(true)))
360 });
361
362 let ctx = NodeContext::new(State::new(), ExecutionConfig::default(), 0);
363 let policy = TimeoutPolicy {
364 run_timeout: Some(Duration::from_millis(50)),
365 idle_timeout: None,
366 on_timeout: OnTimeout::Skip,
367 };
368
369 let result = execute_with_timeout(&node, &ctx, &policy).await;
370 assert!(result.is_ok());
371 let output = result.unwrap();
372 assert!(output.updates.is_empty());
373 }
374
375 #[tokio::test]
376 async fn test_retry_retries_up_to_max_attempts() {
377 use std::sync::atomic::AtomicUsize;
378
379 let attempt_count = Arc::new(AtomicUsize::new(0));
380 let count_clone = attempt_count.clone();
381
382 let node = FunctionNode::new("flaky", move |_ctx| {
383 let count = count_clone.clone();
384 async move {
385 count.fetch_add(1, Ordering::SeqCst);
386 tokio::time::sleep(Duration::from_secs(10)).await;
387 Ok(NodeOutput::new())
388 }
389 });
390
391 let ctx = NodeContext::new(State::new(), ExecutionConfig::default(), 0);
392 let policy = TimeoutPolicy {
393 run_timeout: Some(Duration::from_millis(50)),
394 idle_timeout: None,
395 on_timeout: OnTimeout::Retry { max_attempts: 3 },
396 };
397
398 let result = execute_with_timeout(&node, &ctx, &policy).await;
399 assert!(result.is_err());
400 assert_eq!(attempt_count.load(Ordering::SeqCst), 3);
401 }
402
403 #[tokio::test]
404 async fn test_fast_node_with_timeout_succeeds() {
405 let node = FunctionNode::new("fast", |_ctx| async {
406 Ok(NodeOutput::new().with_update("value", serde_json::json!(42)))
407 });
408
409 let ctx = NodeContext::new(State::new(), ExecutionConfig::default(), 0);
410 let policy = TimeoutPolicy {
411 run_timeout: Some(Duration::from_secs(5)),
412 idle_timeout: None,
413 on_timeout: OnTimeout::Fail,
414 };
415
416 let result = execute_with_timeout(&node, &ctx, &policy).await;
417 assert!(result.is_ok());
418 let output = result.unwrap();
419 assert_eq!(output.updates.get("value"), Some(&serde_json::json!(42)));
420 }
421
422 #[test]
423 fn test_progress_handle_updates_timestamp() {
424 let handle = ProgressHandle::new();
425 let initial = handle.last_progress_ms();
426
427 std::thread::sleep(Duration::from_millis(10));
429 handle.report_progress();
430
431 let updated = handle.last_progress_ms();
432 assert!(updated >= initial);
433 }
434}