1use std::fmt;
7#[cfg(feature = "yaml")]
8use std::path::Path;
9use std::sync::{PoisonError, RwLock};
10#[cfg(feature = "yaml")]
11use std::{fs, io};
12
13use serde::Deserialize;
14#[cfg(feature = "yaml")]
15use serde_saphyr::Budget;
16#[cfg(feature = "yaml")]
17use serde_saphyr::budget::BudgetBreach;
18
19#[cfg(feature = "yaml")]
20use super::{Input, InputError};
21
22#[cfg(feature = "yaml")]
24pub const REPO_FILE: &str = ".ctl/input.yaml";
25
26macro_rules! limits {
27 (
28 shared { $( $(#[$sdoc:meta])* $sfield:ident = $sdefault:ident, )* }
29 yaml { $( $(#[$ydoc:meta])* $yfield:ident: $yty:ty, )* }
30 ) => {
31 #[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize)]
58 #[serde(deny_unknown_fields, default)]
59 pub struct Limits {
60 $( $(#[$sdoc])* pub $sfield: Option<usize>, )*
61 $( $(#[$ydoc])* #[cfg(feature = "yaml")] pub $yfield: Option<$yty>, )*
62 }
63
64 impl Limits {
65 pub const NONE: Self = Self {
67 $( $sfield: None, )*
68 $( #[cfg(feature = "yaml")] $yfield: None, )*
69 };
70
71 #[must_use]
73 pub fn or(self, lower: &Self) -> Self {
74 Self {
75 $( $sfield: self.$sfield.or(lower.$sfield), )*
76 $( #[cfg(feature = "yaml")] $yfield: self.$yfield.or(lower.$yfield), )*
77 }
78 }
79
80 #[cfg(feature = "yaml")]
84 pub(super) fn budget(&self) -> Budget {
85 let bounds = self.bounds();
86 let mut budget = Budget::default();
87 budget.max_reader_input_bytes = Some(bounds.input_bytes);
88 budget.max_depth = bounds.depth;
89 budget.max_nodes = bounds.nodes;
90 $( if let Some(value) = self.$yfield {
91 budget.$yfield = value;
92 } )*
93 budget
94 }
95
96 #[cfg(feature = "yaml")]
98 fn loosened(&self) -> Vec<Loosened> {
99 let mut loosened = Vec::new();
100 $( if let Some(value) = self.$sfield
101 && value > Self::$sdefault
102 {
103 loosened.push(Loosened {
104 field: stringify!($sfield),
105 value: value.to_string(),
106 default: Self::$sdefault.to_string(),
107 });
108 } )*
109 let default = Budget::default();
110 $( if let Some(value) = self.$yfield
111 && value > default.$yfield
112 {
113 loosened.push(Loosened {
114 field: stringify!($yfield),
115 value: value.to_string(),
116 default: default.$yfield.to_string(),
117 });
118 } )*
119 loosened
120 }
121 }
122 };
123}
124
125limits! {
126 shared {
127 max_reader_input_bytes = DEFAULT_MAX_READER_INPUT_BYTES,
129 max_depth = DEFAULT_MAX_DEPTH,
132 max_nodes = DEFAULT_MAX_NODES,
135 }
136 yaml {
137 max_buffered_comment_events: usize,
139 simple_key_max_lookahead: usize,
141 flow_nesting_limit: usize,
143 max_events: usize,
145 max_aliases: usize,
147 max_anchors: usize,
149 max_recorded_anchor_events: usize,
151 max_recorded_anchor_bytes: usize,
153 max_property_expansion_depth: usize,
155 max_total_property_interpolation_work: usize,
157 max_inclusion_depth: u32,
159 max_documents: usize,
161 max_total_scalar_bytes: usize,
163 max_total_comment_bytes: usize,
165 max_merge_keys: usize,
167 alias_anchor_min_aliases: usize,
169 alias_anchor_ratio_multiplier: usize,
171 }
172}
173
174impl Limits {
175 pub const DEFAULT_MAX_READER_INPUT_BYTES: usize = 256 * 1024 * 1024;
177 pub const DEFAULT_MAX_DEPTH: usize = 64;
179 pub const DEFAULT_MAX_NODES: usize = 250_000;
181
182 pub(super) fn bounds(&self) -> Bounds {
185 Bounds {
186 input_bytes: self
187 .max_reader_input_bytes
188 .unwrap_or(Self::DEFAULT_MAX_READER_INPUT_BYTES),
189 depth: self.max_depth.unwrap_or(Self::DEFAULT_MAX_DEPTH),
190 nodes: self.max_nodes.unwrap_or(Self::DEFAULT_MAX_NODES),
191 }
192 }
193}
194
195#[derive(Clone, Copy)]
197pub(super) struct Bounds {
198 pub(super) input_bytes: usize,
199 pub(super) depth: usize,
200 pub(super) nodes: usize,
201}
202
203static PROCESS: RwLock<Limits> = RwLock::new(Limits::NONE);
204#[cfg(feature = "yaml")]
205static REPOSITORY: RwLock<Limits> = RwLock::new(Limits::NONE);
206
207pub fn set_default_limits(limits: Limits) {
211 *PROCESS.write().unwrap_or_else(PoisonError::into_inner) = limits;
212}
213
214#[cfg(feature = "yaml")]
228pub fn use_repo_limits(root: &Path) -> Result<Vec<Loosened>, InputError> {
229 let path = root.join(REPO_FILE);
230 let limits = match fs::read_to_string(&path) {
231 Ok(text) => {
232 let process = PROCESS
233 .read()
234 .unwrap_or_else(PoisonError::into_inner)
235 .clone();
236 Input::new(path.display().to_string(), text)
237 .parse_within::<RepoFile>(&process, Raise::InProcess)?
238 .limits
239 }
240 Err(error) if error.kind() == io::ErrorKind::NotFound => Limits::NONE,
241 Err(error) => {
242 return Err(InputError::unread(path.display().to_string(), &error));
243 }
244 };
245 let loosened = limits.loosened();
246 *REPOSITORY.write().unwrap_or_else(PoisonError::into_inner) = limits;
247 Ok(loosened)
248}
249
250#[cfg(feature = "yaml")]
252#[derive(Clone, Debug, PartialEq, Eq)]
253pub struct Loosened {
254 pub field: &'static str,
256 pub value: String,
258 pub default: String,
261}
262
263#[cfg(feature = "yaml")]
264impl fmt::Display for Loosened {
265 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
266 write!(
267 formatter,
268 "{REPO_FILE} raises {} to {}, above the default {}",
269 self.field, self.value, self.default
270 )
271 }
272}
273
274#[cfg(feature = "yaml")]
276#[derive(Deserialize)]
277#[serde(deny_unknown_fields)]
278struct RepoFile {
279 #[serde(default)]
280 limits: Limits,
281}
282
283pub(super) fn effective(call: &Limits) -> Limits {
285 let process = PROCESS.read().unwrap_or_else(PoisonError::into_inner);
286 #[cfg(feature = "yaml")]
287 let call = call
288 .clone()
289 .or(&REPOSITORY.read().unwrap_or_else(PoisonError::into_inner));
290 #[cfg(not(feature = "yaml"))]
291 let call = call.clone();
292 call.or(&process)
293}
294
295#[derive(Clone, Copy)]
297pub(super) enum Raise {
298 #[cfg(feature = "yaml")]
300 InRepository,
301 #[cfg(feature = "yaml")]
304 InProcess,
305 #[cfg(not(feature = "yaml"))]
308 InTool,
309}
310
311impl Raise {
312 #[cfg(feature = "yaml")]
314 pub(super) const FOR_TEXT: Self = Self::InRepository;
315 #[cfg(not(feature = "yaml"))]
317 pub(super) const FOR_TEXT: Self = Self::InTool;
318}
319
320pub(super) struct Exceeded {
322 field: &'static str,
323 limit: String,
324 raise: Raise,
325}
326
327impl Exceeded {
328 pub(super) fn input_bytes(limit: usize, raise: Raise) -> Self {
329 Self::new("max_reader_input_bytes", limit, raise)
330 }
331
332 pub(super) fn new(field: &'static str, limit: usize, raise: Raise) -> Self {
334 Self {
335 field,
336 limit: limit.to_string(),
337 raise,
338 }
339 }
340
341 #[cfg(feature = "yaml")]
345 #[expect(
346 clippy::wildcard_enum_match_arm,
347 reason = "BudgetBreach is non_exhaustive: a variant added later keeps serde-saphyr's wording"
348 )]
349 pub(super) fn breach(breach: &BudgetBreach, budget: &Budget, raise: Raise) -> Option<Self> {
350 let (field, limit) = match breach {
351 BudgetBreach::Events { .. } => ("max_events", budget.max_events.to_string()),
352 BudgetBreach::Aliases { .. } => ("max_aliases", budget.max_aliases.to_string()),
353 BudgetBreach::Anchors { .. } => ("max_anchors", budget.max_anchors.to_string()),
354 BudgetBreach::Depth { .. } => ("max_depth", budget.max_depth.to_string()),
355 BudgetBreach::InclusionDepth { .. } => (
356 "max_inclusion_depth",
357 budget.max_inclusion_depth.to_string(),
358 ),
359 BudgetBreach::Documents { .. } => ("max_documents", budget.max_documents.to_string()),
360 BudgetBreach::Nodes { .. } => ("max_nodes", budget.max_nodes.to_string()),
361 BudgetBreach::ScalarBytes { .. } => (
362 "max_total_scalar_bytes",
363 budget.max_total_scalar_bytes.to_string(),
364 ),
365 BudgetBreach::CommentBytes { .. } => (
366 "max_total_comment_bytes",
367 budget.max_total_comment_bytes.to_string(),
368 ),
369 BudgetBreach::MergeKeys { .. } => ("max_merge_keys", budget.max_merge_keys.to_string()),
370 BudgetBreach::AliasAnchorRatio { .. } => (
371 "alias_anchor_ratio_multiplier",
372 budget.alias_anchor_ratio_multiplier.to_string(),
373 ),
374 BudgetBreach::InputBytes { .. } => (
375 "max_reader_input_bytes",
376 budget
377 .max_reader_input_bytes
378 .map_or_else(|| "none".to_owned(), |limit| limit.to_string()),
379 ),
380 BudgetBreach::RecordedAnchorEvents { .. } => (
381 "max_recorded_anchor_events",
382 budget.max_recorded_anchor_events.to_string(),
383 ),
384 BudgetBreach::RecordedAnchorBytes { .. } => (
385 "max_recorded_anchor_bytes",
386 budget.max_recorded_anchor_bytes.to_string(),
387 ),
388 BudgetBreach::PropertyExpansionDepth { .. } => (
389 "max_property_expansion_depth",
390 budget.max_property_expansion_depth.to_string(),
391 ),
392 BudgetBreach::PropertyInterpolationWork { .. } => (
393 "max_total_property_interpolation_work",
394 budget.max_total_property_interpolation_work.to_string(),
395 ),
396 _ => return None,
397 };
398 Some(Self {
399 field,
400 limit,
401 raise,
402 })
403 }
404}
405
406impl fmt::Display for Exceeded {
407 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
408 write!(formatter, "exceeds {} ({}); ", self.field, self.limit)?;
409 match self.raise {
410 #[cfg(feature = "yaml")]
411 Raise::InRepository => {
412 write!(formatter, "raise limits.{} in {REPO_FILE}", self.field)
413 }
414 #[cfg(feature = "yaml")]
415 Raise::InProcess => write!(
416 formatter,
417 "raise {} in the tool's process default, which reads {REPO_FILE}",
418 self.field
419 ),
420 #[cfg(not(feature = "yaml"))]
421 Raise::InTool => write!(formatter, "the tool sets this limit"),
422 }
423 }
424}
425
426#[cfg(all(test, feature = "yaml"))]
427mod tests {
428 use serde_saphyr::Budget;
429
430 use super::Limits;
431
432 #[test]
436 fn the_shared_defaults_match_serde_saphyr() {
437 let budget = Budget::default();
438 assert_eq!(
439 budget.max_reader_input_bytes,
440 Some(Limits::DEFAULT_MAX_READER_INPUT_BYTES)
441 );
442 assert_eq!(budget.max_depth, Limits::DEFAULT_MAX_DEPTH);
443 assert_eq!(budget.max_nodes, Limits::DEFAULT_MAX_NODES);
444 }
445}