#[cfg(test)]
pub mod test;
#[cfg(test)]
mod test_find_or_infer;
use std::{borrow::Cow, fmt};
use jiff::tz::{self, TimeZone};
use tracing::{debug, instrument};
use crate::{
Verdict, cdr, country, from_warning_all, json,
schema::{self, FromSchema as _, HasElement as _},
warning,
};
#[derive(Debug)]
pub enum Warning {
CantInferTimezoneFromCountry(&'static str),
ContainsEscapeCodes,
Country(country::Warning),
Decode(json::decode::Warning),
InvalidTimezone,
LocationCountryShouldBeAlpha3,
MiscasedTimezone,
NoLocationCountry,
NoLocation,
V221CdrHasLocationField,
}
from_warning_all!(
country::Warning => Warning::Country,
json::decode::Warning => Warning::Decode
);
impl fmt::Display for Warning {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::CantInferTimezoneFromCountry(country_code) => write!(f, "Unable to infer timezone from the `location`'s `country`: `{country_code}`"),
Self::ContainsEscapeCodes => f.write_str("The CDR location contains needless escape codes."),
Self::Country(kind) => fmt::Display::fmt(kind, f),
Self::Decode(warning) => fmt::Display::fmt(warning, f),
Self::InvalidTimezone => f.write_str("The CDR location did not contain a valid IANA time-zone."),
Self::LocationCountryShouldBeAlpha3 => f.write_str("The `location.country` field should be an alpha-3 country code."),
Self::MiscasedTimezone => f.write_str("The CDR location's time-zone differs in letter case from the IANA name."),
Self::NoLocationCountry => {
f.write_str("The CDR's `location` has no `country` element and so the timezone can't be inferred.")
},
Self::NoLocation => {
f.write_str("The CDR has no `location` element and so the timezone can't be found or inferred.")
}
Self::V221CdrHasLocationField => f.write_str("the v2.2.1 CDR contains a `location` field but the v2.2.1 spec defines a `cdr_location` field."),
}
}
}
impl crate::Warning for Warning {
fn id(&self) -> warning::Id {
match self {
Self::CantInferTimezoneFromCountry(_) => {
warning::Id::from_static("cant_infer_timezone_from_country")
}
Self::ContainsEscapeCodes => warning::Id::from_static("contains_escape_codes"),
Self::Decode(warning) => warning.id(),
Self::Country(warning) => warning.id(),
Self::InvalidTimezone => warning::Id::from_static("invalid_timezone"),
Self::LocationCountryShouldBeAlpha3 => {
warning::Id::from_static("location_country_should_be_alpha3")
}
Self::MiscasedTimezone => warning::Id::from_static("miscased_timezone"),
Self::NoLocationCountry => warning::Id::from_static("no_location_country"),
Self::NoLocation => warning::Id::from_static("no_location"),
Self::V221CdrHasLocationField => {
warning::Id::from_static("v221_cdr_has_location_field")
}
}
}
}
#[derive(Clone, Debug)]
pub enum Source {
Found(TimeZone),
Inferred(TimeZone),
}
impl Source {
pub fn into_timezone(self) -> TimeZone {
match self {
Source::Found(tz) | Source::Inferred(tz) => tz,
}
}
}
pub fn find_or_infer(cdr: &cdr::Checked<'_>) -> Verdict<Source, Warning> {
let mut warnings = warning::Gatherer::new();
let source = find_or_infer_into(cdr, &mut warnings);
warnings.into_verdict(source)
}
fn find_or_infer_into(
cdr: &cdr::Checked<'_>,
warnings: &mut dyn warning::Gather<Warning>,
) -> Result<Source, warning::Error<Warning>> {
let location = location(cdr, warnings)?;
debug!("Searching for time-zone in CDR");
let tz = match &location.time_zone {
schema::Integrity::Ok(Some(tz)) => try_parse_location_timezone(tz, warnings),
schema::Integrity::Ok(None) | schema::Integrity::Missing(_) | schema::Integrity::Err(_) => {
return infer_from_country(&location, warnings);
}
};
let tz = match tz {
Ok(tz) => tz,
Err(error) => {
warnings.deescalate(error);
return infer_from_country(&location, warnings);
}
};
Ok(Source::Found(tz))
}
struct Location<'a, 'buf> {
time_zone: &'a schema::Integrity<Option<schema::Str<'buf>>>,
country: &'a schema::Integrity<schema::Str<'buf>>,
}
fn location<'a, 'buf>(
cdr: &'a cdr::Checked<'buf>,
warnings: &mut dyn warning::Gather<Warning>,
) -> Result<Location<'a, 'buf>, warning::Error<Warning>> {
let (time_zone, country) = match cdr.schema() {
cdr::Version::V211(ir) => match &ir.location {
schema::Integrity::Ok(location) => (&location.time_zone, &location.country),
schema::Integrity::Missing(elem) | schema::Integrity::Err(elem) => {
return Err(warning::Error::at(elem.clone(), Warning::NoLocation));
}
},
cdr::Version::V221(ir) => match (&ir.location, &ir.cdr_location) {
(schema::Integrity::Ok(location), _) => {
warnings.insert(cdr.as_element(), Warning::V221CdrHasLocationField);
(&location.time_zone, &location.country)
}
(_, schema::Integrity::Ok(location)) => (&location.time_zone, &location.country),
(_, schema::Integrity::Missing(elem) | schema::Integrity::Err(elem)) => {
return Err(warning::Error::at(elem.clone(), Warning::NoLocation));
}
},
};
Ok(Location { time_zone, country })
}
fn infer_from_country(
location: &Location<'_, '_>,
warnings: &mut dyn warning::Gather<Warning>,
) -> Result<Source, warning::Error<Warning>> {
debug!("No time-zone found in CDR; trying to infer time-zone from country");
let country = match &location.country {
schema::Integrity::Ok(country) => country,
schema::Integrity::Missing(elem) | schema::Integrity::Err(elem) => {
return Err(warning::Error::at(elem.clone(), Warning::NoLocationCountry));
}
};
let tz = infer_timezone_from_location_country(country, warnings)?;
Ok(Source::Inferred(tz))
}
fn try_parse_location_timezone(
tz: &schema::Str<'_>,
warnings: &mut dyn warning::Gather<Warning>,
) -> Result<TimeZone, warning::Error<Warning>> {
let elem = tz.element();
let raw = tz.value();
let (tz, warning) = raw.decode_escapes();
if let Some(warning) = warning {
warnings.insert(elem, warning.into());
}
if matches!(tz, Cow::Owned(_)) {
warnings.insert(elem, Warning::ContainsEscapeCodes);
}
debug!(%tz, "Escaped time-zone found in CDR");
let Ok(timezone) = TimeZone::get(&tz) else {
return Err(warning::Error::new(elem, Warning::InvalidTimezone));
};
if timezone.iana_name() != Some(&*tz) {
warnings.insert(elem, Warning::MiscasedTimezone);
}
Ok(timezone)
}
#[instrument(skip_all)]
fn infer_timezone_from_location_country(
country: &schema::Str<'_>,
warnings: &mut dyn warning::Gather<Warning>,
) -> Result<TimeZone, warning::Error<Warning>> {
let elem = country.element();
let code_set = country::CodeSet::from_schema(country, warnings)?;
let country_code = match code_set {
country::CodeSet::Alpha2(code) => {
warnings.insert(elem, Warning::LocationCountryShouldBeAlpha3);
code
}
country::CodeSet::Alpha3(code) => code,
};
let Some(tz) = try_detect_timezone(country_code) else {
return Err(warning::Error::new(
elem,
Warning::CantInferTimezoneFromCountry(country_code.into_alpha_2_str()),
));
};
Ok(tz)
}
#[instrument]
#[expect(
clippy::wildcard_enum_match_arm,
reason = "There are many `Code` variants that do not map to a timezone."
)]
fn try_detect_timezone(country_code: country::Code) -> Option<TimeZone> {
let tz = match country_code {
country::Code::Ad => tz::get!("Europe/Andorra"),
country::Code::Al => tz::get!("Europe/Tirane"),
country::Code::At => tz::get!("Europe/Vienna"),
country::Code::Ba => tz::get!("Europe/Sarajevo"),
country::Code::Be => tz::get!("Europe/Brussels"),
country::Code::Bg => tz::get!("Europe/Sofia"),
country::Code::By => tz::get!("Europe/Minsk"),
country::Code::Ch => tz::get!("Europe/Zurich"),
country::Code::Cy => tz::get!("Europe/Nicosia"),
country::Code::Cz => tz::get!("Europe/Prague"),
country::Code::De => tz::get!("Europe/Berlin"),
country::Code::Dk => tz::get!("Europe/Copenhagen"),
country::Code::Ee => tz::get!("Europe/Tallinn"),
country::Code::Es => tz::get!("Europe/Madrid"),
country::Code::Fi => tz::get!("Europe/Helsinki"),
country::Code::Fr => tz::get!("Europe/Paris"),
country::Code::Gb => tz::get!("Europe/London"),
country::Code::Gr => tz::get!("Europe/Athens"),
country::Code::Hr => tz::get!("Europe/Zagreb"),
country::Code::Hu => tz::get!("Europe/Budapest"),
country::Code::Ie => tz::get!("Europe/Dublin"),
country::Code::Is => tz::get!("Atlantic/Reykjavik"),
country::Code::It => tz::get!("Europe/Rome"),
country::Code::Li => tz::get!("Europe/Vaduz"),
country::Code::Lt => tz::get!("Europe/Vilnius"),
country::Code::Lu => tz::get!("Europe/Luxembourg"),
country::Code::Lv => tz::get!("Europe/Riga"),
country::Code::Mc => tz::get!("Europe/Monaco"),
country::Code::Md => tz::get!("Europe/Chisinau"),
country::Code::Me => tz::get!("Europe/Podgorica"),
country::Code::Mk => tz::get!("Europe/Skopje"),
country::Code::Mt => tz::get!("Europe/Malta"),
country::Code::Nl => tz::get!("Europe/Amsterdam"),
country::Code::No => tz::get!("Europe/Oslo"),
country::Code::Pl => tz::get!("Europe/Warsaw"),
country::Code::Pt => tz::get!("Europe/Lisbon"),
country::Code::Ro => tz::get!("Europe/Bucharest"),
country::Code::Rs => tz::get!("Europe/Belgrade"),
country::Code::Ru => tz::get!("Europe/Moscow"),
country::Code::Se => tz::get!("Europe/Stockholm"),
country::Code::Si => tz::get!("Europe/Ljubljana"),
country::Code::Sk => tz::get!("Europe/Bratislava"),
country::Code::Sm => tz::get!("Europe/San_Marino"),
country::Code::Tr => tz::get!("Europe/Istanbul"),
country::Code::Ua => tz::get!("Europe/Kyiv"),
_ => return None,
};
debug!(tz = tz.iana_name(), "time-zone detected");
Some(tz)
}