Skip to main content

datadog_agent_config_corpus/
model.rs

1//! Rust types for saved Agent configuration inputs and observations, returned by [`crate::read`].
2//!
3//! A [`Corpus`] holds recording metadata and test [`Case`]s. Each case pairs its inputs with either
4//! a startup error or the Agent's stream settings and configuration method results. Stream settings
5//! describe what ADP receives; method results describe what Agent components read.
6//!
7//! The reader reconstructs omitted fields according to `config-recorder/docs/record.md`, so callers
8//! do not need to understand the file's space-saving rules. [`Corpus::first_snapshot`] combines the
9//! recorded defaults with a case's changes to recover its starting settings. [`Violation`] and
10//! [`Rule`] describe format errors rather than differences between Agent and ADP behavior.
11
12use std::collections::{BTreeMap, BTreeSet};
13use std::fmt;
14use std::num::NonZeroU64;
15
16use serde_json::Value;
17
18use crate::getter::GetterResult;
19use crate::lists::{Getter, Group, Level, Source};
20
21/// The name of the baseline case, whose key lines are layer 1 of every first snapshot (record.md §3.2).
22pub const BASELINE_CASE: &str = "baseline-default";
23
24/// A whole corpus (record.md §1).
25#[derive(Clone, Debug)]
26#[non_exhaustive]
27pub struct Corpus {
28    /// The header line (record.md §2).
29    pub header: Header,
30    /// The cases, in file order, which is byte order of their names.
31    pub cases: Vec<Case>,
32}
33
34/// The header line (record.md §2). The reader accepts only `format` 1, so it is not kept.
35#[derive(Clone, Debug)]
36#[non_exhaustive]
37pub struct Header {
38    /// The full 40-hex Agent commit the recorder built against.
39    pub agent_commit: String,
40    /// `runtime.GOOS` of the recorder processes.
41    pub goos: String,
42    /// `runtime.GOARCH` of the recorder processes.
43    pub goarch: String,
44    /// `runtime.Version()`.
45    pub go_version: String,
46    /// The digest-pinned image the recorder processes ran in.
47    pub container_image: String,
48    /// `env.IsContainerized()` in the baseline process.
49    pub containerized: bool,
50    /// Sorted detected features in the baseline process (record.md §6).
51    pub features: Vec<String>,
52    /// `sha256:` and 64 hex: the recorder inputs the corpus was made from.
53    pub inputs_digest: String,
54}
55
56/// One case: its case line and its key lines (record.md §3, §5).
57#[derive(Clone, Debug)]
58#[non_exhaustive]
59pub struct Case {
60    /// The case name.
61    pub name: String,
62    /// The coverage group.
63    pub group: Group,
64    /// The 1-based `corpus.jsonl` line of the case line, which holds the case's `inputs`
65    /// (record.md §3.1): where a diagnostic about generated inputs points.
66    pub input_line: usize,
67    /// Behavior catalog ids, in file order.
68    pub why: Vec<String>,
69    /// The inputs, with `keys` reconstructed when omitted (record.md §3.1).
70    pub inputs: Inputs,
71    /// Filtered warnings logged before the first snapshot (record.md §7).
72    pub construction_warnings: Vec<Warning>,
73    /// Whether the config was constructed, and what was recorded if so.
74    pub outcome: Outcome,
75}
76
77/// How a case's construction ended (record.md §3.3, §4.1).
78#[derive(Clone, Debug)]
79pub enum Outcome {
80    /// Construction succeeded and the first snapshot arrived.
81    Started(Started),
82    /// Construction returned this error; nothing else was recorded.
83    StartupError(String),
84}
85
86/// What a case that started recorded.
87#[derive(Clone, Debug)]
88#[non_exhaustive]
89pub struct Started {
90    /// The first snapshot's `origin`.
91    pub origin: String,
92    /// `env.IsContainerized()`, taken from the header when the case line omits it.
93    pub containerized: bool,
94    /// Detected features, taken from the header when the case line omits them.
95    pub features: Vec<String>,
96    /// Settings that differ from the baseline's first snapshot, by key (record.md §3.2).
97    pub side_effects: Vec<SideEffect>,
98    /// One result per case update, in order (record.md §4.2).
99    pub updates: Vec<UpdateResult>,
100    /// The key lines, in byte order of key (record.md §5).
101    pub keys: Vec<KeyLine>,
102}
103
104/// The case's inputs as the case file gave them (record.md §3.1).
105#[derive(Clone, Debug)]
106#[non_exhaustive]
107pub struct Inputs {
108    /// The whole process environment, when the case gave one.
109    pub env: Option<BTreeMap<String, String>>,
110    /// The verbatim `datadog.yaml`, when given.
111    pub yaml: Option<String>,
112    /// The verbatim fleet `datadog.yaml`, when given.
113    pub fleet_policy: Option<String>,
114    /// Startup CLI overrides.
115    pub cli: Vec<CliOverride>,
116    /// Runtime updates, in order.
117    pub updates: Vec<Update>,
118    /// The keys to record, in the case's order; reconstructed from the key lines when omitted.
119    pub keys: Vec<KeySpec>,
120}
121
122/// A startup CLI override (case.md §4.5).
123#[derive(Clone, Debug)]
124#[non_exhaustive]
125pub struct CliOverride {
126    /// The key.
127    pub key: String,
128    /// The typed value, in the JSON form of case.md §7.
129    pub value: Value,
130}
131
132/// A runtime update (case.md §5).
133#[derive(Clone, Debug)]
134#[non_exhaustive]
135pub struct Update {
136    /// The key as passed to the Agent.
137    pub key: String,
138    /// What the update does.
139    pub op: UpdateOp,
140    /// The layer written or cleared; one of [`Source::UPDATE`].
141    pub source: Source,
142}
143
144/// A runtime update's operation.
145#[derive(Clone, Debug)]
146pub enum UpdateOp {
147    /// `cfg.Set` with this typed value (case.md §7).
148    Set(Value),
149    /// `cfg.UnsetForSource`.
150    Unset,
151}
152
153/// An entry of `inputs.keys` (case.md §6).
154#[derive(Clone, Debug)]
155#[non_exhaustive]
156pub struct KeySpec {
157    /// The key.
158    pub key: String,
159    /// The case's getter override, if it gave one.
160    pub getters: Option<Vec<Getter>>,
161}
162
163/// One streamed `pb.ConfigSetting`, without its key (record.md §5.1).
164#[derive(Clone, Debug, PartialEq)]
165#[non_exhaustive]
166pub struct Setting {
167    /// The setting's source.
168    pub source: Source,
169    /// The source an unset cleared, if any.
170    pub unset_source: Option<Source>,
171    /// The protojson value, parsed; `None` when the proto field is unset.
172    pub value: Option<Value>,
173}
174
175/// An element of `side_effects` (record.md §3.2).
176#[derive(Clone, Debug)]
177#[non_exhaustive]
178pub struct SideEffect {
179    /// The key.
180    pub key: String,
181    /// The case's setting, or `None` when the key is absent from the case's first snapshot.
182    pub setting: Option<Setting>,
183}
184
185/// The recorded outcome of one update (record.md §4.2).
186#[derive(Clone, Debug)]
187#[non_exhaustive]
188pub struct UpdateResult {
189    /// Notifications the config issued: `after - before`.
190    pub seq_delta: u64,
191    /// Whether the wait for events ended at 5 s; never with `seq_delta` 0.
192    pub timed_out: bool,
193    /// Warnings logged during the update call.
194    pub warnings: Vec<Warning>,
195}
196
197/// A key line (record.md §5).
198#[derive(Clone, Debug)]
199#[non_exhaustive]
200pub struct KeyLine {
201    /// The key.
202    pub key: String,
203    /// The first snapshot's setting for the key, or `None` when absent.
204    pub snapshot: Option<Setting>,
205    /// Later stream events for the key, in arrival order.
206    pub events: Vec<Event>,
207    /// The getter reads.
208    pub reads: Reads,
209}
210
211/// A stream event (record.md §5.2).
212#[derive(Clone, Debug)]
213#[non_exhaustive]
214pub struct Event {
215    /// The streamed setting.
216    pub setting: Setting,
217    /// `sequence_id - before` of its update; the first event of an update is 1.
218    pub seq: NonZeroU64,
219    /// The index of the update the event belongs to, reconstructed when omitted.
220    pub update: usize,
221}
222
223/// A key line's reads (record.md §5.3).
224#[derive(Clone, Debug)]
225#[non_exhaustive]
226pub struct Reads {
227    /// The read after the first snapshot, before any update.
228    pub snapshot: Read,
229    /// The read after the last update, present exactly when the case has updates.
230    pub final_: Option<Read>,
231}
232
233/// The getter reads at one checkpoint (record.md §5.3).
234#[derive(Clone, Debug)]
235#[non_exhaustive]
236pub struct Read {
237    /// One result per getter in the key's list, in order.
238    pub getters: Vec<GetterRead>,
239    /// `fmt.Sprintf("%T", cfg.Get(key))`.
240    pub go_type: String,
241    /// `cfg.GetSource(key)`, reconstructed from the streamed source when omitted.
242    pub source: Source,
243}
244
245/// One getter call's result (record.md §5.3; getter-map.md §3).
246#[derive(Clone, Debug)]
247#[non_exhaustive]
248pub struct GetterRead {
249    /// The getter called.
250    pub getter: Getter,
251    /// The decoded result.
252    pub result: GetterResult,
253    /// Warnings the call logged that mention the key.
254    pub warnings: Vec<Warning>,
255}
256
257/// A recorded warning (record.md §7).
258#[derive(Clone, Debug, PartialEq, Eq)]
259#[non_exhaustive]
260pub struct Warning {
261    /// The slog level.
262    pub level: Level,
263    /// The record's message.
264    pub message: String,
265}
266
267/// Which family of format rules a violation breaks.
268#[derive(Clone, Copy, Debug, PartialEq, Eq)]
269pub enum Rule {
270    /// Encoding and line structure (record.md §1).
271    File,
272    /// Canonical JSON: whitespace, member order, escaping (record.md §1).
273    Canonical,
274    /// Line order (record.md §1).
275    Order,
276    /// A member's presence, type, `null`-ness or allowed values.
277    Shape,
278    /// The consistency rules between members and lines (record.md §3.3).
279    Consistency,
280    /// The rules for members a writer omits (record.md §3.1, §5.2, §5.3).
281    Reconstruction,
282    /// A getter result that does not match its getter's encoding (getter-map.md §3).
283    GetterResult,
284}
285
286impl fmt::Display for Rule {
287    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288        f.write_str(match self {
289            Rule::File => "file",
290            Rule::Canonical => "canonical form",
291            Rule::Order => "order",
292            Rule::Shape => "shape",
293            Rule::Consistency => "consistency",
294            Rule::Reconstruction => "reconstruction",
295            Rule::GetterResult => "getter result",
296        })
297    }
298}
299
300/// A broken format rule.
301#[derive(Clone, Debug, PartialEq, Eq)]
302#[non_exhaustive]
303pub struct Violation {
304    /// The 1-based line, or 0 for the file as a whole.
305    pub line: usize,
306    /// The rule family.
307    pub rule: Rule,
308    /// What is wrong.
309    pub message: String,
310}
311
312impl fmt::Display for Violation {
313    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
314        if self.line == 0 {
315            write!(f, "file: {}: {}", self.rule, self.message)
316        } else {
317            write!(f, "line {}: {}: {}", self.line, self.rule, self.message)
318        }
319    }
320}
321
322impl Case {
323    /// The stable origin of the case's checks: what produced them, stripped of the naming a
324    /// schema bump reshuffles (case.md §3.2, §3.2.1).
325    ///
326    /// The `baseline`, `behavior` and `unknown` groups keep the case name. A `depth` case drops
327    /// the `--<key>` suffix of a bisection part, leaving `depth-<variant>`. The batched groups
328    /// (`breadth`, `unsupported`, `excluded`) drop the section batch and any `--<key>` suffix,
329    /// leaving `<group>-<source>`, since a recorded read's own `key` member already names the
330    /// exact setting. This is an assertion identity for replay expectations, not a runtime case
331    /// filter or a category grouping.
332    pub fn check_origin(&self) -> &str {
333        match self.group {
334            Group::Baseline | Group::Behavior | Group::Unknown => &self.name,
335            Group::Depth => match self.name.split_once("--") {
336                Some((origin, _)) => origin,
337                None => &self.name,
338            },
339            Group::Breadth | Group::Unsupported | Group::Excluded => {
340                let mut segments = self.name.splitn(3, '-');
341                let len = match (segments.next(), segments.next()) {
342                    (Some(group), Some(source)) => group.len() + 1 + source.len(),
343                    _ => return &self.name,
344                };
345                self.name.get(..len).unwrap_or(&self.name)
346            }
347        }
348    }
349}
350
351impl Corpus {
352    /// The case with this name.
353    pub fn case(&self, name: &str) -> Option<&Case> {
354        self.cases
355            .binary_search_by(|c| c.name.as_bytes().cmp(name.as_bytes()))
356            .ok()
357            .map(|i| &self.cases[i])
358    }
359
360    /// The keys of the [`BASELINE_CASE`] key lines: every key ADP modeled when the corpus was recorded.
361    ///
362    /// The set is fixed at recording time. It changes only when the corpus is re-recorded, never
363    /// when ADP's support for a key changes afterwards. Keys are lowercase, as the reader requires.
364    ///
365    /// Returns `None` when the baseline case did not start, so a missing baseline cannot pass as an
366    /// empty set. [`crate::read`] rejects a corpus without a baseline case, but not one whose
367    /// baseline hit a startup error.
368    pub fn surface(&self) -> Option<BTreeSet<&str>> {
369        let Outcome::Started(baseline) = &self.case(BASELINE_CASE)?.outcome else {
370            return None;
371        };
372        Some(baseline.keys.iter().map(|k| k.key.as_str()).collect())
373    }
374
375    /// Rebuilds a case's first snapshot, key to setting, by the three layers of record.md §3.2:
376    /// the `baseline-default` case's key-line snapshots, then the case's `side_effects` (an absent
377    /// element removes the key), then the case's own key-line snapshots (`null` removes the key).
378    ///
379    /// Keys the corpus neither models nor saw change are not in the result. Returns `None` when the
380    /// case does not exist or did not start. Without a started baseline case, layer 1 is empty.
381    pub fn first_snapshot(&self, case: &str) -> Option<BTreeMap<&str, &Setting>> {
382        let Outcome::Started(started) = &self.case(case)?.outcome else {
383            return None;
384        };
385        let mut snapshot = BTreeMap::new();
386        if let Some(Case {
387            outcome: Outcome::Started(baseline),
388            ..
389        }) = self.case(BASELINE_CASE)
390        {
391            for k in &baseline.keys {
392                if let Some(s) = &k.snapshot {
393                    snapshot.insert(k.key.as_str(), s);
394                }
395            }
396        }
397        for e in &started.side_effects {
398            match &e.setting {
399                Some(s) => snapshot.insert(e.key.as_str(), s),
400                None => snapshot.remove(e.key.as_str()),
401            };
402        }
403        for k in &started.keys {
404            match &k.snapshot {
405                Some(s) => snapshot.insert(k.key.as_str(), s),
406                None => snapshot.remove(k.key.as_str()),
407            };
408        }
409        Some(snapshot)
410    }
411}