1#[cfg(test)]
3pub mod test;
4
5#[cfg(test)]
6mod test_find_or_infer;
7
8use std::{borrow::Cow, fmt};
9
10use chrono_tz::Tz;
11use tracing::{debug, instrument};
12
13use crate::{
14 cdr, country, from_warning_all,
15 json::{self, FieldsAsExt as _, FromJson as _},
16 warning::{self, GatherWarnings as _},
17 IntoCaveat, ParseError, Verdict, Version, Versioned,
18};
19
20#[derive(Debug)]
22pub enum Warning {
23 CantInferTimezoneFromCountry(&'static str),
25
26 ContainsEscapeCodes,
28
29 Country(country::Warning),
31
32 Decode(json::decode::Warning),
34
35 Deserialize(ParseError),
37
38 InvalidLocationType,
40
41 InvalidTimezone,
45
46 InvalidTimezoneType,
48
49 LocationCountryShouldBeAlpha3,
53
54 NoLocationCountry,
56
57 NoLocation,
59
60 Parser(json::Error),
62
63 ShouldBeAnObject,
65
66 V221CdrHasLocationField,
68}
69
70from_warning_all!(
71 country::Warning => Warning::Country,
72 json::decode::Warning => Warning::Decode
73);
74
75impl fmt::Display for Warning {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 match self {
78 Self::CantInferTimezoneFromCountry(country_code) => write!(f, "Unable to infer timezone from the `location`'s `country`: `{country_code}`"),
79 Self::ContainsEscapeCodes => f.write_str("The CDR location contains needless escape codes."),
80 Self::Country(kind) => fmt::Display::fmt(kind, f),
81 Self::Decode(warning) => fmt::Display::fmt(warning, f),
82 Self::Deserialize(err) => fmt::Display::fmt(err, f),
83 Self::InvalidLocationType => f.write_str("The CDR location is not a String."),
84 Self::InvalidTimezone => f.write_str("The CDR location did not contain a valid IANA time-zone."),
85 Self::InvalidTimezoneType => f.write_str("The CDR timezone is not a String."),
86 Self::LocationCountryShouldBeAlpha3 => f.write_str("The `location.country` field should be an alpha-3 country code."),
87 Self::NoLocationCountry => {
88 f.write_str("The CDR's `location` has no `country` element and so the timezone can't be inferred.")
89 },
90 Self::NoLocation => {
91 f.write_str("The CDR has no `location` element and so the timezone can't be found or inferred.")
92 }
93 Self::Parser(err) => fmt::Display::fmt(err, f),
94 Self::ShouldBeAnObject => f.write_str("The CDR should be a JSON object"),
95 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."),
96
97 }
98 }
99}
100
101impl crate::Warning for Warning {
102 fn id(&self) -> warning::Id {
103 match self {
104 Self::CantInferTimezoneFromCountry(_) => {
105 warning::Id::from_static("cant_infer_timezone_from_country")
106 }
107 Self::ContainsEscapeCodes => warning::Id::from_static("contains_escape_codes"),
108 Self::Decode(warning) => warning.id(),
109 Self::Deserialize(err) => warning::Id::from_string(format!("deserialize.{err}")),
110 Self::Country(warning) => warning.id(),
111 Self::InvalidLocationType => warning::Id::from_static("invalid_location_type"),
112 Self::InvalidTimezone => warning::Id::from_static("invalid_timezone"),
113 Self::InvalidTimezoneType => warning::Id::from_static("invalid_timezone_type"),
114 Self::LocationCountryShouldBeAlpha3 => {
115 warning::Id::from_static("location_country_should_be_alpha3")
116 }
117 Self::NoLocationCountry => warning::Id::from_static("no_location_country"),
118 Self::NoLocation => warning::Id::from_static("no_location"),
119 Self::Parser(_err) => warning::Id::from_static("parser_error"),
120 Self::ShouldBeAnObject => warning::Id::from_static("should_be_an_object"),
121 Self::V221CdrHasLocationField => {
122 warning::Id::from_static("v221_cdr_has_location_field")
123 }
124 }
125 }
126}
127
128#[derive(Copy, Clone, Debug)]
130pub enum Source {
131 Found(Tz),
133
134 Inferred(Tz),
136}
137
138impl Source {
139 pub fn into_timezone(self) -> Tz {
141 match self {
142 Source::Found(tz) | Source::Inferred(tz) => tz,
143 }
144 }
145}
146
147pub fn find_or_infer(cdr: &cdr::Versioned<'_>) -> Verdict<Source, Warning> {
161 const LOCATION_FIELD_V211: &str = "location";
162 const LOCATION_FIELD_V221: &str = "cdr_location";
163 const TIMEZONE_FIELD: &str = "time_zone";
164 const COUNTRY_FIELD: &str = "country";
165
166 let mut warnings = warning::Set::new();
167
168 let cdr_root = cdr.as_element();
169 let Some(fields) = cdr_root.as_object_fields() else {
170 return warnings.bail(Warning::ShouldBeAnObject, cdr_root);
171 };
172
173 let cdr_fields = fields.as_raw_map();
174
175 let v211_location = cdr_fields.get(LOCATION_FIELD_V211);
176
177 if cdr.version() == Version::V221 && v211_location.is_some() {
182 warnings.insert(Warning::V221CdrHasLocationField, cdr_root);
183 }
184
185 let Some(location_elem) = v211_location.or_else(|| cdr_fields.get(LOCATION_FIELD_V221)) else {
192 return warnings.bail(Warning::NoLocation, cdr_root);
193 };
194
195 let json::Value::Object(fields) = location_elem.as_value() else {
196 return warnings.bail(Warning::InvalidLocationType, cdr_root);
197 };
198
199 let location_fields = fields.as_raw_map();
200
201 debug!("Searching for time-zone in CDR");
202
203 let tz = location_fields
208 .get(TIMEZONE_FIELD)
209 .map(|elem| try_parse_location_timezone(elem).gather_warnings_into(&mut warnings))
210 .transpose();
211
212 let tz = tz
216 .map_err(|err_set| {
217 warnings.deescalate_error(err_set);
218 })
219 .ok()
220 .flatten();
221
222 if let Some(tz) = tz {
223 return Ok(Source::Found(tz).into_caveat(warnings));
224 }
225
226 debug!("No time-zone found in CDR; trying to infer time-zone from country");
227
228 let Some(country_elem) = location_fields.get(COUNTRY_FIELD) else {
230 return warnings.bail(Warning::NoLocationCountry, location_elem);
235 };
236 let tz =
237 infer_timezone_from_location_country(country_elem).gather_warnings_into(&mut warnings)?;
238
239 Ok(Source::Inferred(tz).into_caveat(warnings))
240}
241
242fn try_parse_location_timezone(tz_elem: &json::Element<'_>) -> Verdict<Tz, Warning> {
244 let tz = tz_elem.as_value();
245 debug!(tz = %tz, "Raw time-zone found in CDR");
246
247 let mut warnings = warning::Set::new();
248 let Some(tz) = tz.to_raw_str() else {
249 return warnings.bail(Warning::InvalidTimezoneType, tz_elem);
250 };
251
252 let tz = tz
253 .decode_escapes(tz_elem)
254 .gather_warnings_into(&mut warnings);
255
256 if matches!(tz, Cow::Owned(_)) {
257 warnings.insert(Warning::ContainsEscapeCodes, tz_elem);
258 }
259
260 debug!(%tz, "Escaped time-zone found in CDR");
261
262 let Ok(tz) = tz.parse::<Tz>() else {
263 return warnings.bail(Warning::InvalidTimezone, tz_elem);
264 };
265
266 Ok(tz.into_caveat(warnings))
267}
268
269#[instrument(skip_all)]
271fn infer_timezone_from_location_country(country_elem: &json::Element<'_>) -> Verdict<Tz, Warning> {
272 let mut warnings = warning::Set::new();
273 let code_set = country::CodeSet::from_json(country_elem)?.gather_warnings_into(&mut warnings);
274
275 let country_code = match code_set {
279 country::CodeSet::Alpha2(code) => {
280 warnings.insert(Warning::LocationCountryShouldBeAlpha3, country_elem);
281 code
282 }
283 country::CodeSet::Alpha3(code) => code,
284 };
285 let Some(tz) = try_detect_timezone(country_code) else {
286 return warnings.bail(
287 Warning::CantInferTimezoneFromCountry(country_code.into_alpha_2_str()),
288 country_elem,
289 );
290 };
291
292 Ok(tz.into_caveat(warnings))
293}
294
295#[instrument]
303fn try_detect_timezone(country_code: country::Code) -> Option<Tz> {
304 let tz = match country_code {
305 country::Code::Ad => Tz::Europe__Andorra,
306 country::Code::Al => Tz::Europe__Tirane,
307 country::Code::At => Tz::Europe__Vienna,
308 country::Code::Ba => Tz::Europe__Sarajevo,
309 country::Code::Be => Tz::Europe__Brussels,
310 country::Code::Bg => Tz::Europe__Sofia,
311 country::Code::By => Tz::Europe__Minsk,
312 country::Code::Ch => Tz::Europe__Zurich,
313 country::Code::Cy => Tz::Europe__Nicosia,
314 country::Code::Cz => Tz::Europe__Prague,
315 country::Code::De => Tz::Europe__Berlin,
316 country::Code::Dk => Tz::Europe__Copenhagen,
317 country::Code::Ee => Tz::Europe__Tallinn,
318 country::Code::Es => Tz::Europe__Madrid,
319 country::Code::Fi => Tz::Europe__Helsinki,
320 country::Code::Fr => Tz::Europe__Paris,
321 country::Code::Gb => Tz::Europe__London,
322 country::Code::Gr => Tz::Europe__Athens,
323 country::Code::Hr => Tz::Europe__Zagreb,
324 country::Code::Hu => Tz::Europe__Budapest,
325 country::Code::Ie => Tz::Europe__Dublin,
326 country::Code::Is => Tz::Iceland,
327 country::Code::It => Tz::Europe__Rome,
328 country::Code::Li => Tz::Europe__Vaduz,
329 country::Code::Lt => Tz::Europe__Vilnius,
330 country::Code::Lu => Tz::Europe__Luxembourg,
331 country::Code::Lv => Tz::Europe__Riga,
332 country::Code::Mc => Tz::Europe__Monaco,
333 country::Code::Md => Tz::Europe__Chisinau,
334 country::Code::Me => Tz::Europe__Podgorica,
335 country::Code::Mk => Tz::Europe__Skopje,
336 country::Code::Mt => Tz::Europe__Malta,
337 country::Code::Nl => Tz::Europe__Amsterdam,
338 country::Code::No => Tz::Europe__Oslo,
339 country::Code::Pl => Tz::Europe__Warsaw,
340 country::Code::Pt => Tz::Europe__Lisbon,
341 country::Code::Ro => Tz::Europe__Bucharest,
342 country::Code::Rs => Tz::Europe__Belgrade,
343 country::Code::Ru => Tz::Europe__Moscow,
344 country::Code::Se => Tz::Europe__Stockholm,
345 country::Code::Si => Tz::Europe__Ljubljana,
346 country::Code::Sk => Tz::Europe__Bratislava,
347 country::Code::Sm => Tz::Europe__San_Marino,
348 country::Code::Tr => Tz::Turkey,
349 country::Code::Ua => Tz::Europe__Kiev,
350 _ => return None,
351 };
352
353 debug!(%tz, "time-zone detected");
354
355 Some(tz)
356}