Skip to main content

goliath_normalize/
normalizer.rs

1//! Source definitions compiled for use, and records through them.
2
3use std::collections::BTreeMap;
4
5use goliath_ocsf::schema::{self, Base};
6use goliath_rule::FieldPath;
7use serde::{Deserialize, Deserializer, Serialize, Serializer};
8use serde_json::{Map, Value};
9
10use crate::definition::{Coercion, Decoding, FieldSpec, Framing, SourceDefinition};
11use crate::error::DefinitionError;
12
13/// A source definition, checked and compiled.
14///
15/// Built once, then used for every record of the source. Normalizing is
16/// deterministic: the same bytes under the same definition version always give
17/// the same outcome.
18#[derive(Debug, Clone)]
19pub struct Normalizer {
20    name: String,
21    version: u32,
22    framing: Framing,
23    kinds: Vec<Kind>,
24}
25
26#[derive(Debug, Clone)]
27struct Kind {
28    name: String,
29    when: Vec<(SourcePath, Value)>,
30    /// `class_uid`, `category_uid`, `type_uid`, and `activity_id`.
31    class: Vec<(&'static str, Value)>,
32    /// The common fields, then the kind's own.
33    fields: Vec<Field>,
34    unmapped: Vec<SourcePath>,
35}
36
37#[derive(Debug, Clone)]
38struct Field {
39    target: FieldPath,
40    source: Source,
41}
42
43#[derive(Debug, Clone)]
44enum Source {
45    Constant(Value),
46    Path {
47        path: SourcePath,
48        coercion: Option<Coercion>,
49    },
50    Translate {
51        path: SourcePath,
52        map: BTreeMap<String, Value>,
53        otherwise: Option<Value>,
54    },
55}
56
57/// A dotted path into a decoded record. Unlike an OCSF path, it names exactly
58/// one value: records are read, not searched.
59///
60/// A member whose own name holds dots, as Falco's `proc.cmdline` does, is
61/// named by writing it out: `output_fields.proc.cmdline`. At each object a
62/// member named by the next segment alone is tried first, then by the next
63/// two joined with a dot, and so on.
64#[derive(Debug, Clone, PartialEq, Eq)]
65struct SourcePath {
66    text: String,
67    segments: Vec<String>,
68}
69
70impl SourcePath {
71    fn parse(text: &str) -> Option<Self> {
72        let segments: Vec<String> = text.split('.').map(str::to_owned).collect();
73        segments
74            .iter()
75            .all(|segment| !segment.is_empty())
76            .then(|| Self {
77                text: text.to_owned(),
78                segments,
79            })
80    }
81
82    fn lookup<'a>(&self, record: &'a Value) -> Option<&'a Value> {
83        find(record, &self.segments)
84    }
85
86    /// The name, within the object at `object`, of the member this path
87    /// names, if it is one.
88    fn member_of(&self, object: &Self) -> Option<String> {
89        (self.segments.len() > object.segments.len() && self.segments.starts_with(&object.segments))
90            .then(|| self.segments[object.segments.len()..].join("."))
91    }
92
93    /// Whether this path names the member `key` of the object at `object`.
94    fn is_member(&self, object: &Self, key: &str) -> bool {
95        self.member_of(object).is_some_and(|member| member == key)
96    }
97}
98
99fn find<'a>(value: &'a Value, segments: &[String]) -> Option<&'a Value> {
100    if segments.is_empty() {
101        return Some(value);
102    }
103    let object = value.as_object()?;
104    let mut name = String::new();
105    for (index, segment) in segments.iter().enumerate() {
106        if index > 0 {
107            name.push('.');
108        }
109        name.push_str(segment);
110        if let Some(found) = object
111            .get(&name)
112            .and_then(|member| find(member, &segments[index + 1..]))
113        {
114            return Some(found);
115        }
116    }
117    None
118}
119
120/// What became of one record.
121#[non_exhaustive]
122#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
123#[serde(rename_all = "snake_case")]
124pub enum Outcome {
125    /// The record became an OCSF event.
126    Event(Normalized),
127    /// The record could not become an event, and is kept whole.
128    DeadLetter(DeadLetter),
129}
130
131/// An OCSF event, and anything that did not convert on the way.
132#[non_exhaustive]
133#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
134pub struct Normalized {
135    /// Identifies the record the event came from, so that storage can drop
136    /// a record delivered twice.
137    pub id: EventId,
138    /// The event.
139    pub event: Value,
140    /// The kind of record it was.
141    pub kind: String,
142    /// Values that did not convert. Each is kept as written under
143    /// `unmapped`, and the event is still produced, so that a malformed field
144    /// cannot keep an event away from detection.
145    pub issues: Vec<Issue>,
146}
147
148/// The identity of a record: 128 bits of the BLAKE3 hash of the source's
149/// name and the record's raw bytes.
150///
151/// It depends on nothing else, so a record delivered again, or collected
152/// again, gets the same identity and can be dropped as a duplicate. Two
153/// records with identical bytes from one source are the same record.
154///
155/// The hash is cryptographic on purpose. Whoever writes the logs chooses the
156/// bytes, and with a hash built only for speed they could craft a record
157/// whose identity equals that of another, and have storage drop one of the
158/// two as a duplicate.
159#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
160pub struct EventId([u8; 16]);
161
162impl EventId {
163    /// Keys the hash, so that identities cannot be confused with any other
164    /// use of BLAKE3. Changing it changes every identity.
165    const CONTEXT: &str = "goliath 2026-09-25 event id";
166
167    /// The identity of the record `raw` from the source `source`.
168    pub fn of(source: &str, raw: &[u8]) -> Self {
169        let mut hasher = blake3::Hasher::new_derive_key(Self::CONTEXT);
170        // The name's length first, so that no name and record pair can end
171        // where another pair's name does.
172        hasher.update(&(source.len() as u64).to_le_bytes());
173        hasher.update(source.as_bytes());
174        hasher.update(raw);
175        let mut id = [0; 16];
176        hasher.finalize_xof().fill(&mut id);
177        Self(id)
178    }
179
180    /// The identity's bytes.
181    pub fn as_bytes(&self) -> &[u8; 16] {
182        &self.0
183    }
184}
185
186impl std::fmt::Display for EventId {
187    /// Lowercase hexadecimal.
188    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
189        self.0.iter().try_for_each(|byte| write!(f, "{byte:02x}"))
190    }
191}
192
193impl std::str::FromStr for EventId {
194    type Err = String;
195
196    /// Parses the lowercase or uppercase hexadecimal [`Display`] writes.
197    ///
198    /// [`Display`]: std::fmt::Display
199    fn from_str(text: &str) -> Result<Self, Self::Err> {
200        let invalid = || format!("`{text}` is not 32 hexadecimal digits");
201        if text.len() != 32 {
202            return Err(invalid());
203        }
204        let mut id = [0; 16];
205        let (pairs, _) = text.as_bytes().as_chunks::<2>();
206        for (byte, pair) in id.iter_mut().zip(pairs) {
207            let pair = std::str::from_utf8(pair).map_err(|_| invalid())?;
208            *byte = u8::from_str_radix(pair, 16).map_err(|_| invalid())?;
209        }
210        Ok(Self(id))
211    }
212}
213
214/// As its hexadecimal text, so that it reads the same in JSON as in logs.
215impl Serialize for EventId {
216    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
217        serializer.collect_str(self)
218    }
219}
220
221impl<'de> Deserialize<'de> for EventId {
222    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
223        let text = String::deserialize(deserializer)?;
224        text.parse().map_err(serde::de::Error::custom)
225    }
226}
227
228impl std::fmt::Debug for EventId {
229    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
230        write!(f, "EventId({self})")
231    }
232}
233
234/// A value that did not convert.
235#[non_exhaustive]
236#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
237pub struct Issue {
238    /// The OCSF attribute it was meant for.
239    pub target: String,
240    /// Where it was read from.
241    pub source: String,
242    /// Why it did not convert.
243    pub reason: String,
244}
245
246/// A record that could not become an event.
247///
248/// The raw bytes are kept exactly, so the record can be processed again once
249/// the source definition is fixed. Nothing a source sends is dropped.
250#[non_exhaustive]
251#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
252pub struct DeadLetter {
253    /// The stage that failed.
254    pub stage: Stage,
255    /// Why.
256    pub error: String,
257    /// The record as received; for a stream that could not be framed, the
258    /// rest of the stream.
259    pub raw: Vec<u8>,
260}
261
262/// A stage of normalization, in order.
263#[non_exhaustive]
264#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
265#[serde(rename_all = "snake_case")]
266pub enum Stage {
267    /// Splitting the stream into records.
268    Framing,
269    /// Turning a record into a field map.
270    Decoding,
271    /// Choosing a kind and writing the OCSF event.
272    Mapping,
273}
274
275impl Stage {
276    /// The stage's name, as reports and metrics use it.
277    pub fn as_str(self) -> &'static str {
278        match self {
279            Self::Framing => "framing",
280            Self::Decoding => "decoding",
281            Self::Mapping => "mapping",
282        }
283    }
284}
285
286impl Normalizer {
287    /// Loads a source definition from YAML, as untrusted input.
288    ///
289    /// # Errors
290    ///
291    /// Returns [`DefinitionError`] if the YAML is not a valid definition.
292    pub fn from_yaml(text: &str) -> Result<Self, DefinitionError> {
293        let definition: SourceDefinition = goliath_sigma::yaml::from_str(text)?;
294        Self::new(&definition)
295    }
296
297    /// Checks and compiles a source definition.
298    ///
299    /// # Errors
300    ///
301    /// Returns [`DefinitionError`] if a path does not parse, two fields
302    /// would write over each other, a field writes an attribute that is set
303    /// otherwise, or a kind would accept every record; and if a class,
304    /// activity, or target is not in the OCSF schema, or a field writes a
305    /// value its attribute cannot hold.
306    pub fn new(definition: &SourceDefinition) -> Result<Self, DefinitionError> {
307        if definition.kinds.is_empty() {
308            return Err(DefinitionError::NoKinds);
309        }
310        let common = compile_fields("common", &definition.common)?;
311        let mut kinds = Vec::with_capacity(definition.kinds.len());
312        for kind in &definition.kinds {
313            if kind.when.is_empty() {
314                return Err(DefinitionError::Unconditional {
315                    kind: kind.name.clone(),
316                });
317            }
318            let when = kind
319                .when
320                .iter()
321                .map(|(path, value)| Ok((source_path(&kind.name, path)?, Value::from(value))))
322                .collect::<Result<_, DefinitionError>>()?;
323            let mut fields = common.clone();
324            fields.extend(compile_fields(&kind.name, &kind.fields)?);
325            check_overlaps(&kind.name, &fields)?;
326            check_schema(
327                &kind.name,
328                kind.class.class_uid,
329                kind.class.activity_id,
330                &fields,
331            )?;
332            let unmapped = kind
333                .unmapped
334                .iter()
335                .map(|path| source_path(&kind.name, path))
336                .collect::<Result<_, _>>()?;
337
338            let class_uid = kind.class.class_uid;
339            let activity_id = kind.class.activity_id;
340            let category_uid = goliath_ocsf::Event::derive_category_uid(class_uid);
341            let type_uid = goliath_ocsf::Event::derive_type_uid(class_uid, activity_id);
342            kinds.push(Kind {
343                name: kind.name.clone(),
344                when,
345                class: vec![
346                    ("class_uid", Value::from(class_uid)),
347                    ("category_uid", Value::from(category_uid)),
348                    ("type_uid", Value::from(type_uid)),
349                    ("activity_id", Value::from(activity_id)),
350                ],
351                fields,
352                unmapped,
353            });
354        }
355        // Only JSON exists so far; the match makes a new decoding a compile
356        // error here rather than a silent fallback.
357        match definition.decoding {
358            Decoding::Json => {}
359        }
360        Ok(Self {
361            name: definition.name.clone(),
362            version: definition.version,
363            framing: definition.framing,
364            kinds,
365        })
366    }
367
368    /// The source's name.
369    pub fn name(&self) -> &str {
370        &self.name
371    }
372
373    /// The definition's version, to be stored with every event it produces.
374    pub fn version(&self) -> u32 {
375        self.version
376    }
377
378    /// Splits `bytes` into records and normalizes each, calling `out` with
379    /// every outcome in order.
380    pub fn normalize(&self, bytes: &[u8], mut out: impl FnMut(Outcome)) {
381        match self.framing {
382            Framing::Lines => {
383                for line in bytes.split(|&byte| byte == b'\n') {
384                    let line = line.strip_suffix(b"\r").unwrap_or(line);
385                    if line.iter().all(u8::is_ascii_whitespace) {
386                        continue;
387                    }
388                    out(match serde_json::from_slice::<Value>(line) {
389                        Ok(record) => self.record(&record, line),
390                        Err(error) => dead(Stage::Decoding, error.to_string(), line),
391                    });
392                }
393            }
394            Framing::JsonValues => {
395                let mut stream = serde_json::Deserializer::from_slice(bytes).into_iter::<Value>();
396                let mut start = 0;
397                while let Some(next) = stream.next() {
398                    match next {
399                        Ok(record) => {
400                            let end = stream.byte_offset();
401                            out(self.record(&record, trim(&bytes[start..end])));
402                            start = end;
403                        }
404                        Err(error) => {
405                            // Where one value ends cannot be known once the
406                            // stream is broken, so the rest is kept together.
407                            out(dead(
408                                Stage::Framing,
409                                error.to_string(),
410                                trim(&bytes[start..]),
411                            ));
412                            return;
413                        }
414                    }
415                }
416            }
417        }
418    }
419
420    /// Normalizes one decoded record, whose raw bytes are `raw`.
421    fn record(&self, record: &Value, raw: &[u8]) -> Outcome {
422        if !record.is_object() {
423            return dead(
424                Stage::Decoding,
425                "the record is not a JSON object".to_owned(),
426                raw,
427            );
428        }
429        let Some(kind) = self.kinds.iter().find(|kind| {
430            kind.when
431                .iter()
432                .all(|(path, expected)| path.lookup(record) == Some(expected))
433        }) else {
434            return dead(
435                Stage::Mapping,
436                format!("no kind of source `{}` accepts the record", self.name),
437                raw,
438            );
439        };
440
441        let mut event = Map::new();
442        let mut unmapped = Map::new();
443        let mut issues = Vec::new();
444        let mut consumed: Vec<&SourcePath> = Vec::new();
445        for (name, value) in &kind.class {
446            event.insert((*name).to_owned(), value.clone());
447        }
448        for field in &kind.fields {
449            let path = match &field.source {
450                Source::Constant(value) => {
451                    set(&mut event, field.target.segments(), value.clone());
452                    continue;
453                }
454                Source::Path { path, .. } | Source::Translate { path, .. } => path,
455            };
456            let Some(found) = path.lookup(record).filter(|value| !value.is_null()) else {
457                continue;
458            };
459            consumed.push(path);
460            match field.source.convert(found) {
461                Ok(value) => set(&mut event, field.target.segments(), value),
462                Err(reason) => {
463                    issues.push(Issue {
464                        target: field.target.as_str().to_owned(),
465                        source: path.text.clone(),
466                        reason,
467                    });
468                    // Kept by the name the `unmapped` lists would give it, or
469                    // by its whole path where they give none, so that it
470                    // cannot take another member's name.
471                    let name = kind
472                        .unmapped
473                        .iter()
474                        .find_map(|object| path.member_of(object))
475                        .unwrap_or_else(|| path.text.clone());
476                    unmapped.insert(name, found.clone());
477                }
478            }
479        }
480        for object in &kind.unmapped {
481            let Some(Value::Object(members)) = object.lookup(record) else {
482                continue;
483            };
484            for (key, member) in members {
485                if member.is_null() || consumed.iter().any(|path| path.is_member(object, key)) {
486                    continue;
487                }
488                unmapped
489                    .entry(key.clone())
490                    .or_insert_with(|| member.clone());
491            }
492        }
493        if !unmapped.is_empty() {
494            event.insert("unmapped".to_owned(), Value::Object(unmapped));
495        }
496        Outcome::Event(Normalized {
497            id: EventId::of(&self.name, raw),
498            event: Value::Object(event),
499            kind: kind.name.clone(),
500            issues,
501        })
502    }
503}
504
505fn dead(stage: Stage, error: String, raw: &[u8]) -> Outcome {
506    Outcome::DeadLetter(DeadLetter {
507        stage,
508        error,
509        raw: raw.to_vec(),
510    })
511}
512
513fn trim(bytes: &[u8]) -> &[u8] {
514    let start = bytes
515        .iter()
516        .position(|byte| !byte.is_ascii_whitespace())
517        .unwrap_or(bytes.len());
518    let end = bytes
519        .iter()
520        .rposition(|byte| !byte.is_ascii_whitespace())
521        .map_or(start, |position| position + 1);
522    &bytes[start..end]
523}
524
525fn source_path(kind: &str, text: &str) -> Result<SourcePath, DefinitionError> {
526    SourcePath::parse(text).ok_or_else(|| DefinitionError::SourcePath {
527        kind: kind.to_owned(),
528        path: text.to_owned(),
529    })
530}
531
532fn compile_fields(
533    kind: &str,
534    specs: &std::collections::BTreeMap<String, FieldSpec>,
535) -> Result<Vec<Field>, DefinitionError> {
536    specs
537        .iter()
538        .map(|(target, spec)| {
539            let path = FieldPath::parse(target).map_err(|source| DefinitionError::Target {
540                kind: kind.to_owned(),
541                target: target.clone(),
542                source,
543            })?;
544            let reserved = match path.segments()[0].as_str() {
545                "class_uid" | "category_uid" | "type_uid" | "activity_id" => {
546                    Some("the kind's `class`")
547                }
548                "unmapped" => Some("the kind's `unmapped` list"),
549                _ => None,
550            };
551            if let Some(reason) = reserved {
552                return Err(DefinitionError::Reserved {
553                    kind: kind.to_owned(),
554                    target: target.clone(),
555                    reason,
556                });
557            }
558            let source = match spec {
559                FieldSpec::Path(from) => Source::Path {
560                    path: source_path(kind, from)?,
561                    coercion: None,
562                },
563                FieldSpec::Converted { from, coercion } => Source::Path {
564                    path: source_path(kind, from)?,
565                    coercion: Some(*coercion),
566                },
567                FieldSpec::Translated {
568                    from,
569                    map,
570                    otherwise,
571                } => {
572                    let invalid = |reason| DefinitionError::Translation {
573                        kind: kind.to_owned(),
574                        target: target.clone(),
575                        reason,
576                    };
577                    let mut values = map.values().chain(otherwise).map(Value::from);
578                    let first = values.next().ok_or_else(|| invalid("is empty"))?;
579                    if values.any(|value| Writes::of(&value) != Writes::of(&first)) {
580                        return Err(invalid("mixes values of different types"));
581                    }
582                    Source::Translate {
583                        path: source_path(kind, from)?,
584                        map: map
585                            .iter()
586                            .map(|(key, value)| (key.clone(), Value::from(value)))
587                            .collect(),
588                        otherwise: otherwise.as_ref().map(Value::from),
589                    }
590                }
591                FieldSpec::Value { value } => Source::Constant(Value::from(value)),
592            };
593            Ok(Field {
594                target: path,
595                source,
596            })
597        })
598        .collect()
599}
600
601/// Rejects two fields writing the same attribute, or one inside another:
602/// the second write would replace or be lost under the first.
603fn check_overlaps(kind: &str, fields: &[Field]) -> Result<(), DefinitionError> {
604    for (index, first) in fields.iter().enumerate() {
605        for second in &fields[index + 1..] {
606            let (a, b) = (first.target.segments(), second.target.segments());
607            if a.starts_with(b) || b.starts_with(a) {
608                return Err(DefinitionError::Overlap {
609                    kind: kind.to_owned(),
610                    first: first.target.as_str().to_owned(),
611                    second: second.target.as_str().to_owned(),
612                });
613            }
614        }
615    }
616    Ok(())
617}
618
619/// Checks the class, the activity, and every field against the OCSF schema,
620/// so that a misspelled attribute fails here rather than produce events no
621/// rule reads.
622fn check_schema(
623    kind: &str,
624    class_uid: u32,
625    activity_id: u32,
626    fields: &[Field],
627) -> Result<(), DefinitionError> {
628    let class = schema::class(class_uid).ok_or_else(|| DefinitionError::UnknownClass {
629        kind: kind.to_owned(),
630        class_uid,
631        version: goliath_ocsf::SCHEMA_VERSION,
632    })?;
633    let activities = class
634        .attribute("activity_id")
635        .map(schema::Attribute::enum_values)
636        .unwrap_or_default();
637    if !activities.contains(&i64::from(activity_id)) {
638        return Err(DefinitionError::UnknownActivity {
639            kind: kind.to_owned(),
640            class: class.name(),
641            activity_id,
642        });
643    }
644    for field in fields {
645        let target = field.target.as_str();
646        let found = class
647            .resolve(target)
648            .map_err(|source| DefinitionError::Attribute {
649                kind: kind.to_owned(),
650                source,
651            })?;
652        if found.within_array {
653            return Err(DefinitionError::WithinArray {
654                kind: kind.to_owned(),
655                target: target.to_owned(),
656            });
657        }
658        // A copy keeps whatever the source holds, and a free-form attribute
659        // takes anything, so neither has a type to check.
660        let Some(writes) = field.source.writes() else {
661            continue;
662        };
663        if found.free_form {
664            continue;
665        }
666        let attribute = found.attribute;
667        let fits = !attribute.is_array()
668            && match writes {
669                Writes::Boolean => attribute.base() == Base::Boolean,
670                Writes::Integer => matches!(attribute.base(), Base::Integer | Base::Long),
671                Writes::Text => attribute.base() == Base::String,
672                Writes::Timestamp => attribute.type_name() == "timestamp_t",
673            };
674        if !fits {
675            let holds = match (attribute.is_array(), attribute.base()) {
676                (true, _) => format!("an array of `{}`", attribute.type_name()),
677                (false, Base::Object) => format!("an object `{}`", attribute.type_name()),
678                (false, _) => format!("`{}`", attribute.type_name()),
679            };
680            return Err(DefinitionError::Type {
681                kind: kind.to_owned(),
682                target: target.to_owned(),
683                holds,
684                writes: writes.describe(),
685            });
686        }
687        let values = attribute.enum_values();
688        let unknown = field
689            .source
690            .constants()
691            .filter_map(Value::as_i64)
692            .find(|value| !values.is_empty() && !values.contains(value));
693        if let Some(value) = unknown {
694            return Err(DefinitionError::UnknownValue {
695                kind: kind.to_owned(),
696                target: target.to_owned(),
697                value,
698            });
699        }
700    }
701    Ok(())
702}
703
704/// What a field writes, where that is known before any record is read.
705#[derive(Debug, Clone, Copy, PartialEq, Eq)]
706enum Writes {
707    Boolean,
708    Integer,
709    Text,
710    Timestamp,
711}
712
713impl Writes {
714    /// What writing `value` writes; nothing known for a list or an object.
715    fn of(value: &Value) -> Option<Self> {
716        match value {
717            Value::Bool(_) => Some(Self::Boolean),
718            Value::Number(_) => Some(Self::Integer),
719            Value::String(_) => Some(Self::Text),
720            _ => None,
721        }
722    }
723
724    fn describe(self) -> &'static str {
725        match self {
726            Self::Boolean => "a boolean",
727            Self::Integer => "an integer",
728            Self::Text => "text",
729            Self::Timestamp => "a timestamp",
730        }
731    }
732}
733
734impl Source {
735    fn writes(&self) -> Option<Writes> {
736        match self {
737            Self::Constant(value) => Writes::of(value),
738            // Every value of a table has the same type, checked when it is
739            // compiled.
740            Self::Translate { map, .. } => map.values().next().and_then(Writes::of),
741            Self::Path { coercion: None, .. } => None,
742            Self::Path {
743                coercion: Some(coercion),
744                ..
745            } => Some(match coercion {
746                Coercion::String => Writes::Text,
747                Coercion::Integer => Writes::Integer,
748                Coercion::Timestamp => Writes::Timestamp,
749            }),
750        }
751    }
752}
753
754impl Source {
755    /// Every value this source can write that is fixed by the definition.
756    fn constants(&self) -> impl Iterator<Item = &Value> {
757        let (map, extra) = match self {
758            Self::Constant(value) => (None, Some(value)),
759            Self::Translate { map, otherwise, .. } => (Some(map), otherwise.as_ref()),
760            Self::Path { .. } => (None, None),
761        };
762        map.into_iter().flat_map(BTreeMap::values).chain(extra)
763    }
764
765    /// The value to write for `found`, or why there is none.
766    fn convert(&self, found: &Value) -> Result<Value, String> {
767        match self {
768            Self::Constant(value) => Ok(value.clone()),
769            Self::Path { coercion, .. } => coerce(found, *coercion),
770            Self::Translate { map, otherwise, .. } => {
771                let key = match found {
772                    Value::String(text) => text.clone(),
773                    Value::Number(_) | Value::Bool(_) => found.to_string(),
774                    other => return Err(format!("cannot translate {}", describe(other))),
775                };
776                map.get(&key)
777                    .or(otherwise.as_ref())
778                    .cloned()
779                    .ok_or_else(|| format!("`{key}` is not in the translation table"))
780            }
781        }
782    }
783}
784
785/// Writes `value` at `segments`, creating objects on the way. Overlapping
786/// targets are rejected when the definition is compiled, so the way is
787/// always clear.
788fn set(object: &mut Map<String, Value>, segments: &[String], value: Value) {
789    let Some((last, parents)) = segments.split_last() else {
790        return;
791    };
792    let mut object = object;
793    for segment in parents {
794        let child = object
795            .entry(segment.clone())
796            .or_insert_with(|| Value::Object(Map::new()));
797        let Value::Object(child) = child else {
798            return;
799        };
800        object = child;
801    }
802    object.insert(last.clone(), value);
803}
804
805fn coerce(value: &Value, coercion: Option<Coercion>) -> Result<Value, String> {
806    let Some(coercion) = coercion else {
807        return Ok(value.clone());
808    };
809    match (coercion, value) {
810        (Coercion::String, Value::String(_)) => Ok(value.clone()),
811        (Coercion::String, Value::Number(number)) => Ok(Value::String(number.to_string())),
812        (Coercion::Integer, Value::Number(number)) => number
813            .as_i64()
814            .map(Value::from)
815            .ok_or_else(|| format!("{number} is not a whole number")),
816        (Coercion::Integer, Value::String(text)) => text
817            .trim()
818            .parse::<i64>()
819            .map(Value::from)
820            .map_err(|_| format!("`{text}` is not a whole number")),
821        (Coercion::Timestamp, Value::String(text)) => text
822            .parse::<jiff::Timestamp>()
823            .map(|time| Value::from(time.as_millisecond()))
824            .map_err(|error| format!("`{text}` is not an RFC 3339 time: {error}")),
825        (coercion, other) => Err(format!(
826            "cannot convert {} to {coercion:?}",
827            describe(other)
828        )),
829    }
830}
831
832fn describe(value: &Value) -> &'static str {
833    match value {
834        Value::Null => "null",
835        Value::Bool(_) => "a boolean",
836        Value::Number(_) => "a number",
837        Value::String(_) => "text",
838        Value::Array(_) => "a list",
839        Value::Object(_) => "an object",
840    }
841}