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(email): union read endpoints across linked inboxes; single-inbox writes via X-Email-Link-Id (#3685)

gbirmanb9bf4561cb57
diff --git a/js/app/packages/service-clients/service-email/generated/client.ts b/js/app/packages/service-clients/service-email/generated/client.ts
index 4d0959647d..61eaea6f8d 100644
--- a/js/app/packages/service-clients/service-email/generated/client.ts
+++ b/js/app/packages/service-clients/service-email/generated/client.ts
@@ -397,11 +397,6 @@ export type listContactsResponse401 = {
status: 401;
};
-export type listContactsResponse404 = {
- data: ErrorResponse;
- status: 404;
-};
-
export type listContactsResponse500 = {
data: ErrorResponse;
status: 500;
@@ -412,7 +407,6 @@ export type listContactsResponseSuccess = listContactsResponse200 & {
};
export type listContactsResponseError = (
| listContactsResponse401
- | listContactsResponse404
| listContactsResponse500
) & {
headers: Headers;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiThreadPreviewCursorInner.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiThreadPreviewCursorInner.ts
index d04f3da2ce..5b45b2749c 100644
--- a/js/app/packages/service-clients/service-email/generated/schemas/apiThreadPreviewCursorInner.ts
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiThreadPreviewCursorInner.ts
@@ -19,6 +19,7 @@ export interface ApiThreadPreviewCursorInner {
isDraft: boolean;
isImportant: boolean;
isRead: boolean;
+ linkId: string;
name?: ApiThreadPreviewCursorInnerName;
ownerId: string;
providerId?: ApiThreadPreviewCursorInnerProviderId;
diff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.json
index 49441748c1..04ebe4a85d 100644
--- a/js/app/packages/service-clients/service-email/openapi.json
+++ b/js/app/packages/service-clients/service-email/openapi.json
@@ -347,16 +347,6 @@
}
}
},
- "404": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ErrorResponse"
- }
- }
- }
- },
"500": {
"description": "",
"content": {
@@ -3554,7 +3544,8 @@
"isImportant",
"sortTs",
"createdAt",
- "updatedAt"
+ "updatedAt",
+ "linkId"
],
"properties": {
"createdAt": {
@@ -3577,6 +3568,10 @@
"isRead": {
"type": "boolean"
},
+ "linkId": {
+ "type": "string",
+ "format": "uuid"
+ },
"name": {
"type": ["string", "null"]
},
diff --git a/rust/cloud-storage/.sqlx/query-fe76f71ae6e0484ff8d47427ccc0eecee1c64c422b0745a6ba5d0cd680e56f9e.json b/rust/cloud-storage/.sqlx/query-2f51ce444a7d59339909afba8296d2076f0654d89c89495858fec18432df7074.json
similarity index 91%
rename from rust/cloud-storage/.sqlx/query-fe76f71ae6e0484ff8d47427ccc0eecee1c64c422b0745a6ba5d0cd680e56f9e.json
rename to rust/cloud-storage/.sqlx/query-2f51ce444a7d59339909afba8296d2076f0654d89c89495858fec18432df7074.json
index 9bc626ab26..538ce89fdb 100644
--- a/rust/cloud-storage/.sqlx/query-fe76f71ae6e0484ff8d47427ccc0eecee1c64c422b0745a6ba5d0cd680e56f9e.json
+++ b/rust/cloud-storage/.sqlx/query-2f51ce444a7d59339909afba8296d2076f0654d89c89495858fec18432df7074.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n WITH ApplicableLabelIDs AS (\n SELECT id\n FROM email_labels\n WHERE link_id = ANY($1)\n AND (name = 'INBOX')\n ),\n QualifyingMessages AS (\n SELECT m.thread_id,\n m.internal_date_ts,\n m.created_at AS fallback_ts,\n m.is_draft,\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name\n FROM email_messages m\n WHERE m.link_id = ANY($1)\n AND NOT EXISTS (\n SELECT 1\n FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id\n AND l.name = 'TRASH'\n AND l.link_id = m.link_id\n )\n AND EXISTS (\n SELECT 1\n FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id\n AND l.name = 'IMPORTANT'\n )\n AND EXISTS (\n SELECT 1\n FROM email_message_labels ml\n JOIN ApplicableLabelIDs ali ON ml.label_id = ali.id\n WHERE ml.message_id = m.id\n )\n\n UNION ALL\n\n SELECT m.thread_id,\n m.internal_date_ts,\n m.created_at AS fallback_ts,\n m.is_draft,\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name\n FROM email_messages m\n WHERE m.link_id = ANY($1)\n AND m.is_draft = TRUE\n AND NOT EXISTS (\n SELECT 1\n FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id\n AND l.name = 'TRASH'\n AND l.link_id = m.link_id\n )\n ),\n AllImportantThreads AS (\n -- From all qualifying messages, get the single most recent one per thread.\n SELECT DISTINCT ON (thread_id)\n thread_id,\n internal_date_ts,\n fallback_ts,\n is_draft,\n subject,\n snippet,\n from_contact_id,\n from_name\n FROM QualifyingMessages\n ORDER BY thread_id, COALESCE(internal_date_ts, fallback_ts) DESC\n ),\n ImportantWithSortKey AS (\n -- Join with user_history to calculate the final effective sort key.\n SELECT\n ait.thread_id,\n ait.internal_date_ts,\n ait.fallback_ts,\n ait.is_draft,\n ait.subject,\n ait.snippet,\n ait.from_contact_id,\n ait.from_name,\n COALESCE(ait.internal_date_ts, ait.fallback_ts) as created_at,\n COALESCE(ait.internal_date_ts, ait.fallback_ts) as updated_at,\n uh.updated_at as viewed_at,\n -- This CASE statement dynamically selects the correct timestamp for sorting.\n -- For 'updated_at' and 'created_at', we use the important message timestamp\n -- For 'viewed_at', we use the history timestamp.\n -- For 'viewed_updated', we use the history timestamp if it exists, otherwise the important message timestamp.\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, COALESCE(ait.internal_date_ts, ait.fallback_ts))\n ELSE COALESCE(ait.internal_date_ts, ait.fallback_ts)\n END AS effective_ts\n FROM AllImportantThreads ait\n JOIN email_threads tt ON tt.id = ait.thread_id\n -- This has to be a left join to support all sort methods.\n LEFT JOIN email_user_history uh ON uh.thread_id = ait.thread_id AND uh.link_id = tt.link_id\n )\n SELECT\n isk.thread_id as \"id!\",\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n isk.effective_ts as \"sort_ts!\",\n isk.created_at as \"created_at!\",\n isk.updated_at as \"updated_at!\",\n t.project_id,\n isk.viewed_at as \"viewed_at?\",\n isk.is_draft as \"is_draft!\",\n -- It's the important view - all threads here are important\n true as \"is_important!\",\n isk.subject as \"name?\",\n isk.snippet as \"snippet?\",\n c.email_address AS \"sender_email?\",\n COALESCE(isk.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\"\n FROM ImportantWithSortKey isk\n JOIN email_threads t ON isk.thread_id = t.id\n LEFT JOIN email_contacts c ON isk.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n WHERE\n ($3::timestamptz IS NULL) OR (isk.effective_ts, isk.thread_id) < ($3::timestamptz, $4::uuid)\n ORDER BY isk.effective_ts DESC, isk.thread_id DESC\n LIMIT $2\n ",
+ "query": "\n WITH ApplicableLabelIDs AS (\n SELECT id\n FROM email_labels\n WHERE link_id = ANY($1)\n AND (name = 'INBOX')\n ),\n QualifyingMessages AS (\n SELECT m.thread_id,\n m.internal_date_ts,\n m.created_at AS fallback_ts,\n m.is_draft,\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name\n FROM email_messages m\n WHERE m.link_id = ANY($1)\n AND NOT EXISTS (\n SELECT 1\n FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id\n AND l.name = 'TRASH'\n AND l.link_id = m.link_id\n )\n AND EXISTS (\n SELECT 1\n FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id\n AND l.name = 'IMPORTANT'\n )\n AND EXISTS (\n SELECT 1\n FROM email_message_labels ml\n JOIN ApplicableLabelIDs ali ON ml.label_id = ali.id\n WHERE ml.message_id = m.id\n )\n\n UNION ALL\n\n SELECT m.thread_id,\n m.internal_date_ts,\n m.created_at AS fallback_ts,\n m.is_draft,\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name\n FROM email_messages m\n WHERE m.link_id = ANY($1)\n AND m.is_draft = TRUE\n AND NOT EXISTS (\n SELECT 1\n FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id\n AND l.name = 'TRASH'\n AND l.link_id = m.link_id\n )\n ),\n AllImportantThreads AS (\n -- From all qualifying messages, get the single most recent one per thread.\n SELECT DISTINCT ON (thread_id)\n thread_id,\n internal_date_ts,\n fallback_ts,\n is_draft,\n subject,\n snippet,\n from_contact_id,\n from_name\n FROM QualifyingMessages\n ORDER BY thread_id, COALESCE(internal_date_ts, fallback_ts) DESC\n ),\n ImportantWithSortKey AS (\n -- Join with user_history to calculate the final effective sort key.\n SELECT\n ait.thread_id,\n ait.internal_date_ts,\n ait.fallback_ts,\n ait.is_draft,\n ait.subject,\n ait.snippet,\n ait.from_contact_id,\n ait.from_name,\n COALESCE(ait.internal_date_ts, ait.fallback_ts) as created_at,\n COALESCE(ait.internal_date_ts, ait.fallback_ts) as updated_at,\n uh.updated_at as viewed_at,\n -- This CASE statement dynamically selects the correct timestamp for sorting.\n -- For 'updated_at' and 'created_at', we use the important message timestamp\n -- For 'viewed_at', we use the history timestamp.\n -- For 'viewed_updated', we use the history timestamp if it exists, otherwise the important message timestamp.\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, COALESCE(ait.internal_date_ts, ait.fallback_ts))\n ELSE COALESCE(ait.internal_date_ts, ait.fallback_ts)\n END AS effective_ts\n FROM AllImportantThreads ait\n JOIN email_threads tt ON tt.id = ait.thread_id\n -- This has to be a left join to support all sort methods.\n LEFT JOIN email_user_history uh ON uh.thread_id = ait.thread_id AND uh.link_id = tt.link_id\n )\n SELECT\n isk.thread_id as \"id!\",\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n isk.effective_ts as \"sort_ts!\",\n isk.created_at as \"created_at!\",\n isk.updated_at as \"updated_at!\",\n t.project_id,\n isk.viewed_at as \"viewed_at?\",\n isk.is_draft as \"is_draft!\",\n -- It's the important view - all threads here are important\n true as \"is_important!\",\n isk.subject as \"name?\",\n isk.snippet as \"snippet?\",\n c.email_address AS \"sender_email?\",\n COALESCE(isk.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\",\n el.id AS \"link_id!\"\n FROM ImportantWithSortKey isk\n JOIN email_threads t ON isk.thread_id = t.id\n LEFT JOIN email_contacts c ON isk.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n WHERE\n ($3::timestamptz IS NULL) OR (isk.effective_ts, isk.thread_id) < ($3::timestamptz, $4::uuid)\n ORDER BY isk.effective_ts DESC, isk.thread_id DESC\n LIMIT $2\n ",
"describe": {
"columns": [
{
@@ -87,6 +87,11 @@
"ordinal": 16,
"name": "owner_id!",
"type_info": "Text"
+ },
+ {
+ "ordinal": 17,
+ "name": "link_id!",
+ "type_info": "Uuid"
}
],
"parameters": {
@@ -115,8 +120,9 @@
false,
null,
true,
+ false,
false
]
},
- "hash": "fe76f71ae6e0484ff8d47427ccc0eecee1c64c422b0745a6ba5d0cd680e56f9e"
+ "hash": "2f51ce444a7d59339909afba8296d2076f0654d89c89495858fec18432df7074"
}
diff --git a/rust/cloud-storage/.sqlx/query-3fdecaafcd87b6e4776cdc7aeb36e46b5a0410a1229f53886035fd0fd1d88a63.json b/rust/cloud-storage/.sqlx/query-3fdecaafcd87b6e4776cdc7aeb36e46b5a0410a1229f53886035fd0fd1d88a63.json
deleted file mode 100644
index e6717d3115..0000000000
--- a/rust/cloud-storage/.sqlx/query-3fdecaafcd87b6e4776cdc7aeb36e46b5a0410a1229f53886035fd0fd1d88a63.json
+++ /dev/null
@@ -1,122 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n (\n SELECT EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_labels ml ON m_imp.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m_imp.thread_id = t.id\n AND l.name = 'IMPORTANT'\n AND l.link_id = t.link_id\n )\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\"\n FROM (\n -- Step 1: Efficiently find and sort ONLY the top N+1 candidate threads.\n -- This subquery only touches `threads` and `user_history`.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n t.latest_outbound_message_ts AS created_at,\n t.latest_outbound_message_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_outbound_message_ts)\n ELSE t.latest_outbound_message_ts\n END AS effective_ts\n FROM email_threads t\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n t.link_id = ANY($1)\n AND t.latest_outbound_message_ts IS NOT NULL\n \n -- Cursor logic moved inside for maximum efficiency\n AND (($3::timestamptz IS NULL) OR (\n -- This CASE must exactly match the one that defines `effective_ts`\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_outbound_message_ts)\n ELSE t.latest_outbound_message_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find its latest SENT, non-trashed message.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND m.is_sent = TRUE -- This condition is specific to the \"Sent\" view\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = t.link_id\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details for the final result set.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n -- Final ordering is preserved because the input `t` is already sorted.\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "provider_id",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "inbox_visible",
- "type_info": "Bool"
- },
- {
- "ordinal": 3,
- "name": "is_read",
- "type_info": "Bool"
- },
- {
- "ordinal": 4,
- "name": "sort_ts!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 5,
- "name": "created_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 6,
- "name": "updated_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 7,
- "name": "project_id",
- "type_info": "Text"
- },
- {
- "ordinal": 8,
- "name": "viewed_at?",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 9,
- "name": "name?",
- "type_info": "Text"
- },
- {
- "ordinal": 10,
- "name": "snippet?",
- "type_info": "Text"
- },
- {
- "ordinal": 11,
- "name": "is_draft",
- "type_info": "Bool"
- },
- {
- "ordinal": 12,
- "name": "is_important!",
- "type_info": "Bool"
- },
- {
- "ordinal": 13,
- "name": "sender_email?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 14,
- "name": "sender_name?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 15,
- "name": "sender_photo_url?",
- "type_info": "Text"
- },
- {
- "ordinal": 16,
- "name": "owner_id!",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "UuidArray",
- "Int8",
- "Timestamptz",
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- false,
- true,
- false,
- false,
- null,
- true,
- true,
- true,
- false,
- true,
- true,
- false,
- null,
- false,
- null,
- true,
- false
- ]
- },
- "hash": "3fdecaafcd87b6e4776cdc7aeb36e46b5a0410a1229f53886035fd0fd1d88a63"
-}
diff --git a/rust/cloud-storage/.sqlx/query-26dea63de88041b56c6a105b66cb71cb35883ece0f9928887b7ed5d628fe6696.json b/rust/cloud-storage/.sqlx/query-523326bd4435e4f15ca5e0cc7f015e99eac0492d7e855375a0389e246c400049.json
similarity index 50%
rename from rust/cloud-storage/.sqlx/query-26dea63de88041b56c6a105b66cb71cb35883ece0f9928887b7ed5d628fe6696.json
rename to rust/cloud-storage/.sqlx/query-523326bd4435e4f15ca5e0cc7f015e99eac0492d7e855375a0389e246c400049.json
index 10930d913b..167cd55550 100644
--- a/rust/cloud-storage/.sqlx/query-26dea63de88041b56c6a105b66cb71cb35883ece0f9928887b7ed5d628fe6696.json
+++ b/rust/cloud-storage/.sqlx/query-523326bd4435e4f15ca5e0cc7f015e99eac0492d7e855375a0389e246c400049.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n WITH trash_labels AS (\n SELECT id, link_id FROM email_labels WHERE link_id = ANY($1) AND name = 'TRASH'\n ),\n important_labels AS (\n SELECT id, link_id FROM email_labels WHERE link_id = ANY($1) AND name = 'IMPORTANT'\n )\n SELECT\n t.id,\n t.provider_id,\n TRUE AS \"inbox_visible!\",\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_labels ml ON m_imp.id = ml.message_id\n JOIN important_labels il ON ml.label_id = il.id\n WHERE m_imp.thread_id = t.id\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\"\n FROM (\n -- Step 1: Efficiently find and sort ONLY the top N+1 candidate threads.\n -- This subquery is fast as it only touches `threads` and `user_history`.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.is_read,\n t.project_id,\n t.latest_inbound_message_ts AS created_at,\n t.latest_inbound_message_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_inbound_message_ts)\n ELSE t.latest_inbound_message_ts\n END AS effective_ts\n FROM email_threads t\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n t.link_id = ANY($1)\n AND t.inbox_visible = TRUE\n AND t.latest_inbound_message_ts IS NOT NULL\n\n -- The cursor logic is moved inside this subquery for maximum efficiency.\n AND (($3::timestamptz IS NULL) OR (\n -- This CASE must exactly match the one that defines `effective_ts`\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_inbound_message_ts)\n ELSE t.latest_inbound_message_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC -- fall back to updated_at if effective_ts is the same\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find its latest non-trashed message.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN trash_labels tl ON ml.label_id = tl.id\n WHERE ml.message_id = m.id\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details for the final result set.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n -- Final ordering is preserved because the input `t` is already sorted.\n ORDER BY t.effective_ts DESC, t.updated_at DESC -- fall back to updated_at if effective_ts is the same\n ",
+ "query": "\n WITH trash_labels AS (\n SELECT id, link_id FROM email_labels WHERE link_id = ANY($1) AND name = 'TRASH'\n ),\n important_labels AS (\n SELECT id, link_id FROM email_labels WHERE link_id = ANY($1) AND name = 'IMPORTANT'\n )\n SELECT\n t.id,\n t.provider_id,\n TRUE AS \"inbox_visible!\",\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_labels ml ON m_imp.id = ml.message_id\n JOIN important_labels il ON ml.label_id = il.id\n WHERE m_imp.thread_id = t.id\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\",\n el.id AS \"link_id!\"\n FROM (\n -- Step 1: Efficiently find and sort ONLY the top N+1 candidate threads.\n -- This subquery is fast as it only touches `threads` and `user_history`.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.is_read,\n t.project_id,\n t.latest_inbound_message_ts AS created_at,\n t.latest_inbound_message_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_inbound_message_ts)\n ELSE t.latest_inbound_message_ts\n END AS effective_ts\n FROM email_threads t\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n t.link_id = ANY($1)\n AND t.inbox_visible = TRUE\n AND t.latest_inbound_message_ts IS NOT NULL\n\n -- The cursor logic is moved inside this subquery for maximum efficiency.\n AND (($3::timestamptz IS NULL) OR (\n -- This CASE must exactly match the one that defines `effective_ts`\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_inbound_message_ts)\n ELSE t.latest_inbound_message_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC -- fall back to updated_at if effective_ts is the same\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find its latest non-trashed message.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN trash_labels tl ON ml.label_id = tl.id\n WHERE ml.message_id = m.id\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details for the final result set.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n -- Final ordering is preserved because the input `t` is already sorted.\n ORDER BY t.effective_ts DESC, t.updated_at DESC -- fall back to updated_at if effective_ts is the same\n ",
"describe": {
"columns": [
{
@@ -87,6 +87,11 @@
"ordinal": 16,
"name": "owner_id!",
"type_info": "Text"
+ },
+ {
+ "ordinal": 17,
+ "name": "link_id!",
+ "type_info": "Uuid"
}
],
"parameters": {
@@ -115,8 +120,9 @@
false,
null,
true,
+ false,
false
]
},
- "hash": "26dea63de88041b56c6a105b66cb71cb35883ece0f9928887b7ed5d628fe6696"
+ "hash": "523326bd4435e4f15ca5e0cc7f015e99eac0492d7e855375a0389e246c400049"
}
diff --git a/rust/cloud-storage/.sqlx/query-45930469737986c5b9c3055100e9bc14644eb671d892b299e93fef31f0df9d9e.json b/rust/cloud-storage/.sqlx/query-5fc28ed3d53550bec9f1d5fdd1c330f4678e3d3d44f1369bdd0b31f21600fdb1.json
similarity index 52%
rename from rust/cloud-storage/.sqlx/query-45930469737986c5b9c3055100e9bc14644eb671d892b299e93fef31f0df9d9e.json
rename to rust/cloud-storage/.sqlx/query-5fc28ed3d53550bec9f1d5fdd1c330f4678e3d3d44f1369bdd0b31f21600fdb1.json
index a0b5543e3a..fcde9acfef 100644
--- a/rust/cloud-storage/.sqlx/query-45930469737986c5b9c3055100e9bc14644eb671d892b299e93fef31f0df9d9e.json
+++ b/rust/cloud-storage/.sqlx/query-5fc28ed3d53550bec9f1d5fdd1c330f4678e3d3d44f1369bdd0b31f21600fdb1.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n WITH spam_labels AS (\n SELECT id, link_id FROM email_labels WHERE link_id = ANY($1) AND name = 'SPAM'\n ),\n trash_labels AS (\n SELECT id, link_id FROM email_labels WHERE link_id = ANY($1) AND name = 'TRASH'\n ),\n important_labels AS (\n SELECT id, link_id FROM email_labels WHERE link_id = ANY($1) AND name = 'IMPORTANT'\n )\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_labels ml ON m_imp.id = ml.message_id\n JOIN important_labels il ON ml.label_id = il.id\n WHERE m_imp.thread_id = t.id\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\"\n FROM (\n -- Step 1: Efficiently find, sort, and limit the top N+1 threads.\n -- This subquery only touches `threads` and `user_history`, making it very fast.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n t.latest_non_spam_message_ts AS created_at,\n t.latest_non_spam_message_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)\n ELSE t.latest_non_spam_message_ts\n END AS effective_ts\n FROM email_threads t\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n t.link_id = ANY($1)\n AND t.latest_non_spam_message_ts IS NOT NULL\n\n -- Cursor logic is moved inside for maximum efficiency\n AND (($3::timestamptz IS NULL) OR (\n -- This CASE must exactly match the one that defines `effective_ts`\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)\n ELSE t.latest_non_spam_message_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find its latest non-SPAM/TRASH message.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.is_draft,\n m.from_contact_id,\n m.from_name\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN spam_labels sl ON ml.label_id = sl.id\n WHERE ml.message_id = m.id\n )\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN trash_labels tl ON ml.label_id = tl.id\n WHERE ml.message_id = m.id\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details for the final result set.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
+ "query": "\n WITH spam_labels AS (\n SELECT id, link_id FROM email_labels WHERE link_id = ANY($1) AND name = 'SPAM'\n ),\n trash_labels AS (\n SELECT id, link_id FROM email_labels WHERE link_id = ANY($1) AND name = 'TRASH'\n ),\n important_labels AS (\n SELECT id, link_id FROM email_labels WHERE link_id = ANY($1) AND name = 'IMPORTANT'\n )\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_labels ml ON m_imp.id = ml.message_id\n JOIN important_labels il ON ml.label_id = il.id\n WHERE m_imp.thread_id = t.id\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\",\n el.id AS \"link_id!\"\n FROM (\n -- Step 1: Efficiently find, sort, and limit the top N+1 threads.\n -- This subquery only touches `threads` and `user_history`, making it very fast.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n t.latest_non_spam_message_ts AS created_at,\n t.latest_non_spam_message_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)\n ELSE t.latest_non_spam_message_ts\n END AS effective_ts\n FROM email_threads t\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n t.link_id = ANY($1)\n AND t.latest_non_spam_message_ts IS NOT NULL\n\n -- Cursor logic is moved inside for maximum efficiency\n AND (($3::timestamptz IS NULL) OR (\n -- This CASE must exactly match the one that defines `effective_ts`\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)\n ELSE t.latest_non_spam_message_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find its latest non-SPAM/TRASH message.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.is_draft,\n m.from_contact_id,\n m.from_name\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN spam_labels sl ON ml.label_id = sl.id\n WHERE ml.message_id = m.id\n )\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN trash_labels tl ON ml.label_id = tl.id\n WHERE ml.message_id = m.id\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details for the final result set.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
"describe": {
"columns": [
{
@@ -87,6 +87,11 @@
"ordinal": 16,
"name": "owner_id!",
"type_info": "Text"
+ },
+ {
+ "ordinal": 17,
+ "name": "link_id!",
+ "type_info": "Uuid"
}
],
"parameters": {
@@ -115,8 +120,9 @@
false,
null,
true,
+ false,
false
]
},
- "hash": "45930469737986c5b9c3055100e9bc14644eb671d892b299e93fef31f0df9d9e"
+ "hash": "5fc28ed3d53550bec9f1d5fdd1c330f4678e3d3d44f1369bdd0b31f21600fdb1"
}
diff --git a/rust/cloud-storage/.sqlx/query-60710a9df963aaf5edfef7d459aa8be243aa9c5fb36da66fa6c2faa8395209af.json b/rust/cloud-storage/.sqlx/query-60710a9df963aaf5edfef7d459aa8be243aa9c5fb36da66fa6c2faa8395209af.json
deleted file mode 100644
index 09db373d19..0000000000
--- a/rust/cloud-storage/.sqlx/query-60710a9df963aaf5edfef7d459aa8be243aa9c5fb36da66fa6c2faa8395209af.json
+++ /dev/null
@@ -1,122 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n (\n SELECT EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_labels ml ON m_imp.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m_imp.thread_id = t.id\n AND l.name = 'IMPORTANT'\n AND l.link_id = t.link_id\n )\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\"\n FROM (\n -- Step 1: Find the latest starred timestamp for each thread, calculate the\n -- effective sort key, then sort and limit the results.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n lspt.latest_starred_ts AS created_at,\n lspt.latest_starred_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, lspt.latest_starred_ts)\n ELSE lspt.latest_starred_ts\n END AS effective_ts\n FROM (\n -- This sub-subquery efficiently finds the latest starred timestamp for every thread.\n SELECT m.thread_id, MAX(m.internal_date_ts) as latest_starred_ts\n FROM email_messages m\n WHERE m.link_id = ANY($1) AND m.is_starred = TRUE\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = m.link_id\n )\n GROUP BY m.thread_id\n ) lspt\n JOIN email_threads t ON lspt.thread_id = t.id\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n (($3::timestamptz IS NULL) OR (\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, lspt.latest_starred_ts)\n ELSE lspt.latest_starred_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find the full details of its latest starred message.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND m.is_starred = TRUE\n AND m.is_draft = FALSE\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = t.link_id\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "provider_id",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "inbox_visible",
- "type_info": "Bool"
- },
- {
- "ordinal": 3,
- "name": "is_read",
- "type_info": "Bool"
- },
- {
- "ordinal": 4,
- "name": "sort_ts!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 5,
- "name": "created_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 6,
- "name": "updated_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 7,
- "name": "project_id",
- "type_info": "Text"
- },
- {
- "ordinal": 8,
- "name": "viewed_at?",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 9,
- "name": "name?",
- "type_info": "Text"
- },
- {
- "ordinal": 10,
- "name": "snippet?",
- "type_info": "Text"
- },
- {
- "ordinal": 11,
- "name": "is_draft",
- "type_info": "Bool"
- },
- {
- "ordinal": 12,
- "name": "is_important!",
- "type_info": "Bool"
- },
- {
- "ordinal": 13,
- "name": "sender_email?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 14,
- "name": "sender_name?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 15,
- "name": "sender_photo_url?",
- "type_info": "Text"
- },
- {
- "ordinal": 16,
- "name": "owner_id!",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "UuidArray",
- "Int8",
- "Timestamptz",
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- false,
- true,
- false,
- false,
- null,
- null,
- null,
- true,
- false,
- true,
- true,
- false,
- null,
- false,
- null,
- true,
- false
- ]
- },
- "hash": "60710a9df963aaf5edfef7d459aa8be243aa9c5fb36da66fa6c2faa8395209af"
-}
diff --git a/rust/cloud-storage/.sqlx/query-6e259a736102ed24f06b6f91f7b4a1b47adc45114d3232411f7c391cb88c27b5.json b/rust/cloud-storage/.sqlx/query-6e259a736102ed24f06b6f91f7b4a1b47adc45114d3232411f7c391cb88c27b5.json
deleted file mode 100644
index ec341fdbee..0000000000
--- a/rust/cloud-storage/.sqlx/query-6e259a736102ed24f06b6f91f7b4a1b47adc45114d3232411f7c391cb88c27b5.json
+++ /dev/null
@@ -1,123 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n (\n SELECT EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_labels ml ON m_imp.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m_imp.thread_id = t.id\n AND l.link_id = t.link_id\n AND l.name = 'IMPORTANT'\n )\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\"\n FROM (\n -- Step 1: Find the latest labeled message timestamp for each thread,\n -- calculate the effective sort key, then sort and limit the results.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n llpt.latest_labeled_ts AS created_at,\n llpt.latest_labeled_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $6 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, llpt.latest_labeled_ts)\n ELSE llpt.latest_labeled_ts\n END AS effective_ts\n FROM (\n -- This sub-subquery efficiently finds the latest timestamp for every thread\n -- that has at least one message with the specified label.\n SELECT\n m.thread_id,\n MAX(m.internal_date_ts) as latest_labeled_ts\n FROM email_messages m\n JOIN email_message_labels ml ON m.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m.link_id = ANY($1) AND l.name = $5\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml2\n JOIN email_labels l2 ON ml2.label_id = l2.id\n WHERE ml2.message_id = m.id AND l2.name = 'TRASH' AND l2.link_id = m.link_id\n )\n GROUP BY m.thread_id\n ) llpt\n JOIN email_threads t ON llpt.thread_id = t.id\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n (($3::timestamptz IS NULL) OR (\n CASE $6 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, llpt.latest_labeled_ts)\n ELSE llpt.latest_labeled_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find the full details of its latest message with that specific label.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n JOIN email_message_labels ml ON m.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m.thread_id = t.id AND m.is_draft = FALSE AND l.link_id = t.link_id AND l.name = $5\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml2\n JOIN email_labels l2 ON ml2.label_id = l2.id\n WHERE ml2.message_id = m.id AND l2.name = 'TRASH' AND l2.link_id = t.link_id\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "provider_id",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "inbox_visible",
- "type_info": "Bool"
- },
- {
- "ordinal": 3,
- "name": "is_read",
- "type_info": "Bool"
- },
- {
- "ordinal": 4,
- "name": "sort_ts!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 5,
- "name": "created_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 6,
- "name": "updated_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 7,
- "name": "project_id",
- "type_info": "Text"
- },
- {
- "ordinal": 8,
- "name": "viewed_at?",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 9,
- "name": "name?",
- "type_info": "Text"
- },
- {
- "ordinal": 10,
- "name": "snippet?",
- "type_info": "Text"
- },
- {
- "ordinal": 11,
- "name": "is_draft",
- "type_info": "Bool"
- },
- {
- "ordinal": 12,
- "name": "is_important!",
- "type_info": "Bool"
- },
- {
- "ordinal": 13,
- "name": "sender_email?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 14,
- "name": "sender_name?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 15,
- "name": "sender_photo_url?",
- "type_info": "Text"
- },
- {
- "ordinal": 16,
- "name": "owner_id!",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "UuidArray",
- "Int8",
- "Timestamptz",
- "Uuid",
- "Text",
- "Text"
- ]
- },
- "nullable": [
- false,
- true,
- false,
- false,
- null,
- null,
- null,
- true,
- false,
- true,
- true,
- false,
- null,
- false,
- null,
- true,
- false
- ]
- },
- "hash": "6e259a736102ed24f06b6f91f7b4a1b47adc45114d3232411f7c391cb88c27b5"
-}
diff --git a/rust/cloud-storage/.sqlx/query-836ce70023dde942fb6c49c76901919d486794aef06d9296b91c7f13ad846d1c.json b/rust/cloud-storage/.sqlx/query-836ce70023dde942fb6c49c76901919d486794aef06d9296b91c7f13ad846d1c.json
new file mode 100644
index 0000000000..4cb45741c1
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-836ce70023dde942fb6c49c76901919d486794aef06d9296b91c7f13ad846d1c.json
@@ -0,0 +1,128 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n (\n SELECT EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_labels ml ON m_imp.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m_imp.thread_id = t.id\n AND l.name = 'IMPORTANT'\n AND l.link_id = t.link_id\n )\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\",\n el.id AS \"link_id!\"\n FROM (\n -- Step 1: Find the latest starred timestamp for each thread, calculate the\n -- effective sort key, then sort and limit the results.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n lspt.latest_starred_ts AS created_at,\n lspt.latest_starred_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, lspt.latest_starred_ts)\n ELSE lspt.latest_starred_ts\n END AS effective_ts\n FROM (\n -- This sub-subquery efficiently finds the latest starred timestamp for every thread.\n SELECT m.thread_id, MAX(m.internal_date_ts) as latest_starred_ts\n FROM email_messages m\n WHERE m.link_id = ANY($1) AND m.is_starred = TRUE\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = m.link_id\n )\n GROUP BY m.thread_id\n ) lspt\n JOIN email_threads t ON lspt.thread_id = t.id\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n (($3::timestamptz IS NULL) OR (\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, lspt.latest_starred_ts)\n ELSE lspt.latest_starred_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find the full details of its latest starred message.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND m.is_starred = TRUE\n AND m.is_draft = FALSE\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = t.link_id\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "provider_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "inbox_visible",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 3,
+ "name": "is_read",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 4,
+ "name": "sort_ts!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "updated_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "project_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "viewed_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "name?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "snippet?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 11,
+ "name": "is_draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 12,
+ "name": "is_important!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 13,
+ "name": "sender_email?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 14,
+ "name": "sender_name?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 15,
+ "name": "sender_photo_url?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 16,
+ "name": "owner_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 17,
+ "name": "link_id!",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "Int8",
+ "Timestamptz",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ false,
+ null,
+ null,
+ null,
+ true,
+ false,
+ true,
+ true,
+ false,
+ null,
+ false,
+ null,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "836ce70023dde942fb6c49c76901919d486794aef06d9296b91c7f13ad846d1c"
+}
diff --git a/rust/cloud-storage/.sqlx/query-85d69f162075e61284c5db892a0b771facff06efe446a9b002254447ffcd4a9a.json b/rust/cloud-storage/.sqlx/query-85d69f162075e61284c5db892a0b771facff06efe446a9b002254447ffcd4a9a.json
deleted file mode 100644
index 36db6c1cf4..0000000000
--- a/rust/cloud-storage/.sqlx/query-85d69f162075e61284c5db892a0b771facff06efe446a9b002254447ffcd4a9a.json
+++ /dev/null
@@ -1,122 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n -- A thread in \"Other\" can still be \"Important\", so we must perform the check.\n (\n SELECT EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_labels ml ON m_imp.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m_imp.thread_id = t.id\n AND l.link_id = t.link_id\n AND l.name = 'IMPORTANT'\n )\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\"\n FROM (\n -- Step 1: Efficiently find, sort, and limit the top N+1 threads that qualify for the \"Other\" inbox.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n t.latest_non_spam_message_ts AS created_at,\n t.latest_non_spam_message_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)\n ELSE t.latest_non_spam_message_ts\n END AS effective_ts\n FROM email_threads t\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n t.link_id = ANY($1)\n AND t.latest_non_spam_message_ts IS NOT NULL\n -- Inclusion Criteria: Must have a category label.\n AND EXISTS (\n SELECT 1 FROM email_messages m JOIN email_message_labels ml ON m.id = ml.message_id JOIN email_labels l ON ml.label_id = l.id\n WHERE m.thread_id = t.id AND l.link_id = t.link_id AND l.name IN ('CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS')\n )\n -- ****** CORRECTED EXCLUSION CRITERIA ******\n -- This now matches the logic of your original query, which did NOT filter out 'INBOX' or 'IMPORTANT'.\n AND NOT EXISTS (\n SELECT 1 FROM email_messages m JOIN email_message_labels ml ON m.id = ml.message_id JOIN email_labels l ON ml.label_id = l.id\n WHERE m.thread_id = t.id AND l.link_id = t.link_id AND l.name IN ('SPAM', 'TRASH', 'DRAFT')\n )\n \n AND (($3::timestamptz IS NULL) OR (\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)\n ELSE t.latest_non_spam_message_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find its latest non-spam/trash message for the preview.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.is_draft,\n m.from_contact_id,\n m.from_name\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND m.is_draft = FALSE\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.link_id = t.link_id AND l.name IN ('SPAM', 'TRASH')\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "provider_id",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "inbox_visible",
- "type_info": "Bool"
- },
- {
- "ordinal": 3,
- "name": "is_read",
- "type_info": "Bool"
- },
- {
- "ordinal": 4,
- "name": "sort_ts!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 5,
- "name": "created_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 6,
- "name": "updated_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 7,
- "name": "project_id",
- "type_info": "Text"
- },
- {
- "ordinal": 8,
- "name": "viewed_at?",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 9,
- "name": "name?",
- "type_info": "Text"
- },
- {
- "ordinal": 10,
- "name": "snippet?",
- "type_info": "Text"
- },
- {
- "ordinal": 11,
- "name": "is_draft",
- "type_info": "Bool"
- },
- {
- "ordinal": 12,
- "name": "is_important!",
- "type_info": "Bool"
- },
- {
- "ordinal": 13,
- "name": "sender_email?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 14,
- "name": "sender_name?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 15,
- "name": "sender_photo_url?",
- "type_info": "Text"
- },
- {
- "ordinal": 16,
- "name": "owner_id!",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "UuidArray",
- "Int8",
- "Timestamptz",
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- false,
- true,
- false,
- false,
- null,
- true,
- true,
- true,
- false,
- true,
- true,
- false,
- null,
- false,
- null,
- true,
- false
- ]
- },
- "hash": "85d69f162075e61284c5db892a0b771facff06efe446a9b002254447ffcd4a9a"
-}
diff --git a/rust/cloud-storage/.sqlx/query-9a4d3cd17bbfd022b2097a3c661cdf23a4a1c1d900d9a0267b1b38a054c49dc3.json b/rust/cloud-storage/.sqlx/query-9a4d3cd17bbfd022b2097a3c661cdf23a4a1c1d900d9a0267b1b38a054c49dc3.json
new file mode 100644
index 0000000000..9256ea8725
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-9a4d3cd17bbfd022b2097a3c661cdf23a4a1c1d900d9a0267b1b38a054c49dc3.json
@@ -0,0 +1,128 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n -- A thread in \"Other\" can still be \"Important\", so we must perform the check.\n (\n SELECT EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_labels ml ON m_imp.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m_imp.thread_id = t.id\n AND l.link_id = t.link_id\n AND l.name = 'IMPORTANT'\n )\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\",\n el.id AS \"link_id!\"\n FROM (\n -- Step 1: Efficiently find, sort, and limit the top N+1 threads that qualify for the \"Other\" inbox.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n t.latest_non_spam_message_ts AS created_at,\n t.latest_non_spam_message_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)\n ELSE t.latest_non_spam_message_ts\n END AS effective_ts\n FROM email_threads t\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n t.link_id = ANY($1)\n AND t.latest_non_spam_message_ts IS NOT NULL\n -- Inclusion Criteria: Must have a category label.\n AND EXISTS (\n SELECT 1 FROM email_messages m JOIN email_message_labels ml ON m.id = ml.message_id JOIN email_labels l ON ml.label_id = l.id\n WHERE m.thread_id = t.id AND l.link_id = t.link_id AND l.name IN ('CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS')\n )\n -- ****** CORRECTED EXCLUSION CRITERIA ******\n -- This now matches the logic of your original query, which did NOT filter out 'INBOX' or 'IMPORTANT'.\n AND NOT EXISTS (\n SELECT 1 FROM email_messages m JOIN email_message_labels ml ON m.id = ml.message_id JOIN email_labels l ON ml.label_id = l.id\n WHERE m.thread_id = t.id AND l.link_id = t.link_id AND l.name IN ('SPAM', 'TRASH', 'DRAFT')\n )\n \n AND (($3::timestamptz IS NULL) OR (\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)\n ELSE t.latest_non_spam_message_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find its latest non-spam/trash message for the preview.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.is_draft,\n m.from_contact_id,\n m.from_name\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND m.is_draft = FALSE\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.link_id = t.link_id AND l.name IN ('SPAM', 'TRASH')\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "provider_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "inbox_visible",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 3,
+ "name": "is_read",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 4,
+ "name": "sort_ts!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "updated_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "project_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "viewed_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "name?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "snippet?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 11,
+ "name": "is_draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 12,
+ "name": "is_important!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 13,
+ "name": "sender_email?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 14,
+ "name": "sender_name?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 15,
+ "name": "sender_photo_url?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 16,
+ "name": "owner_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 17,
+ "name": "link_id!",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "Int8",
+ "Timestamptz",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ false,
+ null,
+ true,
+ true,
+ true,
+ false,
+ true,
+ true,
+ false,
+ null,
+ false,
+ null,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "9a4d3cd17bbfd022b2097a3c661cdf23a4a1c1d900d9a0267b1b38a054c49dc3"
+}
diff --git a/rust/cloud-storage/.sqlx/query-a41adc6c58c65f57c24024944c53511df82109d39b5a8aee46bc8759eb07d2a2.json b/rust/cloud-storage/.sqlx/query-a41adc6c58c65f57c24024944c53511df82109d39b5a8aee46bc8759eb07d2a2.json
deleted file mode 100644
index 8b908e8cfc..0000000000
--- a/rust/cloud-storage/.sqlx/query-a41adc6c58c65f57c24024944c53511df82109d39b5a8aee46bc8759eb07d2a2.json
+++ /dev/null
@@ -1,122 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n (\n SELECT EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_labels ml ON m_imp.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m_imp.thread_id = t.id\n AND l.name = 'IMPORTANT'\n AND l.link_id = t.link_id\n )\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\"\n FROM (\n -- Step 1: Find the latest draft timestamp for each thread, calculate the\n -- effective sort key, then sort and limit the results. This is the core optimization.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n ldpt.latest_draft_ts AS created_at,\n ldpt.latest_draft_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, ldpt.latest_draft_ts)\n ELSE ldpt.latest_draft_ts\n END AS effective_ts\n FROM (\n -- This sub-subquery efficiently finds the latest draft timestamp for every thread.\n SELECT m.thread_id, MAX(m.updated_at) as latest_draft_ts\n FROM email_messages m\n -- we only display macro drafts, not drafts created in gmail\n WHERE m.link_id = ANY($1) AND m.is_draft = TRUE AND m.internal_date_ts IS NULL\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = m.link_id\n )\n GROUP BY m.thread_id\n ) ldpt\n JOIN email_threads t ON ldpt.thread_id = t.id\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n (($3::timestamptz IS NULL) OR (\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, ldpt.latest_draft_ts)\n ELSE ldpt.latest_draft_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find the full details of its latest draft.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND m.is_draft = TRUE\n -- we only display macro drafts, not drafts created in gmail\n AND m.internal_date_ts IS NULL\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = t.link_id\n )\n ORDER BY m.updated_at DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "provider_id",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "inbox_visible",
- "type_info": "Bool"
- },
- {
- "ordinal": 3,
- "name": "is_read",
- "type_info": "Bool"
- },
- {
- "ordinal": 4,
- "name": "sort_ts!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 5,
- "name": "created_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 6,
- "name": "updated_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 7,
- "name": "project_id",
- "type_info": "Text"
- },
- {
- "ordinal": 8,
- "name": "viewed_at?",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 9,
- "name": "name?",
- "type_info": "Text"
- },
- {
- "ordinal": 10,
- "name": "snippet?",
- "type_info": "Text"
- },
- {
- "ordinal": 11,
- "name": "is_draft",
- "type_info": "Bool"
- },
- {
- "ordinal": 12,
- "name": "is_important!",
- "type_info": "Bool"
- },
- {
- "ordinal": 13,
- "name": "sender_email?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 14,
- "name": "sender_name?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 15,
- "name": "sender_photo_url?",
- "type_info": "Text"
- },
- {
- "ordinal": 16,
- "name": "owner_id!",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "UuidArray",
- "Int8",
- "Timestamptz",
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- false,
- true,
- false,
- false,
- null,
- null,
- null,
- true,
- false,
- true,
- true,
- false,
- null,
- false,
- null,
- true,
- false
- ]
- },
- "hash": "a41adc6c58c65f57c24024944c53511df82109d39b5a8aee46bc8759eb07d2a2"
-}
diff --git a/rust/cloud-storage/.sqlx/query-b39489dade5d8c0fd17bacd9413969f502fe88c58012d041623d1689aa8cbbf1.json b/rust/cloud-storage/.sqlx/query-b39489dade5d8c0fd17bacd9413969f502fe88c58012d041623d1689aa8cbbf1.json
new file mode 100644
index 0000000000..871b5047f5
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-b39489dade5d8c0fd17bacd9413969f502fe88c58012d041623d1689aa8cbbf1.json
@@ -0,0 +1,73 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, macro_id, fusionauth_user_id, email_address, provider as \"provider: _\",\n is_sync_active, created_at, updated_at\n FROM email_links\n WHERE fusionauth_user_id = $1\n ORDER BY 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": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "b39489dade5d8c0fd17bacd9413969f502fe88c58012d041623d1689aa8cbbf1"
+}
diff --git a/rust/cloud-storage/.sqlx/query-b58ccd6afec0fb6636951e7cdb17390b5d1e56dbaa6b8e59bc35e2a2e4937c34.json b/rust/cloud-storage/.sqlx/query-b58ccd6afec0fb6636951e7cdb17390b5d1e56dbaa6b8e59bc35e2a2e4937c34.json
new file mode 100644
index 0000000000..525ad24a53
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-b58ccd6afec0fb6636951e7cdb17390b5d1e56dbaa6b8e59bc35e2a2e4937c34.json
@@ -0,0 +1,128 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n (\n SELECT EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_labels ml ON m_imp.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m_imp.thread_id = t.id\n AND l.name = 'IMPORTANT'\n AND l.link_id = t.link_id\n )\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\",\n el.id AS \"link_id!\"\n FROM (\n -- Step 1: Find the latest draft timestamp for each thread, calculate the\n -- effective sort key, then sort and limit the results. This is the core optimization.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n ldpt.latest_draft_ts AS created_at,\n ldpt.latest_draft_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, ldpt.latest_draft_ts)\n ELSE ldpt.latest_draft_ts\n END AS effective_ts\n FROM (\n -- This sub-subquery efficiently finds the latest draft timestamp for every thread.\n SELECT m.thread_id, MAX(m.updated_at) as latest_draft_ts\n FROM email_messages m\n -- we only display macro drafts, not drafts created in gmail\n WHERE m.link_id = ANY($1) AND m.is_draft = TRUE AND m.internal_date_ts IS NULL\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = m.link_id\n )\n GROUP BY m.thread_id\n ) ldpt\n JOIN email_threads t ON ldpt.thread_id = t.id\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n (($3::timestamptz IS NULL) OR (\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, ldpt.latest_draft_ts)\n ELSE ldpt.latest_draft_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find the full details of its latest draft.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND m.is_draft = TRUE\n -- we only display macro drafts, not drafts created in gmail\n AND m.internal_date_ts IS NULL\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = t.link_id\n )\n ORDER BY m.updated_at DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "provider_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "inbox_visible",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 3,
+ "name": "is_read",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 4,
+ "name": "sort_ts!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "updated_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "project_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "viewed_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "name?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "snippet?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 11,
+ "name": "is_draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 12,
+ "name": "is_important!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 13,
+ "name": "sender_email?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 14,
+ "name": "sender_name?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 15,
+ "name": "sender_photo_url?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 16,
+ "name": "owner_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 17,
+ "name": "link_id!",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "Int8",
+ "Timestamptz",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ false,
+ null,
+ null,
+ null,
+ true,
+ false,
+ true,
+ true,
+ false,
+ null,
+ false,
+ null,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "b58ccd6afec0fb6636951e7cdb17390b5d1e56dbaa6b8e59bc35e2a2e4937c34"
+}
diff --git a/rust/cloud-storage/.sqlx/query-c1c20d7762c16e50a8ec9d7fec86b41cb97712cdfb74480980aa7f138c8ff20e.json b/rust/cloud-storage/.sqlx/query-c1c20d7762c16e50a8ec9d7fec86b41cb97712cdfb74480980aa7f138c8ff20e.json
new file mode 100644
index 0000000000..20f461611a
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-c1c20d7762c16e50a8ec9d7fec86b41cb97712cdfb74480980aa7f138c8ff20e.json
@@ -0,0 +1,74 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT l.id, l.macro_id, l.fusionauth_user_id, l.email_address, l.provider as \"provider: _\",\n l.is_sync_active, l.created_at, l.updated_at\n FROM email_threads t\n JOIN email_links l ON l.id = t.link_id\n WHERE t.id = $1 AND l.fusionauth_user_id = $2\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": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "c1c20d7762c16e50a8ec9d7fec86b41cb97712cdfb74480980aa7f138c8ff20e"
+}
diff --git a/rust/cloud-storage/.sqlx/query-cd1b9c3eb3d9efe710902559ff97a12bd84caee88e8fb5d9f6f8ae2aa4dc06ec.json b/rust/cloud-storage/.sqlx/query-cd1b9c3eb3d9efe710902559ff97a12bd84caee88e8fb5d9f6f8ae2aa4dc06ec.json
new file mode 100644
index 0000000000..160af11a14
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-cd1b9c3eb3d9efe710902559ff97a12bd84caee88e8fb5d9f6f8ae2aa4dc06ec.json
@@ -0,0 +1,74 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT l.id, l.macro_id, l.fusionauth_user_id, l.email_address, l.provider as \"provider: _\",\n l.is_sync_active, l.created_at, l.updated_at\n FROM email_messages m\n JOIN email_links l ON l.id = m.link_id\n WHERE m.id = $1 AND l.fusionauth_user_id = $2\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": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "cd1b9c3eb3d9efe710902559ff97a12bd84caee88e8fb5d9f6f8ae2aa4dc06ec"
+}
diff --git a/rust/cloud-storage/.sqlx/query-d742a92f0fe0ee9d7804e59bf37182fb33d0dcc2df012cdc4eed91e8994ca2b7.json b/rust/cloud-storage/.sqlx/query-d742a92f0fe0ee9d7804e59bf37182fb33d0dcc2df012cdc4eed91e8994ca2b7.json
new file mode 100644
index 0000000000..773603fabb
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-d742a92f0fe0ee9d7804e59bf37182fb33d0dcc2df012cdc4eed91e8994ca2b7.json
@@ -0,0 +1,129 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n (\n SELECT EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_labels ml ON m_imp.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m_imp.thread_id = t.id\n AND l.link_id = t.link_id\n AND l.name = 'IMPORTANT'\n )\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\",\n el.id AS \"link_id!\"\n FROM (\n -- Step 1: Find the latest labeled message timestamp for each thread,\n -- calculate the effective sort key, then sort and limit the results.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n llpt.latest_labeled_ts AS created_at,\n llpt.latest_labeled_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $6 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, llpt.latest_labeled_ts)\n ELSE llpt.latest_labeled_ts\n END AS effective_ts\n FROM (\n -- This sub-subquery efficiently finds the latest timestamp for every thread\n -- that has at least one message with the specified label.\n SELECT\n m.thread_id,\n MAX(m.internal_date_ts) as latest_labeled_ts\n FROM email_messages m\n JOIN email_message_labels ml ON m.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m.link_id = ANY($1) AND l.name = $5\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml2\n JOIN email_labels l2 ON ml2.label_id = l2.id\n WHERE ml2.message_id = m.id AND l2.name = 'TRASH' AND l2.link_id = m.link_id\n )\n GROUP BY m.thread_id\n ) llpt\n JOIN email_threads t ON llpt.thread_id = t.id\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n (($3::timestamptz IS NULL) OR (\n CASE $6 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, llpt.latest_labeled_ts)\n ELSE llpt.latest_labeled_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find the full details of its latest message with that specific label.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n JOIN email_message_labels ml ON m.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m.thread_id = t.id AND m.is_draft = FALSE AND l.link_id = t.link_id AND l.name = $5\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml2\n JOIN email_labels l2 ON ml2.label_id = l2.id\n WHERE ml2.message_id = m.id AND l2.name = 'TRASH' AND l2.link_id = t.link_id\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "provider_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "inbox_visible",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 3,
+ "name": "is_read",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 4,
+ "name": "sort_ts!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "updated_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "project_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "viewed_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "name?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "snippet?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 11,
+ "name": "is_draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 12,
+ "name": "is_important!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 13,
+ "name": "sender_email?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 14,
+ "name": "sender_name?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 15,
+ "name": "sender_photo_url?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 16,
+ "name": "owner_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 17,
+ "name": "link_id!",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "Int8",
+ "Timestamptz",
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ false,
+ null,
+ null,
+ null,
+ true,
+ false,
+ true,
+ true,
+ false,
+ null,
+ false,
+ null,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "d742a92f0fe0ee9d7804e59bf37182fb33d0dcc2df012cdc4eed91e8994ca2b7"
+}
diff --git a/rust/cloud-storage/.sqlx/query-e802b95145183d9bec6fb5f542fe93d392fdcf0fbebc9935f263f3f4fd1d8c34.json b/rust/cloud-storage/.sqlx/query-e802b95145183d9bec6fb5f542fe93d392fdcf0fbebc9935f263f3f4fd1d8c34.json
new file mode 100644
index 0000000000..e30af0774f
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-e802b95145183d9bec6fb5f542fe93d392fdcf0fbebc9935f263f3f4fd1d8c34.json
@@ -0,0 +1,128 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n (\n SELECT EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_labels ml ON m_imp.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m_imp.thread_id = t.id\n AND l.name = 'IMPORTANT'\n AND l.link_id = t.link_id\n )\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\",\n el.id AS \"link_id!\"\n FROM (\n -- Step 1: Efficiently find and sort ONLY the top N+1 candidate threads.\n -- This subquery only touches `threads` and `user_history`.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n t.latest_outbound_message_ts AS created_at,\n t.latest_outbound_message_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_outbound_message_ts)\n ELSE t.latest_outbound_message_ts\n END AS effective_ts\n FROM email_threads t\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n t.link_id = ANY($1)\n AND t.latest_outbound_message_ts IS NOT NULL\n \n -- Cursor logic moved inside for maximum efficiency\n AND (($3::timestamptz IS NULL) OR (\n -- This CASE must exactly match the one that defines `effective_ts`\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_outbound_message_ts)\n ELSE t.latest_outbound_message_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find its latest SENT, non-trashed message.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND m.is_sent = TRUE -- This condition is specific to the \"Sent\" view\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = t.link_id\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details for the final result set.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n -- Final ordering is preserved because the input `t` is already sorted.\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "provider_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "inbox_visible",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 3,
+ "name": "is_read",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 4,
+ "name": "sort_ts!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "updated_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "project_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "viewed_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "name?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "snippet?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 11,
+ "name": "is_draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 12,
+ "name": "is_important!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 13,
+ "name": "sender_email?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 14,
+ "name": "sender_name?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 15,
+ "name": "sender_photo_url?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 16,
+ "name": "owner_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 17,
+ "name": "link_id!",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "Int8",
+ "Timestamptz",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ false,
+ null,
+ true,
+ true,
+ true,
+ false,
+ true,
+ true,
+ false,
+ null,
+ false,
+ null,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "e802b95145183d9bec6fb5f542fe93d392fdcf0fbebc9935f263f3f4fd1d8c34"
+}
diff --git a/rust/cloud-storage/email/src/domain/models/preview.rs b/rust/cloud-storage/email/src/domain/models/preview.rs
index 5b55695aeb..e4fd65ac8d 100644
--- a/rust/cloud-storage/email/src/domain/models/preview.rs
+++ b/rust/cloud-storage/email/src/domain/models/preview.rs
@@ -93,6 +93,7 @@ pub struct EmailThreadPreview {
pub updated_at: DateTime<Utc>,
pub viewed_at: Option<DateTime<Utc>>,
pub project_id: Option<String>,
+ pub link_id: Uuid,
}
#[non_exhaustive]
diff --git a/rust/cloud-storage/email/src/domain/ports.rs b/rust/cloud-storage/email/src/domain/ports.rs
index 6fa762cfac..e8418d4afc 100644
--- a/rust/cloud-storage/email/src/domain/ports.rs
+++ b/rust/cloud-storage/email/src/domain/ports.rs
@@ -74,6 +74,21 @@ pub trait EmailRepo: Send + Sync + 'static {
macro_id: MacroUserIdStr<'_>,
) -> impl Future<Output = Result<Option<Link>, Self::Err>> + Send;
+ /// Returns every email_link owned by the given fusionauth user, one row per
+ /// linked inbox, ordered newest first.
+ fn links_by_fusionauth_user_id(
+ &self,
+ fusionauth_user_id: &str,
+ ) -> impl Future<Output = Result<Vec<Link>, Self::Err>> + Send;
+
+ /// Resolve the inbox owning a thread, only when that inbox belongs to the
+ /// given fusionauth user.
+ fn owned_link_for_thread(
+ &self,
+ thread_id: Uuid,
+ fusionauth_user_id: &str,
+ ) -> impl Future<Output = Result<Option<Link>, Self::Err>> + Send;
+
/// Returns every inbox accessible to `macro_id`: their own email_links plus
/// any reachable via a `macro_user_links` edge (narrow-graph multi-inbox).
fn inboxes_for_macro_id(
@@ -329,6 +344,24 @@ pub trait EmailService: Send + Sync + 'static {
macro_id: MacroUserIdStr<'_>,
) -> impl Future<Output = Result<Vec<Link>, EmailErr>> + Send;
+ /// Fetch every inbox owned by the caller, keyed on their fusionauth user id
+ /// (one row per linked inbox). The read-side multi-inbox union resolves over
+ /// these; the single-inbox mutating extractor selects one by header or by
+ /// primary-email match.
+ fn get_links_by_fusionauth_user_id(
+ &self,
+ auth_id: &str,
+ ) -> impl Future<Output = Result<Vec<Link>, EmailErr>> + Send;
+
+ /// Resolve the inbox owning a thread, scoped to the caller's own inboxes.
+ /// Lets thread-targeted mutations derive the inbox from the thread instead
+ /// of an `X-Email-Link-Id` header.
+ fn get_owned_link_for_thread(
+ &self,
+ auth_id: &str,
+ thread_id: Uuid,
+ ) -> impl Future<Output = Result<Option<Link>, EmailErr>> + Send;
+
/// Fetch a thread with paginated messages, verifying access via the provided receipt.
fn get_thread_with_messages(
&self,
diff --git a/rust/cloud-storage/email/src/domain/service/mod.rs b/rust/cloud-storage/email/src/domain/service/mod.rs
index fd1f6a6b34..5f3f2f5d58 100644
--- a/rust/cloud-storage/email/src/domain/service/mod.rs
+++ b/rust/cloud-storage/email/src/domain/service/mod.rs
@@ -159,6 +159,27 @@ where
.map_err(|e| EmailErr::RepoErr(e.into()))
}
+ async fn get_links_by_fusionauth_user_id(
+ &self,
+ auth_id: &str,
+ ) -> Result<Vec<crate::domain::models::Link>, EmailErr> {
+ self.email_repo
+ .links_by_fusionauth_user_id(auth_id)
+ .await
+ .map_err(|e| EmailErr::RepoErr(e.into()))
+ }
+
+ async fn get_owned_link_for_thread(
+ &self,
+ auth_id: &str,
+ thread_id: uuid::Uuid,
+ ) -> Result<Option<crate::domain::models::Link>, EmailErr> {
+ self.email_repo
+ .owned_link_for_thread(thread_id, auth_id)
+ .await
+ .map_err(|e| EmailErr::RepoErr(e.into()))
+ }
+
async fn get_thread_with_messages(
&self,
receipt: EntityAccessReceipt<ViewAccessLevel>,
diff --git a/rust/cloud-storage/email/src/inbound/axum.rs b/rust/cloud-storage/email/src/inbound/axum.rs
index 44b9200526..790b5fae35 100644
--- a/rust/cloud-storage/email/src/inbound/axum.rs
+++ b/rust/cloud-storage/email/src/inbound/axum.rs
@@ -19,5 +19,6 @@ pub use api_types::{
};
pub use axum_impls::{
EmailLinkErr, EmailLinkExtractor, GetPreviewsCursorError, GetPreviewsCursorParams,
- GmailAccessTokenErr, GmailAccessTokenExtractor, GmailTokenState, OptionalEmailLinkExtractor,
+ GmailAccessTokenErr, GmailAccessTokenExtractor, GmailTokenState, MultiEmailLinkExtractor,
+ OptionalEmailLinkExtractor,
};
diff --git a/rust/cloud-storage/email/src/inbound/axum/api_types/preview.rs b/rust/cloud-storage/email/src/inbound/axum/api_types/preview.rs
index 45ea4f79c8..7fae9be291 100644
--- a/rust/cloud-storage/email/src/inbound/axum/api_types/preview.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/api_types/preview.rs
@@ -56,6 +56,7 @@ pub struct ApiThreadPreviewCursorInner {
created_at: DateTime<Utc>,
updated_at: DateTime<Utc>,
viewed_at: Option<DateTime<Utc>>,
+ link_id: Uuid,
}
#[derive(Debug, ToSchema, Serialize, Deserialize, Doppleganger)]
diff --git a/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs b/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs
index 1c6606fa65..76ae4e0d8c 100644
--- a/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs
@@ -17,6 +17,14 @@ use std::sync::Arc;
use std::{marker::PhantomData, str::FromStr};
use thiserror::Error;
use utoipa::{IntoParams, ToSchema};
+use uuid::Uuid;
+
+/// Request header that selects which inbox a single-inbox (mutating) request
+/// targets. When absent, the caller's primary inbox is used.
+pub const EMAIL_LINK_ID_HEADER: &str = "x-email-link-id";
+
+#[cfg(test)]
+mod test;
#[derive(Debug, Error)]
pub enum GetPreviewsCursorError {
@@ -82,6 +90,10 @@ pub enum EmailLinkErr {
DbErr(#[from] crate::domain::models::EmailErr),
#[error("Email link not found")]
NotFound,
+ #[error("Invalid X-Email-Link-Id header")]
+ InvalidLinkIdHeader,
+ #[error("No inbox specified; provide the X-Email-Link-Id header")]
+ NoInboxSelected,
#[error(transparent)]
UserErr(#[from] UserExtractorErr),
}
@@ -94,12 +106,57 @@ impl IntoResponse for EmailLinkErr {
let status = match &self {
EmailLinkErr::DbErr(_) | EmailLinkErr::UserErr(_) => StatusCode::INTERNAL_SERVER_ERROR,
EmailLinkErr::NotFound => StatusCode::NOT_FOUND,
+ EmailLinkErr::InvalidLinkIdHeader | EmailLinkErr::NoInboxSelected => {
+ StatusCode::BAD_REQUEST
+ }
};
(status, self.to_string()).into_response()
}
}
+/// Resolve the single inbox a mutating request targets from the caller's owned
+/// `links`. With an `X-Email-Link-Id` value, the matching owned link is used
+/// (404 when it isn't one of theirs). Without a header, the primary inbox is
+/// used — the link whose address matches the caller's account email,
+/// case-insensitively, mirroring the client's primary-inbox rule. A caller with
+/// no primary inbox (e.g. it was removed) must name an inbox explicitly.
+fn resolve_target_link(
+ links: Vec<Link>,
+ header_link_id: Option<Uuid>,
+ account_email: &str,
+) -> Result<Link, EmailLinkErr> {
+ match header_link_id {
+ Some(id) => links
+ .into_iter()
+ .find(|link| link.id == id)
+ .ok_or(EmailLinkErr::NotFound),
+ None => links
+ .into_iter()
+ .find(|link| {
+ link.email_address
+ .0
+ .as_ref()
+ .eq_ignore_ascii_case(account_email)
+ })
+ .ok_or(EmailLinkErr::NoInboxSelected),
+ }
+}
+
+/// Parse the `X-Email-Link-Id` header into a link id, if present. A malformed
+/// value is a client error.
+fn parse_link_id_header(parts: &Parts) -> Result<Option<Uuid>, EmailLinkErr> {
+ let Some(value) = parts.headers.get(EMAIL_LINK_ID_HEADER) else {
+ return Ok(None);
+ };
+ let raw = value
+ .to_str()
+ .map_err(|_| EmailLinkErr::InvalidLinkIdHeader)?;
+ Uuid::parse_str(raw.trim())
+ .map(Some)
+ .map_err(|_| EmailLinkErr::InvalidLinkIdHeader)
+}
+
impl<S, U> FromRequestParts<S> for EmailLinkExtractor<U>
where
EmailRouterState<U>: FromRef<S>,
@@ -109,17 +166,49 @@ where
type Rejection = EmailLinkErr;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ let header_link_id = parse_link_id_header(parts)?;
let Cached(MacroUserExtractor {
macro_user_id,
user_context,
..
}) = parts.extract_with_state(state).await?;
- let res = <EmailRouterState<U>>::from_ref(state)
+ let links = <EmailRouterState<U>>::from_ref(state)
.inner
- .get_link_by_auth_id_and_macro_id(&user_context.fusion_user_id, macro_user_id)
- .await?
- .ok_or(EmailLinkErr::NotFound)?;
- Ok(Self(res, PhantomData))
+ .get_links_by_fusionauth_user_id(&user_context.fusion_user_id)
+ .await?;
+ let link = resolve_target_link(links, header_link_id, macro_user_id.0.email_str())?;
+ Ok(Self(link, PhantomData))
+ }
+}
+
+/// Extractor that resolves *every* inbox the caller owns, for the multi-inbox
+/// read union. Read endpoints fan out over all returned links. A caller with no
+/// linked inboxes yields an empty `Vec` (and hence empty results) rather than a
+/// 404 — the union over zero inboxes is empty, not missing.
+pub struct MultiEmailLinkExtractor<U>(pub Vec<Link>, pub PhantomData<U>);
+
+impl<U> Clone for MultiEmailLinkExtractor<U> {
+ fn clone(&self) -> Self {
+ Self(self.0.clone(), PhantomData)
+ }
+}
+
+impl<S, U> FromRequestParts<S> for MultiEmailLinkExtractor<U>
+where
+ EmailRouterState<U>: FromRef<S>,
+ U: EmailService,
+ S: Send + Sync + 'static,
+{
+ type Rejection = EmailLinkErr;
+
+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ let Cached(MacroUserExtractor { user_context, .. }) =
+ parts.extract_with_state(state).await?;
+ let links = <EmailRouterState<U>>::from_ref(state)
+ .inner
+ .get_links_by_fusionauth_user_id(&user_context.fusion_user_id)
+ .await?;
+ Ok(Self(links, PhantomData))
}
}
diff --git a/rust/cloud-storage/email/src/inbound/axum/axum_impls/test.rs b/rust/cloud-storage/email/src/inbound/axum/axum_impls/test.rs
new file mode 100644
index 0000000000..1897421971
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound/axum/axum_impls/test.rs
@@ -0,0 +1,69 @@
+use super::{EmailLinkErr, resolve_target_link};
+use crate::domain::models::{Link, UserProvider};
+use chrono::Utc;
+use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};
+use uuid::Uuid;
+
+fn test_link(id: Uuid, email: &str) -> Link {
+ Link {
+ id,
+ macro_id: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ fusionauth_user_id: "fa-user".to_string(),
+ email_address: EmailStr::try_from(email.to_string()).unwrap(),
+ provider: UserProvider::Gmail,
+ is_sync_active: true,
+ created_at: Utc::now(),
+ updated_at: Utc::now(),
+ }
+}
+
+#[test]
+fn header_selects_owned_link() {
+ let id1 = Uuid::from_u128(1);
+ let id2 = Uuid::from_u128(2);
+ let links = vec![
+ test_link(id1, "[email protected]"),
+ test_link(id2, "[email protected]"),
+ ];
+ let resolved = resolve_target_link(links, Some(id2), "[email protected]").unwrap();
+ assert_eq!(resolved.id, id2);
+}
+
+#[test]
+fn header_for_unowned_link_is_not_found() {
+ let links = vec![test_link(Uuid::from_u128(1), "[email protected]")];
+ let result = resolve_target_link(links, Some(Uuid::from_u128(99)), "[email protected]");
+ assert!(matches!(result, Err(EmailLinkErr::NotFound)));
+}
+
+#[test]
+fn no_header_falls_back_to_primary_email_match() {
+ let primary = Uuid::from_u128(1);
+ let links = vec![
+ test_link(Uuid::from_u128(2), "[email protected]"),
+ test_link(primary, "[email protected]"),
+ ];
+ let resolved = resolve_target_link(links, None, "[email protected]").unwrap();
+ assert_eq!(resolved.id, primary);
+}
+
+#[test]
+fn primary_match_is_case_insensitive() {
+ let primary = Uuid::from_u128(1);
+ let links = vec![test_link(primary, "[email protected]")];
+ let resolved = resolve_target_link(links, None, "[email protected]").unwrap();
+ assert_eq!(resolved.id, primary);
+}
+
+#[test]
+fn no_header_and_no_primary_is_rejected() {
+ let links = vec![test_link(Uuid::from_u128(2), "[email protected]")];
+ let result = resolve_target_link(links, None, "[email protected]");
+ assert!(matches!(result, Err(EmailLinkErr::NoInboxSelected)));
+}
+
+#[test]
+fn no_links_at_all_is_rejected() {
+ let result = resolve_target_link(vec![], None, "[email protected]");
+ assert!(matches!(result, Err(EmailLinkErr::NoInboxSelected)));
+}
diff --git a/rust/cloud-storage/email/src/inbound/axum/list_labels_router.rs b/rust/cloud-storage/email/src/inbound/axum/list_labels_router.rs
index 50a793849e..bec619d617 100644
--- a/rust/cloud-storage/email/src/inbound/axum/list_labels_router.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/list_labels_router.rs
@@ -6,7 +6,7 @@ use thiserror::Error;
use crate::domain::{models::EmailErr, ports::EmailService};
use super::{
- api_types::ApiLabel, axum_impls::EmailLinkExtractor, previews_router::EmailRouterState,
+ api_types::ApiLabel, axum_impls::MultiEmailLinkExtractor, previews_router::EmailRouterState,
};
/// Response body for listing labels.
@@ -68,9 +68,12 @@ where
#[tracing::instrument(err, skip_all)]
pub async fn list_labels_handler<T: EmailService>(
State(state): State<EmailRouterState<T>>,
- Cached(EmailLinkExtractor(link, _)): Cached<EmailLinkExtractor<T>>,
+ Cached(MultiEmailLinkExtractor(links, _)): Cached<MultiEmailLinkExtractor<T>>,
) -> Result<Json<ListLabelsResponse>, ListLabelsError> {
- let labels = state.inner.list_labels(&link).await?;
+ let mut labels = Vec::new();
+ for link in &links {
+ labels.extend(state.inner.list_labels(link).await?);
+ }
Ok(Json(ListLabelsResponse {
labels: labels.into_iter().map(Into::into).collect(),
}))
diff --git a/rust/cloud-storage/email/src/inbound/axum/previews_router.rs b/rust/cloud-storage/email/src/inbound/axum/previews_router.rs
index 9a6154a1ae..7c6a1dd759 100644
--- a/rust/cloud-storage/email/src/inbound/axum/previews_router.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/previews_router.rs
@@ -17,7 +17,7 @@ use crate::{
inbound::axum::{
api_types::ApiPaginatedThreadCursor,
axum_impls::{
- EmailLinkExtractor, GetPreviewsCursorError, GetPreviewsCursorParams,
+ GetPreviewsCursorError, GetPreviewsCursorParams, MultiEmailLinkExtractor,
PreviewViewPathExtractor,
},
},
@@ -79,11 +79,11 @@ where
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(link, macro_user, service), fields(user_id=macro_user.macro_user_id.as_ref(), fusionauth_user_id=macro_user.user_context.fusion_user_id))]
+#[tracing::instrument(skip(links, macro_user, service), fields(user_id=macro_user.macro_user_id.as_ref(), fusionauth_user_id=macro_user.user_context.fusion_user_id))]
async fn cursor_handler<T: EmailService>(
State(service): State<EmailRouterState<T>>,
Cached(macro_user): Cached<MacroUserExtractor>,
- Cached(EmailLinkExtractor(link, _)): Cached<EmailLinkExtractor<T>>,
+ Cached(MultiEmailLinkExtractor(links, _)): Cached<MultiEmailLinkExtractor<T>>,
PreviewViewPathExtractor(preview_view): PreviewViewPathExtractor,
extract::Query(params): extract::Query<GetPreviewsCursorParams>,
cursor: Option<CursorWithValAndFilter<Uuid, SimpleSortMethod, ()>>,
@@ -93,7 +93,7 @@ async fn cursor_handler<T: EmailService>(
.inner
.get_email_thread_previews(GetEmailsRequest {
view: preview_view,
- link_ids: vec![link.id],
+ link_ids: links.iter().map(|link| link.id).collect(),
macro_id: macro_user.macro_user_id,
limit: params.limit,
query: cursor
diff --git a/rust/cloud-storage/email/src/inbound/axum/thread_labels_router.rs b/rust/cloud-storage/email/src/inbound/axum/thread_labels_router.rs
index 3634de1998..f3f2d3a056 100644
--- a/rust/cloud-storage/email/src/inbound/axum/thread_labels_router.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/thread_labels_router.rs
@@ -5,7 +5,9 @@ use axum::{
response::IntoResponse,
routing::patch,
};
+use axum_extra::extract::Cached;
use model_error_response::ErrorResponse;
+use model_user::axum_extractor::MacroUserExtractor;
use thiserror::Error;
use uuid::Uuid;
@@ -14,10 +16,7 @@ use crate::domain::{
ports::{EmailService, GmailTokenProvider},
};
-use super::{
- axum_impls::{GmailAccessTokenExtractor, GmailTokenState},
- previews_router::EmailRouterState,
-};
+use super::{axum_impls::GmailTokenState, previews_router::EmailRouterState};
/// Request body for updating a thread's labels.
#[derive(serde::Serialize, serde::Deserialize, Debug, utoipa::ToSchema)]
@@ -111,22 +110,27 @@ where
(status = 500, body = ErrorResponse),
)
)]
-#[tracing::instrument(err, skip(state, gmail_extractor, body))]
+#[tracing::instrument(err, skip(state, token_state, macro_user, body))]
pub async fn update_thread_labels_handler<T: EmailService, G: GmailTokenProvider>(
State(state): State<EmailRouterState<T>>,
- gmail_extractor: GmailAccessTokenExtractor<T, G>,
+ State(token_state): State<GmailTokenState<G>>,
+ Cached(macro_user): Cached<MacroUserExtractor>,
Path(thread_id): Path<Uuid>,
Json(body): Json<UpdateThreadLabelRequest>,
) -> Result<Json<UpdateThreadLabelsResponse>, UpdateThreadLabelError> {
+ // Resolve the inbox from the thread (scoped to the caller's own inboxes),
+ // then use that inbox's own Gmail token.
+ let link = state
+ .inner
+ .get_owned_link_for_thread(&macro_user.user_context.fusion_user_id, thread_id)
+ .await?
+ .ok_or_else(|| UpdateThreadLabelError::NotFound("Thread not found".to_string()))?;
+
+ let access_token = token_state.inner.fetch_gmail_access_token(&link).await?;
+
let result = state
.inner
- .update_thread_labels(
- &gmail_extractor.access_token,
- &gmail_extractor.link,
- thread_id,
- body.label_id,
- body.value,
- )
+ .update_thread_labels(&access_token, &link, thread_id, body.label_id, body.value)
.await?;
Ok(Json(UpdateThreadLabelsResponse {
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs
index ac24338c9d..fb0628c6d7 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs
@@ -46,6 +46,8 @@ pub struct ThreadPreviewCursorDbRow {
pub project_id: Option<String>,
/// The macro user ID of the thread owner, resolved from email_links.
pub owner_id: String,
+ /// The id of the email_link (inbox) this thread belongs to.
+ pub link_id: Uuid,
}
#[derive(Debug, sqlx::Type, Clone, Copy, PartialEq, Eq, Doppleganger)]
@@ -115,6 +117,7 @@ impl ThreadPreviewCursorDbRow {
updated_at,
project_id,
owner_id,
+ link_id,
} = self;
EmailThreadPreview {
@@ -137,6 +140,7 @@ impl ThreadPreviewCursorDbRow {
updated_at,
viewed_at,
project_id,
+ link_id,
}
}
}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs
index d0e0351289..14f5bf9dae 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs
@@ -317,7 +317,8 @@ fn build_query(
c.email_address AS sender_email,
c.name AS sender_name,
c.sfs_photo_url as sender_photo_url,
- el.macro_id AS owner_id
+ el.macro_id AS owner_id,
+ el.id AS link_id
FROM (
-- Step 1: Efficiently find and sort candidate threads
SELECT *
@@ -627,6 +628,7 @@ pub(crate) async fn dynamic_email_thread_cursor(
updated_at: row.try_get("updated_at")?,
project_id: row.try_get("project_id")?,
owner_id: row.try_get("owner_id")?,
+ link_id: row.try_get("link_id")?,
})
})
.fetch_all(pool)
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/link.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/link.rs
index b1361969e8..6fb071cf45 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/link.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/link.rs
@@ -1,6 +1,7 @@
use crate::domain::models::{Link, UserProvider};
use macro_user_id::user_id::MacroUserIdStr;
use sqlx::PgPool;
+use uuid::Uuid;
use super::db_types::{DbLink, DbUserProvider};
@@ -70,6 +71,61 @@ pub(super) async fn link_by_fusionauth_email_provider(
.map_err(|e| sqlx::Error::Decode(Box::new(e)))
}
+#[tracing::instrument(err, skip(pool))]
+pub(super) async fn links_by_fusionauth_user_id(
+ pool: &PgPool,
+ fusionauth_user_id: &str,
+) -> Result<Vec<Link>, sqlx::Error> {
+ let db_links: Vec<DbLink> = sqlx::query_as!(
+ DbLink,
+ r#"
+ SELECT id, macro_id, fusionauth_user_id, email_address, provider as "provider: _",
+ is_sync_active, created_at, updated_at
+ FROM email_links
+ WHERE fusionauth_user_id = $1
+ ORDER BY created_at DESC
+ "#,
+ fusionauth_user_id
+ )
+ .fetch_all(pool)
+ .await?;
+
+ db_links
+ .into_iter()
+ .map(|v| {
+ v.try_into_model()
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))
+ })
+ .collect()
+}
+
+#[tracing::instrument(err, skip(pool))]
+pub(super) async fn owned_link_for_thread(
+ pool: &PgPool,
+ thread_id: Uuid,
+ fusionauth_user_id: &str,
+) -> Result<Option<Link>, sqlx::Error> {
+ let db_link: Option<DbLink> = sqlx::query_as!(
+ DbLink,
+ r#"
+ SELECT l.id, l.macro_id, l.fusionauth_user_id, l.email_address, l.provider as "provider: _",
+ l.is_sync_active, l.created_at, l.updated_at
+ FROM email_threads t
+ JOIN email_links l ON l.id = t.link_id
+ WHERE t.id = $1 AND l.fusionauth_user_id = $2
+ "#,
+ thread_id,
+ fusionauth_user_id
+ )
+ .fetch_optional(pool)
+ .await?;
+
+ db_link
+ .map(|v| v.try_into_model())
+ .transpose()
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))
+}
+
#[tracing::instrument(err, skip(pool))]
pub(super) async fn link_by_macro_id(
pool: &PgPool,
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs
index 257217dfb5..71982f8986 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs
@@ -97,6 +97,21 @@ impl EmailRepo for EmailPgRepo {
link::link_by_macro_id(&self.pool, macro_id).await
}
+ async fn links_by_fusionauth_user_id(
+ &self,
+ fusionauth_user_id: &str,
+ ) -> Result<Vec<Link>, Self::Err> {
+ link::links_by_fusionauth_user_id(&self.pool, fusionauth_user_id).await
+ }
+
+ async fn owned_link_for_thread(
+ &self,
+ thread_id: Uuid,
+ fusionauth_user_id: &str,
+ ) -> Result<Option<Link>, Self::Err> {
+ link::owned_link_for_thread(&self.pool, thread_id, fusionauth_user_id).await
+ }
+
async fn inboxes_for_macro_id(
&self,
macro_id: MacroUserIdStr<'_>,
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/all_mail.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/all_mail.rs
index 2c02fdc78a..94e2d0b596 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/all_mail.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/all_mail.rs
@@ -54,7 +54,8 @@ pub(crate) async fn all_mail_preview_cursor(
c.email_address AS "sender_email?",
COALESCE(lmp.from_name, c.name) AS "sender_name?",
c.sfs_photo_url as "sender_photo_url?",
- el.macro_id AS "owner_id!"
+ el.macro_id AS "owner_id!",
+ el.id AS "link_id!"
FROM (
-- Step 1: Efficiently find, sort, and limit the top N+1 threads.
-- This subquery only touches `threads` and `user_history`, making it very fast.
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/draft.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/draft.rs
index cc73168b3d..5267ed1ab0 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/draft.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/draft.rs
@@ -47,7 +47,8 @@ pub(crate) async fn drafts_preview_cursor(
c.email_address AS "sender_email?",
COALESCE(lmp.from_name, c.name) AS "sender_name?",
c.sfs_photo_url as "sender_photo_url?",
- el.macro_id AS "owner_id!"
+ el.macro_id AS "owner_id!",
+ el.id AS "link_id!"
FROM (
-- Step 1: Find the latest draft timestamp for each thread, calculate the
-- effective sort key, then sort and limit the results. This is the core optimization.
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/important.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/important.rs
index db79fe496a..c9d1575e04 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/important.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/important.rs
@@ -143,7 +143,8 @@ pub(crate) async fn important_preview_cursor(
c.email_address AS "sender_email?",
COALESCE(isk.from_name, c.name) AS "sender_name?",
c.sfs_photo_url as "sender_photo_url?",
- el.macro_id AS "owner_id!"
+ el.macro_id AS "owner_id!",
+ el.id AS "link_id!"
FROM ImportantWithSortKey isk
JOIN email_threads t ON isk.thread_id = t.id
LEFT JOIN email_contacts c ON isk.from_contact_id = c.id
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/new_inbox.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/new_inbox.rs
index cfcf5be0d9..22e5338876 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/new_inbox.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/new_inbox.rs
@@ -50,7 +50,8 @@ pub(crate) async fn new_inbox_preview_cursor(
c.email_address AS "sender_email?",
COALESCE(lmp.from_name, c.name) AS "sender_name?",
c.sfs_photo_url as "sender_photo_url?",
- el.macro_id AS "owner_id!"
+ el.macro_id AS "owner_id!",
+ el.id AS "link_id!"
FROM (
-- Step 1: Efficiently find and sort ONLY the top N+1 candidate threads.
-- This subquery is fast as it only touches `threads` and `user_history`.
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/other_inbox.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/other_inbox.rs
index 6dbfbb171c..d55d5b7862 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/other_inbox.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/other_inbox.rs
@@ -48,7 +48,8 @@ pub(crate) async fn other_inbox_preview_cursor(
c.email_address AS "sender_email?",
COALESCE(lmp.from_name, c.name) AS "sender_name?",
c.sfs_photo_url as "sender_photo_url?",
- el.macro_id AS "owner_id!"
+ el.macro_id AS "owner_id!",
+ el.id AS "link_id!"
FROM (
-- Step 1: Efficiently find, sort, and limit the top N+1 threads that qualify for the "Other" inbox.
SELECT
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/sent.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/sent.rs
index 9b499d431a..b96bd012b6 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/sent.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/sent.rs
@@ -48,7 +48,8 @@ pub(crate) async fn sent_preview_cursor(
c.email_address AS "sender_email?",
COALESCE(lmp.from_name, c.name) AS "sender_name?",
c.sfs_photo_url as "sender_photo_url?",
- el.macro_id AS "owner_id!"
+ el.macro_id AS "owner_id!",
+ el.id AS "link_id!"
FROM (
-- Step 1: Efficiently find and sort ONLY the top N+1 candidate threads.
-- This subquery only touches `threads` and `user_history`.
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/starred.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/starred.rs
index 51cc359d1a..8b68e44dde 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/starred.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/starred.rs
@@ -48,7 +48,8 @@ pub(crate) async fn starred_preview_cursor(
c.email_address AS "sender_email?",
COALESCE(lmp.from_name, c.name) AS "sender_name?",
c.sfs_photo_url as "sender_photo_url?",
- el.macro_id AS "owner_id!"
+ el.macro_id AS "owner_id!",
+ el.id AS "link_id!"
FROM (
-- Step 1: Find the latest starred timestamp for each thread, calculate the
-- effective sort key, then sort and limit the results.
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/user_label.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/user_label.rs
index f2356da4cf..d582494816 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/user_label.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/user_label.rs
@@ -49,7 +49,8 @@ pub(crate) async fn user_label_preview_cursor(
c.email_address AS "sender_email?",
COALESCE(lmp.from_name, c.name) AS "sender_name?",
c.sfs_photo_url as "sender_photo_url?",
- el.macro_id AS "owner_id!"
+ el.macro_id AS "owner_id!",
+ el.id AS "link_id!"
FROM (
-- Step 1: Find the latest labeled message timestamp for each thread,
-- calculate the effective sort key, then sort and limit the results.
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/link.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/link.rs
index 981a065fa9..c9289e2e0a 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/link.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/link.rs
@@ -66,6 +66,47 @@ async fn test_link_by_fusionauth_and_macro_id_wrong_macro_id(
Ok(())
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_links_by_fusionauth_user_id_returns_all_owned_inboxes(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ sqlx::query(
+ r#"
+ INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+ VALUES
+ ('a1000000-0000-0000-0000-000000000001'::uuid, 'macro|[email protected]', 'fa-alice', '[email protected]', 'GMAIL', true, NOW() - INTERVAL '1 hour', NOW()),
+ ('a2000000-0000-0000-0000-000000000002'::uuid, 'macro|[email protected]', 'fa-alice', '[email protected]', 'GMAIL', true, NOW(), NOW()),
+ ('b1000000-0000-0000-0000-000000000001'::uuid, 'macro|[email protected]', 'fa-bob', '[email protected]', 'GMAIL', true, NOW(), NOW())
+ "#,
+ )
+ .execute(&pool)
+ .await?;
+
+ let repo = EmailPgRepo::new(pool);
+ let links = repo.links_by_fusionauth_user_id("fa-alice").await?;
+
+ assert_eq!(links.len(), 2, "should return both of fa-alice's inboxes");
+ // ordered by created_at DESC: the newer work inbox comes first
+ assert_eq!(links[0].email_address.0.as_ref(), "[email protected]");
+ assert_eq!(links[1].email_address.0.as_ref(), "[email protected]");
+ assert!(links.iter().all(|l| l.fusionauth_user_id == "fa-alice"));
+
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_links_by_fusionauth_user_id_empty_when_no_inboxes(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+ let links = repo.links_by_fusionauth_user_id("fa-nobody").await?;
+ assert!(
+ links.is_empty(),
+ "user with no inboxes should yield empty vec"
+ );
+ Ok(())
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../../fixtures", scripts("email_message"))
diff --git a/rust/cloud-storage/email_db_client/fixtures/fetch_contacts_two_links.sql b/rust/cloud-storage/email_db_client/fixtures/fetch_contacts_two_links.sql
new file mode 100644
index 0000000000..7d695b12c6
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/fixtures/fetch_contacts_two_links.sql
@@ -0,0 +1,33 @@
+-- Two inboxes (links) owned by the same fusionauth user, each with one
+-- sent-to contact. Used to verify the multi-inbox /email/contacts union groups
+-- contacts by link id.
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES
+ ('d1000000-0000-0000-0000-000000000001', 'macro|[email protected]', 'fa-multi', '[email protected]', 'GMAIL', true, NOW() - INTERVAL '1 hour', NOW()),
+ ('d2000000-0000-0000-0000-000000000002', 'macro|[email protected]', 'fa-multi', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+-- One recipient contact per link
+INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)
+VALUES
+ ('dc000000-0000-0000-0000-000000000001', 'd1000000-0000-0000-0000-000000000001', '[email protected]', 'Alice', NOW(), NOW()),
+ ('dc000000-0000-0000-0000-000000000002', 'd2000000-0000-0000-0000-000000000002', '[email protected]', 'Bob', NOW(), NOW());
+
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES
+ ('d3000000-0000-0000-0000-000000000001', 'd1000000-0000-0000-0000-000000000001', true, true, NOW(), NOW()),
+ ('d3000000-0000-0000-0000-000000000002', 'd2000000-0000-0000-0000-000000000002', true, true, NOW(), NOW());
+
+-- A sent message per link, addressed to that link's contact
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)
+VALUES
+ ('d4000000-0000-0000-0000-000000000001', 'd3000000-0000-0000-0000-000000000001', 'd1000000-0000-0000-0000-000000000001',
+ 'provider-msg-d1', TRUE, '2026-01-05 10:00:00 +00:00', false, true, false, false, NOW(), NOW()),
+ ('d4000000-0000-0000-0000-000000000002', 'd3000000-0000-0000-0000-000000000002', 'd2000000-0000-0000-0000-000000000002',
+ 'provider-msg-d2', TRUE, '2026-01-05 11:00:00 +00:00', false, true, false, false, NOW(), NOW());
+
+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type)
+VALUES
+ ('d4000000-0000-0000-0000-000000000001', 'dc000000-0000-0000-0000-000000000001', 'TO'),
+ ('d4000000-0000-0000-0000-000000000002', 'dc000000-0000-0000-0000-000000000002', 'TO');
diff --git a/rust/cloud-storage/email_db_client/src/contacts/get/test.rs b/rust/cloud-storage/email_db_client/src/contacts/get/test.rs
index 8519364170..d105c8c31a 100644
--- a/rust/cloud-storage/email_db_client/src/contacts/get/test.rs
+++ b/rust/cloud-storage/email_db_client/src/contacts/get/test.rs
@@ -1,9 +1,40 @@
-use crate::contacts::get::{fetch_db_recipients_in_bulk, fetch_senders_by_message_ids};
+use crate::contacts::get::{
+ fetch_contacts_by_link_id, fetch_db_recipients_in_bulk, fetch_senders_by_message_ids,
+};
use anyhow::Result;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use models_email::db::address::EmailRecipientType;
+use models_email::email::service::address::ContactInfoWithInteraction;
use sqlx::types::Uuid;
use sqlx::{Pool, Postgres};
+use std::collections::HashMap;
+
+/// Mirrors the `/email/contacts` handler: union the caller's owned inboxes and
+/// group each inbox's contacts by link id. A two-inbox user must see both
+/// inboxes' contacts under their own link ids.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("fetch_contacts_two_links"))
+)]
+async fn fetch_contacts_unions_across_links_for_one_user(pool: Pool<Postgres>) -> Result<()> {
+ let links = crate::links::get::fetch_links_by_fusionauth_user_id(&pool, "fa-multi").await?;
+ assert_eq!(links.len(), 2, "user owns two inboxes");
+
+ let mut contacts: HashMap<Uuid, Vec<ContactInfoWithInteraction>> = HashMap::new();
+ for link in &links {
+ contacts.insert(link.id, fetch_contacts_by_link_id(&pool, link.id).await?);
+ }
+
+ let link1 = Uuid::parse_str("d1000000-0000-0000-0000-000000000001")?;
+ let link2 = Uuid::parse_str("d2000000-0000-0000-0000-000000000002")?;
+
+ assert_eq!(contacts[&link1].len(), 1);
+ assert_eq!(contacts[&link1][0].extra.email_address, "[email protected]");
+ assert_eq!(contacts[&link2].len(), 1);
+ assert_eq!(contacts[&link2][0].extra.email_address, "[email protected]");
+
+ Ok(())
+}
// ============================================================================
// Tests for fetch_senders_by_message_ids
diff --git a/rust/cloud-storage/email_db_client/src/links/get.rs b/rust/cloud-storage/email_db_client/src/links/get.rs
index c1e440b596..ef3b06b35f 100644
--- a/rust/cloud-storage/email_db_client/src/links/get.rs
+++ b/rust/cloud-storage/email_db_client/src/links/get.rs
@@ -147,6 +147,61 @@ pub async fn fetch_links_by_fusionauth_user_id(
Ok(service_links?)
}
+/// Resolves the inbox (email_link) that owns a thread, but only when the thread's
+/// inbox belongs to the given fusionauth user. Returns `None` when the thread
+/// doesn't exist or its inbox isn't one the caller owns — callers map that to a
+/// not-found/unauthorized response. Lets mutating thread routes derive the inbox
+/// from the thread instead of an `X-Email-Link-Id` header.
+#[tracing::instrument(skip(pool), err)]
+pub async fn fetch_owned_link_for_thread(
+ pool: &PgPool,
+ fusionauth_user_id: &str,
+ thread_id: Uuid,
+) -> anyhow::Result<Option<link::Link>> {
+ let db_link = sqlx::query_as!(
+ DbLink,
+ r#"
+ SELECT l.id, l.macro_id, l.fusionauth_user_id, l.email_address, l.provider as "provider: _",
+ l.is_sync_active, l.created_at, l.updated_at
+ FROM email_threads t
+ JOIN email_links l ON l.id = t.link_id
+ WHERE t.id = $1 AND l.fusionauth_user_id = $2
+ "#,
+ thread_id,
+ fusionauth_user_id
+ )
+ .fetch_optional(pool)
+ .await?;
+
+ Ok(db_link.map(service::link::Link::try_from).transpose()?)
+}
+
+/// Resolves the inbox (email_link) that owns a message, scoped to the caller's
+/// own inboxes. See [`fetch_owned_link_for_thread`].
+#[tracing::instrument(skip(pool), err)]
+pub async fn fetch_owned_link_for_message(
+ pool: &PgPool,
+ fusionauth_user_id: &str,
+ message_id: Uuid,
+) -> anyhow::Result<Option<link::Link>> {
+ let db_link = sqlx::query_as!(
+ DbLink,
+ r#"
+ SELECT l.id, l.macro_id, l.fusionauth_user_id, l.email_address, l.provider as "provider: _",
+ l.is_sync_active, l.created_at, l.updated_at
+ FROM email_messages m
+ JOIN email_links l ON l.id = m.link_id
+ WHERE m.id = $1 AND l.fusionauth_user_id = $2
+ "#,
+ message_id,
+ fusionauth_user_id
+ )
+ .fetch_optional(pool)
+ .await?;
+
+ Ok(db_link.map(service::link::Link::try_from).transpose()?)
+}
+
/// Fetches a link by its ID.
/// Returns None if no link with the given ID exists.
#[tracing::instrument(skip(pool), err)]
diff --git a/rust/cloud-storage/email_service/src/api/email/attachments/get.rs b/rust/cloud-storage/email_service/src/api/email/attachments/get.rs
index e22d117e31..336a2a1d3d 100644
--- a/rust/cloud-storage/email_service/src/api/email/attachments/get.rs
+++ b/rust/cloud-storage/email_service/src/api/email/attachments/get.rs
@@ -8,7 +8,6 @@ use cloudfront_sign::{SignedOptions, get_signed_url};
use model::response::ErrorResponse;
use model::user::UserContext;
use models_email::email::service::attachment;
-use models_email::email::service::link::Link;
use models_email::service;
use std::time::{SystemTime, UNIX_EPOCH};
use utoipa::ToSchema;
@@ -37,47 +36,66 @@ pub struct GetAttachmentResponse {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context, link, gmail_token), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id
+#[tracing::instrument(skip(ctx, user_context), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id
))]
pub async fn handler(
State(ctx): State<ApiContext>,
user_context: Extension<UserContext>,
- link: Extension<Link>,
- gmail_token: Extension<String>,
Path(attachment_id): Path<Uuid>,
) -> Result<Response, Response> {
- // get attachment metadata from db
- let (mut db_attachment, message_provider_id) =
- email_db_client::attachments::provider::fetch_attachment_by_id(
- &ctx.db,
- attachment_id,
- link.id,
+ // Resolve which of the caller's inboxes owns this attachment. Each inbox is a
+ // distinct Google account, so the owning link also determines the Gmail token.
+ let links = email_db_client::links::get::fetch_links_by_fusionauth_user_id(
+ &ctx.db,
+ &user_context.fusion_user_id,
+ )
+ .await
+ .map_err(|e| {
+ tracing::warn!(error=?e, "error fetching links");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "error fetching attachment".into(),
+ }),
)
- .await
- .map_err(|e| {
- tracing::warn!(error=?e, "error fetching attachment from db");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "error fetching attachment".into(),
- }),
- )
- .into_response()
- })?
- .ok_or_else(|| {
- tracing::warn!(
- "attachment with id {} for link {} not found",
+ .into_response()
+ })?;
+
+ let mut owned = None;
+ for link in links {
+ if let Some((db_attachment, message_provider_id)) =
+ email_db_client::attachments::provider::fetch_attachment_by_id(
+ &ctx.db,
attachment_id,
- link.id
- );
- (
- StatusCode::BAD_REQUEST,
- Json(ErrorResponse {
- message: "attachment does not exist".into(),
- }),
+ link.id,
)
- .into_response()
- })?;
+ .await
+ .map_err(|e| {
+ tracing::warn!(error=?e, "error fetching attachment from db");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "error fetching attachment".into(),
+ }),
+ )
+ .into_response()
+ })?
+ {
+ owned = Some((db_attachment, message_provider_id, link));
+ break;
+ }
+ }
+
+ let (mut db_attachment, message_provider_id, link) = owned.ok_or_else(|| {
+ tracing::warn!("attachment with id {} not found for caller", attachment_id);
+ (
+ StatusCode::NOT_FOUND,
+ Json(ErrorResponse {
+ message: "attachment does not exist".into(),
+ }),
+ )
+ .into_response()
+ })?;
let bucket = &ctx.config.attachment_bucket;
@@ -112,14 +130,43 @@ pub async fn handler(
})?;
presigned_request.to_string()
} else {
- // Object doesn't exist, need to fetch from Gmail and upload
+ // Object doesn't exist, need to fetch from Gmail and upload.
+ // Use the owning inbox's own token, not the caller's primary inbox token.
+ let gmail_token = email_service::util::gmail::auth::fetch_gmail_access_token_from_link(
+ &link,
+ &ctx.redis_client,
+ &ctx.auth_service_client,
+ )
+ .await
+ .map_err(|e| {
+ tracing::warn!(error=?e, "error fetching gmail token for attachment inbox");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "error fetching attachment".into(),
+ }),
+ )
+ .into_response()
+ })?;
+
+ let provider_attachment_id = db_attachment.provider_id.as_ref().ok_or_else(|| {
+ tracing::warn!(attachment_id=%attachment_id, "attachment is missing a provider_id");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "error fetching attachment".into(),
+ }),
+ )
+ .into_response()
+ })?;
+
// fetch attachment data from gmail api
let attachment_data = ctx
.gmail_client
.get_attachment_data(
gmail_token.as_str(),
&message_provider_id,
- db_attachment.provider_id.as_ref().unwrap(),
+ provider_attachment_id,
)
.await
.map_err(|e| {
diff --git a/rust/cloud-storage/email_service/src/api/email/attachments/mod.rs b/rust/cloud-storage/email_service/src/api/email/attachments/mod.rs
index 3374e432eb..a2bada1de3 100644
--- a/rust/cloud-storage/email_service/src/api/email/attachments/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/attachments/mod.rs
@@ -8,8 +8,12 @@ pub(crate) mod get;
pub(crate) mod get_document_id;
pub fn router(state: ApiContext) -> Router<ApiContext> {
- Router::new()
- .route("/{id}", get(get::handler))
+ // The attachment download unions across the caller's inboxes: it resolves the
+ // owning inbox (and that inbox's Gmail token) itself, so it carries neither
+ // the single-inbox link middleware nor the primary-inbox token middleware.
+ let union_read_routes = Router::new().route("/{id}", get(get::handler));
+
+ let single_inbox_routes = Router::new()
.route("/{id}/document_id", get(get_document_id::handler))
.layer(
ServiceBuilder::new()
@@ -21,5 +25,9 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
state.clone(),
crate::api::middleware::gmail_token::attach_gmail_token,
)),
- )
+ );
+
+ Router::new()
+ .merge(union_read_routes)
+ .merge(single_inbox_routes)
}
diff --git a/rust/cloud-storage/email_service/src/api/email/contacts/list.rs b/rust/cloud-storage/email_service/src/api/email/contacts/list.rs
index 11d196aa39..cb27ae0ce1 100644
--- a/rust/cloud-storage/email_service/src/api/email/contacts/list.rs
+++ b/rust/cloud-storage/email_service/src/api/email/contacts/list.rs
@@ -26,7 +26,6 @@ pub struct ListContactsResponse {
responses(
(status = 200, body=ListContactsResponse),
(status = 401, body=ErrorResponse),
- (status = 404, body=ErrorResponse),
(status = 500, body=ErrorResponse),
)
)]
@@ -35,46 +34,40 @@ pub async fn list_contacts_handler(
State(ctx): State<ApiContext>,
user_context: Extension<UserContext>,
) -> Result<Response, Response> {
- let link = email_db_client::links::get::fetch_link_by_macro_id(&ctx.db, &user_context.user_id)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to fetch links");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "unable to fetch links".into(),
- }),
- )
- .into_response()
- })?
- .ok_or_else(|| {
- (
- StatusCode::NOT_FOUND,
- Json(ErrorResponse {
- message: "link not found".into(),
- }),
- )
- .into_response()
- })?;
+ let links = email_db_client::links::get::fetch_links_by_fusionauth_user_id(
+ &ctx.db,
+ &user_context.fusion_user_id,
+ )
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "unable to fetch links");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "unable to fetch links".into(),
+ }),
+ )
+ .into_response()
+ })?;
- let contacts = email_db_client::contacts::get::fetch_contacts_by_link_id(&ctx.db, link.id)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to fetch contacts");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "unable to fetch contacts".into(),
- }),
- )
- .into_response()
- })?;
+ let mut contacts: HashMap<Uuid, Vec<ContactInfoWithInteraction>> =
+ HashMap::with_capacity(links.len());
+ for link in links {
+ let link_contacts =
+ email_db_client::contacts::get::fetch_contacts_by_link_id(&ctx.db, link.id)
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "unable to fetch contacts");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "unable to fetch contacts".into(),
+ }),
+ )
+ .into_response()
+ })?;
+ contacts.insert(link.id, link_contacts);
+ }
- Ok((
- StatusCode::OK,
- Json(ListContactsResponse {
- contacts: HashMap::from([(link.id, contacts)]),
- }),
- )
- .into_response())
+ Ok((StatusCode::OK, Json(ListContactsResponse { contacts })).into_response())
}
diff --git a/rust/cloud-storage/email_service/src/api/email/messages/get.rs b/rust/cloud-storage/email_service/src/api/email/messages/get.rs
index 9bfcb7cc24..cef461d660 100644
--- a/rust/cloud-storage/email_service/src/api/email/messages/get.rs
+++ b/rust/cloud-storage/email_service/src/api/email/messages/get.rs
@@ -7,11 +7,25 @@ use axum::{
response::{IntoResponse, Json, Response},
};
use model::{response::ErrorResponse, user::UserContext};
-use models_email::service::link::Link;
use sqlx::types::Uuid;
+use std::collections::HashSet;
use strum_macros::AsRefStr;
use thiserror::Error;
+/// The set of link ids the caller owns — every message read unions across these.
+async fn owned_link_ids(
+ ctx: &ApiContext,
+ fusionauth_user_id: &str,
+) -> anyhow::Result<HashSet<Uuid>> {
+ Ok(
+ email_db_client::links::get::fetch_links_by_fusionauth_user_id(&ctx.db, fusionauth_user_id)
+ .await?
+ .into_iter()
+ .map(|link| link.id)
+ .collect(),
+ )
+}
+
#[derive(Debug, Error, AsRefStr)]
pub enum GetMessageError {
#[error("Message not found")]
@@ -66,25 +80,25 @@ pub struct PathParams {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context, link), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id, link_id=%link.id))]
+#[tracing::instrument(skip(ctx, user_context), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
user_context: Extension<UserContext>,
- link: Extension<Link>,
Path(PathParams { id }): Path<PathParams>,
) -> Result<Response, GetMessageError> {
let message = email_db_client::messages::get_parsed::get_parsed_message_by_id(&ctx.db, &id)
.await
.context("Failed to get message by id")?;
- if let Some(message) = message {
- if message.link_id == link.id {
- Ok(Json(message).into_response())
- } else {
- Err(GetMessageError::Unauthorized)
- }
+ let Some(message) = message else {
+ return Err(GetMessageError::MessageNotFound);
+ };
+
+ let link_ids = owned_link_ids(&ctx, &user_context.fusion_user_id).await?;
+ if link_ids.contains(&message.link_id) {
+ Ok(Json(message).into_response())
} else {
- Err(GetMessageError::MessageNotFound)
+ Err(GetMessageError::Unauthorized)
}
}
@@ -102,11 +116,10 @@ pub async fn handler(
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context, link), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id, link_id=%link.id))]
+#[tracing::instrument(skip(ctx, user_context), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id))]
pub async fn batch_handler(
State(ctx): State<ApiContext>,
user_context: Extension<UserContext>,
- link: Extension<Link>,
Json(ids): Json<Vec<Uuid>>,
) -> Result<Response, GetMessageError> {
let messages =
@@ -119,9 +132,10 @@ pub async fn batch_handler(
return Err(GetMessageError::MessageNotFound);
}
+ let link_ids = owned_link_ids(&ctx, &user_context.fusion_user_id).await?;
let accessible_messages = messages
.into_iter()
- .filter(|msg| msg.link_id == link.id)
+ .filter(|msg| link_ids.contains(&msg.link_id))
.collect::<Vec<_>>();
if accessible_messages.is_empty() {
diff --git a/rust/cloud-storage/email_service/src/api/email/messages/labels.rs b/rust/cloud-storage/email_service/src/api/email/messages/labels.rs
index c029658e26..ee2d3a98e8 100644
--- a/rust/cloud-storage/email_service/src/api/email/messages/labels.rs
+++ b/rust/cloud-storage/email_service/src/api/email/messages/labels.rs
@@ -8,7 +8,6 @@ use axum::{Extension, Json};
use model::response::ErrorResponse;
use model::user::UserContext;
use models_email::service;
-use models_email::service::link::Link;
use sqlx::types::Uuid;
use utoipa::ToSchema;
@@ -42,11 +41,10 @@ pub struct UpdateLabelBatchResponse {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context, link, body), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, user_context, body), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
user_context: Extension<UserContext>,
- link: Extension<Link>,
Json(body): Json<UpdateLabelBatchRequest>,
) -> Result<Response, Response> {
if body.message_ids.is_empty() || body.message_ids.len() > BATCH_UPDATE_MESSAGE_LIMIT {
@@ -62,6 +60,34 @@ pub async fn handler(
.into_response());
}
+ // Resolve the inbox from the batch's messages (scoped to the caller's own
+ // inboxes); a single label op targets messages in one inbox.
+ let link = email_db_client::links::get::fetch_owned_link_for_message(
+ &ctx.db,
+ &user_context.fusion_user_id,
+ body.message_ids[0],
+ )
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "unable to resolve inbox for messages");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "unable to resolve inbox for messages".into(),
+ }),
+ )
+ .into_response()
+ })?
+ .ok_or_else(|| {
+ (
+ StatusCode::NOT_FOUND,
+ Json(ErrorResponse {
+ message: "message not found".into(),
+ }),
+ )
+ .into_response()
+ })?;
+
let label = email_db_client::labels::get::fetch_label_by_id(&ctx.db, body.label_id, link.id)
.await
.map_err(|e| {
diff --git a/rust/cloud-storage/email_service/src/api/email/messages/mod.rs b/rust/cloud-storage/email_service/src/api/email/messages/mod.rs
index 43786dc3a4..3f4de22cd2 100644
--- a/rust/cloud-storage/email_service/src/api/email/messages/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/messages/mod.rs
@@ -10,13 +10,12 @@ use crate::api::ApiContext;
const BATCH_UPDATE_MESSAGE_LIMIT: usize = 10;
pub fn router(state: ApiContext) -> Router<ApiContext> {
+ // Every route resolves its own inbox — send via EmailLinkExtractor, label
+ // batch from the messages, and the reads union across the caller's inboxes —
+ // so none carry the single-inbox X-Email-Link-Id middleware.
Router::new()
.merge(send_router(state.email_service.clone()))
.route("/labels", patch(labels::handler))
.route("/batch", post(get::batch_handler))
- .layer(axum::middleware::from_fn_with_state(
- state.email_service,
- crate::api::middleware::link::attach_link_context,
- ))
.route("/{id}", get(get::handler))
}
diff --git a/rust/cloud-storage/email_service/src/api/email/threads/archived.rs b/rust/cloud-storage/email_service/src/api/email/threads/archived.rs
index 8ff164bce3..3808ba9f09 100644
--- a/rust/cloud-storage/email_service/src/api/email/threads/archived.rs
+++ b/rust/cloud-storage/email_service/src/api/email/threads/archived.rs
@@ -7,7 +7,6 @@ use axum::{Extension, Json};
use email_db_client::threads::update::update_inbox_visible_status;
use model::response::{EmptyResponse, ErrorResponse};
use model::user::UserContext;
-use models_email::email::service::link::Link;
use models_email::service::label::system_labels;
use models_email::service::message::Message;
use sqlx::types::Uuid;
@@ -67,16 +66,24 @@ pub struct ArchiveThreadRequest {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context, link, body), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id), err)]
+#[tracing::instrument(skip(ctx, user_context, body), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id), err)]
pub async fn archived_handler(
State(ctx): State<ApiContext>,
user_context: Extension<UserContext>,
- link: Extension<Link>,
Path(thread_id): Path<Uuid>,
Json(body): Json<ArchiveThreadRequest>,
) -> Result<Response, ArchiveThreadError> {
let is_archiving = body.value;
+ // Resolve the inbox from the thread itself, scoped to the caller's own inboxes.
+ let link = email_db_client::links::get::fetch_owned_link_for_thread(
+ &ctx.db,
+ &user_context.fusion_user_id,
+ thread_id,
+ )
+ .await?
+ .ok_or(ArchiveThreadError::ThreadNotFound)?;
+
let thread =
email_db_client::threads::get::get_thread_by_id_and_link_id(&ctx.db, thread_id, link.id)
.await?
diff --git a/rust/cloud-storage/email_service/src/api/email/threads/get.rs b/rust/cloud-storage/email_service/src/api/email/threads/get.rs
index c448a9207a..f7431de4cc 100644
--- a/rust/cloud-storage/email_service/src/api/email/threads/get.rs
+++ b/rust/cloud-storage/email_service/src/api/email/threads/get.rs
@@ -6,8 +6,8 @@ use axum::response::{IntoResponse, Response};
use axum::{Extension, Json, extract};
use model::response::ErrorResponse;
use model::user::UserContext;
-use models_email::service::link::Link;
use sqlx::types::Uuid;
+use std::collections::HashSet;
use strum_macros::AsRefStr;
use thiserror::Error;
use utoipa::ToSchema;
@@ -89,16 +89,25 @@ const MESSAGE_MAX: i64 = 100;
(status = 500, description = "Internal Server Error", body = ErrorResponse),
),
)]
-#[tracing::instrument(skip(ctx, user_context, link), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id, link_id=%link.id))]
+#[tracing::instrument(skip(ctx, user_context), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id), err)]
pub async fn get_thread_messages_handler(
State(ctx): State<ApiContext>,
user_context: Extension<UserContext>,
- link: Extension<Link>,
Path(PathParams { id }): Path<PathParams>,
extract::Query(query_params): extract::Query<GetThreadMessagesParams>,
) -> Result<Response, GetThreadError> {
let p = process_get_thread_params(&query_params)?;
+ let link_ids: HashSet<Uuid> = email_db_client::links::get::fetch_links_by_fusionauth_user_id(
+ &ctx.db,
+ &user_context.fusion_user_id,
+ )
+ .await
+ .context("Failed to fetch links")?
+ .into_iter()
+ .map(|link| link.id)
+ .collect();
+
let messages =
email_db_client::messages::get_parsed::get_paginated_parsed_messages_by_thread_id(
&ctx.db, id, p.offset, p.limit,
@@ -108,7 +117,7 @@ pub async fn get_thread_messages_handler(
let accessible_messages = messages
.into_iter()
- .filter(|msg| msg.link_id == link.id)
+ .filter(|msg| link_ids.contains(&msg.link_id))
.collect::<Vec<_>>();
if accessible_messages.is_empty() {
diff --git a/rust/cloud-storage/email_service/src/api/email/threads/mod.rs b/rust/cloud-storage/email_service/src/api/email/threads/mod.rs
index 1446c5a6f3..ab5586dea2 100644
--- a/rust/cloud-storage/email_service/src/api/email/threads/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/threads/mod.rs
@@ -8,18 +8,17 @@ use axum::routing::{get, patch, post};
use crate::api::ApiContext;
pub fn router(state: ApiContext) -> Router<ApiContext> {
- let required_link_routes = Router::new()
+ // These routes resolve their own inbox — reads union across the caller's
+ // inboxes, and the mutating routes derive the inbox from the thread — so
+ // none of them carry the single-inbox X-Email-Link-Id middleware.
+ let routes = Router::new()
.nest(
"/previews",
email::inbound::axum::previews_router::router(state.email_service.clone()),
)
- .route("/{id}/seen", post(seen::seen_handler))
.route("/{id}/messages", get(get::get_thread_messages_handler))
- .route("/{id}/archived", patch(archived::archived_handler))
- .layer(axum::middleware::from_fn_with_state(
- state.email_service.clone(),
- crate::api::middleware::link::attach_link_context,
- ));
+ .route("/{id}/seen", post(seen::seen_handler))
+ .route("/{id}/archived", patch(archived::archived_handler));
let hex_thread_routes =
email::inbound::axum::get_thread_router::thread_router(state.email_thread_state.clone());
@@ -36,7 +35,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
);
Router::new()
- .merge(required_link_routes)
+ .merge(routes)
.merge(hex_thread_routes)
.merge(hex_thread_labels_routes)
.merge(hex_thread_project_routes)
diff --git a/rust/cloud-storage/email_service/src/api/email/threads/seen.rs b/rust/cloud-storage/email_service/src/api/email/threads/seen.rs
index a86098ef18..9220b86882 100644
--- a/rust/cloud-storage/email_service/src/api/email/threads/seen.rs
+++ b/rust/cloud-storage/email_service/src/api/email/threads/seen.rs
@@ -7,7 +7,6 @@ use axum::{Extension, Json};
use model::response::{EmptyResponse, ErrorResponse};
use model::user::UserContext;
use models_email::service::label::system_labels;
-use models_email::service::link::Link;
use models_email::service::message::Message;
use sqlx::types::Uuid;
use strum_macros::AsRefStr;
@@ -71,9 +70,18 @@ pub struct PathParams {
pub async fn seen_handler(
State(ctx): State<ApiContext>,
user_context: Extension<UserContext>,
- link: Extension<Link>,
Path(PathParams { id: thread_id }): Path<PathParams>,
) -> Result<Response, SeenThreadError> {
+ // Resolve the inbox from the thread itself, scoped to the caller's own inboxes.
+ let link = email_db_client::links::get::fetch_owned_link_for_thread(
+ &ctx.db,
+ &user_context.fusion_user_id,
+ thread_id,
+ )
+ .await
+ .context("Failed to resolve inbox for thread")?
+ .ok_or(SeenThreadError::ThreadNotFound)?;
+
// update viewed_at value in user_history table for thread
email_db_client::user_history::upsert_user_history(&ctx.db, link.id, thread_id)
.await
diff --git a/rust/cloud-storage/macro_cors/src/lib.rs b/rust/cloud-storage/macro_cors/src/lib.rs
index 0ac7f4a40a..6ef7dd473c 100644
--- a/rust/cloud-storage/macro_cors/src/lib.rs
+++ b/rust/cloud-storage/macro_cors/src/lib.rs
@@ -20,7 +20,12 @@ static ALLOWED_ORIGINS: [&str; 11] = [
"https://apollo-testing.macro.com",
];
-static EXTRA_HEADERS: [&str; 3] = ["x-permissions-token", "traceparent", "tracestate"];
+static EXTRA_HEADERS: [&str; 4] = [
+ "x-permissions-token",
+ "traceparent",
+ "tracestate",
+ "x-email-link-id",
+];
fn get_allowed_origins() -> Vec<Cow<'static, str>> {
match std::env::var("ALLOWED_ORIGINS") {
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
index 3bf1570a16..559cd53980 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
@@ -167,6 +167,21 @@ impl EmailService for MockEmail {
Ok(Vec::new())
}
+ async fn get_links_by_fusionauth_user_id(
+ &self,
+ _auth_id: &str,
+ ) -> Result<Vec<email::domain::models::Link>, email::domain::models::EmailErr> {
+ Ok(Vec::new())
+ }
+
+ async fn get_owned_link_for_thread(
+ &self,
+ _auth_id: &str,
+ _thread_id: uuid::Uuid,
+ ) -> Result<Option<email::domain::models::Link>, email::domain::models::EmailErr> {
+ Ok(None)
+ }
+
async fn get_thread_with_messages(
&self,
_receipt: EntityAccessReceipt<ViewAccessLevel>,
@@ -448,6 +463,21 @@ impl EmailService for MockEmailLinkResult {
(self.get_link_result)().map(|opt| opt.into_iter().collect())
}
+ async fn get_links_by_fusionauth_user_id(
+ &self,
+ _auth_id: &str,
+ ) -> Result<Vec<email::domain::models::Link>, email::domain::models::EmailErr> {
+ (self.get_link_result)().map(|opt| opt.into_iter().collect())
+ }
+
+ async fn get_owned_link_for_thread(
+ &self,
+ _auth_id: &str,
+ _thread_id: uuid::Uuid,
+ ) -> Result<Option<email::domain::models::Link>, email::domain::models::EmailErr> {
+ (self.get_link_result)()
+ }
+
async fn get_thread_with_messages(
&self,
_receipt: EntityAccessReceipt<ViewAccessLevel>,