Skip to main content

datadog_agent_config_overlay_model/
lib.rs

1//! Deserialization types for `schema_overlay.yaml`.
2//!
3//! This crate provides the model for management of our inventory and metadata around Datadog Agent
4//! configuration. It is designed to be used during build processes by `build.rs` and, for
5//! simplicity, should not depend on any other crates from our workspace.
6//!
7//! Loading checks section and key ordering, deserializes with unknown fields rejected, then
8//! validates schema coverage and entry constraints.
9
10pub mod saluki_keys;
11pub mod schema_gen;
12
13use std::collections::HashSet;
14use std::path::{Path, PathBuf};
15
16use indexmap::IndexMap;
17use serde::Deserialize;
18use serde_json::{Map, Value};
19
20/// Top-level overlay structure.
21///
22/// `inventory` classifies keys by support level; `excluded` gives reasons for ignoring other keys.
23/// Together they must cover every key in the composed Datadog and OTel schema exactly once.
24#[derive(Debug, Clone, Deserialize)]
25#[serde(deny_unknown_fields)]
26pub struct SchemaOverlay {
27    pub inventory: IndexMap<String, KnownEntry>,
28    pub excluded: IndexMap<String, String>,
29}
30
31/// Support classification for a key in the overlay's `inventory`.
32#[derive(Debug, Clone, Deserialize)]
33#[serde(tag = "support", rename_all = "snake_case")]
34pub enum KnownEntry {
35    /// ADP reads and fully supports this key; behavior matches the core Agent.
36    Full(FullSupport),
37    /// ADP reads this key but behavior diverges from the core Agent in some cases.
38    Partial(PartialSupport),
39    /// ADP does not support this key.
40    #[serde(rename = "none")]
41    Unsupported(Unsupported),
42    /// ADP's compatibility with this key has not yet been determined.
43    Unknown(UnknownSupport),
44}
45
46/// Metadata for a fully supported configuration key.
47#[derive(Debug, Clone, Deserialize)]
48#[serde(rename_all = "snake_case", deny_unknown_fields)]
49pub struct FullSupport {
50    /// Which pipelines depend on this key (non-empty).
51    pub pipelines: PipelineAffinity,
52    /// Short description for documentation tables, limited by UTF-8 byte length.
53    pub description: String,
54    /// Extended documentation (appears in generated docs).
55    #[serde(default)]
56    pub documentation: Option<String>,
57    /// GitHub issue tracking number.
58    #[serde(default)]
59    pub issue: Option<String>,
60}
61
62/// Metadata for a partially supported configuration key.
63#[derive(Debug, Clone, Deserialize)]
64#[serde(rename_all = "snake_case", deny_unknown_fields)]
65pub struct PartialSupport {
66    /// Which pipelines depend on this key (non-empty).
67    pub pipelines: PipelineAffinity,
68    /// Short description for documentation tables, limited by UTF-8 byte length.
69    pub description: String,
70    /// Extended documentation explaining the behavioral divergence. Required for partial keys.
71    pub documentation: String,
72    /// Whether non-default values can trigger compatibility warnings. Defaults to false.
73    #[serde(default)]
74    pub warn: bool,
75    /// GitHub issue tracking number.
76    #[serde(default)]
77    pub issue: Option<String>,
78}
79
80/// Metadata for an unsupported configuration key.
81#[derive(Debug, Clone, Deserialize)]
82#[serde(rename_all = "snake_case", deny_unknown_fields)]
83pub struct Unsupported {
84    /// Pipelines affected by the lack of support.
85    pub pipelines: PipelineAffinity,
86    /// Short description for documentation tables, limited by UTF-8 byte length.
87    pub description: String,
88    /// Longer explanation of why it is unsupported and future plans.
89    #[serde(default)]
90    pub documentation: Option<String>,
91    /// How severe the lack of support is.
92    pub severity: Severity,
93    /// Whether support is planned. When true, `issue` must be present.
94    pub planned: bool,
95    /// GitHub issue tracking number.
96    #[serde(default)]
97    pub issue: Option<String>,
98    /// Whether the core Agent's behavior depends on whether the key is set, not only on its value.
99    /// When true, the compatibility check reports the key even when it is set to its default value.
100    /// Keys without a schema default are always treated this way. Defaults to false.
101    #[serde(default)]
102    pub presence_matters: bool,
103}
104
105/// Metadata for a key whose support level has not yet been determined.
106#[derive(Debug, Clone, Deserialize)]
107#[serde(rename_all = "snake_case", deny_unknown_fields)]
108pub struct UnknownSupport {
109    /// Optional description for documentation tables, limited by UTF-8 byte length.
110    #[serde(default)]
111    pub description: Option<String>,
112    /// Severity estimate, if there is intuition about the impact.
113    #[serde(default)]
114    pub severity: Option<Severity>,
115    /// GitHub issue tracking the investigation.
116    #[serde(default)]
117    pub issue: Option<String>,
118}
119
120/// Impact severity of an unsupported or unknown key.
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
122#[serde(rename_all = "snake_case")]
123pub enum Severity {
124    Low,
125    Medium,
126    High,
127}
128
129/// A single pipeline in the ADP vocabulary.
130#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize)]
131#[serde(rename_all = "snake_case")]
132pub enum Pipeline {
133    #[serde(rename = "dogstatsd")]
134    DogStatsD,
135    Checks,
136    Otlp,
137    Traces,
138    Logs,
139}
140
141/// Which pipelines a config key is associated with.
142///
143/// Deserialized from a flat YAML list of pipeline tokens. An empty list is rejected. A list
144/// containing only `cross_cutting` folds to [`PipelineAffinity::CrossCutting`]; `cross_cutting`
145/// may not appear alongside other tokens.
146#[derive(Debug, Clone)]
147pub enum PipelineAffinity {
148    /// The key affects all pipelines / ADP behaviour as a whole.
149    CrossCutting,
150    /// The key affects the listed pipelines (non-empty, in declaration order).
151    Pipelines(Vec<Pipeline>),
152}
153
154impl<'de> serde::Deserialize<'de> for PipelineAffinity {
155    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
156        #[derive(Deserialize, PartialEq)]
157        #[serde(rename_all = "snake_case")]
158        enum Token {
159            CrossCutting,
160            #[serde(rename = "dogstatsd")]
161            DogStatsD,
162            Checks,
163            Otlp,
164            Traces,
165            Logs,
166        }
167
168        let tokens: Vec<Token> = Vec::deserialize(d)?;
169
170        if tokens.is_empty() {
171            return Err(serde::de::Error::custom("pipelines must be non-empty"));
172        }
173
174        let has_cc = tokens.iter().any(|t| t == &Token::CrossCutting);
175
176        if has_cc && tokens.len() > 1 {
177            return Err(serde::de::Error::custom(
178                "cross_cutting must appear alone in pipelines list",
179            ));
180        }
181
182        if has_cc {
183            return Ok(PipelineAffinity::CrossCutting);
184        }
185
186        let pipelines = tokens
187            .into_iter()
188            .map(|t| match t {
189                Token::DogStatsD => Pipeline::DogStatsD,
190                Token::Checks => Pipeline::Checks,
191                Token::Otlp => Pipeline::Otlp,
192                Token::Traces => Pipeline::Traces,
193                Token::Logs => Pipeline::Logs,
194                Token::CrossCutting => unreachable!(),
195            })
196            .collect();
197
198        Ok(PipelineAffinity::Pipelines(pipelines))
199    }
200}
201
202/// Paths to the core schema, OTel schema directory, and overlay.
203///
204/// Defaults to their locations in the sibling `config` crate.
205pub struct Files {
206    /// The Datadog Agent core schema file (`schema/core/core_schema.yaml`).
207    pub datadog_schema: PathBuf,
208    /// Directory containing the vendored OTel receiver schema (`schema/otel/`).
209    pub otel_schema_dir: PathBuf,
210    /// The schema overlay (`schema/schema_overlay.yaml`).
211    pub overlay: PathBuf,
212}
213
214impl Default for Files {
215    fn default() -> Self {
216        let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
217            .join("..")
218            .join("config")
219            .join("schema");
220        Files {
221            datadog_schema: dir.join("core").join("core_schema.yaml"),
222            otel_schema_dir: dir.join("otel"),
223            overlay: dir.join("schema_overlay.yaml"),
224        }
225    }
226}
227
228/// A top-level overlay section as seen by [`SchemaOverlay::lint_yaml`]: only the key order of
229/// mapping sections matters, so values are skipped.
230#[derive(Deserialize)]
231#[serde(untagged)]
232enum LintSection {
233    Mapping(IndexMap<String, serde::de::IgnoredAny>),
234    Other(#[allow(dead_code)] serde::de::IgnoredAny),
235}
236
237impl SchemaOverlay {
238    pub fn load(files: Files) -> Result<Self, Error> {
239        let loaded = Self::from_file(&files.overlay)?;
240        loaded.validate(&files.datadog_schema, &files.otel_schema_dir)?;
241        Ok(loaded)
242    }
243
244    fn from_yaml(s: &str) -> Result<Self, Error> {
245        // Linting needs the keys in file order, so parse into insertion-ordered maps first.
246        let sections: IndexMap<String, LintSection> = serde_saphyr::from_str(s).map_err(Error::Yaml)?;
247        Self::lint_yaml(&sections)?;
248        serde_saphyr::from_str(s).map_err(Error::Yaml)
249    }
250
251    fn from_file(path: &Path) -> Result<Self, Error> {
252        let contents = std::fs::read_to_string(path).map_err(|e| Error::Io((path.into(), e)))?;
253        Self::from_yaml(&contents)
254    }
255
256    fn validate(&self, datadog_schema: &Path, otel_schema_dir: &Path) -> Result<(), Error> {
257        self.validate_keys_match(datadog_schema, otel_schema_dir)?;
258        self.validate_entries()?;
259        Ok(())
260    }
261
262    /// Ensure that sections appear in the required order and that keys within each section are
263    /// sorted alphabetically.
264    fn lint_yaml(sections: &IndexMap<String, LintSection>) -> Result<(), Error> {
265        let section_names: Vec<&str> = sections.keys().map(String::as_str).collect();
266
267        for required in ["inventory", "excluded"] {
268            if !section_names.contains(&required) {
269                return Err(Error::Validation(format!(
270                    "overlay missing required section '{}'",
271                    required
272                )));
273            }
274        }
275
276        let pos_known = section_names.iter().position(|&k| k == "inventory").unwrap();
277        let pos_ignored = section_names.iter().position(|&k| k == "excluded").unwrap();
278
279        if pos_known >= pos_ignored {
280            return Err(Error::Validation(
281                "sections must appear in order: known, ignored".to_string(),
282            ));
283        }
284
285        for section_name in ["inventory", "excluded"] {
286            if let Some(LintSection::Mapping(section)) = sections.get(section_name) {
287                let mut prev = "";
288                for key in section.keys().map(String::as_str) {
289                    if key < prev {
290                        return Err(Error::Validation(format!(
291                            "{}: key '{}' is out of alphabetical order (after '{}')",
292                            section_name, key, prev
293                        )));
294                    }
295                    prev = key;
296                }
297            }
298        }
299
300        Ok(())
301    }
302
303    /// Ensure that each core schema key appears exactly once across the overlay sections.
304    fn validate_keys_match(&self, datadog_schema: &Path, otel_schema_dir: &Path) -> Result<(), Error> {
305        let schema_keys = Self::schema_keys(datadog_schema, otel_schema_dir)?;
306
307        for key in self.excluded.keys() {
308            if self.inventory.contains_key(key.as_str()) {
309                return Err(Error::Validation(format!(
310                    "key '{}' appears in more than one overlay section",
311                    key
312                )));
313            }
314        }
315
316        for key in self.inventory.keys().chain(self.excluded.keys()) {
317            if !schema_keys.contains(key.as_str()) {
318                return Err(Error::Validation(format!(
319                    "overlay key '{}' is not present in the schema",
320                    key
321                )));
322            }
323        }
324
325        let overlay_keys: HashSet<&str> = self
326            .inventory
327            .keys()
328            .chain(self.excluded.keys())
329            .map(|s| s.as_str())
330            .collect();
331        for key in &schema_keys {
332            if !overlay_keys.contains(key.as_str()) {
333                return Err(Error::Validation(format!(
334                    "schema key '{}' is not covered by the overlay",
335                    key
336                )));
337            }
338        }
339
340        Ok(())
341    }
342
343    fn schema_keys(datadog_schema: &Path, otel_schema_dir: &Path) -> Result<HashSet<String>, Error> {
344        let schema = load_composed_schema(datadog_schema, otel_schema_dir)?;
345        let props = schema
346            .get("properties")
347            .and_then(|v| v.as_object())
348            .ok_or_else(|| Error::Validation("schema missing 'properties' section".to_string()))?;
349        let mut keys = HashSet::new();
350        Self::collect_schema_keys(props, "", &mut keys);
351        Ok(keys)
352    }
353
354    fn collect_schema_keys(props: &Map<String, Value>, prefix: &str, keys: &mut HashSet<String>) {
355        for (name, v) in props {
356            let full_key = if prefix.is_empty() {
357                name.to_string()
358            } else {
359                format!("{}.{}", prefix, name)
360            };
361            // `$ref`s have already been inlined by `load_resolved_schema`, so a node either
362            // carries `properties` (recurse) or is a leaf key. A `setting` is a leaf even when it
363            // describes its object value with `properties`, such as `logs_config.tag_filters`.
364            let is_setting = v.get("node_type").and_then(|t| t.as_str()) == Some("setting");
365            if let Some(sub_props) = v.get("properties").and_then(|p| p.as_object()).filter(|_| !is_setting) {
366                Self::collect_schema_keys(sub_props, &full_key, keys);
367            } else {
368                keys.insert(full_key);
369            }
370        }
371    }
372
373    /// Checks description lengths and requires an issue for planned support.
374    fn validate_entries(&self) -> Result<(), Error> {
375        for (key, entry) in &self.inventory {
376            match entry {
377                KnownEntry::Full(f) => {
378                    if f.description.len() > 50 {
379                        return Err(Error::Validation(format!(
380                            "full key '{}': description exceeds 50 chars ({} chars)",
381                            key,
382                            f.description.len()
383                        )));
384                    }
385                }
386                KnownEntry::Partial(p) => {
387                    if p.description.len() > 50 {
388                        return Err(Error::Validation(format!(
389                            "partial key '{}': description exceeds 50 chars ({} chars)",
390                            key,
391                            p.description.len()
392                        )));
393                    }
394                }
395                KnownEntry::Unsupported(u) => {
396                    if u.description.len() > 50 {
397                        return Err(Error::Validation(format!(
398                            "unsupported key '{}': description exceeds 50 chars ({} chars)",
399                            key,
400                            u.description.len()
401                        )));
402                    }
403                    if u.planned && u.issue.is_none() {
404                        return Err(Error::Validation(format!(
405                            "unsupported key '{}': planned requires an issue",
406                            key
407                        )));
408                    }
409                }
410                KnownEntry::Unknown(u) => {
411                    if let Some(desc) = &u.description {
412                        if desc.len() > 50 {
413                            return Err(Error::Validation(format!(
414                                "unknown key '{}': description exceeds 50 chars ({} chars)",
415                                key,
416                                desc.len()
417                            )));
418                        }
419                    }
420                }
421            }
422        }
423        Ok(())
424    }
425}
426
427/// Read a YAML file into a [`Value`], mapping failures onto [`Error`].
428fn read_yaml(path: &Path) -> Result<Value, Error> {
429    let contents = std::fs::read_to_string(path).map_err(|e| Error::Io((path.into(), e)))?;
430    serde_saphyr::from_str(&contents).map_err(Error::Yaml)
431}
432
433/// Load the core schema and recursively inline every `$ref: <file>` reference into a single
434/// resolved document with no remaining `$ref` nodes.
435///
436/// Referenced files are resolved relative to the directory containing `schema_path`. This is the
437/// one place that reads subsystem schema files; downstream consumers traverse the returned tree
438/// and never handle `$ref` themselves. Build-time only.
439///
440/// # Errors
441///
442/// Returns [`Error::Io`] if `schema_path` or any referenced file cannot be read, and
443/// [`Error::Yaml`] if any file fails to parse. The offending path is carried in the error.
444pub fn load_resolved_schema(schema_path: &Path) -> Result<Value, Error> {
445    let schema_dir = schema_path.parent().unwrap_or_else(|| Path::new("."));
446    let mut doc = read_yaml(schema_path)?;
447    resolve_refs(&mut doc, schema_dir)?;
448    Ok(doc)
449}
450
451/// Recursively replace any mapping node containing a `$ref: <file>` entry with the (also resolved)
452/// contents of the referenced file, found relative to `schema_dir`.
453fn resolve_refs(value: &mut Value, schema_dir: &Path) -> Result<(), Error> {
454    if let Some(map) = value.as_object_mut() {
455        if let Some(ref_path) = map.get("$ref").and_then(|v| v.as_str()) {
456            let ref_file = schema_dir.join(ref_path);
457            let mut ref_doc = read_yaml(&ref_file)?;
458            resolve_refs(&mut ref_doc, schema_dir)?;
459            *value = ref_doc;
460            return Ok(());
461        }
462        for (_k, v) in map.iter_mut() {
463            resolve_refs(v, schema_dir)?;
464        }
465    }
466    Ok(())
467}
468
469/// Load the Datadog schema with the OTel receiver schema patched in.
470pub fn load_composed_schema(datadog_schema: &Path, otel_schema_dir: &Path) -> Result<Value, Error> {
471    let mut datadog_schema = load_resolved_schema(datadog_schema)?;
472    let otel_receiver = load_otel_receiver(otel_schema_dir)?;
473    patch_receiver(&mut datadog_schema, otel_receiver)?;
474    Ok(datadog_schema)
475}
476
477/// Load and completely resolve the OTel receiver schema into a Datadog compatible subtree.
478fn load_otel_receiver(otel_dir: &Path) -> Result<Value, Error> {
479    let schema_path = otel_dir.join("config.schema.yaml");
480    let doc = read_yaml(&schema_path)?;
481
482    let defs = doc
483        .get("$defs")
484        .and_then(|v| v.as_object())
485        .ok_or_else(|| Error::Validation("OTel schema missing $defs".to_string()))?
486        .clone();
487
488    // Start from properties.protocols (the root of the receiver config).
489    let mut protocols = doc
490        .get("properties")
491        .and_then(|v| v.get("protocols"))
492        .cloned()
493        .ok_or_else(|| Error::Validation("OTel schema missing properties.protocols".to_string()))?;
494
495    // Resolve all $ref, $defs, and allOf.
496    resolve_otel_refs(&mut protocols, otel_dir, &defs)?;
497
498    // Convert to Datadog schema dialect.
499    convert_to_datadog_dialect(&mut protocols);
500
501    // Tag env bindings. Only a subset is is registered and gets an explicit `env_vars` designation; the rest get `no-env`.
502    tag_otel_env_bindings(&mut protocols, &["protocols"]);
503
504    // Wrap in a "receiver" section to match the Datadog schema structure.
505    let mut receiver_section = Map::new();
506    receiver_section.insert("node_type".to_string(), Value::String("section".to_string()));
507    receiver_section.insert("type".to_string(), Value::String("object".to_string()));
508    let mut properties = Map::new();
509    properties.insert("protocols".to_string(), protocols);
510    receiver_section.insert("properties".to_string(), Value::Object(properties));
511
512    Ok(Value::Object(receiver_section))
513}
514
515/// Merge the resolved OTel receiver subtree into the Datadog schema's `otlp_config.receiver` while
516/// honoring default values not native to OTel.
517fn patch_receiver(datadog_schema: &mut Value, otel_receiver: Value) -> Result<(), Error> {
518    let Some(otlp_config) = datadog_schema
519        .get_mut("properties")
520        .and_then(|v| v.get_mut("otlp_config"))
521    else {
522        return Ok(());
523    };
524
525    let Some(receiver) = otlp_config.get_mut("properties").and_then(|v| v.get_mut("receiver")) else {
526        return Ok(());
527    };
528
529    let datadog_receiver = std::mem::take(receiver);
530    let mut merged = otel_receiver;
531    merge_receiver_node(&mut merged, &datadog_receiver);
532    *receiver = merged;
533    Ok(())
534}
535
536/// Recursively overlay Datadog-specific metadata from the core schema onto the resolved OTel node.
537fn merge_receiver_node(otel: &mut Value, datadog: &Value) {
538    let Some(otel_map) = otel.as_object_mut() else { return };
539    let Some(datadog_map) = datadog.as_object() else {
540        return;
541    };
542
543    // Overlay all Datadog metadata fields onto the OTel node, except `properties`
544    // which is merged recursively to preserve OTel's additional keys.
545    for (key, val) in datadog_map.iter() {
546        if key == "properties" {
547            continue;
548        }
549        otel_map.insert(key.clone(), val.clone());
550    }
551
552    // Recursively merge `properties` containers.
553    if let (Some(otel_props), Some(datadog_props)) = (
554        otel_map.get_mut("properties").and_then(|v| v.as_object_mut()),
555        datadog_map.get("properties").and_then(|v| v.as_object()),
556    ) {
557        // Merge overlapping OTel properties with corresponding Datadog properties.
558        let otel_keys: Vec<String> = otel_props.keys().cloned().collect();
559        for key in &otel_keys {
560            if let Some(datadog_val) = datadog_props.get(key) {
561                if let Some(otel_val) = otel_props.get_mut(key) {
562                    merge_receiver_node(otel_val, datadog_val);
563                }
564            }
565        }
566        // Add Datadog-only properties that don't exist in OTel.
567        for (key, val) in datadog_props.iter() {
568            if !otel_props.contains_key(key) {
569                otel_props.insert(key.clone(), val.clone());
570            }
571        }
572    }
573}
574
575/// Resolve OTel schema references into a flat tree.
576fn resolve_otel_refs(value: &mut Value, otel_dir: &Path, current_defs: &Map<String, Value>) -> Result<(), Error> {
577    let Some(map) = value.as_object_mut() else {
578        return Ok(());
579    };
580
581    // 1. Handle $ref: replace this node with the resolved definition.
582    if let Some(ref_str) = map.get("$ref").and_then(|v| v.as_str()) {
583        // Save sibling keys (everything except $ref): for example x-optional, description.
584        let siblings: Vec<(String, Value)> = map
585            .iter()
586            .filter(|(k, _)| *k != "$ref")
587            .map(|(k, v)| (k.clone(), v.clone()))
588            .collect();
589
590        // Resolve the ref target, getting the definition value and its source $defs.
591        let (mut resolved, source_defs) = resolve_otel_ref_target(ref_str, otel_dir, current_defs)?;
592
593        // Recursively resolve refs inside the definition using the source file's $defs.
594        resolve_otel_refs(&mut resolved, otel_dir, &source_defs)?;
595
596        // Resolve siblings using current_defs (they belong to the current file).
597        let mut resolved_siblings: Vec<(String, Value)> = Vec::new();
598        for (k, mut v) in siblings {
599            resolve_otel_refs(&mut v, otel_dir, current_defs)?;
600            resolved_siblings.push((k, v));
601        }
602
603        // Merge siblings into the resolved definition (siblings override def keys).
604        if let Some(resolved_map) = resolved.as_object_mut() {
605            for (k, v) in resolved_siblings {
606                resolved_map.insert(k, v);
607            }
608        }
609
610        *value = resolved;
611        return Ok(());
612    }
613
614    // 2. Handle allOf: merge each fragment's properties into this node.
615    if let Some(allof) = map.remove("allOf") {
616        if let Some(allof_seq) = allof.as_array() {
617            for fragment in allof_seq {
618                let mut resolved_fragment = fragment.clone();
619                resolve_otel_refs(&mut resolved_fragment, otel_dir, current_defs)?;
620
621                // Merge fragment's properties into value's properties.
622                if let Some(source_props) = resolved_fragment.get("properties").and_then(|v| v.as_object()) {
623                    if map.get("properties").is_none() {
624                        map.insert("properties".to_string(), Value::Object(Map::new()));
625                    }
626                    if let Some(target_props) = map.get_mut("properties").and_then(|v| v.as_object_mut()) {
627                        for (k, v) in source_props {
628                            target_props.insert(k.clone(), v.clone());
629                        }
630                    }
631                }
632            }
633        }
634    }
635
636    // 3. Recurse into properties, stripping auth and middlewares that reference excluded packages.
637    if let Some(props) = map.get_mut("properties").and_then(|v| v.as_object_mut()) {
638        // Strip auth/middlewares if they have a $ref (direct or via allOf/items) that
639        // transitively references configauth/configmiddleware. A plain `auth` field
640        // (like tpm_config.auth: type: string) has no $ref and must be kept.
641        if let Some(auth) = props.get("auth") {
642            let auth_str = serde_json::to_string(auth).unwrap_or_default();
643            if auth_str.contains("$ref") {
644                props.remove("auth");
645            }
646        }
647        if let Some(middlewares) = props.get("middlewares") {
648            let mw_str = serde_json::to_string(middlewares).unwrap_or_default();
649            if mw_str.contains("$ref") {
650                props.remove("middlewares");
651            }
652        }
653        for (_, v) in props.iter_mut() {
654            resolve_otel_refs(v, otel_dir, current_defs)?;
655        }
656    }
657
658    Ok(())
659}
660
661/// Resolve a single `$ref` target, returning the definition value and its source `$defs`.
662fn resolve_otel_ref_target(
663    ref_str: &str, otel_dir: &Path, current_defs: &Map<String, Value>,
664) -> Result<(Value, Map<String, Value>), Error> {
665    if let Some(stripped) = ref_str.strip_prefix('/') {
666        // Package-qualified ref: /config/`configgrpc`.server_config
667        let last_dot = stripped
668            .rfind('.')
669            .ok_or_else(|| Error::Validation(format!("invalid package-qualified ref (no dot): {ref_str}")))?;
670        let package_path = &stripped[..last_dot];
671        let def_name = &stripped[last_dot + 1..];
672
673        // Handle configopaque refs inline (not vendored).
674        if package_path == "config/configopaque" {
675            let inline = match def_name {
676                "string" => Value::Object([("type".into(), "string".into())].into_iter().collect()),
677                "map_list" => {
678                    let mut m = Map::new();
679                    m.insert("type".into(), "object".into());
680                    let mut addl = Map::new();
681                    addl.insert("type".into(), "string".into());
682                    m.insert("additionalProperties".into(), Value::Object(addl));
683                    Value::Object(m)
684                }
685                other => return Err(Error::Validation(format!("unknown configopaque ref: {other}"))),
686            };
687            return Ok((inline, Map::new()));
688        }
689
690        // Reject refs to excluded packages (should not be reached if auth/middlewares are stripped).
691        if package_path == "config/configauth" || package_path == "config/configmiddleware" {
692            return Err(Error::Validation(format!(
693                "unexpected ref to excluded package: {ref_str}"
694            )));
695        }
696
697        // Load the package's schema file.
698        let file_path = otel_dir.join(package_path).join("config.schema.yaml");
699        let file_doc = read_yaml(&file_path)?;
700        let file_defs = file_doc
701            .get("$defs")
702            .and_then(|v| v.as_object())
703            .ok_or_else(|| Error::Validation(format!("OTel schema {file_path:?} missing $defs")))?
704            .clone();
705        let def_value = file_defs
706            .get(def_name)
707            .cloned()
708            .ok_or_else(|| Error::Validation(format!("$defs.{def_name} not found in {file_path:?}")))?;
709
710        Ok((def_value, file_defs))
711    } else {
712        // Local ref: protocols, http_config, sanitized_url_path, etc.
713        let def_value = current_defs
714            .get(ref_str)
715            .cloned()
716            .ok_or_else(|| Error::Validation(format!("local $def {ref_str} not found")))?;
717        Ok((def_value, current_defs.clone()))
718    }
719}
720
721/// Convert an OTel schema tree to the Datadog compatible schema dialect.
722fn convert_to_datadog_dialect(value: &mut Value) {
723    let Some(map) = value.as_object_mut() else {
724        return;
725    };
726
727    // Remove OTel-specific extensions.
728    map.remove("x-optional");
729    map.remove("x-customType");
730
731    // Determine if this is a section (has properties) or a setting (leaf).
732    let is_section = map.get("properties").is_some();
733    let node_type = if is_section { "section" } else { "setting" };
734
735    // Add node_type if not present.
736    if map.get("node_type").is_none() {
737        map.insert("node_type".to_string(), Value::String(node_type.to_string()));
738    }
739
740    // Recurse into properties.
741    if let Some(props) = map.get_mut("properties").and_then(|v| v.as_object_mut()) {
742        for (_, v) in props.iter_mut() {
743            convert_to_datadog_dialect(v);
744        }
745    }
746}
747
748/// List of env-reachable `otlp_config.receiver` keys
749const ENV_REGISTERED_OTEL_KEYS: &[&str] = &[
750    "otlp_config.receiver.protocols.grpc.endpoint",
751    "otlp_config.receiver.protocols.grpc.transport",
752    "otlp_config.receiver.protocols.grpc.max_recv_msg_size_mib",
753    "otlp_config.receiver.protocols.grpc.max_concurrent_streams",
754    "otlp_config.receiver.protocols.grpc.read_buffer_size",
755    "otlp_config.receiver.protocols.grpc.write_buffer_size",
756    "otlp_config.receiver.protocols.grpc.include_metadata",
757    "otlp_config.receiver.protocols.grpc.keepalive.enforcement_policy.min_time",
758    "otlp_config.receiver.protocols.http.endpoint",
759    "otlp_config.receiver.protocols.http.max_request_body_size",
760    "otlp_config.receiver.protocols.http.include_metadata",
761    "otlp_config.receiver.protocols.http.cors.allowed_headers",
762    "otlp_config.receiver.protocols.http.cors.allowed_origins",
763];
764
765/// Walks the OTel receiver subtree and tags each setting with `env_vars` or `no-env`.
766fn tag_otel_env_bindings(value: &mut Value, path_parts: &[&str]) {
767    let Some(map) = value.as_object_mut() else { return };
768
769    if map.get("node_type").and_then(|v| v.as_str()) == Some("setting") {
770        let full_path = format!("otlp_config.receiver.{}", path_parts.join("."));
771        if ENV_REGISTERED_OTEL_KEYS.contains(&full_path.as_str()) {
772            let env_var = format!("DD_{}", full_path.replace('.', "_").to_uppercase());
773            let env_vars = Value::Array(vec![Value::String(env_var)]);
774            map.insert("env_vars".to_string(), env_vars);
775        } else {
776            let mut tags = map.get("tags").and_then(|v| v.as_array().cloned()).unwrap_or_default();
777            if !tags.iter().any(|t| t.as_str() == Some("no-env")) {
778                tags.push(Value::String("no-env".to_string()));
779            }
780            map.insert("tags".to_string(), Value::Array(tags));
781        }
782        return;
783    }
784
785    if let Some(props) = map.get_mut("properties").and_then(|v| v.as_object_mut()) {
786        for (key, val) in props.iter_mut() {
787            let mut parts = path_parts.to_vec();
788            parts.push(key);
789            tag_otel_env_bindings(val, &parts);
790        }
791    }
792}
793
794const VALIDATION_RULES: &str = "\n\
795    \n\
796    Rules that must hold in schema_overlay.yaml:\n\
797    - Every core_schema.yaml key appears in exactly one section (known / ignored).\n\
798    - No key appears in more than one section.\n\
799    - Sections appear in order: known, ignored.\n\
800    - Keys within each section are sorted alphabetically.\n\
801    - full entries: pipelines non-empty, description <= 50 chars.\n\
802    - partial entries: pipelines non-empty, description <= 50 chars, documentation required.\n\
803    - unsupported entries: pipelines non-empty, description <= 50 chars, planned+issue consistent.\n\
804    - unknown entries: description <= 50 chars (when present).\n\
805    Fix: edit lib/datadog-agent/config/schema/schema_overlay.yaml.";
806
807/// Errors that can occur when loading a schema overlay.
808#[derive(Debug)]
809pub enum Error {
810    Io((PathBuf, std::io::Error)),
811    Yaml(serde_saphyr::Error),
812    Validation(String),
813}
814
815impl std::fmt::Display for Error {
816    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
817        match self {
818            Error::Io(e) => write!(f, "Error reading {}: {}", e.0.display(), e.1),
819            Error::Yaml(e) => write!(f, "YAML parse error in overlay: {e}"),
820            Error::Validation(s) => write!(f, "schema_overlay.yaml validation failed: {s}{VALIDATION_RULES}"),
821        }
822    }
823}
824
825impl std::error::Error for Error {
826    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
827        match self {
828            Error::Io(e) => Some(&e.1),
829            Error::Yaml(e) => Some(e),
830            Error::Validation(_) => None,
831        }
832    }
833}
834
835#[cfg(test)]
836mod tests {
837    use super::*;
838
839    /// Returns the OTel schema directory for tests that need the composed schema.
840    fn otel_schema_dir_for_tests() -> PathBuf {
841        Path::new(env!("CARGO_MANIFEST_DIR"))
842            .join("..")
843            .join("config")
844            .join("schema")
845            .join("otel")
846    }
847
848    #[test]
849    fn overlay_loads() {
850        let test_files = Files {
851            datadog_schema: Path::new(env!("CARGO_MANIFEST_DIR"))
852                .join("test")
853                .join("fake_schema.yaml"),
854            otel_schema_dir: otel_schema_dir_for_tests(),
855            overlay: Path::new(env!("CARGO_MANIFEST_DIR"))
856                .join("test")
857                .join("fake_overlay.yaml"),
858        };
859        let validated = SchemaOverlay::load(test_files).unwrap();
860        assert_eq!(validated.inventory.len(), 18);
861    }
862
863    #[test]
864    fn pipeline_affinity_cross_cutting() {
865        let yaml = "pipelines: [cross_cutting]";
866        #[derive(Deserialize)]
867        struct W {
868            pipelines: PipelineAffinity,
869        }
870        let w: W = serde_saphyr::from_str(yaml).unwrap();
871        assert!(matches!(w.pipelines, PipelineAffinity::CrossCutting));
872    }
873
874    #[test]
875    fn pipeline_affinity_multi() {
876        let yaml = "pipelines: [dogstatsd, traces]";
877        #[derive(Deserialize)]
878        struct W {
879            pipelines: PipelineAffinity,
880        }
881        let w: W = serde_saphyr::from_str(yaml).unwrap();
882        if let PipelineAffinity::Pipelines(ps) = w.pipelines {
883            assert_eq!(ps.len(), 2);
884            assert!(matches!(ps[0], Pipeline::DogStatsD));
885            assert!(matches!(ps[1], Pipeline::Traces));
886        } else {
887            panic!("expected Pipelines");
888        }
889    }
890
891    #[test]
892    fn pipeline_affinity_cross_cutting_must_be_alone() {
893        let yaml = "pipelines: [cross_cutting, dogstatsd]";
894        #[derive(Deserialize)]
895        #[allow(dead_code)]
896        struct W {
897            pipelines: PipelineAffinity,
898        }
899        assert!(serde_saphyr::from_str::<W>(yaml).is_err());
900    }
901
902    fn load_from_strs(schema: &str, overlay: &str) -> Result<SchemaOverlay, Error> {
903        let dir = tempfile::tempdir().unwrap();
904        let schema_path = dir.path().join("fake_schema.yaml");
905        let overlay_path = dir.path().join("overlay.yaml");
906        std::fs::write(&schema_path, schema).unwrap();
907        std::fs::write(&overlay_path, overlay).unwrap();
908        let otel_schema_dir = otel_schema_dir_for_tests();
909        SchemaOverlay::load(Files {
910            datadog_schema: schema_path,
911            otel_schema_dir,
912            overlay: overlay_path,
913        })
914    }
915
916    #[test]
917    fn validation_rejects_schema_key_missing_from_overlay() {
918        let schema = "\
919properties:
920  key_a:
921    type: string
922  key_b:
923    type: string
924";
925        let overlay = "\
926inventory:
927  key_a:
928    support: full
929    pipelines: [cross_cutting]
930    description: \"Key A\"
931excluded: {}
932";
933        let err = load_from_strs(schema, overlay).unwrap_err();
934        assert!(
935            err.to_string().contains("schema key 'key_b' is not covered"),
936            "unexpected error: {err}"
937        );
938    }
939
940    #[test]
941    fn validation_rejects_overlay_key_absent_from_schema() {
942        let schema = "\
943properties:
944  key_a:
945    type: string
946";
947        let overlay = "\
948inventory:
949  key_a:
950    support: full
951    pipelines: [cross_cutting]
952    description: \"Key A\"
953excluded:
954  key_b: \"not in schema\"
955";
956        let err = load_from_strs(schema, overlay).unwrap_err();
957        assert!(
958            err.to_string().contains("overlay key 'key_b' is not present"),
959            "unexpected error: {err}"
960        );
961    }
962
963    #[test]
964    fn a_setting_described_with_properties_is_one_schema_key() {
965        let props = serde_json::json!({
966            "a": {
967                "node_type": "section",
968                "properties": {
969                    "b": {"node_type": "setting", "type": "string"},
970                    "c": {
971                        "node_type": "setting",
972                        "type": "object",
973                        "properties": {"include": {"type": "array"}, "exclude": {"type": "array"}},
974                    },
975                },
976            },
977        });
978        let mut keys = HashSet::new();
979
980        SchemaOverlay::collect_schema_keys(props.as_object().unwrap(), "", &mut keys);
981
982        assert_eq!(keys, HashSet::from(["a.b".to_string(), "a.c".to_string()]));
983    }
984
985    #[test]
986    fn validation_rejects_an_overlay_key_inside_a_setting() {
987        let schema = "\
988properties:
989  filters:
990    node_type: setting
991    type: object
992    properties:
993      include:
994        type: array
995";
996        let overlay = "\
997inventory:
998  filters:
999    support: full
1000    pipelines: [cross_cutting]
1001    description: \"Filters\"
1002excluded:
1003  filters.include: \"part of a setting\"
1004";
1005        let err = load_from_strs(schema, overlay).unwrap_err();
1006        assert!(
1007            err.to_string().contains("overlay key 'filters.include' is not present"),
1008            "unexpected error: {err}"
1009        );
1010    }
1011
1012    #[test]
1013    fn validation_rejects_key_in_two_sections() {
1014        let schema = "\
1015properties:
1016  key_a:
1017    type: string
1018  key_b:
1019    type: string
1020";
1021        let overlay = "\
1022inventory:
1023  key_a:
1024    support: full
1025    pipelines: [cross_cutting]
1026    description: \"Key A\"
1027excluded:
1028  key_a: \"duplicate\"
1029  key_b: \"ok\"
1030";
1031        let err = load_from_strs(schema, overlay).unwrap_err();
1032        assert!(
1033            err.to_string()
1034                .contains("key 'key_a' appears in more than one overlay section"),
1035            "unexpected error: {err}"
1036        );
1037    }
1038
1039    /// A `$ref` is inlined and its leaf keys are namespaced under the parent key.
1040    #[test]
1041    fn schema_ref_is_resolved_and_keys_namespaced() {
1042        let dir = tempfile::tempdir().unwrap();
1043        std::fs::write(
1044            dir.path().join("sub.yaml"),
1045            "properties:\n  enabled:\n    type: boolean\n",
1046        )
1047        .unwrap();
1048        let schema_path = dir.path().join("core_schema.yaml");
1049        std::fs::write(&schema_path, "properties:\n  feature:\n    $ref: sub.yaml\n").unwrap();
1050
1051        let keys = SchemaOverlay::schema_keys(&schema_path, &otel_schema_dir_for_tests()).unwrap();
1052        assert_eq!(
1053            keys,
1054            HashSet::from(["feature.enabled".to_string()]),
1055            "unexpected keys: {keys:?}"
1056        );
1057    }
1058
1059    /// A missing `$ref` target surfaces a clear I/O error naming the file, not a misleading
1060    /// "key not covered" validation error.
1061    #[test]
1062    fn missing_schema_ref_reports_io_error() {
1063        let dir = tempfile::tempdir().unwrap();
1064        let schema_path = dir.path().join("core_schema.yaml");
1065        std::fs::write(&schema_path, "properties:\n  feature:\n    $ref: does_not_exist.yaml\n").unwrap();
1066
1067        let err = SchemaOverlay::schema_keys(&schema_path, &otel_schema_dir_for_tests()).unwrap_err();
1068        assert!(matches!(err, Error::Io(_)), "expected Io error, got: {err}");
1069        assert!(
1070            err.to_string().contains("does_not_exist.yaml"),
1071            "error should name the missing file: {err}"
1072        );
1073    }
1074
1075    #[test]
1076    fn validation_rejects_unsorted_inventory_keys() {
1077        let schema = "\
1078properties:
1079  key_a:
1080    type: string
1081  key_b:
1082    type: string
1083";
1084        let overlay = "\
1085inventory:
1086  key_b:
1087    support: full
1088    pipelines: [cross_cutting]
1089    description: \"Key B\"
1090  key_a:
1091    support: full
1092    pipelines: [cross_cutting]
1093    description: \"Key A\"
1094excluded: {}
1095";
1096        let err = load_from_strs(schema, overlay).unwrap_err();
1097        assert!(
1098            err.to_string().contains("out of alphabetical order"),
1099            "unexpected error: {err}"
1100        );
1101    }
1102
1103    // The per-entry validation rules (`validate_entries`) are documented in `VALIDATION_RULES` and
1104    // enforced independently of the schema cross-check, so these tests deserialize an overlay in
1105    // isolation (via `from_yaml`) and run only that pass: no matching core schema is needed.
1106    fn validate_entries_of(overlay: &str) -> Result<(), Error> {
1107        SchemaOverlay::from_yaml(overlay)
1108            .expect("overlay should deserialize")
1109            .validate_entries()
1110    }
1111
1112    #[test]
1113    fn deserialization_rejects_unknown_fields() {
1114        let cases: &[(&str, &str)] = &[
1115            (
1116                "full",
1117                "inventory:\n  key_a:\n    support: full\n    pipelines: [dogstatsd]\n    description: \"A\"\n    \
1118                 misspelled_field: true\nexcluded: {}\n",
1119            ),
1120            (
1121                "partial",
1122                "inventory:\n  key_a:\n    support: partial\n    pipelines: [dogstatsd]\n    description: \"A\"\n    \
1123                 documentation: \"diverges\"\n    misspelled_field: true\nexcluded: {}\n",
1124            ),
1125            (
1126                "unsupported",
1127                "inventory:\n  key_a:\n    support: none\n    pipelines: [dogstatsd]\n    description: \"A\"\n    \
1128                 severity: low\n    planned: false\n    misspelled_field: true\nexcluded: {}\n",
1129            ),
1130            (
1131                "unknown",
1132                "inventory:\n  key_a:\n    support: unknown\n    misspelled_field: true\nexcluded: {}\n",
1133            ),
1134            ("top level", "inventory: {}\nexcluded: {}\nignored: {}\n"),
1135        ];
1136
1137        for (kind, overlay) in cases {
1138            let err =
1139                SchemaOverlay::from_yaml(overlay).expect_err(&format!("{kind}: unknown field should be rejected"));
1140            assert!(
1141                err.to_string().contains("unknown field"),
1142                "{kind}: unexpected error: {err}"
1143            );
1144        }
1145    }
1146
1147    #[test]
1148    fn per_entry_validation_accepts_a_well_formed_entry_of_every_kind() {
1149        let overlay = "\
1150inventory:
1151  full_key:
1152    support: full
1153    pipelines: [dogstatsd]
1154    description: \"Fully supported key\"
1155  partial_key:
1156    support: partial
1157    pipelines: [traces]
1158    description: \"Partially supported key\"
1159    documentation: \"Behaves differently from the core agent.\"
1160  unknown_key:
1161    support: unknown
1162    description: \"Not yet classified\"
1163  unsupported_key:
1164    support: none
1165    pipelines: [checks]
1166    description: \"Unsupported key\"
1167    severity: high
1168    planned: true
1169    issue: \"1234\"
1170excluded: {}
1171";
1172        validate_entries_of(overlay).expect("a well-formed overlay should pass per-entry validation");
1173    }
1174
1175    #[test]
1176    fn per_entry_validation_rejects_over_long_description_for_every_entry_kind() {
1177        let long = "x".repeat(60);
1178        let cases: &[(&str, String)] = &[
1179            (
1180                "full",
1181                format!(
1182                    "inventory:\n  key_a:\n    support: full\n    pipelines: [dogstatsd]\n    \
1183                     description: \"{long}\"\nexcluded: {{}}\n"
1184                ),
1185            ),
1186            (
1187                "partial",
1188                format!(
1189                    "inventory:\n  key_a:\n    support: partial\n    pipelines: [dogstatsd]\n    \
1190                     description: \"{long}\"\n    documentation: \"diverges\"\nexcluded: {{}}\n"
1191                ),
1192            ),
1193            (
1194                "unsupported",
1195                format!(
1196                    "inventory:\n  key_a:\n    support: none\n    pipelines: [dogstatsd]\n    \
1197                     description: \"{long}\"\n    severity: low\n    planned: false\nexcluded: {{}}\n"
1198                ),
1199            ),
1200            (
1201                "unknown",
1202                format!("inventory:\n  key_a:\n    support: unknown\n    description: \"{long}\"\nexcluded: {{}}\n"),
1203            ),
1204        ];
1205
1206        for (kind, overlay) in cases {
1207            let err = validate_entries_of(overlay).expect_err(&format!("{kind} entry should be rejected"));
1208            assert!(
1209                err.to_string().contains("description exceeds 50 chars"),
1210                "{kind}: unexpected error: {err}"
1211            );
1212        }
1213    }
1214
1215    #[test]
1216    fn per_entry_validation_rejects_planned_unsupported_entry_without_issue() {
1217        let overlay = "\
1218inventory:
1219  key_a:
1220    support: none
1221    pipelines: [dogstatsd]
1222    description: \"Key A\"
1223    severity: medium
1224    planned: true
1225excluded: {}
1226";
1227        let err = validate_entries_of(overlay).expect_err("planned unsupported entry without issue should be rejected");
1228        assert!(
1229            err.to_string()
1230                .contains("unsupported key 'key_a': planned requires an issue"),
1231            "unexpected error: {err}"
1232        );
1233    }
1234
1235    #[test]
1236    fn verify_otel_receiver_env_bindings() {
1237        let schema_path = Path::new(env!("CARGO_MANIFEST_DIR"))
1238            .join("..")
1239            .join("config")
1240            .join("schema")
1241            .join("core")
1242            .join("core_schema.yaml");
1243        let otel_schema_dir = otel_schema_dir_for_tests();
1244        let schema_map = crate::schema_gen::load_schema(&schema_path, &otel_schema_dir);
1245
1246        let registered: HashSet<&str> = super::ENV_REGISTERED_OTEL_KEYS.iter().copied().collect();
1247
1248        for (key, info) in &schema_map {
1249            if !key.starts_with("otlp_config.receiver.protocols.") {
1250                continue;
1251            }
1252            if registered.contains(key.as_str()) {
1253                assert!(
1254                    matches!(info.env, crate::schema_gen::EnvBinding::Overridden(_)),
1255                    "registered key `{key}` should have explicit env_vars"
1256                );
1257            } else {
1258                assert!(
1259                    matches!(info.env, crate::schema_gen::EnvBinding::None),
1260                    "unregistered key `{key}` should be no-env"
1261                );
1262            }
1263        }
1264    }
1265}