alopex_cli/streaming/
timeout.rs1use std::time::{Duration, Instant};
4
5use crate::error::{CliError, Result};
6
7pub const DEFAULT_DEADLINE: Duration = Duration::from_secs(60);
8
9#[derive(Debug, Clone, Copy)]
10pub struct Deadline {
11 start: Instant,
12 duration: Duration,
13}
14
15impl Deadline {
16 pub fn new(duration: Duration) -> Self {
17 Self {
18 start: Instant::now(),
19 duration,
20 }
21 }
22
23 pub fn remaining(&self) -> Duration {
24 let elapsed = self.start.elapsed();
25 if elapsed >= self.duration {
26 Duration::from_secs(0)
27 } else {
28 self.duration - elapsed
29 }
30 }
31
32 pub fn duration(&self) -> Duration {
33 self.duration
34 }
35
36 pub fn check(&self) -> Result<()> {
37 if self.remaining().is_zero() {
38 return Err(CliError::Timeout(format!(
39 "deadline exceeded after {}",
40 humantime::format_duration(self.duration)
41 )));
42 }
43 Ok(())
44 }
45}
46
47pub fn parse_deadline(value: Option<&str>) -> Result<Duration> {
48 let duration = match value {
49 Some(raw) => humantime::parse_duration(raw)
50 .map_err(|err| CliError::InvalidArgument(format!("Invalid deadline: {err}")))?,
51 None => DEFAULT_DEADLINE,
52 };
53 Ok(duration)
54}