gix_lock/lib.rs
1//! git-style registered lock files to make altering resources atomic.
2//!
3//! In this model, reads are always atomic and can be performed directly while writes are facilitated by the locking mechanism
4//! implemented here. Locks are acquired atomically, then written to, to finally atomically overwrite the actual resource.
5//!
6//! Lock files are wrapped [`gix-tempfile`](gix_tempfile)-handles and add the following:
7//!
8//! * consistent naming of lock files
9//! * block the thread (with timeout) or fail immediately if a lock cannot be obtained right away
10//! * commit lock files to atomically put them into the location of the originally locked file
11//!
12//! # Limitations
13//!
14//! * [All limitations of `gix-tempfile`](gix_tempfile) apply. **A highlight of such a limitation is resource leakage
15//! which results in them being permanently locked unless there is user-intervention.**
16//! * As the lock file is separate from the actual resource, locking is merely a convention rather than being enforced.
17//!
18//! ## Examples
19//!
20//! ```
21//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
22//! use std::io::Write;
23//!
24//! # let dir = tempfile::tempdir()?;
25//! let resource = dir.path().join("config");
26//! std::fs::write(&resource, b"old = value\n")?;
27//! let mut lock = gix_lock::File::acquire_to_update_resource(
28//! &resource,
29//! gix_lock::acquire::Fail::Immediately,
30//! None,
31//! )?;
32//! lock.write_all(b"new = value\n")?;
33//! let (resource_path, _) = lock.commit()?;
34//!
35//! assert_eq!(resource_path, resource);
36//! assert_eq!(std::fs::read_to_string(&resource)?, "new = value\n");
37//! # Ok(()) }
38//! ```
39#![deny(missing_docs, rust_2018_idioms, unsafe_code)]
40
41use std::path::PathBuf;
42
43pub use gix_tempfile as tempfile;
44use gix_tempfile::handle::{Closed, Writable};
45
46const DOT_LOCK_SUFFIX: &str = ".lock";
47
48///
49pub mod acquire;
50
51pub use gix_utils::backoff;
52///
53pub mod commit;
54
55/// Locks a resource to eventually be overwritten with the content of this file.
56///
57/// Dropping the file without [committing][File::commit] will delete it, leaving the underlying resource unchanged.
58#[must_use = "A File that is immediately dropped doesn't allow resource updates"]
59#[derive(Debug)]
60pub struct File {
61 inner: gix_tempfile::Handle<Writable>,
62 lock_path: PathBuf,
63}
64
65/// Locks a resource to allow related resources to be updated using [files][File].
66///
67/// As opposed to the [File] type this one won't keep the tempfile open for writing and thus consumes no
68/// system resources, nor can it be persisted.
69#[must_use = "A Marker that is immediately dropped doesn't lock a resource meaningfully"]
70#[derive(Debug)]
71pub struct Marker {
72 inner: gix_tempfile::Handle<Closed>,
73 created_from_file: bool,
74 lock_path: PathBuf,
75}
76
77///
78pub mod file;