Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(soup): ast file assoc expansion (#2674)

Sean Aye5e79b74b23e1
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 0dda191fa5..03fcee282e 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -5513,6 +5513,7 @@ dependencies = [
"model_file_type",
"nom 8.0.0",
"non_empty",
+ "rootcause",
"schemars",
"serde",
"serde_json",
diff --git a/rust/cloud-storage/item_filters/Cargo.toml b/rust/cloud-storage/item_filters/Cargo.toml
index 3630c38777..8354939aeb 100644
--- a/rust/cloud-storage/item_filters/Cargo.toml
+++ b/rust/cloud-storage/item_filters/Cargo.toml
@@ -10,13 +10,14 @@ schema = ["dep:schemars", "dep:utoipa"]
[dependencies]
chrono = { workspace = true }
-either = { workspace = true }
document_sub_type = { path = "../document_sub_type" }
+either = { workspace = true }
filter_ast = { path = "../filter_ast" }
macro_user_id = { path = "../macro_user_id" }
model_file_type = { path = "../model_file_type" }
nom = { workspace = true }
non_empty = { path = "../non_empty" }
+rootcause = { workspace = true }
schemars = { workspace = true, optional = true }
serde = { workspace = true, features = ["rc"] }
serde_json = { workspace = true }
diff --git a/rust/cloud-storage/item_filters/src/ast.rs b/rust/cloud-storage/item_filters/src/ast.rs
index 3ad6030ef8..ee26e871ce 100644
--- a/rust/cloud-storage/item_filters/src/ast.rs
+++ b/rust/cloud-storage/item_filters/src/ast.rs
@@ -82,7 +82,6 @@ pub type LiteralTree<T> = Option<Arc<Expr<T>>>;
/// Describes a bundle of filters that should be applied across different entity types
#[derive(Debug, Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
-#[non_exhaustive]
pub struct EntityFilterAst {
/// the filters that should be applied to the document entity
#[serde(default, rename = "df")]
diff --git a/rust/cloud-storage/item_filters/src/ast/document.rs b/rust/cloud-storage/item_filters/src/ast/document.rs
index 7cb2d246ff..ca99c60435 100644
--- a/rust/cloud-storage/item_filters/src/ast/document.rs
+++ b/rust/cloud-storage/item_filters/src/ast/document.rs
@@ -8,8 +8,10 @@ use model_file_type::{
Font, Image, Md, Media, Pdf, ThreeD, ValueError, Vector, Video, Vm, Write,
};
use nom::{
- IResult, Parser, branch::alt, bytes::complete::tag, combinator::eof, sequence::separated_pair,
+ Finish, IResult, Parser, branch::alt, bytes::complete::tag, combinator::eof,
+ sequence::separated_pair,
};
+use rootcause::Report;
use serde::{Deserialize, Serialize};
use std::str::FromStr;
use strum::IntoEnumIterator;
@@ -111,7 +113,7 @@ fn other(s: &str) -> IResult<&str, impl Iterator<Item = FileType>> {
.parse(s)
}
-fn format(s: &str) -> IResult<&str, impl Iterator<Item = FileType>> {
+fn parse_to_file_types_inner(s: &str) -> IResult<&str, impl Iterator<Item = FileType>> {
let (rest, (_, out)) = separated_pair(
prefix,
tag(":"),
@@ -126,6 +128,13 @@ fn format(s: &str) -> IResult<&str, impl Iterator<Item = FileType>> {
Ok((rest, out))
}
+/// given an input str which is assumed to be a "assoc:SOME_ASSOC" string, return an iter over the file types
+pub fn parse_to_file_types(s: &str) -> Result<(&str, impl Iterator<Item = FileType>), Report> {
+ Ok(parse_to_file_types_inner(s)
+ .finish()
+ .map_err(|e| e.cloned())?)
+}
+
/// Resolve a file type string to concrete [FileType] variants.
/// Handles both plain extensions (e.g. `"md"`, `"pdf"`) and `assoc:*` prefixes
/// (e.g. `"assoc:code"`, `"assoc:other"`). Returns an empty vec if the string
@@ -134,7 +143,7 @@ pub fn resolve_file_types(s: &str) -> Vec<FileType> {
if let Ok(ft) = FileType::from_str(s) {
return vec![ft];
}
- match format(s) {
+ match parse_to_file_types(s) {
Ok((_, iter)) => iter.collect(),
Err(_) => vec![],
}
@@ -144,7 +153,7 @@ fn create_file_iter(s: &str) -> impl Iterator<Item = Result<FileType, ValueError
match FileType::from_str(s) {
Ok(f) => Either::Left(Some(Ok(f)).into_iter()),
Err(e) => {
- let Ok((_, file_types)) = format(s) else {
+ let Ok((_, file_types)) = parse_to_file_types(s) else {
return Either::Left(Some(Err(e)).into_iter());
};
Either::Right(file_types.map(Result::Ok))
diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.toml
index 3bd67840d7..e188831465 100644
--- a/rust/cloud-storage/soup/Cargo.toml
+++ b/rust/cloud-storage/soup/Cargo.toml
@@ -38,9 +38,9 @@ ports = ["dep:tokio", "frecency/ports"]
ai = { path = "../ai", optional = true }
anyhow = { workspace = true }
async-trait = { workspace = true, optional = true }
-call = { path = "../call", default-features = false, features = ["ports"] }
axum = { workspace = true, optional = true }
axum-extra = { workspace = true, optional = true }
+call = { path = "../call", default-features = false, features = ["ports"] }
chrono = { workspace = true }
comms = { path = "../comms", default-features = false }
cowlike = { path = "../cowlike" }
@@ -62,6 +62,7 @@ non_empty = { path = "../non_empty" }
properties_db_client = { path = "../properties_db_client/" }
readonly_pool = { path = "../readonly_pool", optional = true }
recursion = { workspace = true }
+rootcause = { workspace = true }
schemars = { workspace = true, optional = true }
serde = { workspace = true }
sqlx = { workspace = true, optional = true }
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router.rs b/rust/cloud-storage/soup/src/inbound/axum_router.rs
index d9e1c5558e..32cf27ae3b 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router.rs
@@ -17,9 +17,14 @@ use email::{
},
inbound::{EmailLinkErr, EmailLinkExtractor, EmailRouterState},
};
+use filter_ast::{Expr, ExprFrame};
use item_filters::{
EntityFilters,
- ast::{EntityFilterAst, ExpandErr},
+ ast::{
+ EntityFilterAst, ExpandErr, LiteralTree, call::CallLiteral, channel::ChannelLiteral,
+ chat::ChatLiteral, document::DocumentLiteral, email::EmailLiteral, project::ProjectLiteral,
+ properties::PropertiesLiteral,
+ },
};
use macro_user_id::user_id::MacroUserIdStr;
use model_error_response::ErrorResponse;
@@ -29,6 +34,8 @@ use models_pagination::{
TypeEraseCursor,
};
use models_soup::item::SoupItem;
+use recursion::CollapsibleExt;
+use rootcause::{Report, report};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use thiserror::Error;
@@ -213,6 +220,8 @@ pub enum SoupHandlerErr {
EmailLinkErr(#[from] EmailLinkErr),
#[error("Invalid filter arguments provided")]
ExpandErr(ExpandErr),
+ #[error("Invalid compound filter could not be expanded")]
+ Expand,
}
impl From<SoupErr> for SoupHandlerErr {
@@ -227,7 +236,7 @@ impl From<SoupErr> for SoupHandlerErr {
impl IntoResponse for SoupHandlerErr {
fn into_response(self) -> axum::response::Response {
let status_code = match &self {
- SoupHandlerErr::ExpandErr(_) => StatusCode::BAD_REQUEST,
+ SoupHandlerErr::ExpandErr(_) | SoupHandlerErr::Expand => StatusCode::BAD_REQUEST,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(
@@ -360,7 +369,8 @@ where
#[serde(rename_all = "camelCase")]
pub struct PostSoupAstRequest {
#[serde(default, flatten)]
- filters: EntityFilterAst,
+ #[schema(value_type = EntityFilterAst)]
+ filters: ApiEntityFilterAst,
#[serde(default, flatten)]
params: Params,
/// the view of specific emails to display
@@ -404,6 +414,9 @@ where
Err(EmailLinkErr::NotFound) => None,
Err(e) => Err(e)?,
};
+ let filters = filters
+ .into_entity_ast()
+ .map_err(|_| SoupHandlerErr::Expand)?;
service
.handle(
macro_user_id,
@@ -417,3 +430,90 @@ where
)
.await
}
+
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub struct ApiEntityFilterAst {
+ /// the filters that should be applied to the document entity
+ #[serde(default, rename = "df")]
+ pub document_filter: LiteralTree<ApiDocumentLiteral>,
+ /// the filters that should be applied to the project entity
+ #[serde(default, rename = "pf")]
+ pub project_filter: LiteralTree<ProjectLiteral>,
+ /// the filters that should be applied to the chat entity
+ #[serde(default, rename = "cf")]
+ pub chat_filter: LiteralTree<ChatLiteral>,
+ /// the filters that should be applied to the email entity
+ #[serde(default, rename = "ef")]
+ pub email_filter: LiteralTree<EmailLiteral>,
+ /// the filters that should be applied to the channel entity
+ #[serde(default, rename = "chanf")]
+ pub channel_filter: LiteralTree<ChannelLiteral>,
+ /// the filters that should be applied to the call entity
+ #[serde(default, rename = "callf")]
+ pub call_filter: LiteralTree<CallLiteral>,
+ /// the filters that should be applied based on entity properties
+ #[serde(default, rename = "propf")]
+ pub properties_filter: LiteralTree<PropertiesLiteral>,
+}
+
+#[derive(Debug, Serialize, Deserialize, Clone)]
+#[serde(untagged)]
+pub enum ApiDocumentLiteral {
+ Plain(DocumentLiteral),
+ FileAssoc(CompoundDocumentLiteral),
+}
+
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub enum CompoundDocumentLiteral {
+ #[serde(rename = "fa")]
+ FileAssoc(String),
+}
+
+impl ApiEntityFilterAst {
+ #[tracing::instrument(err, skip(self))]
+ fn into_entity_ast(self) -> Result<EntityFilterAst, Report> {
+ let ApiEntityFilterAst {
+ document_filter,
+ project_filter,
+ chat_filter,
+ email_filter,
+ channel_filter,
+ call_filter,
+ properties_filter,
+ } = self;
+
+ let document_filter = document_filter
+ .map(|tree| {
+ tree.as_ref().try_collapse_frames(|frame| match frame {
+ ExprFrame::And(a, b) => Ok(Expr::and(a, b)),
+ ExprFrame::Or(a, b) => Ok(Expr::or(a, b)),
+ ExprFrame::Not(a) => Ok(Expr::is_not(a)),
+ ExprFrame::Literal(ApiDocumentLiteral::Plain(doc_lit)) => {
+ Ok(Expr::val(doc_lit))
+ }
+ ExprFrame::Literal(ApiDocumentLiteral::FileAssoc(compound)) => match compound {
+ CompoundDocumentLiteral::FileAssoc(s) => {
+ let (_, file_types) =
+ item_filters::ast::document::parse_to_file_types(&s)?;
+ file_types
+ .map(|ft| Expr::val(DocumentLiteral::FileType(ft)))
+ .reduce(Expr::or)
+ .ok_or(report!("File association list cannot be empty"))
+ }
+ },
+ })
+ })
+ .transpose()?
+ .map(Arc::new);
+
+ Ok(EntityFilterAst {
+ document_filter,
+ project_filter,
+ chat_filter,
+ email_filter,
+ channel_filter,
+ call_filter,
+ properties_filter,
+ })
+ }
+}
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
index 375aeacd8c..4fb08ed0e5 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
@@ -20,6 +20,8 @@ use std::sync::Arc;
use tower::util::ServiceExt;
use uuid::Uuid;
+use item_filters::ast::EntityFilterAst;
+
use crate::{
domain::{
models::{
@@ -942,3 +944,187 @@ async fn it_can_filter_chat_owners() {
vec!["macro|[email protected]".to_string()]
);
}
+
+#[tokio::test]
+async fn ast_endpoint_expands_file_assoc_pdf() {
+ let soup = MockSoup::new();
+ let inner_counter = soup.called.clone();
+ let router: Router = soup_router(SoupRouterState::new(
+ soup,
+ MockEmailLinkResult {
+ get_link_result: Arc::new(|| Ok(None)),
+ },
+ ))
+ .layer(Extension(UserContext {
+ user_id: "macro|[email protected]".to_string(),
+ fusion_user_id: "1234".to_string(),
+ permissions: None,
+ organization_id: None,
+ }));
+
+ let request = Request::builder()
+ .uri("/soup/ast")
+ .method(Method::POST)
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::to_vec(&json!({
+ "df": { "l": { "fa": "assoc:pdf" } }
+ }))
+ .unwrap(),
+ ))
+ .unwrap();
+
+ let _res = router.oneshot(request).await.unwrap();
+
+ let arg = {
+ let mut guard = inner_counter.lock().unwrap();
+ guard
+ .pop()
+ .expect("SoupService::handle should have been called")
+ };
+
+ let filter: EntityFilterAst = serde_json::from_value(arg.filter).unwrap();
+ let doc_tree = filter
+ .document_filter
+ .expect("document_filter should be set");
+ let doc_json = serde_json::to_value(doc_tree.as_ref()).unwrap();
+ assert_eq!(doc_json, json!({ "l": { "ft": "pdf" } }));
+}
+
+#[tokio::test]
+async fn ast_endpoint_passes_through_plain_document_literal() {
+ let soup = MockSoup::new();
+ let inner_counter = soup.called.clone();
+ let router: Router = soup_router(SoupRouterState::new(
+ soup,
+ MockEmailLinkResult {
+ get_link_result: Arc::new(|| Ok(None)),
+ },
+ ))
+ .layer(Extension(UserContext {
+ user_id: "macro|[email protected]".to_string(),
+ fusion_user_id: "1234".to_string(),
+ permissions: None,
+ organization_id: None,
+ }));
+
+ let doc_id = Uuid::new_v4();
+ let request = Request::builder()
+ .uri("/soup/ast")
+ .method(Method::POST)
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::to_vec(&json!({
+ "df": { "l": { "id": doc_id.to_string() } }
+ }))
+ .unwrap(),
+ ))
+ .unwrap();
+
+ let _res = router.oneshot(request).await.unwrap();
+
+ let arg = {
+ let mut guard = inner_counter.lock().unwrap();
+ guard
+ .pop()
+ .expect("SoupService::handle should have been called")
+ };
+
+ let filter: EntityFilterAst = serde_json::from_value(arg.filter).unwrap();
+ let doc_tree = filter
+ .document_filter
+ .expect("document_filter should be set");
+ let doc_json = serde_json::to_value(doc_tree.as_ref()).unwrap();
+ assert_eq!(doc_json, json!({ "l": { "id": doc_id.to_string() } }));
+}
+
+#[tokio::test]
+async fn ast_endpoint_expands_file_assoc_image_to_or_tree() {
+ let soup = MockSoup::new();
+ let inner_counter = soup.called.clone();
+ let router: Router = soup_router(SoupRouterState::new(
+ soup,
+ MockEmailLinkResult {
+ get_link_result: Arc::new(|| Ok(None)),
+ },
+ ))
+ .layer(Extension(UserContext {
+ user_id: "macro|[email protected]".to_string(),
+ fusion_user_id: "1234".to_string(),
+ permissions: None,
+ organization_id: None,
+ }));
+
+ let request = Request::builder()
+ .uri("/soup/ast")
+ .method(Method::POST)
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::to_vec(&json!({
+ "df": { "l": { "fa": "assoc:image" } }
+ }))
+ .unwrap(),
+ ))
+ .unwrap();
+
+ let _res = router.oneshot(request).await.unwrap();
+
+ let arg = {
+ let mut guard = inner_counter.lock().unwrap();
+ guard
+ .pop()
+ .expect("SoupService::handle should have been called")
+ };
+
+ let filter: EntityFilterAst = serde_json::from_value(arg.filter).unwrap();
+ let doc_tree = filter
+ .document_filter
+ .expect("document_filter should be set");
+
+ // collect all file type strings from the expanded OR-tree
+ fn collect_file_types(
+ expr: &filter_ast::Expr<item_filters::ast::document::DocumentLiteral>,
+ out: &mut Vec<String>,
+ ) {
+ match expr {
+ filter_ast::Expr::Or(a, b) => {
+ collect_file_types(a, out);
+ collect_file_types(b, out);
+ }
+ filter_ast::Expr::Literal(item_filters::ast::document::DocumentLiteral::FileType(
+ ft,
+ )) => {
+ out.push(
+ serde_json::to_value(ft)
+ .unwrap()
+ .as_str()
+ .unwrap()
+ .to_string(),
+ );
+ }
+ other => panic!("unexpected node in expanded image tree: {other:?}"),
+ }
+ }
+
+ let mut actual: Vec<String> = Vec::new();
+ collect_file_types(doc_tree.as_ref(), &mut actual);
+ actual.sort();
+
+ let mut expected: Vec<String> = item_filters::ast::document::resolve_file_types("assoc:image")
+ .into_iter()
+ .map(|ft| {
+ serde_json::to_value(ft)
+ .unwrap()
+ .as_str()
+ .unwrap()
+ .to_string()
+ })
+ .collect();
+ expected.sort();
+
+ assert_eq!(actual, expected);
+ assert!(
+ actual.len() > 1,
+ "image association should expand to multiple file types"
+ );
+}