xudong963 commented on code in PR #27883: URL: https://github.com/apache/datafusion/pull/27883#discussion_r4779010114
########## datafusion/common/src/timezone.rs: ########## @@ -0,0 +1,224 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! UTC offset transitions of timezones, computed once per timezone name. +//! +//! # Public Only for Internal Use: +//! +//! This is not a public API and is for internal use only; see [API policy] for details. +//! +//! [API policy]: https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis + +use std::collections::HashMap; +use std::sync::{Arc, LazyLock, Mutex, PoisonError}; + +use arrow::array::timezone::Tz; +use chrono::{DateTime, Offset, TimeZone}; + +/// 1800-01-01 and 2200-01-01 in epoch seconds; chrono-tz has no transitions +/// outside this window. +const TRANSITION_SCAN_START: i64 = -5_364_662_400; +const TRANSITION_SCAN_END: i64 = 7_258_118_400; +const SECONDS_PER_DAY: i64 = 86_400; + +/// The UTC offsets of a timezone over time: `offsets[i]` holds from +/// `transitions[i - 1]` (inclusive) to `transitions[i]` (exclusive), both in +/// epoch seconds, with the first and last spans unbounded. +/// +/// ``` +/// use datafusion_common::timezone::UtcOffsetSpans; +/// +/// let spans = UtcOffsetSpans::for_timezone("America/New_York").unwrap(); +/// // New York moved from UTC-5 to UTC-4 at 2024-03-10T07:00:00Z. +/// assert_eq!(spans.span(1_710_053_999).offset, -5 * 3600); +/// assert_eq!(spans.span(1_710_054_000).offset, -4 * 3600); +/// assert_eq!(spans.span(1_710_054_000).start, 1_710_054_000); +/// ``` +#[derive(Debug)] +pub struct UtcOffsetSpans { + transitions: Box<[i64]>, + offsets: Box<[i32]>, +} + +/// The epoch seconds `[start, end)` over which a timezone is `offset` seconds +/// ahead of UTC. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct UtcOffsetSpan { + pub start: i64, + pub end: i64, + pub offset: i32, +} + +impl UtcOffsetSpan { + /// Whether `seconds`, in epoch seconds, falls in this span. + pub fn contains(&self, seconds: i64) -> bool { + self.start <= seconds && seconds < self.end + } +} + +impl UtcOffsetSpans { + /// The spans of the timezone named `tz`, or `None` if arrow cannot parse + /// the name. + /// + /// `UTC` and fixed offsets such as `+05:30` have a single span, built on + /// every call. Other zones are scanned for transitions on the first call, + /// which takes milliseconds, and cached for the life of the process, so + /// the cache holds at most one entry per tz database name. + pub fn for_timezone(tz: &str) -> Option<Arc<Self>> { + // Arrow parses a name that starts with `+` or `-` as a fixed offset, + // and no tz database name starts with either. + if tz.eq_ignore_ascii_case("UTC") || tz.starts_with(['+', '-']) { + let offset = offset_at(&tz.parse().ok()?, 0)?; + return Some(Arc::new(Self { + transitions: Box::default(), + offsets: Box::new([offset]), + })); + } + static CACHE: LazyLock<Mutex<HashMap<String, Option<Arc<UtcOffsetSpans>>>>> = + LazyLock::new(Default::default); + let lock = || CACHE.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(spans) = lock().get(tz) { + return spans.clone(); + } + // Scan without holding the lock. A name that fails to parse is not + // cached. + let spans = Self::scan(&tz.parse().ok()?).map(Arc::new); + lock().entry(tz.to_owned()).or_insert(spans).clone() + } + + /// The epoch seconds at which the UTC offset changes, in ascending order. + pub fn transitions(&self) -> &[i64] { + &self.transitions + } + + /// The span that contains `seconds`, in epoch seconds. + pub fn span(&self, seconds: i64) -> UtcOffsetSpan { + let i = self.transitions.partition_point(|&t| t <= seconds); + UtcOffsetSpan { + start: i.checked_sub(1).map_or(i64::MIN, |i| self.transitions[i]), + end: self.transitions.get(i).copied().unwrap_or(i64::MAX), + offset: self.offsets[i], + } + } + + /// Finds every UTC offset transition of `tz` between 1800 and 2200 by + /// stepping a day at a time and bisecting to the second. Steps of a day catch + /// every transition, since tz database transitions are days apart. + fn scan(tz: &Tz) -> Option<Self> { Review Comment: It would be simpler. Once arrow's `Tz` is backed by jiff (apache/arrow-rs#9183), this can become `following()`/`preceding()`. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
