exchange_hours/calendar/coverage/error.rs
1// SPDX-License-Identifier: MIT-0
2
3//! The explicit coverage-error vocabulary for identity-backed queries
4//! (LAW-COVERAGE).
5
6use chrono::NaiveDate;
7
8use super::SUPPORT_FLOOR;
9use crate::calendar::exchange_calendar::CalendarSource;
10
11use super::baseline::NormalWeekBaseline;
12
13/// Why an identity-backed date-aware query cannot answer.
14///
15/// LAW-COVERAGE requires an unsupported date to be an explicit error rather
16/// than a claim that a market is open or closed, and it requires an unsupported
17/// date to stay distinguishable from a bounded search that simply ran out of
18/// room to look. The four variants are that distinction:
19///
20/// - [`Self::BeforeSupportFloor`] — the instant or date precedes the permanent
21/// 2010-01-01 local-date floor;
22/// - [`Self::OutsideCoveredRange`] — at or after the floor, but the identity has
23/// no sourced answer there: its weekday profile is carried backwards, it ships
24/// no holiday table, its holiday layer has no audited answer for the date, or it
25/// declares a phase-level gap that applies on the date;
26/// - [`Self::UnresolvedGap`] — inside a covered range on a date the identity
27/// explicitly withholds as `Unsourced`;
28/// - [`Self::SearchExhausted`] — a bounded forward or period search needed a
29/// date it could not establish and could not continue past.
30///
31/// A **known closure** is never an error: a date whose sourced answer is
32/// "closed" — a holiday row, a pre-launch closure, a weekend — returns a normal
33/// `Ok` result, and so does a genuine absence inside the covered range.
34///
35/// The type carries no allocation and no `String`: the identity, the offending
36/// venue-local date and, for an exhausted search, the bound it hit. It is
37/// `Copy + Send + Sync + 'static` so a caller can log or return it without
38/// ceremony.
39///
40/// **The mapping from [`DateCoverage`](super::DateCoverage) to these variants
41/// is exact in one direction only.** A date the metadata calls
42/// [`DateCoverage::Covered`](super::DateCoverage::Covered) promises that every
43/// query addressed to an instant of it answers, or refuses naming a date the
44/// metadata itself does not call covered (#151) — a wrapped session can open on
45/// the previous civil day, and the next session's trade date can lie beyond the
46/// day, so the refusal a caller sees on a covered date names the *neighbour*
47/// the answer depends on, never a market state for the covered date itself.
48#[non_exhaustive]
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
50pub enum CalendarQueryError {
51 /// The date precedes the venue-local support floor.
52 ///
53 /// The floor is a *local* date ([`SUPPORT_FLOOR`]), so two identities in
54 /// opposing zones reach it at different UTC instants.
55 BeforeSupportFloor {
56 /// The identity that cannot answer.
57 source: CalendarSource,
58 /// The offending venue-local date.
59 date: NaiveDate,
60 },
61 /// The date is at or after the floor but outside the ranges this identity
62 /// has a sourced answer for.
63 ///
64 /// Either the weekday profile is carried backwards below the identity's
65 /// recorded horizon, the date falls outside every holiday window the
66 /// identity's built-in table audited, or a declared phase-level gap applies
67 /// on the date. The reason is available from
68 /// [`CalendarCoverage::gaps`](super::CalendarCoverage::gaps), which reports
69 /// the same derivation as spans.
70 OutsideCoveredRange {
71 /// The identity that cannot answer.
72 source: CalendarSource,
73 /// The offending venue-local date.
74 date: NaiveDate,
75 },
76 /// The date is inside an audited window on a date the identity explicitly
77 /// withholds as `Unsourced`, or the date sits on a one-flank bridged span
78 /// **below the identity's first audited window**, whose holiday-table
79 /// classification refuses (issue #296, the 2026-10-07 ruling).
80 ///
81 /// The withheld case is the one LAW-HOLIDAY-SCOPE means by "a date without
82 /// a row is audited normal, while `Unsourced` expressly withholds that
83 /// claim". The one-flank case is the ruling's asymmetry with two-flank
84 /// bridged spans: a date whose session questions answer from the sourced
85 /// normal week still refuses `is_closed_trade_date`, because no audited
86 /// window brackets it from below and nothing witnesses the holiday layer —
87 /// two flanks bracket a span, one does not. Either way the crate has no
88 /// answer and will not guess one, and
89 /// [`Self::normal_week_baseline`] names the sourced week the refusal sits
90 /// inside.
91 UnresolvedGap {
92 /// The identity that cannot answer.
93 source: CalendarSource,
94 /// The withheld venue-local date.
95 date: NaiveDate,
96 },
97 /// A bounded search ran out of room on a date it could not establish.
98 ///
99 /// A forward or period search inspects at most a documented bounded number
100 /// of venue-local days. When the date it needs next is one it cannot
101 /// establish, the search stops here rather than skipping it and claiming
102 /// the next known session is the next session.
103 SearchExhausted {
104 /// The identity whose search was bounded.
105 source: CalendarSource,
106 /// The venue-local date the search needed to establish.
107 date: NaiveDate,
108 /// The last venue-local date the bounded search examined.
109 bound: NaiveDate,
110 },
111}
112
113impl CalendarQueryError {
114 /// Returns the identity that cannot answer.
115 #[must_use]
116 pub const fn source(self) -> CalendarSource {
117 match self {
118 Self::BeforeSupportFloor { source, .. }
119 | Self::OutsideCoveredRange { source, .. }
120 | Self::UnresolvedGap { source, .. }
121 | Self::SearchExhausted { source, .. } => source,
122 }
123 }
124
125 /// Returns the venue-local date the query could not establish.
126 #[must_use]
127 pub const fn date(self) -> NaiveDate {
128 match self {
129 Self::BeforeSupportFloor { date, .. }
130 | Self::OutsideCoveredRange { date, .. }
131 | Self::UnresolvedGap { date, .. }
132 | Self::SearchExhausted { date, .. } => date,
133 }
134 }
135
136 /// Returns the sourced normal-week baseline the refused date sits inside,
137 /// or `None` when the crate states none (issue #296, Tier 3).
138 ///
139 /// This is the context a consumer needs to make its own call beside a
140 /// refusal: the weekday the refused date falls on and the normal-week
141 /// windows the identity's sourced timeline serves there — "Wednesday;
142 /// normal week open 09:30-16:30" — rendered by
143 /// [`NormalWeekBaseline`]'s `Display`. The enrichment is additive: the
144 /// refusal is unchanged, and the baseline says nothing about the holiday
145 /// arrangement the refusal withholds.
146 ///
147 /// The baseline is absent where claiming one would state a sourced fact
148 /// the ledger does not record: the date precedes the support floor, or the
149 /// identity's normal week is carried backwards below its recorded horizon
150 /// at the date.
151 #[must_use]
152 pub fn normal_week_baseline(self) -> Option<NormalWeekBaseline> {
153 super::baseline::for_error(self)
154 }
155}
156
157/// Renders an identity by its canonical `snake_case` wire name.
158const fn identity_name(source: CalendarSource) -> &'static str {
159 match source {
160 CalendarSource::Exchange(exchange) => exchange.as_str(),
161 CalendarSource::MarketHoursKey(key) => key.as_str(),
162 }
163}
164
165impl core::fmt::Display for CalendarQueryError {
166 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
167 let name = identity_name(self.source());
168 match *self {
169 Self::BeforeSupportFloor { date, .. } => write!(
170 f,
171 "{name}: {date} precedes the {SUPPORT_FLOOR} venue-local support floor"
172 ),
173 Self::OutsideCoveredRange { date, .. } => {
174 write!(
175 f,
176 "{name}: {date} is outside this identity's covered ranges"
177 )
178 }
179 Self::UnresolvedGap { date, .. } => {
180 write!(
181 f,
182 "{name}: {date} is an unresolved gap in the covered range"
183 )?;
184 // Tier 3 (issue #296): the refusal carries the normal-week
185 // baseline it sits inside, so a consumer can make its own call.
186 // The holiday arrangement stays unsourced — the baseline is
187 // context, never an answer.
188 if let Some(baseline) = self.normal_week_baseline() {
189 write!(f, " ({baseline}; the holiday arrangement is unsourced)")?;
190 }
191 Ok(())
192 }
193 Self::SearchExhausted { date, bound, .. } => write!(
194 f,
195 "{name}: no answer for {date}; the bounded search ended at {bound}"
196 ),
197 }
198 }
199}
200
201impl std::error::Error for CalendarQueryError {}