use core::fmt;
use core::time::Duration;
use super::repository::EvseRepository;
use crate::emp::PullEvseDataRequest;
use crate::types::{DateTime, GeoCoordinatesFormat, ProviderId};
#[derive(Clone, Debug, PartialEq)]
pub enum Plan {
Full {
request: Box<PullEvseDataRequest>,
reason: FullPullReason,
},
Delta {
request: Box<PullEvseDataRequest>,
since: DateTime,
},
}
impl Plan {
#[must_use]
pub fn request(&self) -> &PullEvseDataRequest {
match self {
Self::Full { request, .. } | Self::Delta { request, .. } => request,
}
}
#[must_use]
pub const fn replaces_everything(&self) -> bool {
matches!(self, Self::Full { .. })
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FullPullReason {
NoWatermark,
EmptyRepository,
WatermarkTooOld,
WatermarkInFuture,
Requested,
}
impl fmt::Display for FullPullReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::NoWatermark => "nothing has been pulled yet",
Self::EmptyRepository => "the local copy is empty",
Self::WatermarkTooOld => "the watermark is older than the maximum delta age",
Self::WatermarkInFuture => "the watermark is in the future",
Self::Requested => "a re-baseline was requested",
})
}
}
#[derive(Clone, Debug)]
pub struct PlannerConfig {
pub provider_id: ProviderId,
pub geo_format: GeoCoordinatesFormat,
pub max_delta_age: Duration,
pub force_full: bool,
pub clock_skew_guard: Duration,
}
impl PlannerConfig {
#[must_use]
pub fn new(provider_id: ProviderId, geo_format: GeoCoordinatesFormat) -> Self {
Self {
provider_id,
geo_format,
max_delta_age: Duration::from_secs(24 * 60 * 60),
force_full: false,
clock_skew_guard: Duration::from_secs(5 * 60),
}
}
#[must_use]
pub const fn with_clock_skew_guard(mut self, guard: Duration) -> Self {
self.clock_skew_guard = guard;
self
}
#[must_use]
pub const fn with_max_delta_age(mut self, age: Duration) -> Self {
self.max_delta_age = age;
self
}
#[must_use]
pub const fn rebaseline(mut self) -> Self {
self.force_full = true;
self
}
}
#[derive(Clone, Debug)]
pub struct Planner {
config: PlannerConfig,
}
impl Planner {
#[must_use]
pub const fn new(config: PlannerConfig) -> Self {
Self { config }
}
#[must_use]
pub const fn config(&self) -> &PlannerConfig {
&self.config
}
pub fn plan<R: EvseRepository>(&self, repository: &R) -> Result<(Plan, DateTime), R::Error> {
self.plan_at(repository, DateTime::now())
}
pub fn begin<R: EvseRepository>(&self, repository: &mut R) -> Result<(Plan, DateTime), R::Error> {
self.begin_at(repository, DateTime::now())
}
pub fn begin_at<R: EvseRepository>(
&self,
repository: &mut R,
now: DateTime,
) -> Result<(Plan, DateTime), R::Error> {
let (plan, watermark) = self.plan_at(repository, now)?;
if plan.replaces_everything() {
repository.clear()?;
}
Ok((plan, watermark))
}
pub fn plan_at<R: EvseRepository>(
&self,
repository: &R,
now: DateTime,
) -> Result<(Plan, DateTime), R::Error> {
let plan = if let Some(reason) = self.full_pull_reason(repository, &now)? {
Plan::Full {
request: Box::new(PullEvseDataRequest::full(
self.config.provider_id.clone(),
self.config.geo_format,
)),
reason,
}
} else {
let since = repository.last_call()?.expect("a delta plan requires a watermark");
Plan::Delta {
request: Box::new(PullEvseDataRequest::delta(
self.config.provider_id.clone(),
self.config.geo_format,
since.clone(),
)),
since,
}
};
Ok((plan, self.guarded(&now)))
}
fn guarded(&self, now: &DateTime) -> DateTime {
let (Some(instant), Ok(guard)) =
(now.as_offset(), time::Duration::try_from(self.config.clock_skew_guard))
else {
return now.clone();
};
DateTime::from_offset(instant - guard)
}
fn full_pull_reason<R: EvseRepository>(
&self,
repository: &R,
now: &DateTime,
) -> Result<Option<FullPullReason>, R::Error> {
if self.config.force_full {
return Ok(Some(FullPullReason::Requested));
}
let Some(watermark) = repository.last_call()? else {
return Ok(Some(FullPullReason::NoWatermark));
};
if repository.is_empty()? {
return Ok(Some(FullPullReason::EmptyRepository));
}
let (Some(now), Some(mark)) = (now.as_offset(), watermark.as_offset()) else {
return Ok(Some(FullPullReason::NoWatermark));
};
let elapsed = now - mark;
if elapsed.is_negative() {
return Ok(Some(FullPullReason::WatermarkInFuture));
}
if elapsed.unsigned_abs() > self.config.max_delta_age {
return Ok(Some(FullPullReason::WatermarkTooOld));
}
Ok(None)
}
pub fn commit<R: EvseRepository>(&self, repository: &mut R, at: DateTime) -> Result<(), R::Error> {
repository.set_last_call(at)
}
}
#[cfg(all(test, feature = "testkit"))]
mod tests {
use super::*;
use crate::sync::{EvseRepository, InMemoryEvseRepository};
use crate::testkit::samples;
use crate::types::Validate;
fn planner() -> Planner {
Planner::new(PlannerConfig::new("DE-DCB".parse().unwrap(), GeoCoordinatesFormat::Google))
}
fn populated() -> InMemoryEvseRepository {
let mut repo = InMemoryEvseRepository::new();
repo.upsert(samples::pull_evse_data_record("DE*ABC*E1")).unwrap();
repo
}
#[test]
fn the_first_pull_is_always_a_full_one() {
let (plan, _) = planner().plan(&InMemoryEvseRepository::new()).unwrap();
assert!(matches!(plan, Plan::Full { reason: FullPullReason::NoWatermark, .. }));
assert!(plan.replaces_everything());
assert!(!plan.request().is_delta());
}
#[test]
fn a_recent_watermark_and_a_populated_copy_gives_a_delta() {
let mut repo = populated();
let now: DateTime = "2026-08-31T12:00:00.000Z".parse().unwrap();
repo.set_last_call("2026-08-31T11:00:00.000Z".parse().unwrap()).unwrap();
let (plan, watermark) = planner().plan_at(&repo, now.clone()).unwrap();
let Plan::Delta { request, since } = plan else { panic!("expected a delta") };
assert_eq!(since.as_str(), "2026-08-31T11:00:00.000Z");
assert!(request.is_delta());
assert!(request.conflicting_filters().is_empty());
assert!(request.validate().is_ok());
assert_eq!(watermark.as_str(), "2026-08-31T11:55:00Z");
assert!(watermark < now);
}
#[test]
fn the_committed_watermark_is_held_back_by_the_skew_guard() {
let mut repo = populated();
let now: DateTime = "2026-08-31T12:00:00.000Z".parse().unwrap();
repo.set_last_call("2026-08-31T11:00:00.000Z".parse().unwrap()).unwrap();
let (_, watermark) = planner().plan_at(&repo, now.clone()).unwrap();
assert_eq!(watermark.as_str(), "2026-08-31T11:55:00Z", "five minutes by default");
let strict = Planner::new(
PlannerConfig::new("DE-DCB".parse().unwrap(), GeoCoordinatesFormat::Google)
.with_clock_skew_guard(Duration::ZERO),
);
let (_, watermark) = strict.plan_at(&repo, now.clone()).unwrap();
assert_eq!(watermark, now);
}
#[test]
fn begin_empties_the_copy_for_a_full_pull_and_leaves_it_alone_for_a_delta() {
let mut repo = populated();
let now: DateTime = "2026-08-31T12:00:00.000Z".parse().unwrap();
let (plan, _) = planner().begin_at(&mut repo, now.clone()).unwrap();
assert!(plan.replaces_everything());
assert_eq!(repo.len().unwrap(), 0, "a full pull starts from an empty copy");
repo.upsert(samples::pull_evse_data_record("DE*ABC*E1")).unwrap();
repo.set_last_call("2026-08-31T11:00:00.000Z".parse().unwrap()).unwrap();
let (plan, _) = planner().begin_at(&mut repo, now).unwrap();
assert!(!plan.replaces_everything());
assert_eq!(repo.len().unwrap(), 1);
}
#[test]
fn a_stale_watermark_forces_a_rebaseline() {
let mut repo = populated();
repo.set_last_call("2026-08-01T11:00:00.000Z".parse().unwrap()).unwrap();
let now: DateTime = "2026-08-31T12:00:00.000Z".parse().unwrap();
let (plan, _) = planner().plan_at(&repo, now).unwrap();
assert!(matches!(plan, Plan::Full { reason: FullPullReason::WatermarkTooOld, .. }));
}
#[test]
fn every_full_pull_reason_says_something_different() {
let reasons = [
FullPullReason::NoWatermark,
FullPullReason::EmptyRepository,
FullPullReason::WatermarkTooOld,
FullPullReason::WatermarkInFuture,
FullPullReason::Requested,
];
let rendered: Vec<String> = reasons.iter().map(ToString::to_string).collect();
for text in &rendered {
assert!(!text.is_empty(), "a reason rendered as nothing");
}
let mut unique = rendered.clone();
unique.sort_unstable();
unique.dedup();
assert_eq!(unique.len(), reasons.len(), "two reasons render the same: {rendered:?}");
}
#[test]
fn the_maximum_delta_age_is_a_boundary_not_a_vibe() {
let mut repo = populated();
repo.set_last_call("2026-08-31T12:00:00.000Z".parse().unwrap()).unwrap();
let planner = Planner::new(
PlannerConfig::new("DE-DCB".parse().unwrap(), GeoCoordinatesFormat::Google)
.with_max_delta_age(Duration::from_secs(3600)),
);
let (plan, _) = planner.plan_at(&repo, "2026-08-31T13:00:00.000Z".parse().unwrap()).unwrap();
assert!(matches!(plan, Plan::Delta { .. }), "exactly one hour old is still a delta");
let (plan, _) = planner.plan_at(&repo, "2026-08-31T13:00:01.000Z".parse().unwrap()).unwrap();
assert!(matches!(plan, Plan::Full { reason: FullPullReason::WatermarkTooOld, .. }));
}
#[test]
fn a_watermark_from_the_future_forces_a_rebaseline() {
let mut repo = populated();
repo.set_last_call("2026-09-30T11:00:00.000Z".parse().unwrap()).unwrap();
let now: DateTime = "2026-08-31T12:00:00.000Z".parse().unwrap();
let (plan, _) = planner().plan_at(&repo, now).unwrap();
assert!(matches!(plan, Plan::Full { reason: FullPullReason::WatermarkInFuture, .. }));
}
#[test]
fn a_watermark_without_a_copy_forces_a_full_pull() {
let mut repo = InMemoryEvseRepository::new();
repo.set_last_call("2026-08-31T11:00:00.000Z".parse().unwrap()).unwrap();
let now: DateTime = "2026-08-31T12:00:00.000Z".parse().unwrap();
let (plan, _) = planner().plan_at(&repo, now).unwrap();
assert!(matches!(plan, Plan::Full { reason: FullPullReason::EmptyRepository, .. }));
}
#[test]
fn a_rebaseline_can_be_asked_for() {
let mut repo = populated();
repo.set_last_call("2026-08-31T11:00:00.000Z".parse().unwrap()).unwrap();
let planner = Planner::new(
PlannerConfig::new("DE-DCB".parse().unwrap(), GeoCoordinatesFormat::Google).rebaseline(),
);
let (plan, _) = planner.plan_at(&repo, "2026-08-31T12:00:00.000Z".parse().unwrap()).unwrap();
assert!(matches!(plan, Plan::Full { reason: FullPullReason::Requested, .. }));
}
#[test]
fn the_watermark_moves_only_on_commit() {
let mut repo = populated();
let now: DateTime = "2026-08-31T12:00:00.000Z".parse().unwrap();
let planner = planner();
let (_, watermark) = planner.plan_at(&repo, now).unwrap();
assert_eq!(repo.last_call().unwrap(), None, "planning does not move the watermark");
planner.commit(&mut repo, watermark.clone()).unwrap();
assert_eq!(repo.last_call().unwrap(), Some(watermark));
}
}