Skip to main content

feldera_types/
config_diagnostics.rs

1//! Configuration errors without the rejected values, which can be secrets.
2
3/// Describe a deserialization failure without the rejected input.
4///
5/// Serde's messages quote the rejected scalar, enum variant, or map key,
6/// and a custom deserializer can copy arbitrary input into its message. The
7/// parts that come from the schema stay: the list of expected values or
8/// fields, the name of a missing or repeated field, and the position that
9/// serde_json appends. Callers supply the endpoint or source position
10/// separately.
11///
12/// This is an allow list over the messages of serde's `de::Error`
13/// constructors: `invalid_type`, `invalid_value`, `invalid_length`,
14/// `unknown_variant`, `unknown_field`, `missing_field` and
15/// `duplicate_field`. Any other message, such as one from `custom`, becomes
16/// a generic text: an unknown shape loses detail but never shows a value.
17pub fn deserialization_error(error: &impl std::fmt::Display) -> String {
18    let error = error.to_string();
19    // The rejected token comes before the last ", expected ": the expected
20    // part is schema-defined and never holds it.
21    let expected = || {
22        error
23            .rsplit_once(", expected ")
24            .map(|(_, expected)| expected)
25    };
26    if error.starts_with("invalid type:") {
27        match expected() {
28            Some(expected) => {
29                format!("a configuration value has the wrong type; expected {expected}")
30            }
31            None => "a configuration value has the wrong type; check the documented field types"
32                .to_string(),
33        }
34    } else if error.starts_with("invalid value:") || error.starts_with("unknown variant ") {
35        match expected() {
36            Some(expected) => {
37                format!("a configuration value is not supported; expected {expected}")
38            }
39            None => "a configuration value is not supported; check the documented allowed values"
40                .to_string(),
41        }
42    } else if let Some(rest) = error.strip_prefix("unknown field ") {
43        // The field name is an option name the user typed, not a value:
44        // keep it when it looks like one, so the user knows what to fix.
45        let token = rest
46            .rsplit_once(", expected ")
47            .map_or(rest, |(token, _)| token);
48        let token = token.split(" at line ").next().unwrap_or_default();
49        let name = option_name(token).map_or(String::new(), |name| format!(" {name}"));
50        match expected() {
51            Some(expected) => {
52                format!("the configuration contains an unknown field{name}; expected {expected}")
53            }
54            None => format!(
55                "the configuration contains an unknown field{name}; check the documented option names"
56            ),
57        }
58    } else if error.starts_with("invalid length ")
59        || error.starts_with("missing field ")
60        || error.starts_with("duplicate field ")
61    {
62        // The length is a number, and the field names are schema-defined.
63        error
64    } else {
65        "the configuration could not be parsed; check its syntax and documented options".to_string()
66    }
67}
68
69/// `token` when it is a backquoted option name: letters, digits, `_`, `.`
70/// and `-`, at most 64 characters.
71fn option_name(token: &str) -> Option<&str> {
72    let name = token.strip_prefix('`')?.strip_suffix('`')?;
73    let plain = name
74        .chars()
75        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'));
76    (!name.is_empty() && name.len() <= 64 && plain).then_some(token)
77}
78
79#[cfg(test)]
80mod tests {
81    use super::deserialization_error;
82    use crate::format::avro::{AvroEncoderConfig, AvroUpdateFormat};
83    use serde_json::json;
84
85    /// The rejected input is left out; the schema-defined parts stay.
86    #[test]
87    fn rejected_input_is_left_out_and_the_expected_part_stays() {
88        #[derive(Debug, serde::Deserialize)]
89        #[serde(deny_unknown_fields)]
90        #[allow(dead_code)]
91        struct Options {
92            update_format: Option<AvroUpdateFormat>,
93            threads: Option<usize>,
94        }
95        let cases = [
96            (json!("hunter2"), "wrong type; expected struct Options"),
97            (
98                json!({"update_format": "hunter2"}),
99                "not supported; expected one of `raw`, `debezium`",
100            ),
101            (json!({"threads": "hunter2"}), "wrong type; expected usize"),
102        ];
103        for (config, expected) in cases {
104            let error = serde_json::from_value::<Options>(config).unwrap_err();
105            let reason = deserialization_error(&error);
106            assert!(!reason.contains("hunter2"), "{reason}");
107            assert!(reason.contains(expected), "{reason}");
108        }
109        // An unknown field is an option name the user typed: it is named.
110        let error = serde_json::from_value::<Options>(json!({"treads": true})).unwrap_err();
111        assert_eq!(
112            deserialization_error(&error),
113            "the configuration contains an unknown field `treads`; expected `update_format` or `threads`"
114        );
115        let error = serde_json::from_value::<Options>(json!({"a b": true})).unwrap_err();
116        assert!(!deserialization_error(&error).contains("a b"));
117    }
118
119    /// A struct with a flattened field gets no expected list from serde;
120    /// the category and the advice remain.
121    #[test]
122    fn a_flattened_config_keeps_the_category() {
123        let error =
124            serde_json::from_value::<AvroEncoderConfig>(json!({"hunter2": true})).unwrap_err();
125        assert_eq!(
126            deserialization_error(&error),
127            "the configuration contains an unknown field `hunter2`; check the documented option names"
128        );
129    }
130
131    /// Serde's position suffix and the schema-defined field names stay.
132    #[test]
133    fn positions_and_schema_field_names_stay() {
134        let error = serde_json::from_str::<AvroEncoderConfig>(
135            r#"{"namespace": "hunter2", "namespace": "a"}"#,
136        )
137        .unwrap_err();
138        assert_eq!(
139            deserialization_error(&error),
140            "duplicate field `namespace` at line 1 column 36"
141        );
142        #[derive(Debug, serde::Deserialize)]
143        #[allow(dead_code)]
144        struct Required {
145            key: String,
146        }
147        let error = serde_json::from_str::<Required>(r#"{"hunter2": "x"}"#).unwrap_err();
148        assert_eq!(
149            deserialization_error(&error),
150            "missing field `key` at line 1 column 16"
151        );
152    }
153
154    /// A custom deserializer error can hold anything: none of it is copied,
155    /// also when it contains ", expected ".
156    #[test]
157    fn custom_errors_are_not_copied() {
158        for error in ["custom error: hunter2", "hunter2, expected hunter2"] {
159            let reason = deserialization_error(&error);
160            assert!(!reason.contains("hunter2"), "{reason}");
161            assert!(reason.contains("check its syntax"), "{reason}");
162        }
163    }
164}