ocpi-kit 0.2.0

OCPI (Open Charge Point Interface) toolkit for EV roaming: spec-exact typed models for OCPI 2.3.0 / 2.2.1 / 2.1.1, transport envelope, client, server and hub building blocks, and an auditable tariff engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
//! `DateTime` — the OCPI timestamp type: RFC 3339, always UTC.

use core::fmt;
use core::str::FromStr;

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use time::{OffsetDateTime, PrimitiveDateTime, UtcOffset};

use super::validate::{Validate, Validator, ViolationCode};

/// An OCPI timestamp: an instant in UTC, serialised as RFC 3339 with a `Z` designator.
///
/// > *All timestamps are formatted as string(25) following RFC 3339, with some additional
/// > limitations. All timestamps SHALL be in UTC. The absence of the timezone designator implies
/// > a UTC timestamp. Fractional seconds MAY be used.*
///
/// The six forms the spec lists as the only allowed ones are, by example:
///
/// ```text
/// 2015-06-29T20:39:09Z        2015-06-29T20:39:09
/// 2016-12-29T17:45:09.2Z      2016-12-29T17:45:09.2
/// 2018-01-01T01:08:01.123Z    2018-01-01T01:08:01.123
/// ```
///
/// # `+00:00` is not `Z`
///
/// The spec is explicit: *"NOTE: +00:00 is not the same as UTC."* A `DateTime` parsed from a
/// timestamp carrying an explicit offset — even `+00:00` — is converted to the correct UTC
/// instant so no data is lost, but is flagged: [`DateTime::is_canonical`] returns `false` and
/// [`Validate::validate`] reports it. Serialising always emits the canonical `Z` form, so a
/// value that passes through this crate comes out conformant.
///
/// # Fractional seconds are preserved
///
/// A timestamp read as `…09.2Z` is written back as `…09.2Z`, not `…09.200Z`. The number of
/// fractional digits is formatting metadata: it takes no part in [`PartialEq`], [`Ord`] or
/// [`std::hash::Hash`], which compare the instant alone.
///
/// ```
/// use ocpi_kit::types::DateTime;
///
/// let t: DateTime = "2016-12-29T17:45:09.2Z".parse().unwrap();
/// assert_eq!(t.to_string(), "2016-12-29T17:45:09.2Z");
/// assert_eq!(t, "2016-12-29T17:45:09.200Z".parse::<DateTime>().unwrap());
/// ```
///
/// Spec: 2.3.0 §types_datetime_type
#[derive(Clone, Copy)]
pub struct DateTime {
    /// Always normalised to `UtcOffset::UTC`.
    instant: OffsetDateTime,
    /// Number of fractional-second digits to emit (0..=9).
    frac_digits: u8,
    /// Whether the source text used one of the six forms the spec permits.
    canonical: bool,
}

impl DateTime {
    /// The current time, with second precision.
    #[must_use]
    pub fn now() -> Self {
        Self::from_utc(
            OffsetDateTime::now_utc().replace_nanosecond(0).unwrap_or_else(|_| OffsetDateTime::now_utc()),
        )
    }

    /// Wraps an [`OffsetDateTime`], converting it to UTC.
    ///
    /// The number of fractional digits emitted is chosen to be the shortest that represents the
    /// value exactly: none, three, six or nine.
    ///
    /// Crate-private for the same reason as
    /// [`as_offset_date_time`](Self::as_offset_date_time): the backend stays swappable.
    /// [`from_unix_timestamp`](Self::from_unix_timestamp), [`parse`](Self::parse) and
    /// [`now`](Self::now) are the public constructors.
    pub(crate) fn from_utc(value: OffsetDateTime) -> Self {
        let instant = value.to_offset(UtcOffset::UTC);
        Self { instant, frac_digits: shortest_frac_digits(instant.nanosecond()), canonical: true }
    }

