From c10861c2fb3b24c08a5b976645bc4a59c5c91a7c Mon Sep 17 00:00:00 2001 From: Paul Campbell Date: Sun, 21 Jul 2024 09:32:45 +0100 Subject: [PATCH] WIP: feat: dispatch NotifyUser messages to server actor (2/2) --- crates/git/src/lib.rs | 2 + crates/git/src/user_notification.rs | 27 ++++++++++ crates/git/src/validation/positions.rs | 18 ++++--- .../src/handlers/load_config_from_repo.rs | 26 +++++++--- .../src/handlers/receive_ci_status.rs | 15 +++++- .../src/handlers/register_webhook.rs | 23 ++++----- .../repo-actor/src/handlers/validate_repo.rs | 12 +++-- crates/repo-actor/src/lib.rs | 23 +++++---- crates/repo-actor/src/messages.rs | 3 +- .../tests/handlers/load_config_from_repo.rs | 18 ++----- .../src/tests/handlers/receive_ci_status.rs | 1 - .../src/tests/handlers/validate_repo.rs | 51 +++++++++++++++++-- crates/repo-actor/src/user_notification.rs | 9 ---- 13 files changed, 157 insertions(+), 71 deletions(-) create mode 100644 crates/git/src/user_notification.rs delete mode 100644 crates/repo-actor/src/user_notification.rs diff --git a/crates/git/src/lib.rs b/crates/git/src/lib.rs index a04978e..99a93e0 100644 --- a/crates/git/src/lib.rs +++ b/crates/git/src/lib.rs @@ -10,6 +10,7 @@ mod git_remote; pub mod push; mod repo_details; pub mod repository; +mod user_notification; pub mod validation; #[cfg(test)] @@ -24,3 +25,4 @@ pub use git_remote::GitRemote; pub use repo_details::RepoDetails; pub use repository::OpenRepository; pub use repository::Repository; +pub use user_notification::UserNotification; diff --git a/crates/git/src/user_notification.rs b/crates/git/src/user_notification.rs new file mode 100644 index 0000000..624e0f0 --- /dev/null +++ b/crates/git/src/user_notification.rs @@ -0,0 +1,27 @@ +use crate::Commit; +use git_next_config::{BranchName, ForgeAlias, RepoAlias}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum UserNotification { + CICheckFailed { + forge_alias: ForgeAlias, + repo_alias: RepoAlias, + commit: Commit, + }, + RepoConfigLoadFailure { + forge_alias: ForgeAlias, + repo_alias: RepoAlias, + reason: String, + }, + WebhookRegistration { + forge_alias: ForgeAlias, + repo_alias: RepoAlias, + reason: String, + }, + DevNotBasedOnMain { + forge_alias: ForgeAlias, + repo_alias: RepoAlias, + dev_branch: BranchName, + main_branch: BranchName, + }, +} diff --git a/crates/git/src/validation/positions.rs b/crates/git/src/validation/positions.rs index ff60e2d..247b37b 100644 --- a/crates/git/src/validation/positions.rs +++ b/crates/git/src/validation/positions.rs @@ -1,5 +1,5 @@ // -use crate as git; +use crate::{self as git, UserNotification}; use git_next_config as config; pub type Result = core::result::Result; @@ -40,10 +40,14 @@ pub fn validate_positions( // Validations: // Dev must be on main branch, else the USER must rebase it if is_not_based_on(&commit_histories.dev, &main) { - return Err(Error::UserIntervention(format!( - "Branch '{}' not based on '{}'", - dev_branch, main_branch - ))); + return Err(Error::UserIntervention( + UserNotification::DevNotBasedOnMain { + forge_alias: repo_details.forge.forge_alias().clone(), + repo_alias: repo_details.repo_alias.clone(), + dev_branch, + main_branch, + }, + )); } // verify that next is on main or at most one commit on top of main, else reset it back to main if is_not_based_on( @@ -120,8 +124,8 @@ pub enum Error { #[error("{0} - not retrying")] NonRetryable(String), - #[error("{0} - user intervention required")] - UserIntervention(String), + #[error("user intervention required")] + UserIntervention(UserNotification), } impl From for Error { fn from(value: git::fetch::Error) -> Self { diff --git a/crates/repo-actor/src/handlers/load_config_from_repo.rs b/crates/repo-actor/src/handlers/load_config_from_repo.rs index d270ad5..bff4c35 100644 --- a/crates/repo-actor/src/handlers/load_config_from_repo.rs +++ b/crates/repo-actor/src/handlers/load_config_from_repo.rs @@ -1,5 +1,6 @@ // use actix::prelude::*; +use git_next_git::UserNotification; use tracing::Instrument as _; use crate::{self as actor}; @@ -18,18 +19,27 @@ impl Handler for actor::RepoActor { }; let open_repository = open_repository.duplicate(); let repo_details = self.repo_details.clone(); + let forge_alias = repo_details.forge.forge_alias().clone(); + let repo_alias = repo_details.repo_alias.clone(); let addr = ctx.address(); + let notify_user_recipient = self.notify_user_recipient.clone(); let log = self.log.clone(); async move { match actor::load::config_from_repository(repo_details, &*open_repository).await { - Ok(repo_config) => { - actor::logger(log.as_ref(), "send: LoadedConfig"); - addr.do_send(actor::messages::ReceiveRepoConfig::new(repo_config)) - } - Err(err) => { - tracing::warn!(?err, "Failed to load config"); - // self.notify_user(UserNotification::RepoConfigLoadFailure(err)) - } + Ok(repo_config) => actor::do_send( + addr, + actor::messages::ReceiveRepoConfig::new(repo_config), + log.as_ref(), + ), + Err(err) => actor::notify_user( + notify_user_recipient.as_ref(), + UserNotification::RepoConfigLoadFailure { + forge_alias, + repo_alias, + reason: err.to_string(), + }, + log.as_ref(), + ), } } .in_current_span() diff --git a/crates/repo-actor/src/handlers/receive_ci_status.rs b/crates/repo-actor/src/handlers/receive_ci_status.rs index d5a5e81..38f4473 100644 --- a/crates/repo-actor/src/handlers/receive_ci_status.rs +++ b/crates/repo-actor/src/handlers/receive_ci_status.rs @@ -1,6 +1,7 @@ // -use crate::{self as actor, UserNotification}; +use crate::{self as actor}; use actix::prelude::*; +use git::UserNotification; use git_next_git as git; impl Handler for actor::RepoActor { @@ -15,6 +16,8 @@ impl Handler for actor::RepoActor { actor::logger(log.as_ref(), "start: ReceiveCIStatus"); let addr = ctx.address(); let (next, status) = msg.unwrap(); + let forge_alias = self.repo_details.forge.forge_alias().clone(); + let repo_alias = self.repo_details.repo_alias.clone(); let message_token = self.message_token; let sleep_duration = self.sleep_duration; @@ -37,7 +40,15 @@ impl Handler for actor::RepoActor { } git::forge::commit::Status::Fail => { tracing::warn!("Checks have failed"); - self.notify_user(UserNotification::CICheckFailed(next)); + actor::notify_user( + self.notify_user_recipient.as_ref(), + UserNotification::CICheckFailed { + forge_alias, + repo_alias, + commit: next, + }, + log.as_ref(), + ); actor::delay_send( addr, sleep_duration, diff --git a/crates/repo-actor/src/handlers/register_webhook.rs b/crates/repo-actor/src/handlers/register_webhook.rs index 4ec6f19..ca2a4e2 100644 --- a/crates/repo-actor/src/handlers/register_webhook.rs +++ b/crates/repo-actor/src/handlers/register_webhook.rs @@ -2,8 +2,9 @@ use actix::prelude::*; use tracing::Instrument as _; -use crate::{self as actor, messages::NotifyUser, UserNotification}; +use crate::{self as actor}; use actor::{messages::RegisterWebhook, RepoActor}; +use git_next_git::UserNotification; impl Handler for RepoActor { type Result = (); @@ -29,17 +30,15 @@ impl Handler for RepoActor { ); } Err(err) => { - let msg = NotifyUser::from(UserNotification::WebhookRegistration( - forge_alias, - repo_alias, - err.to_string(), - )); - let log_message = format!("send: {:?}", msg); - tracing::debug!(log_message); - actor::logger(log.as_ref(), log_message); - if let Some(notify_user_recipient) = notify_user_recipient { - notify_user_recipient.do_send(msg); - } + actor::notify_user( + notify_user_recipient.as_ref(), + UserNotification::WebhookRegistration { + forge_alias, + repo_alias, + reason: err.to_string(), + }, + log.as_ref(), + ); } } } diff --git a/crates/repo-actor/src/handlers/validate_repo.rs b/crates/repo-actor/src/handlers/validate_repo.rs index 3fc86cf..4e04bf1 100644 --- a/crates/repo-actor/src/handlers/validate_repo.rs +++ b/crates/repo-actor/src/handlers/validate_repo.rs @@ -100,13 +100,17 @@ impl Handler for actor::RepoActor { .into_actor(self) .wait(ctx); } - Err(git::validation::positions::Error::NonRetryable(message)) - | Err(git::validation::positions::Error::UserIntervention(message)) => { + Err(git::validation::positions::Error::UserIntervention(user_notification)) => { + actor::notify_user( + self.notify_user_recipient.as_ref(), + user_notification, + self.log.as_ref(), + ) + } + Err(git::validation::positions::Error::NonRetryable(message)) => { actor::logger(self.log.as_ref(), message); } } - - tracing::debug!("Handler: ValidateRepo: finish"); } } diff --git a/crates/repo-actor/src/lib.rs b/crates/repo-actor/src/lib.rs index 4e0557f..73c2bfc 100644 --- a/crates/repo-actor/src/lib.rs +++ b/crates/repo-actor/src/lib.rs @@ -2,7 +2,6 @@ mod branch; pub mod handlers; mod load; pub mod messages; -mod user_notification; #[cfg(test)] mod tests; @@ -13,9 +12,8 @@ use actix::prelude::*; use derive_more::Deref; use git_next_config as config; -use git_next_git as git; +use git_next_git::{self as git, UserNotification}; use messages::NotifyUser; -pub use user_notification::UserNotification; use kxio::network::Network; use tracing::{info, warn, Instrument}; @@ -85,12 +83,6 @@ impl RepoActor { notify_user_recipient, } } - - fn notify_user(&mut self, user_notification: UserNotification) { - if let Some(recipient) = &self.notify_user_recipient { - recipient.do_send(NotifyUser::from(user_notification)); - } - } } impl Actor for RepoActor { type Context = Context; @@ -151,3 +143,16 @@ pub fn logger(log: Option<&RepoActorLog>, message: impl Into) { let _ = log.write().map(|mut l| l.push(message)); } } +pub fn notify_user( + recipient: Option<&Recipient>, + user_notification: UserNotification, + log: Option<&RepoActorLog>, +) { + let msg = NotifyUser::from(user_notification); + let log_message = format!("send: {:?}", msg); + tracing::debug!(log_message); + logger(log, log_message); + if let Some(recipient) = &recipient { + recipient.do_send(msg); + } +} diff --git a/crates/repo-actor/src/messages.rs b/crates/repo-actor/src/messages.rs index 7a61491..65e3a8f 100644 --- a/crates/repo-actor/src/messages.rs +++ b/crates/repo-actor/src/messages.rs @@ -2,12 +2,11 @@ use config::newtype; use derive_more::Display; +use git::UserNotification; use git_next_actor_macros::message; use git_next_config as config; use git_next_git as git; -use crate::UserNotification; - message!(LoadConfigFromRepo: "Request to load the `git-next.toml` from the git repo."); message!(CloneRepo: "Request to clone (or open) the git repo."); message!(ReceiveRepoConfig: config::RepoConfig: r#"Notification that the `git-next.toml` file has been loaded from the repo and parsed. diff --git a/crates/repo-actor/src/tests/handlers/load_config_from_repo.rs b/crates/repo-actor/src/tests/handlers/load_config_from_repo.rs index ce8022c..98de118 100644 --- a/crates/repo-actor/src/tests/handlers/load_config_from_repo.rs +++ b/crates/repo-actor/src/tests/handlers/load_config_from_repo.rs @@ -45,16 +45,12 @@ async fn when_read_file_ok_should_send_config_loaded() -> TestResult { //then tracing::debug!(?log, ""); - log.read().map_err(|e| e.to_string()).map(|l| { - assert!(l - .iter() - .any(|message| message.contains("send: LoadedConfig"))) - })?; + log.require_message_containing("send: ReceiveRepoConfig")?; + log.no_message_contains("send: NotifyUsers")?; Ok(()) } #[actix::test] -#[ignore] //TODO: (#95) should notify user async fn when_read_file_err_should_notify_user() -> TestResult { //given let fs = given::a_filesystem(); @@ -80,13 +76,7 @@ async fn when_read_file_err_should_notify_user() -> TestResult { //then tracing::debug!(?log, ""); - log.read().map_err(|e| e.to_string()).map(|l| { - assert!(l.iter().any(|message| message.contains("send: NotifyUser"))); - assert!( - !l.iter() - .any(|message| message.contains("send: LoadedConfig")), - "not send LoadedConfig" - ); - })?; + log.require_message_containing("send: NotifyUser")?; + log.no_message_contains("send: ReceiveRepoConfig")?; Ok(()) } diff --git a/crates/repo-actor/src/tests/handlers/receive_ci_status.rs b/crates/repo-actor/src/tests/handlers/receive_ci_status.rs index d0a87f8..9d8ff1d 100644 --- a/crates/repo-actor/src/tests/handlers/receive_ci_status.rs +++ b/crates/repo-actor/src/tests/handlers/receive_ci_status.rs @@ -88,7 +88,6 @@ async fn when_fail_should_recheck_after_delay() -> TestResult { } #[test_log::test(actix::test)] -#[ignore] //TODO: (#95) should notify user async fn when_fail_should_notify_user() -> TestResult { //given let fs = given::a_filesystem(); diff --git a/crates/repo-actor/src/tests/handlers/validate_repo.rs b/crates/repo-actor/src/tests/handlers/validate_repo.rs index 8fca719..4b2b1cc 100644 --- a/crates/repo-actor/src/tests/handlers/validate_repo.rs +++ b/crates/repo-actor/src/tests/handlers/validate_repo.rs @@ -279,7 +279,52 @@ async fn repo_with_dev_ahead_of_next_should_advance_next() -> TestResult { Ok(()) } -// TODO: (#95) test: repo with dev not a child of main should notify user +#[test_log::test(actix::test)] +async fn repo_with_dev_not_ahead_of_main_should_notify_user() -> TestResult { + //given + let fs = given::a_filesystem(); + let (mut open_repository, repo_details) = given::an_open_repository(&fs); + #[allow(clippy::unwrap_used)] + let repo_config = repo_details.repo_config.clone().unwrap(); + // Validate repo branches + expect::fetch_ok(&mut open_repository); + let branches = repo_config.branches(); + // commit_log main + let main_commit = expect::main_commit_log(&mut open_repository, branches.main()); + // next - on main + let next_commit = main_commit.clone(); + let next_branch_log = vec![next_commit.clone(), given::a_commit()]; + // dev - not ahead of next + let dev_commit = given::a_named_commit("dev"); + let dev_branch_log = vec![dev_commit]; + // commit_log next + open_repository + .expect_commit_log() + .times(1) + .with(eq(branches.next()), eq([main_commit.clone()])) + .return_once(move |_, _| Ok(next_branch_log)); + // commit_log dev + let dev_commit_log = dev_branch_log.clone(); + open_repository + .expect_commit_log() + .times(1) + .with(eq(branches.dev()), eq([main_commit])) + .return_once(move |_, _| Ok(dev_commit_log)); + + //when + let (addr, log) = when::start_actor_with_open_repository( + Box::new(open_repository), + repo_details, + given::a_forge(), + ); + addr.send(crate::messages::ValidateRepo::new(MessageToken::default())) + .await?; + System::current().stop(); + + //then + log.require_message_containing("send: NotifyUser")?; + Ok(()) +} #[test_log::test(actix::test)] async fn should_accept_message_with_current_token() -> TestResult { @@ -382,7 +427,7 @@ async fn should_send_validate_repo_when_retryable_error() -> TestResult { } #[test_log::test(actix::test)] -async fn should_send_nothing_when_non_retryable_error() -> TestResult { +async fn should_send_notify_user_when_non_retryable_error() -> TestResult { //given let fs = given::a_filesystem(); let (mut open_repository, repo_details) = given::an_open_repository(&fs); @@ -424,6 +469,6 @@ async fn should_send_nothing_when_non_retryable_error() -> TestResult { //then log.require_message_containing("accepted token")?; - log.no_message_contains("send:")?; + log.require_message_containing("send: NotifyUser")?; Ok(()) } diff --git a/crates/repo-actor/src/user_notification.rs b/crates/repo-actor/src/user_notification.rs deleted file mode 100644 index f4a91e6..0000000 --- a/crates/repo-actor/src/user_notification.rs +++ /dev/null @@ -1,9 +0,0 @@ -use git_next_config::{ForgeAlias, RepoAlias}; -use git_next_git::Commit; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum UserNotification { - CICheckFailed(Commit), - RepoConfigLoadFailure(String), - WebhookRegistration(ForgeAlias, RepoAlias, String), -}