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};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum EventKind {
Started,
Updated,
Ended,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TransactionEvent {
pub identity: Identity,
pub transaction_id: String,
pub evse_id: Option<i32>,
pub connector_id: Option<i32>,
pub seq_no: i32,
pub kind: EventKind,
pub timestamp: DateTime,
pub offline: bool,
pub meter_wh: Option<Decimal>,
pub signed: Vec<SignedReading>,
pub id_token: Option<String>,
pub stopped_reason: Option<String>,
}
impl TransactionEvent {
#[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,
}
}
#[must_use]
pub fn with_meter(mut self, wh: impl Into<Decimal>) -> Self {
self.meter_wh = Some(wh.into());
self
}
#[must_use]
pub fn with_signed(mut self, signed: SignedReading) -> Self {
self.signed.push(signed);
self
}
#[must_use]
pub fn with_id_token(mut self, id_token: impl Into<String>) -> Self {
self.id_token = Some(id_token.into());
self
}
#[must_use]
pub fn offline(mut self) -> Self {
self.offline = true;
self
}
}
#[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 {
Applied,
AppliedWithGap {
missing: Vec<i32>,
},
Duplicate,
AfterEnd,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Record {
pub identity: Identity,
pub transaction_id: String,
pub evse_id: Option<i32>,
pub connector_id: Option<i32>,
pub started_at: Option<DateTime>,
pub ended_at: Option<DateTime>,
pub id_token: Option<String>,
pub stopped_reason: Option<String>,
pub meter_start_wh: Option<Decimal>,
pub meter_stop_wh: Option<Decimal>,
pub signed: Vec<SignedReading>,
pub had_offline_events: bool,
seen: BTreeSet<i32>,
unsequenced: BTreeSet<(EventKind, DateTime)>,
highest: i32,
}
impl Record {
#[must_use]
pub fn missing(&self) -> Vec<i32> {
(0..=self.highest)
.filter(|seq| !self.seen.contains(seq))
.collect()
}
#[must_use]
pub const fn is_open(&self) -> bool {
self.ended_at.is_none()
}
#[must_use]
pub fn events(&self) -> usize {
self.seen.len()
}
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))
}
#[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,
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[must_use]
pub struct RegisterDelta<'a> {
wh: Decimal,
signed: &'a [SignedReading],
}
impl<'a> RegisterDelta<'a> {
#[must_use]
pub const fn unverified_wh(&self) -> Decimal {
self.wh
}
#[must_use]
pub const fn signed(&self) -> &'a [SignedReading] {
self.signed
}
#[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)
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Ledger {
records: BTreeMap<(Identity, String), Record>,
next_seq: BTreeMap<(Identity, String), i32>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct LedgerSnapshot {
records: Vec<Record>,
next_seq: Vec<(Identity, String, i32)>,
}
impl Ledger {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[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(),
}
}
#[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(),
}
}
#[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))
}
#[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)))
}
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;
if record.evse_id.is_none() {
record.evse_id = event.evse_id;
}
if record.connector_id.is_none() {
record.connector_id = event.connector_id;
}
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 {
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 }
}
}
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
}
#[must_use]
pub fn transaction(&self, identity: &Identity, transaction_id: &str) -> Option<&Record> {
self.records.get(&(identity.clone(), transaction_id.into()))
}
pub fn open(&self, identity: &Identity) -> impl Iterator<Item = &Record> {
self.records
.values()
.filter(move |record| &record.identity == identity && record.is_open())
}
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))
})
}
#[must_use]
pub fn len(&self) -> usize {
self.records.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.records.is_empty()
}
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
);
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);
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());
}
#[test]
fn meter_readings_come_from_started_and_ended_whatever_the_arrival_order() {
let mut ledger = Ledger::new();
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)),
);
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))
);
}
#[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);
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());
}
}