    /// The wall clock this instant shows in a zone `offset_seconds` east of UTC.
    ///
    /// Every time-of-day and day-of-week rule in OCPI is written in a Location's local time —
    /// tariff restrictions, opening hours — so reading one means converting first. The result is
    /// in this crate's own [`LocalParts`](crate::types::LocalParts), so no date-time library
    /// reaches the API.
    ///
    /// The offset has to come from somewhere: a `Location` carries an IANA `time_zone`, and
    /// [`TimeZone`](crate::tariffs::TimeZone) resolves it against the zone database, which is
    /// what a rule spanning a daylight-saving change needs.
    ///
    /// ```
    /// use ocpi_kit::types::DateTime;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let instant: DateTime = "2024-01-15T23:30:00Z".parse()?;
    /// let local = instant.local_parts(3600); // CET, UTC+1
    /// assert_eq!(local.time.hour(), 0);
    /// assert_eq!(local.date.day(), 16);
    /// assert_eq!(local.iso_weekday, 2); // Tuesday
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn local_parts(self, offset_seconds: i32) -> crate::types::LocalParts {
        let local = self.instant + time::Duration::seconds(i64::from(offset_seconds));
        crate::types::LocalParts {
            date: crate::types::LocalDate::from_date(local.date()),
            // Hour and minute out of a real timestamp are always in range.
            time: crate::types::LocalTime::new(local.hour(), local.minute())
                .expect("an hour and minute from a timestamp are in range"),
            iso_weekday: local.weekday().number_from_monday(),
        }
    }

    /// Seconds since the Unix epoch.
    #[must_use]
    pub const fn unix_timestamp(self) -> i64 {
        self.instant.unix_timestamp()
    }

    /// Builds a timestamp from seconds since the Unix epoch.
    ///
    /// # Errors
    ///
    /// Returns [`InvalidDateTime`] if the value is outside the supported range.
    pub fn from_unix_timestamp(secs: i64) -> Result<Self, InvalidDateTime> {
        OffsetDateTime::from_unix_timestamp(secs)
            .map(Self::from_utc)
            .map_err(|_| InvalidDateTime::new("timestamp out of range"))
    }

    /// Whether the value was written in one of the six forms the spec allows.
    ///
    /// `false` means the source used an explicit UTC offset (including `+00:00`), a lower-case
    /// `z`, or a space instead of `T`. The instant itself is still correct.
    #[must_use]
    pub const fn is_canonical(self) -> bool {
        self.canonical
    }

    /// Returns a copy that will be written with exactly `digits` fractional-second digits.
    ///
    /// `digits` is clamped to 9.
    #[must_use]
    pub const fn with_fractional_digits(mut self, digits: u8) -> Self {
        self.frac_digits = if digits > 9 { 9 } else { digits };
        self
    }

    /// How many fractional-second digits this value will be written with.
    #[must_use]
    pub const fn fractional_digits(self) -> u8 {
        self.frac_digits
    }

    /// Parses one of the RFC 3339 forms OCPI allows, plus the tolerated deviations described on
    /// the type.
    ///
    /// # Errors
    ///
    /// Returns [`InvalidDateTime`] when the text is not a date-time at all, or carries an
    /// offset that would place it outside the representable range.
    pub fn parse(text: &str) -> Result<Self, InvalidDateTime> {
        parse_ocpi_datetime(text)
    }
}

fn shortest_frac_digits(nanos: u32) -> u8 {
    if nanos == 0 {
        0
    } else if nanos.is_multiple_of(1_000_000) {
        3
    } else if nanos.is_multiple_of(1_000) {
        6
    } else {
        9
    }
}

/// Why a timestamp could not be parsed.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InvalidDateTime(String);

impl InvalidDateTime {
    fn new(message: impl Into<String>) -> Self {
        Self(message.into())
    }
}

impl fmt::Display for InvalidDateTime {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "invalid OCPI DateTime: {}", self.0)
    }
}

