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): dynamic soup filter (#112)

Sean Ayede87864de3fd
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 2b5e9ac40f..38b30ad26a 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -7785,6 +7785,7 @@ dependencies = [
"models_soup",
"non_empty",
"ordered-float",
+ "recursion",
"serde",
"serde_json",
"sqlx",
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 81ec00e1d7..dfae9b9f96 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -154,6 +154,7 @@ nom = "8"
openssl = { version = "0.10.71", features = ["vendored"] }
pdfium-render = { version = "0.8.28" }
rand = "0.9.0"
+recursion = "0.5.4"
redis = "0.29.0"
regex = "1.11.1"
reqwest = { version = "0.12.12", features = ["json"] }
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.rs
index 6c0f88bd90..353d145735 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
@@ -100,11 +100,8 @@ impl Identify for ThreadPreviewFrecency {
}
impl SortOn<SimpleSortMethod> for ThreadPreviewFrecency {
- fn sort_on<F>(
- sort: SimpleSortMethod,
- filter: F,
- ) -> impl FnOnce(&Self) -> CursorVal<SimpleSortMethod, F> {
- let cb = ThreadPreviewCursor::sort_on(sort, filter);
+ fn sort_on(sort: SimpleSortMethod) -> impl FnOnce(&Self) -> CursorVal<SimpleSortMethod> {
+ let cb = ThreadPreviewCursor::sort_on(sort);
move |v| cb(&v.preview)
}
}
diff --git a/rust/cloud-storage/filter_ast/Cargo.toml b/rust/cloud-storage/filter_ast/Cargo.toml
index 37e5608d20..f31d5a65d6 100644
--- a/rust/cloud-storage/filter_ast/Cargo.toml
+++ b/rust/cloud-storage/filter_ast/Cargo.toml
@@ -1,9 +1,9 @@
[package]
-name = "filter_ast"
-version = "0.1.0"
edition = "2024"
+name = "filter_ast"
publish = false
+version = "0.1.0"
[dependencies]
-recursion = "0.5.4"
+recursion = { workspace = true }
serde = { workspace = true }
diff --git a/rust/cloud-storage/item_filters/src/ast.rs b/rust/cloud-storage/item_filters/src/ast.rs
index 0899095585..00b176a86d 100644
--- a/rust/cloud-storage/item_filters/src/ast.rs
+++ b/rust/cloud-storage/item_filters/src/ast.rs
@@ -15,11 +15,16 @@ use serde::{Deserialize, Serialize};
use std::{marker::PhantomData, sync::Arc};
use thiserror::Error;
-mod channel;
-mod chat;
-mod document;
-mod email;
-mod project;
+/// contains the ast literal value for channels
+pub mod channel;
+/// contains the ast literal value for chat
+pub mod chat;
+/// contains the ast literal value for documents
+pub mod document;
+/// contains the ast literal value for emails
+pub mod email;
+/// contains the ast literal value for projects
+pub mod project;
#[cfg(test)]
mod tests;
diff --git a/rust/cloud-storage/item_filters/src/ast/chat.rs b/rust/cloud-storage/item_filters/src/ast/chat.rs
index 73476611a2..fb1dd03d9f 100644
--- a/rust/cloud-storage/item_filters/src/ast/chat.rs
+++ b/rust/cloud-storage/item_filters/src/ast/chat.rs
@@ -8,18 +8,27 @@ use crate::{
ast::{ExpandErr, ParseFromStr, UnknownValue},
};
-#[derive(Debug, Serialize, Deserialize)]
+/// the literal ast type for the chat entity
+#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum ChatLiteral {
+ /// the chat is in some nested project structure where [Uuid] is a parent node
ProjectId(Uuid),
+ /// the chat has role [ChatRole]
Role(ChatRole),
+ /// the chat has the id [Uuid]
ChatId(Uuid),
+ /// the chat is owned by [MacroUserIdStr]
Owner(MacroUserIdStr<'static>),
}
-#[derive(Debug, Serialize, Deserialize)]
+/// the possible roles for a chat
+#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum ChatRole {
+ /// the role is user
User,
+ /// the role is system
System,
+ /// the role is assistant
Assistant,
}
diff --git a/rust/cloud-storage/item_filters/src/ast/document.rs b/rust/cloud-storage/item_filters/src/ast/document.rs
index b1abd14f77..4f041b68c8 100644
--- a/rust/cloud-storage/item_filters/src/ast/document.rs
+++ b/rust/cloud-storage/item_filters/src/ast/document.rs
@@ -7,7 +7,7 @@ use std::str::FromStr;
use uuid::Uuid;
/// the literal type that can appear in the item filer ast
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum DocumentLiteral {
/// this node value filters by [FileType]
FileType(FileType),
diff --git a/rust/cloud-storage/item_filters/src/ast/project.rs b/rust/cloud-storage/item_filters/src/ast/project.rs
index f47a82e24f..7707c2cfe4 100644
--- a/rust/cloud-storage/item_filters/src/ast/project.rs
+++ b/rust/cloud-storage/item_filters/src/ast/project.rs
@@ -5,9 +5,12 @@ use uuid::Uuid;
use crate::{ProjectFilters, ast::ExpandErr};
-#[derive(Debug, Serialize, Deserialize)]
+/// the literal ast types for a project
+#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum ProjectLiteral {
+ /// the id of the project
ProjectId(Uuid),
+ /// the owner of the project
Owner(MacroUserIdStr<'static>),
}
diff --git a/rust/cloud-storage/macro_user_id/src/user_id.rs b/rust/cloud-storage/macro_user_id/src/user_id.rs
index a8e9b81243..92c468e391 100644
--- a/rust/cloud-storage/macro_user_id/src/user_id.rs
+++ b/rust/cloud-storage/macro_user_id/src/user_id.rs
@@ -67,6 +67,12 @@ where
#[serde(try_from = "String", into = "String")]
pub struct MacroUserIdStr<'a>(pub MacroUserId<ArcCowStr<'a>>);
+impl<'a> std::fmt::Display for MacroUserIdStr<'a> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.0.as_ref())
+ }
+}
+
impl<'a> Deref for MacroUserIdStr<'a> {
type Target = MacroUserId<ArcCowStr<'a>>;
diff --git a/rust/cloud-storage/model_notifications/src/lib.rs b/rust/cloud-storage/model_notifications/src/lib.rs
index e9ba4be5ec..f71d8a8c77 100644
--- a/rust/cloud-storage/model_notifications/src/lib.rs
+++ b/rust/cloud-storage/model_notifications/src/lib.rs
@@ -277,16 +277,12 @@ impl Identify for Notification {
}
impl SortOn<CreatedAt> for UserNotification {
- fn sort_on<F>(
- sort: CreatedAt,
- filter: F,
- ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<CreatedAt, F> {
+ fn sort_on(sort: CreatedAt) -> impl FnOnce(&Self) -> models_pagination::CursorVal<CreatedAt> {
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.rs
index 367f7df2ca..3f71d207bb 100644
--- a/rust/cloud-storage/model_notifications/src/raw.rs
+++ b/rust/cloud-storage/model_notifications/src/raw.rs
@@ -254,32 +254,24 @@ impl Identify for RawNotification {
}
impl SortOn<CreatedAt> for RawNotification {
- fn sort_on<F>(
- sort: CreatedAt,
- filter: F,
- ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<CreatedAt, F> {
+ fn sort_on(sort: CreatedAt) -> impl FnOnce(&Self) -> models_pagination::CursorVal<CreatedAt> {
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<F>(
- sort: CreatedAt,
- filter: F,
- ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<CreatedAt, F> {
+ fn sort_on(sort: CreatedAt) -> impl FnOnce(&Self) -> models_pagination::CursorVal<CreatedAt> {
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/thread.rs b/rust/cloud-storage/models_email/src/email/service/thread.rs
index dec566fac9..06f29e3fdf 100644
--- a/rust/cloud-storage/models_email/src/email/service/thread.rs
+++ b/rust/cloud-storage/models_email/src/email/service/thread.rs
@@ -184,16 +184,14 @@ impl ThreadPreviewCursor {
}
impl SortOn<SimpleSortMethod> for ThreadPreviewCursor {
- fn sort_on<F>(
+ fn sort_on(
sort: SimpleSortMethod,
- filter: F,
- ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<SimpleSortMethod, F> {
+ ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<SimpleSortMethod> {
move |v| {
let last_val = v.timestamp_for_sort_method(sort);
models_pagination::CursorVal {
sort_type: sort,
last_val,
- filter,
}
}
}
diff --git a/rust/cloud-storage/models_pagination/src/axum.rs b/rust/cloud-storage/models_pagination/src/axum.rs
index 4f4627a1e1..585ab29ec1 100644
--- a/rust/cloud-storage/models_pagination/src/axum.rs
+++ b/rust/cloud-storage/models_pagination/src/axum.rs
@@ -16,13 +16,13 @@ use thiserror::Error;
#[derive(Debug)]
pub enum CursorExtractor<Id, S: Sortable, F> {
/// the client provided a valid parsed cursor
- Some(Cursor<Id, CursorVal<S, F>>),
+ Some(Cursor<Id, CursorVal<S>, F>),
/// the client did not provide a cursor param
None,
}
impl<Id, S: Sortable, F> CursorExtractor<Id, S, F> {
- /// convert self into an [Option]
+ /// convert self into an [Option]CursorWithVal
pub fn into_option(self) -> Option<CursorWithValAndFilter<Id, S, F>> {
match self {
CursorExtractor::Some(parsed_cursor) => Some(parsed_cursor),
@@ -85,7 +85,6 @@ where
else {
return Ok(CursorExtractor::None);
};
-
let encoded: Base64Str<CursorWithValAndFilter<Id, Sort, F>> =
Base64Str::new_from_string(cursor);
diff --git a/rust/cloud-storage/models_pagination/src/cursor.rs b/rust/cloud-storage/models_pagination/src/cursor.rs
index 7c2701dfdd..b5e98f0271 100644
--- a/rust/cloud-storage/models_pagination/src/cursor.rs
+++ b/rust/cloud-storage/models_pagination/src/cursor.rs
@@ -32,7 +32,7 @@ impl<T, U> Paginated<T, U> {
/// Top level cursor information encodes all the required information for paginating by [Cursor]
#[derive(Debug, Serialize, Deserialize, Clone)]
-pub struct Cursor<Id, C> {
+pub struct Cursor<Id, C, F> {
/// the unique id (e.g. i64, uuid, stc) that identifies the last entity
/// on the previous page
pub id: Id,
@@ -41,24 +41,25 @@ pub struct Cursor<Id, C> {
/// the value of the cursor
/// this is usually a [CursorVal]
pub val: C,
+
+ /// the value we are filtering on
+ pub filter: F,
}
/// 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>>;
+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, F> {
+pub struct CursorVal<C: Sortable> {
/// the type that we are sorting on, must implement [Sortable]
pub sort_type: C,
/// the last value of the [Sortable] from the previous page
pub 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]
@@ -74,41 +75,48 @@ pub struct Paginator<Iter, Cb, S, F> {
limit: usize,
cb: Cb,
sort_on: PhantomData<S>,
- filter_on: PhantomData<F>,
+ filter_on: F,
+}
+
+impl<Iter, Cb, S> Paginator<Iter, Cb, S, ()> {
+ /// define the filter that the cursor is using
+ pub fn filter_on<F>(self, filter: F) -> Paginator<Iter, Cb, S, F> {
+ let Paginator {
+ iter,
+ limit,
+ cb,
+ sort_on,
+ filter_on: (),
+ } = self;
+ Paginator {
+ iter,
+ limit,
+ cb,
+ sort_on,
+ filter_on: filter,
+ }
+ }
}
/// The base trait which extends [Iterator] to create a [Paginator] if the trait bounds are met
pub trait Paginate: Iterator + Sized {
/// turn the iterator into a [Paginator]
- fn paginate<Cb, S, F>(self, limit: usize, cb: Cb) -> Paginator<Self, Cb, S, F>
+ fn paginate<Cb, S>(self, limit: usize, cb: Cb) -> Paginator<Self, Cb, S, ()>
where
- Cb: FnOnce(&<Self as Iterator>::Item) -> CursorVal<S, F>,
+ Cb: FnOnce(&<Self as Iterator>::Item) -> CursorVal<S>,
S: Sortable;
}
/// extension to [Paginate] with the further requirement that the iterator item implements [SortOn] for this sort value T
pub trait PaginateOn<T: Sortable>: Paginate {
/// wrapper over [Paginate::paginate]
- fn paginate_filter_on<F>(
- self,
- limit: usize,
- sort: 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, ()>
+ ) -> 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, ())
- }
+ <Self as Iterator>::Item: SortOn<T>;
}
/// the trait used to uniquely identify a record
@@ -124,7 +132,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 on
pub 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<F>(sort: T, filter: F) -> impl FnOnce(&Self) -> CursorVal<T, F>;
+ fn sort_on(sort: T) -> impl FnOnce(&Self) -> CursorVal<T>;
}
impl<T> Paginate for T
@@ -132,9 +140,9 @@ where
T: Iterator,
T::Item: Identify,
{
- fn paginate<Cb, S, F>(self, limit: usize, cb: Cb) -> Paginator<Self, Cb, S, F>
+ fn paginate<Cb, S>(self, limit: usize, cb: Cb) -> Paginator<Self, Cb, S, ()>
where
- Cb: FnOnce(&<Self as Iterator>::Item) -> CursorVal<S, F>,
+ Cb: FnOnce(&<Self as Iterator>::Item) -> CursorVal<S>,
S: Sortable,
{
Paginator {
@@ -142,7 +150,7 @@ where
limit,
cb,
sort_on: PhantomData,
- filter_on: PhantomData,
+ filter_on: (),
}
}
}
@@ -151,16 +159,15 @@ impl<Iter, T: Sortable> PaginateOn<T> for Iter
where
Iter: Paginate,
{
- fn paginate_filter_on<F>(
+ fn paginate_on(
self,
limit: usize,
sort: T,
- filter: F,
- ) -> Paginator<Self, impl FnOnce(&<Self as Iterator>::Item) -> CursorVal<T, F>, T, F>
+ ) -> Paginator<Self, impl FnOnce(&<Self as Iterator>::Item) -> CursorVal<T>, T, ()>
where
<Self as Iterator>::Item: SortOn<T>,
{
- let cb = <<Self as Iterator>::Item as SortOn<T>>::sort_on(sort, filter);
+ let cb = <<Self as Iterator>::Item as SortOn<T>>::sort_on(sort);
self.paginate(limit, cb)
}
}
@@ -175,7 +182,7 @@ impl<Iter, Cb, S, F> Paginator<Iter, Cb, S, F>
where
Iter: Iterator,
Iter::Item: Identify,
- Cb: FnOnce(&Iter::Item) -> CursorVal<S, F>,
+ Cb: FnOnce(&Iter::Item) -> CursorVal<S>,
S: Sortable + Serialize,
S::Value: Serialize,
F: Serialize,
@@ -185,7 +192,11 @@ where
/// 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) -> PaginatedCursor<Iter::Item, <Iter::Item as Identify>::Id, S, F> {
let Paginator {
- iter, limit, cb, ..
+ iter,
+ limit,
+ cb,
+ filter_on,
+ ..
} = self;
let res: Vec<_> = iter.take(limit).collect();
@@ -202,6 +213,7 @@ where
id: last.id(),
limit,
val: cb(last),
+ filter: filter_on,
})
.map(Base64Str::encode_json),
items: res,
@@ -365,7 +377,7 @@ impl<I, T: Sortable, F> Query<I, T, F> {
pub fn filter(&self) -> &F {
match self {
Query::Sort(_, f) => f,
- Query::Cursor(cursor) => &cursor.val.filter,
+ Query::Cursor(cursor) => &cursor.filter,
}
}
@@ -376,32 +388,4 @@ impl<I, T: Sortable, F> Query<I, T, F> {
Query::Cursor(cursor) => (Some(&cursor.id), Some(&cursor.val.last_val)),
}
}
-
- /// maps the type of filter from one type to another
- pub fn map_filter<Cb, U>(self, cb: Cb) -> Query<I, T, U>
- where
- Cb: FnOnce(F) -> U,
- {
- match self {
- Query::Sort(s, f) => Query::Sort(s, cb(f)),
- Query::Cursor(Cursor {
- id,
- limit,
- val:
- CursorVal {
- sort_type,
- last_val,
- filter,
- },
- }) => Query::Cursor(Cursor {
- id,
- limit,
- val: CursorVal {
- sort_type,
- last_val,
- filter: cb(filter),
- },
- }),
- }
- }
}
diff --git a/rust/cloud-storage/models_soup/src/item.rs b/rust/cloud-storage/models_soup/src/item.rs
index aa3e2660db..454085cf38 100644
--- a/rust/cloud-storage/models_soup/src/item.rs
+++ b/rust/cloud-storage/models_soup/src/item.rs
@@ -159,16 +159,14 @@ impl Identify for SoupItem {
}
impl SortOn<SimpleSortMethod> for SoupItem {
- fn sort_on<F>(
+ fn sort_on(
sort: SimpleSortMethod,
- filter: F,
- ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<SimpleSortMethod, F> {
+ ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<SimpleSortMethod> {
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.rs
index 00adf2ce5a..2843617613 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
@@ -131,9 +131,10 @@ mod tests {
.type_erase();
assert_eq!(
paginated.next_cursor.unwrap(),
- Base64Str::encode_json(CursorWithVal {
+ Base64Str::encode_json(Cursor {
id: paginated.items.first().unwrap().notification_id,
limit: 1,
+ filter: (),
val: CursorVal {
sort_type: CreatedAt,
last_val: paginated
@@ -142,7 +143,6 @@ mod tests {
.unwrap()
.created_at
.unwrap_or(DateTime::UNIX_EPOCH),
- filter: ()
}
})
.type_erase()
@@ -174,6 +174,7 @@ mod tests {
Base64Str::encode_json(Cursor {
id: paginated_result.items.last().unwrap().notification_id,
limit: 1,
+ filter: (),
val: CursorVal {
sort_type: CreatedAt,
last_val: paginated_result
@@ -182,8 +183,7 @@ mod tests {
.unwrap()
.created_at
.unwrap_or(DateTime::UNIX_EPOCH),
- filter: ()
- }
+ },
})
.type_erase()
);
diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.toml
index 2c16549a8b..79f975dbc7 100644
--- a/rust/cloud-storage/soup/Cargo.toml
+++ b/rust/cloud-storage/soup/Cargo.toml
@@ -17,6 +17,7 @@ axum = [
[dependencies]
anyhow = { workspace = true }
axum = { workspace = true, optional = true }
+chrono = { workspace = true }
either = { workspace = true }
filter_ast = { path = "../filter_ast" }
frecency = { path = "../frecency" }
@@ -28,6 +29,7 @@ model_user = { path = "../model_user", optional = true, features = ["axum"] }
models_pagination = { path = "../models_pagination" }
models_soup = { path = "../models_soup" }
non_empty = { path = "../non_empty" }
+recursion = { workspace = true }
serde = { workspace = true }
sqlx = { workspace = true }
thiserror = { workspace = true }
@@ -36,7 +38,6 @@ utoipa = { workspace = true, optional = true }
uuid = { workspace = true }
[dev-dependencies]
-chrono = { workspace = true }
cool_asserts = "2"
frecency = { path = "../frecency", features = ["mock"] }
futures = { workspace = true }
diff --git a/rust/cloud-storage/soup/src/domain/models.rs b/rust/cloud-storage/soup/src/domain/models.rs
index 3e8ca03855..db731e2e0f 100644
--- a/rust/cloud-storage/soup/src/domain/models.rs
+++ b/rust/cloud-storage/soup/src/domain/models.rs
@@ -3,7 +3,7 @@ use item_filters::ast::EntityFilterAst;
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::Entity;
use models_pagination::{
- CursorVal, Frecency, FrecencyValue, Identify, Query, SimpleSortMethod, SortOn,
+ Cursor, CursorVal, Frecency, FrecencyValue, Identify, Query, SimpleSortMethod, SortOn,
};
use models_soup::item::SoupItem;
use thiserror::Error;
@@ -20,19 +20,67 @@ pub struct SimpleSortRequest<'a> {
/// the limit of the number of items to return
pub(crate) limit: u16,
/// the [Query] the client passes (if any)
- pub(crate) cursor: Query<String, SimpleSortMethod, Option<SimpleSortFilter>>,
+ pub(crate) cursor: SimpleSortQuery,
/// the id of the user
pub(crate) user_id: MacroUserIdStr<'a>,
}
-/// the types of values we can potentially filter out of a [SimpleSortRequest]
#[derive(Debug)]
-pub enum SimpleSortFilter {
- /// remove frecency values from output
- Frecency(Frecency),
- /// remove the ast values from output
- Ast(EntityFilterAst),
- FrecencyAst(Frecency, EntityFilterAst),
+pub(crate) enum SimpleSortQuery {
+ /// we dont have anything to filter out
+ NoFilter(Query<String, SimpleSortMethod, ()>),
+ /// we filter out items that DO have a [Frecency] record
+ FilterFrecency(Query<String, SimpleSortMethod, Frecency>),
+ /// we filter out items based on the input [EntityFilterAst]
+ ItemsFilter(Query<String, SimpleSortMethod, EntityFilterAst>),
+ /// we filter out items based on the input [EntityFilterAst] IN ADDITION to ANY items that DO have a [Frecency] score
+ #[allow(dead_code, reason = "this is used in a later PR")]
+ ItemsAndFrecencyFilter(Query<String, SimpleSortMethod, (Frecency, EntityFilterAst)>),
+}
+
+impl SimpleSortQuery {
+ pub(crate) fn from_entity_cursor(
+ cursor: Query<String, SimpleSortMethod, Option<EntityFilterAst>>,
+ ) -> Self {
+ match cursor {
+ Query::Sort(s, Some(f)) => SimpleSortQuery::ItemsFilter(Query::Sort(s, f)),
+ Query::Sort(s, None) => SimpleSortQuery::NoFilter(Query::Sort(s, ())),
+ Query::Cursor(Cursor {
+ id,
+ limit,
+ val,
+ filter: Some(filter),
+ }) => SimpleSortQuery::ItemsFilter(Query::Cursor(Cursor {
+ id,
+ limit,
+ val,
+ filter,
+ })),
+ Query::Cursor(Cursor {
+ id,
+ limit,
+ val,
+ filter: None,
+ }) => SimpleSortQuery::NoFilter(Query::Cursor(Cursor {
+ id,
+ limit,
+ val,
+ filter: (),
+ })),
+ }
+ }
+}
+
+impl SimpleSortQuery {
+ #[cfg(test)]
+ pub(crate) fn sort_method(&self) -> &SimpleSortMethod {
+ match self {
+ SimpleSortQuery::NoFilter(query) => query.sort_method(),
+ SimpleSortQuery::FilterFrecency(query) => query.sort_method(),
+ SimpleSortQuery::ItemsFilter(query) => query.sort_method(),
+ SimpleSortQuery::ItemsAndFrecencyFilter(query) => query.sort_method(),
+ }
+ }
}
#[derive(Debug)]
@@ -81,10 +129,9 @@ impl Identify for FrecencySoupItem {
}
impl SortOn<Frecency> for FrecencySoupItem {
- fn sort_on<F>(
+ fn sort_on(
sort_type: Frecency,
- filter: F,
- ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<Frecency, F> {
+ ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<Frecency> {
move |val| CursorVal {
sort_type,
// if this record does not have a frecency score we fallback to created_at as the sort
@@ -92,17 +139,13 @@ 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<F>(
- sort: SimpleSortMethod,
- filter: F,
- ) -> impl FnOnce(&Self) -> CursorVal<SimpleSortMethod, F> {
- let cb = SoupItem::sort_on(sort, filter);
+ fn sort_on(sort: SimpleSortMethod) -> impl FnOnce(&Self) -> CursorVal<SimpleSortMethod> {
+ let cb = SoupItem::sort_on(sort);
move |v| cb(&v.item)
}
}
diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rs
index 7736e039b2..42e90e06b6 100644
--- a/rust/cloud-storage/soup/src/domain/service.rs
+++ b/rust/cloud-storage/soup/src/domain/service.rs
@@ -1,6 +1,6 @@
use crate::domain::{
models::{
- AdvancedSortParams, FrecencySoupItem, SimpleSortFilter, SimpleSortRequest, SoupErr,
+ AdvancedSortParams, FrecencySoupItem, SimpleSortQuery, SimpleSortRequest, SoupErr,
SoupQuery, SoupRequest, SoupType,
},
ports::{SoupOutput, SoupRepo, SoupService},
@@ -94,10 +94,10 @@ where
soup_type,
SimpleSortRequest {
limit: remainder_to_fetch.try_into().unwrap_or(500),
- cursor: Query::Sort(
+ cursor: SimpleSortQuery::FilterFrecency(Query::Sort(
SimpleSortMethod::UpdatedAt,
- Some(SimpleSortFilter::Frecency(Frecency)),
- ),
+ Frecency,
+ )),
user_id: user,
},
)
@@ -119,8 +119,8 @@ where
CursorVal {
sort_type: Frecency,
last_val: FrecencyValue::FrecencyScore(score),
- filter,
},
+ filter,
..
}) => Some((score, filter)),
// we have passed all the frecency values on this cursor so we pull from updated at
@@ -131,23 +131,38 @@ where
CursorVal {
sort_type: Frecency,
last_val: FrecencyValue::UpdatedAt(updated),
- filter: _,
},
+ filter,
}) => {
return Ok(Either::Left(
self.handle_simple_request(
soup_type,
SimpleSortRequest {
limit,
- cursor: Query::Cursor(Cursor {
- id,
- limit: cursor_limit,
- val: CursorVal {
- sort_type: SimpleSortMethod::UpdatedAt,
- last_val: updated,
- filter: Some(SimpleSortFilter::Frecency(Frecency)),
- },
- }),
+ cursor: match filter {
+ // the input has no ast filter, just filter out items with frecency score and sort by update at
+ None => SimpleSortQuery::FilterFrecency(Query::Cursor(Cursor {
+ id,
+ limit: cursor_limit,
+ val: CursorVal {
+ sort_type: SimpleSortMethod::UpdatedAt,
+ last_val: updated,
+ },
+ filter: Frecency,
+ })),
+ // the input has an ast filter, we need to filter out items that have a frecency score and also items that don't match the filter
+ Some(ast) => {
+ SimpleSortQuery::ItemsAndFrecencyFilter(Query::Cursor(Cursor {
+ id,
+ limit: cursor_limit,
+ val: CursorVal {
+ sort_type: SimpleSortMethod::UpdatedAt,
+ last_val: updated,
+ },
+ filter: (Frecency, ast),
+ }))
+ }
+ },
user_id: user,
},
)
@@ -230,19 +245,21 @@ where
req.soup_type,
SimpleSortRequest {
limit,
- cursor: cursor.map_filter(|cur| cur.map(SimpleSortFilter::Ast)),
+ cursor: SimpleSortQuery::from_entity_cursor(cursor),
user_id: req.user,
},
)
.await?
- .paginate_filter_on(limit.into(), sort_method, paginate_filter)
+ .paginate_on(limit.into(), sort_method)
+ .filter_on(paginate_filter)
.into_page(),
))
}
SoupQuery::Frecency(cursor) => Ok(Either::Right(
self.handle_advanced_sort(cursor, req.soup_type, req.user, limit)
.await?
- .paginate_filter_on(limit.into(), Frecency, paginate_filter)
+ .paginate_on(limit.into(), Frecency)
+ .filter_on(paginate_filter)
.into_page(),
)),
}
diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rs
index eaf75a890a..ab4be24f03 100644
--- a/rust/cloud-storage/soup/src/domain/service/tests.rs
+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs
@@ -1,4 +1,3 @@
-use crate::domain::models::SimpleSortFilter;
use crate::domain::ports::MockSoupRepo;
use chrono::Days;
use cool_asserts::assert_matches;
@@ -48,7 +47,7 @@ async fn it_should_not_query_frecency() {
SimpleSortRequest {
limit: 20,
user_id,
- cursor: models_pagination::Query::Sort(SimpleSortMethod::ViewedUpdated, None),
+ cursor: SimpleSortQuery::NoFilter(Query::Sort(SimpleSortMethod::ViewedUpdated, ())),
} => {
assert_eq!(user_id.as_ref(), "macro|[email protected]");
true
@@ -266,7 +265,7 @@ async fn frecency_should_fallback() {
params,
SimpleSortRequest {
limit: 75,
- cursor: Query::Sort(SimpleSortMethod::UpdatedAt, Some(SimpleSortFilter::Frecency(Frecency))),
+ cursor: SimpleSortQuery::FilterFrecency(Query::Sort(SimpleSortMethod::UpdatedAt, Frecency)),
..
} => {
true
@@ -313,7 +312,7 @@ async fn frecency_should_fallback() {
let typed_cursor = res.next_cursor.unwrap().decode_json().unwrap();
assert_matches!(
typed_cursor,
- Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::UpdatedAt(updated), filter: None }} => {
+ Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::UpdatedAt(updated) }, filter: None } => {
assert_eq!(id, "doc-100");
assert_eq!(updated, <DateTime<Utc>>::default() + Days::new(100));
@@ -379,7 +378,7 @@ async fn frecency_should_paginate() {
let typed_cursor = res.next_cursor.unwrap().decode_json().unwrap();
assert_matches!(
typed_cursor,
- Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::FrecencyScore(score), filter: None }} => {
+ Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::FrecencyScore(score) }, filter: None} => {
assert_eq!(id, "doc-1");
// last item should be the lowest score because we sort desc
assert_eq!(score as u32, 1u32);
@@ -428,8 +427,8 @@ async fn frecency_should_resume_cursor() {
val: CursorVal {
sort_type: Frecency,
last_val: FrecencyValue::FrecencyScore(5.0),
- filter: Default::default(),
},
+ filter: Default::default(),
})),
user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
})
@@ -450,7 +449,7 @@ async fn frecency_should_resume_cursor() {
let typed_cursor = res.next_cursor.unwrap().decode_json().unwrap();
assert_matches!(
typed_cursor,
- Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::FrecencyScore(score), filter: None }} => {
+ Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::FrecencyScore(score) }, filter: None} => {
assert_eq!(id, "doc-next-100");
// last item should be the lowest score because we sort desc
assert_eq!(score as u32, 4u32);
@@ -468,15 +467,15 @@ async fn frecency_fallback_cursor_should_resume() {
params,
SimpleSortRequest {
limit: 100,
- cursor: Query::Cursor(Cursor {
+ cursor: SimpleSortQuery::FilterFrecency(Query::Cursor(Cursor {
id,
limit: 100,
+ filter: Frecency,
val: CursorVal {
sort_type: SimpleSortMethod::UpdatedAt,
last_val,
- filter: Some(SimpleSortFilter::Frecency(Frecency))
}
- }),
+ })),
..
} => {
let expected_time = <DateTime<Utc>>::default() + Days::new(5);
@@ -510,8 +509,8 @@ async fn frecency_fallback_cursor_should_resume() {
val: CursorVal {
sort_type: Frecency,
last_val: FrecencyValue::UpdatedAt(DateTime::default() + Days::new(5)),
- filter: None,
},
+ filter: None,
})),
user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
})
@@ -521,7 +520,7 @@ async fn frecency_fallback_cursor_should_resume() {
assert!(res.items.iter().all(|v| v.frecency_score.is_none()));
let cursor = res.next_cursor.unwrap().decode_json().unwrap();
- assert_matches!(cursor, Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::UpdatedAt(updated), filter: None } } => {
+ assert_matches!(cursor, Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::UpdatedAt(updated) }, filter: None } => {
assert_eq!(id, "doc-next-100");
let expected_date = <DateTime<Utc>>::default() + Days::new(100);
assert_eq!(updated, expected_date);
@@ -540,7 +539,7 @@ async fn cursor_should_return_simple_sort() {
SimpleSortRequest {
limit: 20,
user_id,
- cursor: models_pagination::Query::Sort(SimpleSortMethod::ViewedUpdated, None),
+ cursor: SimpleSortQuery::NoFilter(Query::Sort(SimpleSortMethod::ViewedUpdated, ())),
} => {
assert_eq!(user_id.as_ref(), "macro|[email protected]");
true
@@ -571,7 +570,7 @@ async fn cursor_should_return_simple_sort() {
let simple_cursor = res.unwrap_left();
let cursor_decoded = simple_cursor.next_cursor.unwrap().decode_json().unwrap();
- assert_matches!(cursor_decoded, Cursor { id, limit: 20, val: CursorVal { sort_type: SimpleSortMethod::ViewedUpdated, last_val, filter } } => {
+ assert_matches!(cursor_decoded, Cursor { id, limit: 20, val: CursorVal { sort_type: SimpleSortMethod::ViewedUpdated, last_val }, filter } => {
assert_eq!(id, "my-document-19");
let date: DateTime<Utc> = Default::default();
assert_eq!(last_val, date);
@@ -623,7 +622,7 @@ async fn cursor_should_return_frecency() {
let simple_cursor = res.unwrap_right();
let cursor_decoded = simple_cursor.next_cursor.unwrap().decode_json().unwrap();
- assert_matches!(cursor_decoded, Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::FrecencyScore(1.0), filter } } => {
+ assert_matches!(cursor_decoded, Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::FrecencyScore(1.0) }, filter } => {
// frecency sort is descending so the last item is id 1
assert_eq!(id, "doc-1");
assert!(filter.is_none());
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs
index 6bdb7c12b4..d8bc6630e7 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs
@@ -1,5 +1,5 @@
use crate::domain::{
- models::{AdvancedSortParams, SimpleSortFilter, SimpleSortRequest},
+ models::{AdvancedSortParams, SimpleSortQuery, SimpleSortRequest},
ports::SoupRepo,
};
use either::Either;
@@ -26,22 +26,33 @@ impl SoupRepo for PgSoupRepo {
&self,
req: SimpleSortRequest<'a>,
) -> impl Future<Output = Result<Vec<SoupItem>, Self::Err>> + Send {
- match req.cursor.filter() {
- Some(SimpleSortFilter::Ast(_ast) | SimpleSortFilter::FrecencyAst(_, _ast)) => todo!(),
- Some(SimpleSortFilter::Frecency(f)) => {
- let f = *f;
- Either::Left(expanded::by_cursor::no_frecency_expanded_generic_soup(
+ match req.cursor {
+ SimpleSortQuery::ItemsAndFrecencyFilter(_) => {
+ Either::Left(Either::Left(Box::pin(async move { todo!() })))
+ }
+ SimpleSortQuery::ItemsFilter(ast) => Either::Left(Either::Right(
+ expanded::dynamic::expanded_dynamic_cursor_soup(
&self.inner,
req.user_id,
req.limit,
- req.cursor.map_filter(|_| f),
- ))
- }
- None => Either::Right(expanded::by_cursor::expanded_generic_cursor_soup(
- &self.inner,
- req.user_id,
- req.limit,
- req.cursor.map_filter(|_| ()),
+ ast,
+ ),
+ )),
+ SimpleSortQuery::FilterFrecency(f) => Either::Right(Either::Left(
+ expanded::by_cursor::no_frecency_expanded_generic_soup(
+ &self.inner,
+ req.user_id,
+ req.limit,
+ f,
+ ),
+ )),
+ SimpleSortQuery::NoFilter(f) => Either::Right(Either::Right(
+ expanded::by_cursor::expanded_generic_cursor_soup(
+ &self.inner,
+ req.user_id,
+ req.limit,
+ f,
+ ),
)),
}
}
@@ -50,23 +61,24 @@ impl SoupRepo for PgSoupRepo {
&self,
req: SimpleSortRequest<'a>,
) -> impl Future<Output = Result<Vec<SoupItem>, Self::Err>> + Send {
- match req.cursor.filter() {
- Some(SimpleSortFilter::Ast(_ast) | SimpleSortFilter::FrecencyAst(_, _ast)) => todo!(),
- Some(SimpleSortFilter::Frecency(f)) => {
- let f = *f;
+ match req.cursor {
+ SimpleSortQuery::ItemsFilter(_) | SimpleSortQuery::ItemsAndFrecencyFilter(_) => todo!(),
+ SimpleSortQuery::FilterFrecency(f) => {
Either::Left(expanded::by_cursor::no_frecency_expanded_generic_soup(
&self.inner,
req.user_id,
req.limit,
- req.cursor.map_filter(|_| f),
+ f,
+ ))
+ }
+ SimpleSortQuery::NoFilter(f) => {
+ Either::Right(unexpanded::by_cursor::unexpanded_generic_cursor_soup(
+ &self.inner,
+ req.user_id,
+ req.limit,
+ f,
))
}
- None => Either::Right(unexpanded::by_cursor::unexpanded_generic_cursor_soup(
- &self.inner,
- req.user_id,
- req.limit,
- req.cursor.map_filter(|_| ()),
- )),
}
}
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded.rs
index 363bc68de1..7c92f5d6d5 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded.rs
@@ -3,3 +3,4 @@ mod tests;
pub(super) mod by_cursor;
pub(super) mod by_ids;
+pub(super) mod dynamic;
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
new file mode 100644
index 0000000000..d707fdf0ab
--- /dev/null
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
@@ -0,0 +1,410 @@
+//! This module exposes a expanded dynamic query builder which is able to build specific soup queries
+//! which filter out content basd on some input ast
+
+use chrono::{DateTime, Utc};
+use filter_ast::Expr;
+use item_filters::ast::{
+ EntityFilterAst, chat::ChatLiteral, document::DocumentLiteral, project::ProjectLiteral,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use models_pagination::{Query, SimpleSortMethod};
+use models_soup::{chat::SoupChat, document::SoupDocument, item::SoupItem, project::SoupProject};
+use recursion::CollapsibleExt;
+use sqlx::{PgPool, Postgres, QueryBuilder, Row, postgres::PgRow, prelude::FromRow};
+
+static PREFIX: &str = r#"
+ WITH RECURSIVE ProjectHierarchy AS (
+ SELECT p.id, uia.access_level
+ FROM "Project" p
+ JOIN "UserItemAccess" uia ON p.id = uia.item_id AND uia.item_type = 'project'
+ WHERE uia.user_id = $1 AND p."deletedAt" IS NULL
+ UNION ALL
+ SELECT p.id, ph.access_level
+ FROM "Project" p
+ JOIN ProjectHierarchy ph ON p."parentId" = ph.id
+ WHERE p."deletedAt" IS NULL
+ ),
+ AllAccessGrants AS (
+ SELECT item_id, item_type, access_level
+ FROM "UserItemAccess"
+ WHERE user_id = $1
+ UNION ALL
+ SELECT d.id AS item_id, 'document' AS item_type, ph.access_level
+ FROM "Document" d
+ JOIN ProjectHierarchy ph ON d."projectId" = ph.id
+ WHERE d."projectId" IS NOT NULL AND d."deletedAt" IS NULL
+ UNION ALL
+ SELECT c.id AS item_id, 'chat' AS item_type, ph.access_level
+ FROM "Chat" c
+ JOIN ProjectHierarchy ph ON c."projectId" = ph.id
+ WHERE c."projectId" IS NOT NULL AND c."deletedAt" IS NULL
+ UNION ALL
+ SELECT ph.id AS item_id, 'project' AS item_type, ph.access_level
+ FROM ProjectHierarchy ph
+ ),
+ UserAccessibleItems AS (
+ SELECT DISTINCT ON (item_id, item_type) item_id, item_type
+ FROM AllAccessGrants
+ ORDER BY item_id, item_type,
+ CASE access_level
+ WHEN 'owner' THEN 4
+ WHEN 'edit' THEN 3
+ WHEN 'comment' THEN 2
+ WHEN 'view' THEN 1
+ ELSE 0
+ END DESC
+ ),
+"#;
+
+static DOCUMENT_CLAUSE: &str = r#"
+ SELECT
+ 'document' as "item_type!",
+ d.id as "id!",
+ CAST(COALESCE(di.id, db.id) as TEXT) as "document_version_id",
+ d.owner as "user_id!",
+ d.name as "name!",
+ d."branchedFromId" as "branched_from_id",
+ d."branchedFromVersionId" as "branched_from_version_id",
+ d."documentFamilyId" as "document_family_id",
+ d."fileType" as "file_type",
+ d."createdAt"::timestamptz as "created_at!",
+ d."updatedAt"::timestamptz as "updated_at!",
+ d."projectId" as "project_id",
+ NULL as "is_persistent",
+ di.sha as "sha",
+ uh."updatedAt"::timestamptz as "viewed_at",
+ CASE $2
+ WHEN 'viewed_updated' THEN COALESCE(uh."updatedAt", d."updatedAt")
+ WHEN 'viewed_at' THEN COALESCE(uh."updatedAt", '1970-01-01 00:00:00+00')
+ WHEN 'created_at' THEN d."createdAt"
+ ELSE d."updatedAt"
+ END::timestamptz as "sort_ts!"
+ FROM "Document" d
+ INNER JOIN UserAccessibleItems uai ON uai.item_id = d.id AND uai.item_type = 'document'
+ -- This MUST be a LEFT JOIN to support all three sort methods
+ LEFT JOIN "UserHistory" uh ON uh."itemId" = d.id AND uh."itemType" = 'document' AND uh."userId" = $1
+ LEFT JOIN LATERAL (
+ SELECT b.id
+ FROM "DocumentBom" b
+ WHERE b."documentId" = d.id
+ ORDER BY b."createdAt" DESC
+ LIMIT 1
+ ) db ON true
+ LEFT JOIN LATERAL (
+ SELECT i.id, i.sha
+ FROM "DocumentInstance" i
+ WHERE i."documentId" = d.id
+ ORDER BY i."updatedAt" DESC
+ LIMIT 1
+ ) di ON true
+ WHERE d."deletedAt" IS NULL
+"#;
+
+static CHAT_CLAUSE: &str = r#"
+ SELECT
+ 'chat' as "item_type!",
+ c.id as "id!",
+ NULL as "document_version_id",
+ c."userId" as "user_id!",
+ c.name as "name!",
+ NULL as "branched_from_id",
+ NULL as "branched_from_version_id",
+ NULL as "document_family_id",
+ NULL as "file_type",
+ c."createdAt"::timestamptz as "created_at!",
+ c."updatedAt"::timestamptz as "updated_at!",
+ c."projectId" as "project_id",
+ c."isPersistent" as "is_persistent",
+ NULL as "sha",
+ uh."updatedAt"::timestamptz as "viewed_at",
+ CASE $2
+ WHEN 'viewed_updated' THEN COALESCE(uh."updatedAt", c."updatedAt")
+ WHEN 'viewed_at' THEN COALESCE(uh."updatedAt", '1970-01-01 00:00:00+00')
+ WHEN 'created_at' THEN c."createdAt"
+ ELSE c."updatedAt"
+ END::timestamptz as "sort_ts!"
+ FROM "Chat" c
+ INNER JOIN UserAccessibleItems uai ON uai.item_id = c.id AND uai.item_type = 'chat'
+ LEFT JOIN "UserHistory" uh ON uh."itemId" = c.id AND uh."itemType" = 'chat' AND uh."userId" = $1
+ WHERE c."deletedAt" IS NULL
+"#;
+
+static PROJECT_CLAUSE: &str = r#"
+ SELECT
+ 'project' as "item_type!",
+ p.id as "id!",
+ NULL as "document_version_id",
+ p."userId" as "user_id!",
+ p.name as "name!",
+ NULL as "branched_from_id",
+ NULL as "branched_from_version_id",
+ NULL as "document_family_id",
+ NULL as "file_type",
+ p."createdAt"::timestamptz as "created_at!",
+ p."updatedAt"::timestamptz as "updated_at!",
+ p."parentId" as "project_id",
+ NULL as "is_persistent",
+ NULL as "sha",
+ uh."updatedAt"::timestamptz as "viewed_at",
+ CASE $2
+ WHEN 'viewed_updated' THEN COALESCE(uh."updatedAt", p."updatedAt")
+ WHEN 'viewed_at' THEN COALESCE(uh."updatedAt", '1970-01-01 00:00:00+00')
+ WHEN 'created_at' THEN p."createdAt"
+ ELSE p."updatedAt"
+ END::timestamptz as "sort_ts!"
+ FROM "Project" p
+ INNER JOIN UserAccessibleItems uai
+ ON uai.item_id = p.id
+ AND uai.item_type = 'project'
+ LEFT JOIN "UserHistory" uh
+ ON uh."itemId" = p.id
+ AND uh."itemType" = 'project'
+ AND uh."userId" = $1
+ WHERE p."deletedAt" IS NULL
+"#;
+
+static SUFFIX: &str = r#"
+ SELECT * FROM Combined
+ WHERE
+ ($4::timestamptz IS NULL)
+ OR
+ ("sort_ts!", "id!") < ($4, $5)
+ ORDER BY "sort_ts!" DESC, "updated_at!" DESC
+ LIMIT $3
+"#;
+
+fn build_document_clause(ast: Option<&Expr<DocumentLiteral>>) -> QueryBuilder<'static, Postgres> {
+ let mut res = sqlx::QueryBuilder::new(DOCUMENT_CLAUSE);
+ let Some(expr) = ast else {
+ return res;
+ };
+ let formatting = expr.collapse_frames(|frame| match frame {
+ filter_ast::ExprFrame::And(a, b) => format!("({a} AND {b})"),
+ filter_ast::ExprFrame::Or(a, b) => format!("({a} OR {b})"),
+ filter_ast::ExprFrame::Not(a) => format!("(NOT {a})"),
+ filter_ast::ExprFrame::Literal(DocumentLiteral::FileType(f)) => {
+ format!(r#"d."fileType" = '{f}'"#)
+ }
+ filter_ast::ExprFrame::Literal(DocumentLiteral::Id(i)) => format!("d.id = '{i}'"),
+ filter_ast::ExprFrame::Literal(DocumentLiteral::ProjectId(p)) => {
+ format!(r#"d."projectId" = '{p}'"#)
+ }
+ filter_ast::ExprFrame::Literal(DocumentLiteral::Owner(o)) => format!("d.owner = '{o}'"),
+ });
+ res.push(formatting);
+
+ res
+}
+
+fn build_chat_clause(ast: Option<&Expr<ChatLiteral>>) -> QueryBuilder<'static, Postgres> {
+ let mut res = sqlx::QueryBuilder::new(CHAT_CLAUSE);
+ let Some(expr) = ast else {
+ return res;
+ };
+ let formatting = expr.collapse_frames(|frame| match frame {
+ filter_ast::ExprFrame::And(a, b) => format!("({a} AND {b})"),
+ filter_ast::ExprFrame::Or(a, b) => format!("({a} OR {b})"),
+ filter_ast::ExprFrame::Not(a) => format!("(NOT {a})"),
+ filter_ast::ExprFrame::Literal(ChatLiteral::ProjectId(p)) => {
+ format!(r#"c."projectId" = '{p}'"#)
+ }
+ // todo? I'm not sure what a chat role filter looks like
+ filter_ast::ExprFrame::Literal(ChatLiteral::Role(_r)) => String::new(),
+ filter_ast::ExprFrame::Literal(ChatLiteral::ChatId(i)) => format!("c.id = '{i}'"),
+ filter_ast::ExprFrame::Literal(ChatLiteral::Owner(o)) => format!("c.owner = '{o}'"),
+ });
+ res.push(formatting);
+
+ res
+}
+
+fn build_project_clause(ast: Option<&Expr<ProjectLiteral>>) -> QueryBuilder<'static, Postgres> {
+ let mut res = sqlx::QueryBuilder::new(PROJECT_CLAUSE);
+ let Some(expr) = ast else {
+ return res;
+ };
+ let formatting = expr.collapse_frames(|frame| match frame {
+ filter_ast::ExprFrame::And(a, b) => format!("({a} AND {b})"),
+ filter_ast::ExprFrame::Or(a, b) => format!("({a} OR {b})"),
+ filter_ast::ExprFrame::Not(a) => format!("(NOT {a})"),
+ filter_ast::ExprFrame::Literal(ProjectLiteral::ProjectId(p)) => {
+ format!("c.id = '{p}'")
+ }
+ filter_ast::ExprFrame::Literal(ProjectLiteral::Owner(o)) => format!("c.owner = '{o}'"),
+ });
+ res.push(formatting);
+
+ res
+}
+
+fn build_query(filter_ast: &EntityFilterAst) -> QueryBuilder<'_, Postgres> {
+ let mut builder = sqlx::QueryBuilder::new(PREFIX);
+ builder
+ .push("Combined AS (")
+ .separated("UNION_ALL")
+ .push(build_document_clause(filter_ast.inner.document_filter.as_ref()).sql())
+ .push(build_chat_clause(filter_ast.inner.chat_filter.as_ref()).sql())
+ .push(build_project_clause(filter_ast.inner.project_filter.as_ref()).sql())
+ .push_unseparated(") ")
+ .push(SUFFIX);
+
+ builder
+}
+
+#[derive(Debug, FromRow)]
+struct DocumentRow {
+ id: String,
+ user_id: String,
+ document_version_id: String,
+ name: String,
+ sha: Option<String>,
+ file_type: Option<String>,
+ document_family_id: Option<i64>,
+ branched_from_id: Option<String>,
+ branched_from_version_id: Option<i64>,
+ project_id: Option<String>,
+ created_at: DateTime<Utc>,
+ updated_at: DateTime<Utc>,
+ viewed_at: Option<DateTime<Utc>>,
+}
+
+#[derive(Debug, FromRow)]
+struct ChatRow {
+ id: String,
+ user_id: String,
+ name: String,
+ project_id: Option<String>,
+ #[sqlx(default)]
+ is_persistent: bool,
+ created_at: DateTime<Utc>,
+ updated_at: DateTime<Utc>,
+ viewed_at: Option<DateTime<Utc>>,
+}
+
+#[derive(Debug, FromRow)]
+struct ProjectRow {
+ id: String,
+ user_id: String,
+ name: String,
+ project_id: Option<String>,
+ created_at: DateTime<Utc>,
+ updated_at: DateTime<Utc>,
+ viewed_at: Option<DateTime<Utc>>,
+}
+
+#[derive(Debug)]
+enum SoupRow {
+ Document(DocumentRow),
+ Chat(ChatRow),
+ Project(ProjectRow),
+}
+
+impl<'a> FromRow<'a, PgRow> for SoupRow {
+ fn from_row(row: &'a PgRow) -> Result<Self, sqlx::Error> {
+ let item_type: &'a str = row.try_get("item_type")?;
+ match item_type {
+ "document" => Ok(SoupRow::Document(DocumentRow::from_row(row)?)),
+ "chat" => Ok(SoupRow::Chat(ChatRow::from_row(row)?)),
+ "project" => Ok(SoupRow::Project(ProjectRow::from_row(row)?)),
+ _ => Err(sqlx::Error::TypeNotFound {
+ type_name: item_type.to_string(),
+ }),
+ }
+ }
+}
+
+impl SoupRow {
+ fn into_soup_item(self) -> Result<SoupItem, sqlx::Error> {
+ Ok(match self {
+ SoupRow::Document(DocumentRow {
+ id,
+ user_id,
+ document_version_id,
+ name,
+ sha,
+ file_type,
+ document_family_id,
+ branched_from_id,
+ branched_from_version_id,
+ project_id,
+ created_at,
+ updated_at,
+ viewed_at,
+ }) => SoupItem::Document(SoupDocument {
+ id,
+ document_version_id: document_version_id
+ .parse()
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,
+ owner_id: user_id,
+ name,
+ file_type,
+ sha,
+ project_id,
+ branched_from_id,
+ branched_from_version_id,
+ document_family_id,
+ created_at,
+ updated_at,
+ viewed_at,
+ }),
+ SoupRow::Chat(ChatRow {
+ id,
+ user_id,
+ name,
+ project_id,
+ is_persistent,
+ created_at,
+ updated_at,
+ viewed_at,
+ }) => SoupItem::Chat(SoupChat {
+ id,
+ name,
+ owner_id: user_id,
+ project_id,
+ is_persistent,
+ created_at,
+ updated_at,
+ viewed_at,
+ }),
+ SoupRow::Project(ProjectRow {
+ id,
+ user_id,
+ name,
+ project_id,
+ created_at,
+ updated_at,
+ viewed_at,
+ }) => SoupItem::Project(SoupProject {
+ id,
+ name,
+ owner_id: user_id,
+ parent_id: project_id,
+ created_at,
+ updated_at,
+ viewed_at,
+ }),
+ })
+ }
+}
+
+#[tracing::instrument(skip(db, limit))]
+pub async fn expanded_dynamic_cursor_soup(
+ db: &PgPool,
+ user_id: MacroUserIdStr<'_>,
+ limit: u16,
+ 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();
+ let (cursor_id, cursor_timestamp) = cursor.vals();
+ build_query(cursor.filter())
+ .build()
+ .bind(user_id.as_ref())
+ .bind(sort_method_str)
+ .bind(query_limit)
+ .bind(cursor_timestamp)
+ .bind(cursor_id)
+ .try_map(|row| SoupRow::from_row(&row)?.into_soup_item())
+ .fetch_all(db)
+ .await
+}
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.rs
index 75c5ad0a00..172fe195eb 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
@@ -151,7 +151,7 @@ async fn test_get_user_items_expanded_cursor(pool: Pool<Postgres>) -> anyhow::Re
)
.await?
.into_iter()
- .paginate_filter_on(1, SimpleSortMethod::ViewedAt, ())
+ .paginate_on(1, SimpleSortMethod::ViewedAt)
.into_page();
let items = result.items;
@@ -598,7 +598,8 @@ async fn test_no_frecency_expanded_cursor_pagination(pool: Pool<Postgres>) -> an
)
.await?
.into_iter()
- .paginate_filter_on(2, SimpleSortMethod::UpdatedAt, Frecency)
+ .paginate_on(2, SimpleSortMethod::UpdatedAt)
+ .filter_on(Frecency)
.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.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/unexpanded.rs
index 363bc68de1..7c92f5d6d5 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/unexpanded.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/unexpanded.rs
@@ -3,3 +3,4 @@ mod tests;
pub(super) mod by_cursor;
pub(super) mod by_ids;
+pub(super) mod dynamic;
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/unexpanded/dynamic.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/unexpanded/dynamic.rs
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/unexpanded/dynamic.rs
@@ -0,0 +1 @@
+
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.rs
index 7a00af82f3..6aa434d5dc 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
@@ -220,7 +220,7 @@ async fn test_get_user_items_unexpanded_cursor(pool: Pool<Postgres>) -> anyhow::
)
.await?
.into_iter()
- .paginate_filter_on(1, SimpleSortMethod::ViewedAt, ())
+ .paginate_on(1, SimpleSortMethod::ViewedAt)
.into_page();
assert_eq!(result.items.len(), 1, "Should get 1 item");