Skip to main content

kute_types/
event.rs

1//! Typed event streams: symbols that keep their time and their grouping.
2//!
3//! A [`crate::Payload`] of symbols is an ordered list of names and nothing
4//! else. An [`EventStream`] is the same list with what the source knew about
5//! it kept alongside: which entity each event belongs to, when it happened,
6//! and the schema that says how both were read. Tokenizers and discovery
7//! still consume the symbols; the times stay aligned with them, position by
8//! position, for whatever needs them afterwards.
9
10use crate::{sha256_tagged, KuteError, Result};
11use serde::{Deserialize, Serialize};
12use std::collections::HashMap;
13use std::io::BufRead;
14
15/// Most events one stream will hold.
16pub const MAX_EVENTS: u64 = 1 << 32;
17/// Longest line the JSONL reader accepts.
18pub const MAX_EVENT_LINE: usize = 1 << 20;
19
20/// What one tick of a timestamp means.
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
22#[serde(rename_all = "snake_case")]
23pub enum TimeUnit {
24    Seconds,
25    Milliseconds,
26    Microseconds,
27    Nanoseconds,
28}
29
30impl TimeUnit {
31    pub fn parse(name: &str) -> Result<Self> {
32        Ok(match name {
33            "s" | "seconds" => TimeUnit::Seconds,
34            "ms" | "milliseconds" => TimeUnit::Milliseconds,
35            "us" | "microseconds" => TimeUnit::Microseconds,
36            "ns" | "nanoseconds" => TimeUnit::Nanoseconds,
37            other => return Err(KuteError::InvalidConfig(format!("time unit {other:?}: expected s, ms, us or ns"))),
38        })
39    }
40
41    pub fn ticks_per_second(self) -> f64 {
42        match self {
43            TimeUnit::Seconds => 1.0,
44            TimeUnit::Milliseconds => 1e3,
45            TimeUnit::Microseconds => 1e6,
46            TimeUnit::Nanoseconds => 1e9,
47        }
48    }
49}
50
51/// How events were read from their source. The schema travels with the
52/// stream and is part of its fingerprint, so two streams read from the same
53/// file under different schemas are different streams.
54#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
55pub struct EventSchema {
56    /// A name for this schema, chosen by whoever defines it.
57    pub id: String,
58    /// Bumped when the meaning of a field changes.
59    pub version: u32,
60    /// Field holding the event name.
61    pub symbol_field: String,
62    /// Field holding the timestamp: an integer count of `time_unit`.
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub time_field: Option<String>,
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub time_unit: Option<TimeUnit>,
67    /// Field naming the entity an event belongs to. Events with the same
68    /// value form one record. Without it, the whole source is one record.
69    /// A numeric value is read as its text: `1` and `"1"` name the same
70    /// record, and `1.0` names another.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub group_field: Option<String>,
73}
74
75impl EventSchema {
76    pub fn validate(&self) -> Result<()> {
77        let bad = |why: &str| Err(KuteError::InvalidConfig(format!("event schema: {why}")));
78        if self.id.is_empty() || self.id.len() > 256 {
79            return bad("id must be 1 to 256 bytes");
80        }
81        for field in [Some(&self.symbol_field), self.time_field.as_ref(), self.group_field.as_ref()].into_iter().flatten() {
82            if field.is_empty() || field.len() > 256 {
83                return bad("field names must be 1 to 256 bytes");
84            }
85        }
86        if self.time_field.is_some() != self.time_unit.is_some() {
87            return bad("a time field and a time unit come together or not at all");
88        }
89        Ok(())
90    }
91}
92
93/// The events of one entity, in time order.
94#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
95pub struct EventRecord {
96    /// Value of the group field, when the schema has one.
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub key: Option<String>,
99    pub symbols: Vec<String>,
100    /// One timestamp per symbol, or empty when the schema has no time field.
101    #[serde(default, skip_serializing_if = "Vec::is_empty")]
102    pub times: Vec<i64>,
103}
104
105#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
106pub struct EventStream {
107    pub schema: EventSchema,
108    pub records: Vec<EventRecord>,
109}
110
111impl EventStream {
112    pub fn new(schema: EventSchema) -> Result<Self> {
113        schema.validate()?;
114        Ok(EventStream { schema, records: Vec::new() })
115    }
116
117    pub fn events(&self) -> u64 {
118        self.records.iter().map(|r| r.symbols.len() as u64).sum()
119    }
120
121    pub fn timed(&self) -> bool {
122        self.schema.time_field.is_some()
123    }
124
125    /// Structural check: times aligned with symbols and never going back.
126    pub fn validate(&self) -> Result<()> {
127        self.schema.validate()?;
128        for (i, r) in self.records.iter().enumerate() {
129            let bad = |why: &str| Err(KuteError::InvalidInput(format!("event record {i}: {why}")));
130            if r.symbols.is_empty() {
131                return bad("no events");
132            }
133            if r.symbols.iter().any(|s| s.is_empty() || s.len() > crate::vocab::MAX_SYMBOL_BYTES) {
134                return bad("an event name is empty or oversized");
135            }
136            if self.timed() {
137                if r.times.len() != r.symbols.len() {
138                    return bad("timestamps are not aligned with events");
139                }
140                if r.times.windows(2).any(|w| w[1] < w[0]) {
141                    return bad("timestamps go backwards");
142                }
143            } else if !r.times.is_empty() {
144                return bad("timestamps present but the schema has no time field");
145            }
146        }
147        Ok(())
148    }
149
150    /// The symbols alone, one sequence per record.
151    pub fn symbol_records(&self) -> Vec<Vec<String>> {
152        self.records.iter().map(|r| r.symbols.clone()).collect()
153    }
154
155    /// SHA-256 over the schema and every record: keys, names and times.
156    pub fn fingerprint(&self) -> Result<String> {
157        use sha2::{Digest, Sha256};
158        let mut h = Sha256::new();
159        let schema = serde_json::to_vec(&self.schema)?;
160        h.update((schema.len() as u64).to_le_bytes());
161        h.update(&schema);
162        for r in &self.records {
163            let key = r.key.as_deref().unwrap_or("");
164            h.update([r.key.is_some() as u8]);
165            h.update((key.len() as u64).to_le_bytes());
166            h.update(key);
167            h.update((r.symbols.len() as u64).to_le_bytes());
168            for s in &r.symbols {
169                h.update((s.len() as u64).to_le_bytes());
170                h.update(s);
171            }
172            h.update((r.times.len() as u64).to_le_bytes());
173            for t in &r.times {
174                h.update(t.to_le_bytes());
175            }
176        }
177        Ok(format!("sha256:{}", crate::hex(&h.finalize())))
178    }
179
180    /// Split into the first records and the last `fraction` of them. Each
181    /// side gets at least one record; a stream with fewer than two is an error.
182    pub fn split_last(mut self, fraction: f64) -> Result<(EventStream, EventStream)> {
183        if !(fraction > 0.0 && fraction < 1.0) {
184            return Err(KuteError::InvalidConfig("the held-out fraction must be between 0 and 1".into()));
185        }
186        if self.records.len() < 2 {
187            return Err(KuteError::InvalidInput("splitting needs at least two records, one for each side".into()));
188        }
189        let cut = ((self.records.len() as f64) * (1.0 - fraction)).round() as usize;
190        // Both sides keep at least one record, whatever the fraction rounds to.
191        let tail = self.records.split_off(cut.clamp(1, self.records.len() - 1));
192        let schema = self.schema.clone();
193        Ok((self, EventStream { schema, records: tail }))
194    }
195
196    /// Read JSON Lines: one object per line, one event per object.
197    ///
198    /// Records are formed by the group field and listed in order of first
199    /// appearance. Within a record events are put in time order; events with
200    /// equal times keep the order of the file. A line without the symbol
201    /// field, with a symbol that is not a string, or with a time that is not
202    /// a whole number is an error: nothing is skipped or rounded.
203    pub fn read_jsonl(&mut self, reader: impl BufRead, source: &str) -> Result<()> {
204        let schema = self.schema.clone();
205        let mut index: HashMap<String, usize> = HashMap::new();
206        for (i, r) in self.records.iter().enumerate() {
207            if let Some(k) = &r.key {
208                index.insert(k.clone(), i);
209            }
210        }
211        let mut total = self.events();
212        let mut touched = vec![false; self.records.len()];
213        let mut reader = reader;
214        let mut line: Vec<u8> = Vec::new();
215        let mut n = 0usize;
216        loop {
217            // At most one byte past the limit is ever read for one line, so
218            // a source with no line breaks cannot be pulled into memory.
219            line.clear();
220            let read = std::io::Read::take(&mut reader, MAX_EVENT_LINE as u64 + 1).read_until(b'\n', &mut line)?;
221            if read == 0 {
222                break;
223            }
224            n += 1;
225            let at = |why: String| KuteError::InvalidInput(format!("{source}, line {n}: {why}"));
226            if line.last() == Some(&b'\n') {
227                line.pop();
228            }
229            if line.len() > MAX_EVENT_LINE {
230                return Err(at("longer than 1 MiB".into()));
231            }
232            if line.iter().all(|b| b.is_ascii_whitespace()) {
233                continue;
234            }
235            let value: serde_json::Value = serde_json::from_slice(&line).map_err(|e| at(format!("not JSON: {e}")))?;
236            let object = value.as_object().ok_or_else(|| at("not a JSON object".into()))?;
237            let symbol = match object.get(&schema.symbol_field) {
238                Some(serde_json::Value::String(s)) if !s.is_empty() && s.len() <= crate::vocab::MAX_SYMBOL_BYTES => s.clone(),
239                Some(serde_json::Value::String(_)) => return Err(at(format!("field {:?} is empty or oversized", schema.symbol_field))),
240                Some(_) => return Err(at(format!("field {:?} is not a string", schema.symbol_field))),
241                None => return Err(at(format!("no field {:?}", schema.symbol_field))),
242            };
243            let time = match &schema.time_field {
244                None => None,
245                Some(field) => Some(match object.get(field) {
246                    Some(serde_json::Value::Number(x)) => match x.as_i64() {
247                        Some(t) => t,
248                        None => match x.as_f64() {
249                            Some(f) if f.fract() == 0.0 && f.abs() < 9.0e15 => f as i64,
250                            _ => return Err(at(format!("field {field:?} is not a whole number; choose a finer time unit"))),
251                        },
252                    },
253                    Some(_) => return Err(at(format!("field {field:?} is not a number"))),
254                    None => return Err(at(format!("no field {field:?}"))),
255                }),
256            };
257            let slot = match &schema.group_field {
258                None => {
259                    if self.records.is_empty() {
260                        self.records.push(EventRecord { key: None, symbols: Vec::new(), times: Vec::new() });
261                        touched.push(false);
262                    }
263                    0
264                }
265                Some(field) => {
266                    let key = match object.get(field) {
267                        Some(serde_json::Value::String(s)) => s.clone(),
268                        Some(serde_json::Value::Number(x)) => x.to_string(),
269                        Some(_) => return Err(at(format!("field {field:?} is neither a string nor a number"))),
270                        None => return Err(at(format!("no field {field:?}"))),
271                    };
272                    match index.get(&key) {
273                        Some(&i) => i,
274                        None => {
275                            self.records.push(EventRecord { key: Some(key.clone()), symbols: Vec::new(), times: Vec::new() });
276                            touched.push(false);
277                            index.insert(key, self.records.len() - 1);
278                            self.records.len() - 1
279                        }
280                    }
281                }
282            };
283            total += 1;
284            if total > MAX_EVENTS {
285                return Err(KuteError::LimitExceeded("more than 2^32 events".into()));
286            }
287            let record = &mut self.records[slot];
288            if let Some(t) = time {
289                if record.times.last().is_some_and(|&last| t < last) {
290                    touched[slot] = true;
291                }
292                record.times.push(t);
293            }
294            record.symbols.push(symbol);
295        }
296        // Stable sort of the records that arrived out of time order.
297        for (record, _) in self.records.iter_mut().zip(&touched).filter(|&(_, &t)| t) {
298            let mut order: Vec<usize> = (0..record.times.len()).collect();
299            order.sort_by_key(|&i| record.times[i]);
300            record.times = order.iter().map(|&i| record.times[i]).collect();
301            let mut symbols: Vec<Option<String>> = std::mem::take(&mut record.symbols).into_iter().map(Some).collect();
302            record.symbols = order.iter().map(|&i| symbols[i].take().expect("each index once")).collect();
303        }
304        Ok(())
305    }
306}
307
308/// Fingerprint helper kept next to the type for callers that only have bytes.
309pub fn schema_fingerprint(schema: &EventSchema) -> Result<String> {
310    Ok(sha256_tagged(&serde_json::to_vec(schema)?))
311}