-
Notifications
You must be signed in to change notification settings - Fork 48
Add repository caching and enqueue clone on startup #721
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
Open
reddevilmidzy
wants to merge
3
commits into
rust-lang:main
Choose a base branch
from
reddevilmidzy:local
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.
+181
−42
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 hidden or 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 hidden or 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 |
|---|---|---|
|
|
@@ -8,9 +8,12 @@ use secrecy::SecretString; | |
| use std::collections::HashSet; | ||
| use std::fmt::{Debug, Formatter}; | ||
| use std::future::Future; | ||
| #[cfg(not(test))] | ||
| use std::path::PathBuf; | ||
| use std::pin::Pin; | ||
| use std::sync::{Arc, RwLock}; | ||
| use std::time::Duration; | ||
| use tempfile::TempDir; | ||
| use tokio::sync::mpsc; | ||
| use tracing::Instrument; | ||
|
|
||
|
|
@@ -21,6 +24,9 @@ const GITOPS_QUEUE_CAPACITY: usize = 3; | |
| /// Maximum duration of a local git operation before it times out. | ||
| const GITOP_TIMEOUT: Duration = Duration::from_secs(60); | ||
|
|
||
| /// Special pull request number used for clone operations. | ||
| const CLONE_PR_NUMBER: PullRequestNumber = PullRequestNumber(0); | ||
|
|
||
| #[derive(Debug, Hash, PartialEq, Eq, Clone)] | ||
| pub struct PullRequestId { | ||
| pub repo: GithubRepoName, | ||
|
|
@@ -35,6 +41,8 @@ pub struct GitOpsQueueEntry { | |
|
|
||
| struct GitOpsSharedState { | ||
| git: Option<Git>, | ||
| /// Temporary directory used for caching local repository clones. | ||
| cache_dir: TempDir, | ||
| /// Pull requests on which a local git operation is currently queued or in-progress. | ||
| pending_prs: HashSet<PullRequestId>, | ||
| } | ||
|
|
@@ -80,20 +88,49 @@ impl GitOpsQueueSender { | |
| } | ||
| } | ||
| } | ||
|
|
||
| pub fn enqueue_clone_repository(&self, repository: GithubRepoName) -> anyhow::Result<bool> { | ||
| let log_repo = repository.clone(); | ||
| let pr_id = PullRequestId { | ||
| repo: repository.clone(), | ||
| pr: CLONE_PR_NUMBER, | ||
| }; | ||
| let command = GitOpsCommand::CloneRepository(CloneRepositoryCommand { | ||
| repository, | ||
| on_finish: Box::new(|result| { | ||
| Box::pin(async move { | ||
| if let Err(error) = result { | ||
| tracing::warn!( | ||
| "Repository cache initialization failed for {log_repo}: {error:?}" | ||
| ); | ||
| } | ||
| Ok(()) | ||
| }) | ||
| }), | ||
| }); | ||
| self.try_send(pr_id, command) | ||
| } | ||
| } | ||
|
|
||
| /// Command that can be executed by the gitops queue. | ||
| #[derive(Debug)] | ||
| pub enum GitOpsCommand { | ||
| /// Push a commit from one repository to another. | ||
| Push(PushCommand), | ||
| /// Clone or initialize a repository cache for later operations. | ||
| CloneRepository(CloneRepositoryCommand), | ||
| } | ||
|
|
||
| pub type PushCallback = Box< | ||
| dyn FnOnce(anyhow::Result<()>) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send>> | ||
| + Send, | ||
| >; | ||
|
|
||
| pub type CloneCallback = Box< | ||
| dyn FnOnce(anyhow::Result<()>) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send>> | ||
| + Send, | ||
| >; | ||
|
|
||
| /// Force push `commit` from `source_repo` to `target_branch` of `target_repo`. | ||
| /// Use `token` for authentication. | ||
| /// | ||
|
|
@@ -107,6 +144,23 @@ pub struct PushCommand { | |
| pub on_finish: PushCallback, | ||
| } | ||
|
|
||
| pub struct CloneRepositoryCommand { | ||
| pub repository: GithubRepoName, | ||
| pub on_finish: CloneCallback, | ||
| } | ||
|
|
||
| impl Debug for CloneRepositoryCommand { | ||
| fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { | ||
| let Self { | ||
| repository, | ||
| on_finish: _, | ||
| } = self; | ||
| f.debug_struct("CloneRepositoryCommand") | ||
| .field("repository", repository) | ||
| .finish() | ||
| } | ||
| } | ||
|
|
||
| impl Debug for PushCommand { | ||
| fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { | ||
| let Self { | ||
|
|
@@ -128,9 +182,23 @@ impl Debug for PushCommand { | |
|
|
||
| pub fn create_gitops_queue(git: Option<Git>) -> (GitOpsQueueSender, GitOpsQueueReceiver) { | ||
| let (tx, rx) = mpsc::channel(GITOPS_QUEUE_CAPACITY); | ||
| #[cfg(test)] | ||
| let cache_dir = tempfile::Builder::new() | ||
| .prefix("bors-gitops-cache-") | ||
| .tempdir() | ||
| .expect("Cannot create gitops cache temp dir"); | ||
| #[cfg(not(test))] | ||
| let cache_dir = { | ||
| let base_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); | ||
| tempfile::Builder::new() | ||
| .prefix("gitops-cache-") | ||
| .tempdir_in(&base_dir) | ||
| .expect("Cannot create gitops cache temp dir") | ||
| }; | ||
|
Comment on lines
+185
to
+197
Member
Author
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 create the cache |
||
| let state = Arc::new(RwLock::new(GitOpsSharedState { | ||
| pending_prs: Default::default(), | ||
| git, | ||
| cache_dir, | ||
| })); | ||
| ( | ||
| GitOpsQueueSender { | ||
|
|
@@ -164,7 +232,10 @@ pub async fn handle_gitops_entry( | |
| "{source_repo}:{commit} -> {target_repo}:{target_branch}" | ||
| ); | ||
|
|
||
| let git = rx.state.read().unwrap().git.clone(); | ||
| let (git, _cache_dir) = { | ||
| let state = rx.state.read().unwrap(); | ||
| (state.git.clone(), state.cache_dir.path().to_path_buf()) | ||
| }; | ||
| let res = if let Some(_git) = git { | ||
| let fut = async move { | ||
| use std::time::Instant; | ||
|
|
@@ -173,15 +244,20 @@ pub async fn handle_gitops_entry( | |
| #[cfg(test)] | ||
| let res = anyhow::Ok(()); | ||
| #[cfg(not(test))] | ||
| let res = _git | ||
| .transfer_commit_between_repositories( | ||
| &source_repo, | ||
| let res = async { | ||
| let repo_path = _cache_dir.join(source_repo.to_string()); | ||
| _git.prepare_repository_for_commit(&repo_path, &source_repo, &commit) | ||
| .await?; | ||
| _git.transfer_commit_between_repositories( | ||
| &repo_path, | ||
| &target_repo, | ||
| &commit, | ||
| &target_branch, | ||
| _token, | ||
| ) | ||
| .await; | ||
| .await | ||
| } | ||
| .await; | ||
| tracing::trace!("Push took {:.3}s", start.elapsed().as_secs_f64()); | ||
| res | ||
| } | ||
|
|
@@ -204,6 +280,42 @@ pub async fn handle_gitops_entry( | |
| } | ||
| Ok(()) | ||
| } | ||
| GitOpsCommand::CloneRepository(CloneRepositoryCommand { | ||
| repository, | ||
| on_finish, | ||
| }) => { | ||
| let span = tracing::debug_span!("clone repository cache", "{repository}"); | ||
| let (git, cache_dir) = { | ||
| let state = rx.state.read().unwrap(); | ||
| (state.git.clone(), state.cache_dir.path().to_path_buf()) | ||
| }; | ||
| let res = if let Some(_git) = git { | ||
| let fut = async move { | ||
| let _repo_path = cache_dir.join(repository.to_string()); | ||
| #[cfg(test)] | ||
| let res = anyhow::Ok(()); | ||
| #[cfg(not(test))] | ||
| let res = _git.init_repository_cache(&_repo_path).await; | ||
| res | ||
| } | ||
| .instrument(span.clone()); | ||
| match tokio::time::timeout(GITOP_TIMEOUT, fut).await { | ||
| Ok(res) => res, | ||
| Err(_) => Err(anyhow::anyhow!("Clone timeouted")), | ||
| } | ||
| } else { | ||
| Err(anyhow::anyhow!("Local git is not available")) | ||
| }; | ||
| if let Err(error) = on_finish(res).instrument(span.clone()).await { | ||
| span.in_scope(|| { | ||
| tracing::error!("Completion callback failed: {error:?}"); | ||
| }); | ||
|
|
||
| #[cfg(test)] | ||
| return Err(error); | ||
| } | ||
| Ok(()) | ||
| } | ||
| } | ||
| }; | ||
|
|
||
|
|
||
This file contains hidden or 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.
I use
CLONE_PR_NUMBER = 0as a synthetic PR ID for clone tasks. Is this OK?