Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
refactor(email-service): migrate email-service backfill tracking to redis (#47)
Evan Hutnik753866c63560
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex ec1baaa81f..91bf5ab006 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -2823,10 +2823,8 @@ dependencies = ["http-body-util","infer 0.19.0","insight_service_client",- "lazy_static","lol_html","macro_auth",- "macro_axum_utils","macro_cors","macro_entrypoint","macro_env",@@ -2841,7 +2839,6 @@ dependencies = ["models_email","models_pagination","redis",- "regex","reqwest","s3_client","schemars",diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-07c9b31abc07e3535dd10c6e8c8db3bdc74f80a332b8438bf8595fbdf846d4a4.json b/rust/cloud-storage/email_db_client/.sqlx/query-07c9b31abc07e3535dd10c6e8c8db3bdc74f80a332b8438bf8595fbdf846d4a4.jsondeleted file mode 100644index 8a9e931d2d..0000000000--- a/rust/cloud-storage/email_db_client/.sqlx/query-07c9b31abc07e3535dd10c6e8c8db3bdc74f80a332b8438bf8595fbdf846d4a4.json+++ /dev/null@@ -1,55 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE email_backfill_threads\n SET status = $3, metadata_updated = true, updated_at = NOW()\n WHERE backfill_job_id = $1 AND thread_provider_id = $2\n RETURNING messages_retrieved_count, messages_processed_count, messages_succeeded_count, messages_failed_count\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "messages_retrieved_count",- "type_info": "Int4"- },- {- "ordinal": 1,- "name": "messages_processed_count",- "type_info": "Int4"- },- {- "ordinal": 2,- "name": "messages_succeeded_count",- "type_info": "Int4"- },- {- "ordinal": 3,- "name": "messages_failed_count",- "type_info": "Int4"- }- ],- "parameters": {- "Left": [- "Uuid",- "Text",- {- "Custom": {- "name": "email_backfill_thread_status",- "kind": {- "Enum": [- "InProgress",- "Skipped",- "Completed",- "Failed",- "Cancelled"- ]- }- }- }- ]- },- "nullable": [- false,- false,- false,- false- ]- },- "hash": "07c9b31abc07e3535dd10c6e8c8db3bdc74f80a332b8438bf8595fbdf846d4a4"-}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-408f876183bf964a31bf2103385962960b394995e04fe343ed35c4d36a86a3b4.json b/rust/cloud-storage/email_db_client/.sqlx/query-0b25861527e4ecd715a759799e7dc2d43865571925e95582689df12c3b02322a.jsonsimilarity index 50%rename from rust/cloud-storage/email_db_client/.sqlx/query-408f876183bf964a31bf2103385962960b394995e04fe343ed35c4d36a86a3b4.jsonrename to rust/cloud-storage/email_db_client/.sqlx/query-0b25861527e4ecd715a759799e7dc2d43865571925e95582689df12c3b02322a.jsonindex 7235d736d6..9263cd881c 100644--- a/rust/cloud-storage/email_db_client/.sqlx/query-408f876183bf964a31bf2103385962960b394995e04fe343ed35c4d36a86a3b4.json+++ b/rust/cloud-storage/email_db_client/.sqlx/query-0b25861527e4ecd715a759799e7dc2d43865571925e95582689df12c3b02322a.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id,\n link_id,\n fusionauth_user_id,\n threads_requested_limit,\n total_threads,\n threads_retrieved_count,\n messages_retrieved_count,\n threads_processed_count,\n threads_succeeded_count,\n threads_failed_count,\n threads_skipped_count,\n messages_processed_count,\n messages_succeeded_count,\n messages_failed_count,\n status as \"status: db::backfill::BackfillJobStatus\",\n created_at,\n updated_at\n FROM email_backfill_jobs\n WHERE fusionauth_user_id = $1\n AND created_at > NOW() - INTERVAL '24 hours'\n ORDER BY created_at DESC\n ",+ "query": "\n SELECT\n id,\n link_id,\n fusionauth_user_id,\n threads_requested_limit,\n total_threads,\n threads_retrieved_count,\n status as \"status: db::backfill::BackfillJobStatus\",\n created_at,\n updated_at\n FROM email_backfill_jobs\n WHERE fusionauth_user_id = $1\n AND created_at > NOW() - INTERVAL '24 hours'\n ORDER BY created_at DESC\n ","describe": {"columns": [{@@ -35,46 +35,6 @@},{"ordinal": 6,- "name": "messages_retrieved_count",- "type_info": "Int4"- },- {- "ordinal": 7,- "name": "threads_processed_count",- "type_info": "Int4"- },- {- "ordinal": 8,- "name": "threads_succeeded_count",- "type_info": "Int4"- },- {- "ordinal": 9,- "name": "threads_failed_count",- "type_info": "Int4"- },- {- "ordinal": 10,- "name": "threads_skipped_count",- "type_info": "Int4"- },- {- "ordinal": 11,- "name": "messages_processed_count",- "type_info": "Int4"- },- {- "ordinal": 12,- "name": "messages_succeeded_count",- "type_info": "Int4"- },- {- "ordinal": 13,- "name": "messages_failed_count",- "type_info": "Int4"- },- {- "ordinal": 14,"name": "status: db::backfill::BackfillJobStatus","type_info": {"Custom": {@@ -92,12 +52,12 @@}},{- "ordinal": 15,+ "ordinal": 7,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 16,+ "ordinal": 8,"name": "updated_at","type_info": "Timestamptz"}@@ -116,16 +76,8 @@false,false,false,- false,- false,- false,- false,- false,- false,- false,- false,false]},- "hash": "408f876183bf964a31bf2103385962960b394995e04fe343ed35c4d36a86a3b4"+ "hash": "0b25861527e4ecd715a759799e7dc2d43865571925e95582689df12c3b02322a"}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-57bbc51305d61ed26f9eda68daea0941c0157aa2585e1a1cd819ff3c464d3e65.json b/rust/cloud-storage/email_db_client/.sqlx/query-57bbc51305d61ed26f9eda68daea0941c0157aa2585e1a1cd819ff3c464d3e65.jsondeleted file mode 100644index 7f7ae40af8..0000000000--- a/rust/cloud-storage/email_db_client/.sqlx/query-57bbc51305d61ed26f9eda68daea0941c0157aa2585e1a1cd819ff3c464d3e65.json+++ /dev/null@@ -1,41 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE email_backfill_threads\n SET\n messages_processed_count = messages_processed_count + 1,\n messages_succeeded_count = messages_succeeded_count + 1,\n updated_at = now()\n WHERE backfill_job_id = $1\n AND thread_provider_id = $2\n RETURNING\n messages_retrieved_count,\n messages_processed_count,\n messages_succeeded_count,\n messages_failed_count\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "messages_retrieved_count",- "type_info": "Int4"- },- {- "ordinal": 1,- "name": "messages_processed_count",- "type_info": "Int4"- },- {- "ordinal": 2,- "name": "messages_succeeded_count",- "type_info": "Int4"- },- {- "ordinal": 3,- "name": "messages_failed_count",- "type_info": "Int4"- }- ],- "parameters": {- "Left": [- "Uuid",- "Text"- ]- },- "nullable": [- false,- false,- false,- false- ]- },- "hash": "57bbc51305d61ed26f9eda68daea0941c0157aa2585e1a1cd819ff3c464d3e65"-}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-5a3c744038712b1277cb6ad4af8ec69e6a6e8a1cc63526cea13d67ce44f3e5a4.json b/rust/cloud-storage/email_db_client/.sqlx/query-5a3c744038712b1277cb6ad4af8ec69e6a6e8a1cc63526cea13d67ce44f3e5a4.jsondeleted file mode 100644index cdcd2aa888..0000000000--- a/rust/cloud-storage/email_db_client/.sqlx/query-5a3c744038712b1277cb6ad4af8ec69e6a6e8a1cc63526cea13d67ce44f3e5a4.json+++ /dev/null@@ -1,29 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE email_backfill_messages\n SET status = $4, updated_at = NOW()\n WHERE backfill_job_id = $1 AND thread_provider_id = $2 AND message_provider_id = $3\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text",- "Text",- {- "Custom": {- "name": "email_backfill_message_status",- "kind": {- "Enum": [- "InProgress",- "Completed",- "Failed",- "Cancelled"- ]- }- }- }- ]- },- "nullable": []- },- "hash": "5a3c744038712b1277cb6ad4af8ec69e6a6e8a1cc63526cea13d67ce44f3e5a4"-}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-5b5ae005981ad0f5d3b3b2bedd4ae645c568455e29ed6abacdd5256c8e4b046a.json b/rust/cloud-storage/email_db_client/.sqlx/query-5b5ae005981ad0f5d3b3b2bedd4ae645c568455e29ed6abacdd5256c8e4b046a.jsondeleted file mode 100644index aa049c85e2..0000000000--- a/rust/cloud-storage/email_db_client/.sqlx/query-5b5ae005981ad0f5d3b3b2bedd4ae645c568455e29ed6abacdd5256c8e4b046a.json+++ /dev/null@@ -1,30 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE email_backfill_messages\n SET status = $4, error_message = $5, updated_at = NOW()\n WHERE backfill_job_id = $1 AND thread_provider_id = $2 AND message_provider_id = $3\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text",- "Text",- {- "Custom": {- "name": "email_backfill_message_status",- "kind": {- "Enum": [- "InProgress",- "Completed",- "Failed",- "Cancelled"- ]- }- }- },- "Text"- ]- },- "nullable": []- },- "hash": "5b5ae005981ad0f5d3b3b2bedd4ae645c568455e29ed6abacdd5256c8e4b046a"-}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-783cfa4d140e45fc0df49929da288cdb955c8ebc4694074a58bd0e32b7fba36a.json b/rust/cloud-storage/email_db_client/.sqlx/query-783cfa4d140e45fc0df49929da288cdb955c8ebc4694074a58bd0e32b7fba36a.jsondeleted file mode 100644index 0d2508077c..0000000000--- a/rust/cloud-storage/email_db_client/.sqlx/query-783cfa4d140e45fc0df49929da288cdb955c8ebc4694074a58bd0e32b7fba36a.json+++ /dev/null@@ -1,16 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE email_backfill_threads\n SET messages_retrieved_count = $3, updated_at = NOW()\n WHERE backfill_job_id = $1 AND thread_provider_id = $2\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text",- "Int4"- ]- },- "nullable": []- },- "hash": "783cfa4d140e45fc0df49929da288cdb955c8ebc4694074a58bd0e32b7fba36a"-}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-9c06f6d3124e987e63f2ed9685895d07d9183dbdb992c2a7a6e0e02b9224ee75.json b/rust/cloud-storage/email_db_client/.sqlx/query-8359035e915d0949500ede9f520fb3ea45d1766256ee45b0c5967618301b2ea6.jsonsimilarity index 52%rename from rust/cloud-storage/email_db_client/.sqlx/query-9c06f6d3124e987e63f2ed9685895d07d9183dbdb992c2a7a6e0e02b9224ee75.jsonrename to rust/cloud-storage/email_db_client/.sqlx/query-8359035e915d0949500ede9f520fb3ea45d1766256ee45b0c5967618301b2ea6.jsonindex ff3d9e91f1..fe47607402 100644--- a/rust/cloud-storage/email_db_client/.sqlx/query-9c06f6d3124e987e63f2ed9685895d07d9183dbdb992c2a7a6e0e02b9224ee75.json+++ b/rust/cloud-storage/email_db_client/.sqlx/query-8359035e915d0949500ede9f520fb3ea45d1766256ee45b0c5967618301b2ea6.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id,\n link_id,\n fusionauth_user_id,\n threads_requested_limit,\n total_threads,\n threads_retrieved_count,\n messages_retrieved_count,\n threads_processed_count,\n threads_succeeded_count,\n threads_failed_count,\n threads_skipped_count,\n messages_processed_count,\n messages_succeeded_count,\n messages_failed_count,\n status as \"status: db::backfill::BackfillJobStatus\",\n created_at,\n updated_at\n FROM email_backfill_jobs\n WHERE id = $1\n ",+ "query": "\n SELECT\n id,\n link_id,\n fusionauth_user_id,\n threads_requested_limit,\n total_threads,\n threads_retrieved_count,\n status as \"status: db::backfill::BackfillJobStatus\",\n created_at,\n updated_at\n FROM email_backfill_jobs\n WHERE id = $1\n ","describe": {"columns": [{@@ -35,46 +35,6 @@},{"ordinal": 6,- "name": "messages_retrieved_count",- "type_info": "Int4"- },- {- "ordinal": 7,- "name": "threads_processed_count",- "type_info": "Int4"- },- {- "ordinal": 8,- "name": "threads_succeeded_count",- "type_info": "Int4"- },- {- "ordinal": 9,- "name": "threads_failed_count",- "type_info": "Int4"- },- {- "ordinal": 10,- "name": "threads_skipped_count",- "type_info": "Int4"- },- {- "ordinal": 11,- "name": "messages_processed_count",- "type_info": "Int4"- },- {- "ordinal": 12,- "name": "messages_succeeded_count",- "type_info": "Int4"- },- {- "ordinal": 13,- "name": "messages_failed_count",- "type_info": "Int4"- },- {- "ordinal": 14,"name": "status: db::backfill::BackfillJobStatus","type_info": {"Custom": {@@ -92,12 +52,12 @@}},{- "ordinal": 15,+ "ordinal": 7,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 16,+ "ordinal": 8,"name": "updated_at","type_info": "Timestamptz"}@@ -116,16 +76,8 @@false,false,false,- false,- false,- false,- false,- false,- false,- false,- false,false]},- "hash": "9c06f6d3124e987e63f2ed9685895d07d9183dbdb992c2a7a6e0e02b9224ee75"+ "hash": "8359035e915d0949500ede9f520fb3ea45d1766256ee45b0c5967618301b2ea6"}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-990807886a7d453a62aeae10489aff849e65cdb68a1a95b88ce7c38ef2e86053.json b/rust/cloud-storage/email_db_client/.sqlx/query-990807886a7d453a62aeae10489aff849e65cdb68a1a95b88ce7c38ef2e86053.jsondeleted file mode 100644index 56d180da07..0000000000--- a/rust/cloud-storage/email_db_client/.sqlx/query-990807886a7d453a62aeae10489aff849e65cdb68a1a95b88ce7c38ef2e86053.json+++ /dev/null@@ -1,28 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE email_backfill_jobs\n SET\n threads_processed_count = threads_processed_count + 1,\n threads_skipped_count = threads_skipped_count + 1,\n updated_at = now()\n WHERE id = $1\n RETURNING total_threads, threads_processed_count\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "total_threads",- "type_info": "Int4"- },- {- "ordinal": 1,- "name": "threads_processed_count",- "type_info": "Int4"- }- ],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": [- false,- false- ]- },- "hash": "990807886a7d453a62aeae10489aff849e65cdb68a1a95b88ce7c38ef2e86053"-}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-9b50efccd55f4383c0d859ad89629317f8b15bfc787edfc5428a43c7603a088a.json b/rust/cloud-storage/email_db_client/.sqlx/query-9b50efccd55f4383c0d859ad89629317f8b15bfc787edfc5428a43c7603a088a.jsondeleted file mode 100644index 68ff64ce78..0000000000--- a/rust/cloud-storage/email_db_client/.sqlx/query-9b50efccd55f4383c0d859ad89629317f8b15bfc787edfc5428a43c7603a088a.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE email_backfill_jobs\n SET messages_retrieved_count = messages_retrieved_count + $2,\n updated_at = NOW()\n WHERE id = $1\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Int4"- ]- },- "nullable": []- },- "hash": "9b50efccd55f4383c0d859ad89629317f8b15bfc787edfc5428a43c7603a088a"-}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-9bc2118879aed226b2735a910981d9e51f9caca3ab2e6ba5176b7e97eddd5abb.json b/rust/cloud-storage/email_db_client/.sqlx/query-9bc2118879aed226b2735a910981d9e51f9caca3ab2e6ba5176b7e97eddd5abb.jsondeleted file mode 100644index 4d94577615..0000000000--- a/rust/cloud-storage/email_db_client/.sqlx/query-9bc2118879aed226b2735a910981d9e51f9caca3ab2e6ba5176b7e97eddd5abb.json+++ /dev/null@@ -1,30 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE email_backfill_threads\n SET status = $3, error_message = $4, updated_at = NOW()\n WHERE backfill_job_id = $1 AND thread_provider_id = $2\n AND status != $3\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text",- {- "Custom": {- "name": "email_backfill_thread_status",- "kind": {- "Enum": [- "InProgress",- "Skipped",- "Completed",- "Failed",- "Cancelled"- ]- }- }- },- "Text"- ]- },- "nullable": []- },- "hash": "9bc2118879aed226b2735a910981d9e51f9caca3ab2e6ba5176b7e97eddd5abb"-}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-a391a7c2882d97adf6125ab73a448aa1eefc82074225ada45373ca6dccd16831.json b/rust/cloud-storage/email_db_client/.sqlx/query-a391a7c2882d97adf6125ab73a448aa1eefc82074225ada45373ca6dccd16831.jsondeleted file mode 100644index b5d1c44cf6..0000000000--- a/rust/cloud-storage/email_db_client/.sqlx/query-a391a7c2882d97adf6125ab73a448aa1eefc82074225ada45373ca6dccd16831.json+++ /dev/null@@ -1,31 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE email_backfill_jobs\n SET\n threads_processed_count = threads_processed_count + 1,\n threads_succeeded_count = threads_succeeded_count + 1,\n messages_processed_count = messages_processed_count + $2,\n messages_succeeded_count = messages_succeeded_count + $3,\n messages_failed_count = messages_failed_count + $4,\n updated_at = now()\n WHERE id = $1\n RETURNING total_threads, threads_processed_count\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "total_threads",- "type_info": "Int4"- },- {- "ordinal": 1,- "name": "threads_processed_count",- "type_info": "Int4"- }- ],- "parameters": {- "Left": [- "Uuid",- "Int4",- "Int4",- "Int4"- ]- },- "nullable": [- false,- false- ]- },- "hash": "a391a7c2882d97adf6125ab73a448aa1eefc82074225ada45373ca6dccd16831"-}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-b25c594338bca2fe5e16576ed22a0941ae2199dc4f7d0b9e879b800c49ad86f5.json b/rust/cloud-storage/email_db_client/.sqlx/query-b25c594338bca2fe5e16576ed22a0941ae2199dc4f7d0b9e879b800c49ad86f5.jsondeleted file mode 100644index c80c282f0f..0000000000--- a/rust/cloud-storage/email_db_client/.sqlx/query-b25c594338bca2fe5e16576ed22a0941ae2199dc4f7d0b9e879b800c49ad86f5.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO email_backfill_threads (backfill_job_id, thread_provider_id, status)\n VALUES ($1, $2, 'InProgress')\n ON CONFLICT (backfill_job_id, thread_provider_id)\n DO UPDATE SET \n updated_at = NOW(),\n retry_count = email_backfill_threads.retry_count + 1\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Varchar"- ]- },- "nullable": []- },- "hash": "b25c594338bca2fe5e16576ed22a0941ae2199dc4f7d0b9e879b800c49ad86f5"-}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-c6cc9b711e7f302a37e0c035420d1f9d0bf618a3c270c05ac932b10d5c7573fe.json b/rust/cloud-storage/email_db_client/.sqlx/query-c6cc9b711e7f302a37e0c035420d1f9d0bf618a3c270c05ac932b10d5c7573fe.jsondeleted file mode 100644index 3b5cf3ffd1..0000000000--- a/rust/cloud-storage/email_db_client/.sqlx/query-c6cc9b711e7f302a37e0c035420d1f9d0bf618a3c270c05ac932b10d5c7573fe.json+++ /dev/null@@ -1,16 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO email_backfill_messages (backfill_job_id, thread_provider_id, message_provider_id, status)\n VALUES ($1, $2, $3, 'InProgress')\n ON CONFLICT (backfill_job_id, thread_provider_id, message_provider_id)\n DO UPDATE SET \n updated_at = NOW(),\n retry_count = email_backfill_messages.retry_count + 1\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Varchar",- "Varchar"- ]- },- "nullable": []- },- "hash": "c6cc9b711e7f302a37e0c035420d1f9d0bf618a3c270c05ac932b10d5c7573fe"-}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-f1a9f8fd55665c69838d2a73f6c2479564ab0ce18b24f411335b9d9b3c00fe65.json b/rust/cloud-storage/email_db_client/.sqlx/query-d1c575aba71170e53f0d8a786d9c1a67edb6dd76a80889a538b6c1aceb837e45.jsonsimilarity index 52%rename from rust/cloud-storage/email_db_client/.sqlx/query-f1a9f8fd55665c69838d2a73f6c2479564ab0ce18b24f411335b9d9b3c00fe65.jsonrename to rust/cloud-storage/email_db_client/.sqlx/query-d1c575aba71170e53f0d8a786d9c1a67edb6dd76a80889a538b6c1aceb837e45.jsonindex ef8cad1ff5..9b6865d2db 100644--- a/rust/cloud-storage/email_db_client/.sqlx/query-f1a9f8fd55665c69838d2a73f6c2479564ab0ce18b24f411335b9d9b3c00fe65.json+++ b/rust/cloud-storage/email_db_client/.sqlx/query-d1c575aba71170e53f0d8a786d9c1a67edb6dd76a80889a538b6c1aceb837e45.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id,\n link_id,\n fusionauth_user_id,\n threads_requested_limit,\n total_threads,\n threads_retrieved_count,\n messages_retrieved_count,\n threads_processed_count,\n threads_succeeded_count,\n threads_failed_count,\n threads_skipped_count,\n messages_processed_count,\n messages_succeeded_count,\n messages_failed_count,\n status as \"status: db::backfill::BackfillJobStatus\",\n created_at,\n updated_at\n FROM email_backfill_jobs\n WHERE id = $1\n AND link_id = $2\n ",+ "query": "\n SELECT\n id,\n link_id,\n fusionauth_user_id,\n threads_requested_limit,\n total_threads,\n threads_retrieved_count,\n status as \"status: db::backfill::BackfillJobStatus\",\n created_at,\n updated_at\n FROM email_backfill_jobs\n WHERE id = $1\n AND link_id = $2\n ","describe": {"columns": [{@@ -35,46 +35,6 @@},{"ordinal": 6,- "name": "messages_retrieved_count",- "type_info": "Int4"- },- {- "ordinal": 7,- "name": "threads_processed_count",- "type_info": "Int4"- },- {- "ordinal": 8,- "name": "threads_succeeded_count",- "type_info": "Int4"- },- {- "ordinal": 9,- "name": "threads_failed_count",- "type_info": "Int4"- },- {- "ordinal": 10,- "name": "threads_skipped_count",- "type_info": "Int4"- },- {- "ordinal": 11,- "name": "messages_processed_count",- "type_info": "Int4"- },- {- "ordinal": 12,- "name": "messages_succeeded_count",- "type_info": "Int4"- },- {- "ordinal": 13,- "name": "messages_failed_count",- "type_info": "Int4"- },- {- "ordinal": 14,"name": "status: db::backfill::BackfillJobStatus","type_info": {"Custom": {@@ -92,12 +52,12 @@}},{- "ordinal": 15,+ "ordinal": 7,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 16,+ "ordinal": 8,"name": "updated_at","type_info": "Timestamptz"}@@ -117,16 +77,8 @@false,false,false,- false,- false,- false,- false,- false,- false,- false,- false,false]},- "hash": "f1a9f8fd55665c69838d2a73f6c2479564ab0ce18b24f411335b9d9b3c00fe65"+ "hash": "d1c575aba71170e53f0d8a786d9c1a67edb6dd76a80889a538b6c1aceb837e45"}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-95c474f3d249b90ac0760ede1de8a21b3ecd01be892540385231f5924af72c99.json b/rust/cloud-storage/email_db_client/.sqlx/query-ea7622c671b053d5519e2fb2a996372002b31d070e2cbfe2d58ae763bc04b7c6.jsonsimilarity index 55%rename from rust/cloud-storage/email_db_client/.sqlx/query-95c474f3d249b90ac0760ede1de8a21b3ecd01be892540385231f5924af72c99.jsonrename to rust/cloud-storage/email_db_client/.sqlx/query-ea7622c671b053d5519e2fb2a996372002b31d070e2cbfe2d58ae763bc04b7c6.jsonindex 6d57a20387..071f6b7b3a 100644--- a/rust/cloud-storage/email_db_client/.sqlx/query-95c474f3d249b90ac0760ede1de8a21b3ecd01be892540385231f5924af72c99.json+++ b/rust/cloud-storage/email_db_client/.sqlx/query-ea7622c671b053d5519e2fb2a996372002b31d070e2cbfe2d58ae763bc04b7c6.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO email_backfill_jobs (id, link_id, fusionauth_user_id, threads_requested_limit, status)\n VALUES ($1, $2, $3, $4, 'Init')\n RETURNING \n id, \n link_id, \n fusionauth_user_id,\n threads_requested_limit,\n total_threads,\n threads_retrieved_count,\n messages_retrieved_count,\n threads_processed_count,\n threads_succeeded_count,\n threads_failed_count,\n threads_skipped_count,\n messages_processed_count,\n messages_succeeded_count,\n messages_failed_count,\n status as \"status: db::backfill::BackfillJobStatus\",\n created_at, \n updated_at\n ",+ "query": "\n INSERT INTO email_backfill_jobs (id, link_id, fusionauth_user_id, threads_requested_limit, status)\n VALUES ($1, $2, $3, $4, 'Init')\n RETURNING \n id, \n link_id, \n fusionauth_user_id,\n threads_requested_limit,\n total_threads,\n threads_retrieved_count,\n status as \"status: db::backfill::BackfillJobStatus\",\n created_at, \n updated_at\n ","describe": {"columns": [{@@ -35,46 +35,6 @@},{"ordinal": 6,- "name": "messages_retrieved_count",- "type_info": "Int4"- },- {- "ordinal": 7,- "name": "threads_processed_count",- "type_info": "Int4"- },- {- "ordinal": 8,- "name": "threads_succeeded_count",- "type_info": "Int4"- },- {- "ordinal": 9,- "name": "threads_failed_count",- "type_info": "Int4"- },- {- "ordinal": 10,- "name": "threads_skipped_count",- "type_info": "Int4"- },- {- "ordinal": 11,- "name": "messages_processed_count",- "type_info": "Int4"- },- {- "ordinal": 12,- "name": "messages_succeeded_count",- "type_info": "Int4"- },- {- "ordinal": 13,- "name": "messages_failed_count",- "type_info": "Int4"- },- {- "ordinal": 14,"name": "status: db::backfill::BackfillJobStatus","type_info": {"Custom": {@@ -92,12 +52,12 @@}},{- "ordinal": 15,+ "ordinal": 7,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 16,+ "ordinal": 8,"name": "updated_at","type_info": "Timestamptz"}@@ -119,16 +79,8 @@false,false,false,- false,- false,- false,- false,- false,- false,- false,- false,false]},- "hash": "95c474f3d249b90ac0760ede1de8a21b3ecd01be892540385231f5924af72c99"+ "hash": "ea7622c671b053d5519e2fb2a996372002b31d070e2cbfe2d58ae763bc04b7c6"}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-ed5881e8c67f654f3bdb053cbde1cf449baf4e12894848ae2b3a41a8cecd623d.json b/rust/cloud-storage/email_db_client/.sqlx/query-ed5881e8c67f654f3bdb053cbde1cf449baf4e12894848ae2b3a41a8cecd623d.jsondeleted file mode 100644index c07b78f24e..0000000000--- a/rust/cloud-storage/email_db_client/.sqlx/query-ed5881e8c67f654f3bdb053cbde1cf449baf4e12894848ae2b3a41a8cecd623d.json+++ /dev/null@@ -1,14 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE email_backfill_jobs\n SET\n threads_processed_count = threads_processed_count + 1,\n threads_failed_count = threads_failed_count + 1,\n updated_at = now()\n WHERE id = $1\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": []- },- "hash": "ed5881e8c67f654f3bdb053cbde1cf449baf4e12894848ae2b3a41a8cecd623d"-}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-efd2c4f9b96af87ae335be58decb0d02e2b7e991081167f7fcf681d3bf8a8e4f.json b/rust/cloud-storage/email_db_client/.sqlx/query-efd2c4f9b96af87ae335be58decb0d02e2b7e991081167f7fcf681d3bf8a8e4f.jsondeleted file mode 100644index 5fbb4997c2..0000000000--- a/rust/cloud-storage/email_db_client/.sqlx/query-efd2c4f9b96af87ae335be58decb0d02e2b7e991081167f7fcf681d3bf8a8e4f.json+++ /dev/null@@ -1,41 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE email_backfill_threads\n SET\n messages_processed_count = messages_processed_count + 1,\n messages_failed_count = messages_failed_count + 1,\n updated_at = now()\n WHERE backfill_job_id = $1\n AND thread_provider_id = $2\n RETURNING\n messages_retrieved_count,\n messages_processed_count,\n messages_succeeded_count,\n messages_failed_count\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "messages_retrieved_count",- "type_info": "Int4"- },- {- "ordinal": 1,- "name": "messages_processed_count",- "type_info": "Int4"- },- {- "ordinal": 2,- "name": "messages_succeeded_count",- "type_info": "Int4"- },- {- "ordinal": 3,- "name": "messages_failed_count",- "type_info": "Int4"- }- ],- "parameters": {- "Left": [- "Uuid",- "Text"- ]- },- "nullable": [- false,- false,- false,- false- ]- },- "hash": "efd2c4f9b96af87ae335be58decb0d02e2b7e991081167f7fcf681d3bf8a8e4f"-}diff --git a/rust/cloud-storage/email_db_client/src/backfill/job/get.rs b/rust/cloud-storage/email_db_client/src/backfill/job/get.rsindex 3dfc0afd3c..e36706f0e6 100644--- a/rust/cloud-storage/email_db_client/src/backfill/job/get.rs+++ b/rust/cloud-storage/email_db_client/src/backfill/job/get.rs@@ -19,14 +19,6 @@ pub async fn get_backfill_job(threads_requested_limit,total_threads,threads_retrieved_count,- messages_retrieved_count,- threads_processed_count,- threads_succeeded_count,- threads_failed_count,- threads_skipped_count,- messages_processed_count,- messages_succeeded_count,- messages_failed_count,status as "status: db::backfill::BackfillJobStatus",created_at,updated_at@@ -58,14 +50,6 @@ pub async fn get_backfill_job_with_link_id(threads_requested_limit,total_threads,threads_retrieved_count,- messages_retrieved_count,- threads_processed_count,- threads_succeeded_count,- threads_failed_count,- threads_skipped_count,- messages_processed_count,- messages_succeeded_count,- messages_failed_count,status as "status: db::backfill::BackfillJobStatus",created_at,updated_at@@ -100,14 +84,6 @@ pub async fn get_recent_jobs_by_fusionauth_user_id(threads_requested_limit,total_threads,threads_retrieved_count,- messages_retrieved_count,- threads_processed_count,- threads_succeeded_count,- threads_failed_count,- threads_skipped_count,- messages_processed_count,- messages_succeeded_count,- messages_failed_count,status as "status: db::backfill::BackfillJobStatus",created_at,updated_atdiff --git a/rust/cloud-storage/email_db_client/src/backfill/job/insert.rs b/rust/cloud-storage/email_db_client/src/backfill/job/insert.rsindex 5204cf2075..724ac80978 100644--- a/rust/cloud-storage/email_db_client/src/backfill/job/insert.rs+++ b/rust/cloud-storage/email_db_client/src/backfill/job/insert.rs@@ -25,14 +25,6 @@ pub async fn create_backfill_job(threads_requested_limit,total_threads,threads_retrieved_count,- messages_retrieved_count,- threads_processed_count,- threads_succeeded_count,- threads_failed_count,- threads_skipped_count,- messages_processed_count,- messages_succeeded_count,- messages_failed_count,status as "status: db::backfill::BackfillJobStatus",created_at,updated_atdiff --git a/rust/cloud-storage/email_db_client/src/backfill/job/update.rs b/rust/cloud-storage/email_db_client/src/backfill/job/update.rsindex f4eee3053e..488fb93304 100644--- a/rust/cloud-storage/email_db_client/src/backfill/job/update.rs+++ b/rust/cloud-storage/email_db_client/src/backfill/job/update.rs@@ -117,150 +117,3 @@ pub async fn update_job_threads_retrieved_count(Ok(())}--/// Updates the number of messages discovered for a backfill job-#[tracing::instrument(skip(executor))]-pub async fn update_backfill_job_messages_discovered<'e, E>(- executor: E,- backfill_job_id: Uuid,- messages_retrieved_count: i32,-) -> anyhow::Result<()>-where- E: sqlx::Executor<'e, Database = sqlx::Postgres>,-{- let result = sqlx::query!(- r#"- UPDATE email_backfill_jobs- SET messages_retrieved_count = messages_retrieved_count + $2,- updated_at = NOW()- WHERE id = $1- "#,- backfill_job_id,- messages_retrieved_count- )- .execute(executor)- .await- .with_context(|| {- format!(- "Failed to update messages_retrieved_count for backfill job with backfill_job_id {}",- backfill_job_id- )- })?;-- if result.rows_affected() == 0 {- return Err(anyhow::anyhow!(- "No backfill job found with backfill_job_id {}",- backfill_job_id,- ));- }-- Ok(())-}--// increment the relevant counters when a thread is successfully processed-#[tracing::instrument(skip(executor), level = "info")]-pub async fn record_thread_success_in_job<'e, E>(- executor: E,- job_id: Uuid,- counters: service::backfill::BackfillThreadCounters,-) -> anyhow::Result<service::backfill::BackfillJobCounters>-where- E: sqlx::Executor<'e, Database = sqlx::Postgres>,-{- let counters: service::backfill::BackfillThreadCounters = counters;-- let job_counters = sqlx::query_as!(- db::backfill::BackfillJobCounters,- r#"- UPDATE email_backfill_jobs- SET- threads_processed_count = threads_processed_count + 1,- threads_succeeded_count = threads_succeeded_count + 1,- messages_processed_count = messages_processed_count + $2,- messages_succeeded_count = messages_succeeded_count + $3,- messages_failed_count = messages_failed_count + $4,- updated_at = now()- WHERE id = $1- RETURNING total_threads, threads_processed_count- "#,- job_id,- counters.messages_processed_count,- counters.messages_succeeded_count,- counters.messages_failed_count- )- .fetch_one(executor)- .await- .with_context(|| {- format!(- "Failed to record thread success for backfill job {}",- job_id- )- })?;-- Ok(job_counters.into())-}--#[tracing::instrument(skip(executor), level = "info")]-pub async fn record_thread_skipped_in_job<'e, E>(- executor: E,- job_id: Uuid,-) -> anyhow::Result<service::backfill::BackfillJobCounters>-where- E: sqlx::Executor<'e, Database = sqlx::Postgres>,-{- let job_counters = sqlx::query_as!(- db::backfill::BackfillJobCounters,- r#"- UPDATE email_backfill_jobs- SET- threads_processed_count = threads_processed_count + 1,- threads_skipped_count = threads_skipped_count + 1,- updated_at = now()- WHERE id = $1- RETURNING total_threads, threads_processed_count- "#,- job_id- )- .fetch_one(executor)- .await- .with_context(|| {- format!(- "Failed to record thread skipped for backfill job {}",- job_id- )- })?;-- Ok(job_counters.into())-}--#[tracing::instrument(skip(pool), level = "info")]-pub async fn record_thread_failure_in_job(pool: &PgPool, job_id: Uuid) -> anyhow::Result<()> {- let result = sqlx::query!(- r#"- UPDATE email_backfill_jobs- SET- threads_processed_count = threads_processed_count + 1,- threads_failed_count = threads_failed_count + 1,- updated_at = now()- WHERE id = $1- "#,- job_id- )- .execute(pool)- .await- .with_context(|| {- format!(- "Failed to record thread failure for backfill job {}",- job_id- )- })?;-- if result.rows_affected() == 0 {- return Err(anyhow::anyhow!(- "Attempted to record thread failure, but no backfill job was found with ID: {}",- job_id- ));- }-- Ok(())-}diff --git a/rust/cloud-storage/email_db_client/src/backfill/message/mod.rs b/rust/cloud-storage/email_db_client/src/backfill/message/mod.rsdeleted file mode 100644index 282fd57434..0000000000--- a/rust/cloud-storage/email_db_client/src/backfill/message/mod.rs+++ /dev/null@@ -1,103 +0,0 @@-use anyhow::Context;-use models_email::email::db;-use models_email::email::db::backfill::BackfillMessageStatus;-use models_email::email::service::backfill;-use sqlx::types::Uuid;--/// Creates a backfill message record in the database or increments retry count if it exists-#[tracing::instrument(skip(executor))]-pub async fn upsert_backfill_message<'e, E>(- executor: E,- backfill_job_id: Uuid,- thread_provider_id: &str,- message_provider_id: &str,-) -> anyhow::Result<()>-where- E: sqlx::Executor<'e, Database = sqlx::Postgres>,-{- sqlx::query!(- r#"- INSERT INTO email_backfill_messages (backfill_job_id, thread_provider_id, message_provider_id, status)- VALUES ($1, $2, $3, 'InProgress')- ON CONFLICT (backfill_job_id, thread_provider_id, message_provider_id)- DO UPDATE SET- updated_at = NOW(),- retry_count = email_backfill_messages.retry_count + 1- "#,- backfill_job_id,- thread_provider_id,- message_provider_id- )- .execute(executor)- .await- .with_context(|| {- format!(- "Failed to create backfill message record for backfill_job_id {}, thread_provider_id {} and message_provider_id {}",- backfill_job_id, thread_provider_id, message_provider_id- )- })?;-- Ok(())-}--#[tracing::instrument(skip(executor))]-pub async fn update_backfill_message_status<'e, E>(- executor: E,- backfill_job_id: Uuid,- thread_provider_id: &str,- message_provider_id: &str,- status: backfill::BackfillMessageStatus,- error_message: Option<String>,-) -> anyhow::Result<()>-where- E: sqlx::Executor<'e, Database = sqlx::Postgres>,-{- let db_status: BackfillMessageStatus = status.into();-- // If error_message is None, we'll keep the existing error_message in the database- if error_message.is_none() {- sqlx::query!(- r#"- UPDATE email_backfill_messages- SET status = $4, updated_at = NOW()- WHERE backfill_job_id = $1 AND thread_provider_id = $2 AND message_provider_id = $3- "#,- backfill_job_id,- thread_provider_id,- message_provider_id,- db_status as db::backfill::BackfillMessageStatus,- )- .execute(executor)- .await- .with_context(|| {- format!(- "Failed to update status for backfill message with backfill_job_id {}, thread_provider_id {} and message_provider_id {}",- backfill_job_id, thread_provider_id, message_provider_id- )- })?;- } else {- // If error_message is Some, update both status and error_message- sqlx::query!(- r#"- UPDATE email_backfill_messages- SET status = $4, error_message = $5, updated_at = NOW()- WHERE backfill_job_id = $1 AND thread_provider_id = $2 AND message_provider_id = $3- "#,- backfill_job_id,- thread_provider_id,- message_provider_id,- db_status as db::backfill::BackfillMessageStatus,- error_message- )- .execute(executor)- .await- .with_context(|| {- format!(- "Failed to update status for backfill message with backfill_job_id {}, thread_provider_id {} and message_provider_id {}",- backfill_job_id, thread_provider_id, message_provider_id- )- })?;- }-- Ok(())-}diff --git a/rust/cloud-storage/email_db_client/src/backfill/mod.rs b/rust/cloud-storage/email_db_client/src/backfill/mod.rsindex f166be6b2e..80daa3eae2 100644--- a/rust/cloud-storage/email_db_client/src/backfill/mod.rs+++ b/rust/cloud-storage/email_db_client/src/backfill/mod.rs@@ -1,3 +1 @@pub mod job;-pub mod message;-pub mod thread;diff --git a/rust/cloud-storage/email_db_client/src/backfill/thread/mod.rs b/rust/cloud-storage/email_db_client/src/backfill/thread/mod.rsdeleted file mode 100644index 3eeacbffc4..0000000000--- a/rust/cloud-storage/email_db_client/src/backfill/thread/mod.rs+++ /dev/null@@ -1,227 +0,0 @@-use anyhow::Context;-use models_email::email::{db, service};-use sqlx::PgPool;-use sqlx::types::Uuid;--/// Creates a backfill thread record in the database or increments retry count if it exists-#[tracing::instrument(skip(executor))]-pub async fn upsert_backfill_thread<'e, E>(- executor: E,- backfill_job_id: Uuid,- thread_provider_id: &str,-) -> anyhow::Result<()>-where- E: sqlx::Executor<'e, Database = sqlx::Postgres>,-{- sqlx::query!(- r#"- INSERT INTO email_backfill_threads (backfill_job_id, thread_provider_id, status)- VALUES ($1, $2, 'InProgress')- ON CONFLICT (backfill_job_id, thread_provider_id)- DO UPDATE SET- updated_at = NOW(),- retry_count = email_backfill_threads.retry_count + 1- "#,- backfill_job_id,- thread_provider_id- )- .execute(executor)- .await- .with_context(|| {- format!(- "Failed to create or update backfill thread record for backfill_job_id {} and thread_provider_id {}",- backfill_job_id, thread_provider_id- )- })?;-- Ok(())-}--/// Updates the status of a backfill thread record in the database-#[tracing::instrument(skip(executor))]-pub async fn update_backfill_thread_status<'e, E>(- executor: E,- backfill_job_id: Uuid,- thread_provider_id: &str,- status: service::backfill::BackfillThreadStatus,- error_message: Option<String>,-) -> anyhow::Result<()>-where- E: sqlx::Executor<'e, Database = sqlx::Postgres>,-{- let db_status: db::backfill::BackfillThreadStatus = status.into();-- sqlx::query!(- r#"- UPDATE email_backfill_threads- SET status = $3, error_message = $4, updated_at = NOW()- WHERE backfill_job_id = $1 AND thread_provider_id = $2- AND status != $3- "#,- backfill_job_id,- thread_provider_id,- db_status as db::backfill::BackfillThreadStatus,- error_message- )- .execute(executor)- .await- .with_context(|| {- format!(- "Failed to update status for backfill thread with backfill_job_id {} and thread_provider_id {}",- backfill_job_id, thread_provider_id- )- })?;-- Ok(())-}--pub async fn update_backfill_thread_success<'e, E>(- executor: E,- backfill_job_id: Uuid,- thread_provider_id: &str,-) -> anyhow::Result<service::backfill::BackfillThreadCounters>-where- E: sqlx::Executor<'e, Database = sqlx::Postgres>,-{- let db_status = db::backfill::BackfillThreadStatus::Completed;-- let counters = sqlx::query_as!(- db::backfill::BackfillThreadCounters,- r#"- UPDATE email_backfill_threads- SET status = $3, metadata_updated = true, updated_at = NOW()- WHERE backfill_job_id = $1 AND thread_provider_id = $2- RETURNING messages_retrieved_count, messages_processed_count, messages_succeeded_count, messages_failed_count- "#,- backfill_job_id,- thread_provider_id,- db_status as db::backfill::BackfillThreadStatus,- )- .fetch_one(executor)- .await- .with_context(|| {- format!(- "Failed to update status for backfill thread with backfill_job_id {} and thread_provider_id {}",- backfill_job_id, thread_provider_id- )- })?;-- Ok(counters.into())-}--/// Updates the number of messages discovered for a backfill thread-#[tracing::instrument(skip(executor))]-pub async fn update_backfill_thread_messages_discovered<'e, E>(- executor: E,- backfill_job_id: Uuid,- thread_provider_id: &str,- messages_retrieved_count: i32,-) -> anyhow::Result<()>-where- E: sqlx::Executor<'e, Database = sqlx::Postgres>,-{- let result = sqlx::query!(- r#"- UPDATE email_backfill_threads- SET messages_retrieved_count = $3, updated_at = NOW()- WHERE backfill_job_id = $1 AND thread_provider_id = $2- "#,- backfill_job_id,- thread_provider_id,- messages_retrieved_count- )- .execute(executor)- .await- .with_context(|| {- format!(- "Failed to update messages_retrieved_count for backfill thread with backfill_job_id {} and thread_provider_id {}",- backfill_job_id, thread_provider_id- )- })?;-- if result.rows_affected() == 0 {- return Err(anyhow::anyhow!(- "No backfill thread found with backfill_job_id: {} and thread_provider_id: {}",- backfill_job_id,- thread_provider_id- ));- }-- Ok(())-}--#[tracing::instrument(skip(pool), level = "info")]-pub async fn record_message_success_in_thread(- pool: &PgPool,- job_id: Uuid,- thread_provider_id: &str,-) -> anyhow::Result<service::backfill::BackfillThreadCounters> {- // using RETURNING avoids a second network round trip- let counters = sqlx::query_as!(- db::backfill::BackfillThreadCounters,- r#"- UPDATE email_backfill_threads- SET- messages_processed_count = messages_processed_count + 1,- messages_succeeded_count = messages_succeeded_count + 1,- updated_at = now()- WHERE backfill_job_id = $1- AND thread_provider_id = $2- RETURNING- messages_retrieved_count,- messages_processed_count,- messages_succeeded_count,- messages_failed_count- "#,- job_id,- thread_provider_id- )- .fetch_one(pool)- .await- .with_context(|| {- format!(- "Failed to record message success for backfill job {} thread {}",- job_id, thread_provider_id- )- })?;-- Ok(counters.into())-}--#[tracing::instrument(skip(pool), level = "info")]-pub async fn record_message_failure_in_thread(- pool: &PgPool,- job_id: Uuid,- thread_provider_id: &str,-) -> anyhow::Result<service::backfill::BackfillThreadCounters> {- // using RETURNING avoids a second networkround trip- let counters = sqlx::query_as!(- db::backfill::BackfillThreadCounters,- r#"- UPDATE email_backfill_threads- SET- messages_processed_count = messages_processed_count + 1,- messages_failed_count = messages_failed_count + 1,- updated_at = now()- WHERE backfill_job_id = $1- AND thread_provider_id = $2- RETURNING- messages_retrieved_count,- messages_processed_count,- messages_succeeded_count,- messages_failed_count- "#,- job_id,- thread_provider_id- )- .fetch_one(pool)- .await- .with_context(|| {- format!(- "Failed to record message failure for backfill job {} thread {}",- job_id, thread_provider_id- )- })?;-- Ok(counters.into())-}diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.tomlindex 7516ff8618..5cf38645f7 100644--- a/rust/cloud-storage/email_service/Cargo.toml+++ b/rust/cloud-storage/email_service/Cargo.toml@@ -42,10 +42,8 @@ html-escape = "0.2"http-body-util = { workspace = true }infer = "0.19.0"insight_service_client = { path = "../insight_service_client" }-lazy_static = { workspace = true }lol_html = "2.4.0"macro_auth = { path = "../macro_auth" }-macro_axum_utils = { path = "../macro_axum_utils" }macro_cors = { path = "../macro_cors" }macro_entrypoint = { path = "../macro_entrypoint" }macro_env = { path = "../macro_env" }@@ -65,7 +63,6 @@ redis = { workspace = true, features = ["cluster-async","tokio-native-tls-comp",] }-regex = { workspace = true }reqwest = { workspace = true, features = ["stream"] }s3_client = { path = "../s3_client" }schemars = { workspace = true }diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rsindex 31db0fea43..f3ad58e301 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rs@@ -1,10 +1,8 @@+use crate::pubsub::backfill::increment_counters;use crate::pubsub::context::PubSubContext;use crate::pubsub::util::check_gmail_rate_limit;use crate::util::process_pre_insert::process_message_pre_insert;-use models_email::email::service::backfill::{- BackfillMessagePayload, BackfillMessageStatus, BackfillOperation, BackfillPubsubMessage,- UpdateMetadataPayload,-};+use models_email::email::service::backfill::{BackfillMessagePayload, BackfillPubsubMessage};use models_email::email::service::link;use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};use models_email::gmail::operations::GmailApiOperation;@@ -20,21 +18,6 @@ pub async fn backfill_message(link: &link::Link,p: &BackfillMessagePayload,) -> Result<(), ProcessingError> {- // creates the backfill message or increments its retry count if it already exists- email_db_client::backfill::message::upsert_backfill_message(- &ctx.db,- data.job_id,- &p.thread_provider_id,- &p.message_provider_id,- )- .await- .map_err(|e| {- ProcessingError::Retryable(DetailedError {- reason: FailureReason::DatabaseQueryFailed,- source: e.context("Failed to create backfill message record"),- })- })?;-check_gmail_rate_limit(&ctx.redis_client,link.id,@@ -42,6 +25,7 @@ pub async fn backfill_message(true,).await?;+// get message from gmaillet mut message = match ctx.gmail_client@@ -83,81 +67,5 @@ pub async fn backfill_message(})?;// Handle all success-related operations- handle_message_success(ctx, link, data, p).await-}--/// Handles all success-related operations after a message has been successfully processed-#[tracing::instrument(skip(ctx))]-async fn handle_message_success(- ctx: &PubSubContext,- link: &link::Link,- data: &BackfillPubsubMessage,- p: &BackfillMessagePayload,-) -> Result<(), ProcessingError> {- // Update message status to completed- email_db_client::backfill::message::update_backfill_message_status(- &ctx.db,- data.job_id,- &p.thread_provider_id,- &p.message_provider_id,- BackfillMessageStatus::Completed,- None,- )- .await- .map_err(|e| {- ProcessingError::Retryable(DetailedError {- reason: FailureReason::DatabaseQueryFailed,- source: e.context(format!(- "Update backfill message status db call for {} failed",- p.message_provider_id- )),- })- })?;-- // Update thread-level counters- let thread_counters = email_db_client::backfill::thread::record_message_success_in_thread(- &ctx.db,- data.job_id,- &p.thread_provider_id,- )- .await- .map_err(|e| {- ProcessingError::Retryable(DetailedError {- reason: FailureReason::DatabaseQueryFailed,- source: e.context(format!(- "Record message success for {} failed",- p.message_provider_id- )),- })- })?;-- // If this is the last message to be processed in the thread, we can move on to updating the- // thread metadata.- let thread_backfill_complete =- thread_counters.messages_processed_count >= thread_counters.messages_retrieved_count;-- if thread_backfill_complete {- let new_payload = UpdateMetadataPayload {- thread_provider_id: p.thread_provider_id.clone(),- thread_db_id: p.thread_db_id,- };-- let ps_message = BackfillPubsubMessage {- link_id: link.id,- job_id: data.job_id,- backfill_operation: BackfillOperation::UpdateThreadMetadata(new_payload),- };-- ctx.sqs_client- .enqueue_email_backfill_message(ps_message)- .await- .map_err(|e| {- ProcessingError::NonRetryable(DetailedError {- reason: FailureReason::SqsEnqueueFailed,- source: e.context("Failed to enqueue metadata message".to_string()),- })- })?;- }-- Ok(())+ increment_counters::incr_completed_messages(ctx, link.id, data.job_id, p).await}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_thread.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_thread.rsindex 3054adad19..dfbc9961b9 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_thread.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_thread.rs@@ -1,10 +1,8 @@+use crate::pubsub::backfill::increment_counters::incr_completed_threads;use crate::pubsub::context::PubSubContext;use crate::pubsub::util::check_gmail_rate_limit;-use crate::util::backfill::backfill_insights::backfill_email_insights;-use model::insight_context::email_insights::BackfillEmailInsightsFilter;use models_email::email::service::backfill::{- BackfillJobStatus, BackfillMessagePayload, BackfillOperation, BackfillPubsubMessage,- BackfillThreadPayload, BackfillThreadStatus,+ BackfillMessagePayload, BackfillOperation, BackfillPubsubMessage, BackfillThreadPayload,};use models_email::email::service::link;use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};@@ -24,23 +22,6 @@ pub async fn backfill_thread() -> Result<(), ProcessingError> {let thread_provider_id = p.thread_provider_id.clone();- // creates the backfill message or increments its retry count if it already exists- email_db_client::backfill::thread::upsert_backfill_thread(- &ctx.db,- data.job_id,- &thread_provider_id,- )- .await- .map_err(|e| {- ProcessingError::Retryable(DetailedError {- reason: FailureReason::DatabaseQueryFailed,- source: e.context(format!(- "Failed to create backfill thread record for {}",- thread_provider_id- )),- })- })?;-let existing_threads = email_db_client::threads::get::get_threads_by_link_id_and_provider_ids(&ctx.db,link.id,@@ -57,9 +38,9 @@ pub async fn backfill_thread(})})?;- // if the thread already exists, skip backfilling and update backfill_job counters+ // if the thread already exists, skip backfilling and update redis countersif !existing_threads.is_empty() {- skip_thread(&ctx, data, link, &thread_provider_id).await?;+ incr_completed_threads(ctx, &link.macro_id, data.job_id).await?;return Ok(());}@@ -88,6 +69,19 @@ pub async fn backfill_thread(}};+ ctx.redis_client+ .init_backfill_thread_progress(data.job_id, &thread_provider_id, message_ids.len() as i32)+ .await+ .map_err(|e| {+ ProcessingError::Retryable(DetailedError {+ reason: FailureReason::RedisQueryFailed,+ source: e.context(format!(+ "Failed to create entry in redis for thread {}",+ &thread_provider_id+ )),+ })+ })?;+// insert thread objectlet thread_db_id = email_db_client::threads::insert::insert_blank_thread(&ctx.db,@@ -105,40 +99,6 @@ pub async fn backfill_thread(})})?;- // update messages_retrieved_count counter for thread and job- email_db_client::backfill::thread::update_backfill_thread_messages_discovered(- &ctx.db,- data.job_id,- &p.thread_provider_id,- message_ids.len() as i32,- )- .await- .map_err(|e| {- ProcessingError::Retryable(DetailedError {- reason: FailureReason::DatabaseQueryFailed,- source: e.context(format!(- "update thread messages discovered call for {} failed",- thread_provider_id- )),- })- })?;-- email_db_client::backfill::job::update::update_backfill_job_messages_discovered(- &ctx.db,- data.job_id,- message_ids.len() as i32,- )- .await- .map_err(|e| {- ProcessingError::Retryable(DetailedError {- reason: FailureReason::DatabaseQueryFailed,- source: e.context(format!(- "update job messages discovered call for {} failed",- thread_provider_id- )),- })- })?;-// create backfill pubsub message for each email messagefor message_id in message_ids.clone() {let new_payload = BackfillMessagePayload {@@ -166,93 +126,3 @@ pub async fn backfill_thread(Ok(())}--async fn skip_thread(- ctx: &&PubSubContext,- data: &BackfillPubsubMessage,- link: &link::Link,- thread_provider_id: &str,-) -> Result<(), ProcessingError> {- email_db_client::backfill::thread::update_backfill_thread_status(- &ctx.db,- data.job_id,- thread_provider_id,- BackfillThreadStatus::Skipped,- None,- )- .await- .map_err(|e| {- ProcessingError::Retryable(DetailedError {- reason: FailureReason::DatabaseQueryFailed,- source: e.context(format!(- "Update backfill thread status db call to {} for {} failed",- BackfillThreadStatus::Skipped,- thread_provider_id- )),- })- })?;-- let job_counters =- email_db_client::backfill::job::update::record_thread_skipped_in_job(&ctx.db, data.job_id)- .await- .map_err(|e| {- ProcessingError::Retryable(DetailedError {- reason: FailureReason::DatabaseQueryFailed,- source: e.context(format!(- "record backfill thread skipped call for {} failed",- thread_provider_id- )),- })- })?;-- // if all threads needing backfill have been processed, update job status to complete- let all_threads_processed_count =- job_counters.threads_processed_count >= job_counters.total_threads;-- if all_threads_processed_count {- tracing::info!("Backfill complete for job {}", data.job_id);- email_db_client::backfill::job::update::update_backfill_job_status(- &ctx.db,- data.job_id,- BackfillJobStatus::Complete,- )- .await- .map_err(|e| {- ProcessingError::Retryable(DetailedError {- reason: FailureReason::DatabaseQueryFailed,- source: e.context("Failed to update thread status to complete"),- })- })?;-- tracing::info!("Backfilling email insights for user {}", link.macro_id);- let backfill_email_insights_filter = BackfillEmailInsightsFilter {- user_ids: Some(vec![link.macro_id.clone()]),- user_thread_limit: None,- };-- match backfill_email_insights(- ctx.sqs_client.clone(),- &ctx.db,- backfill_email_insights_filter,- )- .await- {- Ok(res) => {- tracing::info!(- "Backfilled email insights for user {} with job ids: {:?}",- link.macro_id,- res.job_ids- );- }- Err(e) => {- tracing::error!(- error = ?e,- "Failed to backfill email insights for user {}",- link.macro_id- );- }- }- }-- Ok(())-}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rsindex 96674fe1e0..f28643ae00 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rs@@ -1,8 +1,8 @@+use crate::pubsub::backfill::increment_counters;+use crate::pubsub::backfill::increment_counters::incr_completed_threads;use crate::pubsub::context::PubSubContext;-use models_email::email::service::backfill::UpdateMetadataPayload;use models_email::email::service::backfill::{- BackfillJobStatus, BackfillMessagePayload, BackfillMessageStatus, BackfillOperation,- BackfillPubsubMessage, BackfillThreadStatus,+ BackfillJobStatus, BackfillMessagePayload, BackfillOperation, BackfillPubsubMessage,};use models_email::email::service::pubsub::{DetailedError, ProcessingError};use sqs_worker::cleanup_message;@@ -49,26 +49,14 @@ pub async fn handle_non_retryable_error();}}- BackfillOperation::BackfillThread(p) => {- handle_thread_failure(- ctx,- data.job_id,- &p.thread_provider_id,- &e.reason.to_string(),- )- .await;+ BackfillOperation::BackfillThread(_) => {+ handle_thread_failure(ctx, data.link_id, data.job_id).await;}BackfillOperation::BackfillMessage(p) => {- handle_message_failure(ctx, data, p, &e.reason.to_string()).await?;+ handle_message_failure(ctx, data, p).await?;}- BackfillOperation::UpdateThreadMetadata(p) => {- handle_thread_failure(- ctx,- data.job_id,- &p.thread_provider_id,- &e.reason.to_string(),- )- .await;+ BackfillOperation::UpdateThreadMetadata(_) => {+ handle_thread_failure(ctx, data.link_id, data.job_id).await;}}@@ -77,11 +65,10 @@ pub async fn handle_non_retryable_error(}/// Handles retryable errors by updating status to InProgress and adding the error message-#[tracing::instrument(skip(ctx))]+#[tracing::instrument(err)]pub async fn handle_retryable_error(- ctx: &PubSubContext,data: &BackfillPubsubMessage,- e: &DetailedError,+ _e: &DetailedError,) -> anyhow::Result<()> {match &data.backfill_operation {BackfillOperation::Init => {@@ -95,23 +82,6 @@ pub async fn handle_retryable_error(thread_id = %p.thread_provider_id,"Retryable error backfilling thread");-- // update error_message of backfill_thread but keep status as InProgress- if let Err(db_err) = email_db_client::backfill::thread::update_backfill_thread_status(- &ctx.db,- data.job_id,- &p.thread_provider_id,- BackfillThreadStatus::InProgress,- Some(e.reason.to_string()),- )- .await- {- tracing::error!(- error = %db_err,- thread_id = %p.thread_provider_id,- "Failed to update backfill thread error message"- );- }}BackfillOperation::BackfillMessage(p) => {tracing::debug!(@@ -119,83 +89,43 @@ pub async fn handle_retryable_error(message_id = %p.message_provider_id,"Retryable error backfilling message");-- // update error message of backfill_message but keep status as InProgress- if let Err(db_err) = email_db_client::backfill::message::update_backfill_message_status(- &ctx.db,- data.job_id,- &p.thread_provider_id,- &p.message_provider_id,- BackfillMessageStatus::InProgress,- Some(e.reason.to_string()),- )- .await- {- tracing::error!(- error = %db_err,- thread_id = %p.thread_provider_id,- message_id = %p.message_provider_id,- "Failed to update backfill message error message"- );- }}BackfillOperation::UpdateThreadMetadata(p) => {tracing::debug!(thread_id = %p.thread_provider_id,"Retryable error backfilling thread");-- // update error_message of backfill_thread but keep status as InProgress- if let Err(db_err) = email_db_client::backfill::thread::update_backfill_thread_status(- &ctx.db,- data.job_id,- &p.thread_provider_id,- BackfillThreadStatus::InProgress,- Some(e.reason.to_string()),- )- .await- {- tracing::error!(- error = %db_err,- thread_id = %p.thread_provider_id,- "Failed to update backfill thread error message"- );- }}}Ok(())}#[tracing::instrument(skip(ctx))]-async fn handle_thread_failure(- ctx: &PubSubContext,- job_id: Uuid,- thread_provider_id: &str,- error_reason: &str,-) {- // update status of backfill_thread entry to failed- if let Err(db_err) = email_db_client::backfill::thread::update_backfill_thread_status(- &ctx.db,- job_id,- thread_provider_id,- BackfillThreadStatus::Failed,- Some(error_reason.to_string()),- )- .await- {- tracing::error!(- error = %db_err,- "Failed to update backfill thread status to Failed"- );- }+async fn handle_thread_failure(ctx: &PubSubContext, link_id: Uuid, job_id: Uuid) {+ let link = match email_db_client::links::get::fetch_link_by_id(&ctx.db, link_id).await {+ Ok(Some(link)) => link,+ Ok(None) => {+ tracing::error!(+ link_id = link_id.to_string(),+ job_id = job_id.to_string(),+ "Link not found"+ );+ return;+ }+ Err(db_err) => {+ tracing::error!(+ error = %db_err,+ "Failed to fetch link"+ );+ return;+ }+ };- // update counters in backfill_job- if let Err(db_err) =- email_db_client::backfill::job::update::record_thread_failure_in_job(&ctx.db, job_id).await- {+ if let Err(err) = incr_completed_threads(ctx, &link.macro_id, job_id).await {tracing::error!(- error = %db_err,- "Failed to record backfill thread failure"+ error = %err,+ job_id = job_id.to_string(),+ "Failed to check if job is completed in handle thread failure");}}@@ -205,72 +135,6 @@ pub async fn handle_message_failure(ctx: &PubSubContext,data: &BackfillPubsubMessage,p: &BackfillMessagePayload,- error_reason: &str,) -> Result<(), ProcessingError> {- // Update status of backfill_message entry to failed- if let Err(db_err) = email_db_client::backfill::message::update_backfill_message_status(- &ctx.db,- data.job_id,- &p.thread_provider_id,- &p.message_provider_id,- BackfillMessageStatus::Failed,- Some(error_reason.to_string()),- )- .await- {- tracing::error!(- error = %db_err,- "Failed to update backfill message status to Failed"- );- }-- // Update thread-level counters- let thread_counters = match email_db_client::backfill::thread::record_message_failure_in_thread(- &ctx.db,- data.job_id,- &p.thread_provider_id,- )- .await- {- Ok(counters) => counters,- Err(db_err) => {- tracing::error!(- error = %db_err,- "Failed to record backfill message failure in thread"- );- return Ok(());- }- };-- // If this is the last message to be processed in the thread, we can move on to updating the- // thread metadata.- let thread_backfill_complete =- thread_counters.messages_processed_count >= thread_counters.messages_retrieved_count;-- if thread_backfill_complete {- let new_payload = UpdateMetadataPayload {- thread_provider_id: p.thread_provider_id.clone(),- thread_db_id: p.thread_db_id,- };-- let ps_message = BackfillPubsubMessage {- link_id: Uuid::default(), // UpdateThreadMetadata doesn't use this, and we don't have it- job_id: data.job_id,- backfill_operation: BackfillOperation::UpdateThreadMetadata(new_payload),- };-- if let Err(e) = ctx- .sqs_client- .enqueue_email_backfill_message(ps_message)- .await- {- tracing::error!(- error = %e,- "Failed to enqueue metadata message for thread_id {}",- p.thread_provider_id- );- }- }-- Ok(())+ increment_counters::incr_completed_messages(ctx, data.link_id, data.job_id, p).await}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rsnew file mode 100644index 0000000000..071e6a1dbe--- /dev/null+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs@@ -0,0 +1,120 @@+use crate::pubsub::context::PubSubContext;+use crate::util::backfill::backfill_insights::backfill_email_insights;+use model::insight_context::email_insights::BackfillEmailInsightsFilter;+use models_email::service::backfill::{+ BackfillJobStatus, BackfillMessagePayload, BackfillOperation, BackfillPubsubMessage,+ UpdateMetadataPayload,+};+use models_email::service::pubsub::{DetailedError, FailureReason, ProcessingError};+use uuid::Uuid;++// called when a thread has completed processing. checks if it is the last thread to be processed+// for the job, and if so, performs the necessary actions for job completion.+#[tracing::instrument(skip(ctx))]+pub async fn incr_completed_threads(+ ctx: &PubSubContext,+ macro_id: &str,+ job_id: Uuid,+) -> Result<(), ProcessingError> {+ let all_threads_processed = ctx+ .redis_client+ .incr_completed_threads(job_id)+ .await+ .map_err(|e| {+ ProcessingError::Retryable(DetailedError {+ reason: FailureReason::RedisQueryFailed,+ source: e.context("Failed to increment completed thread count"),+ })+ })?;++ if all_threads_processed {+ tracing::info!("Backfill complete for job {}", job_id);+ email_db_client::backfill::job::update::update_backfill_job_status(+ &ctx.db,+ job_id,+ BackfillJobStatus::Complete,+ )+ .await+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: e.context("Failed to update thread status to complete"),+ })+ })?;++ tracing::info!("Backfilling email insights for user {}", macro_id);+ let backfill_email_insights_filter = BackfillEmailInsightsFilter {+ user_ids: Some(vec![macro_id.to_string()]),+ user_thread_limit: None,+ };++ let backfill_res = backfill_email_insights(+ ctx.sqs_client.clone(),+ &ctx.db,+ backfill_email_insights_filter,+ )+ .await+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: e.context("Failed to backfill email insights"),+ })+ })?;++ tracing::info!(+ "Backfilled email insights for user {} with job ids: {:?}",+ macro_id,+ backfill_res.job_ids+ );+ }++ Ok(())+}++/// If this message was the last one in the thread to be processed, proceed to next stage of backfill for thread+#[tracing::instrument(skip(ctx))]+pub async fn incr_completed_messages(+ ctx: &PubSubContext,+ link_id: Uuid,+ job_id: Uuid,+ p: &BackfillMessagePayload,+) -> Result<(), ProcessingError> {+ let thread_backfill_complete = ctx+ .redis_client+ .incr_completed_messages(job_id, &p.thread_provider_id)+ .await+ .map_err(|e| {+ ProcessingError::Retryable(DetailedError {+ reason: FailureReason::RedisQueryFailed,+ source: e.context(format!(+ "Handle completed message for {} failed",+ p.message_provider_id+ )),+ })+ })?;++ if thread_backfill_complete {+ let new_payload = UpdateMetadataPayload {+ thread_provider_id: p.thread_provider_id.clone(),+ thread_db_id: p.thread_db_id,+ };++ let ps_message = BackfillPubsubMessage {+ link_id,+ job_id,+ backfill_operation: BackfillOperation::UpdateThreadMetadata(new_payload),+ };++ ctx.sqs_client+ .enqueue_email_backfill_message(ps_message)+ .await+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::SqsEnqueueFailed,+ source: e.context("Failed to enqueue metadata message".to_string()),+ })+ })?;+ }++ Ok(())+}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/init.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/init.rsindex 47b6e1a1ec..09cebf138f 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/init.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/init.rs@@ -90,6 +90,16 @@ pub async fn init_backfill(})})?;+ ctx.redis_client+ .init_backfill_job_progress(data.job_id, total_threads)+ .await+ .map_err(|e| {+ ProcessingError::Retryable(DetailedError {+ reason: FailureReason::RedisQueryFailed,+ source: e.context("Failed to create entry in redis for job"),+ })+ })?;+let thread_sqs_msg = BackfillPubsubMessage {link_id: data.link_id,job_id: data.job_id,diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rsindex 088368a08c..324ab44df9 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rs@@ -1,6 +1,7 @@mod backfill_message;mod backfill_thread;mod error_handlers;+mod increment_counters;mod init;mod list_threads;mod process;diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/process.rsindex 831a9d1481..b8ad3532b0 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs@@ -5,8 +5,7 @@ use crate::pubsub::context::PubSubContext;use crate::util::gmail::auth::fetch_gmail_access_token_from_link;use anyhow::Context;use models_email::email::service::backfill::{- BackfillJobStatus, BackfillMessageStatus, BackfillOperation, BackfillPubsubMessage,- BackfillThreadStatus,+ BackfillJobStatus, BackfillOperation, BackfillPubsubMessage,};use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};use sqs_worker::cleanup_message;@@ -44,7 +43,7 @@ pub async fn process_message(// A temporary failure occurred. We log it and don't clean up the message, so it gets retriedErr(ProcessingError::Retryable(e)) => {- error_handlers::handle_retryable_error(&ctx, &data, &e).await+ error_handlers::handle_retryable_error(&data, &e).await}}}@@ -145,88 +144,22 @@ async fn handle_cancel_backfill_job(ctx: &PubSubContext,data: &BackfillPubsubMessage,) -> anyhow::Result<()> {+ let _ = ctx+ .redis_client+ .delete_backfill_job_progress(data.job_id)+ .await;+match &data.backfill_operation {BackfillOperation::Init => Ok(()),BackfillOperation::ListThreads(_) => Ok(()),- BackfillOperation::BackfillThread(p) => {- let _ = email_db_client::backfill::thread::update_backfill_thread_status(- &ctx.db,- data.job_id,- &p.thread_provider_id,- BackfillThreadStatus::Cancelled,- None,- )- .await- .inspect_err(|e| {- tracing::warn!(- "Failed to set thread status to cancelled \- for job_id {} and thread_provider_id {}: {}",- data.job_id,- p.thread_provider_id,- e- )- });- Ok(())- }+ BackfillOperation::BackfillThread(_) => Ok(()),BackfillOperation::BackfillMessage(p) => {- let _ = email_db_client::backfill::thread::update_backfill_thread_status(- &ctx.db,- data.job_id,- &p.thread_provider_id,- BackfillThreadStatus::Cancelled,- None,- )- .await- .inspect_err(|e| {- tracing::warn!(- "Failed to set thread status to cancelled \- for job_id {} and thread_provider_id {}: {}",- data.job_id,- p.thread_provider_id,- e- )- });-- let _ = email_db_client::backfill::message::update_backfill_message_status(- &ctx.db,- data.job_id,- &p.thread_provider_id,- &p.message_provider_id,- BackfillMessageStatus::Cancelled,- None,- )- .await- .inspect_err(|e| {- tracing::warn!(- "Failed to set message status to cancelled \- for job_id {} and thread_provider_id {} and message_provider_id {}: {}",- data.job_id,- p.thread_provider_id,- p.message_provider_id,- e- )- });- Ok(())- }- BackfillOperation::UpdateThreadMetadata(p) => {- let _ = email_db_client::backfill::thread::update_backfill_thread_status(- &ctx.db,- data.job_id,- &p.thread_provider_id,- BackfillThreadStatus::Cancelled,- None,- )- .await- .inspect_err(|e| {- tracing::warn!(- "Failed to set thread status to cancelled \- for job_id {} and thread_provider_id {}: {}",- data.job_id,- p.thread_provider_id,- e- )- });+ let _ = ctx+ .redis_client+ .delete_backfill_thread_progress(data.job_id, &p.thread_provider_id)+ .await;Ok(())}+ BackfillOperation::UpdateThreadMetadata(_) => Ok(()),}}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/update_metadata.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/update_metadata.rsindex cb6cc3a70c..32e5793765 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/update_metadata.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/update_metadata.rs@@ -1,9 +1,6 @@+use crate::pubsub::backfill::increment_counters::incr_completed_threads;use crate::pubsub::context::PubSubContext;-use crate::util::backfill::backfill_insights::backfill_email_insights;-use model::insight_context::email_insights::BackfillEmailInsightsFilter;-use models_email::email::service::backfill::{- BackfillJobStatus, BackfillPubsubMessage, UpdateMetadataPayload,-};+use models_email::email::service::backfill::{BackfillPubsubMessage, UpdateMetadataPayload};use models_email::email::service::link;use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};use sqs_client::search::SearchQueueMessage;@@ -56,99 +53,6 @@ pub async fn update_thread_metadata(})})?;- // update job status to complete and get back counters to update the job with- let thread_counters = email_db_client::backfill::thread::update_backfill_thread_success(- &mut *tx,- data.job_id,- &p.thread_provider_id,- )- .await- .map_err(|e| {- ProcessingError::Retryable(DetailedError {- reason: FailureReason::DatabaseQueryFailed,- source: e.context("Failed to update thread status to complete"),- })- })?;-- // notify search-service about the new thread- let search_message = SearchQueueMessage::ExtractEmailThreadMessage(EmailThreadMessage {- thread_id: p.thread_db_id.clone().to_string(),- macro_user_id: link.macro_id.clone(),- });-- ctx.sqs_client- .send_message_to_search_event_queue(search_message)- .await- .map_err(|e| {- ProcessingError::NonRetryable(DetailedError {- reason: FailureReason::SqsEnqueueFailed,- source: e.context("Failed to send message to search extractor queue"),- })- })?;-- // update job counters with thread counters- let job_counters = email_db_client::backfill::job::update::record_thread_success_in_job(- &mut *tx,- data.job_id,- thread_counters,- )- .await- .map_err(|e| {- ProcessingError::Retryable(DetailedError {- reason: FailureReason::DatabaseQueryFailed,- source: e.context("Failed to update thread status to complete"),- })- })?;-- // if all threads needing backfill have been processed, update job status to complete- let all_threads_processed =- job_counters.threads_processed_count >= job_counters.total_threads;-- if all_threads_processed {- tracing::info!("Backfill complete for job {}", data.job_id);- email_db_client::backfill::job::update::update_backfill_job_status(- &mut *tx,- data.job_id,- BackfillJobStatus::Complete,- )- .await- .map_err(|e| {- ProcessingError::Retryable(DetailedError {- reason: FailureReason::DatabaseQueryFailed,- source: e.context("Failed to update thread status to complete"),- })- })?;-- tracing::info!("Backfilling email insights for user {}", link.macro_id);- let backfill_email_insights_filter = BackfillEmailInsightsFilter {- user_ids: Some(vec![link.macro_id.clone()]),- user_thread_limit: None,- };-- match backfill_email_insights(- ctx.sqs_client.clone(),- &ctx.db,- backfill_email_insights_filter,- )- .await- {- Ok(res) => {- tracing::info!(- "Backfilled email insights for user {} with job ids: {:?}",- link.macro_id,- res.job_ids- );- }- Err(e) => {- tracing::error!(- error = ?e,- "Failed to backfill email insights for user {}",- link.macro_id- );- }- }- }-Ok(())}.await;@@ -174,5 +78,23 @@ pub async fn update_thread_metadata(})})?;+ // notify search-service about the new thread+ let search_message = SearchQueueMessage::ExtractEmailThreadMessage(EmailThreadMessage {+ thread_id: p.thread_db_id.clone().to_string(),+ macro_user_id: link.macro_id.clone(),+ });++ ctx.sqs_client+ .send_message_to_search_event_queue(search_message)+ .await+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::SqsEnqueueFailed,+ source: e.context("Failed to send message to search extractor queue"),+ })+ })?;++ incr_completed_threads(ctx, &link.macro_id, data.job_id).await?;+Ok(())}diff --git a/rust/cloud-storage/email_service/src/util/redis/backfill.rs b/rust/cloud-storage/email_service/src/util/redis/backfill.rsnew file mode 100644index 0000000000..a261ad6eee--- /dev/null+++ b/rust/cloud-storage/email_service/src/util/redis/backfill.rs@@ -0,0 +1,192 @@+use crate::util::redis::RedisClient;+use anyhow::Context;+use redis::AsyncCommands;+use uuid::Uuid;++impl RedisClient {+ fn job_status_key(job_id: Uuid) -> String {+ format!("bf_job_status:{}", job_id)+ }++ fn thread_status_key(job_id: Uuid, thread_id: &str) -> String {+ format!("bf_thread_status:{}:{}", job_id, thread_id)+ }++ /// Initialize backfill job progress in Redis+ pub async fn init_backfill_job_progress(+ &self,+ job_id: Uuid,+ total_threads: i32,+ ) -> anyhow::Result<()> {+ let key = Self::job_status_key(job_id);++ let mut redis_connection = self+ .inner+ .get_multiplexed_async_connection()+ .await+ .context("unable to connect to redis")?;++ redis_connection+ .hset_multiple::<&str, &str, i32, ()>(+ &key,+ &[("total_threads", total_threads), ("completed_threads", 0)],+ )+ .await?;++ Ok(())+ }++ /// Increment completed threads count and return true if job is complete, deleting redis entry for job if so+ pub async fn incr_completed_threads(&self, job_id: Uuid) -> anyhow::Result<bool> {+ let key = Self::job_status_key(job_id);++ let mut redis_connection = self+ .inner+ .get_multiplexed_async_connection()+ .await+ .context("unable to connect to redis")?;++ let script = r#"+ local key = KEYS[1]+ local completed = redis.call('HINCRBY', key, 'completed_threads', 1)+ local total = redis.call('HGET', key, 'total_threads')+ return {completed, total}+ "#;++ let result: Vec<i32> = redis::Script::new(script)+ .key(&key)+ .invoke_async(&mut redis_connection)+ .await?;++ let completed_threads = result[0];+ let total_threads = result[1];++ let job_complete = completed_threads >= total_threads;++ if job_complete {+ let redis_client = self.clone();+ tokio::spawn(async move {+ if let Err(e) = redis_client.delete_backfill_job_progress(job_id).await {+ tracing::error!(+ "Failed to delete backfill job progress for job {}: {}",+ job_id,+ e+ );+ }+ });+ }++ Ok(job_complete)+ }++ pub async fn delete_backfill_job_progress(&self, job_id: Uuid) -> anyhow::Result<()> {+ let key = Self::job_status_key(job_id);++ let mut redis_connection = self+ .inner+ .get_multiplexed_async_connection()+ .await+ .context("unable to connect to redis")?;++ redis_connection.del::<&str, ()>(&key).await?;++ Ok(())+ }++ /// Initialize backfill thread progress in Redis+ pub async fn init_backfill_thread_progress(+ &self,+ job_id: Uuid,+ thread_id: &str,+ total_messages: i32,+ ) -> anyhow::Result<()> {+ let key = Self::thread_status_key(job_id, thread_id);++ let mut redis_connection = self+ .inner+ .get_multiplexed_async_connection()+ .await+ .context("unable to connect to redis")?;++ redis_connection+ .hset_multiple::<&str, &str, i32, ()>(+ &key,+ &[+ ("total_messages", total_messages),+ ("completed_messages", 0),+ ],+ )+ .await?;++ Ok(())+ }++ /// Increment completed messages count and return true if thread is complete, deleting redis entry for thread if so+ pub async fn incr_completed_messages(+ &self,+ job_id: Uuid,+ thread_id: &str,+ ) -> anyhow::Result<bool> {+ let key = Self::thread_status_key(job_id, thread_id);++ let mut redis_connection = self+ .inner+ .get_multiplexed_async_connection()+ .await+ .context("unable to connect to redis")?;++ let script = r#"+ local key = KEYS[1]+ local completed = redis.call('HINCRBY', key, 'completed_messages', 1)+ local total = redis.call('HGET', key, 'total_messages')+ return {completed, total}+ "#;++ let result: Vec<i32> = redis::Script::new(script)+ .key(&key)+ .invoke_async(&mut redis_connection)+ .await?;++ let completed_messages = result[0];+ let total_messages = result[1];++ let thread_complete = completed_messages >= total_messages;++ if thread_complete {+ let redis_client = self.clone();+ let thread_id = thread_id.to_string();+ tokio::spawn(async move {+ if let Err(e) = redis_client+ .delete_backfill_thread_progress(job_id, &thread_id)+ .await+ {+ tracing::error!(+ "Failed to delete backfill thread progress for thread {}: {}",+ thread_id,+ e+ );+ }+ });+ }++ Ok(thread_complete)+ }++ pub async fn delete_backfill_thread_progress(+ &self,+ job_id: Uuid,+ thread_id: &str,+ ) -> anyhow::Result<()> {+ let key = Self::thread_status_key(job_id, thread_id);++ let mut redis_connection = self+ .inner+ .get_multiplexed_async_connection()+ .await+ .context("unable to connect to redis")?;++ redis_connection.del::<&str, ()>(&key).await?;++ Ok(())+ }+}diff --git a/rust/cloud-storage/email_service/src/util/redis/mod.rs b/rust/cloud-storage/email_service/src/util/redis/mod.rsindex 96194259a4..fb50324695 100644--- a/rust/cloud-storage/email_service/src/util/redis/mod.rs+++ b/rust/cloud-storage/email_service/src/util/redis/mod.rs@@ -1,4 +1,5 @@pub mod access_token;+pub mod backfill;pub mod rate_limit;#[derive(Clone)]diff --git a/rust/cloud-storage/macro_db_client/migrations/20251111151333_email_backfill_redis.sql b/rust/cloud-storage/macro_db_client/migrations/20251111151333_email_backfill_redis.sqlnew file mode 100644index 0000000000..5e31687bcc--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20251111151333_email_backfill_redis.sql@@ -0,0 +1,15 @@+-- we now use redis to track backfill progress instead of postgres++DROP TABLE email_backfill_messages;++DROP TABLE email_backfill_threads;++ALTER TABLE email_backfill_jobs+DROP COLUMN threads_processed_count,+DROP COLUMN messages_retrieved_count,+DROP COLUMN messages_processed_count,+DROP COLUMN threads_succeeded_count,+DROP COLUMN threads_skipped_count,+DROP COLUMN threads_failed_count,+DROP COLUMN messages_succeeded_count,+DROP COLUMN messages_failed_count;diff --git a/rust/cloud-storage/models_email/src/email/db/backfill.rs b/rust/cloud-storage/models_email/src/email/db/backfill.rsindex 02598a5a1e..dc3c9c520c 100644--- a/rust/cloud-storage/models_email/src/email/db/backfill.rs+++ b/rust/cloud-storage/models_email/src/email/db/backfill.rs@@ -1,7 +1,6 @@use crate::email::service::backfill as service_backfill;use chrono::{DateTime, Utc};use serde::{Deserialize, Serialize};-use sqlx::FromRow;use strum::{AsRefStr, Display, EnumString};use uuid::Uuid;@@ -50,25 +49,6 @@ pub struct BackfillJob {// Total number of threads we pulled from gmail api during backfillpub threads_retrieved_count: i32,- // Number of threads that have been processed (succeeded + failed + skipped)- pub threads_processed_count: i32,-- // Total number of messages we pull from gmail api during backfill- pub messages_retrieved_count: i32,- // Number of messages that either succeeded or failed- pub messages_processed_count: i32,-- // Number of threads that were successfully backfilled- pub threads_succeeded_count: i32,- // Number of threads that were skipped during backfill due to already existing- pub threads_skipped_count: i32,- // Number of threads that failed during backfill- pub threads_failed_count: i32,-- // Number of messages successfully backfilled- pub messages_succeeded_count: i32,- // Number of messages that failed during backfill- pub messages_failed_count: i32,pub created_at: DateTime<Utc>,pub updated_at: DateTime<Utc>,@@ -97,58 +77,6 @@ pub enum BackfillThreadStatus {Cancelled,}-// Struct for backfill thread (Service layer)-#[derive(Debug, Serialize, Deserialize, Clone)]-pub struct BackfillThread {- pub backfill_job_id: Uuid,- pub thread_provider_id: String,- pub messages_retrieved_count: i32,- pub messages_processed_count: i32,- pub messages_succeeded_count: i32,- pub messages_failed_count: i32,- pub metadata_updated: bool,- pub status: BackfillThreadStatus,- pub error_message: Option<String>,- pub retry_count: i32,- pub created_at: DateTime<Utc>,- pub updated_at: DateTime<Utc>,-}--// Enum for backfill message status-#[derive(- Debug,- Serialize,- Deserialize,- sqlx::Type,- Clone,- Copy,- PartialEq,- Eq,- EnumString,- AsRefStr,- Display,-)]-#[sqlx(type_name = "email_backfill_message_status", rename_all = "PascalCase")]-pub enum BackfillMessageStatus {- InProgress,- Completed,- Failed,- Cancelled,-}--// Struct for the backfill_message table-#[derive(Debug, Serialize, Deserialize, Clone)]-pub struct BackfillMessage {- pub backfill_job_id: Uuid,- pub thread_provider_id: String,- pub message_provider_id: String,- pub status: BackfillMessageStatus,- pub error_message: Option<String>,- pub retry_count: i32,- pub created_at: DateTime<Utc>,- pub updated_at: DateTime<Utc>,-}-impl From<service_backfill::BackfillJobStatus> for BackfillJobStatus {fn from(status: service_backfill::BackfillJobStatus) -> Self {match status {@@ -172,18 +100,6 @@ impl From<service_backfill::BackfillJob> for BackfillJob {// Ground Truth Counterstotal_threads: job.total_threads,threads_retrieved_count: job.threads_retrieved_count,- messages_retrieved_count: job.messages_retrieved_count,-- // Thread-Level Progress- threads_processed_count: job.threads_processed_count,- threads_succeeded_count: job.threads_succeeded_count,- threads_failed_count: job.threads_failed_count,- threads_skipped_count: job.threads_skipped_count,-- // Message-Level Progress- messages_processed_count: job.messages_processed_count,- messages_succeeded_count: job.messages_succeeded_count,- messages_failed_count: job.messages_failed_count,// Job Metadatastatus: job.status.into(),@@ -204,84 +120,3 @@ impl From<service_backfill::BackfillThreadStatus> for BackfillThreadStatus {}}}--impl From<service_backfill::BackfillThread> for BackfillThread {- fn from(thread: service_backfill::BackfillThread) -> Self {- BackfillThread {- backfill_job_id: thread.backfill_job_id,- thread_provider_id: thread.thread_provider_id,- messages_retrieved_count: thread.messages_retrieved_count,- messages_processed_count: thread.messages_processed_count,- messages_succeeded_count: thread.messages_succeeded_count,- messages_failed_count: thread.messages_failed_count,- metadata_updated: thread.metadata_updated,- status: thread.status.into(),- error_message: thread.error_message,- retry_count: thread.retry_count,- created_at: thread.created_at,- updated_at: thread.updated_at,- }- }-}--impl From<service_backfill::BackfillMessageStatus> for BackfillMessageStatus {- fn from(status: service_backfill::BackfillMessageStatus) -> Self {- match status {- service_backfill::BackfillMessageStatus::InProgress => {- BackfillMessageStatus::InProgress- }- service_backfill::BackfillMessageStatus::Completed => BackfillMessageStatus::Completed,- service_backfill::BackfillMessageStatus::Failed => BackfillMessageStatus::Failed,- service_backfill::BackfillMessageStatus::Cancelled => BackfillMessageStatus::Cancelled,- }- }-}--impl From<service_backfill::BackfillMessage> for BackfillMessage {- fn from(message: service_backfill::BackfillMessage) -> Self {- BackfillMessage {- backfill_job_id: message.backfill_job_id,- thread_provider_id: message.thread_provider_id,- message_provider_id: message.message_provider_id,- status: message.status.into(),- error_message: message.error_message,- retry_count: message.retry_count,- created_at: message.created_at,- updated_at: message.updated_at,- }- }-}--#[derive(Debug, FromRow)]-pub struct BackfillJobCounters {- pub total_threads: i32,- pub threads_processed_count: i32,-}--impl From<service_backfill::BackfillJobCounters> for BackfillJobCounters {- fn from(counters: service_backfill::BackfillJobCounters) -> Self {- BackfillJobCounters {- total_threads: counters.total_threads,- threads_processed_count: counters.threads_processed_count,- }- }-}--#[derive(Debug, FromRow)]-pub struct BackfillThreadCounters {- pub messages_retrieved_count: i32,- pub messages_processed_count: i32,- pub messages_succeeded_count: i32,- pub messages_failed_count: i32,-}--impl From<service_backfill::BackfillThreadCounters> for BackfillThreadCounters {- fn from(counters: service_backfill::BackfillThreadCounters) -> Self {- BackfillThreadCounters {- messages_retrieved_count: counters.messages_retrieved_count,- messages_processed_count: counters.messages_processed_count,- messages_succeeded_count: counters.messages_succeeded_count,- messages_failed_count: counters.messages_failed_count,- }- }-}diff --git a/rust/cloud-storage/models_email/src/email/service/backfill.rs b/rust/cloud-storage/models_email/src/email/service/backfill.rsindex a1b33ebf80..bf2df30f20 100644--- a/rust/cloud-storage/models_email/src/email/service/backfill.rs+++ b/rust/cloud-storage/models_email/src/email/service/backfill.rs@@ -96,25 +96,6 @@ pub struct BackfillJob {// Total number of threads we pulled from gmail api during backfillpub threads_retrieved_count: i32,- // Number of threads that have been processed (succeeded + failed + skipped)- pub threads_processed_count: i32,-- // Total number of messages we pull from gmail api during backfill- pub messages_retrieved_count: i32,- // Number of messages that either succeeded or failed- pub messages_processed_count: i32,-- // Number of threads that were successfully backfilled- pub threads_succeeded_count: i32,- // Number of threads that were skipped during backfill due to already existing- pub threads_skipped_count: i32,- // Number of threads that failed during backfill- pub threads_failed_count: i32,-- // Number of messages successfully backfilled- pub messages_succeeded_count: i32,- // Number of messages that failed during backfill- pub messages_failed_count: i32,pub created_at: DateTime<Utc>,pub updated_at: DateTime<Utc>,@@ -142,58 +123,6 @@ pub enum BackfillThreadStatus {Cancelled,}-// Struct for backfill thread (Service layer)-#[derive(Debug, Serialize, Deserialize, Clone)]-pub struct BackfillThread {- pub backfill_job_id: Uuid,- pub thread_provider_id: String,- pub messages_retrieved_count: i32,- pub messages_processed_count: i32,- pub messages_succeeded_count: i32,- pub messages_failed_count: i32,- pub metadata_updated: bool,- pub status: BackfillThreadStatus,- pub error_message: Option<String>,- pub retry_count: i32,- pub created_at: DateTime<Utc>,- pub updated_at: DateTime<Utc>,-}--// Enum for backfill message status-#[derive(- Debug,- Serialize,- Deserialize,- sqlx::Type,- Clone,- Copy,- PartialEq,- Eq,- EnumString,- AsRefStr,- Display,-)]-#[sqlx(type_name = "email_backfill_message_status", rename_all = "PascalCase")]-pub enum BackfillMessageStatus {- InProgress,- Completed,- Failed,- Cancelled,-}--// Struct for the backfill_message table-#[derive(Debug, Serialize, Deserialize, Clone)]-pub struct BackfillMessage {- pub backfill_job_id: Uuid,- pub thread_provider_id: String,- pub message_provider_id: String,- pub status: BackfillMessageStatus,- pub error_message: Option<String>,- pub retry_count: i32,- pub created_at: DateTime<Utc>,- pub updated_at: DateTime<Utc>,-}-impl From<db_backfill::BackfillJobStatus> for BackfillJobStatus {fn from(status: db_backfill::BackfillJobStatus) -> Self {match status {@@ -217,18 +146,6 @@ impl From<db_backfill::BackfillJob> for BackfillJob {// Ground Truth Counterstotal_threads: job.total_threads,threads_retrieved_count: job.threads_retrieved_count,- messages_retrieved_count: job.messages_retrieved_count,-- // Thread-Level Progress- threads_processed_count: job.threads_processed_count,- threads_succeeded_count: job.threads_succeeded_count,- threads_failed_count: job.threads_failed_count,- threads_skipped_count: job.threads_skipped_count,-- // Message-Level Progress- messages_processed_count: job.messages_processed_count,- messages_succeeded_count: job.messages_succeeded_count,- messages_failed_count: job.messages_failed_count,// Job Metadatastatus: job.status.into(),@@ -238,97 +155,12 @@ impl From<db_backfill::BackfillJob> for BackfillJob {}}-impl From<db_backfill::BackfillThreadStatus> for BackfillThreadStatus {- fn from(status: db_backfill::BackfillThreadStatus) -> Self {- match status {- db_backfill::BackfillThreadStatus::InProgress => BackfillThreadStatus::InProgress,- db_backfill::BackfillThreadStatus::Skipped => BackfillThreadStatus::Skipped,- db_backfill::BackfillThreadStatus::Completed => BackfillThreadStatus::Completed,- db_backfill::BackfillThreadStatus::Failed => BackfillThreadStatus::Failed,- db_backfill::BackfillThreadStatus::Cancelled => BackfillThreadStatus::Cancelled,- }- }-}--impl From<db_backfill::BackfillThread> for BackfillThread {- fn from(thread: db_backfill::BackfillThread) -> Self {- BackfillThread {- backfill_job_id: thread.backfill_job_id,- thread_provider_id: thread.thread_provider_id,- messages_retrieved_count: thread.messages_retrieved_count,- messages_processed_count: thread.messages_processed_count,- messages_succeeded_count: thread.messages_succeeded_count,- messages_failed_count: thread.messages_failed_count,- metadata_updated: thread.metadata_updated,- status: thread.status.into(),- error_message: thread.error_message,- retry_count: thread.retry_count,- created_at: thread.created_at,- updated_at: thread.updated_at,- }- }-}--impl From<db_backfill::BackfillMessageStatus> for BackfillMessageStatus {- fn from(status: db_backfill::BackfillMessageStatus) -> Self {- match status {- db_backfill::BackfillMessageStatus::InProgress => BackfillMessageStatus::InProgress,- db_backfill::BackfillMessageStatus::Completed => BackfillMessageStatus::Completed,- db_backfill::BackfillMessageStatus::Failed => BackfillMessageStatus::Failed,- db_backfill::BackfillMessageStatus::Cancelled => BackfillMessageStatus::Cancelled,- }- }-}--impl From<db_backfill::BackfillMessage> for BackfillMessage {- fn from(message: db_backfill::BackfillMessage) -> Self {- BackfillMessage {- backfill_job_id: message.backfill_job_id,- thread_provider_id: message.thread_provider_id,- message_provider_id: message.message_provider_id,- status: message.status.into(),- error_message: message.error_message,- retry_count: message.retry_count,- created_at: message.created_at,- updated_at: message.updated_at,- }- }-}-#[derive(Debug, FromRow)]pub struct BackfillJobCounters {pub total_threads: i32,pub threads_processed_count: i32,}-impl From<db_backfill::BackfillJobCounters> for BackfillJobCounters {- fn from(counters: db_backfill::BackfillJobCounters) -> Self {- BackfillJobCounters {- total_threads: counters.total_threads,- threads_processed_count: counters.threads_processed_count,- }- }-}--#[derive(Debug, FromRow)]-pub struct BackfillThreadCounters {- pub messages_retrieved_count: i32,- pub messages_processed_count: i32,- pub messages_succeeded_count: i32,- pub messages_failed_count: i32,-}--impl From<db_backfill::BackfillThreadCounters> for BackfillThreadCounters {- fn from(counters: db_backfill::BackfillThreadCounters) -> Self {- BackfillThreadCounters {- messages_retrieved_count: counters.messages_retrieved_count,- messages_processed_count: counters.messages_processed_count,- messages_succeeded_count: counters.messages_succeeded_count,- messages_failed_count: counters.messages_failed_count,- }- }-}-#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]pub struct UpdateMetadataPayload {pub thread_provider_id: String,diff --git a/rust/cloud-storage/models_email/src/email/service/pubsub.rs b/rust/cloud-storage/models_email/src/email/service/pubsub.rsindex c1c525cd19..44536a5be0 100644--- a/rust/cloud-storage/models_email/src/email/service/pubsub.rs+++ b/rust/cloud-storage/models_email/src/email/service/pubsub.rs@@ -24,6 +24,7 @@ pub enum ProcessingError {#[derive(Debug, Clone, Copy, PartialEq, Eq, Display, EnumString)]pub enum FailureReason {DatabaseQueryFailed,+ RedisQueryFailed,SqsEnqueueFailed,AccessTokenFetchFailed,MessageNotFoundInProvider,