Skip to main content

datadog_agent_config_overlay_model/
schema_gen.rs

1//! Loads Datadog Agent configuration schemas for build-time code generation.
2//!
3//! Resolves schema file references and incorporates the OTel receiver schema, producing a map
4//! from dotted YAML paths to [`FieldInfo`].
5use std::collections::HashSet;
6use std::path::Path;
7
8use indexmap::IndexMap;
9use serde_json::{Map, Value};
10
11/// Value type of a config field, as declared in the schema YAML.
12///
13/// `Unknown` covers missing or unsupported types, including arrays of non-string items.
14pub enum FieldType {
15    String,
16    Bool,
17    Integer,
18    Float,
19    StringList,
20    Duration,
21    Unknown,
22}
23
24/// A named environment-variable parser declared by the schema's `env_parser` key.
25///
26/// The Datadog Agent registers a bespoke transform for these settings instead of the default
27/// type-based cast. Codegen maps supported parsers onto runtime decoders and rejects unsupported
28/// parsers for modeled keys. A setting without `env_parser` falls back to its declared type.
29pub enum EnvParser {
30    Json,
31    CommaSeparated,
32    CsvCommaSeparated,
33    CommaAndSpaceSeparated,
34    CommaThenSpaceSeparated,
35    JsonListOrCommaSeparated,
36    JsonListOrSpaceSeparated,
37    TracesSpan,
38}
39
40impl EnvParser {
41    /// Parses a schema `env_parser` value, panicking on an unrecognized name so a not-modeled parser
42    /// fails the build rather than silently degrading to the type-based fallback.
43    fn parse(name: &str) -> Self {
44        match name {
45            "json" => EnvParser::Json,
46            "comma_separated" => EnvParser::CommaSeparated,
47            "csv_comma_separated" => EnvParser::CsvCommaSeparated,
48            "comma_and_space_separated" => EnvParser::CommaAndSpaceSeparated,
49            "comma_then_space_separated" => EnvParser::CommaThenSpaceSeparated,
50            "json_list_or_comma_separated" => EnvParser::JsonListOrCommaSeparated,
51            "json_list_or_space_separated" => EnvParser::JsonListOrSpaceSeparated,
52            "traces_span" => EnvParser::TracesSpan,
53            other => panic!("unknown env_parser `{other}` in schema; add it to EnvParser and env_decode"),
54        }
55    }
56}
57
58/// How a config field is reachable through an environment variable.
59///
60/// Mirrors the Datadog Agent's `bindEnv`: a setting either has no env var, uses the standard
61/// `DD_` + `UPPER(dotted_path)` name derived from its key, or declares explicit names that
62/// replace that derived default. The distinction matters to codegen: the standard name is
63/// computable from the path, an overridden name is not, and a field with no env var must never be
64/// treated as env-reachable.
65pub enum EnvBinding {
66    /// The field carries a `no-env` tag: no environment variable maps to it.
67    None,
68    /// No explicit env vars are declared, so the Agent derives `DD_` + `UPPER(dotted_path)`.
69    Standard,
70    /// The schema declares explicit environment variable names, which replace the derived default. Non-empty.
71    Overridden(Vec<String>),
72}
73
74/// Parsed metadata for a single config field.
75pub struct FieldInfo {
76    /// Resolved value type (see [`FieldType`]).
77    pub value_type: FieldType,
78    /// How the field is reachable through an environment variable (see [`EnvBinding`]).
79    pub env: EnvBinding,
80    /// The schema's named `env_parser`, if any (see [`EnvParser`]); `None` uses the type fallback.
81    pub env_parser: Option<EnvParser>,
82    /// Default value serialised as a JSON literal, or `None` if the schema omits one.
83    pub default: Option<String>,
84    /// Former dotted names of the setting, from the schema's `renamed_from`, highest priority first.
85    ///
86    /// The Agent's codegen orders them by the version that deprecated each, oldest first, then by
87    /// name. A `no-env` setting has none: the Agent declares it with `SetDefault`, which registers no
88    /// former names.
89    pub renamed_from: Vec<String>,
90}
91
92/// Load and flatten the schema at `schema_path` into a `yaml_path → FieldInfo` map.
93///
94/// Resolves `$ref: <filename>` entries by loading the referenced files from the same directory.
95/// The map is sorted by key. Panics if the file cannot be read or parsed.
96pub fn load_schema(datadog_schema: &Path, otel_schema_dir: &Path) -> IndexMap<String, FieldInfo> {
97    let doc = crate::load_composed_schema(datadog_schema, otel_schema_dir)
98        .unwrap_or_else(|e| panic!("failed to load composed schema: {e}"));
99    load_schema_from_value(&doc)
100}
101
102/// Builds the flat `yaml_path → FieldInfo` map from a pre-loaded composed schema.
103///
104/// Callers that already hold the composed schema should use this instead of [`load_schema`] to
105/// avoid a redundant disk read and guarantee every consumer sees the same document.
106pub fn load_schema_from_value(doc: &Value) -> IndexMap<String, FieldInfo> {
107    let properties = doc
108        .get("properties")
109        .and_then(|v| v.as_object())
110        .expect("schema root must have a 'properties' mapping");
111
112    let mut entries = Vec::new();
113    collect_entries(properties, &[], &mut entries);
114    entries.sort_by(|a, b| a.0.cmp(&b.0));
115
116    let mut map = IndexMap::new();
117    for (yaml_path, info) in entries {
118        map.insert(yaml_path, info);
119    }
120    map
121}
122
123fn collect_entries(mapping: &Map<String, Value>, path_parts: &[&str], out: &mut Vec<(String, FieldInfo)>) {
124    for (key, value) in mapping {
125        let mut parts = path_parts.to_vec();
126        parts.push(key);
127
128        // `$ref`s are inlined by `crate::load_resolved_schema` before we get here, so every node
129        // is either a `setting`, a `section`, or some other container with `properties`.
130        let node_type = value.get("node_type").and_then(|v| v.as_str()).unwrap_or("");
131
132        match node_type {
133            "setting" => out.push(parse_setting(&parts, value)),
134            "section" => {
135                if let Some(props) = value.get("properties").and_then(|v| v.as_object()) {
136                    collect_entries(props, &parts, out);
137                }
138            }
139            _ => {
140                if let Some(props) = value.get("properties").and_then(|v| v.as_object()) {
141                    collect_entries(props, &parts, out);
142                }
143            }
144        }
145    }
146}
147
148fn parse_setting(path_parts: &[&str], value: &Value) -> (String, FieldInfo) {
149    let yaml_path = path_parts.join(".");
150
151    let has_no_env_tag = value
152        .get("tags")
153        .and_then(|v| v.as_array())
154        .map(|tags| tags.iter().any(|t| t.as_str() == Some("no-env")))
155        .unwrap_or(false);
156
157    let explicit_env_vars: Vec<String> = value
158        .get("env_vars")
159        .and_then(|v| v.as_array())
160        .map(|seq| seq.iter().filter_map(|v| v.as_str()).map(|s| s.to_string()).collect())
161        .unwrap_or_default();
162
163    // A `no-env` tag wins over any declared names: the field is not env-reachable at all.
164    let env = if has_no_env_tag {
165        EnvBinding::None
166    } else if explicit_env_vars.is_empty() {
167        EnvBinding::Standard
168    } else {
169        EnvBinding::Overridden(explicit_env_vars)
170    };
171
172    let value_type = parse_value_type(value);
173    let default = value.get("default").and_then(yaml_value_to_json_str);
174    let env_parser = value.get("env_parser").and_then(|v| v.as_str()).map(EnvParser::parse);
175    let renamed_from = if has_no_env_tag {
176        Vec::new()
177    } else {
178        parse_renamed_from(&yaml_path, value)
179    };
180
181    (
182        yaml_path,
183        FieldInfo {
184            value_type,
185            env,
186            env_parser,
187            default,
188            renamed_from,
189        },
190    )
191}
192
193/// Parses `renamed_from`, a map of former name to the `MAJOR.MINOR.PATCH` Agent version that
194/// deprecated it, into former names ordered as the Agent's `deprecated_names` orders them.
195///
196/// Panics on a malformed entry, which the Agent's schema lint also rejects.
197fn parse_renamed_from(yaml_path: &str, value: &Value) -> Vec<String> {
198    let Some(renamed_from) = value.get("renamed_from") else {
199        return Vec::new();
200    };
201    let entries = renamed_from
202        .as_object()
203        .unwrap_or_else(|| panic!("`{yaml_path}`: `renamed_from` must map former names to versions"));
204    let mut names: Vec<((u64, u64, u64), String)> = entries
205        .iter()
206        .map(|(name, version)| {
207            let version = version
208                .as_str()
209                .and_then(parse_version)
210                .unwrap_or_else(|| panic!("`{yaml_path}`: `renamed_from.{name}` must be a `MAJOR.MINOR.PATCH` string"));
211            (version, name.clone())
212        })
213        .collect();
214    names.sort();
215    names.into_iter().map(|(_, name)| name).collect()
216}
217
218fn parse_version(version: &str) -> Option<(u64, u64, u64)> {
219    let mut parts = version.split('.').map(|part| {
220        (!part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()))
221            .then(|| part.parse().ok())
222            .flatten()
223    });
224    let parsed = (parts.next()??, parts.next()??, parts.next()??);
225    parts.next().is_none().then_some(parsed)
226}
227
228/// A former name of a schema setting, from its `renamed_from`.
229#[derive(Debug, PartialEq)]
230pub struct FormerName<'a> {
231    /// The former dotted name.
232    pub former: &'a str,
233    /// The dotted name of the setting.
234    pub key: &'a str,
235    /// The environment variable derived from the former name, if the environment reader reads the
236    /// setting. It is also among the setting's [`env_var_names`].
237    pub env_var: Option<String>,
238}
239
240/// Derives the Agent's standard environment name for a key: `DD_` + `UPPER(dotted_path)`.
241pub fn standard_env_name(key: &str) -> String {
242    format!("DD_{}", key.replace('.', "_").to_uppercase())
243}
244
245/// The environment variables the Agent reads for the setting at `key`, highest priority first.
246///
247/// Explicit `env_vars` are used verbatim, in declared order. Otherwise each former name derives a
248/// name ahead of the key's own, as `BindEnvAndSetDefaultWithDeprecation` binds them. A `no-env`
249/// setting, or a key without schema metadata, derives only its own name.
250///
251/// Panics when a setting has both `env_vars` and `renamed_from`. The environment reader calls this
252/// only for modeled settings, so only those fail the build.
253pub fn env_var_names(key: &str, info: Option<&FieldInfo>) -> Vec<String> {
254    match info.map(|i| (i, &i.env)) {
255        Some((info, EnvBinding::Overridden(env_vars))) => {
256            if !info.renamed_from.is_empty() {
257                panic!(
258                    "`{key}` has both `env_vars` and `renamed_from`: confirm which environment variables the \
259                     Agent reads for its former names, and generate them here"
260                );
261            }
262            env_vars.clone()
263        }
264        Some((info, EnvBinding::Standard)) => info
265            .renamed_from
266            .iter()
267            .map(String::as_str)
268            .chain(std::iter::once(key))
269            .map(standard_env_name)
270            .collect(),
271        None | Some((_, EnvBinding::None)) => vec![standard_env_name(key)],
272    }
273}
274
275/// Every former name of every setting in `schema`, grouped by setting and highest priority first
276/// within a setting.
277///
278/// A former name's environment variable is derived for a `modeled` setting, which is the only kind
279/// the environment reader reads.
280///
281/// Panics when a former name is a schema path, or a setting or another former name contains or holds
282/// it, since the file reader could not tell which one a key addresses.
283pub fn former_names<'a>(schema: &'a IndexMap<String, FieldInfo>, modeled: &HashSet<&str>) -> Vec<FormerName<'a>> {
284    let leaves: HashSet<&str> = schema.keys().map(String::as_str).collect();
285    let sections: HashSet<&str> = leaves.iter().flat_map(|key| proper_prefixes(key)).collect();
286    let mut names: Vec<FormerName<'a>> = Vec::new();
287    for (key, info) in schema {
288        for former in &info.renamed_from {
289            let clash = std::iter::once(former.as_str())
290                .filter(|path| leaves.contains(path) || sections.contains(path))
291                .chain(proper_prefixes(former).filter(|prefix| leaves.contains(prefix)))
292                .next();
293            if let Some(clash) = clash {
294                panic!("former name `{former}` of `{key}` overlaps the schema path `{clash}`");
295            }
296            let other = names.iter().find(|other| {
297                other.former == former
298                    || proper_prefixes(former).any(|prefix| prefix == other.former)
299                    || proper_prefixes(other.former).any(|prefix| prefix == former)
300            });
301            if let Some(other) = other {
302                panic!(
303                    "former name `{former}` of `{key}` overlaps the former name `{}` of `{}`",
304                    other.former, other.key
305                );
306            }
307
308            let env_var = match info.env {
309                EnvBinding::Standard if modeled.contains(key.as_str()) => Some(standard_env_name(former)),
310                _ => None,
311            };
312            names.push(FormerName { former, key, env_var });
313        }
314    }
315    names
316}
317
318/// Every dotted proper prefix of `key`.
319fn proper_prefixes(key: &str) -> impl Iterator<Item = &str> {
320    key.match_indices('.').map(|(end, _)| &key[..end])
321}
322
323fn parse_value_type(value: &Value) -> FieldType {
324    let ty = value.get("type").and_then(|v| v.as_str());
325    let format = value.get("format").and_then(|v| v.as_str());
326
327    // `format: duration` folds into a single effective `Duration` type regardless of the declared
328    // base type. The vendored Agent schema currently declares these as `type: number` (nanoseconds
329    // on the wire) but has also used `type: string` (Go duration text); both are durations to us.
330    if format == Some("duration") {
331        return match ty {
332            Some("string") | Some("number") | Some("integer") => FieldType::Duration,
333            other => panic!(
334                "config schema field has `format: duration` with unsupported base type {:?}; \
335                 expected string, number, or integer",
336                other
337            ),
338        };
339    }
340
341    match ty {
342        Some("string") => FieldType::String,
343        Some("boolean") => FieldType::Bool,
344        Some("integer") => FieldType::Integer,
345        Some("number") => FieldType::Float,
346        Some("array") => {
347            let item_type = value.get("items").and_then(|v| v.get("type")).and_then(|v| v.as_str());
348            if item_type == Some("string") {
349                FieldType::StringList
350            } else {
351                FieldType::Unknown
352            }
353        }
354        _ => FieldType::Unknown,
355    }
356}
357
358fn yaml_value_to_json_str(value: &Value) -> Option<String> {
359    match value {
360        Value::Null => None,
361        Value::Bool(b) => Some(b.to_string()),
362        Value::Number(n) => Some(n.to_string()),
363        Value::String(s) => {
364            let escaped = s.replace('\\', "\\\\").replace('"', "\\\"");
365            Some(format!("\"{}\"", escaped))
366        }
367        Value::Array(seq) => {
368            let items: Option<Vec<String>> = seq.iter().map(yaml_value_to_json_str).collect();
369            items.map(|elems| format!("[{}]", elems.join(",")))
370        }
371        Value::Object(map) if map.is_empty() => Some("{}".to_string()),
372        _ => None,
373    }
374}
375
376/// Escape backslashes and double-quotes in `s` for use inside a Rust string literal.
377pub fn escape_str(s: &str) -> String {
378    s.replace('\\', "\\\\").replace('"', "\\\"")
379}
380
381#[cfg(test)]
382mod tests {
383    use serde_json::json;
384
385    use super::*;
386
387    fn renamed_from(setting: Value) -> Vec<String> {
388        parse_setting(&["new_name"], &setting).1.renamed_from
389    }
390
391    fn env_names(key: &str, setting: Value) -> Vec<String> {
392        let path: Vec<&str> = key.split('.').collect();
393        env_var_names(key, Some(&parse_setting(&path, &setting).1))
394    }
395
396    /// The flattened schema whose root `properties` are `properties`.
397    fn schema(properties: Value) -> IndexMap<String, FieldInfo> {
398        load_schema_from_value(&json!({ "properties": properties }))
399    }
400
401    fn setting(renamed_from: Value) -> Value {
402        json!({"node_type": "setting", "type": "boolean", "renamed_from": renamed_from})
403    }
404
405    fn plain_setting() -> Value {
406        json!({"node_type": "setting", "type": "boolean"})
407    }
408
409    #[test]
410    fn former_names_are_ordered_by_deprecating_version_then_name() {
411        let setting = json!({
412            "node_type": "setting",
413            "type": "boolean",
414            "renamed_from": {"c_name": "7.10.0", "b_name": "7.9.1", "a_name": "7.10.0", "d_name": "6.99.0"},
415        });
416
417        assert_eq!(renamed_from(setting), ["d_name", "b_name", "a_name", "c_name"]);
418    }
419
420    #[test]
421    fn a_setting_without_renamed_from_or_with_no_env_has_no_former_names() {
422        assert!(renamed_from(json!({"node_type": "setting", "type": "boolean"})).is_empty());
423        assert!(renamed_from(json!({
424            "node_type": "setting",
425            "type": "boolean",
426            "tags": ["no-env"],
427            "renamed_from": {"old_name": "7.86.0"},
428        }))
429        .is_empty());
430    }
431
432    #[test]
433    fn the_vendored_schema_renames_the_dogstatsd_blocklist() {
434        let files = crate::Files::default();
435        let schema = load_schema(&files.datadog_schema, &files.otel_schema_dir);
436
437        assert_eq!(schema["metric_filterlist"].renamed_from, ["statsd_metric_blocklist"]);
438        assert_eq!(
439            schema["metric_filterlist_match_prefix"].renamed_from,
440            ["statsd_metric_blocklist_match_prefix"]
441        );
442    }
443
444    #[test]
445    #[should_panic(expected = "`renamed_from` must map former names to versions")]
446    fn a_renamed_from_that_is_not_a_map_is_rejected() {
447        renamed_from(json!({"node_type": "setting", "renamed_from": ["old_name"]}));
448    }
449
450    #[test]
451    fn former_names_derive_environment_variables_ahead_of_the_current_name() {
452        let names = env_names(
453            "section.new_name",
454            setting(json!({"legacy.old_name": "7.1.0", "oldest_name": "6.0.0"})),
455        );
456
457        assert_eq!(names, ["DD_OLDEST_NAME", "DD_LEGACY_OLD_NAME", "DD_SECTION_NEW_NAME"]);
458        assert_eq!(env_names("new_name", plain_setting()), ["DD_NEW_NAME"]);
459    }
460
461    #[test]
462    fn a_no_env_setting_or_unknown_key_derives_only_its_own_variable() {
463        let no_env = json!({
464            "node_type": "setting",
465            "type": "boolean",
466            "tags": ["no-env"],
467            "renamed_from": {"old_name": "7.1.0"},
468        });
469
470        assert_eq!(env_names("new_name", no_env), ["DD_NEW_NAME"]);
471        assert_eq!(env_var_names("new_name", None), ["DD_NEW_NAME"]);
472    }
473
474    #[test]
475    fn explicit_environment_variables_are_read_verbatim() {
476        let setting = json!({"node_type": "setting", "type": "boolean", "env_vars": ["DD_B", "DD_A"]});
477
478        assert_eq!(env_names("new_name", setting), ["DD_B", "DD_A"]);
479    }
480
481    #[test]
482    #[should_panic(expected = "`new_name` has both `env_vars` and `renamed_from`")]
483    fn a_setting_with_explicit_environment_variables_and_former_names_is_rejected() {
484        env_names(
485            "new_name",
486            json!({
487                "node_type": "setting",
488                "type": "boolean",
489                "env_vars": ["DD_NEW_NAME"],
490                "renamed_from": {"old_name": "7.1.0"},
491            }),
492        );
493    }
494
495    #[test]
496    fn former_names_are_listed_per_setting_with_variables_for_modeled_settings_only() {
497        let schema = schema(json!({
498            "modeled": setting(json!({"old_modeled": "7.2.0", "oldest_modeled": "7.1.0"})),
499            "section": {
500                "node_type": "section",
501                "properties": {"unmodeled": setting(json!({"legacy.old_unmodeled": "7.1.0"}))},
502            },
503            "untouched": plain_setting(),
504        }));
505
506        let names = former_names(&schema, &HashSet::from(["modeled", "untouched"]));
507
508        let name = |former, key, env_var: Option<&str>| FormerName {
509            former,
510            key,
511            env_var: env_var.map(str::to_owned),
512        };
513        assert_eq!(
514            names,
515            [
516                name("oldest_modeled", "modeled", Some("DD_OLDEST_MODELED")),
517                name("old_modeled", "modeled", Some("DD_OLD_MODELED")),
518                name("legacy.old_unmodeled", "section.unmodeled", None),
519            ]
520        );
521    }
522
523    #[test]
524    #[should_panic(expected = "former name `taken` of `new_name` overlaps the schema path `taken`")]
525    fn a_former_name_that_is_a_setting_is_rejected() {
526        former_names(
527            &schema(json!({"new_name": setting(json!({"taken": "7.1.0"})), "taken": plain_setting()})),
528            &HashSet::new(),
529        );
530    }
531
532    #[test]
533    #[should_panic(expected = "former name `section` of `new_name` overlaps the schema path `section`")]
534    fn a_former_name_that_is_a_section_is_rejected() {
535        former_names(
536            &schema(json!({
537                "new_name": setting(json!({"section": "7.1.0"})),
538                "section": {"node_type": "section", "properties": {"leaf": plain_setting()}},
539            })),
540            &HashSet::new(),
541        );
542    }
543
544    #[test]
545    #[should_panic(expected = "former name `taken.old_name` of `new_name` overlaps the schema path `taken`")]
546    fn a_former_name_inside_a_setting_is_rejected() {
547        former_names(
548            &schema(json!({"new_name": setting(json!({"taken.old_name": "7.1.0"})), "taken": plain_setting()})),
549            &HashSet::new(),
550        );
551    }
552
553    #[test]
554    #[should_panic(expected = "former name `old.inner` of `second` overlaps the former name `old` of `first`")]
555    fn former_names_that_hold_each_other_are_rejected() {
556        former_names(
557            &schema(json!({
558                "first": setting(json!({"old": "7.1.0"})),
559                "second": setting(json!({"old.inner": "7.1.0"})),
560            })),
561            &HashSet::new(),
562        );
563    }
564
565    #[test]
566    #[should_panic(expected = "former name `old` of `second` overlaps the former name `old.inner` of `first`")]
567    fn a_former_name_that_holds_an_earlier_former_name_is_rejected() {
568        former_names(
569            &schema(json!({
570                "first": setting(json!({"old.inner": "7.1.0"})),
571                "second": setting(json!({"old": "7.1.0"})),
572            })),
573            &HashSet::new(),
574        );
575    }
576
577    #[test]
578    #[should_panic(expected = "former name `old` of `second` overlaps the former name `old` of `first`")]
579    fn a_former_name_of_two_settings_is_rejected() {
580        former_names(
581            &schema(json!({
582                "first": setting(json!({"old": "7.1.0"})),
583                "second": setting(json!({"old": "7.1.0"})),
584            })),
585            &HashSet::new(),
586        );
587    }
588
589    #[test]
590    #[should_panic(expected = "must be a `MAJOR.MINOR.PATCH` string")]
591    fn a_partial_version_is_rejected() {
592        renamed_from(json!({"node_type": "setting", "renamed_from": {"old_name": "7.86"}}));
593    }
594
595    #[test]
596    fn versions_parse_only_in_full_semantic_form() {
597        assert_eq!(parse_version("7.86.0"), Some((7, 86, 0)));
598        for invalid in ["7.86", "7.86.0.1", "v7.86.0", "7.86.0-rc.1", "7..0", "7.+1.0"] {
599            assert_eq!(parse_version(invalid), None, "{invalid}");
600        }
601    }
602}