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): drive mobile lead and welcome emails through Loops events (#5392)

Evan Hutnik9800952ca801
diff --git a/Cargo.lock b/Cargo.lock
index ccb074688f..34d2995d8d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -8358,6 +8358,7 @@ dependencies = [
"reqwest 0.13.4",
"serde",
"serde_json",
+ "sha2 0.10.9",
"tracing",
"workspace-hack",
]
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/client.ts b/apps/web/src/lib/service-clients/service-auth/generated/client.ts
index 90ce275257..573cfc8a56 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/client.ts
@@ -1370,8 +1370,9 @@ export const verifyMergeRequest = async (
};
/**
- * @summary Sends a mobile welcome email to the given address, if it hasn't already been sent
-and the email is not blocked.
+ * @summary Enrolls a mobile lead in the Loops nurture sequence, which sends the welcome
+email inviting them to register on desktop. No-ops if the address was already
+enrolled, and rejects blocked addresses.
*/
export type sendMobileWelcomeEmailResponse200 = {
data: SendMobileWelcomeEmailResponse;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/sendMobileWelcomeEmailResponse.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/sendMobileWelcomeEmailResponse.ts
index 30e9f1900d..15c1bddee4 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/sendMobileWelcomeEmailResponse.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/sendMobileWelcomeEmailResponse.ts
@@ -6,6 +6,6 @@
*/
export interface SendMobileWelcomeEmailResponse {
- /** Whether the email was sent (false if it was already sent previously) */
+ /** Whether the lead was enrolled (false if they were already enrolled previously) */
sent: boolean;
}
diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.json
index 99ad3890bb..4a957eb9b2 100644
--- a/apps/web/src/lib/service-clients/service-auth/openapi.json
+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json
@@ -1165,7 +1165,7 @@
"/mobile-welcome-email": {
"post": {
"tags": ["mobile_welcome_email"],
- "summary": "Sends a mobile welcome email to the given address, if it hasn't already been sent\nand the email is not blocked.",
+ "summary": "Enrolls a mobile lead in the Loops nurture sequence, which sends the welcome\nemail inviting them to register on desktop. No-ops if the address was already\nenrolled, and rejects blocked addresses.",
"operationId": "send_mobile_welcome_email",
"requestBody": {
"content": {
@@ -4326,7 +4326,7 @@
"properties": {
"sent": {
"type": "boolean",
- "description": "Whether the email was sent (false if it was already sent previously)"
+ "description": "Whether the lead was enrolled (false if they were already enrolled previously)"
}
}
},
diff --git a/crates/loops_client/Cargo.toml b/crates/loops_client/Cargo.toml
index 228b5567e3..38b4efe8db 100644
--- a/crates/loops_client/Cargo.toml
+++ b/crates/loops_client/Cargo.toml
@@ -8,5 +8,6 @@ version = "0.1.0"
reqwest = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
+sha2 = { workspace = true }
tracing = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/crates/loops_client/src/lib.rs b/crates/loops_client/src/lib.rs
index 18cd8ced6d..fabdf05519 100644
--- a/crates/loops_client/src/lib.rs
+++ b/crates/loops_client/src/lib.rs
@@ -3,13 +3,48 @@
//!
//! Used to push Macro sign-ups into Loops so they receive our marketing emails.
+#[cfg(test)]
+mod test;
+
use serde::Serialize;
+use sha2::{Digest, Sha256};
/// Base URL for the Loops API.
const LOOPS_API_BASE_URL: &str = "https://app.loops.so/api";
const REQUEST_TIMEOUT_SECONDS: u64 = 15;
+/// Loops suppresses duplicate sends for the same key within 24 hours.
+const IDEMPOTENCY_KEY_HEADER: &str = "Idempotency-Key";
+
+/// Hashes an idempotency key to a fixed 64 characters.
+///
+/// Loops caps the header at 100 characters, and callers build keys from
+/// unbounded input — an email, or a `MacroUserId`, which embeds one. Hashing
+/// keeps every key in range while staying deterministic across retries, which
+/// is the whole point of the header.
+fn idempotency_digest(key: &str) -> String {
+ format!("{:x}", Sha256::digest(key.as_bytes()))
+}
+
+/// Normalizes an email for use as a Loops contact identifier: lowercased, with
+/// any `+` tag stripped from the local part.
+///
+/// Every Loops call site must use this. A mobile lead captured as
+/// `[email protected]` and the account they later register as `[email protected]` must
+/// resolve to the same contact, or the nurture sequence never sees the
+/// registration and both sequences run at once.
+pub fn normalize_email(email: &str) -> String {
+ let lowercase = email.to_lowercase();
+ match lowercase.split_once('@') {
+ Some((local, domain)) => {
+ let local = local.split('+').next().unwrap_or(local);
+ format!("{local}@{domain}")
+ }
+ None => lowercase,
+ }
+}
+
/// Client for the Loops (loops.so) API.
///
/// When no API key is configured the client is a no-op, mirroring the
@@ -83,6 +118,55 @@ impl LoopsClient {
Ok(())
}
+
+ /// Sends an event to Loops. Events trigger Loops automations, and upsert
+ /// the contact in the same request — so this both creates the contact (if
+ /// new) and fires the trigger, with no window where a loop can evaluate
+ /// before the contact properties land.
+ ///
+ /// Returns `Ok(())` if Loops is not configured (no-op).
+ ///
+ /// - `email`: the contact's address; pass through [`normalize_email`] first
+ /// - `event_name`: matched against the trigger configured on a Loop
+ /// - `contact_properties`: JSON object of properties to set on the contact.
+ /// Each must already exist in Loops. Ignored if not an object.
+ /// - `idempotency_key`: suppresses duplicate sends within 24 hours. Any
+ /// length is fine; it is hashed before being sent.
+ #[tracing::instrument(skip(self, contact_properties), err)]
+ pub async fn send_event(
+ &self,
+ email: &str,
+ event_name: &str,
+ contact_properties: &serde_json::Value,
+ idempotency_key: Option<&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/events/send");
+
+ // Contact properties sit at the top level of the body, alongside
+ // `email` and `eventName`. Insert them first so the required fields
+ // win if a caller passes a colliding key.
+ let mut payload = serde_json::Map::new();
+ if let Some(properties) = contact_properties.as_object() {
+ payload.extend(properties.clone());
+ }
+ payload.insert("email".to_string(), email.into());
+ payload.insert("eventName".to_string(), event_name.into());
+
+ let mut request = inner.client.post(&url).bearer_auth(&inner.api_key);
+
+ if let Some(key) = idempotency_key {
+ request = request.header(IDEMPOTENCY_KEY_HEADER, idempotency_digest(key));
+ }
+
+ request.json(&payload).send().await?.error_for_status()?;
+
+ Ok(())
+ }
}
/// Request body for the Loops "create contact" endpoint.
diff --git a/crates/loops_client/src/test.rs b/crates/loops_client/src/test.rs
new file mode 100644
index 0000000000..ea0fe501fd
--- /dev/null
+++ b/crates/loops_client/src/test.rs
@@ -0,0 +1,52 @@
+use super::*;
+
+#[test]
+fn normalize_email_lowercases() {
+ assert_eq!(normalize_email("[email protected]"), "[email protected]");
+}
+
+#[test]
+fn normalize_email_strips_plus_tag() {
+ assert_eq!(normalize_email("[email protected]"), "[email protected]");
+}
+
+#[test]
+fn normalize_email_agrees_across_signup_paths() {
+ // The bug this guards: lead capture stripped `+` tags and the user webhook
+ // did not, so one person landed on two Loops contacts and the nurture
+ // sequence never saw their registration.
+ assert_eq!(
+ normalize_email("[email protected]"),
+ normalize_email("[email protected]")
+ );
+}
+
+#[test]
+fn normalize_email_leaves_malformed_input_alone() {
+ assert_eq!(normalize_email("not-an-email"), "not-an-email");
+}
+
+#[test]
+fn normalize_email_only_strips_the_local_part() {
+ assert_eq!(normalize_email("evan@ma+cro.com"), "evan@ma+cro.com");
+}
+
+#[test]
+fn idempotency_digest_fits_the_loops_header_limit() {
+ // A `MacroUserId` embeds an email, so an untruncated key can run well past
+ // the 100 characters Loops accepts.
+ let long_key = format!("user-registered-{}@macro.com", "a".repeat(300));
+ assert_eq!(idempotency_digest(&long_key).len(), 64);
+}
+
+#[test]
+fn idempotency_digest_is_stable_and_distinct() {
+ assert_eq!(
+ idempotency_digest("mobile-lead-a"),
+ idempotency_digest("mobile-lead-a")
+ );
+ assert_ne!(
+ idempotency_digest("mobile-lead-a"),
+ idempotency_digest("mobile-lead-b")
+ );
+}
diff --git a/packages/sdk/generated/auth/sdk.gen.ts b/packages/sdk/generated/auth/sdk.gen.ts
index 49ff22442b..9b9d856a84 100644
--- a/packages/sdk/generated/auth/sdk.gen.ts
+++ b/packages/sdk/generated/auth/sdk.gen.ts
@@ -266,8 +266,9 @@ export class Sdk extends HeyApiClient {
}
/**
- * Sends a mobile welcome email to the given address, if it hasn't already been sent
- * and the email is not blocked.
+ * Enrolls a mobile lead in the Loops nurture sequence, which sends the welcome
+ * email inviting them to register on desktop. No-ops if the address was already
+ * enrolled, and rejects blocked addresses.
*/
public sendMobileWelcomeEmail<ThrowOnError extends boolean = false>(options: Options<SendMobileWelcomeEmailData, ThrowOnError>): RequestResult<SendMobileWelcomeEmailResponses, SendMobileWelcomeEmailErrors, ThrowOnError> {
return (options.client ?? this.client).post<SendMobileWelcomeEmailResponses, SendMobileWelcomeEmailErrors, ThrowOnError>({
diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.ts
index 2410726758..639711cd15 100644
--- a/packages/sdk/generated/auth/types.gen.ts
+++ b/packages/sdk/generated/auth/types.gen.ts
@@ -672,7 +672,7 @@ export type SendMobileWelcomeEmailRequest = {
export type SendMobileWelcomeEmailResponse = {
/**
- * Whether the email was sent (false if it was already sent previously)
+ * Whether the lead was enrolled (false if they were already enrolled previously)
*/
sent: boolean;
};
diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.json
index 99ad3890bb..4a957eb9b2 100644
--- a/packages/sdk/specs/auth.json
+++ b/packages/sdk/specs/auth.json
@@ -1165,7 +1165,7 @@
"/mobile-welcome-email": {
"post": {
"tags": ["mobile_welcome_email"],
- "summary": "Sends a mobile welcome email to the given address, if it hasn't already been sent\nand the email is not blocked.",
+ "summary": "Enrolls a mobile lead in the Loops nurture sequence, which sends the welcome\nemail inviting them to register on desktop. No-ops if the address was already\nenrolled, and rejects blocked addresses.",
"operationId": "send_mobile_welcome_email",
"requestBody": {
"content": {
@@ -4326,7 +4326,7 @@
"properties": {
"sent": {
"type": "boolean",
- "description": "Whether the email was sent (false if it was already sent previously)"
+ "description": "Whether the lead was enrolled (false if they were already enrolled previously)"
}
}
},
diff --git a/services/authentication_service/src/api/mobile_welcome_email/_welcome_email_template.html b/services/authentication_service/src/api/mobile_welcome_email/_welcome_email_template.html
deleted file mode 100644
index d207c23b44..0000000000
--- a/services/authentication_service/src/api/mobile_welcome_email/_welcome_email_template.html
+++ /dev/null
@@ -1,124 +0,0 @@
-<!DOCTYPE html>
-<html lang="en" xmlns:v="urn:schemas-microsoft-com:vml">
-<head>
- <meta charset="utf-8" />
- <meta name="x-apple-disable-message-reformatting" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <meta
- name="format-detection"
- content="telephone=no, date=no, address=no, email=no"
- />
- <meta name="color-scheme" content="dark" />
- <meta name="supported-color-schemes" content="dark" />
- <title>Welcome to Macro</title>
- <!--[if mso]><style>body{font-family:Helvetica,Arial,sans-serif}</style><![endif]-->
-</head>
-
-<body>
-<div
- role="article"
- aria-roledescription="email"
- aria-label="Welcome to Macro"
- lang="en"
- style="background-color: #030303; width: 100%; font-family: 'Rajdhani', Helvetica, Arial, sans-serif"
->
- <table
- cellpadding="0"
- cellspacing="0"
- role="presentation"
- style="width: 100%; max-width: 640px; margin: 0 auto; background-color: #030303"
- >
- <tr>
- <td align="center" style="padding: 56px 0 32px">
- <a href="https://macro.com">
- <img
- src="https://macro.com/logo-256px.png"
- width="128"
- alt="Macro"
- style="border: 0; max-width: 100%"
- />
- </a>
- </td>
- </tr>
- <tr>
- <td>
- <div style="background-color: #090909; border-radius: 5px; padding: 56px 40px; margin: 0 16px; border: 1px solid #484848">
- <h1
- style="
- margin: 0 0 16px;
- text-align: center;
- font-size: 36px;
- font-weight: 450;
- font-family: 'Roboto Slab', Rockwell, Georgia, serif;
- letter-spacing: -0.02em;
- color: #f2f2f2;
- "
- >
- You're in.
- </h1>
- <p
- style="
- margin: 0;
- text-align: center;
- font-size: 16px;
- color: #aeaeae;
- font-family: 'Rajdhani', Helvetica, Arial, sans-serif;
- "
- >
- Tap below from your computer to get started.
- </p>
- <div style="text-align: center; margin: 56px 0">
- <a
- href="https://macro.com/app/welcome?mobile_welcome_email=true"
- style="
- display: inline-block;
- background-color: #ff8f00;
- color: #090909;
- text-decoration: none;
- padding: 16px 32px;
- border-radius: 3px;
- font-size: 16px;
- font-family: 'Rajdhani', Helvetica, Arial, sans-serif;
- font-weight: 600;
- "
- >
- Launch Macro
- </a>
- </div>
- <!--[if mso]>
- <table cellpadding="0" cellspacing="0" role="presentation" style="margin: 56px auto;">
- <tr>
- <td style="background-color: #ff8f00; border-radius: 3px;">
- <a href="https://macro.com/app/welcome?mobile_welcome_email=true" style="color: #090909; text-decoration: none; display: block; padding: 16px 32px; font-size: 16px; font-weight: 600; font-family: 'Rajdhani', Helvetica, Arial, sans-serif;">
- Launch Macro
- </a>
- </td>
- </tr>
- </table>
- <![endif]-->
- </div>
- </td>
- </tr>
- <tr>
- <td style="padding: 48px 0; text-align: center">
- <p
- style="
- margin: 0;
- font-size: 14px;
- color: #484848;
- font-family: 'Rajdhani', Helvetica, Arial, sans-serif;
- "
- >
- Questions? Email us at
- <a
- href="mailto:[email protected]"
- style="color: #aeaeae; text-decoration: none"
- >
- </p>
- </td>
- </tr>
- </table>
-</div>
-</body>
-</html>
diff --git a/services/authentication_service/src/api/mobile_welcome_email/mod.rs b/services/authentication_service/src/api/mobile_welcome_email/mod.rs
index 4ae1a960c6..5c00b3338a 100644
--- a/services/authentication_service/src/api/mobile_welcome_email/mod.rs
+++ b/services/authentication_service/src/api/mobile_welcome_email/mod.rs
@@ -12,8 +12,6 @@ use utoipa::ToSchema;
use crate::api::{context::ApiContext, middleware};
-static WELCOME_EMAIL_TEMPLATE: &str = include_str!("./_welcome_email_template.html");
-
#[derive(Debug, Error)]
pub enum SendMobileWelcomeEmailError {
#[error("Invalid email address")]
@@ -52,7 +50,7 @@ pub struct SendMobileWelcomeEmailRequest {
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct SendMobileWelcomeEmailResponse {
- /// Whether the email was sent (false if it was already sent previously)
+ /// Whether the lead was enrolled (false if they were already enrolled previously)
pub sent: bool,
}
@@ -68,8 +66,9 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
)
}
-/// Sends a mobile welcome email to the given address, if it hasn't already been sent
-/// and the email is not blocked.
+/// Enrolls a mobile lead in the Loops nurture sequence, which sends the welcome
+/// email inviting them to register on desktop. No-ops if the address was already
+/// enrolled, and rejects blocked addresses.
#[utoipa::path(
post,
path = "/mobile-welcome-email",
@@ -90,13 +89,7 @@ pub async fn handler(
return Err(SendMobileWelcomeEmailError::InvalidEmail);
}
- let lowercase_email = req.email.to_lowercase();
- let lowercase_email = if let Some((local, domain)) = lowercase_email.split_once('@') {
- let local = local.split('+').next().unwrap_or(local);
- format!("{local}@{domain}")
- } else {
- lowercase_email
- };
+ let lowercase_email = loops_client::normalize_email(&req.email);
// Check if the email is blocked
let blocked_emails =
@@ -118,15 +111,27 @@ pub async fn handler(
return Ok(Json(SendMobileWelcomeEmailResponse { sent: false }));
}
- let welcome_email_content = WELCOME_EMAIL_TEMPLATE.to_string();
- ctx.ses_client
- .send_email(
+ // Enrolls the lead in the Loops nurture sequence, which owns the welcome
+ // email from here. Awaited rather than fire-and-forget: `sent: true` tells
+ // the caller mail is on the way, so it must not report success on a
+ // Loops failure. The key is namespaced by event so it can't collide with
+ // the `user_registered` event sent when the lead converts.
+ ctx.loops_client
+ .send_event(
&lowercase_email,
- "Welcome to Macro",
- &welcome_email_content,
+ "mobile_lead_captured",
+ // `hasAccount` is set explicitly rather than left unset: the
+ // workflow's audience filter tests `isFalse`, which an absent
+ // property would not satisfy.
+ &serde_json::json!({
+ "signupStage": "lead",
+ "hasAccount": false,
+ "source": "mobile-lead-capture",
+ }),
+ Some(&format!("mobile-lead-{lowercase_email}")),
)
- .await?;
+ .await
+ .map_err(|e| SendMobileWelcomeEmailError::InternalError(e.into()))?;
Ok(Json(SendMobileWelcomeEmailResponse { sent: true }))
}
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 904920b846..83d61078c3 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
@@ -287,16 +287,31 @@ 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.
+ // Tell Loops the account now exists. This upserts the contact into our
+ // marketing audience, triggers the welcome sequence, and is the exit
+ // condition for the mobile-lead nurture sequence — so a lead who converts
+ // stops being asked to sign up. Fire-and-forget: a Loops failure must never
+ // block user creation.
tokio::spawn({
let loops_client = ctx.loops_client.clone();
- let email = email.clone();
+ let email = loops_client::normalize_email(&email);
+ let user_id = user_id.clone();
async move {
let _ = loops_client
- .add_contact(&email, "macro-signup")
+ .send_event(
+ &email,
+ "user_registered",
+ &serde_json::json!({
+ "signupStage": "registered",
+ "hasAccount": true,
+ "source": "macro-signup",
+ }),
+ Some(&format!("user-registered-{user_id}")),
+ )
.await
- .inspect_err(|e| tracing::warn!(error=?e, "failed to add contact to Loops"));
+ .inspect_err(
+ |e| tracing::error!(error=?e, "failed to send Loops user_registered event"),
+ );
}
});
diff --git a/services/authentication_service/src/main.rs b/services/authentication_service/src/main.rs
index 235858929f..7475defb78 100644
--- a/services/authentication_service/src/main.rs
+++ b/services/authentication_service/src/main.rs
@@ -279,11 +279,13 @@ 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.
+ // Initialize Loops client. Production and develop sign-ups are added to
+ // Loops; on localhost, or wherever no API key is configured, this is a
+ // no-op. Note there is one Loops audience — a develop sign-up creates a
+ // real contact and can trigger live workflows, so leave the key unset in
+ // any environment that should not send.
let loops_client = match (config.environment, config.loops_api_key.value()) {
- (Environment::Production, Some(api_key)) => {
+ (Environment::Production | Environment::Develop, Some(api_key)) => {
tracing::info!("configuring Loops");
LoopsClient::new(api_key.to_string())
}