1use std::fmt;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7pub enum ResourceOperation {
8 WorkbookOpen,
9 WorkbookSave,
10 FormulaParse,
11 FormulaMutate,
12 FormulaCalculate,
13 DataTraverse,
14 Render,
15 Export,
16 Encrypt,
17 Decrypt,
18 MacroRead,
19 StreamRead,
20 StreamWrite,
21}
22
23impl ResourceOperation {
24 pub const fn code(self) -> &'static str {
26 match self {
27 Self::WorkbookOpen => "workbook_open",
28 Self::WorkbookSave => "workbook_save",
29 Self::FormulaParse => "formula_parse",
30 Self::FormulaMutate => "formula_mutate",
31 Self::FormulaCalculate => "formula_calculate",
32 Self::DataTraverse => "data_traverse",
33 Self::Render => "render",
34 Self::Export => "export",
35 Self::Encrypt => "encrypt",
36 Self::Decrypt => "decrypt",
37 Self::MacroRead => "macro_read",
38 Self::StreamRead => "stream_read",
39 Self::StreamWrite => "stream_write",
40 }
41 }
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
46pub enum ResourceCategory {
47 Archive,
48 Container,
49 Xml,
50 Formula,
51 Traversal,
52 Output,
53 Encryption,
54 Macro,
55 Streaming,
56 Structure,
57}
58
59impl ResourceCategory {
60 pub const fn code(self) -> &'static str {
62 match self {
63 Self::Archive => "archive",
64 Self::Container => "container",
65 Self::Xml => "xml",
66 Self::Formula => "formula",
67 Self::Traversal => "traversal",
68 Self::Output => "output",
69 Self::Encryption => "encryption",
70 Self::Macro => "macro",
71 Self::Streaming => "streaming",
72 Self::Structure => "structure",
73 }
74 }
75}
76
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
79pub enum ResourceDimension {
80 InputBytes,
81 OutputBytes,
82 RetainedBytes,
83 EntryCount,
84 EntryDeclaredBytes,
85 EntryActualBytes,
86 AggregateDeclaredBytes,
87 AggregateActualBytes,
88 CompressionRatio,
89 CompressionRatioFloorBytes,
90 XmlBytes,
91 NestingDepth,
92 TokenCount,
93 NodeCount,
94 RangeCellCount,
95 DependencyEdgeCount,
96 OperationCount,
97 MatchWork,
98 RowCount,
99 ColumnCount,
100 CellCount,
101 StreamCount,
102 ModuleCount,
103 ChunkCount,
104 IterationCount,
105 CollectionCount,
106}
107
108impl ResourceDimension {
109 pub const fn code(self) -> &'static str {
111 match self {
112 Self::InputBytes => "input_bytes",
113 Self::OutputBytes => "output_bytes",
114 Self::RetainedBytes => "retained_bytes",
115 Self::EntryCount => "entry_count",
116 Self::EntryDeclaredBytes => "entry_declared_bytes",
117 Self::EntryActualBytes => "entry_actual_bytes",
118 Self::AggregateDeclaredBytes => "aggregate_declared_bytes",
119 Self::AggregateActualBytes => "aggregate_actual_bytes",
120 Self::CompressionRatio => "compression_ratio",
121 Self::CompressionRatioFloorBytes => "compression_ratio_floor_bytes",
122 Self::XmlBytes => "xml_bytes",
123 Self::NestingDepth => "nesting_depth",
124 Self::TokenCount => "token_count",
125 Self::NodeCount => "node_count",
126 Self::RangeCellCount => "range_cell_count",
127 Self::DependencyEdgeCount => "dependency_edge_count",
128 Self::OperationCount => "operation_count",
129 Self::MatchWork => "match_work",
130 Self::RowCount => "row_count",
131 Self::ColumnCount => "column_count",
132 Self::CellCount => "cell_count",
133 Self::StreamCount => "stream_count",
134 Self::ModuleCount => "module_count",
135 Self::ChunkCount => "chunk_count",
136 Self::IterationCount => "iteration_count",
137 Self::CollectionCount => "collection_count",
138 }
139 }
140}
141
142#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
144pub enum ResourceStage {
145 Inspect,
146 Read,
147 Parse,
148 Decode,
149 Validate,
150 Calculate,
151 Render,
152 Serialize,
153 Write,
154 Replace,
155}
156
157impl ResourceStage {
158 pub const fn code(self) -> &'static str {
160 match self {
161 Self::Inspect => "inspect",
162 Self::Read => "read",
163 Self::Parse => "parse",
164 Self::Decode => "decode",
165 Self::Validate => "validate",
166 Self::Calculate => "calculate",
167 Self::Render => "render",
168 Self::Serialize => "serialize",
169 Self::Write => "write",
170 Self::Replace => "replace",
171 }
172 }
173}
174
175#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
181pub struct ResourceLimitError {
182 operation: ResourceOperation,
183 category: ResourceCategory,
184 dimension: ResourceDimension,
185 limit: u64,
186 observed: u64,
187 stage: Option<ResourceStage>,
188}
189
190impl ResourceLimitError {
191 pub const CODE: &'static str = "resource_limit_exceeded";
193
194 pub const fn exceeded(
196 operation: ResourceOperation,
197 category: ResourceCategory,
198 dimension: ResourceDimension,
199 limit: u64,
200 observed: u64,
201 stage: Option<ResourceStage>,
202 ) -> Option<Self> {
203 if observed <= limit {
204 return None;
205 }
206
207 Some(Self {
208 operation,
209 category,
210 dimension,
211 limit,
212 observed,
213 stage,
214 })
215 }
216
217 pub const fn operation(self) -> ResourceOperation {
218 self.operation
219 }
220
221 pub const fn category(self) -> ResourceCategory {
222 self.category
223 }
224
225 pub const fn dimension(self) -> ResourceDimension {
226 self.dimension
227 }
228
229 pub const fn limit(self) -> u64 {
230 self.limit
231 }
232
233 pub const fn observed(self) -> u64 {
234 self.observed
235 }
236
237 pub const fn stage(self) -> Option<ResourceStage> {
238 self.stage
239 }
240
241 pub const fn operation_code(self) -> &'static str {
242 self.operation.code()
243 }
244
245 pub const fn category_code(self) -> &'static str {
246 self.category.code()
247 }
248
249 pub const fn dimension_code(self) -> &'static str {
250 self.dimension.code()
251 }
252
253 pub const fn stage_code(self) -> Option<&'static str> {
254 match self.stage {
255 Some(stage) => Some(stage.code()),
256 None => None,
257 }
258 }
259}
260
261impl fmt::Display for ResourceLimitError {
262 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
263 write!(
264 formatter,
265 "resource limit exceeded: operation={} category={} dimension={} limit={} observed={}",
266 self.operation.code(),
267 self.category.code(),
268 self.dimension.code(),
269 self.limit,
270 self.observed,
271 )?;
272 if let Some(stage) = self.stage {
273 write!(formatter, " stage={}", stage.code())?;
274 }
275 Ok(())
276 }
277}
278
279impl std::error::Error for ResourceLimitError {}
280
281#[cfg(test)]
282mod tests {
283 use super::*;
284
285 #[test]
286 fn metadata_contains_only_closed_codes_and_numbers() {
287 let metadata = ResourceLimitError::exceeded(
288 ResourceOperation::FormulaCalculate,
289 ResourceCategory::Formula,
290 ResourceDimension::OperationCount,
291 100,
292 101,
293 Some(ResourceStage::Calculate),
294 )
295 .unwrap();
296
297 assert_eq!(metadata.operation_code(), "formula_calculate");
298 assert_eq!(metadata.category_code(), "formula");
299 assert_eq!(metadata.dimension_code(), "operation_count");
300 assert_eq!(metadata.stage_code(), Some("calculate"));
301 assert_eq!(metadata.limit(), 100);
302 assert_eq!(metadata.observed(), 101);
303 }
304
305 #[test]
306 fn metadata_requires_an_exceeded_limit() {
307 assert!(ResourceLimitError::exceeded(
308 ResourceOperation::WorkbookOpen,
309 ResourceCategory::Archive,
310 ResourceDimension::InputBytes,
311 u64::MAX,
312 u64::MAX,
313 None,
314 )
315 .is_none());
316 }
317
318 #[test]
319 fn archive_dimensions_distinguish_admission_from_actual_reads() {
320 assert_eq!(
321 ResourceDimension::EntryDeclaredBytes.code(),
322 "entry_declared_bytes"
323 );
324 assert_eq!(
325 ResourceDimension::EntryActualBytes.code(),
326 "entry_actual_bytes"
327 );
328 assert_eq!(
329 ResourceDimension::AggregateDeclaredBytes.code(),
330 "aggregate_declared_bytes"
331 );
332 assert_eq!(
333 ResourceDimension::AggregateActualBytes.code(),
334 "aggregate_actual_bytes"
335 );
336 }
337}