ocpp-kit 0.5.0

Open Charge Point Protocol (OCPP 1.6J, 2.0.1, 2.1) toolkit for Rust: typed messages, OCPP-J framing, a sans-I/O protocol engine, and transports for charging stations, CSMS and local controllers.
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
//! An idempotent transaction ledger for the CSMS side.
//!
//! A Charging Station may legitimately send the same `TransactionEvent` twice: it timed out
//! waiting for the answer, retried, and the first copy arrived after all (1.6 §3.7.1 and the
//! 2.x `MessageAttempts` rules make this normal, not exceptional). A CSMS that treats the
//! second copy as a new event double-bills. `seqNo` is what makes deduplication possible,
//! and the same field makes it possible to *notice* that an offline period lost events
//! entirely.
//!
//! The ledger stores one record per `(charging station, transaction)` and answers three
//! questions: have I seen this event, am I missing any, and is this transaction still open.
//! It works the same for 1.6, where `StartTransaction` / `MeterValues` / `StopTransaction`
//! are folded into the same shape.
//!
//! # What the energy figures are, and are not
//!
//! [`Record::energy`] is the difference of the station's own start and stop registers,
//! computed exactly: the readings are [`Decimal`]s at the resolution the meter wrote, and the
//! subtraction is the one OCPP defines a session's energy as. Nothing here is rounded and
//! nothing goes through an `f64`, so the figure can be carried into an invoice without
//! having quietly lost exactness on the way.
//!
//! Exact is not the same as *authoritative*, and the distinction is worth keeping:
//!
//! * **The registers may not even be the quantity you want.** In the Open Charge Alliance's
//!   own example message a 1.6 `StopTransaction` reports `meterStop: 108814` — the meter's
//!   *lifetime* total in Wh — while the signed record beside it reports the transaction
//!   running `0.000 → 0.636` kWh. `energy` subtracts what the station reported, exactly;
//!   whether those two readings are the session's is the station's claim, not this ledger's.
//! * **It is what the station said**, over a transport with no integrity guarantee beyond
//!   TLS. Where calibration law requires the billable kWh to be traceable to the meter itself
//!   — Germany's Eichrecht, for one — the basis is the signed record, carried through as
//!   [`Record::signed`] and verified against the meter's public key obtained somewhere other
//!   than this socket. See [`crate::metering`].
//! * A gap ([`Ingested::AppliedWithGap`]) or an event after the end
//!   ([`Ingested::AfterEnd`]) says the record is incomplete, not that the energy is wrong —
//!   but a transaction that ends without a `Started` event has no start register, and
//!   `energy` returns `None` rather than guessing at one.
//!
//! That is why the figure is a [`RegisterDelta`] and not a bare [`Decimal`]: the number is
//! reached only through [`unverified_wh`](RegisterDelta::unverified_wh), which says what it
//! is at the call site, and it arrives together with the signed records a billing chain
//! settles on. Code that passes it straight to an invoice line has to write the word.
//!
//! # Surviving a restart
//!
//! The ledger is a deterministic fold over the events it was given, so durability is a
//! journal of those events: see [`DurableLedger`](super::ledger_store::DurableLedger).

use alloc::collections::{BTreeMap, BTreeSet};
use alloc::string::String;
use alloc::vec::Vec;

use serde::{Deserialize, Serialize};

use super::events::SignedReading;
use crate::types::{DateTime, Decimal, Identity};

/// Which phase of a transaction an event belongs to.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum EventKind {
    /// The transaction began.
    Started,
    /// Something changed during the transaction.
    Updated,
    /// The transaction finished.
    Ended,
}

