Skip to main content

ctl_input/
limits.rs

1//! How much a text may hold before [`Input::parse`](super::Input::parse)
2//! refuses it, and who decides. The order is on [`Limits`]. Three fields hold
3//! a text of every format: `max_reader_input_bytes`, `max_depth`, and
4//! `max_nodes`. The others name YAML syntax and exist only with `yaml`.
5
6use 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/// Where a repository overrides limits, relative to its root.
23#[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        /// Overrides for the limits a text is held to, one per field. `None`
32        /// leaves the field to the next tier.
33        ///
34        /// Each field is decided on its own, highest first:
35        ///
36        /// 1. the call: [`Input::limits`](super::Input::limits);
37        /// 2. with `yaml`, the repository: `limits:` in
38        ///    `.ctl/input.yaml`, installed by `use_repo_limits`;
39        /// 3. the process: [`set_default_limits`], or `App::input_limits`;
40        /// 4. the default: ctl-core's for the three fields every format
41        ///    reads, and serde-saphyr's for the YAML-only fields.
42        ///
43        /// A repository beats the CLI's default because the user owns the
44        /// repository, as a user's environment beats the CLI's built-in width.
45        ///
46        /// The field set follows the enabled format features.
47        /// `max_reader_input_bytes`, `max_depth`, and `max_nodes` exist in
48        /// every build, and the YAML-only fields exist with `yaml`.
49        /// Cargo enables a feature for every crate in a build, so another
50        /// crate can add fields to a build of yours. Build a value with
51        /// `..Limits::NONE`, as in `Limits { max_depth: Some(8),
52        /// ..Limits::NONE }`, and it compiles whatever the build enables.
53        ///
54        /// `enforce_alias_anchor_ratio` is not here: the ratio check is one
55        /// comparison after scanning, so turning it off saves nothing. It
56        /// stays on; its multiplier and minimum alias count are overridable.
57        #[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            /// No overrides: every field falls through.
66            pub const NONE: Self = Self {
67                $( $sfield: None, )*
68                $( #[cfg(feature = "yaml")] $yfield: None, )*
69            };
70
71            /// `self`, with each unset field taken from `lower`.
72            #[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            /// serde-saphyr's settings for these limits. An unset shared
81            /// field takes ctl-core's default, and an unset YAML-only field
82            /// takes serde-saphyr's.
83            #[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            /// Each set field that is looser than its default.
97            #[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        /// Bytes of input text. Also checked for text already in memory.
128        max_reader_input_bytes = DEFAULT_MAX_READER_INPUT_BYTES,
129        /// Nesting of YAML sequences and mappings, or of TOML arrays and
130        /// tables, with the root table as 1.
131        max_depth = DEFAULT_MAX_DEPTH,
132        /// YAML sequences, mappings, and scalars in total; in TOML, the root
133        /// table and every table, array, and value.
134        max_nodes = DEFAULT_MAX_NODES,
135    }
136    yaml {
137        /// Comment events buffered while resolving an ambiguous entry.
138        max_buffered_comment_events: usize,
139        /// Characters scanned to resolve a simple key.
140        simple_key_max_lookahead: usize,
141        /// Simultaneously nested flow collections.
142        flow_nesting_limit: usize,
143        /// Parser events in total.
144        max_events: usize,
145        /// Alias (`*ref`) events.
146        max_aliases: usize,
147        /// Distinct anchor (`&anchor`) definitions.
148        max_anchors: usize,
149        /// Event copies retained for anchors.
150        max_recorded_anchor_events: usize,
151        /// Bytes of string payload retained for anchors.
152        max_recorded_anchor_bytes: usize,
153        /// Nested expansions in one property interpolation.
154        max_property_expansion_depth: usize,
155        /// Bytes inspected across all property interpolation.
156        max_total_property_interpolation_work: usize,
157        /// Nesting of `!include`.
158        max_inclusion_depth: u32,
159        /// YAML documents in one text.
160        max_documents: usize,
161        /// Bytes of scalar text in total.
162        max_total_scalar_bytes: usize,
163        /// Bytes of comment text in total.
164        max_total_comment_bytes: usize,
165        /// Merge keys (`<<`). ctl-core refuses merge keys whatever this says.
166        max_merge_keys: usize,
167        /// Aliases allowed before the alias-to-anchor ratio applies.
168        alias_anchor_min_aliases: usize,
169        /// How many aliases each anchor may have once the ratio applies.
170        alias_anchor_ratio_multiplier: usize,
171    }
172}
173
174impl Limits {
175    /// `max_reader_input_bytes` when no tier sets it: 256 MiB.
176    pub const DEFAULT_MAX_READER_INPUT_BYTES: usize = 256 * 1024 * 1024;
177    /// `max_depth` when no tier sets it.
178    pub const DEFAULT_MAX_DEPTH: usize = 64;
179    /// `max_nodes` when no tier sets it.
180    pub const DEFAULT_MAX_NODES: usize = 250_000;
181
182    /// The three limits every format reads, with ctl-core's default for each
183    /// unset field.
184    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/// The three limits every format reads, as they are in force.
196#[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
207/// Set the process-wide default, which a call's
208/// [`Input::limits`](super::Input::limits) beats, and with `yaml` a
209/// repository's `.ctl/input.yaml` too.
210pub fn set_default_limits(limits: Limits) {
211    *PROCESS.write().unwrap_or_else(PoisonError::into_inner) = limits;
212}
213
214/// Read `limits:` from `root`'s [`REPO_FILE`] and install it for every later
215/// parse in this process. A repository without the file overrides nothing.
216/// The file itself is read under the process default, not under whatever
217/// repository was installed before.
218///
219/// Returns each limit the repository raises above its default. Print each as
220/// `{bin}: warning: {loosened}`. A raised limit is one above ctl-core's or
221/// serde-saphyr's default, whatever the CLI set as its process default.
222///
223/// # Errors
224///
225/// An [`InputError`] when the file cannot be read, is not YAML, or names a
226/// field [`Limits`] does not have.
227#[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/// A limit a repository's [`REPO_FILE`] raises above its default.
251#[cfg(feature = "yaml")]
252#[derive(Clone, Debug, PartialEq, Eq)]
253pub struct Loosened {
254    /// The [`Limits`] field.
255    pub field: &'static str,
256    /// The repository's value.
257    pub value: String,
258    /// The default: ctl-core's for a field every format reads, and
259    /// serde-saphyr's for a YAML-only field.
260    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/// The shape of [`REPO_FILE`].
275#[cfg(feature = "yaml")]
276#[derive(Deserialize)]
277#[serde(deny_unknown_fields)]
278struct RepoFile {
279    #[serde(default)]
280    limits: Limits,
281}
282
283/// What a parse with `call` uses, field by field.
284pub(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/// Where a user raises a limit a text went past.
296#[derive(Clone, Copy)]
297pub(super) enum Raise {
298    /// In the repository's [`REPO_FILE`].
299    #[cfg(feature = "yaml")]
300    InRepository,
301    /// In the tool's process default, for [`REPO_FILE`] itself, which is
302    /// read before any repository override applies.
303    #[cfg(feature = "yaml")]
304    InProcess,
305    /// Nowhere the user can reach: a build without `yaml` reads no
306    /// repository file, so only the tool sets limits.
307    #[cfg(not(feature = "yaml"))]
308    InTool,
309}
310
311impl Raise {
312    /// Where a limit hit by a CLI's own text is raised.
313    #[cfg(feature = "yaml")]
314    pub(super) const FOR_TEXT: Self = Self::InRepository;
315    /// Where a limit hit by a CLI's own text is raised.
316    #[cfg(not(feature = "yaml"))]
317    pub(super) const FOR_TEXT: Self = Self::InTool;
318}
319
320/// A limit a text went past: the field and the value in force.
321pub(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    /// The [`Limits`] `field` the text went past, with the value in force.
333    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    /// The field serde-saphyr reports as breached, with its value in `budget`.
342    /// `None` for a breach this version does not know, which keeps
343    /// serde-saphyr's own wording.
344    #[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    /// ctl-core states the three shared defaults, and a YAML text meets the
433    /// same ones it met under serde-saphyr's. A serde-saphyr release that
434    /// moves its defaults fails here before it ships.
435    #[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}