Skip to main content

kute_cli/
live.rs

1//! `kute live`: windowed discovery over JSON Lines arriving on a file or
2//! on standard input.
3//!
4//! One JSON object per line goes in; one JSON object per line comes out:
5//! `{"window": ...}` for each window that closes and `{"summary": ...}` at
6//! the end. Reading is synchronous, so a writer on a pipe is slowed to the
7//! speed of counting and nothing queues beyond the watch's own bounded
8//! buffer.
9
10use kute_discover::watch::{Watch, WatchParams};
11use serde_json::{json, Value};
12use std::io::{BufRead, Read, Write};
13use std::path::{Path, PathBuf};
14
15/// Longest line read as one event.
16const MAX_LINE_BYTES: usize = 1 << 20;
17
18pub struct Options {
19    /// The file to read; standard input when absent.
20    pub input: Option<PathBuf>,
21    pub symbol_field: String,
22    pub time_field: String,
23    pub group_field: Option<String>,
24    pub params: WatchParams,
25    /// Where state is saved, and resumed from when `resume` is set.
26    pub checkpoint: Option<PathBuf>,
27    /// Save after this many window reports.
28    pub checkpoint_every: u64,
29    pub resume: bool,
30    /// Count and pass over lines that cannot be read as events, instead
31    /// of stopping.
32    pub skip_bad_lines: bool,
33}
34
35fn invalid(why: String) -> kute::KuteError {
36    kute::KuteError::InvalidInput(why)
37}
38
39/// The three fields of one line, or why it is not an event.
40fn fields<'a>(line: &'a [u8], options: &Options, scratch: &'a mut String) -> Result<(&'a str, String, i64), String> {
41    let value: Value = serde_json::from_slice(line).map_err(|e| format!("not JSON: {e}"))?;
42    let object = value.as_object().ok_or("not a JSON object")?;
43    let symbol = match object.get(&options.symbol_field) {
44        Some(Value::String(s)) => s.clone(),
45        Some(_) => return Err(format!("field {:?} is not a string", options.symbol_field)),
46        None => return Err(format!("no field {:?}", options.symbol_field)),
47    };
48    let time = match object.get(&options.time_field) {
49        Some(Value::Number(n)) => n.as_i64().ok_or_else(|| format!("field {:?} is not a whole number in 64 bits", options.time_field))?,
50        Some(_) => return Err(format!("field {:?} is not a number", options.time_field)),
51        None => return Err(format!("no field {:?}", options.time_field)),
52    };
53    scratch.clear();
54    if let Some(field) = &options.group_field {
55        match object.get(field) {
56            // The JSON text, so that 1 and "1" are two entities.
57            Some(v @ (Value::String(_) | Value::Number(_) | Value::Bool(_))) => scratch.push_str(&v.to_string()),
58            Some(_) => return Err(format!("field {field:?} is not a string, a number or a boolean")),
59            None => return Err(format!("no field {field:?}")),
60        }
61    }
62    Ok((scratch.as_str(), symbol, time))
63}
64
65/// The watch's state with the reader's position, written beside the old
66/// file and moved over it, so that a crash leaves one whole checkpoint.
67fn save(path: &Path, watch: &Watch, lines: u64, bad: u64) -> kute::Result<()> {
68    let state: Value = serde_json::from_slice(&watch.checkpoint()?)?;
69    let mut partial = path.as_os_str().to_owned();
70    partial.push(".partial");
71    let partial = PathBuf::from(partial);
72    std::fs::write(&partial, serde_json::to_vec(&json!({ "kute_live_checkpoint": 1, "lines": lines, "bad_lines": bad, "watch": state }))?)?;
73    std::fs::rename(&partial, path)?;
74    Ok(())
75}
76
77pub fn run(options: Options) -> kute::Result<()> {
78    let started = std::time::Instant::now();
79    let (mut watch, skip, mut bad) = match (&options.checkpoint, options.resume) {
80        (Some(path), true) => {
81            let saved: Value = serde_json::from_slice(&std::fs::read(path)?)?;
82            if saved["kute_live_checkpoint"] != 1 {
83                return Err(invalid(format!("{} is not a live checkpoint", path.display())));
84            }
85            let watch = Watch::restore(&serde_json::to_vec(&saved["watch"])?)?;
86            if watch.params() != &options.params {
87                return Err(kute::KuteError::InvalidConfig("the checkpoint was made with other parameters; resume with the same ones".into()));
88            }
89            let number = |key: &str| saved[key].as_u64().ok_or_else(|| invalid(format!("the checkpoint has no {key}")));
90            (watch, number("lines")?, number("bad_lines")?)
91        }
92        (None, true) => return Err(kute::KuteError::InvalidConfig("--resume needs --checkpoint".into())),
93        _ => (Watch::new(options.params.clone())?, 0, 0),
94    };
95    if options.checkpoint_every == 0 {
96        return Err(kute::KuteError::InvalidConfig("--checkpoint-every must be at least 1".into()));
97    }
98    let mut reader: Box<dyn BufRead> = match &options.input {
99        Some(path) => Box::new(std::io::BufReader::with_capacity(1 << 20, std::fs::File::open(path)?)),
100        None => Box::new(std::io::stdin().lock()),
101    };
102    let mut out = std::io::BufWriter::new(std::io::stdout().lock());
103    let mut line: Vec<u8> = Vec::new();
104    let mut scratch = String::new();
105    // Lines that are not blank, counted from the start of the input.
106    let mut lines: u64 = 0;
107    let mut since_save: u64 = 0;
108    let mut windows: u64 = 0;
109    let mut checkpoints: u64 = 0;
110    let resumed_from = skip;
111    loop {
112        line.clear();
113        // At most one byte past the limit is read for one line.
114        let read = Read::take(&mut reader, MAX_LINE_BYTES as u64 + 1).read_until(b'\n', &mut line)?;
115        if read == 0 {
116            break;
117        }
118        if line.iter().all(|b| b.is_ascii_whitespace()) {
119            continue;
120        }
121        lines += 1;
122        if lines <= skip {
123            continue;
124        }
125        let event = if line.len() > MAX_LINE_BYTES && line.last() != Some(&b'\n') { Err("longer than 1 MiB".to_string()) } else { fields(&line, &options, &mut scratch) };
126        let reports = match event {
127            Ok((entity, symbol, time)) => watch.observe(entity, &symbol, time),
128            Err(why) if options.skip_bad_lines => {
129                // What is left of an overlong line is read as lines of its
130                // own and, not being JSON objects, counted as bad too.
131                let _ = why;
132                bad += 1;
133                continue;
134            }
135            Err(why) => return Err(invalid(format!("line {lines}: {why}"))),
136        };
137        if reports.is_empty() {
138            continue;
139        }
140        for report in &reports {
141            writeln!(out, "{}", serde_json::to_string(&json!({ "window": report }))?)?;
142        }
143        out.flush()?;
144        windows += reports.len() as u64;
145        since_save += reports.len() as u64;
146        if let Some(path) = options.checkpoint.as_ref().filter(|_| since_save >= options.checkpoint_every) {
147            save(path, &watch, lines, bad)?;
148            since_save = 0;
149            checkpoints += 1;
150        }
151    }
152    if lines < skip {
153        return Err(invalid(format!("the checkpoint is {skip} lines into its input and this input has {lines}")));
154    }
155    let bound = watch.params().state_bytes_bound();
156    let (reports, totals) = watch.finish();
157    for report in &reports {
158        writeln!(out, "{}", serde_json::to_string(&json!({ "window": report }))?)?;
159    }
160    windows += reports.len() as u64;
161    let seconds = started.elapsed().as_secs_f64();
162    let read_now = lines - resumed_from;
163    let summary = json!({
164        "lines": lines,
165        "lines_skipped_on_resume": resumed_from,
166        "bad_lines": bad,
167        "totals": totals,
168        "windows_reported_this_run": windows,
169        "checkpoints_written": checkpoints,
170        "seconds": (seconds * 1000.0).round() / 1000.0,
171        "events_per_second": if seconds > 0.0 { (read_now as f64 / seconds).round() } else { 0.0 },
172        "state_bytes_bound": bound,
173    });
174    writeln!(out, "{}", serde_json::to_string(&json!({ "summary": summary }))?)?;
175    out.flush()?;
176    Ok(())
177}