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): allow caller to type erase (#79)

Sean Ayea9fa8e38cd2e
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index ed9298815d..7a9d9ca85a 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -5268,6 +5268,7 @@ dependencies = [
"axum",
"base64 0.22.1",
"chrono",
+ "either",
"model-error-response",
"serde",
"serde_json",
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 43bc00e629..e72198433e 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -5,6 +5,7 @@ members = [
"ai",
"ai_format",
"ai_tools",
+ "anthropic",
"authentication_service",
"authentication_service_client",
"comms_db_client",
@@ -60,7 +61,8 @@ members = [
"metering_service",
"metering_service_client",
"model",
- "model_notifications", "model_user",
+ "model_notifications",
+ "model_user",
"models_dcs",
"models_email",
"models_metering",
@@ -95,7 +97,8 @@ members = [
"ses_client",
"sha_cleanup_worker",
"sha_ref_count_resetter",
- "sns_client", "soup",
+ "sns_client",
+ "soup",
"sqs_client",
"sqs_worker",
"static_file_service",
@@ -108,7 +111,6 @@ members = [
"user_link_cleanup_handler",
"user_quota",
"worker_trigger",
- "anthropic"
]
[workspace.dependencies]
@@ -139,6 +141,7 @@ cookie = "0.18.1"
dashmap = "6.1.0"
dotenv = "0.15.0"
ego-tree = "0.6.2"
+either = "1"
futures = "0.3.31"
hex = "0.4.3"
http-body-util = "0.1.2"
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 d70a0e8813..f85596d2ba 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
@@ -24,6 +24,7 @@ use models_email::service::link::Link;
use models_email::service::thread::ThreadPreviewCursor;
use models_pagination::{
CursorExtractor, CursorVal, Identify, PaginateOn, Paginated, SimpleSortMethod, SortOn,
+ TypeEraseCursor,
};
use schemars::JsonSchema;
use serde::Serialize;
diff --git a/rust/cloud-storage/item_filters/Cargo.toml b/rust/cloud-storage/item_filters/Cargo.toml
index 909a0d0fc1..c2ac5ed5eb 100644
--- a/rust/cloud-storage/item_filters/Cargo.toml
+++ b/rust/cloud-storage/item_filters/Cargo.toml
@@ -11,7 +11,7 @@ macro_user_id = { path = "../macro_user_id" }
model_file_type = { path = "../model_file_type" }
non_empty = { path = "../non_empty" }
schemars = { workspace = true }
-serde = { workspace = true }
+serde = { workspace = true, features = ["rc"] }
serde_json = { workspace = true }
strum = { workspace = true }
thiserror = { workspace = true }
diff --git a/rust/cloud-storage/item_filters/src/ast.rs b/rust/cloud-storage/item_filters/src/ast.rs
index d5567cefd6..dd2b81e55e 100644
--- a/rust/cloud-storage/item_filters/src/ast.rs
+++ b/rust/cloud-storage/item_filters/src/ast.rs
@@ -12,7 +12,7 @@ use document::DocumentLiteral;
use filter_ast::{ExpandFrame, Expr};
use non_empty::IsEmpty;
use serde::{Deserialize, Serialize};
-use std::marker::PhantomData;
+use std::{marker::PhantomData, sync::Arc};
use thiserror::Error;
mod channel;
@@ -52,7 +52,7 @@ pub enum ExpandErr {
/// Describes a bundle of filters that should be applied across different entity types
#[derive(Default, Debug, Serialize, Deserialize)]
-pub struct EntityFilterAst {
+pub struct EntityFilterInner {
/// the filters that should be applied to the document entity
#[serde(default)]
pub document_filter: Option<Expr<DocumentLiteral>>,
@@ -64,6 +64,13 @@ pub struct EntityFilterAst {
pub chat_filter: Option<Expr<ChatLiteral>>,
}
+/// wrapper over [EntityFilterInner] which gives us cheaper clones
+#[derive(Default, Debug, Serialize, Deserialize, Clone)]
+pub struct EntityFilterAst {
+ /// we wrap the inner type in an arc to avoid large allocations when cloning boxed values
+ pub inner: Arc<EntityFilterInner>,
+}
+
impl EntityFilterAst {
/// expand the input [EntityFilters] into an ast representation
pub fn new_from_filters(entity_filter: EntityFilters) -> Result<Self, ExpandErr> {
@@ -71,20 +78,22 @@ impl EntityFilterAst {
return Ok(Self::default());
}
Ok(Self {
- document_filter: DocumentFilters::expand_ast(entity_filter.document_filters)?,
- project_filter: ProjectFilters::expand_ast(entity_filter.project_filters)?,
- chat_filter: ChatFilters::expand_ast(entity_filter.chat_filters)?,
+ inner: Arc::new(EntityFilterInner {
+ document_filter: DocumentFilters::expand_ast(entity_filter.document_filters)?,
+ project_filter: ProjectFilters::expand_ast(entity_filter.project_filters)?,
+ chat_filter: ChatFilters::expand_ast(entity_filter.chat_filters)?,
+ }),
})
}
}
impl IsEmpty for EntityFilterAst {
fn is_empty(&self) -> bool {
- let EntityFilterAst {
+ let EntityFilterInner {
document_filter,
project_filter,
chat_filter,
- } = self;
+ } = &*self.inner;
document_filter.is_none() && project_filter.is_none() && chat_filter.is_none()
}
}
diff --git a/rust/cloud-storage/item_filters/src/ast/tests.rs b/rust/cloud-storage/item_filters/src/ast/tests.rs
index d2219f0814..0c0687875d 100644
--- a/rust/cloud-storage/item_filters/src/ast/tests.rs
+++ b/rust/cloud-storage/item_filters/src/ast/tests.rs
@@ -33,7 +33,7 @@ fn it_expands_filters() {
..Default::default()
};
- let ast = EntityFilterAst::new_from_filters(f)
+ let ast = Arc::into_inner(EntityFilterAst::new_from_filters(f).unwrap().inner)
.unwrap()
.document_filter
.unwrap();
diff --git a/rust/cloud-storage/models_pagination/Cargo.toml b/rust/cloud-storage/models_pagination/Cargo.toml
index 1fc52d7dbc..070ff0b9a7 100644
--- a/rust/cloud-storage/models_pagination/Cargo.toml
+++ b/rust/cloud-storage/models_pagination/Cargo.toml
@@ -13,6 +13,7 @@ docs = [
axum = { workspace = true, optional = true }
base64 = { workspace = true }
chrono = { workspace = true }
+either = { workspace = true }
model-error-response = { path = "../model-error-response", optional = true }
serde = { workspace = true }
serde_json = { workspace = true }
diff --git a/rust/cloud-storage/models_pagination/src/axum.rs b/rust/cloud-storage/models_pagination/src/axum.rs
index 11d8926068..19a24321c1 100644
--- a/rust/cloud-storage/models_pagination/src/axum.rs
+++ b/rust/cloud-storage/models_pagination/src/axum.rs
@@ -3,6 +3,7 @@ use axum::extract::{FromRequestParts, Query};
use axum::http::{StatusCode, request::Parts};
use axum::response::IntoResponse;
use axum::{Json, RequestPartsExt, async_trait};
+pub use either::Either;
use model_error_response::ErrorResponse;
use serde::Deserialize;
use serde::de::DeserializeOwned;
@@ -97,20 +98,15 @@ where
}
/// utility type for handling the cases where exactly 1 of 2 extractors must pass
-pub enum Either<L, R> {
- /// the left value
- Left(L),
- /// the right value
- Right(R),
-}
+pub struct EitherWrapper<L, R>(pub Either<L, R>);
-impl<L, R> IntoResponse for Either<L, R>
+impl<L, R> IntoResponse for EitherWrapper<L, R>
where
L: IntoResponse,
R: IntoResponse,
{
fn into_response(self) -> axum::response::Response {
- match self {
+ match self.0 {
Either::Left(l) => l.into_response(),
Either::Right(r) => r.into_response(),
}
@@ -118,7 +114,7 @@ where
}
#[axum::async_trait]
-impl<S, L, R> FromRequestParts<S> for Either<L, R>
+impl<S, L, R> FromRequestParts<S> for EitherWrapper<L, R>
where
L: FromRequestParts<S> + Send + 'static,
L::Rejection: Send,
@@ -126,15 +122,18 @@ where
R::Rejection: Send,
S: Send + Sync,
{
- type Rejection = Either<L::Rejection, R::Rejection>;
+ type Rejection = EitherWrapper<L::Rejection, R::Rejection>;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let res: Result<L, _> = parts.extract_with_state(state).await;
if let Ok(left) = res {
- return Ok(Either::Left(left));
+ return Ok(EitherWrapper(Either::Left(left)));
}
let res2: Result<R, _> = parts.extract_with_state(state).await;
- res2.map(Either::Right).map_err(Either::Right)
+ res2.map(Either::Right)
+ .map(EitherWrapper)
+ .map_err(Either::Right)
+ .map_err(EitherWrapper)
}
}
diff --git a/rust/cloud-storage/models_pagination/src/cursor.rs b/rust/cloud-storage/models_pagination/src/cursor.rs
index 2eb117c0b5..f51e984935 100644
--- a/rust/cloud-storage/models_pagination/src/cursor.rs
+++ b/rust/cloud-storage/models_pagination/src/cursor.rs
@@ -1,4 +1,5 @@
use base64::{DecodeError, Engine, engine::general_purpose};
+use either::Either;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::{cmp::Ordering, marker::PhantomData};
use thiserror::Error;
@@ -210,10 +211,16 @@ where
}
}
-impl<T, I, C: Sortable, F> PaginatedCursor<T, I, C, F> {
+/// trait for erasing the strong typing of a Cursor
+/// This makes the type less specific but maintains the same inner data
+pub trait TypeEraseCursor<T> {
/// 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> {
+ fn type_erase(self) -> PaginatedOpaqueCursor<T>;
+}
+
+impl<T, I, C: Sortable, F> TypeEraseCursor<T> for PaginatedCursor<T, I, C, F> {
+ fn type_erase(self) -> PaginatedOpaqueCursor<T> {
let Self { items, next_cursor } = self;
PaginatedOpaqueCursor {
items,
@@ -222,6 +229,17 @@ impl<T, I, C: Sortable, F> PaginatedCursor<T, I, C, F> {
}
}
+impl<T, I, I2, C: Sortable, C2: Sortable, F, F2> TypeEraseCursor<T>
+ for Either<PaginatedCursor<T, I, C, F>, PaginatedCursor<T, I2, C2, F2>>
+{
+ fn type_erase(self) -> PaginatedOpaqueCursor<T> {
+ match self {
+ Either::Left(l) => l.type_erase(),
+ Either::Right(r) => r.type_erase(),
+ }
+ }
+}
+
fn serialize_json_string<T: Serialize>(val: &T) -> String {
serde_json::to_string(val).expect("This is infallible")
}
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 dc4a99fb0a..5d33b888e4 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
@@ -112,7 +112,9 @@ pub async fn get_all_user_notifications_by_event_item_ids(
mod tests {
use super::*;
use chrono::DateTime;
- use models_pagination::{Base64Str, Cursor, CursorVal, CursorWithVal, Paginate, PaginateOn};
+ use models_pagination::{
+ Base64Str, Cursor, CursorVal, CursorWithVal, Paginate, PaginateOn, TypeEraseCursor,
+ };
use sqlx::{Pool, Postgres};
#[sqlx::test(fixtures(path = "../../../fixtures", scripts("user_notifications")))]
@@ -156,7 +158,7 @@ mod tests {
let paginated_result = get_all_user_notifications_by_event_item_ids(
&pool,
- &vec!["test"],
+ &["test"],
1,
Query::Sort(CreatedAt),
)
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.rs
index 9c207d0edd..5e82f94b19 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
@@ -5,7 +5,9 @@ use axum::{
};
use model::response::ErrorResponse;
use model_notifications::UserNotification;
-use models_pagination::{CreatedAt, CursorExtractor, PaginateOn, PaginatedOpaqueCursor};
+use models_pagination::{
+ CreatedAt, CursorExtractor, PaginateOn, PaginatedOpaqueCursor, TypeEraseCursor,
+};
use sqlx::types::Uuid;
use crate::api::{
@@ -89,7 +91,11 @@ pub async fn handler(
message: "failed to convert notification",
}),
)
- })?.into_iter().paginate_on(limit as usize, CreatedAt).into_page().type_erase();
+ })?
+ .into_iter()
+ .paginate_on(limit as usize, CreatedAt)
+ .into_page()
+ .type_erase();
Ok((StatusCode::OK, Json(result)))
}
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.rs
index 5479ed9ff4..918587050b 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
@@ -7,7 +7,7 @@ use axum::{
use model::response::ErrorResponse;
use model::user::UserContext;
use model_notifications::UserNotification;
-use models_pagination::{CreatedAt, CursorExtractor, PaginateOn, Paginated};
+use models_pagination::{CreatedAt, CursorExtractor, PaginateOn, Paginated, TypeEraseCursor};
use notification_db_client::user_notification::get::get_all::get_all_user_notifications;
use serde::Serialize;
use sqlx::types::Uuid;
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.rs
index 4a85a590fb..5a1e4dd727 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
@@ -9,7 +9,7 @@ use axum::{
use model::response::ErrorResponse;
use model::user::UserContext;
use model_notifications::UserNotification;
-use models_pagination::{CreatedAt, CursorExtractor, PaginateOn, Paginated};
+use models_pagination::{CreatedAt, CursorExtractor, PaginateOn, Paginated, TypeEraseCursor};
use sqlx::types::Uuid;
#[derive(serde::Deserialize)]
@@ -80,7 +80,11 @@ pub async fn handler(
message: "failed to convert notification",
}),
)
- })?.into_iter().paginate_on(limit as usize, CreatedAt).into_page().type_erase();
+ })?
+ .into_iter()
+ .paginate_on(limit as usize, CreatedAt)
+ .into_page()
+ .type_erase();
let Paginated {
items, next_cursor, ..
diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.toml
index cd3960e7ff..2c16549a8b 100644
--- a/rust/cloud-storage/soup/Cargo.toml
+++ b/rust/cloud-storage/soup/Cargo.toml
@@ -17,7 +17,7 @@ axum = [
[dependencies]
anyhow = { workspace = true }
axum = { workspace = true, optional = true }
-either = { version = "1" }
+either = { workspace = true }
filter_ast = { path = "../filter_ast" }
frecency = { path = "../frecency" }
item_filters = { path = "../item_filters" }
diff --git a/rust/cloud-storage/soup/src/domain/models.rs b/rust/cloud-storage/soup/src/domain/models.rs
index 97ac638070..c4107c861e 100644
--- a/rust/cloud-storage/soup/src/domain/models.rs
+++ b/rust/cloud-storage/soup/src/domain/models.rs
@@ -1,5 +1,3 @@
-use std::sync::Arc;
-
use frecency::domain::{models::AggregateFrecency, ports::FrecencyQueryErr};
use item_filters::ast::EntityFilterAst;
use macro_user_id::user_id::MacroUserIdStr;
@@ -27,8 +25,8 @@ pub(crate) enum SoupFilter {
#[derive(Debug)]
#[expect(dead_code)]
pub(crate) enum AstFilter {
- Normal(Arc<EntityFilterAst>),
- Frecency(Arc<EntityFilterAst>),
+ Normal(EntityFilterAst),
+ Frecency(EntityFilterAst),
}
/// the parameters required for a [SimpleSortMethod]
@@ -60,7 +58,7 @@ pub struct SoupRequest {
pub limit: u16,
pub cursor: SoupQuery,
pub user: MacroUserIdStr<'static>,
- pub filters: Arc<EntityFilterAst>,
+ pub filters: EntityFilterAst,
}
/// a [SoupItem] with an associated frecency score
diff --git a/rust/cloud-storage/soup/src/domain/ports.rs b/rust/cloud-storage/soup/src/domain/ports.rs
index cf6f3e7930..cde74f36f1 100644
--- a/rust/cloud-storage/soup/src/domain/ports.rs
+++ b/rust/cloud-storage/soup/src/domain/ports.rs
@@ -1,7 +1,9 @@
use crate::domain::models::{
AdvancedSortParams, FrecencySoupItem, SimpleSortRequest, SoupErr, SoupRequest,
};
-use models_pagination::PaginatedOpaqueCursor;
+use either::Either;
+use item_filters::ast::EntityFilterAst;
+use models_pagination::{Frecency, PaginatedCursor, SimpleSortMethod};
use models_soup::item::SoupItem;
#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]
@@ -28,9 +30,20 @@ pub trait SoupRepo: Send + Sync + 'static {
) -> impl Future<Output = Result<Vec<SoupItem>, Self::Err>> + Send;
}
+/// type alias which represents the posible outputs of soup
+/// The response is a paginated cursor where
+/// 1. The item type is [FrecencySoupItem]
+/// 1. The id type is [String] (this should be changed to uuid)
+/// 1. The sort method is [Either] [SimpleSortMethod] or [Frecency]
+/// 1. The filter type is [EntityFilterAst]
+pub type SoupOutput = Either<
+ PaginatedCursor<FrecencySoupItem, String, SimpleSortMethod, EntityFilterAst>,
+ PaginatedCursor<FrecencySoupItem, String, Frecency, EntityFilterAst>,
+>;
+
pub trait SoupService: Send + Sync + 'static {
fn get_user_soup(
&self,
req: SoupRequest,
- ) -> impl Future<Output = Result<PaginatedOpaqueCursor<FrecencySoupItem>, SoupErr>> + Send;
+ ) -> impl Future<Output = Result<SoupOutput, SoupErr>> + Send;
}
diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rs
index ec7002cb7b..c555bec495 100644
--- a/rust/cloud-storage/soup/src/domain/service.rs
+++ b/rust/cloud-storage/soup/src/domain/service.rs
@@ -3,7 +3,7 @@ use crate::domain::{
AdvancedSortParams, AstFilter, FrecencySoupItem, SimpleSortRequest, SoupErr, SoupFilter,
SoupQuery, SoupRequest, SoupType,
},
- ports::{SoupRepo, SoupService},
+ ports::{SoupOutput, SoupRepo, SoupService},
};
use either::Either;
use frecency::domain::{
@@ -14,8 +14,7 @@ use item_filters::ast::EntityFilterAst;
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model_entity::as_owned::ShallowClone;
use models_pagination::{
- Cursor, CursorVal, Frecency, FrecencyValue, PaginateOn, PaginatedOpaqueCursor, Query,
- SimpleSortMethod,
+ Cursor, CursorVal, Frecency, FrecencyValue, PaginateOn, Query, SimpleSortMethod,
};
use models_soup::item::SoupItem;
use non_empty::IsEmpty;
@@ -219,17 +218,14 @@ where
anyhow::Error: From<T::Err>,
U: FrecencyQueryService,
{
- async fn get_user_soup(
- &self,
- req: SoupRequest,
- ) -> Result<PaginatedOpaqueCursor<FrecencySoupItem>, SoupErr> {
+ async fn get_user_soup(&self, req: SoupRequest) -> Result<SoupOutput, SoupErr> {
let limit = req.limit.clamp(20, 500);
match req.cursor {
SoupQuery::Simple(cursor) => {
let sort_method = *cursor.sort_method();
- Ok(self
- .handle_simple_request(
+ Ok(Either::Left(
+ self.handle_simple_request(
req.soup_type,
SimpleSortRequest {
limit,
@@ -245,15 +241,15 @@ where
)
.await?
.paginate_filter_on(limit.into(), sort_method, req.filters)
- .into_page()
- .type_erase())
+ .into_page(),
+ ))
}
- SoupQuery::Frecency(cursor) => Ok(self
- .handle_advanced_sort(cursor, req.soup_type, req.user, limit)
- .await?
- .paginate_filter_on(limit.into(), Frecency, req.filters)
- .into_page()
- .type_erase()),
+ SoupQuery::Frecency(cursor) => Ok(Either::Right(
+ self.handle_advanced_sort(cursor, req.soup_type, req.user, limit)
+ .await?
+ .paginate_filter_on(limit.into(), Frecency, req.filters)
+ .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 249eda6a93..c63660ea45 100644
--- a/rust/cloud-storage/soup/src/domain/service/tests.rs
+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs
@@ -7,6 +7,7 @@ use frecency::{domain::models::AggregateFrecency, outbound::mock::MockFrecencySt
use model_entity::EntityType;
use models_pagination::{
Base64Str, Cursor, CursorVal, CursorWithValAndFilter, FrecencyValue, SimpleSortMethod,
+ TypeEraseCursor,
};
use models_soup::document::SoupDocument;
use ordered_float::OrderedFloat;
@@ -83,7 +84,8 @@ async fn it_should_not_query_frecency() {
filters: Default::default(),
})
.await
- .unwrap();
+ .unwrap()
+ .type_erase();
dbg!(&res);
@@ -151,7 +153,8 @@ async fn it_should_query_frecency() {
filters: Default::default(),
})
.await
- .unwrap();
+ .unwrap()
+ .type_erase();
dbg!(&res);
@@ -219,7 +222,8 @@ async fn it_should_sort_frecency_descending() {
filters: Default::default(),
})
.await
- .unwrap();
+ .unwrap()
+ .type_erase();
dbg!(&res);
@@ -303,7 +307,8 @@ async fn frecency_should_fallback() {
filters: Default::default(),
})
.await
- .unwrap();
+ .unwrap()
+ .type_erase();
// output should be the limit
assert_eq!(res.items.len(), 100);
@@ -372,7 +377,8 @@ async fn frecency_should_paginate() {
filters: Default::default(),
})
.await
- .unwrap();
+ .unwrap()
+ .type_erase();
// output should be the limit
assert_eq!(res.items.len(), 100);
@@ -451,7 +457,8 @@ async fn frecency_should_resume_cursor() {
filters: Default::default(),
})
.await
- .unwrap();
+ .unwrap()
+ .type_erase();
// first all items should be frecency
assert!(
@@ -495,11 +502,7 @@ async fn frecency_fallback_cursor_should_resume() {
val: CursorVal {
sort_type: SimpleSortMethod::UpdatedAt,
last_val,
- filter: EntityFilterAst {
- document_filter: None,
- project_filter: None,
- chat_filter: None
- }
+ filter: _
}
}),
filters,
@@ -544,7 +547,8 @@ async fn frecency_fallback_cursor_should_resume() {
filters: Default::default(),
})
.await
- .unwrap();
+ .unwrap()
+ .type_erase();
assert!(res.items.iter().all(|v| v.frecency_score.is_none()));
let cursor =
@@ -559,3 +563,109 @@ async fn frecency_fallback_cursor_should_resume() {
assert_eq!(updated, expected_date);
})
}
+
+#[tokio::test]
+async fn cursor_should_return_simple_sort() {
+ let mut soup_mock = MockSoupRepo::new();
+ soup_mock
+ .expect_unexpanded_generic_cursor_soup()
+ .withf(|a| {
+ matches!(a.cursor.sort_method(), SimpleSortMethod::ViewedUpdated)
+ && assert_matches!(
+ a,
+ SimpleSortRequest {
+ limit: 20,
+ user_id,
+ cursor: models_pagination::Query::Sort(SimpleSortMethod::ViewedUpdated),
+ filters
+ } => {
+ assert_matches!(filters, None);
+ assert_eq!(user_id.as_ref(), "macro|[email protected]");
+ true
+ }
+ )
+ })
+ .times(1)
+ .returning(|_params| {
+ let res = (0..100)
+ .map(|i| soup_document(format!("my-document-{i}")))
+ .map(SoupItem::Document)
+ .collect();
+ Box::pin(async move { Ok(res) })
+ });
+
+ let res = SoupImpl::new(
+ soup_mock,
+ FrecencyQueryServiceImpl::new(MockFrecencyStorage::new()),
+ )
+ .get_user_soup(SoupRequest {
+ soup_type: SoupType::UnExpanded,
+ limit: 0,
+ cursor: SoupQuery::Simple(Query::Sort(SimpleSortMethod::ViewedUpdated)),
+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ filters: Default::default(),
+ })
+ .await
+ .unwrap();
+
+ 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_eq!(id, "my-document-19");
+ let date: DateTime<Utc> = Default::default();
+ assert_eq!(last_val, date);
+ assert!(filter.is_empty());
+ })
+}
+
+#[tokio::test]
+async fn cursor_should_return_frecency() {
+ let mut frecency = MockFrecencyQueryService::new();
+ let mut soup = MockSoupRepo::new();
+
+ frecency
+ .expect_get_frecency_page()
+ .withf(|params| assert_matches!(params, FrecencyPageRequest { limit: 100, .. } => true))
+ .times(1)
+ .returning(|params| {
+ let iter = (1..=params.limit).map(|v| {
+ AggregateFrecency::new_mock(
+ EntityType::Document.with_entity_string(format!("doc-{v}")),
+ v.into(),
+ )
+ });
+ let res = Ok(FrecencyPageResponse::new_mock(iter));
+ Box::pin(async move { res })
+ });
+
+ soup.expect_unexpanded_soup_by_ids()
+ .times(1)
+ .returning(|params| {
+ let vec = params
+ .entities
+ .iter()
+ .map(|id| soup_document(id.entity_id.to_string()))
+ .map(SoupItem::Document)
+ .collect();
+ Box::pin(async move { Ok(vec) })
+ });
+
+ let res = SoupImpl::new(soup, frecency)
+ .get_user_soup(SoupRequest {
+ soup_type: SoupType::UnExpanded,
+ limit: 100,
+ cursor: SoupQuery::Frecency(Query::Sort(Frecency)),
+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ filters: Default::default(),
+ })
+ .await
+ .unwrap();
+
+ 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 } } => {
+ // frecency sort is descending so the last item is id 1
+ assert_eq!(id, "doc-1");
+ assert!(filter.is_empty());
+ })
+}
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router.rs b/rust/cloud-storage/soup/src/inbound/axum_router.rs
index d71c2ebd0b..89087d8025 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router.rs
@@ -17,7 +17,8 @@ use macro_user_id::user_id::MacroUserIdStr;
use model_error_response::ErrorResponse;
use model_user::axum_extractor::MacroUserExtractor;
use models_pagination::{
- CursorExtractor, Either, Frecency, PaginatedOpaqueCursor, SimpleSortMethod, SortMethod,
+ CursorExtractor, Either, EitherWrapper, Frecency, PaginatedOpaqueCursor, SimpleSortMethod,
+ SortMethod, TypeEraseCursor,
};
use models_soup::item::SoupItem;
use serde::{Deserialize, Serialize};
@@ -113,7 +114,7 @@ where
}
};
- let cursor = match cursor {
+ let cursor = match cursor.0 {
Either::Left(l) => l
.into_option()
.map(models_pagination::Query::Cursor)
@@ -136,11 +137,13 @@ where
limit: params.limit.unwrap_or(20),
cursor,
user: macro_user_id,
- filters: Arc::new(EntityFilterAst::new_from_filters(filters)?),
+ filters: EntityFilterAst::new_from_filters(filters)?,
})
.await?;
- Ok(Json(res.map(SoupApiItem::from_frecency_soup_item)))
+ Ok(Json(
+ res.type_erase().map(SoupApiItem::from_frecency_soup_item),
+ ))
}
}
@@ -240,7 +243,7 @@ pub struct PostSoupRequest {
params: Params,
}
-type SoupCursor = Either<
+type SoupCursor = EitherWrapper<
CursorExtractor<String, SimpleSortMethod, EntityFilterAst>,
CursorExtractor<String, Frecency, EntityFilterAst>,
>;
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
index 2add931faa..466d7e3a82 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
@@ -9,8 +9,8 @@ use tower::util::ServiceExt;
use crate::{
domain::{
- models::{FrecencySoupItem, SoupErr},
- ports::SoupService,
+ models::SoupErr,
+ ports::{SoupOutput, SoupService},
},
inbound::axum_router::{SoupRouterState, soup_router},
};
@@ -23,7 +23,7 @@ impl SoupService for MockSoup {
async fn get_user_soup(
&self,
_req: crate::domain::models::SoupRequest,
- ) -> Result<models_pagination::PaginatedOpaqueCursor<FrecencySoupItem>, SoupErr> {
+ ) -> Result<SoupOutput, SoupErr> {
Err(SoupErr::SoupDbErr(anyhow::anyhow!("Not implemented")))
}
}