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.

move from names index to querying macrodb directly (#793)

Will Hutchinson21bdcb2da0e3
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 1f48b50ac9..fa3934429a 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -5714,6 +5714,23 @@ version = "0.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc0287524726960e07b119cebd01678f852f147742ae0d925e6a520dca956126"
+[[package]]
+name = "name_search"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "macro_db_migrator",
+ "macro_user_id",
+ "models_opensearch",
+ "non_empty",
+ "serde",
+ "sqlx",
+ "thiserror 2.0.17",
+ "tokio",
+ "tracing",
+ "uuid",
+]
+
[[package]]
name = "native-tls"
version = "0.2.13"
@@ -7621,10 +7638,12 @@ dependencies = [
"macro_entrypoint",
"macro_env",
"macro_middleware",
+ "macro_user_id",
"model",
"models_email",
"models_opensearch",
"models_search",
+ "name_search",
"opensearch_client",
"secretsmanager_client",
"serde",
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index bd0f9ae55f..e5d69c7574 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -76,6 +76,7 @@ members = [
"models_sfs",
"models_soup",
"models_team",
+ "name_search",
"non_empty",
"notification_db_client",
"notification_service",
diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfile
index 804f2f90a7..2ac95b97b2 100644
--- a/rust/cloud-storage/justfile
+++ b/rust/cloud-storage/justfile
@@ -58,6 +58,7 @@ setup_test_envs:
echo "DATABASE_URL={{ MACRODB }}" >> ./email/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./system_properties/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./properties/.env
+ echo "DATABASE_URL={{ MACRODB }}" >> ./name_search/.env
setup_macrodb:
just macro_db_client/migrate_db
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260106165331_email_subject_search_indices.sql b/rust/cloud-storage/macro_db_client/migrations/20260106165331_email_subject_search_indices.sql
new file mode 100644
index 0000000000..93ac6fbf58
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260106165331_email_subject_search_indices.sql
@@ -0,0 +1,16 @@
+-- Creates necesary email indices to improve the performance of subject-search
+
+-- Enable trigram extension for fuzzy text matching
+CREATE EXTENSION IF NOT EXISTS pg_trgm;
+
+-- The search query orders by (thread_id, internal_date_ts ASC) but existing index uses DESC
+CREATE INDEX IF NOT EXISTS idx_email_messages_thread_id_internal_date_asc
+ ON email_messages (thread_id, internal_date_ts ASC);
+
+-- GIN trigram index allows efficient partial string matching
+CREATE INDEX IF NOT EXISTS idx_email_messages_subject_trgm
+ ON email_messages USING gin (subject gin_trgm_ops);
+
+-- Optimize the non-ids_only query path that filters by link_id
+CREATE INDEX IF NOT EXISTS idx_email_messages_link_id_thread_id_date_asc
+ ON email_messages (link_id, thread_id, internal_date_ts ASC);
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260106165341_document_search_indices.sql b/rust/cloud-storage/macro_db_client/migrations/20260106165341_document_search_indices.sql
new file mode 100644
index 0000000000..322d3e7569
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260106165341_document_search_indices.sql
@@ -0,0 +1,8 @@
+-- Creates necessary document indices to improve the performance of name search
+
+-- Enable trigram extension for fuzzy text matching
+CREATE EXTENSION IF NOT EXISTS pg_trgm;
+
+-- GIN trigram index allows efficient partial string matching
+CREATE INDEX IF NOT EXISTS idx_document_name_trgm
+ ON "Document" USING gin (name gin_trgm_ops);
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260106165345_chat_search_indices.sql b/rust/cloud-storage/macro_db_client/migrations/20260106165345_chat_search_indices.sql
new file mode 100644
index 0000000000..e3cc4d1355
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260106165345_chat_search_indices.sql
@@ -0,0 +1,8 @@
+-- Creates necessary chat indices to improve the performance of name search
+
+-- Enable trigram extension for fuzzy text matching
+CREATE EXTENSION IF NOT EXISTS pg_trgm;
+
+-- GIN trigram index allows efficient partial string matching
+CREATE INDEX IF NOT EXISTS idx_chat_name_trgm
+ ON "Chat" USING gin (name gin_trgm_ops);
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260106165348_project_search_indices.sql b/rust/cloud-storage/macro_db_client/migrations/20260106165348_project_search_indices.sql
new file mode 100644
index 0000000000..d9f99c7653
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260106165348_project_search_indices.sql
@@ -0,0 +1,8 @@
+-- Creates necessary project indices to improve the performance of name search
+
+-- Enable trigram extension for fuzzy text matching
+CREATE EXTENSION IF NOT EXISTS pg_trgm;
+
+-- GIN trigram index allows efficient partial string matching
+CREATE INDEX IF NOT EXISTS idx_project_name_trgm
+ ON "Project" USING gin (name gin_trgm_ops);
diff --git a/rust/cloud-storage/models_search/src/lib.rs b/rust/cloud-storage/models_search/src/lib.rs
index dca80980d9..c78ebfc2e1 100644
--- a/rust/cloud-storage/models_search/src/lib.rs
+++ b/rust/cloud-storage/models_search/src/lib.rs
@@ -18,17 +18,7 @@ pub use simple::*;
pub use timestamp::*;
#[derive(
- Serialize,
- Deserialize,
- Debug,
- ToSchema,
- Copy,
- Clone,
- EnumString,
- Display,
- PartialEq,
- JsonSchema,
- Default,
+ Serialize, Deserialize, Debug, ToSchema, Copy, Clone, EnumString, Display, JsonSchema, Default,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
diff --git a/rust/cloud-storage/name_search/.sqlx/query-33b53a9416b38ba5801627767061f440b4755192af39a0b38ab75482324e32c7.json b/rust/cloud-storage/name_search/.sqlx/query-33b53a9416b38ba5801627767061f440b4755192af39a0b38ab75482324e32c7.json
new file mode 100644
index 0000000000..9467ec9a25
--- /dev/null
+++ b/rust/cloud-storage/name_search/.sqlx/query-33b53a9416b38ba5801627767061f440b4755192af39a0b38ab75482324e32c7.json
@@ -0,0 +1,32 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n d.id as entity_id,\n d.name\n FROM \"Document\" d\n WHERE (d.owner = $1 OR d.id = ANY($2))\n AND d.\"deletedAt\" IS NULL\n AND d.name ILIKE $3\n ORDER BY d.\"updatedAt\" DESC\n LIMIT $4\n OFFSET $5\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "name",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "TextArray",
+ "Text",
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "33b53a9416b38ba5801627767061f440b4755192af39a0b38ab75482324e32c7"
+}
diff --git a/rust/cloud-storage/name_search/.sqlx/query-37557ab1a0fd8180269c401b89c5cc9ae1526f2b7126f21cee6c9ac17b5c51c3.json b/rust/cloud-storage/name_search/.sqlx/query-37557ab1a0fd8180269c401b89c5cc9ae1526f2b7126f21cee6c9ac17b5c51c3.json
new file mode 100644
index 0000000000..d64ce700e8
--- /dev/null
+++ b/rust/cloud-storage/name_search/.sqlx/query-37557ab1a0fd8180269c401b89c5cc9ae1526f2b7126f21cee6c9ac17b5c51c3.json
@@ -0,0 +1,32 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n p.id as entity_id,\n p.name\n FROM \"Project\" p\n WHERE (p.\"userId\" = $1 OR p.id = ANY($2))\n AND p.\"deletedAt\" IS NULL\n AND p.name ILIKE $3\n ORDER BY p.\"updatedAt\" DESC\n LIMIT $4\n OFFSET $5\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "name",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "TextArray",
+ "Text",
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "37557ab1a0fd8180269c401b89c5cc9ae1526f2b7126f21cee6c9ac17b5c51c3"
+}
diff --git a/rust/cloud-storage/name_search/.sqlx/query-3f0ed2175e561447f2ece9e875428a9052496b4e6b6d60e35e0b6e50b7d61a85.json b/rust/cloud-storage/name_search/.sqlx/query-3f0ed2175e561447f2ece9e875428a9052496b4e6b6d60e35e0b6e50b7d61a85.json
new file mode 100644
index 0000000000..854ea4b349
--- /dev/null
+++ b/rust/cloud-storage/name_search/.sqlx/query-3f0ed2175e561447f2ece9e875428a9052496b4e6b6d60e35e0b6e50b7d61a85.json
@@ -0,0 +1,31 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH oldest_messages AS (\n SELECT DISTINCT ON (thread_id)\n thread_id,\n subject\n FROM email_messages\n WHERE thread_id = ANY($1)\n ORDER BY thread_id, internal_date_ts ASC\n )\n SELECT\n t.id as entity_id,\n om.subject as \"name!\"\n FROM email_threads t\n INNER JOIN oldest_messages om ON om.thread_id = t.id\n WHERE om.subject ILIKE $2\n ORDER BY t.latest_non_spam_message_ts DESC\n LIMIT $3\n OFFSET $4\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "name!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "Text",
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ true
+ ]
+ },
+ "hash": "3f0ed2175e561447f2ece9e875428a9052496b4e6b6d60e35e0b6e50b7d61a85"
+}
diff --git a/rust/cloud-storage/name_search/.sqlx/query-4666b1f3cddd519e0a461257e9aa91c26eb255c7a4a2eaf9143f03c3a1600fce.json b/rust/cloud-storage/name_search/.sqlx/query-4666b1f3cddd519e0a461257e9aa91c26eb255c7a4a2eaf9143f03c3a1600fce.json
new file mode 100644
index 0000000000..970c0fb35e
--- /dev/null
+++ b/rust/cloud-storage/name_search/.sqlx/query-4666b1f3cddd519e0a461257e9aa91c26eb255c7a4a2eaf9143f03c3a1600fce.json
@@ -0,0 +1,32 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n c.id as entity_id,\n c.name\n FROM \"Chat\" c\n WHERE (c.\"userId\" = $1 OR c.id = ANY($2))\n AND c.\"deletedAt\" IS NULL\n AND c.name ILIKE $3\n ORDER BY c.\"updatedAt\" DESC\n LIMIT $4\n OFFSET $5\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "name",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "TextArray",
+ "Text",
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "4666b1f3cddd519e0a461257e9aa91c26eb255c7a4a2eaf9143f03c3a1600fce"
+}
diff --git a/rust/cloud-storage/name_search/.sqlx/query-9fea14ffa4f42968dc58e1da081ca87e317d7bf3e54708e3c1425c910b2640b5.json b/rust/cloud-storage/name_search/.sqlx/query-9fea14ffa4f42968dc58e1da081ca87e317d7bf3e54708e3c1425c910b2640b5.json
new file mode 100644
index 0000000000..a8e9bf6272
--- /dev/null
+++ b/rust/cloud-storage/name_search/.sqlx/query-9fea14ffa4f42968dc58e1da081ca87e317d7bf3e54708e3c1425c910b2640b5.json
@@ -0,0 +1,31 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n d.id as entity_id,\n d.name -- If there is a name match name obviously name exists\n FROM \"Document\" d\n WHERE d.id = ANY($1)\n AND d.\"deletedAt\" IS NULL\n AND d.name ILIKE $2\n ORDER BY d.\"updatedAt\" DESC\n LIMIT $3\n OFFSET $4\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "name",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray",
+ "Text",
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "9fea14ffa4f42968dc58e1da081ca87e317d7bf3e54708e3c1425c910b2640b5"
+}
diff --git a/rust/cloud-storage/name_search/.sqlx/query-a5773b5116e356b3c148e80c2fcb99799a074deeab9f9446359897536cfc772f.json b/rust/cloud-storage/name_search/.sqlx/query-a5773b5116e356b3c148e80c2fcb99799a074deeab9f9446359897536cfc772f.json
new file mode 100644
index 0000000000..431e732bac
--- /dev/null
+++ b/rust/cloud-storage/name_search/.sqlx/query-a5773b5116e356b3c148e80c2fcb99799a074deeab9f9446359897536cfc772f.json
@@ -0,0 +1,33 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH oldest_messages AS (\n SELECT DISTINCT ON (thread_id)\n thread_id,\n subject\n FROM email_messages\n WHERE link_id IN (\n SELECT id FROM email_links WHERE macro_id = $1\n )\n AND (thread_id = ANY($2) OR $3)\n ORDER BY thread_id, internal_date_ts ASC\n )\n SELECT\n t.id as entity_id,\n om.subject as \"name!\"\n FROM email_threads t\n INNER JOIN oldest_messages om ON om.thread_id = t.id\n WHERE t.link_id IN (\n SELECT id FROM email_links WHERE macro_id = $1\n )\n AND om.subject ILIKE $4\n ORDER BY t.latest_non_spam_message_ts DESC\n LIMIT $5\n OFFSET $6\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "name!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "UuidArray",
+ "Bool",
+ "Text",
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ true
+ ]
+ },
+ "hash": "a5773b5116e356b3c148e80c2fcb99799a074deeab9f9446359897536cfc772f"
+}
diff --git a/rust/cloud-storage/name_search/.sqlx/query-b6ffefe0291e41a22f8e4c383f26a37ce7478a83aed3110bd2b2999085ac3882.json b/rust/cloud-storage/name_search/.sqlx/query-b6ffefe0291e41a22f8e4c383f26a37ce7478a83aed3110bd2b2999085ac3882.json
new file mode 100644
index 0000000000..3c7558deec
--- /dev/null
+++ b/rust/cloud-storage/name_search/.sqlx/query-b6ffefe0291e41a22f8e4c383f26a37ce7478a83aed3110bd2b2999085ac3882.json
@@ -0,0 +1,31 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n c.id as entity_id,\n c.name\n FROM \"Chat\" c\n WHERE c.id = ANY($1)\n AND c.\"deletedAt\" IS NULL\n AND c.name ILIKE $2\n ORDER BY c.\"updatedAt\" DESC\n LIMIT $3\n OFFSET $4\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "name",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray",
+ "Text",
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "b6ffefe0291e41a22f8e4c383f26a37ce7478a83aed3110bd2b2999085ac3882"
+}
diff --git a/rust/cloud-storage/name_search/.sqlx/query-c9cb7e2eedc56971de5831b85df4ad182b902afb511bce1b5ea1c94d90632dee.json b/rust/cloud-storage/name_search/.sqlx/query-c9cb7e2eedc56971de5831b85df4ad182b902afb511bce1b5ea1c94d90632dee.json
new file mode 100644
index 0000000000..c5a7a422be
--- /dev/null
+++ b/rust/cloud-storage/name_search/.sqlx/query-c9cb7e2eedc56971de5831b85df4ad182b902afb511bce1b5ea1c94d90632dee.json
@@ -0,0 +1,31 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n p.id as entity_id,\n p.name\n FROM \"Project\" p\n WHERE p.id = ANY($1)\n AND p.\"deletedAt\" IS NULL\n AND p.name ILIKE $2\n ORDER BY p.\"updatedAt\" DESC\n LIMIT $3\n OFFSET $4\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "name",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray",
+ "Text",
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "c9cb7e2eedc56971de5831b85df4ad182b902afb511bce1b5ea1c94d90632dee"
+}
diff --git a/rust/cloud-storage/name_search/Cargo.toml b/rust/cloud-storage/name_search/Cargo.toml
new file mode 100644
index 0000000000..fd7c38735f
--- /dev/null
+++ b/rust/cloud-storage/name_search/Cargo.toml
@@ -0,0 +1,20 @@
+[package]
+edition = "2024"
+name = "name_search"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+anyhow = { workspace = true }
+macro_user_id = { path = "../macro_user_id" }
+models_opensearch = { path = "../models_opensearch" }
+non_empty = { path = "../non_empty" }
+serde = { workspace = true }
+sqlx = { workspace = true }
+thiserror = { workspace = true }
+tracing = { workspace = true }
+uuid = { workspace = true }
+
+[dev-dependencies]
+macro_db_migrator = { path = "../macro_db_migrator" }
+tokio = { workspace = true }
diff --git a/rust/cloud-storage/name_search/fixtures/chat.sql b/rust/cloud-storage/name_search/fixtures/chat.sql
new file mode 100644
index 0000000000..361a7945fd
--- /dev/null
+++ b/rust/cloud-storage/name_search/fixtures/chat.sql
@@ -0,0 +1,36 @@
+-- Test users
+INSERT INTO "User" (id, email, name)
+VALUES
+ ('macro|[email protected]', '[email protected]', 'Test User 1'),
+ ('macro|[email protected]', '[email protected]', 'Test User 2'),
+ ('macro|[email protected]', '[email protected]', 'Test User 3');
+
+-- Test chats for user1 (userId)
+INSERT INTO "Chat" (id, name, "userId", "createdAt", "updatedAt", "deletedAt", model, "isPersistent")
+VALUES
+ -- Chats matching "project"
+ ('11111111-1111-1111-1111-111111111111', 'Project Planning Chat', 'macro|[email protected]', '2024-01-01 10:00:00', '2024-12-01 10:00:00', NULL, 'gpt-4o', true),
+ ('22222222-2222-2222-2222-222222222222', 'Project Review Chat', 'macro|[email protected]', '2024-02-01 10:00:00', '2024-12-02 10:00:00', NULL, 'gpt-4o', true),
+
+ -- Chats matching "meeting"
+ ('33333333-3333-3333-3333-333333333333', 'Team Meeting Chat', 'macro|[email protected]', '2024-03-01 10:00:00', '2024-12-03 10:00:00', NULL, 'gpt-4o', true),
+ ('44444444-4444-4444-4444-444444444444', 'Client Meeting', 'macro|[email protected]', '2024-04-01 10:00:00', '2024-12-04 10:00:00', NULL, 'gpt-4o', true),
+
+ -- Chats not matching common search terms
+ ('55555555-5555-5555-5555-555555555555', 'Budget Discussion', 'macro|[email protected]', '2024-05-01 10:00:00', '2024-12-05 10:00:00', NULL, 'gpt-4o', true),
+
+ -- Test case sensitivity (should match "PROJECT" search)
+ ('66666666-6666-6666-6666-666666666666', 'IMPORTANT PROJECT', 'macro|[email protected]', '2024-06-01 10:00:00', '2024-12-06 10:00:00', NULL, 'gpt-4o', true),
+
+ -- Soft deleted chat (should be excluded from search results)
+ ('77777777-7777-7777-7777-777777777777', 'Deleted Project Chat', 'macro|[email protected]', '2024-07-01 10:00:00', '2024-12-07 10:00:00', '2024-12-08 10:00:00', 'gpt-4o', true);
+
+-- Test chats for user2 (not accessible to user1 unless shared)
+INSERT INTO "Chat" (id, name, "userId", "createdAt", "updatedAt", "deletedAt", model, "isPersistent")
+VALUES
+ ('88888888-8888-8888-8888-888888888888', 'User2 Project Chat', 'macro|[email protected]', '2024-08-01 10:00:00', '2024-12-09 10:00:00', NULL, 'gpt-4o', true);
+
+-- Test chats for user3 (used for sharing tests)
+INSERT INTO "Chat" (id, name, "userId", "createdAt", "updatedAt", "deletedAt", model, "isPersistent")
+VALUES
+ ('99999999-9999-9999-9999-999999999999', 'User3 Shared Project', 'macro|[email protected]', '2024-09-01 10:00:00', '2024-12-10 10:00:00', NULL, 'gpt-4o', true);
diff --git a/rust/cloud-storage/name_search/fixtures/document.sql b/rust/cloud-storage/name_search/fixtures/document.sql
new file mode 100644
index 0000000000..14504140b8
--- /dev/null
+++ b/rust/cloud-storage/name_search/fixtures/document.sql
@@ -0,0 +1,36 @@
+-- Test users
+INSERT INTO "User" (id, email, name)
+VALUES
+ ('macro|[email protected]', '[email protected]', 'Test User 1'),
+ ('macro|[email protected]', '[email protected]', 'Test User 2'),
+ ('macro|[email protected]', '[email protected]', 'Test User 3');
+
+-- Test documents for user1 (owner)
+INSERT INTO "Document" (id, name, owner, "fileType", "createdAt", "updatedAt", uploaded)
+VALUES
+ -- Documents matching "report"
+ ('11111111-1111-1111-1111-111111111111', 'Quarterly Report 2024', 'macro|[email protected]', 'pdf', '2024-01-01 10:00:00', '2024-12-01 10:00:00', true),
+ ('22222222-2222-2222-2222-222222222222', 'Sales Report December', 'macro|[email protected]', 'docx', '2024-02-01 10:00:00', '2024-12-02 10:00:00', true),
+ ('33333333-3333-3333-3333-333333333333', 'Financial Report Q3', 'macro|[email protected]', 'xlsx', '2024-03-01 10:00:00', '2024-12-03 10:00:00', true),
+
+ -- Documents matching "meeting"
+ ('44444444-4444-4444-4444-444444444444', 'Team Meeting Notes', 'macro|[email protected]', 'txt', '2024-04-01 10:00:00', '2024-12-04 10:00:00', true),
+ ('55555555-5555-5555-5555-555555555555', 'Client Meeting Agenda', 'macro|[email protected]', 'pdf', '2024-05-01 10:00:00', '2024-12-05 10:00:00', true),
+
+ -- Documents not matching common search terms
+ ('66666666-6666-6666-6666-666666666666', 'Budget Analysis', 'macro|[email protected]', 'xlsx', '2024-06-01 10:00:00', '2024-12-06 10:00:00', true),
+ ('77777777-7777-7777-7777-777777777777', 'Project Proposal', 'macro|[email protected]', 'docx', '2024-07-01 10:00:00', '2024-12-07 10:00:00', true),
+
+ -- Test case sensitivity (should match "REPORT" search)
+ ('88888888-8888-8888-8888-888888888888', 'ANNUAL REPORT 2024', 'macro|[email protected]', 'pdf', '2024-08-01 10:00:00', '2024-12-08 10:00:00', true);
+
+-- Test documents for user2 (not accessible to user1 unless shared)
+INSERT INTO "Document" (id, name, owner, "fileType", "createdAt", "updatedAt", uploaded)
+VALUES
+ ('99999999-9999-9999-9999-999999999999', 'User2 Report Private', 'macro|[email protected]', 'pdf', '2024-09-01 10:00:00', '2024-12-09 10:00:00', true),
+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'User2 Meeting Notes', 'macro|[email protected]', 'txt', '2024-10-01 10:00:00', '2024-12-10 10:00:00', true);
+
+-- Test documents for user3
+INSERT INTO "Document" (id, name, owner, "fileType", "createdAt", "updatedAt", uploaded)
+VALUES
+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'User3 Report Shared', 'macro|[email protected]', 'pdf', '2024-11-01 10:00:00', '2024-12-11 10:00:00', true);
diff --git a/rust/cloud-storage/name_search/fixtures/email.sql b/rust/cloud-storage/name_search/fixtures/email.sql
new file mode 100644
index 0000000000..22d846c2a5
--- /dev/null
+++ b/rust/cloud-storage/name_search/fixtures/email.sql
@@ -0,0 +1,124 @@
+-- Test users
+INSERT INTO "User" (id, email, name)
+VALUES
+ ('macro|[email protected]', '[email protected]', 'Test User 1'),
+ ('macro|[email protected]', '[email protected]', 'Test User 2'),
+ ('macro|[email protected]', '[email protected]', 'Test User 3');
+
+-- Email links (email account connections for each user)
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES
+ ('00000000-0000-0001-0000-000000000001', 'macro|[email protected]', 'fa_user1', '[email protected]', 'GMAIL', true, '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),
+ ('00000000-0000-0002-0000-000000000002', 'macro|[email protected]', 'fa_user2', '[email protected]', 'GMAIL', true, '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),
+ ('00000000-0000-0003-0000-000000000003', 'macro|[email protected]', 'fa_user3', '[email protected]', 'GMAIL', true, '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00');
+
+-- Email contacts (senders/recipients)
+INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)
+VALUES
+ -- Contacts for user1's link
+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '00000000-0000-0001-0000-000000000001', '[email protected]', 'Sender One', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),
+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '00000000-0000-0001-0000-000000000001', '[email protected]', 'Sender Two', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),
+
+ -- Contacts for user2's link
+ ('cccccccc-cccc-cccc-cccc-cccccccccccc', '00000000-0000-0002-0000-000000000002', '[email protected]', 'Sender Three', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),
+
+ -- Contacts for user3's link
+ ('dddddddd-dddd-dddd-dddd-dddddddddddd', '00000000-0000-0003-0000-000000000003', '[email protected]', 'Sender Four', '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00');
+
+-- Email threads for user1
+-- Threads matching "invoice" (3 threads)
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, latest_non_spam_message_ts, created_at, updated_at)
+VALUES
+ -- Thread 1: Invoice from Q1 2024 (oldest invoice, latest_non_spam_message_ts: 2024-12-01)
+ ('11111111-1111-1111-1111-111111111111', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-01 10:00:00+00', '2024-01-01 10:00:00+00', '2024-12-01 10:00:00+00'),
+
+ -- Thread 2: Monthly Invoice - December (multiple messages, latest_non_spam_message_ts: 2024-12-02)
+ ('22222222-2222-2222-2222-222222222222', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-02 10:00:00+00', '2024-02-01 10:00:00+00', '2024-12-02 10:00:00+00'),
+
+ -- Thread 3: IMPORTANT: INVOICE DUE (uppercase, latest_non_spam_message_ts: 2024-12-06)
+ ('66666666-6666-6666-6666-666666666666', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-06 10:00:00+00', '2024-06-01 10:00:00+00', '2024-12-06 10:00:00+00');
+
+-- Threads matching "meet" (2 threads)
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, latest_non_spam_message_ts, created_at, updated_at)
+VALUES
+ -- Thread 4: Team Meeting Notes (latest_non_spam_message_ts: 2024-12-03)
+ ('33333333-3333-3333-3333-333333333333', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-03 10:00:00+00', '2024-03-01 10:00:00+00', '2024-12-03 10:00:00+00'),
+
+ -- Thread 5: Fwd: Client Meeting Tomorrow (latest_non_spam_message_ts: 2024-12-04)
+ ('44444444-4444-4444-4444-444444444444', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-04 10:00:00+00', '2024-04-01 10:00:00+00', '2024-12-04 10:00:00+00');
+
+-- Other threads for user1 (for various test scenarios)
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, latest_non_spam_message_ts, created_at, updated_at)
+VALUES
+ -- Thread 6: Weekly Update (no match, latest_non_spam_message_ts: 2024-12-05)
+ ('55555555-5555-5555-5555-555555555555', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-05 10:00:00+00', '2024-05-01 10:00:00+00', '2024-12-05 10:00:00+00'),
+
+ -- Thread 7: Project Status (no match, latest_non_spam_message_ts: 2024-12-07)
+ ('77777777-7777-7777-7777-777777777777', '00000000-0000-0001-0000-000000000001', true, false, '2024-12-07 10:00:00+00', '2024-07-01 10:00:00+00', '2024-12-07 10:00:00+00');
+
+-- Email threads for user2 (for isolation testing)
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, latest_non_spam_message_ts, created_at, updated_at)
+VALUES
+ ('88888888-8888-8888-8888-888888888888', '00000000-0000-0002-0000-000000000002', true, false, '2024-12-08 10:00:00+00', '2024-08-01 10:00:00+00', '2024-12-08 10:00:00+00');
+
+-- Email threads for user3 (for shared thread testing)
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, latest_non_spam_message_ts, created_at, updated_at)
+VALUES
+ ('99999999-9999-9999-9999-999999999999', '00000000-0000-0003-0000-000000000003', true, false, '2024-12-09 10:00:00+00', '2024-09-01 10:00:00+00', '2024-12-09 10:00:00+00');
+
+-- Email messages for user1's threads
+-- Thread 11111111: Invoice from Q1 2024 (multiple messages, oldest has the search subject)
+INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)
+VALUES
+ -- Oldest message (this is what gets searched)
+ ('10000000-0001-0000-0000-000000000001', '11111111-1111-1111-1111-111111111111', '00000000-0000-0001-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Invoice from Q1 2024', '2024-01-01 10:00:00+00', false, false, '2024-01-01 10:00:00+00', '2024-01-01 10:00:00+00'),
+
+ -- Newer reply (should not be used for search)
+ ('10000000-0001-0000-0000-000000000002', '11111111-1111-1111-1111-111111111111', '00000000-0000-0001-0000-000000000001', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Re: Invoice from Q1 2024', '2024-12-01 10:00:00+00', false, true, '2024-12-01 10:00:00+00', '2024-12-01 10:00:00+00');
+
+-- Thread 22222222: Monthly Invoice - December (3 messages to test oldest message logic)
+INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)
+VALUES
+ -- Oldest message with "Monthly Invoice" (this is what gets searched)
+ ('10000000-0002-0000-0000-000000000001', '22222222-2222-2222-2222-222222222222', '00000000-0000-0001-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Re: Monthly Invoice - December', '2024-02-01 10:00:00+00', false, false, '2024-02-01 10:00:00+00', '2024-02-01 10:00:00+00'),
+
+ -- Middle message (should not be used for search)
+ ('10000000-0002-0000-0000-000000000002', '22222222-2222-2222-2222-222222222222', '00000000-0000-0001-0000-000000000001', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Re: Re: Monthly Invoice - December', '2024-02-02 10:00:00+00', false, true, '2024-02-02 10:00:00+00', '2024-02-02 10:00:00+00'),
+
+ -- Newest message with different subject (should not be used for search)
+ ('10000000-0002-0000-0000-000000000003', '22222222-2222-2222-2222-222222222222', '00000000-0000-0001-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Re: Re: Re: Payment Processed', '2024-12-02 10:00:00+00', false, false, '2024-12-02 10:00:00+00', '2024-12-02 10:00:00+00');
+
+-- Thread 33333333: Team Meeting Notes
+INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)
+VALUES
+ ('10000000-0003-0000-0000-000000000001', '33333333-3333-3333-3333-333333333333', '00000000-0000-0001-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Team Meeting Notes', '2024-03-01 10:00:00+00', false, false, '2024-03-01 10:00:00+00', '2024-03-01 10:00:00+00');
+
+-- Thread 44444444: Fwd: Client Meeting Tomorrow
+INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)
+VALUES
+ ('10000000-0004-0000-0000-000000000001', '44444444-4444-4444-4444-444444444444', '00000000-0000-0001-0000-000000000001', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Fwd: Client Meeting Tomorrow', '2024-04-01 10:00:00+00', false, false, '2024-04-01 10:00:00+00', '2024-04-01 10:00:00+00');
+
+-- Thread 55555555: Weekly Update
+INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)
+VALUES
+ ('10000000-0005-0000-0000-000000000001', '55555555-5555-5555-5555-555555555555', '00000000-0000-0001-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Weekly Update - January 2024', '2024-05-01 10:00:00+00', false, false, '2024-05-01 10:00:00+00', '2024-05-01 10:00:00+00');
+
+-- Thread 66666666: IMPORTANT: INVOICE DUE (uppercase invoice)
+INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)
+VALUES
+ ('10000000-0006-0000-0000-000000000001', '66666666-6666-6666-6666-666666666666', '00000000-0000-0001-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'IMPORTANT: INVOICE DUE', '2024-06-01 10:00:00+00', false, false, '2024-06-01 10:00:00+00', '2024-06-01 10:00:00+00');
+
+-- Thread 77777777: Project Status
+INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)
+VALUES
+ ('10000000-0007-0000-0000-000000000001', '77777777-7777-7777-7777-777777777777', '00000000-0000-0001-0000-000000000001', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Project Status Report', '2024-07-01 10:00:00+00', false, false, '2024-07-01 10:00:00+00', '2024-07-01 10:00:00+00');
+
+-- Email messages for user2's threads (for isolation testing)
+INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)
+VALUES
+ ('10000000-0008-0000-0000-000000000001', '88888888-8888-8888-8888-888888888888', '00000000-0000-0002-0000-000000000002', 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'User2 Private Email', '2024-08-01 10:00:00+00', false, false, '2024-08-01 10:00:00+00', '2024-08-01 10:00:00+00');
+
+-- Email messages for user3's threads (for shared thread testing)
+INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, subject, internal_date_ts, is_read, is_sent, created_at, updated_at)
+VALUES
+ ('10000000-0009-0000-0000-000000000001', '99999999-9999-9999-9999-999999999999', '00000000-0000-0003-0000-000000000003', 'dddddddd-dddd-dddd-dddd-dddddddddddd', 'User3 Invoice Shared', '2024-09-01 10:00:00+00', false, false, '2024-09-01 10:00:00+00', '2024-09-01 10:00:00+00');
diff --git a/rust/cloud-storage/name_search/fixtures/project.sql b/rust/cloud-storage/name_search/fixtures/project.sql
new file mode 100644
index 0000000000..5d69d35831
--- /dev/null
+++ b/rust/cloud-storage/name_search/fixtures/project.sql
@@ -0,0 +1,36 @@
+-- Test users
+INSERT INTO "User" (id, email, name)
+VALUES
+ ('macro|[email protected]', '[email protected]', 'Test User 1'),
+ ('macro|[email protected]', '[email protected]', 'Test User 2'),
+ ('macro|[email protected]', '[email protected]', 'Test User 3');
+
+-- Test projects for user1 (userId)
+INSERT INTO "Project" (id, name, "userId", "createdAt", "updatedAt", "deletedAt")
+VALUES
+ -- Projects matching "mobile"
+ ('11111111-1111-1111-1111-111111111111', 'Mobile Development', 'macro|[email protected]', '2024-01-01 10:00:00', '2024-12-01 10:00:00', NULL),
+ ('22222222-2222-2222-2222-222222222222', 'Mobile App Redesign', 'macro|[email protected]', '2024-02-01 10:00:00', '2024-12-02 10:00:00', NULL),
+
+ -- Projects matching "web"
+ ('33333333-3333-3333-3333-333333333333', 'Web Platform Upgrade', 'macro|[email protected]', '2024-03-01 10:00:00', '2024-12-03 10:00:00', NULL),
+ ('44444444-4444-4444-4444-444444444444', 'Website Optimization', 'macro|[email protected]', '2024-04-01 10:00:00', '2024-12-04 10:00:00', NULL),
+
+ -- Projects not matching common search terms
+ ('55555555-5555-5555-5555-555555555555', 'Marketing Campaign', 'macro|[email protected]', '2024-05-01 10:00:00', '2024-12-05 10:00:00', NULL),
+
+ -- Test case sensitivity (should match "MOBILE" search)
+ ('66666666-6666-6666-6666-666666666666', 'MOBILE PLATFORM', 'macro|[email protected]', '2024-06-01 10:00:00', '2024-12-06 10:00:00', NULL),
+
+ -- Soft deleted project (should be excluded from search results)
+ ('77777777-7777-7777-7777-777777777777', 'Deleted Mobile Project', 'macro|[email protected]', '2024-07-01 10:00:00', '2024-12-07 10:00:00', '2024-12-08 10:00:00');
+
+-- Test projects for user2 (not accessible to user1 unless shared)
+INSERT INTO "Project" (id, name, "userId", "createdAt", "updatedAt", "deletedAt")
+VALUES
+ ('88888888-8888-8888-8888-888888888888', 'User2 Mobile Project', 'macro|[email protected]', '2024-08-01 10:00:00', '2024-12-09 10:00:00', NULL);
+
+-- Test projects for user3 (used for sharing tests)
+INSERT INTO "Project" (id, name, "userId", "createdAt", "updatedAt", "deletedAt")
+VALUES
+ ('99999999-9999-9999-9999-999999999999', 'User3 Shared Mobile', 'macro|[email protected]', '2024-09-01 10:00:00', '2024-12-10 10:00:00', NULL);
diff --git a/rust/cloud-storage/name_search/justfile b/rust/cloud-storage/name_search/justfile
new file mode 100644
index 0000000000..380509e6a1
--- /dev/null
+++ b/rust/cloud-storage/name_search/justfile
@@ -0,0 +1,28 @@
+DATABASE_URL := "postgres://user:password@localhost:5432/macrodb"
+
+mod sqlx '../sqlx.just'
+
+prepare_db:
+ just sqlx::prepare_db {{ DATABASE_URL }}
+
+export RUSTFLAGS := "-Dwarnings"
+export RUSTDOCFLAGS := "-Dwarnings"
+export CARGO_TERM_COLOR := "always"
+
+clippy:
+ cargo clippy
+
+clippy-fix:
+ cargo clippy --fix
+
+fmt-check:
+ cargo fmt --check
+
+fmt:
+ cargo fmt
+
+check:
+ cargo check
+
+test:
+ cargo test
diff --git a/rust/cloud-storage/name_search/src/chat.rs b/rust/cloud-storage/name_search/src/chat.rs
new file mode 100644
index 0000000000..295c6c6b6d
--- /dev/null
+++ b/rust/cloud-storage/name_search/src/chat.rs
@@ -0,0 +1,126 @@
+//! This module contains logic for searching chats by name
+
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use sqlx::{Pool, Postgres};
+use uuid::Uuid;
+
+use crate::{NameSearchError, NameSearchResult, SearchEntityType};
+
+/// Searches chats by IDs only
+async fn ids_search(
+ db: &Pool<Postgres>,
+ chat_ids: &[Uuid],
+ search_pattern: String,
+ limit: u32,
+ offset: u32,
+) -> Result<Vec<NameSearchResult>, NameSearchError> {
+ if chat_ids.is_empty() {
+ return Err(NameSearchError::EmptyIdsWithIdsOnly);
+ }
+
+ let rows = sqlx::query!(
+ r#"
+ SELECT
+ c.id as entity_id,
+ c.name
+ FROM "Chat" c
+ WHERE c.id = ANY($1)
+ AND c."deletedAt" IS NULL
+ AND c.name ILIKE $2
+ ORDER BY c."updatedAt" DESC
+ LIMIT $3
+ OFFSET $4
+ "#,
+ &chat_ids
+ .iter()
+ .map(|id| id.to_string())
+ .collect::<Vec<String>>(),
+ search_pattern,
+ limit as i64,
+ offset as i64,
+ )
+ .fetch_all(db)
+ .await
+ .map_err(NameSearchError::DatabaseError)?;
+
+ Ok(rows
+ .into_iter()
+ .map(|row| NameSearchResult {
+ entity_id: row.entity_id.parse().unwrap(),
+ entity_type: SearchEntityType::Chats,
+ name: row.name,
+ })
+ .collect())
+}
+
+/// Searches chats by owner or IDs
+async fn owner_search<'a>(
+ db: &Pool<Postgres>,
+ macro_user_id: &MacroUserId<Lowercase<'a>>,
+ chat_ids: &[Uuid],
+ search_pattern: String,
+ limit: u32,
+ offset: u32,
+) -> Result<Vec<NameSearchResult>, NameSearchError> {
+ let rows = sqlx::query!(
+ r#"
+ SELECT
+ c.id as entity_id,
+ c.name
+ FROM "Chat" c
+ WHERE (c."userId" = $1 OR c.id = ANY($2))
+ AND c."deletedAt" IS NULL
+ AND c.name ILIKE $3
+ ORDER BY c."updatedAt" DESC
+ LIMIT $4
+ OFFSET $5
+ "#,
+ macro_user_id.as_ref(),
+ &chat_ids
+ .iter()
+ .map(|id| id.to_string())
+ .collect::<Vec<String>>(),
+ search_pattern,
+ limit as i64,
+ offset as i64,
+ )
+ .fetch_all(db)
+ .await
+ .map_err(NameSearchError::DatabaseError)?;
+
+ Ok(rows
+ .into_iter()
+ .map(|row| NameSearchResult {
+ entity_id: row.entity_id.parse().unwrap(),
+ entity_type: SearchEntityType::Chats,
+ name: row.name,
+ })
+ .collect())
+}
+
+/// Searches over the user's chats by name
+#[tracing::instrument(skip(db), err)]
+pub async fn search_chat_names<'a>(
+ db: &Pool<Postgres>,
+ macro_user_id: &MacroUserId<Lowercase<'a>>,
+ chat_ids: &[Uuid],
+ term: String,
+ ids_only: bool,
+ limit: u32,
+ offset: u32,
+) -> Result<Vec<NameSearchResult>, NameSearchError> {
+ if term.is_empty() {
+ return Err(NameSearchError::EmptySearchTerm);
+ }
+
+ let search_pattern = format!("%{term}%");
+
+ if ids_only {
+ ids_search(db, chat_ids, search_pattern, limit, offset).await
+ } else {
+ owner_search(db, macro_user_id, chat_ids, search_pattern, limit, offset).await
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/name_search/src/chat/test.rs b/rust/cloud-storage/name_search/src/chat/test.rs
new file mode 100644
index 0000000000..c803bf30d5
--- /dev/null
+++ b/rust/cloud-storage/name_search/src/chat/test.rs
@@ -0,0 +1,353 @@
+//! Tests for chat module
+
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::{Pool, Postgres};
+use uuid::Uuid;
+
+use super::*;
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("chat"))
+)]
+async fn test_search_chat_names_empty_term(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ let result = search_chat_names(&pool, &user_id, &[], "".to_string(), false, 10, 0).await;
+
+ assert!(result.is_err());
+ assert!(matches!(
+ result.unwrap_err(),
+ NameSearchError::EmptySearchTerm
+ ));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("chat"))
+)]
+async fn test_search_chat_names_ids_only_with_empty_ids(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ let result = search_chat_names(&pool, &user_id, &[], "project".to_string(), true, 10, 0).await;
+
+ assert!(result.is_err());
+ assert!(matches!(
+ result.unwrap_err(),
+ NameSearchError::EmptyIdsWithIdsOnly
+ ));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("chat"))
+)]
+async fn test_search_chat_names_ids_only_mode(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for "project" within specific chat IDs
+ let chat_ids = vec![
+ Uuid::parse_str("11111111-1111-1111-1111-111111111111")?,
+ Uuid::parse_str("22222222-2222-2222-2222-222222222222")?,
+ Uuid::parse_str("55555555-5555-5555-5555-555555555555")?, // Budget Discussion - won't match
+ ];
+
+ let results = search_chat_names(
+ &pool,
+ &user_id,
+ &chat_ids,
+ "project".to_string(),
+ true,
+ 10,
+ 0,
+ )
+ .await?;
+
+ // Should only return the 2 chats that match "project" from the provided IDs
+ assert_eq!(results.len(), 2);
+
+ // Verify results contain expected chats (ordered by updatedAt DESC)
+ assert_eq!(
+ results[0].entity_id.to_string(),
+ "22222222-2222-2222-2222-222222222222"
+ );
+ assert_eq!(results[0].entity_type, SearchEntityType::Chats);
+ assert_eq!(results[0].name, "Project Review Chat");
+
+ assert_eq!(
+ results[1].entity_id.to_string(),
+ "11111111-1111-1111-1111-111111111111"
+ );
+ assert_eq!(results[1].name, "Project Planning Chat");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("chat"))
+)]
+async fn test_search_chat_names_normal_mode_owned_chats(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for "project" across all user1's owned chats
+ let results =
+ search_chat_names(&pool, &user_id, &[], "project".to_string(), false, 10, 0).await?;
+
+ // Should return 3 chats matching "project" (2 lowercase + 1 uppercase)
+ assert_eq!(results.len(), 3);
+
+ // Verify ordering by updatedAt DESC
+ assert_eq!(
+ results[0].entity_id.to_string(),
+ "66666666-6666-6666-6666-666666666666"
+ );
+ assert_eq!(results[0].name, "IMPORTANT PROJECT");
+
+ assert_eq!(
+ results[1].entity_id.to_string(),
+ "22222222-2222-2222-2222-222222222222"
+ );
+ assert_eq!(results[1].name, "Project Review Chat");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("chat"))
+)]
+async fn test_search_chat_names_case_insensitive(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search with uppercase term should match both lowercase and uppercase names
+ let results =
+ search_chat_names(&pool, &user_id, &[], "PROJECT".to_string(), false, 10, 0).await?;
+
+ assert_eq!(results.len(), 3);
+
+ // Search with lowercase term should also match both
+ let results =
+ search_chat_names(&pool, &user_id, &[], "project".to_string(), false, 10, 0).await?;
+
+ assert_eq!(results.len(), 3);
+
+ // Search with mixed case
+ let results =
+ search_chat_names(&pool, &user_id, &[], "PrOjEcT".to_string(), false, 10, 0).await?;
+
+ assert_eq!(results.len(), 3);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("chat"))
+)]
+async fn test_search_chat_names_with_shared_chats(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Include a chat from user3 (shared via chat_ids parameter)
+ let shared_chat_ids = vec![Uuid::parse_str("99999999-9999-9999-9999-999999999999")?];
+
+ let results = search_chat_names(
+ &pool,
+ &user_id,
+ &shared_chat_ids,
+ "project".to_string(),
+ false,
+ 10,
+ 0,
+ )
+ .await?;
+
+ // Should return user1's 3 "project" chats + user3's 1 "project" chat
+ assert_eq!(results.len(), 4);
+
+ // Verify user3's chat is included
+ let user3_chat = results.iter().find(|r| {
+ r.entity_id
+ .to_string()
+ .eq("99999999-9999-9999-9999-999999999999")
+ });
+ assert!(user3_chat.is_some());
+ assert_eq!(user3_chat.unwrap().name, "User3 Shared Project");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("chat"))
+)]
+async fn test_search_chat_names_pagination_limit(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search with limit of 2
+ let results =
+ search_chat_names(&pool, &user_id, &[], "project".to_string(), false, 2, 0).await?;
+
+ assert_eq!(results.len(), 2);
+
+ // Should get the 2 most recently updated chats with "project"
+ assert_eq!(
+ results[0].entity_id.to_string(),
+ "66666666-6666-6666-6666-666666666666"
+ );
+ assert_eq!(
+ results[1].entity_id.to_string(),
+ "22222222-2222-2222-2222-222222222222"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("chat"))
+)]
+async fn test_search_chat_names_pagination_offset(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search with offset of 2
+ let results =
+ search_chat_names(&pool, &user_id, &[], "project".to_string(), false, 10, 2).await?;
+
+ assert_eq!(results.len(), 1);
+
+ // Should skip the first 2 and get the next 1
+ assert_eq!(
+ results[0].entity_id.to_string(),
+ "11111111-1111-1111-1111-111111111111"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("chat"))
+)]
+async fn test_search_chat_names_no_results(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for a term that doesn't match any chats
+ let results = search_chat_names(
+ &pool,
+ &user_id,
+ &[],
+ "nonexistent".to_string(),
+ false,
+ 10,
+ 0,
+ )
+ .await?;
+
+ assert_eq!(results.len(), 0);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("chat"))
+)]
+async fn test_search_chat_names_partial_match(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for partial term "meet" should match "meeting"
+ let results = search_chat_names(&pool, &user_id, &[], "meet".to_string(), false, 10, 0).await?;
+
+ assert_eq!(results.len(), 2);
+ assert_eq!(
+ results[0].entity_id.to_string(),
+ "44444444-4444-4444-4444-444444444444"
+ );
+ assert_eq!(results[0].name, "Client Meeting");
+
+ assert_eq!(
+ results[1].entity_id.to_string(),
+ "33333333-3333-3333-3333-333333333333"
+ );
+ assert_eq!(results[1].name, "Team Meeting Chat");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("chat"))
+)]
+async fn test_search_chat_names_user_isolation(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for "User2" - user1 should not see user2's private chats
+ let results =
+ search_chat_names(&pool, &user_id, &[], "User2".to_string(), false, 10, 0).await?;
+
+ // Should return 0 results (user2's chats are not owned by user1 and not shared)
+ assert_eq!(results.len(), 0);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("chat"))
+)]
+async fn test_search_chat_names_excludes_soft_deleted(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for "project" - should NOT include soft-deleted chat
+ let results =
+ search_chat_names(&pool, &user_id, &[], "project".to_string(), false, 10, 0).await?;
+
+ // Should NOT include the deleted chat (id: 77777777-7777-7777-7777-777777777777)
+ assert!(!results.iter().any(|r| {
+ r.entity_id
+ .to_string()
+ .eq("77777777-7777-7777-7777-777777777777")
+ }));
+
+ // Should include non-deleted chats
+ assert!(results.iter().any(|r| {
+ r.entity_id
+ .to_string()
+ .eq("11111111-1111-1111-1111-111111111111")
+ }));
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/name_search/src/document.rs b/rust/cloud-storage/name_search/src/document.rs
new file mode 100644
index 0000000000..b9f52ffed3
--- /dev/null
+++ b/rust/cloud-storage/name_search/src/document.rs
@@ -0,0 +1,134 @@
+//! This module contains logic for searching documents by name
+
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use sqlx::{Pool, Postgres};
+use uuid::Uuid;
+
+use crate::{NameSearchError, NameSearchResult, SearchEntityType};
+
+/// Searches documents by IDs only
+async fn ids_search(
+ db: &Pool<Postgres>,
+ document_ids: &[Uuid],
+ search_pattern: String,
+ limit: u32,
+ offset: u32,
+) -> Result<Vec<NameSearchResult>, NameSearchError> {
+ if document_ids.is_empty() {
+ return Err(NameSearchError::EmptyIdsWithIdsOnly);
+ }
+
+ let rows = sqlx::query!(
+ r#"
+ SELECT
+ d.id as entity_id,
+ d.name -- If there is a name match name obviously name exists
+ FROM "Document" d
+ WHERE d.id = ANY($1)
+ AND d."deletedAt" IS NULL
+ AND d.name ILIKE $2
+ ORDER BY d."updatedAt" DESC
+ LIMIT $3
+ OFFSET $4
+ "#,
+ &document_ids
+ .iter()
+ .map(|d| d.to_string())
+ .collect::<Vec<String>>(),
+ search_pattern,
+ limit as i64,
+ offset as i64,
+ )
+ .fetch_all(db)
+ .await
+ .map_err(NameSearchError::DatabaseError)?;
+
+ Ok(rows
+ .into_iter()
+ .map(|row| NameSearchResult {
+ entity_id: row.entity_id.parse().unwrap(),
+ entity_type: SearchEntityType::Documents,
+ name: row.name,
+ })
+ .collect())
+}
+
+/// Searches documents by owner or IDs
+async fn owner_search<'a>(
+ db: &Pool<Postgres>,
+ macro_user_id: &MacroUserId<Lowercase<'a>>,
+ document_ids: &[Uuid],
+ search_pattern: String,
+ limit: u32,
+ offset: u32,
+) -> Result<Vec<NameSearchResult>, NameSearchError> {
+ let rows = sqlx::query!(
+ r#"
+ SELECT
+ d.id as entity_id,
+ d.name
+ FROM "Document" d
+ WHERE (d.owner = $1 OR d.id = ANY($2))
+ AND d."deletedAt" IS NULL
+ AND d.name ILIKE $3
+ ORDER BY d."updatedAt" DESC
+ LIMIT $4
+ OFFSET $5
+ "#,
+ macro_user_id.as_ref(),
+ &document_ids
+ .iter()
+ .map(|d| d.to_string())
+ .collect::<Vec<String>>(),
+ search_pattern,
+ limit as i64,
+ offset as i64,
+ )
+ .fetch_all(db)
+ .await
+ .map_err(NameSearchError::DatabaseError)?;
+
+ Ok(rows
+ .into_iter()
+ .map(|row| NameSearchResult {
+ entity_id: row.entity_id.parse().unwrap(),
+ entity_type: SearchEntityType::Documents,
+ name: row.name,
+ })
+ .collect())
+}
+
+/// Searches over the users documents by name
+#[tracing::instrument(skip(db), err)]
+pub async fn search_document_names<'a>(
+ db: &Pool<Postgres>,
+ macro_user_id: &MacroUserId<Lowercase<'a>>,
+ document_ids: &[Uuid],
+ term: String,
+ ids_only: bool,
+ limit: u32,
+ offset: u32,
+) -> Result<Vec<NameSearchResult>, NameSearchError> {
+ if term.is_empty() {
+ return Err(NameSearchError::EmptySearchTerm);
+ }
+
+ let search_pattern = format!("%{term}%");
+
+ if ids_only {
+ ids_search(db, document_ids, search_pattern, limit, offset).await
+ } else {
+ owner_search(
+ db,
+ macro_user_id,
+ document_ids,
+ search_pattern,
+ limit,
+ offset,
+ )
+ .await
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/name_search/src/document/test.rs b/rust/cloud-storage/name_search/src/document/test.rs
new file mode 100644
index 0000000000..00d8dbc0c0
--- /dev/null
+++ b/rust/cloud-storage/name_search/src/document/test.rs
@@ -0,0 +1,323 @@
+//! Tests for document module
+
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::{Pool, Postgres};
+use uuid::Uuid;
+
+use super::*;
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("document"))
+)]
+async fn test_search_document_names_empty_term(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ let result = search_document_names(&pool, &user_id, &[], "".to_string(), false, 10, 0).await;
+
+ assert!(result.is_err());
+ assert!(matches!(
+ result.unwrap_err(),
+ NameSearchError::EmptySearchTerm
+ ));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("document"))
+)]
+async fn test_search_document_names_ids_only_with_empty_ids(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ let result =
+ search_document_names(&pool, &user_id, &[], "report".to_string(), true, 10, 0).await;
+
+ assert!(result.is_err());
+ assert!(matches!(
+ result.unwrap_err(),
+ NameSearchError::EmptyIdsWithIdsOnly
+ ));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("document"))
+)]
+async fn test_search_document_names_ids_only_mode(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for "report" within specific document IDs
+ let doc_ids = vec![
+ Uuid::parse_str("11111111-1111-1111-1111-111111111111")?,
+ Uuid::parse_str("22222222-2222-2222-2222-222222222222")?,
+ Uuid::parse_str("66666666-6666-6666-6666-666666666666")?, // Budget Analysis - won't match
+ ];
+
+ let results =
+ search_document_names(&pool, &user_id, &doc_ids, "report".to_string(), true, 10, 0).await?;
+
+ // Should only return the 2 documents that match "report" from the provided IDs
+ assert_eq!(results.len(), 2);
+
+ // Verify results contain expected documents (ordered by updatedAt DESC)
+ assert_eq!(
+ results[0].entity_id.to_string(),
+ "22222222-2222-2222-2222-222222222222"
+ );
+ assert_eq!(results[0].entity_type, SearchEntityType::Documents);
+ assert_eq!(results[0].name, "Sales Report December");
+
+ assert_eq!(
+ results[1].entity_id.to_string(),
+ "11111111-1111-1111-1111-111111111111"
+ );
+ assert_eq!(results[1].name, "Quarterly Report 2024");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("document"))
+)]
+async fn test_search_document_names_normal_mode_owned_documents(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for "report" across all user1's owned documents
+ let results =
+ search_document_names(&pool, &user_id, &[], "report".to_string(), false, 10, 0).await?;
+
+ // Should return 4 documents matching "report" (3 lowercase + 1 uppercase)
+ assert_eq!(results.len(), 4);
+
+ // Verify ordering by updatedAt DESC
+ assert_eq!(
+ results[0].entity_id.to_string(),
+ "88888888-8888-8888-8888-888888888888"
+ );
+ assert_eq!(results[0].name, "ANNUAL REPORT 2024");
+
+ assert_eq!(
+ results[1].entity_id.to_string(),
+ "33333333-3333-3333-3333-333333333333"
+ );
+ assert_eq!(results[1].name, "Financial Report Q3");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("document"))
+)]
+async fn test_search_document_names_case_insensitive(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search with uppercase term should match both lowercase and uppercase names
+ let results =
+ search_document_names(&pool, &user_id, &[], "REPORT".to_string(), false, 10, 0).await?;
+
+ assert_eq!(results.len(), 4);
+
+ // Search with lowercase term should also match both
+ let results =
+ search_document_names(&pool, &user_id, &[], "report".to_string(), false, 10, 0).await?;
+
+ assert_eq!(results.len(), 4);
+
+ // Search with mixed case
+ let results =
+ search_document_names(&pool, &user_id, &[], "RePoRt".to_string(), false, 10, 0).await?;
+
+ assert_eq!(results.len(), 4);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("document"))
+)]
+async fn test_search_document_names_with_shared_documents(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Include a document from user3 (shared via document_ids parameter)
+ let shared_doc_ids = vec![Uuid::parse_str("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")?];
+
+ let results = search_document_names(
+ &pool,
+ &user_id,
+ &shared_doc_ids,
+ "report".to_string(),
+ false,
+ 10,
+ 0,
+ )
+ .await?;
+
+ // Should return user1's 4 "report" documents + user3's 1 "report" document
+ assert_eq!(results.len(), 5);
+
+ // Verify user3's document is included
+ let user3_doc = results.iter().find(|r| {
+ r.entity_id
+ .to_string()
+ .eq("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")
+ });
+ assert!(user3_doc.is_some());
+ assert_eq!(user3_doc.unwrap().name, "User3 Report Shared");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("document"))
+)]
+async fn test_search_document_names_pagination_limit(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search with limit of 2
+ let results =
+ search_document_names(&pool, &user_id, &[], "report".to_string(), false, 2, 0).await?;
+
+ assert_eq!(results.len(), 2);
+
+ // Should get the 2 most recently updated documents with "report"
+ assert_eq!(
+ results[0].entity_id.to_string(),
+ "88888888-8888-8888-8888-888888888888"
+ );
+ assert_eq!(
+ results[1].entity_id.to_string(),
+ "33333333-3333-3333-3333-333333333333"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("document"))
+)]
+async fn test_search_document_names_pagination_offset(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search with offset of 2
+ let results =
+ search_document_names(&pool, &user_id, &[], "report".to_string(), false, 10, 2).await?;
+
+ assert_eq!(results.len(), 2);
+
+ // Should skip the first 2 and get the next 2
+ assert_eq!(
+ results[0].entity_id.to_string(),
+ "22222222-2222-2222-2222-222222222222"
+ );
+ assert_eq!(
+ results[1].entity_id.to_string(),
+ "11111111-1111-1111-1111-111111111111"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("document"))
+)]
+async fn test_search_document_names_no_results(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for a term that doesn't match any documents
+ let results = search_document_names(
+ &pool,
+ &user_id,
+ &[],
+ "nonexistent".to_string(),
+ false,
+ 10,
+ 0,
+ )
+ .await?;
+
+ assert_eq!(results.len(), 0);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("document"))
+)]
+async fn test_search_document_names_partial_match(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for partial term "meet" should match "meeting"
+ let results =
+ search_document_names(&pool, &user_id, &[], "meet".to_string(), false, 10, 0).await?;
+
+ assert_eq!(results.len(), 2);
+ assert_eq!(
+ results[0].entity_id.to_string(),
+ "55555555-5555-5555-5555-555555555555"
+ );
+ assert_eq!(results[0].name, "Client Meeting Agenda");
+
+ assert_eq!(
+ results[1].entity_id.to_string(),
+ "44444444-4444-4444-4444-444444444444"
+ );
+ assert_eq!(results[1].name, "Team Meeting Notes");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("document"))
+)]
+async fn test_search_document_names_user_isolation(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for "User2" - user1 should not see user2's private documents
+ let results =
+ search_document_names(&pool, &user_id, &[], "User2".to_string(), false, 10, 0).await?;
+
+ // Should return 0 results (user2's documents are not owned by user1 and not shared)
+ assert_eq!(results.len(), 0);
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/name_search/src/email.rs b/rust/cloud-storage/name_search/src/email.rs
new file mode 100644
index 0000000000..c54dd1eabc
--- /dev/null
+++ b/rust/cloud-storage/name_search/src/email.rs
@@ -0,0 +1,139 @@
+//! This module contains logic for searching email threads by oldest message subject
+use crate::{NameSearchError, NameSearchResult, SearchEntityType};
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use sqlx::{Pool, Postgres};
+use uuid::Uuid;
+
+/// Searches email threads by IDs only
+async fn ids_search(
+ db: &Pool<Postgres>,
+ thread_ids: &[Uuid],
+ search_pattern: String,
+ limit: u32,
+ offset: u32,
+) -> Result<Vec<NameSearchResult>, NameSearchError> {
+ if thread_ids.is_empty() {
+ return Err(NameSearchError::EmptyIdsWithIdsOnly);
+ }
+
+ let rows = sqlx::query!(
+ r#"
+ WITH oldest_messages AS (
+ SELECT DISTINCT ON (thread_id)
+ thread_id,
+ subject
+ FROM email_messages
+ WHERE thread_id = ANY($1)
+ ORDER BY thread_id, internal_date_ts ASC
+ )
+ SELECT
+ t.id as entity_id,
+ om.subject as "name!"
+ FROM email_threads t
+ INNER JOIN oldest_messages om ON om.thread_id = t.id
+ WHERE om.subject ILIKE $2
+ ORDER BY t.latest_non_spam_message_ts DESC
+ LIMIT $3
+ OFFSET $4
+ "#,
+ thread_ids,
+ search_pattern,
+ limit as i64,
+ offset as i64,
+ )
+ .fetch_all(db)
+ .await
+ .map_err(NameSearchError::DatabaseError)?;
+
+ Ok(rows
+ .into_iter()
+ .map(|row| NameSearchResult {
+ entity_id: row.entity_id,
+ entity_type: SearchEntityType::Emails,
+ name: row.name,
+ })
+ .collect())
+}
+
+/// Searches email threads by owner or IDs
+async fn owner_search<'a>(
+ db: &Pool<Postgres>,
+ macro_user_id: &MacroUserId<Lowercase<'a>>,
+ thread_ids: &[Uuid],
+ search_pattern: String,
+ limit: u32,
+ offset: u32,
+) -> Result<Vec<NameSearchResult>, NameSearchError> {
+ let rows = sqlx::query!(
+ r#"
+ WITH oldest_messages AS (
+ SELECT DISTINCT ON (thread_id)
+ thread_id,
+ subject
+ FROM email_messages
+ WHERE link_id IN (
+ SELECT id FROM email_links WHERE macro_id = $1
+ )
+ AND (thread_id = ANY($2) OR $3)
+ ORDER BY thread_id, internal_date_ts ASC
+ )
+ SELECT
+ t.id as entity_id,
+ om.subject as "name!"
+ FROM email_threads t
+ INNER JOIN oldest_messages om ON om.thread_id = t.id
+ WHERE t.link_id IN (
+ SELECT id FROM email_links WHERE macro_id = $1
+ )
+ AND om.subject ILIKE $4
+ ORDER BY t.latest_non_spam_message_ts DESC
+ LIMIT $5
+ OFFSET $6
+ "#,
+ macro_user_id.as_ref(),
+ &thread_ids,
+ thread_ids.is_empty(), // If empty, don't filter by thread_ids
+ search_pattern,
+ limit as i64,
+ offset as i64,
+ )
+ .fetch_all(db)
+ .await
+ .map_err(NameSearchError::DatabaseError)?;
+
+ Ok(rows
+ .into_iter()
+ .map(|row| NameSearchResult {
+ entity_id: row.entity_id,
+ entity_type: SearchEntityType::Emails,
+ name: row.name,
+ })
+ .collect())
+}
+
+/// Searches over email threads by the subject of the oldest message in each thread
+#[tracing::instrument(skip(db), err)]
+pub async fn search_email_subjects<'a>(
+ db: &Pool<Postgres>,
+ macro_user_id: &MacroUserId<Lowercase<'a>>,
+ thread_ids: &[Uuid],
+ term: String,
+ ids_only: bool,
+ limit: u32,
+ offset: u32,
+) -> Result<Vec<NameSearchResult>, NameSearchError> {
+ if term.is_empty() {
+ return Err(NameSearchError::EmptySearchTerm);
+ }
+
+ let search_pattern = format!("%{term}%");
+
+ if ids_only {
+ ids_search(db, thread_ids, search_pattern, limit, offset).await
+ } else {
+ owner_search(db, macro_user_id, thread_ids, search_pattern, limit, offset).await
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/name_search/src/email/test.rs b/rust/cloud-storage/name_search/src/email/test.rs
new file mode 100644
index 0000000000..bf7ea0ca28
--- /dev/null
+++ b/rust/cloud-storage/name_search/src/email/test.rs
@@ -0,0 +1,417 @@
+//! Tests for email module
+
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::{Pool, Postgres};
+use uuid::Uuid;
+
+use super::*;
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("email"))
+)]
+async fn test_search_email_subjects_empty_term(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ let result = search_email_subjects(&pool, &user_id, &[], "".to_string(), false, 10, 0).await;
+
+ assert!(result.is_err());
+ assert!(matches!(
+ result.unwrap_err(),
+ NameSearchError::EmptySearchTerm
+ ));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("email"))
+)]
+async fn test_search_email_subjects_ids_only_with_empty_ids(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ let result =
+ search_email_subjects(&pool, &user_id, &[], "invoice".to_string(), true, 10, 0).await;
+
+ assert!(result.is_err());
+ assert!(matches!(
+ result.unwrap_err(),
+ NameSearchError::EmptyIdsWithIdsOnly
+ ));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("email"))
+)]
+async fn test_search_email_subjects_ids_only_mode(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for "invoice" within specific thread IDs
+ let thread_ids = vec![
+ Uuid::parse_str("11111111-1111-1111-1111-111111111111")?, // Invoice from Q1 2024
+ Uuid::parse_str("22222222-2222-2222-2222-222222222222")?, // Monthly Invoice
+ Uuid::parse_str("55555555-5555-5555-5555-555555555555")?, // Weekly Update - won't match
+ ];
+
+ let results = search_email_subjects(
+ &pool,
+ &user_id,
+ &thread_ids,
+ "invoice".to_string(),
+ true,
+ 10,
+ 0,
+ )
+ .await?;
+
+ // Should only return the 2 threads that match "invoice" from the provided IDs
+ assert_eq!(results.len(), 2);
+
+ // Verify results contain expected threads (ordered by latest_non_spam_message_ts DESC)
+ assert_eq!(
+ results[0].entity_id.to_string(),
+ "22222222-2222-2222-2222-222222222222"
+ );
+ assert_eq!(results[0].entity_type, SearchEntityType::Emails);
+ assert_eq!(results[0].name, "Re: Monthly Invoice - December");
+
+ assert_eq!(
+ results[1].entity_id.to_string(),
+ "11111111-1111-1111-1111-111111111111"
+ );
+ assert_eq!(results[1].name, "Invoice from Q1 2024");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("email"))
+)]
+async fn test_search_email_subjects_normal_mode_owned_threads(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for "invoice" across all user1's email threads
+ let results =
+ search_email_subjects(&pool, &user_id, &[], "invoice".to_string(), false, 10, 0).await?;
+
+ // Should return 3 threads matching "invoice" (2 with "invoice" + 1 with "INVOICE")
+ assert_eq!(results.len(), 3);
+
+ // Verify ordering by latest_non_spam_message_ts DESC
+ assert_eq!(
+ results[0].entity_id.to_string(),
+ "66666666-6666-6666-6666-666666666666"
+ );
+ assert_eq!(results[0].name, "IMPORTANT: INVOICE DUE");
+
+ assert_eq!(
+ results[1].entity_id.to_string(),
+ "22222222-2222-2222-2222-222222222222"
+ );
+ assert_eq!(results[1].name, "Re: Monthly Invoice - December");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("email"))
+)]
+async fn test_search_email_subjects_case_insensitive(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search with uppercase term should match both lowercase and uppercase subjects
+ let results =
+ search_email_subjects(&pool, &user_id, &[], "INVOICE".to_string(), false, 10, 0).await?;
+
+ assert_eq!(results.len(), 3);
+
+ // Search with lowercase term should also match both
+ let results =
+ search_email_subjects(&pool, &user_id, &[], "invoice".to_string(), false, 10, 0).await?;
+
+ assert_eq!(results.len(), 3);
+
+ // Search with mixed case
+ let results =
+ search_email_subjects(&pool, &user_id, &[], "InVoIcE".to_string(), false, 10, 0).await?;
+
+ assert_eq!(results.len(), 3);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("email"))
+)]
+async fn test_search_email_subjects_with_shared_threads(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Try to access a thread from user3 by passing its ID
+ // In normal mode, even when thread_ids are specified, only threads belonging to
+ // the user's link_id are returned. User3's thread belongs to user3's link_id,
+ // so it won't be accessible to user1.
+ let user3_thread_id = vec![Uuid::parse_str("99999999-9999-9999-9999-999999999999")?];
+
+ let results = search_email_subjects(
+ &pool,
+ &user_id,
+ &user3_thread_id,
+ "invoice".to_string(),
+ false,
+ 10,
+ 0,
+ )
+ .await?;
+
+ // Should return 0 results because user3's thread doesn't belong to user1's link_id
+ // Email isolation is enforced via link_id, not just thread ownership
+ assert_eq!(results.len(), 0);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("email"))
+)]
+async fn test_search_email_subjects_pagination_limit(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search with limit of 2
+ let results =
+ search_email_subjects(&pool, &user_id, &[], "invoice".to_string(), false, 2, 0).await?;
+
+ assert_eq!(results.len(), 2);
+
+ // Should get the 2 most recently updated threads with "invoice"
+ assert_eq!(
+ results[0].entity_id.to_string(),
+ "66666666-6666-6666-6666-666666666666"
+ );
+ assert_eq!(
+ results[1].entity_id.to_string(),
+ "22222222-2222-2222-2222-222222222222"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("email"))
+)]
+async fn test_search_email_subjects_pagination_offset(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search with offset of 2
+ let results =
+ search_email_subjects(&pool, &user_id, &[], "invoice".to_string(), false, 10, 2).await?;
+
+ assert_eq!(results.len(), 1);
+
+ // Should skip the first 2 and get the next 1
+ assert_eq!(
+ results[0].entity_id.to_string(),
+ "11111111-1111-1111-1111-111111111111"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("email"))
+)]
+async fn test_search_email_subjects_no_results(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for a term that doesn't match any email subjects
+ let results = search_email_subjects(
+ &pool,
+ &user_id,
+ &[],
+ "nonexistent".to_string(),
+ false,
+ 10,
+ 0,
+ )
+ .await?;
+
+ assert_eq!(results.len(), 0);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("email"))
+)]
+async fn test_search_email_subjects_partial_match(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for partial term "meet" should match "meeting"
+ let results =
+ search_email_subjects(&pool, &user_id, &[], "meet".to_string(), false, 10, 0).await?;
+
+ assert_eq!(results.len(), 2);
+ assert_eq!(
+ results[0].entity_id.to_string(),
+ "44444444-4444-4444-4444-444444444444"
+ );
+ assert_eq!(results[0].name, "Fwd: Client Meeting Tomorrow");
+
+ assert_eq!(
+ results[1].entity_id.to_string(),
+ "33333333-3333-3333-3333-333333333333"
+ );
+ assert_eq!(results[1].name, "Team Meeting Notes");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("email"))
+)]
+async fn test_search_email_subjects_user_isolation(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for "User2" - user1 should not see user2's private email threads
+ let results =
+ search_email_subjects(&pool, &user_id, &[], "User2".to_string(), false, 10, 0).await?;
+
+ // Should return 0 results (user2's emails are not linked to user1)
+ assert_eq!(results.len(), 0);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("email"))
+)]
+async fn test_search_email_subjects_searches_oldest_message(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Thread 22222222 has 3 messages:
+ // 1. Oldest (2024-02-01): "Re: Monthly Invoice - December"
+ // 2. Middle (2024-02-02): "Re: Re: Monthly Invoice - December"
+ // 3. Newest (2024-12-02): "Re: Re: Re: Payment Processed"
+
+ // Searching for "Monthly Invoice" should find the thread because the oldest message matches
+ let results = search_email_subjects(
+ &pool,
+ &user_id,
+ &[],
+ "Monthly Invoice".to_string(),
+ false,
+ 10,
+ 0,
+ )
+ .await?;
+
+ assert!(results.iter().any(|r| {
+ r.entity_id
+ .to_string()
+ .eq("22222222-2222-2222-2222-222222222222")
+ }));
+
+ // Searching for "Payment Processed" should NOT find it because oldest message doesn't match
+ let results = search_email_subjects(
+ &pool,
+ &user_id,
+ &[],
+ "Payment Processed".to_string(),
+ false,
+ 10,
+ 0,
+ )
+ .await?;
+
+ assert!(!results.iter().any(|r| {
+ r.entity_id
+ .to_string()
+ .eq("22222222-2222-2222-2222-222222222222")
+ }));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("email"))
+)]
+async fn test_search_email_subjects_multiple_messages_per_thread(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Thread 11111111 has multiple messages - should return thread only once with oldest subject
+ let results =
+ search_email_subjects(&pool, &user_id, &[], "invoice".to_string(), false, 10, 0).await?;
+
+ // Count how many times thread 11111111 appears (should be exactly once)
+ let count = results
+ .iter()
+ .filter(|r| {
+ r.entity_id
+ .to_string()
+ .eq("11111111-1111-1111-1111-111111111111")
+ })
+ .count();
+ assert_eq!(count, 1);
+
+ // Verify it returns the oldest message's subject
+ let thread_result = results
+ .iter()
+ .find(|r| {
+ r.entity_id
+ .to_string()
+ .eq("11111111-1111-1111-1111-111111111111")
+ })
+ .unwrap();
+ assert_eq!(thread_result.name, "Invoice from Q1 2024");
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/name_search/src/lib.rs b/rust/cloud-storage/name_search/src/lib.rs
new file mode 100644
index 0000000000..5b2f6046d6
--- /dev/null
+++ b/rust/cloud-storage/name_search/src/lib.rs
@@ -0,0 +1,38 @@
+#![deny(missing_docs)]
+//! This crate contains queries to search over macro db entities by their name
+
+mod chat;
+mod document;
+mod email;
+mod project;
+
+pub use chat::*;
+pub use document::*;
+pub use email::*;
+pub use models_opensearch::SearchEntityType;
+pub use project::*;
+
+/// Errors for name search crate
+#[derive(Debug, thiserror::Error)]
+pub enum NameSearchError {
+ /// Database error
+ #[error("database error occurred")]
+ DatabaseError(#[from] sqlx::Error),
+ /// Empty search term
+ #[error("empty search term provided")]
+ EmptySearchTerm,
+ /// Empty ids provided with ids only set to true
+ #[error("empty ids provided with ids only set to true")]
+ EmptyIdsWithIdsOnly,
+}
+
+/// Name search result match
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct NameSearchResult {
+ /// The id of the entity
+ pub entity_id: uuid::Uuid,
+ /// The type of the entity
+ pub entity_type: SearchEntityType,
+ /// The name that was matched
+ pub name: String,
+}
diff --git a/rust/cloud-storage/name_search/src/project.rs b/rust/cloud-storage/name_search/src/project.rs
new file mode 100644
index 0000000000..322786368c
--- /dev/null
+++ b/rust/cloud-storage/name_search/src/project.rs
@@ -0,0 +1,134 @@
+//! This module contains logic for searching projects by name
+
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use sqlx::{Pool, Postgres};
+use uuid::Uuid;
+
+use crate::{NameSearchError, NameSearchResult, SearchEntityType};
+
+/// Searches projects by IDs only
+async fn ids_search(
+ db: &Pool<Postgres>,
+ project_ids: &[Uuid],
+ search_pattern: String,
+ limit: u32,
+ offset: u32,
+) -> Result<Vec<NameSearchResult>, NameSearchError> {
+ if project_ids.is_empty() {
+ return Err(NameSearchError::EmptyIdsWithIdsOnly);
+ }
+
+ let rows = sqlx::query!(
+ r#"
+ SELECT
+ p.id as entity_id,
+ p.name
+ FROM "Project" p
+ WHERE p.id = ANY($1)
+ AND p."deletedAt" IS NULL
+ AND p.name ILIKE $2
+ ORDER BY p."updatedAt" DESC
+ LIMIT $3
+ OFFSET $4
+ "#,
+ &project_ids
+ .iter()
+ .map(|id| id.to_string())
+ .collect::<Vec<String>>(),
+ search_pattern,
+ limit as i64,
+ offset as i64,
+ )
+ .fetch_all(db)
+ .await
+ .map_err(NameSearchError::DatabaseError)?;
+
+ Ok(rows
+ .into_iter()
+ .map(|row| NameSearchResult {
+ entity_id: row.entity_id.parse().unwrap(),
+ entity_type: SearchEntityType::Projects,
+ name: row.name,
+ })
+ .collect())
+}
+
+/// Searches projects by owner or IDs
+async fn owner_search<'a>(
+ db: &Pool<Postgres>,
+ macro_user_id: &MacroUserId<Lowercase<'a>>,
+ project_ids: &[Uuid],
+ search_pattern: String,
+ limit: u32,
+ offset: u32,
+) -> Result<Vec<NameSearchResult>, NameSearchError> {
+ let rows = sqlx::query!(
+ r#"
+ SELECT
+ p.id as entity_id,
+ p.name
+ FROM "Project" p
+ WHERE (p."userId" = $1 OR p.id = ANY($2))
+ AND p."deletedAt" IS NULL
+ AND p.name ILIKE $3
+ ORDER BY p."updatedAt" DESC
+ LIMIT $4
+ OFFSET $5
+ "#,
+ macro_user_id.as_ref(),
+ &project_ids
+ .iter()
+ .map(|id| id.to_string())
+ .collect::<Vec<String>>(),
+ search_pattern,
+ limit as i64,
+ offset as i64,
+ )
+ .fetch_all(db)
+ .await
+ .map_err(NameSearchError::DatabaseError)?;
+
+ Ok(rows
+ .into_iter()
+ .map(|row| NameSearchResult {
+ entity_id: row.entity_id.parse().unwrap(),
+ entity_type: SearchEntityType::Projects,
+ name: row.name,
+ })
+ .collect())
+}
+
+/// Searches over the user's projects by name
+#[tracing::instrument(skip(db), err)]
+pub async fn search_project_names<'a>(
+ db: &Pool<Postgres>,
+ macro_user_id: &MacroUserId<Lowercase<'a>>,
+ project_ids: &[Uuid],
+ term: String,
+ ids_only: bool,
+ limit: u32,
+ offset: u32,
+) -> Result<Vec<NameSearchResult>, NameSearchError> {
+ if term.is_empty() {
+ return Err(NameSearchError::EmptySearchTerm);
+ }
+
+ let search_pattern = format!("%{term}%");
+
+ if ids_only {
+ ids_search(db, project_ids, search_pattern, limit, offset).await
+ } else {
+ owner_search(
+ db,
+ macro_user_id,
+ project_ids,
+ search_pattern,
+ limit,
+ offset,
+ )
+ .await
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/name_search/src/project/test.rs b/rust/cloud-storage/name_search/src/project/test.rs
new file mode 100644
index 0000000000..9c9bb82999
--- /dev/null
+++ b/rust/cloud-storage/name_search/src/project/test.rs
@@ -0,0 +1,359 @@
+//! Tests for project module
+
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::{Pool, Postgres};
+use uuid::Uuid;
+
+use super::*;
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("project"))
+)]
+async fn test_search_project_names_empty_term(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ let result = search_project_names(&pool, &user_id, &[], "".to_string(), false, 10, 0).await;
+
+ assert!(result.is_err());
+ assert!(matches!(
+ result.unwrap_err(),
+ NameSearchError::EmptySearchTerm
+ ));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("project"))
+)]
+async fn test_search_project_names_ids_only_with_empty_ids(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ let result =
+ search_project_names(&pool, &user_id, &[], "mobile".to_string(), true, 10, 0).await;
+
+ assert!(result.is_err());
+ assert!(matches!(
+ result.unwrap_err(),
+ NameSearchError::EmptyIdsWithIdsOnly
+ ));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("project"))
+)]
+async fn test_search_project_names_ids_only_mode(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for "mobile" within specific project IDs
+ let project_ids = vec![
+ Uuid::parse_str("11111111-1111-1111-1111-111111111111")?,
+ Uuid::parse_str("22222222-2222-2222-2222-222222222222")?,
+ Uuid::parse_str("55555555-5555-5555-5555-555555555555")?, // Marketing Campaign - won't match
+ ];
+
+ let results = search_project_names(
+ &pool,
+ &user_id,
+ &project_ids,
+ "mobile".to_string(),
+ true,
+ 10,
+ 0,
+ )
+ .await?;
+
+ // Should only return the 2 projects that match "mobile" from the provided IDs
+ assert_eq!(results.len(), 2);
+
+ // Verify results contain expected projects (ordered by updatedAt DESC)
+ assert_eq!(
+ results[0].entity_id.to_string(),
+ "22222222-2222-2222-2222-222222222222"
+ );
+ assert_eq!(results[0].entity_type, SearchEntityType::Projects);
+ assert_eq!(results[0].name, "Mobile App Redesign");
+
+ assert_eq!(
+ results[1].entity_id.to_string(),
+ "11111111-1111-1111-1111-111111111111"
+ );
+ assert_eq!(results[1].name, "Mobile Development");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("project"))
+)]
+async fn test_search_project_names_normal_mode_owned_projects(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for "mobile" across all user1's owned projects
+ let results =
+ search_project_names(&pool, &user_id, &[], "mobile".to_string(), false, 10, 0).await?;
+
+ // Should return 3 projects matching "mobile" (2 lowercase + 1 uppercase)
+ assert_eq!(results.len(), 3);
+
+ // Verify ordering by updatedAt DESC
+ assert_eq!(
+ results[0].entity_id.to_string(),
+ "66666666-6666-6666-6666-666666666666"
+ );
+ assert_eq!(results[0].name, "MOBILE PLATFORM");
+
+ assert_eq!(
+ results[1].entity_id.to_string(),
+ "22222222-2222-2222-2222-222222222222"
+ );
+ assert_eq!(results[1].name, "Mobile App Redesign");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("project"))
+)]
+async fn test_search_project_names_case_insensitive(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search with uppercase term should match both lowercase and uppercase names
+ let results =
+ search_project_names(&pool, &user_id, &[], "MOBILE".to_string(), false, 10, 0).await?;
+
+ assert_eq!(results.len(), 3);
+
+ // Search with lowercase term should also match both
+ let results =
+ search_project_names(&pool, &user_id, &[], "mobile".to_string(), false, 10, 0).await?;
+
+ assert_eq!(results.len(), 3);
+
+ // Search with mixed case
+ let results =
+ search_project_names(&pool, &user_id, &[], "MoBiLe".to_string(), false, 10, 0).await?;
+
+ assert_eq!(results.len(), 3);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("project"))
+)]
+async fn test_search_project_names_with_shared_projects(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Include a project from user3 (shared via project_ids parameter)
+ let shared_project_ids = vec![Uuid::parse_str("99999999-9999-9999-9999-999999999999")?];
+
+ let results = search_project_names(
+ &pool,
+ &user_id,
+ &shared_project_ids,
+ "mobile".to_string(),
+ false,
+ 10,
+ 0,
+ )
+ .await?;
+
+ // Should return user1's 3 "mobile" projects + user3's 1 "mobile" project
+ assert_eq!(results.len(), 4);
+
+ // Verify user3's project is included
+ let user3_project = results.iter().find(|r| {
+ r.entity_id
+ .to_string()
+ .eq("99999999-9999-9999-9999-999999999999")
+ });
+ assert!(user3_project.is_some());
+ assert_eq!(user3_project.unwrap().name, "User3 Shared Mobile");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("project"))
+)]
+async fn test_search_project_names_pagination_limit(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search with limit of 2
+ let results =
+ search_project_names(&pool, &user_id, &[], "mobile".to_string(), false, 2, 0).await?;
+
+ assert_eq!(results.len(), 2);
+
+ // Should get the 2 most recently updated projects with "mobile"
+ assert_eq!(
+ results[0].entity_id.to_string(),
+ "66666666-6666-6666-6666-666666666666"
+ );
+ assert_eq!(
+ results[1].entity_id.to_string(),
+ "22222222-2222-2222-2222-222222222222"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("project"))
+)]
+async fn test_search_project_names_pagination_offset(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search with offset of 2
+ let results =
+ search_project_names(&pool, &user_id, &[], "mobile".to_string(), false, 10, 2).await?;
+
+ assert_eq!(results.len(), 1);
+
+ // Should skip the first 2 and get the next 1
+ assert_eq!(
+ results[0].entity_id.to_string(),
+ "11111111-1111-1111-1111-111111111111"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("project"))
+)]
+async fn test_search_project_names_no_results(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for a term that doesn't match any projects
+ let results = search_project_names(
+ &pool,
+ &user_id,
+ &[],
+ "nonexistent".to_string(),
+ false,
+ 10,
+ 0,
+ )
+ .await?;
+
+ assert_eq!(results.len(), 0);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("project"))
+)]
+async fn test_search_project_names_partial_match(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for partial term "web" should match "website"
+ let results =
+ search_project_names(&pool, &user_id, &[], "web".to_string(), false, 10, 0).await?;
+
+ assert_eq!(results.len(), 2);
+ assert_eq!(
+ results[0].entity_id.to_string(),
+ "44444444-4444-4444-4444-444444444444"
+ );
+ assert_eq!(results[0].name, "Website Optimization");
+
+ assert_eq!(
+ results[1].entity_id.to_string(),
+ "33333333-3333-3333-3333-333333333333"
+ );
+ assert_eq!(results[1].name, "Web Platform Upgrade");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("project"))
+)]
+async fn test_search_project_names_user_isolation(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for "User2" - user1 should not see user2's private projects
+ let results =
+ search_project_names(&pool, &user_id, &[], "User2".to_string(), false, 10, 0).await?;
+
+ // Should return 0 results (user2's projects are not owned by user1 and not shared)
+ assert_eq!(results.len(), 0);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("project"))
+)]
+async fn test_search_project_names_excludes_soft_deleted(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")
+ .map(|l| l.lowercase())
+ .unwrap();
+
+ // Search for "mobile" - should NOT include soft-deleted project
+ let results =
+ search_project_names(&pool, &user_id, &[], "mobile".to_string(), false, 10, 0).await?;
+
+ // Should NOT include the deleted project (id: 77777777-7777-7777-7777-777777777777)
+ assert!(!results.iter().any(|r| {
+ r.entity_id
+ .to_string()
+ .eq("77777777-7777-7777-7777-777777777777")
+ }));
+
+ // Should include non-deleted projects
+ assert!(results.iter().any(|r| {
+ r.entity_id
+ .to_string()
+ .eq("11111111-1111-1111-1111-111111111111")
+ }));
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/opensearch_client/src/error.rs b/rust/cloud-storage/opensearch_client/src/error.rs
index 0ea0b10dc3..bf80fcc9cc 100644
--- a/rust/cloud-storage/opensearch_client/src/error.rs
+++ b/rust/cloud-storage/opensearch_client/src/error.rs
@@ -51,6 +51,9 @@ pub enum OpensearchClientError {
#[error("empty ids with ids only for {0}")]
EmptyIdsWithIdsOnly(SearchEntityType),
+
+ #[error("unsupported search_on")]
+ InvalidSearchOn,
}
impl From<anyhow::Error> for OpensearchClientError {
diff --git a/rust/cloud-storage/opensearch_client/src/lib.rs b/rust/cloud-storage/opensearch_client/src/lib.rs
index 8037695a34..ed40d724ab 100644
--- a/rust/cloud-storage/opensearch_client/src/lib.rs
+++ b/rust/cloud-storage/opensearch_client/src/lib.rs
@@ -4,7 +4,6 @@ pub mod error;
pub mod name;
pub mod search;
pub mod search_on;
-pub mod unified;
pub mod upsert;
pub use search_on::SearchOn;
diff --git a/rust/cloud-storage/opensearch_client/src/project.rs b/rust/cloud-storage/opensearch_client/src/project.rs
index bca7be1a85..e4b4bf3c5d 100644
--- a/rust/cloud-storage/opensearch_client/src/project.rs
+++ b/rust/cloud-storage/opensearch_client/src/project.rs
@@ -1,10 +1,6 @@
use crate::{
OpensearchClient, Result,
delete::project::{delete_project_bulk_ids, delete_project_by_id, delete_projects_by_user_id},
- search::{
- model::SearchHit,
- projects::{ProjectSearchArgs, search_projects},
- },
upsert::project::{UpsertProjectArgs, upsert_project},
};
@@ -27,12 +23,6 @@ impl OpensearchClient {
delete_project_bulk_ids(&self.inner, ids).await
}
- /// Searches for projects in the opensearch index
- #[tracing::instrument(skip(self))]
- pub async fn search_project(&self, args: ProjectSearchArgs) -> Result<Vec<SearchHit>> {
- search_projects(&self.inner, args).await
- }
-
pub async fn delete_projects_by_user_id(&self, user_id: &str) -> Result<()> {
delete_projects_by_user_id(&self.inner, user_id).await
}
diff --git a/rust/cloud-storage/opensearch_client/src/search/builder.rs b/rust/cloud-storage/opensearch_client/src/search/builder.rs
index db4546a643..b915c9763f 100644
--- a/rust/cloud-storage/opensearch_client/src/search/builder.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/builder.rs
@@ -8,7 +8,6 @@ use crate::search::query::Keys;
use crate::search::query::QueryKey;
use crate::search::query::generate_terms_must_query;
use models_opensearch::SearchEntityType;
-use models_opensearch::SearchIndex;
use opensearch_query_builder::*;
/// A macro for generating delegation methods that forward calls to an inner field
@@ -92,7 +91,6 @@ pub trait SearchQueryConfig {
/// Returns the default sort types that are used on the search query.
/// Override this method if you need custom sort logic
fn default_sort_types<'a>() -> Vec<SortType<'a>> {
- println!("CALLED");
// Use the updated_at_sort by default
updated_at_sort()
}
@@ -148,11 +146,6 @@ pub struct SearchQueryBuilder<T: SearchQueryConfig> {
_phantom: std::marker::PhantomData<T>,
}
-pub struct ContentAndNameBoolQueries<'a> {
- pub content_bool_query: Option<BoolQueryBuilder<'a>>,
- pub name_bool_query: Option<BoolQueryBuilder<'a>>,
-}
-
impl<T: SearchQueryConfig> SearchQueryBuilder<T> {
pub fn new(terms: Vec<String>) -> Self {
Self {
@@ -254,10 +247,12 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {
}
}
- /// Builds a content and name bool query
- pub fn build_content_and_name_bool_query<'a>(
- &'a self,
- ) -> Result<ContentAndNameBoolQueries<'a>> {
+ /// Builds a content bool query
+ pub fn build_content_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
+ // We only support searching over content in opensearch now
+ if self.search_on == SearchOn::Name {
+ return Err(OpensearchClientError::InvalidSearchOn);
+ }
// FIXES: https://linear.app/macro-eng/issue/BAC-173/sending-invalid-queries-to-opensearch
// If we try and build queries with ids only = true and no ids provided we should
// error out as it creates an invalid query since we have minimum_should_match = 1.
@@ -265,187 +260,82 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {
return Err(OpensearchClientError::EmptyIdsWithIdsOnly(T::ENTITY_INDEX));
}
- let content_bool_query = match self.search_on {
- SearchOn::Name => None,
- SearchOn::NameContent | SearchOn::Content => {
- let mut access_bool_query = BoolQueryBuilder::new();
-
- // For name OR content queries, we can build a much more simple bool query
- let term_must_array: Vec<QueryType<'a>> =
- self.build_must_term_query(SearchOn::Content)?;
-
- let mut inner_bool_query = BoolQueryBuilder::new();
-
- inner_bool_query.minimum_should_match(1);
-
- // For email search, we want to search over the participants
- // For all other indices we want to search over the owner
- match T::ENTITY_INDEX {
- SearchEntityType::Emails => {
- let mut participant_queries: Vec<QueryType> = Vec::new();
- for term in &self.terms {
- let formatted_term = format!("{}*", term);
- participant_queries.push(
- WildcardQuery::new(
- "sender",
- formatted_term.clone(),
- true,
- Some(5000.0),
- )
- .into(),
- );
- participant_queries.push(
- WildcardQuery::new(
- "cc",
- formatted_term.clone(),
- true,
- Some(5000.0),
- )
- .into(),
- );
- participant_queries.push(
- WildcardQuery::new(
- "bcc",
- formatted_term.clone(),
- true,
- Some(5000.0),
- )
- .into(),
- );
- participant_queries.push(
- WildcardQuery::new(
- "recipients",
- formatted_term.clone(),
- true,
- Some(5000.0),
- )
- .into(),
- );
- }
-
- for participant_query in participant_queries {
- inner_bool_query.should(participant_query);
- }
- }
- _ => {
- // Create a vec of owner queries for each term
- // We want to search over the content **and** the owner here
- let mut owner_queries: Vec<QueryType> = Vec::new();
- for term in &self.terms {
- let formatted_term = format!("macro|{}*", term);
- owner_queries.push(
- WildcardQuery::new(
- T::USER_ID_KEY,
- formatted_term,
- true,
- Some(5000.0),
- )
- .into(),
- );
- }
-
- // Add the owner queries to the bool query
- for owner_query in owner_queries {
- inner_bool_query.should(owner_query);
- }
- }
+ let mut access_bool_query = BoolQueryBuilder::new();
+
+ // For name OR content queries, we can build a much more simple bool query
+ let term_must_array: Vec<QueryType<'a>> = self.build_must_term_query(SearchOn::Content)?;
+
+ let mut inner_bool_query = BoolQueryBuilder::new();
+
+ inner_bool_query.minimum_should_match(1);
+
+ // For email search, we want to search over the participants
+ // For all other indices we want to search over the owner
+ match T::ENTITY_INDEX {
+ SearchEntityType::Emails => {
+ let mut participant_queries: Vec<QueryType> = Vec::new();
+ for term in &self.terms {
+ let formatted_term = format!("{}*", term);
+ participant_queries.push(
+ WildcardQuery::new("sender", formatted_term.clone(), true, Some(5000.0))
+ .into(),
+ );
+ participant_queries.push(
+ WildcardQuery::new("cc", formatted_term.clone(), true, Some(5000.0)).into(),
+ );
+ participant_queries.push(
+ WildcardQuery::new("bcc", formatted_term.clone(), true, Some(5000.0))
+ .into(),
+ );
+ participant_queries.push(
+ WildcardQuery::new(
+ "recipients",
+ formatted_term.clone(),
+ true,
+ Some(5000.0),
+ )
+ .into(),
+ );
}
- for must in term_must_array {
- inner_bool_query.should(must);
+ for participant_query in participant_queries {
+ inner_bool_query.should(participant_query);
}
-
- // Add in the inner bool query on content + owner to must of access bool query
- access_bool_query.must(inner_bool_query.build().into());
-
- // Filter over only items you have access to
- let filter_bool_query = self.build_filter_query(T::USER_ID_KEY)?;
- access_bool_query.filter(filter_bool_query);
-
- // Only search on the provided index
- access_bool_query.filter(QueryType::term("_index", T::ENTITY_INDEX.as_ref()));
-
- Some(access_bool_query)
}
- };
-
- let name_bool_query = match self.search_on {
- SearchOn::Content => None,
- SearchOn::Name | SearchOn::NameContent => {
- let mut bool_query = BoolQueryBuilder::new();
-
- // For name OR content queries, we can build a much more simple bool query
- let term_must_array: Vec<QueryType<'a>> =
- self.build_must_term_query(SearchOn::Name)?;
-
- // For each item in term must array, add to bool must query
- for must in term_must_array {
- bool_query.must(must);
+ _ => {
+ // Create a vec of owner queries for each term
+ // We want to search over the content **and** the owner here
+ let mut owner_queries: Vec<QueryType> = Vec::new();
+ for term in &self.terms {
+ let formatted_term = format!("macro|{}*", term);
+ owner_queries.push(
+ WildcardQuery::new(T::USER_ID_KEY, formatted_term, true, Some(5000.0))
+ .into(),
+ );
}
- // Filter over only items you have access to
- // For name index queries we want to always use user_id as the user id key
- let filter_bool_query = self.build_filter_query("user_id")?;
- bool_query.filter(filter_bool_query);
-
- match T::ENTITY_INDEX {
- SearchEntityType::Projects => {
- bool_query
- .filter(QueryType::term("_index", SearchIndex::Projects.as_ref()));
- }
- _ => {
- bool_query.filter(QueryType::term("_index", SearchIndex::Names.as_ref()));
- bool_query.filter(QueryType::term("entity_type", T::ENTITY_INDEX.as_ref()));
- }
+ // Add the owner queries to the bool query
+ for owner_query in owner_queries {
+ inner_bool_query.should(owner_query);
}
-
- Some(bool_query)
}
- };
-
- Ok(ContentAndNameBoolQueries {
- content_bool_query,
- name_bool_query,
- })
- }
+ }
- /// Builds the core bool query using the content_and_name_bool_queries
- /// generated from self.build_content_and_name_bool_query().
- /// They must be geneated separately as they could be modified after initially
- /// being built.
- pub fn build_bool_query<'a>(
- &self,
- content_and_name_bool_queries: ContentAndNameBoolQueries<'a>,
- ) -> Result<BoolQueryBuilder<'a>> {
- // If we have name content search, we need to combine the content and name bool queries
- // under a single root bool query
- match self.search_on {
- SearchOn::Name => Ok(content_and_name_bool_queries
- .name_bool_query
- .ok_or(OpensearchClientError::BoolQueryNotBuilt)?),
- SearchOn::Content => Ok(content_and_name_bool_queries
- .content_bool_query
- .ok_or(OpensearchClientError::BoolQueryNotBuilt)?),
- SearchOn::NameContent => {
- let mut bool_query = BoolQueryBuilder::new();
+ for must in term_must_array {
+ inner_bool_query.should(must);
+ }
- // Currently, the minimum should match is always one.
- // This should of the bool query contains the ids and potentially the user_id
- bool_query.minimum_should_match(1);
+ // Add in the inner bool query on content + owner to must of access bool query
+ access_bool_query.must(inner_bool_query.build().into());
- let content_bool_query = content_and_name_bool_queries
- .content_bool_query
- .ok_or(OpensearchClientError::BoolQueryNotBuilt)?;
- let name_bool_query = content_and_name_bool_queries
- .name_bool_query
- .ok_or(OpensearchClientError::BoolQueryNotBuilt)?;
+ // Filter over only items you have access to
+ let filter_bool_query = self.build_filter_query(T::USER_ID_KEY)?;
+ access_bool_query.filter(filter_bool_query);
- bool_query.should(content_bool_query.build().into());
- bool_query.should(name_bool_query.build().into());
+ // Only search on the provided index
+ access_bool_query.filter(QueryType::term("_index", T::ENTITY_INDEX.as_ref()));
- Ok(bool_query)
- }
- }
+ Ok(access_bool_query)
}
/// Builds the search request with the provided main bool query
diff --git a/rust/cloud-storage/opensearch_client/src/search/builder/test.rs b/rust/cloud-storage/opensearch_client/src/search/builder/test.rs
index f46b4ad6a4..15d01a0194 100644
--- a/rust/cloud-storage/opensearch_client/src/search/builder/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/builder/test.rs
@@ -241,7 +241,7 @@ fn test_build_search_request() -> anyhow::Result<()> {
}
#[test]
-fn test_build_content_and_name_query_empty_ids() -> anyhow::Result<()> {
+fn test_build_contentquery_empty_ids() -> anyhow::Result<()> {
// Empty ids ok with ids only false
let term = vec!["test".to_string()];
let ids: Vec<String> = vec![];
@@ -258,10 +258,9 @@ fn test_build_content_and_name_query_empty_ids() -> anyhow::Result<()> {
.ids(ids.clone())
.ids_only(false);
- let result = builder.build_content_and_name_bool_query()?;
+ let result = builder.build_content_bool_query();
- assert!(result.name_bool_query.is_none());
- assert!(result.content_bool_query.is_some());
+ assert!(result.is_ok());
// Empty ids fails with ids only true
let builder = SearchQueryBuilder::<TestSearchConfig>::new(term.clone())
@@ -273,7 +272,7 @@ fn test_build_content_and_name_query_empty_ids() -> anyhow::Result<()> {
.ids(ids.clone())
.ids_only(true);
- let error = builder.build_content_and_name_bool_query().err().unwrap();
+ let error = builder.build_content_bool_query().err().unwrap();
assert_eq!(
OpensearchClientError::EmptyIdsWithIdsOnly(SearchEntityType::Documents),
@@ -299,7 +298,7 @@ fn test_build_bool_query() -> anyhow::Result<()> {
.search_on(SearchOn::Content)
.ids(ids.clone());
- let query = builder.build_bool_query(builder.build_content_and_name_bool_query()?)?;
+ let query = builder.build_content_bool_query()?;
let expected = serde_json::json!({
"bool": {
@@ -352,7 +351,7 @@ fn test_build_bool_query() -> anyhow::Result<()> {
.search_on(SearchOn::Content)
.ids(ids.clone());
- let query = builder.build_bool_query(builder.build_content_and_name_bool_query()?)?;
+ let query = builder.build_content_bool_query()?;
let expected = serde_json::json!({
"bool": {
@@ -399,86 +398,49 @@ fn test_build_bool_query() -> anyhow::Result<()> {
.search_on(SearchOn::NameContent)
.ids(ids.clone());
- let query = builder.build_bool_query(builder.build_content_and_name_bool_query()?)?;
+ let query = builder.build_content_bool_query()?;
let expected = serde_json::json!({
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "bool": {
- "must": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "test_user_id": {
- "case_insensitive": true,
- "value": "macro|test*",
- "boost": 5000.0
- }
+ "bool": {
+ "must": [
+ {
+ "bool": {
+ "minimum_should_match": 1,
+ "should": [
+ {
+ "wildcard": {
+ "test_user_id": {
+ "case_insensitive": true,
+ "value": "macro|test*",
+ "boost": 5000.0
}
- },
- {
- "match_phrase_prefix": {
- "content": {
- "query": "test"
- }
+ }
+ },
+ {
+ "match_phrase_prefix": {
+ "content": {
+ "query": "test"
}
}
- ]
- }
- },
- ],
- "filter": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "_index": "documents",
}
+ ]
}
- ]
- }
- },
- {
- "bool": {
- "must": [
- {
- "match_phrase_prefix": {
- "test_title": {
- "query": "test"
- }
- }
- },
- ],
- "filter": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "_index": "names",
- }
- },
- {
- "term": {
- "entity_type": "documents"
- }
+ },
+ ],
+ "filter": [
+ {
+ "terms": {
+ "entity_id": ["id1", "id2"]
}
- ]
- }
+ },
+ {
+ "term": {
+ "_index": "documents",
+ }
+ }
+ ]
}
- ]
- }
- });
+ });
assert_eq!(query.build().to_json(), expected);
diff --git a/rust/cloud-storage/opensearch_client/src/search/channels.rs b/rust/cloud-storage/opensearch_client/src/search/channels.rs
index 336ecb03dc..23278cde09 100644
--- a/rust/cloud-storage/opensearch_client/src/search/channels.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/channels.rs
@@ -98,38 +98,26 @@ impl ChannelMessageQueryBuilder {
/// Builds the main bool query for the index
pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
- let mut content_and_name_bool_queries = self.inner.build_content_and_name_bool_query()?;
+ let mut content_bool_query = self.inner.build_content_bool_query()?;
// CUSTOM ATTRIBUTES SECTION
- if self.inner.search_on == SearchOn::Content
- || self.inner.search_on == SearchOn::NameContent
- {
- let mut bool_query = content_and_name_bool_queries
- .content_bool_query
- .ok_or(OpensearchClientError::BoolQueryNotBuilt)?;
-
- // Add thread_ids to must clause if provided
- if !self.thread_ids.is_empty() {
- bool_query.filter(QueryType::terms("thread_id", self.thread_ids.clone()));
- }
-
- // Add mentions to must clause if provided
- if !self.mentions.is_empty() {
- bool_query.filter(QueryType::terms("mentions", self.mentions.clone()));
- }
+ // Add thread_ids to must clause if provided
+ if !self.thread_ids.is_empty() {
+ content_bool_query.filter(QueryType::terms("thread_id", self.thread_ids.clone()));
+ }
- // Add sender_ids to must clause if provided
- if !self.sender_ids.is_empty() {
- bool_query.filter(QueryType::terms("sender_id", self.sender_ids.clone()));
- }
+ // Add mentions to must clause if provided
+ if !self.mentions.is_empty() {
+ content_bool_query.filter(QueryType::terms("mentions", self.mentions.clone()));
+ }
- content_and_name_bool_queries.content_bool_query = Some(bool_query);
+ // Add sender_ids to must clause if provided
+ if !self.sender_ids.is_empty() {
+ content_bool_query.filter(QueryType::terms("sender_id", self.sender_ids.clone()));
}
// END CUSTOM ATTRIBUTES SECTION
- let bool_query = self.inner.build_bool_query(content_and_name_bool_queries)?;
-
- Ok(bool_query)
+ Ok(content_bool_query)
}
fn build_search_request<'a>(&'a self) -> Result<SearchRequest<'a>> {
@@ -192,16 +180,12 @@ pub(crate) async fn search_channel_messages(
client: &opensearch::OpenSearch,
args: ChannelMessageSearchArgs,
) -> Result<Vec<SearchHit>> {
- let indices = match args.search_on {
- SearchOn::Content => vec![SearchIndex::Channels.as_ref()],
- SearchOn::NameContent => vec![SearchIndex::Channels.as_ref(), SearchIndex::Names.as_ref()],
- SearchOn::Name => vec![SearchIndex::Names.as_ref()],
- };
-
let query_body = args.build()?;
let response = client
- .search(opensearch::SearchParts::Index(&indices))
+ .search(opensearch::SearchParts::Index(&[
+ SearchIndex::Channels.as_ref()
+ ]))
.body(query_body)
.send()
.await
diff --git a/rust/cloud-storage/opensearch_client/src/search/chats.rs b/rust/cloud-storage/opensearch_client/src/search/chats.rs
index 546cc26b1a..c454a7877d 100644
--- a/rust/cloud-storage/opensearch_client/src/search/chats.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/chats.rs
@@ -75,29 +75,17 @@ impl ChatQueryBuilder {
}
pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
- let mut content_and_name_bool_queries = self.inner.build_content_and_name_bool_query()?;
+ let mut content_bool_query = self.inner.build_content_bool_query()?;
// CUSTOM ATTRIBUTES SECTION
- if self.inner.search_on == SearchOn::Content
- || self.inner.search_on == SearchOn::NameContent
- {
- let mut bool_query = content_and_name_bool_queries
- .content_bool_query
- .ok_or(OpensearchClientError::BoolQueryNotBuilt)?;
-
- // Add role to must clause if provided
- if !self.role.is_empty() {
- let should_query = should_wildcard_field_query_builder("role", &self.role);
- bool_query.filter(should_query);
- }
-
- content_and_name_bool_queries.content_bool_query = Some(bool_query);
+ // Add role to must clause if provided
+ if !self.role.is_empty() {
+ let should_query = should_wildcard_field_query_builder("role", &self.role);
+ content_bool_query.filter(should_query);
}
// END CUSTOM ATTRIBUTES SECTION
- let bool_query = self.inner.build_bool_query(content_and_name_bool_queries)?;
-
- Ok(bool_query)
+ Ok(content_bool_query)
}
fn build_search_request<'a>(&'a self) -> Result<SearchRequest<'a>> {
@@ -155,15 +143,12 @@ pub(crate) async fn search_chats(
client: &opensearch::OpenSearch,
args: ChatSearchArgs,
) -> Result<Vec<SearchHit>> {
- let indices = match args.search_on {
- SearchOn::Content => vec![SearchIndex::Chats.as_ref()],
- SearchOn::NameContent => vec![SearchIndex::Chats.as_ref(), SearchIndex::Names.as_ref()],
- SearchOn::Name => vec![SearchIndex::Names.as_ref()],
- };
let query_body = args.build()?;
let response = client
- .search(opensearch::SearchParts::Index(&indices))
+ .search(opensearch::SearchParts::Index(&[
+ SearchIndex::Chats.as_ref()
+ ]))
.body(query_body)
.send()
.await
diff --git a/rust/cloud-storage/opensearch_client/src/search/documents.rs b/rust/cloud-storage/opensearch_client/src/search/documents.rs
index b4cbe019fa..ea5af95e80 100644
--- a/rust/cloud-storage/opensearch_client/src/search/documents.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/documents.rs
@@ -56,8 +56,7 @@ impl DocumentQueryBuilder {
}
pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
- self.inner
- .build_bool_query(self.inner.build_content_and_name_bool_query()?)
+ self.inner.build_content_bool_query()
}
fn build_search_request<'a>(&'a self) -> Result<SearchRequest<'a>> {
@@ -131,18 +130,14 @@ pub(crate) async fn search_documents(
client: &opensearch::OpenSearch,
args: DocumentSearchArgs,
) -> Result<Vec<SearchHit>> {
- let indices = match args.search_on {
- SearchOn::Content => vec![SearchIndex::Documents.as_ref()],
- SearchOn::NameContent => vec![SearchIndex::Documents.as_ref(), SearchIndex::Names.as_ref()],
- SearchOn::Name => vec![SearchIndex::Names.as_ref()],
- };
-
let query_body = args.build()?;
tracing::trace!("query: {}", query_body);
let response = client
- .search(opensearch::SearchParts::Index(&indices))
+ .search(opensearch::SearchParts::Index(&[
+ SearchIndex::Documents.as_ref()
+ ]))
.body(query_body)
.send()
.await
diff --git a/rust/cloud-storage/opensearch_client/src/search/emails.rs b/rust/cloud-storage/opensearch_client/src/search/emails.rs
index 3dc5601f9c..723a51be23 100644
--- a/rust/cloud-storage/opensearch_client/src/search/emails.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/emails.rs
@@ -99,54 +99,43 @@ impl EmailQueryBuilder {
}
pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
- let mut content_and_name_bool_queries = self.inner.build_content_and_name_bool_query()?;
+ let mut content_bool_query = self.inner.build_content_bool_query()?;
// CUSTOM ATTRIBUTES SECTION
- if self.inner.search_on == SearchOn::Content
- || self.inner.search_on == SearchOn::NameContent
- {
- let mut bool_query = content_and_name_bool_queries
- .content_bool_query
- .ok_or(OpensearchClientError::BoolQueryNotBuilt)?;
-
- // We don't want to include trash items in your email search
- bool_query.must_not(QueryType::term("labels", "TRASH"));
-
- // If link_ids are provided, add them to the query
- if !self.link_ids.is_empty() {
- bool_query.filter(QueryType::terms("link_id", self.link_ids.clone()));
- }
-
- if !self.sender.is_empty() {
- // Create new query for senders
- let senders_query = should_wildcard_field_query_builder("sender", &self.sender);
- bool_query.filter(senders_query);
- }
+ // We don't want to include trash items in your email search
+ content_bool_query.must_not(QueryType::term("labels", "TRASH"));
- if !self.cc.is_empty() {
- let ccs_query = should_wildcard_field_query_builder("cc", &self.cc);
- bool_query.filter(ccs_query);
- }
+ // If link_ids are provided, add them to the query
+ if !self.link_ids.is_empty() {
+ content_bool_query.filter(QueryType::terms("link_id", self.link_ids.clone()));
+ }
- if !self.bcc.is_empty() {
- // Create new query for bccs
- let bccs_query = should_wildcard_field_query_builder("bcc", &self.bcc);
- bool_query.filter(bccs_query);
- }
+ if !self.sender.is_empty() {
+ // Create new query for senders
+ let senders_query = should_wildcard_field_query_builder("sender", &self.sender);
+ content_bool_query.filter(senders_query);
+ }
- if !self.recipients.is_empty() {
- // Create new query for recipients
- let recipients_query =
- should_wildcard_field_query_builder("recipients", &self.recipients);
- bool_query.filter(recipients_query);
- }
+ if !self.cc.is_empty() {
+ let ccs_query = should_wildcard_field_query_builder("cc", &self.cc);
+ content_bool_query.filter(ccs_query);
+ }
- content_and_name_bool_queries.content_bool_query = Some(bool_query);
+ if !self.bcc.is_empty() {
+ // Create new query for bccs
+ let bccs_query = should_wildcard_field_query_builder("bcc", &self.bcc);
+ content_bool_query.filter(bccs_query);
}
+ if !self.recipients.is_empty() {
+ // Create new query for recipients
+ let recipients_query =
+ should_wildcard_field_query_builder("recipients", &self.recipients);
+ content_bool_query.filter(recipients_query);
+ }
// END CUSTOM ATTRIBUTES SECTION
- let bool_query = self.inner.build_bool_query(content_and_name_bool_queries)?;
- Ok(bool_query)
+
+ Ok(content_bool_query)
}
fn build_search_request<'a>(&'a self) -> Result<SearchRequest<'a>> {
@@ -246,18 +235,14 @@ pub(crate) async fn search_emails(
client: &opensearch::OpenSearch,
args: EmailSearchArgs,
) -> Result<Vec<SearchHit>> {
- let indices = match args.search_on {
- SearchOn::Content => vec![SearchIndex::Emails.as_ref()],
- SearchOn::NameContent => vec![SearchIndex::Emails.as_ref(), SearchIndex::Names.as_ref()],
- SearchOn::Name => vec![SearchIndex::Names.as_ref()],
- };
-
let query_body = args.build()?;
tracing::trace!("query: {}", query_body);
let response = client
- .search(opensearch::SearchParts::Index(&indices))
+ .search(opensearch::SearchParts::Index(&[
+ SearchIndex::Emails.as_ref()
+ ]))
.body(query_body)
.send()
.await
diff --git a/rust/cloud-storage/opensearch_client/src/search/mod.rs b/rust/cloud-storage/opensearch_client/src/search/mod.rs
index f8b184883a..8cbcb574ab 100644
--- a/rust/cloud-storage/opensearch_client/src/search/mod.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/mod.rs
@@ -4,7 +4,6 @@ pub mod chats;
pub mod documents;
pub mod emails;
pub mod model;
-pub mod projects;
mod query;
pub mod unified;
mod utils;
diff --git a/rust/cloud-storage/opensearch_client/src/search/projects.rs b/rust/cloud-storage/opensearch_client/src/search/projects.rs
deleted file mode 100644
index 8f98015901..0000000000
--- a/rust/cloud-storage/opensearch_client/src/search/projects.rs
+++ /dev/null
@@ -1,184 +0,0 @@
-use crate::{
- Result, delegate_methods,
- error::{OpensearchClientError, ResponseExt},
- search::{
- builder::{SearchQueryBuilder, SearchQueryConfig},
- model::{MacroEm, SearchHit, SearchResponse, parse_highlight_hit},
- query::Keys,
- },
-};
-
-use crate::SearchOn;
-use models_opensearch::{SearchEntityType, SearchIndex};
-use opensearch_query_builder::{BoolQueryBuilder, HighlightField, SearchRequest, ToOpenSearchJson};
-use serde::{Deserialize, Serialize};
-use serde_json::Value;
-
-#[derive(Clone, Default)]
-pub(crate) struct ProjectSearchConfig;
-
-impl SearchQueryConfig for ProjectSearchConfig {
- const USER_ID_KEY: &'static str = "user_id";
- const TITLE_KEY: &'static str = "project_name";
- const ENTITY_INDEX: SearchEntityType = SearchEntityType::Projects;
-
- // Projects have no "content" to highlight match on, so match on the TITLE_KEY instead
- fn default_highlight<'a>() -> opensearch_query_builder::Highlight<'a> {
- opensearch_query_builder::Highlight::new()
- .require_field_match(true)
- .field(
- // we know the title key exists because it's implemented right above
- Self::TITLE_KEY,
- HighlightField::new()
- .highlight_type("plain")
- .number_of_fragments(1)
- .pre_tags(vec![MacroEm::Open.to_string()])
- .post_tags(vec![MacroEm::Close.to_string()]),
- )
- }
-}
-
-#[derive(Default)]
-pub(crate) struct ProjectQueryBuilder {
- inner: SearchQueryBuilder<ProjectSearchConfig>,
-}
-
-impl ProjectQueryBuilder {
- pub fn new(terms: Vec<String>) -> Self {
- Self {
- inner: SearchQueryBuilder::new(terms),
- }
- }
-
- // Copy function signature from SearchQueryBuilder
- delegate_methods! {
- fn match_type(match_type: &str) -> Self;
- fn page(page: u32) -> Self;
- fn page_size(page_size: u32) -> Self;
- fn user_id(user_id: &str) -> Self;
- fn search_on(search_on: SearchOn) -> Self;
- fn collapse(collapse: bool) -> Self;
- fn ids(ids: Vec<String>) -> Self;
- fn ids_only(ids_only: bool) -> Self;
- fn disable_recency(disable_recency: bool) -> Self;
- }
-
- pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
- self.inner
- .build_bool_query(self.inner.build_content_and_name_bool_query()?)
- }
-
- fn build_search_request<'a>(&'a self) -> Result<SearchRequest<'a>> {
- // Build the search request with the bool query
- // This will automatically wrap the bool query in a function score if
- // SearchOn::NameContent is used
- let search_request = self
- .inner
- .build_search_request(self.build_bool_query()?.build())?;
-
- Ok(search_request)
- }
-}
-
-#[derive(Debug, Serialize, Deserialize)]
-pub struct ProjectIndex {
- pub entity_id: uuid::Uuid,
- pub user_id: String,
- pub parent_project_id: Option<uuid::Uuid>,
- pub project_name: String,
-}
-
-#[derive(Debug, Default)]
-pub struct ProjectSearchArgs {
- pub terms: Vec<String>,
- pub user_id: String,
- pub page: u32,
- pub page_size: u32,
- pub match_type: String,
- pub project_ids: Vec<String>,
- pub search_on: SearchOn,
- pub collapse: bool,
- pub ids_only: bool,
- pub disable_recency: bool,
-}
-
-impl From<ProjectSearchArgs> for ProjectQueryBuilder {
- fn from(args: ProjectSearchArgs) -> Self {
- ProjectQueryBuilder::new(args.terms)
- .match_type(&args.match_type)
- .page_size(args.page_size)
- .page(args.page)
- .user_id(&args.user_id)
- .search_on(args.search_on)
- .collapse(args.collapse)
- .ids(args.project_ids)
- .ids_only(args.ids_only)
- .disable_recency(args.disable_recency)
- }
-}
-
-impl ProjectSearchArgs {
- pub fn build(self) -> Result<Value> {
- let builder: ProjectQueryBuilder = self.into();
- Ok(builder.build_search_request()?.to_json())
- }
-}
-
-#[tracing::instrument(skip(client, args), err)]
-pub(crate) async fn search_projects(
- client: &opensearch::OpenSearch,
- args: ProjectSearchArgs,
-) -> Result<Vec<SearchHit>> {
- let query_body = args.build()?;
-
- let response = client
- .search(opensearch::SearchParts::Index(&[
- SearchIndex::Projects.as_ref()
- ]))
- .body(query_body)
- .send()
- .await
- .map_client_error()
- .await?;
-
- let bytes = response
- .bytes()
- .await
- .map_err(|e| OpensearchClientError::HttpBytesError {
- details: e.to_string(),
- })?;
-
- let result: SearchResponse<ProjectIndex> = serde_json::from_slice(&bytes).map_err(|e| {
- OpensearchClientError::SearchDeserializationFailed {
- details: e.to_string(),
- raw_body: String::from_utf8_lossy(&bytes).to_string(),
- }
- })?;
-
- Ok(result
- .hits
- .hits
- .into_iter()
- .map(|hit| SearchHit {
- entity_id: hit.source.entity_id,
- entity_type: SearchEntityType::Projects,
- score: hit.score,
- highlight: hit
- .highlight
- .map(|h| {
- parse_highlight_hit(
- h,
- Keys {
- title_key: ProjectSearchConfig::TITLE_KEY,
- content_key: ProjectSearchConfig::CONTENT_KEY,
- },
- )
- })
- .unwrap_or_default(),
- goto: None,
- })
- .collect())
-}
-
-#[cfg(test)]
-mod test;
diff --git a/rust/cloud-storage/opensearch_client/src/search/projects/test.rs b/rust/cloud-storage/opensearch_client/src/search/projects/test.rs
deleted file mode 100644
index d897931ab3..0000000000
--- a/rust/cloud-storage/opensearch_client/src/search/projects/test.rs
+++ /dev/null
@@ -1,65 +0,0 @@
-use super::*;
-use opensearch_query_builder::ToOpenSearchJson;
-
-#[test]
-fn test_build_search_request() -> anyhow::Result<()> {
- let builder = ProjectQueryBuilder::new(vec!["test".to_string()])
- .match_type("exact")
- .page_size(20)
- .page(1)
- .user_id("user123")
- .search_on(SearchOn::Name)
- .collapse(true)
- .ids(vec!["proj1".to_string(), "proj2".to_string()]);
-
- let result = builder.build_search_request()?;
-
- let expected = serde_json::json!({
- "from": 20,
- "size": 20,
- "collapse": {
- "field": "entity_id"
- },
- "sort": ProjectSearchConfig::default_sort_types().iter().map(|s| s.to_json()).collect::<Vec<_>>(),
- "highlight": ProjectSearchConfig::append_owner_highlights(ProjectSearchConfig::default_highlight()).to_json(),
- "query": {
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "terms": {
- "entity_id": ["proj1", "proj2"]
- }
- },
- {
- "term": {
- "user_id": "user123"
- }
- }
- ]
- }
- },
- {
- "term": {
- "_index": "projects"
- }
- }
- ],
- "must": [
- {
- "match_phrase": {
- "project_name": "test"
- }
- }
- ]
- }
- },
- });
-
- assert_eq!(result.to_json(), expected);
-
- Ok(())
-}
diff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rs
index c1380bd16c..34ddd42018 100644
--- a/rust/cloud-storage/opensearch_client/src/search/unified.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs
@@ -1,186 +1,17 @@
-use std::collections::HashSet;
-
-use crate::{
- Result,
- error::{OpensearchClientError, ResponseExt},
- search::{
- builder::{SearchQueryConfig, create_highlight_field, updated_at_sort},
- channels::{
- ChannelMessageIndex, ChannelMessageQueryBuilder, ChannelMessageSearchArgs,
- ChannelMessageSearchConfig,
- },
- chats::{ChatIndex, ChatQueryBuilder, ChatSearchArgs, ChatSearchConfig},
- documents::{
- DocumentIndex, DocumentQueryBuilder, DocumentSearchArgs, DocumentSearchConfig,
- },
- emails::{EmailIndex, EmailQueryBuilder, EmailSearchArgs, EmailSearchConfig},
- model::{
- DefaultSearchResponse, Hit, MacroEm, NameIndex, SearchGotoChannel, SearchGotoChat,
- SearchGotoContent, SearchGotoDocument, SearchGotoEmail, SearchHit, parse_highlight_hit,
- },
- projects::{ProjectIndex, ProjectQueryBuilder, ProjectSearchArgs, ProjectSearchConfig},
- query::Keys,
+use crate::search::{
+ builder::SearchQueryConfig,
+ channels::{ChannelMessageIndex, ChannelMessageSearchConfig},
+ chats::{ChatIndex, ChatSearchConfig},
+ documents::{DocumentIndex, DocumentSearchConfig},
+ emails::{EmailIndex, EmailSearchConfig},
+ model::{
+ Hit, NameIndex, SearchGotoChannel, SearchGotoChat, SearchGotoContent, SearchGotoDocument,
+ SearchGotoEmail, SearchHit, parse_highlight_hit,
},
+ query::Keys,
};
-use crate::SearchOn;
-use models_opensearch::{SearchEntityType, SearchIndex};
-use opensearch_query_builder::*;
-
-#[derive(Debug, Default, Clone)]
-pub struct UnifiedSearchArgs {
- pub terms: Vec<String>,
- pub user_id: String,
- pub page: u32,
- pub page_size: u32,
- pub match_type: String,
- pub search_on: SearchOn,
- pub collapse: bool,
- pub disable_recency: bool,
- /// The indices to search over
- pub search_indices: HashSet<SearchEntityType>,
- /// The document search args
- pub document_search_args: UnifiedDocumentSearchArgs,
- /// The email search args. If None, we do not search emails
- pub email_search_args: UnifiedEmailSearchArgs,
- /// The channel message search args. If None, we do not search channel messages
- pub channel_message_search_args: UnifiedChannelMessageSearchArgs,
- /// The chat search args. If None, we do not search chats
- pub chat_search_args: UnifiedChatSearchArgs,
- /// The project search args. If None, we do not search projects
- pub project_search_args: UnifiedProjectSearchArgs,
-}
-
-impl From<UnifiedSearchArgs> for DocumentSearchArgs {
- fn from(args: UnifiedSearchArgs) -> Self {
- DocumentSearchArgs {
- terms: args.terms,
- user_id: args.user_id,
- page: args.page,
- page_size: args.page_size,
- match_type: args.match_type,
- search_on: args.search_on,
- collapse: args.collapse,
- disable_recency: args.disable_recency,
- ids_only: args.document_search_args.ids_only,
- document_ids: args.document_search_args.document_ids,
- }
- }
-}
-
-impl From<UnifiedSearchArgs> for EmailSearchArgs {
- fn from(args: UnifiedSearchArgs) -> Self {
- EmailSearchArgs {
- terms: args.terms,
- user_id: args.user_id,
- page: args.page,
- page_size: args.page_size,
- match_type: args.match_type,
- search_on: args.search_on,
- collapse: args.collapse,
- ids_only: false, // Email is never ids only at the moment
- disable_recency: args.disable_recency,
- thread_ids: args.email_search_args.thread_ids,
- link_ids: args.email_search_args.link_ids,
- sender: args.email_search_args.sender,
- cc: args.email_search_args.cc,
- bcc: args.email_search_args.bcc,
- recipients: args.email_search_args.recipients,
- }
- }
-}
-
-impl From<UnifiedSearchArgs> for ChannelMessageSearchArgs {
- fn from(args: UnifiedSearchArgs) -> Self {
- ChannelMessageSearchArgs {
- terms: args.terms,
- user_id: args.user_id,
- page: args.page,
- page_size: args.page_size,
- match_type: args.match_type,
- search_on: args.search_on,
- collapse: args.collapse,
- ids_only: true, // channel messages are always ids only
- disable_recency: args.disable_recency,
- channel_ids: args.channel_message_search_args.channel_ids,
- thread_ids: args.channel_message_search_args.thread_ids,
- mentions: args.channel_message_search_args.mentions,
- sender_ids: args.channel_message_search_args.sender_ids,
- }
- }
-}
-
-impl From<UnifiedSearchArgs> for ChatSearchArgs {
- fn from(args: UnifiedSearchArgs) -> Self {
- ChatSearchArgs {
- terms: args.terms,
- user_id: args.user_id,
- page: args.page,
- page_size: args.page_size,
- match_type: args.match_type,
- search_on: args.search_on,
- collapse: args.collapse,
- disable_recency: args.disable_recency,
- ids_only: args.chat_search_args.ids_only,
- chat_ids: args.chat_search_args.chat_ids,
- role: args.chat_search_args.role,
- }
- }
-}
-
-impl From<UnifiedSearchArgs> for ProjectSearchArgs {
- fn from(args: UnifiedSearchArgs) -> Self {
- ProjectSearchArgs {
- terms: args.terms,
- user_id: args.user_id,
- page: args.page,
- page_size: args.page_size,
- match_type: args.match_type,
- search_on: args.search_on,
- collapse: args.collapse,
- disable_recency: args.disable_recency,
- ids_only: args.project_search_args.ids_only,
- project_ids: args.project_search_args.project_ids,
- }
- }
-}
-
-#[derive(Debug, Default, Clone)]
-pub struct UnifiedChatSearchArgs {
- pub chat_ids: Vec<String>,
- pub role: Vec<String>,
- pub ids_only: bool,
-}
-
-#[derive(Debug, Default, Clone)]
-pub struct UnifiedDocumentSearchArgs {
- pub document_ids: Vec<String>,
- pub ids_only: bool,
-}
-
-#[derive(Debug, Default, Clone)]
-pub struct UnifiedEmailSearchArgs {
- pub thread_ids: Vec<String>,
- pub link_ids: Vec<String>,
- pub sender: Vec<String>,
- pub cc: Vec<String>,
- pub bcc: Vec<String>,
- pub recipients: Vec<String>,
-}
-
-#[derive(Debug, Default, Clone)]
-pub struct UnifiedProjectSearchArgs {
- pub project_ids: Vec<String>,
- pub ids_only: bool,
-}
-
-#[derive(Debug, Default, Clone)]
-pub struct UnifiedChannelMessageSearchArgs {
- pub channel_ids: Vec<String>,
- pub thread_ids: Vec<String>,
- pub mentions: Vec<String>,
- pub sender_ids: Vec<String>,
-}
+use models_opensearch::SearchEntityType;
/// Possible search result indices for unified search
#[derive(Debug, serde::Serialize, serde::Deserialize)]
@@ -190,7 +21,6 @@ pub(crate) enum UnifiedSearchIndex {
Document(DocumentIndex),
Chat(ChatIndex),
Email(EmailIndex),
- Project(ProjectIndex),
Name(NameIndex),
}
@@ -319,24 +149,7 @@ impl From<Hit<UnifiedSearchIndex>> for SearchHit {
recipients: a.recipients,
})),
},
- UnifiedSearchIndex::Project(a) => SearchHit {
- entity_id: a.entity_id,
- entity_type: SearchEntityType::Projects,
- score: index.score,
- highlight: index
- .highlight
- .map(|h| {
- parse_highlight_hit(
- h,
- Keys {
- title_key: ProjectSearchConfig::TITLE_KEY,
- content_key: ProjectSearchConfig::CONTENT_KEY,
- },
- )
- })
- .unwrap_or_default(),
- goto: None,
- },
+
UnifiedSearchIndex::Chat(a) => SearchHit {
entity_id: a.entity_id,
entity_type: SearchEntityType::Chats,
@@ -379,217 +192,3 @@ impl From<Hit<UnifiedSearchIndex>> for SearchHit {
}
}
}
-
-#[tracing::instrument(skip(args), err)]
-fn build_unified_search_request(args: &UnifiedSearchArgs) -> Result<SearchRequest<'static>> {
- if args.search_indices.is_empty() {
- return Err(OpensearchClientError::EmptySearchIndices);
- }
- // Build out the title keys that we could need for highlighting
- let mut title_keys: HashSet<&'static str> = HashSet::new();
- for index in &args.search_indices {
- match index {
- SearchEntityType::Channels => title_keys.insert(ChannelMessageSearchConfig::TITLE_KEY),
- SearchEntityType::Chats => title_keys.insert(ChatSearchConfig::TITLE_KEY),
- SearchEntityType::Documents => title_keys.insert(DocumentSearchConfig::TITLE_KEY),
- SearchEntityType::Emails => title_keys.insert(EmailSearchConfig::TITLE_KEY),
- SearchEntityType::Projects => title_keys.insert(ProjectSearchConfig::TITLE_KEY),
- };
- }
-
- let title_keys: Vec<&'static str> = title_keys.into_iter().collect();
-
- let mut bool_query = BoolQueryBuilder::new();
-
- // There will always be 1 query as the indices are never empty
- bool_query.minimum_should_match(1);
-
- if args.search_indices.contains(&SearchEntityType::Documents) {
- let document_search_args: DocumentSearchArgs = args.clone().into();
- let document_query_builder: DocumentQueryBuilder = document_search_args.into();
- let document_bool_query = document_query_builder.build_bool_query()?;
- let query_type: QueryType = document_bool_query.build().into();
- bool_query.should(query_type.to_owned());
- }
-
- if args.search_indices.contains(&SearchEntityType::Emails) {
- let email_search_args: EmailSearchArgs = args.clone().into();
- let email_query_builder: EmailQueryBuilder = email_search_args.into();
- let email_bool_query = email_query_builder.build_bool_query()?;
- let query_type: QueryType = email_bool_query.build().into();
- bool_query.should(query_type.to_owned());
- }
-
- // We can only search over channels if we are not explicitly searching by name
- if args.search_indices.contains(&SearchEntityType::Channels) && args.search_on != SearchOn::Name
- {
- let channel_message_search_args: ChannelMessageSearchArgs = args.clone().into();
- let channel_message_query_builder: ChannelMessageQueryBuilder =
- channel_message_search_args.into();
- let channel_message_bool_query = channel_message_query_builder.build_bool_query()?;
- let query_type: QueryType = channel_message_bool_query.build().into();
- bool_query.should(query_type.to_owned());
- }
-
- if args.search_indices.contains(&SearchEntityType::Chats) {
- let chat_search_args: ChatSearchArgs = args.clone().into();
- let chat_query_builder: ChatQueryBuilder = chat_search_args.into();
- let chat_bool_query = chat_query_builder.build_bool_query()?;
- let query_type: QueryType = chat_bool_query.build().into();
- bool_query.should(query_type.to_owned());
- }
-
- if args.search_indices.contains(&SearchEntityType::Projects)
- && args.search_on != SearchOn::Content
- {
- let project_search_args: ProjectSearchArgs = args.clone().into();
- let project_query_builder: ProjectQueryBuilder = project_search_args.into();
- let project_bool_query = project_query_builder.build_bool_query()?;
- let query_type: QueryType = project_bool_query.build().into();
- bool_query.should(query_type.to_owned());
- }
-
- // create the search request
- let mut search_request_builder = SearchRequestBuilder::new();
-
- search_request_builder.from(args.page * args.page_size);
- search_request_builder.size(args.page_size);
-
- if args.collapse {
- search_request_builder.collapse(Collapse::new("entity_id"));
- }
-
- // Build sort
- let sort = updated_at_sort();
-
- for sort in sort {
- search_request_builder.add_sort(sort);
- }
-
- // Build highlight
- let mut highlight = match args.search_on {
- SearchOn::Content => Highlight::new().require_field_match(true).field(
- "content",
- HighlightField::new()
- .highlight_type("plain")
- .pre_tags(vec![MacroEm::Open.to_string()])
- .post_tags(vec![MacroEm::Close.to_string()])
- .number_of_fragments(500),
- ),
- SearchOn::Name => {
- let mut highlight = Highlight::new();
-
- highlight = highlight.require_field_match(true);
-
- for field in title_keys {
- highlight = highlight.field(
- field,
- HighlightField::new()
- .highlight_type("plain")
- .pre_tags(vec![MacroEm::Open.to_string()])
- .post_tags(vec![MacroEm::Close.to_string()])
- .number_of_fragments(1),
- );
- }
- highlight
- }
- SearchOn::NameContent => {
- let mut highlight = Highlight::new();
-
- highlight = highlight.require_field_match(false);
-
- for field in title_keys {
- highlight = highlight.field(
- field,
- HighlightField::new()
- .highlight_type("plain")
- .pre_tags(vec![MacroEm::Open.to_string()])
- .post_tags(vec![MacroEm::Close.to_string()])
- .number_of_fragments(1),
- );
- }
-
- highlight = highlight.field(
- "content",
- HighlightField::new()
- .highlight_type("plain")
- .pre_tags(vec![MacroEm::Open.to_string()])
- .post_tags(vec![MacroEm::Close.to_string()])
- .number_of_fragments(1),
- );
-
- highlight
- }
- };
-
- // For content and name content search, we need to add in highlights for the owner
- // fields
- match args.search_on {
- SearchOn::Content | SearchOn::NameContent => {
- // Commenting out for now as it's causing highlights on the user_id of filter matches
- // Need to think of a different way to surface the owner matches
- // highlight = highlight.field("user_id", create_highlight_field("plain", 1));
- // highlight = highlight.field("owner_id", create_highlight_field("plain", 1));
- highlight = highlight.field("sender", create_highlight_field("plain", 1));
- highlight = highlight.field("recipients", create_highlight_field("plain", 1));
- highlight = highlight.field("cc", create_highlight_field("plain", 1));
- highlight = highlight.field("bcc", create_highlight_field("plain", 1));
- }
- SearchOn::Name => {}
- }
-
- search_request_builder.highlight(highlight);
-
- let query_object = bool_query.build();
-
- let built_query: QueryType = query_object.into();
-
- search_request_builder.query(built_query);
-
- Ok(search_request_builder.build())
-}
-
-#[tracing::instrument(skip(client, args), err)]
-pub(crate) async fn search_unified(
- client: &opensearch::OpenSearch,
- args: UnifiedSearchArgs,
-) -> Result<Vec<SearchHit>> {
- let search_request = build_unified_search_request(&args)?.to_json();
-
- tracing::trace!("search request {:?}", search_request);
-
- let mut search_indices: Vec<&str> = args.search_indices.iter().map(|i| i.as_ref()).collect();
-
- match args.search_on {
- SearchOn::NameContent | SearchOn::Name => {
- search_indices.push(SearchIndex::Names.as_ref());
- }
- SearchOn::Content => {}
- }
-
- let response = client
- .search(opensearch::SearchParts::Index(&search_indices))
- .body(search_request)
- .send()
- .await
- .map_client_error()
- .await?;
-
- let bytes = response
- .bytes()
- .await
- .map_err(|e| OpensearchClientError::HttpBytesError {
- details: e.to_string(),
- })?;
-
- let result: DefaultSearchResponse<UnifiedSearchIndex> = serde_json::from_slice(&bytes)
- .map_err(|e| OpensearchClientError::SearchDeserializationFailed {
- details: e.to_string(),
- raw_body: String::from_utf8_lossy(&bytes).to_string(),
- })?;
-
- Ok(result.hits.hits.into_iter().map(|h| h.into()).collect())
-}
-
-#[cfg(test)]
-mod test;
diff --git a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
deleted file mode 100644
index fef3802d4c..0000000000
--- a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
+++ /dev/null
@@ -1,2002 +0,0 @@
-use super::*;
-
-use opensearch_query_builder::ToOpenSearchJson;
-
-#[test]
-fn test_deserialization() -> anyhow::Result<()> {
- let json = serde_json::json!({
- "took": 20,
- "timed_out": false,
- "_shards": {
- "total": 15,
- "successful": 15,
- "skipped": 0,
- "failed": 0
- },
- "hits": {
- "total": {
- "value": 739,
- "relation": "eq"
- },
- "max_score": 27.399992,
- "hits": [
- {
- "_index": "emails",
- "_id": "019a5a07-a1ed-7342-93a7-861582b59a55:019a5a07-b09d-7af9-b6ce-98bced9353d2",
- "_score": 27.399992,
- "_source": {
- "cc": [
- ],
- "bcc": [],
- "subject": "[macro-inc/macro-api] chore: improve ws api gateway authorizer lambda (PR #2520)",
- "message_id": "019a5a07-b09d-7af9-b6ce-98bced9353d2",
- "entity_id": "019a5a07-a1ed-7342-93a7-861582b59a55",
- "link_id": "01976c0a-7554-719c-a2fc-d4dcf7e8a8bf",
- "content": "## Summary\ntype safety + better deny policy\n## Screenshots, GIFs, and Videos\n## Checklist\n* Included (`MACRO-N`) in the PR title.\n* QA'd\nTests for PR (pick one):\n* N/A\n* 🤖 Automated\n#### You can view, comment on, or merge this pull request online at:\nhttps://github.com/macro-inc/macro-api/pull/2520\n#### Commit Summary\n* 20b26f7 update\n* f39426a make it TS\n#### File Changes\n(6 files)\n* **A** websocket/handlers/authorization-handler/.gitignore (5)\n* **D** websocket/handlers/authorization-handler/index.js (105)\n* **A** websocket/handlers/authorization-handler/index.ts (159)\n* **M** websocket/handlers/authorization-handler/package.json (10)\n* **A** websocket/handlers/authorization-handler/tsconfig.json (18)\n* **M** websocket/infra/index.ts (65)\n#### Patch Links:\n* https://github.com/macro-inc/macro-api/pull/2520.patch\n* https://github.com/macro-inc/macro-api/pull/2520.diff\n—\nReply to this email directly, view it on GitHub, or unsubscribe.\nYou are receiving this because your review was requested.Message ID: <macro-inc/macro-api/pull/[email protected]>",
- "labels": [
- "github",
- "CATEGORY_PERSONAL",
- "UNREAD",
- "IMPORTANT"
- ],
- "thread_id": "019a5a07-a1ed-7342-93a7-861582b59a55",
- "sent_at_seconds": 1762447040,
- "sender": "[email protected]",
- "user_id": "macro|[email protected]",
- "updated_at_seconds": 1762447044,
- "recipients": [
- ]
- },
- "highlight": {
- "content": [
- ":\n* N/A\n* 🤖 Automated\n#### You can view, comment on, or merge this pull request online at:\nhttps://<macro_em>github.com</macro_em>",
- "* f39426a make it TS\n#### File Changes\n(6 files)\n* **A** websocket/handlers/authorization-handler/.<macro_em>gitignore</macro_em>",
- "authorization-handler/tsconfig.json (18)\n* **M** websocket/infra/index.ts (65)\n#### Patch Links:\n* https://<macro_em>github.com</macro_em>",
- "/macro-inc/macro-api/pull/2520.patch\n* https://<macro_em>github.com</macro_em>/macro-inc/macro-api/pull/2520.diff\n—\nReply",
- "to this email directly, view it on <macro_em>GitHub</macro_em>, or unsubscribe.",
- "You are receiving this because your review was requested.Message ID: <macro-inc/macro-api/pull/2520@<macro_em>github.com</macro_em>"
- ]
- }
- },
- {
- "_index": "emails",
- "_id": "01999c74-fb30-7c8a-b334-16035ee46783:01999c75-1c32-7cf4-a168-7741881ceec3",
- "_score": 22.173065,
- "_source": {
- "cc": [],
- "bcc": [],
- "subject": "From IaC to AI Platform Engineering: Insights You Can’t Afford to Miss",
- "message_id": "01999c75-1c32-7cf4-a168-7741881ceec3",
- "entity_id": "01999c74-fb30-7c8a-b334-16035ee46783",
- "link_id": "01976c0a-7554-719c-a2fc-d4dcf7e8a8bf",
- "content": "Learn, connect, and explore the future of IaC, platform engineering, DevOps, and AI.\n pulumi email banner \nHi Will,\nPulumi is on the move, bringing together communities of builders who are pushing the boundaries of Platform Engineering and DevOps with AI.\nThis is where new ideas surface, best practices are shared first, and the conversations shaping tomorrow’s infrastructure are happening now. Don't miss your chance to be part of it!\n### Pulumi User Groups (PUG) Meetups\nOct 1 São Paulo, BR Sao Paulo PUG: Evento de Lançamento - Do IaC ao Platform Engineering \nOct 9 Copenhagen, DK PUG In-Person Meetup Nº 1: Discover AI in a DevOps World\nOct 22 London, UK PUG In-Person Meetup Nº 3: Building Better Platforms with Pulumi IDP\nOct 29 Tel Aviv, IL In-Person Meetup Nº 2: Platform Engineering and DevOps in the Age of AI \n### Events & Conferences\nOct 8 Copenhagen, DK Join Engin Diri, Senior Solutions Architect at Pulumi, for his talk on GitOps Promotion Tools to add to your GitOps Toolkit in 2025. \nOct 17 Santa Monica, CA AWS MCP Hackathon\nOct 27–29 San Francisco, CA TechCrunch Disrupt\nOct 29 Bellevue, WA MCP Academy\nWe hope to see you soon!\nHappy building,\nThe Pulumi Team\n ai-workshop-series-banner \n cloud-red \nTry Pulumi\n docs \nView Docs\ntwitter GitHub-Mark-120px-plus linkedin youtube-play slack-2 \n© 2025 Pulumi. All rights reserved.\nPulumi Corporation, Two Union Square, 601 Union St, Pulumi Suite 1415, Seattle, WA 98101\nUnsubscribe Manage preferences",
- "labels": [
- "INBOX",
- "CATEGORY_PROMOTIONS"
- ],
- "sent_at": 1759241406,
- "thread_id": "01999c74-fb30-7c8a-b334-16035ee46783",
- "updated_at": 1759266586,
- "sent_at_seconds": 1759241406,
- "sender": "[email protected]",
- "user_id": "macro|[email protected]",
- "updated_at_seconds": 1759266586,
- "recipients": [
- ]
- },
- "highlight": {
- "content": [
- "Oct 8 Copenhagen, DK Join Engin Diri, Senior Solutions Architect at Pulumi, for his talk on <macro_em>GitOps</macro_em>",
- "Promotion Tools to add to your <macro_em>GitOps</macro_em> Toolkit in 2025.",
- "The Pulumi Team\n ai-workshop-series-banner \n cloud-red \nTry Pulumi\n docs \nView Docs\ntwitter <macro_em>GitHub</macro_em>-Mark"
- ]
- }
- },
- {
- "_index": "documents",
- "_id": "013021c7-5e14-4aab-855e-01413fff85dc:77",
- "_score": 18.047625,
- "_source": {
- "document_name": "Rust for Rustaceans Idiomatic Programming for Experienced Developers (1)",
- "updated_at": 1752523635,
- "updated_at_seconds": 1752523635,
- "file_type": "pdf",
- "owner_id": "macro|[email protected]",
- "document_id": "013021c7-5e14-4aab-855e-01413fff85dc",
- "document_version_id": 10091,
- "entity_id": "013021c7-5e14-4aab-855e-01413fff85dc",
- "content": "74   Chapter 6\r\n[patch.crates-io]\r\n# use a local (presumably modified) source\r\nregex = { path = \"/home/jon/regex\" }\r\n# use a modification on a git branch\r\nserde = { git = \"https://github.com/serde-rs/serde.git\", branch = \"faster\" }\r\n# patch a git dependency\r\n[patch.'https://github.com/jonhoo/project.git']\r\nproject = { path = \"/home/jon/project\" }\r\nListing 6-6: Overriding dependency sources in Cargo.toml using [patch]\r\nEven if you patch a dependency, Cargo takes care to check the crate \r\nversions so that you don’t accidentally end up patching the wrong major version of a crate. If you for some reason transitively depend on multiple major \r\nversions of the same crate, you can patch each one by giving them distinct \r\nidentifiers, as shown in Listing 6-7.\r\n[patch.crates-io]\r\nnom4 = { path = \"/home/jon/nom4\", package = \"nom\" }\r\nnom5 = { path = \"/home/jon/nom5\", package = \"nom\" }\r\nListing 6-7: Overriding multiple versions of the same crate in Cargo.toml using [patch]\r\nCargo will look at the Cargo.toml inside each path, realize that /nom4\r\ncontains major version 4 and that /nom5 contains major version 5, and patch \r\nthe two versions appropriately. The package keyword tells Cargo to look for a \r\ncrate by the name nom in both cases instead of using the dependency identifiers (the part on the left) as it does by default. You can use package this way \r\nin your regular dependencies as well to rename a dependency!\r\nKeep in mind that patches are not taken into account in the package \r\nthat’s uploaded when you publish a crate. A crate that depends on your \r\ncrate will use only its own [patch] section (which may be empty), not that of \r\nyour crate!\r\nCR ATES VS. PACKAGES\r\nYou may wonder what the difference between a package and a crate is. \r\nThese two terms are often used interchangeably in informal contexts, but they \r\nalso have specific definitions that vary depending on whether you’re talking \r\nabout the Rust compiler, Cargo, crates.io, or something else. I personally think \r\nof a crate as a Rust module hierarchy starting at a root .rs file (one where you \r\ncan use crate-level attributes like #![feature])—usually something like lib.rs or \r\nmain.rs. In contrast, a package is a collection of crates and metadata, so essentially all that’s described by a Cargo.toml file. That may include a library crate, \r\nmultiple binary crates, some integration test crates, and maybe even multiple \r\nworkspace members that themselves have Cargo.toml files.\r\nIntermediate Rust (Early Access) © 2022 by Jon Gjengset ",
- "node_id": "77"
- },
- "highlight": {
- "content": [
- "local (presumably modified) source\r\nregex = { path = \"/home/jon/regex\" }\r\n# use a modification on a <macro_em>git</macro_em>",
- "branch\r\nserde = { <macro_em>git</macro_em> = \"https://<macro_em>github.com</macro_em>/serde-rs/serde.git\", branch = \"faster\" }\r\n# patch a <macro_em>git</macro_em>",
- "https://<macro_em>github.com</macro_em>/jonhoo/project.git']\r\nproject = { path = \"/home/jon/project\" }\r\nListing 6-6: Overriding"
- ]
- }
- },
- {
- "_index": "emails",
- "_id": "019a3002-d9ff-79ad-9a5f-c3116b5b229a:019a3002-da01-71aa-aed0-3d699723ba58",
- "_score": 17.734608,
- "_source": {
- "cc": [],
- "bcc": [],
- "subject": "[GitHub] A personal access token (classic) has been regenerated for your account",
- "message_id": "019a3002-da01-71aa-aed0-3d699723ba58",
- "entity_id": "019a3002-d9ff-79ad-9a5f-c3116b5b229a",
- "link_id": "01976c0a-7554-719c-a2fc-d4dcf7e8a8bf",
- "content": "Hey whutchinson98!\r\n\r\nA personal access token (classic) \"zephyr\" with notifications scopes was recently regenerated for your account. Visit https://github.com/settings/tokens for more information.\r\n\r\nTo see this and other security events for your account, visit https://github.com/settings/security-log\r\n\r\nIf you run into problems, please contact support by visiting https://github.com/contact\r\n\r\nThanks,\r\nThe GitHub Team",
- "labels": [
- "INBOX",
- "CATEGORY_UPDATES",
- "UNREAD"
- ],
- "sent_at": 1761742081,
- "thread_id": "019a3002-d9ff-79ad-9a5f-c3116b5b229a",
- "updated_at": 1761742084,
- "sent_at_seconds": 1761742081,
- "sender": "[email protected]",
- "user_id": "macro|[email protected]",
- "updated_at_seconds": 1761742084,
- "recipients": [
- ]
- },
- "highlight": {
- "content": [
- "Visit https://<macro_em>github.com</macro_em>/settings/tokens for more information.",
- "To see this and other security events for your account, visit https://<macro_em>github.com</macro_em>/settings/security-log",
- "If you run into problems, please contact support by visiting https://<macro_em>github.com</macro_em>/contact\r\n\r\nThanks",
- ",\r\nThe <macro_em>GitHub</macro_em> Team"
- ]
- }
- },
- {
- "_index": "documents",
- "_id": "71ff8822-b421-4cab-b23e-f65355bf90d4:77",
- "_score": 17.689163,
- "_source": {
- "document_name": "Rust for Rustaceans Idiomatic Programming for Experienced Developers (1)",
- "updated_at": 1752522588,
- "updated_at_seconds": 1752522588,
- "file_type": "pdf",
- "owner_id": "macro|[email protected]",
- "document_id": "71ff8822-b421-4cab-b23e-f65355bf90d4",
- "document_version_id": 511386,
- "entity_id": "71ff8822-b421-4cab-b23e-f65355bf90d4",
- "content": "74   Chapter 6\r\n[patch.crates-io]\r\n# use a local (presumably modified) source\r\nregex = { path = \"/home/jon/regex\" }\r\n# use a modification on a git branch\r\nserde = { git = \"https://github.com/serde-rs/serde.git\", branch = \"faster\" }\r\n# patch a git dependency\r\n[patch.'https://github.com/jonhoo/project.git']\r\nproject = { path = \"/home/jon/project\" }\r\nListing 6-6: Overriding dependency sources in Cargo.toml using [patch]\r\nEven if you patch a dependency, Cargo takes care to check the crate \r\nversions so that you don’t accidentally end up patching the wrong major version of a crate. If you for some reason transitively depend on multiple major \r\nversions of the same crate, you can patch each one by giving them distinct \r\nidentifiers, as shown in Listing 6-7.\r\n[patch.crates-io]\r\nnom4 = { path = \"/home/jon/nom4\", package = \"nom\" }\r\nnom5 = { path = \"/home/jon/nom5\", package = \"nom\" }\r\nListing 6-7: Overriding multiple versions of the same crate in Cargo.toml using [patch]\r\nCargo will look at the Cargo.toml inside each path, realize that /nom4\r\ncontains major version 4 and that /nom5 contains major version 5, and patch \r\nthe two versions appropriately. The package keyword tells Cargo to look for a \r\ncrate by the name nom in both cases instead of using the dependency identifiers (the part on the left) as it does by default. You can use package this way \r\nin your regular dependencies as well to rename a dependency!\r\nKeep in mind that patches are not taken into account in the package \r\nthat’s uploaded when you publish a crate. A crate that depends on your \r\ncrate will use only its own [patch] section (which may be empty), not that of \r\nyour crate!\r\nCR ATES VS. PACKAGES\r\nYou may wonder what the difference between a package and a crate is. \r\nThese two terms are often used interchangeably in informal contexts, but they \r\nalso have specific definitions that vary depending on whether you’re talking \r\nabout the Rust compiler, Cargo, crates.io, or something else. I personally think \r\nof a crate as a Rust module hierarchy starting at a root .rs file (one where you \r\ncan use crate-level attributes like #![feature])—usually something like lib.rs or \r\nmain.rs. In contrast, a package is a collection of crates and metadata, so essentially all that’s described by a Cargo.toml file. That may include a library crate, \r\nmultiple binary crates, some integration test crates, and maybe even multiple \r\nworkspace members that themselves have Cargo.toml files.\r\nIntermediate Rust (Early Access) © 2022 by Jon Gjengset ",
- "node_id": "77"
- },
- "highlight": {
- "content": [
- "local (presumably modified) source\r\nregex = { path = \"/home/jon/regex\" }\r\n# use a modification on a <macro_em>git</macro_em>",
- "branch\r\nserde = { <macro_em>git</macro_em> = \"https://<macro_em>github.com</macro_em>/serde-rs/serde.git\", branch = \"faster\" }\r\n# patch a <macro_em>git</macro_em>",
- "https://<macro_em>github.com</macro_em>/jonhoo/project.git']\r\nproject = { path = \"/home/jon/project\" }\r\nListing 6-6: Overriding"
- ]
- }
- },
- {
- "_index": "emails",
- "_id": "019a1675-844c-7dcc-bd45-109c25b94fa0:019a1675-8467-7cb3-b57d-8c5c45d5b50c",
- "_score": 17.500538,
- "_source": {
- "cc": [
- ],
- "bcc": [],
- "subject": "[macro-inc/macro-api] fix table name in policy (PR #2425)",
- "message_id": "019a1675-8467-7cb3-b57d-8c5c45d5b50c",
- "entity_id": "019a1675-844c-7dcc-bd45-109c25b94fa0",
- "link_id": "01976c0a-7554-719c-a2fc-d4dcf7e8a8bf",
- "content": "#### You can view, comment on, or merge this pull request online at:\nhttps://github.com/macro-inc/macro-api/pull/2425\n#### Commit Summary\n* 624dc3f fix table name in policy\n#### File Changes\n(1 file)\n* **M** cloud-storage/infra/packages/resources/src/resources/frecency.ts (4)\n#### Patch Links:\n* https://github.com/macro-inc/macro-api/pull/2425.patch\n* https://github.com/macro-inc/macro-api/pull/2425.diff\n—\nReply to this email directly, view it on GitHub, or unsubscribe.\nYou are receiving this because your review was requested.Message ID: <macro-inc/macro-api/pull/[email protected]>",
- "labels": [
- "github",
- "CATEGORY_UPDATES",
- "UNREAD",
- "IMPORTANT"
- ],
- "sent_at": 1761313387,
- "thread_id": "019a1675-844c-7dcc-bd45-109c25b94fa0",
- "updated_at": 1761313391,
- "sent_at_seconds": 1761313387,
- "sender": "[email protected]",
- "user_id": "macro|[email protected]",
- "updated_at_seconds": 1761313391,
- "recipients": [
- ]
- },
- "highlight": {
- "content": [
- "#### You can view, comment on, or merge this pull request online at:\nhttps://<macro_em>github.com</macro_em>/macro-inc/macro-api",
- "** cloud-storage/infra/packages/resources/src/resources/frecency.ts (4)\n#### Patch Links:\n* https://<macro_em>github.com</macro_em>",
- "/macro-inc/macro-api/pull/2425.patch\n* https://<macro_em>github.com</macro_em>/macro-inc/macro-api/pull/2425.diff\n—\nReply",
- "to this email directly, view it on <macro_em>GitHub</macro_em>, or unsubscribe.",
- "You are receiving this because your review was requested.Message ID: <macro-inc/macro-api/pull/2425@<macro_em>github.com</macro_em>"
- ]
- }
- },
- {
- "_index": "emails",
- "_id": "019a3653-c914-769b-9454-3b70dc2ad966:019a3653-cd3b-7b24-9dd7-9090e7d30f65",
- "_score": 17.168581,
- "_source": {
- "cc": [
- ],
- "bcc": [],
- "subject": "[macro-inc/macro-api] Fix conn gateway var name (PR #2471)",
- "message_id": "019a3653-cd3b-7b24-9dd7-9090e7d30f65",
- "entity_id": "019a3653-c914-769b-9454-3b70dc2ad966",
- "link_id": "01976c0a-7554-719c-a2fc-d4dcf7e8a8bf",
- "content": "just rename the thing\n#### You can view, comment on, or merge this pull request online at:\nhttps://github.com/macro-inc/macro-api/pull/2471\n#### Commit Summary\n* f3e3ab1 rename env var\n#### File Changes\n(1 file)\n* **M** cloud-storage/infra/stacks/connection-gateway/index.ts (2)\n#### Patch Links:\n* https://github.com/macro-inc/macro-api/pull/2471.patch\n* https://github.com/macro-inc/macro-api/pull/2471.diff\n—\nReply to this email directly, view it on GitHub, or unsubscribe.\nYou are receiving this because your review was requested.Message ID: <macro-inc/macro-api/pull/[email protected]>",
- "labels": [
- "github",
- "CATEGORY_PERSONAL",
- "UNREAD",
- "IMPORTANT"
- ],
- "sent_at": 1761848050,
- "thread_id": "019a3653-c914-769b-9454-3b70dc2ad966",
- "updated_at": 1761848053,
- "sent_at_seconds": 1761848050,
- "sender": "[email protected]",
- "user_id": "macro|[email protected]",
- "updated_at_seconds": 1761848053,
- "recipients": [
- ]
- },
- "highlight": {
- "content": [
- "just rename the thing\n#### You can view, comment on, or merge this pull request online at:\nhttps://<macro_em>github.com</macro_em>",
- "file)\n* **M** cloud-storage/infra/stacks/connection-gateway/index.ts (2)\n#### Patch Links:\n* https://<macro_em>github.com</macro_em>",
- "/macro-inc/macro-api/pull/2471.patch\n* https://<macro_em>github.com</macro_em>/macro-inc/macro-api/pull/2471.diff\n—\nReply",
- "to this email directly, view it on <macro_em>GitHub</macro_em>, or unsubscribe.",
- "You are receiving this because your review was requested.Message ID: <macro-inc/macro-api/pull/2471@<macro_em>github.com</macro_em>"
- ]
- }
- },
- {
- "_index": "emails",
- "_id": "019a12cf-ed6d-7cbc-b705-a78bbbe1bba0:019a12d7-9a39-7ce4-a407-a737db30bdfd",
- "_score": 17.127216,
- "_source": {
- "cc": [
- ],
- "bcc": [],
- "subject": "Re: [macro-inc/macro-api] Update macrodb to use sqlx (PR #2423)",
- "message_id": "019a12d7-9a39-7ce4-a407-a737db30bdfd",
- "entity_id": "019a12cf-ed6d-7cbc-b705-a78bbbe1bba0",
- "link_id": "01976c0a-7554-719c-a2fc-d4dcf7e8a8bf",
- "content": "@evanhutnik commented on this pull request.\nIn .github/workflows/db-client-check.yml:\n> @@ -1,12 +1,12 @@\nname: db client check\non:\npull_request:\n- branches: 'never'\n- # branches: 'dev', 'prod'\n- # paths:\n+ branches: 'never' \nimage.png (view on web)\nsometimes it be your own self\n—\nReply to this email directly, view it on GitHub, or unsubscribe.\nYou are receiving this because you commented.Message ID: <macro-inc/macro-api/pull/2423/review/[email protected]>",
- "labels": [
- "github",
- "CATEGORY_PERSONAL",
- "UNREAD",
- "IMPORTANT"
- ],
- "sent_at": 1761252648,
- "thread_id": "019a12cf-ed6d-7cbc-b705-a78bbbe1bba0",
- "updated_at": 1761252711,
- "sent_at_seconds": 1761252648,
- "sender": "[email protected]",
- "user_id": "macro|[email protected]",
- "updated_at_seconds": 1761252711,
- "recipients": [
- ]
- },
- "highlight": {
- "content": [
- "In .<macro_em>github</macro_em>/workflows/db-client-check.yml:\n> @@ -1,12 +1,12 @@\nname: db client check\non:\npull_request:",
- "' \nimage.png (view on web)\nsometimes it be your own self\n—\nReply to this email directly, view it on <macro_em>GitHub</macro_em>",
- "are receiving this because you commented.Message ID: <macro-inc/macro-api/pull/2423/review/3372627995@<macro_em>github.com</macro_em>"
- ]
- }
- },
- {
- "_index": "emails",
- "_id": "019a3575-3540-7231-8b83-51279a1bf623:019a3575-3541-7c31-9857-5dfea488c4c6",
- "_score": 17.092716,
- "_source": {
- "cc": [
- ],
- "bcc": [],
- "subject": "[macro-inc/macro-api] Upgrade db version (PR #2466)",
- "message_id": "019a3575-3541-7c31-9857-5dfea488c4c6",
- "entity_id": "019a3575-3540-7231-8b83-51279a1bf623",
- "link_id": "01976c0a-7554-719c-a2fc-d4dcf7e8a8bf",
- "content": "## Summary\nAWS auto updated our dbs from 16.3 to 16.8. Updating pulumi to reflect this.\n## Screenshots, GIFs, and Videos\n## Checklist\n* Included (`MACRO-N`) in the PR title.\n* QA'd\nTests for PR (pick one):\n* N/A\n* 🤖 Automated\n#### You can view, comment on, or merge this pull request online at:\nhttps://github.com/macro-inc/macro-api/pull/2466\n#### Commit Summary\n* 452175c Upgrade db version\n#### File Changes\n(1 file)\n* **M** cloud-storage/infra/packages/resources/src/resources/rds.ts (2)\n#### Patch Links:\n* https://github.com/macro-inc/macro-api/pull/2466.patch\n* https://github.com/macro-inc/macro-api/pull/2466.diff\n—\nReply to this email directly, view it on GitHub, or unsubscribe.\nYou are receiving this because your review was requested.Message ID: <macro-inc/macro-api/pull/[email protected]>",
- "labels": [
- "github",
- "CATEGORY_UPDATES",
- "UNREAD"
- ],
- "sent_at": 1761833460,
- "thread_id": "019a3575-3540-7231-8b83-51279a1bf623",
- "updated_at": 1761833465,
- "sent_at_seconds": 1761833460,
- "sender": "[email protected]",
- "user_id": "macro|[email protected]",
- "updated_at_seconds": 1761833465,
- "recipients": [
- ]
- },
- "highlight": {
- "content": [
- ":\n* N/A\n* 🤖 Automated\n#### You can view, comment on, or merge this pull request online at:\nhttps://<macro_em>github.com</macro_em>",
- "* **M** cloud-storage/infra/packages/resources/src/resources/rds.ts (2)\n#### Patch Links:\n* https://<macro_em>github.com</macro_em>",
- "/macro-inc/macro-api/pull/2466.patch\n* https://<macro_em>github.com</macro_em>/macro-inc/macro-api/pull/2466.diff\n—\nReply",
- "to this email directly, view it on <macro_em>GitHub</macro_em>, or unsubscribe.",
- "You are receiving this because your review was requested.Message ID: <macro-inc/macro-api/pull/2466@<macro_em>github.com</macro_em>"
- ]
- }
- },
- {
- "_index": "emails",
- "_id": "019a30ae-2a24-78b3-9eef-e3aa7594a1e4:019a30b1-c647-7949-8be2-1ef3f2195790",
- "_score": 17.033447,
- "_source": {
- "cc": [
- ],
- "bcc": [],
- "subject": "[macro-inc/macro-api] seanaye/add/conn gateway pg frecency (PR #2457)",
- "message_id": "019a30b1-c647-7949-8be2-1ef3f2195790",
- "entity_id": "019a30ae-2a24-78b3-9eef-e3aa7594a1e4",
- "link_id": "01976c0a-7554-719c-a2fc-d4dcf7e8a8bf",
- "content": "## Summary\nThis PR swaps the backing storage layer for frecency in connection gateway from dynamo -> pg\n* **add inbound poller worker**\n* **switch connection gateway to pg frecency**\n* **use secret macro_db connection string**\n## Screenshots, GIFs, and Videos\n## Checklist\n* Included (`MACRO-N`) in the PR title.\n* QA'd\nTests for PR (pick one):\n* N/A\n* 🤖 Automated\n#### You can view, comment on, or merge this pull request online at:\nhttps://github.com/macro-inc/macro-api/pull/2457\n#### Commit Summary\n* 1575c1b add inbound poller worker\n* b51c9a4 switch connection gateway to pg frecency\n* 3c44249 use secret macro_db connection string\n#### File Changes\n(14 files)\n* **M** .github/CODEOWNERS (2)\n* **M** cloud-storage/Cargo.lock (1)\n* **M** cloud-storage/connection_gateway/Cargo.toml (3)\n* **M** cloud-storage/connection_gateway/src/context.rs (9)\n* **M** cloud-storage/connection_gateway/src/main.rs (33)\n* **M** cloud-storage/frecency/Cargo.toml (11)\n* **M** cloud-storage/frecency/src/domain/models.rs (20)\n* **M** cloud-storage/frecency/src/domain/ports.rs (6)\n* **M** cloud-storage/frecency/src/domain/services.rs (39)\n* **M** cloud-storage/frecency/src/inbound.rs (2)\n* **M** cloud-storage/frecency/src/inbound/polling_aggregator.rs (91)\n* **M** cloud-storage/frecency/src/outbound/postgres.rs (3)\n* **M** cloud-storage/infra/stacks/connection-gateway/index.ts (12)\n* **M** cloud-storage/remote_env_var/src/lib.rs (16)\n#### Patch Links:\n* https://github.com/macro-inc/macro-api/pull/2457.patch\n* https://github.com/macro-inc/macro-api/pull/2457.diff\n—\nReply to this email directly, view it on GitHub, or unsubscribe.\nYou are receiving this because your review was requested.Message ID: <macro-inc/macro-api/pull/[email protected]>",
- "labels": [
- "github",
- "CATEGORY_PERSONAL",
- "UNREAD",
- "IMPORTANT"
- ],
- "sent_at": 1761753544,
- "thread_id": "019a30ae-2a24-78b3-9eef-e3aa7594a1e4",
- "updated_at": 1761753548,
- "sent_at_seconds": 1761753544,
- "sender": "[email protected]",
- "user_id": "macro|[email protected]",
- "updated_at_seconds": 1761753548,
- "recipients": [
- ]
- },
- "highlight": {
- "content": [
- ":\n* N/A\n* 🤖 Automated\n#### You can view, comment on, or merge this pull request online at:\nhttps://<macro_em>github.com</macro_em>",
- "to pg frecency\n* 3c44249 use secret macro_db connection string\n#### File Changes\n(14 files)\n* **M** .<macro_em>github</macro_em>",
- "connection-gateway/index.ts (12)\n* **M** cloud-storage/remote_env_var/src/lib.rs (16)\n#### Patch Links:\n* https://<macro_em>github.com</macro_em>",
- "/macro-inc/macro-api/pull/2457.patch\n* https://<macro_em>github.com</macro_em>/macro-inc/macro-api/pull/2457.diff\n—\nReply",
- "to this email directly, view it on <macro_em>GitHub</macro_em>, or unsubscribe.",
- "You are receiving this because your review was requested.Message ID: <macro-inc/macro-api/pull/2457@<macro_em>github.com</macro_em>"
- ]
- }
- }
- ]
- }
- });
-
- let _: DefaultSearchResponse<UnifiedSearchIndex> = serde_json::from_value(json)?;
-
- Ok(())
-}
-
-#[test]
-fn test_build_unified_search_request_content() -> anyhow::Result<()> {
- let unified_search_args = UnifiedSearchArgs {
- search_indices: vec![
- SearchEntityType::Documents,
- SearchEntityType::Emails,
- SearchEntityType::Projects,
- SearchEntityType::Channels,
- SearchEntityType::Chats,
- ]
- .into_iter()
- .collect(),
- terms: vec!["test".to_string()],
- user_id: "user".to_string(),
- page: 1,
- page_size: 20,
- match_type: "exact".to_string(),
- search_on: SearchOn::Content,
- collapse: true,
- disable_recency: false,
- document_search_args: UnifiedDocumentSearchArgs {
- document_ids: vec!["id1".to_string(), "id2".to_string()],
- ids_only: false,
- },
- email_search_args: UnifiedEmailSearchArgs {
- thread_ids: vec!["id1".to_string(), "id2".to_string()],
- link_ids: vec!["id1".to_string(), "id2".to_string()],
- sender: vec!["id1".to_string(), "id2".to_string()],
- cc: vec!["id1".to_string(), "id2".to_string()],
- bcc: vec!["id1".to_string(), "id2".to_string()],
- recipients: vec!["id1".to_string(), "id2".to_string()],
- },
- channel_message_search_args: UnifiedChannelMessageSearchArgs {
- channel_ids: vec!["id1".to_string(), "id2".to_string()],
- thread_ids: vec!["id1".to_string(), "id2".to_string()],
- mentions: vec!["id1".to_string(), "id2".to_string()],
- sender_ids: vec!["id1".to_string(), "id2".to_string()],
- },
- chat_search_args: UnifiedChatSearchArgs {
- chat_ids: vec!["id1".to_string(), "id2".to_string()],
- role: vec!["id1".to_string(), "id2".to_string()],
- ids_only: false,
- },
- project_search_args: UnifiedProjectSearchArgs {
- project_ids: vec!["id1".to_string(), "id2".to_string()],
- ids_only: false,
- },
- };
-
- let result = build_unified_search_request(&unified_search_args)?;
-
- let expected = serde_json::json!({
- "collapse": {
- "field": "entity_id"
- },
- "from": 20,
- "highlight": {
- "fields": {
- "bcc": {
- "number_of_fragments": 1,
- "post_tags": ["</macro_em>"],
- "pre_tags": ["<macro_em>"],
- "type": "plain"
- },
- "cc": {
- "number_of_fragments": 1,
- "post_tags": ["</macro_em>"],
- "pre_tags": ["<macro_em>"],
- "type": "plain"
- },
- "content": {
- "number_of_fragments": 500,
- "post_tags": ["</macro_em>"],
- "pre_tags": ["<macro_em>"],
- "type": "plain"
- },
- "recipients": {
- "number_of_fragments": 1,
- "post_tags": ["</macro_em>"],
- "pre_tags": ["<macro_em>"],
- "type": "plain"
- },
- "sender": {
- "number_of_fragments": 1,
- "post_tags": ["</macro_em>"],
- "pre_tags": ["<macro_em>"],
- "type": "plain"
- }
- },
- "require_field_match": true
- },
- "query": {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "owner_id": "user"
- }
- }
- ]
- }
- },
- {
- "term": {
- "_index": "documents"
- }
- }
- ],
- "must": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "owner_id": {
- "boost": 5000.0,
- "case_insensitive": true,
- "value": "macro|test*"
- }
- }
- },
- {
- "match_phrase": {
- "content": "test"
- }
- }
- ]
- }
- }
- ]
- }
- },
- {
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "user_id": "user"
- }
- }
- ]
- }
- },
- {
- "term": {
- "_index": "emails"
- }
- },
- {
- "terms": {
- "link_id": ["id1", "id2"]
- }
- },
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "sender": {
- "case_insensitive": true,
- "value": "*id1*"
- }
- }
- },
- {
- "wildcard": {
- "sender": {
- "case_insensitive": true,
- "value": "*id2*"
- }
- }
- }
- ]
- }
- },
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "cc": {
- "case_insensitive": true,
- "value": "*id1*"
- }
- }
- },
- {
- "wildcard": {
- "cc": {
- "case_insensitive": true,
- "value": "*id2*"
- }
- }
- }
- ]
- }
- },
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "bcc": {
- "case_insensitive": true,
- "value": "*id1*"
- }
- }
- },
- {
- "wildcard": {
- "bcc": {
- "case_insensitive": true,
- "value": "*id2*"
- }
- }
- }
- ]
- }
- },
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "recipients": {
- "case_insensitive": true,
- "value": "*id1*"
- }
- }
- },
- {
- "wildcard": {
- "recipients": {
- "case_insensitive": true,
- "value": "*id2*"
- }
- }
- }
- ]
- }
- }
- ],
- "must": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "sender": {
- "boost": 5000.0,
- "case_insensitive": true,
- "value": "test*"
- }
- }
- },
- {
- "wildcard": {
- "cc": {
- "boost": 5000.0,
- "case_insensitive": true,
- "value": "test*"
- }
- }
- },
- {
- "wildcard": {
- "bcc": {
- "boost": 5000.0,
- "case_insensitive": true,
- "value": "test*"
- }
- }
- },
- {
- "wildcard": {
- "recipients": {
- "boost": 5000.0,
- "case_insensitive": true,
- "value": "test*"
- }
- }
- },
- {
- "match_phrase": {
- "content": "test"
- }
- }
- ]
- }
- }
- ],
- "must_not": [
- {
- "term": {
- "labels": "TRASH"
- }
- }
- ]
- }
- },
- {
- "bool": {
- "filter": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "_index": "channels"
- }
- },
- {
- "terms": {
- "thread_id": ["id1", "id2"]
- }
- },
- {
- "terms": {
- "mentions": ["id1", "id2"]
- }
- },
- {
- "terms": {
- "sender_id": ["id1", "id2"]
- }
- }
- ],
- "must": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "sender_id": {
- "boost": 5000.0,
- "case_insensitive": true,
- "value": "macro|test*"
- }
- }
- },
- {
- "match_phrase": {
- "content": "test"
- }
- }
- ]
- }
- }
- ]
- }
- },
- {
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "user_id": "user"
- }
- }
- ]
- }
- },
- {
- "term": {
- "_index": "chats"
- }
- },
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "role": {
- "case_insensitive": true,
- "value": "*id1*"
- }
- }
- },
- {
- "wildcard": {
- "role": {
- "case_insensitive": true,
- "value": "*id2*"
- }
- }
- }
- ]
- }
- }
- ],
- "must": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "user_id": {
- "boost": 5000.0,
- "case_insensitive": true,
- "value": "macro|test*"
- }
- }
- },
- {
- "match_phrase": {
- "content": "test"
- }
- }
- ]
- }
- }
- ]
- }
- }
- ]
- }
- },
- "size": 20,
- "sort": updated_at_sort().iter().map(|s| s.to_json()).collect::<Vec<_>>(),
- });
-
- assert_eq!(result.to_json(), expected);
-
- Ok(())
-}
-
-#[test]
-fn test_build_unified_search_request_name() -> anyhow::Result<()> {
- let unified_search_args = UnifiedSearchArgs {
- search_indices: vec![
- SearchEntityType::Documents,
- SearchEntityType::Emails,
- SearchEntityType::Projects,
- SearchEntityType::Channels,
- SearchEntityType::Chats,
- ]
- .into_iter()
- .collect(),
- terms: vec!["test".to_string()],
- user_id: "user".to_string(),
- page: 1,
- page_size: 20,
- match_type: "exact".to_string(),
- search_on: SearchOn::Name,
- collapse: true,
- disable_recency: false,
- document_search_args: UnifiedDocumentSearchArgs {
- document_ids: vec!["id1".to_string(), "id2".to_string()],
- ids_only: false,
- },
- email_search_args: UnifiedEmailSearchArgs {
- thread_ids: vec!["id1".to_string(), "id2".to_string()],
- link_ids: vec!["id1".to_string(), "id2".to_string()],
- sender: vec!["id1".to_string(), "id2".to_string()],
- cc: vec!["id1".to_string(), "id2".to_string()],
- bcc: vec!["id1".to_string(), "id2".to_string()],
- recipients: vec!["id1".to_string(), "id2".to_string()],
- },
- channel_message_search_args: UnifiedChannelMessageSearchArgs {
- channel_ids: vec!["id1".to_string(), "id2".to_string()],
- thread_ids: vec!["id1".to_string(), "id2".to_string()],
- mentions: vec!["id1".to_string(), "id2".to_string()],
- sender_ids: vec!["id1".to_string(), "id2".to_string()],
- },
- chat_search_args: UnifiedChatSearchArgs {
- chat_ids: vec!["id1".to_string(), "id2".to_string()],
- role: vec!["id1".to_string(), "id2".to_string()],
- ids_only: false,
- },
- project_search_args: UnifiedProjectSearchArgs {
- project_ids: vec!["id1".to_string(), "id2".to_string()],
- ids_only: false,
- },
- };
-
- let result = build_unified_search_request(&unified_search_args)?;
-
- let expected = serde_json::json!({
- "collapse": {
- "field": "entity_id"
- },
- "from": 20,
- "highlight": {
- "fields": {
- "name": {
- "number_of_fragments": 1,
- "post_tags": ["</macro_em>"],
- "pre_tags": ["<macro_em>"],
- "type": "plain"
- },
- "project_name": {
- "number_of_fragments": 1,
- "post_tags": ["</macro_em>"],
- "pre_tags": ["<macro_em>"],
- "type": "plain"
- }
- },
- "require_field_match": true
- },
- "query": {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "user_id": "user"
- }
- }
- ]
- }
- },
- {
- "term": {
- "_index": "names"
- }
- },
- {
- "term": {
- "entity_type": "documents"
- }
- }
- ],
- "must": [
- {
- "match_phrase": {
- "name": "test"
- }
- }
- ]
- }
- },
- {
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "user_id": "user"
- }
- }
- ]
- }
- },
- {
- "term": {
- "_index": "names"
- }
- },
- {
- "term": {
- "entity_type": "emails"
- }
- }
- ],
- "must": [
- {
- "match_phrase": {
- "name": "test"
- }
- }
- ]
- }
- },
- {
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "user_id": "user"
- }
- }
- ]
- }
- },
- {
- "term": {
- "_index": "names"
- }
- },
- {
- "term": {
- "entity_type": "chats"
- }
- }
- ],
- "must": [
- {
- "match_phrase": {
- "name": "test"
- }
- }
- ]
- }
- },
- {
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "user_id": "user"
- }
- }
- ]
- }
- },
- {
- "term": {
- "_index": "projects"
- }
- }
- ],
- "must": [
- {
- "match_phrase": {
- "project_name": "test"
- }
- }
- ]
- }
- }
- ]
- }
- },
- "size": 20,
- "sort": updated_at_sort().iter().map(|s| s.to_json()).collect::<Vec<_>>(),
- });
-
- assert_eq!(result.to_json(), expected);
-
- Ok(())
-}
-
-#[test]
-fn test_build_unified_search_request_name_content() -> anyhow::Result<()> {
- let unified_search_args = UnifiedSearchArgs {
- search_indices: vec![
- SearchEntityType::Documents,
- SearchEntityType::Emails,
- SearchEntityType::Projects,
- SearchEntityType::Channels,
- SearchEntityType::Chats,
- ]
- .into_iter()
- .collect(),
- terms: vec!["test".to_string()],
- user_id: "user".to_string(),
- page: 1,
- page_size: 20,
- match_type: "exact".to_string(),
- search_on: SearchOn::NameContent,
- collapse: true,
- disable_recency: false,
- document_search_args: UnifiedDocumentSearchArgs {
- document_ids: vec!["id1".to_string(), "id2".to_string()],
- ids_only: false,
- },
- email_search_args: UnifiedEmailSearchArgs {
- thread_ids: vec!["id1".to_string(), "id2".to_string()],
- link_ids: vec!["id1".to_string(), "id2".to_string()],
- sender: vec!["id1".to_string(), "id2".to_string()],
- cc: vec!["id1".to_string(), "id2".to_string()],
- bcc: vec!["id1".to_string(), "id2".to_string()],
- recipients: vec!["id1".to_string(), "id2".to_string()],
- },
- channel_message_search_args: UnifiedChannelMessageSearchArgs {
- channel_ids: vec!["id1".to_string(), "id2".to_string()],
- thread_ids: vec!["id1".to_string(), "id2".to_string()],
- mentions: vec!["id1".to_string(), "id2".to_string()],
- sender_ids: vec!["id1".to_string(), "id2".to_string()],
- },
- chat_search_args: UnifiedChatSearchArgs {
- chat_ids: vec!["id1".to_string(), "id2".to_string()],
- role: vec!["id1".to_string(), "id2".to_string()],
- ids_only: false,
- },
- project_search_args: UnifiedProjectSearchArgs {
- project_ids: vec!["id1".to_string(), "id2".to_string()],
- ids_only: false,
- },
- };
-
- let result = build_unified_search_request(&unified_search_args)?;
-
- let expected = serde_json::json!({
- "collapse": {
- "field": "entity_id"
- },
- "from": 20,
- "highlight": {
- "fields": {
- "bcc": {
- "number_of_fragments": 1,
- "post_tags": ["</macro_em>"],
- "pre_tags": ["<macro_em>"],
- "type": "plain"
- },
- "cc": {
- "number_of_fragments": 1,
- "post_tags": ["</macro_em>"],
- "pre_tags": ["<macro_em>"],
- "type": "plain"
- },
- "content": {
- "number_of_fragments": 1,
- "post_tags": ["</macro_em>"],
- "pre_tags": ["<macro_em>"],
- "type": "plain"
- },
- "name": {
- "number_of_fragments": 1,
- "post_tags": ["</macro_em>"],
- "pre_tags": ["<macro_em>"],
- "type": "plain"
- },
- "project_name": {
- "number_of_fragments": 1,
- "post_tags": ["</macro_em>"],
- "pre_tags": ["<macro_em>"],
- "type": "plain"
- },
- "recipients": {
- "number_of_fragments": 1,
- "post_tags": ["</macro_em>"],
- "pre_tags": ["<macro_em>"],
- "type": "plain"
- },
- "sender": {
- "number_of_fragments": 1,
- "post_tags": ["</macro_em>"],
- "pre_tags": ["<macro_em>"],
- "type": "plain"
- }
- },
- "require_field_match": false
- },
- "query": {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "owner_id": "user"
- }
- }
- ]
- }
- },
- {
- "term": {
- "_index": "documents"
- }
- }
- ],
- "must": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "owner_id": {
- "boost": 5000.0,
- "case_insensitive": true,
- "value": "macro|test*"
- }
- }
- },
- {
- "match_phrase": {
- "content": "test"
- }
- }
- ]
- }
- }
- ]
- }
- },
- {
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "user_id": "user"
- }
- }
- ]
- }
- },
- {
- "term": {
- "_index": "names"
- }
- },
- {
- "term": {
- "entity_type": "documents"
- }
- }
- ],
- "must": [
- {
- "match_phrase": {
- "name": "test"
- }
- }
- ]
- }
- }
- ]
- }
- },
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "user_id": "user"
- }
- }
- ]
- }
- },
- {
- "term": {
- "_index": "emails"
- }
- },
- {
- "terms": {
- "link_id": ["id1", "id2"]
- }
- },
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "sender": {
- "case_insensitive": true,
- "value": "*id1*"
- }
- }
- },
- {
- "wildcard": {
- "sender": {
- "case_insensitive": true,
- "value": "*id2*"
- }
- }
- }
- ]
- }
- },
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "cc": {
- "case_insensitive": true,
- "value": "*id1*"
- }
- }
- },
- {
- "wildcard": {
- "cc": {
- "case_insensitive": true,
- "value": "*id2*"
- }
- }
- }
- ]
- }
- },
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "bcc": {
- "case_insensitive": true,
- "value": "*id1*"
- }
- }
- },
- {
- "wildcard": {
- "bcc": {
- "case_insensitive": true,
- "value": "*id2*"
- }
- }
- }
- ]
- }
- },
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "recipients": {
- "case_insensitive": true,
- "value": "*id1*"
- }
- }
- },
- {
- "wildcard": {
- "recipients": {
- "case_insensitive": true,
- "value": "*id2*"
- }
- }
- }
- ]
- }
- }
- ],
- "must": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "sender": {
- "boost": 5000.0,
- "case_insensitive": true,
- "value": "test*"
- }
- }
- },
- {
- "wildcard": {
- "cc": {
- "boost": 5000.0,
- "case_insensitive": true,
- "value": "test*"
- }
- }
- },
- {
- "wildcard": {
- "bcc": {
- "boost": 5000.0,
- "case_insensitive": true,
- "value": "test*"
- }
- }
- },
- {
- "wildcard": {
- "recipients": {
- "boost": 5000.0,
- "case_insensitive": true,
- "value": "test*"
- }
- }
- },
- {
- "match_phrase": {
- "content": "test"
- }
- }
- ]
- }
- }
- ],
- "must_not": [
- {
- "term": {
- "labels": "TRASH"
- }
- }
- ]
- }
- },
- {
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "user_id": "user"
- }
- }
- ]
- }
- },
- {
- "term": {
- "_index": "names"
- }
- },
- {
- "term": {
- "entity_type": "emails"
- }
- }
- ],
- "must": [
- {
- "match_phrase": {
- "name": "test"
- }
- }
- ]
- }
- }
- ]
- }
- },
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "bool": {
- "filter": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "_index": "channels"
- }
- },
- {
- "terms": {
- "thread_id": ["id1", "id2"]
- }
- },
- {
- "terms": {
- "mentions": ["id1", "id2"]
- }
- },
- {
- "terms": {
- "sender_id": ["id1", "id2"]
- }
- }
- ],
- "must": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "sender_id": {
- "boost": 5000.0,
- "case_insensitive": true,
- "value": "macro|test*"
- }
- }
- },
- {
- "match_phrase": {
- "content": "test"
- }
- }
- ]
- }
- }
- ]
- }
- },
- {
- "bool": {
- "filter": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "_index": "names"
- }
- },
- {
- "term": {
- "entity_type": "channels"
- }
- }
- ],
- "must": [
- {
- "match_phrase": {
- "name": "test"
- }
- }
- ]
- }
- }
- ]
- }
- },
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "user_id": "user"
- }
- }
- ]
- }
- },
- {
- "term": {
- "_index": "chats"
- }
- },
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "role": {
- "case_insensitive": true,
- "value": "*id1*"
- }
- }
- },
- {
- "wildcard": {
- "role": {
- "case_insensitive": true,
- "value": "*id2*"
- }
- }
- }
- ]
- }
- }
- ],
- "must": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "user_id": {
- "boost": 5000.0,
- "case_insensitive": true,
- "value": "macro|test*"
- }
- }
- },
- {
- "match_phrase": {
- "content": "test"
- }
- }
- ]
- }
- }
- ]
- }
- },
- {
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "user_id": "user"
- }
- }
- ]
- }
- },
- {
- "term": {
- "_index": "names"
- }
- },
- {
- "term": {
- "entity_type": "chats"
- }
- }
- ],
- "must": [
- {
- "match_phrase": {
- "name": "test"
- }
- }
- ]
- }
- }
- ]
- }
- },
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "user_id": "user"
- }
- }
- ]
- }
- },
- {
- "term": {
- "_index": "projects"
- }
- }
- ],
- "must": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "user_id": {
- "boost": 5000.0,
- "case_insensitive": true,
- "value": "macro|test*"
- }
- }
- },
- {
- "match_phrase": {
- "content": "test"
- }
- }
- ]
- }
- }
- ]
- }
- },
- {
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "user_id": "user"
- }
- }
- ]
- }
- },
- {
- "term": {
- "_index": "projects"
- }
- }
- ],
- "must": [
- {
- "match_phrase": {
- "project_name": "test"
- }
- }
- ]
- }
- }
- ]
- }
- }
- ]
- }
- },
- "size": 20,
- "sort": updated_at_sort().iter().map(|s| s.to_json()).collect::<Vec<_>>(),
- });
-
- assert_eq!(result.to_json(), expected);
-
- Ok(())
-}
-
-#[test]
-fn test_build_unified_search_request_single_index() -> anyhow::Result<()> {
- let unified_search_args = UnifiedSearchArgs {
- search_indices: vec![SearchEntityType::Documents].into_iter().collect(),
- terms: vec!["test".to_string()],
- user_id: "user".to_string(),
- page: 1,
- page_size: 20,
- match_type: "exact".to_string(),
- search_on: SearchOn::Content,
- collapse: true,
- disable_recency: false,
- document_search_args: UnifiedDocumentSearchArgs {
- document_ids: vec!["id1".to_string(), "id2".to_string()],
- ids_only: false,
- },
- ..Default::default()
- };
-
- let result = build_unified_search_request(&unified_search_args)?;
- let expected = serde_json::json!(
- {
- "collapse": {
- "field": "entity_id"
- },
- "from": 20,
- "highlight": {
- "fields": {
- "bcc": {
- "number_of_fragments": 1,
- "post_tags": ["</macro_em>"],
- "pre_tags": ["<macro_em>"],
- "type": "plain"
- },
- "cc": {
- "number_of_fragments": 1,
- "post_tags": ["</macro_em>"],
- "pre_tags": ["<macro_em>"],
- "type": "plain"
- },
- "content": {
- "number_of_fragments": 500,
- "post_tags": ["</macro_em>"],
- "pre_tags": ["<macro_em>"],
- "type": "plain"
- },
- "recipients": {
- "number_of_fragments": 1,
- "post_tags": ["</macro_em>"],
- "pre_tags": ["<macro_em>"],
- "type": "plain"
- },
- "sender": {
- "number_of_fragments": 1,
- "post_tags": ["</macro_em>"],
- "pre_tags": ["<macro_em>"],
- "type": "plain"
- }
- },
- "require_field_match": true
- },
- "query": {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "bool": {
- "filter": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "terms": {
- "entity_id": ["id1", "id2"]
- }
- },
- {
- "term": {
- "owner_id": "user"
- }
- }
- ]
- }
- },
- {
- "term": {
- "_index": "documents"
- }
- }
- ],
- "must": [
- {
- "bool": {
- "minimum_should_match": 1,
- "should": [
- {
- "wildcard": {
- "owner_id": {
- "boost": 5000.0,
- "case_insensitive": true,
- "value": "macro|test*"
- }
- }
- },
- {
- "match_phrase": {
- "content": "test"
- }
- }
- ]
- }
- }
- ]
- }
- }
- ]
- }
- },
- "size": 20,
- "sort": updated_at_sort().iter().map(|s| s.to_json()).collect::<Vec<_>>(),
- });
-
- assert_eq!(result.to_json(), expected);
-
- Ok(())
-}
-
-#[test]
-fn test_build_unified_search_request_empty_indices() -> anyhow::Result<()> {
- let unified_search_args = UnifiedSearchArgs {
- search_indices: vec![].into_iter().collect(),
- ..Default::default()
- };
-
- let err = build_unified_search_request(&unified_search_args).unwrap_err();
-
- assert_eq!(err, OpensearchClientError::EmptySearchIndices);
-
- Ok(())
-}
diff --git a/rust/cloud-storage/opensearch_client/src/unified.rs b/rust/cloud-storage/opensearch_client/src/unified.rs
deleted file mode 100644
index 1531fb7486..0000000000
--- a/rust/cloud-storage/opensearch_client/src/unified.rs
+++ /dev/null
@@ -1,12 +0,0 @@
-use crate::{
- OpensearchClient, Result,
- search::{self, model::SearchHit, unified::UnifiedSearchArgs},
-};
-
-impl OpensearchClient {
- /// Performs a unified search
- #[tracing::instrument(skip(self, args))]
- pub async fn search_unified(&self, args: UnifiedSearchArgs) -> Result<Vec<SearchHit>> {
- search::unified::search_unified(&self.inner, args).await
- }
-}
diff --git a/rust/cloud-storage/search_service/Cargo.toml b/rust/cloud-storage/search_service/Cargo.toml
index 6666cf5af7..2abd355d03 100644
--- a/rust/cloud-storage/search_service/Cargo.toml
+++ b/rust/cloud-storage/search_service/Cargo.toml
@@ -12,37 +12,39 @@ axum = { workspace = true }
chrono = { workspace = true }
comms_service_client = { path = "../comms_service_client" }
document_storage_service_client = { path = "../document_storage_service_client" }
+document_sub_type = { path = "../document_sub_type" }
email_service_client = { path = "../email_service_client" }
futures = { workspace = true }
-indexmap = "2"
http-body-util = { workspace = true }
+indexmap = "2"
+item_filters = { path = "../item_filters" }
macro_auth = { path = "../macro_auth" }
-macro_db_client = { path = "../macro_db_client" }
macro_cors = { path = "../macro_cors" }
+macro_db_client = { path = "../macro_db_client" }
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
macro_middleware = { path = "../macro_middleware", default-features = false, features = [
- "auth",
+ "auth",
] }
+macro_user_id = { path = "../macro_user_id" }
model = { path = "../model" }
models_email = { path = "../models_email" }
+models_opensearch = { path = "../models_opensearch" }
models_search = { path = "../models_search" }
+name_search = { path = "../name_search" }
opensearch_client = { path = "../opensearch_client" }
secretsmanager_client = { path = "../secretsmanager_client" }
serde = { workspace = true }
serde_json = { workspace = true }
-strum = { workspace = true }
sqlx = { workspace = true }
+strum = { workspace = true }
+thiserror = { workspace = true }
tokio = { workspace = true }
tower = { workspace = true }
tower-http = { workspace = true }
tracing = { workspace = true }
utoipa = { workspace = true }
utoipa-swagger-ui = { workspace = true }
-item_filters = { path = "../item_filters" }
-thiserror = { workspace = true }
-models_opensearch = { path = "../models_opensearch" }
-document_sub_type = { path = "../document_sub_type" }
[dev-dependencies]
macro_auth = { path = "../macro_auth", features = ["testing"] }
diff --git a/rust/cloud-storage/search_service/src/api/search/simple/filter.rs b/rust/cloud-storage/search_service/src/api/search/simple/filter.rs
deleted file mode 100644
index 58b77985c2..0000000000
--- a/rust/cloud-storage/search_service/src/api/search/simple/filter.rs
+++ /dev/null
@@ -1,166 +0,0 @@
-//! This module is responsible for defining a trait to convert item_filters into a UnifiedSearchArgsVariant
-//! This is used in simple_unified.rs
-
-use opensearch_client::search::unified::{
- UnifiedChannelMessageSearchArgs, UnifiedChatSearchArgs, UnifiedDocumentSearchArgs,
- UnifiedEmailSearchArgs, UnifiedProjectSearchArgs,
-};
-
-use crate::api::{
- context::ApiContext,
- search::simple::{
- SearchError, simple_channel::filter_channels, simple_chat::filter_chats,
- simple_document::filter_documents, simple_project::filter_projects,
- },
-};
-
-#[derive(Debug)]
-pub(super) enum UnifiedSearchArgsVariant {
- Document(UnifiedDocumentSearchArgs),
- Channel(UnifiedChannelMessageSearchArgs),
- Chat(UnifiedChatSearchArgs),
- Project(UnifiedProjectSearchArgs),
- Email(UnifiedEmailSearchArgs),
-}
-
-/// Trait to convert item_filters into a UnifiedSearchArgsVariant
-pub(super) trait FilterVariantToSearchArgs {
- fn filter_to_search_args(
- &self,
- ctx: &ApiContext,
- user_id: &str,
- user_organization_id: Option<i32>,
- should_include: bool,
- ) -> impl Future<Output = Result<UnifiedSearchArgsVariant, SearchError>> + Send;
-}
-
-impl FilterVariantToSearchArgs for item_filters::DocumentFilters {
- async fn filter_to_search_args(
- &self,
- ctx: &ApiContext,
- user_id: &str,
- _user_organization_id: Option<i32>,
- should_include: bool,
- ) -> Result<UnifiedSearchArgsVariant, SearchError> {
- if !should_include {
- Ok(UnifiedSearchArgsVariant::Document(
- UnifiedDocumentSearchArgs::default(),
- ))
- } else {
- let filter_document_response = filter_documents(ctx, user_id, self).await?;
-
- Ok(UnifiedSearchArgsVariant::Document(
- UnifiedDocumentSearchArgs {
- document_ids: filter_document_response.document_ids,
- ids_only: filter_document_response.ids_only,
- },
- ))
- }
- }
-}
-
-impl FilterVariantToSearchArgs for item_filters::ChannelFilters {
- async fn filter_to_search_args(
- &self,
- ctx: &ApiContext,
- user_id: &str,
- user_organization_id: Option<i32>,
- should_include: bool,
- ) -> Result<UnifiedSearchArgsVariant, SearchError> {
- if !should_include {
- Ok(UnifiedSearchArgsVariant::Channel(
- UnifiedChannelMessageSearchArgs::default(),
- ))
- } else {
- let filter_channel_response =
- filter_channels(ctx, user_id, user_organization_id, self).await?;
-
- Ok(UnifiedSearchArgsVariant::Channel(
- UnifiedChannelMessageSearchArgs {
- channel_ids: filter_channel_response
- .channel_ids
- .iter()
- .map(|c| c.to_string())
- .collect(),
- thread_ids: self.thread_ids.clone(),
- mentions: self.mentions.clone(),
- sender_ids: self.sender_ids.clone(),
- },
- ))
- }
- }
-}
-
-impl FilterVariantToSearchArgs for item_filters::ChatFilters {
- async fn filter_to_search_args(
- &self,
- ctx: &ApiContext,
- user_id: &str,
- _user_organization_id: Option<i32>,
- should_include: bool,
- ) -> Result<UnifiedSearchArgsVariant, SearchError> {
- if !should_include {
- Ok(UnifiedSearchArgsVariant::Chat(
- UnifiedChatSearchArgs::default(),
- ))
- } else {
- let filter_chat_response = filter_chats(ctx, user_id, self).await?;
-
- Ok(UnifiedSearchArgsVariant::Chat(UnifiedChatSearchArgs {
- chat_ids: filter_chat_response.chat_ids,
- ids_only: filter_chat_response.ids_only,
- role: self.role.clone(),
- }))
- }
- }
-}
-
-impl FilterVariantToSearchArgs for item_filters::ProjectFilters {
- async fn filter_to_search_args(
- &self,
- ctx: &ApiContext,
- user_id: &str,
- _user_organization_id: Option<i32>,
- should_include: bool,
- ) -> Result<UnifiedSearchArgsVariant, SearchError> {
- if !should_include {
- Ok(UnifiedSearchArgsVariant::Project(
- UnifiedProjectSearchArgs::default(),
- ))
- } else {
- let filter_project_response = filter_projects(ctx, user_id, self).await?;
-
- Ok(UnifiedSearchArgsVariant::Project(
- UnifiedProjectSearchArgs {
- project_ids: filter_project_response.project_ids,
- ids_only: filter_project_response.ids_only,
- },
- ))
- }
- }
-}
-
-impl FilterVariantToSearchArgs for item_filters::EmailFilters {
- async fn filter_to_search_args(
- &self,
- _ctx: &ApiContext,
- _user_id: &str,
- _user_organization_id: Option<i32>,
- should_include: bool,
- ) -> Result<UnifiedSearchArgsVariant, SearchError> {
- if !should_include {
- Ok(UnifiedSearchArgsVariant::Email(
- UnifiedEmailSearchArgs::default(),
- ))
- } else {
- Ok(UnifiedSearchArgsVariant::Email(UnifiedEmailSearchArgs {
- thread_ids: vec![],
- link_ids: vec![],
- sender: self.senders.clone(),
- cc: self.cc.clone(),
- bcc: self.bcc.clone(),
- recipients: self.recipients.clone(),
- }))
- }
- }
-}
diff --git a/rust/cloud-storage/search_service/src/api/search/simple/mod.rs b/rust/cloud-storage/search_service/src/api/search/simple/mod.rs
index fab496412a..5bede8bfa5 100644
--- a/rust/cloud-storage/search_service/src/api/search/simple/mod.rs
+++ b/rust/cloud-storage/search_service/src/api/search/simple/mod.rs
@@ -6,9 +6,9 @@ use axum::{
routing::post,
};
use model::response::ErrorResponse;
+use name_search::NameSearchError;
use opensearch_client::error::OpensearchClientError;
-pub(in crate::api::search::simple) mod filter;
pub(in crate::api) mod simple_channel;
pub(in crate::api) mod simple_chat;
pub(in crate::api) mod simple_document;
@@ -31,6 +31,9 @@ pub enum SearchError {
/// No user id found in user context
#[error("no user id found in user context")]
NoUserId,
+ /// Invalid macro user id
+ #[error("invalid macro user id {0}")]
+ InvalidUserId(String),
/// Invalid page size
#[error("page_size must be between 0 and 100")]
InvalidPageSize,
@@ -43,6 +46,9 @@ pub enum SearchError {
/// Opensearch error occurred
#[error("unable to search")]
Search(#[from] OpensearchClientError),
+ /// Name search error occurred
+ #[error("unable to name search")]
+ NameSearch(#[from] NameSearchError),
/// Internal error occurred
#[error("internal error")]
InternalError(#[from] anyhow::Error),
@@ -51,12 +57,13 @@ pub enum SearchError {
impl IntoResponse for SearchError {
fn into_response(self) -> Response {
let status_code = match self {
- SearchError::NoUserId => StatusCode::UNAUTHORIZED,
+ SearchError::NoUserId | SearchError::InvalidUserId(_) => StatusCode::UNAUTHORIZED,
SearchError::InvalidPageSize
| SearchError::InvalidQuerySize
| SearchError::NoQueryOrTermsProvided => StatusCode::BAD_REQUEST,
- SearchError::Search(_) => StatusCode::INTERNAL_SERVER_ERROR,
- SearchError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ SearchError::Search(_) | SearchError::NameSearch(_) | SearchError::InternalError(_) => {
+ StatusCode::INTERNAL_SERVER_ERROR
+ }
};
(
diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_channel.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_channel.rs
index a3e48e9264..914a32ec88 100644
--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_channel.rs
+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_channel.rs
@@ -9,7 +9,7 @@ use axum::{
};
use model::{response::ErrorResponse, user::UserContext};
use models_search::{
- SimpleSearchResponse,
+ SearchOn, SimpleSearchResponse,
channel::{ChannelSearchRequest, SimpleChannelSearchResponse},
};
use opensearch_client::search::channels::ChannelMessageSearchArgs;
@@ -114,6 +114,10 @@ pub(in crate::api::search) async fn search_channels(
query_params: &SearchPaginationParams,
req: ChannelSearchRequest,
) -> Result<Vec<opensearch_client::search::model::SearchHit>, SearchError> {
+ // We don't support searching on channels by name
+ if let SearchOn::Name = req.search_on {
+ return Ok(Vec::new());
+ }
if user_id.is_empty() {
return Err(SearchError::NoUserId);
}
diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_chat.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_chat.rs
index a56d64c426..1550af5f33 100644
--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_chat.rs
+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_chat.rs
@@ -1,20 +1,28 @@
+use std::future::ready;
+
use crate::api::search::{SearchPaginationParams, simple::SearchError};
use axum::{
Extension,
extract::{self, State},
response::Json,
};
+use futures::future::Either;
use item_filters::ChatFilters;
+use macro_user_id::user_id::MacroUserId;
use model::{
item::{ShareableItem, ShareableItemType},
response::ErrorResponse,
user::UserContext,
};
use models_search::{
- SimpleSearchResponse,
+ SearchOn, SimpleSearchResponse,
chat::{ChatSearchRequest, SimpleChatSearchResponse},
};
-use opensearch_client::search::chats::ChatSearchArgs;
+use opensearch_client::search::{
+ chats::ChatSearchArgs,
+ model::{Highlight, SearchHit},
+};
+use sqlx::types::Uuid;
use crate::api::ApiContext;
@@ -151,6 +159,10 @@ pub(in crate::api::search) async fn search_chats(
return Err(SearchError::NoUserId);
}
+ let user_id = MacroUserId::parse_from_str(user_id)
+ .map_err(|_| SearchError::InvalidUserId(user_id.to_string()))?
+ .lowercase();
+
let page = query_params.page.unwrap_or(0);
let page_size = if let Some(page_size) = query_params.page_size {
@@ -179,29 +191,68 @@ pub(in crate::api::search) async fn search_chats(
let filters = req.filters.unwrap_or_default();
- let filter_chat_response = filter_chats(ctx, user_id, &filters).await?;
+ let filter_chat_response = filter_chats(ctx, user_id.as_ref(), &filters).await?;
if filter_chat_response.chat_ids.is_empty() && filter_chat_response.ids_only {
return Ok(Vec::new());
}
- let results = ctx
- .opensearch_client
- .search_chats(ChatSearchArgs {
- terms,
- user_id: user_id.to_string(),
- chat_ids: filter_chat_response.chat_ids,
- page,
+ let chat_uuids = filter_chat_response
+ .chat_ids
+ .iter()
+ .map(|c| c.parse().unwrap())
+ .collect::<Vec<Uuid>>();
+
+ let name_results = match req.search_on {
+ SearchOn::Name | SearchOn::NameContent => Either::Left(name_search::search_chat_names(
+ &ctx.db,
+ &user_id,
+ &chat_uuids,
+ terms[0].clone(),
+ filter_chat_response.ids_only,
page_size,
- match_type: req.match_type.to_string(),
- role: filters.role,
- search_on: req.search_on.into(),
- collapse: req.collapse.unwrap_or(false),
- ids_only: filter_chat_response.ids_only,
- disable_recency: req.disable_recency,
+ page * page_size,
+ )),
+ SearchOn::Content => Either::Right(ready(Ok(Vec::new()))),
+ };
+
+ let content_results = match req.search_on {
+ SearchOn::Content | SearchOn::NameContent => {
+ Either::Left(ctx.opensearch_client.search_chats(ChatSearchArgs {
+ terms,
+ user_id: user_id.as_ref().to_string(),
+ chat_ids: filter_chat_response.chat_ids,
+ page,
+ page_size,
+ match_type: req.match_type.to_string(),
+ role: filters.role,
+ search_on: req.search_on.into(),
+ collapse: req.collapse.unwrap_or(false),
+ ids_only: filter_chat_response.ids_only,
+ disable_recency: req.disable_recency,
+ }))
+ }
+ SearchOn::Name => Either::Right(ready(Ok(Vec::new()))),
+ };
+
+ let (name_result, content_result) = tokio::join!(name_results, content_results);
+ let name_result = name_result.map_err(SearchError::NameSearch)?;
+ let content_result = content_result.map_err(SearchError::Search)?;
+
+ let results: Vec<SearchHit> = name_result
+ .into_iter()
+ .map(|n| SearchHit {
+ entity_id: n.entity_id,
+ entity_type: n.entity_type,
+ score: None,
+ highlight: Highlight {
+ name: Some(n.name),
+ ..Default::default()
+ },
+ goto: None,
})
- .await
- .map_err(SearchError::Search)?;
+ .chain(content_result)
+ .collect();
Ok(results)
}
diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_document.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_document.rs
index c56fce41c6..584bb28a4d 100644
--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_document.rs
+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_document.rs
@@ -1,20 +1,28 @@
+use std::future::ready;
+
use crate::api::search::{SearchPaginationParams, simple::SearchError};
use axum::{
Extension,
extract::{self, State},
response::Json,
};
+use futures::future::Either;
use item_filters::DocumentFilters;
+use macro_user_id::user_id::MacroUserId;
use model::{
item::{ShareableItem, ShareableItemType},
response::ErrorResponse,
user::UserContext,
};
use models_search::{
- SimpleSearchResponse,
+ SearchOn, SimpleSearchResponse,
document::{DocumentSearchRequest, SimpleDocumentSearchResponse},
};
-use opensearch_client::search::documents::DocumentSearchArgs;
+use opensearch_client::search::{
+ documents::DocumentSearchArgs,
+ model::{Highlight, SearchHit},
+};
+use sqlx::types::Uuid;
use crate::api::ApiContext;
@@ -174,11 +182,15 @@ pub(in crate::api::search) async fn search_documents(
user_id: &str,
query_params: &SearchPaginationParams,
req: DocumentSearchRequest,
-) -> Result<Vec<opensearch_client::search::model::SearchHit>, SearchError> {
+) -> Result<Vec<SearchHit>, SearchError> {
if user_id.is_empty() {
return Err(SearchError::NoUserId);
}
+ let user_id = MacroUserId::parse_from_str(user_id)
+ .map_err(|_| SearchError::InvalidUserId(user_id.to_string()))?
+ .lowercase();
+
let page = query_params.page.unwrap_or(0);
let page_size = if let Some(page_size) = query_params.page_size {
@@ -206,28 +218,67 @@ pub(in crate::api::search) async fn search_documents(
};
let filter_document_response =
- filter_documents(ctx, user_id, &req.filters.unwrap_or_default()).await?;
+ filter_documents(ctx, user_id.as_ref(), &req.filters.unwrap_or_default()).await?;
if filter_document_response.document_ids.is_empty() && filter_document_response.ids_only {
return Ok(Vec::new());
}
- let results = ctx
- .opensearch_client
- .search_documents(DocumentSearchArgs {
- terms,
- user_id: user_id.to_string(),
- document_ids: filter_document_response.document_ids,
- page,
+ let document_uuids = filter_document_response
+ .document_ids
+ .iter()
+ .map(|d| d.parse().unwrap())
+ .collect::<Vec<Uuid>>();
+
+ let name_results = match req.search_on {
+ SearchOn::Name | SearchOn::NameContent => Either::Left(name_search::search_document_names(
+ &ctx.db,
+ &user_id,
+ &document_uuids,
+ terms[0].clone(),
+ filter_document_response.ids_only,
page_size,
- match_type: req.match_type.to_string(),
- search_on: req.search_on.into(),
- collapse: req.collapse.unwrap_or(false),
- ids_only: filter_document_response.ids_only,
- disable_recency: req.disable_recency,
+ page * page_size,
+ )),
+ SearchOn::Content => Either::Right(ready(Ok(Vec::new()))),
+ };
+
+ let content_results = match req.search_on {
+ SearchOn::Content | SearchOn::NameContent => {
+ Either::Left(ctx.opensearch_client.search_documents(DocumentSearchArgs {
+ terms: terms.clone(),
+ user_id: user_id.as_ref().to_string(),
+ document_ids: filter_document_response.document_ids.clone(),
+ page,
+ page_size,
+ match_type: req.match_type.to_string(),
+ search_on: req.search_on.into(),
+ collapse: req.collapse.unwrap_or(false),
+ ids_only: filter_document_response.ids_only,
+ disable_recency: req.disable_recency,
+ }))
+ }
+ SearchOn::Name => Either::Right(ready(Ok(Vec::new()))),
+ };
+
+ let (name_result, content_result) = tokio::join!(name_results, content_results);
+ let name_result = name_result.map_err(SearchError::NameSearch)?;
+ let content_result = content_result.map_err(SearchError::Search)?;
+
+ let results: Vec<SearchHit> = name_result
+ .into_iter()
+ .map(|n| SearchHit {
+ entity_id: n.entity_id,
+ entity_type: n.entity_type,
+ score: None,
+ highlight: Highlight {
+ name: Some(n.name),
+ ..Default::default()
+ },
+ goto: None,
})
- .await
- .map_err(SearchError::Search)?;
+ .chain(content_result)
+ .collect();
Ok(results)
}
diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_email.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_email.rs
index 4d13e4e8d7..f41a95f42f 100644
--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_email.rs
+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_email.rs
@@ -1,15 +1,23 @@
+use std::future::ready;
+
use crate::api::search::{SearchPaginationParams, simple::SearchError};
use axum::{
Extension,
extract::{self, State},
response::Json,
};
+use futures::future::Either;
+use macro_user_id::user_id::MacroUserId;
use model::{response::ErrorResponse, user::UserContext};
use models_search::{
- SimpleSearchResponse,
+ SearchOn, SimpleSearchResponse,
email::{EmailSearchRequest, SimpleEmailSearchResponse},
};
-use opensearch_client::search::emails::EmailSearchArgs;
+use opensearch_client::search::{
+ emails::EmailSearchArgs,
+ model::{Highlight, SearchHit},
+};
+use sqlx::types::Uuid;
use crate::api::ApiContext;
@@ -56,6 +64,10 @@ pub(in crate::api::search) async fn search_emails(
return Err(SearchError::NoUserId);
}
+ let user_id = MacroUserId::parse_from_str(user_id)
+ .map_err(|_| SearchError::InvalidUserId(user_id.to_string()))?
+ .lowercase();
+
let page = query_params.page.unwrap_or(0);
let page_size = if let Some(page_size) = query_params.page_size {
@@ -67,44 +79,81 @@ pub(in crate::api::search) async fn search_emails(
10
};
- let terms: Vec<String> = if let Some(terms) = req.terms {
+ let terms: Vec<String> = if let Some(terms) = req.terms.as_ref() {
terms
- .into_iter()
- .filter_map(|t| if t.len() < 3 { None } else { Some(t) })
+ .iter()
+ .filter_map(|t| if t.len() < 3 { None } else { Some(t.clone()) })
.collect()
- } else if let Some(query) = req.query {
+ } else if let Some(query) = req.query.as_ref() {
if query.len() < 3 {
return Err(SearchError::InvalidQuerySize);
}
- vec![query]
+ vec![query.clone()]
} else {
return Err(SearchError::NoQueryOrTermsProvided);
};
let filters = req.filters.unwrap_or_default();
- let results = ctx
- .opensearch_client
- .search_emails(EmailSearchArgs {
- terms,
- user_id: user_id.to_string(),
- thread_ids: vec![],
- link_ids: vec![],
- sender: filters.senders,
- cc: filters.cc,
- bcc: filters.bcc,
- recipients: filters.recipients,
- page,
+ // For emails, thread_ids are not pre-filtered like documents/chats
+ // Empty vec means search all accessible emails for the user
+ let thread_uuids: Vec<Uuid> = vec![];
+
+ let name_results = match req.search_on {
+ SearchOn::Name | SearchOn::NameContent => Either::Left(name_search::search_email_subjects(
+ &ctx.db,
+ &user_id,
+ &thread_uuids,
+ terms[0].clone(),
+ false, // ids_only is false since we're not pre-filtering
page_size,
- match_type: req.match_type.to_string(),
- search_on: req.search_on.into(),
- collapse: req.collapse.unwrap_or(false),
- ids_only: false, // TODO: implement
- disable_recency: req.disable_recency,
+ page * page_size,
+ )),
+ SearchOn::Content => Either::Right(ready(Ok(Vec::new()))),
+ };
+
+ let content_results = match req.search_on {
+ SearchOn::Content | SearchOn::NameContent => {
+ Either::Left(ctx.opensearch_client.search_emails(EmailSearchArgs {
+ terms: terms.clone(),
+ user_id: user_id.as_ref().to_string(),
+ thread_ids: vec![],
+ link_ids: vec![],
+ sender: filters.senders,
+ cc: filters.cc,
+ bcc: filters.bcc,
+ recipients: filters.recipients,
+ page,
+ page_size,
+ match_type: req.match_type.to_string(),
+ search_on: req.search_on.into(),
+ collapse: req.collapse.unwrap_or(false),
+ ids_only: false,
+ disable_recency: req.disable_recency,
+ }))
+ }
+ SearchOn::Name => Either::Right(ready(Ok(Vec::new()))),
+ };
+
+ let (name_result, content_result) = tokio::join!(name_results, content_results);
+ let name_result = name_result.map_err(SearchError::NameSearch)?;
+ let content_result = content_result.map_err(SearchError::Search)?;
+
+ let results: Vec<SearchHit> = name_result
+ .into_iter()
+ .map(|n| SearchHit {
+ entity_id: n.entity_id,
+ entity_type: n.entity_type,
+ score: None,
+ highlight: Highlight {
+ name: Some(n.name),
+ ..Default::default()
+ },
+ goto: None,
})
- .await
- .map_err(SearchError::Search)?;
+ .chain(content_result)
+ .collect();
Ok(results)
}
diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_project.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_project.rs
index 80dae536bb..b543b162f4 100644
--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_project.rs
+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_project.rs
@@ -5,6 +5,7 @@ use axum::{
response::Json,
};
use item_filters::ProjectFilters;
+use macro_user_id::user_id::MacroUserId;
use model::{
item::{ShareableItem, ShareableItemType},
response::ErrorResponse,
@@ -12,7 +13,8 @@ use model::{
};
use models_search::project::{ProjectSearchRequest, SimpleProjectSearchResponse};
use models_search::{SearchOn, SimpleSearchResponse};
-use opensearch_client::search::projects::ProjectSearchArgs;
+use opensearch_client::search::model::{Highlight, SearchHit};
+use sqlx::types::Uuid;
use crate::api::ApiContext;
@@ -144,7 +146,7 @@ pub(in crate::api::search) async fn search_projects(
req: ProjectSearchRequest,
) -> Result<Vec<opensearch_client::search::model::SearchHit>, SearchError> {
// content search is not applicable for projects
- if req.search_on == SearchOn::Content {
+ if let SearchOn::Content = req.search_on {
return Ok(Vec::new());
}
@@ -152,6 +154,10 @@ pub(in crate::api::search) async fn search_projects(
return Err(SearchError::NoUserId);
}
+ let user_id = MacroUserId::parse_from_str(user_id)
+ .map_err(|_| SearchError::InvalidUserId(user_id.to_string()))?
+ .lowercase();
+
let page = query_params.page.unwrap_or(0);
let page_size = if let Some(page_size) = query_params.page_size {
@@ -180,28 +186,42 @@ pub(in crate::api::search) async fn search_projects(
let filters = req.filters.unwrap_or_default();
- let filter_project_response = filter_projects(ctx, user_id, &filters).await?;
+ let filter_project_response = filter_projects(ctx, user_id.as_ref(), &filters).await?;
if filter_project_response.project_ids.is_empty() && filter_project_response.ids_only {
return Ok(Vec::new());
}
- let results = ctx
- .opensearch_client
- .search_project(ProjectSearchArgs {
- terms,
- user_id: user_id.to_string(),
- page,
- page_size,
- match_type: req.match_type.to_string(),
- project_ids: filter_project_response.project_ids,
- search_on: req.search_on.into(),
- collapse: req.collapse.unwrap_or(false),
- ids_only: filter_project_response.ids_only,
- disable_recency: req.disable_recency,
+ let project_ids = filter_project_response
+ .project_ids
+ .iter()
+ .map(|p| p.parse().unwrap())
+ .collect::<Vec<Uuid>>();
+
+ let results = name_search::search_project_names(
+ &ctx.db,
+ &user_id,
+ &project_ids,
+ terms[0].clone(),
+ filter_project_response.ids_only,
+ page_size,
+ page * page_size,
+ )
+ .await?;
+
+ let results: Vec<SearchHit> = results
+ .into_iter()
+ .map(|n| SearchHit {
+ entity_id: n.entity_id,
+ entity_type: n.entity_type,
+ score: None,
+ highlight: Highlight {
+ name: Some(n.name),
+ ..Default::default()
+ },
+ goto: None,
})
- .await
- .map_err(SearchError::Search)?;
+ .collect();
Ok(results)
}
diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs
index 511adca165..24887ab38d 100644
--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs
+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs
@@ -3,8 +3,9 @@ use crate::api::{
search::{
SearchPaginationParams,
simple::{
- SearchError,
- filter::{FilterVariantToSearchArgs, UnifiedSearchArgsVariant},
+ SearchError, simple_channel::search_channels, simple_chat::search_chats,
+ simple_document::search_documents, simple_email::search_emails,
+ simple_project::search_projects,
},
},
};
@@ -16,15 +17,16 @@ use axum::{
use model::{response::ErrorResponse, user::UserContext};
use models_search::{
SimpleSearchResponse,
- unified::{
- SimpleUnifiedSearchResponse, UnifiedSearchIndex, UnifiedSearchRequest,
- generate_unified_search_indices,
- },
+ channel::ChannelSearchRequest,
+ chat::ChatSearchRequest,
+ document::DocumentSearchRequest,
+ email::EmailSearchRequest,
+ project::ProjectSearchRequest,
+ unified::{SimpleUnifiedSearchResponse, UnifiedSearchIndex, UnifiedSearchRequest},
};
-use opensearch_client::search::unified::UnifiedSearchArgs;
/// Creates a unified search request and performs the search
-/// Returning the opensearch results
+/// by calling individual simple search endpoints for each entity type
#[tracing::instrument(skip(ctx, user_context, query_params, req), err)]
pub(in crate::api::search) async fn perform_unified_search(
ctx: &ApiContext,
@@ -33,22 +35,17 @@ pub(in crate::api::search) async fn perform_unified_search(
req: UnifiedSearchRequest,
) -> Result<Vec<opensearch_client::search::model::SearchHit>, SearchError> {
let user_id = &user_context.user_id;
- let user_organization_id = user_context.organization_id;
- let search_on = req.search_on;
- let collapse = req.collapse.unwrap_or(false);
if user_id.is_empty() {
return Err(SearchError::NoUserId);
}
- let page = query_params.page.unwrap_or(0);
-
let page_size = query_params.page_size.unwrap_or(10);
if !(0..=100).contains(&page_size) {
return Err(SearchError::InvalidPageSize);
}
- let terms: Vec<String> = match (req.terms, req.query) {
+ let terms: Vec<String> = match (req.terms.clone(), req.query.clone()) {
(Some(terms), _) => terms.into_iter().filter(|t| t.len() >= 3).collect(),
(None, Some(query)) if query.len() >= 3 => vec![query],
(None, Some(_)) => {
@@ -61,115 +58,124 @@ pub(in crate::api::search) async fn perform_unified_search(
return Err(SearchError::NoQueryOrTermsProvided);
}
- let match_type = req.match_type;
- let disable_recency = req.disable_recency;
-
- let include = req.include;
-
- // Create default filters
+ let include = &req.include;
let filters = req.filters.unwrap_or_default();
- let channel_filters = filters.channel.unwrap_or_default();
- let email_filters = filters.email.unwrap_or_default();
- let chat_filters = filters.chat.unwrap_or_default();
- let project_filters = filters.project.unwrap_or_default();
- let doc_filters = filters.document.unwrap_or_default();
let should_include_documents =
include.is_empty() || include.contains(&UnifiedSearchIndex::Documents);
-
let should_include_channels =
include.is_empty() || include.contains(&UnifiedSearchIndex::Channels);
-
let should_include_chats = include.is_empty() || include.contains(&UnifiedSearchIndex::Chats);
-
let should_include_projects =
include.is_empty() || include.contains(&UnifiedSearchIndex::Projects);
-
let should_include_emails = include.is_empty() || include.contains(&UnifiedSearchIndex::Emails);
- // Await all tasks in parallel
- let (doc_result, channel_result, chat_result, project_result, email_result) = tokio::try_join!(
- doc_filters.filter_to_search_args(
- ctx,
- user_id,
- user_organization_id,
- should_include_documents,
- ),
- channel_filters.filter_to_search_args(
- ctx,
- user_id,
- user_organization_id,
- should_include_channels,
- ),
- chat_filters.filter_to_search_args(
- ctx,
- user_id,
- user_organization_id,
- should_include_chats,
- ),
- project_filters.filter_to_search_args(
- ctx,
- user_id,
- user_organization_id,
- should_include_projects,
- ),
- email_filters.filter_to_search_args(
- ctx,
- user_id,
- user_organization_id,
- should_include_emails,
- ),
- )
- .map_err(|e| SearchError::InternalError(anyhow::anyhow!("tokio error: {:?}", e)))?;
-
- let filter_document_response = match doc_result {
- UnifiedSearchArgsVariant::Document(response) => response,
- _ => unreachable!(),
+ // Build individual search requests for each entity type
+ let doc_request = DocumentSearchRequest {
+ terms: Some(terms.clone()),
+ query: req.query.clone(),
+ match_type: req.match_type,
+ search_on: req.search_on,
+ collapse: req.collapse,
+ disable_recency: req.disable_recency,
+ filters: Some(filters.document.unwrap_or_default()),
};
- let filter_channel_response = match channel_result {
- UnifiedSearchArgsVariant::Channel(response) => response,
- _ => unreachable!(),
+ let chat_request = ChatSearchRequest {
+ terms: Some(terms.clone()),
+ query: req.query.clone(),
+ match_type: req.match_type,
+ search_on: req.search_on,
+ collapse: req.collapse,
+ disable_recency: req.disable_recency,
+ filters: Some(filters.chat.unwrap_or_default()),
};
- let filter_chat_response = match chat_result {
- UnifiedSearchArgsVariant::Chat(response) => response,
- _ => unreachable!(),
+ let email_request = EmailSearchRequest {
+ terms: Some(terms.clone()),
+ query: req.query.clone(),
+ match_type: req.match_type,
+ search_on: req.search_on,
+ collapse: req.collapse,
+ disable_recency: req.disable_recency,
+ filters: Some(filters.email.unwrap_or_default()),
};
- let filter_project_response = match project_result {
- UnifiedSearchArgsVariant::Project(response) => response,
- _ => unreachable!(),
+ let project_request = ProjectSearchRequest {
+ terms: Some(terms.clone()),
+ query: req.query.clone(),
+ match_type: req.match_type,
+ search_on: req.search_on,
+ collapse: req.collapse,
+ disable_recency: req.disable_recency,
+ filters: Some(filters.project.unwrap_or_default()),
};
- let filter_email_response = match email_result {
- UnifiedSearchArgsVariant::Email(response) => response,
- _ => unreachable!(),
+ let channel_request = ChannelSearchRequest {
+ terms: Some(terms.clone()),
+ query: req.query.clone(),
+ match_type: req.match_type,
+ search_on: req.search_on,
+ collapse: req.collapse,
+ disable_recency: req.disable_recency,
+ filters: Some(filters.channel.unwrap_or_default()),
};
- let unified_search_args = UnifiedSearchArgs {
- terms,
- user_id: user_id.to_string(),
- page,
- page_size,
- match_type: match_type.to_string(),
- search_on: search_on.into(),
- collapse,
- disable_recency,
- search_indices: generate_unified_search_indices(include),
- document_search_args: filter_document_response,
- email_search_args: filter_email_response,
- channel_message_search_args: filter_channel_response,
- chat_search_args: filter_chat_response,
- project_search_args: filter_project_response,
- };
+ // Call search functions in parallel for included entity types
+ let (doc_results, chat_results, email_results, project_results, channel_results) = tokio::join!(
+ async {
+ if should_include_documents {
+ search_documents(ctx, user_id, &query_params, doc_request).await
+ } else {
+ Ok(vec![])
+ }
+ },
+ async {
+ if should_include_chats {
+ search_chats(ctx, user_id, &query_params, chat_request).await
+ } else {
+ Ok(vec![])
+ }
+ },
+ async {
+ if should_include_emails {
+ search_emails(ctx, user_id, &query_params, email_request).await
+ } else {
+ Ok(vec![])
+ }
+ },
+ async {
+ if should_include_projects {
+ search_projects(ctx, user_id, &query_params, project_request).await
+ } else {
+ Ok(vec![])
+ }
+ },
+ async {
+ if should_include_channels {
+ search_channels(
+ ctx,
+ user_id,
+ user_context.organization_id,
+ &query_params,
+ channel_request,
+ )
+ .await
+ } else {
+ Ok(vec![])
+ }
+ },
+ );
- let results = ctx
- .opensearch_client
- .search_unified(unified_search_args)
- .await?;
+ // Combine all results
+ let mut combined_results = Vec::new();
+ combined_results.extend(doc_results?);
+ combined_results.extend(chat_results?);
+ combined_results.extend(email_results?);
+ combined_results.extend(project_results?);
+ combined_results.extend(channel_results?);
- Ok(results)
+ Ok(combined_results)
}
/// Perform a search through all items.