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
perf(email): fetch links list with a single joined query (#4919)
Evan Hutnik0836e6c8f412
diff --git a/.sqlx/query-d1a0fe539e47a9394246dcebcdf0b01463fe872365d6ded02c64a40a498a4295.json b/.sqlx/query-d1a0fe539e47a9394246dcebcdf0b01463fe872365d6ded02c64a40a498a4295.jsonnew file mode 100644index 0000000000..24b2e209da--- /dev/null+++ b/.sqlx/query-d1a0fe539e47a9394246dcebcdf0b01463fe872365d6ded02c64a40a498a4295.json@@ -0,0 +1,128 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT l.id as \"id!\", l.macro_id as \"macro_id!\",\n l.fusionauth_user_id as \"fusionauth_user_id!\",\n l.email_address as \"email_address!\",\n l.provider as \"provider!: _\",\n l.is_sync_active as \"is_sync_active!\",\n l.is_primary as \"is_primary!\",\n l.needs_reauth as \"needs_reauth!\",\n l.last_sync_error_at,\n l.created_at as \"created_at!\",\n l.updated_at as \"updated_at!\",\n s.signature_on_replies_forwards as \"signature_on_replies_forwards?\",\n s.signature,\n bj.status as \"latest_backfill_status?: _\",\n c.sfs_photo_url as \"photo_url?\"\n FROM (\n SELECT el.id, el.macro_id, el.fusionauth_user_id, el.email_address,\n el.provider, el.is_sync_active, el.is_primary, el.needs_reauth,\n el.last_sync_error_at, el.created_at, el.updated_at\n FROM email_links el\n WHERE el.macro_id = $1\n UNION\n SELECT el.id, el.macro_id, el.fusionauth_user_id, el.email_address,\n el.provider, el.is_sync_active, el.is_primary, el.needs_reauth,\n el.last_sync_error_at, el.created_at, el.updated_at\n FROM email_links el\n JOIN macro_user_links mul ON el.id = mul.link_id\n WHERE mul.primary_macro_id = $1\n ) l\n LEFT JOIN email_settings s ON s.link_id = l.id\n LEFT JOIN LATERAL (\n SELECT status FROM email_backfill_jobs\n WHERE link_id = l.id\n ORDER BY created_at DESC\n LIMIT 1\n ) bj ON true\n LEFT JOIN email_contacts c\n ON c.link_id = l.id AND LOWER(c.email_address) = LOWER(l.email_address)\n ORDER BY l.created_at DESC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "macro_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "fusionauth_user_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "email_address!",+ "type_info": "Varchar"+ },+ {+ "ordinal": 4,+ "name": "provider!: _",+ "type_info": {+ "Custom": {+ "name": "email_user_provider_enum",+ "kind": {+ "Enum": [+ "GMAIL"+ ]+ }+ }+ }+ },+ {+ "ordinal": 5,+ "name": "is_sync_active!",+ "type_info": "Bool"+ },+ {+ "ordinal": 6,+ "name": "is_primary!",+ "type_info": "Bool"+ },+ {+ "ordinal": 7,+ "name": "needs_reauth!",+ "type_info": "Bool"+ },+ {+ "ordinal": 8,+ "name": "last_sync_error_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,+ "name": "created_at!",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 10,+ "name": "updated_at!",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 11,+ "name": "signature_on_replies_forwards?",+ "type_info": "Bool"+ },+ {+ "ordinal": 12,+ "name": "signature",+ "type_info": "Text"+ },+ {+ "ordinal": 13,+ "name": "latest_backfill_status?: _",+ "type_info": {+ "Custom": {+ "name": "email_backfill_job_status",+ "kind": {+ "Enum": [+ "Init",+ "InProgress",+ "Complete",+ "Cancelled",+ "Failed"+ ]+ }+ }+ }+ },+ {+ "ordinal": 14,+ "name": "photo_url?",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null,+ null,+ null,+ null,+ null,+ null,+ null,+ null,+ null,+ null,+ null,+ false,+ true,+ false,+ true+ ]+ },+ "hash": "d1a0fe539e47a9394246dcebcdf0b01463fe872365d6ded02c64a40a498a4295"+}diff --git a/crates/email_db_client/src/links/get.rs b/crates/email_db_client/src/links/get.rsindex 4e7c9c77fa..07a7746fb7 100644--- a/crates/email_db_client/src/links/get.rs+++ b/crates/email_db_client/src/links/get.rs@@ -1,4 +1,7 @@+use chrono::{DateTime, Utc};use doppleganger::Mirror;+use macro_user_id::user_id::MacroUserIdStr;+use models_email::email::db;use models_email::email::service::link;use models_email::service;use sqlx::PgPool;@@ -162,6 +165,123 @@ pub async fn fetch_inboxes_for_macro_id(Ok(service_links?)}+/// An accessible inbox plus the per-inbox details the links list endpoint+/// renders: settings, latest backfill job status, and the self-contact photo.+#[derive(Debug, Clone)]+pub struct InboxDetails {+ pub link: link::Link,+ pub settings: service::settings::Settings,+ pub latest_backfill_status: Option<service::backfill::BackfillJobStatus>,+ pub photo_url: Option<String>,+}++struct DbInboxDetailsRow {+ id: Uuid,+ macro_id: String,+ fusionauth_user_id: String,+ email_address: String,+ provider: DbUserProvider,+ is_sync_active: bool,+ is_primary: bool,+ needs_reauth: bool,+ last_sync_error_at: Option<DateTime<Utc>>,+ created_at: DateTime<Utc>,+ updated_at: DateTime<Utc>,+ signature_on_replies_forwards: Option<bool>,+ signature: Option<String>,+ latest_backfill_status: Option<db::backfill::BackfillJobStatus>,+ photo_url: Option<String>,+}++/// Single-query variant of [`fetch_inboxes_for_macro_id`] that also joins each+/// inbox's settings, its most recent backfill job status, and its own photo+/// (the self-contact's SFS photo, synced from people/me). Inboxes without an+/// `email_settings` row get default settings.+#[tracing::instrument(skip(pool), err)]+pub async fn fetch_inbox_details_for_macro_id(+ pool: &PgPool,+ macro_id: &MacroUserIdStr<'_>,+) -> anyhow::Result<Vec<InboxDetails>> {+ let macro_id: &str = macro_id.as_ref();++ let rows = sqlx::query_as!(+ DbInboxDetailsRow,+ r#"+ SELECT l.id as "id!", l.macro_id as "macro_id!",+ l.fusionauth_user_id as "fusionauth_user_id!",+ l.email_address as "email_address!",+ l.provider as "provider!: _",+ l.is_sync_active as "is_sync_active!",+ l.is_primary as "is_primary!",+ l.needs_reauth as "needs_reauth!",+ l.last_sync_error_at,+ l.created_at as "created_at!",+ l.updated_at as "updated_at!",+ s.signature_on_replies_forwards as "signature_on_replies_forwards?",+ s.signature,+ bj.status as "latest_backfill_status?: _",+ c.sfs_photo_url as "photo_url?"+ FROM (+ SELECT el.id, el.macro_id, el.fusionauth_user_id, el.email_address,+ el.provider, el.is_sync_active, el.is_primary, el.needs_reauth,+ el.last_sync_error_at, el.created_at, el.updated_at+ FROM email_links el+ WHERE el.macro_id = $1+ UNION+ SELECT el.id, el.macro_id, el.fusionauth_user_id, el.email_address,+ el.provider, el.is_sync_active, el.is_primary, el.needs_reauth,+ el.last_sync_error_at, el.created_at, el.updated_at+ FROM email_links el+ JOIN macro_user_links mul ON el.id = mul.link_id+ WHERE mul.primary_macro_id = $1+ ) l+ LEFT JOIN email_settings s ON s.link_id = l.id+ LEFT JOIN LATERAL (+ SELECT status FROM email_backfill_jobs+ WHERE link_id = l.id+ ORDER BY created_at DESC+ LIMIT 1+ ) bj ON true+ LEFT JOIN email_contacts c+ ON c.link_id = l.id AND LOWER(c.email_address) = LOWER(l.email_address)+ ORDER BY l.created_at DESC+ "#,+ macro_id+ )+ .fetch_all(pool)+ .await?;++ rows.into_iter()+ .map(|row| {+ let settings = service::settings::Settings {+ link_id: row.id,+ // Missing settings row → schema default (FALSE).+ signature_on_replies_forwards: row.signature_on_replies_forwards.unwrap_or(false),+ signature: row.signature,+ };+ let link = link::Link::try_from(DbLink {+ id: row.id,+ macro_id: row.macro_id,+ fusionauth_user_id: row.fusionauth_user_id,+ email_address: row.email_address,+ provider: row.provider,+ is_sync_active: row.is_sync_active,+ is_primary: row.is_primary,+ needs_reauth: row.needs_reauth,+ last_sync_error_at: row.last_sync_error_at,+ created_at: row.created_at,+ updated_at: row.updated_at,+ })?;+ Ok(InboxDetails {+ link,+ settings,+ latest_backfill_status: row.latest_backfill_status.map(Into::into),+ photo_url: row.photo_url,+ })+ })+ .collect()+}+/// fetches email_links given a fusionauth_user_id. a fusionauth_user_id can have multiple email_links, each with a unique macro_id#[tracing::instrument(skip(pool), err)]pub async fn fetch_links_by_fusionauth_user_id(diff --git a/crates/email_db_client/src/links/get/test.rs b/crates/email_db_client/src/links/get/test.rsindex e30b38e4c7..9292508c8e 100644--- a/crates/email_db_client/src/links/get/test.rs+++ b/crates/email_db_client/src/links/get/test.rs@@ -1,8 +1,12 @@use crate::links::get::{- fetch_inboxes_for_macro_id, fetch_link_by_email, fetch_link_by_macro_id_and_email_address,- fetch_owned_link_for_message, fetch_owned_link_for_thread,+ fetch_inbox_details_for_macro_id, fetch_inboxes_for_macro_id, fetch_link_by_email,+ fetch_link_by_macro_id_and_email_address, fetch_owned_link_for_message,+ fetch_owned_link_for_thread,};use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_user_id::user_id::MacroUserIdStr;+use models_email::email::db;+use models_email::service::backfill::BackfillJobStatus;use models_email::service::link::UserProvider;use sqlx::types::Uuid;use sqlx::{Pool, Postgres};@@ -11,6 +15,10 @@ const CHILD: &str = "macro|[email protected]"; // owns the inboxconst PRIMARY: &str = "macro|[email protected]"; // delegateconst STRANGER: &str = "macro|[email protected]"; // no relationship+fn macro_id(s: &str) -> MacroUserIdStr<'_> {+ MacroUserIdStr::try_from(s).unwrap()+}+/// macro_user + "User" rows so macro_user_links FKs resolve.async fn insert_user(pool: &Pool<Postgres>, macro_id: &str, email: &str) {let macro_uuid = Uuid::new_v4();@@ -94,6 +102,77 @@ async fn insert_inbox_with_thread_and_message((link_id, thread_id, message_id)}+async fn insert_settings(+ pool: &Pool<Postgres>,+ link_id: Uuid,+ signature_on_replies_forwards: bool,+ signature: Option<&str>,+) {+ sqlx::query!(+ r#"INSERT INTO email_settings (link_id, signature_on_replies_forwards, signature)+ VALUES ($1, $2, $3)"#,+ link_id,+ signature_on_replies_forwards,+ signature,+ )+ .execute(pool)+ .await+ .unwrap();+}++/// A backfill job created `age_minutes` ago, so tests can control which job is latest.+async fn insert_backfill_job(+ pool: &Pool<Postgres>,+ link_id: Uuid,+ macro_id: &str,+ status: db::backfill::BackfillJobStatus,+ age_minutes: i32,+) {+ sqlx::query!(+ r#"INSERT INTO email_backfill_jobs (id, link_id, fusionauth_user_id, status, created_at)+ VALUES ($1, $2, $3, $4, now() - make_interval(mins => $5))"#,+ Uuid::new_v4(),+ link_id,+ macro_id,+ status as _,+ age_minutes,+ )+ .execute(pool)+ .await+ .unwrap();+}++/// Backdates a link so tests can control the newest-first ordering.+async fn age_link(pool: &Pool<Postgres>, link_id: Uuid, age_minutes: i32) {+ sqlx::query!(+ r#"UPDATE email_links SET created_at = now() - make_interval(mins => $2) WHERE id = $1"#,+ link_id,+ age_minutes,+ )+ .execute(pool)+ .await+ .unwrap();+}++async fn insert_contact_with_photo(+ pool: &Pool<Postgres>,+ link_id: Uuid,+ email: &str,+ sfs_photo_url: Option<&str>,+) {+ sqlx::query!(+ r#"INSERT INTO email_contacts (id, link_id, email_address, sfs_photo_url)+ VALUES ($1, $2, $3, $4)"#,+ Uuid::new_v4(),+ link_id,+ email,+ sfs_photo_url,+ )+ .execute(pool)+ .await+ .unwrap();+}+async fn insert_delegation(pool: &Pool<Postgres>, primary: &str, child: &str, link_id: Uuid) {sqlx::query!(r#"INSERT INTO macro_user_links (primary_macro_id, child_macro_id, link_id)@@ -209,6 +288,285 @@ async fn scoped_delegation_sees_only_its_link(pool: Pool<Postgres>) -> anyhow::ROk(())}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn fetch_inbox_details_joins_settings_backfill_and_photo(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ insert_user(&pool, CHILD, "[email protected]").await;+ let (link_id, _, _) =+ insert_inbox_with_thread_and_message(&pool, CHILD, "[email protected]").await;+ insert_settings(&pool, link_id, true, Some("<p>sig</p>")).await;++ // Older Complete job then a newer Failed one — the latest wins.+ insert_backfill_job(+ &pool,+ link_id,+ CHILD,+ db::backfill::BackfillJobStatus::Complete,+ 60,+ )+ .await;+ insert_backfill_job(+ &pool,+ link_id,+ CHILD,+ db::backfill::BackfillJobStatus::Failed,+ 0,+ )+ .await;++ // The self-contact carries the inbox photo and must match case-insensitively;+ // the helper's unrelated sender contact must not bleed in.+ insert_contact_with_photo(+ &pool,+ link_id,+ "[email protected]",+ Some("https://sfs/photo.png"),+ )+ .await;++ let details = fetch_inbox_details_for_macro_id(&pool, ¯o_id(CHILD)).await?;+ assert_eq!(details.len(), 1);+ let inbox = &details[0];+ assert_eq!(inbox.link.id, link_id);+ assert!(inbox.settings.signature_on_replies_forwards);+ assert_eq!(inbox.settings.signature.as_deref(), Some("<p>sig</p>"));+ assert_eq!(+ inbox.latest_backfill_status,+ Some(BackfillJobStatus::Failed)+ );+ assert_eq!(inbox.photo_url.as_deref(), Some("https://sfs/photo.png"));++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn fetch_inbox_details_includes_delegated_inbox_with_optional_fields_absent(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ insert_user(&pool, CHILD, "[email protected]").await;+ insert_user(&pool, PRIMARY, "[email protected]").await;+ let (link_id, _, _) =+ insert_inbox_with_thread_and_message(&pool, CHILD, "[email protected]").await;+ insert_settings(&pool, link_id, false, None).await;+ insert_delegation(&pool, PRIMARY, CHILD, link_id).await;++ // No backfill jobs and no self-contact — the delegate still sees the inbox,+ // with the optional details absent.+ let details = fetch_inbox_details_for_macro_id(&pool, ¯o_id(PRIMARY)).await?;+ assert_eq!(details.len(), 1);+ let inbox = &details[0];+ assert_eq!(inbox.link.id, link_id);+ assert!(!inbox.settings.signature_on_replies_forwards);+ assert!(inbox.settings.signature.is_none());+ assert!(inbox.latest_backfill_status.is_none());+ assert!(inbox.photo_url.is_none());++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn fetch_inbox_details_orders_newest_first_and_pairs_rows_per_inbox(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ insert_user(&pool, CHILD, "[email protected]").await;+ let (link_a, _, _) =+ insert_inbox_with_thread_and_message(&pool, CHILD, "[email protected]").await;+ age_link(&pool, link_a, 60).await;+ let (link_b, _, _) =+ insert_inbox_with_thread_and_message(&pool, CHILD, "[email protected]").await;++ insert_settings(&pool, link_a, true, Some("<p>sig-a</p>")).await;+ insert_settings(&pool, link_b, false, None).await;++ // Details must attach only to their own inbox: photo on A, backfill job on B.+ insert_contact_with_photo(+ &pool,+ link_a,+ "[email protected]",+ Some("https://sfs/a.png"),+ )+ .await;+ insert_backfill_job(+ &pool,+ link_b,+ CHILD,+ db::backfill::BackfillJobStatus::InProgress,+ 0,+ )+ .await;++ let details = fetch_inbox_details_for_macro_id(&pool, ¯o_id(CHILD)).await?;+ let ids: Vec<Uuid> = details.iter().map(|d| d.link.id).collect();+ assert_eq!(ids, vec![link_b, link_a]);++ let (newer, older) = (&details[0], &details[1]);+ assert!(!newer.settings.signature_on_replies_forwards);+ assert!(newer.settings.signature.is_none());+ assert_eq!(+ newer.latest_backfill_status,+ Some(BackfillJobStatus::InProgress)+ );+ assert!(newer.photo_url.is_none());++ assert!(older.settings.signature_on_replies_forwards);+ assert_eq!(older.settings.signature.as_deref(), Some("<p>sig-a</p>"));+ assert!(older.latest_backfill_status.is_none());+ assert_eq!(older.photo_url.as_deref(), Some("https://sfs/a.png"));++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn fetch_inbox_details_dedupes_inbox_that_is_both_owned_and_delegated(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ insert_user(&pool, CHILD, "[email protected]").await;+ insert_user(&pool, PRIMARY, "[email protected]").await;+ let (link_id, _, _) =+ insert_inbox_with_thread_and_message(&pool, CHILD, "[email protected]").await;+ insert_settings(&pool, link_id, false, None).await;++ // CHILD owns the inbox AND appears as its delegate via macro_user_links+ // (the check constraint forbids self-rows, so the grant's child is another+ // user). Both UNION branches match and must collapse to one row.+ insert_delegation(&pool, CHILD, PRIMARY, link_id).await;++ let details = fetch_inbox_details_for_macro_id(&pool, ¯o_id(CHILD)).await?;+ assert_eq!(details.len(), 1);+ assert_eq!(details[0].link.id, link_id);++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn fetch_inbox_details_photo_ignores_matching_email_on_other_link(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ insert_user(&pool, CHILD, "[email protected]").await;+ insert_user(&pool, STRANGER, "[email protected]").await;+ let (own_link, _, _) =+ insert_inbox_with_thread_and_message(&pool, CHILD, "[email protected]").await;+ insert_settings(&pool, own_link, false, None).await;++ // The inbox's address exists as a contact with a photo — but on someone+ // else's link, so it must not be picked up as the inbox photo.+ let (other_link, _, _) =+ insert_inbox_with_thread_and_message(&pool, STRANGER, "[email protected]").await;+ insert_settings(&pool, other_link, false, None).await;+ insert_contact_with_photo(+ &pool,+ other_link,+ "[email protected]",+ Some("https://sfs/other.png"),+ )+ .await;++ let details = fetch_inbox_details_for_macro_id(&pool, ¯o_id(CHILD)).await?;+ assert_eq!(details.len(), 1);+ assert!(details[0].photo_url.is_none());++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn fetch_inbox_details_photo_absent_when_self_contact_has_no_photo(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ insert_user(&pool, CHILD, "[email protected]").await;+ let (link_id, _, _) =+ insert_inbox_with_thread_and_message(&pool, CHILD, "[email protected]").await;+ insert_settings(&pool, link_id, false, None).await;++ // Self-contact row exists but has no SFS photo yet.+ insert_contact_with_photo(&pool, link_id, "[email protected]", None).await;++ let details = fetch_inbox_details_for_macro_id(&pool, ¯o_id(CHILD)).await?;+ assert_eq!(details.len(), 1);+ assert!(details[0].photo_url.is_none());++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn fetch_inbox_details_maps_each_backfill_status(pool: Pool<Postgres>) -> anyhow::Result<()> {+ insert_user(&pool, CHILD, "[email protected]").await;++ // One inbox per status — the uq_active_backfill_job_per_link index allows+ // only a single Init/InProgress job per link.+ let statuses = vec![+ (+ db::backfill::BackfillJobStatus::Init,+ BackfillJobStatus::Init,+ ),+ (+ db::backfill::BackfillJobStatus::InProgress,+ BackfillJobStatus::InProgress,+ ),+ (+ db::backfill::BackfillJobStatus::Complete,+ BackfillJobStatus::Complete,+ ),+ (+ db::backfill::BackfillJobStatus::Cancelled,+ BackfillJobStatus::Cancelled,+ ),+ (+ db::backfill::BackfillJobStatus::Failed,+ BackfillJobStatus::Failed,+ ),+ ];+ let mut expected_by_link = Vec::new();+ for (i, (db_status, expected)) in statuses.into_iter().enumerate() {+ let email = format!("inbox{i}@corp.test");+ let (link_id, _, _) = insert_inbox_with_thread_and_message(&pool, CHILD, &email).await;+ insert_settings(&pool, link_id, false, None).await;+ insert_backfill_job(&pool, link_id, CHILD, db_status, 0).await;+ expected_by_link.push((link_id, expected));+ }++ let details = fetch_inbox_details_for_macro_id(&pool, ¯o_id(CHILD)).await?;+ assert_eq!(details.len(), expected_by_link.len());+ for (link_id, expected) in expected_by_link {+ let inbox = details.iter().find(|d| d.link.id == link_id).unwrap();+ assert_eq!(inbox.latest_backfill_status, Some(expected));+ }++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn fetch_inbox_details_empty_for_user_without_inboxes(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ insert_user(&pool, CHILD, "[email protected]").await;++ let details = fetch_inbox_details_for_macro_id(&pool, ¯o_id(CHILD)).await?;+ assert!(details.is_empty());++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn fetch_inbox_details_defaults_settings_when_row_missing(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ insert_user(&pool, CHILD, "[email protected]").await;+ let (link_id, _, _) =+ insert_inbox_with_thread_and_message(&pool, CHILD, "[email protected]").await;++ // A legacy link with no email_settings row must still be listed, with+ // default settings.+ let details = fetch_inbox_details_for_macro_id(&pool, ¯o_id(CHILD)).await?;+ assert_eq!(details.len(), 1);+ let inbox = &details[0];+ assert_eq!(inbox.link.id, link_id);+ assert!(!inbox.settings.signature_on_replies_forwards);+ assert!(inbox.settings.signature.is_none());++ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn fetch_link_by_email_finds_link_owned_by_another_macro_user(pool: Pool<Postgres>,diff --git a/crates/macro_db_client/migrations/20260716144800_email_contacts_link_id_lower_email_index.sql b/crates/macro_db_client/migrations/20260716144800_email_contacts_link_id_lower_email_index.sqlnew file mode 100644index 0000000000..0f93ed1512--- /dev/null+++ b/crates/macro_db_client/migrations/20260716144800_email_contacts_link_id_lower_email_index.sql@@ -0,0 +1,5 @@+-- no-transaction++-- Case-insensitive self-contact lookup for the inbox photo (links list).+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_email_contacts_link_id_lower_email+ ON email_contacts (link_id, LOWER(email_address));diff --git a/crates/macro_db_client/migrations/20260716144813_email_backfill_jobs_link_id_created_at_index.sql b/crates/macro_db_client/migrations/20260716144813_email_backfill_jobs_link_id_created_at_index.sqlnew file mode 100644index 0000000000..cfc6b49c9b--- /dev/null+++ b/crates/macro_db_client/migrations/20260716144813_email_backfill_jobs_link_id_created_at_index.sql@@ -0,0 +1,5 @@+-- no-transaction++-- Latest-backfill-job-per-link lookup (links list sync status).+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_email_backfill_jobs_link_id_created_at+ ON email_backfill_jobs (link_id, created_at DESC);diff --git a/services/email_service/src/api/email/links/list.rs b/services/email_service/src/api/email/links/list.rsindex 759d5f445e..e286c2af86 100644--- a/services/email_service/src/api/email/links/list.rs+++ b/services/email_service/src/api/email/links/list.rs@@ -3,7 +3,7 @@ use axum::extract::State;use axum::http::StatusCode;use axum::response::{IntoResponse, Response};use axum::{Extension, Json};-use futures::future::join_all;+use macro_user_id::user_id::MacroUserIdStr;use model::response::ErrorResponse;use model::user::UserContext;use models_email::api;@@ -16,12 +16,15 @@ use thiserror::Error;pub enum ListLinksError {#[error("Database error")]DatabaseError(anyhow::Error),+ #[error("Invalid macro user id")]+ InvalidMacroId,}impl IntoResponse for ListLinksError {fn into_response(self) -> Response {let status_code = match &self {ListLinksError::DatabaseError(_) => StatusCode::INTERNAL_SERVER_ERROR,+ ListLinksError::InvalidMacroId => StatusCode::BAD_REQUEST,};(status_code, self.to_string()).into_response()@@ -53,53 +56,29 @@ pub async fn list_links_handler(State(ctx): State<ApiContext>,user_context: Extension<UserContext>,) -> Result<Response, ListLinksError> {- let links =- email_db_client::links::get::fetch_inboxes_for_macro_id(&ctx.db, &user_context.user_id)- .await- .map_err(ListLinksError::DatabaseError)?;+ let macro_id = MacroUserIdStr::parse_from_str(&user_context.user_id)+ .map_err(|_| ListLinksError::InvalidMacroId)?;- let tasks = links.into_iter().map(|link| {- let ctx = ctx.clone();- async move {- let settings = email_db_client::settings::fetch_settings(&ctx.db, link.id)- .await- .map_err(ListLinksError::DatabaseError)?;+ let inboxes = email_db_client::links::get::fetch_inbox_details_for_macro_id(&ctx.db, ¯o_id)+ .await+ .map_err(ListLinksError::DatabaseError)?;- let latest_job =- email_db_client::backfill::job::get::get_latest_backfill_job_by_link_id(- &ctx.db, link.id,- )- .await- .map_err(ListLinksError::DatabaseError)?;+ let links = inboxes+ .into_iter()+ .map(|inbox| {let sync_status = api::link::SyncStatus::derive(- link.is_sync_active,- link.needs_reauth,- latest_job.map(|job| job.status),+ inbox.link.is_sync_active,+ inbox.link.needs_reauth,+ inbox.latest_backfill_status,);-- // The inbox's own photo comes from its self-contact (synced from people/me).- let photo_url = email_db_client::contacts::get::fetch_contact_by_email(- &ctx.db,- link.id,- link.email_address.0.as_ref(),- )- .await- .map_err(ListLinksError::DatabaseError)?- .and_then(|contact| contact.photo_url);-- Ok(api::link::Link::new(- link,- api::settings::Settings::from(settings),+ api::link::Link::new(+ inbox.link,+ api::settings::Settings::from(inbox.settings),sync_status,- photo_url,- ))- }- });-- let results = join_all(tasks).await;-- let api_links: Result<Vec<_>, _> = results.into_iter().collect();- let api_links = api_links?;+ inbox.photo_url,+ )+ })+ .collect();- Ok((StatusCode::OK, Json(ListLinksResponse { links: api_links })).into_response())+ Ok((StatusCode::OK, Json(ListLinksResponse { links })).into_response())}