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.

chore(email-service): Hexify apply thread labels endpoint (#1779)

Evan Hutnik87ed81fc1013
diff --git a/js/app/packages/service-clients/service-email/client.ts b/js/app/packages/service-clients/service-email/client.ts
index 25d888e434..4718cdf5ae 100644
--- a/js/app/packages/service-clients/service-email/client.ts
+++ b/js/app/packages/service-clients/service-email/client.ts
@@ -27,6 +27,7 @@ import type {
UpdateLabelBatchRequest,
UpdateLabelBatchResponse,
UpdateThreadLabelRequest,
+ UpdateThreadLabelsResponse,
UpsertScheduledRequest,
UpsertScheduledResponse,
} from './generated/schemas';
@@ -126,7 +127,7 @@ export const emailClient = {
) {
const { thread_id, label_id, value } = args;
return mapOk(
- await emailFetch<UpdateLabelBatchResponse>(
+ await emailFetch<UpdateThreadLabelsResponse>(
`/email/threads/${thread_id}/labels`,
{
method: 'PATCH',
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 ee6633efba..69be358b47 100644
--- a/js/app/packages/service-clients/service-email/generated/client.ts
+++ b/js/app/packages/service-clients/service-email/generated/client.ts
@@ -41,6 +41,7 @@ import type {
UpdateLabelBatchRequest,
UpdateLabelBatchResponse,
UpdateThreadLabelRequest,
+ UpdateThreadLabelsResponse,
UpsertScheduledRequest,
UpsertScheduledResponse,
} from './schemas';
@@ -1899,10 +1900,10 @@ export const archiveThread = async (
};
/**
- * @summary Add or remove a label from all messages in a thread
+ * @summary Add or remove a label from all messages in a thread.
*/
export type addRemoveThreadLabelResponse200 = {
- data: UpdateLabelBatchResponse;
+ data: UpdateThreadLabelsResponse;
status: 200;
};
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/index.ts b/js/app/packages/service-clients/service-email/generated/schemas/index.ts
index adfc458cac..f443fd3539 100644
--- a/js/app/packages/service-clients/service-email/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-email/generated/schemas/index.ts
@@ -236,6 +236,7 @@ export * from './threadSummary';
export * from './updateLabelBatchRequest';
export * from './updateLabelBatchResponse';
export * from './updateThreadLabelRequest';
+export * from './updateThreadLabelsResponse';
export * from './upsertScheduledRequest';
export * from './upsertScheduledResponse';
export * from './userProvider';
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/updateThreadLabelRequest.ts b/js/app/packages/service-clients/service-email/generated/schemas/updateThreadLabelRequest.ts
index 12a575b548..f3c76540bf 100644
--- a/js/app/packages/service-clients/service-email/generated/schemas/updateThreadLabelRequest.ts
+++ b/js/app/packages/service-clients/service-email/generated/schemas/updateThreadLabelRequest.ts
@@ -5,6 +5,9 @@
* OpenAPI spec version: 0.1.0
*/
+/**
+ * Request body for updating a thread's labels.
+ */
export interface UpdateThreadLabelRequest {
label_id: string;
value: boolean;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/updateThreadLabelsResponse.ts b/js/app/packages/service-clients/service-email/generated/schemas/updateThreadLabelsResponse.ts
new file mode 100644
index 0000000000..0bb94ab24f
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/updateThreadLabelsResponse.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Response body for updating a thread's labels.
+ */
+export interface UpdateThreadLabelsResponse {
+ failed_ids: string[];
+ successful_ids: string[];
+}
diff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.json
index 159b1da4bd..f9de69189e 100644
--- a/js/app/packages/service-clients/service-email/openapi.json
+++ b/js/app/packages/service-clients/service-email/openapi.json
@@ -1824,7 +1824,7 @@
"/email/threads/{id}/labels": {
"patch": {
"tags": ["Threads"],
- "summary": "Add or remove a label from all messages in a thread",
+ "summary": "Add or remove a label from all messages in a thread.",
"operationId": "add_remove_thread_label",
"parameters": [
{
@@ -1854,7 +1854,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/UpdateLabelBatchResponse"
+ "$ref": "#/components/schemas/UpdateThreadLabelsResponse"
}
}
}
@@ -4204,6 +4204,7 @@
},
"UpdateThreadLabelRequest": {
"type": "object",
+ "description": "Request body for updating a thread's labels.",
"required": ["label_id", "value"],
"properties": {
"label_id": {
@@ -4215,6 +4216,27 @@
}
}
},
+ "UpdateThreadLabelsResponse": {
+ "type": "object",
+ "description": "Response body for updating a thread's labels.",
+ "required": ["successful_ids", "failed_ids"],
+ "properties": {
+ "failed_ids": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ "successful_ids": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ }
+ },
"UpsertScheduledRequest": {
"type": "object",
"required": ["send_time"],
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 0c7df3dbb0..dfc3d71e48 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -3298,6 +3298,7 @@ name = "email"
version = "0.1.0"
dependencies = [
"anyhow",
+ "authentication_service_client",
"axum",
"axum-extra",
"base64 0.22.1",
@@ -3309,6 +3310,7 @@ dependencies = [
"filter_ast",
"frecency",
"futures",
+ "gmail_client",
"item_filters",
"macro_db_migrator",
"macro_user_id",
@@ -3318,6 +3320,7 @@ dependencies = [
"model_user",
"models_pagination",
"recursion",
+ "redis",
"schemars",
"serde",
"serde_json",
@@ -6097,19 +6100,11 @@ dependencies = [
"anyhow",
"base64 0.22.1",
"chrono",
- "doppleganger",
- "ego-tree",
- "email",
"email_utils",
"html2text",
- "lazy_static",
"macro_user_id",
- "macro_uuid",
"models_pagination",
- "models_permissions",
- "regex",
"schemars",
- "scraper",
"serde",
"serde_json",
"serde_with",
diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rs
index 8f1f1cf69c..c432b98f89 100644
--- a/rust/cloud-storage/ai_tools/src/tool_context.rs
+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs
@@ -24,8 +24,12 @@ pub type ToolScribe =
pub type ToolFrecencyService = FrecencyQueryServiceImpl<FrecencyPgStorage>;
/// Type alias for the email service implementation
-pub type ToolEmailService =
- EmailServiceImpl<EmailPgRepo, ToolFrecencyService, email::domain::ports::NoOpEnqueuer>;
+pub type ToolEmailService = EmailServiceImpl<
+ EmailPgRepo,
+ ToolFrecencyService,
+ email::domain::ports::NoOpEnqueuer,
+ email::domain::ports::NoOpGmailLabelModifier,
+>;
/// Type alias for the comms/channels service implementation
pub type ToolCommsService = ChannelServiceImpl<PgCommsRepo, PgUserRepo, FrecencyPgStorage>;
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
index 3e69047811..f59cdcf8ad 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
@@ -196,6 +196,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
EmailPgRepo::new(pool.clone()),
frecency_service.clone(),
email::domain::ports::NoOpEnqueuer,
+ email::domain::ports::NoOpGmailLabelModifier,
0,
);
let user_repo = PgUserRepo::new(pool.clone());
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index d28806c93c..c88f2d5085 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -154,6 +154,7 @@ async fn main() -> anyhow::Result<()> {
EmailPgRepo::new(db.clone()),
frecency_service.clone(),
email::domain::ports::NoOpEnqueuer,
+ email::domain::ports::NoOpGmailLabelModifier,
0,
);
let channels_service = ChannelServiceImpl::new(
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index 252b24d0e7..7a4c06529e 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -64,6 +64,7 @@ type DssSoupState = SoupRouterState<
EmailPgRepo,
FrecencyQueryServiceImpl<FrecencyPgStorage>,
email::domain::ports::NoOpEnqueuer,
+ email::domain::ports::NoOpGmailLabelModifier,
>,
ChannelServiceImpl<PgCommsRepo, PgUserRepo, FrecencyPgStorage>,
>,
@@ -71,6 +72,7 @@ type DssSoupState = SoupRouterState<
EmailPgRepo,
FrecencyQueryServiceImpl<FrecencyPgStorage>,
email::domain::ports::NoOpEnqueuer,
+ email::domain::ports::NoOpGmailLabelModifier,
>,
>;
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index c746ec96fc..660ae95224 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -207,6 +207,7 @@ async fn main() -> anyhow::Result<()> {
EmailPgRepo::new(db.clone()),
frecency_service.clone(),
email::domain::ports::NoOpEnqueuer,
+ email::domain::ports::NoOpGmailLabelModifier,
0,
);
let system_properties_service =
diff --git a/rust/cloud-storage/email/.sqlx/query-16fe6d8422135f9b01d5acb48576c9ebeea62fe8b80747ddcf9c5fdeee1a6c7e.json b/rust/cloud-storage/email/.sqlx/query-16fe6d8422135f9b01d5acb48576c9ebeea62fe8b80747ddcf9c5fdeee1a6c7e.json
new file mode 100644
index 0000000000..08f519fb97
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-16fe6d8422135f9b01d5acb48576c9ebeea62fe8b80747ddcf9c5fdeee1a6c7e.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO email_message_labels (message_id, label_id)\n SELECT\n unnested_message_id,\n l.id\n FROM\n UNNEST($1::uuid[]) AS t(unnested_message_id)\n CROSS JOIN\n email_labels l\n WHERE\n l.link_id = $2 AND l.provider_label_id = $3\n ON CONFLICT (message_id, label_id) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "16fe6d8422135f9b01d5acb48576c9ebeea62fe8b80747ddcf9c5fdeee1a6c7e"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-59eb39577b1b566ef0a95f74f75904a62689388c0b28b77a02946952e6aa8b36.json b/rust/cloud-storage/email/.sqlx/query-59eb39577b1b566ef0a95f74f75904a62689388c0b28b77a02946952e6aa8b36.json
new file mode 100644
index 0000000000..bf8b77e46c
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-59eb39577b1b566ef0a95f74f75904a62689388c0b28b77a02946952e6aa8b36.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE email_messages m\n SET\n is_starred = $1,\n updated_at = NOW()\n WHERE\n m.id = ANY($2)\n AND m.link_id = $3\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Bool",
+ "UuidArray",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "59eb39577b1b566ef0a95f74f75904a62689388c0b28b77a02946952e6aa8b36"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-b0e8935f157a7ae307fb050b39d0dde4e9e2e39f7cb20c716fbbcc1ffe320cd1.json b/rust/cloud-storage/email/.sqlx/query-b0e8935f157a7ae307fb050b39d0dde4e9e2e39f7cb20c716fbbcc1ffe320cd1.json
new file mode 100644
index 0000000000..e2f94b21f4
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-b0e8935f157a7ae307fb050b39d0dde4e9e2e39f7cb20c716fbbcc1ffe320cd1.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM email_message_labels\n WHERE\n message_id = ANY($1)\n AND label_id = (\n SELECT id FROM email_labels\n WHERE link_id = $2 AND provider_label_id = $3\n )\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "b0e8935f157a7ae307fb050b39d0dde4e9e2e39f7cb20c716fbbcc1ffe320cd1"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-b1c4d610f2fe772e88b8e78bc872f01c886031d866616effed3c6a61a99d2413.json b/rust/cloud-storage/email/.sqlx/query-b1c4d610f2fe772e88b8e78bc872f01c886031d866616effed3c6a61a99d2413.json
new file mode 100644
index 0000000000..9d7bd134c0
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-b1c4d610f2fe772e88b8e78bc872f01c886031d866616effed3c6a61a99d2413.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE email_messages m\n SET\n is_read = $1,\n updated_at = NOW()\n WHERE\n m.id = ANY($2)\n AND m.link_id = $3\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Bool",
+ "UuidArray",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "b1c4d610f2fe772e88b8e78bc872f01c886031d866616effed3c6a61a99d2413"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-b79ca4a7b148d78ddf48b5c57dea59763b17693c09564a0190ed377dd09342cf.json b/rust/cloud-storage/email/.sqlx/query-b79ca4a7b148d78ddf48b5c57dea59763b17693c09564a0190ed377dd09342cf.json
new file mode 100644
index 0000000000..9c01b8fe22
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-b79ca4a7b148d78ddf48b5c57dea59763b17693c09564a0190ed377dd09342cf.json
@@ -0,0 +1,96 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id,\n link_id,\n provider_label_id,\n name,\n created_at,\n message_list_visibility as \"message_list_visibility: _\",\n label_list_visibility as \"label_list_visibility: _\",\n type as \"type_: _\"\n FROM email_labels\n WHERE id = $1 AND link_id = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "link_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "provider_label_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "name",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 4,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "message_list_visibility: _",
+ "type_info": {
+ "Custom": {
+ "name": "email_message_list_visibility_enum",
+ "kind": {
+ "Enum": [
+ "Show",
+ "Hide"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 6,
+ "name": "label_list_visibility: _",
+ "type_info": {
+ "Custom": {
+ "name": "email_label_list_visibility_enum",
+ "kind": {
+ "Enum": [
+ "LabelShow",
+ "LabelShowIfUnread",
+ "LabelHide"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 7,
+ "name": "type_: _",
+ "type_info": {
+ "Custom": {
+ "name": "email_label_type_enum",
+ "kind": {
+ "Enum": [
+ "System",
+ "User"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "b79ca4a7b148d78ddf48b5c57dea59763b17693c09564a0190ed377dd09342cf"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-dfc54abc6dd32c35bf3d3c65288ead04d9990d5f6613bd7668dd7cba38ebe3a5.json b/rust/cloud-storage/email/.sqlx/query-dfc54abc6dd32c35bf3d3c65288ead04d9990d5f6613bd7668dd7cba38ebe3a5.json
new file mode 100644
index 0000000000..f8ffb29abe
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-dfc54abc6dd32c35bf3d3c65288ead04d9990d5f6613bd7668dd7cba38ebe3a5.json
@@ -0,0 +1,149 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n m.id,\n m.provider_id,\n m.thread_id,\n m.provider_thread_id,\n m.replying_to_id,\n m.global_id,\n m.link_id,\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.provider_history_id,\n m.internal_date_ts,\n m.sent_at,\n m.size_estimate,\n m.is_read,\n m.is_starred,\n m.is_sent,\n m.is_draft,\n m.has_attachments,\n m.headers_jsonb,\n m.created_at,\n m.updated_at\n FROM email_messages m\n WHERE m.thread_id = $1 AND m.link_id = $2\n ORDER BY m.internal_date_ts DESC NULLS LAST\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "provider_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "provider_thread_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "replying_to_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 5,
+ "name": "global_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "link_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 7,
+ "name": "subject",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "snippet",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 9,
+ "name": "from_contact_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 10,
+ "name": "provider_history_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 11,
+ "name": "internal_date_ts",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 12,
+ "name": "sent_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 13,
+ "name": "size_estimate",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 14,
+ "name": "is_read",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 15,
+ "name": "is_starred",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 16,
+ "name": "is_sent",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 17,
+ "name": "is_draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 18,
+ "name": "has_attachments",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 19,
+ "name": "headers_jsonb",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 20,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 21,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ true,
+ true,
+ true,
+ false,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "dfc54abc6dd32c35bf3d3c65288ead04d9990d5f6613bd7668dd7cba38ebe3a5"
+}
diff --git a/rust/cloud-storage/email/Cargo.toml b/rust/cloud-storage/email/Cargo.toml
index c065466835..1b7b64223d 100644
--- a/rust/cloud-storage/email/Cargo.toml
+++ b/rust/cloud-storage/email/Cargo.toml
@@ -15,6 +15,7 @@ axum = [
"model_user/axum",
"models_pagination/axum",
]
+gmail_token = ["dep:authentication_service_client", "dep:gmail_client", "dep:redis", "ports"]
inbound = ["ports"]
outbound = ["dep:sqlx", "ports"]
ports = ["dep:tokio", "frecency/ports"]
@@ -32,6 +33,7 @@ either = { workspace = true }
email_utils = { path = "../email_utils" }
filter_ast = { path = "../filter_ast" }
frecency = { path = "../frecency" }
+gmail_client = { path = "../gmail_client", optional = true }
item_filters = { path = "../item_filters" }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
@@ -44,6 +46,8 @@ schemars = { workspace = true, optional = true, features = ["uuid1"] }
serde = { workspace = true }
serde_json = { workspace = true }
serde_with = { workspace = true }
+authentication_service_client = { path = "../authentication_service_client", optional = true }
+redis = { workspace = true, features = ["tokio-native-tls-comp"], optional = true }
sqlx = { workspace = true, optional = true }
strum = { workspace = true }
thiserror = { workspace = true }
diff --git a/rust/cloud-storage/email/fixtures/email_thread_labels.sql b/rust/cloud-storage/email/fixtures/email_thread_labels.sql
new file mode 100644
index 0000000000..5d71413b53
--- /dev/null
+++ b/rust/cloud-storage/email/fixtures/email_thread_labels.sql
@@ -0,0 +1,40 @@
+-- Fixture for testing thread label repo methods:
+-- get_label_by_id, get_thread_label_messages,
+-- insert/delete_message_labels_batch,
+-- update_message_read/starred_status_batch
+
+-- Insert test links
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES
+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro1', 'user1', '[email protected]', 'GMAIL', true, NOW(), NOW()),
+ ('aaaaaaaa-aaaa-aaaa-aaaa-bbbbbbbbbbbb', 'macro2', 'user2', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+-- Insert test threads
+INSERT INTO email_threads (id, provider_id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES
+ ('11111111-1111-1111-1111-111111111111', 'thread1', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', true, false, NOW(), NOW()),
+ ('22222222-2222-2222-2222-222222222222', 'thread2', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', true, false, NOW(), NOW());
+
+-- Insert test labels
+INSERT INTO email_labels (id, link_id, provider_label_id, name, message_list_visibility, label_list_visibility, type, created_at)
+VALUES
+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'INBOX', 'INBOX', 'Show', 'LabelShow', 'System', NOW()),
+ ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'UNREAD', 'UNREAD', 'Hide', 'LabelHide', 'System', NOW()),
+ ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'STARRED', 'STARRED', 'Show', 'LabelShowIfUnread', 'System', NOW()),
+ ('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Label_123', 'MyCustomLabel', 'Show', 'LabelShow', 'User', NOW()),
+ -- Label belonging to a different link
+ ('ffffffff-ffff-ffff-ffff-ffffffffffff', 'aaaaaaaa-aaaa-aaaa-aaaa-bbbbbbbbbbbb', 'INBOX', 'INBOX', 'Show', 'LabelShow', 'System', NOW());
+
+-- Insert test messages for thread 1 (2 messages, both unread, not starred)
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_read, is_starred, is_sent, is_draft, has_attachments, internal_date_ts, created_at, updated_at)
+VALUES
+ ('11111111-aaaa-aaaa-aaaa-111111111111', '11111111-1111-1111-1111-111111111111', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg1a', false, false, false, false, false, '2025-01-01T10:00:00Z', NOW(), NOW()),
+ ('11111111-bbbb-bbbb-bbbb-111111111111', '11111111-1111-1111-1111-111111111111', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg1b', false, false, false, false, false, '2025-01-01T11:00:00Z', NOW(), NOW());
+
+-- Insert test messages for thread 2 (empty thread scenario - no messages)
+
+-- Message labels: msg1a has INBOX, msg1b has INBOX
+INSERT INTO email_message_labels (message_id, label_id)
+VALUES
+ ('11111111-aaaa-aaaa-aaaa-111111111111', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'),
+ ('11111111-bbbb-bbbb-bbbb-111111111111', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb');
diff --git a/rust/cloud-storage/email/src/domain/models/error.rs b/rust/cloud-storage/email/src/domain/models/error.rs
index c10a190686..219b737c85 100644
--- a/rust/cloud-storage/email/src/domain/models/error.rs
+++ b/rust/cloud-storage/email/src/domain/models/error.rs
@@ -8,6 +8,9 @@ pub enum EmailErr {
/// A repository/infrastructure error.
#[error(transparent)]
RepoErr(#[from] anyhow::Error),
+ /// An external provider API error (e.g. Gmail API).
+ #[error("Provider error: {0}")]
+ ProviderErr(anyhow::Error),
/// A frecency query error.
#[error(transparent)]
Frecency(#[from] FrecencyQueryErr),
@@ -26,4 +29,13 @@ pub enum EmailErr {
/// Decoded bytes are not valid UTF-8.
#[error("Failed to convert decoded HTML body to UTF-8")]
Utf8Error(#[from] std::string::FromUtf8Error),
+ /// The referenced label was not found.
+ #[error("Label not found")]
+ LabelNotFound,
+ /// The label has an empty provider label ID.
+ #[error("Label has empty provider label ID")]
+ EmptyProviderLabelId,
+ /// No messages found for thread.
+ #[error("No messages found for thread")]
+ ThreadEmpty,
}
diff --git a/rust/cloud-storage/email/src/domain/models/label.rs b/rust/cloud-storage/email/src/domain/models/label.rs
index 63a5209cc1..c38d6caeb7 100644
--- a/rust/cloud-storage/email/src/domain/models/label.rs
+++ b/rust/cloud-storage/email/src/domain/models/label.rs
@@ -53,3 +53,31 @@ pub struct MessageLabel {
/// Label type (system or user).
pub type_: Option<LabelType>,
}
+
+/// A label looked up by ID, used for thread label operations.
+#[derive(Debug, Clone)]
+pub struct LinkLabel {
+ pub id: Uuid,
+ pub link_id: Uuid,
+ pub provider_label_id: String,
+ pub name: String,
+ pub created_at: DateTime<Utc>,
+ pub message_list_visibility: MessageListVisibility,
+ pub label_list_visibility: LabelListVisibility,
+ pub type_: LabelType,
+}
+
+/// Result of updating labels on a thread's messages.
+#[derive(Debug, Clone)]
+pub struct UpdateThreadLabelsResult {
+ pub successful_ids: Vec<Uuid>,
+ pub failed_ids: Vec<Uuid>,
+}
+
+/// Well-known system label identifiers.
+pub mod system_labels {
+ /// The UNREAD label.
+ pub const UNREAD: &str = "UNREAD";
+ /// The STARRED label.
+ pub const STARRED: &str = "STARRED";
+}
diff --git a/rust/cloud-storage/email/src/domain/models/message.rs b/rust/cloud-storage/email/src/domain/models/message.rs
index 32992037dd..f1cb78ecdf 100644
--- a/rust/cloud-storage/email/src/domain/models/message.rs
+++ b/rust/cloud-storage/email/src/domain/models/message.rs
@@ -57,6 +57,55 @@ pub struct MessageRow {
pub updated_at: DateTime<Utc>,
}
+/// A simplified message record with core fields and no assembled sub-types.
+#[derive(Debug, Clone)]
+pub struct SimpleMessage {
+ /// Database ID of the message.
+ pub db_id: uuid::Uuid,
+ /// Provider message ID.
+ pub provider_id: Option<String>,
+ /// Database ID of the thread this message belongs to.
+ pub thread_db_id: uuid::Uuid,
+ /// Provider thread ID.
+ pub provider_thread_id: Option<String>,
+ /// Database ID of the message this is replying to.
+ pub replying_to_id: Option<uuid::Uuid>,
+ /// Globally unique Message-ID header value.
+ pub global_id: Option<String>,
+ /// Link ID this message belongs to.
+ pub link_id: uuid::Uuid,
+ /// Message subject.
+ pub subject: Option<String>,
+ /// Message snippet.
+ pub snippet: Option<String>,
+ /// Database ID of the sender contact.
+ pub from_contact_id: Option<uuid::Uuid>,
+ /// Provider history ID.
+ pub provider_history_id: Option<String>,
+ /// Internal date timestamp from the provider.
+ pub internal_date_ts: Option<DateTime<Utc>>,
+ /// When the message was sent.
+ pub sent_at: Option<DateTime<Utc>>,
+ /// Estimated size of the message.
+ pub size_estimate: Option<i64>,
+ /// Whether the message has been read.
+ pub is_read: bool,
+ /// Whether the message is starred.
+ pub is_starred: bool,
+ /// Whether the message was sent by the user.
+ pub is_sent: bool,
+ /// Whether the message is a draft.
+ pub is_draft: bool,
+ /// Whether the message has attachments.
+ pub has_attachments: bool,
+ /// Raw headers as JSON.
+ pub headers_json: Option<serde_json::Value>,
+ /// When the message was created.
+ pub created_at: DateTime<Utc>,
+ /// When the message was last updated.
+ pub updated_at: DateTime<Utc>,
+}
+
/// A fully assembled message with all sub-types resolved.
#[derive(Debug, Clone)]
pub struct Message {
diff --git a/rust/cloud-storage/email/src/domain/models/mod.rs b/rust/cloud-storage/email/src/domain/models/mod.rs
index ef814654cc..85dda6f769 100644
--- a/rust/cloud-storage/email/src/domain/models/mod.rs
+++ b/rust/cloud-storage/email/src/domain/models/mod.rs
@@ -18,9 +18,12 @@ pub use draft::{
UpsertedContacts, UpsertedRecipient,
};
pub use error::EmailErr;
-pub use label::{Label, LabelListVisibility, LabelType, MessageLabel, MessageListVisibility};
+pub use label::{
+ Label, LabelListVisibility, LabelType, LinkLabel, MessageLabel, MessageListVisibility,
+ UpdateThreadLabelsResult,
+};
pub use link::{Link, UserProvider};
-pub use message::{Message, MessageRow};
+pub use message::{Message, MessageRow, SimpleMessage};
pub use preview::{
EmailThreadPreview, EnrichedEmailThreadPreview, GetEmailsRequest, PreviewCursorQuery,
PreviewView, PreviewViewStandardLabel,
diff --git a/rust/cloud-storage/email/src/domain/ports.rs b/rust/cloud-storage/email/src/domain/ports.rs
index 4697ba1a59..253621744a 100644
--- a/rust/cloud-storage/email/src/domain/ports.rs
+++ b/rust/cloud-storage/email/src/domain/ports.rs
@@ -1,9 +1,9 @@
use crate::domain::models::{
Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, CreateDraftInput,
CreatedDraft, EmailErr, EmailThreadPreview, EnrichedEmailThreadPreview, GetEmailsRequest,
- Label, Link, MessageAttachment, MessageLabel, MessageRow, ParsedAddresses, PreviewCursorQuery,
- RecipientType, ResolvedDraftInput, SimpleMessageInfo, Thread, ThreadRow, UpsertedContacts,
- UserProvider,
+ Label, Link, LinkLabel, MessageAttachment, MessageLabel, MessageRow, ParsedAddresses,
+ PreviewCursorQuery, RecipientType, ResolvedDraftInput, SimpleMessage, SimpleMessageInfo,
+ Thread, ThreadRow, UpdateThreadLabelsResult, UpsertedContacts, UserProvider,
};
use chrono::{DateTime, Utc};
use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};
@@ -149,6 +149,52 @@ pub trait EmailRepo: Send + Sync + 'static {
new_thread: Option<ThreadRow>,
is_draft: bool,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Fetch a label by its database ID and link ID.
+ fn get_label_by_id(
+ &self,
+ label_id: Uuid,
+ link_id: Uuid,
+ ) -> impl Future<Output = Result<Option<LinkLabel>, Self::Err>> + Send;
+
+ /// Fetch all messages in a thread for label operations.
+ fn get_thread_label_messages(
+ &self,
+ thread_id: Uuid,
+ link_id: Uuid,
+ ) -> impl Future<Output = Result<Vec<SimpleMessage>, Self::Err>> + Send;
+
+ /// Bulk insert a label for multiple messages.
+ fn insert_message_labels_batch(
+ &self,
+ message_ids: &[Uuid],
+ provider_label_id: &str,
+ link_id: Uuid,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Bulk delete a label from multiple messages.
+ fn delete_message_labels_batch(
+ &self,
+ message_ids: &[Uuid],
+ provider_label_id: &str,
+ link_id: Uuid,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Update the read status for a batch of messages, verified by link_id.
+ fn update_message_read_status_batch(
+ &self,
+ message_ids: &[Uuid],
+ link_id: Uuid,
+ is_read: bool,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Update the starred status for a batch of messages, verified by link_id.
+ fn update_message_starred_status_batch(
+ &self,
+ message_ids: &[Uuid],
+ link_id: Uuid,
+ is_starred: bool,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
}
pub trait EmailService: Send + Sync + 'static {
@@ -189,6 +235,44 @@ pub trait EmailService: Send + Sync + 'static {
link: &Link,
input: CreateDraftInput,
) -> impl Future<Output = Result<CreatedDraft, EmailErr>> + Send;
+
+ /// Add or remove a label from all messages in a thread.
+ fn update_thread_labels(
+ &self,
+ access_token: &str,
+ link: &Link,
+ thread_id: Uuid,
+ label_id: Uuid,
+ add: bool,
+ ) -> impl Future<Output = Result<UpdateThreadLabelsResult, EmailErr>> + Send;
+}
+
+/// Port for modifying Gmail message labels via the provider API.
+pub trait GmailLabelModifier: Send + Sync + 'static {
+ /// Add and remove labels on a single message identified by its provider message ID.
+ fn modify_message_labels(
+ &self,
+ access_token: &str,
+ provider_message_id: &str,
+ label_ids_to_add: &[String],
+ label_ids_to_remove: &[String],
+ ) -> impl Future<Output = Result<(), EmailErr>> + Send;
+}
+
+/// No-op label modifier for callers that don't need Gmail label operations.
+#[derive(Clone)]
+pub struct NoOpGmailLabelModifier;
+
+impl GmailLabelModifier for NoOpGmailLabelModifier {
+ async fn modify_message_labels(
+ &self,
+ _access_token: &str,
+ _provider_message_id: &str,
+ _label_ids_to_add: &[String],
+ _label_ids_to_remove: &[String],
+ ) -> Result<(), EmailErr> {
+ Ok(())
+ }
}
/// No-op enqueuer for callers that don't need send capability.
diff --git a/rust/cloud-storage/email/src/domain/service/draft.rs b/rust/cloud-storage/email/src/domain/service/draft.rs
index eae50a16ee..f68d652e28 100644
--- a/rust/cloud-storage/email/src/domain/service/draft.rs
+++ b/rust/cloud-storage/email/src/domain/service/draft.rs
@@ -12,7 +12,7 @@ use uuid::Uuid;
use super::EmailServiceImpl;
-impl<T, U, E> EmailServiceImpl<T, U, E>
+impl<T, U, E, G> EmailServiceImpl<T, U, E, G>
where
T: EmailRepo,
U: FrecencyQueryService,
diff --git a/rust/cloud-storage/email/src/domain/service/mod.rs b/rust/cloud-storage/email/src/domain/service/mod.rs
index d549ec2177..9dd6ac06a8 100644
--- a/rust/cloud-storage/email/src/domain/service/mod.rs
+++ b/rust/cloud-storage/email/src/domain/service/mod.rs
@@ -2,13 +2,14 @@ mod draft;
mod previews;
mod send;
mod thread;
+mod thread_labels;
use crate::domain::{
models::{
CreateDraftInput, CreatedDraft, EmailErr, EnrichedEmailThreadPreview, GetEmailsRequest,
- Link, Thread,
+ Link, Thread, UpdateThreadLabelsResult,
},
- ports::{EmailMessageEnqueuer, EmailRepo, EmailService},
+ ports::{EmailMessageEnqueuer, EmailRepo, EmailService, GmailLabelModifier},
};
use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};
use frecency::domain::ports::FrecencyQueryService;
@@ -16,39 +17,44 @@ use models_pagination::{PaginatedCursor, SimpleSortMethod};
use uuid::Uuid;
#[derive(Clone)]
-pub struct EmailServiceImpl<T, U, E> {
+pub struct EmailServiceImpl<T, U, E, G> {
email_repo: T,
frecency_service: U,
enqueuer: E,
+ gmail_label_modifier: G,
sent_undo_delay_secs: u32,
}
-impl<T, U, E> EmailServiceImpl<T, U, E>
+impl<T, U, E, G> EmailServiceImpl<T, U, E, G>
where
T: EmailRepo,
U: FrecencyQueryService,
E: EmailMessageEnqueuer,
+ G: GmailLabelModifier,
{
pub fn new(
email_repo: T,
frecency_service: U,
enqueuer: E,
+ gmail_label_modifier: G,
sent_undo_delay_secs: u32,
- ) -> EmailServiceImpl<T, U, E> {
+ ) -> EmailServiceImpl<T, U, E, G> {
EmailServiceImpl {
email_repo,
frecency_service,
enqueuer,
+ gmail_label_modifier,
sent_undo_delay_secs,
}
}
}
-impl<T, U, E> EmailService for EmailServiceImpl<T, U, E>
+impl<T, U, E, G> EmailService for EmailServiceImpl<T, U, E, G>
where
T: EmailRepo,
U: FrecencyQueryService,
E: EmailMessageEnqueuer,
+ G: GmailLabelModifier,
anyhow::Error: From<T::Err>,
anyhow::Error: From<E::Err>,
{
@@ -94,4 +100,16 @@ where
) -> Result<CreatedDraft, EmailErr> {
self.send_message_impl(link, input).await
}
+
+ async fn update_thread_labels(
+ &self,
+ access_token: &str,
+ link: &Link,
+ thread_id: Uuid,
+ label_id: Uuid,
+ add: bool,
+ ) -> Result<UpdateThreadLabelsResult, EmailErr> {
+ self.update_thread_labels_impl(access_token, link, thread_id, label_id, add)
+ .await
+ }
}
diff --git a/rust/cloud-storage/email/src/domain/service/previews.rs b/rust/cloud-storage/email/src/domain/service/previews.rs
index 6785b1141e..77e22d0745 100644
--- a/rust/cloud-storage/email/src/domain/service/previews.rs
+++ b/rust/cloud-storage/email/src/domain/service/previews.rs
@@ -16,7 +16,7 @@ use uuid::Uuid;
use super::EmailServiceImpl;
-impl<T, U, E> EmailServiceImpl<T, U, E>
+impl<T, U, E, G> EmailServiceImpl<T, U, E, G>
where
T: EmailRepo,
U: FrecencyQueryService,
diff --git a/rust/cloud-storage/email/src/domain/service/send.rs b/rust/cloud-storage/email/src/domain/service/send.rs
index 13b281ce0c..1c07c0863a 100644
--- a/rust/cloud-storage/email/src/domain/service/send.rs
+++ b/rust/cloud-storage/email/src/domain/service/send.rs
@@ -8,7 +8,7 @@ use frecency::domain::ports::FrecencyQueryService;
use super::EmailServiceImpl;
-impl<T, U, E> EmailServiceImpl<T, U, E>
+impl<T, U, E, G> EmailServiceImpl<T, U, E, G>
where
T: EmailRepo,
U: FrecencyQueryService,
diff --git a/rust/cloud-storage/email/src/domain/service/thread.rs b/rust/cloud-storage/email/src/domain/service/thread.rs
index 08e47a6947..008a877d89 100644
--- a/rust/cloud-storage/email/src/domain/service/thread.rs
+++ b/rust/cloud-storage/email/src/domain/service/thread.rs
@@ -11,7 +11,7 @@ use uuid::Uuid;
use super::EmailServiceImpl;
-impl<T, U, E> EmailServiceImpl<T, U, E>
+impl<T, U, E, G> EmailServiceImpl<T, U, E, G>
where
T: EmailRepo,
U: FrecencyQueryService,
diff --git a/rust/cloud-storage/email/src/domain/service/thread_labels.rs b/rust/cloud-storage/email/src/domain/service/thread_labels.rs
new file mode 100644
index 0000000000..d436531344
--- /dev/null
+++ b/rust/cloud-storage/email/src/domain/service/thread_labels.rs
@@ -0,0 +1,149 @@
+use crate::domain::{
+ models::{EmailErr, Link, UpdateThreadLabelsResult, label::system_labels},
+ ports::{EmailMessageEnqueuer, EmailRepo, GmailLabelModifier},
+};
+use frecency::domain::ports::FrecencyQueryService;
+use futures::{StreamExt, stream};
+use uuid::Uuid;
+
+use super::EmailServiceImpl;
+
+impl<T, U, E, G> EmailServiceImpl<T, U, E, G>
+where
+ T: EmailRepo,
+ U: FrecencyQueryService,
+ E: EmailMessageEnqueuer,
+ G: GmailLabelModifier,
+ anyhow::Error: From<T::Err>,
+{
+ #[tracing::instrument(err, skip(self, access_token, link))]
+ pub(crate) async fn update_thread_labels_impl(
+ &self,
+ access_token: &str,
+ link: &Link,
+ thread_id: Uuid,
+ label_id: Uuid,
+ add: bool,
+ ) -> Result<UpdateThreadLabelsResult, EmailErr> {
+ let label = self
+ .email_repo
+ .get_label_by_id(label_id, link.id)
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?
+ .ok_or(EmailErr::LabelNotFound)?;
+
+ let messages = self
+ .email_repo
+ .get_thread_label_messages(thread_id, link.id)
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?;
+
+ if messages.is_empty() {
+ return Err(EmailErr::ThreadEmpty);
+ }
+
+ let provider_label_id = label.provider_label_id.clone();
+
+ if provider_label_id.is_empty() {
+ return Err(EmailErr::EmptyProviderLabelId);
+ }
+
+ // Fan out Gmail API calls with limited concurrency.
+ // Take a reference to the modifier outside the loop so each future
+ // only borrows the modifier (not all of `self`), allowing true
+ // concurrent polling via buffer_unordered.
+ const MAX_CONCURRENT: usize = 10;
+ let modifier = &self.gmail_label_modifier;
+ let mut join_handles = Vec::with_capacity(messages.len());
+ for msg in &messages {
+ let db_id = msg.db_id;
+ // don't modify messages without provider_ids (drafts)
+ let provider_msg_id = match &msg.provider_id {
+ Some(id) if !id.is_empty() => id.clone(),
+ _ => {
+ continue;
+ }
+ };
+ let plid = provider_label_id.clone();
+ let token = access_token.to_owned();
+ let (to_add, to_remove) = if add {
+ (vec![plid], vec![])
+ } else {
+ (vec![], vec![plid])
+ };
+ join_handles.push(async move {
+ let result = modifier
+ .modify_message_labels(&token, &provider_msg_id, &to_add, &to_remove)
+ .await;
+ (db_id, result)
+ });
+ }
+
+ let results: Vec<_> = stream::iter(join_handles)
+ .buffer_unordered(MAX_CONCURRENT)
+ .collect()
+ .await;
+
+ let mut successful_ids = Vec::new();
+ let mut failed_ids = Vec::new();
+
+ for (msg_id, result) in results {
+ match result {
+ Ok(()) => successful_ids.push(msg_id),
+ Err(e) => {
+ tracing::error!(error=?e, message_id=%msg_id, "failed to modify labels in Gmail");
+ failed_ids.push(msg_id);
+ }
+ }
+ }
+
+ // Bulk DB update for successful messages
+ if !successful_ids.is_empty() {
+ let db_result = if add {
+ self.email_repo
+ .insert_message_labels_batch(&successful_ids, &provider_label_id, link.id)
+ .await
+ } else {
+ self.email_repo
+ .delete_message_labels_batch(&successful_ids, &provider_label_id, link.id)
+ .await
+ };
+
+ if let Err(e) = db_result {
+ let err = anyhow::Error::from(e);
+ tracing::error!(error=?err, "failed to update message labels in database");
+ failed_ids.append(&mut successful_ids);
+ }
+ }
+
+ // Side effects for system labels
+ if !successful_ids.is_empty() {
+ if provider_label_id == system_labels::UNREAD {
+ if let Err(e) = self
+ .email_repo
+ .update_message_read_status_batch(&successful_ids, link.id, !add)
+ .await
+ {
+ let err = anyhow::Error::from(e);
+ tracing::error!(error=?err, "failed to update message read status");
+ }
+ } else if provider_label_id == system_labels::STARRED
+ && let Err(e) = self
+ .email_repo
+ .update_message_starred_status_batch(&successful_ids, link.id, add)
+ .await
+ {
+ let err = anyhow::Error::from(e);
+ tracing::error!(error=?err, "failed to update message starred status");
+ }
+ }
+
+ successful_ids.sort();
+ failed_ids.sort();
+
+ Ok(UpdateThreadLabelsResult {
+ successful_ids,
+ failed_ids,
+ })
+ }
+}
diff --git a/rust/cloud-storage/email/src/inbound/axum.rs b/rust/cloud-storage/email/src/inbound/axum.rs
index 21653ba277..b52c01d9ee 100644
--- a/rust/cloud-storage/email/src/inbound/axum.rs
+++ b/rust/cloud-storage/email/src/inbound/axum.rs
@@ -4,6 +4,7 @@ mod draft_router;
mod get_thread_router;
mod previews_router;
mod send_router;
+mod thread_labels_router;
pub use api_types::*;
pub use axum_impls::*;
@@ -11,3 +12,4 @@ pub use draft_router::*;
pub use get_thread_router::*;
pub use previews_router::*;
pub use send_router::*;
+pub use thread_labels_router::*;
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 0d8aeb8b81..a51efe9f27 100644
--- a/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs
@@ -13,6 +13,8 @@ use axum::{
};
use axum_extra::extract::Cached;
use model_user::axum_extractor::{MacroUserExtractor, UserExtractorErr};
+use std::future::Future;
+use std::sync::Arc;
use std::{marker::PhantomData, str::FromStr};
use thiserror::Error;
use utoipa::{IntoParams, ToSchema};
@@ -156,3 +158,103 @@ where
Ok(Self(res, PhantomData))
}
}
+
+/// Port for fetching a Gmail access token for a given link.
+///
+/// This is an inbound concern — the domain service receives the token as an
+/// opaque `&str`. The trait lives here (rather than in `domain::ports`)
+/// because only the axum extractor layer uses it.
+pub trait GmailTokenProvider: Send + Sync + 'static {
+ /// Fetch a Gmail OAuth access token for the given email link.
+ fn fetch_gmail_access_token(
+ &self,
+ link: &Link,
+ ) -> impl Future<Output = Result<String, EmailErr>> + Send;
+}
+
+/// Axum state wrapper for a [`GmailTokenProvider`] implementation.
+pub struct GmailTokenState<T> {
+ pub(crate) inner: Arc<T>,
+}
+
+impl<T> Clone for GmailTokenState<T> {
+ fn clone(&self) -> Self {
+ Self {
+ inner: Arc::clone(&self.inner),
+ }
+ }
+}
+
+impl<T> GmailTokenState<T> {
+ /// Create a new `GmailTokenState` wrapping the given provider.
+ pub fn new(provider: T) -> Self {
+ Self {
+ inner: Arc::new(provider),
+ }
+ }
+}
+
+/// Extractor that resolves the user's email link and fetches a Gmail access token.
+pub struct GmailAccessTokenExtractor<U, V> {
+ /// The fetched Gmail OAuth access token.
+ pub access_token: String,
+ /// The email link used to fetch the token.
+ pub link: Link,
+ _phantom: PhantomData<(U, V)>,
+}
+
+/// Errors from [`GmailAccessTokenExtractor`].
+#[derive(Debug, Error)]
+pub enum GmailAccessTokenErr {
+ /// Failed to resolve the email link.
+ #[error(transparent)]
+ Link(#[from] EmailLinkErr),
+ /// Failed to fetch the Gmail access token.
+ #[error("Failed to fetch Gmail access token")]
+ TokenFetch(#[source] EmailErr),
+}
+
+impl IntoResponse for GmailAccessTokenErr {
+ fn into_response(self) -> Response {
+ match self {
+ GmailAccessTokenErr::Link(e) => e.into_response(),
+ GmailAccessTokenErr::TokenFetch(e) => {
+ tracing::error!(error=?e, "gmail token fetch error");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "Failed to fetch Gmail access token",
+ )
+ .into_response()
+ }
+ }
+ }
+}
+
+#[async_trait]
+impl<S, U, V> FromRequestParts<S> for GmailAccessTokenExtractor<U, V>
+where
+ EmailRouterState<U>: FromRef<S>,
+ GmailTokenState<V>: FromRef<S>,
+ U: EmailService,
+ V: GmailTokenProvider,
+ S: Send + Sync + 'static,
+{
+ type Rejection = GmailAccessTokenErr;
+
+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ let Cached(EmailLinkExtractor(link, _)) = parts
+ .extract_with_state::<Cached<EmailLinkExtractor<U>>, S>(state)
+ .await?;
+ let token_state = <GmailTokenState<V>>::from_ref(state);
+ let token = token_state
+ .inner
+ .fetch_gmail_access_token(&link)
+ .await
+ .map_err(GmailAccessTokenErr::TokenFetch)?;
+ Ok(Self {
+ access_token: token,
+ link,
+ _phantom: PhantomData,
+ })
+ }
+}
diff --git a/rust/cloud-storage/email/src/inbound/axum/draft_router.rs b/rust/cloud-storage/email/src/inbound/axum/draft_router.rs
index e87b2b71b9..23768f088b 100644
--- a/rust/cloud-storage/email/src/inbound/axum/draft_router.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/draft_router.rs
@@ -60,7 +60,7 @@ impl From<EmailErr> for CreateDraftError {
| EmailErr::CannotReplyToDraft
| EmailErr::Base64DecodeError(_)
| EmailErr::Utf8Error(_) => CreateDraftError::Validation(err.to_string()),
- EmailErr::RepoErr(_) | EmailErr::Frecency(_) => CreateDraftError::Internal(err),
+ _ => CreateDraftError::Internal(err),
}
}
}
diff --git a/rust/cloud-storage/email/src/inbound/axum/send_router.rs b/rust/cloud-storage/email/src/inbound/axum/send_router.rs
index 61c7b0e22e..5e5f69f609 100644
--- a/rust/cloud-storage/email/src/inbound/axum/send_router.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/send_router.rs
@@ -60,7 +60,7 @@ impl From<EmailErr> for SendMessageError {
| EmailErr::CannotReplyToDraft
| EmailErr::Base64DecodeError(_)
| EmailErr::Utf8Error(_) => SendMessageError::Validation(err.to_string()),
- EmailErr::RepoErr(_) | EmailErr::Frecency(_) => SendMessageError::Internal(err),
+ _ => SendMessageError::Internal(err),
}
}
}
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
new file mode 100644
index 0000000000..aff27091bd
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound/axum/thread_labels_router.rs
@@ -0,0 +1,124 @@
+use axum::{
+ Json, Router,
+ extract::{Path, State},
+ http::StatusCode,
+ response::IntoResponse,
+ routing::patch,
+};
+use model_error_response::ErrorResponse;
+use thiserror::Error;
+use uuid::Uuid;
+
+use crate::domain::{models::EmailErr, ports::EmailService};
+
+use super::{EmailRouterState, GmailAccessTokenExtractor, GmailTokenProvider, GmailTokenState};
+
+/// Request body for updating a thread's labels.
+#[derive(serde::Serialize, serde::Deserialize, Debug, utoipa::ToSchema)]
+pub struct UpdateThreadLabelRequest {
+ pub label_id: Uuid,
+ pub value: bool,
+}
+
+/// Response body for updating a thread's labels.
+#[derive(serde::Serialize, serde::Deserialize, Debug, utoipa::ToSchema)]
+pub struct UpdateThreadLabelsResponse {
+ pub successful_ids: Vec<Uuid>,
+ pub failed_ids: Vec<Uuid>,
+}
+
+/// Errors from the update thread labels handler.
+#[derive(Debug, Error)]
+pub enum UpdateThreadLabelError {
+ /// Validation / bad request.
+ #[error("{0}")]
+ Validation(String),
+ /// Not found.
+ #[error("{0}")]
+ NotFound(String),
+ /// Internal error.
+ #[error("Internal error")]
+ Internal(EmailErr),
+}
+
+impl IntoResponse for UpdateThreadLabelError {
+ fn into_response(self) -> axum::response::Response {
+ if matches!(self, UpdateThreadLabelError::Internal(_)) {
+ tracing::error!(error=?self, "update thread labels error");
+ }
+
+ let status = match &self {
+ UpdateThreadLabelError::Validation(_) => StatusCode::BAD_REQUEST,
+ UpdateThreadLabelError::NotFound(_) => StatusCode::NOT_FOUND,
+ UpdateThreadLabelError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+
+ let message = self.to_string();
+ (status, Json(ErrorResponse { message: &message })).into_response()
+ }
+}
+
+impl From<EmailErr> for UpdateThreadLabelError {
+ fn from(err: EmailErr) -> Self {
+ match &err {
+ EmailErr::LabelNotFound => UpdateThreadLabelError::NotFound(err.to_string()),
+ EmailErr::ThreadEmpty => UpdateThreadLabelError::NotFound(err.to_string()),
+ EmailErr::EmptyProviderLabelId => UpdateThreadLabelError::Validation(err.to_string()),
+ _ => UpdateThreadLabelError::Internal(err),
+ }
+ }
+}
+
+/// Create the thread labels router with a `PATCH /:id/labels` handler.
+pub fn thread_labels_router<S, T, G>() -> Router<S>
+where
+ S: Send + Sync + Clone + 'static,
+ T: EmailService,
+ G: GmailTokenProvider,
+ EmailRouterState<T>: axum::extract::FromRef<S>,
+ GmailTokenState<G>: axum::extract::FromRef<S>,
+{
+ Router::new().route("/:id/labels", patch(update_thread_labels_handler::<T, G>))
+}
+
+/// Add or remove a label from all messages in a thread.
+#[utoipa::path(
+ patch,
+ tag = "Threads",
+ path = "/email/threads/{id}/labels",
+ operation_id = "add_remove_thread_label",
+ request_body = UpdateThreadLabelRequest,
+ params(
+ ("id" = Uuid, Path, description = "Thread ID."),
+ ),
+ responses(
+ (status = 200, body = UpdateThreadLabelsResponse),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(err, skip(state, gmail_extractor, body))]
+pub async fn update_thread_labels_handler<T: EmailService, G: GmailTokenProvider>(
+ State(state): State<EmailRouterState<T>>,
+ gmail_extractor: GmailAccessTokenExtractor<T, G>,
+ Path(thread_id): Path<Uuid>,
+ Json(body): Json<UpdateThreadLabelRequest>,
+) -> Result<Json<UpdateThreadLabelsResponse>, UpdateThreadLabelError> {
+ let result = state
+ .inner
+ .update_thread_labels(
+ &gmail_extractor.access_token,
+ &gmail_extractor.link,
+ thread_id,
+ body.label_id,
+ body.value,
+ )
+ .await?;
+
+ Ok(Json(UpdateThreadLabelsResponse {
+ successful_ids: result.successful_ids,
+ failed_ids: result.failed_ids,
+ }))
+}
diff --git a/rust/cloud-storage/email/src/outbound.rs b/rust/cloud-storage/email/src/outbound.rs
index fffc16f08e..024f329042 100644
--- a/rust/cloud-storage/email/src/outbound.rs
+++ b/rust/cloud-storage/email/src/outbound.rs
@@ -1,3 +1,11 @@
mod email_pg_repo;
+#[cfg(feature = "gmail_token")]
+mod gmail_label_modifier;
+#[cfg(feature = "gmail_token")]
+mod gmail_token_provider;
pub use email_pg_repo::*;
+#[cfg(feature = "gmail_token")]
+pub use gmail_label_modifier::*;
+#[cfg(feature = "gmail_token")]
+pub use gmail_token_provider::*;
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/label.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/label.rs
new file mode 100644
index 0000000000..f2ccc90111
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/label.rs
@@ -0,0 +1,306 @@
+use crate::domain::models::{
+ LabelListVisibility, LabelType, LinkLabel, MessageListVisibility, SimpleMessage,
+};
+use crate::outbound::email_pg_repo::db_types::{
+ LabelListVisibilityDbRow, LabelTypeDbRow, MessageListVisibilityDbRow,
+};
+use chrono::{DateTime, Utc};
+use sqlx::PgPool;
+use uuid::Uuid;
+
+/// DB row for a label looked up by ID.
+struct LinkLabelDbRow {
+ id: Uuid,
+ link_id: Uuid,
+ provider_label_id: String,
+ name: String,
+ created_at: DateTime<Utc>,
+ message_list_visibility: MessageListVisibilityDbRow,
+ label_list_visibility: LabelListVisibilityDbRow,
+ type_: LabelTypeDbRow,
+}
+
+impl From<LinkLabelDbRow> for LinkLabel {
+ fn from(row: LinkLabelDbRow) -> Self {
+ Self {
+ id: row.id,
+ link_id: row.link_id,
+ provider_label_id: row.provider_label_id,
+ name: row.name,
+ created_at: row.created_at,
+ message_list_visibility: match row.message_list_visibility {
+ MessageListVisibilityDbRow::Show => MessageListVisibility::Show,
+ MessageListVisibilityDbRow::Hide => MessageListVisibility::Hide,
+ },
+ label_list_visibility: match row.label_list_visibility {
+ LabelListVisibilityDbRow::LabelShow => LabelListVisibility::LabelShow,
+ LabelListVisibilityDbRow::LabelShowIfUnread => {
+ LabelListVisibility::LabelShowIfUnread
+ }
+ LabelListVisibilityDbRow::LabelHide => LabelListVisibility::LabelHide,
+ },
+ type_: match row.type_ {
+ LabelTypeDbRow::System => LabelType::System,
+ LabelTypeDbRow::User => LabelType::User,
+ },
+ }
+ }
+}
+
+/// DB row for a simplified message in thread label operations.
+struct SimpleMessageDbRow {
+ id: Uuid,
+ provider_id: Option<String>,
+ thread_id: Uuid,
+ provider_thread_id: Option<String>,
+ replying_to_id: Option<Uuid>,
+ global_id: Option<String>,
+ link_id: Uuid,
+ subject: Option<String>,
+ snippet: Option<String>,
+ from_contact_id: Option<Uuid>,
+ provider_history_id: Option<String>,
+ internal_date_ts: Option<DateTime<Utc>>,
+ sent_at: Option<DateTime<Utc>>,
+ size_estimate: Option<i64>,
+ is_read: bool,
+ is_starred: bool,
+ is_sent: bool,
+ is_draft: bool,
+ has_attachments: bool,
+ headers_jsonb: Option<serde_json::Value>,
+ created_at: DateTime<Utc>,
+ updated_at: DateTime<Utc>,
+}
+
+impl From<SimpleMessageDbRow> for SimpleMessage {
+ fn from(row: SimpleMessageDbRow) -> Self {
+ Self {
+ db_id: row.id,
+ provider_id: row.provider_id,
+ thread_db_id: row.thread_id,
+ provider_thread_id: row.provider_thread_id,
+ replying_to_id: row.replying_to_id,
+ global_id: row.global_id,
+ link_id: row.link_id,
+ subject: row.subject,
+ snippet: row.snippet,
+ from_contact_id: row.from_contact_id,
+ provider_history_id: row.provider_history_id,
+ internal_date_ts: row.internal_date_ts,
+ sent_at: row.sent_at,
+ size_estimate: row.size_estimate,
+ is_read: row.is_read,
+ is_starred: row.is_starred,
+ is_sent: row.is_sent,
+ is_draft: row.is_draft,
+ has_attachments: row.has_attachments,
+ headers_json: row.headers_jsonb,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ }
+ }
+}
+
+#[tracing::instrument(skip(pool), err)]
+pub(crate) async fn get_label_by_id(
+ pool: &PgPool,
+ label_id: Uuid,
+ link_id: Uuid,
+) -> Result<Option<LinkLabel>, sqlx::Error> {
+ let row: Option<LinkLabelDbRow> = sqlx::query_as!(
+ LinkLabelDbRow,
+ r#"
+ SELECT
+ id,
+ link_id,
+ provider_label_id,
+ name,
+ created_at,
+ message_list_visibility as "message_list_visibility: _",
+ label_list_visibility as "label_list_visibility: _",
+ type as "type_: _"
+ FROM email_labels
+ WHERE id = $1 AND link_id = $2
+ "#,
+ label_id,
+ link_id
+ )
+ .fetch_optional(pool)
+ .await?;
+
+ Ok(row.map(Into::into))
+}
+
+#[tracing::instrument(skip(pool), err)]
+pub(crate) async fn get_thread_label_messages(
+ pool: &PgPool,
+ thread_id: Uuid,
+ link_id: Uuid,
+) -> Result<Vec<SimpleMessage>, sqlx::Error> {
+ let rows: Vec<SimpleMessageDbRow> = sqlx::query_as!(
+ SimpleMessageDbRow,
+ r#"
+ SELECT
+ m.id,
+ m.provider_id,
+ m.thread_id,
+ m.provider_thread_id,
+ m.replying_to_id,
+ m.global_id,
+ m.link_id,
+ m.subject,
+ m.snippet,
+ m.from_contact_id,
+ m.provider_history_id,
+ m.internal_date_ts,
+ m.sent_at,
+ m.size_estimate,
+ m.is_read,
+ m.is_starred,
+ m.is_sent,
+ m.is_draft,
+ m.has_attachments,
+ m.headers_jsonb,
+ m.created_at,
+ m.updated_at
+ FROM email_messages m
+ WHERE m.thread_id = $1 AND m.link_id = $2
+ ORDER BY m.internal_date_ts DESC NULLS LAST
+ "#,
+ thread_id,
+ link_id
+ )
+ .fetch_all(pool)
+ .await?;
+
+ Ok(rows.into_iter().map(Into::into).collect())
+}
+
+#[tracing::instrument(skip(pool), err)]
+pub(crate) async fn insert_message_labels_batch(
+ pool: &PgPool,
+ message_ids: &[Uuid],
+ provider_label_id: &str,
+ link_id: Uuid,
+) -> Result<(), sqlx::Error> {
+ if message_ids.is_empty() {
+ return Ok(());
+ }
+
+ sqlx::query!(
+ r#"
+ INSERT INTO email_message_labels (message_id, label_id)
+ SELECT
+ unnested_message_id,
+ l.id
+ FROM
+ UNNEST($1::uuid[]) AS t(unnested_message_id)
+ CROSS JOIN
+ email_labels l
+ WHERE
+ l.link_id = $2 AND l.provider_label_id = $3
+ ON CONFLICT (message_id, label_id) DO NOTHING
+ "#,
+ message_ids,
+ link_id,
+ provider_label_id
+ )
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
+#[tracing::instrument(skip(pool), err)]
+pub(crate) async fn delete_message_labels_batch(
+ pool: &PgPool,
+ message_ids: &[Uuid],
+ provider_label_id: &str,
+ link_id: Uuid,
+) -> Result<(), sqlx::Error> {
+ if message_ids.is_empty() {
+ return Ok(());
+ }
+
+ sqlx::query!(
+ r#"
+ DELETE FROM email_message_labels
+ WHERE
+ message_id = ANY($1)
+ AND label_id = (
+ SELECT id FROM email_labels
+ WHERE link_id = $2 AND provider_label_id = $3
+ )
+ "#,
+ message_ids,
+ link_id,
+ provider_label_id
+ )
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
+#[tracing::instrument(skip(pool), err)]
+pub(crate) async fn update_message_read_status_batch(
+ pool: &PgPool,
+ message_ids: &[Uuid],
+ link_id: Uuid,
+ is_read: bool,
+) -> Result<(), sqlx::Error> {
+ if message_ids.is_empty() {
+ return Ok(());
+ }
+
+ sqlx::query!(
+ r#"
+ UPDATE email_messages m
+ SET
+ is_read = $1,
+ updated_at = NOW()
+ WHERE
+ m.id = ANY($2)
+ AND m.link_id = $3
+ "#,
+ is_read,
+ message_ids,
+ link_id
+ )
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
+#[tracing::instrument(skip(pool), err)]
+pub(crate) async fn update_message_starred_status_batch(
+ pool: &PgPool,
+ message_ids: &[Uuid],
+ link_id: Uuid,
+ is_starred: bool,
+) -> Result<(), sqlx::Error> {
+ if message_ids.is_empty() {
+ return Ok(());
+ }
+
+ sqlx::query!(
+ r#"
+ UPDATE email_messages m
+ SET
+ is_starred = $1,
+ updated_at = NOW()
+ WHERE
+ m.id = ANY($2)
+ AND m.link_id = $3
+ "#,
+ is_starred,
+ message_ids,
+ link_id
+ )
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
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 6a8d5c653e..82813adb48 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
@@ -1,9 +1,9 @@
use crate::domain::{
models::{
Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, EmailThreadPreview,
- Label, Link, MessageAttachment, MessageLabel, MessageRow, ParsedAddresses,
- PreviewCursorQuery, ResolvedDraftInput, SimpleMessageInfo, ThreadRow, UpsertedContacts,
- UserProvider,
+ Label, Link, LinkLabel, MessageAttachment, MessageLabel, MessageRow, ParsedAddresses,
+ PreviewCursorQuery, ResolvedDraftInput, SimpleMessage, SimpleMessageInfo, ThreadRow,
+ UpsertedContacts, UserProvider,
},
ports::{EmailRepo, RecipientsByMessageId},
};
@@ -17,6 +17,7 @@ mod contact;
mod db_types;
mod draft;
mod dynamic;
+mod label;
mod link;
mod message;
mod preview;
@@ -169,4 +170,59 @@ impl EmailRepo for EmailPgRepo {
) -> Result<(), Self::Err> {
draft::insert_message(&self.pool, input, contacts, link_id, new_thread, is_draft).await
}
+
+ async fn get_label_by_id(
+ &self,
+ label_id: Uuid,
+ link_id: Uuid,
+ ) -> Result<Option<LinkLabel>, Self::Err> {
+ label::get_label_by_id(&self.pool, label_id, link_id).await
+ }
+
+ async fn get_thread_label_messages(
+ &self,
+ thread_id: Uuid,
+ link_id: Uuid,
+ ) -> Result<Vec<SimpleMessage>, Self::Err> {
+ label::get_thread_label_messages(&self.pool, thread_id, link_id).await
+ }
+
+ async fn insert_message_labels_batch(
+ &self,
+ message_ids: &[Uuid],
+ provider_label_id: &str,
+ link_id: Uuid,
+ ) -> Result<(), Self::Err> {
+ label::insert_message_labels_batch(&self.pool, message_ids, provider_label_id, link_id)
+ .await
+ }
+
+ async fn delete_message_labels_batch(
+ &self,
+ message_ids: &[Uuid],
+ provider_label_id: &str,
+ link_id: Uuid,
+ ) -> Result<(), Self::Err> {
+ label::delete_message_labels_batch(&self.pool, message_ids, provider_label_id, link_id)
+ .await
+ }
+
+ async fn update_message_read_status_batch(
+ &self,
+ message_ids: &[Uuid],
+ link_id: Uuid,
+ is_read: bool,
+ ) -> Result<(), Self::Err> {
+ label::update_message_read_status_batch(&self.pool, message_ids, link_id, is_read).await
+ }
+
+ async fn update_message_starred_status_batch(
+ &self,
+ message_ids: &[Uuid],
+ link_id: Uuid,
+ is_starred: bool,
+ ) -> Result<(), Self::Err> {
+ label::update_message_starred_status_batch(&self.pool, message_ids, link_id, is_starred)
+ .await
+ }
}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs
index fba3abc412..43642494a7 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs
@@ -5,6 +5,7 @@ mod link;
mod message;
mod preview;
mod thread;
+mod thread_labels;
use std::sync::Arc;
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/thread_labels.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/thread_labels.rs
new file mode 100644
index 0000000000..25f955e468
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/thread_labels.rs
@@ -0,0 +1,441 @@
+use super::*;
+use crate::domain::models::{LabelListVisibility, LabelType, MessageListVisibility};
+
+// ── get_label_by_id ─────────────────────────────────────────────────
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn test_get_label_by_id_found(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let label_id = Uuid::parse_str("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")?;
+
+ let label = repo.get_label_by_id(label_id, link_id).await?;
+ assert!(label.is_some(), "Label should be found");
+
+ let label = label.unwrap();
+ assert_eq!(label.id, label_id);
+ assert_eq!(label.link_id, link_id);
+ assert_eq!(label.provider_label_id, "INBOX");
+ assert_eq!(label.name, "INBOX");
+ assert_eq!(label.message_list_visibility, MessageListVisibility::Show);
+ assert_eq!(label.label_list_visibility, LabelListVisibility::LabelShow);
+ assert_eq!(label.type_, LabelType::System);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn test_get_label_by_id_user_label(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let label_id = Uuid::parse_str("eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee")?;
+
+ let label = repo.get_label_by_id(label_id, link_id).await?;
+ assert!(label.is_some());
+
+ let label = label.unwrap();
+ assert_eq!(label.provider_label_id, "Label_123");
+ assert_eq!(label.name, "MyCustomLabel");
+ assert_eq!(label.type_, LabelType::User);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn test_get_label_by_id_wrong_link(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+ // Label belongs to link aaa..., but we look it up with link bbb...
+ let label_id = Uuid::parse_str("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")?;
+ let wrong_link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-bbbbbbbbbbbb")?;
+
+ let label = repo.get_label_by_id(label_id, wrong_link_id).await?;
+ assert!(label.is_none(), "Label should not be found for wrong link");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn test_get_label_by_id_not_found(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let nonexistent = Uuid::parse_str("99999999-9999-9999-9999-999999999999")?;
+
+ let label = repo.get_label_by_id(nonexistent, link_id).await?;
+ assert!(label.is_none());
+
+ Ok(())
+}
+
+// ── get_thread_label_messages ───────────────────────────────────────
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn test_get_thread_label_messages(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let thread_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
+
+ let messages = repo.get_thread_label_messages(thread_id, link_id).await?;
+ assert_eq!(messages.len(), 2, "Thread 1 should have 2 messages");
+
+ // Ordered by internal_date_ts DESC, so msg1b (11:00) comes first
+ assert_eq!(messages[0].provider_id.as_deref(), Some("msg1b"));
+ assert_eq!(messages[1].provider_id.as_deref(), Some("msg1a"));
+
+ // Verify fields are populated
+ assert_eq!(messages[0].thread_db_id, thread_id);
+ assert_eq!(messages[0].link_id, link_id);
+ assert!(!messages[0].is_read);
+ assert!(!messages[0].is_starred);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn test_get_thread_label_messages_empty_thread(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ // Thread 2 exists but has no messages
+ let thread_id = Uuid::parse_str("22222222-2222-2222-2222-222222222222")?;
+
+ let messages = repo.get_thread_label_messages(thread_id, link_id).await?;
+ assert!(
+ messages.is_empty(),
+ "Thread with no messages should return empty"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn test_get_thread_label_messages_wrong_link(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+ let wrong_link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-bbbbbbbbbbbb")?;
+ let thread_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
+
+ let messages = repo
+ .get_thread_label_messages(thread_id, wrong_link_id)
+ .await?;
+ assert!(
+ messages.is_empty(),
+ "Should not return messages for wrong link"
+ );
+
+ Ok(())
+}
+
+// ── insert_message_labels_batch ─────────────────────────────────────
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn test_insert_message_labels_batch(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool.clone());
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let msg1a = Uuid::parse_str("11111111-aaaa-aaaa-aaaa-111111111111")?;
+ let msg1b = Uuid::parse_str("11111111-bbbb-bbbb-bbbb-111111111111")?;
+ let unread_label_id = Uuid::parse_str("cccccccc-cccc-cccc-cccc-cccccccccccc")?;
+
+ // Add UNREAD label to both messages
+ repo.insert_message_labels_batch(&[msg1a, msg1b], "UNREAD", link_id)
+ .await?;
+
+ let count: i64 = sqlx::query_scalar(
+ "SELECT COUNT(*) FROM email_message_labels WHERE label_id = $1 AND message_id = ANY($2)",
+ )
+ .bind(unread_label_id)
+ .bind(&[msg1a, msg1b])
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(count, 2, "Both messages should have the UNREAD label");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn test_insert_message_labels_batch_idempotent(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool.clone());
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let msg1a = Uuid::parse_str("11111111-aaaa-aaaa-aaaa-111111111111")?;
+
+ // msg1a already has INBOX label from fixture — inserting again should not error
+ repo.insert_message_labels_batch(&[msg1a], "INBOX", link_id)
+ .await?;
+
+ let count: i64 = sqlx::query_scalar(
+ "SELECT COUNT(*) FROM email_message_labels WHERE message_id = $1 AND label_id = $2",
+ )
+ .bind(msg1a)
+ .bind(Uuid::parse_str("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")?)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(
+ count, 1,
+ "Should still be exactly 1 row (ON CONFLICT DO NOTHING)"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn test_insert_message_labels_batch_empty(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+
+ // Should be a no-op, not an error
+ repo.insert_message_labels_batch(&[], "INBOX", link_id)
+ .await?;
+
+ Ok(())
+}
+
+// ── delete_message_labels_batch ─────────────────────────────────────
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn test_delete_message_labels_batch(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool.clone());
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let msg1a = Uuid::parse_str("11111111-aaaa-aaaa-aaaa-111111111111")?;
+ let msg1b = Uuid::parse_str("11111111-bbbb-bbbb-bbbb-111111111111")?;
+ let inbox_label_id = Uuid::parse_str("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")?;
+
+ // Both messages have INBOX label from fixture
+ repo.delete_message_labels_batch(&[msg1a, msg1b], "INBOX", link_id)
+ .await?;
+
+ let count: i64 = sqlx::query_scalar(
+ "SELECT COUNT(*) FROM email_message_labels WHERE label_id = $1 AND message_id = ANY($2)",
+ )
+ .bind(inbox_label_id)
+ .bind(&[msg1a, msg1b])
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(count, 0, "INBOX label should be removed from both messages");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn test_delete_message_labels_batch_nonexistent(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let msg1a = Uuid::parse_str("11111111-aaaa-aaaa-aaaa-111111111111")?;
+
+ // Messages don't have UNREAD label — should be a no-op
+ repo.delete_message_labels_batch(&[msg1a], "UNREAD", link_id)
+ .await?;
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn test_delete_message_labels_batch_empty(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+
+ repo.delete_message_labels_batch(&[], "INBOX", link_id)
+ .await?;
+
+ Ok(())
+}
+
+// ── update_message_read_status_batch ────────────────────────────────
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn test_update_message_read_status_batch_mark_read(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool.clone());
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let msg1a = Uuid::parse_str("11111111-aaaa-aaaa-aaaa-111111111111")?;
+ let msg1b = Uuid::parse_str("11111111-bbbb-bbbb-bbbb-111111111111")?;
+
+ // Both messages start as unread (is_read=false in fixture)
+ repo.update_message_read_status_batch(&[msg1a, msg1b], link_id, true)
+ .await?;
+
+ let rows: Vec<bool> =
+ sqlx::query_scalar("SELECT is_read FROM email_messages WHERE id = ANY($1) ORDER BY id")
+ .bind(&[msg1a, msg1b])
+ .fetch_all(&pool)
+ .await?;
+ assert!(
+ rows.iter().all(|&r| r),
+ "All messages should be marked as read"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn test_update_message_read_status_batch_wrong_link(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool.clone());
+ let wrong_link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-bbbbbbbbbbbb")?;
+ let msg1a = Uuid::parse_str("11111111-aaaa-aaaa-aaaa-111111111111")?;
+
+ // Should not update — message belongs to a different link
+ repo.update_message_read_status_batch(&[msg1a], wrong_link_id, true)
+ .await?;
+
+ let is_read: bool = sqlx::query_scalar("SELECT is_read FROM email_messages WHERE id = $1")
+ .bind(msg1a)
+ .fetch_one(&pool)
+ .await?;
+ assert!(!is_read, "Message should remain unread (wrong link_id)");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn test_update_message_read_status_batch_empty(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+
+ repo.update_message_read_status_batch(&[], link_id, true)
+ .await?;
+
+ Ok(())
+}
+
+// ── update_message_starred_status_batch ─────────────────────────────
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn test_update_message_starred_status_batch_star(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool.clone());
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let msg1a = Uuid::parse_str("11111111-aaaa-aaaa-aaaa-111111111111")?;
+ let msg1b = Uuid::parse_str("11111111-bbbb-bbbb-bbbb-111111111111")?;
+
+ // Both messages start as not starred (is_starred=false in fixture)
+ repo.update_message_starred_status_batch(&[msg1a, msg1b], link_id, true)
+ .await?;
+
+ let rows: Vec<bool> =
+ sqlx::query_scalar("SELECT is_starred FROM email_messages WHERE id = ANY($1) ORDER BY id")
+ .bind(&[msg1a, msg1b])
+ .fetch_all(&pool)
+ .await?;
+ assert!(rows.iter().all(|&s| s), "All messages should be starred");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn test_update_message_starred_status_batch_unstar(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool.clone());
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let msg1a = Uuid::parse_str("11111111-aaaa-aaaa-aaaa-111111111111")?;
+
+ // Star first, then unstar
+ repo.update_message_starred_status_batch(&[msg1a], link_id, true)
+ .await?;
+ repo.update_message_starred_status_batch(&[msg1a], link_id, false)
+ .await?;
+
+ let is_starred: bool =
+ sqlx::query_scalar("SELECT is_starred FROM email_messages WHERE id = $1")
+ .bind(msg1a)
+ .fetch_one(&pool)
+ .await?;
+ assert!(!is_starred, "Message should be unstarred");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn test_update_message_starred_status_batch_wrong_link(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool.clone());
+ let wrong_link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-bbbbbbbbbbbb")?;
+ let msg1a = Uuid::parse_str("11111111-aaaa-aaaa-aaaa-111111111111")?;
+
+ repo.update_message_starred_status_batch(&[msg1a], wrong_link_id, true)
+ .await?;
+
+ let is_starred: bool =
+ sqlx::query_scalar("SELECT is_starred FROM email_messages WHERE id = $1")
+ .bind(msg1a)
+ .fetch_one(&pool)
+ .await?;
+ assert!(
+ !is_starred,
+ "Message should remain unstarred (wrong link_id)"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn test_update_message_starred_status_batch_empty(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+
+ repo.update_message_starred_status_batch(&[], link_id, true)
+ .await?;
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email/src/outbound/gmail_label_modifier.rs b/rust/cloud-storage/email/src/outbound/gmail_label_modifier.rs
new file mode 100644
index 0000000000..d1608b2375
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/gmail_label_modifier.rs
@@ -0,0 +1,36 @@
+use std::sync::Arc;
+
+use crate::domain::{models::EmailErr, ports::GmailLabelModifier};
+
+/// Adapter implementing [`GmailLabelModifier`] via the Gmail API client.
+#[derive(Clone)]
+pub struct GmailClientLabelModifier {
+ gmail_client: Arc<gmail_client::GmailClient>,
+}
+
+impl GmailClientLabelModifier {
+ /// Create a new modifier wrapping the given Gmail client.
+ pub fn new(gmail_client: Arc<gmail_client::GmailClient>) -> Self {
+ Self { gmail_client }
+ }
+}
+
+impl GmailLabelModifier for GmailClientLabelModifier {
+ async fn modify_message_labels(
+ &self,
+ access_token: &str,
+ provider_message_id: &str,
+ label_ids_to_add: &[String],
+ label_ids_to_remove: &[String],
+ ) -> Result<(), EmailErr> {
+ self.gmail_client
+ .modify_message_labels(
+ access_token,
+ provider_message_id,
+ label_ids_to_add,
+ label_ids_to_remove,
+ )
+ .await
+ .map_err(EmailErr::ProviderErr)
+ }
+}
diff --git a/rust/cloud-storage/email/src/outbound/gmail_token_provider.rs b/rust/cloud-storage/email/src/outbound/gmail_token_provider.rs
new file mode 100644
index 0000000000..79c121d62d
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/gmail_token_provider.rs
@@ -0,0 +1,101 @@
+use anyhow::Context;
+use authentication_service_client::AuthServiceClient;
+use email_utils::token_cache_key::TokenCacheKey;
+use redis::AsyncCommands;
+use redis::aio::MultiplexedConnection;
+use std::sync::Arc;
+
+use crate::domain::models::{EmailErr, Link};
+use crate::inbound::GmailTokenProvider;
+
+/// Ten minutes less than the hour the token is valid for, for long-running jobs.
+static GMAIL_ACCESS_TOKEN_EXPIRY_SECONDS: u64 = 3000;
+
+/// Adapter implementing [`GmailTokenProvider`] using Redis cache with auth service fallback.
+pub struct GmailTokenProviderImpl {
+ redis_conn: MultiplexedConnection,
+ auth_service_client: Arc<AuthServiceClient>,
+}
+
+impl GmailTokenProviderImpl {
+ /// Create a new provider with the given Redis connection and auth service client.
+ ///
+ /// The [`MultiplexedConnection`] is cheap to clone and designed to be shared.
+ pub fn new(
+ redis_conn: MultiplexedConnection,
+ auth_service_client: Arc<AuthServiceClient>,
+ ) -> Self {
+ Self {
+ redis_conn,
+ auth_service_client,
+ }
+ }
+}
+
+impl GmailTokenProvider for GmailTokenProviderImpl {
+ async fn fetch_gmail_access_token(&self, link: &Link) -> Result<String, EmailErr> {
+ let key = TokenCacheKey::new(
+ &link.fusionauth_user_id,
+ link.macro_id.0.as_ref(),
+ link.provider.as_str(),
+ );
+ fetch_gmail_access_token(&key, &self.redis_conn, &self.auth_service_client)
+ .await
+ .map_err(EmailErr::ProviderErr)
+ }
+}
+
+/// Fetches a Gmail access token, first checking the Redis cache then falling back to the auth
+/// service. Caches newly fetched tokens in Redis.
+///
+/// [`MultiplexedConnection`] is cheap to clone internally, so passing a reference is fine.
+pub async fn fetch_gmail_access_token(
+ key: &TokenCacheKey,
+ redis_conn: &MultiplexedConnection,
+ auth_service_client: &AuthServiceClient,
+) -> anyhow::Result<String> {
+ // MultiplexedConnection::clone is just an Arc bump
+ let mut conn = redis_conn.clone();
+ let redis_key = key.to_redis_key();
+
+ let token_from_redis: Option<String> = conn
+ .get(&redis_key)
+ .await
+ .map_err(|e| anyhow::anyhow!("Redis error: {}. TokenCacheKey: {:?}", e, key))
+ .ok()
+ .flatten();
+
+ let access_token = if let Some(token) = token_from_redis {
+ token
+ } else {
+ let fetched_token = auth_service_client
+ .get_google_access_token(&key.fusion_user_id, &key.macro_id)
+ .await
+ .with_context(|| {
+ format!(
+ "Failed to get Google access token from auth service. TokenCacheKey: {:?}",
+ key
+ )
+ })?;
+
+ // Cache newly fetched token
+ if let Err(cache_err) = conn
+ .set_ex::<&str, &str, ()>(
+ &redis_key,
+ &fetched_token.access_token,
+ GMAIL_ACCESS_TOKEN_EXPIRY_SECONDS,
+ )
+ .await
+ {
+ tracing::warn!(
+ error = ?cache_err,
+ token_cache_key = ?key,
+ "Failed to cache fetched access token in Redis"
+ );
+ }
+
+ fetched_token.access_token
+ };
+
+ Ok(access_token)
+}
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.toml
index 92d2952022..4832f43e4a 100644
--- a/rust/cloud-storage/email_service/Cargo.toml
+++ b/rust/cloud-storage/email_service/Cargo.toml
@@ -81,7 +81,7 @@ connection_gateway = { path = "../connection_gateway" }
document_storage_service_client = { path = "../document_storage_service_client" }
doppleganger = { workspace = true }
ego-tree = { workspace = true }
-email = { path = "../email", features = ["axum", "inbound", "outbound"] }
+email = { path = "../email", features = ["axum", "gmail_token", "inbound", "outbound"] }
entity_access = { path = "../entity_access", default-features = false, features = ["outbound"] }
email_db_client = { path = "../email_db_client" }
email_utils = { path = "../email_utils" }
diff --git a/rust/cloud-storage/email_service/src/api/context.rs b/rust/cloud-storage/email_service/src/api/context.rs
index 7e33eefcc4..ef24bdfadd 100644
--- a/rust/cloud-storage/email_service/src/api/context.rs
+++ b/rust/cloud-storage/email_service/src/api/context.rs
@@ -2,9 +2,11 @@ use axum::extract::FromRef;
use document_storage_service_client::DocumentStorageServiceClient;
use email::{
domain::service::EmailServiceImpl,
- inbound::{EmailRouterState, EmailThreadRouterState},
- outbound::EmailPgRepo,
+ inbound::{EmailRouterState, EmailThreadRouterState, GmailTokenState},
+ outbound::{EmailPgRepo, GmailTokenProviderImpl},
};
+
+use email::outbound::GmailClientLabelModifier;
use email_service::config::Config;
use email_service::util::redis::RedisClient;
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
@@ -17,8 +19,12 @@ use std::sync::Arc;
use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};
pub(crate) type EmailEntityAccessService = EntityAccessServiceImpl<PgAccessRepository>;
-type EmailSvc =
- EmailServiceImpl<EmailPgRepo, FrecencyQueryServiceImpl<FrecencyPgStorage>, sqs_client::SQS>;
+pub(crate) type EmailSvc = EmailServiceImpl<
+ EmailPgRepo,
+ FrecencyQueryServiceImpl<FrecencyPgStorage>,
+ sqs_client::SQS,
+ GmailClientLabelModifier,
+>;
#[derive(Clone, FromRef)]
pub(crate) struct ApiContext {
@@ -37,4 +43,5 @@ pub(crate) struct ApiContext {
pub email_service: EmailRouterState<EmailSvc>,
pub entity_access_service: Arc<EmailEntityAccessService>,
pub email_thread_state: EmailThreadRouterState<EmailSvc, EmailEntityAccessService>,
+ pub gmail_token_state: GmailTokenState<GmailTokenProviderImpl>,
}
diff --git a/rust/cloud-storage/email_service/src/api/email/threads/labels.rs b/rust/cloud-storage/email_service/src/api/email/threads/labels.rs
deleted file mode 100644
index 03755519d5..0000000000
--- a/rust/cloud-storage/email_service/src/api/email/threads/labels.rs
+++ /dev/null
@@ -1,141 +0,0 @@
-use crate::api::context::ApiContext;
-use crate::api::email::messages::labels::{
- UpdateLabelBatchResponse, add_label_to_messages, remove_label_from_messages,
-};
-use axum::extract::{Path, State};
-use axum::http::StatusCode;
-use axum::response::{IntoResponse, Response};
-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 strum_macros::AsRefStr;
-use thiserror::Error;
-use utoipa::ToSchema;
-
-#[derive(Debug, Error, AsRefStr)]
-pub enum UpdateThreadLabelError {
- #[error("Label not found")]
- LabelNotFound,
-
- #[error("No messages found for thread")]
- ThreadEmpty,
-
- #[error("Internal error")]
- InternalError(#[from] anyhow::Error),
-}
-
-impl IntoResponse for UpdateThreadLabelError {
- fn into_response(self) -> Response {
- let status_code = match &self {
- UpdateThreadLabelError::LabelNotFound => StatusCode::BAD_REQUEST,
- UpdateThreadLabelError::ThreadEmpty => StatusCode::NOT_FOUND,
- UpdateThreadLabelError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,
- };
-
- (
- status_code,
- Json(ErrorResponse {
- message: self.to_string().as_str(),
- }),
- )
- .into_response()
- }
-}
-
-#[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema)]
-pub struct UpdateThreadLabelRequest {
- pub label_id: Uuid,
- pub value: bool,
-}
-
-/// Add or remove a label from all messages in a thread
-#[utoipa::path(
- patch,
- tag = "Threads",
- path = "/email/threads/{id}/labels",
- operation_id = "add_remove_thread_label",
- request_body = UpdateThreadLabelRequest,
- params(
- ("id" = Uuid, Path, description = "Thread ID."),
- ),
- responses(
- (status = 200, body=UpdateLabelBatchResponse),
- (status = 400, body=ErrorResponse),
- (status = 401, body=ErrorResponse),
- (status = 404, body=ErrorResponse),
- (status = 500, body=ErrorResponse),
- )
-)]
-#[tracing::instrument(skip(ctx, user_context, gmail_token, body), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id), err)]
-pub async fn handler(
- State(ctx): State<ApiContext>,
- user_context: Extension<UserContext>,
- gmail_token: Extension<String>,
- link: Extension<Link>,
- Path(thread_id): Path<Uuid>,
- Json(body): Json<UpdateThreadLabelRequest>,
-) -> Result<Json<UpdateLabelBatchResponse>, UpdateThreadLabelError> {
- let label = email_db_client::labels::get::fetch_label_by_id(&ctx.db, body.label_id, link.id)
- .await?
- .ok_or(UpdateThreadLabelError::LabelNotFound)?;
-
- let db_messages =
- email_db_client::messages::get_simple_messages::get_simple_messages_for_thread(
- &ctx.db, thread_id, link.id,
- )
- .await?;
-
- if db_messages.is_empty() {
- return Err(UpdateThreadLabelError::ThreadEmpty);
- }
-
- let gmail_access_token = gmail_token.as_str();
-
- let (successful_ids, failed_ids) = if body.value {
- add_label_to_messages(
- &ctx.db,
- gmail_access_token,
- &ctx.gmail_client,
- db_messages,
- label.provider_label_id.as_str(),
- )
- .await?
- } else {
- remove_label_from_messages(
- &ctx.db,
- gmail_access_token,
- &ctx.gmail_client,
- db_messages,
- label.provider_label_id.as_str(),
- )
- .await?
- };
-
- // need to update flags on message object for certain labels
- if label.provider_label_id.as_str() == service::label::system_labels::UNREAD {
- email_db_client::messages::update::update_message_read_status_batch(
- &ctx.db,
- successful_ids.clone(),
- &user_context.fusion_user_id,
- !body.value,
- )
- .await?;
- } else if label.provider_label_id.as_str() == service::label::system_labels::STARRED {
- email_db_client::messages::update::update_message_starred_status_batch(
- &ctx.db,
- successful_ids.clone(),
- &user_context.fusion_user_id,
- body.value,
- )
- .await?;
- }
-
- Ok(Json(UpdateLabelBatchResponse {
- successful_ids,
- failed_ids,
- missing_ids: vec![],
- }))
-}
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 6cd74c8033..9caeb57550 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
@@ -1,6 +1,5 @@
pub(crate) mod archived;
pub(crate) mod get;
-pub(crate) mod labels;
pub(crate) mod seen;
use axum::Router;
@@ -32,13 +31,6 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
),
)),
)
- .route(
- "/:id/labels",
- patch(labels::handler).layer(axum::middleware::from_fn_with_state(
- state.clone(),
- crate::api::middleware::gmail_token::attach_gmail_token,
- )),
- )
.layer(axum::middleware::from_fn_with_state(
state.email_service.clone(),
crate::api::middleware::link::attach_link_context,
@@ -46,7 +38,14 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
let hex_thread_routes = email::inbound::thread_router(state.email_thread_state.clone());
+ let hex_thread_labels_routes = email::inbound::thread_labels_router::<
+ ApiContext,
+ crate::api::context::EmailSvc,
+ email::outbound::GmailTokenProviderImpl,
+ >();
+
Router::new()
.merge(required_link_routes)
.merge(hex_thread_routes)
+ .merge(hex_thread_labels_routes)
}
diff --git a/rust/cloud-storage/email_service/src/api/middleware/link.rs b/rust/cloud-storage/email_service/src/api/middleware/link.rs
index 66f754e091..b1e134ea4d 100644
--- a/rust/cloud-storage/email_service/src/api/middleware/link.rs
+++ b/rust/cloud-storage/email_service/src/api/middleware/link.rs
@@ -1,6 +1,9 @@
-use axum::{extract::Request, middleware::Next, response::Response};
+use axum::{
+ extract::Request,
+ middleware::Next,
+ response::{IntoResponse, Response},
+};
use axum_extra::extract::Cached;
-use doppleganger::Mirror;
use email::{domain::ports::EmailService, inbound::EmailLinkExtractor};
pub(in crate::api) async fn attach_link_context<U: EmailService>(
@@ -8,10 +11,28 @@ pub(in crate::api) async fn attach_link_context<U: EmailService>(
mut req: Request,
next: Next,
) -> Result<Response, Response> {
+ let provider = match link.provider.as_str() {
+ "GMAIL" => models_email::email::service::link::UserProvider::Gmail,
+ other => {
+ tracing::error!(provider = other, "unknown provider in link");
+ return Err((
+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,
+ "unknown provider",
+ )
+ .into_response());
+ }
+ };
req.extensions_mut()
- .insert(models_email::email::service::link::Link::mirror(
- link.clone(),
- ));
+ .insert(models_email::email::service::link::Link {
+ id: link.id,
+ macro_id: link.macro_id.clone(),
+ fusionauth_user_id: link.fusionauth_user_id.clone(),
+ email_address: link.email_address.clone(),
+ provider,
+ is_sync_active: link.is_sync_active,
+ created_at: link.created_at,
+ updated_at: link.updated_at,
+ });
// Also insert the hex Link for use by hex crate handlers.
req.extensions_mut().insert(link);
Ok(next.run(req).await)
diff --git a/rust/cloud-storage/email_service/src/api/swagger.rs b/rust/cloud-storage/email_service/src/api/swagger.rs
index 4e6c712ea4..f4b4efc690 100644
--- a/rust/cloud-storage/email_service/src/api/swagger.rs
+++ b/rust/cloud-storage/email_service/src/api/swagger.rs
@@ -17,7 +17,6 @@ use crate::api::email::links::list::ListLinksResponse;
use crate::api::email::messages::labels::{UpdateLabelBatchRequest, UpdateLabelBatchResponse};
use crate::api::email::settings::patch::{PatchSettingsRequest, PatchSettingsResponse};
use crate::api::email::threads::archived::ArchiveThreadRequest;
-use crate::api::email::threads::labels::UpdateThreadLabelRequest;
use crate::api::{email, health};
use ::email::inbound;
use ::email::inbound::{
@@ -26,6 +25,7 @@ use ::email::inbound::{
CreateDraftResponse as HexCreateDraftResponse, GetPreviewsCursorParams, GetThreadResponse,
SendMessageRequest as HexSendMessageRequest, SendMessageResponse as HexSendMessageResponse,
};
+use ::email::inbound::{UpdateThreadLabelRequest, UpdateThreadLabelsResponse};
use model::response::EmptyResponse;
use models_email::api::settings::Settings;
use models_email::email::service;
@@ -67,7 +67,7 @@ use utoipa::OpenApi;
email::threads::seen::seen_handler,
email::threads::get::get_thread_messages_handler,
email::threads::archived::archived_handler,
- email::threads::labels::handler,
+ inbound::update_thread_labels_handler,
inbound::cursor_handler,
inbound::get_thread_handler,
email::links::list::list_links_handler,
@@ -112,6 +112,7 @@ use utoipa::OpenApi;
// Thread types
ArchiveThreadRequest,
UpdateThreadLabelRequest,
+ UpdateThreadLabelsResponse,
ThreadPreviewCursor,
GetThreadResponse,
ApiThread,
diff --git a/rust/cloud-storage/email_service/src/main.rs b/rust/cloud-storage/email_service/src/main.rs
index 7ce566e57e..a2c0e0b57b 100644
--- a/rust/cloud-storage/email_service/src/main.rs
+++ b/rust/cloud-storage/email_service/src/main.rs
@@ -3,8 +3,8 @@ use anyhow::Context;
use document_storage_service_client::DocumentStorageServiceClient;
use email::{
domain::service::EmailServiceImpl,
- inbound::{EmailRouterState, EmailThreadRouterState},
- outbound::EmailPgRepo,
+ inbound::{EmailRouterState, EmailThreadRouterState, GmailTokenState},
+ outbound::{EmailPgRepo, GmailTokenProviderImpl},
};
use email_service::config::EmailServiceCloudfrontSignerPrivateKey;
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
@@ -124,10 +124,13 @@ async fn main() -> anyhow::Result<()> {
.await?;
let sqs_client = Arc::new(sqs_client);
+ let gmail_client = Arc::new(gmail_client);
+ let gmail_label_modifier = email::outbound::GmailClientLabelModifier::new(gmail_client.clone());
let email_service = EmailRouterState::new(EmailServiceImpl::new(
EmailPgRepo::new(db.clone()),
FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone())),
(*sqs_client).clone(),
+ gmail_label_modifier,
config.sent_undo_delay_secs,
));
let entity_access_service = Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
@@ -137,14 +140,25 @@ async fn main() -> anyhow::Result<()> {
service: email_service.service(),
access_service: entity_access_service.clone(),
};
+ let auth_service_client = Arc::new(auth_service_client);
+ let redis_conn = redis_client
+ .inner
+ .get_multiplexed_async_connection()
+ .await
+ .context("failed to get multiplexed redis connection for gmail token provider")?;
+ let redis_client = Arc::new(redis_client);
+ let gmail_token_state = GmailTokenState::new(GmailTokenProviderImpl::new(
+ redis_conn,
+ auth_service_client.clone(),
+ ));
api::setup_and_serve(ApiContext {
db,
config: Arc::new(config),
- auth_service_client: Arc::new(auth_service_client),
- redis_client: Arc::new(redis_client),
+ auth_service_client,
+ redis_client,
sqs_client,
sfs_client: Arc::new(sfs_client),
- gmail_client: Arc::new(gmail_client),
+ gmail_client: gmail_client.clone(),
s3_client: Arc::new(s3_client),
dss_client: Arc::new(dss_client),
system_properties_service,
@@ -153,6 +167,7 @@ async fn main() -> anyhow::Result<()> {
email_service,
entity_access_service,
email_thread_state,
+ gmail_token_state,
})
.await?;
Ok(())
diff --git a/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rs b/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rs
index 83a07161b6..caaca39f34 100644
--- a/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rs
@@ -123,11 +123,11 @@ async fn handle_delete(
// delete cached access token, in case user re-enables within cache window
ctx.redis_client
- .delete_gmail_access_token(&TokenCacheKey {
- fusion_user_id: link.fusionauth_user_id.clone(),
- macro_id: link.macro_id.to_string(),
- provider: UserProvider::Gmail,
- })
+ .delete_gmail_access_token(&TokenCacheKey::new(
+ link.fusionauth_user_id.clone(),
+ link.macro_id.to_string(),
+ UserProvider::Gmail.as_str(),
+ ))
.await
.inspect_err(|e| {
tracing::warn!(error=?e, "Failed to delete Gmail access token");
diff --git a/rust/cloud-storage/email_service/src/util/gmail/auth.rs b/rust/cloud-storage/email_service/src/util/gmail/auth.rs
index 7f25b239ab..e9c200d391 100644
--- a/rust/cloud-storage/email_service/src/util/gmail/auth.rs
+++ b/rust/cloud-storage/email_service/src/util/gmail/auth.rs
@@ -72,7 +72,7 @@ pub async fn fetch_gmail_access_token_from_link(
let key = TokenCacheKey::new(
&link.fusionauth_user_id,
link.macro_id.0.as_ref(),
- link.provider,
+ link.provider.as_str(),
);
fetch_gmail_access_token(&key, redis_client, auth_service_client).await
@@ -88,7 +88,7 @@ pub async fn fetch_gmail_token_usercontext_response(
let key = TokenCacheKey::new(
&user_context.fusion_user_id,
&user_context.user_id,
- UserProvider::Gmail,
+ UserProvider::Gmail.as_str(),
);
fetch_gmail_access_token(&key, redis_client, auth_service_client)
@@ -105,48 +105,20 @@ pub async fn fetch_gmail_token_usercontext_response(
})
}
-/// Fetches the gmail access token, first looking in the redis cache then hitting the auth service
+/// Fetches the gmail access token, first looking in the redis cache then hitting the auth service.
+///
+/// Delegates to [`email::outbound::fetch_gmail_access_token`].
pub async fn fetch_gmail_access_token(
key: &TokenCacheKey,
redis_client: &RedisClient,
auth_service_client: &AuthServiceClient,
) -> anyhow::Result<String> {
- let token_from_redis = redis_client
- .get_gmail_access_token(key)
+ let conn = redis_client
+ .inner
+ .get_multiplexed_async_connection()
.await
- .map_err(|e| anyhow::anyhow!("Redis error: {}. TokenCacheKey: {:?}", e, key))
- .ok()
- .flatten();
-
- let access_token = if let Some(token) = token_from_redis {
- token
- } else {
- let fetched_token = auth_service_client
- .get_google_access_token(&key.fusion_user_id, &key.macro_id)
- .await
- .with_context(|| {
- format!(
- "Failed to get Google access token from auth service. TokenCacheKey: {:?}",
- key
- )
- })?;
-
- // Cache newly fetched token
- if let Err(cache_err) = redis_client
- .set_gmail_access_token(key, &fetched_token.access_token)
- .await
- {
- tracing::warn!(
- error = ?cache_err,
- token_cache_key = ?key,
- "Failed to cache fetched access token in Redis"
- );
- }
-
- fetched_token.access_token
- };
-
- Ok(access_token)
+ .context("unable to connect to redis")?;
+ email::outbound::fetch_gmail_access_token(key, &conn, auth_service_client).await
}
/// Retrieves Google public keys, first looking in the redis cache then fetching them from the Gmail client
diff --git a/rust/cloud-storage/email_utils/src/lib.rs b/rust/cloud-storage/email_utils/src/lib.rs
index 1d65f54d48..30d5b3f9ba 100644
--- a/rust/cloud-storage/email_utils/src/lib.rs
+++ b/rust/cloud-storage/email_utils/src/lib.rs
@@ -1,6 +1,7 @@
pub mod body_replyless;
pub mod generic_email;
pub mod normalize_contact;
+pub mod token_cache_key;
pub use generic_email::{dedupe_emails, is_generic_email};
pub use normalize_contact::normalize_contact_name;
diff --git a/rust/cloud-storage/email_utils/src/token_cache_key.rs b/rust/cloud-storage/email_utils/src/token_cache_key.rs
new file mode 100644
index 0000000000..1ff2d3efde
--- /dev/null
+++ b/rust/cloud-storage/email_utils/src/token_cache_key.rs
@@ -0,0 +1,33 @@
+/// A key for caching OAuth tokens in Redis.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct TokenCacheKey {
+ /// The FusionAuth user ID.
+ pub fusion_user_id: String,
+ /// The Macro user ID.
+ pub macro_id: String,
+ /// The provider name (e.g. "GMAIL").
+ pub provider: String,
+}
+
+impl TokenCacheKey {
+ /// Create a new TokenCacheKey.
+ pub fn new(
+ fusion_user_id: impl Into<String>,
+ macro_id: impl Into<String>,
+ provider: impl Into<String>,
+ ) -> Self {
+ Self {
+ fusion_user_id: fusion_user_id.into(),
+ macro_id: macro_id.into(),
+ provider: provider.into(),
+ }
+ }
+
+ /// Convert the key to a Redis-compatible string.
+ pub fn to_redis_key(&self) -> String {
+ format!(
+ "gmail_token:{}:{}:{}",
+ self.provider, self.fusion_user_id, self.macro_id
+ )
+ }
+}
diff --git a/rust/cloud-storage/models_email/Cargo.toml b/rust/cloud-storage/models_email/Cargo.toml
index b66284420e..e9d0bf5d35 100644
--- a/rust/cloud-storage/models_email/Cargo.toml
+++ b/rust/cloud-storage/models_email/Cargo.toml
@@ -8,19 +8,11 @@ version = "0.1.0"
anyhow = { workspace = true }
base64 = { workspace = true }
chrono = { workspace = true }
-doppleganger = { workspace = true, features = ["chrono", "uuid"] }
-ego-tree = { workspace = true }
-email = { path = "../email" }
email_utils = { path = "../email_utils" }
html2text = "0.15.1"
-lazy_static = { workspace = true }
macro_user_id = { path = "../macro_user_id" }
-macro_uuid = { path = "../macro_uuid" }
models_pagination = { path = "../models_pagination" }
-models_permissions = { path = "../models_permissions" }
-regex = { workspace = true }
schemars = { workspace = true }
-scraper = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true, features = ["raw_value"] }
serde_with = { workspace = true }
diff --git a/rust/cloud-storage/models_email/src/email/service/cache.rs b/rust/cloud-storage/models_email/src/email/service/cache.rs
index 5b20420c84..b38ab1075e 100644
--- a/rust/cloud-storage/models_email/src/email/service/cache.rs
+++ b/rust/cloud-storage/models_email/src/email/service/cache.rs
@@ -1,34 +1 @@
-use crate::email::service::link::UserProvider;
-
-/// A key for caching OAuth tokens in Redis
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct TokenCacheKey {
- pub fusion_user_id: String,
- pub macro_id: String,
- pub provider: UserProvider,
-}
-
-impl TokenCacheKey {
- /// Create a new TokenCacheKey
- pub fn new(
- fusion_user_id: impl Into<String>,
- macro_id: impl Into<String>,
- provider: UserProvider,
- ) -> Self {
- Self {
- fusion_user_id: fusion_user_id.into(),
- macro_id: macro_id.into(),
- provider,
- }
- }
-
- /// Convert the key to a Redis-compatible string
- pub fn to_redis_key(&self) -> String {
- format!(
- "gmail_token:{}:{}:{}",
- self.provider.as_str(),
- self.fusion_user_id,
- self.macro_id
- )
- }
-}
+pub use email_utils::token_cache_key::TokenCacheKey;
diff --git a/rust/cloud-storage/models_email/src/email/service/link.rs b/rust/cloud-storage/models_email/src/email/service/link.rs
index 470db342d3..c1b9891ba0 100644
--- a/rust/cloud-storage/models_email/src/email/service/link.rs
+++ b/rust/cloud-storage/models_email/src/email/service/link.rs
@@ -1,12 +1,10 @@
use chrono::{DateTime, Utc};
-use doppleganger::Doppleganger;
use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid;
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, Doppleganger)]
-#[dg(backward = email::domain::models::Link)]
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct Link {
pub id: Uuid,
#[schema(value_type = String)]
@@ -20,8 +18,7 @@ pub struct Link {
pub updated_at: DateTime<Utc>,
}
-#[derive(Debug, Clone, Copy, ToSchema, Doppleganger, Serialize, Deserialize, PartialEq, Eq)]
-#[dg(backward = email::domain::models::UserProvider)]
+#[derive(Debug, Clone, Copy, ToSchema, Serialize, Deserialize, PartialEq, Eq)]
pub enum UserProvider {
Gmail,
}
diff --git a/rust/cloud-storage/soup/examples/ai_tools_cli.rs b/rust/cloud-storage/soup/examples/ai_tools_cli.rs
index dcc5ad737d..7ed16b62ee 100644
--- a/rust/cloud-storage/soup/examples/ai_tools_cli.rs
+++ b/rust/cloud-storage/soup/examples/ai_tools_cli.rs
@@ -56,6 +56,7 @@ async fn main() {
email_repo,
frecency_service.clone(),
email::domain::ports::NoOpEnqueuer,
+ email::domain::ports::NoOpGmailLabelModifier,
0,
);
diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rs
index c30add8536..8e26d72886 100644
--- a/rust/cloud-storage/soup/src/domain/service/tests.rs
+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs
@@ -71,6 +71,17 @@ impl EmailService for NoopEmailService {
) -> Result<email::domain::models::CreatedDraft, EmailErr> {
Err(EmailErr::RepoErr(anyhow::anyhow!("not implemented")))
}
+
+ async fn update_thread_labels(
+ &self,
+ _access_token: &str,
+ _link: &email::domain::models::Link,
+ _thread_id: uuid::Uuid,
+ _label_id: uuid::Uuid,
+ _add: bool,
+ ) -> Result<email::domain::models::UpdateThreadLabelsResult, EmailErr> {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("not implemented")))
+ }
}
struct NoopCommsService;
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 1ad84f8eed..6b518916f3 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
@@ -115,6 +115,17 @@ impl EmailService for MockEmail {
) -> Result<email::domain::models::CreatedDraft, EmailErr> {
Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
}
+
+ async fn update_thread_labels(
+ &self,
+ _access_token: &str,
+ _link: &email::domain::models::Link,
+ _thread_id: uuid::Uuid,
+ _label_id: uuid::Uuid,
+ _add: bool,
+ ) -> Result<email::domain::models::UpdateThreadLabelsResult, EmailErr> {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
+ }
}
fn mock_router() -> Router {
@@ -203,6 +214,17 @@ impl EmailService for MockEmailLinkResult {
) -> Result<email::domain::models::CreatedDraft, EmailErr> {
Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
}
+
+ async fn update_thread_labels(
+ &self,
+ _access_token: &str,
+ _link: &email::domain::models::Link,
+ _thread_id: uuid::Uuid,
+ _label_id: uuid::Uuid,
+ _add: bool,
+ ) -> Result<email::domain::models::UpdateThreadLabelsResult, EmailErr> {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
+ }
}
#[tokio::test]