1use goliath_rule::FieldPath;
4use serde_json::{Map, Value};
5
6use crate::definition::{Coercion, Decoding, FieldSpec, Framing, SourceDefinition};
7use crate::error::DefinitionError;
8
9#[derive(Debug, Clone)]
15pub struct Normalizer {
16 name: String,
17 version: u32,
18 framing: Framing,
19 kinds: Vec<Kind>,
20}
21
22#[derive(Debug, Clone)]
23struct Kind {
24 name: String,
25 when: Vec<(SourcePath, Value)>,
26 class: Vec<(&'static str, Value)>,
28 fields: Vec<Field>,
30 unmapped: Vec<SourcePath>,
31}
32
33#[derive(Debug, Clone)]
34struct Field {
35 target: FieldPath,
36 source: Source,
37}
38
39#[derive(Debug, Clone)]
40enum Source {
41 Constant(Value),
42 Path {
43 path: SourcePath,
44 coercion: Option<Coercion>,
45 },
46}
47
48#[derive(Debug, Clone, PartialEq, Eq)]
51struct SourcePath {
52 text: String,
53 segments: Vec<String>,
54}
55
56impl SourcePath {
57 fn parse(text: &str) -> Option<Self> {
58 let segments: Vec<String> = text.split('.').map(str::to_owned).collect();
59 segments
60 .iter()
61 .all(|segment| !segment.is_empty())
62 .then(|| Self {
63 text: text.to_owned(),
64 segments,
65 })
66 }
67
68 fn lookup<'a>(&self, record: &'a Value) -> Option<&'a Value> {
69 self.segments
70 .iter()
71 .try_fold(record, |value, segment| value.get(segment.as_str()))
72 }
73
74 fn is_member(&self, object: &Self, key: &str) -> bool {
76 self.segments.len() == object.segments.len() + 1
77 && self.segments.starts_with(&object.segments)
78 && self.segments.last().is_some_and(|last| last == key)
79 }
80
81 fn last(&self) -> &str {
82 self.segments.last().map_or("", String::as_str)
83 }
84}
85
86#[non_exhaustive]
88#[derive(Debug, Clone, PartialEq)]
89pub enum Outcome {
90 Event(Normalized),
92 DeadLetter(DeadLetter),
94}
95
96#[non_exhaustive]
98#[derive(Debug, Clone, PartialEq)]
99pub struct Normalized {
100 pub event: Value,
102 pub kind: String,
104 pub issues: Vec<Issue>,
108}
109
110#[non_exhaustive]
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct Issue {
114 pub target: String,
116 pub source: String,
118 pub reason: String,
120}
121
122#[non_exhaustive]
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct DeadLetter {
129 pub stage: Stage,
131 pub error: String,
133 pub raw: Vec<u8>,
136}
137
138#[non_exhaustive]
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum Stage {
142 Framing,
144 Decoding,
146 Mapping,
148}
149
150impl Stage {
151 pub fn as_str(self) -> &'static str {
153 match self {
154 Self::Framing => "framing",
155 Self::Decoding => "decoding",
156 Self::Mapping => "mapping",
157 }
158 }
159}
160
161impl Normalizer {
162 pub fn from_yaml(text: &str) -> Result<Self, DefinitionError> {
168 let definition: SourceDefinition = goliath_sigma::yaml::from_str(text)?;
169 Self::new(&definition)
170 }
171
172 pub fn new(definition: &SourceDefinition) -> Result<Self, DefinitionError> {
180 if definition.kinds.is_empty() {
181 return Err(DefinitionError::NoKinds);
182 }
183 let common = compile_fields("common", &definition.common)?;
184 let mut kinds = Vec::with_capacity(definition.kinds.len());
185 for kind in &definition.kinds {
186 if kind.when.is_empty() {
187 return Err(DefinitionError::Unconditional {
188 kind: kind.name.clone(),
189 });
190 }
191 let when = kind
192 .when
193 .iter()
194 .map(|(path, value)| Ok((source_path(&kind.name, path)?, Value::from(value))))
195 .collect::<Result<_, DefinitionError>>()?;
196 let mut fields = common.clone();
197 fields.extend(compile_fields(&kind.name, &kind.fields)?);
198 check_overlaps(&kind.name, &fields)?;
199 let unmapped = kind
200 .unmapped
201 .iter()
202 .map(|path| source_path(&kind.name, path))
203 .collect::<Result<_, _>>()?;
204
205 let class_uid = kind.class.class_uid;
206 let activity_id = kind.class.activity_id;
207 let category_uid = goliath_ocsf::Event::derive_category_uid(class_uid);
208 let type_uid = goliath_ocsf::Event::derive_type_uid(class_uid, activity_id);
209 kinds.push(Kind {
210 name: kind.name.clone(),
211 when,
212 class: vec![
213 ("class_uid", Value::from(class_uid)),
214 ("category_uid", Value::from(category_uid)),
215 ("type_uid", Value::from(type_uid)),
216 ("activity_id", Value::from(activity_id)),
217 ],
218 fields,
219 unmapped,
220 });
221 }
222 match definition.decoding {
225 Decoding::Json => {}
226 }
227 Ok(Self {
228 name: definition.name.clone(),
229 version: definition.version,
230 framing: definition.framing,
231 kinds,
232 })
233 }
234
235 pub fn name(&self) -> &str {
237 &self.name
238 }
239
240 pub fn version(&self) -> u32 {
242 self.version
243 }
244
245 pub fn normalize(&self, bytes: &[u8], mut out: impl FnMut(Outcome)) {
248 match self.framing {
249 Framing::Lines => {
250 for line in bytes.split(|&byte| byte == b'\n') {
251 let line = line.strip_suffix(b"\r").unwrap_or(line);
252 if line.iter().all(u8::is_ascii_whitespace) {
253 continue;
254 }
255 out(match serde_json::from_slice::<Value>(line) {
256 Ok(record) => self.record(&record, line),
257 Err(error) => dead(Stage::Decoding, error.to_string(), line),
258 });
259 }
260 }
261 Framing::JsonValues => {
262 let mut stream = serde_json::Deserializer::from_slice(bytes).into_iter::<Value>();
263 let mut start = 0;
264 while let Some(next) = stream.next() {
265 match next {
266 Ok(record) => {
267 let end = stream.byte_offset();
268 out(self.record(&record, trim(&bytes[start..end])));
269 start = end;
270 }
271 Err(error) => {
272 out(dead(
275 Stage::Framing,
276 error.to_string(),
277 trim(&bytes[start..]),
278 ));
279 return;
280 }
281 }
282 }
283 }
284 }
285 }
286
287 fn record(&self, record: &Value, raw: &[u8]) -> Outcome {
289 if !record.is_object() {
290 return dead(
291 Stage::Decoding,
292 "the record is not a JSON object".to_owned(),
293 raw,
294 );
295 }
296 let Some(kind) = self.kinds.iter().find(|kind| {
297 kind.when
298 .iter()
299 .all(|(path, expected)| path.lookup(record) == Some(expected))
300 }) else {
301 return dead(
302 Stage::Mapping,
303 format!("no kind of source `{}` accepts the record", self.name),
304 raw,
305 );
306 };
307
308 let mut event = Map::new();
309 let mut unmapped = Map::new();
310 let mut issues = Vec::new();
311 let mut consumed: Vec<&SourcePath> = Vec::new();
312 for (name, value) in &kind.class {
313 event.insert((*name).to_owned(), value.clone());
314 }
315 for field in &kind.fields {
316 match &field.source {
317 Source::Constant(value) => set(&mut event, field.target.segments(), value.clone()),
318 Source::Path { path, coercion } => {
319 let Some(found) = path.lookup(record).filter(|value| !value.is_null()) else {
320 continue;
321 };
322 consumed.push(path);
323 match coerce(found, *coercion) {
324 Ok(value) => set(&mut event, field.target.segments(), value),
325 Err(reason) => {
326 issues.push(Issue {
327 target: field.target.as_str().to_owned(),
328 source: path.text.clone(),
329 reason,
330 });
331 let listed = kind
335 .unmapped
336 .iter()
337 .any(|object| path.is_member(object, path.last()));
338 let name = if listed { path.last() } else { &path.text };
339 unmapped.insert(name.to_owned(), found.clone());
340 }
341 }
342 }
343 }
344 }
345 for object in &kind.unmapped {
346 let Some(Value::Object(members)) = object.lookup(record) else {
347 continue;
348 };
349 for (key, member) in members {
350 if member.is_null() || consumed.iter().any(|path| path.is_member(object, key)) {
351 continue;
352 }
353 unmapped
354 .entry(key.clone())
355 .or_insert_with(|| member.clone());
356 }
357 }
358 if !unmapped.is_empty() {
359 event.insert("unmapped".to_owned(), Value::Object(unmapped));
360 }
361 Outcome::Event(Normalized {
362 event: Value::Object(event),
363 kind: kind.name.clone(),
364 issues,
365 })
366 }
367}
368
369fn dead(stage: Stage, error: String, raw: &[u8]) -> Outcome {
370 Outcome::DeadLetter(DeadLetter {
371 stage,
372 error,
373 raw: raw.to_vec(),
374 })
375}
376
377fn trim(bytes: &[u8]) -> &[u8] {
378 let start = bytes
379 .iter()
380 .position(|byte| !byte.is_ascii_whitespace())
381 .unwrap_or(bytes.len());
382 let end = bytes
383 .iter()
384 .rposition(|byte| !byte.is_ascii_whitespace())
385 .map_or(start, |position| position + 1);
386 &bytes[start..end]
387}
388
389fn source_path(kind: &str, text: &str) -> Result<SourcePath, DefinitionError> {
390 SourcePath::parse(text).ok_or_else(|| DefinitionError::SourcePath {
391 kind: kind.to_owned(),
392 path: text.to_owned(),
393 })
394}
395
396fn compile_fields(
397 kind: &str,
398 specs: &std::collections::BTreeMap<String, FieldSpec>,
399) -> Result<Vec<Field>, DefinitionError> {
400 specs
401 .iter()
402 .map(|(target, spec)| {
403 let path = FieldPath::parse(target).map_err(|source| DefinitionError::Target {
404 kind: kind.to_owned(),
405 target: target.clone(),
406 source,
407 })?;
408 let reserved = match path.segments()[0].as_str() {
409 "class_uid" | "category_uid" | "type_uid" | "activity_id" => {
410 Some("the kind's `class`")
411 }
412 "unmapped" => Some("the kind's `unmapped` list"),
413 _ => None,
414 };
415 if let Some(reason) = reserved {
416 return Err(DefinitionError::Reserved {
417 kind: kind.to_owned(),
418 target: target.clone(),
419 reason,
420 });
421 }
422 let source = match spec {
423 FieldSpec::Path(from) => Source::Path {
424 path: source_path(kind, from)?,
425 coercion: None,
426 },
427 FieldSpec::Converted { from, coercion } => Source::Path {
428 path: source_path(kind, from)?,
429 coercion: Some(*coercion),
430 },
431 FieldSpec::Value { value } => Source::Constant(Value::from(value)),
432 };
433 Ok(Field {
434 target: path,
435 source,
436 })
437 })
438 .collect()
439}
440
441fn check_overlaps(kind: &str, fields: &[Field]) -> Result<(), DefinitionError> {
444 for (index, first) in fields.iter().enumerate() {
445 for second in &fields[index + 1..] {
446 let (a, b) = (first.target.segments(), second.target.segments());
447 if a.starts_with(b) || b.starts_with(a) {
448 return Err(DefinitionError::Overlap {
449 kind: kind.to_owned(),
450 first: first.target.as_str().to_owned(),
451 second: second.target.as_str().to_owned(),
452 });
453 }
454 }
455 }
456 Ok(())
457}
458
459fn set(object: &mut Map<String, Value>, segments: &[String], value: Value) {
463 let Some((last, parents)) = segments.split_last() else {
464 return;
465 };
466 let mut object = object;
467 for segment in parents {
468 let child = object
469 .entry(segment.clone())
470 .or_insert_with(|| Value::Object(Map::new()));
471 let Value::Object(child) = child else {
472 return;
473 };
474 object = child;
475 }
476 object.insert(last.clone(), value);
477}
478
479fn coerce(value: &Value, coercion: Option<Coercion>) -> Result<Value, String> {
480 let Some(coercion) = coercion else {
481 return Ok(value.clone());
482 };
483 match (coercion, value) {
484 (Coercion::String, Value::String(_)) => Ok(value.clone()),
485 (Coercion::String, Value::Number(number)) => Ok(Value::String(number.to_string())),
486 (Coercion::Integer, Value::Number(number)) => number
487 .as_i64()
488 .map(Value::from)
489 .ok_or_else(|| format!("{number} is not a whole number")),
490 (Coercion::Integer, Value::String(text)) => text
491 .trim()
492 .parse::<i64>()
493 .map(Value::from)
494 .map_err(|_| format!("`{text}` is not a whole number")),
495 (Coercion::Timestamp, Value::String(text)) => text
496 .parse::<jiff::Timestamp>()
497 .map(|time| Value::from(time.as_millisecond()))
498 .map_err(|error| format!("`{text}` is not an RFC 3339 time: {error}")),
499 (coercion, other) => Err(format!(
500 "cannot convert {} to {coercion:?}",
501 describe(other)
502 )),
503 }
504}
505
506fn describe(value: &Value) -> &'static str {
507 match value {
508 Value::Null => "null",
509 Value::Bool(_) => "a boolean",
510 Value::Number(_) => "a number",
511 Value::String(_) => "text",
512 Value::Array(_) => "a list",
513 Value::Object(_) => "an object",
514 }
515}