use crate::paths::Paths;
use crate::run;
use crate::session::{self, PULSE_SESSION};
use anyhow::Result;
use std::process::ExitCode;
use std::time::Duration;
pub fn cmd_up(paths: &Paths, json: bool) -> Result<ExitCode> {
if session::is_alive(paths, PULSE_SESSION) {
println!("looop: pulse already running");
} else {
if session::status_exists(paths, PULSE_SESSION) {
session::reap(paths, PULSE_SESSION);
}
if json {
unsafe { std::env::set_var("LOOOP_LOG_FORMAT", "json") };
}
let bin = paths.bin.to_string_lossy().to_string();
session::spawn_detached(
paths,
vec![bin, "_".to_string(), "pulse".to_string()],
PULSE_SESSION,
)?;
session::await_alive(paths, PULSE_SESSION, Duration::from_secs(5));
println!("looop: pulse started{}", if json { " [json]" } else { "" });
}
Ok(ExitCode::SUCCESS)
}
pub fn cmd_down(paths: &Paths) -> Result<ExitCode> {
let live: Vec<String> = session::list_workers(paths)
.into_iter()
.filter(|s| s.alive)
.map(|s| s.id)
.collect();
for id in &live {
let _ = session::kill_quiet(paths, id);
}
if !live.is_empty() {
println!(
"looop: stopped {} worker{} ({})",
live.len(),
if live.len() == 1 { "" } else { "s" },
live.join(", ")
);
}
if session::is_alive(paths, PULSE_SESSION) {
let _ = session::kill_quiet(paths, PULSE_SESSION);
let deadline = std::time::Instant::now() + Duration::from_secs(2);
while session::is_alive(paths, PULSE_SESSION) && std::time::Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(50));
}
}
if session::status_exists(paths, PULSE_SESSION) {
session::reap(paths, PULSE_SESSION);
}
println!("looop: pulse stopped");
Ok(ExitCode::SUCCESS)
}
pub fn cmd_pulse(paths: &Paths) -> Result<ExitCode> {
run::cmd_run(paths)
}