Skip to main content

saluki_config/
yaml.rs

1//! YAML parsing for configuration files.
2
3use serde::de::{DeserializeOwned, DeserializeSeed};
4
5/// Deserializes a YAML document using YAML 1.1 scalar resolution.
6///
7/// Configuration files are commonly written against YAML 1.1 parsers, so plain scalars resolve the way those parsers
8/// resolve them rather than by the stricter YAML 1.2 core schema:
9///
10/// - `yes`/`no`, `on`/`off`, and `y`/`n` (in any case) are booleans.
11/// - Integers with a leading zero, such as `012`, are octal.
12/// - `<<` merge keys are expanded.
13///
14/// Non-finite floats (`.inf`, `.nan`) in untyped positions are kept as their string spelling rather than rejecting
15/// the whole document, leaving it to the consumer of that value to decide whether it's valid.
16///
17/// The default limits on the number of parsed nodes and events are lifted, as configuration files can legitimately
18/// hold very large lists. Nesting depth, alias expansion, and total scalar size are still bounded.
19///
20/// Errors report only a message and location, never the surrounding source lines, as configuration files can hold
21/// credentials. Comments are not retained, so runs of comments don't count against the comment limits.
22///
23/// # Errors
24///
25/// If the document isn't valid YAML, or doesn't deserialize as `T`, an error is returned.
26pub fn from_str<T>(input: &str) -> Result<T, serde_saphyr::Error>
27where
28    T: DeserializeOwned,
29{
30    serde_saphyr::from_str_with_options(input, options())
31}
32
33/// Deserializes a YAML document with `seed`, parsing it as [`from_str`] does.
34///
35/// # Errors
36///
37/// If the document isn't valid YAML, or `seed` fails to deserialize it, an error is returned.
38pub fn from_str_seed<'de, S>(input: &'de str, seed: S) -> Result<S::Value, serde_saphyr::Error>
39where
40    S: DeserializeSeed<'de>,
41{
42    serde_saphyr::with_deserializer_from_str_with_options(input, options(), |deserializer| {
43        seed.deserialize(deserializer)
44    })
45}
46
47fn options() -> serde_saphyr::Options {
48    let mut budget = serde_saphyr::Budget::default();
49    budget.max_nodes = usize::MAX;
50    budget.max_events = usize::MAX;
51
52    serde_saphyr::options! {
53        budget: Some(budget),
54        emit_comments: false,
55        legacy_octal_numbers: true,
56        non_finite_float_policy: serde_saphyr::NonFiniteFloatPolicy::AsString,
57        with_snippet: false,
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use std::marker::PhantomData;
64
65    use serde_json::{json, Value};
66
67    use super::*;
68
69    #[test]
70    fn resolves_plain_scalars_with_yaml_1_1_rules() {
71        let value: Value = from_str(
72            "yes: yes\noff: Off\nshort: n\noctal: 012\nhex: 0x1F\nnot_octal: 08\nquoted: '012'\nkeyword: \"on\"\n",
73        )
74        .unwrap();
75
76        assert_eq!(
77            value,
78            json!({
79                "yes": true,
80                "off": false,
81                "short": false,
82                "octal": 10,
83                "hex": 31,
84                "not_octal": 8.0,
85                "quoted": "012",
86                "keyword": "on",
87            })
88        );
89    }
90
91    #[test]
92    fn expands_merge_keys() {
93        let value: Value = from_str("base: &base {a: 1, b: 2}\nderived:\n  <<: *base\n  b: 3\n").unwrap();
94
95        assert_eq!(value["derived"], json!({"a": 1, "b": 3}));
96    }
97
98    #[test]
99    fn keeps_non_finite_floats_as_strings() {
100        let value: Value = from_str("a: .inf\nb: -.inf\nc: .nan\n").unwrap();
101
102        assert_eq!(value, json!({"a": ".inf", "b": "-.inf", "c": ".nan"}));
103    }
104
105    #[test]
106    fn parses_documents_with_very_large_lists() {
107        let mut input = String::from("items:\n");
108        for i in 0..300_000 {
109            input.push_str(&format!("  - item_{i}\n"));
110        }
111
112        let value: Value = from_str(&input).unwrap();
113
114        assert_eq!(value["items"].as_array().unwrap().len(), 300_000);
115    }
116
117    #[test]
118    fn rejects_duplicate_keys() {
119        assert!(from_str::<Value>("a: 1\na: 2\n").is_err());
120    }
121
122    #[test]
123    fn errors_do_not_include_source_lines() {
124        let input = "api_key: 0123456789abcdef0123456789abcdef\nlog_level: [unclosed\n";
125
126        let error = from_str::<Value>(input).unwrap_err().to_string();
127
128        assert!(!error.contains("0123456789abcdef"), "error leaks source: {error}");
129        assert!(error.contains("line 2"), "error lacks location: {error}");
130    }
131
132    #[test]
133    fn a_seed_parses_documents_as_from_str_does() {
134        let mut large_list = String::from("items:\n");
135        for i in 0..300_000 {
136            large_list.push_str(&format!("  - item_{i}\n"));
137        }
138        let inputs = [
139            "yes: yes\noff: Off\nshort: n\noctal: 012\nhex: 0x1F\nnot_octal: 08\nquoted: '012'\nkeyword: \"on\"\n",
140            "base: &base {a: 1, b: 2}\nderived:\n  <<: *base\n  b: 3\n",
141            "a: .inf\nb: -.inf\nc: .nan\n",
142            &large_list,
143            "proxy: # optional\n# a comment\nlog_level: info\n",
144            "",
145            "a: 1\na: 2\n",
146            "api_key: 0123456789abcdef0123456789abcdef\nlog_level: [unclosed\n",
147            "--- a\n--- b\n",
148        ];
149
150        for input in inputs {
151            let seeded = from_str_seed(input, PhantomData::<Value>).map_err(|e| e.to_string());
152            let plain = from_str::<Value>(input).map_err(|e| e.to_string());
153            assert_eq!(seeded, plain, "{input:?}");
154        }
155    }
156
157    #[test]
158    fn parses_long_runs_of_comments() {
159        let mut input = String::from("proxy: # optional\n");
160        for i in 0..100 {
161            input.push_str(&format!("# documentation line {i}\n"));
162        }
163        input.push_str("log_level: info\n");
164
165        let value: Value = from_str(&input).unwrap();
166
167        assert_eq!(value, json!({"proxy": null, "log_level": "info"}));
168    }
169}