#![forbid(unsafe_code)]
use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr as _;
use flexpool_core::{EurPerMwh, Granularity, RoundDirection};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use time::{Date, OffsetDateTime, Time};
const BUNDLED_SOURCES: &str = include_str!("../rules/sources.toml");
const BUNDLED_PACKS: &[(&str, &str)] = &[
(
"rules/day-ahead.toml",
include_str!("../rules/day-ahead.toml"),
),
(
"rules/intraday.toml",
include_str!("../rules/intraday.toml"),
),
("rules/alarms.toml", include_str!("../rules/alarms.toml")),
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum SourceStatus {
Checked,
Unverified,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Source {
pub id: String,
pub title: String,
pub publisher: String,
pub url: String,
pub date: Date,
pub status: SourceStatus,
#[serde(default)]
pub sha256: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(untagged)]
pub enum Value {
Minutes(u16),
Gate {
local_time: Time,
day_offset: i8,
},
PriceRange {
min: EurPerMwh,
max: EurPerMwh,
},
Step(Granularity),
Alarm(Box<AlarmDef>),
Rate {
count: u32,
window_secs: u32,
},
Seconds(u32),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Texts {
pub de: String,
pub en: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct AlarmDef {
pub priority: u8,
pub respond_minutes: u16,
pub on_delay_secs: u32,
pub off_delay_secs: u32,
pub threshold: Option<Decimal>,
pub title: Texts,
pub cause: Texts,
pub consequence: Texts,
pub action: Texts,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Entry {
pub id: String,
pub valid_from: Date,
pub valid_until: Option<Date>,
pub source: String,
pub clause: String,
pub value: Value,
pub pack: String,
}
impl Entry {
#[must_use]
pub fn applies(&self, day: Date) -> bool {
self.valid_from <= day && self.valid_until.is_none_or(|until| day < until)
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{location}: {message}")]
pub struct RuleProblem {
pub location: String,
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("no entry of rule {rule} applies to delivery day {day}")]
pub struct Missing {
pub rule: String,
pub day: Date,
}
#[derive(Debug, Clone)]
pub struct RuleBook {
sources: BTreeMap<String, Source>,
entries: BTreeMap<String, Vec<Entry>>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Registry {
source: Vec<Source>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Pack {
rule: Vec<RawEntry>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawEntry {
id: String,
valid_from: Date,
valid_until: Option<Date>,
source: String,
clause: String,
minutes: Option<u16>,
local_time: Option<String>,
day_offset: Option<i8>,
min: Option<String>,
max: Option<String>,
step: Option<String>,
direction: Option<String>,
alarm: Option<RawAlarm>,
count: Option<u32>,
window_secs: Option<u32>,
seconds: Option<u32>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawAlarm {
priority: u8,
respond_minutes: u16,
on_delay_secs: u32,
off_delay_secs: u32,
threshold: Option<String>,
title_de: String,
title_en: String,
cause_de: String,
cause_en: String,
consequence_de: String,
consequence_en: String,
action_de: String,
action_en: String,
}
fn alarm(raw: &RawAlarm) -> Result<Value, String> {
if !(1..=3).contains(&raw.priority) {
return Err(format!("priority {} must be 1, 2 or 3", raw.priority));
}
if raw.respond_minutes == 0 {
return Err("respond_minutes must be positive".to_owned());
}
if raw.on_delay_secs > 86_400 || raw.off_delay_secs > 86_400 {
return Err("delays must be at most one day".to_owned());
}
let texts = [
("title_de", &raw.title_de),
("title_en", &raw.title_en),
("cause_de", &raw.cause_de),
("cause_en", &raw.cause_en),
("consequence_de", &raw.consequence_de),
("consequence_en", &raw.consequence_en),
("action_de", &raw.action_de),
("action_en", &raw.action_en),
];
if let Some((k, _)) = texts.iter().find(|(_, v)| v.trim().is_empty()) {
return Err(format!("{k} must not be empty"));
}
if !raw.title_de.contains("{subject}") || !raw.title_en.contains("{subject}") {
return Err("titles must name the {subject}".to_owned());
}
let threshold = match raw.threshold.as_deref() {
None => None,
Some(t) => {
let d = decimal(t)?;
if d <= Decimal::ZERO || d > Decimal::ONE {
return Err(format!("threshold {d} must be in (0, 1]"));
}
Some(d)
}
};
let t = |de: &String, en: &String| Texts {
de: de.clone(),
en: en.clone(),
};
Ok(Value::Alarm(Box::new(AlarmDef {
priority: raw.priority,
respond_minutes: raw.respond_minutes,
on_delay_secs: raw.on_delay_secs,
off_delay_secs: raw.off_delay_secs,
threshold,
title: t(&raw.title_de, &raw.title_en),
cause: t(&raw.cause_de, &raw.cause_en),
consequence: t(&raw.consequence_de, &raw.consequence_en),
action: t(&raw.action_de, &raw.action_en),
})))
}
fn decimal(s: &str) -> Result<Decimal, String> {
Decimal::from_str(s).map_err(|_| format!("{s:?} is not a decimal"))
}
fn value(raw: &RawEntry) -> Result<Value, String> {
let stray: Vec<&str> = [
(
"day_offset",
raw.day_offset.is_some() && raw.local_time.is_none(),
),
("max", raw.max.is_some() && raw.min.is_none()),
("direction", raw.direction.is_some() && raw.step.is_none()),
(
"window_secs",
raw.window_secs.is_some() && raw.count.is_none(),
),
]
.into_iter()
.filter_map(|(f, bad)| bad.then_some(f))
.collect();
if !stray.is_empty() {
return Err(format!(
"field(s) {} do not belong to this value",
stray.join(", ")
));
}
let shapes = [
raw.minutes.is_some(),
raw.local_time.is_some(),
raw.min.is_some(),
raw.step.is_some(),
raw.alarm.is_some(),
raw.count.is_some(),
raw.seconds.is_some(),
];
if shapes.iter().filter(|s| **s).count() > 1 {
return Err(
"exactly one of minutes, local_time, min/max, step, alarm, count or seconds must be given"
.to_owned(),
);
}
if let Some(a) = &raw.alarm {
return alarm(a);
}
if let Some(count) = raw.count {
let window_secs = raw.window_secs.ok_or("a rate needs window_secs")?;
if count == 0 || window_secs == 0 {
return Err("count and window_secs must be positive".to_owned());
}
return Ok(Value::Rate { count, window_secs });
}
if let Some(seconds) = raw.seconds {
if seconds == 0 {
return Err("seconds must be positive".to_owned());
}
return Ok(Value::Seconds(seconds));
}
let time_fmt = time::macros::format_description!("[hour]:[minute]");
match (&raw.minutes, &raw.local_time, &raw.min, &raw.step) {
(Some(m), None, None, None) if *m > 0 && 60 % *m == 0 => Ok(Value::Minutes(*m)),
(Some(m), None, None, None) => Err(format!("minutes {m} must divide 60")),
(None, Some(t), None, None) => Ok(Value::Gate {
local_time: Time::parse(t, time_fmt).map_err(|_| format!("{t:?} is not HH:MM"))?,
day_offset: raw.day_offset.ok_or("a gate needs day_offset")?,
}),
(None, None, Some(min), None) => {
let max = raw.max.as_deref().ok_or("a price range needs max")?;
let (min, max) = (decimal(min)?, decimal(max)?);
if min >= max {
return Err(format!("min {min} must be below max {max}"));
}
Ok(Value::PriceRange {
min: EurPerMwh::new(min),
max: EurPerMwh::new(max),
})
}
(None, None, None, Some(step)) => {
let direction = match raw.direction.as_deref() {
Some("toward-zero") => RoundDirection::TowardZero,
Some("away-from-zero") => RoundDirection::AwayFromZero,
Some("nearest-half-even") => RoundDirection::NearestHalfEven,
other => {
return Err(format!(
"direction {other:?} must be toward-zero, away-from-zero or nearest-half-even"
));
}
};
Granularity::new(decimal(step)?, direction)
.map(Value::Step)
.map_err(|e| e.to_string())
}
_ => Err(
"exactly one of minutes, local_time, min/max, step, alarm, count or seconds must be given"
.to_owned(),
),
}
}
impl RuleBook {
pub fn bundled_texts() -> impl Iterator<Item = (&'static str, &'static str)> {
std::iter::once(("rules/sources.toml", BUNDLED_SOURCES))
.chain(BUNDLED_PACKS.iter().copied())
}
pub fn bundled() -> Result<Self, Vec<RuleProblem>> {
Self::parse(BUNDLED_SOURCES, BUNDLED_PACKS)
}
pub fn parse(sources: &str, packs: &[(&str, &str)]) -> Result<Self, Vec<RuleProblem>> {
let mut problems = Vec::new();
let mut registry = BTreeMap::new();
match toml::from_str::<Registry>(sources) {
Err(e) => problems.push(RuleProblem {
location: "rules/sources.toml".into(),
message: e.message().to_owned(),
}),
Ok(r) => {
for s in r.source {
let location = format!("rules/sources.toml {}", s.id);
for (field, v) in [("title", &s.title), ("publisher", &s.publisher)] {
if v.trim().is_empty() {
problems.push(RuleProblem {
location: location.clone(),
message: format!("{field} is empty"),
});
}
}
if !s.url.starts_with("https://") {
problems.push(RuleProblem {
location: location.clone(),
message: "url must be https".into(),
});
}
if registry.insert(s.id.clone(), s).is_some() {
problems.push(RuleProblem {
location,
message: "duplicate source id".into(),
});
}
}
}
}
let mut entries: BTreeMap<String, Vec<Entry>> = BTreeMap::new();
for (name, text) in packs {
let pack = match toml::from_str::<Pack>(text) {
Ok(p) => p,
Err(e) => {
problems.push(RuleProblem {
location: (*name).to_owned(),
message: e.message().to_owned(),
});
continue;
}
};
for raw in pack.rule {
let location = format!("{name} {}", raw.id);
if !registry.contains_key(&raw.source) {
problems.push(RuleProblem {
location: location.clone(),
message: format!("cites unregistered source {:?}", raw.source),
});
}
if raw.valid_until.is_some_and(|u| u <= raw.valid_from) {
problems.push(RuleProblem {
location: location.clone(),
message: "valid_until must be after valid_from".into(),
});
}
match value(&raw) {
Err(message) => problems.push(RuleProblem { location, message }),
Ok(value) => entries.entry(raw.id.clone()).or_default().push(Entry {
id: raw.id,
valid_from: raw.valid_from,
valid_until: raw.valid_until,
source: raw.source,
clause: raw.clause,
value,
pack: (*name).to_owned(),
}),
}
}
}
for (id, list) in &mut entries {
list.sort_by_key(|e| e.valid_from);
for pair in list.windows(2) {
if pair[0]
.valid_until
.is_none_or(|until| until > pair[1].valid_from)
{
problems.push(RuleProblem {
location: id.to_string(),
message: format!(
"entries from {} ({}) and {} ({}) overlap",
pair[0].valid_from, pair[0].pack, pair[1].valid_from, pair[1].pack
),
});
}
}
}
if problems.is_empty() {
Ok(Self {
sources: registry,
entries,
})
} else {
Err(problems)
}
}
pub fn sources(&self) -> impl Iterator<Item = &Source> {
self.sources.values()
}
#[must_use]
pub fn source_of(&self, entry: &Entry) -> Option<&Source> {
self.sources.get(&entry.source)
}
pub fn entries(&self) -> impl Iterator<Item = &Entry> {
self.entries.values().flatten()
}
pub fn entry(&self, rule: &str, day: Date) -> Result<&Entry, Missing> {
self.entries
.get(rule)
.and_then(|list| list.iter().find(|e| e.applies(day)))
.ok_or_else(|| Missing {
rule: rule.to_owned(),
day,
})
}
pub fn da_mtu(&self, day: Date) -> Result<(u16, &Entry), Missing> {
let e = self.entry("da.mtu", day)?;
match e.value {
Value::Minutes(m) => Ok((m, e)),
_ => Err(Missing {
rule: "da.mtu".into(),
day,
}),
}
}
pub fn gate(&self, rule: &str, day: Date) -> Result<(OffsetDateTime, &Entry), Missing> {
let e = self.entry(rule, day)?;
let missing = || Missing {
rule: rule.to_owned(),
day,
};
let Value::Gate {
local_time,
day_offset,
} = e.value
else {
return Err(missing());
};
let date = day
.checked_add(time::Duration::days(i64::from(day_offset)))
.ok_or_else(missing)?;
let period = flexpool_core::calendar::BusinessDay::new(date).map_err(|_| missing())?;
let target = local_time - Time::MIDNIGHT;
let mut instant = period.start() + target;
let local = flexpool_core::calendar::to_berlin(instant).time() - Time::MIDNIGHT;
if local != target {
instant += target - local;
}
if flexpool_core::calendar::to_berlin(instant).time() != local_time {
return Err(missing());
}
Ok((instant, e))
}
pub fn da_price_limits(&self, day: Date) -> Result<(EurPerMwh, EurPerMwh, &Entry), Missing> {
let e = self.entry("da.price-limits", day)?;
match e.value {
Value::PriceRange { min, max } => Ok((min, max, e)),
_ => Err(Missing {
rule: "da.price-limits".into(),
day,
}),
}
}
pub fn alarm(&self, rule: &str, day: Date) -> Result<(&AlarmDef, &Entry), Missing> {
let e = self.entry(rule, day)?;
match &e.value {
Value::Alarm(a) => Ok((a, e)),
_ => Err(Missing {
rule: rule.to_owned(),
day,
}),
}
}
pub fn rate(&self, rule: &str, day: Date) -> Result<(u32, u32, &Entry), Missing> {
let e = self.entry(rule, day)?;
match e.value {
Value::Rate { count, window_secs } => Ok((count, window_secs, e)),
_ => Err(Missing {
rule: rule.to_owned(),
day,
}),
}
}
pub fn seconds(&self, rule: &str, day: Date) -> Result<(u32, &Entry), Missing> {
let e = self.entry(rule, day)?;
match e.value {
Value::Seconds(s) => Ok((s, e)),
_ => Err(Missing {
rule: rule.to_owned(),
day,
}),
}
}
pub fn granularity(&self, rule: &str, day: Date) -> Result<(Granularity, &Entry), Missing> {
let e = self.entry(rule, day)?;
match e.value {
Value::Step(g) => Ok((g, e)),
_ => Err(Missing {
rule: rule.to_owned(),
day,
}),
}
}
}
impl fmt::Display for SourceStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Checked => "checked",
Self::Unverified => "unverified",
})
}
}