PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Logging: a second launch leaves the running instance's log alone (#6432) (#6478)
Gert Pellin - GPEba40454b1895
diff --git a/apps/photocraft/src/logging.rs b/apps/photocraft/src/logging.rsindex 292428b8c..33b7df246 100644--- a/apps/photocraft/src/logging.rs+++ b/apps/photocraft/src/logging.rs@@ -4,7 +4,9 @@//! lost device, the crash guard's panic report) vanished. A launch from a desktop menu has no//! terminal, so the file is what a bug report can attach: `<settings dir>/logs/photocraft.log`//! (see `app_dirs`). Each start moves the previous log to `photocraft.1.log` (and that one to-//! `.2`), so the log of a run that crashed survives the next launch.+//! `.2`), so the log of a run that crashed survives the next launch. A start while another+//! instance is still running leaves that instance's log alone and writes `photocraft-<pid>.log`+//! (see [`rotate`]).//!//! Levels: `info` for PhotoCraft's own crates, `warn` for everything else (wgpu and naga are//! chatty). `RUST_LOG` replaces that with env_logger-style directives: `debug`,@@ -15,7 +17,7 @@//! written once the file is attached. Writing never panics: a file that can't be created or//! written leaves standard error as the only sink.-use std::fs::File;+use std::fs::{File, OpenOptions, TryLockError};use std::io::Write;use std::path::{Path, PathBuf};use std::sync::{Mutex, OnceLock, PoisonError};@@ -116,10 +118,76 @@ fn numbered(dir: &Path, n: usize) -> PathBuf {if n == 0 { dir.join(LOG_FILE) } else { dir.join(format!("photocraft.{n}.log")) }}-/// Shift the previous logs up one (`.log` → `.1.log` → … → `.<KEEP>.log`, the oldest dropped)-/// and create a fresh, empty log file in `dir` (created if missing).-pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> {+/// Held by the instance that writes [`LOG_FILE`], from its start until it exits. A separate lock+/// file rather than a lock on the log itself: Windows locks are mandatory, and a locked log could+/// not be opened for a bug report while the app runs.+pub const OWNER_LOCK: &str = "photocraft.lock";+/// Held while one start rotates and prunes the logs, so two starts at once can't interleave.+pub const ROTATE_LOCK: &str = "rotate.lock";++/// The log of an instance started while another one was writing [`LOG_FILE`].+fn instance_log(dir: &Path, pid: u32) -> PathBuf {+ dir.join(format!("photocraft-{pid}.log"))+}++/// The lock file that marks [`instance_log`] as in use.+fn instance_lock(dir: &Path, pid: u32) -> PathBuf {+ dir.join(format!("photocraft-{pid}.lock"))+}++/// The process id in an [`instance_log`] file name.+fn instance_pid(name: &str) -> Option<u32> {+ let digits = name.strip_prefix("photocraft-")?.strip_suffix(".log")?;+ if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {+ return None;+ }+ digits.parse().ok()+}++fn open_lock(path: &Path) -> std::io::Result<File> {+ OpenOptions::new().read(true).write(true).create(true).truncate(false).open(path)+}++/// Take `file`'s lock without waiting: `Ok(true)` holds it, `Ok(false)` when another process holds it.+fn try_hold(file: &File) -> std::io::Result<bool> {+ match file.try_lock() {+ Ok(()) => Ok(true),+ Err(TryLockError::WouldBlock) => Ok(false),+ Err(TryLockError::Error(e)) => Err(e),+ }+}++/// Open a fresh, empty log file in `dir` (created if missing).+///+/// Normally the previous logs shift up one (`.log` → `.1.log` → … → `.<KEEP>.log`, the oldest+/// dropped). While another instance is still writing [`LOG_FILE`] (it holds [`OWNER_LOCK`]), the+/// chain is left alone and this start writes `photocraft-<pid>.log` instead: rotating would move+/// that instance's live log away and, a few launches later, delete it (#6432). Such side-by-side+/// logs are pruned to the newest [`KEEP`] once their instances have exited. On a file system+/// without locks every start rotates, as before.+pub fn rotate(dir: &Path) -> std::io::Result<LogFile> {std::fs::create_dir_all(dir)?;+ // Waits only for another start's few file operations; without locking support, go on.+ let guard = open_lock(&dir.join(ROTATE_LOCK)).ok().filter(|g| g.lock().is_ok());+ let log = rotate_locked(dir);+ drop(guard);+ log+}++fn rotate_locked(dir: &Path) -> std::io::Result<LogFile> {+ prune_instance_logs(dir);+ let owner = open_lock(&dir.join(OWNER_LOCK))?;+ let state = try_hold(&owner);+ if let Ok(false) = state {+ let pid = std::process::id();+ let lock = open_lock(&instance_lock(dir, pid))?;+ let held = try_hold(&lock).unwrap_or(false);+ let path = instance_log(dir, pid);+ let file = File::create(&path)?;+ return Ok(LogFile { path, file, owner: held.then_some(lock) });+ }+ // This start holds the owner lock (or the file system has no locks).+ let held = state.unwrap_or(false);for n in (1..=KEEP).rev() {match std::fs::rename(numbered(dir, n - 1), numbered(dir, n)) {Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e),@@ -128,7 +196,40 @@ pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> {}let path = numbered(dir, 0);let file = File::create(&path)?;- Ok((path, file))+ Ok(LogFile { path, file, owner: held.then_some(owner) })+}++/// Remove the side-by-side logs of instances that have exited, all but the newest [`KEEP`].+/// A log whose lock file is held belongs to a running instance and is never touched. Failures+/// are ignored: pruning only saves disk space.+fn prune_instance_logs(dir: &Path) {+ let Ok(entries) = std::fs::read_dir(dir) else { return };+ let mut finished: Vec<(SystemTime, u32)> = Vec::new();+ for entry in entries.flatten() {+ let Some(pid) = entry.file_name().to_str().and_then(instance_pid) else { continue };+ // A missing lock file means nobody holds it; an unknown lock state counts as running.+ let running = match OpenOptions::new().read(true).write(true).open(instance_lock(dir, pid)) {+ Ok(lock) => !try_hold(&lock).unwrap_or(false),+ Err(_) => false,+ };+ if !running {+ let modified = entry.metadata().and_then(|m| m.modified()).unwrap_or(SystemTime::UNIX_EPOCH);+ finished.push((modified, pid));+ }+ }+ finished.sort_unstable_by(|a, b| b.cmp(a));+ for &(_, pid) in finished.iter().skip(KEEP) {+ let _ = std::fs::remove_file(instance_log(dir, pid));+ let _ = std::fs::remove_file(instance_lock(dir, pid));+ }+}++/// A log file opened by [`rotate`].+pub struct LogFile {+ pub path: PathBuf,+ pub file: File,+ /// The held lock that marks `path` as in use; `None` where locking isn't supported.+ owner: Option<File>,}/// One formatted log line: `<timestamp> <LEVEL> [<thread>] <target>: <message>\n`.@@ -205,17 +306,20 @@ pub struct AppLogger {filter: Filter,stderr: bool,sink: Mutex<Sink>,+ /// The lock that marks the attached log file as in use (see [`rotate`]); held until exit.+ owner: Mutex<Option<File>>,}impl AppLogger {pub fn new(filter: Filter, stderr: bool) -> AppLogger {- AppLogger { filter, stderr, sink: Mutex::new(Sink::new(MAX_FILE_BYTES)) }+ AppLogger { filter, stderr, sink: Mutex::new(Sink::new(MAX_FILE_BYTES)), owner: Mutex::new(None) }}/// Rotate the logs in `dir` and send records to the fresh file; returns its path.pub fn attach_dir(&self, dir: &Path) -> Result<PathBuf, String> {- let (path, file) = rotate(dir).map_err(|e| format!("{}: {e}", dir.display()))?;+ let LogFile { path, file, owner } = rotate(dir).map_err(|e| format!("{}: {e}", dir.display()))?;self.sink.lock().unwrap_or_else(PoisonError::into_inner).attach(file);+ *self.owner.lock().unwrap_or_else(PoisonError::into_inner) = owner;Ok(path)}}@@ -318,7 +422,7 @@ mod tests {fn rotation_keeps_the_previous_logs_and_starts_an_empty_file() {let dir = temp_dir("rotate");for run in 1..=4 {- let (path, _file) = rotate(&dir).expect("rotate");+ let LogFile { path, file: _file, owner: _owner } = rotate(&dir).expect("rotate");assert_eq!(path, dir.join(LOG_FILE));assert_eq!(std::fs::read_to_string(&path).expect("read"), "");std::fs::write(&path, format!("run {run}")).expect("write");@@ -330,6 +434,64 @@ mod tests {let _ = std::fs::remove_dir_all(&dir);}+ /// #6432: a second launch moved the running instance's live log to `.1.log`, a third to+ /// `.2.log`, and a fourth deleted it.+ #[test]+ fn a_second_start_leaves_the_running_instance_log_alone() {+ let dir = temp_dir("second");+ let mut first = rotate(&dir).expect("first start");+ assert_eq!(first.path, dir.join(LOG_FILE));+ first.file.write_all(b"first, before\n").expect("write");+ for _ in 0..KEEP + 1 {+ let second = rotate(&dir).expect("second start");+ assert_eq!(second.path, instance_log(&dir, std::process::id()));+ assert_eq!(read(&second.path), "");+ }+ first.file.write_all(b"first, after\n").expect("write");+ assert_eq!(read(&dir.join(LOG_FILE)), "first, before\nfirst, after\n");+ assert!(!dir.join("photocraft.1.log").exists(), "the running instance's log was rotated");+ // Once the first instance is gone, the next start rotates as before.+ drop(first);+ let third = rotate(&dir).expect("third start");+ assert_eq!(third.path, dir.join(LOG_FILE));+ assert_eq!(read(&dir.join("photocraft.1.log")), "first, before\nfirst, after\n");+ drop(third);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn instance_logs_are_pruned_only_when_no_one_holds_them() {+ let dir = temp_dir("prune");+ let first = rotate(&dir).expect("first start");+ // Earlier side-by-side runs that have exited, oldest first; the oldest has no lock file+ // (as if its lock file had been removed), the others an unlocked one.+ let now = SystemTime::now();+ for (age, pid) in [(400u64, 1u32), (300, 2), (200, 3), (100, 4)] {+ let path = instance_log(&dir, pid);+ std::fs::write(&path, format!("run {pid}")).expect("write");+ File::options().write(true).open(&path).expect("open").set_modified(now - Duration::from_secs(age)).expect("mtime");+ if pid != 1 {+ std::fs::write(instance_lock(&dir, pid), "").expect("lock file");+ }+ }+ // One older still running: its log is never removed, however old.+ let live = instance_log(&dir, 5);+ std::fs::write(&live, "live").expect("write");+ File::options().write(true).open(&live).expect("open").set_modified(now - Duration::from_secs(900)).expect("mtime");+ let held = File::create(instance_lock(&dir, 5)).expect("lock file");+ held.try_lock().expect("hold");++ let second = rotate(&dir).expect("second start");+ assert_eq!(second.path, instance_log(&dir, std::process::id()));+ // The newest KEEP finished ones stay, the rest go with their lock files.+ assert!(instance_log(&dir, 4).exists() && instance_log(&dir, 3).exists());+ assert!(!instance_log(&dir, 2).exists() && !instance_log(&dir, 1).exists());+ assert!(!instance_lock(&dir, 2).exists());+ assert_eq!(read(&live), "live");+ drop((first, second, held));+ let _ = std::fs::remove_dir_all(&dir);+ }+#[test]fn rotation_into_an_unusable_directory_is_an_error_not_a_panic() {let dir = temp_dir("blocked");@@ -355,7 +517,7 @@ mod tests {#[test]fn lines_logged_before_the_file_exists_are_written_when_it_is_attached() {let dir = temp_dir("pending");- let (path, file) = rotate(&dir).expect("rotate");+ let LogFile { path, file, .. } = rotate(&dir).expect("rotate");let mut sink = Sink::new(MAX_FILE_BYTES);sink.write("early 1\n");sink.write("early 2\n");@@ -368,7 +530,7 @@ mod tests {#[test]fn the_pending_buffer_is_bounded_and_says_how_much_it_dropped() {let dir = temp_dir("bounded");- let (path, file) = rotate(&dir).expect("rotate");+ let LogFile { path, file, .. } = rotate(&dir).expect("rotate");let mut sink = Sink::new(MAX_FILE_BYTES);for i in 0..MAX_PENDING + 5 {sink.write(&format!("line {i}\n"));@@ -384,7 +546,7 @@ mod tests {#[test]fn the_file_stops_at_its_size_cap_with_one_note() {let dir = temp_dir("cap");- let (path, file) = rotate(&dir).expect("rotate");+ let LogFile { path, file, .. } = rotate(&dir).expect("rotate");let mut sink = Sink::new(100);sink.attach(file);for i in 0..50 {diff --git a/docs/development.md b/docs/development.mdindex 035efbbcf..239f9456b 100644--- a/docs/development.md+++ b/docs/development.md@@ -99,7 +99,7 @@ If the device is lost while running (#243), every GPU entry point checks the dev## Logs-The desktop app writes its `log` records to standard error and to `logs/photocraft.log` in the settings directory (Linux `~/.config/photocraft/logs/`, macOS `~/Library/Application Support/Photocraft/logs/`, Windows `%APPDATA%\Photocraft\logs\`, or under `PHOTOCRAFT_CONFIG_DIR` / the portable data folder). A start launched from a desktop menu or the Dock has no terminal, so this file is what to attach to a bug report: GPU startup fallbacks, a lost device and the crash guard's panic report all land there. Each launch moves the previous log to `photocraft.1.log` (and that one to `photocraft.2.log`), so the log of a run that crashed survives the next start. The file stops growing at 16 MiB. `--version` and command-line errors write no file.+The desktop app writes its `log` records to standard error and to `logs/photocraft.log` in the settings directory (Linux `~/.config/photocraft/logs/`, macOS `~/Library/Application Support/Photocraft/logs/`, Windows `%APPDATA%\Photocraft\logs\`, or under `PHOTOCRAFT_CONFIG_DIR` / the portable data folder). A start launched from a desktop menu or the Dock has no terminal, so this file is what to attach to a bug report: GPU startup fallbacks, a lost device and the crash guard's panic report all land there. Each launch moves the previous log to `photocraft.1.log` (and that one to `photocraft.2.log`), so the log of a run that crashed survives the next start. A launch while another PhotoCraft is still running leaves that instance's log where it is and writes its own `photocraft-<pid>.log` next to it (the newest two of those are kept once their instances have exited; the `PhotoCraft <version>, log file <path>` line at startup names the file in use). The file stops growing at 16 MiB. `--version` and command-line errors write no file.By default PhotoCraft's own crates log at `info` and everything else at `warn`. `RUST_LOG` replaces that with env_logger-style directives, for example `RUST_LOG=debug`, `RUST_LOG=warn,photocraft_gpu=trace` or `RUST_LOG=info,wgpu_core=warn`; a directive ending in `*` covers every target starting with it (`photocraft*=debug`). The logger is `apps/photocraft/src/logging.rs`; the web build logs to the browser console instead.