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.

fix(soup): cursor deserialization (#64)

Sean Ayebcf27cdb083b
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 9dd2716eaf..0d72f8d4fb 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -7755,6 +7755,8 @@ dependencies = [
"either",
"filter_ast",
"frecency",
+ "futures",
+ "http-body-util",
"item_filters",
"macro_db_migrator",
"macro_user_id",
@@ -7767,9 +7769,11 @@ dependencies = [
"non_empty",
"ordered-float",
"serde",
+ "serde_json",
"sqlx",
"thiserror 2.0.17",
"tokio",
+ "tower 0.5.2",
"tracing",
"utoipa",
"uuid",
diff --git a/rust/cloud-storage/models_pagination/src/axum.rs b/rust/cloud-storage/models_pagination/src/axum.rs
index fd6fff2648..11d8926068 100644
--- a/rust/cloud-storage/models_pagination/src/axum.rs
+++ b/rust/cloud-storage/models_pagination/src/axum.rs
@@ -70,7 +70,7 @@ where
Sort: Sortable + DeserializeOwned,
Sort::Value: DeserializeOwned,
Id: DeserializeOwned,
- F: DeserializeOwned,
+ F: DeserializeOwned + Default,
{
type Rejection = CusorExtractErr;
diff --git a/rust/cloud-storage/models_pagination/src/cursor.rs b/rust/cloud-storage/models_pagination/src/cursor.rs
index 6e25ab47bf..2eb117c0b5 100644
--- a/rust/cloud-storage/models_pagination/src/cursor.rs
+++ b/rust/cloud-storage/models_pagination/src/cursor.rs
@@ -57,6 +57,7 @@ pub struct CursorVal<C: Sortable, F> {
/// the last value of the [Sortable] from the previous page
pub last_val: C::Value,
/// the value that we are filtering on
+ #[serde(default)]
pub filter: F,
}
@@ -165,8 +166,7 @@ where
}
/// Type alias for a [Paginated] where we still know the underlying type information of the encoded cursor
-pub type PaginatedTypedCursor<T, I, C, F> =
- Paginated<T, Base64Str<CursorWithValAndFilter<I, C, F>>>;
+pub type PaginatedCursor<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>;
@@ -183,7 +183,7 @@ where
{
/// 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, F> {
+ pub fn into_page(self) -> PaginatedCursor<Iter::Item, <Iter::Item as Identify>::Id, S, F> {
let Paginator {
iter, limit, cb, ..
} = self;
@@ -210,7 +210,7 @@ where
}
}
-impl<T, I, C: Sortable, F> PaginatedTypedCursor<T, I, C, F> {
+impl<T, I, C: Sortable, F> PaginatedCursor<T, I, C, F> {
/// Erase the type of self.
/// This doesn't actually change any data it just makes the type less sepcific
pub fn type_erase(self) -> PaginatedOpaqueCursor<T> {
diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.toml
index ef00311602..e87818a2d1 100644
--- a/rust/cloud-storage/soup/Cargo.toml
+++ b/rust/cloud-storage/soup/Cargo.toml
@@ -11,6 +11,7 @@ axum = [
"dep:model-error-response",
"dep:model_user",
"dep:utoipa",
+ "models_pagination/axum",
]
@@ -43,3 +44,7 @@ macro_db_migrator = { path = "../macro_db_migrator" }
mockall = { workspace = true }
ordered-float = "5"
tokio = { workspace = true }
+tower = { workspace = true }
+futures = { workspace = true }
+http-body-util = { workspace = true }
+serde_json = { workspace = true }
diff --git a/rust/cloud-storage/soup/src/domain/models.rs b/rust/cloud-storage/soup/src/domain/models.rs
index c4107c861e..97ac638070 100644
--- a/rust/cloud-storage/soup/src/domain/models.rs
+++ b/rust/cloud-storage/soup/src/domain/models.rs
@@ -1,3 +1,5 @@
+use std::sync::Arc;
+
use frecency::domain::{models::AggregateFrecency, ports::FrecencyQueryErr};
use item_filters::ast::EntityFilterAst;
use macro_user_id::user_id::MacroUserIdStr;
@@ -25,8 +27,8 @@ pub(crate) enum SoupFilter {
#[derive(Debug)]
#[expect(dead_code)]
pub(crate) enum AstFilter {
- Normal(EntityFilterAst),
- Frecency(EntityFilterAst),
+ Normal(Arc<EntityFilterAst>),
+ Frecency(Arc<EntityFilterAst>),
}
/// the parameters required for a [SimpleSortMethod]
@@ -58,7 +60,7 @@ pub struct SoupRequest {
pub limit: u16,
pub cursor: SoupQuery,
pub user: MacroUserIdStr<'static>,
- pub filters: EntityFilterAst,
+ pub filters: Arc<EntityFilterAst>,
}
/// a [SoupItem] with an associated frecency score
diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rs
index 5388a0d0d9..ec7002cb7b 100644
--- a/rust/cloud-storage/soup/src/domain/service.rs
+++ b/rust/cloud-storage/soup/src/domain/service.rs
@@ -237,19 +237,21 @@ where
user_id: req.user,
filters: match req.filters.is_empty() {
true => None,
- false => Some(SoupFilter::Ast(AstFilter::Normal(req.filters))),
+ false => {
+ Some(SoupFilter::Ast(AstFilter::Normal(req.filters.clone())))
+ }
},
},
)
.await?
- .paginate_on(limit.into(), sort_method)
+ .paginate_filter_on(limit.into(), sort_method, req.filters)
.into_page()
.type_erase())
}
SoupQuery::Frecency(cursor) => Ok(self
.handle_advanced_sort(cursor, req.soup_type, req.user, limit)
.await?
- .paginate_on(limit.into(), Frecency)
+ .paginate_filter_on(limit.into(), Frecency, req.filters)
.into_page()
.type_erase()),
}
diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rs
index 90b67b0d4c..2f5e01c9d3 100644
--- a/rust/cloud-storage/soup/src/domain/service/tests.rs
+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs
@@ -6,7 +6,8 @@ use frecency::domain::services::FrecencyQueryServiceImpl;
use frecency::{domain::models::AggregateFrecency, outbound::mock::MockFrecencyStorage};
use model_entity::EntityType;
use models_pagination::{
- Base64Str, Cursor, CursorVal, CursorWithVal, FrecencyValue, SimpleSortMethod,
+ Base64Str, Cursor, CursorVal, CursorWithVal, CursorWithValAndFilter, FrecencyValue,
+ SimpleSortMethod,
};
use models_soup::document::SoupDocument;
use ordered_float::OrderedFloat;
@@ -317,12 +318,14 @@ async fn frecency_should_fallback() {
});
// cursor should encode correct info
let typed_cursor =
- <Base64Str<CursorWithVal<String, Frecency>>>::new_from_string(res.next_cursor.unwrap())
- .decode_json()
- .unwrap();
+ <Base64Str<CursorWithValAndFilter<String, Frecency, EntityFilterAst>>>::new_from_string(
+ 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: () }} => {
+ Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::UpdatedAt(updated), filter: EntityFilterAst { document_filter: None } }} => {
assert_eq!(id, "doc-100");
assert_eq!(updated, <DateTime<Utc>>::default() + Days::new(100));
@@ -386,12 +389,14 @@ async fn frecency_should_paginate() {
// cursor should encode correct info
let typed_cursor =
- <Base64Str<CursorWithVal<String, Frecency>>>::new_from_string(res.next_cursor.unwrap())
- .decode_json()
- .unwrap();
+ <Base64Str<CursorWithValAndFilter<String, Frecency, EntityFilterAst>>>::new_from_string(
+ 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: () }} => {
+ Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::FrecencyScore(score), filter: EntityFilterAst { document_filter: None } }} => {
assert_eq!(id, "doc-1");
// last item should be the lowest score because we sort desc
assert_eq!(score as u32, 1u32);
@@ -460,12 +465,14 @@ async fn frecency_should_resume_cursor() {
// cursor should encode correct info
let typed_cursor =
- <Base64Str<CursorWithVal<String, Frecency>>>::new_from_string(res.next_cursor.unwrap())
- .decode_json()
- .unwrap();
+ <Base64Str<CursorWithValAndFilter<String, Frecency, EntityFilterAst>>>::new_from_string(
+ 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: () }} => {
+ Cursor { id, limit: 100, val: CursorVal { sort_type: Frecency, last_val: FrecencyValue::FrecencyScore(score), filter: EntityFilterAst { document_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);
@@ -523,10 +530,12 @@ async fn frecency_fallback_cursor_should_resume() {
assert!(res.items.iter().all(|v| v.frecency_score.is_none()));
let cursor =
- <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), filter: () } } => {
+ <Base64Str<CursorWithValAndFilter<String, Frecency, EntityFilterAst>>>::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), filter: EntityFilterAst { document_filter: None } } } => {
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.rs
index 103cf88be1..d71c2ebd0b 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router.rs
@@ -25,6 +25,9 @@ use std::sync::Arc;
use thiserror::Error;
use utoipa::{IntoParams, ToSchema};
+#[cfg(test)]
+mod tests;
+
#[derive(Debug, Default, serde::Deserialize, IntoParams, ToSchema)]
#[into_params(parameter_in = Query)]
pub struct Params {
@@ -133,7 +136,7 @@ where
limit: params.limit.unwrap_or(20),
cursor,
user: macro_user_id,
- filters: EntityFilterAst::new_from_filters(filters)?,
+ filters: Arc::new(EntityFilterAst::new_from_filters(filters)?),
})
.await?;
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
new file mode 100644
index 0000000000..2add931faa
--- /dev/null
+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
@@ -0,0 +1,59 @@
+use axum::{
+ Extension, Router,
+ http::{Request, StatusCode},
+};
+use http_body_util::BodyExt;
+use model_user::UserContext;
+use serde_json::json;
+use tower::util::ServiceExt;
+
+use crate::{
+ domain::{
+ models::{FrecencySoupItem, SoupErr},
+ ports::SoupService,
+ },
+ inbound::axum_router::{SoupRouterState, soup_router},
+};
+
+static CURSOR: &str = "eyJpZCI6ImUzNmM5MTJlLTU2M2MtNDIxZS1iMTAzLWE0YjAwY2ZmMzBlZSIsImxpbWl0IjoxMDAsInZhbCI6eyJzb3J0X3R5cGUiOiJ1cGRhdGVkX2F0IiwibGFzdF92YWwiOiIyMDI1LTExLTA3VDE5OjEyOjU5Ljc4MFoifX0=";
+
+struct MockSoup;
+
+impl SoupService for MockSoup {
+ async fn get_user_soup(
+ &self,
+ _req: crate::domain::models::SoupRequest,
+ ) -> Result<models_pagination::PaginatedOpaqueCursor<FrecencySoupItem>, SoupErr> {
+ Err(SoupErr::SoupDbErr(anyhow::anyhow!("Not implemented")))
+ }
+}
+
+fn mock_router() -> Router {
+ soup_router(SoupRouterState::new(MockSoup)).layer(Extension(UserContext {
+ user_id: "macro|[email protected]".to_string(),
+ fusion_user_id: "1234".to_string(),
+ permissions: None,
+ organization_id: None,
+ }))
+}
+
+#[tokio::test]
+async fn it_should_deserialize_empty_filter() {
+ let router = mock_router();
+
+ let request = Request::builder()
+ .uri(format!("/soup?cursor={CURSOR}"))
+ .body(axum::body::Body::empty())
+ .unwrap();
+
+ let res = router.oneshot(request).await.unwrap();
+ assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
+ let bytes = res.into_body().collect().await.unwrap().to_bytes();
+ let json: serde_json::Value = serde_json::from_slice(bytes.as_ref()).unwrap();
+ assert_eq!(
+ json,
+ json!({
+ "message": "An internal server error has occurred"
+ })
+ );
+}