/// A version-neutral transaction event.
///
/// 1.6 has no `seqNo`; use `0` for `StartTransaction`, increasing numbers for each
/// `MeterValues`, and the highest for `StopTransaction`, or let
/// [`Ledger::ingest_unsequenced`] assign them.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TransactionEvent {
    /// Which Charging Station sent it.
    pub identity: Identity,
    /// The transaction id.
    pub transaction_id: String,
    /// The EVSE the transaction is at, when the message named one.
    pub evse_id: Option<i32>,
    /// The connector, when the message named one. 1.6 names one on `StartTransaction` and on
    /// `MeterValues`, and none on `StopTransaction`.
    pub connector_id: Option<i32>,
    /// Its position in the transaction.
    pub seq_no: i32,
    /// Which phase it belongs to.
    pub kind: EventKind,
    /// When the station says it happened — not when it arrived.
    pub timestamp: DateTime,
    /// Whether the station was offline when it happened.
    pub offline: bool,
    /// The energy register, in Wh, if the event carried one — exactly as the meter stated
    /// it, trailing zeros and all.
    pub meter_wh: Option<Decimal>,
    /// Every signed meter value the event carried, in the order they arrived.
    ///
    /// Where calibration law applies this — not [`meter_wh`](Self::meter_wh) — is the
    /// billable value. See [`crate::metering`].
    pub signed: Vec<SignedReading>,
    /// The token that authorized the transaction.
    pub id_token: Option<String>,
    /// Why the transaction stopped, on an `Ended` event.
    pub stopped_reason: Option<String>,
}

impl TransactionEvent {
    /// A minimal event.
    #[must_use]
    pub fn new(
        identity: Identity,
        transaction_id: impl Into<String>,
        seq_no: i32,
        kind: EventKind,
        timestamp: DateTime,
    ) -> Self {
        Self {
            identity,
            transaction_id: transaction_id.into(),
            evse_id: None,
            connector_id: None,
            seq_no,
            kind,
            timestamp,
            offline: false,
            meter_wh: None,
            signed: Vec::new(),
            id_token: None,
            stopped_reason: None,
        }
    }

    /// Attaches the energy register, in Wh.
    ///
    /// Takes anything that converts into a [`Decimal`] — an integer, or a
    /// [`decimal!`](crate::decimal) literal. It deliberately does not take an `f64`: a
    /// register that has been through a float has already lost the resolution it claimed.
    #[must_use]
    pub fn with_meter(mut self, wh: impl Into<Decimal>) -> Self {
        self.meter_wh = Some(wh.into());
        self
    }

    /// Attaches a signed meter value.
    #[must_use]
    pub fn with_signed(mut self, signed: SignedReading) -> Self {
        self.signed.push(signed);
        self
    }

    /// Attaches the authorizing token.
    #[must_use]
    pub fn with_id_token(mut self, id_token: impl Into<String>) -> Self {
        self.id_token = Some(id_token.into());
        self
    }

    /// Marks the event as one that happened while the station was offline.
    #[must_use]
    pub fn offline(mut self) -> Self {
        self.offline = true;
        self
    }
}

/// What the ledger did with an event.
///
/// # Acting on it
///
/// This is the whole output of the ledger: the record it keeps is derived from these verdicts,
/// and only the caller can act on one. `Duplicate` and `AfterEnd` both mean *this message has
/// already been accounted for* — a station that lost the answer to its `StopTransaction` sends
/// it again, and OCPP requires it to. Billing the second copy settles a second record out of one
/// message, which on 1.6 produces a session that begins and ends at the same instant.
///
/// `AppliedWithGap` is not a refusal: the event is recorded, and `missing` names the `seqNo`s
/// that never arrived. A consumer that discards it bills a transaction with a hole in it.
///
/// The enum is `#[non_exhaustive]`, so a consumer has to decide what an unrecognised verdict
/// means rather than matching its way out of the question. Both directions cost something and
/// the right one depends on what is downstream: treating it as a refusal risks dropping energy
/// that was really delivered, and treating it as a fresh delivery risks a double-settlement
/// unless something further on deduplicates. `Applied`, `AppliedWithGap`, `Duplicate` and
/// `AfterEnd` keep the meanings documented here.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
#[must_use = "the ledger's verdict decides whether this message may be billed: `Duplicate` is a \
              retry of a message already accounted for, `AfterEnd` arrived after the transaction \
              closed, and `AppliedWithGap` names events that never arrived"]
pub enum Ingested {
    /// Recorded.
    Applied,
    /// Recorded, but sequence numbers are missing before it. Almost always an offline
    /// period whose queue overflowed, or a station that skipped a message after exhausting
    /// its retries.
    AppliedWithGap {
        /// The `seqNo`s that have never arrived.
        missing: Vec<i32>,
    },
    /// This exact `(station, transaction, seqNo)` has already been recorded. The station
    /// retried; do not bill it twice.
    Duplicate,
    /// The transaction had already ended when this arrived. Recorded, but flagged.
    AfterEnd,
}

