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