feat: dispatch NotifyUser messages to server for user (2/2)

This commit is contained in:
Paul Campbell 2024-07-21 09:32:45 +01:00
parent 4978400ece
commit 288c20c24b
13 changed files with 157 additions and 71 deletions

View file

@ -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;

View file

@ -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,
},
}

View file

@ -1,5 +1,5 @@
//
use crate as git;
use crate::{self as git, UserNotification};
use git_next_config as config;
pub type Result<T> = core::result::Result<T, Error>;
@ -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<git::fetch::Error> for Error {
fn from(value: git::fetch::Error) -> Self {

View file

@ -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<actor::messages::LoadConfigFromRepo> 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()

View file

@ -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<actor::messages::ReceiveCIStatus> for actor::RepoActor {
@ -15,6 +16,8 @@ impl Handler<actor::messages::ReceiveCIStatus> 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<actor::messages::ReceiveCIStatus> 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,

View file

@ -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<RegisterWebhook> for RepoActor {
type Result = ();
@ -29,17 +30,15 @@ impl Handler<RegisterWebhook> for RepoActor {
);
}
Err(err) => {
let msg = NotifyUser::from(UserNotification::WebhookRegistration(
actor::notify_user(
notify_user_recipient.as_ref(),
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);
}
reason: err.to_string(),
},
log.as_ref(),
);
}
}
}

View file

@ -100,13 +100,17 @@ impl Handler<actor::messages::ValidateRepo> 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");
}
}

View file

@ -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<Self>;
@ -151,3 +143,16 @@ pub fn logger(log: Option<&RepoActorLog>, message: impl Into<String>) {
let _ = log.write().map(|mut l| l.push(message));
}
}
pub fn notify_user(
recipient: Option<&Recipient<NotifyUser>>,
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);
}
}

View file

@ -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.

View file

@ -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(())
}

View file

@ -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();

View file

@ -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(())
}

View file

@ -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),
}