Skip to main content

datadog_agent_config_corpus/
getter.rs

1//! Decodes recorded Agent configuration method results into Rust values for compatibility tests.
2//!
3//! A **getter** is an Agent method that reads a setting, such as `GetInt` or `GetStringMap`.
4//! The Go config recorder calls these methods and saves their results alongside the values the
5//! Agent streams to ADP. The two can differ because getters convert stored values to Go types.
6//!
7//! The corpus reader passes each saved result and method name to [`decode`]. This module checks
8//! the result against that method's return type: `GetInt` must hold an integer, for example, and
9//! `GetStringSlice` must hold strings or a nil slice. It decodes the result; it does not call Go
10//! or reproduce the getter's conversions.
11//!
12//! [`GetterResult`] preserves nil versus empty collections and integers versus floats. [`Number`]
13//! also keeps the original JSON number text so a test need not rely on a rounded parsed value.
14//! The method types and encodings are defined in `config-recorder/docs/getter-map.md`.
15
16use std::collections::BTreeMap;
17
18use crate::json::Json;
19use crate::lists::Getter;
20
21/// A number and the exact token the corpus wrote for it.
22#[derive(Clone, Debug, PartialEq)]
23pub struct Number<T> {
24    /// The parsed value.
25    pub value: T,
26    /// The token as written.
27    pub token: String,
28}
29
30/// A Go `float64`: a float token, or one of the non-finite forms `{"$float":...}`.
31#[derive(Clone, Debug, PartialEq)]
32pub enum GoFloat {
33    /// A finite float, written with `.`, `e` or `E`.
34    Finite(Number<f64>),
35    /// `{"$float":"NaN"}`.
36    NaN,
37    /// `{"$float":"+Inf"}`.
38    PosInf,
39    /// `{"$float":"-Inf"}`.
40    NegInf,
41}
42
43/// A generic Go value, as `Get` and `GetStringMap` return it.
44#[derive(Clone, Debug, PartialEq)]
45pub enum GoValue {
46    /// `nil`, or a nil slice or map.
47    Null,
48    /// A `bool`.
49    Bool(bool),
50    /// Any Go integer type; `i128` holds every `int64` and `uint64`.
51    Int(Number<i128>),
52    /// A `float32` or `float64`.
53    Float(GoFloat),
54    /// A `string`.
55    String(String),
56    /// A slice or array.
57    List(Vec<GoValue>),
58    /// A map, keys in byte order.
59    Map(BTreeMap<String, GoValue>),
60}
61
62/// The recorded return value of an Agent configuration method, decoded into the matching Rust type.
63#[derive(Clone, Debug, PartialEq)]
64pub enum GetterResult {
65    /// `GetBool`.
66    Bool(bool),
67    /// `GetString`.
68    String(String),
69    /// `GetInt` and `GetInt64`.
70    Int(Number<i64>),
71    /// `GetInt32`.
72    Int32(Number<i32>),
73    /// `GetSizeInBytes`.
74    SizeInBytes(Number<u64>),
75    /// `GetDuration`, in nanoseconds.
76    Duration(Number<i64>),
77    /// `GetFloat64`.
78    Float64(GoFloat),
79    /// `GetFloat64Slice`; `None` for a nil slice.
80    Float64Slice(Option<Vec<GoFloat>>),
81    /// `GetStringSlice`; `None` for a nil slice.
82    StringSlice(Option<Vec<String>>),
83    /// `GetStringMap`; `None` for a nil map.
84    StringMap(Option<BTreeMap<String, GoValue>>),
85    /// `GetStringMapString`; `None` for a nil map.
86    StringMapString(Option<BTreeMap<String, String>>),
87    /// `GetStringMapStringSlice`, which never returns a nil map; a `None` value is a nil slice.
88    StringMapStringSlice(BTreeMap<String, Option<Vec<String>>>),
89    /// `Get`.
90    Get(GoValue),
91    /// `ReadConfigSection` (getter-map.md §2.1): the nested section map, never `null`.
92    Section(BTreeMap<String, GoValue>),
93    /// `IsConfigured` (getter-map.md §2.1): whether the user set the key.
94    IsConfigured(bool),
95}
96
97type R<T> = Result<T, String>;
98
99fn is_float_token(n: &str) -> bool {
100    n.contains(['.', 'e', 'E'])
101}
102
103fn integer<T: std::str::FromStr>(v: &Json, what: &str) -> R<Number<T>> {
104    match v {
105        Json::Num(n) if !is_float_token(n) => n
106            .parse()
107            .map(|value| Number {
108                value,
109                token: n.clone(),
110            })
111            .map_err(|_| format!("{what}: integer {n} is out of range")),
112        other => Err(format!("{what}: expected an integer token, found {}", describe(other))),
113    }
114}
115
116fn describe(v: &Json) -> String {
117    match v {
118        Json::Num(n) => format!("number {n}"),
119        other => other.kind().to_string(),
120    }
121}
122
123/// The non-finite form, if `m` is an object whose only member is `$float`.
124fn non_finite(m: &[(crate::json::JStr, Json)]) -> Option<R<GoFloat>> {
125    let [(k, v)] = m else { return None };
126    if k.text != "$float" {
127        return None;
128    }
129    Some(match v.as_str() {
130        Some("NaN") => Ok(GoFloat::NaN),
131        Some("+Inf") => Ok(GoFloat::PosInf),
132        Some("-Inf") => Ok(GoFloat::NegInf),
133        _ => Err("a map whose only key is \"$float\" must be NaN, +Inf or -Inf".into()),
134    })
135}
136
137fn float(v: &Json, what: &str) -> R<GoFloat> {
138    match v {
139        Json::Num(n) if is_float_token(n) => {
140            let value: f64 = n.parse().map_err(|_| format!("{what}: bad float {n}"))?;
141            if !value.is_finite() {
142                return Err(format!("{what}: float {n} is out of range"));
143            }
144            Ok(GoFloat::Finite(Number {
145                value,
146                token: n.clone(),
147            }))
148        }
149        Json::Obj(m) => non_finite(m).unwrap_or_else(|| Err(format!("{what}: expected a float, found object"))),
150        other => Err(format!(
151            "{what}: expected a float token (with '.', 'e' or 'E'), found {}",
152            describe(other)
153        )),
154    }
155}
156
157fn string(v: &Json, what: &str) -> R<String> {
158    v.as_str()
159        .map(str::to_string)
160        .ok_or_else(|| format!("{what}: expected a string, found {}", describe(v)))
161}
162
163fn nullable<T>(v: &Json, f: impl FnOnce(&Json) -> R<T>) -> R<Option<T>> {
164    match v {
165        Json::Null => Ok(None),
166        v => f(v).map(Some),
167    }
168}
169
170fn list<T>(v: &Json, what: &str, f: impl Fn(&Json) -> R<T>) -> R<Vec<T>> {
171    match v {
172        Json::Arr(a) => a.iter().map(f).collect(),
173        other => Err(format!("{what}: expected an array, found {}", describe(other))),
174    }
175}
176
177fn map<T>(v: &Json, what: &str, f: impl Fn(&Json) -> R<T>) -> R<BTreeMap<String, T>> {
178    match v {
179        Json::Obj(m) => {
180            if non_finite(m).is_some() {
181                return Err(format!("{what}: a map whose only key is \"$float\" is not a map"));
182            }
183            m.iter().map(|(k, x)| Ok((k.text.clone(), f(x)?))).collect()
184        }
185        other => Err(format!("{what}: expected an object, found {}", describe(other))),
186    }
187}
188
189fn go_value(v: &Json) -> R<GoValue> {
190    Ok(match v {
191        Json::Null => GoValue::Null,
192        Json::Bool(b) => GoValue::Bool(*b),
193        Json::Num(n) if is_float_token(n) => GoValue::Float(float(v, "value")?),
194        Json::Num(_) => GoValue::Int(integer(v, "value")?),
195        Json::Str(s) => GoValue::String(s.text.clone()),
196        Json::Arr(_) => GoValue::List(list(v, "value", go_value)?),
197        Json::Obj(m) => match non_finite(m) {
198            Some(f) => GoValue::Float(f?),
199            None => GoValue::Map(map(v, "value", go_value)?),
200        },
201    })
202}
203
204/// Decodes `v` as the result of `getter`; a shape mismatch is an error.
205pub(crate) fn decode(getter: Getter, v: &Json) -> R<GetterResult> {
206    let what = getter.as_str();
207    Ok(match getter {
208        Getter::GetBool => match v {
209            Json::Bool(b) => GetterResult::Bool(*b),
210            other => return Err(format!("{what}: expected a boolean, found {}", describe(other))),
211        },
212        Getter::GetString => GetterResult::String(string(v, what)?),
213        Getter::GetInt | Getter::GetInt64 => GetterResult::Int(integer(v, what)?),
214        Getter::GetInt32 => GetterResult::Int32(integer(v, what)?),
215        Getter::GetSizeInBytes => GetterResult::SizeInBytes(integer(v, what)?),
216        Getter::GetDuration => GetterResult::Duration(integer(v, what)?),
217        Getter::GetFloat64 => GetterResult::Float64(float(v, what)?),
218        Getter::GetFloat64Slice => GetterResult::Float64Slice(nullable(v, |v| list(v, what, |x| float(x, what)))?),
219        Getter::GetStringSlice => GetterResult::StringSlice(nullable(v, |v| list(v, what, |x| string(x, what)))?),
220        Getter::GetStringMap => GetterResult::StringMap(nullable(v, |v| map(v, what, go_value))?),
221        Getter::GetStringMapString => {
222            GetterResult::StringMapString(nullable(v, |v| map(v, what, |x| string(x, what)))?)
223        }
224        Getter::GetStringMapStringSlice => {
225            GetterResult::StringMapStringSlice(map(v, what, |x| nullable(x, |x| list(x, what, |s| string(s, what))))?)
226        }
227        Getter::Get => GetterResult::Get(go_value(v)?),
228        Getter::ReadConfigSection => GetterResult::Section(map(v, what, go_value)?),
229        Getter::IsConfigured => match v {
230            Json::Bool(b) => GetterResult::IsConfigured(*b),
231            other => return Err(format!("{what}: expected a boolean, found {}", describe(other))),
232        },
233    })
234}