1#[cfg(test)]
5pub mod test;
6
7#[cfg(test)]
8mod test_find_or_infer;
9
10use std::{borrow::Cow, fmt};
11
12use jiff::tz::{self, TimeZone};
13use tracing::{debug, instrument};
14
15use crate::{
16 Verdict, cdr, country, from_warning_all, json,
17 schema::{self, FromSchema as _, HasElement as _},
18 warning,
19};
20
21#[derive(Debug)]
23pub enum Warning {
24 CantInferTimezoneFromCountry(&'static str),
26
27 ContainsEscapeCodes,
29
30 Country(country::Warning),
32
33 Decode(json::decode::Warning),
35
36 InvalidTimezone,
40
41 LocationCountryShouldBeAlpha3,
45
46 MiscasedTimezone,
52
53 NoLocationCountry,
55
56 NoLocation,
58
59 V221CdrHasLocationField,
61}
62
63from_warning_all!(
64 country::Warning => Warning::Country,
65 json::decode::Warning => Warning::Decode
66);
67
68impl fmt::Display for Warning {
69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 match self {
71 Self::CantInferTimezoneFromCountry(country_code) => write!(f, "Unable to infer timezone from the `location`'s `country`: `{country_code}`"),
72 Self::ContainsEscapeCodes => f.write_str("The CDR location contains needless escape codes."),
73 Self::Country(kind) => fmt::Display::fmt(kind, f),
74 Self::Decode(warning) => fmt::Display::fmt(warning, f),
75 Self::InvalidTimezone => f.write_str("The CDR location did not contain a valid IANA time-zone."),
76 Self::LocationCountryShouldBeAlpha3 => f.write_str("The `location.country` field should be an alpha-3 country code."),
77 Self::MiscasedTimezone => f.write_str("The CDR location's time-zone differs in letter case from the IANA name."),
78 Self::NoLocationCountry => {
79 f.write_str("The CDR's `location` has no `country` element and so the timezone can't be inferred.")
80 },
81 Self::NoLocation => {
82 f.write_str("The CDR has no `location` element and so the timezone can't be found or inferred.")
83 }
84 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."),
85
86 }
87 }
88}
89
90impl crate::Warning for Warning {
91 fn id(&self) -> warning::Id {
92 match self {
93 Self::CantInferTimezoneFromCountry(_) => {
94 warning::Id::from_static("cant_infer_timezone_from_country")
95 }
96 Self::ContainsEscapeCodes => warning::Id::from_static("contains_escape_codes"),
97 Self::Decode(warning) => warning.id(),
98 Self::Country(warning) => warning.id(),
99 Self::InvalidTimezone => warning::Id::from_static("invalid_timezone"),
100 Self::LocationCountryShouldBeAlpha3 => {
101 warning::Id::from_static("location_country_should_be_alpha3")
102 }
103 Self::MiscasedTimezone => warning::Id::from_static("miscased_timezone"),
104 Self::NoLocationCountry => warning::Id::from_static("no_location_country"),
105 Self::NoLocation => warning::Id::from_static("no_location"),
106 Self::V221CdrHasLocationField => {
107 warning::Id::from_static("v221_cdr_has_location_field")
108 }
109 }
110 }
111}
112
113#[derive(Clone, Debug)]
115pub enum Source {
116 Found(TimeZone),
118
119 Inferred(TimeZone),
121}
122
123impl Source {
124 pub fn into_timezone(self) -> TimeZone {
126 match self {
127 Source::Found(tz) | Source::Inferred(tz) => tz,
128 }
129 }
130}
131
132pub fn find_or_infer(cdr: &cdr::Checked<'_>) -> Verdict<Source, Warning> {
154 let mut warnings = warning::Gatherer::new();
155 let source = find_or_infer_into(cdr, &mut warnings);
156 warnings.into_verdict(source)
157}
158
159fn find_or_infer_into(
162 cdr: &cdr::Checked<'_>,
163 warnings: &mut dyn warning::Gather<Warning>,
164) -> Result<Source, warning::Error<Warning>> {
165 let location = location(cdr, warnings)?;
166
167 debug!("Searching for time-zone in CDR");
168
169 let tz = match &location.time_zone {
175 schema::Integrity::Ok(Some(tz)) => try_parse_location_timezone(tz, warnings),
176 schema::Integrity::Ok(None) | schema::Integrity::Missing(_) | schema::Integrity::Err(_) => {
179 return infer_from_country(&location, warnings);
180 }
181 };
182
183 let tz = match tz {
186 Ok(tz) => tz,
187 Err(error) => {
188 warnings.deescalate(error);
189 return infer_from_country(&location, warnings);
190 }
191 };
192
193 Ok(Source::Found(tz))
194}
195
196struct Location<'a, 'buf> {
199 time_zone: &'a schema::Integrity<Option<schema::Str<'buf>>>,
200 country: &'a schema::Integrity<schema::Str<'buf>>,
201}
202
203fn location<'a, 'buf>(
213 cdr: &'a cdr::Checked<'buf>,
214 warnings: &mut dyn warning::Gather<Warning>,
215) -> Result<Location<'a, 'buf>, warning::Error<Warning>> {
216 let (time_zone, country) = match cdr.schema() {
217 cdr::Version::V211(ir) => match &ir.location {
218 schema::Integrity::Ok(location) => (&location.time_zone, &location.country),
219 schema::Integrity::Missing(elem) | schema::Integrity::Err(elem) => {
220 return Err(warning::Error::at(elem.clone(), Warning::NoLocation));
221 }
222 },
223 cdr::Version::V221(ir) => match (&ir.location, &ir.cdr_location) {
226 (schema::Integrity::Ok(location), _) => {
227 warnings.insert(cdr.as_element(), Warning::V221CdrHasLocationField);
230
231 (&location.time_zone, &location.country)
232 }
233 (_, schema::Integrity::Ok(location)) => (&location.time_zone, &location.country),
234 (_, schema::Integrity::Missing(elem) | schema::Integrity::Err(elem)) => {
235 return Err(warning::Error::at(elem.clone(), Warning::NoLocation));
236 }
237 },
238 };
239
240 Ok(Location { time_zone, country })
241}
242
243fn infer_from_country(
245 location: &Location<'_, '_>,
246 warnings: &mut dyn warning::Gather<Warning>,
247) -> Result<Source, warning::Error<Warning>> {
248 debug!("No time-zone found in CDR; trying to infer time-zone from country");
249
250 let country = match &location.country {
256 schema::Integrity::Ok(country) => country,
257 schema::Integrity::Missing(elem) | schema::Integrity::Err(elem) => {
258 return Err(warning::Error::at(elem.clone(), Warning::NoLocationCountry));
259 }
260 };
261
262 let tz = infer_timezone_from_location_country(country, warnings)?;
263
264 Ok(Source::Inferred(tz))
265}
266
267fn try_parse_location_timezone(
269 tz: &schema::Str<'_>,
270 warnings: &mut dyn warning::Gather<Warning>,
271) -> Result<TimeZone, warning::Error<Warning>> {
272 let elem = tz.element();
273
274 let raw = tz.value();
276 let (tz, warning) = raw.decode_escapes();
277
278 if let Some(warning) = warning {
279 warnings.insert(elem, warning.into());
280 }
281
282 if matches!(tz, Cow::Owned(_)) {
283 warnings.insert(elem, Warning::ContainsEscapeCodes);
284 }
285
286 debug!(%tz, "Escaped time-zone found in CDR");
287
288 let Ok(timezone) = TimeZone::get(&tz) else {
289 return Err(warning::Error::new(elem, Warning::InvalidTimezone));
290 };
291
292 if timezone.iana_name() != Some(&*tz) {
296 warnings.insert(elem, Warning::MiscasedTimezone);
297 }
298
299 Ok(timezone)
300}
301
302#[instrument(skip_all)]
304fn infer_timezone_from_location_country(
305 country: &schema::Str<'_>,
306 warnings: &mut dyn warning::Gather<Warning>,
307) -> Result<TimeZone, warning::Error<Warning>> {
308 let elem = country.element();
309 let code_set = country::CodeSet::from_schema(country, warnings)?;
310
311 let country_code = match code_set {
315 country::CodeSet::Alpha2(code) => {
316 warnings.insert(elem, Warning::LocationCountryShouldBeAlpha3);
317 code
318 }
319 country::CodeSet::Alpha3(code) => code,
320 };
321 let Some(tz) = try_detect_timezone(country_code) else {
322 return Err(warning::Error::new(
323 elem,
324 Warning::CantInferTimezoneFromCountry(country_code.into_alpha_2_str()),
325 ));
326 };
327
328 Ok(tz)
329}
330
331#[instrument]
339#[expect(
340 clippy::wildcard_enum_match_arm,
341 reason = "There are many `Code` variants that do not map to a timezone."
342)]
343fn try_detect_timezone(country_code: country::Code) -> Option<TimeZone> {
344 let tz = match country_code {
345 country::Code::Ad => tz::get!("Europe/Andorra"),
346 country::Code::Al => tz::get!("Europe/Tirane"),
347 country::Code::At => tz::get!("Europe/Vienna"),
348 country::Code::Ba => tz::get!("Europe/Sarajevo"),
349 country::Code::Be => tz::get!("Europe/Brussels"),
350 country::Code::Bg => tz::get!("Europe/Sofia"),
351 country::Code::By => tz::get!("Europe/Minsk"),
352 country::Code::Ch => tz::get!("Europe/Zurich"),
353 country::Code::Cy => tz::get!("Europe/Nicosia"),
354 country::Code::Cz => tz::get!("Europe/Prague"),
355 country::Code::De => tz::get!("Europe/Berlin"),
356 country::Code::Dk => tz::get!("Europe/Copenhagen"),
357 country::Code::Ee => tz::get!("Europe/Tallinn"),
358 country::Code::Es => tz::get!("Europe/Madrid"),
359 country::Code::Fi => tz::get!("Europe/Helsinki"),
360 country::Code::Fr => tz::get!("Europe/Paris"),
361 country::Code::Gb => tz::get!("Europe/London"),
362 country::Code::Gr => tz::get!("Europe/Athens"),
363 country::Code::Hr => tz::get!("Europe/Zagreb"),
364 country::Code::Hu => tz::get!("Europe/Budapest"),
365 country::Code::Ie => tz::get!("Europe/Dublin"),
366 country::Code::Is => tz::get!("Atlantic/Reykjavik"),
367 country::Code::It => tz::get!("Europe/Rome"),
368 country::Code::Li => tz::get!("Europe/Vaduz"),
369 country::Code::Lt => tz::get!("Europe/Vilnius"),
370 country::Code::Lu => tz::get!("Europe/Luxembourg"),
371 country::Code::Lv => tz::get!("Europe/Riga"),
372 country::Code::Mc => tz::get!("Europe/Monaco"),
373 country::Code::Md => tz::get!("Europe/Chisinau"),
374 country::Code::Me => tz::get!("Europe/Podgorica"),
375 country::Code::Mk => tz::get!("Europe/Skopje"),
376 country::Code::Mt => tz::get!("Europe/Malta"),
377 country::Code::Nl => tz::get!("Europe/Amsterdam"),
378 country::Code::No => tz::get!("Europe/Oslo"),
379 country::Code::Pl => tz::get!("Europe/Warsaw"),
380 country::Code::Pt => tz::get!("Europe/Lisbon"),
381 country::Code::Ro => tz::get!("Europe/Bucharest"),
382 country::Code::Rs => tz::get!("Europe/Belgrade"),
383 country::Code::Ru => tz::get!("Europe/Moscow"),
384 country::Code::Se => tz::get!("Europe/Stockholm"),
385 country::Code::Si => tz::get!("Europe/Ljubljana"),
386 country::Code::Sk => tz::get!("Europe/Bratislava"),
387 country::Code::Sm => tz::get!("Europe/San_Marino"),
388 country::Code::Tr => tz::get!("Europe/Istanbul"),
389 country::Code::Ua => tz::get!("Europe/Kyiv"),
390 _ => return None,
391 };
392
393 debug!(tz = tz.iana_name(), "time-zone detected");
394
395 Some(tz)
396}