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}
27
28#[derive(Debug, Clone)]
29struct Kind {
30 name: String,
31 when: Vec<(SourcePath, Value)>,
32 class: Vec<(&'static str, Value)>,
34 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#[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 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 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#[non_exhaustive]
124#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
125#[serde(rename_all = "snake_case")]
126pub enum Outcome {
127 Event(Normalized),
129 DeadLetter(DeadLetter),
131}
132
133#[non_exhaustive]
135#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
136pub struct Normalized {
137 pub id: EventId,
140 pub event: Value,
142 pub kind: String,
144 pub issues: Vec<Issue>,
148}
149
150#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
162pub struct EventId([u8; 16]);
163
164impl EventId {
165 const CONTEXT: &str = "goliath 2026-09-25 event id";
168
169 pub fn of(source: &str, raw: &[u8]) -> Self {
171 let mut hasher = blake3::Hasher::new_derive_key(Self::CONTEXT);
172 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 pub fn as_bytes(&self) -> &[u8; 16] {
184 &self.0
185 }
186}
187
188impl std::fmt::Display for EventId {
189 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 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
216impl 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#[non_exhaustive]
238#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
239pub struct Issue {
240 pub target: String,
242 pub source: String,
244 pub reason: String,
246}
247
248#[non_exhaustive]
253#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
254pub struct DeadLetter {
255 pub stage: Stage,
257 pub error: String,
259 pub raw: Vec<u8>,
262}
263
264#[non_exhaustive]
266#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
267#[serde(rename_all = "snake_case")]
268pub enum Stage {
269 Framing,
271 Decoding,
273 Mapping,
275}
276
277impl Stage {
278 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 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 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 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 pub fn name(&self) -> &str {
403 &self.name
404 }
405
406 pub fn version(&self) -> u32 {
408 self.version
409 }
410
411 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 out(dead(
462 Stage::Framing,
463 error.to_string(),
464 trim(&bytes[start..]),
465 ));
466 return;
467 }
468 }
469 }
470 }
471 }
472 }
473
474 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 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 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 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
678fn 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
696fn 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
783enum Writes {
784 Boolean,
785 Integer,
786 Text,
787 Timestamp,
788}
789
790impl Writes {
791 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 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 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 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
862fn 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
911fn 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}