use std::path::PathBuf;
use flexpool_core::{AssetId, BusinessDay};
use flexpool_telemetry::sim::{Fault, FaultKind};
use serde::Deserialize;
use time::format_description::well_known::Rfc3339;
use time::{Date, OffsetDateTime};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MarketSource {
Synthetic {
seed: u64,
history_days: u16,
},
File {
path: PathBuf,
},
}
pub const DEFAULT_HISTORY_DAYS: u16 = 28;
pub const MAX_HISTORY_DAYS: u16 = 60;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Scenario {
pub name: String,
pub day: Date,
pub market: MarketSource,
pub start: OffsetDateTime,
pub end: OffsetDateTime,
pub faults: Vec<Fault>,
pub dso: Option<Dso>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dso {
pub congestion_point: String,
pub request_at: OffsetDateTime,
pub isps: (u32, u32),
pub min_kw: i64,
pub max_kw: i64,
pub dispute_isp: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{location}: {message}")]
pub struct ScenarioProblem {
pub location: String,
pub message: String,
}
#[derive(Deserialize)]
struct Raw {
name: Option<String>,
day: Option<toml::Value>,
market: Option<RawMarket>,
clock: Option<RawClock>,
fault: Option<Vec<RawFault>>,
dso: Option<RawDso>,
}
#[derive(Deserialize)]
struct RawDso {
congestion_point: Option<String>,
request_at: Option<String>,
isps: Option<Vec<i64>>,
min_kw: Option<i64>,
max_kw: Option<i64>,
dispute_isp: Option<i64>,
}
#[derive(Deserialize)]
struct RawFault {
asset: Option<String>,
kind: Option<String>,
from: Option<String>,
to: Option<String>,
}
#[derive(Deserialize)]
struct RawMarket {
source: Option<String>,
seed: Option<u64>,
file: Option<String>,
history_days: Option<i64>,
}
#[derive(Deserialize)]
struct RawClock {
start: Option<String>,
end: Option<String>,
}
const KNOWN: &[(&str, &[&str])] = &[
("", &["name", "day", "market", "clock", "fault", "dso"]),
("market", &["source", "seed", "file", "history_days"]),
("clock", &["start", "end"]),
(
"dso",
&[
"congestion_point",
"request_at",
"isps",
"min_kw",
"max_kw",
"dispute_isp",
],
),
];
fn unknown_keys(table: &toml::Table) -> Vec<ScenarioProblem> {
let mut out = Vec::new();
for (section, keys) in KNOWN {
let t = if section.is_empty() {
Some(table)
} else {
table.get(*section).and_then(toml::Value::as_table)
};
for key in t.into_iter().flat_map(toml::Table::keys) {
if !keys.contains(&key.as_str()) {
let location = if section.is_empty() {
key.clone()
} else {
format!("{section}.{key}")
};
out.push(problem(&location, "unknown key"));
}
}
}
let faults = table.get("fault").and_then(toml::Value::as_array);
for (i, f) in faults.into_iter().flatten().enumerate() {
for key in f.as_table().into_iter().flat_map(toml::Table::keys) {
if !["asset", "kind", "from", "to"].contains(&key.as_str()) {
out.push(problem(&format!("fault[{}].{key}", i + 1), "unknown key"));
}
}
}
out
}
fn faults(raw: Vec<RawFault>, problems: &mut Vec<ScenarioProblem>) -> Vec<Fault> {
let mut out = Vec::new();
for (i, f) in raw.into_iter().enumerate() {
let at = |k: &str| format!("fault[{}].{k}", i + 1);
let asset = match f.asset.map(AssetId::parse) {
Some(Ok(id)) => Some(id),
Some(Err(e)) => {
problems.push(problem(&at("asset"), e.to_string()));
None
}
None => {
problems.push(problem(&at("asset"), "required"));
None
}
};
let kind = match f.kind.as_deref() {
Some("offline") => Some(FaultKind::Offline),
Some("stuck") => Some(FaultKind::Stuck),
Some("tripped") => Some(FaultKind::Tripped),
Some(other) => {
problems.push(problem(
&at("kind"),
format!("{other:?} must be \"offline\", \"stuck\" or \"tripped\""),
));
None
}
None => {
problems.push(problem(
&at("kind"),
"required: \"offline\", \"stuck\" or \"tripped\"",
));
None
}
};
let mut when = |k: &str, v: Option<String>| match v {
Some(s) => instant(&at(k), &s, problems),
None => {
problems.push(problem(&at(k), "required"));
None
}
};
let (from, to) = (when("from", f.from), when("to", f.to));
if let (Some(from), Some(to)) = (from, to)
&& to <= from
{
problems.push(problem(&at("to"), "must be after from"));
continue;
}
if let (Some(asset), Some(kind), Some(from), Some(to)) = (asset, kind, from, to) {
out.push(Fault {
asset,
kind,
from: from.unix_timestamp(),
to: to.unix_timestamp(),
});
}
}
out
}
fn dso(raw: RawDso, quarters: u16, problems: &mut Vec<ScenarioProblem>) -> Option<Dso> {
let before = problems.len();
let cp = raw.congestion_point.unwrap_or_default();
if !(cp.starts_with("ea1.") && cp.contains(':')) {
problems.push(problem(
"dso.congestion_point",
format!("{cp:?} is not a UFTP entity address like ea1.2026-11.netz.example:cp-1"),
));
}
let request_at = match raw.request_at {
Some(s) => instant("dso.request_at", &s, problems),
None => {
problems.push(problem("dso.request_at", "required"));
None
}
};
let n = i64::from(quarters);
let isps = match raw.isps.as_deref() {
Some(&[a, b]) if 1 <= a && a <= b && b <= n => {
Some((u32::try_from(a).ok()?, u32::try_from(b).ok()?))
}
_ => {
problems.push(problem(
"dso.isps",
format!("[first, last] within 1–{n}, first ≤ last"),
));
None
}
};
let (min_kw, max_kw) = (raw.min_kw.unwrap_or(0), raw.max_kw.unwrap_or(0));
if raw.min_kw.is_none() || raw.max_kw.is_none() {
problems.push(problem("dso", "min_kw and max_kw are required"));
} else if min_kw > max_kw || (min_kw < 0 && max_kw > 0) || (min_kw == 0 && max_kw == 0) {
problems.push(problem(
"dso.max_kw",
"the band needs min_kw ≤ max_kw on one side of zero (UFTP: a requested deviation has one direction)",
));
}
let dispute_isp = match (raw.dispute_isp, isps) {
(None, _) => None,
(Some(d), Some((a, b))) if (i64::from(a)..=i64::from(b)).contains(&d) => {
u32::try_from(d).ok()
}
(Some(_), _) => {
problems.push(problem("dso.dispute_isp", "must lie within dso.isps"));
None
}
};
let (Some(request_at), Some(isps), true) = (request_at, isps, problems.len() == before) else {
return None;
};
Some(Dso {
congestion_point: cp,
request_at,
isps,
min_kw,
max_kw,
dispute_isp,
})
}
#[must_use]
pub fn data_file(text: &str) -> Option<PathBuf> {
let table: toml::Table = text.parse().ok()?;
let market = table.get("market")?.as_table()?;
(market.get("source")?.as_str()? == "file")
.then(|| market.get("file")?.as_str().map(PathBuf::from))?
}
fn problem(location: &str, message: impl Into<String>) -> ScenarioProblem {
ScenarioProblem {
location: location.to_owned(),
message: message.into(),
}
}
fn instant(location: &str, s: &str, problems: &mut Vec<ScenarioProblem>) -> Option<OffsetDateTime> {
match OffsetDateTime::parse(s, &Rfc3339) {
Ok(t) => Some(t.to_offset(time::UtcOffset::UTC)),
Err(_) => {
problems.push(problem(
location,
format!("{s:?} is not an RFC 3339 instant like 2025-10-01T10:00:00+02:00"),
));
None
}
}
}
impl Scenario {
pub fn parse(text: &str) -> Result<Self, Vec<ScenarioProblem>> {
let table: toml::Table = text.parse().map_err(|e: toml::de::Error| {
let at = e.span().map_or_else(
|| "(file)".into(),
|s| format!("(file) at byte {}", s.start),
);
vec![problem(&at, e.message())]
})?;
let mut problems = unknown_keys(&table);
let raw: Raw = match toml::Value::Table(table).try_into() {
Ok(raw) => raw,
Err(e) => {
problems.push(problem("(file)", e.message()));
return Err(problems);
}
};
let name = raw.name.unwrap_or_else(|| {
problems.push(problem("name", "required"));
String::new()
});
let date_fmt = time::macros::format_description!("[year]-[month]-[day]");
let day = match raw.day {
None => {
problems.push(problem("day", "required, e.g. day = \"2025-10-02\""));
None
}
Some(toml::Value::Datetime(d)) => {
Date::parse(&d.to_string(), date_fmt).ok().or_else(|| {
problems.push(problem("day", format!("{d} is not a calendar date")));
None
})
}
Some(toml::Value::String(s)) => Date::parse(&s, date_fmt).ok().or_else(|| {
problems.push(problem(
"day",
format!("{s:?} is not a date like 2025-10-02"),
));
None
}),
Some(other) => {
problems.push(problem("day", format!("{other} is not a date")));
None
}
};
let business = day.and_then(|d| match BusinessDay::new(d) {
Ok(b) => Some(b),
Err(e) => {
problems.push(problem("day", e.to_string()));
None
}
});
let market = match raw.market {
None => {
problems.push(problem(
"market",
"required: [market] source = \"synthetic\" or \"file\"",
));
None
}
Some(m) => match (m.source.as_deref(), m.seed, m.file) {
(Some("synthetic"), Some(seed), None) => match m.history_days {
None => Some(MarketSource::Synthetic {
seed,
history_days: DEFAULT_HISTORY_DAYS,
}),
Some(d) => match u16::try_from(d).ok().filter(|d| *d <= MAX_HISTORY_DAYS) {
Some(history_days) => Some(MarketSource::Synthetic { seed, history_days }),
None => {
problems.push(problem(
"market.history_days",
format!("{d} must be 0–{MAX_HISTORY_DAYS}"),
));
None
}
},
},
(Some("synthetic"), None, None) => {
problems.push(problem(
"market.seed",
"required for source = \"synthetic\"",
));
None
}
(Some("file"), None, Some(_)) if m.history_days.is_some() => {
problems.push(problem(
"market.history_days",
"applies to source = \"synthetic\" only; a data file holds one day",
));
None
}
(Some("file"), None, Some(file)) => Some(MarketSource::File {
path: PathBuf::from(file),
}),
(Some("file"), None, None) => {
problems.push(problem("market.file", "required for source = \"file\""));
None
}
(Some(s @ ("synthetic" | "file")), _, _) => {
problems.push(problem(
"market",
format!(
"source = {s:?} takes {} only",
if s == "file" { "file" } else { "seed" }
),
));
None
}
(other, _, _) => {
problems.push(problem(
"market.source",
format!("{other:?} must be \"synthetic\" or \"file\""),
));
None
}
},
};
let clock = raw.clock.unwrap_or(RawClock {
start: None,
end: None,
});
let start = clock
.start
.as_deref()
.and_then(|s| instant("clock.start", s, &mut problems));
let end = clock
.end
.as_deref()
.and_then(|s| instant("clock.end", s, &mut problems));
let faults = faults(raw.fault.unwrap_or_default(), &mut problems);
let (Some(business), Some(market)) = (business, market) else {
return Err(problems);
};
let dso = raw.dso.and_then(|d| dso(d, business.len(), &mut problems));
let start = start.unwrap_or_else(|| business.start() - time::Duration::hours(14));
let end = end.unwrap_or_else(|| business.end());
if end <= start {
problems.push(problem("clock.end", "must be after clock.start"));
}
if let Some(d) = &dso
&& !(start..end).contains(&d.request_at)
{
problems.push(problem(
"dso.request_at",
"must lie within the clock's range",
));
}
if !problems.is_empty() {
return Err(problems);
}
Ok(Self {
name,
day: business.date(),
market,
start,
end,
faults,
dso,
})
}
}