agent_sdk/task/
file_lock.rs1use fs2::FileExt;
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use crate::error::{SdkError, SdkResult};
6
7pub struct FileLock {
8 file: fs::File,
9 path: PathBuf,
10}
11
12impl FileLock {
13 pub fn try_acquire(path: &Path) -> SdkResult<Option<Self>> {
14 let file = fs::OpenOptions::new()
15 .read(true)
16 .write(true)
17 .create(true)
18 .truncate(false)
19 .open(path)
20 .map_err(SdkError::Io)?;
21
22 match file.try_lock_exclusive() {
23 Ok(()) => Ok(Some(FileLock {
24 file,
25 path: path.to_owned(),
26 })),
27 Err(_) => Ok(None),
28 }
29 }
30
31 pub fn acquire_blocking(path: &Path) -> SdkResult<Self> {
32 let file = fs::OpenOptions::new()
33 .read(true)
34 .write(true)
35 .create(true)
36 .truncate(false)
37 .open(path)
38 .map_err(SdkError::Io)?;
39
40 file.lock_exclusive()
41 .map_err(|_| SdkError::LockFailed {
42 path: path.to_owned(),
43 })?;
44
45 Ok(FileLock {
46 file,
47 path: path.to_owned(),
48 })
49 }
50
51 pub fn path(&self) -> &Path {
52 &self.path
53 }
54
55 pub fn file(&self) -> &fs::File {
56 &self.file
57 }
58}
59
60impl Drop for FileLock {
61 fn drop(&mut self) {
62 let _ = self.file.unlock();
63 }
64}