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.

feat(auth): add Loops integration for sign-up emails (#4636)

juliawest236ba02ef201
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 4f812c8e29..750f700225 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -355,6 +355,7 @@
"item_filters",
"last_online_tracker",
"lexical_client",
+ "loops_client",
"macro_auth",
"macro_aws_config",
"macro_cache_client",
@@ -2784,6 +2785,10 @@
"remote_env_var",
"workspace-hack"
],
+ "loops_client": [
+ "loops_client",
+ "workspace-hack"
+ ],
"macro_auth": [
"cowlike",
"macro_auth",
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 8467f3c360..490a9e463b 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -967,6 +967,7 @@ dependencies = [
"http-body-util",
"jsonwebtoken 10.3.0",
"last_online_tracker",
+ "loops_client",
"macro_auth",
"macro_aws_config",
"macro_cache_client",
@@ -7619,6 +7620,17 @@ dependencies = [
"imgref",
]
+[[package]]
+name = "loops_client"
+version = "0.1.0"
+dependencies = [
+ "reqwest 0.13.4",
+ "serde",
+ "serde_json",
+ "tracing",
+ "workspace-hack",
+]
+
[[package]]
name = "lru"
version = "0.16.4"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 9e794207ea..ad8e8d7a8b 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -41,6 +41,7 @@ members = [
"image_optimizer",
"image_proxy_service",
"integration_tests/local_e2e",
+ "loops_client",
"macro_config",
"macro_event_broker",
"macro_event_topics",
diff --git a/rust/cloud-storage/authentication_service/Cargo.toml b/rust/cloud-storage/authentication_service/Cargo.toml
index ef859f4018..209ee645ca 100644
--- a/rust/cloud-storage/authentication_service/Cargo.toml
+++ b/rust/cloud-storage/authentication_service/Cargo.toml
@@ -60,6 +60,7 @@ github = { path = "../github", default-features = false, features = [
http-body-util = { workspace = true }
jsonwebtoken = { workspace = true }
last_online_tracker = { path = "../last_online_tracker" }
+loops_client = { path = "../loops_client" }
macro_auth = { path = "../macro_auth" }
macro_aws_config = { path = "../macro_aws_config" }
macro_cache_client = { path = "../macro_cache_client", default-features = false, features = [
diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rs
index cedf6f5ea6..ab1601a273 100644
--- a/rust/cloud-storage/authentication_service/src/api/context.rs
+++ b/rust/cloud-storage/authentication_service/src/api/context.rs
@@ -10,6 +10,7 @@ use github::domain::service::GithubLinkServiceImpl;
use github::outbound::github_auth_client::GithubAuthImpl;
use github::outbound::github_oauth_client::GithubOauthImpl;
use github::outbound::pg_github_repo::PgGithubRepo;
+use loops_client::LoopsClient;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_cache_client::MacroCache;
use macro_env::Environment;
@@ -84,6 +85,7 @@ pub(crate) struct ApiContext {
pub entity_access_service: Arc<EntityAccessServiceType>,
pub native_app_service: Arc<NativeAppServiceImpl<DefaultBundleFetcher>>,
pub analytics_client: Arc<AnalyticsClient>,
+ pub loops_client: Arc<LoopsClient>,
pub referral_service: Arc<ReferralServiceType>,
pub rate_limit_service: RateLimiter,
/// The stripe price id
diff --git a/rust/cloud-storage/authentication_service/src/api/webhooks/user/create_user_webhook.rs b/rust/cloud-storage/authentication_service/src/api/webhooks/user/create_user_webhook.rs
index 9a851265a4..0f790b4a4d 100644
--- a/rust/cloud-storage/authentication_service/src/api/webhooks/user/create_user_webhook.rs
+++ b/rust/cloud-storage/authentication_service/src/api/webhooks/user/create_user_webhook.rs
@@ -171,6 +171,19 @@ async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> an
}
});
+ // Add the new sign-up to Loops (our email marketing audience / mailing
+ // list). Fire-and-forget: a Loops failure must never block user creation.
+ tokio::spawn({
+ let loops_client = ctx.loops_client.clone();
+ let email = email.clone();
+ async move {
+ let _ = loops_client
+ .add_contact(&email, "macro-signup")
+ .await
+ .inspect_err(|e| tracing::warn!(error=?e, "failed to add contact to Loops"));
+ }
+ });
+
// add user to all active experiments
tokio::spawn({
let db = ctx.db.clone();
diff --git a/rust/cloud-storage/authentication_service/src/config.rs b/rust/cloud-storage/authentication_service/src/config.rs
index b242fb5542..ad11e82c4d 100644
--- a/rust/cloud-storage/authentication_service/src/config.rs
+++ b/rust/cloud-storage/authentication_service/src/config.rs
@@ -40,6 +40,7 @@ maybe_env_vars! {
pub struct MetaTestEventCode;
pub struct PosthogApiKey;
pub struct PosthogHost;
+ pub struct LoopsApiKey;
}
/// The configuration parameters for the application.
@@ -105,6 +106,9 @@ pub struct Config {
pub posthog_api_key: PosthogApiKey,
/// PostHog host (optional)
pub posthog_host: PosthogHost,
+ /// Loops API key (optional). When set, Macro sign-ups are added to our
+ /// Loops audience.
+ pub loops_api_key: LoopsApiKey,
/// The stripe price id
pub stripe_price_id: StripePriceId,
/// The internal api key
diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rs
index 31d56c7b77..b4cd77c737 100644
--- a/rust/cloud-storage/authentication_service/src/main.rs
+++ b/rust/cloud-storage/authentication_service/src/main.rs
@@ -17,6 +17,7 @@ use github::{
pg_github_repo::PgGithubRepo,
},
};
+use loops_client::LoopsClient;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
use macro_service_urls::AppServiceUrl;
@@ -242,6 +243,18 @@ async fn main() -> anyhow::Result<()> {
}));
tracing::trace!("initialized analytics client");
+ // Initialize Loops client. Only production sign-ups are added to Loops;
+ // in all other environments (or when no API key is configured) this is a
+ // no-op.
+ let loops_client = match (config.environment, config.loops_api_key.value()) {
+ (Environment::Production, Some(api_key)) => {
+ tracing::info!("configuring Loops");
+ LoopsClient::new(api_key.to_string())
+ }
+ _ => LoopsClient::noop(),
+ };
+ tracing::trace!("initialized loops client");
+
let user_roles_and_permissions_macro_db = MacroDB::new(db.clone());
let user_roles_and_permissions_service = UserRolesAndPermissionsServiceImpl::new(
@@ -350,6 +363,7 @@ async fn main() -> anyhow::Result<()> {
ios_app_bundle_id: IOS_APP_BUNDLE_ID.to_string(),
},
}),
+ loops_client: Arc::new(loops_client),
analytics_client,
stripe_price_id: config.stripe_price_id.to_string(),
},
diff --git a/rust/cloud-storage/loops_client/Cargo.toml b/rust/cloud-storage/loops_client/Cargo.toml
new file mode 100644
index 0000000000..228b5567e3
--- /dev/null
+++ b/rust/cloud-storage/loops_client/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+edition = "2024"
+name = "loops_client"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+reqwest = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+tracing = { workspace = true }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/rust/cloud-storage/loops_client/src/lib.rs b/rust/cloud-storage/loops_client/src/lib.rs
new file mode 100644
index 0000000000..18cd8ced6d
--- /dev/null
+++ b/rust/cloud-storage/loops_client/src/lib.rs
@@ -0,0 +1,93 @@
+#![deny(missing_docs)]
+//! Loops (loops.so) client for adding contacts to our Loops audience.
+//!
+//! Used to push Macro sign-ups into Loops so they receive our marketing emails.
+
+use serde::Serialize;
+
+/// Base URL for the Loops API.
+const LOOPS_API_BASE_URL: &str = "https://app.loops.so/api";
+
+const REQUEST_TIMEOUT_SECONDS: u64 = 15;
+
+/// Client for the Loops (loops.so) API.
+///
+/// When no API key is configured the client is a no-op, mirroring the
+/// [`analytics_client`](../analytics_client) pattern so local/dev environments
+/// don't need Loops credentials.
+#[derive(Clone)]
+pub struct LoopsClient {
+ inner: Option<Inner>,
+}
+
+#[derive(Clone)]
+struct Inner {
+ client: reqwest::Client,
+ api_key: String,
+}
+
+impl LoopsClient {
+ /// Creates a new Loops client with the given API key.
+ pub fn new(api_key: String) -> Self {
+ Self {
+ inner: Some(Inner {
+ client: reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(REQUEST_TIMEOUT_SECONDS))
+ .build()
+ .unwrap(),
+ api_key,
+ }),
+ }
+ }
+
+ /// Creates a no-op Loops client (no API key configured).
+ pub fn noop() -> Self {
+ Self { inner: None }
+ }
+
+ /// Creates a contact in Loops, adding them to our audience (subscribed to
+ /// marketing emails by default).
+ ///
+ /// Returns `Ok(())` if Loops is not configured (no-op). A `409 Conflict`
+ /// (the contact already exists in the audience) is treated as success.
+ ///
+ /// - `email`: the contact's email address
+ /// - `source`: a custom source label recorded on the Loops contact
+ #[tracing::instrument(skip(self), err)]
+ pub async fn add_contact(&self, email: &str, source: &str) -> Result<(), reqwest::Error> {
+ let Some(inner) = &self.inner else {
+ tracing::debug!("loops not configured");
+ return Ok(());
+ };
+
+ let url = format!("{LOOPS_API_BASE_URL}/v1/contacts/create");
+
+ let payload = ContactCreateRequest { email, source };
+
+ let response = inner
+ .client
+ .post(&url)
+ .bearer_auth(&inner.api_key)
+ .json(&payload)
+ .send()
+ .await?;
+
+ // A contact that already exists returns 409. Treat that as success —
+ // the person is already in our audience, which is all we care about.
+ if response.status() == reqwest::StatusCode::CONFLICT {
+ tracing::info!("loops contact already exists");
+ return Ok(());
+ }
+
+ response.error_for_status()?;
+
+ Ok(())
+ }
+}
+
+/// Request body for the Loops "create contact" endpoint.
+#[derive(Serialize)]
+struct ContactCreateRequest<'a> {
+ email: &'a str,
+ source: &'a str,
+}