use std::fs::{File, OpenOptions};
use std::path::{Path, PathBuf};
use fs4::FileExt;
use crate::cmd::CmdError;
pub struct WalletGuard(#[allow(dead_code)] File);
pub fn acquire(keystore_path: &Path) -> Result<WalletGuard, CmdError> {
let lock_path = lock_path_for(keystore_path);
let f = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&lock_path)
.map_err(|e| CmdError::Usage(format!("open wallet lock {}: {e}", lock_path.display())))?;
FileExt::lock(&f).map_err(|e| {
CmdError::Usage(format!("acquire wallet lock {}: {e}", lock_path.display()))
})?;
Ok(WalletGuard(f))
}
fn lock_path_for(keystore_path: &Path) -> PathBuf {
let parent = keystore_path.parent().unwrap_or_else(|| Path::new("."));
parent.join(".taskfast-wallet.lock")
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use tempfile::TempDir;
#[test]
fn lock_is_exclusive_across_threads() {
let tmp = TempDir::new().unwrap();
let keystore = tmp.path().join("keystore.json");
std::fs::write(&keystore, "{}").unwrap();
let first = acquire(&keystore).expect("first acquire");
let (tx, rx) = mpsc::channel();
let ks = keystore.clone();
let joiner = thread::spawn(move || {
let _g = acquire(&ks).expect("second acquire");
tx.send(()).unwrap();
});
assert!(
rx.recv_timeout(Duration::from_millis(100)).is_err(),
"second acquire must block while first holds the lock"
);
drop(first);
rx.recv_timeout(Duration::from_secs(2))
.expect("second acquire must unblock after first drops");
joiner.join().unwrap();
}
#[test]
fn lock_path_sits_beside_keystore() {
let p = Path::new("/some/dir/agent.keystore.json");
assert_eq!(
lock_path_for(p),
PathBuf::from("/some/dir/.taskfast-wallet.lock")
);
}
}