advisory-lock-0.3.0/.cargo_vcs_info.json0000644000000001121377322473600136700ustar { "git": { "sha1": "1b9629d66121fc958554b857cef59a8fa7ce27ea" } } advisory-lock-0.3.0/.github/workflows/ci.yml000064400000000000000000000036411377322440100171500ustar 00000000000000name: ci on: pull_request: push: branches: [master] tags: ['**'] env: # Just a reassurance to mitigate sudden network connection problems CARGO_NET_RETRY: 10 RUSTUP_MAX_RETRIES: 10 CARGO_INCREMENTAL: 0 RUST_BACKTRACE: full # We don't need any debug symbols on ci, this also speeds up builds a bunch RUSTFLAGS: --deny warnings -Cdebuginfo=0 RUSTDOCFLAGS: --deny warnings jobs: rust-lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal components: rustfmt, clippy - run: cargo clippy --workspace - run: cargo fmt --all -- --check rust-test: runs-on: ${{ matrix.os }} # We don't want unstable jobs to fail our cicd continue-on-error: ${{ matrix.toolchain != 'stable' }} strategy: matrix: os: [ubuntu-latest, windows-latest, macos-latest] toolchain: [stable] include: - { os: ubuntu-latest, toolchain: beta } - { os: ubuntu-latest, toolchain: nightly } steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.toolchain }} profile: minimal - run: cargo +${{ matrix.toolchain }} build --workspace - run: cargo +${{ matrix.toolchain }} test --workspace --no-run - run: cargo +${{ matrix.toolchain }} test --workspace rust-publish-crate: # Publishing goes when we create a new git tag on the repo if: startsWith(github.ref, 'refs/tags/') runs-on: ubuntu-latest # XXX: this job must execute only if all checks pass! needs: - rust-lint - rust-test steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal - run: cargo publish --token ${{ secrets.CRATES_TOKEN }}) advisory-lock-0.3.0/.gitignore000064400000000000000000000000321370326063600144170ustar 00000000000000/target Cargo.lock /.ideaadvisory-lock-0.3.0/Cargo.toml0000644000000020121377322473600116670ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "advisory-lock" version = "0.3.0" authors = ["topecongiro"] description = "A cross-platform advisory file lock." categories = ["filesystem", "os::unix-apis", "os::windows-apis"] license = "MIT" repository = "https://github.com/topecongiro/advisory-lock-rs" [dependencies] [target."cfg(target_family = \"unix\")".dependencies.libc] version = "0.2" [target."cfg(windows)".dependencies.winapi] version = "0.3" features = ["errhandlingapi", "fileapi", "minwinbase", "winerror"] advisory-lock-0.3.0/Cargo.toml.orig000064400000000000000000000011261377322454100153250ustar 00000000000000[package] name = "advisory-lock" version = "0.3.0" authors = ["topecongiro"] edition = "2018" license = "MIT" description = "A cross-platform advisory file lock." categories = ["filesystem", "os::unix-apis", "os::windows-apis"] repository = "https://github.com/topecongiro/advisory-lock-rs" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] [target.'cfg(windows)'.dependencies.winapi] version = "0.3" features = ["errhandlingapi", "fileapi", "minwinbase", "winerror"] [target.'cfg(target_family = "unix")'.dependencies] libc = "0.2" advisory-lock-0.3.0/LICENSE000064400000000000000000000020571370334246600134470ustar 00000000000000MIT License Copyright (c) 2020 Seiichi Uchida Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. advisory-lock-0.3.0/README.md000064400000000000000000000002621377322443400137160ustar 00000000000000[docs]: https://docs.rs/advisory-lock # advisory-lock-rs A cross-platform advisory file lock in Rust. For detailed documentation please visit [`docs.rs/advisory-locks`][docs]. advisory-lock-0.3.0/src/lib.rs000064400000000000000000000137461377322414400143530ustar 00000000000000//! Advisory lock provides simple and convenient API for using file locks. //! //! These are called advisory because they don't prevent other processes from //! accessing the files directly, bypassing the locks. //! However, if multiple processes agree on acquiring file locks, they should //! work as expected. //! //! The main entity of the crate is [`AdvisoryFileLock`] which is effectively //! a [`RwLock`] but for [`File`]. //! //! Example: //! ``` //! use std::fs::File; //! use advisory_lock::{AdvisoryFileLock, FileLockMode, FileLockError}; //! # //! # //! // Create the file and obtain its exclusive advisory lock //! let exclusive_file = File::create("foo.txt").unwrap(); //! exclusive_file.lock(FileLockMode::Exclusive)?; //! //! let shared_file = File::open("foo.txt")?; //! //! // Try to acquire the lock in non-blocking way //! assert!(matches!(shared_file.try_lock(FileLockMode::Shared), Err(FileLockError::AlreadyLocked))); //! //! exclusive_file.unlock()?; //! //! shared_file.try_lock(FileLockMode::Shared).expect("Works, because the exclusive lock was released"); //! //! let shared_file_2 = File::open("foo.txt")?; //! //! shared_file_2.lock(FileLockMode::Shared).expect("Should be fine to have multiple shared locks"); //! //! // Nope, now we have to wait until all shared locks are released... //! assert!(matches!(exclusive_file.try_lock(FileLockMode::Exclusive), Err(FileLockError::AlreadyLocked))); //! //! // We can unlock them explicitly and handle the potential error //! shared_file.unlock()?; //! // Or drop the lock, such that we `log::error!()` if it happens and discard it //! drop(shared_file_2); //! //! exclusive_file.lock(FileLockMode::Exclusive).expect("All other locks should have been released"); //! # //! # std::fs::remove_file("foo.txt")?; //! # Ok::<(), Box>(()) //! ``` //! //! [`AdvisoryFileLock`]: struct.AdvisoryFileLock.html //! [`RwLock`]: https://doc.rust-lang.org/stable/std/sync/struct.RwLock.html //! [`File`]: https://doc.rust-lang.org/stable/std/fs/struct.File.html use std::{fmt, io}; #[cfg(windows)] mod windows; #[cfg(unix)] mod unix; /// An enumeration of possible errors which can occur while trying to acquire a lock. #[derive(Debug)] pub enum FileLockError { /// The file is already locked by other process. AlreadyLocked, /// The error occurred during I/O operations. Io(io::Error), } impl fmt::Display for FileLockError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { FileLockError::AlreadyLocked => f.write_str("the file is already locked"), FileLockError::Io(err) => write!(f, "I/O error: {}", err), } } } impl std::error::Error for FileLockError {} /// An enumeration of types which represents how to acquire an advisory lock. #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum FileLockMode { /// Obtain an exclusive file lock. Exclusive, /// Obtain a shared file lock. Shared, } /// An advisory lock for files. /// /// An advisory lock provides a mutual-exclusion mechanism among processes which explicitly /// acquires and releases the lock. Processes that are not aware of the lock will ignore it. /// /// `AdvisoryFileLock` provides following features: /// - Blocking or non-blocking operations. /// - Shared or exclusive modes. /// - All operations are thread-safe. /// /// ## Notes /// /// `AdvisoryFileLock` has following limitations: /// - Locks are allowed only on files, but not directories. pub trait AdvisoryFileLock { /// Acquire the advisory file lock. /// /// `lock` is blocking; it will block the current thread until it succeeds or errors. fn lock(&self, file_lock_mode: FileLockMode) -> Result<(), FileLockError>; /// Try to acquire the advisory file lock. /// /// `try_lock` returns immediately. fn try_lock(&self, file_lock_mode: FileLockMode) -> Result<(), FileLockError>; /// Unlock this advisory file lock. fn unlock(&self) -> Result<(), FileLockError>; } #[cfg(test)] mod tests { use super::*; use std::env::temp_dir; use std::fs::File; #[test] fn simple_shared_lock() { let mut test_file = temp_dir(); test_file.push("shared_lock"); File::create(&test_file).unwrap(); { let f1 = File::open(&test_file).unwrap(); f1.lock(FileLockMode::Shared).unwrap(); let f2 = File::open(&test_file).unwrap(); f2.lock(FileLockMode::Shared).unwrap(); } std::fs::remove_file(&test_file).unwrap(); } #[test] fn simple_exclusive_lock() { let mut test_file = temp_dir(); test_file.push("exclusive_lock"); File::create(&test_file).unwrap(); { let f1 = File::open(&test_file).unwrap(); f1.lock(FileLockMode::Exclusive).unwrap(); let f2 = File::open(&test_file).unwrap(); assert!(f2.try_lock(FileLockMode::Exclusive).is_err()); } std::fs::remove_file(&test_file).unwrap(); } #[test] fn simple_shared_exclusive_lock() { let mut test_file = temp_dir(); test_file.push("shared_exclusive_lock"); File::create(&test_file).unwrap(); { let f1 = File::open(&test_file).unwrap(); f1.lock(FileLockMode::Shared).unwrap(); let f2 = File::open(&test_file).unwrap(); assert!(matches!( f2.try_lock(FileLockMode::Exclusive), Err(FileLockError::AlreadyLocked) )); } std::fs::remove_file(&test_file).unwrap(); } #[test] fn simple_exclusive_shared_lock() { let mut test_file = temp_dir(); test_file.push("exclusive_shared_lock"); File::create(&test_file).unwrap(); { let f1 = File::open(&test_file).unwrap(); f1.lock(FileLockMode::Exclusive).unwrap(); let f2 = File::open(&test_file).unwrap(); assert!(f2.try_lock(FileLockMode::Shared).is_err()); } std::fs::remove_file(&test_file).unwrap(); } } advisory-lock-0.3.0/src/unix.rs000064400000000000000000000035001377322445600145610ustar 00000000000000use std::fs::File; use std::io::Error; use std::os::unix::io::{AsRawFd, RawFd}; use crate::{AdvisoryFileLock, FileLockError, FileLockMode}; impl AdvisoryFileLock for File { fn lock(&self, file_lock_mode: FileLockMode) -> Result<(), FileLockError> { self.as_raw_fd().lock(file_lock_mode) } fn try_lock(&self, file_lock_mode: FileLockMode) -> Result<(), FileLockError> { self.as_raw_fd().try_lock(file_lock_mode) } fn unlock(&self) -> Result<(), FileLockError> { self.as_raw_fd().unlock() } } impl AdvisoryFileLock for RawFd { fn lock(&self, file_lock_mode: FileLockMode) -> Result<(), FileLockError> { lock_file(*self, file_lock_mode, false) } fn try_lock(&self, file_lock_mode: FileLockMode) -> Result<(), FileLockError> { lock_file(*self, file_lock_mode, true) } fn unlock(&self) -> Result<(), FileLockError> { unlock_file(*self) } } fn lock_file( raw_fd: RawFd, file_lock_mode: FileLockMode, immediate: bool, ) -> Result<(), FileLockError> { let mut flags = match file_lock_mode { FileLockMode::Shared => libc::LOCK_SH, FileLockMode::Exclusive => libc::LOCK_EX, }; if immediate { flags |= libc::LOCK_NB; } let result = unsafe { libc::flock(raw_fd, flags) }; if result != 0 { let last_os_error = Error::last_os_error(); return Err(match last_os_error.raw_os_error() { Some(code) if code == libc::EWOULDBLOCK => FileLockError::AlreadyLocked, _ => FileLockError::Io(last_os_error), }); } Ok(()) } fn unlock_file(raw_fd: RawFd) -> Result<(), FileLockError> { let result = unsafe { libc::flock(raw_fd, libc::LOCK_UN) }; if result == 0 { Ok(()) } else { Err(FileLockError::Io(Error::last_os_error())) } } advisory-lock-0.3.0/src/windows.rs000064400000000000000000000063521377322433400152730ustar 00000000000000use std::fs::File; use std::io; use std::os::windows::io::{AsRawHandle, RawHandle}; use winapi::{ shared::{ minwindef::TRUE, ntdef::NULL, winerror::{ERROR_LOCK_VIOLATION, ERROR_NOT_LOCKED}, }, um::{ errhandlingapi::GetLastError, fileapi::{LockFileEx, UnlockFileEx}, minwinbase::{ OVERLAPPED_u, OVERLAPPED_u_s, LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY, OVERLAPPED, }, }, }; use crate::{AdvisoryFileLock, FileLockError, FileLockMode}; impl AdvisoryFileLock for File { fn lock(&self, file_lock_mode: FileLockMode) -> Result<(), FileLockError> { lock_file(self.as_raw_handle(), file_lock_mode, false) } fn try_lock(&self, file_lock_mode: FileLockMode) -> Result<(), FileLockError> { lock_file(self.as_raw_handle(), file_lock_mode, true) } fn unlock(&self) -> Result<(), FileLockError> { unlock_file(self.as_raw_handle()) } } impl AdvisoryFileLock for RawHandle { fn lock(&self, file_lock_mode: FileLockMode) -> Result<(), FileLockError> { lock_file(*self, file_lock_mode, false) } fn try_lock(&self, file_lock_mode: FileLockMode) -> Result<(), FileLockError> { lock_file(*self, file_lock_mode, true) } fn unlock(&self) -> Result<(), FileLockError> { unlock_file(*self) } } fn create_overlapped() -> OVERLAPPED { let overlapped = unsafe { let mut overlapped = std::mem::zeroed::(); *overlapped.s_mut() = OVERLAPPED_u_s { Offset: u32::MAX, OffsetHigh: u32::MAX, }; overlapped }; OVERLAPPED { Internal: usize::MAX, InternalHigh: usize::MAX, u: overlapped, hEvent: NULL, } } fn lock_file( raw_handle: RawHandle, file_lock_mode: FileLockMode, immediate: bool, ) -> Result<(), FileLockError> { let mut overlapped = create_overlapped(); let mut flags = 0; if file_lock_mode == FileLockMode::Exclusive { flags |= LOCKFILE_EXCLUSIVE_LOCK; } if immediate { flags |= LOCKFILE_FAIL_IMMEDIATELY; } let result = unsafe { LockFileEx( raw_handle as *mut winapi::ctypes::c_void, flags, 0, 1, 0, &mut overlapped, ) }; if result != TRUE { return match unsafe { GetLastError() } { ERROR_LOCK_VIOLATION => Err(FileLockError::AlreadyLocked), raw_error => Err(FileLockError::Io(io::Error::from_raw_os_error( raw_error as i32, ))), }; } Ok(()) } fn unlock_file(raw_handle: RawHandle) -> Result<(), FileLockError> { let mut overlapped = create_overlapped(); let result = unsafe { UnlockFileEx( raw_handle as *mut winapi::ctypes::c_void, 0, 1, 0, &mut overlapped, ) }; if result == TRUE { Ok(()) } else { let raw_error = unsafe { GetLastError() }; if raw_error == ERROR_NOT_LOCKED { Ok(()) } else { Err(FileLockError::Io(io::Error::from_raw_os_error( raw_error as i32, ))) } } }