/// One transaction, as the CSMS knows it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Record {
    /// Which Charging Station.
    pub identity: Identity,
    /// The transaction id.
    pub transaction_id: String,
    /// The EVSE the transaction is at, from the first event that named one.
    ///
    /// A CDR names the point the session happened at, and only some of a transaction's
    /// messages carry it: 1.6 puts a `connectorId` on `StartTransaction` and none on
    /// `StopTransaction`, and 2.x's `evse` is optional on every `TransactionEvent`. Keeping
    /// the first one seen spares a CSMS remembering it for the rest of the transaction.
    pub evse_id: Option<i32>,
    /// The connector, from the first event that named one. 1.6 has connectors and no EVSEs,
    /// so this is what it fills in.
    pub connector_id: Option<i32>,
    /// When it started, once a `Started` event has arrived.
    pub started_at: Option<DateTime>,
    /// When it ended.
    pub ended_at: Option<DateTime>,
    /// The token that authorized it.
    pub id_token: Option<String>,
    /// Why it stopped.
    pub stopped_reason: Option<String>,
    /// The reading the transaction started at.
    ///
    /// The `Started` event's, whenever one arrives — not merely the first reading seen. The
    /// two differ exactly when events arrive out of order, which is the case this ledger
    /// exists to survive.
    pub meter_start_wh: Option<Decimal>,
    /// The reading the transaction ended at.
    ///
    /// The `Ended` event's once it has arrived; before that, the latest reading seen. A
    /// straggling `Updated` that turns up afterwards does not overwrite it, or the billed
    /// energy would shrink — and could go negative — as late events landed.
    pub meter_stop_wh: Option<Decimal>,
    /// Every signed meter value the transaction's events carried, in arrival order.
    ///
    /// This is what a calibration-law billing chain settles on; the plain registers above are
    /// what the CSMS uses to operate. See the [module documentation](self).
    ///
    /// It is one list rather than a start and a stop because 1.6 does not give the two their
    /// own messages: a `StartTransaction` has nowhere to carry a signed record, so both the
    /// begin and the end record arrive together in `StopTransaction.transactionData`. Tell
    /// them apart with [`signed_with_context`](Self::signed_with_context).
    pub signed: Vec<SignedReading>,
    /// Whether any event was produced while the station was offline.
    pub had_offline_events: bool,
    seen: BTreeSet<i32>,
    /// `(kind, timestamp)` of every event taken through
    /// [`ingest_unsequenced`](Ledger::ingest_unsequenced), which is all 1.6 has to recognise
    /// a retry by.
    unsequenced: BTreeSet<(EventKind, DateTime)>,
    highest: i32,
}

impl Record {
    /// The `seqNo`s that have not arrived, below the highest one seen.
    #[must_use]
    pub fn missing(&self) -> Vec<i32> {
        (0..=self.highest)
            .filter(|seq| !self.seen.contains(seq))
            .collect()
    }

    /// Whether the transaction is still open.
    #[must_use]
    pub const fn is_open(&self) -> bool {
        self.ended_at.is_none()
    }

    /// How many events have been recorded.
    #[must_use]
    pub fn events(&self) -> usize {
        self.seen.len()
    }

    /// The signed meter values whose sample named `context` — `Transaction.Begin`,
    /// `Transaction.End`, and the rest of `ReadingContextEnumType`.
    ///
    /// The context is the sample's, not the signed record's own: an OCMF data set states its
    /// own begin/end marking inside the blob, and reading that is the consumer's business.
    pub fn signed_with_context<'a>(
        &'a self,
        context: &'a str,
    ) -> impl Iterator<Item = &'a SignedReading> {
        self.signed
            .iter()
            .filter(move |signed| signed.context.as_deref() == Some(context))
    }

    /// The difference of the stop and start registers, when both are known.
    ///
    /// Exact: the difference of two decimal registers, at the finer of their two scales. No
    /// rounding, no `f64`, and no drift of the kind that makes `10.1 - 0.1` come out as
    /// `10.000000000000002`. Negative if the stop register is below the start one — the meter
    /// was replaced or rolled over mid-transaction, a real condition the caller should see.
    ///
    /// A [`RegisterDelta`], not a number: read the [module documentation](self) for why.
    #[must_use]
    pub fn energy(&self) -> Option<RegisterDelta<'_>> {
        let wh = self.meter_stop_wh?.checked_sub(self.meter_start_wh?)?;
        Some(RegisterDelta {
            wh,
            signed: &self.signed,
        })
    }
}

