use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;
use ocpp_kit::engine::{
Engine, EngineConfig, Input, Instant, MessageStore, Output, QueuedCall, Role, Seq, StoreError,
};
use ocpp_kit::message::MessageKind;
use ocpp_kit::{RawValue, Version};
use rusqlite::{Connection, TransactionBehavior, params};
const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
const SCHEMA: &str = "
CREATE TABLE IF NOT EXISTS outbox (
seq INTEGER PRIMARY KEY AUTOINCREMENT,
action TEXT NOT NULL,
payload TEXT NOT NULL,
kind TEXT NOT NULL CHECK (kind IN ('call', 'send')),
attempts INTEGER NOT NULL CHECK (attempts >= 0),
transactional INTEGER NOT NULL CHECK (transactional IN (0, 1))
) STRICT;
";
#[allow(clippy::needless_pass_by_value)]
fn db(error: rusqlite::Error) -> StoreError {
StoreError::new(format!("sqlite: {error}"))
}
fn connect(path: &Path) -> Result<Connection, StoreError> {
let mut conn = Connection::open(path).map_err(db)?;
conn.busy_timeout(BUSY_TIMEOUT).map_err(db)?;
let mode: String = conn
.query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0))
.map_err(db)?;
if !mode.eq_ignore_ascii_case("wal") {
return Err(StoreError::new(format!(
"{} cannot use WAL (got journal_mode = {mode})",
path.display()
)));
}
conn.pragma_update(None, "synchronous", "FULL")
.map_err(db)?;
let tx = conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(db)?;
tx.execute_batch(SCHEMA).map_err(db)?;
tx.commit().map_err(db)?;
Ok(conn)
}
fn insert(conn: &mut Connection, entry: &QueuedCall) -> Result<Seq, StoreError> {
let kind = match entry.kind {
MessageKind::Call => "call",
MessageKind::Send => "send",
};
let tx = conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(db)?;
let seq: i64 = tx
.query_row(
"INSERT INTO outbox (action, payload, kind, attempts, transactional)
VALUES (?1, ?2, ?3, ?4, ?5) RETURNING seq",
params![
entry.action,
entry.payload.get(),
kind,
entry.attempts,
entry.transactional
],
|row| row.get(0),
)
.map_err(db)?;
tx.commit().map_err(db)?;
Seq::try_from(seq).map_err(|_| StoreError::new(format!("negative seq {seq}")))
}
pub struct SqliteStore {
conn: Connection,
}
impl SqliteStore {
pub fn open(path: impl AsRef<Path>) -> Result<Self, StoreError> {
Ok(Self {
conn: connect(path.as_ref())?,
})
}
fn write(&mut self, sql: &str, args: impl rusqlite::Params) -> Result<(), StoreError> {
let tx = self
.conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(db)?;
tx.execute(sql, args).map_err(db)?;
tx.commit().map_err(db)
}
}
impl MessageStore for SqliteStore {
fn push(&mut self, entry: &QueuedCall) -> Result<Seq, StoreError> {
insert(&mut self.conn, entry)
}
fn pending(&self) -> Result<Vec<(Seq, QueuedCall)>, StoreError> {
let mut statement = self
.conn
.prepare(
"SELECT seq, action, payload, kind, attempts, transactional
FROM outbox ORDER BY seq",
)
.map_err(db)?;
let rows = statement
.query_map([], |row| {
Ok((
row.get::<_, i64>(0)?,
row.get::<_, String>(1)?,
row.get::<_, String>(2)?,
row.get::<_, String>(3)?,
row.get::<_, u32>(4)?,
row.get::<_, bool>(5)?,
))
})
.map_err(db)?;
let mut pending = Vec::new();
for row in rows {
let (seq, action, payload, kind, attempts, transactional) = row.map_err(db)?;
let seq = Seq::try_from(seq).map_err(|_| StoreError::new("negative seq"))?;
let payload = RawValue::from_string(payload).map_err(|error| {
StoreError::new(format!("stored payload {seq} is not JSON: {error}"))
})?;
let kind = match kind.as_str() {
"call" => MessageKind::Call,
"send" => MessageKind::Send,
other => return Err(StoreError::new(format!("stored kind {other:?}"))),
};
pending.push((
seq,
QueuedCall {
action,
payload,
kind,
attempts,
transactional,
},
));
}
Ok(pending)
}
fn ack(&mut self, seq: Seq) -> Result<(), StoreError> {
self.write(
"DELETE FROM outbox WHERE seq = ?1",
params![seq_param(seq)?],
)
}
fn set_attempts(&mut self, seq: Seq, attempts: u32) -> Result<(), StoreError> {
self.write(
"UPDATE outbox SET attempts = ?2 WHERE seq = ?1",
params![seq_param(seq)?, attempts],
)
}
fn len(&self) -> Result<usize, StoreError> {
let count: i64 = self
.conn
.query_row("SELECT COUNT(*) FROM outbox", [], |row| row.get(0))
.map_err(db)?;
usize::try_from(count).map_err(|_| StoreError::new(format!("row count {count}")))
}
}
fn seq_param(seq: Seq) -> Result<i64, StoreError> {
i64::try_from(seq).map_err(|_| StoreError::new(format!("seq {seq} out of range")))
}
pub struct Producer {
conn: Connection,
}
impl Producer {
pub fn open(path: impl AsRef<Path>) -> Result<Self, StoreError> {
Ok(Self {
conn: connect(path.as_ref())?,
})
}
pub fn push(&mut self, entry: &QueuedCall) -> Result<Seq, StoreError> {
insert(&mut self.conn, entry)
}
}
const PER_PRODUCER: u32 = 50;
const DELIVERED_BEFORE_CRASH: usize = 30;
const PUSH_PACE: Duration = Duration::from_millis(2);
fn transaction_event(transaction_id: &str, seq_no: u32) -> QueuedCall {
let payload = format!(
r#"{{"eventType":"Updated","timestamp":"2026-11-07T12:00:00Z","triggerReason":"MeterValuePeriodic","seqNo":{seq_no},"transactionInfo":{{"transactionId":"{transaction_id}"}}}}"#
);
QueuedCall {
action: "TransactionEvent".into(),
payload: RawValue::from_string(payload).expect("valid JSON"),
kind: MessageKind::Call,
attempts: 0,
transactional: true,
}
}
fn parse_call(frame: &str) -> (String, String, u32) {
let (kind, id, action, payload): (u8, String, String, serde_json::Value) =
serde_json::from_str(frame).expect("a CALL frame");
assert_eq!((kind, action.as_str()), (2, "TransactionEvent"));
let transaction = payload["transactionInfo"]["transactionId"]
.as_str()
.expect("transactionId")
.to_owned();
let seq_no = u32::try_from(payload["seqNo"].as_u64().expect("seqNo")).expect("u32");
(id, transaction, seq_no)
}
fn boot_station(path: &Path) -> Result<Engine<SqliteStore>, Box<dyn std::error::Error>> {
let mut engine = Engine::with_store(
EngineConfig::new(Role::ChargingStation, Version::V2_1),
SqliteStore::open(path)?,
)?;
engine.handle(
Instant::ZERO,
Input::Connected {
version: Version::V2_1,
},
);
engine.call(
Instant::ZERO,
"BootNotification",
RawValue::from_string(
r#"{"reason":"PowerUp","chargingStation":{"model":"M","vendorName":"V"}}"#.into(),
)?,
)?;
let boot_id = next_frame(&mut engine).expect("BootNotification is sent");
let (_, boot_id, _, _): (u8, String, String, serde_json::Value) =
serde_json::from_str(&boot_id)?;
engine.handle(
Instant::ZERO,
Input::Received(&format!(
r#"[3,"{boot_id}",{{"currentTime":"2026-11-07T12:00:00Z","interval":300,"status":"Accepted"}}]"#
)),
);
Ok(engine)
}
fn next_frame<S: MessageStore>(engine: &mut Engine<S>) -> Option<String> {
engine.drain().into_iter().find_map(|output| match output {
Output::Transmit(frame) => Some(frame),
_ => None,
})
}
fn produce(path: &Path, transaction_id: &str) -> Result<(), StoreError> {
let mut queue = Producer::open(path)?;
for seq_no in 0..PER_PRODUCER {
queue.push(&transaction_event(transaction_id, seq_no))?;
std::thread::sleep(PUSH_PACE);
}
Ok(())
}
fn remove_database(path: &Path) {
for suffix in ["", "-wal", "-shm"] {
let mut file = path.as_os_str().to_owned();
file.push(suffix);
let _ = std::fs::remove_file(PathBuf::from(file));
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = std::env::args().collect();
if let [_, role, path] = args.as_slice() {
if role == "--metering-daemon" {
produce(Path::new(path), "tx-meter")?;
return Ok(());
}
}
let path =
std::env::temp_dir().join(format!("ocpp-kit-sqlite-store-{}.db", std::process::id()));
remove_database(&path);
let result = run(&path);
remove_database(&path);
result
}
fn run(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
connect(path)?; let mut daemon = Command::new(std::env::current_exe()?)
.arg("--metering-daemon")
.arg(path)
.spawn()?;
let mut station_store = SqliteStore::open(path)?;
for seq_no in 0..PER_PRODUCER {
station_store.push(&transaction_event("tx-station", seq_no))?;
std::thread::sleep(PUSH_PACE);
}
assert!(daemon.wait()?.success(), "the metering daemon failed");
drop(station_store);
let total = usize::try_from(2 * PER_PRODUCER)?;
let queued = SqliteStore::open(path)?.pending()?;
assert_eq!(
queued.len(),
total,
"every push from both processes is queued once"
);
let order: Vec<(String, u32)> = queued
.iter()
.map(|(_, entry)| {
let (_, transaction, seq_no) = parse_call(&format!(
r#"[2,"x","TransactionEvent",{}]"#,
entry.payload.get()
));
(transaction, seq_no)
})
.collect();
for producer in ["tx-station", "tx-meter"] {
let seq_nos: Vec<u32> = order
.iter()
.filter(|(transaction, _)| transaction == producer)
.map(|(_, seq_no)| *seq_no)
.collect();
assert_eq!(
seq_nos,
(0..PER_PRODUCER).collect::<Vec<_>>(),
"{producer}'s messages keep the order it queued them in"
);
}
let interleaved = order.windows(2).filter(|w| w[0].0 != w[1].0).count();
println!("queued {total} messages from two processes ({interleaved} hand-overs between them)");
let mut delivered: Vec<(String, u32)> = Vec::new();
let mut engine = boot_station(path)?;
assert_eq!(engine.store().len()?, total);
let in_flight = loop {
let frame = next_frame(&mut engine).expect("the queue is not empty yet");
let (id, transaction, seq_no) = parse_call(&frame);
if delivered.len() == DELIVERED_BEFORE_CRASH {
break (transaction, seq_no);
}
delivered.push((transaction, seq_no));
engine.handle(
Instant::ZERO,
Input::Received(&format!(r#"[3,"{id}",{{}}]"#)),
);
};
drop(engine); println!(
"delivered {DELIVERED_BEFORE_CRASH}, then crashed with {} {} in flight",
in_flight.0, in_flight.1
);
let mut engine = boot_station(path)?;
assert_eq!(engine.store().len()?, total - DELIVERED_BEFORE_CRASH);
let mut first_after_reboot = None;
while let Some(frame) = next_frame(&mut engine) {
let (id, transaction, seq_no) = parse_call(&frame);
first_after_reboot.get_or_insert((transaction.clone(), seq_no));
delivered.push((transaction, seq_no));
engine.handle(
Instant::ZERO,
Input::Received(&format!(r#"[3,"{id}",{{}}]"#)),
);
}
assert_eq!(
first_after_reboot.as_ref(),
Some(&in_flight),
"the message in flight at the crash is redelivered, first"
);
assert_eq!(
delivered, order,
"each message acknowledged exactly once, in queue order"
);
assert_eq!(
engine.store().len()?,
0,
"every delivered message was acknowledged"
);
let unique: BTreeSet<_> = delivered.iter().collect();
assert_eq!(unique.len(), total);
println!(
"rebooted: {} {} redelivered first; all {total} acknowledged once, in order; queue empty",
in_flight.0, in_flight.1
);
Ok(())
}