Skip to main content

exchange_hours/calendar/coverage/
baseline.rs

1// SPDX-License-Identifier: MIT-0
2
3//! The normal-week baseline a coverage refusal sits inside (issue #296,
4//! Tier 3).
5//!
6//! A typed refusal is the crate's honest answer where no sourced state decides
7//! a date, and Tier 3 enriches it without changing its verdict: the error value
8//! can now name the **sourced normal week** the refused date sits inside, so a
9//! consumer can make its own call — treat the date as open beside a normal
10//! 09:30-16:30 Wednesday, or exclude it — instead of receiving a bare refusal.
11//! The baseline is derived, never stored: it reads the same static timeline the
12//! query engine reads, anchored on the refused date's own opening day, so a
13//! backtest and a live caller deriving it for the same date see one value
14//! (LAW-DETERMINISM).
15//!
16//! The derivation allocates nothing on the rule slices — they arrive borrowed
17//! from the static tables — and it is total: a date whose normal week is
18//! carried rather than sourced, or that precedes the support floor, has **no**
19//! baseline, because claiming one would fabricate a sourced state the ledger
20//! does not record.
21
22use chrono::{Datelike as _, Utc, Weekday};
23use chrono_tz::Tz;
24
25use super::SUPPORT_FLOOR;
26use crate::calendar::exchange_calendar::{calendar_for_exchange, calendar_for_market_hours_key};
27use crate::calendar::local_time::mk_local_open;
28use crate::calendar::schedules::sourcing;
29use crate::calendar::{CalendarQueryError, CalendarSource, MarketHours, SessionRule};
30
31/// The last second of a venue-local day, the anchor the query gate uses to
32/// select the profile governing the sessions opening on that day.
33const OPEN_DAY_ANCHOR_SSM: u32 = 86_399;
34
35/// The sourced normal-week baseline one coverage refusal sits inside.
36///
37/// The value carries the profile the identity's timeline serves for the
38/// refused date's opening day — the era selection is the same one the query
39/// engine performs, anchored at that day's last local second — and the
40/// refused date's own weekday in the profile's zone. Its accessors project the
41/// weekday's rules, and its [`Display`](core::fmt::Display) renders the
42/// ordinary-week shape a consumer reads beside a holiday-arrangement refusal.
43///
44/// A baseline is a statement about the **normal week only**: it says nothing
45/// about the refused date's holiday arrangement, which is exactly what the
46/// refusal withholds. It is `Clone` rather than `Copy` because it carries the
47/// profile; the rule slices behind it are borrowed static tables.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct NormalWeekBaseline {
50    profile: MarketHours,
51    weekday: Weekday,
52}
53
54impl NormalWeekBaseline {
55    /// Returns the identity the baseline belongs to.
56    #[must_use]
57    pub fn identity(&self) -> CalendarSource {
58        self.profile.source
59    }
60
61    /// Returns the profile's venue zone.
62    #[must_use]
63    pub fn tz(&self) -> Tz {
64        self.profile.tz
65    }
66
67    /// Returns the refused date's weekday in the profile's zone.
68    #[must_use]
69    pub const fn weekday(&self) -> Weekday {
70        self.weekday
71    }
72
73    /// Returns the profile the timeline serves for the refused date's opening
74    /// day, with its rule sets readable through [`MarketHours`]'s public
75    /// fields.
76    #[must_use]
77    pub const fn profile(&self) -> &MarketHours {
78        &self.profile
79    }
80
81    /// Returns the refused date's weekday tradeable rules — the profile's
82    /// `regular` and `extended` sets together, the union every `is_open`
83    /// answer reads — as the static tables state them: seconds since local
84    /// midnight, wrap rules included
85    /// ([`SessionRule::wraps_to_next_day`](crate::SessionRule::wraps_to_next_day)).
86    ///
87    /// A weekday with no tradeable rule yields an empty iterator, which is the
88    /// normal week's own statement that nothing tradeable is scheduled.
89    pub fn tradeable_rules(&self) -> impl Iterator<Item = SessionRule> + use<'_> {
90        self.weekday_rules(
91            self.profile
92                .regular
93                .iter()
94                .chain(self.profile.extended.iter()),
95        )
96    }
97
98    /// Returns the refused date's weekday order-entry rules — the profile's
99    /// `order_entry` set, whose windows accept orders that cannot match — as
100    /// the static tables state them.
101    pub fn order_entry_rules(&self) -> impl Iterator<Item = SessionRule> + use<'_> {
102        self.weekday_rules(self.profile.order_entry.iter())
103    }
104
105    /// Filters one rule-set chain down to the baseline's own weekday.
106    fn weekday_rules<'a>(
107        &'a self,
108        rules: impl Iterator<Item = &'a SessionRule> + 'a,
109    ) -> impl Iterator<Item = SessionRule> + 'a {
110        let weekday_index = self.weekday.num_days_from_monday() as usize;
111        rules.copied().filter(move |rule| rule.days[weekday_index])
112    }
113}
114
115/// Renders the baseline the way a refusal's context names it: the weekday and
116/// the ordinary-week windows, in the profile's own local clock, chronological
117/// within each phase class.
118impl core::fmt::Display for NormalWeekBaseline {
119    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
120        write!(f, "normal week {}: ", weekday_name(self.weekday))?;
121        let mut tradeable: Vec<(u32, u32, bool)> = self
122            .tradeable_rules()
123            .map(|rule| (rule.open_ssm, rule.close_ssm, rule.wraps_to_next_day()))
124            .collect();
125        tradeable.sort_unstable();
126        if tradeable.is_empty() {
127            write!(f, "no ordinary session")?;
128        }
129        for (index, (open_ssm, close_ssm, wraps)) in tradeable.iter().enumerate() {
130            if index > 0 {
131                write!(f, ", ")?;
132            }
133            write!(f, "open {}", window_text(*open_ssm, *close_ssm, *wraps))?;
134        }
135        let mut order_entry: Vec<(u32, u32, bool)> = self
136            .order_entry_rules()
137            .map(|rule| (rule.open_ssm, rule.close_ssm, rule.wraps_to_next_day()))
138            .collect();
139        order_entry.sort_unstable();
140        for (open_ssm, close_ssm, wraps) in order_entry {
141            write!(
142                f,
143                ", order entry {}",
144                window_text(open_ssm, close_ssm, wraps)
145            )?;
146        }
147        Ok(())
148    }
149}
150
151/// Renders one rule's slice as a local-clock window.
152fn window_text(open_ssm: u32, close_ssm: u32, wraps: bool) -> String {
153    if wraps {
154        format!("{}-{} (+1)", clock_text(open_ssm), clock_text(close_ssm))
155    } else {
156        format!("{}-{}", clock_text(open_ssm), clock_text(close_ssm))
157    }
158}
159
160/// Renders seconds since local midnight as `HH:MM` or `HH:MM:SS`.
161fn clock_text(ssm: u32) -> String {
162    let (hour, rest) = (ssm / 3_600, ssm % 3_600);
163    let (minute, second) = (rest / 60, rest % 60);
164    if second == 0 {
165        format!("{hour:02}:{minute:02}")
166    } else {
167        format!("{hour:02}:{minute:02}:{second:02}")
168    }
169}
170
171/// The weekday names the baseline renders, Monday-first.
172fn weekday_name(weekday: Weekday) -> &'static str {
173    match weekday {
174        Weekday::Mon => "Monday",
175        Weekday::Tue => "Tuesday",
176        Weekday::Wed => "Wednesday",
177        Weekday::Thu => "Thursday",
178        Weekday::Fri => "Friday",
179        Weekday::Sat => "Saturday",
180        Weekday::Sun => "Sunday",
181    }
182}
183
184/// Derives the sourced normal-week baseline an error's date sits inside, or
185/// `None` when the crate states none.
186///
187/// Three refusals keep the baseline absent, because claiming it would state a
188/// sourced fact the ledger does not record: the date precedes the support
189/// floor; the identity's normal week is carried backwards below its recorded
190/// horizon at the date (LAW-COVERAGE's carried-below fact); or the identity
191/// resolves no profile at all. Everywhere else the baseline is the timeline's
192/// own era selection for the date's opening day — the same selection the query
193/// gate performs — so the context a caller reads beside the refusal is the
194/// week the crate's answers actually come from.
195pub(crate) fn for_error(error: CalendarQueryError) -> Option<NormalWeekBaseline> {
196    let source = error.source();
197    let date = error.date();
198    if date < SUPPORT_FLOOR {
199        return None;
200    }
201    let declared = sourcing::declared(source);
202    if declared.carried_below.is_some_and(|carried| date < carried) {
203        return None;
204    }
205    let calendar = match source {
206        CalendarSource::Exchange(exchange) => calendar_for_exchange(exchange),
207        CalendarSource::MarketHoursKey(key) => calendar_for_market_hours_key(key),
208    };
209    let tz = calendar.tz();
210    let anchor = mk_local_open(tz, date, OPEN_DAY_ANCHOR_SSM).with_timezone(&Utc);
211    let profile = calendar.hours_at(anchor);
212    Some(NormalWeekBaseline {
213        weekday: date.weekday(),
214        profile,
215    })
216}