1use 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#[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 data_components: Vec<String>,
29}
30
31#[derive(Debug, Clone)]
32struct Kind {
33 name: String,
34 when: Vec<(SourcePath, Value)>,
35 class: Vec<(&'static str, Value)>,
37 fields: Vec<Field>,
39 unmapped: Vec<SourcePath>,
40}
41
42#[derive(Debug, Clone)]
43struct Field {
44 target: FieldPath,
45 source: Source,
46}
47
48#[derive(Debug, Clone)]
49enum Source {
50 Constant(Value),
51 Path {
52 path: SourcePath,
53 coercion: Option<Coercion>,
54 },
55 Translate {
56 path: SourcePath,
57 map: BTreeMap<String, Value>,
58 otherwise: Option<Value>,
59 },
60}
61
62#[derive(Debug, Clone, PartialEq, Eq)]
73struct SourcePath {
74 text: String,
75 segments: Vec<String>,
76}
77
78impl SourcePath {
79 fn parse(text: &str) -> Option<Self> {
80 let segments: Vec<String> = text.split('.').map(str::to_owned).collect();
81 segments
82 .iter()
83 .all(|segment| !segment.is_empty())
84 .then(|| Self {
85 text: text.to_owned(),
86 segments,
87 })
88 }
89
90 fn lookup<'a>(&self, record: &'a Value) -> Option<&'a Value> {
91 find(record, &self.segments)
92 }
93
94 fn member_of(&self, object: &Self) -> Option<String> {
97 (self.segments.len() > object.segments.len() && self.segments.starts_with(&object.segments))
98 .then(|| self.segments[object.segments.len()..].join("."))
99 }
100
101 fn is_member(&self, object: &Self, key: &str) -> bool {
103 self.member_of(object).is_some_and(|member| member == key)
104 }
105}
106
107fn find<'a>(value: &'a Value, segments: &[String]) -> Option<&'a Value> {
108 if segments.is_empty() {
109 return Some(value);
110 }
111 if let Some(items) = value.as_array() {
112 let index: usize = segments[0].parse().ok()?;
113 return find(items.get(index)?, &segments[1..]);
114 }
115 let object = value.as_object()?;
116 let mut name = String::new();
117 for (index, segment) in segments.iter().enumerate() {
118 if index > 0 {
119 name.push('.');
120 }
121 name.push_str(segment);
122 if let Some(found) = object
123 .get(&name)
124 .and_then(|member| find(member, &segments[index + 1..]))
125 {
126 return Some(found);
127 }
128 }
129 None
130}
131
132#[non_exhaustive]
134#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
135#[serde(rename_all = "snake_case")]
136pub enum Outcome {
137 Event(Normalized),
139 DeadLetter(DeadLetter),
141}
142
143#[non_exhaustive]
145#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
146pub struct Normalized {
147 pub id: EventId,
150 pub event: Value,
152 pub kind: String,
154 pub issues: Vec<Issue>,
158}
159
160#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
172pub struct EventId([u8; 16]);
173
174impl EventId {
175 const CONTEXT: &str = "goliath 2026-09-25 event id";
178
179 pub fn of(source: &str, raw: &[u8]) -> Self {
181 let mut hasher = blake3::Hasher::new_derive_key(Self::CONTEXT);
182 hasher.update(&(source.len() as u64).to_le_bytes());
185 hasher.update(source.as_bytes());
186 hasher.update(raw);
187 let mut id = [0; 16];
188 hasher.finalize_xof().fill(&mut id);
189 Self(id)
190 }
191
192 pub fn as_bytes(&self) -> &[u8; 16] {
194 &self.0
195 }
196}
197
198impl std::fmt::Display for EventId {
199 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201 self.0.iter().try_for_each(|byte| write!(f, "{byte:02x}"))
202 }
203}
204
205impl std::str::FromStr for EventId {
206 type Err = String;
207
208 fn from_str(text: &str) -> Result<Self, Self::Err> {
212 let invalid = || format!("`{text}` is not 32 hexadecimal digits");
213 if text.len() != 32 {
214 return Err(invalid());
215 }
216 let mut id = [0; 16];
217 let (pairs, _) = text.as_bytes().as_chunks::<2>();
218 for (byte, pair) in id.iter_mut().zip(pairs) {
219 let pair = std::str::from_utf8(pair).map_err(|_| invalid())?;
220 *byte = u8::from_str_radix(pair, 16).map_err(|_| invalid())?;
221 }
222 Ok(Self(id))
223 }
224}
225
226impl Serialize for EventId {
228 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
229 serializer.collect_str(self)
230 }
231}
232
233impl<'de> Deserialize<'de> for EventId {
234 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
235 let text = String::deserialize(deserializer)?;
236 text.parse().map_err(serde::de::Error::custom)
237 }
238}
239
240impl std::fmt::Debug for EventId {
241 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
242 write!(f, "EventId({self})")
243 }
244}
245
246#[non_exhaustive]
248#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
249pub struct Issue {
250 pub target: String,
252 pub source: String,
254 pub reason: String,
256}
257
258#[non_exhaustive]
263#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
264pub struct DeadLetter {
265 pub stage: Stage,
267 pub error: String,
269 pub raw: Vec<u8>,
272}
273
274#[non_exhaustive]
276#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
277#[serde(rename_all = "snake_case")]
278pub enum Stage {
279 Framing,
281 Decoding,
283 Mapping,
285}
286
287impl Stage {
288 pub fn as_str(self) -> &'static str {
290 match self {
291 Self::Framing => "framing",
292 Self::Decoding => "decoding",
293 Self::Mapping => "mapping",
294 }
295 }
296}
297
298impl Normalizer {
299 pub fn from_yaml(text: &str) -> Result<Self, DefinitionError> {
305 let definition: SourceDefinition = goliath_sigma::yaml::from_str(text)?;
306 Self::new(&definition)
307 }
308
309 pub fn new(definition: &SourceDefinition) -> Result<Self, DefinitionError> {
319 if definition.kinds.is_empty() {
320 return Err(DefinitionError::NoKinds);
321 }
322 let common = compile_fields("common", &definition.common)?;
323 let mut kinds = Vec::with_capacity(definition.kinds.len());
324 for kind in &definition.kinds {
325 if kind.when.is_empty() {
326 return Err(DefinitionError::Unconditional {
327 kind: kind.name.clone(),
328 });
329 }
330 let when = kind
331 .when
332 .iter()
333 .map(|(path, value)| Ok((source_path(&kind.name, path)?, Value::from(value))))
334 .collect::<Result<_, DefinitionError>>()?;
335 let mut fields = common.clone();
336 fields.extend(compile_fields(&kind.name, &kind.fields)?);
337 check_overlaps(&kind.name, &fields)?;
338 check_schema(
339 &kind.name,
340 kind.class.class_uid,
341 kind.class.activity_id,
342 &fields,
343 )?;
344 let unmapped = kind
345 .unmapped
346 .iter()
347 .map(|path| {
348 if path == "." {
351 Ok(SourcePath {
352 text: path.clone(),
353 segments: Vec::new(),
354 })
355 } else {
356 source_path(&kind.name, path)
357 }
358 })
359 .collect::<Result<_, _>>()?;
360
361 let class_uid = kind.class.class_uid;
362 let activity_id = kind.class.activity_id;
363 let category_uid = goliath_ocsf::Event::derive_category_uid(class_uid);
364 let type_uid = goliath_ocsf::Event::derive_type_uid(class_uid, activity_id);
365 kinds.push(Kind {
366 name: kind.name.clone(),
367 when,
368 class: vec![
369 ("class_uid", Value::from(class_uid)),
370 ("category_uid", Value::from(category_uid)),
371 ("type_uid", Value::from(type_uid)),
372 ("activity_id", Value::from(activity_id)),
373 ],
374 fields,
375 unmapped,
376 });
377 }
378 let fits = match definition.framing {
379 Framing::Lines => true,
380 Framing::JsonValues => definition.decoding == Decoding::Json,
381 Framing::AuditEvents => definition.decoding == Decoding::Auditd,
382 Framing::Syslog => {
383 matches!(definition.decoding, Decoding::Syslog | Decoding::SyslogJson)
384 }
385 };
386 if !fits {
387 return Err(DefinitionError::Decoding {
388 framing: match definition.framing {
389 Framing::Lines => "lines",
390 Framing::JsonValues => "json-values",
391 Framing::AuditEvents => "audit-events",
392 Framing::Syslog => "syslog",
393 },
394 decoding: match definition.decoding {
395 Decoding::Json => "json",
396 Decoding::Auditd => "auditd",
397 Decoding::Syslog => "syslog",
398 Decoding::SyslogJson => "syslog-json",
399 },
400 });
401 }
402 Ok(Self {
403 name: definition.name.clone(),
404 version: definition.version,
405 framing: definition.framing,
406 decoding: definition.decoding,
407 kinds,
408 nil: definition
409 .nil
410 .iter()
411 .map(|text| Value::from(text.as_str()))
412 .collect(),
413 unwrap: definition.unwrap.clone(),
414 data_components: definition.data_components.clone(),
415 })
416 }
417
418 pub fn name(&self) -> &str {
420 &self.name
421 }
422
423 pub fn data_components(&self) -> &[String] {
426 &self.data_components
427 }
428
429 pub fn framing(&self) -> Framing {
431 self.framing
432 }
433
434 pub fn version(&self) -> u32 {
436 self.version
437 }
438
439 pub fn normalize(&self, bytes: &[u8], mut out: impl FnMut(Outcome)) {
442 match self.framing {
443 Framing::Lines => {
444 for line in bytes.split(|&byte| byte == b'\n') {
445 let line = line.strip_suffix(b"\r").unwrap_or(line);
446 if line.iter().all(u8::is_ascii_whitespace) {
447 continue;
448 }
449 self.decoded(line, &mut out);
450 }
451 }
452 Framing::AuditEvents => {
453 for event in auditd::events(bytes) {
454 match event {
455 Ok(raw) => self.decoded(&raw, &mut out),
456 Err(line) => out(dead(
457 Stage::Framing,
458 "the line names no audit event".to_owned(),
459 line,
460 )),
461 }
462 }
463 }
464 Framing::Syslog => {
465 for message in syslog::messages(bytes) {
466 match message {
467 Ok(raw) => self.decoded(raw, &mut out),
468 Err(rest) => out(dead(
469 Stage::Framing,
470 "the message is shorter than its octet count".to_owned(),
471 rest,
472 )),
473 }
474 }
475 }
476 Framing::JsonValues => {
477 let mut stream = serde_json::Deserializer::from_slice(bytes).into_iter::<Value>();
478 let mut start = 0;
479 while let Some(next) = stream.next() {
480 match next {
481 Ok(record) => {
482 let end = stream.byte_offset();
483 self.records(&record, trim(&bytes[start..end]), &mut out);
484 start = end;
485 }
486 Err(error) => {
487 out(dead(
490 Stage::Framing,
491 error.to_string(),
492 trim(&bytes[start..]),
493 ));
494 return;
495 }
496 }
497 }
498 }
499 }
500 }
501
502 fn decoded(&self, raw: &[u8], out: &mut impl FnMut(Outcome)) {
504 let record = match self.decoding {
505 Decoding::Json => {
506 serde_json::from_slice::<Value>(raw).map_err(|error| error.to_string())
507 }
508 Decoding::Auditd => auditd::decode(raw),
509 Decoding::Syslog => syslog::decode(raw, syslog::Message::Text, jiff::Timestamp::now),
510 Decoding::SyslogJson => {
511 syslog::decode(raw, syslog::Message::Json, jiff::Timestamp::now)
512 }
513 };
514 match record {
515 Ok(record) => self.records(&record, raw, out),
516 Err(error) => out(dead(Stage::Decoding, error, raw)),
517 }
518 }
519
520 fn records(&self, record: &Value, raw: &[u8], out: &mut impl FnMut(Outcome)) {
523 let batch = self.unwrap.as_ref().and_then(|member| {
524 if member == "." {
525 return record.as_array();
526 }
527 let object = record.as_object().filter(|object| object.len() == 1)?;
528 object.get(member)?.as_array()
529 });
530 match batch {
531 Some(items) => {
532 for item in items {
533 let bytes = serde_json::to_vec(item).unwrap_or_default();
534 out(self.record(item, &bytes));
535 }
536 }
537 None => out(self.record(record, raw)),
538 }
539 }
540
541 fn record(&self, record: &Value, raw: &[u8]) -> Outcome {
543 if !record.is_object() {
544 return dead(
545 Stage::Decoding,
546 "the record is not a JSON object".to_owned(),
547 raw,
548 );
549 }
550 let Some(kind) = self.kinds.iter().find(|kind| {
551 kind.when
552 .iter()
553 .all(|(path, expected)| path.lookup(record) == Some(expected))
554 }) else {
555 return dead(
556 Stage::Mapping,
557 format!("no kind of source `{}` accepts the record", self.name),
558 raw,
559 );
560 };
561
562 let mut event = Map::new();
563 let mut unmapped = Map::new();
564 let mut issues = Vec::new();
565 let mut consumed: Vec<&SourcePath> = Vec::new();
566 for (name, value) in &kind.class {
567 event.insert((*name).to_owned(), value.clone());
568 }
569 for field in &kind.fields {
570 let path = match &field.source {
571 Source::Constant(value) => {
572 set(&mut event, field.target.segments(), value.clone());
573 continue;
574 }
575 Source::Path { path, .. } | Source::Translate { path, .. } => path,
576 };
577 let Some(found) = path
578 .lookup(record)
579 .filter(|value| !value.is_null() && !self.nil.contains(value))
580 else {
581 continue;
582 };
583 consumed.push(path);
584 match field.source.convert(found) {
585 Ok(value) => set(&mut event, field.target.segments(), value),
586 Err(reason) => {
587 issues.push(Issue {
588 target: field.target.as_str().to_owned(),
589 source: path.text.clone(),
590 reason,
591 });
592 let name = kind
596 .unmapped
597 .iter()
598 .find_map(|object| path.member_of(object))
599 .unwrap_or_else(|| path.text.clone());
600 unmapped.insert(name, found.clone());
601 }
602 }
603 }
604 for object in &kind.unmapped {
605 let Some(Value::Object(members)) = object.lookup(record) else {
606 continue;
607 };
608 for (key, member) in members {
609 if member.is_null() || consumed.iter().any(|path| path.is_member(object, key)) {
610 continue;
611 }
612 let name = if unmapped.contains_key(key) {
615 format!("{}.{key}", object.text)
616 } else {
617 key.clone()
618 };
619 unmapped.entry(name).or_insert_with(|| member.clone());
620 }
621 }
622 if !unmapped.is_empty() {
623 event.insert("unmapped".to_owned(), Value::Object(unmapped));
624 }
625 Outcome::Event(Normalized {
626 id: EventId::of(&self.name, raw),
627 event: Value::Object(event),
628 kind: kind.name.clone(),
629 issues,
630 })
631 }
632}
633
634fn dead(stage: Stage, error: String, raw: &[u8]) -> Outcome {
635 Outcome::DeadLetter(DeadLetter {
636 stage,
637 error,
638 raw: raw.to_vec(),
639 })
640}
641
642fn trim(bytes: &[u8]) -> &[u8] {
643 let start = bytes
644 .iter()
645 .position(|byte| !byte.is_ascii_whitespace())
646 .unwrap_or(bytes.len());
647 let end = bytes
648 .iter()
649 .rposition(|byte| !byte.is_ascii_whitespace())
650 .map_or(start, |position| position + 1);
651 &bytes[start..end]
652}
653
654fn source_path(kind: &str, text: &str) -> Result<SourcePath, DefinitionError> {
655 SourcePath::parse(text).ok_or_else(|| DefinitionError::SourcePath {
656 kind: kind.to_owned(),
657 path: text.to_owned(),
658 })
659}
660
661fn compile_fields(
662 kind: &str,
663 specs: &std::collections::BTreeMap<String, FieldSpec>,
664) -> Result<Vec<Field>, DefinitionError> {
665 specs
666 .iter()
667 .map(|(target, spec)| {
668 let path = FieldPath::parse(target).map_err(|source| DefinitionError::Target {
669 kind: kind.to_owned(),
670 target: target.clone(),
671 source,
672 })?;
673 let reserved = match path.segments()[0].as_str() {
674 "class_uid" | "category_uid" | "type_uid" | "activity_id" => {
675 Some("the kind's `class`")
676 }
677 "unmapped" => Some("the kind's `unmapped` list"),
678 _ => None,
679 };
680 if let Some(reason) = reserved {
681 return Err(DefinitionError::Reserved {
682 kind: kind.to_owned(),
683 target: target.clone(),
684 reason,
685 });
686 }
687 let source = match spec {
688 FieldSpec::Path(from) => Source::Path {
689 path: source_path(kind, from)?,
690 coercion: None,
691 },
692 FieldSpec::Converted { from, coercion } => Source::Path {
693 path: source_path(kind, from)?,
694 coercion: Some(*coercion),
695 },
696 FieldSpec::Translated {
697 from,
698 map,
699 otherwise,
700 } => {
701 let invalid = |reason| DefinitionError::Translation {
702 kind: kind.to_owned(),
703 target: target.clone(),
704 reason,
705 };
706 let mut values = map.values().chain(otherwise).map(Value::from);
707 let first = values.next().ok_or_else(|| invalid("is empty"))?;
708 if values.any(|value| Writes::of(&value) != Writes::of(&first)) {
709 return Err(invalid("mixes values of different types"));
710 }
711 Source::Translate {
712 path: source_path(kind, from)?,
713 map: map
714 .iter()
715 .map(|(key, value)| (key.clone(), Value::from(value)))
716 .collect(),
717 otherwise: otherwise.as_ref().map(Value::from),
718 }
719 }
720 FieldSpec::Value { value } => Source::Constant(Value::from(value)),
721 };
722 Ok(Field {
723 target: path,
724 source,
725 })
726 })
727 .collect()
728}
729
730fn check_overlaps(kind: &str, fields: &[Field]) -> Result<(), DefinitionError> {
733 for (index, first) in fields.iter().enumerate() {
734 for second in &fields[index + 1..] {
735 let (a, b) = (first.target.segments(), second.target.segments());
736 if a.starts_with(b) || b.starts_with(a) {
737 return Err(DefinitionError::Overlap {
738 kind: kind.to_owned(),
739 first: first.target.as_str().to_owned(),
740 second: second.target.as_str().to_owned(),
741 });
742 }
743 }
744 }
745 Ok(())
746}
747
748fn check_schema(
752 kind: &str,
753 class_uid: u32,
754 activity_id: u32,
755 fields: &[Field],
756) -> Result<(), DefinitionError> {
757 let class = schema::class(class_uid).ok_or_else(|| DefinitionError::UnknownClass {
758 kind: kind.to_owned(),
759 class_uid,
760 version: goliath_ocsf::SCHEMA_VERSION,
761 })?;
762 let activities = class
763 .attribute("activity_id")
764 .map(schema::Attribute::enum_values)
765 .unwrap_or_default();
766 if !activities.contains(&i64::from(activity_id)) {
767 return Err(DefinitionError::UnknownActivity {
768 kind: kind.to_owned(),
769 class: class.name(),
770 activity_id,
771 });
772 }
773 for field in fields {
774 let target = field.target.as_str();
775 let named = attribute_path(kind, class, field.target.segments())?;
776 let found = class
777 .resolve(&named)
778 .map_err(|source| DefinitionError::Attribute {
779 kind: kind.to_owned(),
780 source,
781 })?;
782 let Some(writes) = field.source.writes() else {
785 continue;
786 };
787 if found.free_form {
788 continue;
789 }
790 let attribute = found.attribute;
791 let fits = !attribute.is_array()
792 && match writes {
793 Writes::Boolean => attribute.base() == Base::Boolean,
794 Writes::Integer => matches!(attribute.base(), Base::Integer | Base::Long),
795 Writes::Text => attribute.base() == Base::String,
796 Writes::Timestamp => attribute.type_name() == "timestamp_t",
797 Writes::Ip => attribute.type_name() == "ip_t",
798 };
799 if !fits {
800 let holds = match (attribute.is_array(), attribute.base()) {
801 (true, _) => format!("an array of `{}`", attribute.type_name()),
802 (false, Base::Object) => format!("an object `{}`", attribute.type_name()),
803 (false, _) => format!("`{}`", attribute.type_name()),
804 };
805 return Err(DefinitionError::Type {
806 kind: kind.to_owned(),
807 target: target.to_owned(),
808 holds,
809 writes: writes.describe(),
810 });
811 }
812 let values = attribute.enum_values();
813 let unknown = field
814 .source
815 .constants()
816 .filter_map(Value::as_i64)
817 .find(|value| !values.is_empty() && !values.contains(value));
818 if let Some(value) = unknown {
819 return Err(DefinitionError::UnknownValue {
820 kind: kind.to_owned(),
821 target: target.to_owned(),
822 value,
823 });
824 }
825 }
826 Ok(())
827}
828
829fn attribute_path(
834 kind: &str,
835 class: &schema::Class,
836 segments: &[String],
837) -> Result<String, DefinitionError> {
838 let target = || segments.join(".");
839 let is_index = |segment: &str| segment.bytes().all(|byte| byte.is_ascii_digit());
840 let mut named = String::new();
841 for (position, segment) in segments.iter().enumerate() {
842 if is_index(segment) && !named.is_empty() {
844 let array = class
845 .resolve(&named)
846 .is_ok_and(|found| found.attribute.is_array());
847 if !array {
848 return Err(DefinitionError::NotAnArray {
849 kind: kind.to_owned(),
850 target: target(),
851 attribute: named,
852 });
853 }
854 continue;
855 }
856 if !named.is_empty() {
857 named.push('.');
858 }
859 named.push_str(segment);
860 let continues = segments
861 .get(position + 1)
862 .is_some_and(|next| !is_index(next));
863 if continues
864 && class
865 .resolve(&named)
866 .is_ok_and(|found| found.attribute.is_array() && !found.free_form)
867 {
868 return Err(DefinitionError::WithinArray {
869 kind: kind.to_owned(),
870 target: target(),
871 });
872 }
873 }
874 Ok(named)
875}
876
877#[derive(Debug, Clone, Copy, PartialEq, Eq)]
879enum Writes {
880 Boolean,
881 Integer,
882 Text,
883 Timestamp,
884 Ip,
885}
886
887impl Writes {
888 fn of(value: &Value) -> Option<Self> {
890 match value {
891 Value::Bool(_) => Some(Self::Boolean),
892 Value::Number(_) => Some(Self::Integer),
893 Value::String(_) => Some(Self::Text),
894 _ => None,
895 }
896 }
897
898 fn describe(self) -> &'static str {
899 match self {
900 Self::Boolean => "a boolean",
901 Self::Integer => "an integer",
902 Self::Text => "text",
903 Self::Timestamp => "a timestamp",
904 Self::Ip => "an IP address",
905 }
906 }
907}
908
909impl Source {
910 fn writes(&self) -> Option<Writes> {
911 match self {
912 Self::Constant(value) => Writes::of(value),
913 Self::Translate { map, .. } => map.values().next().and_then(Writes::of),
916 Self::Path { coercion: None, .. } => None,
917 Self::Path {
918 coercion: Some(coercion),
919 ..
920 } => Some(match coercion {
921 Coercion::String => Writes::Text,
922 Coercion::Integer => Writes::Integer,
923 Coercion::Timestamp | Coercion::UtcTimestamp | Coercion::UnixSeconds => {
924 Writes::Timestamp
925 }
926 Coercion::Ip => Writes::Ip,
927 }),
928 }
929 }
930}
931
932impl Source {
933 fn constants(&self) -> impl Iterator<Item = &Value> {
935 let (map, extra) = match self {
936 Self::Constant(value) => (None, Some(value)),
937 Self::Translate { map, otherwise, .. } => (Some(map), otherwise.as_ref()),
938 Self::Path { .. } => (None, None),
939 };
940 map.into_iter().flat_map(BTreeMap::values).chain(extra)
941 }
942
943 fn convert(&self, found: &Value) -> Result<Value, String> {
945 match self {
946 Self::Constant(value) => Ok(value.clone()),
947 Self::Path { coercion, .. } => coerce(found, *coercion),
948 Self::Translate { map, otherwise, .. } => {
949 let key = match found {
950 Value::String(text) => text.clone(),
951 Value::Number(_) | Value::Bool(_) => found.to_string(),
952 other => return Err(format!("cannot translate {}", describe(other))),
953 };
954 map.get(&key)
955 .or(otherwise.as_ref())
956 .cloned()
957 .ok_or_else(|| format!("`{key}` is not in the translation table"))
958 }
959 }
960 }
961}
962
963fn set(object: &mut Map<String, Value>, segments: &[String], value: Value) {
968 let Some((first, rest)) = segments.split_first() else {
969 return;
970 };
971 if rest.is_empty() {
972 object.insert(first.clone(), value);
973 return;
974 }
975 set_within(
976 object.entry(first.clone()).or_insert(Value::Null),
977 rest,
978 value,
979 );
980}
981
982fn set_within(slot: &mut Value, segments: &[String], value: Value) {
983 let Some((first, rest)) = segments.split_first() else {
984 *slot = value;
985 return;
986 };
987 if let Ok(index) = first.parse::<usize>() {
988 if slot.is_null() {
989 *slot = Value::Array(Vec::new());
990 }
991 let Value::Array(items) = slot else {
992 return;
993 };
994 if items.len() <= index {
995 items.resize(index + 1, Value::Object(Map::new()));
996 }
997 set_within(&mut items[index], rest, value);
998 } else {
999 if slot.is_null() {
1000 *slot = Value::Object(Map::new());
1001 }
1002 let Value::Object(object) = slot else {
1003 return;
1004 };
1005 set_within(
1006 object.entry(first.clone()).or_insert(Value::Null),
1007 rest,
1008 value,
1009 );
1010 }
1011}
1012
1013fn coerce(value: &Value, coercion: Option<Coercion>) -> Result<Value, String> {
1014 let Some(coercion) = coercion else {
1015 return Ok(value.clone());
1016 };
1017 match (coercion, value) {
1018 (Coercion::String, Value::String(_)) => Ok(value.clone()),
1019 (Coercion::String, Value::Number(number)) => Ok(Value::String(number.to_string())),
1020 (Coercion::Integer, Value::Number(number)) => number
1021 .as_i64()
1022 .map(Value::from)
1023 .ok_or_else(|| format!("{number} is not a whole number")),
1024 (Coercion::Integer, Value::String(text)) => {
1025 let trimmed = text.trim();
1026 match trimmed
1027 .strip_prefix("0x")
1028 .or_else(|| trimmed.strip_prefix("0X"))
1029 {
1030 Some(digits) => i64::from_str_radix(digits, 16),
1031 None => trimmed.parse::<i64>(),
1032 }
1033 .map(Value::from)
1034 .map_err(|_| format!("`{text}` is not a whole number"))
1035 }
1036 (Coercion::Timestamp, Value::String(text)) => text
1037 .parse::<jiff::Timestamp>()
1038 .map(|time| Value::from(time.as_millisecond()))
1039 .map_err(|error| format!("`{text}` is not an RFC 3339 time: {error}")),
1040 (Coercion::UtcTimestamp, Value::String(text)) => utc_timestamp(text),
1041 (Coercion::UnixSeconds, Value::String(text)) => unix_seconds(text),
1042 (Coercion::Ip, Value::String(text)) => text
1043 .trim()
1044 .parse::<std::net::IpAddr>()
1045 .map(|_| value.clone())
1046 .map_err(|_| format!("`{text}` is not an IP address")),
1047 (Coercion::UnixSeconds, Value::Number(number)) => unix_seconds(&number.to_string()),
1048 (coercion, other) => Err(format!(
1049 "cannot convert {} to {coercion:?}",
1050 describe(other)
1051 )),
1052 }
1053}
1054
1055fn utc_timestamp(text: &str) -> Result<Value, String> {
1058 if let Ok(time) = text.parse::<jiff::Timestamp>() {
1059 return Ok(Value::from(time.as_millisecond()));
1060 }
1061 text.parse::<jiff::civil::DateTime>()
1062 .and_then(|time| time.to_zoned(jiff::tz::TimeZone::UTC))
1063 .map(|time| Value::from(time.timestamp().as_millisecond()))
1064 .map_err(|error| format!("`{text}` is not an RFC 3339 time: {error}"))
1065}
1066
1067fn unix_seconds(text: &str) -> Result<Value, String> {
1069 let invalid = || format!("`{text}` is not a count of seconds since 1970");
1070 let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
1071 let digits = |part: &str| part.bytes().all(|byte| byte.is_ascii_digit());
1072 if whole.is_empty() || !digits(whole) || !digits(fraction) {
1073 return Err(invalid());
1074 }
1075 let seconds: i64 = whole.parse().map_err(|_| invalid())?;
1076 let millis: i64 = format!("{:0<3}", &fraction[..fraction.len().min(3)])
1077 .parse()
1078 .map_err(|_| invalid())?;
1079 seconds
1080 .checked_mul(1000)
1081 .and_then(|milliseconds| milliseconds.checked_add(millis))
1082 .map(Value::from)
1083 .ok_or_else(invalid)
1084}
1085
1086fn describe(value: &Value) -> &'static str {
1087 match value {
1088 Value::Null => "null",
1089 Value::Bool(_) => "a boolean",
1090 Value::Number(_) => "a number",
1091 Value::String(_) => "text",
1092 Value::Array(_) => "a list",
1093 Value::Object(_) => "an object",
1094 }
1095}