Skip to content

Bug 1822482 - Switch from chrono to time 0.3 #2429

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 41 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion glean-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ zeitstempel = "0.1.0"
crossbeam-channel = "0.5"
thiserror = "1.0.4"
uniffi = { version = "0.23.0", default-features = false }
time = "0.1.40"
env_logger = { version = "0.10.0", default-features = false, optional = true }
time = { version = "0.3.20", features = ["local-offset", "serde", "formatting", "parsing", "macros"] }

[target.'cfg(target_os = "android")'.dependencies]
android_logger = { version = "0.12.0", default-features = false }
Expand Down
5 changes: 3 additions & 2 deletions glean-core/src/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::sync::{Arc, Mutex};

use chrono::{DateTime, FixedOffset};
use once_cell::sync::OnceCell;
use time::OffsetDateTime;

use crate::database::Database;
use crate::debug::DebugOptions;
Expand Down Expand Up @@ -145,7 +146,7 @@ pub struct Glean {
data_path: PathBuf,
application_id: String,
ping_registry: HashMap<String, PingType>,
start_time: DateTime<FixedOffset>,
start_time: OffsetDateTime,
max_events: u32,
is_first_run: bool,
pub(crate) upload_manager: PingUploadManager,
Expand Down Expand Up @@ -656,7 +657,7 @@ impl Glean {
}

/// Get create time of the Glean object.
pub(crate) fn start_time(&self) -> DateTime<FixedOffset> {
pub(crate) fn start_time(&self) -> OffsetDateTime {
self.start_time
}

Expand Down
7 changes: 4 additions & 3 deletions glean-core/src/event_database/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use std::path::{Path, PathBuf};
use std::sync::RwLock;

use chrono::{DateTime, FixedOffset};
use time::OffsetDateTime;

use serde::{Deserialize, Serialize};
use serde_json::{json, Value as JsonValue};
Expand Down Expand Up @@ -357,7 +358,7 @@ impl EventDatabase {
glean: &Glean,
store_name: &str,
store: &mut Vec<StoredEvent>,
glean_start_time: DateTime<FixedOffset>,
glean_start_time: OffsetDateTime,
) {
let is_glean_restarted =
|event: &RecordedEvent| event.category == "glean" && event.name == "restarted";
Expand Down Expand Up @@ -424,7 +425,7 @@ impl EventDatabase {
.as_mut()
.and_then(|extra| {
extra.remove("glean.startup.date").and_then(|date_str| {
DateTime::parse_from_str(&date_str, TimeUnit::Minute.format_pattern())
OffsetDateTime::parse(&date_str, TimeUnit::Minute.format_pattern())
.map_err(|_| {
record_error(
glean,
Expand Down Expand Up @@ -461,7 +462,7 @@ impl EventDatabase {
.get_value(glean, INTERNAL_STORAGE)
.unwrap_or(glean_start_time);
let time_from_ping_start_to_glean_restarted =
(glean_startup_date - ping_start).num_milliseconds();
(glean_startup_date - ping_start).whole_milliseconds();
intra_group_offset = event.event.timestamp;
inter_group_offset =
u64::try_from(time_from_ping_start_to_glean_restarted).unwrap_or(0);
Expand Down
4 changes: 2 additions & 2 deletions glean-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use std::time::{Duration, Instant};

use crossbeam_channel::unbounded;
use once_cell::sync::{Lazy, OnceCell};
Expand Down Expand Up @@ -521,7 +521,7 @@ fn uploader_shutdown() {
// * We don't know how long uploads take until we get data from bug 1814592.
let result = rx.recv_timeout(Duration::from_secs(30));

let stop_time = time::precise_time_ns();
let stop_time = Instant::now();
core::with_glean(|glean| {
glean
.additional_metrics
Expand Down
119 changes: 49 additions & 70 deletions glean-core/src/metrics/datetime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,7 @@ use crate::CommonMetricData;
use crate::Glean;

use chrono::{DateTime, Datelike, FixedOffset, TimeZone, Timelike};

/// A datetime type.
///
/// Used to feed data to the `DatetimeMetric`.
pub type ChronoDatetime = DateTime<FixedOffset>;
use time::{Date, OffsetDateTime, Time, UtcOffset};

/// Representation of a date, time and timezone.
#[derive(Clone, PartialEq, Eq)]
Expand Down Expand Up @@ -94,20 +90,20 @@ impl MetricType for DatetimeMetric {
}
}

impl From<ChronoDatetime> for Datetime {
fn from(dt: ChronoDatetime) -> Self {
impl From<OffsetDateTime> for Datetime {
fn from(dt: OffsetDateTime) -> Self {
let date = dt.date();
let time = dt.time();
let tz = dt.timezone();
let tz = dt.offset();
Self {
year: date.year(),
month: date.month(),
day: date.day(),
hour: time.hour(),
minute: time.minute(),
second: time.second(),
month: date.month() as u32,
day: date.day() as u32,
hour: time.hour() as u32,
minute: time.minute() as u32,
second: time.second() as u32,
nanosecond: time.nanosecond(),
offset_seconds: tz.local_minus_utc(),
offset_seconds: tz.whole_seconds(),
}
}
}
Expand Down Expand Up @@ -149,8 +145,8 @@ impl DatetimeMetric {
let value = match value {
None => local_now_with_offset(),
Some(dt) => {
let timezone_offset = FixedOffset::east_opt(dt.offset_seconds);
if timezone_offset.is_none() {
let timezone_offset = UtcOffset::from_whole_seconds(dt.offset_seconds);
if timezone_offset.is_err() {
let msg = format!(
"Invalid timezone offset {}. Not recording.",
dt.offset_seconds
Expand All @@ -159,30 +155,23 @@ impl DatetimeMetric {
return;
};

let datetime_obj = FixedOffset::east(dt.offset_seconds)
.ymd_opt(dt.year, dt.month, dt.day)
.and_hms_nano_opt(dt.hour, dt.minute, dt.second, dt.nanosecond);
let date = Date::from_calendar_date(dt.year, (dt.month as u8).try_into().unwrap(), dt.day as u8).unwrap();
let time = Time::from_hms_nano(dt.hour as u8, dt.minute as u8, dt.second as u8, dt.nanosecond).unwrap();
let datetime_obj = OffsetDateTime::from_unix_timestamp(0)
.unwrap()
.replace_date(date)
.replace_time(time)
.replace_offset(timezone_offset.unwrap());

if let Some(dt) = datetime_obj.single() {
dt
} else {
record_error(
glean,
&self.meta,
ErrorType::InvalidValue,
"Invalid input data. Not recording.",
None,
);
return;
}
datetime_obj
}
};

self.set_sync_chrono(glean, value);
}

pub(crate) fn set_sync_chrono(&self, glean: &Glean, value: ChronoDatetime) {
let value = Metric::Datetime(value, self.time_unit);
pub(crate) fn set_sync_chrono(&self, glean: &Glean, value: OffsetDateTime) {
let value = Metric::Datetime(value.into(), self.time_unit);
glean.storage().record(glean, &self.meta, &value)
}

Expand All @@ -192,55 +181,45 @@ impl DatetimeMetric {
&self,
glean: &Glean,
ping_name: S,
) -> Option<ChronoDatetime> {
) -> Option<OffsetDateTime> {
let (d, tu) = self.get_value_inner(glean, ping_name.into())?;

// The string version of the test function truncates using string
// parsing. Unfortunately `parse_from_str` errors with `NotEnough` if we
// try to truncate with `get_iso_time_string` and then parse it back
// in a `Datetime`. So we need to truncate manually.
let time = d.time();
match tu {
TimeUnit::Nanosecond => d.date().and_hms_nano_opt(
time.hour(),
time.minute(),
time.second(),
time.nanosecond(),
),
TimeUnit::Microsecond => {
eprintln!(
"microseconds. nanoseconds={}, nanoseconds/1000={}",
time.nanosecond(),
time.nanosecond() / 1000
);
d.date().and_hms_nano_opt(
time.hour(),
time.minute(),
time.second(),
time.nanosecond() / 1000,
)
}
TimeUnit::Millisecond => d.date().and_hms_nano_opt(
time.hour(),
time.minute(),
time.second(),
time.nanosecond() / 1000000,
),
TimeUnit::Second => {
d.date()
.and_hms_nano_opt(time.hour(), time.minute(), time.second(), 0)
}
TimeUnit::Minute => d.date().and_hms_nano_opt(time.hour(), time.minute(), 0, 0),
TimeUnit::Hour => d.date().and_hms_nano_opt(time.hour(), 0, 0, 0),
TimeUnit::Day => d.date().and_hms_nano_opt(0, 0, 0, 0),
}
let dt = match tu {
TimeUnit::Nanosecond => d,
TimeUnit::Microsecond => d.replace_nanosecond(0).unwrap(),
TimeUnit::Millisecond => d.replace_microsecond(0).unwrap(),
TimeUnit::Second => d.replace_millisecond(0).unwrap(),
TimeUnit::Minute => d.replace_millisecond(0).unwrap().replace_second(0).unwrap(),
TimeUnit::Hour => d
.replace_millisecond(0)
.unwrap()
.replace_second(0)
.unwrap()
.replace_minute(0)
.unwrap(),
TimeUnit::Day => d
.replace_millisecond(0)
.unwrap()
.replace_second(0)
.unwrap()
.replace_minute(0)
.unwrap()
.replace_hour(0)
.unwrap(),
};
Some(dt)
}

fn get_value_inner(
&self,
glean: &Glean,
ping_name: Option<&str>,
) -> Option<(ChronoDatetime, TimeUnit)> {
) -> Option<(OffsetDateTime, TimeUnit)> {
let queried_ping_name = ping_name.unwrap_or_else(|| &self.meta().inner.send_in_pings[0]);

match StorageManager.snapshot_metric(
Expand All @@ -249,7 +228,7 @@ impl DatetimeMetric {
&self.meta.identifier(glean),
self.meta.inner.lifetime,
) {
Some(Metric::Datetime(d, tu)) => Some((d, tu)),
Some(Metric::Datetime(d, tu)) => Some((d.inner, tu)),
_ => None,
}
}
Expand Down
Loading