exchange_hours/calendar/exceptions/static_table.rs
1// SPDX-License-Identifier: MIT-0
2
3//! Allocation-free exception providers backed by caller-owned static records.
4
5use chrono::NaiveDate;
6
7use super::{
8 BlockViolation, DateException, ExceptionBlock, ExceptionCoverage, SessionExceptionSource,
9 first_block_violation,
10};
11use crate::calendar::exchange_calendar::CalendarSource;
12
13/// One caller-supplied record for a venue-local trade date.
14///
15/// The three constructors are mutually exclusive by construction: a record
16/// either states that the date is normal, that it carries no session at all, or
17/// that a complete ordered block set replaces it. Nothing can be closed and
18/// replaced at once, and no record carries scalar boundary edits — those belong
19/// to [`DayPolicy`](crate::DayPolicy), which overlays this layer.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub struct SessionExceptionRecord<'a> {
22 trade_date: NaiveDate,
23 state: RecordState<'a>,
24}
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27enum RecordState<'a> {
28 KnownNormal,
29 Closed,
30 ReplaceSessions(&'a [ExceptionBlock]),
31}
32
33impl<'a> SessionExceptionRecord<'a> {
34 /// Records that `trade_date` was audited and follows the normal week.
35 ///
36 /// Explicit normal records are optional: every uncovered-by-a-record date
37 /// inside a table's coverage window already reads as
38 /// [`DateException::KnownNormal`]. They document an audit that found
39 /// nothing.
40 #[must_use]
41 pub const fn known_normal(trade_date: NaiveDate) -> Self {
42 Self {
43 trade_date,
44 state: RecordState::KnownNormal,
45 }
46 }
47
48 /// Records that no session belongs to `trade_date`.
49 #[must_use]
50 pub const fn closed(trade_date: NaiveDate) -> Self {
51 Self {
52 trade_date,
53 state: RecordState::Closed,
54 }
55 }
56
57 /// Records the complete ordered block set that replaces `trade_date`.
58 ///
59 /// The slice is validated by [`StaticSessionExceptions::new`]: it must be
60 /// non-empty, ordered by opening day then open time, and every block must
61 /// hold the [`ExceptionBlock`] domain invariants.
62 #[must_use]
63 pub const fn replace_sessions(trade_date: NaiveDate, blocks: &'a [ExceptionBlock]) -> Self {
64 Self {
65 trade_date,
66 state: RecordState::ReplaceSessions(blocks),
67 }
68 }
69
70 /// Returns the venue-local trade date this record describes.
71 #[must_use]
72 pub const fn trade_date(self) -> NaiveDate {
73 self.trade_date
74 }
75
76 /// Returns this record's state as a [`DateException`].
77 ///
78 /// A record never reports [`DateException::OutOfCoverage`]; that state
79 /// belongs to dates a table has no record *and* no coverage for.
80 #[must_use]
81 pub const fn exception(self) -> DateException<'a> {
82 match self.state {
83 RecordState::KnownNormal => DateException::KnownNormal,
84 RecordState::Closed => DateException::Closed,
85 RecordState::ReplaceSessions(blocks) => DateException::ReplaceSessions(blocks),
86 }
87 }
88}
89
90/// An allocation-free [`SessionExceptionSource`] over caller-owned records.
91///
92/// Records are keyed by venue-local **trade date** and are exact dates, never
93/// inferred weekday or holiday rules. Construction validates the whole slice
94/// once; queries then use exact-date binary search without allocation, I/O, or
95/// clock reads.
96///
97/// The table stores no operator data of its own. It carries the caller's
98/// identity scope and audited window so the engine can refuse a provider built
99/// for another schedule and so an unaudited date stays distinguishable from an
100/// ordinary weekday.
101///
102/// # Example
103///
104/// ```
105/// use chrono::NaiveDate;
106/// use exchange_hours::{
107/// CalendarSource, DateException, Exchange, ExceptionBlock, SessionExceptionRecord,
108/// SessionExceptionSource, StaticSessionExceptions,
109/// };
110///
111/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
112/// let day = |d| NaiveDate::from_ymd_opt(2011, 11, d).ok_or("invalid date");
113///
114/// // A regular-only early close: extended trading continues past 13:00 local.
115/// static BLOCKS: [ExceptionBlock; 2] = [
116/// ExceptionBlock::regular(0, 9 * 3_600 + 30 * 60, 13 * 3_600),
117/// ExceptionBlock::extended(0, 13 * 3_600, 17 * 3_600),
118/// ];
119/// let records = [SessionExceptionRecord::replace_sessions(day(25)?, &BLOCKS)];
120/// let table = StaticSessionExceptions::new(
121/// CalendarSource::Exchange(Exchange::Nasdaq),
122/// day(21)?,
123/// day(28)?,
124/// &records,
125/// )?;
126///
127/// assert_eq!(table.exception_on(day(25)?), DateException::ReplaceSessions(&BLOCKS));
128/// assert_eq!(table.exception_on(day(24)?), DateException::KnownNormal);
129/// assert_eq!(table.exception_on(day(29)?), DateException::OutOfCoverage);
130/// # Ok(())
131/// # }
132/// ```
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub struct StaticSessionExceptions<'a> {
135 source: CalendarSource,
136 coverage: ExceptionCoverage,
137 records: &'a [SessionExceptionRecord<'a>],
138}
139
140impl<'a> StaticSessionExceptions<'a> {
141 /// Validates and borrows a slice of trade-date records for one identity.
142 ///
143 /// `first_covered` and `last_covered` publish the audited window: dates
144 /// inside it with no record are [`DateException::KnownNormal`], and dates
145 /// outside it are [`DateException::OutOfCoverage`]. An empty record slice
146 /// is valid and asserts that the whole window was audited and found normal.
147 /// This is a `const fn`, so a caller can validate while constructing a
148 /// constant or static table.
149 ///
150 /// Validation scans left to right, checking the coverage bounds, then each
151 /// record's ordering and window membership, then each replacement block's
152 /// ordering and domain, and returns the first violation.
153 ///
154 /// # Errors
155 ///
156 /// Returns [`StaticSessionExceptionsError`] for inverted coverage bounds,
157 /// the first duplicate or out-of-order record date, the first record
158 /// outside the coverage window, an empty replacement set, or the first
159 /// replacement block that is out of order, carries an offset outside
160 /// [`ExceptionBlock::MIN_DAY_OFFSET`]`..=`[`ExceptionBlock::MAX_DAY_OFFSET`],
161 /// opens outside `0..86_400`, or closes outside `0..=86_400`.
162 pub const fn new(
163 source: CalendarSource,
164 first_covered: NaiveDate,
165 last_covered: NaiveDate,
166 records: &'a [SessionExceptionRecord<'a>],
167 ) -> Result<Self, StaticSessionExceptionsError> {
168 if last_covered.signed_duration_since(first_covered).num_days() < 0 {
169 return Err(StaticSessionExceptionsError::CoverageBoundsInverted);
170 }
171 let mut index = 0;
172 while index < records.len() {
173 let current = records[index];
174 if index > 0
175 && current
176 .trade_date
177 .signed_duration_since(records[index - 1].trade_date)
178 .num_days()
179 <= 0
180 {
181 return Err(StaticSessionExceptionsError::DatesNotStrictlyIncreasing { index });
182 }
183 if current
184 .trade_date
185 .signed_duration_since(first_covered)
186 .num_days()
187 < 0
188 || last_covered
189 .signed_duration_since(current.trade_date)
190 .num_days()
191 < 0
192 {
193 return Err(StaticSessionExceptionsError::RecordOutsideCoverage { index });
194 }
195 if let RecordState::ReplaceSessions(blocks) = current.state
196 && let Err(error) = validate_blocks(index, blocks)
197 {
198 return Err(error);
199 }
200 index += 1;
201 }
202 Ok(Self {
203 source,
204 coverage: ExceptionCoverage {
205 first: first_covered,
206 last: last_covered,
207 },
208 records,
209 })
210 }
211
212 /// Returns the identity these records are scoped to.
213 #[must_use]
214 pub const fn source(self) -> CalendarSource {
215 self.source
216 }
217
218 /// Returns the audited trade-date window.
219 #[must_use]
220 pub const fn coverage(self) -> ExceptionCoverage {
221 self.coverage
222 }
223
224 /// Returns the exact record for `trade_date`, if one exists.
225 ///
226 /// Lookup is allocation-free and logarithmic in the number of records. A
227 /// date outside the coverage window still returns its record if one was
228 /// supplied, which validation makes impossible.
229 #[must_use]
230 pub fn record_on(self, trade_date: NaiveDate) -> Option<SessionExceptionRecord<'a>> {
231 self.records
232 .binary_search_by_key(&trade_date, |record| record.trade_date)
233 .ok()
234 .and_then(|index| self.records.get(index).copied())
235 }
236
237 /// Returns what this table knows about `trade_date`.
238 #[must_use]
239 pub fn exception_on(self, trade_date: NaiveDate) -> DateException<'a> {
240 if !self.coverage.contains(trade_date) {
241 return DateException::OutOfCoverage;
242 }
243 self.record_on(trade_date).map_or(
244 DateException::KnownNormal,
245 SessionExceptionRecord::exception,
246 )
247 }
248
249 /// Returns the validated records in their strictly increasing order.
250 #[must_use]
251 pub const fn records(self) -> &'a [SessionExceptionRecord<'a>] {
252 self.records
253 }
254}
255
256const fn validate_blocks(
257 index: usize,
258 blocks: &[ExceptionBlock],
259) -> Result<(), StaticSessionExceptionsError> {
260 match first_block_violation(blocks) {
261 None => Ok(()),
262 Some(BlockViolation::Empty) => {
263 Err(StaticSessionExceptionsError::EmptyReplacement { index })
264 }
265 Some(BlockViolation::OffsetOutOfRange {
266 block,
267 open_day_offset,
268 }) => Err(StaticSessionExceptionsError::BlockOffsetOutOfRange {
269 index,
270 block,
271 open_day_offset,
272 }),
273 Some(BlockViolation::OpenOutOfRange { block, open_ssm }) => {
274 Err(StaticSessionExceptionsError::BlockOpenOutOfRange {
275 index,
276 block,
277 open_ssm,
278 })
279 }
280 Some(BlockViolation::CloseOutOfRange { block, close_ssm }) => {
281 Err(StaticSessionExceptionsError::BlockCloseOutOfRange {
282 index,
283 block,
284 close_ssm,
285 })
286 }
287 Some(BlockViolation::ClosesAfterTradeDate { block }) => {
288 Err(StaticSessionExceptionsError::BlockClosesAfterTradeDate { index, block })
289 }
290 Some(BlockViolation::NotOrdered { block }) => {
291 Err(StaticSessionExceptionsError::BlocksNotOrdered { index, block })
292 }
293 }
294}
295
296impl SessionExceptionSource for StaticSessionExceptions<'_> {
297 fn source(&self) -> CalendarSource {
298 StaticSessionExceptions::source(*self)
299 }
300
301 fn coverage(&self) -> Option<ExceptionCoverage> {
302 Some(StaticSessionExceptions::coverage(*self))
303 }
304
305 fn exception_on(&self, trade_date: NaiveDate) -> DateException<'_> {
306 StaticSessionExceptions::exception_on(*self, trade_date)
307 }
308
309 /// One partition point over the validated, sorted records — the same shape
310 /// the built-in table's gate answers from. A provider that audited a
311 /// window and recorded nothing (an empty slice) answers `false` for every
312 /// window, which is what makes it a true no-op on the engine's hot path
313 /// (issue #127): the engine must not derive a trading day — and refuse on
314 /// a day that derivation reaches — for a provider that can move nothing.
315 fn may_affect(&self, first: NaiveDate, last: NaiveDate) -> bool {
316 let start = self
317 .records
318 .partition_point(|record| record.trade_date < first);
319 self.records
320 .get(start)
321 .is_some_and(|record| record.trade_date <= last)
322 }
323}
324
325/// A [`StaticSessionExceptions`] record-set invariant violation.
326#[non_exhaustive]
327#[derive(Debug, Clone, Copy, PartialEq, Eq)]
328pub enum StaticSessionExceptionsError {
329 /// The last covered trade date precedes the first.
330 CoverageBoundsInverted,
331 /// The record at `index` is not later than its predecessor.
332 DatesNotStrictlyIncreasing {
333 /// Index of the duplicate or out-of-order record.
334 index: usize,
335 },
336 /// The record at `index` falls outside the published coverage window.
337 RecordOutsideCoverage {
338 /// Index of the out-of-window record.
339 index: usize,
340 },
341 /// The replacement at `index` carries no blocks; use a closed record.
342 EmptyReplacement {
343 /// Index of the empty replacement record.
344 index: usize,
345 },
346 /// A block's opening-day offset is outside the permitted range.
347 BlockOffsetOutOfRange {
348 /// Index of the owning record.
349 index: usize,
350 /// Position of the invalid block inside that record.
351 block: usize,
352 /// Rejected opening-day offset.
353 open_day_offset: i8,
354 },
355 /// A block's open is outside `0..86_400`.
356 BlockOpenOutOfRange {
357 /// Index of the owning record.
358 index: usize,
359 /// Position of the invalid block inside that record.
360 block: usize,
361 /// Rejected open value.
362 open_ssm: u32,
363 },
364 /// A block's close is outside `0..=86_400`.
365 BlockCloseOutOfRange {
366 /// Index of the owning record.
367 index: usize,
368 /// Position of the invalid block inside that record.
369 block: usize,
370 /// Rejected close value.
371 close_ssm: u32,
372 },
373 /// A block opening on its trade date closes on the following local date.
374 ///
375 /// A trade date is named by the local date of its final close, so a block
376 /// at offset `0` may not wrap. A span covering one whole local day is
377 /// stated as `open_ssm = 0`, `close_ssm = 86_400`, which does not wrap.
378 BlockClosesAfterTradeDate {
379 /// Index of the owning record.
380 index: usize,
381 /// Position of the wrapping block inside that record.
382 block: usize,
383 },
384 /// A block does not start at or after its predecessor.
385 BlocksNotOrdered {
386 /// Index of the owning record.
387 index: usize,
388 /// Position of the out-of-order block inside that record.
389 block: usize,
390 },
391}
392
393impl core::fmt::Display for StaticSessionExceptionsError {
394 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
395 match self {
396 Self::CoverageBoundsInverted => {
397 write!(f, "last covered trade date precedes the first")
398 }
399 Self::DatesNotStrictlyIncreasing { index } => write!(
400 f,
401 "record at index {index} is not later than its predecessor"
402 ),
403 Self::RecordOutsideCoverage { index } => write!(
404 f,
405 "record at index {index} falls outside the published coverage window"
406 ),
407 Self::EmptyReplacement { index } => write!(
408 f,
409 "replacement record at index {index} carries no blocks; record it as closed"
410 ),
411 Self::BlockOffsetOutOfRange {
412 index,
413 block,
414 open_day_offset,
415 } => write!(
416 f,
417 "block {block} of record {index} has open_day_offset {open_day_offset} outside {}..={}",
418 ExceptionBlock::MIN_DAY_OFFSET,
419 ExceptionBlock::MAX_DAY_OFFSET
420 ),
421 Self::BlockOpenOutOfRange {
422 index,
423 block,
424 open_ssm,
425 } => write!(
426 f,
427 "block {block} of record {index} has open_ssm {open_ssm} outside 0..86400"
428 ),
429 Self::BlockCloseOutOfRange {
430 index,
431 block,
432 close_ssm,
433 } => write!(
434 f,
435 "block {block} of record {index} has close_ssm {close_ssm} outside 0..=86400"
436 ),
437 Self::BlockClosesAfterTradeDate { index, block } => write!(
438 f,
439 "block {block} of record {index} opens on its trade date and closes on the next local date"
440 ),
441 Self::BlocksNotOrdered { index, block } => write!(
442 f,
443 "block {block} of record {index} starts before its predecessor"
444 ),
445 }
446 }
447}
448
449impl std::error::Error for StaticSessionExceptionsError {}