Skip to main content

ocpi_tariffs/
timezone.rs

1//! Parse an IANA Timezone from JSON or find a timezone in a CDR.
2
3/// Test support shared by this module's other test files.
4#[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/// The warnings possible when parsing or linting an IANA timezone.
22#[derive(Debug)]
23pub enum Warning {
24    /// A timezone can't be inferred from the `location`'s `country`.
25    CantInferTimezoneFromCountry(&'static str),
26
27    /// Neither the timezone or country field require char escape codes.
28    ContainsEscapeCodes,
29
30    /// The CDR location is not a valid `ISO 3166-1` alpha-3 code.
31    Country(country::Warning),
32
33    /// The field at the path could not be decoded.
34    Decode(json::decode::Warning),
35
36    /// The CDR location did not contain a valid IANA time-zone.
37    ///
38    /// See: <https://www.iana.org/time-zones>.
39    InvalidTimezone,
40
41    /// The `location.country` field should be an alpha-3 country code.
42    ///
43    /// The alpha-2 code can be converted into an alpha-3 but the caller should be warned.
44    LocationCountryShouldBeAlpha3,
45
46    /// The `time_zone` names an IANA time zone in the wrong letter case, such as
47    /// `europe/amsterdam` for `Europe/Amsterdam`.
48    ///
49    /// No two IANA names differ only in case, so [`find_or_infer`] still finds the time zone
50    /// and returns it as [`Source::Found`].
51    MiscasedTimezone,
52
53    /// The CDR's `location` has no `country` element and so the timezone can't be inferred.
54    NoLocationCountry,
55
56    /// The CDR has no `location` element and so the timezone can't be found or inferred.
57    NoLocation,
58
59    /// A v221 CDR is given but it contains a `location` field instead of a `cdr_location` as defined in the spec.
60    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/// The source of the timezone.
114#[derive(Clone, Debug)]
115pub enum Source {
116    /// The timezone was found in the `location` element.
117    Found(TimeZone),
118
119    /// The timezone is inferred from the `location`'s `country`.
120    Inferred(TimeZone),
121}
122
123impl Source {
124    /// Return the timezone and disregard where it came from.
125    pub fn into_timezone(self) -> TimeZone {
126        match self {
127            Source::Found(tz) | Source::Inferred(tz) => tz,
128        }
129    }
130}
131
132/// Find the timezone stated in the `CDR`, or infer one from its country.
133///
134/// [`Source`] says which of the two happened, because a stated timezone is the CDR's own
135/// claim while an inferred one is this library's guess.
136///
137/// `find_or_infer` takes the CDR that [`cdr::check`] returns, so it can run before
138/// [`cdr::build`], and a CDR that `build` refuses can still get a timezone.
139/// [`Source::into_timezone`] gives the timezone that [`cdr::price`] takes.
140///
141/// A `time_zone` field is read wherever it appears. `v2.2.1` dropped it from `CdrLocation`, but
142/// enough CDRs still carry it that the schema reads it and reports `NonSpecField`, and a `v2.2.1`
143/// CDR carrying the old `location` object is preferred over its `cdr_location`, since that is
144/// where such a CDR put the timezone. A `time_zone` that is present but unusable is not fatal: it
145/// becomes a warning and the country is tried instead.
146///
147/// Inferring works only for a country with a single timezone, which in practice means Europe.
148///
149/// # Errors
150///
151/// The CDR has no usable location object, its location states no country, or that country maps to
152/// no timezone.
153pub 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
159/// Find the timezone stated in the CDR, or infer one from its country,
160/// gathering the warnings into `warnings`.
161fn 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    // The `location::time_zone` field is optional in v211 and not part of the v221 spec,
170    // where the schema reports it as a `NonSpecField` and reads it anyway.
171    //
172    // See: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc#mod_cdrs_cdr_location_class>
173    // See: <https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/mod_locations.md#31-location-object>
174    let tz = match &location.time_zone {
175        schema::Integrity::Ok(Some(tz)) => try_parse_location_timezone(tz, warnings),
176        // An absent, `null`, or wrongly typed `time_zone` is located by the schema walk.
177        // There may still be a country to infer from, so the search continues.
178        schema::Integrity::Ok(None) | schema::Integrity::Missing(_) | schema::Integrity::Err(_) => {
179            return infer_from_country(&location, warnings);
180        }
181    };
182
183    // A `time_zone` that is present but unusable is not fatal. The failure is de-escalated to
184    // a warning and the country is tried instead.
185    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
196/// The two fields a timezone can be found or inferred from, borrowed out of whichever
197/// version's location object carries them.
198struct Location<'a, 'buf> {
199    time_zone: &'a schema::Integrity<Option<schema::Str<'buf>>>,
200    country: &'a schema::Integrity<schema::Str<'buf>>,
201}
202
203/// Borrow the location fields out of the CDR's schema IR.
204///
205/// Describes the location that the charge-session took place at. The v211 CDR has a
206/// `location` field while the v221 CDR has a `cdr_location` field. A v221 CDR that still
207/// uses the old name is read from it anyway, because that is the only place its timezone
208/// can be.
209///
210/// * See: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc#mod_cdrs_cdr_object>
211/// * See: <https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/mod_cdrs.md#3-object-description>
212fn 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        // A `location` object in a v221 CDR is the v211 field name. It is preferred over
224        // `cdr_location`, because a CDR that carries it put the timezone there.
225        cdr::Version::V221(ir) => match (&ir.location, &ir.cdr_location) {
226            (schema::Integrity::Ok(location), _) => {
227                // Anchored at the document rather than at the field: the schema walk's
228                // `NonSpecField` warning already locates the field itself.
229                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
243/// Infer the timezone from the location's `country`, having found no usable `time_zone`.
244fn 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    // `ISO 3166-1 alpha-3` code for the country of this location. The field is required in
251    // both versions.
252    //
253    // See: <https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_cdrs.asciidoc#mod_cdrs_cdr_location_class>
254    // See: <https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/mod_locations.md#31-location-object>
255    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
267/// Try to parse the location's `time_zone` into a `TimeZone`.
268fn 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    // The schema proved the value is a JSON string but keeps it raw, so it is decoded here.
275    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    // jiff looks a name up without regard to ASCII case, and returns the name as the
293    // database spells it. It returns an alias such as `Europe/Kiev` as itself, not as
294    // `Europe/Kyiv`. So a returned name that differs from the input differs only in case.
295    if timezone.iana_name() != Some(&*tz) {
296        warnings.insert(elem, Warning::MiscasedTimezone);
297    }
298
299    Ok(timezone)
300}
301
302/// Try to infer a timezone from the location's `country` field.
303#[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    // The `location.country` field should be an alpha-3 country code.
312    //
313    // The alpha-2 code can be converted into an alpha-3 but the caller should be warned.
314    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/// Mapping of European countries to time-zones with geographical naming
332///
333/// This is only possible for countries with a single time-zone and only for countries as they
334/// currently exist (2024). It's a best effort approach to determine a time-zone from just an
335/// ALPHA-3 `ISO 3166-1` country code.
336///
337/// In small edge cases (e.g. Gibraltar) this detection might generate the wrong time-zone.
338#[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}