/// The energy a transaction's registers say was delivered — telemetry, not a billable
/// quantity.
///
/// The figure is the difference of two readings the station reported over a link with no
/// integrity guarantee beyond TLS; where calibration law applies, the billable value is the
/// signed record, verified against the meter's own key. So the number is reachable only
/// through [`unverified_wh`](Self::unverified_wh) — the call site says what it is — and it
/// carries the [`signed`](Self::signed) records with it, so the two arrive together.
///
/// It converts into nothing, on purpose.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[must_use]
pub struct RegisterDelta<'a> {
    wh: Decimal,
    signed: &'a [SignedReading],
}

impl<'a> RegisterDelta<'a> {
    /// The register difference in Wh, exactly as the station's readings give it.
    ///
    /// Fit for operating a CSMS, for a dashboard, for a plausibility check against the signed
    /// records — not, by itself, for an invoice under calibration law.
    #[must_use]
    pub const fn unverified_wh(&self) -> Decimal {
        self.wh
    }

    /// The signed meter values the transaction's events carried — what a billing chain
    /// verifies and settles on.
    #[must_use]
    pub const fn signed(&self) -> &'a [SignedReading] {
        self.signed
    }

    /// Whether any signed record came with the transaction.
    #[must_use]
    pub const fn has_signed_records(&self) -> bool {
        !self.signed.is_empty()
    }
}

impl core::fmt::Display for RegisterDelta<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{} Wh (unverified register delta)", self.wh)
    }
}

/// The ledger.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Ledger {
    records: BTreeMap<(Identity, String), Record>,
    next_seq: BTreeMap<(Identity, String), i32>,
}

/// The whole state of a [`Ledger`], in a form `serde` can write anywhere — JSON included,
/// which has no tuple keys. What a [`LedgerStore`](super::ledger_store::LedgerStore)
/// checkpoints.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct LedgerSnapshot {
    records: Vec<Record>,
    next_seq: Vec<(Identity, String, i32)>,
}

impl Ledger {
    /// An empty ledger.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// The ledger's whole state.
    #[must_use]
    pub fn snapshot(&self) -> LedgerSnapshot {
        LedgerSnapshot {
            records: self.records.values().cloned().collect(),
            next_seq: self
                .next_seq
                .iter()
                .map(|((identity, transaction), seq)| (identity.clone(), transaction.clone(), *seq))
                .collect(),
        }
    }

    /// Rebuilds a ledger from a [`snapshot`](Self::snapshot).
    #[must_use]
    pub fn from_snapshot(snapshot: LedgerSnapshot) -> Self {
        Self {
            records: snapshot
                .records
                .into_iter()
                .map(|record| {
                    (
                        (record.identity.clone(), record.transaction_id.clone()),
                        record,
                    )
                })
                .collect(),
            next_seq: snapshot
                .next_seq
                .into_iter()
                .map(|(identity, transaction, seq)| ((identity, transaction), seq))
                .collect(),
        }
    }

    /// Whether [`ingest`](Self::ingest) would answer [`Ingested::Duplicate`], without
    /// recording anything.
    #[must_use]
    pub fn is_duplicate(&self, event: &TransactionEvent) -> bool {
        self.records
            .get(&(event.identity.clone(), event.transaction_id.clone()))
            .is_some_and(|record| record.seen.contains(&event.seq_no))
    }

    /// Whether [`ingest_unsequenced`](Self::ingest_unsequenced) would answer
    /// [`Ingested::Duplicate`], without recording anything.
    #[must_use]
    pub fn is_duplicate_unsequenced(&self, event: &TransactionEvent) -> bool {
        self.records
            .get(&(event.identity.clone(), event.transaction_id.clone()))
            .is_some_and(|record| record.unsequenced.contains(&(event.kind, event.timestamp)))
    }

