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): filter parsing (#33)
Sean Aye2396d25798a7
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 91bf5ab006..9dd2716eaf 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -3061,6 +3061,14 @@ dependencies = ["subtle",]+[[package]]+name = "filter_ast"+version = "0.1.0"+dependencies = [+ "recursion",+ "serde",+]+[[package]]name = "flate2"version = "1.0.35"@@ -3133,6 +3141,7 @@ dependencies = ["chrono","cool_asserts","futures",+ "item_filters","lambda_runtime","macro_db_migrator","macro_env",@@ -4207,12 +4216,17 @@ name = "item_filters"version = "0.1.0"dependencies = ["chrono",+ "cool_asserts",+ "filter_ast",+ "macro_user_id","non_empty","schemars","serde","serde_json","strum",+ "thiserror 2.0.17","utoipa",+ "uuid",][[package]]@@ -6510,6 +6524,12 @@ dependencies = ["crossbeam-utils",]+[[package]]+name = "recursion"+version = "0.5.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9dba2197bf7b1d87b4dd460c195f4edeb45a94e82e8054f8d5f317c1f0e93ca1"+[[package]]name = "redis"version = "0.29.0"@@ -7733,6 +7753,7 @@ dependencies = ["chrono","cool_asserts","either",+ "filter_ast","frecency","item_filters","macro_db_migrator",@@ -7743,6 +7764,7 @@ dependencies = ["model_user","models_pagination","models_soup",+ "non_empty","ordered-float","serde","sqlx",@@ -7750,6 +7772,7 @@ dependencies = ["tokio","tracing","utoipa",+ "uuid",][[package]]diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 28933e9d0c..43bc00e629 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -147,7 +147,6 @@ lambda_runtime = "0.13.0"lazy_static = "1.5.0"log = "0.4.26"mockall = "0.13"-nanoid = "0.4.0"nom = "8"openssl = { version = "0.10.71", features = ["vendored"] }pdfium-render = { version = "0.8.28" }diff --git a/rust/cloud-storage/email_service/src/api/email/threads/previews/cursor.rs b/rust/cloud-storage/email_service/src/api/email/threads/previews/cursor.rsindex baa065426b..d70a0e8813 100644--- a/rust/cloud-storage/email_service/src/api/email/threads/previews/cursor.rs+++ b/rust/cloud-storage/email_service/src/api/email/threads/previews/cursor.rs@@ -99,8 +99,11 @@ impl Identify for ThreadPreviewFrecency {}impl SortOn<SimpleSortMethod> for ThreadPreviewFrecency {- fn sort_on(sort: SimpleSortMethod) -> impl FnOnce(&Self) -> CursorVal<SimpleSortMethod> {- let cb = ThreadPreviewCursor::sort_on(sort);+ fn sort_on<F>(+ sort: SimpleSortMethod,+ filter: F,+ ) -> impl FnOnce(&Self) -> CursorVal<SimpleSortMethod, F> {+ let cb = ThreadPreviewCursor::sort_on(sort, filter);move |v| cb(&v.preview)}}@@ -142,7 +145,7 @@ pub async fn previews_handler(link: Extension<Link>,PreviewViewExtractor(preview_view): PreviewViewExtractor,extract::Query(params): extract::Query<GetPreviewsCursorParams>,- cursor: CursorExtractor<Uuid, SimpleSortMethod>,+ cursor: CursorExtractor<Uuid, SimpleSortMethod, ()>,) -> Result<Json<GetPreviewsFrecencyResponse>, GetPreviewsCursorError> {let params = GetPreviewsPaginationCursorParams::new_from_params(params);diff --git a/rust/cloud-storage/filter_ast/Cargo.toml b/rust/cloud-storage/filter_ast/Cargo.tomlnew file mode 100644index 0000000000..37e5608d20--- /dev/null+++ b/rust/cloud-storage/filter_ast/Cargo.toml@@ -0,0 +1,9 @@+[package]+name = "filter_ast"+version = "0.1.0"+edition = "2024"+publish = false++[dependencies]+recursion = "0.5.4"+serde = { workspace = true }diff --git a/rust/cloud-storage/filter_ast/src/lib.rs b/rust/cloud-storage/filter_ast/src/lib.rsnew file mode 100644index 0000000000..5c25f7384f--- /dev/null+++ b/rust/cloud-storage/filter_ast/src/lib.rs@@ -0,0 +1,110 @@+use recursion::{Collapsible, Expandable, MappableFrame, PartiallyApplied};+use serde::{Deserialize, Serialize};++pub trait ExpandNode: Iterator {+ fn 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+where+ I: Iterator,+{+ fn 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>,+ ) -> Result<Option<Expr<U>>, E> {+ self.try_fold(None, |acc, cur| {+ let node = Expr::val(cb(cur)?);+ Ok(Some(match acc {+ Some(acc) => fold(acc, node),+ None => node,+ }))+ })+ }+}++#[derive(Debug)]+pub enum ExprFrame<A, B> {+ And(A, A),+ Or(A, A),+ Not(A),+ Literal(B),+}++#[derive(Debug, Serialize, Deserialize)]+pub enum Expr<B> {+ And(Box<Self>, Box<Self>),+ Or(Box<Self>, Box<Self>),+ Not(Box<Self>),+ Literal(B),+}++impl<B> Expr<B> {+ pub fn and(a: Self, b: Self) -> Self {+ Expr::And(Box::new(a), Box::new(b))+ }++ pub fn or(a: Self, b: Self) -> Self {+ Expr::Or(Box::new(a), Box::new(b))+ }++ pub fn is_not(a: Self) -> Self {+ Expr::Not(Box::new(a))+ }++ pub fn val(v: B) -> Self {+ Expr::Literal(v)+ }+}++pub trait ExpandFrame<T> {+ type Err;+ fn expand_ast(input: Self) -> Result<Option<Expr<T>>, Self::Err>;+}++impl<T, U> MappableFrame for ExprFrame<T, U> {+ type Frame<X> = ExprFrame<X, U>;++ fn map_frame<A, B>(input: Self::Frame<A>, mut f: impl FnMut(A) -> B) -> Self::Frame<B> {+ match input {+ ExprFrame::And(a, b) => ExprFrame::And(f(a), f(b)),+ ExprFrame::Or(a, b) => ExprFrame::Or(f(a), f(b)),+ ExprFrame::Not(a) => ExprFrame::Not(f(a)),+ ExprFrame::Literal(a) => ExprFrame::Literal(a),+ }+ }+}++impl<T> Collapsible for &Expr<T>+where+ T: Clone,+{+ type FrameToken = ExprFrame<PartiallyApplied, T>;++ fn into_frame(self) -> <Self::FrameToken as MappableFrame>::Frame<Self> {+ match self {+ Expr::And(a, b) => ExprFrame::And(a.as_ref(), b.as_ref()),+ Expr::Or(a, b) => ExprFrame::Or(a.as_ref(), b.as_ref()),+ Expr::Not(a) => ExprFrame::Not(a.as_ref()),+ Expr::Literal(a) => ExprFrame::Literal(a.clone()),+ }+ }+}++impl<T> Expandable for Expr<T> {+ type FrameToken = ExprFrame<PartiallyApplied, T>;++ fn from_frame(val: <Self::FrameToken as MappableFrame>::Frame<Self>) -> Self {+ match val {+ ExprFrame::And(a, b) => Expr::And(Box::new(a), Box::new(b)),+ ExprFrame::Or(a, b) => Expr::Or(Box::new(a), Box::new(b)),+ ExprFrame::Not(a) => Expr::Not(Box::new(a)),+ ExprFrame::Literal(a) => Expr::Literal(a),+ }+ }+}diff --git a/rust/cloud-storage/frecency/Cargo.toml b/rust/cloud-storage/frecency/Cargo.tomlindex ba303631d3..8af54ab645 100644--- a/rust/cloud-storage/frecency/Cargo.toml+++ b/rust/cloud-storage/frecency/Cargo.toml@@ -12,6 +12,7 @@ postgres = ["dep:serde_json", "dep:sqlx"]anyhow = { workspace = true }chrono = { workspace = true, features = ["serde"] }futures = { workspace = true }+item_filters = { path = "../item_filters" }lambda_runtime = { workspace = true, optional = true, features = ["tracing"] }macro_env = { path = "../macro_env" }macro_env_var = { path = "../macro_env_var", optional = true }diff --git a/rust/cloud-storage/frecency/src/domain/models.rs b/rust/cloud-storage/frecency/src/domain/models.rsindex 8873eb87f8..f4cf630179 100644--- a/rust/cloud-storage/frecency/src/domain/models.rs+++ b/rust/cloud-storage/frecency/src/domain/models.rs@@ -1,5 +1,6 @@//! This crate provides the utilities to compute aggregate frecency scores from some input eventuse chrono::{DateTime, Utc};+use item_filters::ast::EntityFilterAst;use macro_user_id::{cowlike::CowLike,user_id::{MacroUserIdStr, ParseErr},@@ -304,6 +305,8 @@ pub struct FrecencyPageRequest<'a> {pub from_score: Option<f64>,/// the limit to the number of results to return on the pagepub limit: u32,+ /// the filter ast that should remove values from the output+ pub filters: EntityFilterAst,}/// the response which contains the single page of frecency from the servicediff --git a/rust/cloud-storage/gmail_client/src/parse/thread.rs b/rust/cloud-storage/gmail_client/src/parse/thread.rsindex 5f9d78ebf5..6686723f33 100644--- a/rust/cloud-storage/gmail_client/src/parse/thread.rs+++ b/rust/cloud-storage/gmail_client/src/parse/thread.rs@@ -69,23 +69,20 @@ pub async fn map_thread_resource_to_service(// get the latest timestamp of incoming messages for thread.let latest_inbound_message_ts = service_messages.iter()- .filter(|msg| is_inbound(msg))- .next_back()+ .rfind(|msg| is_inbound(msg)).map(|msg| msg.internal_date_ts).unwrap_or_else(|| None);// get the latest timestamp of outgoing messages for thread.let latest_outbound_message_ts = service_messages.iter()- .filter(|msg| is_outbound(msg))- .next_back()+ .rfind(|msg| is_outbound(msg)).map(|msg| msg.internal_date_ts).unwrap_or_else(|| None);let latest_non_spam_message_ts = service_messages.iter()- .filter(|msg| !is_spam_or_trash(msg))- .next_back()+ .rfind(|msg| !is_spam_or_trash(msg)).map(|msg| msg.internal_date_ts).unwrap_or_else(|| None);diff --git a/rust/cloud-storage/item_filters/Cargo.toml b/rust/cloud-storage/item_filters/Cargo.tomlindex d3c6107365..0ec407daed 100644--- a/rust/cloud-storage/item_filters/Cargo.toml+++ b/rust/cloud-storage/item_filters/Cargo.toml@@ -6,9 +6,16 @@ version = "0.1.0"[dependencies]chrono = { workspace = true }+filter_ast = { path = "../filter_ast" }+macro_user_id = { path = "../macro_user_id" }non_empty = { path = "../non_empty" }schemars = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }strum = { workspace = true }+thiserror = { workspace = true }utoipa = { workspace = true }+uuid = { workspace = true }++[dev-dependencies]+cool_asserts = "2.0.3"diff --git a/rust/cloud-storage/item_filters/src/ast.rs b/rust/cloud-storage/item_filters/src/ast.rsnew file mode 100644index 0000000000..354d82a1f4--- /dev/null+++ b/rust/cloud-storage/item_filters/src/ast.rs@@ -0,0 +1,140 @@+//! 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 non_empty::IsEmpty;+use serde::{Deserialize, Serialize};+use thiserror::Error;+use uuid::Uuid;++#[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);++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>),+}++/// the types of errors that can occur when expanding [DocumentFilters] into an ast+#[derive(Debug, Error)]+pub enum ExpandErr {+ /// unknown file type+ #[error(transparent)]+ FileTypeErr(#[from] UnknownFileType),+ /// invalid uuid+ #[error("Invalid uuid string: {0}")]+ Uuid(#[from] uuid::Error),+ /// invalid macro user id+ #[error(transparent)]+ 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>>,+}++impl EntityFilterAst {+ /// expand the input [EntityFilters] into an ast representation+ pub fn new_from_filters(entity_filter: EntityFilters) -> Result<Self, ExpandErr> {+ if entity_filter.is_empty() {+ return Ok(Self::default());+ }+ Ok(Self {+ document_filter: DocumentFilters::expand_ast(entity_filter.document_filters)?,+ })+ }+}++impl IsEmpty for EntityFilterAst {+ fn is_empty(&self) -> bool {+ let EntityFilterAst { document_filter } = self;+ document_filter.is_none()+ }+}diff --git a/rust/cloud-storage/item_filters/src/ast/tests.rs b/rust/cloud-storage/item_filters/src/ast/tests.rsnew file mode 100644index 0000000000..d75942c33c--- /dev/null+++ b/rust/cloud-storage/item_filters/src/ast/tests.rs@@ -0,0 +1,81 @@+use super::*;+use cool_asserts::assert_matches;+use serde_json::json;++#[test]+fn it_works_with_file_type() {+ let res: Result<Vec<_>, _> = ["pdf", "md", "txt", "html"]+ .into_iter()+ .map(FileType::parse_from_str)+ .collect();++ assert_matches!(+ res.unwrap(),+ [FileType::Pdf, FileType::Md, FileType::Txt, FileType::Html]+ );+}++#[test]+fn it_expands_filters() {+ let document_id = Uuid::new_v4();+ let project_id = Uuid::new_v4();+ let f = EntityFilters {+ document_filters: DocumentFilters {+ file_types: vec!["pdf".to_string(), "txt".to_string()],+ document_ids: vec![document_id.to_string()],+ project_ids: vec![project_id.to_string()],+ owners: vec!["macro|[email protected]".to_string()],+ },+ ..Default::default()+ };++ let ast = EntityFilterAst::new_from_filters(f)+ .unwrap()+ .document_filter+ .unwrap();++ let json = serde_json::to_value(ast).unwrap();+ let exp = json!({+ "And": [+ {+ "And": [+ {+ "And": [+ {+ "Or": [+ {+ "Literal": {+ "FileType": "Pdf",+ }+ },+ {+ "Literal": {+ "FileType": "Txt"+ }+ }+ ]+ },+ {+ "Literal": {+ "Id": document_id+ }+ }+ ]+ },+ {+ "Literal": {+ "ProjectId": project_id+ }+ }+ ]+ },+ {+ "Literal": {+ "Owner": "macro|[email protected]"+ }+ }+ ]+ });++ assert_eq!(json, exp);+}diff --git a/rust/cloud-storage/item_filters/src/lib.rs b/rust/cloud-storage/item_filters/src/lib.rsindex 6ef0667881..46a139f686 100644--- a/rust/cloud-storage/item_filters/src/lib.rs+++ b/rust/cloud-storage/item_filters/src/lib.rs@@ -7,6 +7,8 @@ use serde::{Deserialize, Serialize};use strum::{Display, EnumString};use utoipa::ToSchema;+pub mod ast;+/// Fields that can be searched on in search queries#[derive(Serialize,diff --git a/rust/cloud-storage/model_notifications/src/lib.rs b/rust/cloud-storage/model_notifications/src/lib.rsindex f71d8a8c77..e9ba4be5ec 100644--- a/rust/cloud-storage/model_notifications/src/lib.rs+++ b/rust/cloud-storage/model_notifications/src/lib.rs@@ -277,12 +277,16 @@ impl Identify for Notification {}impl SortOn<CreatedAt> for UserNotification {- fn sort_on(sort: CreatedAt) -> impl FnOnce(&Self) -> models_pagination::CursorVal<CreatedAt> {+ fn sort_on<F>(+ sort: CreatedAt,+ filter: F,+ ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<CreatedAt, F> {move |v| {let last_val = v.temporal.created_at.unwrap_or(DateTime::UNIX_EPOCH);models_pagination::CursorVal {sort_type: sort,last_val,+ filter,}}}diff --git a/rust/cloud-storage/model_notifications/src/raw.rs b/rust/cloud-storage/model_notifications/src/raw.rsindex 3f71d207bb..367f7df2ca 100644--- a/rust/cloud-storage/model_notifications/src/raw.rs+++ b/rust/cloud-storage/model_notifications/src/raw.rs@@ -254,24 +254,32 @@ impl Identify for RawNotification {}impl SortOn<CreatedAt> for RawNotification {- fn sort_on(sort: CreatedAt) -> impl FnOnce(&Self) -> models_pagination::CursorVal<CreatedAt> {+ fn sort_on<F>(+ sort: CreatedAt,+ filter: F,+ ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<CreatedAt, F> {move |v| {let last_val = v.created_at.unwrap_or(DateTime::UNIX_EPOCH);CursorVal {sort_type: sort,last_val,+ filter,}}}}impl SortOn<CreatedAt> for RawUserNotification {- fn sort_on(sort: CreatedAt) -> impl FnOnce(&Self) -> models_pagination::CursorVal<CreatedAt> {+ fn sort_on<F>(+ sort: CreatedAt,+ filter: F,+ ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<CreatedAt, F> {move |v| {let last_val = v.created_at.unwrap_or(DateTime::UNIX_EPOCH);CursorVal {sort_type: sort,last_val,+ filter,}}}diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/html_parser.rs b/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/html_parser.rsindex 2a818da6c5..53836a7ae0 100644--- a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/html_parser.rs+++ b/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/html_parser.rs@@ -106,8 +106,7 @@ fn find_outlook_splitter(document: &Html) -> Option<ElementRef<'_>> {// As a final fallback, find the deepest element matching the text pattern.document.select(&ANY_ELEMENT_SELECTOR)- .filter(|el| FROM_SENT_RE.is_match(&el.text().collect::<String>()))- .next_back()+ .rfind(|el| FROM_SENT_RE.is_match(&el.text().collect::<String>()))}fn find_blockquote_splitter(document: &Html) -> Option<ElementRef<'_>> {diff --git a/rust/cloud-storage/models_email/src/email/service/thread.rs b/rust/cloud-storage/models_email/src/email/service/thread.rsindex 17f5031f0e..dec566fac9 100644--- a/rust/cloud-storage/models_email/src/email/service/thread.rs+++ b/rust/cloud-storage/models_email/src/email/service/thread.rs@@ -184,14 +184,16 @@ impl ThreadPreviewCursor {}impl SortOn<SimpleSortMethod> for ThreadPreviewCursor {- fn sort_on(+ fn sort_on<F>(sort: SimpleSortMethod,- ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<SimpleSortMethod> {+ filter: F,+ ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<SimpleSortMethod, F> {move |v| {let last_val = v.timestamp_for_sort_method(sort);models_pagination::CursorVal {sort_type: sort,last_val,+ filter,}}}@@ -390,7 +392,7 @@ pub struct PreviewCursorQuery {pub view: PreviewView,pub link_id: Uuid,pub limit: u32,- pub query: Query<Uuid, SimpleSortMethod>,+ pub query: Query<Uuid, SimpleSortMethod, ()>,}#[cfg(test)]diff --git a/rust/cloud-storage/models_pagination/src/axum.rs b/rust/cloud-storage/models_pagination/src/axum.rsindex 31117529d8..b75e88e12d 100644--- a/rust/cloud-storage/models_pagination/src/axum.rs+++ b/rust/cloud-storage/models_pagination/src/axum.rs@@ -1,4 +1,4 @@-use crate::{Base64SerdeErr, Base64Str, Cursor, CursorVal, CursorWithVal, Sortable};+use crate::{Base64SerdeErr, Base64Str, Cursor, CursorVal, CursorWithValAndFilter, Sortable};use axum::extract::{FromRequestParts, Query};use axum::http::{StatusCode, request::Parts};use axum::response::IntoResponse;@@ -12,23 +12,23 @@ use serde::de::DeserializeOwned;/// Provided but invalid cursors will be rejected as 401// TODO: in axum 0.8 there is OptionalFromRequestParts which is preferable to this#[derive(Debug)]-pub enum CursorExtractor<Id, S: Sortable> {+pub enum CursorExtractor<Id, S: Sortable, F> {/// the client provided a valid parsed cursor- Some(Cursor<Id, CursorVal<S>>),+ Some(Cursor<Id, CursorVal<S, F>>),/// the client did not provide a cursor paramNone,}-impl<Id, S: Sortable> CursorExtractor<Id, S> {+impl<Id, S: Sortable, F> CursorExtractor<Id, S, F> {/// convert self into an [Option]- pub fn into_option(self) -> Option<CursorWithVal<Id, S>> {+ pub fn into_option(self) -> Option<CursorWithValAndFilter<Id, S, F>> {match self {CursorExtractor::Some(parsed_cursor) => Some(parsed_cursor),CursorExtractor::None => None,}}/// convert self into a [Query] by supplying a fallback- pub fn into_query(self, sort: S) -> crate::cursor::Query<Id, S> {+ pub fn into_query(self, sort: S) -> crate::cursor::Query<Id, S, F> {crate::cursor::Query::new(self.into_option(), sort)}}@@ -62,12 +62,13 @@ impl IntoResponse for CusorExtractErr {}#[async_trait]-impl<S, Id, Sort> FromRequestParts<S> for CursorExtractor<Id, Sort>+impl<S, Id, Sort, F> FromRequestParts<S> for CursorExtractor<Id, Sort, F>whereS: Send + Sync,Sort: Sortable + DeserializeOwned,Sort::Value: DeserializeOwned,Id: DeserializeOwned,+ F: DeserializeOwned,{type Rejection = CusorExtractErr;@@ -81,7 +82,8 @@ wherereturn Ok(CursorExtractor::None);};- let encoded: Base64Str<Cursor<Id, CursorVal<Sort>>> = Base64Str::new_from_string(cursor);+ let encoded: Base64Str<CursorWithValAndFilter<Id, Sort, F>> =+ Base64Str::new_from_string(cursor);let decoded = encoded.decode(|bytes| serde_json::from_slice(&bytes))diff --git a/rust/cloud-storage/models_pagination/src/cursor.rs b/rust/cloud-storage/models_pagination/src/cursor.rsindex 47c607c66a..6e25ab47bf 100644--- a/rust/cloud-storage/models_pagination/src/cursor.rs+++ b/rust/cloud-storage/models_pagination/src/cursor.rs@@ -43,16 +43,21 @@ pub struct Cursor<Id, C> {}/// Type alias for a [Cursor] with a [CursorVal] which is [Sortable]-pub type CursorWithVal<Id, V> = Cursor<Id, CursorVal<V>>;+pub type CursorWithVal<Id, V> = Cursor<Id, CursorVal<V, ()>>;++/// Type alias for a [Cursor] with a [CursorVal] which is [Sortable] and some filter value F+pub type CursorWithValAndFilter<Id, V, F> = Cursor<Id, CursorVal<V, F>>;/// The value of the [Cursor]. That is, the type of sort we are performing/// as well as the value of that sort on the last item of the page.#[derive(Debug, Serialize, Deserialize, Clone)]-pub struct CursorVal<C: Sortable> {+pub struct CursorVal<C: Sortable, F> {/// the type that we are sorting on, must implement [Sortable]pub sort_type: C,/// the last value of the [Sortable] from the previous pagepub last_val: C::Value,+ /// the value that we are filtering on+ pub filter: F,}/// defines type to be sortable, sortable types must have an associated [Sortable::Value]@@ -63,32 +68,46 @@ pub trait Sortable: std::fmt::Debug {/// Intermediary struct which holds information about the page we are going to create./// The only use for this struct is to call [Paginator::into_page]-pub struct Paginator<Iter, Cb, S> {+pub struct Paginator<Iter, Cb, S, F> {iter: Iter,limit: usize,cb: Cb,sort_on: PhantomData<S>,+ filter_on: PhantomData<F>,}/// The base trait which extends [Iterator] to create a [Paginator] if the trait bounds are metpub trait Paginate: Iterator + Sized {/// turn the iterator into a [Paginator]- fn paginate<Cb, S>(self, limit: usize, cb: Cb) -> Paginator<Self, Cb, S>+ fn paginate<Cb, S, F>(self, limit: usize, cb: Cb) -> Paginator<Self, Cb, S, F>where- Cb: FnOnce(&<Self as Iterator>::Item) -> CursorVal<S>,+ Cb: FnOnce(&<Self as Iterator>::Item) -> CursorVal<S, F>,S: Sortable;}/// extension to [Paginate] with the further requirement that the iterator item implements [SortOn] for this sort value Tpub trait PaginateOn<T: Sortable>: Paginate {/// wrapper over [Paginate::paginate]- fn paginate_on(+ fn paginate_filter_on<F>(self,limit: usize,sort: T,- ) -> Paginator<Self, impl FnOnce(&<Self as Iterator>::Item) -> CursorVal<T>, T>+ filter: F,+ ) -> Paginator<Self, impl FnOnce(&<Self as Iterator>::Item) -> CursorVal<T, F>, T, F>where<Self as Iterator>::Item: SortOn<T>;++ /// wrapper over [PaginateOn::paginate_filter_on] to create cursor without a filter+ fn paginate_on(+ self,+ limit: usize,+ sort: T,+ ) -> Paginator<Self, impl FnOnce(&<Self as Iterator>::Item) -> CursorVal<T, ()>, T, ()>+ where+ <Self as Iterator>::Item: SortOn<T>,+ {+ PaginateOn::paginate_filter_on(self, limit, sort, ())+ }}/// the trait used to uniquely identify a record@@ -104,7 +123,7 @@ pub trait Identify {/// This should be implemented on the item that we iterate over, for the sortable method T that we are trying to paginate onpub trait SortOn<T: Sortable> {/// Given the input sort method T, return a function which produces the [CursorVal] for that T, from an input Self- fn sort_on(sort: T) -> impl FnOnce(&Self) -> CursorVal<T>;+ fn sort_on<F>(sort: T, filter: F) -> impl FnOnce(&Self) -> CursorVal<T, F>;}impl<T> Paginate for T@@ -112,9 +131,9 @@ whereT: Iterator,T::Item: Identify,{- fn paginate<Cb, S>(self, limit: usize, cb: Cb) -> Paginator<Self, Cb, S>+ fn paginate<Cb, S, F>(self, limit: usize, cb: Cb) -> Paginator<Self, Cb, S, F>where- Cb: FnOnce(&<Self as Iterator>::Item) -> CursorVal<S>,+ Cb: FnOnce(&<Self as Iterator>::Item) -> CursorVal<S, F>,S: Sortable,{Paginator {@@ -122,6 +141,7 @@ wherelimit,cb,sort_on: PhantomData,+ filter_on: PhantomData,}}}@@ -130,37 +150,40 @@ impl<Iter, T: Sortable> PaginateOn<T> for IterwhereIter: Paginate,{- fn paginate_on(+ fn paginate_filter_on<F>(self,limit: usize,sort: T,- ) -> Paginator<Self, impl FnOnce(&<Self as Iterator>::Item) -> CursorVal<T>, T>+ filter: F,+ ) -> Paginator<Self, impl FnOnce(&<Self as Iterator>::Item) -> CursorVal<T, F>, T, F>where<Self as Iterator>::Item: SortOn<T>,{- let cb = <<Self as Iterator>::Item as SortOn<T>>::sort_on(sort);+ let cb = <<Self as Iterator>::Item as SortOn<T>>::sort_on(sort, filter);self.paginate(limit, cb)}}/// Type alias for a [Paginated] where we still know the underlying type information of the encoded cursor-pub type PaginatedTypedCursor<T, I, C> = Paginated<T, Base64Str<CursorWithVal<I, C>>>;+pub type PaginatedTypedCursor<T, I, C, F> =+ Paginated<T, Base64Str<CursorWithValAndFilter<I, C, F>>>;/// Type alias for a [Paginated] where the type information of the cursor has been erased. This is identical in memory layout and serialization shape as [PaginatedTypedCursor]pub type PaginatedOpaqueCursor<T> = Paginated<T, String>;-impl<Iter, Cb, S> Paginator<Iter, Cb, S>+impl<Iter, Cb, S, F> Paginator<Iter, Cb, S, F>whereIter: Iterator,Iter::Item: Identify,- Cb: FnOnce(&Iter::Item) -> CursorVal<S>,+ Cb: FnOnce(&Iter::Item) -> CursorVal<S, F>,S: Sortable + Serialize,S::Value: Serialize,+ F: Serialize,<Iter::Item as Identify>::Id: Serialize,{/// Turn self into a [PaginatedTypedCursor]./// This ensures that the page has the correct number of items and encodes the last element of the page into a base64 json encoded representation of the cursor.- pub fn into_page(self) -> PaginatedTypedCursor<Iter::Item, <Iter::Item as Identify>::Id, S> {+ pub fn into_page(self) -> PaginatedTypedCursor<Iter::Item, <Iter::Item as Identify>::Id, S, F> {let Paginator {iter, limit, cb, ..} = self;@@ -187,7 +210,7 @@ where}}-impl<T, I, C: Sortable> PaginatedTypedCursor<T, I, C> {+impl<T, I, C: Sortable, F> PaginatedTypedCursor<T, I, C, F> {/// Erase the type of self./// This doesn't actually change any data it just makes the type less sepcificpub fn type_erase(self) -> PaginatedOpaqueCursor<T> {@@ -282,18 +305,19 @@ where/// A [Query] is either a sort method T/// Or a [CursorWithVal]#[derive(Debug)]-pub enum Query<I, T: Sortable> {+pub enum Query<I, T: Sortable, F> {/// a Sort method TSort(T),/// a [CursorWithVal]- Cursor(CursorWithVal<I, T>),+ Cursor(CursorWithValAndFilter<I, T, F>),}-impl<I, T> Clone for Query<I, T>+impl<I, T, F> Clone for Query<I, T, F>whereT: Sortable + Clone,T::Value: Clone,I: Clone,+ F: Clone,{fn clone(&self) -> Self {match self {@@ -303,9 +327,9 @@ where}}-impl<I, T: Sortable> Query<I, T> {+impl<I, T: Sortable, F> Query<I, T, F> {/// create an instance of [Query] from optionally a [CursorWithVal], fallling back to T if it does not exist- pub fn new(maybe_cursor: Option<CursorWithVal<I, T>>, fallback: T) -> Self {+ pub fn new(maybe_cursor: Option<CursorWithValAndFilter<I, T, F>>, fallback: T) -> Self {match maybe_cursor {Some(c) => Self::Cursor(c),None => Self::Sort(fallback),diff --git a/rust/cloud-storage/models_soup/src/item.rs b/rust/cloud-storage/models_soup/src/item.rsindex 454085cf38..aa3e2660db 100644--- a/rust/cloud-storage/models_soup/src/item.rs+++ b/rust/cloud-storage/models_soup/src/item.rs@@ -159,14 +159,16 @@ impl Identify for SoupItem {}impl SortOn<SimpleSortMethod> for SoupItem {- fn sort_on(+ fn sort_on<F>(sort: SimpleSortMethod,- ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<SimpleSortMethod> {+ filter: F,+ ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<SimpleSortMethod, F> {move |v| {let last_val = v.cursor_timestamp(sort);models_pagination::CursorVal {sort_type: sort,last_val,+ filter,}}}diff --git a/rust/cloud-storage/notification_db_client/src/user_notification/get/get_all.rs b/rust/cloud-storage/notification_db_client/src/user_notification/get/get_all.rsindex 5a785751c8..dc4a99fb0a 100644--- a/rust/cloud-storage/notification_db_client/src/user_notification/get/get_all.rs+++ b/rust/cloud-storage/notification_db_client/src/user_notification/get/get_all.rs@@ -8,7 +8,7 @@ pub async fn get_all_user_notifications(db: &sqlx::PgPool,user_id: &str,limit: u32,- cursor: Query<Uuid, CreatedAt>,+ cursor: Query<Uuid, CreatedAt, ()>,) -> anyhow::Result<Vec<RawUserNotification>> {let query_limit = limit as i64;let (cursor_id, cursor_timestamp) = cursor.vals();@@ -60,7 +60,7 @@ pub async fn get_all_user_notifications_by_event_item_ids(user_id: &str,event_item_id: &[impl ToString + std::fmt::Debug],limit: u32,- cursor: Query<Uuid, CreatedAt>,+ cursor: Query<Uuid, CreatedAt, ()>,) -> anyhow::Result<Vec<RawUserNotification>> {let query_limit = limit as i64;let (cursor_id, cursor_timestamp) = cursor.vals();@@ -139,7 +139,8 @@ mod tests {.last().unwrap().created_at- .unwrap_or(DateTime::UNIX_EPOCH)+ .unwrap_or(DateTime::UNIX_EPOCH),+ filter: ()}}).type_erase()@@ -178,7 +179,8 @@ mod tests {.last().unwrap().created_at- .unwrap_or(DateTime::UNIX_EPOCH)+ .unwrap_or(DateTime::UNIX_EPOCH),+ filter: ()}}).type_erase()diff --git a/rust/cloud-storage/notification_service/src/api/user_notification/bulk_get_user_notifications_by_event_item_id.rs b/rust/cloud-storage/notification_service/src/api/user_notification/bulk_get_user_notifications_by_event_item_id.rsindex 3d65d53558..9c207d0edd 100644--- a/rust/cloud-storage/notification_service/src/api/user_notification/bulk_get_user_notifications_by_event_item_id.rs+++ b/rust/cloud-storage/notification_service/src/api/user_notification/bulk_get_user_notifications_by_event_item_id.rs@@ -53,7 +53,7 @@ pub async fn handler(State(ctx): State<ApiContext>,user_context: Extension<UserContext>,Query(Params { limit }): Query<Params>,- cursor: CursorExtractor<Uuid, CreatedAt>,+ cursor: CursorExtractor<Uuid, CreatedAt, ()>,Json(req): Json<BulkGetUserNotificationsByEventItemIdRequest>,) -> BulkResponse {tracing::info!("bulk_get_user_notifications_by_event_item_id");diff --git a/rust/cloud-storage/notification_service/src/api/user_notification/get_user_notification.rs b/rust/cloud-storage/notification_service/src/api/user_notification/get_user_notification.rsindex 4d9e5d7bf3..5479ed9ff4 100644--- a/rust/cloud-storage/notification_service/src/api/user_notification/get_user_notification.rs+++ b/rust/cloud-storage/notification_service/src/api/user_notification/get_user_notification.rs@@ -45,7 +45,7 @@ pub async fn handler(State(ctx): State<ApiContext>,user_context: Extension<UserContext>,Query(Params { limit }): Query<Params>,- cursor: CursorExtractor<Uuid, CreatedAt>,+ cursor: CursorExtractor<Uuid, CreatedAt, ()>,) -> Result<Json<GetAllUserNotificationsResponse>, (StatusCode, Json<ErrorResponse<'static>>)> {tracing::info!("get_all_user_notifications");diff --git a/rust/cloud-storage/notification_service/src/api/user_notification/get_user_notifications_by_event_item_id.rs b/rust/cloud-storage/notification_service/src/api/user_notification/get_user_notifications_by_event_item_id.rsindex a3a0e93953..4a85a590fb 100644--- a/rust/cloud-storage/notification_service/src/api/user_notification/get_user_notifications_by_event_item_id.rs+++ b/rust/cloud-storage/notification_service/src/api/user_notification/get_user_notifications_by_event_item_id.rs@@ -45,7 +45,7 @@ pub async fn handler(user_context: Extension<UserContext>,Path(PathParams { event_item_id }): Path<PathParams>,Query(Params { limit }): Query<Params>,- cursor: CursorExtractor<Uuid, CreatedAt>,+ cursor: CursorExtractor<Uuid, CreatedAt, ()>,) -> Result<Json<GetAllUserNotificationsResponse>, (StatusCode, Json<ErrorResponse<'static>>)> {tracing::info!("get_user_notifications_by_event_item_id");diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.tomlindex e12d60bf4d..ef00311602 100644--- a/rust/cloud-storage/soup/Cargo.toml+++ b/rust/cloud-storage/soup/Cargo.toml@@ -18,6 +18,7 @@ axum = [anyhow = { workspace = true }axum = { workspace = true, optional = true }either = { version = "1" }+filter_ast = { path = "../filter_ast" }frecency = { path = "../frecency" }item_filters = { path = "../item_filters", optional = true }macro_user_id = { path = "../macro_user_id" }@@ -26,11 +27,13 @@ model-error-response = { path = "../model-error-response", optional = true }model_user = { path = "../model_user", optional = true, features = ["axum"] }models_pagination = { path = "../models_pagination" }models_soup = { path = "../models_soup" }+non_empty = { path = "../non_empty" }serde = { workspace = true }sqlx = { workspace = true }thiserror = { workspace = true }tracing = { workspace = true }utoipa = { workspace = true, optional = true }+uuid = { workspace = true }[dev-dependencies]chrono = { workspace = true }diff --git a/rust/cloud-storage/soup/src/domain/models.rs b/rust/cloud-storage/soup/src/domain/models.rsindex 749f0e6ed5..c4107c861e 100644--- a/rust/cloud-storage/soup/src/domain/models.rs+++ b/rust/cloud-storage/soup/src/domain/models.rs@@ -1,4 +1,5 @@use frecency::domain::{models::AggregateFrecency, ports::FrecencyQueryErr};+use item_filters::ast::EntityFilterAst;use macro_user_id::user_id::MacroUserIdStr;use model_entity::Entity;use models_pagination::{@@ -14,10 +15,18 @@ pub enum SoupType {}/// possible things we can exclude from the results-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum SoupExclude {+#[derive(Debug)]+pub(crate) enum SoupFilter {/// excludes any item that has a frecency record from the resultsFrecency,+ Ast(AstFilter),+}++#[derive(Debug)]+#[expect(dead_code)]+pub(crate) enum AstFilter {+ Normal(EntityFilterAst),+ Frecency(EntityFilterAst),}/// the parameters required for a [SimpleSortMethod]@@ -26,11 +35,11 @@ pub struct SimpleSortRequest<'a> {/// the limit of the number of items to returnpub limit: u16,/// the [ParsedCursor] the client passes (if any)- pub cursor: Query<String, SimpleSortMethod>,+ pub cursor: Query<String, SimpleSortMethod, EntityFilterAst>,/// the id of the userpub user_id: MacroUserIdStr<'a>,/// a list of things that should be excluded from the query- pub exclude: Vec<SoupExclude>,+ pub(crate) filters: Option<SoupFilter>,}#[derive(Debug)]@@ -40,8 +49,8 @@ pub struct AdvancedSortParams<'a> {}pub enum SoupQuery {- Simple(Query<String, SimpleSortMethod>),- Frecency(Query<String, Frecency>),+ Simple(Query<String, SimpleSortMethod, EntityFilterAst>),+ Frecency(Query<String, Frecency, EntityFilterAst>),}pub struct SoupRequest {@@ -49,6 +58,7 @@ pub struct SoupRequest {pub limit: u16,pub cursor: SoupQuery,pub user: MacroUserIdStr<'static>,+ pub filters: EntityFilterAst,}/// a [SoupItem] with an associated frecency score@@ -70,9 +80,10 @@ impl Identify for FrecencySoupItem {}impl SortOn<Frecency> for FrecencySoupItem {- fn sort_on(+ fn sort_on<F>(sort_type: Frecency,- ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<Frecency> {+ filter: F,+ ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<Frecency, F> {move |val| CursorVal {sort_type,// if this record does not have a frecency score we fallback to created_at as the sort@@ -80,13 +91,17 @@ impl SortOn<Frecency> for FrecencySoupItem {Some(f) => FrecencyValue::FrecencyScore(f.data.frecency_score),None => FrecencyValue::UpdatedAt(val.item.updated_at()),},+ filter,}}}impl SortOn<SimpleSortMethod> for FrecencySoupItem {- fn sort_on(sort: SimpleSortMethod) -> impl FnOnce(&Self) -> CursorVal<SimpleSortMethod> {- let cb = SoupItem::sort_on(sort);+ fn sort_on<F>(+ sort: SimpleSortMethod,+ filter: F,+ ) -> impl FnOnce(&Self) -> CursorVal<SimpleSortMethod, F> {+ let cb = SoupItem::sort_on(sort, filter);move |v| cb(&v.item)}}diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rsindex 41c966f510..5388a0d0d9 100644--- a/rust/cloud-storage/soup/src/domain/service.rs+++ b/rust/cloud-storage/soup/src/domain/service.rs@@ -1,7 +1,7 @@use crate::domain::{models::{- AdvancedSortParams, FrecencySoupItem, SimpleSortRequest, SoupErr, SoupExclude, SoupQuery,- SoupRequest, SoupType,+ AdvancedSortParams, AstFilter, FrecencySoupItem, SimpleSortRequest, SoupErr, SoupFilter,+ SoupQuery, SoupRequest, SoupType,},ports::{SoupRepo, SoupService},};@@ -10,6 +10,7 @@ use frecency::domain::{models::{AggregateId, FrecencyPageRequest, JoinFrecency},ports::FrecencyQueryService,};+use item_filters::ast::EntityFilterAst;use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use model_entity::as_owned::ShallowClone;use models_pagination::{@@ -17,6 +18,7 @@ use models_pagination::{SimpleSortMethod,};use models_soup::item::SoupItem;+use non_empty::IsEmpty;use std::cmp::Ordering;#[cfg(test)]@@ -96,7 +98,7 @@ wherelimit: remainder_to_fetch.try_into().unwrap_or(500),cursor: Query::Sort(SimpleSortMethod::UpdatedAt),user_id: user,- exclude: vec![SoupExclude::Frecency],+ filters: Some(SoupFilter::Frecency),},).await?;@@ -105,7 +107,7 @@ whereasync fn handle_advanced_sort(&self,- cursor: Query<String, Frecency>,+ cursor: Query<String, Frecency, EntityFilterAst>,soup_type: SoupType,user: MacroUserIdStr<'static>,limit: u16,@@ -117,9 +119,10 @@ whereCursorVal {sort_type: Frecency,last_val: FrecencyValue::FrecencyScore(score),+ filter,},..- }) => Some(score),+ }) => Some((score, filter)),// we have passed all the frecency values on this cursor so we pull from updated atQuery::Cursor(Cursor {id,@@ -128,6 +131,7 @@ whereCursorVal {sort_type: Frecency,last_val: FrecencyValue::UpdatedAt(updated),+ filter,},}) => {return Ok(Either::Left(@@ -141,10 +145,11 @@ whereval: CursorVal {sort_type: SimpleSortMethod::UpdatedAt,last_val: updated,+ filter,},}),user_id: user,- exclude: vec![SoupExclude::Frecency],+ filters: Some(SoupFilter::Frecency),},).await?,@@ -160,7 +165,7 @@ whereasync fn handle_frecency_cursor(&self,- #[expect(unused_variables)] from_value: Option<f64>,+ #[expect(unused_variables)] from_value: Option<(f64, EntityFilterAst)>,soup_type: SoupType,user: MacroUserIdStr<'static>,limit: u16,@@ -171,6 +176,7 @@ whereuser_id: user.copied(),from_score: None,limit: limit as u32,+ filters: Default::default(),}).await?;@@ -229,7 +235,10 @@ wherelimit,cursor,user_id: req.user,- exclude: Vec::new(),+ filters: match req.filters.is_empty() {+ true => None,+ false => Some(SoupFilter::Ast(AstFilter::Normal(req.filters))),+ },},).await?diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rsindex 20660bb757..90b67b0d4c 100644--- a/rust/cloud-storage/soup/src/domain/service/tests.rs+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs@@ -51,9 +51,9 @@ async fn it_should_not_query_frecency() {limit: 20,user_id,cursor: models_pagination::Query::Sort(SimpleSortMethod::ViewedUpdated),- exclude+ filters} => {- assert_matches!(exclude, []);+ assert_matches!(filters, None);assert_eq!(user_id.as_ref(), "macro|[email protected]");true}@@ -80,6 +80,7 @@ async fn it_should_not_query_frecency() {limit: 0,cursor: SoupQuery::Simple(Query::Sort(SimpleSortMethod::ViewedUpdated)),user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ filters: Default::default(),}).await.unwrap();@@ -147,6 +148,7 @@ async fn it_should_query_frecency() {limit: u16::MAX,cursor: SoupQuery::Frecency(Query::Sort(Frecency)),user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ filters: Default::default(),}).await.unwrap();@@ -214,6 +216,7 @@ async fn it_should_sort_frecency_descending() {limit: u16::MAX,cursor: SoupQuery::Frecency(Query::Sort(Frecency)),user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ filters: Default::default(),}).await.unwrap();@@ -268,10 +271,10 @@ async fn frecency_should_fallback() {SimpleSortRequest {limit: 75,cursor: Query::Sort(SimpleSortMethod::UpdatedAt),- exclude,+ filters,..} => {- assert_matches!(exclude, [SoupExclude::Frecency]);+ assert_matches!(filters, Some(SoupFilter::Frecency));true})@@ -297,6 +300,7 @@ async fn frecency_should_fallback() {limit: 100,cursor: SoupQuery::Frecency(Query::Sort(Frecency)),user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ filters: Default::default(),}).await.unwrap();@@ -318,7 +322,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) }} => {+ 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));@@ -363,6 +367,7 @@ async fn frecency_should_paginate() {limit: 100,cursor: SoupQuery::Frecency(Query::Sort(Frecency)),user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ filters: Default::default(),}).await.unwrap();@@ -386,7 +391,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) }} => {+ 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);@@ -435,9 +440,11 @@ async fn frecency_should_resume_cursor() {val: CursorVal {sort_type: Frecency,last_val: FrecencyValue::FrecencyScore(5.0),+ filter: Default::default(),},})),user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ filters: Default::default(),}).await.unwrap();@@ -458,7 +465,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) }} => {+ 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);@@ -472,8 +479,8 @@ 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 } }), exclude, .. } => {- assert_matches!(exclude, [SoupExclude::Frecency]);+ 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!(filters, Some(SoupFilter::Frecency));let expected_time = <DateTime<Utc>>::default() + Days::new(5);assert_eq!(last_val, &expected_time);assert_eq!(id, "doc-100");@@ -505,9 +512,11 @@ async fn frecency_fallback_cursor_should_resume() {val: CursorVal {sort_type: Frecency,last_val: FrecencyValue::UpdatedAt(DateTime::default() + Days::new(5)),+ filter: Default::default(),},})),user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ filters: Default::default(),}).await.unwrap();@@ -517,7 +526,7 @@ async fn frecency_fallback_cursor_should_resume() {<Base64Str<CursorWithVal<String, Frecency>>>::new_from_string(res.next_cursor.unwrap()).decode_json().unwrap();- assert_matches!(cursor, Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::UpdatedAt(updated) } } => {+ 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);diff --git a/rust/cloud-storage/soup/src/inbound/axum_router.rs b/rust/cloud-storage/soup/src/inbound/axum_router.rsindex 6b50031fe4..103cf88be1 100644--- a/rust/cloud-storage/soup/src/inbound/axum_router.rs+++ b/rust/cloud-storage/soup/src/inbound/axum_router.rs@@ -9,7 +9,10 @@ use axum::{response::IntoResponse,routing::{get, post},};-use item_filters::EntityFilters;+use item_filters::{+ EntityFilters,+ ast::{EntityFilterAst, ExpandErr},+};use macro_user_id::user_id::MacroUserIdStr;use model_error_response::ErrorResponse;use model_user::axum_extractor::MacroUserExtractor;@@ -89,7 +92,7 @@ whereasync fn handle(&self,macro_user_id: MacroUserIdStr<'static>,- #[expect(unused_variables)] PostSoupRequest { filters, params }: PostSoupRequest,+ PostSoupRequest { filters, params }: PostSoupRequest,cursor: SoupCursor,) -> Result<Json<PaginatedOpaqueCursor<SoupApiItem>>, SoupHandlerErr> {let create_fallback = move || {@@ -130,6 +133,7 @@ wherelimit: params.limit.unwrap_or(20),cursor,user: macro_user_id,+ filters: EntityFilterAst::new_from_filters(filters)?,}).await?;@@ -171,8 +175,12 @@ impl SoupApiItem {}#[derive(Debug, Error)]-#[error("An internal server error has occurred")]-pub struct SoupHandlerErr(#[from] SoupErr);+pub enum SoupHandlerErr {+ #[error("An internal server error has occurred")]+ Internal(#[from] SoupErr),+ #[error("Invalid filter arguments provided")]+ ExpandErr(#[from] ExpandErr),+}impl IntoResponse for SoupHandlerErr {fn into_response(self) -> axum::response::Response {@@ -229,8 +237,10 @@ pub struct PostSoupRequest {params: Params,}-type SoupCursor =- Either<CursorExtractor<String, SimpleSortMethod>, CursorExtractor<String, Frecency>>;+type SoupCursor = Either<+ CursorExtractor<String, SimpleSortMethod, EntityFilterAst>,+ CursorExtractor<String, Frecency, EntityFilterAst>,+>;/// Gets the items the user has access to#[utoipa::path(diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rsindex 711b101e31..ebe03b74dc 100644--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs@@ -1,11 +1,10 @@-use either::Either;-use models_soup::item::SoupItem;-use sqlx::PgPool;-use crate::domain::{- models::{AdvancedSortParams, SimpleSortRequest, SoupExclude},+ models::{AdvancedSortParams, SimpleSortRequest, SoupFilter},ports::SoupRepo,};+use either::Either;+use models_soup::item::SoupItem;+use sqlx::PgPool;mod expanded;mod unexpanded;@@ -27,41 +26,46 @@ impl SoupRepo for PgSoupRepo {&self,req: SimpleSortRequest<'a>,) -> impl Future<Output = Result<Vec<SoupItem>, Self::Err>> + Send {- if req.exclude.contains(&SoupExclude::Frecency) {- return Either::Left(expanded::by_cursor::no_frecency_expanded_generic_soup(+ match req.filters {+ Some(SoupFilter::Ast(_ast)) => todo!(),+ Some(SoupFilter::Frecency) => {+ Either::Left(expanded::by_cursor::no_frecency_expanded_generic_soup(+ &self.inner,+ req.user_id,+ req.limit,+ req.cursor,+ ))+ }+ None => Either::Right(expanded::by_cursor::expanded_generic_cursor_soup(&self.inner,req.user_id,req.limit,req.cursor,- ));+ )),}-- Either::Right(expanded::by_cursor::expanded_generic_cursor_soup(- &self.inner,- req.user_id,- req.limit,- req.cursor,- ))}fn unexpanded_generic_cursor_soup<'a>(&self,req: SimpleSortRequest<'a>,) -> impl Future<Output = Result<Vec<SoupItem>, Self::Err>> + Send {- if req.exclude.contains(&SoupExclude::Frecency) {- return Either::Left(expanded::by_cursor::no_frecency_expanded_generic_soup(+ match req.filters {+ Some(SoupFilter::Ast(_ast)) => todo!(),+ Some(SoupFilter::Frecency) => {+ Either::Left(expanded::by_cursor::no_frecency_expanded_generic_soup(+ &self.inner,+ req.user_id,+ req.limit,+ req.cursor,+ ))+ }+ None => Either::Right(unexpanded::by_cursor::unexpanded_generic_cursor_soup(&self.inner,req.user_id,req.limit,req.cursor,- ));+ )),}- Either::Right(unexpanded::by_cursor::unexpanded_generic_cursor_soup(- &self.inner,- req.user_id,- req.limit,- req.cursor,- ))}fn expanded_soup_by_ids<'a>(diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/by_cursor.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/by_cursor.rsindex ba384e5e6f..74ce49d255 100644--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/by_cursor.rs+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/by_cursor.rs@@ -1,3 +1,4 @@+use item_filters::ast::EntityFilterAst;use macro_user_id::user_id::MacroUserIdStr;use models_pagination::{Query, SimpleSortMethod};use models_soup::project::map_soup_project;@@ -16,7 +17,7 @@ pub async fn expanded_generic_cursor_soup(db: &PgPool,user_id: MacroUserIdStr<'_>,limit: u16,- cursor: Query<String, SimpleSortMethod>,+ cursor: Query<String, SimpleSortMethod, EntityFilterAst>,) -> Result<Vec<SoupItem>, sqlx::Error> {let query_limit = limit as i64;let sort_method_str = cursor.sort_method().to_string();@@ -243,7 +244,7 @@ pub async fn no_frecency_expanded_generic_soup(db: &PgPool,user_id: MacroUserIdStr<'_>,limit: u16,- cursor: Query<String, SimpleSortMethod>,+ cursor: Query<String, SimpleSortMethod, EntityFilterAst>,) -> Result<Vec<SoupItem>, sqlx::Error> {let query_limit = limit as i64;let sort_method_str = cursor.sort_method().to_string();diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rsindex 2fc4b55501..5b6ed5c97e 100644--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs@@ -2,6 +2,7 @@ use crate::outbound::pg_soup_repo::expanded::{by_cursor::{expanded_generic_cursor_soup, no_frecency_expanded_generic_soup},by_ids::expanded_soup_by_ids,};+use item_filters::ast::EntityFilterAst;use macro_db_migrator::MACRO_DB_MIGRATIONS;use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use model_entity::EntityType;@@ -146,7 +147,7 @@ async fn test_get_user_items_expanded_cursor(pool: Pool<Postgres>) -> anyhow::Re).await?.into_iter()- .paginate_on(1, SimpleSortMethod::ViewedAt)+ .paginate_filter_on(1, SimpleSortMethod::ViewedAt, EntityFilterAst::default()).into_page();let items = result.items;@@ -592,7 +593,7 @@ async fn test_no_frecency_expanded_cursor_pagination(pool: Pool<Postgres>) -> an).await?.into_iter()- .paginate_on(2, SimpleSortMethod::UpdatedAt)+ .paginate_filter_on(2, SimpleSortMethod::UpdatedAt, EntityFilterAst::default()).into_page();assert_eq!(result.items.len(), 2, "Should get 2 items in first page");diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/unexpanded/by_cursor.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/unexpanded/by_cursor.rsindex 663ba63a27..34953a5613 100644--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/unexpanded/by_cursor.rs+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/unexpanded/by_cursor.rs@@ -1,3 +1,4 @@+use item_filters::ast::EntityFilterAst;use macro_user_id::user_id::MacroUserIdStr;use models_pagination::{Query, SimpleSortMethod};use models_soup::{@@ -17,7 +18,7 @@ pub async fn unexpanded_generic_cursor_soup(db: &PgPool,user_id: MacroUserIdStr<'_>,limit: u16,- cursor: Query<String, SimpleSortMethod>,+ cursor: Query<String, SimpleSortMethod, EntityFilterAst>,) -> Result<Vec<SoupItem>, sqlx::Error> {let query_limit = limit as i64;let sort_method_str = cursor.sort_method().to_string();@@ -231,7 +232,7 @@ pub async fn no_frecency_unexpanded_generic_cursor_soup(db: &PgPool,user_id: MacroUserIdStr<'_>,limit: u16,- cursor: Query<String, SimpleSortMethod>,+ cursor: Query<String, SimpleSortMethod, ()>,) -> Result<Vec<SoupItem>, sqlx::Error> {let query_limit = limit as i64;let sort_method_str = cursor.sort_method().to_string();diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/unexpanded/tests.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/unexpanded/tests.rsindex de07786f1c..365c828851 100644--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/unexpanded/tests.rs+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/unexpanded/tests.rs@@ -2,6 +2,7 @@ use crate::outbound::pg_soup_repo::unexpanded::{by_cursor::{no_frecency_unexpanded_generic_cursor_soup, unexpanded_generic_cursor_soup},by_ids::unexpanded_soup_by_ids,};+use item_filters::ast::EntityFilterAst;use macro_db_migrator::MACRO_DB_MIGRATIONS;use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use model_entity::EntityType;@@ -220,7 +221,7 @@ async fn test_get_user_items_unexpanded_cursor(pool: Pool<Postgres>) -> anyhow::).await?.into_iter()- .paginate_on(1, SimpleSortMethod::ViewedAt)+ .paginate_filter_on(1, SimpleSortMethod::ViewedAt, EntityFilterAst::default()).into_page();assert_eq!(result.items.len(), 1, "Should get 1 item");