goliath_normalize/wire.rs
1//! How outcomes travel between roles.
2//!
3//! Roles exchange bytes, never shared memory
4//! (`docs/adr/0006-deployment-topology.md`), so the normalizer's output is
5//! encoded before it enters a pipe, and every role reading it decodes the
6//! same format. An encoded outcome starts with a byte naming its format, so
7//! that a later, more compact format can be read alongside records already
8//! waiting in a durable pipe.
9
10use serde::{Deserialize, Serialize};
11
12use crate::normalizer::Outcome;
13
14/// The first byte of an outcome encoded as JSON.
15const JSON: u8 = 1;
16
17/// An outcome, and the source definition that produced it.
18#[non_exhaustive]
19#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
20pub struct Envelope {
21 /// The source's name, such as `sysmon`.
22 pub source: String,
23 /// The version of the source definition.
24 pub version: u32,
25 /// What became of the record.
26 pub outcome: Outcome,
27 /// When the platform took the record, in milliseconds since the Unix
28 /// epoch, if the role that took it said. Envelopes written before this
29 /// field existed have none.
30 #[serde(default, skip_serializing_if = "Option::is_none")]
31 pub received: Option<i64>,
32}
33
34/// Bytes that are not an encoded outcome.
35#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
36#[error("not an encoded outcome: {0}")]
37pub struct WireError(String);
38
39impl Envelope {
40 /// An envelope for `outcome` of the source `source` at definition
41 /// version `version`.
42 pub fn new(source: impl Into<String>, version: u32, outcome: Outcome) -> Self {
43 Self {
44 source: source.into(),
45 version,
46 outcome,
47 received: None,
48 }
49 }
50
51 /// The same envelope, saying the platform took its record at
52 /// `received` milliseconds since the Unix epoch.
53 #[must_use]
54 pub fn received_at(mut self, received: i64) -> Self {
55 self.received = Some(received);
56 self
57 }
58
59 /// The envelope as bytes, for a pipe.
60 pub fn encode(&self) -> Vec<u8> {
61 let mut bytes = vec![JSON];
62 // Writing JSON into a vector fails only for a map with non-string
63 // keys, which no outcome contains.
64 if serde_json::to_writer(&mut bytes, self).is_err() {
65 bytes.truncate(1);
66 }
67 bytes
68 }
69
70 /// An envelope from bytes [`encode`](Self::encode) wrote.
71 ///
72 /// # Errors
73 ///
74 /// Returns [`WireError`] if the bytes are in no known format, or do not
75 /// hold an envelope.
76 pub fn decode(bytes: &[u8]) -> Result<Self, WireError> {
77 match bytes.split_first() {
78 Some((&JSON, json)) => {
79 serde_json::from_slice(json).map_err(|error| WireError(error.to_string()))
80 }
81 Some((format, _)) => Err(WireError(format!("unknown format {format}"))),
82 None => Err(WireError("no bytes".to_owned())),
83 }
84 }
85}