Skip to main content

feldera_types/config/
ignored.rs

1//! Finds configuration settings that deserialization ignores.
2//!
3//! [`serde_ignored`](https://crates.io/crates/serde_ignored) cannot see keys
4//! inside `#[serde(flatten)]` structs, and [`PipelineConfig`] flattens
5//! [`RuntimeConfig`], so this module uses a round trip instead:
6//!
7//! 1. Deserialize the input, serialize it again, and list each key in the
8//!    input that is not in the output.  A key can disappear because it is
9//!    unknown, but also because it is an alias or a default value that
10//!    serialization skips.
11//!
12//! 2. For each such key, replace its value with a string that no setting
13//!    accepts as is.  If the result deserializes to the same configuration,
14//!    the key is ignored.  If deserialization fails or the configuration
15//!    changes, then something read the key.
16//!
17//! [`PipelineConfig`]: super::PipelineConfig
18//! [`RuntimeConfig`]: super::RuntimeConfig
19
20use serde::{Serialize, de::DeserializeOwned};
21use serde_json::Value;
22
23/// Value put in place of a key to find out whether anything reads it.
24///
25/// The probe does not need to be rejected.  A string or `Value` setting accepts
26/// it, but then the probe appears in the serialized output, which then differs
27/// from the baseline.  Other settings fail to deserialize it.  Only a key that
28/// nothing reads gives the baseline again.  This is wrong only for a setting
29/// that accepts the probe and then discards it, such as one that turns bad
30/// input into its default.
31///
32/// The `\0` only makes a match with a real value or enum variant unlikely.
33const PROBE: &str = "\u{0}feldera-ignored-setting-probe";
34
35/// Returns the paths of the keys in `input` that have no effect when it is
36/// deserialized as a `T`, such as `inputs.t.transport.config.foo`.
37///
38/// Returns nothing if `input` does not deserialize as a `T`.  Does not look
39/// inside values that `T` keeps as opaque JSON, such as format configuration.
40pub fn ignored_settings<T>(input: &Value) -> Vec<String>
41where
42    T: DeserializeOwned + Serialize,
43{
44    let Some(baseline) = round_trip::<T>(input) else {
45        return Vec::new();
46    };
47    let mut candidates = Vec::new();
48    find_dropped_keys(input, &baseline, &mut Vec::new(), &mut candidates);
49    candidates
50        .into_iter()
51        .filter(|path| {
52            let mut probe = input.clone();
53            *lookup_mut(&mut probe, path) = Value::String(PROBE.into());
54            round_trip::<T>(&probe).as_ref() == Some(&baseline)
55        })
56        .map(|path| format_path(&path))
57        .collect()
58}
59
60#[derive(Clone)]
61enum Segment {
62    Key(String),
63    Index(usize),
64}
65
66fn round_trip<T>(value: &Value) -> Option<Value>
67where
68    T: DeserializeOwned + Serialize,
69{
70    let t = serde_json::from_value::<T>(value.clone()).ok()?;
71    serde_json::to_value(t).ok()
72}
73
74/// Appends to `dropped` the path of each key in `input` that `output` lacks.
75fn find_dropped_keys(
76    input: &Value,
77    output: &Value,
78    path: &mut Vec<Segment>,
79    dropped: &mut Vec<Vec<Segment>>,
80) {
81    match (input, output) {
82        (Value::Object(input), Value::Object(output)) => {
83            for (key, value) in input {
84                path.push(Segment::Key(key.clone()));
85                match output.get(key) {
86                    Some(output) => find_dropped_keys(value, output, path, dropped),
87                    None => dropped.push(path.clone()),
88                }
89                path.pop();
90            }
91        }
92        (Value::Array(input), Value::Array(output)) if input.len() == output.len() => {
93            for (index, (input, output)) in input.iter().zip(output).enumerate() {
94                path.push(Segment::Index(index));
95                find_dropped_keys(input, output, path, dropped);
96                path.pop();
97            }
98        }
99        _ => (),
100    }
101}
102
103fn lookup_mut<'a>(mut value: &'a mut Value, path: &[Segment]) -> &'a mut Value {
104    for segment in path {
105        value = match segment {
106            Segment::Key(key) => &mut value[key.as_str()],
107            Segment::Index(index) => &mut value[*index],
108        };
109    }
110    value
111}
112
113fn format_path(path: &[Segment]) -> String {
114    let mut s = String::new();
115    for segment in path {
116        match segment {
117            Segment::Key(key) => {
118                if !s.is_empty() {
119                    s.push('.');
120                }
121                s.push_str(key);
122            }
123            Segment::Index(index) => s.push_str(&format!("[{index}]")),
124        }
125    }
126    s
127}
128
129#[cfg(test)]
130mod test {
131    use super::ignored_settings;
132    use crate::config::PipelineConfig;
133    use serde_json::json;
134
135    /// Sorted, because the order follows `serde_json::Map`, which keeps
136    /// input order only with the `preserve_order` feature.
137    fn ignored(input: serde_json::Value) -> Vec<String> {
138        let mut settings = ignored_settings::<PipelineConfig>(&input);
139        settings.sort();
140        settings
141    }
142
143    #[test]
144    fn known_settings_are_not_ignored() {
145        assert_eq!(ignored(json!({})), Vec::<String>::new());
146        assert_eq!(
147            ignored(json!({
148                "workers": 4,
149                "storage": null,
150                "max_rss_mb": 1024,
151                "inputs": {
152                    "t.unnamed-0": {
153                        "stream": "t",
154                        "transport": {"name": "datagen", "config": {"plan": [{}]}},
155                    }
156                },
157            })),
158            Vec::<String>::new()
159        );
160    }
161
162    /// A default value that serialization skips is still a used setting.
163    #[test]
164    fn explicit_defaults_are_not_ignored() {
165        assert_eq!(
166            ignored(json!({
167                "inputs": {
168                    "c": {
169                        "stream": "t",
170                        "transport": {"name": "datagen", "config": {}},
171                        "distributed": false,
172                    }
173                },
174            })),
175            Vec::<String>::new()
176        );
177    }
178
179    #[test]
180    fn unknown_settings_are_ignored() {
181        assert_eq!(
182            ignored(json!({
183                "wokers": 4,
184                "dev_tweaks": {"buffer_size": 1},
185                "storage": {"bogus": null},
186                "inputs": {
187                    "t.unnamed-0": {
188                        "stream": "t",
189                        "transport": {
190                            "name": "file_input",
191                            "config": {"path": "x", "bogus": 2},
192                        },
193                        "bogus": 4,
194                    }
195                },
196            })),
197            vec![
198                "inputs.t.unnamed-0.bogus",
199                "inputs.t.unnamed-0.transport.config.bogus",
200                "storage.bogus",
201                "wokers",
202            ]
203        );
204    }
205}