1use goliath_ocsf::schema::{self, Base};
4use goliath_rule::FieldPath;
5use serde_json::{Map, Value};
6
7use crate::definition::{Coercion, Decoding, FieldSpec, Framing, SourceDefinition};
8use crate::error::DefinitionError;
9
10#[derive(Debug, Clone)]
16pub struct Normalizer {
17 name: String,
18 version: u32,
19 framing: Framing,
20 kinds: Vec<Kind>,
21}
22
23#[derive(Debug, Clone)]
24struct Kind {
25 name: String,
26 when: Vec<(SourcePath, Value)>,
27 class: Vec<(&'static str, Value)>,
29 fields: Vec<Field>,
31 unmapped: Vec<SourcePath>,
32}
33
34#[derive(Debug, Clone)]
35struct Field {
36 target: FieldPath,
37 source: Source,
38}
39
40#[derive(Debug, Clone)]
41enum Source {
42 Constant(Value),
43 Path {
44 path: SourcePath,
45 coercion: Option<Coercion>,
46 },
47}
48
49#[derive(Debug, Clone, PartialEq, Eq)]
52struct SourcePath {
53 text: String,
54 segments: Vec<String>,
55}
56
57impl SourcePath {
58 fn parse(text: &str) -> Option<Self> {
59 let segments: Vec<String> = text.split('.').map(str::to_owned).collect();
60 segments
61 .iter()
62 .all(|segment| !segment.is_empty())
63 .then(|| Self {
64 text: text.to_owned(),
65 segments,
66 })
67 }
68
69 fn lookup<'a>(&self, record: &'a Value) -> Option<&'a Value> {
70 self.segments
71 .iter()
72 .try_fold(record, |value, segment| value.get(segment.as_str()))
73 }
74
75 fn is_member(&self, object: &Self, key: &str) -> bool {
77 self.segments.len() == object.segments.len() + 1
78 && self.segments.starts_with(&object.segments)
79 && self.segments.last().is_some_and(|last| last == key)
80 }
81
82 fn last(&self) -> &str {
83 self.segments.last().map_or("", String::as_str)
84 }
85}
86
87#[non_exhaustive]
89#[derive(Debug, Clone, PartialEq)]
90pub enum Outcome {
91 Event(Normalized),
93 DeadLetter(DeadLetter),
95}
96
97#[non_exhaustive]
99#[derive(Debug, Clone, PartialEq)]
100pub struct Normalized {
101 pub event: Value,
103 pub kind: String,
105 pub issues: Vec<Issue>,
109}
110
111#[non_exhaustive]
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct Issue {
115 pub target: String,
117 pub source: String,
119 pub reason: String,
121}
122
123#[non_exhaustive]
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct DeadLetter {
130 pub stage: Stage,
132 pub error: String,
134 pub raw: Vec<u8>,
137}
138
139#[non_exhaustive]
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub enum Stage {
143 Framing,
145 Decoding,
147 Mapping,
149}
150
151impl Stage {
152 pub fn as_str(self) -> &'static str {
154 match self {
155 Self::Framing => "framing",
156 Self::Decoding => "decoding",
157 Self::Mapping => "mapping",
158 }
159 }
160}
161
162impl Normalizer {
163 pub fn from_yaml(text: &str) -> Result<Self, DefinitionError> {
169 let definition: SourceDefinition = goliath_sigma::yaml::from_str(text)?;
170 Self::new(&definition)
171 }
172
173 pub fn new(definition: &SourceDefinition) -> Result<Self, DefinitionError> {
183 if definition.kinds.is_empty() {
184 return Err(DefinitionError::NoKinds);
185 }
186 let common = compile_fields("common", &definition.common)?;
187 let mut kinds = Vec::with_capacity(definition.kinds.len());
188 for kind in &definition.kinds {
189 if kind.when.is_empty() {
190 return Err(DefinitionError::Unconditional {
191 kind: kind.name.clone(),
192 });
193 }
194 let when = kind
195 .when
196 .iter()
197 .map(|(path, value)| Ok((source_path(&kind.name, path)?, Value::from(value))))
198 .collect::<Result<_, DefinitionError>>()?;
199 let mut fields = common.clone();
200 fields.extend(compile_fields(&kind.name, &kind.fields)?);
201 check_overlaps(&kind.name, &fields)?;
202 check_schema(
203 &kind.name,
204 kind.class.class_uid,
205 kind.class.activity_id,
206 &fields,
207 )?;
208 let unmapped = kind
209 .unmapped
210 .iter()
211 .map(|path| source_path(&kind.name, path))
212 .collect::<Result<_, _>>()?;
213
214 let class_uid = kind.class.class_uid;
215 let activity_id = kind.class.activity_id;
216 let category_uid = goliath_ocsf::Event::derive_category_uid(class_uid);
217 let type_uid = goliath_ocsf::Event::derive_type_uid(class_uid, activity_id);
218 kinds.push(Kind {
219 name: kind.name.clone(),
220 when,
221 class: vec![
222 ("class_uid", Value::from(class_uid)),
223 ("category_uid", Value::from(category_uid)),
224 ("type_uid", Value::from(type_uid)),
225 ("activity_id", Value::from(activity_id)),
226 ],
227 fields,
228 unmapped,
229 });
230 }
231 match definition.decoding {
234 Decoding::Json => {}
235 }
236 Ok(Self {
237 name: definition.name.clone(),
238 version: definition.version,
239 framing: definition.framing,
240 kinds,
241 })
242 }
243
244 pub fn name(&self) -> &str {
246 &self.name
247 }
248
249 pub fn version(&self) -> u32 {
251 self.version
252 }
253
254 pub fn normalize(&self, bytes: &[u8], mut out: impl FnMut(Outcome)) {
257 match self.framing {
258 Framing::Lines => {
259 for line in bytes.split(|&byte| byte == b'\n') {
260 let line = line.strip_suffix(b"\r").unwrap_or(line);
261 if line.iter().all(u8::is_ascii_whitespace) {
262 continue;
263 }
264 out(match serde_json::from_slice::<Value>(line) {
265 Ok(record) => self.record(&record, line),
266 Err(error) => dead(Stage::Decoding, error.to_string(), line),
267 });
268 }
269 }
270 Framing::JsonValues => {
271 let mut stream = serde_json::Deserializer::from_slice(bytes).into_iter::<Value>();
272 let mut start = 0;
273 while let Some(next) = stream.next() {
274 match next {
275 Ok(record) => {
276 let end = stream.byte_offset();
277 out(self.record(&record, trim(&bytes[start..end])));
278 start = end;
279 }
280 Err(error) => {
281 out(dead(
284 Stage::Framing,
285 error.to_string(),
286 trim(&bytes[start..]),
287 ));
288 return;
289 }
290 }
291 }
292 }
293 }
294 }
295
296 fn record(&self, record: &Value, raw: &[u8]) -> Outcome {
298 if !record.is_object() {
299 return dead(
300 Stage::Decoding,
301 "the record is not a JSON object".to_owned(),
302 raw,
303 );
304 }
305 let Some(kind) = self.kinds.iter().find(|kind| {
306 kind.when
307 .iter()
308 .all(|(path, expected)| path.lookup(record) == Some(expected))
309 }) else {
310 return dead(
311 Stage::Mapping,
312 format!("no kind of source `{}` accepts the record", self.name),
313 raw,
314 );
315 };
316
317 let mut event = Map::new();
318 let mut unmapped = Map::new();
319 let mut issues = Vec::new();
320 let mut consumed: Vec<&SourcePath> = Vec::new();
321 for (name, value) in &kind.class {
322 event.insert((*name).to_owned(), value.clone());
323 }
324 for field in &kind.fields {
325 match &field.source {
326 Source::Constant(value) => set(&mut event, field.target.segments(), value.clone()),
327 Source::Path { path, coercion } => {
328 let Some(found) = path.lookup(record).filter(|value| !value.is_null()) else {
329 continue;
330 };
331 consumed.push(path);
332 match coerce(found, *coercion) {
333 Ok(value) => set(&mut event, field.target.segments(), value),
334 Err(reason) => {
335 issues.push(Issue {
336 target: field.target.as_str().to_owned(),
337 source: path.text.clone(),
338 reason,
339 });
340 let listed = kind
344 .unmapped
345 .iter()
346 .any(|object| path.is_member(object, path.last()));
347 let name = if listed { path.last() } else { &path.text };
348 unmapped.insert(name.to_owned(), found.clone());
349 }
350 }
351 }
352 }
353 }
354 for object in &kind.unmapped {
355 let Some(Value::Object(members)) = object.lookup(record) else {
356 continue;
357 };
358 for (key, member) in members {
359 if member.is_null() || consumed.iter().any(|path| path.is_member(object, key)) {
360 continue;
361 }
362 unmapped
363 .entry(key.clone())
364 .or_insert_with(|| member.clone());
365 }
366 }
367 if !unmapped.is_empty() {
368 event.insert("unmapped".to_owned(), Value::Object(unmapped));
369 }
370 Outcome::Event(Normalized {
371 event: Value::Object(event),
372 kind: kind.name.clone(),
373 issues,
374 })
375 }
376}
377
378fn dead(stage: Stage, error: String, raw: &[u8]) -> Outcome {
379 Outcome::DeadLetter(DeadLetter {
380 stage,
381 error,
382 raw: raw.to_vec(),
383 })
384}
385
386fn trim(bytes: &[u8]) -> &[u8] {
387 let start = bytes
388 .iter()
389 .position(|byte| !byte.is_ascii_whitespace())
390 .unwrap_or(bytes.len());
391 let end = bytes
392 .iter()
393 .rposition(|byte| !byte.is_ascii_whitespace())
394 .map_or(start, |position| position + 1);
395 &bytes[start..end]
396}
397
398fn source_path(kind: &str, text: &str) -> Result<SourcePath, DefinitionError> {
399 SourcePath::parse(text).ok_or_else(|| DefinitionError::SourcePath {
400 kind: kind.to_owned(),
401 path: text.to_owned(),
402 })
403}
404
405fn compile_fields(
406 kind: &str,
407 specs: &std::collections::BTreeMap<String, FieldSpec>,
408) -> Result<Vec<Field>, DefinitionError> {
409 specs
410 .iter()
411 .map(|(target, spec)| {
412 let path = FieldPath::parse(target).map_err(|source| DefinitionError::Target {
413 kind: kind.to_owned(),
414 target: target.clone(),
415 source,
416 })?;
417 let reserved = match path.segments()[0].as_str() {
418 "class_uid" | "category_uid" | "type_uid" | "activity_id" => {
419 Some("the kind's `class`")
420 }
421 "unmapped" => Some("the kind's `unmapped` list"),
422 _ => None,
423 };
424 if let Some(reason) = reserved {
425 return Err(DefinitionError::Reserved {
426 kind: kind.to_owned(),
427 target: target.clone(),
428 reason,
429 });
430 }
431 let source = match spec {
432 FieldSpec::Path(from) => Source::Path {
433 path: source_path(kind, from)?,
434 coercion: None,
435 },
436 FieldSpec::Converted { from, coercion } => Source::Path {
437 path: source_path(kind, from)?,
438 coercion: Some(*coercion),
439 },
440 FieldSpec::Value { value } => Source::Constant(Value::from(value)),
441 };
442 Ok(Field {
443 target: path,
444 source,
445 })
446 })
447 .collect()
448}
449
450fn check_overlaps(kind: &str, fields: &[Field]) -> Result<(), DefinitionError> {
453 for (index, first) in fields.iter().enumerate() {
454 for second in &fields[index + 1..] {
455 let (a, b) = (first.target.segments(), second.target.segments());
456 if a.starts_with(b) || b.starts_with(a) {
457 return Err(DefinitionError::Overlap {
458 kind: kind.to_owned(),
459 first: first.target.as_str().to_owned(),
460 second: second.target.as_str().to_owned(),
461 });
462 }
463 }
464 }
465 Ok(())
466}
467
468fn check_schema(
472 kind: &str,
473 class_uid: u32,
474 activity_id: u32,
475 fields: &[Field],
476) -> Result<(), DefinitionError> {
477 let class = schema::class(class_uid).ok_or_else(|| DefinitionError::UnknownClass {
478 kind: kind.to_owned(),
479 class_uid,
480 version: goliath_ocsf::SCHEMA_VERSION,
481 })?;
482 let activities = class
483 .attribute("activity_id")
484 .map(schema::Attribute::enum_values)
485 .unwrap_or_default();
486 if !activities.contains(&i64::from(activity_id)) {
487 return Err(DefinitionError::UnknownActivity {
488 kind: kind.to_owned(),
489 class: class.name(),
490 activity_id,
491 });
492 }
493 for field in fields {
494 let target = field.target.as_str();
495 let found = class
496 .resolve(target)
497 .map_err(|source| DefinitionError::Attribute {
498 kind: kind.to_owned(),
499 source,
500 })?;
501 if found.within_array {
502 return Err(DefinitionError::WithinArray {
503 kind: kind.to_owned(),
504 target: target.to_owned(),
505 });
506 }
507 let Some(writes) = field.source.writes() else {
510 continue;
511 };
512 if found.free_form {
513 continue;
514 }
515 let attribute = found.attribute;
516 let fits = !attribute.is_array()
517 && match writes {
518 Writes::Boolean => attribute.base() == Base::Boolean,
519 Writes::Integer => matches!(attribute.base(), Base::Integer | Base::Long),
520 Writes::Text => attribute.base() == Base::String,
521 Writes::Timestamp => attribute.type_name() == "timestamp_t",
522 };
523 if !fits {
524 let holds = match (attribute.is_array(), attribute.base()) {
525 (true, _) => format!("an array of `{}`", attribute.type_name()),
526 (false, Base::Object) => format!("an object `{}`", attribute.type_name()),
527 (false, _) => format!("`{}`", attribute.type_name()),
528 };
529 return Err(DefinitionError::Type {
530 kind: kind.to_owned(),
531 target: target.to_owned(),
532 holds,
533 writes: writes.describe(),
534 });
535 }
536 let values = attribute.enum_values();
537 if let Source::Constant(Value::Number(number)) = &field.source
538 && let Some(value) = number.as_i64()
539 && !values.is_empty()
540 && !values.contains(&value)
541 {
542 return Err(DefinitionError::UnknownValue {
543 kind: kind.to_owned(),
544 target: target.to_owned(),
545 value,
546 });
547 }
548 }
549 Ok(())
550}
551
552#[derive(Debug, Clone, Copy)]
554enum Writes {
555 Boolean,
556 Integer,
557 Text,
558 Timestamp,
559}
560
561impl Writes {
562 fn describe(self) -> &'static str {
563 match self {
564 Self::Boolean => "a boolean",
565 Self::Integer => "an integer",
566 Self::Text => "text",
567 Self::Timestamp => "a timestamp",
568 }
569 }
570}
571
572impl Source {
573 fn writes(&self) -> Option<Writes> {
574 match self {
575 Self::Constant(Value::Bool(_)) => Some(Writes::Boolean),
576 Self::Constant(Value::Number(_)) => Some(Writes::Integer),
577 Self::Constant(Value::String(_)) => Some(Writes::Text),
578 Self::Constant(_) | Self::Path { coercion: None, .. } => None,
579 Self::Path {
580 coercion: Some(coercion),
581 ..
582 } => Some(match coercion {
583 Coercion::String => Writes::Text,
584 Coercion::Integer => Writes::Integer,
585 Coercion::Timestamp => Writes::Timestamp,
586 }),
587 }
588 }
589}
590
591fn set(object: &mut Map<String, Value>, segments: &[String], value: Value) {
595 let Some((last, parents)) = segments.split_last() else {
596 return;
597 };
598 let mut object = object;
599 for segment in parents {
600 let child = object
601 .entry(segment.clone())
602 .or_insert_with(|| Value::Object(Map::new()));
603 let Value::Object(child) = child else {
604 return;
605 };
606 object = child;
607 }
608 object.insert(last.clone(), value);
609}
610
611fn coerce(value: &Value, coercion: Option<Coercion>) -> Result<Value, String> {
612 let Some(coercion) = coercion else {
613 return Ok(value.clone());
614 };
615 match (coercion, value) {
616 (Coercion::String, Value::String(_)) => Ok(value.clone()),
617 (Coercion::String, Value::Number(number)) => Ok(Value::String(number.to_string())),
618 (Coercion::Integer, Value::Number(number)) => number
619 .as_i64()
620 .map(Value::from)
621 .ok_or_else(|| format!("{number} is not a whole number")),
622 (Coercion::Integer, Value::String(text)) => text
623 .trim()
624 .parse::<i64>()
625 .map(Value::from)
626 .map_err(|_| format!("`{text}` is not a whole number")),
627 (Coercion::Timestamp, Value::String(text)) => text
628 .parse::<jiff::Timestamp>()
629 .map(|time| Value::from(time.as_millisecond()))
630 .map_err(|error| format!("`{text}` is not an RFC 3339 time: {error}")),
631 (coercion, other) => Err(format!(
632 "cannot convert {} to {coercion:?}",
633 describe(other)
634 )),
635 }
636}
637
638fn describe(value: &Value) -> &'static str {
639 match value {
640 Value::Null => "null",
641 Value::Bool(_) => "a boolean",
642 Value::Number(_) => "a number",
643 Value::String(_) => "text",
644 Value::Array(_) => "a list",
645 Value::Object(_) => "an object",
646 }
647}