Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

A render's sweep of leftover work folders asks the system whether their render still runs (runtime/bundle pid.rs: kill(pid, 0) on Unix, OpenProcess and GetExitCodeProcess on Windows) instead of running the kill found on PATH. Under Git Bash on Windows that kill is MSYS's, which knows no Windows PID, so every live render looked dead and its folder was deleted mid-bundle when renders overlapped. A process the system won't answer for (another user's, a protected one) keeps its folder. pid.rs's tests cover a live and an ended process and the sweep itself. (closes #29)

shinyobjectzb2d07d1165b7
diff --git a/Cargo.lock b/Cargo.lock
index 598dc6c4..ff4ed747 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -14632,6 +14632,7 @@ version = "0.1.0"
dependencies = [
"dunce",
"junction",
+ "libc",
"raea-core-scene",
"raea-io-home",
"raea-io-media",
@@ -14639,6 +14640,7 @@ dependencies = [
"raea-runtime-bundle-lib",
"regex",
"serde_json",
+ "windows-sys 0.61.2",
]
[[package]]
diff --git a/runtime/bundle/Cargo.toml b/runtime/bundle/Cargo.toml
index c3cba629..b63c453e 100644
--- a/runtime/bundle/Cargo.toml
+++ b/runtime/bundle/Cargo.toml
@@ -27,9 +27,15 @@ regex = "1"
# (f60e0b7: every JSON map an IndexMap, every number its text, pong's apply 87 -> 159 allocations)
raea-runtime-bundle-lib = { path = "lib" }
+# whether the render that left a work folder still runs (pid.rs), asked of the system rather than a `kill` on PATH
+[target.'cfg(unix)'.dependencies]
+libc = "0.2"
+
# the work folder's node_modules link on Windows (fresh.rs link_node_modules), as raea-io-npm makes its links
[target.'cfg(windows)'.dependencies]
junction = "1"
+# and its process check (pid.rs)
+windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Threading"] }
[dev-dependencies]
# tests/mezz.rs writes its long-GOP clip with the soft backend's H.264
diff --git a/runtime/bundle/src/cache.rs b/runtime/bundle/src/cache.rs
index cee95496..dc328d4c 100644
--- a/runtime/bundle/src/cache.rs
+++ b/runtime/bundle/src/cache.rs
@@ -234,7 +234,11 @@ impl Drop for Gone {
/// render's pictures run to 14 GB; four killed in eight minutes filled the disk, 10-24), else when nothing has touched
/// them for two hours.
pub fn sweep_stale_work() {
- let Ok(rd) = std::fs::read_dir(std::env::temp_dir()) else { return };
+ sweep_stale_work_in(&std::env::temp_dir());
+}
+
+pub(crate) fn sweep_stale_work_in(dir: &Path) {
+ let Ok(rd) = std::fs::read_dir(dir) else { return };
let now = std::time::SystemTime::now();
for e in rd.flatten() {
let name = e.file_name().to_string_lossy().into_owned();
@@ -242,11 +246,9 @@ pub fn sweep_stale_work() {
continue;
}
let old = e.metadata().and_then(|m| m.modified()).ok().and_then(|t| now.duration_since(t).ok()).is_some_and(|d| d.as_secs() > 2 * 3600);
- // raea-cli-r{pid}-ThreadId(n), raea-cli-b{pid}: `kill -0` (which sends nothing) fails when no such process is left
+ // raea-cli-r{pid}-ThreadId(n), raea-cli-b{pid}: gone only when the system says no such process is left
let pid = name.get(10..).and_then(|s| s.split('-').next()).and_then(|p| p.parse::<u32>().ok());
- let gone = pid.is_some_and(|p| {
- p != std::process::id() && std::process::Command::new("kill").args(["-0", &p.to_string()]).stderr(std::process::Stdio::null()).status().is_ok_and(|s| !s.success())
- });
+ let gone = pid.is_some_and(|p| p != std::process::id() && crate::pid::running(p) == Some(false));
if old || gone {
let _ = std::fs::remove_dir_all(e.path());
}
diff --git a/runtime/bundle/src/lib.rs b/runtime/bundle/src/lib.rs
index 05e3b407..17133497 100644
--- a/runtime/bundle/src/lib.rs
+++ b/runtime/bundle/src/lib.rs
@@ -12,6 +12,7 @@ mod cache;
mod entry;
mod fresh;
mod outside;
+mod pid;
mod rewrite;
pub mod styles;
pub use cache::*;
diff --git a/runtime/bundle/src/pid.rs b/runtime/bundle/src/pid.rs
new file mode 100644
index 00000000..702d7870
--- /dev/null
+++ b/runtime/bundle/src/pid.rs
@@ -0,0 +1,101 @@
+//! Whether a process still runs, asked of the system itself: a `kill` found on PATH can't be trusted (on Windows under
+//! Git Bash it is MSYS's, which knows no Windows PID and called every live render dead, #29).
+
+/// Whether process `pid` runs: Some(false) only when there's no such process, None when the system won't say (so a
+/// caller deciding whether to delete what it left keeps it).
+#[cfg(unix)]
+pub(crate) fn running(pid: u32) -> Option<bool> {
+ // 0 and anything past i32::MAX name process groups, not one process
+ let p = i32::try_from(pid).ok().filter(|p| *p > 0)?;
+ // signal 0 sends nothing: it only checks that the process exists and could be signalled
+ if unsafe { libc::kill(p, 0) } == 0 {
+ return Some(true);
+ }
+ match std::io::Error::last_os_error().raw_os_error() {
+ Some(libc::ESRCH) => Some(false),
+ // another user's process
+ Some(libc::EPERM) => Some(true),
+ _ => None,
+ }
+}
+
+/// Whether process `pid` runs: Some(false) only when there's no such process, None when the system won't say (so a
+/// caller deciding whether to delete what it left keeps it).
+#[cfg(windows)]
+pub(crate) fn running(pid: u32) -> Option<bool> {
+ use windows_sys::Win32::Foundation::{CloseHandle, ERROR_INVALID_PARAMETER, GetLastError, STILL_ACTIVE};
+ use windows_sys::Win32::System::Threading::{GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION};
+ unsafe {
+ let h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
+ if h.is_null() {
+ // no such process; access denied (another user's, a protected one) says nothing
+ return (GetLastError() == ERROR_INVALID_PARAMETER).then_some(false);
+ }
+ let mut code = 0u32;
+ let ok = GetExitCodeProcess(h, &mut code) != 0;
+ CloseHandle(h);
+ ok.then_some(code == STILL_ACTIVE as u32)
+ }
+}
+
+#[cfg(not(any(unix, windows)))]
+pub(crate) fn running(_pid: u32) -> Option<bool> {
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::running;
+
+ /// A child that waits until its stdin closes, on any system.
+ fn child() -> std::process::Child {
+ #[cfg(windows)]
+ let mut c = std::process::Command::new("cmd");
+ #[cfg(windows)]
+ c.args(["/c", "more"]);
+ #[cfg(not(windows))]
+ let mut c = std::process::Command::new("cat");
+ c.stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::null()).spawn().unwrap()
+ }
+
+ #[test]
+ fn a_process_runs_until_it_ends() {
+ assert_eq!(running(std::process::id()), Some(true));
+ let mut c = child();
+ let pid = c.id();
+ assert_eq!(running(pid), Some(true));
+ drop(c.stdin.take());
+ c.wait().unwrap();
+ // reaped, so its PID names nothing (until the system hands it out again, which takes far longer than this)
+ assert_eq!(running(pid), Some(false));
+ }
+
+ /// The sweep each render starts with (cache.rs) removes a work folder only once its render's process is gone
+ #[test]
+ fn the_sweep_keeps_a_running_renders_folder() {
+ let dir = std::env::temp_dir().join(format!("raea-pid-sweep-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let mut live = child();
+ let mut ended = child();
+ drop(ended.stdin.take());
+ ended.wait().unwrap();
+ let keep = [format!("raea-cli-b{}", live.id()), format!("raea-cli-r{}-ThreadId(2)", live.id()), "raea-cli-bx".into()];
+ let go = [format!("raea-cli-b{}", ended.id()), format!("raea-cli-r{}-ThreadId(2)", ended.id())];
+ for n in keep.iter().chain(&go) {
+ std::fs::create_dir_all(dir.join(n)).unwrap();
+ }
+ crate::cache::sweep_stale_work_in(&dir);
+ let left: Vec<bool> = keep.iter().chain(&go).map(|n| dir.join(n).exists()).collect();
+ drop(live.stdin.take());
+ live.wait().unwrap();
+ let _ = std::fs::remove_dir_all(&dir);
+ assert_eq!(left, [true, true, true, false, false], "kept: {keep:?}, removed: {go:?}");
+ }
+
+ #[test]
+ fn a_pid_naming_no_one_process_is_unknown_or_gone() {
+ // 0 and pids past i32::MAX are groups to kill(2), never "running"
+ assert_ne!(running(0), Some(true));
+ assert_ne!(running(u32::MAX), Some(true));
+ }
+}