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}
28
29/// Bytes that are not an encoded outcome.
30#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
31#[error("not an encoded outcome: {0}")]
32pub struct WireError(String);
33
34impl Envelope {
35 /// An envelope for `outcome` of the source `source` at definition
36 /// version `version`.
37 pub fn new(source: impl Into<String>, version: u32, outcome: Outcome) -> Self {
38 Self {
39 source: source.into(),
40 version,
41 outcome,
42 }
43 }
44
45 /// The envelope as bytes, for a pipe.
46 pub fn encode(&self) -> Vec<u8> {
47 let mut bytes = vec![JSON];
48 // Writing JSON into a vector fails only for a map with non-string
49 // keys, which no outcome contains.
50 if serde_json::to_writer(&mut bytes, self).is_err() {
51 bytes.truncate(1);
52 }
53 bytes
54 }
55
56 /// An envelope from bytes [`encode`](Self::encode) wrote.
57 ///
58 /// # Errors
59 ///
60 /// Returns [`WireError`] if the bytes are in no known format, or do not
61 /// hold an envelope.
62 pub fn decode(bytes: &[u8]) -> Result<Self, WireError> {
63 match bytes.split_first() {
64 Some((&JSON, json)) => {
65 serde_json::from_slice(json).map_err(|error| WireError(error.to_string()))
66 }
67 Some((format, _)) => Err(WireError(format!("unknown format {format}"))),
68 None => Err(WireError("no bytes".to_owned())),
69 }
70 }
71}