use alloc::collections::{BTreeMap, BTreeSet};
use alloc::string::String;
use alloc::vec::Vec;
use crate::types::{DateTime, Identity};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum EventKind {
Started,
Updated,
Ended,
}
#[derive(Clone, Debug, PartialEq)]
pub struct TransactionEvent {
pub identity: Identity,
pub transaction_id: String,
pub seq_no: i32,
pub kind: EventKind,
pub timestamp: DateTime,
pub offline: bool,
pub meter_wh: Option<f64>,
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(),
seq_no,
kind,
timestamp,
offline: false,
meter_wh: None,
id_token: None,
stopped_reason: None,
}
}
#[must_use]
pub fn with_meter(mut self, wh: f64) -> Self {
self.meter_wh = Some(wh);
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]
pub enum Ingested {
Applied,
AppliedWithGap {
missing: Vec<i32>,
},
Duplicate,
AfterEnd,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Record {
pub identity: Identity,
pub transaction_id: String,
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<f64>,
pub meter_stop_wh: Option<f64>,
pub had_offline_events: bool,
seen: BTreeSet<i32>,
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()
}
#[must_use]
pub fn energy_wh(&self) -> Option<f64> {
match (self.meter_start_wh, self.meter_stop_wh) {
(Some(start), Some(stop)) => Some(stop - start),
_ => None,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct Ledger {
records: BTreeMap<(Identity, String), Record>,
next_seq: BTreeMap<(Identity, String), i32>,
}
impl Ledger {
#[must_use]
pub fn new() -> Self {
Self::default()
}
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(),
started_at: None,
ended_at: None,
id_token: None,
stopped_reason: None,
meter_start_wh: None,
meter_stop_wh: None,
had_offline_events: false,
seen: 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 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());
if let Some(record) = self.records.get(&key) {
let duplicate = match event.kind {
EventKind::Started => record.started_at == Some(event.timestamp),
EventKind::Ended => record.ended_at == Some(event.timestamp),
EventKind::Updated => false,
};
if duplicate {
return Ingested::Duplicate;
}
}
let seq = self.next_seq.entry(key).or_insert(0);
let mut event = event.clone();
event.seq_no = *seq;
*seq += 1;
self.ingest(&event)
}
#[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::*;
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();
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);
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();
ledger.ingest(
&event(0, EventKind::Started)
.with_meter(1000.0)
.with_id_token("CARD-1"),
);
ledger.ingest(&event(1, EventKind::Updated).with_meter(4500.0).offline());
let mut ended = event(2, EventKind::Ended).with_meter(7300.0);
ended.stopped_reason = Some("EVDisconnected".into());
ledger.ingest(&ended);
let record = ledger.transaction(&station(), "tx-1").unwrap();
assert!(!record.is_open());
assert_eq!(record.energy_wh(), Some(6300.0));
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();
ledger.ingest(&event(0, EventKind::Started));
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(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(2100.0);
assert_eq!(ledger.ingest_unsequenced(&meter), Ingested::Applied);
let stop =
TransactionEvent::new(station(), "42", 0, EventKind::Ended, at(120)).with_meter(3400.0);
assert_eq!(ledger.ingest_unsequenced(&stop), Ingested::Applied);
let record = ledger.transaction(&station(), "42").unwrap();
assert_eq!(record.energy_wh(), Some(3300.0));
assert!(record.missing().is_empty());
}
#[test]
fn meter_readings_come_from_started_and_ended_whatever_the_arrival_order() {
let mut ledger = Ledger::new();
ledger.ingest(
&TransactionEvent::new(station(), "tx-1", 1, EventKind::Updated, at(60))
.with_meter(2100.0),
);
ledger.ingest(
&TransactionEvent::new(station(), "tx-1", 0, EventKind::Started, at(0))
.with_meter(1000.0),
);
ledger.ingest(
&TransactionEvent::new(station(), "tx-1", 2, EventKind::Ended, at(120))
.with_meter(3400.0),
);
ledger.ingest(
&TransactionEvent::new(station(), "tx-1", 3, EventKind::Updated, at(90))
.with_meter(2800.0),
);
let record = ledger.transaction(&station(), "tx-1").unwrap();
assert_eq!(record.meter_start_wh, Some(1000.0));
assert_eq!(record.meter_stop_wh, Some(3400.0));
assert_eq!(record.energy_wh(), Some(2400.0));
}
#[test]
fn pruning_keeps_open_transactions() {
let mut ledger = Ledger::new();
ledger.ingest(&event(0, EventKind::Started));
ledger.ingest(&event(1, EventKind::Ended));
let mut other = event(0, EventKind::Started);
other.transaction_id = "tx-2".into();
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());
}
}