Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(email): bootstrap child email_links on first link (self-link case) (#3777)
gbirman85820889e19e
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/initResponse.ts b/js/app/packages/service-clients/service-email/generated/schemas/initResponse.tsindex 87be334052..f86ed25a67 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/initResponse.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/initResponse.ts@@ -7,11 +7,12 @@import type { InitResponseBackfillJobId } from './initResponseBackfillJobId';export interface InitResponse {- /** Present when init enqueued a backfill job. Absent for the graph path,-where the child link's backfill already ran under its own macro_id. */+ /** Present when init enqueued a backfill job. Absent for cross-user delegation,+where the child link's backfill already ran under its own macro_id; present for+the self-link bootstrap, where a fresh link is provisioned and backfilled. */backfill_job_id?: InitResponseBackfillJobId;- /** The email_links row id for the now-accessible inbox. For the graph path-(cross-account add) this is the *existing* child link the caller now-delegates over; for the data-source path it's a freshly upserted row. */+ /** The email_links row id for the now-accessible inbox. For cross-user delegation+this is the *existing* child link the caller now delegates over; for the+self-link bootstrap and the data-source path it's a freshly upserted row. */link_id: string;}diff --git a/js/app/packages/service-clients/service-email/generated/schemas/initResponseBackfillJobId.ts b/js/app/packages/service-clients/service-email/generated/schemas/initResponseBackfillJobId.tsindex 69a6dee19e..6eaa40414b 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/initResponseBackfillJobId.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/initResponseBackfillJobId.ts@@ -6,7 +6,8 @@*//**- * Present when init enqueued a backfill job. Absent for the graph path,-where the child link's backfill already ran under its own macro_id.+ * Present when init enqueued a backfill job. Absent for cross-user delegation,+where the child link's backfill already ran under its own macro_id; present for+the self-link bootstrap, where a fresh link is provisioned and backfilled.*/export type InitResponseBackfillJobId = string | null;diff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.jsonindex a580f59217..12b4479680 100644--- a/js/app/packages/service-clients/service-email/openapi.json+++ b/js/app/packages/service-clients/service-email/openapi.json@@ -4040,12 +4040,12 @@"backfill_job_id": {"type": ["string", "null"],"format": "uuid",- "description": "Present when init enqueued a backfill job. Absent for the graph path,\nwhere the child link's backfill already ran under its own macro_id."+ "description": "Present when init enqueued a backfill job. Absent for cross-user delegation,\nwhere the child link's backfill already ran under its own macro_id; present for\nthe self-link bootstrap, where a fresh link is provisioned and backfilled."},"link_id": {"type": "string","format": "uuid",- "description": "The email_links row id for the now-accessible inbox. For the graph path\n(cross-account add) this is the *existing* child link the caller now\ndelegates over; for the data-source path it's a freshly upserted row."+ "description": "The email_links row id for the now-accessible inbox. For cross-user delegation\nthis is the *existing* child link the caller now delegates over; for the\nself-link bootstrap and the data-source path it's a freshly upserted row."}}},diff --git a/rust/cloud-storage/email_db_client/src/histories/mod.rs b/rust/cloud-storage/email_db_client/src/histories/mod.rsindex a2316a729d..da79a9d987 100644--- a/rust/cloud-storage/email_db_client/src/histories/mod.rs+++ b/rust/cloud-storage/email_db_client/src/histories/mod.rs@@ -35,12 +35,15 @@ pub async fn fetch_history_id_for_link(Ok(result.map(|r| r.history_id))}-#[tracing::instrument(skip(pool), err)]-pub async fn upsert_gmail_history(- pool: &PgPool,+#[tracing::instrument(skip(executor), err)]+pub async fn upsert_gmail_history<'e, E>(+ executor: E,link_id: Uuid,history_id: &str,-) -> anyhow::Result<()> {+) -> anyhow::Result<()>+where+ E: sqlx::Executor<'e, Database = sqlx::Postgres>,+{let service_history = GmailHistory {link_id,history_id: history_id.to_string(),@@ -62,7 +65,7 @@ pub async fn upsert_gmail_history(db_history.link_id,db_history.history_id)- .execute(pool)+ .execute(executor).await?;Ok(())diff --git a/rust/cloud-storage/email_db_client/src/links/insert.rs b/rust/cloud-storage/email_db_client/src/links/insert.rsindex 81c2efd1a9..943e417b44 100644--- a/rust/cloud-storage/email_db_client/src/links/insert.rs+++ b/rust/cloud-storage/email_db_client/src/links/insert.rs@@ -1,10 +1,12 @@use doppleganger::Mirror;use models_email::email::service;-use sqlx::PgPool;use sqlx::types::Uuid;use crate::links::types::DbUserProvider;+#[cfg(test)]+mod test;+struct LinkId {id: Uuid,}@@ -13,9 +15,9 @@ struct LinkId {/// If a record with matching fusionauth_user_id, email_address, and provider already exists,/// updates the existing record with values from the provided Link./// Returns the ID of the inserted or updated link and a boolean indicating if a new record was created.-#[tracing::instrument(skip(pool), err)]+#[tracing::instrument(skip(conn), err)]pub async fn upsert_link(- pool: &PgPool,+ conn: &mut sqlx::PgConnection,service_link: service::link::Link,) -> anyhow::Result<service::link::Link> {if service_link.fusionauth_user_id.is_empty() {@@ -53,7 +55,7 @@ pub async fn upsert_link(db_provider as _,is_sync_active)- .fetch_one(pool)+ .fetch_one(&mut *conn).await?;let service_link = service::link::Link {@@ -76,7 +78,7 @@ pub async fn upsert_link("#,service_link.id,)- .execute(pool)+ .execute(&mut *conn).await?;Ok(service_link)diff --git a/rust/cloud-storage/email_db_client/src/links/insert/test.rs b/rust/cloud-storage/email_db_client/src/links/insert/test.rsnew file mode 100644index 0000000000..ccb6e49890--- /dev/null+++ b/rust/cloud-storage/email_db_client/src/links/insert/test.rs@@ -0,0 +1,69 @@+use super::*;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_user_id::email::EmailStr;+use macro_user_id::user_id::MacroUserIdStr;+use models_email::email::service::link::{Link, UserProvider};+use sqlx::{Pool, Postgres};++/// Mirrors the self-link bootstrap write: the row is owned by the child's macro_id while+/// the OAuth grant (fusionauth_user_id) lives under the primary's fusion id. Exercises the+/// `&mut PgConnection` path so the link, its default settings, and the gmail history all+/// commit atomically within one transaction.+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn upsert_link_in_transaction_persists_divergent_ids(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let child_macro_id = "macro|[email protected]";+ let primary_fusion_id = "11111111-1111-1111-1111-111111111111";+ let child_email = "[email protected]";++ let link = Link {+ id: macro_uuid::generate_uuid_v7(),+ macro_id: MacroUserIdStr::try_from(child_macro_id.to_string())?,+ fusionauth_user_id: primary_fusion_id.to_string(),+ email_address: EmailStr::try_from(child_email.to_string())?,+ provider: UserProvider::Gmail,+ is_sync_active: true,+ created_at: Default::default(),+ updated_at: Default::default(),+ };++ let mut tx = pool.begin().await?;+ let inserted = upsert_link(&mut tx, link).await?;+ crate::histories::upsert_gmail_history(&mut *tx, inserted.id, "history-123").await?;++ // Invisible outside the transaction until commit.+ assert!(+ crate::links::get::fetch_link_by_id(&pool, inserted.id)+ .await?+ .is_none()+ );++ tx.commit().await?;++ let row = sqlx::query!(+ r#"SELECT macro_id, fusionauth_user_id FROM email_links WHERE id = $1"#,+ inserted.id,+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(row.macro_id, child_macro_id);+ assert_eq!(row.fusionauth_user_id, primary_fusion_id);++ assert_eq!(+ crate::histories::fetch_history_id_for_link(&pool, child_email, UserProvider::Gmail)+ .await?+ .as_deref(),+ Some("history-123"),+ );++ let settings_count = sqlx::query_scalar!(+ r#"SELECT COUNT(*) as "count!" FROM email_settings WHERE link_id = $1"#,+ inserted.id,+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(settings_count, 1);++ Ok(())+}diff --git a/rust/cloud-storage/email_service/src/api/email/init.rs b/rust/cloud-storage/email_service/src/api/email/init.rsindex 2c014cb7ea..ecf1999c1d 100644--- a/rust/cloud-storage/email_service/src/api/email/init.rs+++ b/rust/cloud-storage/email_service/src/api/email/init.rs@@ -66,12 +66,13 @@ impl IntoResponse for InitError {#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]pub struct InitResponse {- /// The email_links row id for the now-accessible inbox. For the graph path- /// (cross-account add) this is the *existing* child link the caller now- /// delegates over; for the data-source path it's a freshly upserted row.+ /// The email_links row id for the now-accessible inbox. For cross-user delegation+ /// this is the *existing* child link the caller now delegates over; for the+ /// self-link bootstrap and the data-source path it's a freshly upserted row.pub link_id: Uuid,- /// Present when init enqueued a backfill job. Absent for the graph path,- /// where the child link's backfill already ran under its own macro_id.+ /// Present when init enqueued a backfill job. Absent for cross-user delegation,+ /// where the child link's backfill already ran under its own macro_id; present for+ /// the self-link bootstrap, where a fresh link is provisioned and backfilled.#[serde(skip_serializing_if = "Option::is_none")]pub backfill_job_id: Option<Uuid>,}@@ -154,28 +155,84 @@ pub async fn handler(if let Some(child_macro_id) = existing_owner.as_deref()&& child_macro_id != user_context.user_id{- // Verify the child has actually connected an inbox before mutating any state.- // Looking this up first means a missing email_links row fails cleanly, without- // leaving a dangling edge or consuming the in_progress row with no recovery path.- let child_link = email_db_client::links::get::fetch_link_by_email(+ // Graph path: the linked email belongs to a different macro user. Look the+ // child's inbox up before mutating any state so the in_progress row is only+ // consumed once we know how to proceed.+ let existing_child_link = email_db_client::links::get::fetch_link_by_email(&ctx.db,&linked_email,link::UserProvider::Gmail,).await- .context("Failed to look up child link before delegation")?- .ok_or_else(|| {- InitError::BadRequest("child has not connected their inbox yet".to_string())- })?;-- // Graph path: link primary (caller) → child so primary can read child's inbox.- // The edge insert and in_progress consumption are a coupled pair, so commit them- // atomically: any failure rolls back, leaving the in_progress row for a retry.+ .context("Failed to look up child link before delegation")?;++ if let Some(child_link) = existing_child_link {+ // Cross-user delegation: the child already connected their own inbox under+ // their own fusion id. Link primary (caller) → child so primary can read it.+ // The edge insert and in_progress consumption are a coupled pair, so commit+ // them atomically: any failure rolls back, leaving the in_progress row for a+ // retry.+ let mut tx = ctx+ .db+ .begin()+ .await+ .context("Failed to begin graph delegation transaction")?;++ macro_db_client::macro_user_links::insert_edge(+ &mut *tx,+ &user_context.user_id,+ child_macro_id,+ )+ .await+ .context("Failed to insert macro_user_links edge")?;++ macro_db_client::in_progress_user_link::delete_in_progress_user_link(+ &mut *tx, &link_id,+ )+ .await+ .context("Failed to delete in_progress_user_link after graph delegation")?;++ tx.commit()+ .await+ .context("Failed to commit graph delegation transaction")?;++ return Ok((+ StatusCode::OK,+ Json(InitResponse {+ link_id: child_link.id,+ backfill_job_id: None,+ }),+ )+ .into_response());+ }++ // Self-link bootstrap: the child macro_user exists but never connected an inbox.+ // Provision its email_links row with the child's macro_id (inbox ownership) but the+ // primary's fusionauth_user_id — the OAuth grant lives under the primary's fusion id,+ // and token resolution, message/thread scoping, and backfill rate-limiting key off it.+ let child_macro_id_owned = MacroUserIdStr::try_from(child_macro_id.to_string())?;++ let gmail_token =+ fetch_gmail_token_for_email(&ctx, &user_context.fusion_user_id, &linked_email)+ .await?;+ let watch_response = ctx.gmail_client.register_watch(&gmail_token).await?;++ // All writes commit atomically so a partial failure leaves no dangling link,+ // edge, or consumed in_progress row.let mut tx = ctx.db.begin().await- .context("Failed to begin graph delegation transaction")?;+ .context("Failed to begin self-link bootstrap transaction")?;++ let link = enable_gmail_sync_for(+ tx.as_mut(),+ &user_context.fusion_user_id,+ child_macro_id_owned,+ &linked_email,+ &watch_response.history_id,+ )+ .await?;macro_db_client::macro_user_links::insert_edge(&mut *tx,@@ -189,56 +246,63 @@ pub async fn handler(&mut *tx, &link_id,).await- .context("Failed to delete in_progress_user_link after graph delegation")?;+ .context("Failed to delete in_progress_user_link after self-link bootstrap")?;tx.commit().await- .context("Failed to commit graph delegation transaction")?;-- return Ok((- StatusCode::OK,- Json(InitResponse {- link_id: child_link.id,- backfill_job_id: None,- }),- )- .into_response());- }+ .context("Failed to commit self-link bootstrap transaction")?;++ // Fall through to the shared tail so the freshly bootstrapped inbox gets its+ // initial backfill.+ (link, linked_email)+ } else {+ // Data-source path (same-user re-link or brand-new email with no prior signup).+ if pg_repo+ .link_by_fusionauth_email_provider(+ &user_context.fusion_user_id,+ &linked_email,+ UserProvider::Gmail,+ )+ .await+ .context("Failed to check existing link by email")?+ .is_some()+ {+ return Err(InitError::AlreadyInitialized);+ }++ let gmail_token =+ fetch_gmail_token_for_email(&ctx, &user_context.fusion_user_id, &linked_email)+ .await?;+ let watch_response = ctx.gmail_client.register_watch(&gmail_token).await?;++ let mut tx = ctx+ .db+ .begin()+ .await+ .context("Failed to begin link transaction")?;- // Data-source path (same-user re-link or brand-new email with no prior signup).- if pg_repo- .link_by_fusionauth_email_provider(+ let link = enable_gmail_sync_for(+ tx.as_mut(),&user_context.fusion_user_id,+ macro_user_id.clone(),&linked_email,- UserProvider::Gmail,+ &watch_response.history_id,)- .await- .context("Failed to check existing link by email")?- .is_some()- {- return Err(InitError::AlreadyInitialized);- }+ .await?;- let gmail_token =- fetch_gmail_token_for_email(&ctx, &user_context.fusion_user_id, &linked_email).await?;-- let link = enable_gmail_sync_for(- &ctx,- &user_context.fusion_user_id,- macro_user_id.clone(),- &linked_email,- &gmail_token,- )- .await?;+ tx.commit()+ .await+ .context("Failed to commit link transaction")?;- macro_db_client::in_progress_user_link::delete_in_progress_user_link(&ctx.db, &link_id)- .await- .inspect_err(|e| {- tracing::error!(error=?e, ?link_id, "Failed to delete in_progress_user_link after init");- })- .ok();+ macro_db_client::in_progress_user_link::delete_in_progress_user_link(&ctx.db, &link_id)+ .await+ .inspect_err(|e| {+ tracing::error!(error=?e, ?link_id, "Failed to delete in_progress_user_link after init");+ })+ .ok();- (link, linked_email)+ (link, linked_email)+ }} else {let existing_link = pg_repo.link_by_fusionauth_and_macro_id(@@ -264,15 +328,27 @@ pub async fn handler(.await.map_err(|_| InitError::BadRequest("Failed to fetch Gmail token".to_string()))?;+ let watch_response = ctx.gmail_client.register_watch(&gmail_token).await?;++ let mut tx = ctx+ .db+ .begin()+ .await+ .context("Failed to begin link transaction")?;+let link = enable_gmail_sync_for(- &ctx,+ tx.as_mut(),&user_context.fusion_user_id,macro_user_id.clone(),&email,- &gmail_token,+ &watch_response.history_id,).await?;+ tx.commit()+ .await+ .context("Failed to commit link transaction")?;+(link, email)};@@ -388,19 +464,20 @@ async fn fetch_gmail_token_for_email(})}-/// Registers a Gmail watch, upserts the `email_links` row, and seeds the gmail history entry.-/// Caller-provided identifiers let this serve both the JWT-driven new-user signup and the-/// `link_id`-driven add-inbox flow.-#[tracing::instrument(skip(ctx, gmail_token), err)]+/// Upserts the `email_links` row and seeds the gmail history entry for an already-registered+/// Gmail watch. Runs on a caller-provided connection so the writes can join a wider+/// transaction; callers register the watch (external IO) beforehand and pass its `history_id`.+/// Caller-provided identifiers let this serve the JWT-driven new-user signup, the+/// `link_id`-driven add-inbox flow, and the self-link bootstrap (where `macro_id` is the+/// child's but `fusion_user_id` is the primary's).+#[tracing::instrument(skip(conn), err)]async fn enable_gmail_sync_for(- ctx: &ApiContext,+ conn: &mut sqlx::PgConnection,fusion_user_id: &str,macro_id: MacroUserIdStr<'static>,email_address: &str,- gmail_token: &str,+ history_id: &str,) -> Result<Link, InitError> {- let watch_response = ctx.gmail_client.register_watch(gmail_token).await?;-let link = link::Link {id: macro_uuid::generate_uuid_v7(),macro_id,@@ -412,11 +489,11 @@ async fn enable_gmail_sync_for(updated_at: Default::default(),};- let link = email_db_client::links::insert::upsert_link(&ctx.db, link)+ let link = email_db_client::links::insert::upsert_link(&mut *conn, link).await.context("Failed to upsert link")?;- email_db_client::histories::upsert_gmail_history(&ctx.db, link.id, &watch_response.history_id)+ email_db_client::histories::upsert_gmail_history(&mut *conn, link.id, history_id).await.context("Failed to upsert gmail history")?;diff --git a/rust/cloud-storage/seed_cli/src/service/db/mod.rs b/rust/cloud-storage/seed_cli/src/service/db/mod.rsindex ebf2577567..015a642e5d 100644--- a/rust/cloud-storage/seed_cli/src/service/db/mod.rs+++ b/rust/cloud-storage/seed_cli/src/service/db/mod.rs@@ -194,7 +194,8 @@ impl SeedDb {&self,link: service::link::Link,) -> anyhow::Result<service::link::Link> {- let result = email_db_client::links::insert::upsert_link(&self.inner, link).await?;+ let mut conn = self.inner.acquire().await?;+ let result = email_db_client::links::insert::upsert_link(&mut conn, link).await?;Ok(result)}