1use std::path::PathBuf;
21
22use flexpool_core::{AssetId, BusinessDay};
23use flexpool_telemetry::sim::{Fault, FaultKind};
24use serde::Deserialize;
25use time::format_description::well_known::Rfc3339;
26use time::{Date, OffsetDateTime};
27
28#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum MarketSource {
31 Synthetic {
33 seed: u64,
35 history_days: u16,
37 },
38 File {
40 path: PathBuf,
42 },
43}
44
45pub const DEFAULT_HISTORY_DAYS: u16 = 28;
47pub const MAX_HISTORY_DAYS: u16 = 60;
49
50#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct Scenario {
53 pub name: String,
55 pub day: Date,
57 pub market: MarketSource,
59 pub start: OffsetDateTime,
61 pub end: OffsetDateTime,
63 pub faults: Vec<Fault>,
65}
66
67#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
69#[error("{location}: {message}")]
70pub struct ScenarioProblem {
71 pub location: String,
73 pub message: String,
75}
76
77#[derive(Deserialize)]
78struct Raw {
79 name: Option<String>,
80 day: Option<toml::Value>,
81 market: Option<RawMarket>,
82 clock: Option<RawClock>,
83 fault: Option<Vec<RawFault>>,
84}
85
86#[derive(Deserialize)]
87struct RawFault {
88 asset: Option<String>,
89 kind: Option<String>,
90 from: Option<String>,
91 to: Option<String>,
92}
93
94#[derive(Deserialize)]
95struct RawMarket {
96 source: Option<String>,
97 seed: Option<u64>,
98 file: Option<String>,
99 history_days: Option<i64>,
100}
101
102#[derive(Deserialize)]
103struct RawClock {
104 start: Option<String>,
105 end: Option<String>,
106}
107
108const KNOWN: &[(&str, &[&str])] = &[
109 ("", &["name", "day", "market", "clock", "fault"]),
110 ("market", &["source", "seed", "file", "history_days"]),
111 ("clock", &["start", "end"]),
112];
113
114fn unknown_keys(table: &toml::Table) -> Vec<ScenarioProblem> {
116 let mut out = Vec::new();
117 for (section, keys) in KNOWN {
118 let t = if section.is_empty() {
119 Some(table)
120 } else {
121 table.get(*section).and_then(toml::Value::as_table)
122 };
123 for key in t.into_iter().flat_map(toml::Table::keys) {
124 if !keys.contains(&key.as_str()) {
125 let location = if section.is_empty() {
126 key.clone()
127 } else {
128 format!("{section}.{key}")
129 };
130 out.push(problem(&location, "unknown key"));
131 }
132 }
133 }
134 let faults = table.get("fault").and_then(toml::Value::as_array);
135 for (i, f) in faults.into_iter().flatten().enumerate() {
136 for key in f.as_table().into_iter().flat_map(toml::Table::keys) {
137 if !["asset", "kind", "from", "to"].contains(&key.as_str()) {
138 out.push(problem(&format!("fault[{}].{key}", i + 1), "unknown key"));
139 }
140 }
141 }
142 out
143}
144
145fn faults(raw: Vec<RawFault>, problems: &mut Vec<ScenarioProblem>) -> Vec<Fault> {
146 let mut out = Vec::new();
147 for (i, f) in raw.into_iter().enumerate() {
148 let at = |k: &str| format!("fault[{}].{k}", i + 1);
149 let asset = match f.asset.map(AssetId::parse) {
150 Some(Ok(id)) => Some(id),
151 Some(Err(e)) => {
152 problems.push(problem(&at("asset"), e.to_string()));
153 None
154 }
155 None => {
156 problems.push(problem(&at("asset"), "required"));
157 None
158 }
159 };
160 let kind = match f.kind.as_deref() {
161 Some("offline") => Some(FaultKind::Offline),
162 Some("stuck") => Some(FaultKind::Stuck),
163 Some("tripped") => Some(FaultKind::Tripped),
164 Some(other) => {
165 problems.push(problem(
166 &at("kind"),
167 format!("{other:?} must be \"offline\", \"stuck\" or \"tripped\""),
168 ));
169 None
170 }
171 None => {
172 problems.push(problem(
173 &at("kind"),
174 "required: \"offline\", \"stuck\" or \"tripped\"",
175 ));
176 None
177 }
178 };
179 let mut when = |k: &str, v: Option<String>| match v {
180 Some(s) => instant(&at(k), &s, problems),
181 None => {
182 problems.push(problem(&at(k), "required"));
183 None
184 }
185 };
186 let (from, to) = (when("from", f.from), when("to", f.to));
187 if let (Some(from), Some(to)) = (from, to)
188 && to <= from
189 {
190 problems.push(problem(&at("to"), "must be after from"));
191 continue;
192 }
193 if let (Some(asset), Some(kind), Some(from), Some(to)) = (asset, kind, from, to) {
194 out.push(Fault {
195 asset,
196 kind,
197 from: from.unix_timestamp(),
198 to: to.unix_timestamp(),
199 });
200 }
201 }
202 out
203}
204
205#[must_use]
208pub fn data_file(text: &str) -> Option<PathBuf> {
209 let table: toml::Table = text.parse().ok()?;
210 let market = table.get("market")?.as_table()?;
211 (market.get("source")?.as_str()? == "file")
212 .then(|| market.get("file")?.as_str().map(PathBuf::from))?
213}
214
215fn problem(location: &str, message: impl Into<String>) -> ScenarioProblem {
216 ScenarioProblem {
217 location: location.to_owned(),
218 message: message.into(),
219 }
220}
221
222fn instant(location: &str, s: &str, problems: &mut Vec<ScenarioProblem>) -> Option<OffsetDateTime> {
223 match OffsetDateTime::parse(s, &Rfc3339) {
224 Ok(t) => Some(t.to_offset(time::UtcOffset::UTC)),
225 Err(_) => {
226 problems.push(problem(
227 location,
228 format!("{s:?} is not an RFC 3339 instant like 2025-10-01T10:00:00+02:00"),
229 ));
230 None
231 }
232 }
233}
234
235impl Scenario {
236 pub fn parse(text: &str) -> Result<Self, Vec<ScenarioProblem>> {
241 let table: toml::Table = text.parse().map_err(|e: toml::de::Error| {
242 let at = e.span().map_or_else(
243 || "(file)".into(),
244 |s| format!("(file) at byte {}", s.start),
245 );
246 vec![problem(&at, e.message())]
247 })?;
248 let mut problems = unknown_keys(&table);
250 let raw: Raw = match toml::Value::Table(table).try_into() {
251 Ok(raw) => raw,
252 Err(e) => {
253 problems.push(problem("(file)", e.message()));
254 return Err(problems);
255 }
256 };
257 let name = raw.name.unwrap_or_else(|| {
258 problems.push(problem("name", "required"));
259 String::new()
260 });
261 let date_fmt = time::macros::format_description!("[year]-[month]-[day]");
262 let day = match raw.day {
263 None => {
264 problems.push(problem("day", "required, e.g. day = \"2025-10-02\""));
265 None
266 }
267 Some(toml::Value::Datetime(d)) => {
268 Date::parse(&d.to_string(), date_fmt).ok().or_else(|| {
269 problems.push(problem("day", format!("{d} is not a calendar date")));
270 None
271 })
272 }
273 Some(toml::Value::String(s)) => Date::parse(&s, date_fmt).ok().or_else(|| {
274 problems.push(problem(
275 "day",
276 format!("{s:?} is not a date like 2025-10-02"),
277 ));
278 None
279 }),
280 Some(other) => {
281 problems.push(problem("day", format!("{other} is not a date")));
282 None
283 }
284 };
285 let business = day.and_then(|d| match BusinessDay::new(d) {
286 Ok(b) => Some(b),
287 Err(e) => {
288 problems.push(problem("day", e.to_string()));
289 None
290 }
291 });
292 let market = match raw.market {
293 None => {
294 problems.push(problem(
295 "market",
296 "required: [market] source = \"synthetic\" or \"file\"",
297 ));
298 None
299 }
300 Some(m) => match (m.source.as_deref(), m.seed, m.file) {
301 (Some("synthetic"), Some(seed), None) => match m.history_days {
302 None => Some(MarketSource::Synthetic {
303 seed,
304 history_days: DEFAULT_HISTORY_DAYS,
305 }),
306 Some(d) => match u16::try_from(d).ok().filter(|d| *d <= MAX_HISTORY_DAYS) {
307 Some(history_days) => Some(MarketSource::Synthetic { seed, history_days }),
308 None => {
309 problems.push(problem(
310 "market.history_days",
311 format!("{d} must be 0–{MAX_HISTORY_DAYS}"),
312 ));
313 None
314 }
315 },
316 },
317 (Some("synthetic"), None, None) => {
318 problems.push(problem(
319 "market.seed",
320 "required for source = \"synthetic\"",
321 ));
322 None
323 }
324 (Some("file"), None, Some(_)) if m.history_days.is_some() => {
325 problems.push(problem(
326 "market.history_days",
327 "applies to source = \"synthetic\" only; a data file holds one day",
328 ));
329 None
330 }
331 (Some("file"), None, Some(file)) => Some(MarketSource::File {
332 path: PathBuf::from(file),
333 }),
334 (Some("file"), None, None) => {
335 problems.push(problem("market.file", "required for source = \"file\""));
336 None
337 }
338 (Some(s @ ("synthetic" | "file")), _, _) => {
339 problems.push(problem(
340 "market",
341 format!(
342 "source = {s:?} takes {} only",
343 if s == "file" { "file" } else { "seed" }
344 ),
345 ));
346 None
347 }
348 (other, _, _) => {
349 problems.push(problem(
350 "market.source",
351 format!("{other:?} must be \"synthetic\" or \"file\""),
352 ));
353 None
354 }
355 },
356 };
357 let clock = raw.clock.unwrap_or(RawClock {
358 start: None,
359 end: None,
360 });
361 let start = clock
362 .start
363 .as_deref()
364 .and_then(|s| instant("clock.start", s, &mut problems));
365 let end = clock
366 .end
367 .as_deref()
368 .and_then(|s| instant("clock.end", s, &mut problems));
369 let faults = faults(raw.fault.unwrap_or_default(), &mut problems);
370 let (Some(business), Some(market)) = (business, market) else {
371 return Err(problems);
372 };
373 let start = start.unwrap_or_else(|| business.start() - time::Duration::hours(14));
375 let end = end.unwrap_or_else(|| business.end());
376 if end <= start {
377 problems.push(problem("clock.end", "must be after clock.start"));
378 }
379 if !problems.is_empty() {
380 return Err(problems);
381 }
382 Ok(Self {
383 name,
384 day: business.date(),
385 market,
386 start,
387 end,
388 faults,
389 })
390 }
391}