1use std::time::{Duration, SystemTime, UNIX_EPOCH};
6
7use base64::engine::general_purpose::STANDARD;
8use base64::Engine as _;
9use serde::Serialize;
10
11use crate::core::{Error, Result};
12
13pub const DEFAULT_RANGE: Duration = Duration::from_secs(3600);
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize)]
18#[serde(rename_all = "UPPERCASE")]
19pub enum Step {
20 Day,
22 Hour,
24 #[default]
26 Minute,
27 Second,
29}
30
31impl Step {
32 pub fn as_str(self) -> &'static str {
34 match self {
35 Step::Day => "DAY",
36 Step::Hour => "HOUR",
37 Step::Minute => "MINUTE",
38 Step::Second => "SECOND",
39 }
40 }
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
46pub struct TimeRange {
47 pub start: Option<SystemTime>,
49 pub end: Option<SystemTime>,
51 pub step: Option<Step>,
53}
54
55impl TimeRange {
56 pub fn last(window: Duration) -> Self {
58 TimeRange {
59 start: SystemTime::now().checked_sub(window),
60 end: None,
61 step: None,
62 }
63 }
64 pub fn start(mut self, start: SystemTime) -> Self {
66 self.start = Some(start);
67 self
68 }
69 pub fn end(mut self, end: SystemTime) -> Self {
71 self.end = Some(end);
72 self
73 }
74 pub fn step(mut self, step: Step) -> Self {
76 self.step = Some(step);
77 self
78 }
79}
80
81#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
83pub struct GraphQLDuration {
84 pub start: String,
86 pub end: String,
88 pub step: Step,
90}
91
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub struct ResolvedRange {
95 pub start_ms: i64,
97 pub end_ms: i64,
99 pub step: Step,
101}
102
103pub fn epoch_ms(t: SystemTime) -> i64 {
105 match t.duration_since(UNIX_EPOCH) {
106 Ok(d) => d.as_millis() as i64,
107 Err(e) => -(e.duration().as_millis() as i64),
108 }
109}
110
111pub fn from_epoch_ms(ms: i64) -> SystemTime {
113 UNIX_EPOCH + Duration::from_millis(ms.max(0) as u64)
114}
115
116pub fn parse_timezone(tz: &str) -> i32 {
119 let t = tz.trim();
120 let (sign, rest) = match t.chars().next() {
121 Some('+') => (1, &t[1..]),
122 Some('-') => (-1, &t[1..]),
123 _ => return 0,
124 };
125 let digits: String = rest.chars().filter(|c| *c != ':').collect();
126 let colon_ok = rest.len() == 4 || (rest.len() == 5 && rest.as_bytes()[2] == b':');
127 if digits.len() != 4 || !colon_ok || !digits.bytes().all(|b| b.is_ascii_digit()) {
128 return 0;
129 }
130 let hours: i32 = digits[..2].parse().unwrap_or(0);
131 let minutes: i32 = digits[2..].parse().unwrap_or(0);
132 sign * (hours * 60 + minutes)
133}
134
135fn civil_from_days(days: i64) -> (i64, u32, u32) {
137 let z = days + 719_468;
138 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
139 let doe = z - era * 146_097;
140 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
141 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
142 let mp = (5 * doy + 2) / 153;
143 let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
144 let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
145 let y = yoe + era * 400 + i64::from(m <= 2);
146 (y, m, d)
147}
148
149pub fn format_duration_time(epoch_millis: i64, step: Step, offset_minutes: i32) -> String {
152 let secs = (epoch_millis + i64::from(offset_minutes) * 60_000).div_euclid(1000);
153 let days = secs.div_euclid(86_400);
154 let rem = secs.rem_euclid(86_400);
155 let (y, m, d) = civil_from_days(days);
156 let (hh, mm, ss) = (rem / 3600, (rem % 3600) / 60, rem % 60);
157 let day = format!("{y:04}-{m:02}-{d:02}");
158 match step {
159 Step::Day => day,
160 Step::Hour => format!("{day} {hh:02}"),
161 Step::Minute => format!("{day} {hh:02}{mm:02}"),
162 Step::Second => format!("{day} {hh:02}{mm:02}{ss:02}"),
163 }
164}
165
166pub fn resolve_range(range: &TimeRange, now: SystemTime, operation: &str) -> Result<ResolvedRange> {
168 let end_ms = epoch_ms(range.end.unwrap_or(now));
169 let start_ms = range
170 .start
171 .map(epoch_ms)
172 .unwrap_or(end_ms - DEFAULT_RANGE.as_millis() as i64);
173 if start_ms > end_ms {
174 return Err(Error::validation(format!(
175 "{operation}: start must not be after end"
176 )));
177 }
178 Ok(ResolvedRange {
179 start_ms,
180 end_ms,
181 step: range.step.unwrap_or_default(),
182 })
183}
184
185pub fn to_graphql_duration(range: &ResolvedRange, offset_minutes: i32) -> GraphQLDuration {
187 GraphQLDuration {
188 start: format_duration_time(range.start_ms, range.step, offset_minutes),
189 end: format_duration_time(range.end_ms, range.step, offset_minutes),
190 step: range.step,
191 }
192}
193
194fn b64(text: &str) -> String {
195 STANDARD.encode(text.as_bytes())
196}
197
198pub fn service_id(name: &str) -> String {
200 service_id_with(name, true)
201}
202
203pub fn service_id_with(name: &str, normal: bool) -> String {
205 format!("{}.{}", b64(name), u8::from(normal))
206}
207
208pub fn instance_id(service: &str, instance: &str) -> String {
210 format!("{}_{}", service_id(service), b64(instance))
211}
212
213pub fn endpoint_id(service: &str, endpoint: &str) -> String {
215 format!("{}_{}", service_id(service), b64(endpoint))
216}