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