1use std::path::PathBuf;
28
29use flexpool_core::{AssetId, BusinessDay};
30use flexpool_telemetry::sim::{Fault, FaultKind};
31use serde::Deserialize;
32use time::format_description::well_known::Rfc3339;
33use time::{Date, OffsetDateTime};
34
35#[derive(Debug, Clone, PartialEq, Eq)]
37pub enum MarketSource {
38 Synthetic {
40 seed: u64,
42 history_days: u16,
44 },
45 File {
47 path: PathBuf,
49 },
50}
51
52pub const DEFAULT_HISTORY_DAYS: u16 = 28;
54pub const MAX_HISTORY_DAYS: u16 = 60;
56
57#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct Scenario {
60 pub name: String,
62 pub day: Date,
64 pub market: MarketSource,
66 pub start: OffsetDateTime,
68 pub end: OffsetDateTime,
70 pub faults: Vec<Fault>,
72 pub dso: Option<Dso>,
74}
75
76#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct Dso {
79 pub congestion_point: String,
81 pub request_at: OffsetDateTime,
83 pub isps: (u32, u32),
85 pub min_kw: i64,
88 pub max_kw: i64,
90 pub dispute_isp: Option<u32>,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
96#[error("{location}: {message}")]
97pub struct ScenarioProblem {
98 pub location: String,
100 pub message: String,
102}
103
104#[derive(Deserialize)]
105struct Raw {
106 name: Option<String>,
107 day: Option<toml::Value>,
108 market: Option<RawMarket>,
109 clock: Option<RawClock>,
110 fault: Option<Vec<RawFault>>,
111 dso: Option<RawDso>,
112}
113
114#[derive(Deserialize)]
115struct RawDso {
116 congestion_point: Option<String>,
117 request_at: Option<String>,
118 isps: Option<Vec<i64>>,
119 min_kw: Option<i64>,
120 max_kw: Option<i64>,
121 dispute_isp: Option<i64>,
122}
123
124#[derive(Deserialize)]
125struct RawFault {
126 asset: Option<String>,
127 kind: Option<String>,
128 from: Option<String>,
129 to: Option<String>,
130}
131
132#[derive(Deserialize)]
133struct RawMarket {
134 source: Option<String>,
135 seed: Option<u64>,
136 file: Option<String>,
137 history_days: Option<i64>,
138}
139
140#[derive(Deserialize)]
141struct RawClock {
142 start: Option<String>,
143 end: Option<String>,
144}
145
146const KNOWN: &[(&str, &[&str])] = &[
147 ("", &["name", "day", "market", "clock", "fault", "dso"]),
148 ("market", &["source", "seed", "file", "history_days"]),
149 ("clock", &["start", "end"]),
150 (
151 "dso",
152 &[
153 "congestion_point",
154 "request_at",
155 "isps",
156 "min_kw",
157 "max_kw",
158 "dispute_isp",
159 ],
160 ),
161];
162
163fn unknown_keys(table: &toml::Table) -> Vec<ScenarioProblem> {
165 let mut out = Vec::new();
166 for (section, keys) in KNOWN {
167 let t = if section.is_empty() {
168 Some(table)
169 } else {
170 table.get(*section).and_then(toml::Value::as_table)
171 };
172 for key in t.into_iter().flat_map(toml::Table::keys) {
173 if !keys.contains(&key.as_str()) {
174 let location = if section.is_empty() {
175 key.clone()
176 } else {
177 format!("{section}.{key}")
178 };
179 out.push(problem(&location, "unknown key"));
180 }
181 }
182 }
183 let faults = table.get("fault").and_then(toml::Value::as_array);
184 for (i, f) in faults.into_iter().flatten().enumerate() {
185 for key in f.as_table().into_iter().flat_map(toml::Table::keys) {
186 if !["asset", "kind", "from", "to"].contains(&key.as_str()) {
187 out.push(problem(&format!("fault[{}].{key}", i + 1), "unknown key"));
188 }
189 }
190 }
191 out
192}
193
194fn faults(raw: Vec<RawFault>, problems: &mut Vec<ScenarioProblem>) -> Vec<Fault> {
195 let mut out = Vec::new();
196 for (i, f) in raw.into_iter().enumerate() {
197 let at = |k: &str| format!("fault[{}].{k}", i + 1);
198 let asset = match f.asset.map(AssetId::parse) {
199 Some(Ok(id)) => Some(id),
200 Some(Err(e)) => {
201 problems.push(problem(&at("asset"), e.to_string()));
202 None
203 }
204 None => {
205 problems.push(problem(&at("asset"), "required"));
206 None
207 }
208 };
209 let kind = match f.kind.as_deref() {
210 Some("offline") => Some(FaultKind::Offline),
211 Some("stuck") => Some(FaultKind::Stuck),
212 Some("tripped") => Some(FaultKind::Tripped),
213 Some(other) => {
214 problems.push(problem(
215 &at("kind"),
216 format!("{other:?} must be \"offline\", \"stuck\" or \"tripped\""),
217 ));
218 None
219 }
220 None => {
221 problems.push(problem(
222 &at("kind"),
223 "required: \"offline\", \"stuck\" or \"tripped\"",
224 ));
225 None
226 }
227 };
228 let mut when = |k: &str, v: Option<String>| match v {
229 Some(s) => instant(&at(k), &s, problems),
230 None => {
231 problems.push(problem(&at(k), "required"));
232 None
233 }
234 };
235 let (from, to) = (when("from", f.from), when("to", f.to));
236 if let (Some(from), Some(to)) = (from, to)
237 && to <= from
238 {
239 problems.push(problem(&at("to"), "must be after from"));
240 continue;
241 }
242 if let (Some(asset), Some(kind), Some(from), Some(to)) = (asset, kind, from, to) {
243 out.push(Fault {
244 asset,
245 kind,
246 from: from.unix_timestamp(),
247 to: to.unix_timestamp(),
248 });
249 }
250 }
251 out
252}
253
254fn dso(raw: RawDso, quarters: u16, problems: &mut Vec<ScenarioProblem>) -> Option<Dso> {
255 let before = problems.len();
256 let cp = raw.congestion_point.unwrap_or_default();
257 if !(cp.starts_with("ea1.") && cp.contains(':')) {
258 problems.push(problem(
259 "dso.congestion_point",
260 format!("{cp:?} is not a UFTP entity address like ea1.2026-11.netz.example:cp-1"),
261 ));
262 }
263 let request_at = match raw.request_at {
264 Some(s) => instant("dso.request_at", &s, problems),
265 None => {
266 problems.push(problem("dso.request_at", "required"));
267 None
268 }
269 };
270 let n = i64::from(quarters);
271 let isps = match raw.isps.as_deref() {
272 Some(&[a, b]) if 1 <= a && a <= b && b <= n => {
273 Some((u32::try_from(a).ok()?, u32::try_from(b).ok()?))
274 }
275 _ => {
276 problems.push(problem(
277 "dso.isps",
278 format!("[first, last] within 1–{n}, first ≤ last"),
279 ));
280 None
281 }
282 };
283 let (min_kw, max_kw) = (raw.min_kw.unwrap_or(0), raw.max_kw.unwrap_or(0));
284 if raw.min_kw.is_none() || raw.max_kw.is_none() {
285 problems.push(problem("dso", "min_kw and max_kw are required"));
286 } else if min_kw > max_kw || (min_kw < 0 && max_kw > 0) || (min_kw == 0 && max_kw == 0) {
287 problems.push(problem(
288 "dso.max_kw",
289 "the band needs min_kw ≤ max_kw on one side of zero (UFTP: a requested deviation has one direction)",
290 ));
291 }
292 let dispute_isp = match (raw.dispute_isp, isps) {
293 (None, _) => None,
294 (Some(d), Some((a, b))) if (i64::from(a)..=i64::from(b)).contains(&d) => {
295 u32::try_from(d).ok()
296 }
297 (Some(_), _) => {
298 problems.push(problem("dso.dispute_isp", "must lie within dso.isps"));
299 None
300 }
301 };
302 let (Some(request_at), Some(isps), true) = (request_at, isps, problems.len() == before) else {
303 return None;
304 };
305 Some(Dso {
306 congestion_point: cp,
307 request_at,
308 isps,
309 min_kw,
310 max_kw,
311 dispute_isp,
312 })
313}
314
315#[must_use]
318pub fn data_file(text: &str) -> Option<PathBuf> {
319 let table: toml::Table = text.parse().ok()?;
320 let market = table.get("market")?.as_table()?;
321 (market.get("source")?.as_str()? == "file")
322 .then(|| market.get("file")?.as_str().map(PathBuf::from))?
323}
324
325fn problem(location: &str, message: impl Into<String>) -> ScenarioProblem {
326 ScenarioProblem {
327 location: location.to_owned(),
328 message: message.into(),
329 }
330}
331
332fn instant(location: &str, s: &str, problems: &mut Vec<ScenarioProblem>) -> Option<OffsetDateTime> {
333 match OffsetDateTime::parse(s, &Rfc3339) {
334 Ok(t) => Some(t.to_offset(time::UtcOffset::UTC)),
335 Err(_) => {
336 problems.push(problem(
337 location,
338 format!("{s:?} is not an RFC 3339 instant like 2025-10-01T10:00:00+02:00"),
339 ));
340 None
341 }
342 }
343}
344
345impl Scenario {
346 pub fn parse(text: &str) -> Result<Self, Vec<ScenarioProblem>> {
351 let table: toml::Table = text.parse().map_err(|e: toml::de::Error| {
352 let at = e.span().map_or_else(
353 || "(file)".into(),
354 |s| format!("(file) at byte {}", s.start),
355 );
356 vec![problem(&at, e.message())]
357 })?;
358 let mut problems = unknown_keys(&table);
360 let raw: Raw = match toml::Value::Table(table).try_into() {
361 Ok(raw) => raw,
362 Err(e) => {
363 problems.push(problem("(file)", e.message()));
364 return Err(problems);
365 }
366 };
367 let name = raw.name.unwrap_or_else(|| {
368 problems.push(problem("name", "required"));
369 String::new()
370 });
371 let date_fmt = time::macros::format_description!("[year]-[month]-[day]");
372 let day = match raw.day {
373 None => {
374 problems.push(problem("day", "required, e.g. day = \"2025-10-02\""));
375 None
376 }
377 Some(toml::Value::Datetime(d)) => {
378 Date::parse(&d.to_string(), date_fmt).ok().or_else(|| {
379 problems.push(problem("day", format!("{d} is not a calendar date")));
380 None
381 })
382 }
383 Some(toml::Value::String(s)) => Date::parse(&s, date_fmt).ok().or_else(|| {
384 problems.push(problem(
385 "day",
386 format!("{s:?} is not a date like 2025-10-02"),
387 ));
388 None
389 }),
390 Some(other) => {
391 problems.push(problem("day", format!("{other} is not a date")));
392 None
393 }
394 };
395 let business = day.and_then(|d| match BusinessDay::new(d) {
396 Ok(b) => Some(b),
397 Err(e) => {
398 problems.push(problem("day", e.to_string()));
399 None
400 }
401 });
402 let market = match raw.market {
403 None => {
404 problems.push(problem(
405 "market",
406 "required: [market] source = \"synthetic\" or \"file\"",
407 ));
408 None
409 }
410 Some(m) => match (m.source.as_deref(), m.seed, m.file) {
411 (Some("synthetic"), Some(seed), None) => match m.history_days {
412 None => Some(MarketSource::Synthetic {
413 seed,
414 history_days: DEFAULT_HISTORY_DAYS,
415 }),
416 Some(d) => match u16::try_from(d).ok().filter(|d| *d <= MAX_HISTORY_DAYS) {
417 Some(history_days) => Some(MarketSource::Synthetic { seed, history_days }),
418 None => {
419 problems.push(problem(
420 "market.history_days",
421 format!("{d} must be 0–{MAX_HISTORY_DAYS}"),
422 ));
423 None
424 }
425 },
426 },
427 (Some("synthetic"), None, None) => {
428 problems.push(problem(
429 "market.seed",
430 "required for source = \"synthetic\"",
431 ));
432 None
433 }
434 (Some("file"), None, Some(_)) if m.history_days.is_some() => {
435 problems.push(problem(
436 "market.history_days",
437 "applies to source = \"synthetic\" only; a data file holds one day",
438 ));
439 None
440 }
441 (Some("file"), None, Some(file)) => Some(MarketSource::File {
442 path: PathBuf::from(file),
443 }),
444 (Some("file"), None, None) => {
445 problems.push(problem("market.file", "required for source = \"file\""));
446 None
447 }
448 (Some(s @ ("synthetic" | "file")), _, _) => {
449 problems.push(problem(
450 "market",
451 format!(
452 "source = {s:?} takes {} only",
453 if s == "file" { "file" } else { "seed" }
454 ),
455 ));
456 None
457 }
458 (other, _, _) => {
459 problems.push(problem(
460 "market.source",
461 format!("{other:?} must be \"synthetic\" or \"file\""),
462 ));
463 None
464 }
465 },
466 };
467 let clock = raw.clock.unwrap_or(RawClock {
468 start: None,
469 end: None,
470 });
471 let start = clock
472 .start
473 .as_deref()
474 .and_then(|s| instant("clock.start", s, &mut problems));
475 let end = clock
476 .end
477 .as_deref()
478 .and_then(|s| instant("clock.end", s, &mut problems));
479 let faults = faults(raw.fault.unwrap_or_default(), &mut problems);
480 let (Some(business), Some(market)) = (business, market) else {
481 return Err(problems);
482 };
483 let dso = raw.dso.and_then(|d| dso(d, business.len(), &mut problems));
484 let start = start.unwrap_or_else(|| business.start() - time::Duration::hours(14));
486 let end = end.unwrap_or_else(|| business.end());
487 if end <= start {
488 problems.push(problem("clock.end", "must be after clock.start"));
489 }
490 if let Some(d) = &dso
491 && !(start..end).contains(&d.request_at)
492 {
493 problems.push(problem(
494 "dso.request_at",
495 "must lie within the clock's range",
496 ));
497 }
498 if !problems.is_empty() {
499 return Err(problems);
500 }
501 Ok(Self {
502 name,
503 day: business.date(),
504 market,
505 start,
506 end,
507 faults,
508 dso,
509 })
510 }
511}