Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(soup): add chat and project ast literals (#77)
Sean Aye5a6d425d999d
diff --git a/justfile b/justfilenew file mode 100644index 0000000000..77bb94f154--- /dev/null+++ b/justfile@@ -0,0 +1,2 @@+run_dbs:+ docker-compose up macrodb redis-node-0 redis-node-1 redis-node-2 redis-node-3 redis-node-4 redis-node-5 macrocachediff --git a/rust/cloud-storage/filter_ast/src/lib.rs b/rust/cloud-storage/filter_ast/src/lib.rsindex 5c25f7384f..730ed5032c 100644--- a/rust/cloud-storage/filter_ast/src/lib.rs+++ b/rust/cloud-storage/filter_ast/src/lib.rs@@ -1,19 +1,19 @@use recursion::{Collapsible, Expandable, MappableFrame, PartiallyApplied};use serde::{Deserialize, Serialize};-pub trait ExpandNode: Iterator {- fn expand<U, E>(+pub trait TryExpandNode: Iterator {+ fn try_expand<U, E>(self,cb: impl FnMut(<Self as Iterator>::Item) -> Result<U, E>,fold: impl Fn(Expr<U>, Expr<U>) -> Expr<U>,) -> Result<Option<Expr<U>>, E>;}-impl<I> ExpandNode for I+impl<I> TryExpandNode for IwhereI: Iterator,{- fn expand<U, E>(+ fn try_expand<U, E>(mut self,mut cb: impl FnMut(<Self as Iterator>::Item) -> Result<U, E>,fold: impl Fn(Expr<U>, Expr<U>) -> Expr<U>,@@ -28,6 +28,23 @@ where}}+pub trait FoldTree<T>: Iterator {+ fn fold_with(self, fold: impl Fn(Expr<T>, Expr<T>) -> Expr<T>) -> Option<Expr<T>>;+}++impl<I, T> FoldTree<T> for I+where+ I: Iterator<Item = Option<Expr<T>>>,+{+ fn fold_with(self, fold: impl Fn(Expr<T>, Expr<T>) -> Expr<T>) -> Option<Expr<T>> {+ self.fold(None, |acc, cur| match (acc, cur) {+ (None, None) => None,+ (Some(next), None) | (None, Some(next)) => Some(next),+ (Some(a), Some(b)) => Some(fold(a, b)),+ })+ }+}+#[derive(Debug)]pub enum ExprFrame<A, B> {And(A, A),diff --git a/rust/cloud-storage/item_filters/src/ast.rs b/rust/cloud-storage/item_filters/src/ast.rsindex 354d82a1f4..d5567cefd6 100644--- a/rust/cloud-storage/item_filters/src/ast.rs+++ b/rust/cloud-storage/item_filters/src/ast.rs@@ -1,59 +1,36 @@//! This module defines stricter typing for the filters found in lib.//! This is used to construct a strictly typed ast for the input filters, allowing consumers to have a logical represenation of the required operations-use crate::{DocumentFilters, EntityFilters};-use filter_ast::{ExpandFrame, ExpandNode, Expr};-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};+use crate::{+ ChatFilters, DocumentFilters, EntityFilters, ProjectFilters,+ ast::{+ chat::{ChatLiteral, ChatRole},+ project::ProjectLiteral,+ },+};+use document::DocumentLiteral;+use filter_ast::{ExpandFrame, Expr};use non_empty::IsEmpty;use serde::{Deserialize, Serialize};+use std::marker::PhantomData;use thiserror::Error;-use uuid::Uuid;++mod channel;+mod chat;+mod document;+mod email;+mod project;#[cfg(test)]mod tests;-/// the types of documents we can filter by-#[derive(Debug, Serialize, Deserialize)]-pub enum FileType {- /// the document is a pdf- Pdf,- /// the document is markdown- Md,- /// the document is plaintext- Txt,- /// the document is html- Html,-}-/// encountered an unknown file type#[derive(Debug, Error)]-#[error("Unknown file type: {0}")]-pub struct UnknownFileType(String);+#[error("Found unknown value {0} when attempting to parse {t}", t = std::any::type_name::<T>())]+pub struct UnknownValue<T>(String, PhantomData<T>);-impl FileType {- /// parse the file type from the input- pub fn parse_from_str<T: AsRef<str>>(s: T) -> Result<FileType, UnknownFileType> {- match s.as_ref() {- "pdf" => Ok(FileType::Pdf),- "md" => Ok(FileType::Md),- "txt" => Ok(FileType::Txt),- "html" => Ok(FileType::Html),- _ => Err(UnknownFileType(s.as_ref().to_string())),- }- }-}--/// the literal type that can appear in the item filer ast-#[derive(Debug, Serialize, Deserialize)]-pub enum DocumentLiteral {- /// this node value filters by [FileType]- FileType(FileType),- /// this node value filters by document [Uuid]- Id(Uuid),- /// this node value filters by project [Uuid]- ProjectId(Uuid),- /// this node value filters by document owner- Owner(MacroUserIdStr<'static>),+trait ParseFromStr: Sized {+ fn parse_from_str<T: AsRef<str>>(s: T) -> Result<Self, UnknownValue<Self>>;}/// the types of errors that can occur when expanding [DocumentFilters] into an ast@@ -61,7 +38,10 @@ pub enum DocumentLiteral {pub enum ExpandErr {/// unknown file type#[error(transparent)]- FileTypeErr(#[from] UnknownFileType),+ FileTypeErr(#[from] model_file_type::ValueError<model_file_type::FileType>),+ /// unknown chat type+ #[error(transparent)]+ ChatRoleErr(#[from] UnknownValue<ChatRole>),/// invalid uuid#[error("Invalid uuid string: {0}")]Uuid(#[from] uuid::Error),@@ -70,54 +50,18 @@ pub enum ExpandErr {MacroIdErr(#[from] macro_user_id::user_id::ParseErr),}-impl ExpandFrame<DocumentLiteral> for DocumentFilters {- type Err = ExpandErr;- fn expand_ast(- filter_request: DocumentFilters,- ) -> Result<Option<Expr<DocumentLiteral>>, ExpandErr> {- let DocumentFilters {- file_types,- document_ids,- project_ids,- owners,- } = filter_request;-- let file_types_node = file_types- .iter()- .map(FileType::parse_from_str)- .expand(|r| r.map(DocumentLiteral::FileType), Expr::or)?;-- let document_id_nodes = document_ids- .iter()- .map(|s| Uuid::parse_str(s))- .expand(|r| r.map(DocumentLiteral::Id), Expr::or)?;-- let project_ids = project_ids- .iter()- .map(|s| Uuid::parse_str(s))- .expand(|r| r.map(DocumentLiteral::ProjectId), Expr::or)?;-- let owners = owners- .iter()- .map(|s| MacroUserIdStr::parse_from_str(s).map(CowLike::into_owned))- .expand(|r| r.map(DocumentLiteral::Owner), Expr::or)?;-- Ok([file_types_node, document_id_nodes, project_ids, owners]- .into_iter()- .fold(None, |acc, cur| match (acc, cur) {- (Some(acc), Some(cur)) => Some(Expr::and(acc, cur)),- (None, Some(next)) | (Some(next), None) => Some(next),- (None, None) => None,- }))- }-}-/// Describes a bundle of filters that should be applied across different entity types#[derive(Default, Debug, Serialize, Deserialize)]pub struct EntityFilterAst {/// the filters that should be applied to the document entity#[serde(default)]pub document_filter: Option<Expr<DocumentLiteral>>,+ /// the filters that should be applied to the project entity+ #[serde(default)]+ pub project_filter: Option<Expr<ProjectLiteral>>,+ /// the filters that should be applied to the chat entity+ #[serde(default)]+ pub chat_filter: Option<Expr<ChatLiteral>>,}impl EntityFilterAst {@@ -128,13 +72,19 @@ impl EntityFilterAst {}Ok(Self {document_filter: DocumentFilters::expand_ast(entity_filter.document_filters)?,+ project_filter: ProjectFilters::expand_ast(entity_filter.project_filters)?,+ chat_filter: ChatFilters::expand_ast(entity_filter.chat_filters)?,})}}impl IsEmpty for EntityFilterAst {fn is_empty(&self) -> bool {- let EntityFilterAst { document_filter } = self;- document_filter.is_none()+ let EntityFilterAst {+ document_filter,+ project_filter,+ chat_filter,+ } = self;+ document_filter.is_none() && project_filter.is_none() && chat_filter.is_none()}}diff --git a/rust/cloud-storage/item_filters/src/ast/channel.rs b/rust/cloud-storage/item_filters/src/ast/channel.rsnew file mode 100644index 0000000000..8b13789179--- /dev/null+++ b/rust/cloud-storage/item_filters/src/ast/channel.rs@@ -0,0 +1 @@+diff --git a/rust/cloud-storage/item_filters/src/ast/chat.rs b/rust/cloud-storage/item_filters/src/ast/chat.rsnew file mode 100644index 0000000000..73476611a2--- /dev/null+++ b/rust/cloud-storage/item_filters/src/ast/chat.rs@@ -0,0 +1,75 @@+use filter_ast::{ExpandFrame, Expr, FoldTree, TryExpandNode};+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use crate::{+ ChatFilters,+ ast::{ExpandErr, ParseFromStr, UnknownValue},+};++#[derive(Debug, Serialize, Deserialize)]+pub enum ChatLiteral {+ ProjectId(Uuid),+ Role(ChatRole),+ ChatId(Uuid),+ Owner(MacroUserIdStr<'static>),+}++#[derive(Debug, Serialize, Deserialize)]+pub enum ChatRole {+ User,+ System,+ Assistant,+}++impl ParseFromStr for ChatRole {+ fn parse_from_str<T: AsRef<str>>(s: T) -> Result<Self, super::UnknownValue<Self>> {+ match s.as_ref() {+ "user" => Ok(Self::User),+ "system" => Ok(Self::System),+ "assistant" => Ok(Self::Assistant),+ _ => Err(UnknownValue(+ s.as_ref().to_string(),+ std::marker::PhantomData,+ )),+ }+ }+}++impl ExpandFrame<ChatLiteral> for ChatFilters {+ type Err = ExpandErr;++ fn expand_ast(filter_request: ChatFilters) -> Result<Option<Expr<ChatLiteral>>, Self::Err> {+ let ChatFilters {+ role,+ chat_ids,+ project_ids,+ owners,+ } = filter_request;++ let project_ids = project_ids+ .iter()+ .map(|s| Uuid::parse_str(s))+ .try_expand(|r| r.map(ChatLiteral::ProjectId), Expr::or)?;++ let chat_ids = chat_ids+ .iter()+ .map(|s| Uuid::parse_str(s))+ .try_expand(|r| r.map(ChatLiteral::ChatId), Expr::or)?;++ let role = role+ .iter()+ .map(ChatRole::parse_from_str)+ .try_expand(|r| r.map(ChatLiteral::Role), Expr::or)?;++ let owners = owners+ .iter()+ .map(|s| MacroUserIdStr::parse_from_str(s).map(CowLike::into_owned))+ .try_expand(|r| r.map(ChatLiteral::Owner), Expr::or)?;++ Ok([project_ids, chat_ids, role, owners]+ .into_iter()+ .fold_with(Expr::and))+ }+}diff --git a/rust/cloud-storage/item_filters/src/ast/document.rs b/rust/cloud-storage/item_filters/src/ast/document.rsnew file mode 100644index 0000000000..b1abd14f77--- /dev/null+++ b/rust/cloud-storage/item_filters/src/ast/document.rs@@ -0,0 +1,58 @@+use crate::{DocumentFilters, ast::ExpandErr};+use filter_ast::{ExpandFrame, Expr, FoldTree, TryExpandNode};+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};+use model_file_type::FileType;+use serde::{Deserialize, Serialize};+use std::str::FromStr;+use uuid::Uuid;++/// the literal type that can appear in the item filer ast+#[derive(Debug, Serialize, Deserialize)]+pub enum DocumentLiteral {+ /// this node value filters by [FileType]+ FileType(FileType),+ /// this node value filters by document [Uuid]+ Id(Uuid),+ /// this node value filters by project [Uuid]+ ProjectId(Uuid),+ /// this node value filters by document owner+ Owner(MacroUserIdStr<'static>),+}++impl ExpandFrame<DocumentLiteral> for DocumentFilters {+ type Err = ExpandErr;+ fn expand_ast(+ filter_request: DocumentFilters,+ ) -> Result<Option<Expr<DocumentLiteral>>, ExpandErr> {+ let DocumentFilters {+ file_types,+ document_ids,+ project_ids,+ owners,+ } = filter_request;++ let file_types_node = file_types+ .iter()+ .map(|s| FileType::from_str(s))+ .try_expand(|r| r.map(DocumentLiteral::FileType), Expr::or)?;++ let document_id_nodes = document_ids+ .iter()+ .map(|s| Uuid::parse_str(s))+ .try_expand(|r| r.map(DocumentLiteral::Id), Expr::or)?;++ let project_ids = project_ids+ .iter()+ .map(|s| Uuid::parse_str(s))+ .try_expand(|r| r.map(DocumentLiteral::ProjectId), Expr::or)?;++ let owners = owners+ .iter()+ .map(|s| MacroUserIdStr::parse_from_str(s).map(CowLike::into_owned))+ .try_expand(|r| r.map(DocumentLiteral::Owner), Expr::or)?;++ Ok([file_types_node, document_id_nodes, project_ids, owners]+ .into_iter()+ .fold_with(Expr::and))+ }+}diff --git a/rust/cloud-storage/item_filters/src/ast/email.rs b/rust/cloud-storage/item_filters/src/ast/email.rsnew file mode 100644index 0000000000..8b13789179--- /dev/null+++ b/rust/cloud-storage/item_filters/src/ast/email.rs@@ -0,0 +1 @@+diff --git a/rust/cloud-storage/item_filters/src/ast/project.rs b/rust/cloud-storage/item_filters/src/ast/project.rsnew file mode 100644index 0000000000..f47a82e24f--- /dev/null+++ b/rust/cloud-storage/item_filters/src/ast/project.rs@@ -0,0 +1,35 @@+use filter_ast::{ExpandFrame, Expr, FoldTree, TryExpandNode};+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use crate::{ProjectFilters, ast::ExpandErr};++#[derive(Debug, Serialize, Deserialize)]+pub enum ProjectLiteral {+ ProjectId(Uuid),+ Owner(MacroUserIdStr<'static>),+}++impl ExpandFrame<ProjectLiteral> for ProjectFilters {+ type Err = ExpandErr;++ fn expand_ast(input: Self) -> Result<Option<filter_ast::Expr<ProjectLiteral>>, Self::Err> {+ let ProjectFilters {+ project_ids,+ owners,+ } = input;++ let project_ids = project_ids+ .iter()+ .map(|s| Uuid::parse_str(s))+ .try_expand(|r| r.map(ProjectLiteral::ProjectId), Expr::or)?;++ let owners = owners+ .iter()+ .map(|s| MacroUserIdStr::parse_from_str(s).map(CowLike::into_owned))+ .try_expand(|r| r.map(ProjectLiteral::Owner), Expr::or)?;++ Ok([project_ids, owners].into_iter().fold_with(Expr::and))+ }+}diff --git a/rust/cloud-storage/item_filters/src/ast/tests.rs b/rust/cloud-storage/item_filters/src/ast/tests.rsindex d75942c33c..d2219f0814 100644--- a/rust/cloud-storage/item_filters/src/ast/tests.rs+++ b/rust/cloud-storage/item_filters/src/ast/tests.rs@@ -1,12 +1,16 @@+use std::str::FromStr;+use super::*;use cool_asserts::assert_matches;+use model_file_type::FileType;use serde_json::json;+use uuid::Uuid;#[test]fn it_works_with_file_type() {let res: Result<Vec<_>, _> = ["pdf", "md", "txt", "html"].into_iter()- .map(FileType::parse_from_str)+ .map(FileType::from_str).collect();assert_matches!(@@ -45,12 +49,12 @@ fn it_expands_filters() {"Or": [{"Literal": {- "FileType": "Pdf",+ "FileType": "pdf",}},{"Literal": {- "FileType": "Txt"+ "FileType": "txt"}}]diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.tomlindex e87818a2d1..cd3960e7ff 100644--- a/rust/cloud-storage/soup/Cargo.toml+++ b/rust/cloud-storage/soup/Cargo.toml@@ -7,7 +7,6 @@ version = "0.1.0"[features]axum = ["dep:axum",- "dep:item_filters","dep:model-error-response","dep:model_user","dep:utoipa",@@ -21,7 +20,7 @@ axum = { workspace = true, optional = true }either = { version = "1" }filter_ast = { path = "../filter_ast" }frecency = { path = "../frecency" }-item_filters = { path = "../item_filters", optional = true }+item_filters = { path = "../item_filters" }macro_user_id = { path = "../macro_user_id" }model-entity = { path = "../model-entity" }model-error-response = { path = "../model-error-response", optional = true }@@ -40,11 +39,11 @@ uuid = { workspace = true }chrono = { workspace = true }cool_asserts = "2"frecency = { path = "../frecency", features = ["mock"] }+futures = { workspace = true }+http-body-util = { workspace = true }macro_db_migrator = { path = "../macro_db_migrator" }mockall = { workspace = true }ordered-float = "5"+serde_json = { workspace = true }tokio = { workspace = true }tower = { workspace = true }-futures = { workspace = true }-http-body-util = { workspace = true }-serde_json = { workspace = true }diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rsindex 2f5e01c9d3..249eda6a93 100644--- a/rust/cloud-storage/soup/src/domain/service/tests.rs+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs@@ -6,8 +6,7 @@ use frecency::domain::services::FrecencyQueryServiceImpl;use frecency::{domain::models::AggregateFrecency, outbound::mock::MockFrecencyStorage};use model_entity::EntityType;use models_pagination::{- Base64Str, Cursor, CursorVal, CursorWithVal, CursorWithValAndFilter, FrecencyValue,- SimpleSortMethod,+ Base64Str, Cursor, CursorVal, CursorWithValAndFilter, FrecencyValue, SimpleSortMethod,};use models_soup::document::SoupDocument;use ordered_float::OrderedFloat;@@ -325,7 +324,7 @@ async fn frecency_should_fallback() {.unwrap();assert_matches!(typed_cursor,- Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::UpdatedAt(updated), filter: EntityFilterAst { document_filter: None } }} => {+ Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::UpdatedAt(updated), filter: _ }} => {assert_eq!(id, "doc-100");assert_eq!(updated, <DateTime<Utc>>::default() + Days::new(100));@@ -396,7 +395,7 @@ async fn frecency_should_paginate() {.unwrap();assert_matches!(typed_cursor,- Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::FrecencyScore(score), filter: EntityFilterAst { document_filter: None } }} => {+ Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::FrecencyScore(score), filter: _ }} => {assert_eq!(id, "doc-1");// last item should be the lowest score because we sort descassert_eq!(score as u32, 1u32);@@ -472,7 +471,7 @@ async fn frecency_should_resume_cursor() {.unwrap();assert_matches!(typed_cursor,- Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::FrecencyScore(score), filter: EntityFilterAst { document_filter: None } }} => {+ Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::FrecencyScore(score), filter: _ }} => {assert_eq!(id, "doc-next-100");// last item should be the lowest score because we sort descassert_eq!(score as u32, 4u32);@@ -486,7 +485,26 @@ async fn frecency_fallback_cursor_should_resume() {soup.expect_unexpanded_generic_cursor_soup().withf(|params| {- assert_matches!(params, SimpleSortRequest { limit: 100, cursor: Query::Cursor(Cursor { id, limit: 100, val: CursorVal { sort_type: SimpleSortMethod::UpdatedAt, last_val, filter: EntityFilterAst { document_filter: None } } }), filters, .. } => {+ assert_matches!(+ params,+ SimpleSortRequest {+ limit: 100,+ cursor: Query::Cursor(Cursor {+ id,+ limit: 100,+ val: CursorVal {+ sort_type: SimpleSortMethod::UpdatedAt,+ last_val,+ filter: EntityFilterAst {+ document_filter: None,+ project_filter: None,+ chat_filter: None+ }+ }+ }),+ filters,+ ..+ } => {assert_matches!(filters, Some(SoupFilter::Frecency));let expected_time = <DateTime<Utc>>::default() + Days::new(5);assert_eq!(last_val, &expected_time);@@ -535,7 +553,7 @@ async fn frecency_fallback_cursor_should_resume() {).decode_json().unwrap();- assert_matches!(cursor, Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::UpdatedAt(updated), filter: EntityFilterAst { document_filter: None } } } => {+ assert_matches!(cursor, Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::UpdatedAt(updated), filter: _ } } => {assert_eq!(id, "doc-next-100");let expected_date = <DateTime<Utc>>::default() + Days::new(100);assert_eq!(updated, expected_date);