Skip to main content

common_time/
timezone.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
15use std::fmt::Display;
16
17use chrono::{FixedOffset, TimeZone};
18use chrono_tz::{OffsetComponents, Tz};
19use once_cell::sync::OnceCell;
20use snafu::{OptionExt, ResultExt};
21
22use crate::error::{
23    InvalidTimezoneOffsetSnafu, ParseOffsetStrSnafu, ParseTimezoneNameSnafu, Result,
24};
25use crate::util::find_tz_from_env;
26
27/// System timezone in `frontend`/`standalone`,
28/// config by option `default_timezone` in toml,
29/// default value is `UTC` when `default_timezone` is not set.
30static DEFAULT_TIMEZONE: OnceCell<Timezone> = OnceCell::new();
31
32// Set the System timezone by `tz_str`
33pub fn set_default_timezone(tz_str: Option<&str>) -> Result<()> {
34    let tz = match tz_str {
35        None | Some("") => Timezone::Named(Tz::UTC),
36        Some(tz) => Timezone::from_tz_string(tz)?,
37    };
38    DEFAULT_TIMEZONE.get_or_init(|| tz);
39    Ok(())
40}
41
42#[inline(always)]
43/// If the `tz=Some(timezone)`, return `timezone` directly,
44/// or return current system timezone.
45pub fn get_timezone(tz: Option<&Timezone>) -> &Timezone {
46    tz.unwrap_or_else(|| DEFAULT_TIMEZONE.get().unwrap_or(&Timezone::Named(Tz::UTC)))
47}
48
49#[inline(always)]
50/// If the `tz = Some("") || None || Some(Invalid timezone)`, return system timezone,
51/// or return parsed `tz` as timezone.
52pub fn parse_timezone(tz: Option<&str>) -> Timezone {
53    match tz {
54        None | Some("") => Timezone::Named(Tz::UTC),
55        Some(tz) => Timezone::from_tz_string(tz).unwrap_or(Timezone::Named(Tz::UTC)),
56    }
57}
58
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum Timezone {
61    Offset(FixedOffset),
62    Named(Tz),
63}
64
65impl Timezone {
66    /// Compute timezone from given offset hours and minutes
67    /// Return `Err` if given offset exceeds scope
68    pub fn hours_mins_opt(offset_hours: i32, offset_mins: u32) -> Result<Self> {
69        Self::hours_mins_with_sign(offset_hours, offset_mins, offset_hours < 0)
70    }
71
72    fn hours_mins_with_sign(offset_hours: i32, offset_mins: u32, negative: bool) -> Result<Self> {
73        let minutes = i64::from(offset_mins) * 60;
74        let seconds = i64::from(offset_hours) * 3600 + if negative { -minutes } else { minutes };
75        i32::try_from(seconds)
76            .ok()
77            .filter(|_| offset_mins < 60)
78            .and_then(FixedOffset::east_opt)
79            .map(Self::Offset)
80            .context(InvalidTimezoneOffsetSnafu {
81                hours: offset_hours,
82                minutes: offset_mins,
83            })
84    }
85
86    /// Parse timezone offset string and return None if given offset exceeds
87    /// scope.
88    ///
89    /// String examples are available as described in
90    /// <https://dev.mysql.com/doc/refman/8.0/en/time-zone-support.html>
91    ///
92    /// - `SYSTEM`
93    /// - Offset to UTC: `+08:00` , `-11:30`
94    /// - Named zones: `Asia/Shanghai`, `Europe/Berlin`
95    pub fn from_tz_string(tz_string: &str) -> Result<Self> {
96        // Use system timezone
97        if tz_string.eq_ignore_ascii_case("SYSTEM") {
98            Ok(Timezone::Named(find_tz_from_env().unwrap_or(Tz::UTC)))
99        } else if let Some((hrs, mins)) = tz_string.split_once(':') {
100            let negative = hrs.starts_with('-');
101            let hrs = hrs
102                .parse::<i32>()
103                .context(ParseOffsetStrSnafu { raw: tz_string })?;
104            let mins = mins
105                .parse::<u32>()
106                .context(ParseOffsetStrSnafu { raw: tz_string })?;
107            Self::hours_mins_with_sign(hrs, mins, negative)
108        } else if let Ok(tz) = Tz::from_str_insensitive(tz_string) {
109            Ok(Self::Named(tz))
110        } else {
111            ParseTimezoneNameSnafu { raw: tz_string }.fail()
112        }
113    }
114
115    /// A named zone merely sitting at +00:00 today is not UTC: it may have been
116    /// elsewhere at the timestamp being converted.
117    pub fn is_utc(&self) -> bool {
118        match self {
119            Self::Offset(offset) => offset.local_minus_utc() == 0,
120            Self::Named(tz) => matches!(tz, Tz::UTC),
121        }
122    }
123
124    /// Returns the number of seconds to add to convert from UTC to the local time.
125    pub fn local_minus_utc(&self) -> i64 {
126        match self {
127            Self::Offset(offset) => offset.local_minus_utc().into(),
128            Self::Named(tz) => {
129                let datetime = chrono::DateTime::from_timestamp(0, 0)
130                    .map(|x| x.naive_utc())
131                    .expect("invalid timestamp");
132                let datetime = tz.from_utc_datetime(&datetime);
133                let utc_offset = datetime.offset().base_utc_offset();
134                let dst_offset = datetime.offset().dst_offset();
135                let total_offset = utc_offset + dst_offset;
136                total_offset.num_seconds()
137            }
138        }
139    }
140}
141
142impl Display for Timezone {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        match self {
145            Self::Named(tz) => write!(f, "{}", tz.name()),
146            Self::Offset(offset) => write!(f, "{}", offset),
147        }
148    }
149}
150
151#[inline]
152/// Return current system config timezone, default config is UTC
153pub fn system_timezone_name() -> String {
154    format!("{}", get_timezone(None))
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    #[test]
162    fn test_local_minus_utc() {
163        assert_eq!(
164            28800,
165            Timezone::from_tz_string("+8:00").unwrap().local_minus_utc()
166        );
167        assert_eq!(
168            28800,
169            Timezone::from_tz_string("Asia/Shanghai")
170                .unwrap()
171                .local_minus_utc()
172        );
173        assert_eq!(
174            -14400,
175            Timezone::from_tz_string("America/Aruba")
176                .unwrap()
177                .local_minus_utc()
178        );
179
180        assert_eq!(
181            -36000,
182            Timezone::from_tz_string("HST").unwrap().local_minus_utc()
183        );
184    }
185
186    #[test]
187    fn test_from_tz_string() {
188        unsafe {
189            std::env::remove_var("TZ");
190        }
191        assert_eq!(
192            Timezone::Named(Tz::UTC),
193            Timezone::from_tz_string("SYSTEM").unwrap()
194        );
195
196        let utc_plus_8 = Timezone::Offset(FixedOffset::east_opt(3600 * 8).unwrap());
197        assert_eq!(utc_plus_8, Timezone::from_tz_string("+8:00").unwrap());
198        assert_eq!(utc_plus_8, Timezone::from_tz_string("+08:00").unwrap());
199        assert_eq!(utc_plus_8, Timezone::from_tz_string("08:00").unwrap());
200
201        let utc_minus_8 = Timezone::Offset(FixedOffset::west_opt(3600 * 8).unwrap());
202        assert_eq!(utc_minus_8, Timezone::from_tz_string("-08:00").unwrap());
203        assert_eq!(utc_minus_8, Timezone::from_tz_string("-8:00").unwrap());
204
205        let utc_minus_8_5 = Timezone::Offset(FixedOffset::west_opt(3600 * 8 + 60 * 30).unwrap());
206        assert_eq!(utc_minus_8_5, Timezone::from_tz_string("-8:30").unwrap());
207
208        let utc_plus_max = Timezone::Offset(FixedOffset::east_opt(3600 * 14).unwrap());
209        assert_eq!(utc_plus_max, Timezone::from_tz_string("14:00").unwrap());
210
211        let utc_minus_max = Timezone::Offset(FixedOffset::west_opt(3600 * 13 + 60 * 59).unwrap());
212        assert_eq!(utc_minus_max, Timezone::from_tz_string("-13:59").unwrap());
213
214        assert_eq!(
215            Timezone::Named(Tz::Asia__Shanghai),
216            Timezone::from_tz_string("Asia/Shanghai").unwrap()
217        );
218        assert_eq!(
219            Timezone::Named(Tz::Asia__Shanghai),
220            Timezone::from_tz_string("Asia/ShangHai").unwrap()
221        );
222        assert_eq!(
223            Timezone::Named(Tz::UTC),
224            Timezone::from_tz_string("UTC").unwrap()
225        );
226
227        assert!(Timezone::from_tz_string("WORLD_PEACE").is_err());
228        assert!(Timezone::from_tz_string("A0:01").is_err());
229        assert!(Timezone::from_tz_string("20:0A").is_err());
230        assert!(Timezone::from_tz_string(":::::").is_err());
231        assert!(Timezone::from_tz_string("Asia/London").is_err());
232        assert!(Timezone::from_tz_string("Unknown").is_err());
233    }
234
235    #[test]
236    fn test_zero_hour_offsets_and_invalid_values() {
237        for input in ["+00:30", "00:30", "+0:30", "0:30"] {
238            assert_eq!(
239                1800,
240                Timezone::from_tz_string(input).unwrap().local_minus_utc()
241            );
242        }
243        for input in ["-00:30", "-0:30"] {
244            assert_eq!(
245                -1800,
246                Timezone::from_tz_string(input).unwrap().local_minus_utc()
247            );
248        }
249        assert_eq!(
250            1800,
251            Timezone::hours_mins_opt(0, 30).unwrap().local_minus_utc()
252        );
253        assert_eq!(
254            86340,
255            Timezone::from_tz_string("23:59").unwrap().local_minus_utc()
256        );
257        assert_eq!(
258            -86340,
259            Timezone::from_tz_string("-23:59")
260                .unwrap()
261                .local_minus_utc()
262        );
263        for input in [
264            "1:60",
265            "-0:60",
266            "24:00",
267            "-24:00",
268            "2147483647:00",
269            "-2147483648:00",
270            "0:4294967295",
271        ] {
272            assert!(Timezone::from_tz_string(input).is_err(), "{input}");
273        }
274        assert!(Timezone::hours_mins_opt(i32::MIN, 0).is_err());
275        assert!(Timezone::hours_mins_opt(i32::MAX, 0).is_err());
276        assert!(Timezone::hours_mins_opt(0, u32::MAX).is_err());
277    }
278
279    #[test]
280    fn test_timezone_to_string() {
281        assert_eq!("UTC", Timezone::Named(Tz::UTC).to_string());
282        assert_eq!(
283            "+01:00",
284            Timezone::from_tz_string("01:00").unwrap().to_string()
285        );
286        assert_eq!(
287            "Asia/Shanghai",
288            Timezone::from_tz_string("Asia/Shanghai")
289                .unwrap()
290                .to_string()
291        );
292    }
293}