    /// Records one event, deduplicating on `(station, transaction, seqNo)`.
    pub fn ingest(&mut self, event: &TransactionEvent) -> Ingested {
        let key = (event.identity.clone(), event.transaction_id.clone());
        let record = self.records.entry(key).or_insert_with(|| Record {
            identity: event.identity.clone(),
            transaction_id: event.transaction_id.clone(),
            evse_id: None,
            connector_id: None,
            started_at: None,
            ended_at: None,
            id_token: None,
            stopped_reason: None,
            meter_start_wh: None,
            meter_stop_wh: None,
            signed: Vec::new(),
            had_offline_events: false,
            seen: BTreeSet::new(),
            unsequenced: BTreeSet::new(),
            highest: -1,
        });

        if record.seen.contains(&event.seq_no) {
            return Ingested::Duplicate;
        }
        let after_end = record.ended_at.is_some();

        record.seen.insert(event.seq_no);
        record.highest = record.highest.max(event.seq_no);
        record.had_offline_events |= event.offline;
        // First one seen wins: a transaction happens at one point, and not every message
        // names it.
        if record.evse_id.is_none() {
            record.evse_id = event.evse_id;
        }
        if record.connector_id.is_none() {
            record.connector_id = event.connector_id;
        }
        // Kept whatever the event's kind and whenever it arrives: a signed record is the
        // billable value and there is no version of "too late" that makes it not one. The
        // duplicate check above is what stops a retry appending it twice.
        record.signed.extend(event.signed.iter().cloned());
        if let Some(token) = &event.id_token {
            record.id_token.get_or_insert_with(|| token.clone());
        }
        if let Some(wh) = event.meter_wh {
            // `Started` and `Ended` are authoritative for their own end of the transaction;
            // an `Updated` only fills a gap neither has filled. Letting an `Updated` overwrite
            // either would make the billed energy depend on arrival order, and a straggler
            // after the `Ended` could make it negative.
            match event.kind {
                EventKind::Started => record.meter_start_wh = Some(wh),
                EventKind::Ended => record.meter_stop_wh = Some(wh),
                EventKind::Updated => {
                    if record.meter_start_wh.is_none() {
                        record.meter_start_wh = Some(wh);
                    }
                    if !after_end {
                        record.meter_stop_wh = Some(wh);
                    }
                }
            }
        }
        match event.kind {
            EventKind::Started => record.started_at = Some(event.timestamp),
            EventKind::Ended => {
                record.ended_at = Some(event.timestamp);
                record.stopped_reason.clone_from(&event.stopped_reason);
            }
            EventKind::Updated => {}
        }

        if after_end {
            return Ingested::AfterEnd;
        }
        let missing = record.missing();
        if missing.is_empty() {
            Ingested::Applied
        } else {
            Ingested::AppliedWithGap { missing }
        }
    }

    /// Records an event for a version that has no `seqNo` — OCPP 1.6 — assigning the next
    /// number for the transaction.
    ///
    /// Deduplication then falls back to `(station, transaction, kind, timestamp)`, which is
    /// what 1.6 gives us to work with. It applies to a `MeterValues` retry exactly as it does
    /// to a re-sent `StartTransaction`: 1.6 messages carry no identity of their own, so two
    /// readings of the same kind bearing the same instant are one reading sent twice. A
    /// station that genuinely samples twice within the same second reports the same second,
    /// and a ledger that counted both would count a retry too.
    pub fn ingest_unsequenced(&mut self, event: &TransactionEvent) -> Ingested {
        let key = (event.identity.clone(), event.transaction_id.clone());
        let mark = (event.kind, event.timestamp);
        if self
            .records
            .get(&key)
            .is_some_and(|record| record.unsequenced.contains(&mark))
        {
            return Ingested::Duplicate;
        }
        let seq = self.next_seq.entry(key.clone()).or_insert(0);
        let mut event = event.clone();
        event.seq_no = *seq;
        *seq += 1;
        let outcome = self.ingest(&event);
        if let Some(record) = self.records.get_mut(&key) {
            record.unsequenced.insert(mark);
        }
        outcome
    }

    /// Looks a transaction up.
    #[must_use]
    pub fn transaction(&self, identity: &Identity, transaction_id: &str) -> Option<&Record> {
        self.records.get(&(identity.clone(), transaction_id.into()))
    }

    /// Every transaction still open for one station.
    pub fn open(&self, identity: &Identity) -> impl Iterator<Item = &Record> {
        self.records
            .values()
            .filter(move |record| &record.identity == identity && record.is_open())
    }

    /// Every transaction with missing sequence numbers, across all stations.
    pub fn incomplete(&self) -> impl Iterator<Item = (&Record, Vec<i32>)> {
        self.records.values().filter_map(|record| {
            let missing = record.missing();
            (!missing.is_empty()).then_some((record, missing))
        })
    }

    /// How many transactions are recorded.
    #[must_use]
    pub fn len(&self) -> usize {
        self.records.len()
    }

