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