use std::ffi::{OsStr, OsString};
use std::path::Path;
use sysinfo::{ProcessesToUpdate, System};
use super::install::js_debug_dir;
const INIT_PID: u32 = 1;
const JS_DEBUG_SCRIPTS: [&str; 2] = ["dapDebugServer.js", "watchdog.js"];
fn cmd_is_croft_js_debug(cmd: &[OsString], js_debug_root: &Path) -> bool {
cmd.iter().any(|arg| {
let p = Path::new(arg);
p.starts_with(js_debug_root)
&& p.file_name()
.and_then(OsStr::to_str)
.is_some_and(|name| JS_DEBUG_SCRIPTS.contains(&name))
})
}
fn is_orphaned_js_debug(ppid: Option<u32>, cmd: &[OsString], js_debug_root: &Path) -> bool {
ppid == Some(INIT_PID) && cmd_is_croft_js_debug(cmd, js_debug_root)
}
pub fn reap_orphaned_js_debug() -> usize {
let Some(root) = js_debug_dir() else {
return 0;
};
let mut sys = System::new();
sys.refresh_processes(ProcessesToUpdate::All, true);
let mut reaped = 0;
for (pid, proc_) in sys.processes() {
let ppid = proc_.parent().map(|p| p.as_u32());
if is_orphaned_js_debug(ppid, proc_.cmd(), &root) && proc_.kill() {
reaped += 1;
super::log::log(&format!("reaped orphaned js-debug pid {}", pid.as_u32()));
}
}
reaped
}
pub fn reap_orphaned_js_debug_async(delay: std::time::Duration) {
let _ = std::thread::Builder::new()
.name("js-debug-reaper".into())
.spawn(move || {
if !delay.is_zero() {
std::thread::sleep(delay);
}
reap_orphaned_js_debug();
});
}
#[cfg(test)]
mod tests {
use super::*;
fn root() -> std::path::PathBuf {
std::path::PathBuf::from("/home/u/.croft/js-debug")
}
fn argv(parts: &[&str]) -> Vec<OsString> {
parts.iter().map(OsString::from).collect()
}
#[test]
fn matches_the_dap_server_under_the_croft_install() {
let cmd = argv(&[
"node",
"/home/u/.croft/js-debug/js-debug/src/dapDebugServer.js",
"8123",
]);
assert!(cmd_is_croft_js_debug(&cmd, &root()));
}
#[test]
fn matches_the_detached_watchdog() {
let cmd = argv(&["node", "/home/u/.croft/js-debug/js-debug/src/watchdog.js"]);
assert!(cmd_is_croft_js_debug(&cmd, &root()));
}
#[test]
fn ignores_a_same_named_script_outside_crofts_install() {
let cmd = argv(&["node", "/somewhere/else/js-debug/src/dapDebugServer.js"]);
assert!(
!cmd_is_croft_js_debug(&cmd, &root()),
"only croft's own install is ours to reap"
);
}
#[test]
fn ignores_an_unrelated_node_process() {
let cmd = argv(&["node", "/home/u/project/server.js"]);
assert!(!cmd_is_croft_js_debug(&cmd, &root()));
}
#[test]
fn reaps_only_when_orphaned_to_init() {
let cmd = argv(&["node", "/home/u/.croft/js-debug/js-debug/src/watchdog.js"]);
assert!(
is_orphaned_js_debug(Some(INIT_PID), &cmd, &root()),
"reparented to init -> orphan"
);
assert!(
!is_orphaned_js_debug(Some(4321), &cmd, &root()),
"still parented to a live process -> part of a running session, leave it"
);
assert!(
!is_orphaned_js_debug(None, &cmd, &root()),
"unknown parent -> do not reap"
);
}
}