impl std::error::Error for InvalidDateTime {}

#[allow(clippy::too_many_lines)]
fn parse_ocpi_datetime(text: &str) -> Result<DateTime, InvalidDateTime> {
    let bytes = text.as_bytes();
    let err = |m: &str| InvalidDateTime::new(format!("{m} in {text:?}"));

    if bytes.len() < 19 {
        return Err(err("too short for YYYY-MM-DDTHH:MM:SS"));
    }
    let digits = |from: usize, len: usize| -> Result<u32, InvalidDateTime> {
        let slice = text.get(from..from + len).ok_or_else(|| err("truncated"))?;
        if !slice.bytes().all(|b| b.is_ascii_digit()) {
            return Err(err("expected digits"));
        }
        slice.parse::<u32>().map_err(|_| err("expected digits"))
    };
    if bytes[4] != b'-' || bytes[7] != b'-' {
        return Err(err("expected YYYY-MM-DD"));
    }
    if bytes[13] != b':' || bytes[16] != b':' {
        return Err(err("expected HH:MM:SS"));
    }

    let mut canonical = true;
    match bytes[10] {
        b'T' => {}
        b't' | b' ' => canonical = false,
        _ => return Err(err("expected 'T' between date and time")),
    }

    let year = i32::try_from(digits(0, 4)?).map_err(|_| err("year out of range"))?;
    let month = u8::try_from(digits(5, 2)?).map_err(|_| err("month out of range"))?;
    let day = u8::try_from(digits(8, 2)?).map_err(|_| err("day out of range"))?;
    let hour = u8::try_from(digits(11, 2)?).map_err(|_| err("hour out of range"))?;
    let minute = u8::try_from(digits(14, 2)?).map_err(|_| err("minute out of range"))?;
    let second = u8::try_from(digits(17, 2)?).map_err(|_| err("second out of range"))?;

    let mut idx = 19;
    let mut nanos: u32 = 0;
    let mut frac_digits: u8 = 0;
    if bytes.get(idx) == Some(&b'.') || bytes.get(idx) == Some(&b',') {
        if bytes[idx] == b',' {
            canonical = false;
        }
        idx += 1;
        let start = idx;
        while bytes.get(idx).is_some_and(u8::is_ascii_digit) {
            idx += 1;
        }
        if idx == start {
            return Err(err("fractional separator with no digits"));
        }
        let raw = &text[start..idx];
        // More digits than a `u8` can count is still "more than nine", so it clamps and is
        // flagged like any other over-long fraction rather than falling through as canonical.
        frac_digits = u8::try_from(raw.len()).unwrap_or(u8::MAX);
        // Scale the first nine digits to nanoseconds; ignore any beyond.
        let mut scaled = String::with_capacity(9);
        scaled.push_str(&raw[..raw.len().min(9)]);
        while scaled.len() < 9 {
            scaled.push('0');
        }
        nanos = scaled.parse().map_err(|_| err("bad fractional seconds"))?;
        if frac_digits > 9 {
            frac_digits = 9;
            canonical = false;
        }
    }

    let offset_minutes: i32 = match bytes.get(idx) {
        None => {
            // "The absence of the timezone designator implies a UTC timestamp."
            0
        }
        Some(b'Z') => {
            idx += 1;
            0
        }
        Some(b'z') => {
            canonical = false;
            idx += 1;
            0
        }
        Some(sign @ (b'+' | b'-')) => {
            // Spec: "+00:00 is not the same as UTC" — accepted, but not canonical.
            canonical = false;
            let sign = if *sign == b'-' { -1 } else { 1 };
            idx += 1;
            let oh = i32::try_from(digits(idx, 2)?).map_err(|_| err("offset out of range"))?;
            idx += 2;
            if bytes.get(idx) == Some(&b':') {
                idx += 1;
            }
            let om = i32::try_from(digits(idx, 2)?).map_err(|_| err("offset out of range"))?;
            idx += 2;
            sign * (oh * 60 + om)
        }
        Some(_) => return Err(err("unexpected trailing characters")),
    };
    if idx != bytes.len() {
        return Err(err("unexpected trailing characters"));
    }

    let date = time::Date::from_calendar_date(
        year,
        time::Month::try_from(month).map_err(|_| err("month out of range"))?,
        day,
    )
    .map_err(|_| err("no such calendar date"))?;
    // RFC 3339 allows second 60 for leap seconds; clamp to 59 as `time` has no leap seconds.
    let (second, leap) = if second == 60 { (59, true) } else { (second, false) };
    let time_of_day =
        time::Time::from_hms_nano(hour, minute, second, nanos).map_err(|_| err("no such time of day"))?;
    if leap {
        canonical = false;
    }
    let naive = PrimitiveDateTime::new(date, time_of_day);
    let offset =
        UtcOffset::from_whole_seconds(offset_minutes * 60).map_err(|_| err("offset out of range"))?;
    let instant = naive.assume_offset(offset).to_offset(UtcOffset::UTC);

    Ok(DateTime { instant, frac_digits, canonical })
}

