-
Notifications
You must be signed in to change notification settings - Fork 15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: Add Repository::lock_repo #163
Open
aawsome
wants to merge
3
commits into
main
Choose a base branch
from
lock
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,127 @@ | ||
use std::{process::Command, sync::Arc}; | ||
|
||
use anyhow::Result; | ||
use bytes::Bytes; | ||
use chrono::{DateTime, Local}; | ||
use log::{debug, error}; | ||
|
||
use crate::{ | ||
backend::{FileType, ReadBackend, WriteBackend}, | ||
id::Id, | ||
CommandInput, | ||
}; | ||
|
||
/// A backend which warms up files by simply accessing them. | ||
#[derive(Clone, Debug)] | ||
pub struct LockBackend { | ||
/// The backend to use. | ||
be: Arc<dyn WriteBackend>, | ||
/// The command to be called to lock files in the backend | ||
command: CommandInput, | ||
} | ||
|
||
impl LockBackend { | ||
/// Creates a new `WarmUpAccessBackend`. | ||
/// | ||
/// # Arguments | ||
/// | ||
/// * `be` - The backend to use. | ||
pub fn new_lock(be: Arc<dyn WriteBackend>, command: CommandInput) -> Arc<dyn WriteBackend> { | ||
Arc::new(Self { be, command }) | ||
} | ||
} | ||
|
||
impl ReadBackend for LockBackend { | ||
fn location(&self) -> String { | ||
self.be.location() | ||
} | ||
|
||
fn list_with_size(&self, tpe: FileType) -> Result<Vec<(Id, u32)>> { | ||
self.be.list_with_size(tpe) | ||
} | ||
|
||
fn read_full(&self, tpe: FileType, id: &Id) -> Result<Bytes> { | ||
self.be.read_full(tpe, id) | ||
} | ||
|
||
fn read_partial( | ||
&self, | ||
tpe: FileType, | ||
id: &Id, | ||
cacheable: bool, | ||
offset: u32, | ||
length: u32, | ||
) -> Result<Bytes> { | ||
self.be.read_partial(tpe, id, cacheable, offset, length) | ||
} | ||
|
||
fn list(&self, tpe: FileType) -> Result<Vec<Id>> { | ||
self.be.list(tpe) | ||
} | ||
|
||
fn needs_warm_up(&self) -> bool { | ||
self.be.needs_warm_up() | ||
} | ||
|
||
fn warm_up(&self, tpe: FileType, id: &Id) -> Result<()> { | ||
self.be.warm_up(tpe, id) | ||
} | ||
} | ||
|
||
fn path_to_id_from_file_type(tpe: FileType, id: &Id) -> String { | ||
let hex_id = id.to_hex(); | ||
match tpe { | ||
FileType::Config => "config".into(), | ||
FileType::Pack => format!("data/{}/{}", &hex_id[0..2], &*hex_id), | ||
_ => format!("{}/{}", tpe.dirname(), &*hex_id), | ||
} | ||
} | ||
|
||
impl WriteBackend for LockBackend { | ||
fn create(&self) -> Result<()> { | ||
self.be.create() | ||
} | ||
|
||
fn write_bytes(&self, tpe: FileType, id: &Id, cacheable: bool, buf: Bytes) -> Result<()> { | ||
self.be.write_bytes(tpe, id, cacheable, buf) | ||
} | ||
|
||
fn remove(&self, tpe: FileType, id: &Id, cacheable: bool) -> Result<()> { | ||
self.be.remove(tpe, id, cacheable) | ||
} | ||
|
||
fn can_lock(&self) -> bool { | ||
true | ||
} | ||
|
||
fn lock(&self, tpe: FileType, id: &Id, until: Option<DateTime<Local>>) -> Result<()> { | ||
if !self.can_lock() { | ||
return Err(anyhow::anyhow!("No locking configured.")); | ||
} | ||
|
||
let until = until.map_or_else(String::new, |u| u.to_rfc3339()); | ||
|
||
let path = path_to_id_from_file_type(tpe, id); | ||
|
||
let args = self.command.args().iter().map(|c| { | ||
c.replace("%id", &id.to_hex()) | ||
.replace("%type", tpe.dirname()) | ||
.replace("%path", &path) | ||
.replace("%until", &until) | ||
}); | ||
|
||
debug!("calling {:?}...", self.command); | ||
|
||
let status = Command::new(self.command.command()).args(args).status()?; | ||
|
||
if !status.success() { | ||
error!("lock command was not successful for {tpe:?}, id: {id}. {status}"); | ||
|
||
return Err(anyhow::anyhow!( | ||
"lock command was not successful for {tpe:?}, id: {id}. {status}" | ||
)); | ||
} | ||
|
||
Ok(()) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
//! `lock` subcommand | ||
|
||
use chrono::{DateTime, Local}; | ||
use log::error; | ||
use rayon::ThreadPoolBuilder; | ||
|
||
use crate::{ | ||
error::{CommandErrorKind, RepositoryErrorKind, RusticResult}, | ||
progress::{Progress, ProgressBars}, | ||
repofile::{configfile::ConfigId, IndexId, KeyId, PackId, RepoId, SnapshotId}, | ||
repository::Repository, | ||
WriteBackend, | ||
}; | ||
|
||
pub(super) mod constants { | ||
/// The maximum number of reader threads to use for locking. | ||
pub(super) const MAX_LOCKER_THREADS_NUM: usize = 20; | ||
} | ||
|
||
pub fn lock_repo<P: ProgressBars, S>( | ||
repo: &Repository<P, S>, | ||
until: Option<DateTime<Local>>, | ||
) -> RusticResult<()> { | ||
lock_all_files::<P, S, ConfigId>(repo, until)?; | ||
lock_all_files::<P, S, KeyId>(repo, until)?; | ||
lock_all_files::<P, S, SnapshotId>(repo, until)?; | ||
lock_all_files::<P, S, IndexId>(repo, until)?; | ||
lock_all_files::<P, S, PackId>(repo, until)?; | ||
Ok(()) | ||
} | ||
|
||
pub fn lock_all_files<P: ProgressBars, S, ID: RepoId + std::fmt::Debug>( | ||
repo: &Repository<P, S>, | ||
until: Option<DateTime<Local>>, | ||
) -> RusticResult<()> { | ||
if !repo.be.can_lock() { | ||
return Err(CommandErrorKind::NoLockingConfigured.into()); | ||
} | ||
|
||
Comment on lines
+36
to
+39
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I see we check that here, but I think this should be checked within the |
||
let p = &repo | ||
.pb | ||
.progress_spinner(format!("listing {:?} files..", ID::TYPE)); | ||
let ids: Vec<ID> = repo.list()?.collect(); | ||
p.finish(); | ||
lock_files(repo, &ids, until) | ||
} | ||
|
||
fn lock_files<P: ProgressBars, S, ID: RepoId + std::fmt::Debug>( | ||
repo: &Repository<P, S>, | ||
ids: &[ID], | ||
until: Option<DateTime<Local>>, | ||
) -> RusticResult<()> { | ||
let pool = ThreadPoolBuilder::new() | ||
.num_threads(constants::MAX_LOCKER_THREADS_NUM) | ||
.build() | ||
.map_err(RepositoryErrorKind::FromThreadPoolbilderError)?; | ||
let p = &repo | ||
.pb | ||
.progress_counter(format!("locking {:?} files..", ID::TYPE)); | ||
p.set_length(ids.len().try_into().unwrap()); | ||
let backend = &repo.be; | ||
pool.in_place_scope(|scope| { | ||
for id in ids { | ||
scope.spawn(move |_| { | ||
if let Err(err) = backend.lock(ID::TYPE, id, until) { | ||
// FIXME: Use error handling, e.g. use a channel to collect the errors | ||
error!("lock failed for {:?} {id:?}. {err}", ID::TYPE); | ||
}; | ||
p.inc(1); | ||
}); | ||
} | ||
}); | ||
p.finish(); | ||
Ok(()) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
::lock()
should never be callable/running its body, if::can_lock()
isn't returningtrue
, I think?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A type state design might be better suited here
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
But we do have a problem with the type state pattern here: The Repository traits need to be object save as we do create dynamic trait objects here.
Do you know a way to implement a type state pattern in combination with object safety?