use anyhow::Result;
use prt_core::core::scanner;
use prt_core::model::TICK_RATE;
use std::io::{self, BufWriter, Write};
pub fn run_json_stream() -> Result<()> {
#[cfg(unix)]
unsafe {
nix::sys::signal::signal(
nix::sys::signal::Signal::SIGPIPE,
nix::sys::signal::SigHandler::SigIgn,
)
.ok();
}
let mut stdout = BufWriter::new(io::stdout().lock());
loop {
let entries = scanner::scan()?;
for entry in &entries {
match serde_json::to_writer(&mut stdout, entry) {
Ok(()) => {}
Err(e) if is_broken_pipe(&e) => return Ok(()),
Err(e) => return Err(e.into()),
}
if let Err(e) = stdout.write_all(b"\n") {
if e.kind() == io::ErrorKind::BrokenPipe {
return Ok(());
}
return Err(e.into());
}
}
if let Err(e) = stdout.flush() {
if e.kind() == io::ErrorKind::BrokenPipe {
return Ok(());
}
return Err(e.into());
}
std::thread::sleep(TICK_RATE);
}
}
fn is_broken_pipe(e: &serde_json::Error) -> bool {
if let Some(io_err) = e.io_error_kind() {
io_err == io::ErrorKind::BrokenPipe
} else {
false
}
}