1#![forbid(unsafe_code)]
12
13use std::collections::BTreeMap;
14use std::fmt;
15use std::str::FromStr as _;
16
17use flexpool_core::{EurPerMwh, Granularity, RoundDirection};
18use rust_decimal::Decimal;
19use serde::{Deserialize, Serialize};
20use time::{Date, OffsetDateTime, Time};
21
22const BUNDLED_SOURCES: &str = include_str!("../rules/sources.toml");
23const BUNDLED_PACKS: &[(&str, &str)] = &[
24 (
25 "rules/day-ahead.toml",
26 include_str!("../rules/day-ahead.toml"),
27 ),
28 (
29 "rules/intraday.toml",
30 include_str!("../rules/intraday.toml"),
31 ),
32 ("rules/alarms.toml", include_str!("../rules/alarms.toml")),
33];
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "kebab-case")]
38pub enum SourceStatus {
39 Checked,
41 Unverified,
43}
44
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47#[serde(deny_unknown_fields)]
48pub struct Source {
49 pub id: String,
51 pub title: String,
53 pub publisher: String,
55 pub url: String,
57 pub date: Date,
59 pub status: SourceStatus,
61 #[serde(default)]
63 pub sha256: Option<String>,
64}
65
66#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
68#[serde(untagged)]
69pub enum Value {
70 Minutes(u16),
72 Gate {
74 local_time: Time,
76 day_offset: i8,
78 },
79 PriceRange {
81 min: EurPerMwh,
83 max: EurPerMwh,
85 },
86 Step(Granularity),
88 Alarm(Box<AlarmDef>),
90 Rate {
92 count: u32,
94 window_secs: u32,
96 },
97 Seconds(u32),
99}
100
101#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
103pub struct Texts {
104 pub de: String,
106 pub en: String,
108}
109
110#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
112pub struct AlarmDef {
113 pub priority: u8,
115 pub respond_minutes: u16,
117 pub on_delay_secs: u32,
119 pub off_delay_secs: u32,
121 pub threshold: Option<Decimal>,
123 pub title: Texts,
125 pub cause: Texts,
127 pub consequence: Texts,
129 pub action: Texts,
131}
132
133#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
135pub struct Entry {
136 pub id: String,
138 pub valid_from: Date,
140 pub valid_until: Option<Date>,
142 pub source: String,
144 pub clause: String,
146 pub value: Value,
148 pub pack: String,
150}
151
152impl Entry {
153 #[must_use]
155 pub fn applies(&self, day: Date) -> bool {
156 self.valid_from <= day && self.valid_until.is_none_or(|until| day < until)
157 }
158}
159
160#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
162#[error("{location}: {message}")]
163pub struct RuleProblem {
164 pub location: String,
166 pub message: String,
168}
169
170#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
172#[error("no entry of rule {rule} applies to delivery day {day}")]
173pub struct Missing {
174 pub rule: String,
176 pub day: Date,
178}
179
180#[derive(Debug, Clone)]
182pub struct RuleBook {
183 sources: BTreeMap<String, Source>,
184 entries: BTreeMap<String, Vec<Entry>>,
185}
186
187#[derive(Deserialize)]
188#[serde(deny_unknown_fields)]
189struct Registry {
190 source: Vec<Source>,
191}
192
193#[derive(Deserialize)]
194#[serde(deny_unknown_fields)]
195struct Pack {
196 rule: Vec<RawEntry>,
197}
198
199#[derive(Deserialize)]
200#[serde(deny_unknown_fields)]
201struct RawEntry {
202 id: String,
203 valid_from: Date,
204 valid_until: Option<Date>,
205 source: String,
206 clause: String,
207 minutes: Option<u16>,
208 local_time: Option<String>,
209 day_offset: Option<i8>,
210 min: Option<String>,
211 max: Option<String>,
212 step: Option<String>,
213 direction: Option<String>,
214 alarm: Option<RawAlarm>,
215 count: Option<u32>,
216 window_secs: Option<u32>,
217 seconds: Option<u32>,
218}
219
220#[derive(Deserialize)]
221#[serde(deny_unknown_fields)]
222struct RawAlarm {
223 priority: u8,
224 respond_minutes: u16,
225 on_delay_secs: u32,
226 off_delay_secs: u32,
227 threshold: Option<String>,
228 title_de: String,
229 title_en: String,
230 cause_de: String,
231 cause_en: String,
232 consequence_de: String,
233 consequence_en: String,
234 action_de: String,
235 action_en: String,
236}
237
238fn alarm(raw: &RawAlarm) -> Result<Value, String> {
239 if !(1..=3).contains(&raw.priority) {
240 return Err(format!("priority {} must be 1, 2 or 3", raw.priority));
241 }
242 if raw.respond_minutes == 0 {
243 return Err("respond_minutes must be positive".to_owned());
244 }
245 if raw.on_delay_secs > 86_400 || raw.off_delay_secs > 86_400 {
246 return Err("delays must be at most one day".to_owned());
247 }
248 let texts = [
249 ("title_de", &raw.title_de),
250 ("title_en", &raw.title_en),
251 ("cause_de", &raw.cause_de),
252 ("cause_en", &raw.cause_en),
253 ("consequence_de", &raw.consequence_de),
254 ("consequence_en", &raw.consequence_en),
255 ("action_de", &raw.action_de),
256 ("action_en", &raw.action_en),
257 ];
258 if let Some((k, _)) = texts.iter().find(|(_, v)| v.trim().is_empty()) {
259 return Err(format!("{k} must not be empty"));
260 }
261 if !raw.title_de.contains("{subject}") || !raw.title_en.contains("{subject}") {
262 return Err("titles must name the {subject}".to_owned());
263 }
264 let threshold = match raw.threshold.as_deref() {
265 None => None,
266 Some(t) => {
267 let d = decimal(t)?;
268 if d <= Decimal::ZERO || d > Decimal::ONE {
269 return Err(format!("threshold {d} must be in (0, 1]"));
270 }
271 Some(d)
272 }
273 };
274 let t = |de: &String, en: &String| Texts {
275 de: de.clone(),
276 en: en.clone(),
277 };
278 Ok(Value::Alarm(Box::new(AlarmDef {
279 priority: raw.priority,
280 respond_minutes: raw.respond_minutes,
281 on_delay_secs: raw.on_delay_secs,
282 off_delay_secs: raw.off_delay_secs,
283 threshold,
284 title: t(&raw.title_de, &raw.title_en),
285 cause: t(&raw.cause_de, &raw.cause_en),
286 consequence: t(&raw.consequence_de, &raw.consequence_en),
287 action: t(&raw.action_de, &raw.action_en),
288 })))
289}
290
291fn decimal(s: &str) -> Result<Decimal, String> {
292 Decimal::from_str(s).map_err(|_| format!("{s:?} is not a decimal"))
293}
294
295fn value(raw: &RawEntry) -> Result<Value, String> {
296 let stray: Vec<&str> = [
298 (
299 "day_offset",
300 raw.day_offset.is_some() && raw.local_time.is_none(),
301 ),
302 ("max", raw.max.is_some() && raw.min.is_none()),
303 ("direction", raw.direction.is_some() && raw.step.is_none()),
304 (
305 "window_secs",
306 raw.window_secs.is_some() && raw.count.is_none(),
307 ),
308 ]
309 .into_iter()
310 .filter_map(|(f, bad)| bad.then_some(f))
311 .collect();
312 if !stray.is_empty() {
313 return Err(format!(
314 "field(s) {} do not belong to this value",
315 stray.join(", ")
316 ));
317 }
318 let shapes = [
319 raw.minutes.is_some(),
320 raw.local_time.is_some(),
321 raw.min.is_some(),
322 raw.step.is_some(),
323 raw.alarm.is_some(),
324 raw.count.is_some(),
325 raw.seconds.is_some(),
326 ];
327 if shapes.iter().filter(|s| **s).count() > 1 {
328 return Err(
329 "exactly one of minutes, local_time, min/max, step, alarm, count or seconds must be given"
330 .to_owned(),
331 );
332 }
333 if let Some(a) = &raw.alarm {
334 return alarm(a);
335 }
336 if let Some(count) = raw.count {
337 let window_secs = raw.window_secs.ok_or("a rate needs window_secs")?;
338 if count == 0 || window_secs == 0 {
339 return Err("count and window_secs must be positive".to_owned());
340 }
341 return Ok(Value::Rate { count, window_secs });
342 }
343 if let Some(seconds) = raw.seconds {
344 if seconds == 0 {
345 return Err("seconds must be positive".to_owned());
346 }
347 return Ok(Value::Seconds(seconds));
348 }
349 let time_fmt = time::macros::format_description!("[hour]:[minute]");
350 match (&raw.minutes, &raw.local_time, &raw.min, &raw.step) {
351 (Some(m), None, None, None) if *m > 0 && 60 % *m == 0 => Ok(Value::Minutes(*m)),
352 (Some(m), None, None, None) => Err(format!("minutes {m} must divide 60")),
353 (None, Some(t), None, None) => Ok(Value::Gate {
354 local_time: Time::parse(t, time_fmt).map_err(|_| format!("{t:?} is not HH:MM"))?,
355 day_offset: raw.day_offset.ok_or("a gate needs day_offset")?,
356 }),
357 (None, None, Some(min), None) => {
358 let max = raw.max.as_deref().ok_or("a price range needs max")?;
359 let (min, max) = (decimal(min)?, decimal(max)?);
360 if min >= max {
361 return Err(format!("min {min} must be below max {max}"));
362 }
363 Ok(Value::PriceRange {
364 min: EurPerMwh::new(min),
365 max: EurPerMwh::new(max),
366 })
367 }
368 (None, None, None, Some(step)) => {
369 let direction = match raw.direction.as_deref() {
370 Some("toward-zero") => RoundDirection::TowardZero,
371 Some("away-from-zero") => RoundDirection::AwayFromZero,
372 Some("nearest-half-even") => RoundDirection::NearestHalfEven,
373 other => {
374 return Err(format!(
375 "direction {other:?} must be toward-zero, away-from-zero or nearest-half-even"
376 ));
377 }
378 };
379 Granularity::new(decimal(step)?, direction)
380 .map(Value::Step)
381 .map_err(|e| e.to_string())
382 }
383 _ => Err(
384 "exactly one of minutes, local_time, min/max, step, alarm, count or seconds must be given"
385 .to_owned(),
386 ),
387 }
388}
389
390impl RuleBook {
391 pub fn bundled_texts() -> impl Iterator<Item = (&'static str, &'static str)> {
394 std::iter::once(("rules/sources.toml", BUNDLED_SOURCES))
395 .chain(BUNDLED_PACKS.iter().copied())
396 }
397
398 pub fn bundled() -> Result<Self, Vec<RuleProblem>> {
403 Self::parse(BUNDLED_SOURCES, BUNDLED_PACKS)
404 }
405
406 pub fn parse(sources: &str, packs: &[(&str, &str)]) -> Result<Self, Vec<RuleProblem>> {
411 let mut problems = Vec::new();
412 let mut registry = BTreeMap::new();
413 match toml::from_str::<Registry>(sources) {
414 Err(e) => problems.push(RuleProblem {
415 location: "rules/sources.toml".into(),
416 message: e.message().to_owned(),
417 }),
418 Ok(r) => {
419 for s in r.source {
420 let location = format!("rules/sources.toml {}", s.id);
421 for (field, v) in [("title", &s.title), ("publisher", &s.publisher)] {
422 if v.trim().is_empty() {
423 problems.push(RuleProblem {
424 location: location.clone(),
425 message: format!("{field} is empty"),
426 });
427 }
428 }
429 if !s.url.starts_with("https://") {
430 problems.push(RuleProblem {
431 location: location.clone(),
432 message: "url must be https".into(),
433 });
434 }
435 if registry.insert(s.id.clone(), s).is_some() {
436 problems.push(RuleProblem {
437 location,
438 message: "duplicate source id".into(),
439 });
440 }
441 }
442 }
443 }
444 let mut entries: BTreeMap<String, Vec<Entry>> = BTreeMap::new();
445 for (name, text) in packs {
446 let pack = match toml::from_str::<Pack>(text) {
447 Ok(p) => p,
448 Err(e) => {
449 problems.push(RuleProblem {
450 location: (*name).to_owned(),
451 message: e.message().to_owned(),
452 });
453 continue;
454 }
455 };
456 for raw in pack.rule {
457 let location = format!("{name} {}", raw.id);
458 if !registry.contains_key(&raw.source) {
459 problems.push(RuleProblem {
460 location: location.clone(),
461 message: format!("cites unregistered source {:?}", raw.source),
462 });
463 }
464 if raw.valid_until.is_some_and(|u| u <= raw.valid_from) {
465 problems.push(RuleProblem {
466 location: location.clone(),
467 message: "valid_until must be after valid_from".into(),
468 });
469 }
470 match value(&raw) {
471 Err(message) => problems.push(RuleProblem { location, message }),
472 Ok(value) => entries.entry(raw.id.clone()).or_default().push(Entry {
473 id: raw.id,
474 valid_from: raw.valid_from,
475 valid_until: raw.valid_until,
476 source: raw.source,
477 clause: raw.clause,
478 value,
479 pack: (*name).to_owned(),
480 }),
481 }
482 }
483 }
484 for (id, list) in &mut entries {
485 list.sort_by_key(|e| e.valid_from);
486 for pair in list.windows(2) {
487 if pair[0]
488 .valid_until
489 .is_none_or(|until| until > pair[1].valid_from)
490 {
491 problems.push(RuleProblem {
492 location: id.to_string(),
493 message: format!(
494 "entries from {} ({}) and {} ({}) overlap",
495 pair[0].valid_from, pair[0].pack, pair[1].valid_from, pair[1].pack
496 ),
497 });
498 }
499 }
500 }
501 if problems.is_empty() {
502 Ok(Self {
503 sources: registry,
504 entries,
505 })
506 } else {
507 Err(problems)
508 }
509 }
510
511 pub fn sources(&self) -> impl Iterator<Item = &Source> {
513 self.sources.values()
514 }
515
516 #[must_use]
518 pub fn source_of(&self, entry: &Entry) -> Option<&Source> {
519 self.sources.get(&entry.source)
520 }
521
522 pub fn entries(&self) -> impl Iterator<Item = &Entry> {
524 self.entries.values().flatten()
525 }
526
527 pub fn entry(&self, rule: &str, day: Date) -> Result<&Entry, Missing> {
532 self.entries
533 .get(rule)
534 .and_then(|list| list.iter().find(|e| e.applies(day)))
535 .ok_or_else(|| Missing {
536 rule: rule.to_owned(),
537 day,
538 })
539 }
540
541 pub fn da_mtu(&self, day: Date) -> Result<(u16, &Entry), Missing> {
546 let e = self.entry("da.mtu", day)?;
547 match e.value {
548 Value::Minutes(m) => Ok((m, e)),
549 _ => Err(Missing {
550 rule: "da.mtu".into(),
551 day,
552 }),
553 }
554 }
555
556 pub fn gate(&self, rule: &str, day: Date) -> Result<(OffsetDateTime, &Entry), Missing> {
561 let e = self.entry(rule, day)?;
562 let missing = || Missing {
563 rule: rule.to_owned(),
564 day,
565 };
566 let Value::Gate {
567 local_time,
568 day_offset,
569 } = e.value
570 else {
571 return Err(missing());
572 };
573 let date = day
574 .checked_add(time::Duration::days(i64::from(day_offset)))
575 .ok_or_else(missing)?;
576 let period = flexpool_core::calendar::BusinessDay::new(date).map_err(|_| missing())?;
577 let target = local_time - Time::MIDNIGHT;
580 let mut instant = period.start() + target;
581 let local = flexpool_core::calendar::to_berlin(instant).time() - Time::MIDNIGHT;
582 if local != target {
583 instant += target - local;
584 }
585 if flexpool_core::calendar::to_berlin(instant).time() != local_time {
587 return Err(missing());
588 }
589 Ok((instant, e))
590 }
591
592 pub fn da_price_limits(&self, day: Date) -> Result<(EurPerMwh, EurPerMwh, &Entry), Missing> {
597 let e = self.entry("da.price-limits", day)?;
598 match e.value {
599 Value::PriceRange { min, max } => Ok((min, max, e)),
600 _ => Err(Missing {
601 rule: "da.price-limits".into(),
602 day,
603 }),
604 }
605 }
606
607 pub fn alarm(&self, rule: &str, day: Date) -> Result<(&AlarmDef, &Entry), Missing> {
612 let e = self.entry(rule, day)?;
613 match &e.value {
614 Value::Alarm(a) => Ok((a, e)),
615 _ => Err(Missing {
616 rule: rule.to_owned(),
617 day,
618 }),
619 }
620 }
621
622 pub fn rate(&self, rule: &str, day: Date) -> Result<(u32, u32, &Entry), Missing> {
627 let e = self.entry(rule, day)?;
628 match e.value {
629 Value::Rate { count, window_secs } => Ok((count, window_secs, e)),
630 _ => Err(Missing {
631 rule: rule.to_owned(),
632 day,
633 }),
634 }
635 }
636
637 pub fn seconds(&self, rule: &str, day: Date) -> Result<(u32, &Entry), Missing> {
642 let e = self.entry(rule, day)?;
643 match e.value {
644 Value::Seconds(s) => Ok((s, e)),
645 _ => Err(Missing {
646 rule: rule.to_owned(),
647 day,
648 }),
649 }
650 }
651
652 pub fn granularity(&self, rule: &str, day: Date) -> Result<(Granularity, &Entry), Missing> {
657 let e = self.entry(rule, day)?;
658 match e.value {
659 Value::Step(g) => Ok((g, e)),
660 _ => Err(Missing {
661 rule: rule.to_owned(),
662 day,
663 }),
664 }
665 }
666}
667
668impl fmt::Display for SourceStatus {
669 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
670 f.write_str(match self {
671 Self::Checked => "checked",
672 Self::Unverified => "unverified",
673 })
674 }
675}