Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(search_processing_service): create backfill script for names (#333)

Evan Hutnik5cbb151dc01f
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 7059a329e7..82fd867841 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -7341,7 +7341,9 @@ dependencies = [
"aws-sdk-sqs",
"axum",
"chrono",
+ "comms_db_client",
"comms_service_client",
+ "email_db_client",
"email_service_client",
"futures",
"http-body-util",
diff --git a/rust/cloud-storage/comms_db_client/.sqlx/query-b5578ab6da001f418fe8ff216616b79eb80caf8e2677fcf4e7127151060a50ea.json b/rust/cloud-storage/comms_db_client/.sqlx/query-b5578ab6da001f418fe8ff216616b79eb80caf8e2677fcf4e7127151060a50ea.json
new file mode 100644
index 0000000000..2c70220aed
--- /dev/null
+++ b/rust/cloud-storage/comms_db_client/.sqlx/query-b5578ab6da001f418fe8ff216616b79eb80caf8e2677fcf4e7127151060a50ea.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id as \"channel_id\"\n FROM\n comms_channels\n ORDER BY\n created_at ASC\n LIMIT $1\n OFFSET $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "channel_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "b5578ab6da001f418fe8ff216616b79eb80caf8e2677fcf4e7127151060a50ea"
+}
diff --git a/rust/cloud-storage/comms_db_client/src/channels/get_channels.rs b/rust/cloud-storage/comms_db_client/src/channels/get_channels.rs
index ea2c338389..969aa5a73c 100644
--- a/rust/cloud-storage/comms_db_client/src/channels/get_channels.rs
+++ b/rust/cloud-storage/comms_db_client/src/channels/get_channels.rs
@@ -181,6 +181,34 @@ pub async fn get_org_channels(
Ok(channels)
}
+/// Returns a paginated list of project IDs, sorting by ascending so we don't miss new ones
+#[tracing::instrument(skip(db))]
+pub async fn get_all_channel_ids_paginated(
+ db: &sqlx::Pool<sqlx::Postgres>,
+ limit: i64,
+ offset: i64,
+) -> anyhow::Result<Vec<String>> {
+ let result = sqlx::query!(
+ r#"
+ SELECT
+ id as "channel_id"
+ FROM
+ comms_channels
+ ORDER BY
+ created_at ASC
+ LIMIT $1
+ OFFSET $2
+ "#,
+ limit,
+ offset
+ )
+ .map(|row| row.channel_id.to_string())
+ .fetch_all(db)
+ .await?;
+
+ Ok(result)
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-341489a2c91e2bf15545e01ab49df8ca99355322514ac541a95c0ef65491505d.json b/rust/cloud-storage/email_db_client/.sqlx/query-341489a2c91e2bf15545e01ab49df8ca99355322514ac541a95c0ef65491505d.json
new file mode 100644
index 0000000000..93f4c93d02
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/.sqlx/query-341489a2c91e2bf15545e01ab49df8ca99355322514ac541a95c0ef65491505d.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id as \"thread_id\"\n FROM\n email_threads\n ORDER BY\n created_at ASC\n LIMIT $1\n OFFSET $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "341489a2c91e2bf15545e01ab49df8ca99355322514ac541a95c0ef65491505d"
+}
diff --git a/rust/cloud-storage/email_db_client/src/threads/get.rs b/rust/cloud-storage/email_db_client/src/threads/get.rs
index cffaa730d2..2246a4d586 100644
--- a/rust/cloud-storage/email_db_client/src/threads/get.rs
+++ b/rust/cloud-storage/email_db_client/src/threads/get.rs
@@ -446,6 +446,34 @@ pub async fn get_thread_by_id_and_link_id(
}
}
+/// Returns a paginated list of thread IDs, sorting by ascending so we don't miss new ones
+#[tracing::instrument(skip(db))]
+pub async fn get_all_thread_ids_paginated(
+ db: &sqlx::Pool<sqlx::Postgres>,
+ limit: i64,
+ offset: i64,
+) -> anyhow::Result<Vec<String>> {
+ let result = sqlx::query!(
+ r#"
+ SELECT
+ id as "thread_id"
+ FROM
+ email_threads
+ ORDER BY
+ created_at ASC
+ LIMIT $1
+ OFFSET $2
+ "#,
+ limit,
+ offset
+ )
+ .map(|row| row.thread_id.to_string())
+ .fetch_all(db)
+ .await?;
+
+ Ok(result)
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-11ddfba613626f54d684c1399279df5c3364e8d3dfc0484cda469086991a64fd.json b/rust/cloud-storage/macro_db_client/.sqlx/query-11ddfba613626f54d684c1399279df5c3364e8d3dfc0484cda469086991a64fd.json
new file mode 100644
index 0000000000..f8c1b33c14
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-11ddfba613626f54d684c1399279df5c3364e8d3dfc0484cda469086991a64fd.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id as \"chat_id\"\n FROM\n \"Chat\"\n WHERE\n \"deletedAt\" IS NULL\n ORDER BY\n \"createdAt\" ASC\n LIMIT $1\n OFFSET $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "chat_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "11ddfba613626f54d684c1399279df5c3364e8d3dfc0484cda469086991a64fd"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-65af936c2ba7200bb57024fb52cd27fbb4ac3a6b655e5dc2c11ea4c802587214.json b/rust/cloud-storage/macro_db_client/.sqlx/query-65af936c2ba7200bb57024fb52cd27fbb4ac3a6b655e5dc2c11ea4c802587214.json
new file mode 100644
index 0000000000..9e5261243d
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-65af936c2ba7200bb57024fb52cd27fbb4ac3a6b655e5dc2c11ea4c802587214.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id as \"document_id\"\n FROM\n \"Document\"\n WHERE\n \"deletedAt\" IS NULL\n ORDER BY\n \"createdAt\" ASC\n LIMIT $1\n OFFSET $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "document_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "65af936c2ba7200bb57024fb52cd27fbb4ac3a6b655e5dc2c11ea4c802587214"
+}
diff --git a/rust/cloud-storage/macro_db_client/src/chat/get.rs b/rust/cloud-storage/macro_db_client/src/chat/get.rs
index a311dc5e98..3e116076fb 100644
--- a/rust/cloud-storage/macro_db_client/src/chat/get.rs
+++ b/rust/cloud-storage/macro_db_client/src/chat/get.rs
@@ -273,6 +273,36 @@ pub async fn get_all_chat_ids_with_users_paginated(
Ok(result)
}
+/// Returns a paginated list of chat IDs, sorting by ascending so we don't miss new ones
+#[tracing::instrument(skip(db))]
+pub async fn get_all_chat_ids_paginated(
+ db: &sqlx::Pool<sqlx::Postgres>,
+ limit: i64,
+ offset: i64,
+) -> anyhow::Result<Vec<String>> {
+ let result = sqlx::query!(
+ r#"
+ SELECT
+ id as "chat_id"
+ FROM
+ "Chat"
+ WHERE
+ "deletedAt" IS NULL
+ ORDER BY
+ "createdAt" ASC
+ LIMIT $1
+ OFFSET $2
+ "#,
+ limit,
+ offset
+ )
+ .map(|row| row.chat_id)
+ .fetch_all(db)
+ .await?;
+
+ Ok(result)
+}
+
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ChatHistoryInfo {
pub item_id: String,
diff --git a/rust/cloud-storage/macro_db_client/src/document/get_all_documents.rs b/rust/cloud-storage/macro_db_client/src/document/get_all_documents.rs
index 3a1924e2aa..5ab340316c 100644
--- a/rust/cloud-storage/macro_db_client/src/document/get_all_documents.rs
+++ b/rust/cloud-storage/macro_db_client/src/document/get_all_documents.rs
@@ -129,6 +129,36 @@ pub async fn get_documents_to_delete(
Ok(result)
}
+/// Returns a paginated list of document IDs, sorting by ascending so we don't miss new ones
+#[tracing::instrument(skip(db))]
+pub async fn get_all_document_ids_paginated(
+ db: &sqlx::Pool<sqlx::Postgres>,
+ limit: i64,
+ offset: i64,
+) -> anyhow::Result<Vec<String>> {
+ let result = sqlx::query!(
+ r#"
+ SELECT
+ id as "document_id"
+ FROM
+ "Document"
+ WHERE
+ "deletedAt" IS NULL
+ ORDER BY
+ "createdAt" ASC
+ LIMIT $1
+ OFFSET $2
+ "#,
+ limit,
+ offset
+ )
+ .map(|row| row.document_id)
+ .fetch_all(db)
+ .await?;
+
+ Ok(result)
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/rust/cloud-storage/search_processing_service/Cargo.toml b/rust/cloud-storage/search_processing_service/Cargo.toml
index 249829df20..25bb473667 100644
--- a/rust/cloud-storage/search_processing_service/Cargo.toml
+++ b/rust/cloud-storage/search_processing_service/Cargo.toml
@@ -9,12 +9,18 @@ version = "0.1.0"
default = ["processing", "service"]
processing = []
service = ["macro_db_client"]
+backfill_names = ["email_db_client", "comms_db_client"]
[[bin]]
name = "backfill_chat"
path = "src/bin/backfill_chat.rs"
required-features = ["service"]
+[[bin]]
+name = "backfill_entity_names"
+path = "src/bin/backfill_entity_names.rs"
+required-features = ["backfill_names"]
+
[[bin]]
name = "backfill_project"
path = "src/bin/backfill_project.rs"
@@ -33,7 +39,9 @@ aws-sdk-secretsmanager = { workspace = true }
aws-sdk-sqs = { workspace = true }
axum = { workspace = true }
chrono = { workspace = true }
+comms_db_client = { path = "../comms_db_client", optional = true }
comms_service_client = { path = "../comms_service_client" }
+email_db_client = { path = "../email_db_client", optional = true }
email_service_client = { path = "../email_service_client" }
futures = { workspace = true }
http-body-util = { workspace = true }
diff --git a/rust/cloud-storage/search_processing_service/src/bin/backfill_entity_names.rs b/rust/cloud-storage/search_processing_service/src/bin/backfill_entity_names.rs
new file mode 100644
index 0000000000..cee16357bf
--- /dev/null
+++ b/rust/cloud-storage/search_processing_service/src/bin/backfill_entity_names.rs
@@ -0,0 +1,195 @@
+/// backfill_entity_names.rs is used to trigger a backfill for the entity name index in OS
+/// Required environment variables:
+/// - DATABASE_URL
+/// - SEARCH_EVENT_QUEUE
+///
+/// Usage:
+/// cargo run backfill_entity_names.rs <COMMA_SEPARATED_LIST_OF_INDICES>
+/// Example:
+/// cargo run backfill_entity_names.rs chats,documents
+use anyhow::Context;
+use macro_entrypoint::MacroEntrypoint;
+use models_opensearch::SearchEntityType;
+use sqlx::postgres::PgPoolOptions;
+use sqs_client::search::name::EntityName;
+use std::future::Future;
+use std::str::FromStr;
+use uuid::Uuid;
+
+#[tokio::main]
+async fn main() -> anyhow::Result<()> {
+ MacroEntrypoint::default().init();
+
+ // 1. Parse CLI Arguments
+ let args: Vec<String> = std::env::args().collect();
+
+ let target_indices: Vec<SearchEntityType> = if args.len() < 2 {
+ // Default to all supported entity types
+ println!("No indices specified, backfilling all supported types");
+ vec![
+ SearchEntityType::Chats,
+ SearchEntityType::Documents,
+ SearchEntityType::Channels,
+ SearchEntityType::Emails,
+ // Note: Projects is not included as it's not implemented
+ ]
+ } else {
+ let indices_arg = &args[1];
+ indices_arg
+ .split(',')
+ .map(|s| {
+ // Trim whitespace and parse using strum::EnumString derived on SearchEntityType
+ SearchEntityType::from_str(s.trim())
+ .with_context(|| format!("Invalid entity index type: {}", s))
+ })
+ .collect::<anyhow::Result<_>>()?
+ };
+
+ if target_indices.is_empty() {
+ println!("No valid indices provided to process.");
+ return Ok(());
+ }
+
+ // Check if user is trying to backfill Projects
+ if target_indices.contains(&SearchEntityType::Projects) {
+ anyhow::bail!(
+ "Backfill for 'projects' is not implemented. Supported types: chats, documents, channels, emails"
+ );
+ }
+
+ println!("Starting backfill for indices: {:?}", target_indices);
+
+ 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 = aws_config::defaults(aws_config::BehaviorVersion::latest())
+ .region("us-east-1")
+ .load()
+ .await;
+
+ let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&queue_aws_config))
+ .search_event_queue(&search_event_queue);
+
+ for index in target_indices {
+ match index {
+ SearchEntityType::Chats => {
+ backfill_entities(
+ &sqs_client,
+ "chats",
+ SearchEntityType::Chats,
+ |limit, offset| {
+ macro_db_client::chat::get::get_all_chat_ids_paginated(&db, limit, offset)
+ },
+ )
+ .await?;
+ }
+ SearchEntityType::Documents => {
+ backfill_entities(
+ &sqs_client,
+ "documents",
+ SearchEntityType::Documents,
+ |limit, offset| {
+ macro_db_client::document::get_all_documents::get_all_document_ids_paginated(
+ &db, limit, offset,
+ )
+ },
+ )
+ .await?;
+ }
+ SearchEntityType::Channels => {
+ backfill_entities(
+ &sqs_client,
+ "channels",
+ SearchEntityType::Channels,
+ |limit, offset| {
+ comms_db_client::channels::get_channels::get_all_channel_ids_paginated(
+ &db, limit, offset,
+ )
+ },
+ )
+ .await?;
+ }
+ SearchEntityType::Emails => {
+ backfill_entities(
+ &sqs_client,
+ "email threads",
+ SearchEntityType::Emails,
+ |limit, offset| {
+ email_db_client::threads::get::get_all_thread_ids_paginated(
+ &db, limit, offset,
+ )
+ },
+ )
+ .await?;
+ }
+ SearchEntityType::Projects => {
+ unreachable!("Backfill logic for 'projects' is not implemented.");
+ }
+ }
+ }
+
+ Ok(())
+}
+
+/// Generic function to handle pagination, UUID parsing, and SQS queuing for any entity type
+async fn backfill_entities<F, Fut>(
+ sqs_client: &sqs_client::SQS,
+ name: &str,
+ entity_type: SearchEntityType,
+ fetcher: F,
+) -> anyhow::Result<()>
+where
+ F: Fn(i64, i64) -> Fut, // Function taking (limit, offset)
+ Fut: Future<Output = anyhow::Result<Vec<String>>>,
+{
+ let limit = 5000;
+ let mut offset = 0;
+ let mut count = 0;
+
+ loop {
+ println!("getting {name}");
+
+ let ids = fetcher(limit, offset).await?;
+ println!("got batch offset {offset}");
+
+ if ids.is_empty() {
+ tracing::trace!("no more {name} found");
+ break;
+ }
+
+ count += ids.len();
+
+ tracing::trace!(count = ids.len(), "ready to queue {name}");
+
+ sqs_client
+ .bulk_send_message_to_search_event_queue(
+ ids.iter()
+ .map(|id| {
+ sqs_client::search::SearchQueueMessage::UpdateEntityName(EntityName {
+ entity_id: Uuid::parse_str(id)
+ .with_context(|| {
+ format!("Failed to parse UUID from {}: {}", name, id)
+ })
+ .unwrap(),
+ entity_type: entity_type.clone(),
+ })
+ })
+ .collect(),
+ )
+ .await?;
+ println!("queued batch with offset {offset}");
+
+ offset += limit;
+ }
+
+ println!("Completed. Total {} processed: {}", name, count);
+ Ok(())
+}