Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Keep open files locked on Windows desktop so a DMS doesn't check them in (#8898)

ConnorYoh0be94d1e0f3c
diff --git a/frontend/src-tauri/src/commands/file_lock.rs b/frontend/src-tauri/src/commands/file_lock.rs
new file mode 100644
index 0000000000..6c94844f7a
--- /dev/null
+++ b/frontend/src-tauri/src/commands/file_lock.rs
@@ -0,0 +1,372 @@
+// Holds every disk file a window has open, the way Acrobat and Word do. A DMS
+// (e.g. LEXolution.DMS) that checks a file out to disk polls for that lock and
+// checks the file back in, deleting our copy, as soon as it sees the file free.
+//
+// One handle per file, read+write but sharing read only: other programs can
+// still read it, but cannot write, rename or delete it. Saves go through the
+// same handle, so the lock never lapses mid-save. Windows only; elsewhere
+// nothing is locked and saves take the ordinary path.
+
+use std::collections::BTreeMap;
+use std::fs::File;
+use std::io::{Seek, SeekFrom, Write};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+// A file handed over at launch is locked before the window loads it, and must
+// survive the window's first claims, which do not list it yet.
+const LAUNCH_GRACE: Duration = Duration::from_secs(120);
+
+static LOCKS: Mutex<Locks> = Mutex::new(Locks::new());
+
+struct Held {
+ // Its own lock, so a save holds only this file while it writes. A file
+ // closed mid-save keeps its entry until the save ends, so reopening it in
+ // the meantime reuses this handle rather than failing to open a second.
+ file: Arc<Mutex<File>>,
+ writable: bool,
+ launched_at: Option<Instant>,
+ claimed: bool,
+}
+
+struct Locks {
+ held: BTreeMap<String, Held>,
+}
+
+impl Locks {
+ const fn new() -> Self {
+ Self {
+ held: BTreeMap::new(),
+ }
+ }
+
+ fn lock_launch_file(&mut self, path: &str, now: Instant) {
+ if self.held.contains_key(path) {
+ return;
+ }
+ if let Some((file, writable)) = open_locked(path) {
+ self.held.insert(
+ path.to_string(),
+ Held {
+ file: Arc::new(Mutex::new(file)),
+ writable,
+ launched_at: Some(now),
+ claimed: false,
+ },
+ );
+ }
+ }
+
+ fn sync(&mut self, open: &[String], now: Instant) {
+ self.held.retain(|path, held| {
+ held.claimed = open.contains(path);
+ if held.claimed {
+ held.launched_at = None;
+ }
+ keep(held, now)
+ });
+ for path in open {
+ if self.held.contains_key(path) {
+ continue;
+ }
+ if let Some((file, writable)) = open_locked(path) {
+ self.held.insert(
+ path.clone(),
+ Held {
+ file: Arc::new(Mutex::new(file)),
+ writable,
+ launched_at: None,
+ claimed: true,
+ },
+ );
+ }
+ }
+ }
+
+ /// Drops locks nothing needs any more: unclaimed, past the launch grace, and not mid-save.
+ fn sweep(&mut self, now: Instant) {
+ self.held.retain(|_, held| keep(held, now));
+ }
+
+ /// The held handle a save to `path` must write through, if any.
+ fn writer(&self, path: &str) -> Option<Arc<Mutex<File>>> {
+ self.held
+ .get(path)
+ .filter(|held| held.writable)
+ .map(|held| Arc::clone(&held.file))
+ }
+}
+
+/// Ok(false) when no writable lock is held, so the caller writes normally.
+fn write_through(file: Option<Arc<Mutex<File>>>, bytes: &[u8]) -> std::io::Result<bool> {
+ let Some(file) = file else {
+ return Ok(false);
+ };
+ let mut file = file
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ file.seek(SeekFrom::Start(0))?;
+ file.write_all(bytes)?;
+ file.set_len(bytes.len() as u64)?;
+ file.sync_all()?;
+ Ok(true)
+}
+
+fn keep(held: &Held, now: Instant) -> bool {
+ let launch_pending = held
+ .launched_at
+ .is_some_and(|at| now.duration_since(at) < LAUNCH_GRACE);
+ // A save in progress holds a clone of the handle.
+ held.claimed || launch_pending || Arc::strong_count(&held.file) > 1
+}
+
+#[cfg(windows)]
+fn open_locked(path: &str) -> Option<(File, bool)> {
+ use crate::utils::add_log;
+ use std::io::ErrorKind;
+ use std::os::windows::fs::OpenOptionsExt;
+ const FILE_SHARE_READ: u32 = 0x1;
+ let open = |write: bool| {
+ std::fs::OpenOptions::new()
+ .read(true)
+ .write(write)
+ .share_mode(FILE_SHARE_READ)
+ .open(path)
+ };
+ match open(true) {
+ Ok(file) => Some((file, true)),
+ // A read-only file (e.g. a DMS read-only checkout) can still be held
+ // against deletion. Anything else, such as another program already
+ // holding it, leaves the file unlocked, as before.
+ Err(error) if error.kind() == ErrorKind::PermissionDenied => {
+ open(false).ok().map(|file| (file, false))
+ }
+ Err(error) => {
+ add_log(format!("⚠️ Could not lock {}: {}", path, error));
+ None
+ }
+ }
+}
+
+#[cfg(not(windows))]
+fn open_locked(_path: &str) -> Option<(File, bool)> {
+ None
+}
+
+fn locks() -> std::sync::MutexGuard<'static, Locks> {
+ LOCKS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+}
+
+pub fn lock_launch_file(path: &str) {
+ locks().lock_launch_file(path, Instant::now());
+ // A file that never loads is never claimed, and nothing else may sync the
+ // locks again, so the grace needs its own timer.
+ std::thread::spawn(|| {
+ std::thread::sleep(LAUNCH_GRACE);
+ locks().sweep(Instant::now());
+ });
+}
+
+/// Lock exactly the files some window has open, plus launch files still loading.
+pub fn sync_locks(open: &[String]) {
+ locks().sync(open, Instant::now());
+}
+
+/// Whether a save to `path` goes through write_locked_file. Asked first, so the
+/// bytes cross IPC only when a lock is held.
+#[tauri::command]
+pub fn holds_writable_lock(path: String) -> bool {
+ locks().writer(&path).is_some()
+}
+
+/// Raw body = the bytes; `path` header = the URI-encoded target path.
+#[tauri::command]
+pub async fn write_locked_file(request: tauri::ipc::Request<'_>) -> Result<bool, String> {
+ let tauri::ipc::InvokeBody::Raw(bytes) = request.body() else {
+ return Err("Expected raw file bytes".to_string());
+ };
+ let path = request
+ .headers()
+ .get("path")
+ .and_then(|value| value.to_str().ok())
+ .and_then(|value| urlencoding::decode(value).ok())
+ .ok_or_else(|| "Missing path header".to_string())?;
+ // The global lock is dropped before the write, so a slow save does not
+ // stall opening or closing other files.
+ let file = locks().writer(&path);
+ let written = write_through(file, bytes);
+ // Releases the file if it was closed while this save was writing.
+ locks().sweep(Instant::now());
+ written.map_err(|error| error.to_string())
+}
+
+#[cfg(all(test, windows))]
+mod tests {
+ use super::*;
+ use std::path::{Path, PathBuf};
+
+ fn temp_file(tag: &str) -> PathBuf {
+ let dir =
+ std::env::temp_dir().join(format!("stirling_lock_{}_{}", tag, std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let file = dir.join("checked-out.pdf");
+ std::fs::write(&file, b"original").unwrap();
+ file
+ }
+
+ fn key(path: &Path) -> String {
+ path.to_string_lossy().to_string()
+ }
+
+ // What a DMS does to decide the file is no longer in use.
+ fn exclusive_open_succeeds(path: &Path) -> bool {
+ use std::os::windows::fs::OpenOptionsExt;
+ std::fs::OpenOptions::new()
+ .read(true)
+ .write(true)
+ .share_mode(0)
+ .open(path)
+ .is_ok()
+ }
+
+ #[test]
+ fn an_open_file_looks_in_use_and_cannot_be_deleted() {
+ let path = temp_file("in_use");
+ let mut locks = Locks::new();
+ locks.sync(&[key(&path)], Instant::now());
+
+ assert!(!exclusive_open_succeeds(&path));
+ assert!(std::fs::remove_file(&path).is_err());
+ // Other programs can still read it.
+ assert_eq!(std::fs::read(&path).unwrap(), b"original");
+
+ locks.sync(&[], Instant::now());
+ assert!(exclusive_open_succeeds(&path));
+ std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
+ }
+
+ #[test]
+ fn saves_go_through_the_held_lock() {
+ let path = temp_file("save");
+ let mut locks = Locks::new();
+ locks.sync(&[key(&path)], Instant::now());
+
+ // The ordinary write path is refused while we hold the file.
+ assert!(std::fs::write(&path, b"x").is_err());
+ assert!(write_through(locks.writer(&key(&path)), b"saved").unwrap());
+ assert_eq!(std::fs::read(&path).unwrap(), b"saved");
+ assert!(!exclusive_open_succeeds(&path));
+
+ locks.sync(&[], Instant::now());
+ std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
+ }
+
+ #[test]
+ fn a_file_closed_mid_save_stays_locked_until_the_save_ends() {
+ let path = temp_file("close_mid_save");
+ let mut locks = Locks::new();
+ locks.sync(&[key(&path)], Instant::now());
+ let saving = locks.writer(&key(&path));
+
+ locks.sync(&[], Instant::now());
+ assert!(!exclusive_open_succeeds(&path));
+ assert!(write_through(saving, b"saved").unwrap());
+ locks.sweep(Instant::now());
+ assert!(exclusive_open_succeeds(&path));
+ assert_eq!(std::fs::read(&path).unwrap(), b"saved");
+ std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
+ }
+
+ #[test]
+ fn a_file_reopened_mid_save_stays_locked_after_the_save() {
+ let path = temp_file("reopen_mid_save");
+ let mut locks = Locks::new();
+ locks.sync(&[key(&path)], Instant::now());
+ let saving = locks.writer(&key(&path));
+
+ locks.sync(&[], Instant::now());
+ locks.sync(&[key(&path)], Instant::now());
+ assert!(write_through(saving, b"saved").unwrap());
+ locks.sweep(Instant::now());
+ assert!(!exclusive_open_succeeds(&path));
+
+ locks.sync(&[], Instant::now());
+ assert!(exclusive_open_succeeds(&path));
+ std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
+ }
+
+ #[test]
+ fn an_unlocked_path_is_left_to_the_ordinary_write() {
+ let path = temp_file("unlocked");
+ assert!(!write_through(Locks::new().writer(&key(&path)), b"x").unwrap());
+ std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
+ }
+
+ #[test]
+ fn a_launch_file_stays_locked_until_claimed_or_the_grace_runs_out() {
+ let path = temp_file("launch");
+ let start = Instant::now();
+ let mut locks = Locks::new();
+ locks.lock_launch_file(&key(&path), start);
+
+ locks.sync(&[], start + Duration::from_secs(5));
+ assert!(!exclusive_open_succeeds(&path));
+
+ locks.sync(&[], start + LAUNCH_GRACE);
+ assert!(exclusive_open_succeeds(&path));
+ std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
+ }
+
+ #[test]
+ fn an_unclaimed_launch_file_expires_without_another_sync() {
+ let unclaimed = temp_file("expire_unclaimed");
+ let claimed = temp_file("expire_claimed");
+ let start = Instant::now();
+ let mut locks = Locks::new();
+ locks.lock_launch_file(&key(&unclaimed), start);
+ locks.lock_launch_file(&key(&claimed), start);
+ locks.sync(&[key(&claimed)], start + Duration::from_secs(1));
+
+ locks.sweep(start + Duration::from_secs(5));
+ assert!(!exclusive_open_succeeds(&unclaimed));
+
+ locks.sweep(start + LAUNCH_GRACE);
+ assert!(exclusive_open_succeeds(&unclaimed));
+ assert!(!exclusive_open_succeeds(&claimed));
+
+ locks.sync(&[], start + LAUNCH_GRACE);
+ std::fs::remove_dir_all(unclaimed.parent().unwrap()).unwrap();
+ std::fs::remove_dir_all(claimed.parent().unwrap()).unwrap();
+ }
+
+ #[test]
+ fn a_read_only_file_is_held_against_deletion_but_not_written() {
+ let path = temp_file("read_only");
+ let writable = std::fs::metadata(&path).unwrap().permissions();
+ let mut read_only = writable.clone();
+ read_only.set_readonly(true);
+ std::fs::set_permissions(&path, read_only).unwrap();
+
+ // A read-only file refuses write access anyway, so probe with read.
+ let exclusive_read_succeeds = || {
+ use std::os::windows::fs::OpenOptionsExt;
+ std::fs::OpenOptions::new()
+ .read(true)
+ .share_mode(0)
+ .open(&path)
+ .is_ok()
+ };
+ let mut locks = Locks::new();
+ locks.sync(&[key(&path)], Instant::now());
+ assert!(!exclusive_read_succeeds());
+ assert!(!write_through(locks.writer(&key(&path)), b"x").unwrap());
+
+ locks.sync(&[], Instant::now());
+ assert!(exclusive_read_succeeds());
+ std::fs::set_permissions(&path, writable).unwrap();
+ std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
+ }
+}
diff --git a/frontend/src-tauri/src/commands/files.rs b/frontend/src-tauri/src/commands/files.rs
index efaa690d84..2008533ee5 100644
--- a/frontend/src-tauri/src/commands/files.rs
+++ b/frontend/src-tauri/src/commands/files.rs
@@ -9,6 +9,7 @@ static OPENED_FILES: Mutex<Vec<String>> = Mutex::new(Vec::new());
// Add an opened file path
pub fn add_opened_file(file_path: String) {
+ crate::commands::file_lock::lock_launch_file(&file_path);
let mut opened_files = OPENED_FILES.lock().unwrap();
opened_files.push(file_path.clone());
add_log(format!("📂 File stored for later retrieval: {}", file_path));
diff --git a/frontend/src-tauri/src/commands/mod.rs b/frontend/src-tauri/src/commands/mod.rs
index f447cb28cf..8f6aa4f7e7 100644
--- a/frontend/src-tauri/src/commands/mod.rs
+++ b/frontend/src-tauri/src/commands/mod.rs
@@ -3,6 +3,7 @@ pub mod backend;
pub mod connection;
pub mod default_app;
pub mod file_drop;
+pub mod file_lock;
pub mod files;
pub mod fonts;
pub mod local_proxy;
diff --git a/frontend/src-tauri/src/commands/watcher.rs b/frontend/src-tauri/src/commands/watcher.rs
index 09a509ca86..a192a9afb2 100644
--- a/frontend/src-tauri/src/commands/watcher.rs
+++ b/frontend/src-tauri/src/commands/watcher.rs
@@ -216,6 +216,7 @@ fn reconcile(
}
claims.values().flatten().cloned().collect::<Vec<String>>()
};
+ crate::commands::file_lock::sync_locks(&union);
let (routes, dirs) = build_routes(&union);
*ROUTES.lock().map_err(|e| e.to_string())? = Some(Arc::new(routes));
diff --git a/frontend/src-tauri/src/lib.rs b/frontend/src-tauri/src/lib.rs
index 6d1e42c815..c1b8b087c0 100644
--- a/frontend/src-tauri/src/lib.rs
+++ b/frontend/src-tauri/src/lib.rs
@@ -209,6 +209,8 @@ pub fn run() {
clear_opened_files,
file_disk_state,
commands::files::publish_processing_file,
+ commands::file_lock::holds_writable_lock,
+ commands::file_lock::write_locked_file,
watch_disk_paths,
unwatch_disk_paths,
open_in_new_window,
diff --git a/frontend/src/editor/desktop/services/localFileSaveService.test.ts b/frontend/src/editor/desktop/services/localFileSaveService.test.ts
index b625a7c8bc..00a6889958 100644
--- a/frontend/src/editor/desktop/services/localFileSaveService.test.ts
+++ b/frontend/src/editor/desktop/services/localFileSaveService.test.ts
@@ -9,6 +9,10 @@ import type { FileId } from "@editor/types/file";
const writeFile = vi.hoisted(() => vi.fn(async () => undefined));
vi.mock("@tauri-apps/plugin-fs", () => ({ writeFile }));
+// holds_writable_lock / write_locked_file: true when the path is held locked /
+// the save went through that lock.
+const invoke = vi.hoisted(() => vi.fn(async () => false));
+vi.mock("@tauri-apps/api/core", () => ({ invoke, isTauri: () => true }));
const getDiskFileState = vi.hoisted(() =>
vi.fn(async () => ({
@@ -52,6 +56,7 @@ beforeEach(() => {
__resetSelfWrites();
vi.clearAllMocks();
writeFile.mockResolvedValue(undefined);
+ invoke.mockResolvedValue(false);
});
describe("saveToLocalPath", () => {
@@ -64,6 +69,25 @@ describe("saveToLocalPath", () => {
const result = await saveToLocalPath(file, PATH);
expect(result).toEqual({ success: true });
expect(writeFile).toHaveBeenCalledWith(PATH, expected);
+ // Unlocked (always, off Windows): the bytes are sent once, not twice.
+ expect(invoke).toHaveBeenCalledTimes(1);
+ expect(invoke).toHaveBeenCalledWith("holds_writable_lock", { path: PATH });
+ });
+
+ test("saves an open, locked file through its lock instead", async () => {
+ invoke.mockResolvedValue(true);
+ const file = new File([bytes], "report.pdf");
+ const expected = new Uint8Array(await file.arrayBuffer());
+
+ const result = await saveToLocalPath(
+ file,
+ "C:/Akten/Schröder Gläubiger.pdf",
+ );
+ expect(result).toEqual({ success: true });
+ expect(invoke).toHaveBeenCalledWith("write_locked_file", expected, {
+ headers: { path: encodeURIComponent("C:/Akten/Schröder Gläubiger.pdf") },
+ });
+ expect(writeFile).not.toHaveBeenCalled();
});
test("mutes the path so the watcher cannot re-read our own write", async () => {
diff --git a/frontend/src/editor/desktop/services/localFileSaveService.ts b/frontend/src/editor/desktop/services/localFileSaveService.ts
index 0f242f2fbb..d9177ed15c 100644
--- a/frontend/src/editor/desktop/services/localFileSaveService.ts
+++ b/frontend/src/editor/desktop/services/localFileSaveService.ts
@@ -3,6 +3,7 @@ import type {
MultiFileSaveResult,
} from "@editor-core/services/localFileSaveService";
import i18n from "i18next";
+import { invoke } from "@tauri-apps/api/core";
import { beginSelfWrite, endSelfWrite } from "@editor/services/diskFileSync";
export type { SaveResult, MultiFileSaveResult };
import { assertFilesNotBlocked } from "@editor/services/policyFileGuard";
@@ -23,9 +24,19 @@ export async function saveToLocalPath(
beginSelfWrite(filePath);
try {
const { writeFile } = await import("@tauri-apps/plugin-fs");
- const arrayBuffer = await data.arrayBuffer();
+ const bytes = new Uint8Array(await data.arrayBuffer());
assertFilesNotBlocked();
- await writeFile(filePath, new Uint8Array(arrayBuffer));
+ // An open file is held locked (file_lock.rs), which refuses a plain write.
+ // Asked first so the bytes cross IPC once; never true off Windows.
+ const locked = await invoke<boolean>("holds_writable_lock", {
+ path: filePath,
+ });
+ const wroteThroughLock =
+ locked &&
+ (await invoke<boolean>("write_locked_file", bytes, {
+ headers: { path: encodeURIComponent(filePath) },
+ }));
+ if (!wroteThroughLock) await writeFile(filePath, bytes);
return { success: true };
} catch (error) {
endSelfWrite(filePath);