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