Skip to main content

flexpool_rules/
lib.rs

1//! flexpool market rules.
2//!
3//! Every market rule — the day-ahead time unit, a gate closure, a price limit, an order
4//! granularity — is a dated entry citing a registered source. Rules are keyed by **delivery day**:
5//! the 15-minute day-ahead market went live for delivery day 2025-10-01, so a replay of
6//! 2025-09-30 must run hourly and one of 2025-10-01 quarter-hourly.
7//!
8//! The packs in `rules/` (this crate's, linked from the repository root) are embedded at compile time
9//! ([`RuleBook::bundled`]); this crate performs no I/O.
10
11#![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/// How far a source has been confirmed.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "kebab-case")]
38pub enum SourceStatus {
39    /// The value was confirmed against this primary document.
40    Checked,
41    /// The best available reference; confirm before a real market depends on it.
42    Unverified,
43}
44
45/// A registered source.
46#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47#[serde(deny_unknown_fields)]
48pub struct Source {
49    /// Stable id cited by rule entries.
50    pub id: String,
51    /// Document title.
52    pub title: String,
53    /// Publisher.
54    pub publisher: String,
55    /// Retrieval URL.
56    pub url: String,
57    /// Publication date.
58    pub date: Date,
59    /// Confirmation status.
60    pub status: SourceStatus,
61    /// SHA-256 of the mirrored document, once mirrored.
62    #[serde(default)]
63    pub sha256: Option<String>,
64}
65
66/// A rule's value.
67#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
68#[serde(untagged)]
69pub enum Value {
70    /// A duration in minutes (market time units).
71    Minutes(u16),
72    /// A local Berlin time on the delivery day plus an offset in days (gates, publications).
73    Gate {
74        /// Local wall-clock time in Europe/Berlin.
75        local_time: Time,
76        /// Days relative to the delivery day (−1 = the day before).
77        day_offset: i8,
78    },
79    /// A price range.
80    PriceRange {
81        /// Minimum.
82        min: EurPerMwh,
83        /// Maximum.
84        max: EurPerMwh,
85    },
86    /// A quantity or price step with its rounding direction.
87    Step(Granularity),
88    /// An alarm type: the rationalised record of ISA-18.2 (priority, delays, texts).
89    Alarm(Box<AlarmDef>),
90    /// A rate: `count` per `window_secs` (alarm philosophy).
91    Rate {
92        /// Count.
93        count: u32,
94        /// Window in seconds.
95        window_secs: u32,
96    },
97    /// A duration in seconds.
98    Seconds(u32),
99}
100
101/// A text in German and English.
102#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
103pub struct Texts {
104    /// German.
105    pub de: String,
106    /// English.
107    pub en: String,
108}
109
110/// One alarm type, as rationalised: what it means, what to do, how fast, and when it fires.
111#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
112pub struct AlarmDef {
113    /// 1 high, 2 medium, 3 low.
114    pub priority: u8,
115    /// Time to respond, minutes.
116    pub respond_minutes: u16,
117    /// The condition must last this long before the alarm is raised.
118    pub on_delay_secs: u32,
119    /// The condition must be absent this long before the alarm clears.
120    pub off_delay_secs: u32,
121    /// A share in (0, 1], for alarms on a ratio (pool availability).
122    pub threshold: Option<Decimal>,
123    /// Title; `{subject}` is replaced by the connection, asset or pool.
124    pub title: Texts,
125    /// Likely cause.
126    pub cause: Texts,
127    /// Consequence if nobody acts.
128    pub consequence: Texts,
129    /// What the operator does.
130    pub action: Texts,
131}
132
133/// One dated rule entry.
134#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
135pub struct Entry {
136    /// Rule id, e.g. `da.mtu`.
137    pub id: String,
138    /// First delivery day the entry applies to.
139    pub valid_from: Date,
140    /// First delivery day it no longer applies to (exclusive), if any.
141    pub valid_until: Option<Date>,
142    /// Source id.
143    pub source: String,
144    /// What the source says, in a sentence.
145    pub clause: String,
146    /// The value.
147    pub value: Value,
148    /// The pack file the entry came from.
149    pub pack: String,
150}
151
152impl Entry {
153    /// Whether the entry applies to `day`.
154    #[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/// One problem found while loading rule packs.
161#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
162#[error("{location}: {message}")]
163pub struct RuleProblem {
164    /// Pack file and rule id, or the registry.
165    pub location: String,
166    /// What is wrong.
167    pub message: String,
168}
169
170/// A lookup failed: no entry for this rule and day.
171#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
172#[error("no entry of rule {rule} applies to delivery day {day}")]
173pub struct Missing {
174    /// Rule id.
175    pub rule: String,
176    /// Delivery day.
177    pub day: Date,
178}
179
180/// The loaded rule packs and the source registry.
181#[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    // Fields that belong to another value shape are refused, not silently ignored.
297    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    /// The bundled source register and packs as `(path, text)`, in a fixed order — for a
392    /// fingerprint of the rules a decision was made under.
393    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    /// The rule packs shipped in `rules/`.
399    ///
400    /// # Errors
401    /// Every problem in the bundled packs (a release never ships with any; the gate checks).
402    pub fn bundled() -> Result<Self, Vec<RuleProblem>> {
403        Self::parse(BUNDLED_SOURCES, BUNDLED_PACKS)
404    }
405
406    /// Parses a source registry and named packs, collecting every problem.
407    ///
408    /// # Errors
409    /// Unknown or incomplete sources, malformed entries, overlapping validity.
410    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    /// Every registered source.
512    pub fn sources(&self) -> impl Iterator<Item = &Source> {
513        self.sources.values()
514    }
515
516    /// The source an entry cites.
517    #[must_use]
518    pub fn source_of(&self, entry: &Entry) -> Option<&Source> {
519        self.sources.get(&entry.source)
520    }
521
522    /// Every entry, by rule id.
523    pub fn entries(&self) -> impl Iterator<Item = &Entry> {
524        self.entries.values().flatten()
525    }
526
527    /// The entry of `rule` in force for delivery day `day`.
528    ///
529    /// # Errors
530    /// [`Missing`] if none applies.
531    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    /// The day-ahead market time unit in minutes for `day`.
542    ///
543    /// # Errors
544    /// [`Missing`] if no entry applies or it has the wrong shape.
545    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    /// The instant of gate or publication `rule` for delivery day `day`.
557    ///
558    /// # Errors
559    /// [`Missing`] if no entry applies, it is not a gate, or the instant falls outside the calendar.
560    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        // The local wall-clock time on that Berlin day: walk from local midnight. Gates are never in
578        // the repeated or skipped hour, so the offset at the gate is the offset of the instant found.
579        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        // A local time inside the skipped spring hour does not exist: refuse rather than guess.
586        if flexpool_core::calendar::to_berlin(instant).time() != local_time {
587            return Err(missing());
588        }
589        Ok((instant, e))
590    }
591
592    /// The harmonised day-ahead price limits for `day`.
593    ///
594    /// # Errors
595    /// [`Missing`] if no entry applies.
596    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    /// The alarm type `rule` in force on `day`.
608    ///
609    /// # Errors
610    /// [`Missing`] if no entry applies or it is not an alarm.
611    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    /// A rate rule (`count` per `window_secs`) in force on `day`.
623    ///
624    /// # Errors
625    /// [`Missing`] if no entry applies or it is not a rate.
626    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    /// A duration rule in seconds in force on `day`.
638    ///
639    /// # Errors
640    /// [`Missing`] if no entry applies or it is not a duration.
641    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    /// A granularity rule (`da.volume-granularity`, `da.price-granularity`) for `day`.
653    ///
654    /// # Errors
655    /// [`Missing`] if no entry applies.
656    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}