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.

refactor(sps): hexify with unified backfill surface (#2875)

gbirman744b83dfb11e
diff --git a/infra/biome.jsonc b/infra/biome.jsonc
index 3847cea2ce..dadb850294 100644
--- a/infra/biome.jsonc
+++ b/infra/biome.jsonc
@@ -1,5 +1,5 @@
{
- "$schema": "https://biomejs.dev/schemas/2.4.7/schema.json",
+ "$schema": "https://biomejs.dev/schemas/2.4.12/schema.json",
"vcs": {
"clientKind": "git",
"enabled": true,
diff --git a/infra/bun.lock b/infra/bun.lock
index e09e876db6..6d95ebcf0d 100644
--- a/infra/bun.lock
+++ b/infra/bun.lock
@@ -16,7 +16,7 @@
"minimist": "^1.2.8",
},
"devDependencies": {
- "@biomejs/biome": "2.2.6",
+ "@biomejs/biome": "2.4.12",
"@types/node": "^20.8.10",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
@@ -254,23 +254,23 @@
"@aws-sdk/util-user-agent-node": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/middleware-user-agent": "3.734.0", "@aws-sdk/types": "3.734.0", "@smithy/node-config-provider": "^4.0.1", "@smithy/types": "^4.1.0", "tslib": "^2.6.2" }, "peerDependencies": { "aws-crt": ">=1.0.0" }, "optionalPeers": ["aws-crt"] }, "sha512-c6Iinh+RVQKs6jYUFQ64htOU2HUXFQ3TVx+8Tu3EDF19+9vzWi9UukhIMH9rqyyEXIAkk9XL7avt8y2Uyw2dGA=="],
- "@biomejs/biome": ["@biomejs/[email protected]", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.2.6", "@biomejs/cli-darwin-x64": "2.2.6", "@biomejs/cli-linux-arm64": "2.2.6", "@biomejs/cli-linux-arm64-musl": "2.2.6", "@biomejs/cli-linux-x64": "2.2.6", "@biomejs/cli-linux-x64-musl": "2.2.6", "@biomejs/cli-win32-arm64": "2.2.6", "@biomejs/cli-win32-x64": "2.2.6" }, "bin": { "biome": "bin/biome" } }, "sha512-yKTCNGhek0rL5OEW1jbLeZX8LHaM8yk7+3JRGv08my+gkpmtb5dDE+54r2ZjZx0ediFEn1pYBOJSmOdDP9xtFw=="],
+ "@biomejs/biome": ["@biomejs/[email protected]", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.4.12", "@biomejs/cli-darwin-x64": "2.4.12", "@biomejs/cli-linux-arm64": "2.4.12", "@biomejs/cli-linux-arm64-musl": "2.4.12", "@biomejs/cli-linux-x64": "2.4.12", "@biomejs/cli-linux-x64-musl": "2.4.12", "@biomejs/cli-win32-arm64": "2.4.12", "@biomejs/cli-win32-x64": "2.4.12" }, "bin": { "biome": "bin/biome" } }, "sha512-Rro7adQl3NLq/zJCIL98eElXKI8eEiBtoeu5TbXF/U3qbjuSc7Jb5rjUbeHHcquDWeSf3HnGP7XI5qGrlRk/pA=="],
- "@biomejs/cli-darwin-arm64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-UZPmn3M45CjTYulgcrFJFZv7YmK3pTxTJDrFYlNElT2FNnkkX4fsxjExTSMeWKQYoZjvekpH5cvrYZZlWu3yfA=="],
+ "@biomejs/cli-darwin-arm64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-BnMU4Pc3ciEVteVpZ0BK33MLr7X57F5w1dwDLDn+/iy/yTrA4Q/N2yftidFtsA4vrDh0FMXDpacNV/Tl3fbmng=="],
- "@biomejs/cli-darwin-x64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-HOUIquhHVgh/jvxyClpwlpl/oeMqntlteL89YqjuFDiZ091P0vhHccwz+8muu3nTyHWM5FQslt+4Jdcd67+xWQ=="],
+ "@biomejs/cli-darwin-x64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-x9uJ0bI1rJsWICp3VH8w/5PnAVD3A7SqzDpbrfoUQX1QyWrK5jSU4fRLo/wSgGeplCivbxBRKmt5Xq4/nWvq8A=="],
- "@biomejs/cli-linux-arm64": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-BpGtuMJGN+o8pQjvYsUKZ+4JEErxdSmcRD/JG3mXoWc6zrcA7OkuyGFN1mDggO0Q1n7qXxo/PcupHk8gzijt5g=="],
+ "@biomejs/cli-linux-arm64": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-tOwuCuZZtKi1jVzbk/5nXmIsziOB6yqN8c9r9QM0EJYPU6DpQWf11uBOSCfFKKM4H3d9ZoarvlgMfbcuD051Pw=="],
- "@biomejs/cli-linux-arm64-musl": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-TjCenQq3N6g1C+5UT3jE1bIiJb5MWQvulpUngTIpFsL4StVAUXucWD0SL9MCW89Tm6awWfeXBbZBAhJwjyFbRQ=="],
+ "@biomejs/cli-linux-arm64-musl": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-FhfpkAAlKL6kwvcVap0Hgp4AhZmtd3YImg0kK1jd7C/aSoh4SfsB2f++yG1rU0lr8Y5MCFJrcSkmssiL9Xnnig=="],
- "@biomejs/cli-linux-x64": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-1HaM/dpI/1Z68zp8ZdT6EiBq+/O/z97a2AiHMl+VAdv5/ELckFt9EvRb8hDHpk8hUMoz03gXkC7VPXOVtU7faA=="],
+ "@biomejs/cli-linux-x64": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-8pFeAnLU9QdW9jCIslB/v82bI0lhBmz2ZAKc8pVMFPO0t0wAHsoEkrUQUbMkIorTRIjbqyNZHA3lEXavsPWYSw=="],
- "@biomejs/cli-linux-x64-musl": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-1ZcBux8zVM3JhWN2ZCPaYf0+ogxXG316uaoXJdgoPZcdK/rmRcRY7PqHdAos2ExzvjIdvhQp72UcveI98hgOog=="],
+ "@biomejs/cli-linux-x64-musl": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-dwTIgZrGutzhkQCuvHynCkyW6hJxUuyZqKKO0YNfaS2GUoRO+tOvxXZqZB6SkWAOdfZTzwaw8IEdUnIkHKHoew=="],
- "@biomejs/cli-win32-arm64": ["@biomejs/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-h3A88G8PGM1ryTeZyLlSdfC/gz3e95EJw9BZmA6Po412DRqwqPBa2Y9U+4ZSGUAXCsnSQE00jLV8Pyrh0d+jQw=="],
+ "@biomejs/cli-win32-arm64": ["@biomejs/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-B0DLnx0vA9ya/3v7XyCaP+/lCpnbWbMOfUFFve+xb5OxyYvdHaS55YsSddr228Y+JAFk58agCuZTsqNiw2a6ig=="],
- "@biomejs/cli-win32-x64": ["@biomejs/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-yx0CqeOhPjYQ5ZXgPfu8QYkgBhVJyvWe36as7jRuPrKPO5ylVDfwVtPQ+K/mooNTADW0IhxOZm3aPu16dP8yNQ=="],
+ "@biomejs/cli-win32-x64": ["@biomejs/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-yMckRzTyZ83hkk8iDFWswqSdU8tvZxspJKnYNh7JZr/zhZNOlzH13k4ecboU6MurKExCe2HUkH75pGI/O2JwGA=="],
"@cspotcode/source-map-support": ["@cspotcode/[email protected]", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.9" } }, "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw=="],
diff --git a/infra/package.json b/infra/package.json
index cbb27801bc..4d8b34ec27 100644
--- a/infra/package.json
+++ b/infra/package.json
@@ -12,7 +12,7 @@
"check": "tsc --noEmit"
},
"devDependencies": {
- "@biomejs/biome": "2.2.6",
+ "@biomejs/biome": "2.4.12",
"@types/node": "^20.8.10",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
diff --git a/infra/stacks/opensearch/helpers/client.ts b/infra/stacks/opensearch/helpers/client.ts
index 17266d63ad..998fbb428b 100644
--- a/infra/stacks/opensearch/helpers/client.ts
+++ b/infra/stacks/opensearch/helpers/client.ts
@@ -3,6 +3,9 @@ require('dotenv').config();
import { Client } from '@opensearch-project/opensearch';
const IS_LOCAL = process.env.ENVIRONMENT === 'local' ? true : false;
+// Set to bypass TLS verification when connecting through an SSH tunnel
+// (cert is for the prod hostname, request goes to localhost).
+const INSECURE_TLS = process.env.OPENSEARCH_INSECURE_TLS === 'true';
const OPENSEARCH_URL = process.env.OPENSEARCH_URL;
const USERNAME = process.env.OPENSEARCH_USERNAME;
const PASSWORD = process.env.OPENSEARCH_PASSWORD;
@@ -27,7 +30,7 @@ export function client(): Client {
password: PASSWORD,
},
ssl: {
- rejectUnauthorized: !IS_LOCAL,
+ rejectUnauthorized: !IS_LOCAL && !INSECURE_TLS,
},
});
diff --git a/infra/stacks/opensearch/helpers/constants.ts b/infra/stacks/opensearch/helpers/constants.ts
index 5c26fed0fa..c315aac183 100644
--- a/infra/stacks/opensearch/helpers/constants.ts
+++ b/infra/stacks/opensearch/helpers/constants.ts
@@ -1,6 +1,6 @@
const CHAT_INDEX = 'chats';
const DOCUMENT_INDEX = 'documents';
-const EMAIL_INDEX = 'emails';
+const EMAIL_INDEX = 'emails_v2';
const CHANNEL_INDEX = 'channels';
const CALL_RECORDS_INDEX = 'call_records';
const CALL_RECORDS_ALIAS = 'call_records_alias';
diff --git a/infra/stacks/search-processing-service/Pulumi.dev.yaml b/infra/stacks/search-processing-service/Pulumi.dev.yaml
index fa0a4d3789..78165b9b8b 100644
--- a/infra/stacks/search-processing-service/Pulumi.dev.yaml
+++ b/infra/stacks/search-processing-service/Pulumi.dev.yaml
@@ -1,6 +1,7 @@
config:
aws:region: us-east-1
search-processing-service:database_url_key: macro-db-dev
+ search-processing-service:macro_db_readonly_secret_key: macro-db-readonly-dev
search-processing-service:opensearch_password_key: macro-opensearch-password-dev
search-processing-service:internal_auth_key: document-storage-service-auth-key-dev
search-processing-service:sync_service_auth_key: sync-service-key-dev
diff --git a/infra/stacks/search-processing-service/Pulumi.prod.yaml b/infra/stacks/search-processing-service/Pulumi.prod.yaml
index 2765ad6159..181e465af2 100644
--- a/infra/stacks/search-processing-service/Pulumi.prod.yaml
+++ b/infra/stacks/search-processing-service/Pulumi.prod.yaml
@@ -1,6 +1,7 @@
config:
aws:region: us-east-1
search-processing-service:database_url_key: macro-db-prod
+ search-processing-service:macro_db_readonly_secret_key: macro-db-readonly-prod
search-processing-service:opensearch_password_key: macro-opensearch-password-prod
search-processing-service:internal_auth_key: document-storage-service-auth-key-prod
search-processing-service:sync_service_auth_key: sync-service-key-prod
diff --git a/infra/stacks/search-processing-service/index.ts b/infra/stacks/search-processing-service/index.ts
index 4891b81f41..76deccfbd5 100644
--- a/infra/stacks/search-processing-service/index.ts
+++ b/infra/stacks/search-processing-service/index.ts
@@ -57,6 +57,11 @@ const databaseUrlArn: pulumi.Output<string> = aws.secretsmanager
.getSecretVersionOutput({ secretId: DATABASE_URL })
.apply((secret) => secret.arn);
+const DATABASE_URL_READONLY = config.require('macro_db_readonly_secret_key');
+const databaseUrlReadonlyArn: pulumi.Output<string> = aws.secretsmanager
+ .getSecretVersionOutput({ secretId: DATABASE_URL_READONLY })
+ .apply((secret) => secret.arn);
+
const INTERNAL_AUTH_KEY = aws.secretsmanager
.getSecretVersionOutput({
secretId: config.require(`internal_auth_key`),
@@ -73,6 +78,7 @@ const searchProcessingService = new SearchProcessingService(
{
secretKeyArns: [
databaseUrlArn,
+ databaseUrlReadonlyArn,
opensearchPasswordArn,
syncServiceAuthKeyArn,
],
@@ -97,6 +103,10 @@ const searchProcessingService = new SearchProcessingService(
name: 'DATABASE_URL',
value: pulumi.interpolate`${DATABASE_URL}`,
},
+ {
+ name: 'DATABASE_URL_READONLY',
+ value: pulumi.interpolate`${DATABASE_URL_READONLY}`,
+ },
{
name: 'SEARCH_EVENT_QUEUE',
value: pulumi.interpolate`${searchEventQueueName}`,
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index a336a14ad6..14e83a76e9 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -9666,6 +9666,7 @@ dependencies = [
"sqs_client",
"sqs_worker",
"strum",
+ "thiserror 2.0.17",
"tokio",
"tower 0.5.2",
"tower-http",
diff --git a/rust/cloud-storage/comms_service/Cargo.toml b/rust/cloud-storage/comms_service/Cargo.toml
index 5bcc9769af..90b3a38f5c 100644
--- a/rust/cloud-storage/comms_service/Cargo.toml
+++ b/rust/cloud-storage/comms_service/Cargo.toml
@@ -8,11 +8,6 @@ version = "0.1.0"
name = "comms_service"
path = "src/lib.rs"
-[[bin]]
-name = "backfill_comms_search"
-path = "src/bin/backfill_search.rs"
-required-features = []
-
[[bin]]
name = "comms_service_openapi"
path = "src/openapi.rs"
diff --git a/rust/cloud-storage/comms_service/src/bin/backfill_search.rs b/rust/cloud-storage/comms_service/src/bin/backfill_search.rs
deleted file mode 100644
index be61127f47..0000000000
--- a/rust/cloud-storage/comms_service/src/bin/backfill_search.rs
+++ /dev/null
@@ -1,70 +0,0 @@
-/// backfill_chat.rs is used to trigger a backfill for chats
-/// Required environment variables:
-/// - DATABASE_URL
-/// - SEARCH_EVENT_QUEUE
-use anyhow::Context;
-use macro_entrypoint::MacroEntrypoint;
-use sqlx::postgres::PgPoolOptions;
-use sqs_client::search::channel::ChannelMessageUpdate;
-
-#[tokio::main]
-async fn main() -> anyhow::Result<()> {
- MacroEntrypoint::default().init();
-
- let database_url = std::env::var("DATABASE_URL").context("DATABASE_URL not set")?;
- let db = PgPoolOptions::new()
- .min_connections(1)
- .max_connections(1)
- .connect(&database_url)
- .await
- .context("could not connect to db")?;
-
- let search_event_queue =
- std::env::var("SEARCH_EVENT_QUEUE").context("SEARCH_EVENT_QUEUE not set")?;
-
- let aws_config = macro_aws_config::get_macro_aws_config().await;
-
- let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&aws_config))
- .search_event_queue(&search_event_queue);
-
- let limit = 5000;
- let mut offset = 0;
- let mut count = 0;
- loop {
- let messages =
- comms_db_client::messages::get_messages::get_channel_messages(&db, limit, offset)
- .await?;
-
- println!("got batch offset {offset}");
-
- if messages.is_empty() {
- println!("no more messages found");
- break;
- }
- count += messages.len();
-
- sqs_client
- .bulk_send_message_to_search_event_queue(
- messages
- .iter()
- .map(|(channel_id, message_id)| {
- sqs_client::search::SearchQueueMessage::ChannelMessageUpdate(
- ChannelMessageUpdate {
- channel_id: channel_id.to_string(),
- message_id: message_id.to_string(),
- },
- )
- })
- .collect(),
- )
- .await?;
- println!("queued batch");
-
- // Set offset for next iteration
- offset += limit;
- }
-
- println!("Completed. Total chats processed: {count}");
-
- Ok(())
-}
diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.toml
index 64a91e0817..fb71947967 100644
--- a/rust/cloud-storage/document_cognition_service/Cargo.toml
+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml
@@ -9,10 +9,6 @@ version = "0.1.0"
name = "document_cognition_service"
path = "src/main.rs"
-[[bin]]
-name = "backfill_dcs_search"
-path = "src/bin/backfill_search.rs"
-
[[bin]]
name = "document_cognition_service_openapi"
path = "src/openapi.rs"
diff --git a/rust/cloud-storage/document_cognition_service/src/bin/backfill_search.rs b/rust/cloud-storage/document_cognition_service/src/bin/backfill_search.rs
deleted file mode 100644
index 50413418cf..0000000000
--- a/rust/cloud-storage/document_cognition_service/src/bin/backfill_search.rs
+++ /dev/null
@@ -1,77 +0,0 @@
-/// backfill_search.rs is used to trigger a backfill for document search
-/// Required environment variables:
-/// - DATABASE_URL
-/// - SEARCH_EVENT_QUEUE
-use anyhow::Context;
-use macro_entrypoint::MacroEntrypoint;
-use sqlx::postgres::PgPoolOptions;
-
-#[tokio::main]
-async fn main() -> anyhow::Result<()> {
- MacroEntrypoint::default().init();
-
- tracing::info!("starting backfill_search");
-
- let database_url = std::env::var("DATABASE_URL").context("DATABASE_URL not set")?;
- let db = PgPoolOptions::new()
- .min_connections(10)
- .max_connections(60)
- .connect(&database_url)
- .await
- .context("could not connect to db")?;
-
- let search_event_queue =
- std::env::var("SEARCH_EVENT_QUEUE").context("SEARCH_EVENT_QUEUE not set")?;
-
- let aws_config = macro_aws_config::get_macro_aws_config().await;
-
- let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&aws_config))
- .search_event_queue(&search_event_queue);
-
- let limit = 1000;
- let mut offset = 0;
- let mut total = 0;
-
- loop {
- let chats = macro_db_client::chat::get::get_chat_messages_for_search_backfill(
- &db, limit, offset, None, None,
- )
- .await
- .context("failed to get chats")?;
-
- if chats.is_empty() {
- tracing::info!("no more chats to process");
- break;
- }
-
- total += chats.len();
-
- sqs_client
- .bulk_send_message_to_search_event_queue(
- chats
- .iter()
- .map(|chat| {
- sqs_client::search::SearchQueueMessage::ChatMessage(
- sqs_client::search::chat::ChatMessage {
- chat_id: chat.chat_id.clone(),
- message_id: chat.message_id.clone(),
- user_id: chat.user_id.clone(),
- created_at: chat.created_at,
- updated_at: chat.updated_at,
- },
- )
- })
- .collect(),
- )
- .await
- .context("failed to send messages to search event queue")?;
-
- tracing::info!(offset, "completed offset batch");
-
- offset += limit;
- }
-
- tracing::info!(total, "backfill complete");
-
- Ok(())
-}
diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.toml
index 50afd6e72f..7b95bd942f 100644
--- a/rust/cloud-storage/document_storage_service/Cargo.toml
+++ b/rust/cloud-storage/document_storage_service/Cargo.toml
@@ -9,10 +9,6 @@ version = "0.1.0"
name = "document_storage_service"
path = "src/main.rs"
-[[bin]]
-name = "backfill_document_search"
-path = "src/bin/backfill_search.rs"
-
[[bin]]
name = "document_storage_service_openapi"
path = "src/openapi.rs"
diff --git a/rust/cloud-storage/document_storage_service/src/bin/backfill_search.rs b/rust/cloud-storage/document_storage_service/src/bin/backfill_search.rs
deleted file mode 100644
index 05eb319f36..0000000000
--- a/rust/cloud-storage/document_storage_service/src/bin/backfill_search.rs
+++ /dev/null
@@ -1,116 +0,0 @@
-/// backfill_search.rs is used to trigger a backfill for document search
-/// Required environment variables:
-/// - DATABASE_URL
-/// - SEARCH_EVENT_QUEUE
-use anyhow::Context;
-use chrono::{DateTime, Utc};
-use clap::Parser;
-use macro_entrypoint::MacroEntrypoint;
-use model::document::FileType;
-use sqlx::postgres::PgPoolOptions;
-
-#[derive(clap::Parser, Debug)]
-struct Args {
- /// Comma separated list of file types to process
- #[arg(long = "file_types", short = 'f')]
- file_types: Option<String>,
- /// Filter to only documents with this sub type (e.g. "task")
- #[arg(long = "sub_type", short = 's')]
- sub_type: Option<String>,
- /// Only include documents created after this time (ISO 8601, e.g. "2026-03-24T00:00:00Z")
- #[arg(long = "created_after")]
- created_after: Option<DateTime<Utc>>,
- /// Only include documents created before this time (ISO 8601, e.g. "2026-03-25T00:00:00Z")
- #[arg(long = "created_before")]
- created_before: Option<DateTime<Utc>>,
-}
-
-#[tokio::main]
-async fn main() -> anyhow::Result<()> {
- MacroEntrypoint::default().init();
-
- let args = Args::parse();
-
- let file_types: Option<Vec<String>> = args
- .file_types
- .map(|s| s.split(',').map(|s| s.to_string()).collect());
- let sub_type = args.sub_type;
- let created_after = args.created_after;
- let created_before = args.created_before;
-
- println!(
- "Starting backfill_search with file_types={file_types:?} sub_type={sub_type:?} created_after={created_after:?} created_before={created_before:?}"
- );
-
- let database_url = std::env::var("DATABASE_URL").context("DATABASE_URL not set")?;
- let db = PgPoolOptions::new()
- .min_connections(10)
- .max_connections(60)
- .connect(&database_url)
- .await
- .context("could not connect to db")?;
-
- let search_event_queue =
- std::env::var("SEARCH_EVENT_QUEUE").context("SEARCH_EVENT_QUEUE not set")?;
-
- let queue_aws_config = macro_aws_config::get_macro_aws_config().await;
-
- let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&queue_aws_config))
- .search_event_queue(&search_event_queue);
-
- let limit = 1000;
- let mut offset = 0;
- let mut total = 0;
-
- loop {
- let documents = macro_db_client::document::get_documents_search::get_documents_for_search(
- &db,
- limit,
- offset,
- &file_types,
- &sub_type,
- &created_after,
- &created_before,
- )
- .await
- .context("Failed to get documents")?;
-
- if documents.is_empty() {
- tracing::trace!("no more documents to process");
- break;
- }
-
- let first_created = documents.first().and_then(|d| d.created_at);
- let last_created = documents.last().and_then(|d| d.created_at);
-
- total += documents.len();
-
- sqs_client
- .bulk_send_message_to_search_event_queue(
- documents
- .iter()
- .map(|v| {
- if v.file_type == FileType::Md {
- sqs_client::search::SearchQueueMessage::ExtractSync(v.into())
- } else {
- sqs_client::search::SearchQueueMessage::ExtractDocumentText(v.into())
- }
- })
- .collect(),
- )
- .await?;
-
- println!(
- "completed batch: offset={offset} count={} created_at=[{} .. {}]",
- documents.len(),
- first_created.map_or("N/A".to_string(), |t| t.to_rfc3339()),
- last_created.map_or("N/A".to_string(), |t| t.to_rfc3339()),
- );
-
- offset += limit;
- }
-
- println!("Completed. Total threads processed: {}", total);
-
- Ok(())
-}
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.toml
index 04390fa90a..4f27ed6a18 100644
--- a/rust/cloud-storage/email_service/Cargo.toml
+++ b/rust/cloud-storage/email_service/Cargo.toml
@@ -17,10 +17,6 @@ path = "src/bin/backfill_contacts/backfill_contacts.rs"
name = "backfill_gmail_attachments"
path = "src/bin/backfill_gmail_attachments/backfill_gmail_attachments.rs"
-[[bin]]
-name = "backfill_email_search"
-path = "src/bin/backfill_search/backfill_search.rs"
-
[[bin]]
name = "backfill_sfs_attachments"
path = "src/bin/backfill_sfs_attachments/backfill_sfs_attachments.rs"
diff --git a/rust/cloud-storage/email_service/src/bin/backfill_search/backfill_search.rs b/rust/cloud-storage/email_service/src/bin/backfill_search/backfill_search.rs
deleted file mode 100644
index 28a5de524b..0000000000
--- a/rust/cloud-storage/email_service/src/bin/backfill_search/backfill_search.rs
+++ /dev/null
@@ -1,127 +0,0 @@
-/// backfill_search.rs is used to trigger a backfill for email search across all threads available
-/// in the email_db.
-/// Required environment variables:
-/// - DATABASE_URL
-/// - SEARCH_EVENT_QUEUE
-///
-/// Optional:
-/// - SINCE: ISO 8601 timestamp to only backfill threads updated since that time
-/// e.g. SINCE=2026-03-16T00:00:00Z
-/// - EMAIL_INDEX_OVERRIDE: Override the target OpenSearch index for email upserts
-/// e.g. EMAIL_INDEX_OVERRIDE=emails_v2
-/// - BATCH_SIZE: Number of threads per SQS batch message (default: 50)
-/// e.g. BATCH_SIZE=100
-use anyhow::Context;
-use macro_entrypoint::MacroEntrypoint;
-use sqlx::postgres::PgPoolOptions;
-use sqs_client::search::{SearchQueueMessage, email::EmailThreadBatchMessage};
-
-#[tokio::main]
-async fn main() -> anyhow::Result<()> {
- MacroEntrypoint::default().init();
-
- let database_url = std::env::var("DATABASE_URL").context("DATABASE_URL not set")?;
- let db = PgPoolOptions::new()
- .min_connections(10)
- .max_connections(60)
- .connect(&database_url)
- .await
- .context("could not connect to db")?;
-
- let search_event_queue =
- std::env::var("SEARCH_EVENT_QUEUE").context("SEARCH_EVENT_QUEUE not set")?;
-
- let since = std::env::var("SINCE")
- .ok()
- .map(|s| {
- s.parse::<chrono::DateTime<chrono::Utc>>()
- .context("SINCE must be a valid ISO 8601 timestamp (e.g. 2026-03-16T00:00:00Z)")
- })
- .transpose()?;
-
- let index_override = std::env::var("EMAIL_INDEX_OVERRIDE").ok();
-
- let batch_size: usize = std::env::var("BATCH_SIZE")
- .unwrap_or("50".to_string())
- .parse()
- .context("BATCH_SIZE must be a valid number")?;
-
- if let Some(ref index) = index_override {
- println!("Index override: {}", index);
- }
-
- let queue_aws_config = macro_aws_config::get_macro_aws_config().await;
-
- let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&queue_aws_config))
- .search_event_queue(&search_event_queue);
-
- if let Some(since) = &since {
- println!("Backfilling threads updated since: {}", since);
- } else {
- println!("Backfilling all threads");
- }
-
- let limit = 1000;
- let mut offset = 0;
- let mut total = 0;
-
- loop {
- let thread_and_macro_user_ids = match since {
- Some(since) => {
- email_db_client::threads::get::get_paginated_thread_ids_with_macro_user_id_since(
- &db, limit, offset, since,
- )
- .await
- .context("Failed to get thread ids with macro user id")?
- }
- None => email_db_client::threads::get::get_paginated_thread_ids_with_macro_user_id(
- &db, limit, offset,
- )
- .await
- .context("Failed to get thread ids with macro user id")?,
- };
-
- if thread_and_macro_user_ids.is_empty() {
- tracing::trace!("no more thread ids with macro user id to process");
- break;
- }
-
- total += thread_and_macro_user_ids.len();
-
- let mut user_threads: std::collections::HashMap<String, Vec<String>> =
- std::collections::HashMap::new();
- for (thread_id, macro_user_id) in thread_and_macro_user_ids {
- user_threads
- .entry(macro_user_id)
- .or_default()
- .push(thread_id.to_string());
- }
-
- let search_messages: Vec<SearchQueueMessage> = user_threads
- .into_iter()
- .flat_map(|(macro_user_id, thread_ids)| {
- thread_ids
- .chunks(batch_size)
- .map(|chunk| {
- SearchQueueMessage::ExtractEmailThreadBatch(EmailThreadBatchMessage {
- thread_ids: chunk.to_vec(),
- macro_user_id: macro_user_id.clone(),
- index_override: index_override.clone(),
- })
- })
- .collect::<Vec<_>>()
- })
- .collect();
-
- sqs_client
- .bulk_send_message_to_search_event_queue(search_messages)
- .await
- .context("failed to send search messages to search extractor queue")?;
-
- offset += limit;
- }
-
- println!("Completed. Total threads processed: {}", total);
-
- Ok(())
-}
diff --git a/rust/cloud-storage/remote_env_var/src/lib.rs b/rust/cloud-storage/remote_env_var/src/lib.rs
index d579c023f8..50967f50ba 100644
--- a/rust/cloud-storage/remote_env_var/src/lib.rs
+++ b/rust/cloud-storage/remote_env_var/src/lib.rs
@@ -91,3 +91,41 @@ where
secret_manager.get_maybe_secret_value(Environment::new_or_prod(), val)
}
}
+
+/// Optional variant of [`LocalOrRemoteSecret`]. `None` represents an env var
+/// that wasn't configured at all; `Some(...)` carries a resolved secret.
+/// Useful for secrets that are genuinely optional (e.g. a read-replica URL
+/// that, when absent, lets callers fall back to a different code path).
+#[derive(Clone)]
+pub struct OptionalLocalOrRemoteSecret<T>(pub Option<LocalOrRemoteSecret<T>>);
+
+impl<T> OptionalLocalOrRemoteSecret<T>
+where
+ T: AsRef<str> + Send,
+{
+ /// Resolve `val` through the secret manager when present, propagating
+ /// the manager's error on failure. `None` in → `None` out, with no
+ /// secret-manager call.
+ pub async fn new_from_secret_manager<S>(
+ val: Option<T>,
+ secret_manager: &S,
+ ) -> Result<Self, S::Err>
+ where
+ S: SecretManager,
+ {
+ match val {
+ Some(v) => Ok(Self(Some(
+ LocalOrRemoteSecret::new_from_secret_manager(v, secret_manager).await?,
+ ))),
+ None => Ok(Self(None)),
+ }
+ }
+
+ /// View the resolved secret as `&str`, or `None` when unset.
+ pub fn as_str(&self) -> Option<&str>
+ where
+ T: AsRef<str>,
+ {
+ self.0.as_ref().map(AsRef::as_ref)
+ }
+}
diff --git a/rust/cloud-storage/search_processing_service/Cargo.toml b/rust/cloud-storage/search_processing_service/Cargo.toml
index 2b24382fc9..9822403735 100644
--- a/rust/cloud-storage/search_processing_service/Cargo.toml
+++ b/rust/cloud-storage/search_processing_service/Cargo.toml
@@ -10,16 +10,6 @@ default = ["processing", "service"]
processing = []
service = ["macro_db_client"]
-[[bin]]
-name = "backfill_chat"
-path = "src/bin/backfill_chat.rs"
-required-features = ["service"]
-
-[[bin]]
-name = "backfill_call"
-path = "src/bin/backfill_call.rs"
-required-features = ["service"]
-
[[bin]]
name = "search_processing_service"
path = "src/main.rs"
@@ -69,6 +59,7 @@ sqs_client = { path = "../sqs_client", default-features = false, features = [
] }
sqs_worker = { path = "../sqs_worker" }
strum = { workspace = true }
+thiserror = { workspace = true }
tokio = { workspace = true }
tower = { workspace = true }
tower-http = { workspace = true }
diff --git a/rust/cloud-storage/search_processing_service/README.md b/rust/cloud-storage/search_processing_service/README.md
index 08707b768a..b18d206812 100644
--- a/rust/cloud-storage/search_processing_service/README.md
+++ b/rust/cloud-storage/search_processing_service/README.md
@@ -1,15 +1,40 @@
# Search Processing Service
-This service is responsible for processing search text extraction messages and updating the OpenSearch content for cloud storage items.
+This service owns the search-event pipeline:
+
+- **Consume**: SQS workers drain `SEARCH_EVENT_QUEUE` and index into OpenSearch.
+- **Backfill**: internal HTTP endpoints re-enqueue every indexable record of a given entity type onto that same queue. Every entity's backfill funnels through sps so operators have one URL surface to remember.
+
+## Architecture
+
+sps is hexagonal:
+
+```
+src/
+ domain/ # models, ports (CallBackfill, ChatBackfill, ...), BackfillService trait + orchestrator
+ outbound/backfill/ # one Postgres-backed adapter per entity (calls/chats/channels/documents/emails)
+ api/internal/ # axum handlers — thin pass-throughs to the orchestrator
+ process/ # existing search-event workers
+```
+
+The orchestrator is the single inbound contract for HTTP handlers. Swapping an adapter (e.g. in-process → HTTP-proxied owner service) is a wiring change, not a handler rewrite.
## Running Locally
-The `localdev` sops bundle already carries every env var this service needs (dev `DATABASE_URL`, dev OpenSearch creds, `ENVIRONMENT=local`, dummy `SYNC_SERVICE_AUTH_KEY` / `LEXICAL_SERVICE_URL` that are unused by most processors). Requires valid AWS credentials for secrets manager + SQS.
+Needs valid AWS credentials (secrets manager + SQS).
+
+Two encrypted env bundles live at the repo root:
-From the repo root:
+- `.env-local.enc` — local backing services via docker-compose.
+- `.env-localdev.enc` — dev backing services (dev RDS, dev OpenSearch). Usually what you want for ad-hoc sps work.
+
+`just get_environment <arg>` decrypts `.env-local<arg>.enc` into `.env`. Pass `dev` for the dev-targeting bundle, or no arg for the fully-local one.
```bash
-just get_environment localdev # writes .env at repo root
+# from repo root — pick one:
+just get_environment # .env-local.enc (local services)
+just get_environment dev # .env-localdev.enc (dev services)
+
cd rust/cloud-storage/search_processing_service
cargo run
```
@@ -20,8 +45,58 @@ Override `SEARCH_EVENT_QUEUE` on a per-run basis (e.g. backfills onto a scratch
SEARCH_EVENT_QUEUE=search-event-queue-<scope>-<you> cargo run
```
+When `DATABASE_URL_READONLY` is set, backfill reads run against the macrodb read-replica so they do not contend with writes on the primary. The queue workers always read from the primary (replica lag could cause them to miss rows they are meant to index). When the env var is absent, backfills fall back to the primary.
+
To run the API surface without the worker loop:
```bash
cargo run --features disable_processing
```
+
+## Backfill HTTP Routes
+
+Every search-indexed entity has a POST endpoint on sps's internal surface. They all share the same response shape (`{"enqueued": <usize>}`), share internal-auth via the `x-internal-auth-key` header, and accept a per-entity JSON filter in the request body.
+
+| Entity | Route | Body (all fields optional) |
+|---|---|---|
+| Calls | `POST /internal/backfill/calls` | `{"call_ids": ["<uuid>"]}` — empty = all archived calls |
+| Chats | `POST /internal/backfill/chats` | `{"chat_ids": [...], "user_ids": [...]}` |
+| Channels | `POST /internal/backfill/channels` | `{}` |
+| Documents | `POST /internal/backfill/documents` | `{"file_types": ["pdf"], "sub_type": "task", "created_after": "...", "created_before": "..."}` |
+| Emails | `POST /internal/backfill/emails` | `{"since": "2026-03-16T00:00:00Z", "index_override": "emails_v2", "batch_size": 100}` |
+
+### Against dev (deployed service)
+
+```bash
+AUTH_KEY=$(aws secretsmanager get-secret-value \
+ --secret-id document-storage-service-auth-key-dev \
+ --region us-east-1 --query SecretString --output text)
+
+curl -X POST https://search-processing-dev.macro.com/internal/backfill/calls \
+ -H "Content-Type: application/json" \
+ -H "x-internal-auth-key: $AUTH_KEY" \
+ -d '{}'
+```
+
+Dev sps consumes the shared `search-event-queue-dev`; backfill messages will interleave with normal ingest. If the deploy brings a mapping change, recreate the relevant index (via `infra/stacks/opensearch/helpers/scripts/create_indices.ts`) before triggering the backfill so stale-mapping docs don't linger.
+
+Monitor: `aws sqs get-queue-attributes` on the dev queue, `GET <dev-opensearch>/<index>/_count`, and CloudWatch logs for the `search-processing-dev` ECS task.
+
+### Pre-shipping: validate with a local service + scratch queue
+
+```bash
+aws sqs create-queue --queue-name search-event-queue-<scope>-<you> --region us-east-1
+
+# shell 1
+just get_environment dev
+cd rust/cloud-storage/search_processing_service
+SEARCH_EVENT_QUEUE=search-event-queue-<scope>-<you> cargo run
+
+# shell 2
+curl -X POST http://localhost:8080/internal/backfill/calls \
+ -H "Content-Type: application/json" \
+ -H "x-internal-auth-key: local" \
+ -d '{}'
+
+aws sqs delete-queue --queue-url <scratch-queue-url> --region us-east-1
+```
diff --git a/rust/cloud-storage/search_processing_service/src/api/context.rs b/rust/cloud-storage/search_processing_service/src/api/context.rs
index 4a0ffdf3c0..dddfb12719 100644
--- a/rust/cloud-storage/search_processing_service/src/api/context.rs
+++ b/rust/cloud-storage/search_processing_service/src/api/context.rs
@@ -3,6 +3,7 @@ use macro_middleware::auth::internal_access::InternalApiSecretKey;
use secretsmanager_client::LocalOrRemoteSecret;
use std::sync::Arc;
+use crate::BackfillServiceImpl;
use crate::config::Config;
#[derive(Clone, FromRef)]
@@ -12,4 +13,5 @@ pub(crate) struct ApiContext {
pub opensearch_client: Arc<opensearch_client::OpensearchClient>,
pub internal_auth_key: LocalOrRemoteSecret<InternalApiSecretKey>,
pub config: Arc<Config>,
+ pub backfill_service: Arc<BackfillServiceImpl>,
}
diff --git a/rust/cloud-storage/search_processing_service/src/api/internal/backfill.rs b/rust/cloud-storage/search_processing_service/src/api/internal/backfill.rs
new file mode 100644
index 0000000000..d61bd36abc
--- /dev/null
+++ b/rust/cloud-storage/search_processing_service/src/api/internal/backfill.rs
@@ -0,0 +1,84 @@
+//! Internal HTTP surface for every search-event backfill.
+//!
+//! Every handler is a thin adapter: decode the per-entity request body, call
+//! the matching method on [`BackfillService`], serialise the receipt. All
+//! shared concerns (pagination, DB access, queue publishing) live in the
+//! domain + outbound adapters — this file stays dumb on purpose so adding a
+//! new entity is one handler + one `.route(...)`.
+
+use std::sync::Arc;
+
+use axum::{
+ Router,
+ extract::{self, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+ routing::post,
+};
+
+use crate::BackfillServiceImpl;
+use crate::api::context::ApiContext;
+use crate::domain::models::{
+ BackfillError, BackfillReceipt, CallBackfillRequest, ChannelBackfillRequest,
+ ChatBackfillRequest, DocumentBackfillRequest, EmailBackfillRequest,
+};
+use crate::domain::service::BackfillService;
+
+pub fn router() -> Router<ApiContext> {
+ Router::new()
+ .route("/calls", post(calls))
+ .route("/chats", post(chats))
+ .route("/channels", post(channels))
+ .route("/documents", post(documents))
+ .route("/emails", post(emails))
+}
+
+#[tracing::instrument(skip(service, req))]
+async fn calls(
+ State(service): State<Arc<BackfillServiceImpl>>,
+ extract::Json(req): extract::Json<CallBackfillRequest>,
+) -> Response {
+ receipt(service.backfill_calls(req).await)
+}
+
+#[tracing::instrument(skip(service, req))]
+async fn chats(
+ State(service): State<Arc<BackfillServiceImpl>>,
+ extract::Json(req): extract::Json<ChatBackfillRequest>,
+) -> Response {
+ receipt(service.backfill_chats(req).await)
+}
+
+#[tracing::instrument(skip(service, req))]
+async fn channels(
+ State(service): State<Arc<BackfillServiceImpl>>,
+ extract::Json(req): extract::Json<ChannelBackfillRequest>,
+) -> Response {
+ receipt(service.backfill_channels(req).await)
+}
+
+#[tracing::instrument(skip(service, req))]
+async fn documents(
+ State(service): State<Arc<BackfillServiceImpl>>,
+ extract::Json(req): extract::Json<DocumentBackfillRequest>,
+) -> Response {
+ receipt(service.backfill_documents(req).await)
+}
+
+#[tracing::instrument(skip(service, req))]
+async fn emails(
+ State(service): State<Arc<BackfillServiceImpl>>,
+ extract::Json(req): extract::Json<EmailBackfillRequest>,
+) -> Response {
+ receipt(service.backfill_emails(req).await)
+}
+
+fn receipt(result: Result<BackfillReceipt, BackfillError>) -> Response {
+ match result {
+ Ok(r) => axum::Json(r).into_response(),
+ Err(e) => {
+ tracing::error!(error=?e, "backfill failed");
+ (StatusCode::INTERNAL_SERVER_ERROR, "backfill failed").into_response()
+ }
+ }
+}
diff --git a/rust/cloud-storage/search_processing_service/src/api/internal/backfill_calls.rs b/rust/cloud-storage/search_processing_service/src/api/internal/backfill_calls.rs
deleted file mode 100644
index 95f2270ab1..0000000000
--- a/rust/cloud-storage/search_processing_service/src/api/internal/backfill_calls.rs
+++ /dev/null
@@ -1,99 +0,0 @@
-use axum::{
- extract::{self, State},
- http::StatusCode,
- response::{IntoResponse, Response},
-};
-use sqs_client::search::{SearchQueueMessage, call::CallRecordMessage};
-
-use crate::api::context::ApiContext;
-
-#[derive(serde::Deserialize, Default)]
-#[serde(default)]
-pub struct BackfillCallsRequest {
- /// Empty = every archived call.
- pub call_ids: Vec<String>,
-}
-
-#[derive(serde::Serialize)]
-pub struct BackfillCallsResponse {
- pub enqueued: usize,
-}
-
-const BACKFILL_PAGE: i64 = 2000;
-
-#[tracing::instrument(err(Debug), skip(ctx, req))]
-pub async fn handler(
- State(ctx): State<ApiContext>,
- extract::Json(req): extract::Json<BackfillCallsRequest>,
-) -> Result<Response, Response> {
- if !req.call_ids.is_empty() {
- let messages: Vec<SearchQueueMessage> = req
- .call_ids
- .iter()
- .map(|id| {
- SearchQueueMessage::CallRecord(CallRecordMessage {
- call_id: id.clone(),
- })
- })
- .collect();
-
- let count = messages.len();
- ctx.sqs_client
- .bulk_send_message_to_search_event_queue(messages)
- .await
- .map_err(internal_error)?;
-
- return Ok(axum::Json(BackfillCallsResponse { enqueued: count }).into_response());
- }
-
- let mut offset = 0i64;
- let mut enqueued = 0usize;
-
- loop {
- let batch = macro_db_client::call_record::get::get_call_records_for_search_backfill(
- &ctx.db,
- BACKFILL_PAGE,
- offset,
- )
- .await
- .map_err(internal_error)?;
-
- if batch.is_empty() {
- break;
- }
-
- let batch_len = batch.len();
- let messages: Vec<SearchQueueMessage> = batch
- .into_iter()
- .map(|r| {
- SearchQueueMessage::CallRecord(CallRecordMessage {
- call_id: r.call_id.to_string(),
- })
- })
- .collect();
-
- enqueued += messages.len();
-
- ctx.sqs_client
- .bulk_send_message_to_search_event_queue(messages)
- .await
- .map_err(internal_error)?;
-
- if (batch_len as i64) < BACKFILL_PAGE {
- break;
- }
-
- offset += BACKFILL_PAGE;
- }
-
- Ok(axum::Json(BackfillCallsResponse { enqueued }).into_response())
-}
-
-fn internal_error(e: impl std::fmt::Debug) -> Response {
- tracing::error!(error=?e, "call records backfill failed");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- "failed to enqueue call records",
- )
- .into_response()
-}
diff --git a/rust/cloud-storage/search_processing_service/src/api/internal/mod.rs b/rust/cloud-storage/search_processing_service/src/api/internal/mod.rs
index e93090fd8b..aa8aa092ab 100644
--- a/rust/cloud-storage/search_processing_service/src/api/internal/mod.rs
+++ b/rust/cloud-storage/search_processing_service/src/api/internal/mod.rs
@@ -4,7 +4,7 @@ use axum::{
routing::{delete, post},
};
-pub(in crate::api) mod backfill_calls;
+pub(in crate::api) mod backfill;
pub(in crate::api) mod delete_document;
pub(in crate::api) mod extract_sync;
@@ -12,5 +12,5 @@ pub fn router() -> Router<ApiContext> {
Router::new()
.route("/delete/{document_id}", delete(delete_document::handler))
.route("/extract_sync", post(extract_sync::handler))
- .route("/backfill/calls", post(backfill_calls::handler))
+ .nest("/backfill", backfill::router())
}
diff --git a/rust/cloud-storage/search_processing_service/src/bin/backfill_call.rs b/rust/cloud-storage/search_processing_service/src/bin/backfill_call.rs
deleted file mode 100644
index f1fd2e1096..0000000000
--- a/rust/cloud-storage/search_processing_service/src/bin/backfill_call.rs
+++ /dev/null
@@ -1,65 +0,0 @@
-use anyhow::Context;
-use macro_entrypoint::MacroEntrypoint;
-use sqlx::postgres::PgPoolOptions;
-use sqs_client::search::call::CallRecordMessage;
-
-#[tokio::main]
-async fn main() -> anyhow::Result<()> {
- MacroEntrypoint::default().init();
-
- let database_url = std::env::var("DATABASE_URL").context("DATABASE_URL not set")?;
- let db = PgPoolOptions::new()
- .min_connections(5)
- .max_connections(30)
- .connect(&database_url)
- .await
- .context("could not connect to db")?;
-
- let search_event_queue =
- std::env::var("SEARCH_EVENT_QUEUE").context("SEARCH_EVENT_QUEUE not set")?;
-
- let queue_aws_config = macro_aws_config::get_macro_aws_config().await;
-
- let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&queue_aws_config))
- .search_event_queue(&search_event_queue);
-
- let limit = 2000;
- let mut offset = 0;
- let mut count = 0;
- loop {
- tracing::info!(limit = %limit, offset = %offset, "getting call records");
-
- let records = macro_db_client::call_record::get::get_call_records_for_search_backfill(
- &db, limit, offset,
- )
- .await?;
- tracing::info!(%offset, fetched = records.len(), "fetched batch");
-
- if records.is_empty() {
- tracing::info!("no more call records found");
- break;
- }
-
- count += records.len();
-
- sqs_client
- .bulk_send_message_to_search_event_queue(
- records
- .iter()
- .map(|r| {
- sqs_client::search::SearchQueueMessage::CallRecord(CallRecordMessage {
- call_id: r.call_id.to_string(),
- })
- })
- .collect(),
- )
- .await?;
- tracing::info!(%offset, "queued batch");
-
- offset += limit;
- }
-
- tracing::info!(total = count, "completed call record backfill");
-
- Ok(())
-}
diff --git a/rust/cloud-storage/search_processing_service/src/bin/backfill_chat.rs b/rust/cloud-storage/search_processing_service/src/bin/backfill_chat.rs
deleted file mode 100644
index 264c5f18cf..0000000000
--- a/rust/cloud-storage/search_processing_service/src/bin/backfill_chat.rs
+++ /dev/null
@@ -1,76 +0,0 @@
-/// backfill_chat.rs is used to trigger a backfill for chats
-/// Required environment variables:
-/// - DATABASE_URL
-/// - SEARCH_EVENT_QUEUE
-use anyhow::Context;
-use macro_entrypoint::MacroEntrypoint;
-use sqlx::postgres::PgPoolOptions;
-use sqs_client::search::chat::ChatMessage;
-
-#[tokio::main]
-async fn main() -> anyhow::Result<()> {
- MacroEntrypoint::default().init();
-
- let database_url = std::env::var("DATABASE_URL").context("DATABASE_URL not set")?;
- let db = PgPoolOptions::new()
- .min_connections(10)
- .max_connections(60)
- .connect(&database_url)
- .await
- .context("could not connect to db")?;
-
- let search_event_queue =
- std::env::var("SEARCH_EVENT_QUEUE").context("SEARCH_EVENT_QUEUE not set")?;
-
- let queue_aws_config = macro_aws_config::get_macro_aws_config().await;
-
- let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&queue_aws_config))
- .search_event_queue(&search_event_queue);
-
- let limit = 5000;
- let mut offset = 0;
- let mut count = 0;
- loop {
- tracing::info!(limit=%limit, offset=%offset, "getting chats");
-
- let chats = macro_db_client::chat::get::get_chat_messages_for_search_backfill(
- &db, limit, offset, None, None,
- )
- .await?;
- println!("got batch offset {offset}");
-
- if chats.is_empty() {
- tracing::trace!("no chats more found");
- break;
- }
-
- count += chats.len();
-
- tracing::trace!(chats = chats.len(), "ready to queue chats");
-
- sqs_client
- .bulk_send_message_to_search_event_queue(
- chats
- .iter()
- .map(|chat| {
- sqs_client::search::SearchQueueMessage::ChatMessage(ChatMessage {
- chat_id: chat.chat_id.clone(),
- message_id: chat.message_id.clone(),
- user_id: chat.user_id.clone(),
- created_at: chat.created_at,
- updated_at: chat.updated_at,
- })
- })
- .collect(),
- )
- .await?;
- println!("queued batch");
-
- // Set offset for next iteration
- offset += limit;
- }
-
- println!("Completed. Total chats processed: {}", count);
-
- Ok(())
-}
diff --git a/rust/cloud-storage/search_processing_service/src/config.rs b/rust/cloud-storage/search_processing_service/src/config.rs
index 644ef8f293..a3a9f91338 100644
--- a/rust/cloud-storage/search_processing_service/src/config.rs
+++ b/rust/cloud-storage/search_processing_service/src/config.rs
@@ -1,11 +1,36 @@
use anyhow::Context;
pub use macro_env::Environment;
+/// Per-entity DB page sizes used by the backfill source adapters. Tunable at
+/// runtime via the corresponding `BACKFILL_*_PAGE_SIZE` env vars.
+#[derive(Debug, Clone, Copy)]
+pub struct BackfillPageSizes {
+ pub calls: usize,
+ pub chats: usize,
+ pub channels: usize,
+ pub documents: usize,
+ pub emails: usize,
+}
+
+const DEFAULT_CALLS_PAGE: usize = 2000;
+const DEFAULT_CHATS_PAGE: usize = 5000;
+const DEFAULT_CHANNELS_PAGE: usize = 5000;
+const DEFAULT_DOCUMENTS_PAGE: usize = 1000;
+const DEFAULT_EMAILS_PAGE: usize = 1000;
+
pub struct Config {
/// The connection URL for the Postgres database this application should use.
/// For deployed applications, this is a secret stored in AWS Secrets Manager.
pub database_url: String,
+ /// Optional connection URL (or SM secret id when `environment != Local`)
+ /// for the macrodb read-replica. When present, backfill reads run against
+ /// the replica so they do not contend with writes on the primary; queue
+ /// workers always read from the primary because replica lag would cause
+ /// them to miss rows they are meant to index. When absent, backfills fall
+ /// back to the primary.
+ pub database_url_readonly: Option<String>,
+
/// The port to listen for HTTP requests on.
pub port: usize,
@@ -37,6 +62,24 @@ pub struct Config {
/// The URL for the Lexical service
pub lexical_service_url: String,
+
+ /// Per-entity DB page sizes for backfill adapters.
+ pub backfill_page_sizes: BackfillPageSizes,
+}
+
+fn parse_page_size(name: &str, default: usize) -> anyhow::Result<usize> {
+ match std::env::var(name) {
+ Ok(raw) => raw
+ .parse::<usize>()
+ .with_context(|| format!("{name} must be a positive integer"))
+ .and_then(|n| {
+ if n == 0 {
+ anyhow::bail!("{name} must be > 0");
+ }
+ Ok(n)
+ }),
+ Err(_) => Ok(default),
+ }
}
impl Config {
@@ -44,6 +87,8 @@ impl Config {
let database_url =
std::env::var("DATABASE_URL").context("DATABASE_URL must be provided")?;
+ let database_url_readonly = std::env::var("DATABASE_URL_READONLY").ok();
+
let port: usize = std::env::var("PORT")
.unwrap_or("8080".to_string())
.parse::<usize>()
@@ -85,8 +130,17 @@ impl Config {
let lexical_service_url =
std::env::var("LEXICAL_SERVICE_URL").context("LEXICAL_SERVICE_URL must be provided")?;
+ let backfill_page_sizes = BackfillPageSizes {
+ calls: parse_page_size("BACKFILL_CALLS_PAGE_SIZE", DEFAULT_CALLS_PAGE)?,
+ chats: parse_page_size("BACKFILL_CHATS_PAGE_SIZE", DEFAULT_CHATS_PAGE)?,
+ channels: parse_page_size("BACKFILL_CHANNELS_PAGE_SIZE", DEFAULT_CHANNELS_PAGE)?,
+ documents: parse_page_size("BACKFILL_DOCUMENTS_PAGE_SIZE", DEFAULT_DOCUMENTS_PAGE)?,
+ emails: parse_page_size("BACKFILL_EMAILS_PAGE_SIZE", DEFAULT_EMAILS_PAGE)?,
+ };
+
Ok(Config {
database_url,
+ database_url_readonly,
port,
search_event_queue,
queue_max_messages,
@@ -99,6 +153,7 @@ impl Config {
sync_service_auth_key,
worker_count,
lexical_service_url,
+ backfill_page_sizes,
})
}
}
diff --git a/rust/cloud-storage/search_processing_service/src/domain/mod.rs b/rust/cloud-storage/search_processing_service/src/domain/mod.rs
new file mode 100644
index 0000000000..56308a5110
--- /dev/null
+++ b/rust/cloud-storage/search_processing_service/src/domain/mod.rs
@@ -0,0 +1,12 @@
+//! Domain layer for search-event backfills.
+//!
+//! The application-level concern here is "drain every indexable record of an
+//! entity type from its source of truth onto the search event queue so the
+//! processing workers can re-index it." Each entity type has its own source
+//! (a Postgres table in a different database), its own filter shape, and its
+//! own mapping to [`sqs_client::search::SearchQueueMessage`] — but the public
+//! surface (orchestration + HTTP routes) stays uniform.
+
+pub mod models;
+pub mod ports;
+pub mod service;
diff --git a/rust/cloud-storage/search_processing_service/src/domain/models.rs b/rust/cloud-storage/search_processing_service/src/domain/models.rs
new file mode 100644
index 0000000000..9585c67c4f
--- /dev/null
+++ b/rust/cloud-storage/search_processing_service/src/domain/models.rs
@@ -0,0 +1,86 @@
+use chrono::{DateTime, Utc};
+use serde::{Deserialize, Serialize};
+use sqs_client::search::SearchQueueMessage;
+use thiserror::Error;
+
+/// Reply returned by every backfill port.
+#[derive(Debug, Clone, Copy, Serialize)]
+pub struct BackfillReceipt {
+ /// Total number of source rows the backfill processed.
+ pub enqueued: usize,
+}
+
+/// One page of work produced by a [`super::ports`] source. Holding the
+/// messages and `rows_consumed` together lets the orchestrator advance its
+/// offset by the number of *rows* the source consumed even when the source
+/// batches many rows into fewer SQS messages (see the email source).
+pub struct SourcePage {
+ pub messages: Vec<SearchQueueMessage>,
+ /// Number of source rows the page covered. Drives the orchestrator's
+ /// `offset += rows_consumed` and its termination check (`rows_consumed
+ /// == 0` means the source is exhausted).
+ pub rows_consumed: usize,
+}
+
+impl SourcePage {
+ pub fn empty() -> Self {
+ Self {
+ messages: Vec::new(),
+ rows_consumed: 0,
+ }
+ }
+}
+
+#[derive(Debug, Error)]
+pub enum BackfillError {
+ #[error("failed reading backfill source")]
+ Source(#[source] anyhow::Error),
+ #[error("failed publishing to search event queue")]
+ Publish(#[source] anyhow::Error),
+}
+
+/// Call-record backfill filter. Empty `call_ids` means "all archived calls".
+#[derive(Debug, Clone, Default, Deserialize)]
+#[serde(default)]
+pub struct CallBackfillRequest {
+ pub call_ids: Vec<String>,
+}
+
+/// Chat-message backfill filter. Empty vectors mean "all messages for every
+/// chat / every user".
+#[derive(Debug, Clone, Default, Deserialize)]
+#[serde(default)]
+pub struct ChatBackfillRequest {
+ pub chat_ids: Vec<String>,
+ pub user_ids: Vec<String>,
+}
+
+/// Channel-message backfill filter. No scoping knobs yet — reserved so adding
+/// one later doesn't break the request shape.
+#[derive(Debug, Clone, Default, Deserialize)]
+#[serde(default)]
+pub struct ChannelBackfillRequest {}
+
+/// Document backfill filter. Every field is additive — all `None` means "every
+/// document this service knows about".
+#[derive(Debug, Clone, Default, Deserialize)]
+#[serde(default)]
+pub struct DocumentBackfillRequest {
+ pub file_types: Option<Vec<String>>,
+ pub sub_type: Option<String>,
+ pub created_after: Option<DateTime<Utc>>,
+ pub created_before: Option<DateTime<Utc>>,
+}
+
+/// Email-thread backfill filter.
+#[derive(Debug, Clone, Default, Deserialize)]
+#[serde(default)]
+pub struct EmailBackfillRequest {
+ /// Only backfill threads updated at or after this instant.
+ pub since: Option<DateTime<Utc>>,
+ /// Override the OpenSearch target index for upserts (e.g. blue/green swap).
+ pub index_override: Option<String>,
+ /// Number of thread ids grouped into each SQS batch message. `None` uses
+ /// the adapter's default.
+ pub batch_size: Option<usize>,
+}
diff --git a/rust/cloud-storage/search_processing_service/src/domain/ports.rs b/rust/cloud-storage/search_processing_service/src/domain/ports.rs
new file mode 100644
index 0000000000..7e7b982b44
--- /dev/null
+++ b/rust/cloud-storage/search_processing_service/src/domain/ports.rs
@@ -0,0 +1,70 @@
+//! Outbound trait contracts for the backfill domain.
+//!
+//! Two ports:
+//!
+//! - [`BackfillSource`] — entity-aware reader. One method per searchable
+//! entity, each producing a [`SourcePage`] (messages + rows consumed) for
+//! a given offset. The orchestrator drives sources through these methods.
+//! - [`SearchEventPublisher`] — entity-agnostic batch publisher onto the
+//! search-event queue.
+//!
+//! Splitting reads (source) from the queue write (publisher) keeps each
+//! adapter single-concern and lets the application-level pagination loop be
+//! tested with in-memory fakes.
+
+use std::future::Future;
+
+use sqs_client::search::SearchQueueMessage;
+
+use super::models::{
+ BackfillError, CallBackfillRequest, ChannelBackfillRequest, ChatBackfillRequest,
+ DocumentBackfillRequest, EmailBackfillRequest, SourcePage,
+};
+
+/// Publishes batches of search-event messages.
+pub trait SearchEventPublisher: Send + Sync + 'static {
+ fn publish(
+ &self,
+ messages: Vec<SearchQueueMessage>,
+ ) -> impl Future<Output = Result<(), BackfillError>> + Send;
+}
+
+/// Source of backfill messages across every searchable entity. The
+/// orchestrator's `drain_source` loop calls one of these per request.
+///
+/// `rows_consumed` on each [`SourcePage`] is the unit the orchestrator
+/// advances by; `messages` is what gets handed to the publisher. Sources
+/// that fold many rows into fewer messages (e.g. emails batching threads
+/// per user) must report the row count separately so the loop offsets
+/// correctly.
+pub trait BackfillSource: Send + Sync + 'static {
+ fn fetch_calls(
+ &self,
+ req: &CallBackfillRequest,
+ offset: usize,
+ ) -> impl Future<Output = Result<SourcePage, BackfillError>> + Send;
+
+ fn fetch_chats(
+ &self,
+ req: &ChatBackfillRequest,
+ offset: usize,
+ ) -> impl Future<Output = Result<SourcePage, BackfillError>> + Send;
+
+ fn fetch_channels(
+ &self,
+ req: &ChannelBackfillRequest,
+ offset: usize,
+ ) -> impl Future<Output = Result<SourcePage, BackfillError>> + Send;
+
+ fn fetch_documents(
+ &self,
+ req: &DocumentBackfillRequest,
+ offset: usize,
+ ) -> impl Future<Output = Result<SourcePage, BackfillError>> + Send;
+
+ fn fetch_emails(
+ &self,
+ req: &EmailBackfillRequest,
+ offset: usize,
+ ) -> impl Future<Output = Result<SourcePage, BackfillError>> + Send;
+}
diff --git a/rust/cloud-storage/search_processing_service/src/domain/service.rs b/rust/cloud-storage/search_processing_service/src/domain/service.rs
new file mode 100644
index 0000000000..7cdb93adc9
--- /dev/null
+++ b/rust/cloud-storage/search_processing_service/src/domain/service.rs
@@ -0,0 +1,143 @@
+//! Application-level backfill service.
+//!
+//! [`BackfillService`] is the inbound contract the HTTP layer talks to. The
+//! [`BackfillOrchestrator`] holds one [`BackfillSource`] (which knows about
+//! every entity type) and one [`SearchEventPublisher`], and runs the shared
+//! paginate-and-publish loop that drains a source onto the publisher. The
+//! loop lives here (in the domain) so it can be tested with in-memory fakes
+//! — adapters stay single-concern.
+
+use std::future::Future;
+
+use super::models::{
+ BackfillError, BackfillReceipt, CallBackfillRequest, ChannelBackfillRequest,
+ ChatBackfillRequest, DocumentBackfillRequest, EmailBackfillRequest, SourcePage,
+};
+use super::ports::{BackfillSource, SearchEventPublisher};
+
+/// Inbound contract for all backfill HTTP routes.
+pub trait BackfillService: Send + Sync + 'static {
+ fn backfill_calls(
+ &self,
+ req: CallBackfillRequest,
+ ) -> impl Future<Output = Result<BackfillReceipt, BackfillError>> + Send;
+ fn backfill_chats(
+ &self,
+ req: ChatBackfillRequest,
+ ) -> impl Future<Output = Result<BackfillReceipt, BackfillError>> + Send;
+ fn backfill_channels(
+ &self,
+ req: ChannelBackfillRequest,
+ ) -> impl Future<Output = Result<BackfillReceipt, BackfillError>> + Send;
+ fn backfill_documents(
+ &self,
+ req: DocumentBackfillRequest,
+ ) -> impl Future<Output = Result<BackfillReceipt, BackfillError>> + Send;
+ fn backfill_emails(
+ &self,
+ req: EmailBackfillRequest,
+ ) -> impl Future<Output = Result<BackfillReceipt, BackfillError>> + Send;
+}
+
+pub struct BackfillOrchestrator<S, P> {
+ source: S,
+ publisher: P,
+}
+
+impl<S, P> BackfillOrchestrator<S, P>
+where
+ S: BackfillSource,
+ P: SearchEventPublisher,
+{
+ pub fn new(source: S, publisher: P) -> Self {
+ Self { source, publisher }
+ }
+}
+
+/// Drive a source by repeatedly calling `fetch(offset)`, publishing each
+/// page's messages, and stopping when the source reports zero rows consumed.
+/// Offset advances by `rows_consumed`, *not* by message count — sources are
+/// free to fold many rows into a smaller batch of messages (see the email
+/// path) without confusing the loop into re-reading rows.
+async fn drain_source<Fut, P>(
+ publisher: &P,
+ fetch: impl Fn(usize) -> Fut,
+) -> Result<BackfillReceipt, BackfillError>
+where
+ Fut: Future<Output = Result<SourcePage, BackfillError>>,
+ P: SearchEventPublisher,
+{
+ let mut offset = 0usize;
+ let mut enqueued = 0usize;
+
+ loop {
+ let page = fetch(offset).await?;
+ if page.rows_consumed == 0 {
+ break;
+ }
+ publisher.publish(page.messages).await?;
+ enqueued += page.rows_consumed;
+ offset += page.rows_consumed;
+ }
+
+ Ok(BackfillReceipt { enqueued })
+}
+
+impl<S, P> BackfillService for BackfillOrchestrator<S, P>
+where
+ S: BackfillSource,
+ P: SearchEventPublisher,
+{
+ async fn backfill_calls(
+ &self,
+ req: CallBackfillRequest,
+ ) -> Result<BackfillReceipt, BackfillError> {
+ drain_source(&self.publisher, |offset| {
+ self.source.fetch_calls(&req, offset)
+ })
+ .await
+ }
+
+ async fn backfill_chats(
+ &self,
+ req: ChatBackfillRequest,
+ ) -> Result<BackfillReceipt, BackfillError> {
+ drain_source(&self.publisher, |offset| {
+ self.source.fetch_chats(&req, offset)
+ })
+ .await
+ }
+
+ async fn backfill_channels(
+ &self,
+ req: ChannelBackfillRequest,
+ ) -> Result<BackfillReceipt, BackfillError> {
+ drain_source(&self.publisher, |offset| {
+ self.source.fetch_channels(&req, offset)
+ })
+ .await
+ }
+
+ async fn backfill_documents(
+ &self,
+ req: DocumentBackfillRequest,
+ ) -> Result<BackfillReceipt, BackfillError> {
+ drain_source(&self.publisher, |offset| {
+ self.source.fetch_documents(&req, offset)
+ })
+ .await
+ }
+
+ async fn backfill_emails(
+ &self,
+ req: EmailBackfillRequest,
+ ) -> Result<BackfillReceipt, BackfillError> {
+ drain_source(&self.publisher, |offset| {
+ self.source.fetch_emails(&req, offset)
+ })
+ .await
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/search_processing_service/src/domain/service/test.rs b/rust/cloud-storage/search_processing_service/src/domain/service/test.rs
new file mode 100644
index 0000000000..fbeade8575
--- /dev/null
+++ b/rust/cloud-storage/search_processing_service/src/domain/service/test.rs
@@ -0,0 +1,233 @@
+use std::sync::Mutex;
+
+use sqs_client::search::{SearchQueueMessage, call::CallRecordMessage};
+
+use super::*;
+use crate::domain::models::{CallBackfillRequest, SourcePage};
+use crate::domain::ports::SearchEventPublisher;
+
+/// Programmable fake fetch closure. `drain_source` takes any
+/// `Fn(usize) -> Future<SourcePage>`, so the test fakes don't need to
+/// implement `BackfillSource` — we just give them a method that matches
+/// the closure shape and avoid stubbing 4 unrelated trait methods.
+struct FakeSource {
+ pages: Mutex<std::collections::VecDeque<SourcePage>>,
+ /// Records the offsets `fetch_page` was called with, in order.
+ offsets: Mutex<Vec<usize>>,
+}
+
+impl FakeSource {
+ fn new(pages: Vec<SourcePage>) -> Self {
+ Self {
+ pages: Mutex::new(pages.into_iter().collect()),
+ offsets: Mutex::new(Vec::new()),
+ }
+ }
+
+ async fn fetch_page(
+ &self,
+ _req: &CallBackfillRequest,
+ offset: usize,
+ ) -> Result<SourcePage, BackfillError> {
+ self.offsets.lock().unwrap().push(offset);
+ Ok(self
+ .pages
+ .lock()
+ .unwrap()
+ .pop_front()
+ .unwrap_or_else(SourcePage::empty))
+ }
+
+ fn observed_offsets(&self) -> Vec<usize> {
+ self.offsets.lock().unwrap().clone()
+ }
+}
+
+/// Source that always errors. Verifies error propagation through the loop.
+struct ExplodingSource;
+
+impl ExplodingSource {
+ async fn fetch_page(
+ &self,
+ _req: &CallBackfillRequest,
+ _offset: usize,
+ ) -> Result<SourcePage, BackfillError> {
+ Err(BackfillError::Source(anyhow::anyhow!("source down")))
+ }
+}
+
+/// Records publisher activity. `SearchQueueMessage` doesn't impl `Clone`, so
+/// instead of holding the messages we just count batches + total messages.
+#[derive(Default)]
+struct RecordingPublisher {
+ batch_sizes: Mutex<Vec<usize>>,
+}
+
+impl RecordingPublisher {
+ fn batch_count(&self) -> usize {
+ self.batch_sizes.lock().unwrap().len()
+ }
+
+ fn total_messages(&self) -> usize {
+ self.batch_sizes.lock().unwrap().iter().sum()
+ }
+
+ fn batch_sizes(&self) -> Vec<usize> {
+ self.batch_sizes.lock().unwrap().clone()
+ }
+}
+
+impl SearchEventPublisher for RecordingPublisher {
+ async fn publish(&self, messages: Vec<SearchQueueMessage>) -> Result<(), BackfillError> {
+ self.batch_sizes.lock().unwrap().push(messages.len());
+ Ok(())
+ }
+}
+
+/// Publisher that always errors. Verifies error propagation.
+struct ExplodingPublisher;
+
+impl SearchEventPublisher for ExplodingPublisher {
+ async fn publish(&self, _messages: Vec<SearchQueueMessage>) -> Result<(), BackfillError> {
+ Err(BackfillError::Publish(anyhow::anyhow!("publish down")))
+ }
+}
+
+fn msg(id: &str) -> SearchQueueMessage {
+ SearchQueueMessage::CallRecord(CallRecordMessage {
+ call_id: id.to_string(),
+ })
+}
+
+/// Build a 1:1 page where messages.len() == rows_consumed (the typical case
+/// for non-batching sources like calls/chats/channels/documents).
+fn page(messages: Vec<SearchQueueMessage>) -> SourcePage {
+ let rows_consumed = messages.len();
+ SourcePage {
+ messages,
+ rows_consumed,
+ }
+}
+
+#[tokio::test]
+async fn drains_source_across_full_pages() {
+ // Three full pages of 5; loop terminates on the empty fourth fetch.
+ let source = FakeSource::new(vec![
+ page((0..5).map(|i| msg(&format!("p1-{i}"))).collect()),
+ page((0..5).map(|i| msg(&format!("p2-{i}"))).collect()),
+ page((0..5).map(|i| msg(&format!("p3-{i}"))).collect()),
+ ]);
+ let publisher = RecordingPublisher::default();
+ let req = CallBackfillRequest::default();
+
+ let receipt = drain_source(&publisher, |offset| source.fetch_page(&req, offset))
+ .await
+ .unwrap();
+
+ assert_eq!(receipt.enqueued, 15);
+ assert_eq!(publisher.batch_count(), 3);
+ assert_eq!(publisher.total_messages(), 15);
+ assert_eq!(publisher.batch_sizes(), vec![5, 5, 5]);
+ // Probed at offsets 0, 5, 10, 15 — last returns empty.
+ assert_eq!(source.observed_offsets(), vec![0, 5, 10, 15]);
+}
+
+#[tokio::test]
+async fn short_final_page_short_circuits() {
+ // Pages of 5, 5, 2. The 2-row page advances offset to 12; the next fetch
+ // returns empty and the loop stops.
+ let source = FakeSource::new(vec![
+ page((0..5).map(|i| msg(&format!("a{i}"))).collect()),
+ page((0..5).map(|i| msg(&format!("b{i}"))).collect()),
+ page((0..2).map(|i| msg(&format!("c{i}"))).collect()),
+ ]);
+ let publisher = RecordingPublisher::default();
+ let req = CallBackfillRequest::default();
+
+ let receipt = drain_source(&publisher, |offset| source.fetch_page(&req, offset))
+ .await
+ .unwrap();
+
+ assert_eq!(receipt.enqueued, 12);
+ assert_eq!(publisher.batch_sizes(), vec![5, 5, 2]);
+ assert_eq!(source.observed_offsets(), vec![0, 5, 10, 12]);
+}
+
+#[tokio::test]
+async fn batched_source_advances_by_rows_not_messages() {
+ // Mimics the email source: each page consumes 100 source rows but
+ // produces only 3 batched messages. The loop must advance offset by
+ // `rows_consumed` (100), not by `messages.len()` (3) — otherwise the
+ // next fetch would re-read 97 rows we just processed.
+ let source = FakeSource::new(vec![
+ SourcePage {
+ messages: (0..3).map(|i| msg(&format!("p1-{i}"))).collect(),
+ rows_consumed: 100,
+ },
+ SourcePage {
+ messages: (0..3).map(|i| msg(&format!("p2-{i}"))).collect(),
+ rows_consumed: 100,
+ },
+ SourcePage {
+ messages: (0..2).map(|i| msg(&format!("p3-{i}"))).collect(),
+ rows_consumed: 40,
+ },
+ ]);
+ let publisher = RecordingPublisher::default();
+ let req = CallBackfillRequest::default();
+
+ let receipt = drain_source(&publisher, |offset| source.fetch_page(&req, offset))
+ .await
+ .unwrap();
+
+ // enqueued = sum of rows_consumed (the meaningful unit), not message count.
+ assert_eq!(receipt.enqueued, 240);
+ // The publisher saw the message-count-shaped batches: 3, 3, 2.
+ assert_eq!(publisher.batch_sizes(), vec![3, 3, 2]);
+ // Offsets advance by rows_consumed: 0 → 100 → 200 → 240 → empty.
+ assert_eq!(source.observed_offsets(), vec![0, 100, 200, 240]);
+}
+
+#[tokio::test]
+async fn empty_source_publishes_nothing() {
+ let source = FakeSource::new(vec![]);
+ let publisher = RecordingPublisher::default();
+ let req = CallBackfillRequest::default();
+
+ let receipt = drain_source(&publisher, |offset| source.fetch_page(&req, offset))
+ .await
+ .unwrap();
+
+ assert_eq!(receipt.enqueued, 0);
+ assert_eq!(publisher.batch_count(), 0);
+ assert_eq!(source.observed_offsets(), vec![0]);
+}
+
+#[tokio::test]
+async fn source_error_propagates_without_partial_publish() {
+ let source = ExplodingSource;
+ let publisher = RecordingPublisher::default();
+ let req = CallBackfillRequest::default();
+
+ let err = drain_source(&publisher, |offset| source.fetch_page(&req, offset))
+ .await
+ .unwrap_err();
+
+ assert!(matches!(err, BackfillError::Source(_)));
+ assert_eq!(publisher.batch_count(), 0);
+}
+
+#[tokio::test]
+async fn publish_error_propagates_after_first_fetch() {
+ let source = FakeSource::new(vec![page(vec![msg("only")])]);
+ let publisher = ExplodingPublisher;
+ let req = CallBackfillRequest::default();
+
+ let err = drain_source(&publisher, |offset| source.fetch_page(&req, offset))
+ .await
+ .unwrap_err();
+
+ assert!(matches!(err, BackfillError::Publish(_)));
+ // Source hit once with offset=0; publish failure stops the loop.
+ assert_eq!(source.observed_offsets(), vec![0]);
+}
diff --git a/rust/cloud-storage/search_processing_service/src/main.rs b/rust/cloud-storage/search_processing_service/src/main.rs
index 787859cda7..e9e76ee069 100644
--- a/rust/cloud-storage/search_processing_service/src/main.rs
+++ b/rust/cloud-storage/search_processing_service/src/main.rs
@@ -3,6 +3,8 @@ use std::sync::Arc;
use crate::{
api::context::ApiContext,
+ domain::service::BackfillOrchestrator,
+ outbound::{publisher::SqsSearchEventPublisher, source::PgBackfillSource},
process::{context::SearchProcessingContext, worker::run_search_processing_workers},
};
use anyhow::Context;
@@ -12,14 +14,55 @@ use macro_entrypoint::MacroEntrypoint;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
use opensearch_client::OpensearchClient;
use rust_embed::RustEmbed;
-use secretsmanager_client::{LocalOrRemoteSecret, SecretManager};
+use secretsmanager_client::{LocalOrRemoteSecret, OptionalLocalOrRemoteSecret, SecretManager};
+use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;
mod api;
mod config;
+mod domain;
+mod outbound;
mod parsers;
mod process;
+/// Concrete [`BackfillOrchestrator`] wired to the production Postgres source
+/// and the SQS publisher. Lives in the wiring module so the domain stays
+/// agnostic of which adapters back it.
+pub type BackfillServiceImpl = BackfillOrchestrator<PgBackfillSource, SqsSearchEventPublisher>;
+
+/// Resolve a read-replica macrodb URL via [`OptionalLocalOrRemoteSecret`] and
+/// connect a small pool. Returns `None` when the replica URL is missing,
+/// blank, fails to fetch from Secrets Manager, or is unreachable. Failures
+/// are intentionally warning-level rather than fatal: the readonly pool is a
+/// contention optimisation, not a correctness requirement (e.g. local laptop
+/// dev cannot reach the VPC-gated read replica).
+async fn resolve_readonly_pool(
+ raw: Option<String>,
+ secrets: &secretsmanager_client::SecretsManager,
+) -> Option<PgPool> {
+ let raw = raw.filter(|s| !s.is_empty());
+ let resolved = match OptionalLocalOrRemoteSecret::new_from_secret_manager(raw, secrets).await {
+ Ok(r) => r,
+ Err(e) => {
+ tracing::warn!(error=?e, "unable to fetch readonly db secret; backfills will use primary");
+ return None;
+ }
+ };
+ let url = resolved.as_str()?;
+ match PgPoolOptions::new()
+ .min_connections(1)
+ .max_connections(10)
+ .connect(url)
+ .await
+ {
+ Ok(pool) => Some(pool),
+ Err(e) => {
+ tracing::warn!(error=?e, "could not connect to readonly macrodb; backfills will use primary");
+ None
+ }
+ }
+}
+
#[allow(dead_code)]
#[derive(RustEmbed)]
#[folder = "pdfium-lib/linux/"]
@@ -95,6 +138,31 @@ async fn main() -> anyhow::Result<()> {
let internal_auth_key = LocalOrRemoteSecret::Local(InternalApiSecretKey::new()?);
+ // Backfills run against the read-replica when available so they don't
+ // contend with writes on the primary. Queue workers always read from the
+ // primary because replica lag would cause them to miss rows they are
+ // meant to index.
+ let backfill_db =
+ match resolve_readonly_pool(config.database_url_readonly.clone(), &secretsmanager_client)
+ .await
+ {
+ Some(pool) => {
+ tracing::info!("using read-replica pool for backfill reads");
+ pool
+ }
+ None => {
+ tracing::info!("backfills will read from the primary pool");
+ db.clone()
+ }
+ };
+
+ let sqs_client = Arc::new(sqs_client);
+
+ let backfill_service = Arc::new(BackfillOrchestrator::new(
+ PgBackfillSource::new(backfill_db, config.backfill_page_sizes),
+ SqsSearchEventPublisher::new(sqs_client.clone()),
+ ));
+
#[cfg(feature = "processing")]
{
use std::sync::Arc;
@@ -139,10 +207,11 @@ async fn main() -> anyhow::Result<()> {
api::setup_and_serve(ApiContext {
db,
- sqs_client: Arc::new(sqs_client),
+ sqs_client,
opensearch_client: Arc::new(opensearch_client),
internal_auth_key,
config: Arc::new(config),
+ backfill_service,
})
.await?;
Ok(())
diff --git a/rust/cloud-storage/search_processing_service/src/outbound/mod.rs b/rust/cloud-storage/search_processing_service/src/outbound/mod.rs
new file mode 100644
index 0000000000..7d27ca1d18
--- /dev/null
+++ b/rust/cloud-storage/search_processing_service/src/outbound/mod.rs
@@ -0,0 +1,2 @@
+pub mod publisher;
+pub mod source;
diff --git a/rust/cloud-storage/search_processing_service/src/outbound/publisher.rs b/rust/cloud-storage/search_processing_service/src/outbound/publisher.rs
new file mode 100644
index 0000000000..def8910b0c
--- /dev/null
+++ b/rust/cloud-storage/search_processing_service/src/outbound/publisher.rs
@@ -0,0 +1,30 @@
+use std::sync::Arc;
+
+use sqs_client::search::SearchQueueMessage;
+
+use crate::domain::models::BackfillError;
+use crate::domain::ports::SearchEventPublisher;
+
+/// SQS-backed implementation of [`SearchEventPublisher`]. The only adapter
+/// in sps that talks to the search-event queue.
+pub struct SqsSearchEventPublisher {
+ sqs: Arc<sqs_client::SQS>,
+}
+
+impl SqsSearchEventPublisher {
+ pub fn new(sqs: Arc<sqs_client::SQS>) -> Self {
+ Self { sqs }
+ }
+}
+
+impl SearchEventPublisher for SqsSearchEventPublisher {
+ async fn publish(&self, messages: Vec<SearchQueueMessage>) -> Result<(), BackfillError> {
+ if messages.is_empty() {
+ return Ok(());
+ }
+ self.sqs
+ .bulk_send_message_to_search_event_queue(messages)
+ .await
+ .map_err(BackfillError::Publish)
+ }
+}
diff --git a/rust/cloud-storage/search_processing_service/src/outbound/source.rs b/rust/cloud-storage/search_processing_service/src/outbound/source.rs
new file mode 100644
index 0000000000..06b263e0b2
--- /dev/null
+++ b/rust/cloud-storage/search_processing_service/src/outbound/source.rs
@@ -0,0 +1,256 @@
+use std::collections::HashMap;
+
+use model::document::FileType;
+use sqlx::PgPool;
+use sqs_client::search::{
+ SearchQueueMessage, call::CallRecordMessage, channel::ChannelMessageUpdate, chat::ChatMessage,
+ email::EmailThreadBatchMessage,
+};
+
+use crate::config::BackfillPageSizes;
+use crate::domain::models::{
+ BackfillError, CallBackfillRequest, ChannelBackfillRequest, ChatBackfillRequest,
+ DocumentBackfillRequest, EmailBackfillRequest, SourcePage,
+};
+use crate::domain::ports::BackfillSource;
+
+const DEFAULT_EMAIL_BATCH_SIZE: usize = 50;
+
+/// Postgres-backed [`BackfillSource`] for every search-indexed entity. One
+/// struct, one DB pool, per-entity page sizes — collapses what used to be
+/// five parallel adapters. New entity types just add a method here.
+pub struct PgBackfillSource {
+ db: PgPool,
+ page_sizes: BackfillPageSizes,
+}
+
+impl PgBackfillSource {
+ pub fn new(db: PgPool, page_sizes: BackfillPageSizes) -> Self {
+ Self { db, page_sizes }
+ }
+}
+
+impl BackfillSource for PgBackfillSource {
+ async fn fetch_calls(
+ &self,
+ req: &CallBackfillRequest,
+ offset: usize,
+ ) -> Result<SourcePage, BackfillError> {
+ // Caller passed an explicit set of ids: page through them at the
+ // configured page size so this branch and the full-scan branch share
+ // the same loop shape and failure semantics.
+ if !req.call_ids.is_empty() {
+ let start = offset;
+ if start >= req.call_ids.len() {
+ return Ok(SourcePage::empty());
+ }
+ let end = start
+ .saturating_add(self.page_sizes.calls)
+ .min(req.call_ids.len());
+ let messages: Vec<SearchQueueMessage> = req.call_ids[start..end]
+ .iter()
+ .map(|id| {
+ SearchQueueMessage::CallRecord(CallRecordMessage {
+ call_id: id.clone(),
+ })
+ })
+ .collect();
+ let rows_consumed = messages.len();
+ return Ok(SourcePage {
+ messages,
+ rows_consumed,
+ });
+ }
+
+ let batch = macro_db_client::call_record::get::get_call_records_for_search_backfill(
+ &self.db,
+ self.page_sizes.calls as i64,
+ offset as i64,
+ )
+ .await
+ .map_err(BackfillError::Source)?;
+
+ let rows_consumed = batch.len();
+ let messages: Vec<SearchQueueMessage> = batch
+ .into_iter()
+ .map(|r| {
+ SearchQueueMessage::CallRecord(CallRecordMessage {
+ call_id: r.call_id.to_string(),
+ })
+ })
+ .collect();
+
+ Ok(SourcePage {
+ messages,
+ rows_consumed,
+ })
+ }
+
+ async fn fetch_chats(
+ &self,
+ req: &ChatBackfillRequest,
+ offset: usize,
+ ) -> Result<SourcePage, BackfillError> {
+ let chat_ids = (!req.chat_ids.is_empty()).then_some(&req.chat_ids);
+ let user_ids = (!req.user_ids.is_empty()).then_some(&req.user_ids);
+
+ let batch = macro_db_client::chat::get::get_chat_messages_for_search_backfill(
+ &self.db,
+ self.page_sizes.chats as i64,
+ offset as i64,
+ chat_ids,
+ user_ids,
+ )
+ .await
+ .map_err(BackfillError::Source)?;
+
+ let rows_consumed = batch.len();
+ let messages: Vec<SearchQueueMessage> = batch
+ .into_iter()
+ .map(|chat| {
+ SearchQueueMessage::ChatMessage(ChatMessage {
+ chat_id: chat.chat_id,
+ message_id: chat.message_id,
+ user_id: chat.user_id,
+ created_at: chat.created_at,
+ updated_at: chat.updated_at,
+ })
+ })
+ .collect();
+
+ Ok(SourcePage {
+ messages,
+ rows_consumed,
+ })
+ }
+
+ async fn fetch_channels(
+ &self,
+ _req: &ChannelBackfillRequest,
+ offset: usize,
+ ) -> Result<SourcePage, BackfillError> {
+ let batch = comms_db_client::messages::get_messages::get_channel_messages(
+ &self.db,
+ self.page_sizes.channels as i64,
+ offset as i64,
+ )
+ .await
+ .map_err(BackfillError::Source)?;
+
+ let rows_consumed = batch.len();
+ let messages: Vec<SearchQueueMessage> = batch
+ .into_iter()
+ .map(|(channel_id, message_id)| {
+ SearchQueueMessage::ChannelMessageUpdate(ChannelMessageUpdate {
+ channel_id: channel_id.to_string(),
+ message_id: message_id.to_string(),
+ })
+ })
+ .collect();
+
+ Ok(SourcePage {
+ messages,
+ rows_consumed,
+ })
+ }
+
+ async fn fetch_documents(
+ &self,
+ req: &DocumentBackfillRequest,
+ offset: usize,
+ ) -> Result<SourcePage, BackfillError> {
+ let batch = macro_db_client::document::get_documents_search::get_documents_for_search(
+ &self.db,
+ self.page_sizes.documents as i64,
+ offset as i64,
+ &req.file_types,
+ &req.sub_type,
+ &req.created_after,
+ &req.created_before,
+ )
+ .await
+ .map_err(BackfillError::Source)?;
+
+ let rows_consumed = batch.len();
+ let messages: Vec<SearchQueueMessage> = batch
+ .iter()
+ .map(|d| {
+ if d.file_type == FileType::Md {
+ SearchQueueMessage::ExtractSync(d.into())
+ } else {
+ SearchQueueMessage::ExtractDocumentText(d.into())
+ }
+ })
+ .collect();
+
+ Ok(SourcePage {
+ messages,
+ rows_consumed,
+ })
+ }
+
+ async fn fetch_emails(
+ &self,
+ req: &EmailBackfillRequest,
+ offset: usize,
+ ) -> Result<SourcePage, BackfillError> {
+ let batch_size = req
+ .batch_size
+ .filter(|n| *n > 0)
+ .unwrap_or(DEFAULT_EMAIL_BATCH_SIZE);
+
+ let rows = match req.since {
+ Some(since) => {
+ email_db_client::threads::get::get_paginated_thread_ids_with_macro_user_id_since(
+ &self.db,
+ self.page_sizes.emails as i64,
+ offset as i64,
+ since,
+ )
+ .await
+ .map_err(BackfillError::Source)?
+ }
+ None => email_db_client::threads::get::get_paginated_thread_ids_with_macro_user_id(
+ &self.db,
+ self.page_sizes.emails as i64,
+ offset as i64,
+ )
+ .await
+ .map_err(BackfillError::Source)?,
+ };
+
+ let rows_consumed = rows.len();
+ if rows_consumed == 0 {
+ return Ok(SourcePage::empty());
+ }
+
+ let mut by_user: HashMap<String, Vec<String>> = HashMap::new();
+ for (thread_id, macro_user_id) in rows {
+ by_user
+ .entry(macro_user_id)
+ .or_default()
+ .push(thread_id.to_string());
+ }
+
+ let messages: Vec<SearchQueueMessage> = by_user
+ .into_iter()
+ .flat_map(|(macro_user_id, thread_ids)| {
+ thread_ids
+ .chunks(batch_size)
+ .map(|chunk| {
+ SearchQueueMessage::ExtractEmailThreadBatch(EmailThreadBatchMessage {
+ thread_ids: chunk.to_vec(),
+ macro_user_id: macro_user_id.clone(),
+ index_override: req.index_override.clone(),
+ })
+ })
+ .collect::<Vec<_>>()
+ })
+ .collect();
+
+ Ok(SourcePage {
+ messages,
+ rows_consumed,
+ })
+ }
+}
diff --git a/rust/cloud-storage/secretsmanager_client/src/lib.rs b/rust/cloud-storage/secretsmanager_client/src/lib.rs
index 7ea57bb3e0..d78216c769 100644
--- a/rust/cloud-storage/secretsmanager_client/src/lib.rs
+++ b/rust/cloud-storage/secretsmanager_client/src/lib.rs
@@ -5,7 +5,7 @@ pub use SecretsManagerClient as SecretsManager;
use aws_sdk_secretsmanager as secretsmanager;
#[allow(unused_imports)]
use mockall::automock;
-pub use remote_env_var::{LocalOrRemoteSecret, SecretManager};
+pub use remote_env_var::{LocalOrRemoteSecret, OptionalLocalOrRemoteSecret, SecretManager};
use std::sync::Arc;
use thiserror::Error;