    /// Whether the ledger is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.records.is_empty()
    }

    /// Forgets transactions that ended before `cutoff`, for a CSMS that archives elsewhere.
    pub fn prune_ended_before(&mut self, cutoff: DateTime) -> usize {
        let before = self.records.len();
        self.records
            .retain(|_, record| record.ended_at.is_none_or(|ended| ended >= cutoff));
        before - self.records.len()
    }
}

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

    fn station() -> Identity {
        Identity::new("CS-0001").unwrap()
    }

    fn at(seconds: i64) -> DateTime {
        DateTime::from_timestamp(jiff::Timestamp::from_second(1_700_000_000 + seconds).unwrap())
    }

    fn event(seq: i32, kind: EventKind) -> TransactionEvent {
        TransactionEvent::new(station(), "tx-1", seq, kind, at(i64::from(seq)))
    }

    #[test]
    fn a_retried_event_is_recognised_rather_than_billed_twice() {
        let mut ledger = Ledger::new();
        assert_eq!(
            ledger.ingest(&event(0, EventKind::Started)),
            Ingested::Applied
        );
        assert_eq!(
            ledger.ingest(&event(1, EventKind::Updated)),
            Ingested::Applied
        );
        // The station timed out and re-sent seqNo 1.
        assert_eq!(
            ledger.ingest(&event(1, EventKind::Updated)),
            Ingested::Duplicate
        );
        assert_eq!(ledger.transaction(&station(), "tx-1").unwrap().events(), 2);
    }

    #[test]
    fn a_gap_is_reported_and_closes_when_the_missing_event_arrives() {
        let mut ledger = Ledger::new();
        let _ = ledger.ingest(&event(0, EventKind::Started));
        assert_eq!(
            ledger.ingest(&event(3, EventKind::Updated)),
            Ingested::AppliedWithGap {
                missing: alloc::vec![1, 2]
            }
        );
        assert_eq!(ledger.incomplete().count(), 1);

        let _ = ledger.ingest(&event(1, EventKind::Updated));
        assert_eq!(
            ledger.ingest(&event(2, EventKind::Updated)),
            Ingested::Applied,
            "the gap has closed"
        );
        assert_eq!(ledger.incomplete().count(), 0);
    }

    #[test]
    fn a_transaction_records_its_energy_and_its_reason() {
        let mut ledger = Ledger::new();
        let _ = ledger.ingest(
            &event(0, EventKind::Started)
                .with_meter(decimal!(1000.0))
                .with_id_token("CARD-1"),
        );
        let _ = ledger.ingest(
            &event(1, EventKind::Updated)
                .with_meter(decimal!(4500.0))
                .offline(),
        );
        let mut ended = event(2, EventKind::Ended).with_meter(decimal!(7300.0));
        ended.stopped_reason = Some("EVDisconnected".into());
        let _ = ledger.ingest(&ended);

        let record = ledger.transaction(&station(), "tx-1").unwrap();
        assert!(!record.is_open());
        assert_eq!(
            record.energy().map(|e| e.unverified_wh()),
            Some(decimal!(6300))
        );
        assert_eq!(record.id_token.as_deref(), Some("CARD-1"));
        assert_eq!(record.stopped_reason.as_deref(), Some("EVDisconnected"));
        assert!(record.had_offline_events);
        assert_eq!(ledger.open(&station()).count(), 0);
    }

    #[test]
    fn an_event_after_the_end_is_flagged_but_not_lost() {
        let mut ledger = Ledger::new();
        let _ = ledger.ingest(&event(0, EventKind::Started));
        let _ = ledger.ingest(&event(1, EventKind::Ended));
        assert_eq!(
            ledger.ingest(&event(2, EventKind::Updated)),
            Ingested::AfterEnd
        );
        assert_eq!(ledger.transaction(&station(), "tx-1").unwrap().events(), 3);
    }

    #[test]
    fn ocpp_16_transactions_are_sequenced_by_the_ledger() {
        let mut ledger = Ledger::new();
        let start = TransactionEvent::new(station(), "42", 0, EventKind::Started, at(0))
            .with_meter(decimal!(100.0));
        assert_eq!(ledger.ingest_unsequenced(&start), Ingested::Applied);
        // 1.6 has no seqNo, so a re-sent StartTransaction is caught by its timestamp.
        assert_eq!(ledger.ingest_unsequenced(&start), Ingested::Duplicate);

        let meter = TransactionEvent::new(station(), "42", 0, EventKind::Updated, at(60))
            .with_meter(decimal!(2100.0));
        assert_eq!(ledger.ingest_unsequenced(&meter), Ingested::Applied);
        let stop = TransactionEvent::new(station(), "42", 0, EventKind::Ended, at(120))
            .with_meter(decimal!(3400.0));
        assert_eq!(ledger.ingest_unsequenced(&stop), Ingested::Applied);

        let record = ledger.transaction(&station(), "42").unwrap();
        assert_eq!(
            record.energy().map(|e| e.unverified_wh()),
            Some(decimal!(3300))
        );
        assert!(record.missing().is_empty(), "{:?}", record.missing());
    }

    /// Out-of-order delivery is the case this ledger exists to survive, so the billed energy
    /// must not depend on the order the events happen to arrive in. Both halves of this
    /// failed before: an `Updated` that arrived first became the start reading and kept it
    /// when the real `Started` turned up, and a straggling `Updated` overwrote the stop
    /// reading after the `Ended` had set it.
    #[test]
    fn meter_readings_come_from_started_and_ended_whatever_the_arrival_order() {
        let mut ledger = Ledger::new();

        // The periodic meter value overtakes the transaction's own start.
        let _ = ledger.ingest(
            &TransactionEvent::new(station(), "tx-1", 1, EventKind::Updated, at(60))
                .with_meter(decimal!(2100.0)),
        );
        let _ = ledger.ingest(
            &TransactionEvent::new(station(), "tx-1", 0, EventKind::Started, at(0))
                .with_meter(decimal!(1000.0)),
        );
        let _ = ledger.ingest(
            &TransactionEvent::new(station(), "tx-1", 2, EventKind::Ended, at(120))
                .with_meter(decimal!(3400.0)),
        );
        // And one more straggler lands after the transaction has already ended.
        let _ = ledger.ingest(
            &TransactionEvent::new(station(), "tx-1", 3, EventKind::Updated, at(90))
                .with_meter(decimal!(2800.0)),
        );

        let record = ledger.transaction(&station(), "tx-1").unwrap();
        assert_eq!(record.meter_start_wh, Some(decimal!(1000)));
        assert_eq!(record.meter_stop_wh, Some(decimal!(3400)));
        assert_eq!(
            record.energy().map(|e| e.unverified_wh()),
            Some(decimal!(2400))
        );
    }

    /// 1.6 messages carry no identity of their own, so a retried `MeterValues` is recognised
    /// only by its kind and its instant. Counting it twice appends the same signed record
    /// twice — which is the one thing this ledger exists to stop.
    #[test]
    fn a_retried_16_meter_values_is_recognised_like_any_other_retry() {
        let mut ledger = Ledger::new();
        let start = TransactionEvent::new(station(), "42", 0, EventKind::Started, at(0));
        assert_eq!(ledger.ingest_unsequenced(&start), Ingested::Applied);

        let periodic = TransactionEvent::new(station(), "42", 0, EventKind::Updated, at(60))
            .with_meter(decimal!(2100));
        assert_eq!(ledger.ingest_unsequenced(&periodic), Ingested::Applied);
        assert_eq!(ledger.ingest_unsequenced(&periodic), Ingested::Duplicate);

        // A later reading is a different instant and goes in.
        let later = TransactionEvent::new(station(), "42", 0, EventKind::Updated, at(120))
            .with_meter(decimal!(2600));
        assert_eq!(ledger.ingest_unsequenced(&later), Ingested::Applied);

        let record = ledger.transaction(&station(), "42").unwrap();
        assert_eq!(
            record.events(),
            3,
            "the retry did not become a fourth event"
        );
        assert!(record.missing().is_empty(), "{:?}", record.missing());
    }

    #[test]
    fn pruning_keeps_open_transactions() {
        let mut ledger = Ledger::new();
        let _ = ledger.ingest(&event(0, EventKind::Started));
        let _ = ledger.ingest(&event(1, EventKind::Ended));
        let mut other = event(0, EventKind::Started);
        other.transaction_id = "tx-2".into();
        let _ = ledger.ingest(&other);

        assert_eq!(ledger.prune_ended_before(at(1000)), 1);
        assert_eq!(ledger.len(), 1);
        assert!(ledger.transaction(&station(), "tx-2").is_some());
    }
}