Skip to main content

chronicle_core/
error.rs

1//! Domain errors. Every variant carries the concrete values that explain
2//! the failure (ARCHITECTURE.md section 8.1): an opaque variant name is
3//! never the whole diagnostic.
4
5use core::fmt;
6
7use crate::types::OrderId;
8
9/// Errors returned by book construction and by every book command.
10///
11/// Commands that return an error have mutated nothing: no order, level
12/// aggregate, bitmap bit, lookup entry, or sequence number changes when
13/// any of these is returned (INV-ORD-4).
14#[derive(Clone, Debug, PartialEq, Eq)]
15pub enum BookError {
16    /// `BookConfig` failed validation at construction.
17    InvalidConfig {
18        /// The field that failed validation.
19        field: &'static str,
20        /// The rule the field violated.
21        rule: &'static str,
22    },
23    /// A [`crate::SnapshotState`] failed structural validation during restore.
24    InvalidSnapshot {
25        /// What structural invariant the snapshot state violated.
26        reason: &'static str,
27    },
28    /// An order id of zero was supplied; zero is the lookup sentinel.
29    InvalidOrderId {
30        /// The offending order id (always zero).
31        order_id: OrderId,
32    },
33    /// An active order already uses this id.
34    DuplicateOrderId {
35        /// The conflicting order id.
36        order_id: OrderId,
37    },
38    /// A quantity of zero was supplied on add or amend.
39    InvalidQuantity {
40        /// The offending quantity (always zero).
41        qty: u64,
42    },
43    /// A price failed the tick grid rules of ARCHITECTURE.md section 3.2.
44    InvalidPriceTick {
45        /// The raw price supplied, in quote units.
46        price: u64,
47        /// Configured quote units per tick.
48        tick_size: u64,
49        /// Configured tick value of grid index 0.
50        grid_start_tick: u64,
51        /// Configured number of ticks on the grid.
52        grid_len: u32,
53    },
54    /// Cancel or amend named an order that is not live.
55    OrderNotFound {
56        /// The order id that was not found.
57        order_id: OrderId,
58    },
59    /// The arena has no free slot for an order that would rest.
60    CapacityFull {
61        /// Configured arena capacity.
62        max_orders: u32,
63    },
64    /// The lookup table reached its 50 percent load cap. Defensive: the
65    /// arena cap is enforced first, so this guards the table invariant
66    /// directly rather than relying on that ordering.
67    LookupCapacityFull {
68        /// Table capacity in buckets.
69        capacity: usize,
70        /// Entries present when the insert was refused.
71        len: usize,
72    },
73    /// A Post-Only order price would cross the opposite best price.
74    PostOnlyWouldCross {
75        /// The raw price of the incoming order.
76        price: u64,
77        /// The raw opposite best price it would have crossed.
78        opposite_best: u64,
79    },
80    /// A Fill-or-Kill order could not be filled in full.
81    FokInsufficientLiquidity {
82        /// Quantity the order requested.
83        requested: u64,
84        /// STP-adjusted executable quantity found in preflight.
85        available: u64,
86    },
87    /// An amend would leave the book crossed.
88    AmendWouldCross {
89        /// The order being amended.
90        order_id: OrderId,
91        /// The raw new price requested.
92        new_price: u64,
93        /// The raw opposite best price it would cross.
94        opposite_best: u64,
95    },
96    /// The caller event buffer is smaller than the preflight worst-case
97    /// event count for this command. Returned before any mutation, so
98    /// the identical command can be retried with a larger buffer.
99    EventBufferFull {
100        /// Worst-case events the command could emit.
101        needed: usize,
102        /// Free slots the buffer actually had.
103        available: usize,
104    },
105    /// A checked aggregate operation overflowed. Defensive guard:
106    /// aggregates are sized so this is unreachable in a valid book.
107    ArithmeticOverflow {
108        /// What was being computed when the overflow was detected.
109        what: &'static str,
110    },
111}
112
113impl fmt::Display for BookError {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        match self {
116            Self::InvalidConfig { field, rule } => {
117                write!(
118                    f,
119                    "invalid book configuration: field {field} violates rule: {rule}"
120                )
121            }
122            Self::InvalidSnapshot { reason } => {
123                write!(f, "invalid snapshot state: {reason}")
124            }
125            Self::InvalidOrderId { order_id } => {
126                write!(f, "invalid order id {}: zero is reserved", order_id.0)
127            }
128            Self::DuplicateOrderId { order_id } => {
129                write!(
130                    f,
131                    "duplicate order id {}: an active order already uses it",
132                    order_id.0
133                )
134            }
135            Self::InvalidQuantity { qty } => {
136                write!(f, "invalid quantity {qty}: quantities must be positive")
137            }
138            Self::InvalidPriceTick {
139                price,
140                tick_size,
141                grid_start_tick,
142                grid_len,
143            } => write!(
144                f,
145                "invalid price tick: price {price} with tick size {tick_size} does not land on the grid starting at tick {grid_start_tick} with {grid_len} ticks"
146            ),
147            Self::OrderNotFound { order_id } => {
148                write!(f, "order not found: no live order with id {}", order_id.0)
149            }
150            Self::CapacityFull { max_orders } => {
151                write!(
152                    f,
153                    "book capacity full: arena holds at most {max_orders} live orders"
154                )
155            }
156            Self::LookupCapacityFull { capacity, len } => write!(
157                f,
158                "lookup table at load cap: {len} entries in {capacity} buckets (cap is 50 percent)"
159            ),
160            Self::PostOnlyWouldCross {
161                price,
162                opposite_best,
163            } => write!(
164                f,
165                "post-only order at price {price} would cross the opposite best price {opposite_best}"
166            ),
167            Self::FokInsufficientLiquidity {
168                requested,
169                available,
170            } => write!(
171                f,
172                "fill-or-kill order requested {requested} but only {available} is executable"
173            ),
174            Self::AmendWouldCross {
175                order_id,
176                new_price,
177                opposite_best,
178            } => write!(
179                f,
180                "amend of order {} to price {new_price} would cross the opposite best price {opposite_best}",
181                order_id.0
182            ),
183            Self::EventBufferFull { needed, available } => write!(
184                f,
185                "event buffer full: command needs up to {needed} event slots, buffer has {available}"
186            ),
187            Self::ArithmeticOverflow { what } => {
188                write!(f, "arithmetic overflow while computing {what}")
189            }
190        }
191    }
192}
193
194impl core::error::Error for BookError {}