Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

chg(welcome): welcome channel name formatting, automatically favorite welcome channel (#5089)

teo26413c04a6b5
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index cd957cb0d2..2b27763b6b 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -359,6 +359,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/favorites",
"crates/filter_ast",
"crates/foreign_entity",
"crates/frecency",
diff --git a/Cargo.lock b/Cargo.lock
index dd357052a1..67be3dc046 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -979,6 +979,7 @@ dependencies = [
"email_db_client",
"email_validator",
"entity_access",
+ "favorites",
"foreign_entity",
"fusionauth",
"futures",
diff --git a/crates/favorites/src/domain/ports.rs b/crates/favorites/src/domain/ports.rs
index 967e59619c..a6358403bd 100644
--- a/crates/favorites/src/domain/ports.rs
+++ b/crates/favorites/src/domain/ports.rs
@@ -70,6 +70,18 @@ pub trait FavoritesService: Send + Sync + 'static {
receipt: &EntityAccessReceipt<ViewAccessLevel>,
) -> impl Future<Output = Result<Favorite, FavoritesError>> + Send;
+ /// Add an entity after a trusted caller has already established that the
+ /// user can view it.
+ ///
+ /// This supports internal workflows, such as favoriting an entity that the
+ /// same workflow just created for the user, where no access receipt exists
+ /// at the driving boundary.
+ fn add_favorite_with_established_access(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ entity: &Entity<'_>,
+ ) -> impl Future<Output = Result<Favorite, FavoritesError>> + Send;
+
/// List the user's favorites in manual order.
fn list_favorites(
&self,
diff --git a/crates/favorites/src/domain/service.rs b/crates/favorites/src/domain/service.rs
index f9c9dea0d1..90a0515bde 100644
--- a/crates/favorites/src/domain/service.rs
+++ b/crates/favorites/src/domain/service.rs
@@ -31,6 +31,34 @@ where
pub fn new(repo: R) -> Self {
Self { repo }
}
+
+ async fn add_favorite_for_user(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ entity: &Entity<'_>,
+ ) -> Result<Favorite, FavoritesError> {
+ validate_entity(entity)?;
+ // Cap the collection at add time. Enforcing it here (rather than only
+ // in `reorder_favorites`) keeps table growth bounded and guarantees a
+ // reorder payload can never exceed the limit and be rejected. Re-adding
+ // an already-favorited entity while exactly at the cap is rejected too;
+ // that is a harmless, fail-closed edge.
+ let count = self
+ .repo
+ .count_favorites(user_id)
+ .await
+ .map_err(anyhow::Error::from)?;
+ if count as usize >= MAX_FAVORITES_PER_COLLECTION {
+ return Err(FavoritesError::BadRequest(format!(
+ "cannot have more than {MAX_FAVORITES_PER_COLLECTION} favorites"
+ )));
+ }
+ Ok(self
+ .repo
+ .add_favorite(user_id, entity)
+ .await
+ .map_err(anyhow::Error::from)?)
+ }
}
fn validate_entity(entity: &Entity<'_>) -> Result<(), FavoritesError> {
@@ -59,27 +87,16 @@ where
let entity = receipt_entity
.entity_type
.with_entity_str(&receipt_entity.entity_id);
- validate_entity(&entity)?;
- // Cap the collection at add time. Enforcing it here (rather than only
- // in `reorder_favorites`) keeps table growth bounded and guarantees a
- // reorder payload can never exceed the limit and be rejected. Re-adding
- // an already-favorited entity while exactly at the cap is rejected too;
- // that is a harmless, fail-closed edge.
- let count = self
- .repo
- .count_favorites(user_id)
- .await
- .map_err(anyhow::Error::from)?;
- if count as usize >= MAX_FAVORITES_PER_COLLECTION {
- return Err(FavoritesError::BadRequest(format!(
- "cannot have more than {MAX_FAVORITES_PER_COLLECTION} favorites"
- )));
- }
- Ok(self
- .repo
- .add_favorite(user_id, &entity)
- .await
- .map_err(anyhow::Error::from)?)
+ self.add_favorite_for_user(user_id, &entity).await
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn add_favorite_with_established_access(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ entity: &Entity<'_>,
+ ) -> Result<Favorite, FavoritesError> {
+ self.add_favorite_for_user(user_id, entity).await
}
#[tracing::instrument(err, skip(self))]
diff --git a/crates/favorites/src/domain/service/test.rs b/crates/favorites/src/domain/service/test.rs
index cbcef2024b..df0dc0620d 100644
--- a/crates/favorites/src/domain/service/test.rs
+++ b/crates/favorites/src/domain/service/test.rs
@@ -155,6 +155,35 @@ async fn add_favorite_forwards_authenticated_user_and_receipt_entity() {
);
}
+#[tokio::test]
+async fn add_favorite_with_established_access_forwards_user_and_entity() {
+ let repo = FakeFavoritesRepo::new(0);
+ let service = FavoritesServiceImpl::new(repo.clone());
+ let user_id = user_id();
+ let entity = EntityType::Channel.with_entity_str("channel-123");
+
+ let favorite = service
+ .add_favorite_with_established_access(&user_id, &entity)
+ .await
+ .expect("favorite should be added");
+
+ assert_eq!(favorite.entity_type, EntityType::Channel);
+ assert_eq!(favorite.entity_id, "channel-123");
+ assert_eq!(
+ repo.recorded_calls(),
+ vec![
+ RepoCall::Count {
+ user_id: USER_ID.to_string(),
+ },
+ RepoCall::Add {
+ user_id: USER_ID.to_string(),
+ entity_type: EntityType::Channel,
+ entity_id: "channel-123".to_string(),
+ },
+ ]
+ );
+}
+
#[tokio::test]
async fn add_favorite_rejects_internal_receipt_before_repository_calls() {
let repo = FakeFavoritesRepo::new(0);
diff --git a/services/authentication_service/Cargo.toml b/services/authentication_service/Cargo.toml
index b1c3abc845..00ad153405 100644
--- a/services/authentication_service/Cargo.toml
+++ b/services/authentication_service/Cargo.toml
@@ -58,6 +58,7 @@ email_db_client = { path = "../../crates/email_db_client" }
email_validator = { path = "../../crates/email_validator" }
entity_access = { path = "../../crates/entity_access" }
foreign_entity = { path = "../../crates/foreign_entity" }
+favorites = { path = "../../crates/favorites", features = ["postgres"] }
fusionauth = { path = "../../crates/fusionauth" }
futures = { workspace = true }
github = { path = "../../crates/github", default-features = false, features = [
diff --git a/services/authentication_service/src/api/context.rs b/services/authentication_service/src/api/context.rs
index 3e69f9035d..ec79e7c993 100644
--- a/services/authentication_service/src/api/context.rs
+++ b/services/authentication_service/src/api/context.rs
@@ -74,6 +74,10 @@ pub(crate) type GithubLinkServiceType = GithubLinkServiceImpl<
pub(crate) type EntityAccessServiceType = EntityAccessServiceImpl<PgAccessRepository>;
+pub(crate) type FavoritesServiceType = favorites::domain::service::FavoritesServiceImpl<
+ favorites::outbound::pg_favorites_repo::PgFavoritesRepo,
+>;
+
pub(crate) type AuthorizationService = MacroAuthorizationServiceImpl<MacroAuthJwtValidator>;
#[derive(Clone, FromRef)]
@@ -99,6 +103,7 @@ pub(crate) struct ApiContext {
Arc<UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>>, // Note: since FromRef doesn't support generics we have to specify the concrete types here
pub teams_service: Arc<TeamsServiceType>,
pub channel_service: Arc<ChannelServiceType>,
+ pub favorites_service: Arc<FavoritesServiceType>,
pub entity_access_service: Arc<EntityAccessServiceType>,
pub native_app_service: Arc<NativeAppServiceImpl<DefaultBundleFetcher>>,
pub analytics_client: Arc<AnalyticsClient>,
diff --git a/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs b/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs
index b3f2481fda..b09d2d2d52 100644
--- a/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs
+++ b/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs
@@ -1,3 +1,6 @@
+#[cfg(test)]
+mod test;
+
use analytics_client::{MetaActionSource, MetaUserData};
use anyhow::Context;
use axum::{
@@ -17,15 +20,24 @@ use channels::domain::{
models::{ChannelType, CreateChannelRequest, Sender},
ports::ChannelService,
};
+use favorites::domain::ports::FavoritesService;
use fusionauth::error::FusionAuthClientError;
-use macro_user_id::{email::Email, user_id::MacroUserIdStr};
+use macro_user_id::{
+ email::{Email, ReadEmailParts},
+ user_id::MacroUserIdStr,
+};
use model::authentication::webhooks::FusionAuthUserWebhook;
+use model_entity::EntityType;
use std::collections::HashSet;
use teams::domain::team_repo::TeamService;
/// Macro support team members added to every new user's support channel.
const MACRO_SUPPORT_EMAILS: [&str; 3] = ["[email protected]", "[email protected]", "[email protected]"];
+fn support_channel_name<T: AsRef<str>>(email: &Email<T>) -> String {
+ format!("Macro Support x {}", email.local_part())
+}
+
/// FusionAuth create user webhook
#[tracing::instrument(skip(ctx, req, _internal_authorization), fields(email=%req.event.user.email, fusionauth_user_id=%req.event.user.id, username=?req.event.user.username, event_type=%req.event.event_type, ip_address=%req.event.info.ip_address))]
pub async fn handler(
@@ -110,9 +122,11 @@ async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> an
// FusionAuth's own email validation is more permissive than ours (e.g. it allows
// single quotes). The user.create event is transactional (AbsoluteMajority), so
// returning an error here aborts the FusionAuth user creation entirely.
- if let Err(e) = Email::parse_from_str(&email) {
- anyhow::bail!("email is not a valid macro email: {e}");
- }
+ let parsed_email = match Email::parse_from_str(&email) {
+ Ok(email) => email,
+ Err(e) => anyhow::bail!("email is not a valid macro email: {e}"),
+ };
+ let support_channel_name = support_channel_name(&parsed_email);
// rate limit check for user creation
let rate_limit = ctx
@@ -303,8 +317,10 @@ async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> an
// never block user creation.
tokio::spawn({
let channel_service = ctx.channel_service.clone();
+ let favorites_service = ctx.favorites_service.clone();
let user_id = user_id.clone();
let email = email.clone();
+ let support_channel_name = support_channel_name.clone();
async move {
let owner_id = match MacroUserIdStr::try_from(user_id) {
Ok(owner_id) => owner_id,
@@ -326,12 +342,12 @@ async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> an
}
};
- if let Err(e) = channel_service
+ let channel = match channel_service
.create_channel(
- Sender::new_from_user(owner_id),
+ Sender::new_from_user(owner_id.clone()),
None,
CreateChannelRequest {
- name: Some(format!("{email} x Macro Support")),
+ name: Some(support_channel_name),
channel_type: ChannelType::Private,
team_id: None,
auto_join_team: false,
@@ -340,7 +356,19 @@ async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> an
)
.await
{
- tracing::error!(error=?e, %email, "failed to create Macro support channel");
+ Ok(channel) => channel,
+ Err(e) => {
+ tracing::error!(error=?e, %email, "failed to create Macro support channel");
+ return;
+ }
+ };
+
+ let channel_entity = EntityType::Channel.with_entity_str(&channel.id);
+ if let Err(e) = favorites_service
+ .add_favorite_with_established_access(&owner_id, &channel_entity)
+ .await
+ {
+ tracing::error!(error=?e, channel_id=%channel.id, %email, "failed to favorite Macro support channel");
}
}
});
diff --git a/services/authentication_service/src/api/webhooks/user/create_user_webhook/test.rs b/services/authentication_service/src/api/webhooks/user/create_user_webhook/test.rs
new file mode 100644
index 0000000000..d833ee8870
--- /dev/null
+++ b/services/authentication_service/src/api/webhooks/user/create_user_webhook/test.rs
@@ -0,0 +1,13 @@
+use macro_user_id::email::Email;
+
+use super::support_channel_name;
+
+#[test]
+fn support_channel_name_uses_email_local_part() {
+ let email = Email::parse_from_str("[email protected]").expect("valid email");
+
+ assert_eq!(
+ support_channel_name(&email),
+ "Macro Support x new.user+trial"
+ );
+}
diff --git a/services/authentication_service/src/main.rs b/services/authentication_service/src/main.rs
index 6286d412b9..7d02c661c2 100644
--- a/services/authentication_service/src/main.rs
+++ b/services/authentication_service/src/main.rs
@@ -290,6 +290,9 @@ async fn main() -> anyhow::Result<()> {
config.stripe_price_id.to_string().clone(),
);
let channel_service = ChannelServiceImpl::new(PgChannelsRepo::new(db.clone()));
+ let favorites_service = favorites::domain::service::FavoritesServiceImpl::new(
+ favorites::outbound::pg_favorites_repo::PgFavoritesRepo::new(db.clone()),
+ );
let team_crm_settings_repo_impl =
teams::outbound::team_crm_settings_repo::TeamCrmSettingsRepositoryImpl::new(db.clone());
@@ -383,6 +386,7 @@ async fn main() -> anyhow::Result<()> {
user_roles_and_permissions_service: Arc::new(user_roles_and_permissions_service),
teams_service: Arc::new(teams_service_impl),
channel_service: Arc::new(channel_service),
+ favorites_service: Arc::new(favorites_service),
entity_access_service: Arc::new(entity_access_service_impl),
referral_service: Arc::new(referral_service),
native_app_service: Arc::new(NativeAppServiceImpl {