Skip to main content

grow_apache_skywalking/
duration.rs

1// Service code (Apache SkyWalking): GraphQL `Duration` formatting and id derivation.
2//! GraphQL `Duration` windows (times in the OAP timezone, formatted per step) and the derived
3//! SkyWalking ids (`base64(name).1`).
4
5use 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
13/// Default query window: one hour.
14pub const DEFAULT_RANGE: Duration = Duration::from_secs(3600);
15
16/// Granularity of a GraphQL `Duration`.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize)]
18#[serde(rename_all = "UPPERCASE")]
19pub enum Step {
20    /// `yyyy-MM-dd`.
21    Day,
22    /// `yyyy-MM-dd HH`.
23    Hour,
24    /// `yyyy-MM-dd HHmm` (default).
25    #[default]
26    Minute,
27    /// `yyyy-MM-dd HHmmss`.
28    Second,
29}
30
31impl Step {
32    /// Wire value: `DAY`, `HOUR`, `MINUTE` or `SECOND`.
33    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/// Time window of a metadata/trace/log query. Defaults: `end` = now, `start` = `end` - 1 h,
44/// `step` = `MINUTE`.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
46pub struct TimeRange {
47    /// Window start (default `end` - 1 h).
48    pub start: Option<SystemTime>,
49    /// Window end (default now).
50    pub end: Option<SystemTime>,
51    /// Granularity (default `MINUTE`).
52    pub step: Option<Step>,
53}
54
55impl TimeRange {
56    /// The last `window` up to now.
57    pub fn last(window: Duration) -> Self {
58        TimeRange {
59            start: SystemTime::now().checked_sub(window),
60            end: None,
61            step: None,
62        }
63    }
64    /// Sets the start.
65    pub fn start(mut self, start: SystemTime) -> Self {
66        self.start = Some(start);
67        self
68    }
69    /// Sets the end.
70    pub fn end(mut self, end: SystemTime) -> Self {
71        self.end = Some(end);
72        self
73    }
74    /// Sets the step.
75    pub fn step(mut self, step: Step) -> Self {
76        self.step = Some(step);
77        self
78    }
79}
80
81/// The GraphQL `Duration` input (times in the OAP timezone, formatted per step).
82#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
83pub struct GraphQLDuration {
84    /// Formatted start.
85    pub start: String,
86    /// Formatted end.
87    pub end: String,
88    /// Step.
89    pub step: Step,
90}
91
92/// A window resolved to epoch milliseconds.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub struct ResolvedRange {
95    /// Start, epoch ms.
96    pub start_ms: i64,
97    /// End, epoch ms.
98    pub end_ms: i64,
99    /// Step.
100    pub step: Step,
101}
102
103/// Epoch milliseconds of a time (negative before 1970).
104pub 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
111/// The time at an epoch millisecond (clamped at 1970).
112pub fn from_epoch_ms(ms: i64) -> SystemTime {
113    UNIX_EPOCH + Duration::from_millis(ms.max(0) as u64)
114}
115
116/// Parses an OAP timezone (`getTimeInfo.timezone`, e.g. `+0000`, `-0530`, `+08:00`) into
117/// minutes east of UTC. Unknown text → 0.
118pub 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
135/// Civil date from days since 1970-01-01 (proleptic Gregorian).
136fn 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
149/// Formats an epoch-ms time for a `Duration` field in a timezone `offset_minutes` east of UTC:
150/// `DAY yyyy-MM-dd`, `HOUR yyyy-MM-dd HH`, `MINUTE yyyy-MM-dd HHmm`, `SECOND yyyy-MM-dd HHmmss`.
151pub 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
166/// Applies the [`TimeRange`] defaults; `VALIDATION` when `start` is after `end`.
167pub 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
185/// Builds the GraphQL `Duration` for a resolved window.
186pub 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
198/// SkyWalking service id of a real (normal) service: `base64(name) + ".1"`.
199pub fn service_id(name: &str) -> String {
200    service_id_with(name, true)
201}
202
203/// Service id: `base64(name) + ".1"` when `normal`, `".0"` for a virtual service.
204pub fn service_id_with(name: &str, normal: bool) -> String {
205    format!("{}.{}", b64(name), u8::from(normal))
206}
207
208/// Service instance id: `serviceId + "_" + base64(instanceName)`.
209pub fn instance_id(service: &str, instance: &str) -> String {
210    format!("{}_{}", service_id(service), b64(instance))
211}
212
213/// Endpoint id: `serviceId + "_" + base64(endpointName)`.
214pub fn endpoint_id(service: &str, endpoint: &str) -> String {
215    format!("{}_{}", service_id(service), b64(endpoint))
216}