impl fmt::Display for DateTime {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let d = self.instant.date();
        let t = self.instant.time();
        write!(
            f,
            "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}",
            d.year(),
            u8::from(d.month()),
            d.day(),
            t.hour(),
            t.minute(),
            t.second()
        )?;
        if self.frac_digits > 0 {
            let nanos = t.nanosecond();
            let text = format!("{nanos:09}");
            f.write_str(".")?;
            f.write_str(&text[..usize::from(self.frac_digits)])?;
        }
        f.write_str("Z")
    }
}

impl fmt::Debug for DateTime {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "DateTime({self})")
    }
}

impl PartialEq for DateTime {
    fn eq(&self, other: &Self) -> bool {
        self.instant == other.instant
    }
}
impl Eq for DateTime {}

impl PartialOrd for DateTime {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl Ord for DateTime {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.instant.cmp(&other.instant)
    }
}
impl core::hash::Hash for DateTime {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.instant.hash(state);
    }
}

impl From<OffsetDateTime> for DateTime {
    fn from(value: OffsetDateTime) -> Self {
        Self::from_utc(value)
    }
}

impl From<DateTime> for OffsetDateTime {
    fn from(value: DateTime) -> Self {
        value.instant
    }
}

impl FromStr for DateTime {
    type Err = InvalidDateTime;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        parse_ocpi_datetime(s)
    }
}

impl TryFrom<&str> for DateTime {
    type Error = InvalidDateTime;
    fn try_from(s: &str) -> Result<Self, Self::Error> {
        parse_ocpi_datetime(s)
    }
}

impl Validate for DateTime {
    fn validate_in(&self, v: &mut Validator) {
        if !self.canonical {
            v.report(
                ViolationCode::Inconsistent,
                "timestamp was not written in one of the six forms OCPI allows \
                 (an explicit UTC offset, a lower-case 'z' or a space separator was used); \
                 note that the spec states \"+00:00 is not the same as UTC\"",
            );
        }
    }
}

impl Serialize for DateTime {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for DateTime {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct V;
        impl serde::de::Visitor<'_> for V {
            type Value = DateTime;
            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("an RFC 3339 UTC timestamp such as \"2015-06-29T20:39:09Z\"")
            }
            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<DateTime, E> {
                parse_ocpi_datetime(v).map_err(E::custom)
            }
        }
        deserializer.deserialize_str(V)
    }
}

