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}
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| {
338                    // `.` is the record itself, for sources that write every
339                    // field at its top level.
340                    if path == "." {
341                        Ok(SourcePath {
342                            text: path.clone(),
343                            segments: Vec::new(),
344                        })
345                    } else {
346                        source_path(&kind.name, path)
347                    }
348                })
349                .collect::<Result<_, _>>()?;
350
351            let class_uid = kind.class.class_uid;
352            let activity_id = kind.class.activity_id;
353            let category_uid = goliath_ocsf::Event::derive_category_uid(class_uid);
354            let type_uid = goliath_ocsf::Event::derive_type_uid(class_uid, activity_id);
355            kinds.push(Kind {
356                name: kind.name.clone(),
357                when,
358                class: vec![
359                    ("class_uid", Value::from(class_uid)),
360                    ("category_uid", Value::from(category_uid)),
361                    ("type_uid", Value::from(type_uid)),
362                    ("activity_id", Value::from(activity_id)),
363                ],
364                fields,
365                unmapped,
366            });
367        }
368        let fits = match definition.framing {
369            Framing::Lines => true,
370            Framing::JsonValues => definition.decoding == Decoding::Json,
371            Framing::AuditEvents => definition.decoding == Decoding::Auditd,
372            Framing::Syslog => {
373                matches!(definition.decoding, Decoding::Syslog | Decoding::SyslogJson)
374            }
375        };
376        if !fits {
377            return Err(DefinitionError::Decoding {
378                framing: match definition.framing {
379                    Framing::Lines => "lines",
380                    Framing::JsonValues => "json-values",
381                    Framing::AuditEvents => "audit-events",
382                    Framing::Syslog => "syslog",
383                },
384                decoding: match definition.decoding {
385                    Decoding::Json => "json",
386                    Decoding::Auditd => "auditd",
387                    Decoding::Syslog => "syslog",
388                    Decoding::SyslogJson => "syslog-json",
389                },
390            });
391        }
392        Ok(Self {
393            name: definition.name.clone(),
394            version: definition.version,
395            framing: definition.framing,
396            decoding: definition.decoding,
397            kinds,
398        })
399    }
400
401    /// The source's name.
402    pub fn name(&self) -> &str {
403        &self.name
404    }
405
406    /// The definition's version, to be stored with every event it produces.
407    pub fn version(&self) -> u32 {
408        self.version
409    }
410
411    /// Splits `bytes` into records and normalizes each, calling `out` with
412    /// every outcome in order.
413    pub fn normalize(&self, bytes: &[u8], mut out: impl FnMut(Outcome)) {
414        match self.framing {
415            Framing::Lines => {
416                for line in bytes.split(|&byte| byte == b'\n') {
417                    let line = line.strip_suffix(b"\r").unwrap_or(line);
418                    if line.iter().all(u8::is_ascii_whitespace) {
419                        continue;
420                    }
421                    out(self.decoded(line));
422                }
423            }
424            Framing::AuditEvents => {
425                for event in auditd::events(bytes) {
426                    out(match event {
427                        Ok(raw) => self.decoded(&raw),
428                        Err(line) => dead(
429                            Stage::Framing,
430                            "the line names no audit event".to_owned(),
431                            line,
432                        ),
433                    });
434                }
435            }
436            Framing::Syslog => {
437                for message in syslog::messages(bytes) {
438                    out(match message {
439                        Ok(raw) => self.decoded(raw),
440                        Err(rest) => dead(
441                            Stage::Framing,
442                            "the message is shorter than its octet count".to_owned(),
443                            rest,
444                        ),
445                    });
446                }
447            }
448            Framing::JsonValues => {
449                let mut stream = serde_json::Deserializer::from_slice(bytes).into_iter::<Value>();
450                let mut start = 0;
451                while let Some(next) = stream.next() {
452                    match next {
453                        Ok(record) => {
454                            let end = stream.byte_offset();
455                            out(self.record(&record, trim(&bytes[start..end])));
456                            start = end;
457                        }
458                        Err(error) => {
459                            // Where one value ends cannot be known once the
460                            // stream is broken, so the rest is kept together.
461                            out(dead(
462                                Stage::Framing,
463                                error.to_string(),
464                                trim(&bytes[start..]),
465                            ));
466                            return;
467                        }
468                    }
469                }
470            }
471        }
472    }
473
474    /// Decodes and normalizes one framed record.
475    fn decoded(&self, raw: &[u8]) -> Outcome {
476        let record = match self.decoding {
477            Decoding::Json => {
478                serde_json::from_slice::<Value>(raw).map_err(|error| error.to_string())
479            }
480            Decoding::Auditd => auditd::decode(raw),
481            Decoding::Syslog => syslog::decode(raw, syslog::Message::Text, jiff::Timestamp::now),
482            Decoding::SyslogJson => {
483                syslog::decode(raw, syslog::Message::Json, jiff::Timestamp::now)
484            }
485        };
486        match record {
487            Ok(record) => self.record(&record, raw),
488            Err(error) => dead(Stage::Decoding, error, raw),
489        }
490    }
491
492    /// Normalizes one decoded record, whose raw bytes are `raw`.
493    fn record(&self, record: &Value, raw: &[u8]) -> Outcome {
494        if !record.is_object() {
495            return dead(
496                Stage::Decoding,
497                "the record is not a JSON object".to_owned(),
498                raw,
499            );
500        }
501        let Some(kind) = self.kinds.iter().find(|kind| {
502            kind.when
503                .iter()
504                .all(|(path, expected)| path.lookup(record) == Some(expected))
505        }) else {
506            return dead(
507                Stage::Mapping,
508                format!("no kind of source `{}` accepts the record", self.name),
509                raw,
510            );
511        };
512
513        let mut event = Map::new();
514        let mut unmapped = Map::new();
515        let mut issues = Vec::new();
516        let mut consumed: Vec<&SourcePath> = Vec::new();
517        for (name, value) in &kind.class {
518            event.insert((*name).to_owned(), value.clone());
519        }
520        for field in &kind.fields {
521            let path = match &field.source {
522                Source::Constant(value) => {
523                    set(&mut event, field.target.segments(), value.clone());
524                    continue;
525                }
526                Source::Path { path, .. } | Source::Translate { path, .. } => path,
527            };
528            let Some(found) = path.lookup(record).filter(|value| !value.is_null()) else {
529                continue;
530            };
531            consumed.push(path);
532            match field.source.convert(found) {
533                Ok(value) => set(&mut event, field.target.segments(), value),
534                Err(reason) => {
535                    issues.push(Issue {
536                        target: field.target.as_str().to_owned(),
537                        source: path.text.clone(),
538                        reason,
539                    });
540                    // Kept by the name the `unmapped` lists would give it, or
541                    // by its whole path where they give none, so that it
542                    // cannot take another member's name.
543                    let name = kind
544                        .unmapped
545                        .iter()
546                        .find_map(|object| path.member_of(object))
547                        .unwrap_or_else(|| path.text.clone());
548                    unmapped.insert(name, found.clone());
549                }
550            }
551        }
552        for object in &kind.unmapped {
553            let Some(Value::Object(members)) = object.lookup(record) else {
554                continue;
555            };
556            for (key, member) in members {
557                if member.is_null() || consumed.iter().any(|path| path.is_member(object, key)) {
558                    continue;
559                }
560                // A name an earlier object already gave is qualified with
561                // this object's path, so that neither value is lost.
562                let name = if unmapped.contains_key(key) {
563                    format!("{}.{key}", object.text)
564                } else {
565                    key.clone()
566                };
567                unmapped.entry(name).or_insert_with(|| member.clone());
568            }
569        }
570        if !unmapped.is_empty() {
571            event.insert("unmapped".to_owned(), Value::Object(unmapped));
572        }
573        Outcome::Event(Normalized {
574            id: EventId::of(&self.name, raw),
575            event: Value::Object(event),
576            kind: kind.name.clone(),
577            issues,
578        })
579    }
580}
581
582fn dead(stage: Stage, error: String, raw: &[u8]) -> Outcome {
583    Outcome::DeadLetter(DeadLetter {
584        stage,
585        error,
586        raw: raw.to_vec(),
587    })
588}
589
590fn trim(bytes: &[u8]) -> &[u8] {
591    let start = bytes
592        .iter()
593        .position(|byte| !byte.is_ascii_whitespace())
594        .unwrap_or(bytes.len());
595    let end = bytes
596        .iter()
597        .rposition(|byte| !byte.is_ascii_whitespace())
598        .map_or(start, |position| position + 1);
599    &bytes[start..end]
600}
601
602fn source_path(kind: &str, text: &str) -> Result<SourcePath, DefinitionError> {
603    SourcePath::parse(text).ok_or_else(|| DefinitionError::SourcePath {
604        kind: kind.to_owned(),
605        path: text.to_owned(),
606    })
607}
608
609fn compile_fields(
610    kind: &str,
611    specs: &std::collections::BTreeMap<String, FieldSpec>,
612) -> Result<Vec<Field>, DefinitionError> {
613    specs
614        .iter()
615        .map(|(target, spec)| {
616            let path = FieldPath::parse(target).map_err(|source| DefinitionError::Target {
617                kind: kind.to_owned(),
618                target: target.clone(),
619                source,
620            })?;
621            let reserved = match path.segments()[0].as_str() {
622                "class_uid" | "category_uid" | "type_uid" | "activity_id" => {
623                    Some("the kind's `class`")
624                }
625                "unmapped" => Some("the kind's `unmapped` list"),
626                _ => None,
627            };
628            if let Some(reason) = reserved {
629                return Err(DefinitionError::Reserved {
630                    kind: kind.to_owned(),
631                    target: target.clone(),
632                    reason,
633                });
634            }
635            let source = match spec {
636                FieldSpec::Path(from) => Source::Path {
637                    path: source_path(kind, from)?,
638                    coercion: None,
639                },
640                FieldSpec::Converted { from, coercion } => Source::Path {
641                    path: source_path(kind, from)?,
642                    coercion: Some(*coercion),
643                },
644                FieldSpec::Translated {
645                    from,
646                    map,
647                    otherwise,
648                } => {
649                    let invalid = |reason| DefinitionError::Translation {
650                        kind: kind.to_owned(),
651                        target: target.clone(),
652                        reason,
653                    };
654                    let mut values = map.values().chain(otherwise).map(Value::from);
655                    let first = values.next().ok_or_else(|| invalid("is empty"))?;
656                    if values.any(|value| Writes::of(&value) != Writes::of(&first)) {
657                        return Err(invalid("mixes values of different types"));
658                    }
659                    Source::Translate {
660                        path: source_path(kind, from)?,
661                        map: map
662                            .iter()
663                            .map(|(key, value)| (key.clone(), Value::from(value)))
664                            .collect(),
665                        otherwise: otherwise.as_ref().map(Value::from),
666                    }
667                }
668                FieldSpec::Value { value } => Source::Constant(Value::from(value)),
669            };
670            Ok(Field {
671                target: path,
672                source,
673            })
674        })
675        .collect()
676}
677
678/// Rejects two fields writing the same attribute, or one inside another:
679/// the second write would replace or be lost under the first.
680fn check_overlaps(kind: &str, fields: &[Field]) -> Result<(), DefinitionError> {
681    for (index, first) in fields.iter().enumerate() {
682        for second in &fields[index + 1..] {
683            let (a, b) = (first.target.segments(), second.target.segments());
684            if a.starts_with(b) || b.starts_with(a) {
685                return Err(DefinitionError::Overlap {
686                    kind: kind.to_owned(),
687                    first: first.target.as_str().to_owned(),
688                    second: second.target.as_str().to_owned(),
689                });
690            }
691        }
692    }
693    Ok(())
694}
695
696/// Checks the class, the activity, and every field against the OCSF schema,
697/// so that a misspelled attribute fails here rather than produce events no
698/// rule reads.
699fn check_schema(
700    kind: &str,
701    class_uid: u32,
702    activity_id: u32,
703    fields: &[Field],
704) -> Result<(), DefinitionError> {
705    let class = schema::class(class_uid).ok_or_else(|| DefinitionError::UnknownClass {
706        kind: kind.to_owned(),
707        class_uid,
708        version: goliath_ocsf::SCHEMA_VERSION,
709    })?;
710    let activities = class
711        .attribute("activity_id")
712        .map(schema::Attribute::enum_values)
713        .unwrap_or_default();
714    if !activities.contains(&i64::from(activity_id)) {
715        return Err(DefinitionError::UnknownActivity {
716            kind: kind.to_owned(),
717            class: class.name(),
718            activity_id,
719        });
720    }
721    for field in fields {
722        let target = field.target.as_str();
723        let found = class
724            .resolve(target)
725            .map_err(|source| DefinitionError::Attribute {
726                kind: kind.to_owned(),
727                source,
728            })?;
729        if found.within_array {
730            return Err(DefinitionError::WithinArray {
731                kind: kind.to_owned(),
732                target: target.to_owned(),
733            });
734        }
735        // A copy keeps whatever the source holds, and a free-form attribute
736        // takes anything, so neither has a type to check.
737        let Some(writes) = field.source.writes() else {
738            continue;
739        };
740        if found.free_form {
741            continue;
742        }
743        let attribute = found.attribute;
744        let fits = !attribute.is_array()
745            && match writes {
746                Writes::Boolean => attribute.base() == Base::Boolean,
747                Writes::Integer => matches!(attribute.base(), Base::Integer | Base::Long),
748                Writes::Text => attribute.base() == Base::String,
749                Writes::Timestamp => attribute.type_name() == "timestamp_t",
750            };
751        if !fits {
752            let holds = match (attribute.is_array(), attribute.base()) {
753                (true, _) => format!("an array of `{}`", attribute.type_name()),
754                (false, Base::Object) => format!("an object `{}`", attribute.type_name()),
755                (false, _) => format!("`{}`", attribute.type_name()),
756            };
757            return Err(DefinitionError::Type {
758                kind: kind.to_owned(),
759                target: target.to_owned(),
760                holds,
761                writes: writes.describe(),
762            });
763        }
764        let values = attribute.enum_values();
765        let unknown = field
766            .source
767            .constants()
768            .filter_map(Value::as_i64)
769            .find(|value| !values.is_empty() && !values.contains(value));
770        if let Some(value) = unknown {
771            return Err(DefinitionError::UnknownValue {
772                kind: kind.to_owned(),
773                target: target.to_owned(),
774                value,
775            });
776        }
777    }
778    Ok(())
779}
780
781/// What a field writes, where that is known before any record is read.
782#[derive(Debug, Clone, Copy, PartialEq, Eq)]
783enum Writes {
784    Boolean,
785    Integer,
786    Text,
787    Timestamp,
788}
789
790impl Writes {
791    /// What writing `value` writes; nothing known for a list or an object.
792    fn of(value: &Value) -> Option<Self> {
793        match value {
794            Value::Bool(_) => Some(Self::Boolean),
795            Value::Number(_) => Some(Self::Integer),
796            Value::String(_) => Some(Self::Text),
797            _ => None,
798        }
799    }
800
801    fn describe(self) -> &'static str {
802        match self {
803            Self::Boolean => "a boolean",
804            Self::Integer => "an integer",
805            Self::Text => "text",
806            Self::Timestamp => "a timestamp",
807        }
808    }
809}
810
811impl Source {
812    fn writes(&self) -> Option<Writes> {
813        match self {
814            Self::Constant(value) => Writes::of(value),
815            // Every value of a table has the same type, checked when it is
816            // compiled.
817            Self::Translate { map, .. } => map.values().next().and_then(Writes::of),
818            Self::Path { coercion: None, .. } => None,
819            Self::Path {
820                coercion: Some(coercion),
821                ..
822            } => Some(match coercion {
823                Coercion::String => Writes::Text,
824                Coercion::Integer => Writes::Integer,
825                Coercion::Timestamp | Coercion::UnixSeconds => Writes::Timestamp,
826            }),
827        }
828    }
829}
830
831impl Source {
832    /// Every value this source can write that is fixed by the definition.
833    fn constants(&self) -> impl Iterator<Item = &Value> {
834        let (map, extra) = match self {
835            Self::Constant(value) => (None, Some(value)),
836            Self::Translate { map, otherwise, .. } => (Some(map), otherwise.as_ref()),
837            Self::Path { .. } => (None, None),
838        };
839        map.into_iter().flat_map(BTreeMap::values).chain(extra)
840    }
841
842    /// The value to write for `found`, or why there is none.
843    fn convert(&self, found: &Value) -> Result<Value, String> {
844        match self {
845            Self::Constant(value) => Ok(value.clone()),
846            Self::Path { coercion, .. } => coerce(found, *coercion),
847            Self::Translate { map, otherwise, .. } => {
848                let key = match found {
849                    Value::String(text) => text.clone(),
850                    Value::Number(_) | Value::Bool(_) => found.to_string(),
851                    other => return Err(format!("cannot translate {}", describe(other))),
852                };
853                map.get(&key)
854                    .or(otherwise.as_ref())
855                    .cloned()
856                    .ok_or_else(|| format!("`{key}` is not in the translation table"))
857            }
858        }
859    }
860}
861
862/// Writes `value` at `segments`, creating objects on the way. Overlapping
863/// targets are rejected when the definition is compiled, so the way is
864/// always clear.
865fn set(object: &mut Map<String, Value>, segments: &[String], value: Value) {
866    let Some((last, parents)) = segments.split_last() else {
867        return;
868    };
869    let mut object = object;
870    for segment in parents {
871        let child = object
872            .entry(segment.clone())
873            .or_insert_with(|| Value::Object(Map::new()));
874        let Value::Object(child) = child else {
875            return;
876        };
877        object = child;
878    }
879    object.insert(last.clone(), value);
880}
881
882fn coerce(value: &Value, coercion: Option<Coercion>) -> Result<Value, String> {
883    let Some(coercion) = coercion else {
884        return Ok(value.clone());
885    };
886    match (coercion, value) {
887        (Coercion::String, Value::String(_)) => Ok(value.clone()),
888        (Coercion::String, Value::Number(number)) => Ok(Value::String(number.to_string())),
889        (Coercion::Integer, Value::Number(number)) => number
890            .as_i64()
891            .map(Value::from)
892            .ok_or_else(|| format!("{number} is not a whole number")),
893        (Coercion::Integer, Value::String(text)) => text
894            .trim()
895            .parse::<i64>()
896            .map(Value::from)
897            .map_err(|_| format!("`{text}` is not a whole number")),
898        (Coercion::Timestamp, Value::String(text)) => text
899            .parse::<jiff::Timestamp>()
900            .map(|time| Value::from(time.as_millisecond()))
901            .map_err(|error| format!("`{text}` is not an RFC 3339 time: {error}")),
902        (Coercion::UnixSeconds, Value::String(text)) => unix_seconds(text),
903        (Coercion::UnixSeconds, Value::Number(number)) => unix_seconds(&number.to_string()),
904        (coercion, other) => Err(format!(
905            "cannot convert {} to {coercion:?}",
906            describe(other)
907        )),
908    }
909}
910
911/// Seconds since the epoch, such as `1727251200.123`, as milliseconds.
912fn unix_seconds(text: &str) -> Result<Value, String> {
913    let invalid = || format!("`{text}` is not a count of seconds since 1970");
914    let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
915    let digits = |part: &str| part.bytes().all(|byte| byte.is_ascii_digit());
916    if whole.is_empty() || !digits(whole) || !digits(fraction) {
917        return Err(invalid());
918    }
919    let seconds: i64 = whole.parse().map_err(|_| invalid())?;
920    let millis: i64 = format!("{:0<3}", &fraction[..fraction.len().min(3)])
921        .parse()
922        .map_err(|_| invalid())?;
923    seconds
924        .checked_mul(1000)
925        .and_then(|milliseconds| milliseconds.checked_add(millis))
926        .map(Value::from)
927        .ok_or_else(invalid)
928}
929
930fn describe(value: &Value) -> &'static str {
931    match value {
932        Value::Null => "null",
933        Value::Bool(_) => "a boolean",
934        Value::Number(_) => "a number",
935        Value::String(_) => "text",
936        Value::Array(_) => "a list",
937        Value::Object(_) => "an object",
938    }
939}