Skip to main content

promql/
map_time.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! `time()` and the date functions over evaluated series, following Prometheus `funcTime` and
16//! `dateWrapper`.
17
18use datafusion::arrow::array::Float64Array;
19use datafusion::error::{DataFusionError, Result};
20use datatypes::series::SeriesLabels;
21use datatypes::series::samples::{Samples, Series, SeriesFields, SeriesSchema};
22use datatypes::series::time::{GridRange, TimeAxis};
23
24use crate::grid_series::external;
25
26#[cfg(test)]
27mod tests;
28
29/// A PromQL date function: `minute(v)`, `year()` and so on.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)]
31pub enum DateFunction {
32    DayOfMonth,
33    DayOfWeek,
34    DayOfYear,
35    DaysInMonth,
36    Hour,
37    Minute,
38    Month,
39    Year,
40}
41
42/// `start()`, `end()`, `range()` and `step()`: constants of a query, which Prometheus folds into
43/// number literals before evaluating it.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum QueryContextFunction {
46    Start,
47    End,
48    Range,
49    Step,
50}
51
52impl QueryContextFunction {
53    /// The value for a query from `start_ms` to `end_ms` every `step_ms`. `step()` is 0 when the
54    /// start and end are equal, as for an instant query.
55    pub fn value(self, start_ms: i64, end_ms: i64, step_ms: i64) -> f64 {
56        match self {
57            Self::Start => start_ms as f64 / 1000.0,
58            Self::End => end_ms as f64 / 1000.0,
59            Self::Range => duration_seconds(end_ms.saturating_sub(start_ms)),
60            Self::Step if start_ms == end_ms => 0.0,
61            Self::Step => duration_seconds(step_ms),
62        }
63    }
64}
65
66/// Go's `time.Duration.Seconds` of `ms` milliseconds: whole seconds plus the remainder over 1e9,
67/// two roundings rather than one division. The nanosecond count saturates as `time.Time.Sub` does.
68fn duration_seconds(ms: i64) -> f64 {
69    let nanos = ms.saturating_mul(1_000_000);
70    (nanos / 1_000_000_000) as f64 + (nanos % 1_000_000_000) as f64 / 1e9
71}
72
73/// `time()`: the evaluation time in seconds at every point of the schema's grid, unlabelled.
74pub fn time(schema: &SeriesSchema) -> Result<Series> {
75    eval_time_series(schema, |ms| ms as f64 / 1000.0)
76}
77
78/// A date function without argument, which reads the evaluation time: one unlabelled series
79/// over the whole grid.
80pub fn date_of_eval_time(function: DateFunction, schema: &SeriesSchema) -> Result<Series> {
81    // Prometheus truncates the timestamp to whole seconds towards zero.
82    eval_time_series(schema, |ms| function.apply(ms / 1000))
83}
84
85fn eval_time_series(schema: &SeriesSchema, value: impl Fn(i64) -> f64) -> Result<Series> {
86    let grid = schema.eval_grid.clone().ok_or_else(|| {
87        DataFusionError::Execution("time functions require an evaluation grid".into())
88    })?;
89    let values: Float64Array = grid
90        .timestamps()
91        .map_err(external)?
92        .iter()
93        .map(|&ms| value(ms))
94        .collect();
95    let range = GridRange::try_new(grid.clone(), 0, values.len()).map_err(external)?;
96    let fields = vec![Samples::from_float(values); schema.fields.len()];
97    Series::try_new(
98        schema,
99        SeriesLabels::try_new(None, Vec::new()).map_err(external)?,
100        TimeAxis::Grid(range),
101        SeriesFields::try_from_vec(fields).map_err(external)?,
102    )
103    .map_err(external)
104}
105
106/// Go's `int64(f)` on amd64: NaN and values out of range become `i64::MIN`.
107fn go_int64(value: f64) -> i64 {
108    if (-9_223_372_036_854_775_808.0..9_223_372_036_854_775_808.0).contains(&value) {
109        value as i64
110    } else {
111        i64::MIN
112    }
113}
114
115const SECONDS_PER_DAY: u64 = 86_400;
116const MARCH_THRU_DECEMBER: u32 = 306;
117const ABSOLUTE_YEARS: u64 = 292_277_022_400;
118/// Go's `unixToInternal + internalToAbsolute`.
119const UNIX_TO_ABSOLUTE: i64 = (1969 * 365 + 1969 / 4 - 1969 / 100 + 1969 / 400) * 86_400
120    + (ABSOLUTE_YEARS as i64 / 400 * 146_097 + MARCH_THRU_DECEMBER as i64) * 86_400;
121
122impl DateFunction {
123    /// The PromQL name of the function.
124    pub(crate) fn name(self) -> &'static str {
125        match self {
126            Self::DayOfMonth => "day_of_month",
127            Self::DayOfWeek => "day_of_week",
128            Self::DayOfYear => "day_of_year",
129            Self::DaysInMonth => "days_in_month",
130            Self::Hour => "hour",
131            Self::Minute => "minute",
132            Self::Month => "month",
133            Self::Year => "year",
134        }
135    }
136
137    /// The component of `seconds` read as a Unix time, as Prometheus truncates it with `int64`.
138    pub(crate) fn of_seconds(self, seconds: f64) -> f64 {
139        self.apply(go_int64(seconds))
140    }
141
142    /// The component of Unix second `seconds` in UTC, computed the way Go's `time` package does,
143    /// including its wrapping arithmetic for instants out of its range.
144    fn apply(self, seconds: i64) -> f64 {
145        let abs = seconds.wrapping_add(UNIX_TO_ABSOLUTE) as u64;
146        let days = abs / SECONDS_PER_DAY;
147        let value = match self {
148            Self::Hour => (abs % SECONDS_PER_DAY / 3600) as i64,
149            Self::Minute => (abs % 3600 / 60) as i64,
150            Self::DayOfWeek => ((days + 3) % 7) as i64,
151            Self::Year => civil(days).year,
152            Self::Month => civil(days).month as i64,
153            Self::DayOfMonth => civil(days).day as i64,
154            Self::DayOfYear => civil(days).year_day,
155            Self::DaysInMonth => {
156                let Civil { year, month, .. } = civil(days);
157                let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
158                match month {
159                    2 if leap => 29,
160                    2 => 28,
161                    4 | 6 | 9 | 11 => 30,
162                    _ => 31,
163                }
164            }
165        };
166        value as f64
167    }
168}
169
170struct Civil {
171    year: i64,
172    month: u32,
173    day: u32,
174    year_day: i64,
175}
176
177/// Go's `absDays.split`, `date` and `yearYday`: days since March 1 of year `-ABSOLUTE_YEARS`.
178fn civil(days: u64) -> Civil {
179    let d = days.wrapping_mul(4).wrapping_add(3);
180    let century = d / 146_097;
181    let cd = (d % 146_097) as u32 | 3;
182    let product = 2_939_745u64 * cd as u64;
183    let cyear = (product >> 32) as u32;
184    let ayday = product as u32 / 2_939_745 / 4;
185
186    let m = 2141 * ayday + 197_913;
187    let jan_feb = u32::from(ayday >= MARCH_THRU_DECEMBER);
188    let leap = cyear.is_multiple_of(4) && (cyear != 0 || century.is_multiple_of(4));
189    Civil {
190        year: century.wrapping_mul(100).wrapping_sub(ABSOLUTE_YEARS) as i64
191            + cyear as i64
192            + jan_feb as i64,
193        month: (m >> 16) - jan_feb * 12,
194        day: 1 + (m & 0xFFFF) / 2141,
195        year_day: ayday as i64 + (1 + 31 + 28) + i64::from(leap && jan_feb == 0)
196            - 365 * jan_feb as i64,
197    }
198}