#[cfg(feature = "schema")]
impl schemars::JsonSchema for DateTime {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "DateTime".into()
    }
    fn json_schema(_g: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({
            "type": "string",
            "format": "date-time",
            "maxLength": 25,
            "description": "OCPI DateTime: RFC 3339, always UTC",
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_all_six_spec_forms() {
        for (text, expect) in [
            ("2015-06-29T20:39:09Z", "2015-06-29T20:39:09Z"),
            ("2015-06-29T20:39:09", "2015-06-29T20:39:09Z"),
            ("2016-12-29T17:45:09.2Z", "2016-12-29T17:45:09.2Z"),
            ("2016-12-29T17:45:09.2", "2016-12-29T17:45:09.2Z"),
            ("2018-01-01T01:08:01.123Z", "2018-01-01T01:08:01.123Z"),
            ("2018-01-01T01:08:01.123", "2018-01-01T01:08:01.123Z"),
        ] {
            let dt: DateTime = text.parse().unwrap();
            assert!(dt.is_canonical(), "{text} should be canonical");
            assert_eq!(dt.to_string(), expect, "round-trip of {text}");
        }
    }

    #[test]
    fn explicit_offsets_are_converted_and_flagged() {
        let dt: DateTime = "2015-06-29T22:39:09+02:00".parse().unwrap();
        assert_eq!(dt.to_string(), "2015-06-29T20:39:09Z");
        assert!(!dt.is_canonical());
        let violations = dt.validate().unwrap_err();
        assert_eq!(violations.as_slice()[0].code, ViolationCode::Inconsistent);

        // The spec's own note: +00:00 is not the same as UTC.
        let zero: DateTime = "2015-06-29T20:39:09+00:00".parse().unwrap();
        assert_eq!(zero.to_string(), "2015-06-29T20:39:09Z");
        assert!(!zero.is_canonical());
    }

    #[test]
    fn equality_ignores_fractional_digit_count() {
        let a: DateTime = "2016-12-29T17:45:09.2Z".parse().unwrap();
        let b: DateTime = "2016-12-29T17:45:09.200Z".parse().unwrap();
        assert_eq!(a, b);
        assert_ne!(a.to_string(), b.to_string(), "but formatting is preserved");
    }

    #[test]
    fn rejects_nonsense() {
        for bad in [
            "",
            "2015-06-29",
            "not a date",
            "2015-13-01T00:00:00Z",
            "2015-06-29T25:00:00Z",
            "2015-06-29T20:39:09Zjunk",
        ] {
            assert!(bad.parse::<DateTime>().is_err(), "{bad} should not parse");
        }
    }

    #[test]
    fn an_over_long_fraction_is_truncated_and_flagged() {
        // Nine digits is all a nanosecond timestamp can hold, and `string(25)` cannot carry
        // them anyway; the instant survives, the deviation is reported.
        let dt: DateTime = "2018-01-01T01:08:01.1234567891234Z".parse().unwrap();
        assert_eq!(dt.fractional_digits(), 9);
        assert!(!dt.is_canonical());
        assert_eq!(dt.to_string(), "2018-01-01T01:08:01.123456789Z");

        let absurd = format!("2018-01-01T01:08:01.{}Z", "1".repeat(300));
        let dt: DateTime = absurd.parse().unwrap();
        assert!(!dt.is_canonical(), "300 fractional digits is not one of the six forms");
    }

    #[test]
    fn serde_round_trip() {
        let json = "\"2018-01-01T01:08:01.123Z\"";
        let dt: DateTime = serde_json::from_str(json).unwrap();
        assert_eq!(serde_json::to_string(&dt).unwrap(), json);
    }

    #[test]
    fn from_utc_picks_the_shortest_exact_fraction() {
        let base = OffsetDateTime::from_unix_timestamp(1_500_000_000).unwrap();
        assert_eq!(DateTime::from_utc(base).fractional_digits(), 0);
        let ms = base.replace_nanosecond(120_000_000).unwrap();
        assert_eq!(DateTime::from_utc(ms).fractional_digits(), 3);
        let us = base.replace_nanosecond(120_000_100).unwrap();
        assert_eq!(DateTime::from_utc(us).fractional_digits(), 9);
    }
}