use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use super::repository::EvseRepository;
use crate::emp::PullEvseDataRecord;
use crate::types::{DateTime, EvseId};
#[derive(Debug, thiserror::Error)]
pub enum FileRepositoryError {
#[error("{path}: {source}")]
Io {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("{path} is not an oicp-kit snapshot: {source}")]
Malformed {
path: PathBuf,
#[source]
source: serde_json::Error,
},
}
#[derive(Serialize, Deserialize)]
struct Snapshot {
version: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
last_call: Option<DateTime>,
records: BTreeMap<String, PullEvseDataRecord>,
}
const SNAPSHOT_VERSION: u32 = 1;
#[derive(Debug, Clone)]
pub struct FileEvseRepository {
path: PathBuf,
records: BTreeMap<String, PullEvseDataRecord>,
last_call: Option<DateTime>,
dirty: bool,
}
impl FileEvseRepository {
pub fn open(path: impl Into<PathBuf>) -> Result<Self, FileRepositoryError> {
let path = path.into();
let Ok(text) = std::fs::read_to_string(&path) else {
return Ok(Self { path, records: BTreeMap::new(), last_call: None, dirty: false });
};
let snapshot: Snapshot = serde_json::from_str(&text)
.map_err(|source| FileRepositoryError::Malformed { path: path.clone(), source })?;
if snapshot.version != SNAPSHOT_VERSION {
return Err(FileRepositoryError::Malformed {
path: path.clone(),
source: serde_json::Error::io(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("snapshot format version {} is not {SNAPSHOT_VERSION}", snapshot.version),
)),
});
}
Ok(Self { path, records: snapshot.records, last_call: snapshot.last_call, dirty: false })
}
pub fn save(&mut self) -> Result<(), FileRepositoryError> {
let snapshot = Snapshot {
version: SNAPSHOT_VERSION,
last_call: self.last_call.clone(),
records: self.records.clone(),
};
let json = serde_json::to_vec_pretty(&snapshot)
.map_err(|source| FileRepositoryError::Malformed { path: self.path.clone(), source })?;
let directory = self.path.parent().unwrap_or_else(|| Path::new("."));
std::fs::create_dir_all(directory)
.map_err(|source| FileRepositoryError::Io { path: directory.to_path_buf(), source })?;
let temporary = self.path.with_extension("tmp");
std::fs::write(&temporary, &json)
.map_err(|source| FileRepositoryError::Io { path: temporary.clone(), source })?;
std::fs::rename(&temporary, &self.path)
.map_err(|source| FileRepositoryError::Io { path: self.path.clone(), source })?;
self.dirty = false;
Ok(())
}
#[must_use]
pub fn path(&self) -> &Path {
&self.path
}
#[must_use]
pub const fn is_dirty(&self) -> bool {
self.dirty
}
pub fn iter(&self) -> impl Iterator<Item = &PullEvseDataRecord> {
self.records.values()
}
}
impl EvseRepository for FileEvseRepository {
type Error = FileRepositoryError;
fn upsert(&mut self, record: PullEvseDataRecord) -> Result<bool, Self::Error> {
self.dirty = true;
Ok(self.records.insert(record.evse_id.canonical(), record).is_none())
}
fn delete(&mut self, evse_id: &EvseId) -> Result<bool, Self::Error> {
self.dirty = true;
Ok(self.records.remove(&evse_id.canonical()).is_some())
}
fn get(&self, evse_id: &EvseId) -> Result<Option<PullEvseDataRecord>, Self::Error> {
Ok(self.records.get(&evse_id.canonical()).cloned())
}
fn len(&self) -> Result<u64, Self::Error> {
Ok(self.records.len() as u64)
}
fn last_call(&self) -> Result<Option<DateTime>, Self::Error> {
Ok(self.last_call.clone())
}
fn set_last_call(&mut self, at: DateTime) -> Result<(), Self::Error> {
self.dirty = true;
self.last_call = Some(at);
Ok(())
}
fn clear(&mut self) -> Result<(), Self::Error> {
self.dirty = true;
self.records.clear();
Ok(())
}
}
#[cfg(all(test, feature = "testkit"))]
mod tests {
use super::*;
use crate::testkit::samples;
fn temporary() -> PathBuf {
let mut path = std::env::temp_dir();
path.push(format!("oicp-kit-test-{}-{:?}.json", std::process::id(), std::thread::current().id()));
let _ = std::fs::remove_file(&path);
path
}
#[test]
fn a_missing_file_is_a_first_run_not_an_error() {
let path = temporary();
let repository = FileEvseRepository::open(&path).expect("a missing file starts empty");
assert_eq!(repository.len().unwrap(), 0);
assert_eq!(repository.last_call().unwrap(), None);
assert!(!repository.is_dirty());
}
#[test]
fn iterating_yields_what_was_stored() {
let path = temporary();
let mut repository = FileEvseRepository::open(&path).unwrap();
repository.upsert(samples::pull_evse_data_record("DE*ABC*E1")).unwrap();
repository.upsert(samples::pull_evse_data_record("DE*ABC*E2")).unwrap();
let seen: Vec<String> = repository.iter().map(|r| r.evse_id.canonical()).collect();
assert_eq!(seen, vec!["DEABCE1".to_owned(), "DEABCE2".to_owned()], "in EvseID order");
assert_eq!(seen.len() as u64, repository.len().unwrap());
std::fs::remove_file(&path).ok();
}
#[test]
fn deleting_and_clearing_survive_a_reopen() {
let path = temporary();
let mut repository = FileEvseRepository::open(&path).unwrap();
repository.upsert(samples::pull_evse_data_record("DE*ABC*E1")).unwrap();
repository.upsert(samples::pull_evse_data_record("DE*ABC*E2")).unwrap();
repository.save().unwrap();
let gone: EvseId = "DE*ABC*E1".parse().unwrap();
assert!(repository.delete(&gone).unwrap(), "the record was there");
assert!(!repository.delete(&gone).unwrap(), "and is not there twice");
assert_eq!(repository.len().unwrap(), 1);
assert!(repository.get(&gone).unwrap().is_none());
repository.save().unwrap();
let reopened = FileEvseRepository::open(&path).unwrap();
assert_eq!(reopened.len().unwrap(), 1, "the deletion reached the file");
assert!(reopened.get(&gone).unwrap().is_none());
let mut repository = FileEvseRepository::open(&path).unwrap();
repository.clear().unwrap();
assert_eq!(repository.len().unwrap(), 0);
assert!(repository.is_empty().unwrap());
repository.save().unwrap();
assert_eq!(FileEvseRepository::open(&path).unwrap().len().unwrap(), 0);
std::fs::remove_file(&path).ok();
}
#[test]
fn a_snapshot_survives_a_round_trip() {
let path = temporary();
let mut repository = FileEvseRepository::open(&path).unwrap();
repository.upsert(samples::pull_evse_data_record("DE*ABC*E1")).unwrap();
repository.upsert(samples::pull_evse_data_record("DE*ABC*E2")).unwrap();
repository.set_last_call(samples::fixed_time()).unwrap();
assert!(repository.is_dirty());
repository.save().unwrap();
assert!(!repository.is_dirty());
let reopened = FileEvseRepository::open(&path).expect("reopens");
assert_eq!(reopened.len().unwrap(), 2);
assert_eq!(reopened.last_call().unwrap(), Some(samples::fixed_time()));
assert_eq!(
reopened.get(&"DEABCE1".parse().unwrap()).unwrap().map(|r| r.evse_id.canonical()),
Some("DEABCE1".to_owned()),
"and the identifier still matches however it is written"
);
std::fs::remove_file(&path).ok();
}
#[test]
fn a_file_that_is_not_a_snapshot_is_refused_rather_than_reinterpreted() {
let path = temporary();
std::fs::write(&path, b"{\"not\": \"a snapshot\"}").unwrap();
let error = FileEvseRepository::open(&path).expect_err("refused");
assert!(matches!(error, FileRepositoryError::Malformed { .. }));
std::fs::remove_file(&path).ok();
}
#[test]
fn a_future_snapshot_version_is_refused_rather_than_guessed_at() {
let path = temporary();
std::fs::write(&path, br#"{"version": 99, "records": {}}"#).unwrap();
let error = FileEvseRepository::open(&path).expect_err("refused");
assert!(error.to_string().contains("version"));
std::fs::remove_file(&path).ok();
}
#[test]
fn saving_leaves_no_temporary_file_behind() {
let path = temporary();
let mut repository = FileEvseRepository::open(&path).unwrap();
repository.upsert(samples::pull_evse_data_record("DE*ABC*E1")).unwrap();
repository.save().unwrap();
assert!(!path.with_extension("tmp").exists(), "the temporary file was renamed, not left");
std::fs::remove_file(&path).ok();
}
}