#[cfg(test)]
pub mod test;
#[cfg(test)]
mod test_find_or_infer;
use std::{borrow::Cow, fmt};
use chrono_tz::Tz;
use tracing::{debug, instrument};
use crate::{
cdr, country, from_warning_all, into_caveat_all,
json::{self, FieldsAsExt as _, FromJson as _},
warning::{self, GatherWarnings as _},
IntoCaveat, ParseError, Verdict, Version, Versioned,
};
#[derive(Debug)]
pub enum Warning {
CantInferTimezoneFromCountry(&'static str),
ContainsEscapeCodes,
Country(country::Warning),
Decode(json::decode::Warning),
Deserialize(ParseError),
InvalidLocationType,
InvalidTimezone,
InvalidTimezoneType,
LocationCountryShouldBeAlpha3,
NoLocationCountry,
NoLocation,
Parser(json::Error),
ShouldBeAnObject,
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::Deserialize(err) => fmt::Display::fmt(err, f),
Self::InvalidLocationType => f.write_str("The CDR location is not a String."),
Self::InvalidTimezone => f.write_str("The CDR location did not contain a valid IANA time-zone."),
Self::InvalidTimezoneType => f.write_str("The CDR timezone is not a String."),
Self::LocationCountryShouldBeAlpha3 => f.write_str("The `location.country` field should be an alpha-3 country code."),
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::Parser(err) => fmt::Display::fmt(err, f),
Self::ShouldBeAnObject => f.write_str("The CDR should be a JSON object"),
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::Deserialize(err) => warning::Id::from_string(format!("deserialize.{err}")),
Self::Country(warning) => warning.id(),
Self::InvalidLocationType => warning::Id::from_static("invalid_location_type"),
Self::InvalidTimezone => warning::Id::from_static("invalid_timezone"),
Self::InvalidTimezoneType => warning::Id::from_static("invalid_timezone_type"),
Self::LocationCountryShouldBeAlpha3 => {
warning::Id::from_static("location_country_should_be_alpha3")
}
Self::NoLocationCountry => warning::Id::from_static("no_location_country"),
Self::NoLocation => warning::Id::from_static("no_location"),
Self::Parser(_err) => warning::Id::from_static("parser_error"),
Self::ShouldBeAnObject => warning::Id::from_static("should_be_an_object"),
Self::V221CdrHasLocationField => {
warning::Id::from_static("v221_cdr_has_location_field")
}
}
}
}
#[derive(Copy, Clone, Debug)]
pub enum Source {
Found(Tz),
Inferred(Tz),
}
into_caveat_all!(Source, Tz);
impl Source {
pub fn into_timezone(self) -> Tz {
match self {
Source::Found(tz) | Source::Inferred(tz) => tz,
}
}
}
pub fn find_or_infer(cdr: &cdr::Versioned<'_>) -> Verdict<Source, Warning> {
const LOCATION_FIELD_V211: &str = "location";
const LOCATION_FIELD_V221: &str = "cdr_location";
const TIMEZONE_FIELD: &str = "time_zone";
const COUNTRY_FIELD: &str = "country";
let mut warnings = warning::Set::new();
let cdr_root = cdr.as_element();
let Some(fields) = cdr_root.as_object_fields() else {
return warnings.bail(Warning::ShouldBeAnObject, cdr_root);
};
let cdr_fields = fields.as_raw_map();
let v211_location = cdr_fields.get(LOCATION_FIELD_V211);
if cdr.version() == Version::V221 && v211_location.is_some() {
warnings.insert(Warning::V221CdrHasLocationField, cdr_root);
}
let Some(location_elem) = v211_location.or_else(|| cdr_fields.get(LOCATION_FIELD_V221)) else {
return warnings.bail(Warning::NoLocation, cdr_root);
};
let json::Value::Object(fields) = location_elem.as_value() else {
return warnings.bail(Warning::InvalidLocationType, cdr_root);
};
let location_fields = fields.as_raw_map();
debug!("Searching for time-zone in CDR");
let tz = location_fields
.get(TIMEZONE_FIELD)
.map(|elem| try_parse_location_timezone(elem).gather_warnings_into(&mut warnings))
.transpose();
let tz = tz
.map_err(|err_set| {
warnings.deescalate_error(err_set);
})
.ok()
.flatten();
if let Some(tz) = tz {
return Ok(Source::Found(tz).into_caveat(warnings));
}
debug!("No time-zone found in CDR; trying to infer time-zone from country");
let Some(country_elem) = location_fields.get(COUNTRY_FIELD) else {
return warnings.bail(Warning::NoLocationCountry, location_elem);
};
let tz =
infer_timezone_from_location_country(country_elem).gather_warnings_into(&mut warnings)?;
Ok(Source::Inferred(tz).into_caveat(warnings))
}
fn try_parse_location_timezone(tz_elem: &json::Element<'_>) -> Verdict<Tz, Warning> {
let tz = tz_elem.as_value();
debug!(tz = %tz, "Raw time-zone found in CDR");
let mut warnings = warning::Set::new();
let Some(tz) = tz.as_raw_str() else {
return warnings.bail(Warning::InvalidTimezoneType, tz_elem);
};
let tz = tz
.decode_escapes(tz_elem)
.gather_warnings_into(&mut warnings);
if matches!(tz, Cow::Owned(_)) {
warnings.insert(Warning::ContainsEscapeCodes, tz_elem);
}
debug!(%tz, "Escaped time-zone found in CDR");
let Ok(tz) = tz.parse::<Tz>() else {
return warnings.bail(Warning::InvalidTimezone, tz_elem);
};
Ok(tz.into_caveat(warnings))
}
#[instrument(skip_all)]
fn infer_timezone_from_location_country(country_elem: &json::Element<'_>) -> Verdict<Tz, Warning> {
let mut warnings = warning::Set::new();
let code_set = country::CodeSet::from_json(country_elem)?.gather_warnings_into(&mut warnings);
let country_code = match code_set {
country::CodeSet::Alpha2(code) => {
warnings.insert(Warning::LocationCountryShouldBeAlpha3, country_elem);
code
}
country::CodeSet::Alpha3(code) => code,
};
let Some(tz) = try_detect_timezone(country_code) else {
return warnings.bail(
Warning::CantInferTimezoneFromCountry(country_code.into_alpha_2_str()),
country_elem,
);
};
Ok(tz.into_caveat(warnings))
}
#[instrument]
fn try_detect_timezone(country_code: country::Code) -> Option<Tz> {
let tz = match country_code {
country::Code::Ad => Tz::Europe__Andorra,
country::Code::Al => Tz::Europe__Tirane,
country::Code::At => Tz::Europe__Vienna,
country::Code::Ba => Tz::Europe__Sarajevo,
country::Code::Be => Tz::Europe__Brussels,
country::Code::Bg => Tz::Europe__Sofia,
country::Code::By => Tz::Europe__Minsk,
country::Code::Ch => Tz::Europe__Zurich,
country::Code::Cy => Tz::Europe__Nicosia,
country::Code::Cz => Tz::Europe__Prague,
country::Code::De => Tz::Europe__Berlin,
country::Code::Dk => Tz::Europe__Copenhagen,
country::Code::Ee => Tz::Europe__Tallinn,
country::Code::Es => Tz::Europe__Madrid,
country::Code::Fi => Tz::Europe__Helsinki,
country::Code::Fr => Tz::Europe__Paris,
country::Code::Gb => Tz::Europe__London,
country::Code::Gr => Tz::Europe__Athens,
country::Code::Hr => Tz::Europe__Zagreb,
country::Code::Hu => Tz::Europe__Budapest,
country::Code::Ie => Tz::Europe__Dublin,
country::Code::Is => Tz::Iceland,
country::Code::It => Tz::Europe__Rome,
country::Code::Li => Tz::Europe__Vaduz,
country::Code::Lt => Tz::Europe__Vilnius,
country::Code::Lu => Tz::Europe__Luxembourg,
country::Code::Lv => Tz::Europe__Riga,
country::Code::Mc => Tz::Europe__Monaco,
country::Code::Md => Tz::Europe__Chisinau,
country::Code::Me => Tz::Europe__Podgorica,
country::Code::Mk => Tz::Europe__Skopje,
country::Code::Mt => Tz::Europe__Malta,
country::Code::Nl => Tz::Europe__Amsterdam,
country::Code::No => Tz::Europe__Oslo,
country::Code::Pl => Tz::Europe__Warsaw,
country::Code::Pt => Tz::Europe__Lisbon,
country::Code::Ro => Tz::Europe__Bucharest,
country::Code::Rs => Tz::Europe__Belgrade,
country::Code::Ru => Tz::Europe__Moscow,
country::Code::Se => Tz::Europe__Stockholm,
country::Code::Si => Tz::Europe__Ljubljana,
country::Code::Sk => Tz::Europe__Bratislava,
country::Code::Sm => Tz::Europe__San_Marino,
country::Code::Tr => Tz::Turkey,
country::Code::Ua => Tz::Europe__Kiev,
_ => return None,
};
debug!(%tz, "time-zone detected");
Some(tz)
}