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 framing(&self) -> Framing {
408 self.framing
409 }
410
411 pub fn version(&self) -> u32 {
413 self.version
414 }
415
416 pub fn normalize(&self, bytes: &[u8], mut out: impl FnMut(Outcome)) {
419 match self.framing {
420 Framing::Lines => {
421 for line in bytes.split(|&byte| byte == b'\n') {
422 let line = line.strip_suffix(b"\r").unwrap_or(line);
423 if line.iter().all(u8::is_ascii_whitespace) {
424 continue;
425 }
426 out(self.decoded(line));
427 }
428 }
429 Framing::AuditEvents => {
430 for event in auditd::events(bytes) {
431 out(match event {
432 Ok(raw) => self.decoded(&raw),
433 Err(line) => dead(
434 Stage::Framing,
435 "the line names no audit event".to_owned(),
436 line,
437 ),
438 });
439 }
440 }
441 Framing::Syslog => {
442 for message in syslog::messages(bytes) {
443 out(match message {
444 Ok(raw) => self.decoded(raw),
445 Err(rest) => dead(
446 Stage::Framing,
447 "the message is shorter than its octet count".to_owned(),
448 rest,
449 ),
450 });
451 }
452 }
453 Framing::JsonValues => {
454 let mut stream = serde_json::Deserializer::from_slice(bytes).into_iter::<Value>();
455 let mut start = 0;
456 while let Some(next) = stream.next() {
457 match next {
458 Ok(record) => {
459 let end = stream.byte_offset();
460 out(self.record(&record, trim(&bytes[start..end])));
461 start = end;
462 }
463 Err(error) => {
464 out(dead(
467 Stage::Framing,
468 error.to_string(),
469 trim(&bytes[start..]),
470 ));
471 return;
472 }
473 }
474 }
475 }
476 }
477 }
478
479 fn decoded(&self, raw: &[u8]) -> Outcome {
481 let record = match self.decoding {
482 Decoding::Json => {
483 serde_json::from_slice::<Value>(raw).map_err(|error| error.to_string())
484 }
485 Decoding::Auditd => auditd::decode(raw),
486 Decoding::Syslog => syslog::decode(raw, syslog::Message::Text, jiff::Timestamp::now),
487 Decoding::SyslogJson => {
488 syslog::decode(raw, syslog::Message::Json, jiff::Timestamp::now)
489 }
490 };
491 match record {
492 Ok(record) => self.record(&record, raw),
493 Err(error) => dead(Stage::Decoding, error, raw),
494 }
495 }
496
497 fn record(&self, record: &Value, raw: &[u8]) -> Outcome {
499 if !record.is_object() {
500 return dead(
501 Stage::Decoding,
502 "the record is not a JSON object".to_owned(),
503 raw,
504 );
505 }
506 let Some(kind) = self.kinds.iter().find(|kind| {
507 kind.when
508 .iter()
509 .all(|(path, expected)| path.lookup(record) == Some(expected))
510 }) else {
511 return dead(
512 Stage::Mapping,
513 format!("no kind of source `{}` accepts the record", self.name),
514 raw,
515 );
516 };
517
518 let mut event = Map::new();
519 let mut unmapped = Map::new();
520 let mut issues = Vec::new();
521 let mut consumed: Vec<&SourcePath> = Vec::new();
522 for (name, value) in &kind.class {
523 event.insert((*name).to_owned(), value.clone());
524 }
525 for field in &kind.fields {
526 let path = match &field.source {
527 Source::Constant(value) => {
528 set(&mut event, field.target.segments(), value.clone());
529 continue;
530 }
531 Source::Path { path, .. } | Source::Translate { path, .. } => path,
532 };
533 let Some(found) = path.lookup(record).filter(|value| !value.is_null()) else {
534 continue;
535 };
536 consumed.push(path);
537 match field.source.convert(found) {
538 Ok(value) => set(&mut event, field.target.segments(), value),
539 Err(reason) => {
540 issues.push(Issue {
541 target: field.target.as_str().to_owned(),
542 source: path.text.clone(),
543 reason,
544 });
545 let name = kind
549 .unmapped
550 .iter()
551 .find_map(|object| path.member_of(object))
552 .unwrap_or_else(|| path.text.clone());
553 unmapped.insert(name, found.clone());
554 }
555 }
556 }
557 for object in &kind.unmapped {
558 let Some(Value::Object(members)) = object.lookup(record) else {
559 continue;
560 };
561 for (key, member) in members {
562 if member.is_null() || consumed.iter().any(|path| path.is_member(object, key)) {
563 continue;
564 }
565 let name = if unmapped.contains_key(key) {
568 format!("{}.{key}", object.text)
569 } else {
570 key.clone()
571 };
572 unmapped.entry(name).or_insert_with(|| member.clone());
573 }
574 }
575 if !unmapped.is_empty() {
576 event.insert("unmapped".to_owned(), Value::Object(unmapped));
577 }
578 Outcome::Event(Normalized {
579 id: EventId::of(&self.name, raw),
580 event: Value::Object(event),
581 kind: kind.name.clone(),
582 issues,
583 })
584 }
585}
586
587fn dead(stage: Stage, error: String, raw: &[u8]) -> Outcome {
588 Outcome::DeadLetter(DeadLetter {
589 stage,
590 error,
591 raw: raw.to_vec(),
592 })
593}
594
595fn trim(bytes: &[u8]) -> &[u8] {
596 let start = bytes
597 .iter()
598 .position(|byte| !byte.is_ascii_whitespace())
599 .unwrap_or(bytes.len());
600 let end = bytes
601 .iter()
602 .rposition(|byte| !byte.is_ascii_whitespace())
603 .map_or(start, |position| position + 1);
604 &bytes[start..end]
605}
606
607fn source_path(kind: &str, text: &str) -> Result<SourcePath, DefinitionError> {
608 SourcePath::parse(text).ok_or_else(|| DefinitionError::SourcePath {
609 kind: kind.to_owned(),
610 path: text.to_owned(),
611 })
612}
613
614fn compile_fields(
615 kind: &str,
616 specs: &std::collections::BTreeMap<String, FieldSpec>,
617) -> Result<Vec<Field>, DefinitionError> {
618 specs
619 .iter()
620 .map(|(target, spec)| {
621 let path = FieldPath::parse(target).map_err(|source| DefinitionError::Target {
622 kind: kind.to_owned(),
623 target: target.clone(),
624 source,
625 })?;
626 let reserved = match path.segments()[0].as_str() {
627 "class_uid" | "category_uid" | "type_uid" | "activity_id" => {
628 Some("the kind's `class`")
629 }
630 "unmapped" => Some("the kind's `unmapped` list"),
631 _ => None,
632 };
633 if let Some(reason) = reserved {
634 return Err(DefinitionError::Reserved {
635 kind: kind.to_owned(),
636 target: target.clone(),
637 reason,
638 });
639 }
640 let source = match spec {
641 FieldSpec::Path(from) => Source::Path {
642 path: source_path(kind, from)?,
643 coercion: None,
644 },
645 FieldSpec::Converted { from, coercion } => Source::Path {
646 path: source_path(kind, from)?,
647 coercion: Some(*coercion),
648 },
649 FieldSpec::Translated {
650 from,
651 map,
652 otherwise,
653 } => {
654 let invalid = |reason| DefinitionError::Translation {
655 kind: kind.to_owned(),
656 target: target.clone(),
657 reason,
658 };
659 let mut values = map.values().chain(otherwise).map(Value::from);
660 let first = values.next().ok_or_else(|| invalid("is empty"))?;
661 if values.any(|value| Writes::of(&value) != Writes::of(&first)) {
662 return Err(invalid("mixes values of different types"));
663 }
664 Source::Translate {
665 path: source_path(kind, from)?,
666 map: map
667 .iter()
668 .map(|(key, value)| (key.clone(), Value::from(value)))
669 .collect(),
670 otherwise: otherwise.as_ref().map(Value::from),
671 }
672 }
673 FieldSpec::Value { value } => Source::Constant(Value::from(value)),
674 };
675 Ok(Field {
676 target: path,
677 source,
678 })
679 })
680 .collect()
681}
682
683fn check_overlaps(kind: &str, fields: &[Field]) -> Result<(), DefinitionError> {
686 for (index, first) in fields.iter().enumerate() {
687 for second in &fields[index + 1..] {
688 let (a, b) = (first.target.segments(), second.target.segments());
689 if a.starts_with(b) || b.starts_with(a) {
690 return Err(DefinitionError::Overlap {
691 kind: kind.to_owned(),
692 first: first.target.as_str().to_owned(),
693 second: second.target.as_str().to_owned(),
694 });
695 }
696 }
697 }
698 Ok(())
699}
700
701fn check_schema(
705 kind: &str,
706 class_uid: u32,
707 activity_id: u32,
708 fields: &[Field],
709) -> Result<(), DefinitionError> {
710 let class = schema::class(class_uid).ok_or_else(|| DefinitionError::UnknownClass {
711 kind: kind.to_owned(),
712 class_uid,
713 version: goliath_ocsf::SCHEMA_VERSION,
714 })?;
715 let activities = class
716 .attribute("activity_id")
717 .map(schema::Attribute::enum_values)
718 .unwrap_or_default();
719 if !activities.contains(&i64::from(activity_id)) {
720 return Err(DefinitionError::UnknownActivity {
721 kind: kind.to_owned(),
722 class: class.name(),
723 activity_id,
724 });
725 }
726 for field in fields {
727 let target = field.target.as_str();
728 let found = class
729 .resolve(target)
730 .map_err(|source| DefinitionError::Attribute {
731 kind: kind.to_owned(),
732 source,
733 })?;
734 if found.within_array {
735 return Err(DefinitionError::WithinArray {
736 kind: kind.to_owned(),
737 target: target.to_owned(),
738 });
739 }
740 let Some(writes) = field.source.writes() else {
743 continue;
744 };
745 if found.free_form {
746 continue;
747 }
748 let attribute = found.attribute;
749 let fits = !attribute.is_array()
750 && match writes {
751 Writes::Boolean => attribute.base() == Base::Boolean,
752 Writes::Integer => matches!(attribute.base(), Base::Integer | Base::Long),
753 Writes::Text => attribute.base() == Base::String,
754 Writes::Timestamp => attribute.type_name() == "timestamp_t",
755 };
756 if !fits {
757 let holds = match (attribute.is_array(), attribute.base()) {
758 (true, _) => format!("an array of `{}`", attribute.type_name()),
759 (false, Base::Object) => format!("an object `{}`", attribute.type_name()),
760 (false, _) => format!("`{}`", attribute.type_name()),
761 };
762 return Err(DefinitionError::Type {
763 kind: kind.to_owned(),
764 target: target.to_owned(),
765 holds,
766 writes: writes.describe(),
767 });
768 }
769 let values = attribute.enum_values();
770 let unknown = field
771 .source
772 .constants()
773 .filter_map(Value::as_i64)
774 .find(|value| !values.is_empty() && !values.contains(value));
775 if let Some(value) = unknown {
776 return Err(DefinitionError::UnknownValue {
777 kind: kind.to_owned(),
778 target: target.to_owned(),
779 value,
780 });
781 }
782 }
783 Ok(())
784}
785
786#[derive(Debug, Clone, Copy, PartialEq, Eq)]
788enum Writes {
789 Boolean,
790 Integer,
791 Text,
792 Timestamp,
793}
794
795impl Writes {
796 fn of(value: &Value) -> Option<Self> {
798 match value {
799 Value::Bool(_) => Some(Self::Boolean),
800 Value::Number(_) => Some(Self::Integer),
801 Value::String(_) => Some(Self::Text),
802 _ => None,
803 }
804 }
805
806 fn describe(self) -> &'static str {
807 match self {
808 Self::Boolean => "a boolean",
809 Self::Integer => "an integer",
810 Self::Text => "text",
811 Self::Timestamp => "a timestamp",
812 }
813 }
814}
815
816impl Source {
817 fn writes(&self) -> Option<Writes> {
818 match self {
819 Self::Constant(value) => Writes::of(value),
820 Self::Translate { map, .. } => map.values().next().and_then(Writes::of),
823 Self::Path { coercion: None, .. } => None,
824 Self::Path {
825 coercion: Some(coercion),
826 ..
827 } => Some(match coercion {
828 Coercion::String => Writes::Text,
829 Coercion::Integer => Writes::Integer,
830 Coercion::Timestamp | Coercion::UnixSeconds => Writes::Timestamp,
831 }),
832 }
833 }
834}
835
836impl Source {
837 fn constants(&self) -> impl Iterator<Item = &Value> {
839 let (map, extra) = match self {
840 Self::Constant(value) => (None, Some(value)),
841 Self::Translate { map, otherwise, .. } => (Some(map), otherwise.as_ref()),
842 Self::Path { .. } => (None, None),
843 };
844 map.into_iter().flat_map(BTreeMap::values).chain(extra)
845 }
846
847 fn convert(&self, found: &Value) -> Result<Value, String> {
849 match self {
850 Self::Constant(value) => Ok(value.clone()),
851 Self::Path { coercion, .. } => coerce(found, *coercion),
852 Self::Translate { map, otherwise, .. } => {
853 let key = match found {
854 Value::String(text) => text.clone(),
855 Value::Number(_) | Value::Bool(_) => found.to_string(),
856 other => return Err(format!("cannot translate {}", describe(other))),
857 };
858 map.get(&key)
859 .or(otherwise.as_ref())
860 .cloned()
861 .ok_or_else(|| format!("`{key}` is not in the translation table"))
862 }
863 }
864 }
865}
866
867fn set(object: &mut Map<String, Value>, segments: &[String], value: Value) {
871 let Some((last, parents)) = segments.split_last() else {
872 return;
873 };
874 let mut object = object;
875 for segment in parents {
876 let child = object
877 .entry(segment.clone())
878 .or_insert_with(|| Value::Object(Map::new()));
879 let Value::Object(child) = child else {
880 return;
881 };
882 object = child;
883 }
884 object.insert(last.clone(), value);
885}
886
887fn coerce(value: &Value, coercion: Option<Coercion>) -> Result<Value, String> {
888 let Some(coercion) = coercion else {
889 return Ok(value.clone());
890 };
891 match (coercion, value) {
892 (Coercion::String, Value::String(_)) => Ok(value.clone()),
893 (Coercion::String, Value::Number(number)) => Ok(Value::String(number.to_string())),
894 (Coercion::Integer, Value::Number(number)) => number
895 .as_i64()
896 .map(Value::from)
897 .ok_or_else(|| format!("{number} is not a whole number")),
898 (Coercion::Integer, Value::String(text)) => text
899 .trim()
900 .parse::<i64>()
901 .map(Value::from)
902 .map_err(|_| format!("`{text}` is not a whole number")),
903 (Coercion::Timestamp, Value::String(text)) => text
904 .parse::<jiff::Timestamp>()
905 .map(|time| Value::from(time.as_millisecond()))
906 .map_err(|error| format!("`{text}` is not an RFC 3339 time: {error}")),
907 (Coercion::UnixSeconds, Value::String(text)) => unix_seconds(text),
908 (Coercion::UnixSeconds, Value::Number(number)) => unix_seconds(&number.to_string()),
909 (coercion, other) => Err(format!(
910 "cannot convert {} to {coercion:?}",
911 describe(other)
912 )),
913 }
914}
915
916fn unix_seconds(text: &str) -> Result<Value, String> {
918 let invalid = || format!("`{text}` is not a count of seconds since 1970");
919 let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
920 let digits = |part: &str| part.bytes().all(|byte| byte.is_ascii_digit());
921 if whole.is_empty() || !digits(whole) || !digits(fraction) {
922 return Err(invalid());
923 }
924 let seconds: i64 = whole.parse().map_err(|_| invalid())?;
925 let millis: i64 = format!("{:0<3}", &fraction[..fraction.len().min(3)])
926 .parse()
927 .map_err(|_| invalid())?;
928 seconds
929 .checked_mul(1000)
930 .and_then(|milliseconds| milliseconds.checked_add(millis))
931 .map(Value::from)
932 .ok_or_else(invalid)
933}
934
935fn describe(value: &Value) -> &'static str {
936 match value {
937 Value::Null => "null",
938 Value::Bool(_) => "a boolean",
939 Value::Number(_) => "a number",
940 Value::String(_) => "text",
941 Value::Array(_) => "a list",
942 Value::Object(_) => "an object",
943 }
944}