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): add email service integration (#342)

Sean Aye7b8d8d23b483
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 82fd867841..657d8be7b7 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2550,6 +2550,7 @@ dependencies = [
"connection_gateway",
"cool_asserts",
"dynamodb_client",
+ "email",
"email_service_client",
"frecency",
"futures",
@@ -2682,9 +2683,9 @@ dependencies = [
[[package]]
name = "doppleganger"
-version = "0.3.0"
+version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "07082bf0ceb443d51d52cdb522e014d470ad2f1a22be809361b7947bb6dd828f"
+checksum = "51a96cb2655fc126bfa552d79866bfaa542e9956dcd8f79454a49c405003cf86"
dependencies = [
"doppleganger-core",
"doppleganger-macros",
@@ -2692,9 +2693,9 @@ dependencies = [
[[package]]
name = "doppleganger-core"
-version = "0.3.0"
+version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3163e3d866a7e9935810855bce91e1ade21a4ff355cba093451f2a327650e640"
+checksum = "98a55433d78ee9219f69b8c34d1058f2f26b413a959606c593704eb453f4e7d2"
dependencies = [
"chrono",
"uuid",
@@ -2702,9 +2703,9 @@ dependencies = [
[[package]]
name = "doppleganger-macros"
-version = "0.3.0"
+version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f5ef4fbea2d3584cf0547c8587b73ede38972d4e01f050fb41790ef0f664bfbd"
+checksum = "7eedde8f1d892e8453ec1a3cd51029d19afab36546d0df43e6d31f049de4021d"
dependencies = [
"doppleganger-macros-parse",
"proc-macro2",
@@ -2714,9 +2715,9 @@ dependencies = [
[[package]]
name = "doppleganger-macros-parse"
-version = "0.3.0"
+version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d6802888ef9324ea57ef9ea11a6e42a44c9deeeb2d17dc856882713d54428fee"
+checksum = "8adad89fa08cce316e9a1d678aad6ff3afd9b04c5f70b9bb03bbd7ae5fde8f9b"
dependencies = [
"proc-macro2",
"quote",
@@ -5447,6 +5448,7 @@ dependencies = [
"chrono",
"either",
"model-error-response",
+ "ordered-float",
"serde",
"serde_json",
"thiserror 2.0.17",
@@ -7981,6 +7983,7 @@ dependencies = [
"cool_asserts",
"doppleganger",
"either",
+ "email",
"filter_ast",
"frecency",
"futures",
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 939b5e1240..7d89b0b48b 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -154,6 +154,7 @@ log = "0.4.26"
mockall = "0.13"
nom = "8"
openssl = { version = "0.10.71", features = ["vendored"] }
+ordered-float = "5"
pdfium-render = { version = "0.8.28" }
rand = "0.9.0"
recursion = "0.5.4"
@@ -210,7 +211,7 @@ bzip2 = { version = "0.5.1", default-features = false, features = [
"libbz2-rs-sys",
] }
derive_builder = "0.20.2"
-doppleganger = "0.3"
+doppleganger = "0.5"
once_cell = "1.21.3"
scraper = "0.18"
strum_macros = "0.27.1"
diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.toml
index 3e64467262..027de703fa 100644
--- a/rust/cloud-storage/document_storage_service/Cargo.toml
+++ b/rust/cloud-storage/document_storage_service/Cargo.toml
@@ -42,6 +42,7 @@ cloudfront_sign = { workspace = true }
comms_service_client = { path = "../comms_service_client" }
connection_gateway = { path = "../connection_gateway" }
dynamodb_client = { path = "../dynamodb_client" }
+email = { path = "../email", features = ["outbound", "ports"] }
email_service_client = { path = "../email_service_client" }
frecency = { path = "../frecency", features = ["postgres"] }
futures = { workspace = true }
@@ -72,6 +73,7 @@ model = { path = "../model" }
model-entity = { path = "../model-entity" }
model_notifications = { path = "../model_notifications" }
models_bulk_upload = { path = "../models_bulk_upload" }
+models_opensearch = { path = "../models_opensearch" }
models_pagination = { path = "../models_pagination", features = ["axum"] }
models_permissions = { path = "../models_permissions" }
models_soup = { path = "../models_soup", features = ["schema"] }
@@ -105,13 +107,11 @@ utoipa = { workspace = true, features = ["axum_extras"] }
utoipa-swagger-ui = { workspace = true, features = ["axum"] }
uuid = { workspace = true }
zip = { workspace = true }
-models_opensearch = { path = "../models_opensearch" }
[dev-dependencies]
cool_asserts = "2"
frecency = { path = "../frecency", features = ["mock"] }
-ordered-float = "5"
-
+ordered-float = { workspace = true }
[package.metadata.cargo-machete]
ignored = ["comms_service", "connection_gateway"]
diff --git a/rust/cloud-storage/document_storage_service/justfile b/rust/cloud-storage/document_storage_service/justfile
index 788a6d8c5c..e258eb06a4 100644
--- a/rust/cloud-storage/document_storage_service/justfile
+++ b/rust/cloud-storage/document_storage_service/justfile
@@ -1,16 +1,4 @@
-# export DATABASE_URL := "postgres://user:password@localhost:5432/macrodb"
-# export REDIS_URI := "redis://localhost:6369"
-# export DOCUMENT_STORAGE_BUCKET := "doc-storage-dev"
-# export ENVIRONMENT := "local"
-# export RUST_LOG := "document_text_extractor=trace"
-# export SEARCH_TEXT_EXTRACTOR_QUEUE := "extractor-queue"
-# export DOCX_DOCUMENT_UPLOAD_BUCKET := "testing-bucket"
-# export DOCUMENT_DELETE_QUEUE := "FILL_IN"
-
-export FRECENCY_TABLE_NAME := "frecency"
export DYNAMO_ENDPOINT_URL := 'http://localhost:8000'
-export AWS_ACCESS_KEY_ID := 'dummy'
-export AWS_SECRET_ACCESS_KEY := 'dummy'
set dotenv-load := true
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index 889fd9427e..8d7d212d25 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -2,6 +2,7 @@ use crate::{config::Config, service::s3::S3};
use axum::extract::FromRef;
use connection_gateway_client::client::ConnectionGatewayClient;
use dynamodb_client::DynamodbClient;
+use email::{domain::service::EmailServiceImpl, outbound::EmailPgRepo};
use email_service_client::EmailServiceClient;
use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
@@ -20,8 +21,13 @@ pub struct InternalFlag {
pub internal: bool,
}
-type DssSoupState =
- SoupRouterState<SoupImpl<PgSoupRepo, FrecencyQueryServiceImpl<FrecencyPgStorage>>>;
+type DssSoupState = SoupRouterState<
+ SoupImpl<
+ PgSoupRepo,
+ FrecencyQueryServiceImpl<FrecencyPgStorage>,
+ EmailServiceImpl<EmailPgRepo, FrecencyQueryServiceImpl<FrecencyPgStorage>>,
+ >,
+>;
#[derive(Clone, FromRef)]
pub(crate) struct ApiContext {
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index a30dd8e0a5..2efb2def49 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -1,5 +1,3 @@
-use std::sync::Arc;
-
use crate::{
api::context::{ApiContext, DocumentStorageServiceAuthKey},
config::{CloudfrontSignerPrivateKeySecretName, DocumentPermissionJwtSecretKey},
@@ -10,6 +8,7 @@ use comms_service_client::CommsServiceClient;
use config::{Config, Environment};
use connection_gateway_client::client::ConnectionGatewayClient;
use dynamodb_client::DynamodbClient;
+use email::{domain::service::EmailServiceImpl, outbound::EmailPgRepo};
use email_service_client::EmailServiceClient;
use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
@@ -23,6 +22,7 @@ use soup::{
outbound::pg_soup_repo::PgSoupRepo,
};
use sqlx::postgres::PgPoolOptions;
+use std::sync::Arc;
use sync_service_client::SyncServiceClient;
mod api;
@@ -181,10 +181,12 @@ async fn main() -> anyhow::Result<()> {
JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client)
.await?;
+ let frecency_service = FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone()));
let api_context = ApiContext {
soup_router_state: SoupRouterState::new(SoupImpl::new(
PgSoupRepo::new(db.clone()),
- FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone())),
+ frecency_service.clone(),
+ EmailServiceImpl::new(EmailPgRepo::new(db.clone()), frecency_service),
)),
db,
redis_client: Arc::new(Redis::new(redis_client)),
diff --git a/rust/cloud-storage/email/src/domain/models.rs b/rust/cloud-storage/email/src/domain/models.rs
index 5a3e41d3f2..e1c2b1780c 100644
--- a/rust/cloud-storage/email/src/domain/models.rs
+++ b/rust/cloud-storage/email/src/domain/models.rs
@@ -1,5 +1,5 @@
use chrono::{DateTime, Utc};
-use frecency::domain::models::FrecencyQueryErr;
+use frecency::domain::models::{AggregateFrecency, FrecencyQueryErr};
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{Identify, Query, SimpleSortMethod, SortOn};
use serde_with::{DeserializeFromStr, SerializeDisplay};
@@ -82,11 +82,12 @@ pub struct EmailThreadPreview {
}
#[non_exhaustive]
+#[derive(Debug)]
pub struct EnrichedEmailThreadPreview {
pub thread: EmailThreadPreview,
pub attachments: Vec<Attachment>,
pub attachments_macro: Vec<AttachmentMacro>,
- pub frecency_score: Option<f64>,
+ pub frecency_score: Option<AggregateFrecency>,
pub participants: Vec<Contact>,
}
@@ -101,7 +102,7 @@ impl Identify for EnrichedEmailThreadPreview {
impl SortOn<SimpleSortMethod> for EnrichedEmailThreadPreview {
fn sort_on(
sort: SimpleSortMethod,
- ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<SimpleSortMethod> {
+ ) -> impl FnMut(&Self) -> models_pagination::CursorVal<SimpleSortMethod> {
move |v| {
let val = match sort {
SimpleSortMethod::ViewedAt => v.thread.viewed_at.unwrap_or_default(),
diff --git a/rust/cloud-storage/email/src/domain/service.rs b/rust/cloud-storage/email/src/domain/service.rs
index ec0bdcb700..d63ebd8d79 100644
--- a/rust/cloud-storage/email/src/domain/service.rs
+++ b/rust/cloud-storage/email/src/domain/service.rs
@@ -2,11 +2,14 @@ use crate::domain::{
models::{EmailErr, EnrichedEmailThreadPreview, GetEmailsRequest, PreviewCursorQuery},
ports::{EmailRepo, EmailService},
};
-use frecency::domain::{models::FrecencyByIdsRequest, ports::FrecencyQueryService};
+use frecency::domain::{
+ models::{AggregateId, FrecencyByIdsRequest, FrecencyData},
+ ports::FrecencyQueryService,
+};
use macro_user_id::cowlike::CowLike;
use model_entity::EntityType;
use models_pagination::{CollectBy, PaginateOn, PaginatedCursor, SimpleSortMethod};
-use std::{collections::HashMap, str::FromStr};
+use std::collections::HashMap;
use uuid::Uuid;
pub struct EmailServiceImpl<T, U> {
@@ -103,25 +106,26 @@ where
.into_iter()
.group_by(|v| v.thread_id);
- let mut frecency_scores_map: HashMap<Uuid, f64> = frecency_scores?
- .into_inner()
- .into_iter()
- .filter_map(|(id, data)| {
- Some((
- Uuid::from_str(&id.entity.entity_id).ok()?,
- data.frecency_score,
- ))
- })
- .collect();
+ let mut frecency_scores_map: HashMap<AggregateId<'static>, FrecencyData> =
+ frecency_scores?.into_inner();
Ok(previews
.into_iter()
- .map(|thread| EnrichedEmailThreadPreview {
- attachments: attachment_map.remove(&thread.id).unwrap_or_default(),
- attachments_macro: macro_attachment_map.remove(&thread.id).unwrap_or_default(),
- participants: participant_map.remove(&thread.id).unwrap_or_default(),
- frecency_score: frecency_scores_map.remove(&thread.id),
- thread,
+ .map(|thread| {
+ let id = AggregateId {
+ user_id: thread.owner_id.clone(),
+ entity: EntityType::EmailThread.with_entity_string(thread.id.to_string()),
+ };
+
+ EnrichedEmailThreadPreview {
+ attachments: attachment_map.remove(&thread.id).unwrap_or_default(),
+ attachments_macro: macro_attachment_map.remove(&thread.id).unwrap_or_default(),
+ participants: participant_map.remove(&thread.id).unwrap_or_default(),
+ frecency_score: frecency_scores_map
+ .remove(&id)
+ .map(|data| id.into_aggregate(data)),
+ thread,
+ }
})
.paginate_on(limit as usize, sort_method)
.into_page())
diff --git a/rust/cloud-storage/email/src/inbound/axum/api_types.rs b/rust/cloud-storage/email/src/inbound/axum/api_types.rs
index 79845076e7..c2a8d9d52b 100644
--- a/rust/cloud-storage/email/src/inbound/axum/api_types.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/api_types.rs
@@ -1,5 +1,6 @@
use chrono::{DateTime, Utc};
use doppleganger::{Doppleganger, Mirror};
+use frecency::domain::models::AggregateFrecency;
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{PaginatedOpaqueCursor, SimpleSortMethod};
use serde::{Deserialize, Serialize};
@@ -47,9 +48,14 @@ struct ApiThreadPreviewCursor {
macro_attachments: Vec<ApiAttachmentMacro>,
#[dg(rename = "participants")]
contacts: Vec<ApiContact>,
+ #[dg(map = map_frecency)]
frecency_score: Option<f64>,
}
+fn map_frecency(f: Option<AggregateFrecency>) -> Option<f64> {
+ f.map(|f| f.data.frecency_score)
+}
+
#[derive(Debug, ToSchema, Serialize, Deserialize, Doppleganger)]
#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
diff --git a/rust/cloud-storage/frecency/Cargo.toml b/rust/cloud-storage/frecency/Cargo.toml
index 9a6b032d0b..0c2db0b7c9 100644
--- a/rust/cloud-storage/frecency/Cargo.toml
+++ b/rust/cloud-storage/frecency/Cargo.toml
@@ -22,7 +22,7 @@ macro_user_id = { path = "../macro_user_id" }
mockall = { workspace = true, optional = true }
model-entity = { path = "../model-entity" }
num-traits = { version = "0.2" }
-ordered-float = "5"
+ordered-float = { workspace = true }
recursion = { workspace = true, optional = true }
serde = { workspace = true }
serde_json = { workspace = true, optional = true }
diff --git a/rust/cloud-storage/frecency/src/domain/models.rs b/rust/cloud-storage/frecency/src/domain/models.rs
index 9b6423ea8e..9bd64f2e85 100644
--- a/rust/cloud-storage/frecency/src/domain/models.rs
+++ b/rust/cloud-storage/frecency/src/domain/models.rs
@@ -90,6 +90,14 @@ impl<'a> AggregateId<'a> {
entity: entity.into_owned(),
}
}
+
+ /// joins a [AggregateId] with a [FrecencyData] to construct an [AggregateFrecency]
+ pub fn into_aggregate(self, data: FrecencyData) -> AggregateFrecency {
+ AggregateFrecency {
+ id: self.into_owned(),
+ data,
+ }
+ }
}
/// The aggregated frecency record which is constructed from many [EventRecord]
@@ -108,6 +116,7 @@ pub struct AggregateFrecency {
/// struct which contains the frecency score for a given [AggregateId]
#[derive(Debug, Serialize, Deserialize, Clone)]
+#[non_exhaustive]
pub struct FrecencyData {
/// the total number of events that have occurred on this entity
pub event_count: usize,
diff --git a/rust/cloud-storage/macro_entrypoint/src/lib.rs b/rust/cloud-storage/macro_entrypoint/src/lib.rs
index be152c47a4..edb4d2198d 100644
--- a/rust/cloud-storage/macro_entrypoint/src/lib.rs
+++ b/rust/cloud-storage/macro_entrypoint/src/lib.rs
@@ -39,7 +39,6 @@ impl MacroEntrypoint {
/// consume self, initialize this binary, and return a proof that it was initialized [InitializedEntrypoint]
pub fn init(self) -> InitializedEntrypoint {
std::panic::set_hook(Box::new(tracing_panic::panic_hook));
- dotenv::dotenv().ok();
match (self.env, self.local) {
(Environment::Local, LocalOptions { tree_tracing: None }) => {
@@ -74,6 +73,7 @@ impl MacroEntrypoint {
}
}
+ dotenv::dotenv().unwrap();
InitializedEntrypoint(())
}
diff --git a/rust/cloud-storage/model_notifications/src/lib.rs b/rust/cloud-storage/model_notifications/src/lib.rs
index f71d8a8c77..b08712995e 100644
--- a/rust/cloud-storage/model_notifications/src/lib.rs
+++ b/rust/cloud-storage/model_notifications/src/lib.rs
@@ -277,7 +277,7 @@ impl Identify for Notification {
}
impl SortOn<CreatedAt> for UserNotification {
- fn sort_on(sort: CreatedAt) -> impl FnOnce(&Self) -> models_pagination::CursorVal<CreatedAt> {
+ fn sort_on(sort: CreatedAt) -> impl FnMut(&Self) -> models_pagination::CursorVal<CreatedAt> {
move |v| {
let last_val = v.temporal.created_at.unwrap_or(DateTime::UNIX_EPOCH);
models_pagination::CursorVal {
diff --git a/rust/cloud-storage/model_notifications/src/raw.rs b/rust/cloud-storage/model_notifications/src/raw.rs
index 3f71d207bb..d98066dae6 100644
--- a/rust/cloud-storage/model_notifications/src/raw.rs
+++ b/rust/cloud-storage/model_notifications/src/raw.rs
@@ -254,7 +254,7 @@ impl Identify for RawNotification {
}
impl SortOn<CreatedAt> for RawNotification {
- fn sort_on(sort: CreatedAt) -> impl FnOnce(&Self) -> models_pagination::CursorVal<CreatedAt> {
+ fn sort_on(sort: CreatedAt) -> impl FnMut(&Self) -> models_pagination::CursorVal<CreatedAt> {
move |v| {
let last_val = v.created_at.unwrap_or(DateTime::UNIX_EPOCH);
CursorVal {
@@ -266,7 +266,7 @@ impl SortOn<CreatedAt> for RawNotification {
}
impl SortOn<CreatedAt> for RawUserNotification {
- fn sort_on(sort: CreatedAt) -> impl FnOnce(&Self) -> models_pagination::CursorVal<CreatedAt> {
+ fn sort_on(sort: CreatedAt) -> impl FnMut(&Self) -> models_pagination::CursorVal<CreatedAt> {
move |v| {
let last_val = v.created_at.unwrap_or(DateTime::UNIX_EPOCH);
CursorVal {
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 cff77a3b94..c41a2de11a 100644
--- a/rust/cloud-storage/models_email/src/email/service/thread.rs
+++ b/rust/cloud-storage/models_email/src/email/service/thread.rs
@@ -151,7 +151,7 @@ impl ThreadPreviewCursor {
impl SortOn<SimpleSortMethod> for ThreadPreviewCursor {
fn sort_on(
sort: SimpleSortMethod,
- ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<SimpleSortMethod> {
+ ) -> impl FnMut(&Self) -> models_pagination::CursorVal<SimpleSortMethod> {
move |v| {
let last_val = v.timestamp_for_sort_method(sort);
models_pagination::CursorVal {
diff --git a/rust/cloud-storage/models_pagination/Cargo.toml b/rust/cloud-storage/models_pagination/Cargo.toml
index 070ff0b9a7..2a4919fa27 100644
--- a/rust/cloud-storage/models_pagination/Cargo.toml
+++ b/rust/cloud-storage/models_pagination/Cargo.toml
@@ -15,6 +15,7 @@ base64 = { workspace = true }
chrono = { workspace = true }
either = { workspace = true }
model-error-response = { path = "../model-error-response", optional = true }
+ordered-float = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
diff --git a/rust/cloud-storage/models_pagination/src/cursor.rs b/rust/cloud-storage/models_pagination/src/cursor.rs
index bc7a22c2c7..4e5c077cea 100644
--- a/rust/cloud-storage/models_pagination/src/cursor.rs
+++ b/rust/cloud-storage/models_pagination/src/cursor.rs
@@ -65,7 +65,7 @@ pub struct CursorVal<C: Sortable> {
/// defines type to be sortable, sortable types must have an associated [Sortable::Value]
pub trait Sortable: std::fmt::Debug {
/// the value which we sort on e.g. Utc timestamp, float, etc
- type Value: std::fmt::Debug;
+ type Value: std::fmt::Debug + std::cmp::Ord;
}
/// Intermediary struct which holds information about the page we are going to create.
@@ -76,6 +76,7 @@ pub struct Paginator<Iter, Cb, S, F> {
cb: Cb,
sort_on: PhantomData<S>,
filter_on: F,
+ ensure_sort: bool,
}
impl<Iter, Cb, S> Paginator<Iter, Cb, S, ()> {
@@ -87,6 +88,7 @@ impl<Iter, Cb, S> Paginator<Iter, Cb, S, ()> {
cb,
sort_on,
filter_on: (),
+ ensure_sort,
} = self;
Paginator {
iter,
@@ -94,6 +96,7 @@ impl<Iter, Cb, S> Paginator<Iter, Cb, S, ()> {
cb,
sort_on,
filter_on: filter,
+ ensure_sort,
}
}
}
@@ -103,7 +106,7 @@ pub trait Paginate: Iterator + Sized {
/// turn the iterator into a [Paginator]
fn paginate<Cb, S>(self, limit: usize, cb: Cb) -> Paginator<Self, Cb, S, ()>
where
- Cb: FnOnce(&<Self as Iterator>::Item) -> CursorVal<S>,
+ Cb: FnMut(&<Self as Iterator>::Item) -> CursorVal<S>,
S: Sortable;
}
@@ -114,7 +117,7 @@ pub trait PaginateOn<T: Sortable>: Paginate {
self,
limit: usize,
sort: T,
- ) -> Paginator<Self, impl FnOnce(&<Self as Iterator>::Item) -> CursorVal<T>, T, ()>
+ ) -> Paginator<Self, impl FnMut(&<Self as Iterator>::Item) -> CursorVal<T>, T, ()>
where
<Self as Iterator>::Item: SortOn<T>;
}
@@ -132,7 +135,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(sort: T) -> impl FnOnce(&Self) -> CursorVal<T>;
+ fn sort_on(sort: T) -> impl FnMut(&Self) -> CursorVal<T>;
}
impl<T> Paginate for T
@@ -151,6 +154,7 @@ where
cb,
sort_on: PhantomData,
filter_on: (),
+ ensure_sort: false,
}
}
}
@@ -163,7 +167,7 @@ where
self,
limit: usize,
sort: T,
- ) -> Paginator<Self, impl FnOnce(&<Self as Iterator>::Item) -> CursorVal<T>, T, ()>
+ ) -> Paginator<Self, impl FnMut(&<Self as Iterator>::Item) -> CursorVal<T>, T, ()>
where
<Self as Iterator>::Item: SortOn<T>,
{
@@ -186,24 +190,40 @@ impl<Iter, Cb, S, F> Paginator<Iter, Cb, S, F>
where
Iter: Iterator,
Iter::Item: Identify,
- Cb: FnOnce(&Iter::Item) -> CursorVal<S>,
+ Cb: FnMut(&Iter::Item) -> CursorVal<S>,
S: Sortable + Serialize,
S::Value: Serialize,
F: Serialize,
<Iter::Item as Identify>::Id: Serialize,
{
+ /// ensures that the output will be sorted.
+ /// You should not use this in most cases as the ideal scenario is that the database should
+ /// return an already sorted list.
+ /// This is an escape hatch for use when stitching multiple database queries together.
+ pub fn ensure_sorted(mut self) -> Self {
+ self.ensure_sort = true;
+ self
+ }
/// 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) -> PaginatedCursor<Iter::Item, <Iter::Item as Identify>::Id, S, F> {
let Paginator {
iter,
limit,
- cb,
+ mut cb,
filter_on,
+ ensure_sort,
..
} = self;
- let res: Vec<_> = iter.take(limit).collect();
+ let mut res: Vec<_> = iter.take(limit).collect();
+
+ if ensure_sort {
+ res.sort_by_key(|r| {
+ let cursor = cb(r);
+ cursor.last_val
+ });
+ }
match res.len().cmp(&limit) {
Ordering::Less => Paginated {
diff --git a/rust/cloud-storage/models_pagination/src/sort.rs b/rust/cloud-storage/models_pagination/src/sort.rs
index 31b1adf7fa..0076bef087 100644
--- a/rust/cloud-storage/models_pagination/src/sort.rs
+++ b/rust/cloud-storage/models_pagination/src/sort.rs
@@ -1,5 +1,6 @@
use crate::Sortable;
use chrono::{DateTime, Utc};
+use ordered_float::OrderedFloat;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
@@ -34,7 +35,7 @@ impl Sortable for SimpleSortMethod {
pub struct Frecency;
/// the possible values of the cursor when sorting by frecency
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub enum FrecencyValue {
/// the frecency score of the item
FrecencyScore(f64),
@@ -43,6 +44,32 @@ pub enum FrecencyValue {
UpdatedAt(DateTime<Utc>),
}
+impl Eq for FrecencyValue {}
+
+impl std::cmp::PartialOrd for FrecencyValue {
+ fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
+ Some(self.cmp(other))
+ }
+}
+
+impl std::cmp::Ord for FrecencyValue {
+ fn cmp(&self, other: &Self) -> std::cmp::Ordering {
+ match (self, other) {
+ (FrecencyValue::FrecencyScore(a), FrecencyValue::FrecencyScore(b)) => {
+ OrderedFloat(*a).cmp(&OrderedFloat(*b))
+ }
+ (FrecencyValue::UpdatedAt(a), FrecencyValue::UpdatedAt(b)) => a.cmp(b),
+ // score is always ranked before a timestamp
+ (FrecencyValue::FrecencyScore(_), FrecencyValue::UpdatedAt(_)) => {
+ std::cmp::Ordering::Greater
+ }
+ (FrecencyValue::UpdatedAt(_), FrecencyValue::FrecencyScore(_)) => {
+ std::cmp::Ordering::Less
+ }
+ }
+ }
+}
+
impl Sortable for Frecency {
type Value = FrecencyValue;
}
diff --git a/rust/cloud-storage/models_soup/src/item.rs b/rust/cloud-storage/models_soup/src/item.rs
index 0446a2a909..23e5c941f5 100644
--- a/rust/cloud-storage/models_soup/src/item.rs
+++ b/rust/cloud-storage/models_soup/src/item.rs
@@ -127,7 +127,7 @@ impl Identify for SoupItem {
impl SortOn<SimpleSortMethod> for SoupItem {
fn sort_on(
sort: SimpleSortMethod,
- ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<SimpleSortMethod> {
+ ) -> impl FnMut(&Self) -> models_pagination::CursorVal<SimpleSortMethod> {
move |v| {
let last_val = v.cursor_timestamp(sort);
models_pagination::CursorVal {
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 2843617613..317204afce 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,9 +112,7 @@ 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, PaginateOn, TypeEraseCursor,
- };
+ use models_pagination::{Base64Str, Cursor, CursorVal, PaginateOn, TypeEraseCursor};
use sqlx::{Pool, Postgres};
#[sqlx::test(fixtures(path = "../../../fixtures", scripts("user_notifications")))]
diff --git a/rust/cloud-storage/soup/.sqlx/query-5a843e114ac0cc32159b056320a94ab3ec28cff618e64b6fc794e40118b43c02.json b/rust/cloud-storage/soup/.sqlx/query-52eff164a09a6b7a9eb2f1c7c64f9f5a0e5512f46b3ca607cd456aca66f42cbc.json
similarity index 97%
rename from rust/cloud-storage/soup/.sqlx/query-5a843e114ac0cc32159b056320a94ab3ec28cff618e64b6fc794e40118b43c02.json
rename to rust/cloud-storage/soup/.sqlx/query-52eff164a09a6b7a9eb2f1c7c64f9f5a0e5512f46b3ca607cd456aca66f42cbc.json
index e2a25200e0..41dd4a5407 100644
--- a/rust/cloud-storage/soup/.sqlx/query-5a843e114ac0cc32159b056320a94ab3ec28cff618e64b6fc794e40118b43c02.json
+++ b/rust/cloud-storage/soup/.sqlx/query-52eff164a09a6b7a9eb2f1c7c64f9f5a0e5512f46b3ca607cd456aca66f42cbc.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": " \n WITH RECURSIVE ProjectHierarchy AS (\n SELECT p.id, uia.access_level \n FROM \"Project\" p\n JOIN \"UserItemAccess\" uia ON p.id = uia.item_id AND uia.item_type = 'project'\n WHERE uia.user_id = $1 AND p.\"deletedAt\" IS NULL\n UNION ALL\n SELECT p.id, ph.access_level\n FROM \"Project\" p \n JOIN ProjectHierarchy ph ON p.\"parentId\" = ph.id\n WHERE p.\"deletedAt\" IS NULL\n ),\n AllAccessGrants AS (\n SELECT item_id, item_type, access_level \n FROM \"UserItemAccess\" \n WHERE user_id = $1\n UNION ALL\n SELECT d.id AS item_id, 'document' AS item_type, ph.access_level\n FROM \"Document\" d \n JOIN ProjectHierarchy ph ON d.\"projectId\" = ph.id\n WHERE d.\"projectId\" IS NOT NULL AND d.\"deletedAt\" IS NULL\n UNION ALL\n SELECT c.id AS item_id, 'chat' AS item_type, ph.access_level\n FROM \"Chat\" c \n JOIN ProjectHierarchy ph ON c.\"projectId\" = ph.id\n WHERE c.\"projectId\" IS NOT NULL AND c.\"deletedAt\" IS NULL\n UNION ALL\n SELECT ph.id AS item_id, 'project' AS item_type, ph.access_level \n FROM ProjectHierarchy ph\n ),\n UserAccessibleItems AS (\n SELECT DISTINCT ON (item_id, item_type) item_id, item_type\n FROM AllAccessGrants\n ORDER BY item_id, item_type, \n CASE access_level\n WHEN 'owner' THEN 4\n WHEN 'edit' THEN 3 \n WHEN 'comment' THEN 2\n WHEN 'view' THEN 1\n ELSE 0\n END DESC\n ),\n Combined AS (\n SELECT\n 'document' as \"item_type!\",\n d.id as \"id!\",\n CAST(COALESCE(di.id, db.id) as TEXT) as \"document_version_id\",\n d.owner as \"user_id!\",\n d.name as \"name!\",\n d.\"branchedFromId\" as \"branched_from_id\",\n d.\"branchedFromVersionId\" as \"branched_from_version_id\",\n d.\"documentFamilyId\" as \"document_family_id\",\n d.\"fileType\" as \"file_type\",\n d.\"createdAt\"::timestamptz as \"created_at!\",\n d.\"updatedAt\"::timestamptz as \"updated_at!\",\n d.\"projectId\" as \"project_id\",\n NULL as \"is_persistent\",\n di.sha as \"sha\",\n uh.\"updatedAt\"::timestamptz as \"viewed_at\",\n CASE $2\n WHEN 'viewed_updated' THEN COALESCE(uh.\"updatedAt\", d.\"updatedAt\")\n WHEN 'viewed_at' THEN COALESCE(uh.\"updatedAt\", '1970-01-01 00:00:00+00')\n WHEN 'created_at' THEN d.\"createdAt\"\n ELSE d.\"updatedAt\"\n END::timestamptz as \"sort_ts!\"\n FROM \"Document\" d\n INNER JOIN UserAccessibleItems uai ON uai.item_id = d.id AND uai.item_type = 'document'\n -- This MUST be a LEFT JOIN to support all three sort methods\n LEFT JOIN \"UserHistory\" uh ON uh.\"itemId\" = d.id AND uh.\"itemType\" = 'document' AND uh.\"userId\" = $1\n LEFT JOIN LATERAL (\n SELECT b.id \n FROM \"DocumentBom\" b \n WHERE b.\"documentId\" = d.id \n ORDER BY b.\"createdAt\" DESC \n LIMIT 1\n ) db ON true\n LEFT JOIN LATERAL (\n SELECT i.id, i.sha \n FROM \"DocumentInstance\" i \n WHERE i.\"documentId\" = d.id \n ORDER BY i.\"updatedAt\" DESC \n LIMIT 1\n ) di ON true\n WHERE d.\"deletedAt\" IS NULL\n\n UNION ALL\n \n SELECT\n 'chat' as \"item_type!\",\n c.id as \"id!\",\n NULL as \"document_version_id\",\n c.\"userId\" as \"user_id!\",\n c.name as \"name!\",\n NULL as \"branched_from_id\",\n NULL as \"branched_from_version_id\",\n NULL as \"document_family_id\",\n NULL as \"file_type\",\n c.\"createdAt\"::timestamptz as \"created_at!\",\n c.\"updatedAt\"::timestamptz as \"updated_at!\",\n c.\"projectId\" as \"project_id\",\n c.\"isPersistent\" as \"is_persistent\",\n NULL as \"sha\",\n uh.\"updatedAt\"::timestamptz as \"viewed_at\",\n CASE $2\n WHEN 'viewed_updated' THEN COALESCE(uh.\"updatedAt\", c.\"updatedAt\")\n WHEN 'viewed_at' THEN COALESCE(uh.\"updatedAt\", '1970-01-01 00:00:00+00')\n WHEN 'created_at' THEN c.\"createdAt\"\n ELSE c.\"updatedAt\"\n END::timestamptz as \"sort_ts!\"\n FROM \"Chat\" c\n INNER JOIN UserAccessibleItems uai ON uai.item_id = c.id AND uai.item_type = 'chat'\n LEFT JOIN \"UserHistory\" uh ON uh.\"itemId\" = c.id AND uh.\"itemType\" = 'chat' AND uh.\"userId\" = $1\n WHERE c.\"deletedAt\" IS NULL\n\n UNION ALL\n\n SELECT\n 'project' as \"item_type!\",\n p.id as \"id!\",\n NULL as \"document_version_id\",\n p.\"userId\" as \"user_id!\",\n p.name as \"name!\",\n NULL as \"branched_from_id\",\n NULL as \"branched_from_version_id\",\n NULL as \"document_family_id\",\n NULL as \"file_type\",\n p.\"createdAt\"::timestamptz as \"created_at!\",\n p.\"updatedAt\"::timestamptz as \"updated_at!\",\n p.\"parentId\" as \"project_id\",\n NULL as \"is_persistent\",\n NULL as \"sha\",\n uh.\"updatedAt\"::timestamptz as \"viewed_at\",\n CASE $2\n WHEN 'viewed_updated' THEN COALESCE(uh.\"updatedAt\", p.\"updatedAt\")\n WHEN 'viewed_at' THEN COALESCE(uh.\"updatedAt\", '1970-01-01 00:00:00+00')\n WHEN 'created_at' THEN p.\"createdAt\"\n ELSE p.\"updatedAt\"\n END::timestamptz as \"sort_ts!\"\n FROM \"Project\" p\n INNER JOIN UserAccessibleItems uai\n ON uai.item_id = p.id\n AND uai.item_type = 'project'\n LEFT JOIN \"UserHistory\" uh\n ON uh.\"itemId\" = p.id\n AND uh.\"itemType\" = 'project'\n AND uh.\"userId\" = $1\n WHERE p.\"deletedAt\" IS NULL\n )\n SELECT Combined.* FROM Combined\n LEFT JOIN frecency_aggregates fa\n ON fa.entity_id = Combined.\"id!\"\n AND fa.entity_type = Combined.\"item_type!\"\n AND fa.user_id = $1\n WHERE fa.id IS NULL\n AND (\n ($4::timestamptz IS NULL)\n OR\n (Combined.\"sort_ts!\", Combined.\"id!\") < ($4, $5)\n )\n ORDER BY Combined.\"sort_ts!\" DESC, Combined.\"updated_at!\" DESC\n LIMIT $3\n ",
+ "query": " \n WITH RECURSIVE ProjectHierarchy AS (\n SELECT p.id, uia.access_level \n FROM \"Project\" p\n JOIN \"UserItemAccess\" uia ON p.id = uia.item_id AND uia.item_type = 'project'\n WHERE uia.user_id = $1 AND p.\"deletedAt\" IS NULL\n UNION ALL\n SELECT p.id, ph.access_level\n FROM \"Project\" p \n JOIN ProjectHierarchy ph ON p.\"parentId\" = ph.id\n WHERE p.\"deletedAt\" IS NULL\n ),\n AllAccessGrants AS (\n SELECT item_id, item_type, access_level \n FROM \"UserItemAccess\" \n WHERE user_id = $1\n UNION ALL\n SELECT d.id AS item_id, 'document' AS item_type, ph.access_level\n FROM \"Document\" d \n JOIN ProjectHierarchy ph ON d.\"projectId\" = ph.id\n WHERE d.\"projectId\" IS NOT NULL AND d.\"deletedAt\" IS NULL\n UNION ALL\n SELECT c.id AS item_id, 'chat' AS item_type, ph.access_level\n FROM \"Chat\" c \n JOIN ProjectHierarchy ph ON c.\"projectId\" = ph.id\n WHERE c.\"projectId\" IS NOT NULL AND c.\"deletedAt\" IS NULL\n UNION ALL\n SELECT ph.id AS item_id, 'project' AS item_type, ph.access_level \n FROM ProjectHierarchy ph\n ),\n UserAccessibleItems AS (\n SELECT DISTINCT ON (item_id, item_type) item_id, item_type\n FROM AllAccessGrants\n ORDER BY item_id, item_type, \n CASE access_level\n WHEN 'owner' THEN 4\n WHEN 'edit' THEN 3 \n WHEN 'comment' THEN 2\n WHEN 'view' THEN 1\n ELSE 0\n END DESC\n ),\n Combined AS (\n SELECT\n 'document' as \"item_type!\",\n d.id as \"id!\",\n CAST(COALESCE(di.id, db.id) as TEXT) as \"document_version_id\",\n d.owner as \"user_id!\",\n d.name as \"name!\",\n d.\"branchedFromId\" as \"branched_from_id\",\n d.\"branchedFromVersionId\" as \"branched_from_version_id\",\n d.\"documentFamilyId\" as \"document_family_id\",\n d.\"fileType\" as \"file_type\",\n d.\"createdAt\"::timestamptz as \"created_at!\",\n d.\"updatedAt\"::timestamptz as \"updated_at!\",\n d.\"projectId\" as \"project_id\",\n NULL as \"is_persistent\",\n di.sha as \"sha\",\n uh.\"updatedAt\"::timestamptz as \"viewed_at\",\n CASE $2\n WHEN 'viewed_updated' THEN COALESCE(uh.\"updatedAt\", d.\"updatedAt\")\n WHEN 'viewed_at' THEN COALESCE(uh.\"updatedAt\", '1970-01-01 00:00:00+00')\n WHEN 'created_at' THEN d.\"createdAt\"\n ELSE d.\"updatedAt\"\n END::timestamptz as \"sort_ts!\"\n FROM \"Document\" d\n INNER JOIN UserAccessibleItems uai ON uai.item_id = d.id AND uai.item_type = 'document'\n -- This MUST be a LEFT JOIN to support all three sort methods\n LEFT JOIN \"UserHistory\" uh ON uh.\"itemId\" = d.id AND uh.\"itemType\" = 'document' AND uh.\"userId\" = $1\n LEFT JOIN LATERAL (\n SELECT b.id \n FROM \"DocumentBom\" b \n WHERE b.\"documentId\" = d.id \n ORDER BY b.\"createdAt\" DESC \n LIMIT 1\n ) db ON true\n LEFT JOIN LATERAL (\n SELECT i.id, i.sha \n FROM \"DocumentInstance\" i \n WHERE i.\"documentId\" = d.id \n ORDER BY i.\"updatedAt\" DESC \n LIMIT 1\n ) di ON true\n WHERE d.\"deletedAt\" IS NULL\n\n UNION ALL\n \n SELECT\n 'chat' as \"item_type!\",\n c.id as \"id!\",\n NULL as \"document_version_id\",\n c.\"userId\" as \"user_id!\",\n c.name as \"name!\",\n NULL as \"branched_from_id\",\n NULL as \"branched_from_version_id\",\n NULL as \"document_family_id\",\n NULL as \"file_type\",\n c.\"createdAt\"::timestamptz as \"created_at!\",\n c.\"updatedAt\"::timestamptz as \"updated_at!\",\n c.\"projectId\" as \"project_id\",\n c.\"isPersistent\" as \"is_persistent\",\n NULL as \"sha\",\n uh.\"updatedAt\"::timestamptz as \"viewed_at\",\n CASE $2\n WHEN 'viewed_updated' THEN COALESCE(uh.\"updatedAt\", c.\"updatedAt\")\n WHEN 'viewed_at' THEN COALESCE(uh.\"updatedAt\", '1970-01-01 00:00:00+00')\n WHEN 'created_at' THEN c.\"createdAt\"\n ELSE c.\"updatedAt\"\n END::timestamptz as \"sort_ts!\"\n FROM \"Chat\" c\n INNER JOIN UserAccessibleItems uai ON uai.item_id = c.id AND uai.item_type = 'chat'\n LEFT JOIN \"UserHistory\" uh ON uh.\"itemId\" = c.id AND uh.\"itemType\" = 'chat' AND uh.\"userId\" = $1\n WHERE c.\"deletedAt\" IS NULL\n\n UNION ALL\n\n SELECT\n 'project' as \"item_type!\",\n p.id as \"id!\",\n NULL as \"document_version_id\",\n p.\"userId\" as \"user_id!\",\n p.name as \"name!\",\n NULL as \"branched_from_id\",\n NULL as \"branched_from_version_id\",\n NULL as \"document_family_id\",\n NULL as \"file_type\",\n p.\"createdAt\"::timestamptz as \"created_at!\",\n p.\"updatedAt\"::timestamptz as \"updated_at!\",\n p.\"parentId\" as \"project_id\",\n NULL as \"is_persistent\",\n NULL as \"sha\",\n uh.\"updatedAt\"::timestamptz as \"viewed_at\",\n CASE $2\n WHEN 'viewed_updated' THEN COALESCE(uh.\"updatedAt\", p.\"updatedAt\")\n WHEN 'viewed_at' THEN COALESCE(uh.\"updatedAt\", '1970-01-01 00:00:00+00')\n WHEN 'created_at' THEN p.\"createdAt\"\n ELSE p.\"updatedAt\"\n END::timestamptz as \"sort_ts!\"\n FROM \"Project\" p\n INNER JOIN UserAccessibleItems uai\n ON uai.item_id = p.id\n AND uai.item_type = 'project'\n LEFT JOIN \"UserHistory\" uh\n ON uh.\"itemId\" = p.id\n AND uh.\"itemType\" = 'project'\n AND uh.\"userId\" = $1\n WHERE p.\"deletedAt\" IS NULL\n )\n SELECT Combined.* FROM Combined\n LEFT JOIN frecency_aggregates fa\n ON fa.entity_id = Combined.\"id!\"\n AND fa.entity_type = Combined.\"item_type!\"\n AND fa.user_id = $1\n WHERE fa.id IS NULL\n AND (\n ($4::timestamptz IS NULL)\n OR\n (Combined.\"sort_ts!\", Combined.\"id!\"::text) < ($4, $5)\n )\n ORDER BY Combined.\"sort_ts!\" DESC, Combined.\"updated_at!\" DESC\n LIMIT $3\n ",
"describe": {
"columns": [
{
@@ -112,5 +112,5 @@
null
]
},
- "hash": "5a843e114ac0cc32159b056320a94ab3ec28cff618e64b6fc794e40118b43c02"
+ "hash": "52eff164a09a6b7a9eb2f1c7c64f9f5a0e5512f46b3ca607cd456aca66f42cbc"
}
diff --git a/rust/cloud-storage/soup/.sqlx/query-ec3e5a2554914b75f30d1d9b86f90821830f9edc1ebdd060864c4aac24cedd2f.json b/rust/cloud-storage/soup/.sqlx/query-b8e7abd96ea80bb45986ebb8e36f62af3852fe34b25058b3e79425def0ea0ebe.json
similarity index 97%
rename from rust/cloud-storage/soup/.sqlx/query-ec3e5a2554914b75f30d1d9b86f90821830f9edc1ebdd060864c4aac24cedd2f.json
rename to rust/cloud-storage/soup/.sqlx/query-b8e7abd96ea80bb45986ebb8e36f62af3852fe34b25058b3e79425def0ea0ebe.json
index 4bb58bc2a5..4cf296c7f6 100644
--- a/rust/cloud-storage/soup/.sqlx/query-ec3e5a2554914b75f30d1d9b86f90821830f9edc1ebdd060864c4aac24cedd2f.json
+++ b/rust/cloud-storage/soup/.sqlx/query-b8e7abd96ea80bb45986ebb8e36f62af3852fe34b25058b3e79425def0ea0ebe.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": " \n WITH RECURSIVE ProjectHierarchy AS (\n SELECT p.id, uia.access_level \n FROM \"Project\" p\n JOIN \"UserItemAccess\" uia ON p.id = uia.item_id AND uia.item_type = 'project'\n WHERE uia.user_id = $1 AND p.\"deletedAt\" IS NULL\n UNION ALL\n SELECT p.id, ph.access_level\n FROM \"Project\" p \n JOIN ProjectHierarchy ph ON p.\"parentId\" = ph.id\n WHERE p.\"deletedAt\" IS NULL\n ),\n AllAccessGrants AS (\n SELECT item_id, item_type, access_level \n FROM \"UserItemAccess\" \n WHERE user_id = $1\n UNION ALL\n SELECT d.id AS item_id, 'document' AS item_type, ph.access_level\n FROM \"Document\" d \n JOIN ProjectHierarchy ph ON d.\"projectId\" = ph.id\n WHERE d.\"projectId\" IS NOT NULL AND d.\"deletedAt\" IS NULL\n UNION ALL\n SELECT c.id AS item_id, 'chat' AS item_type, ph.access_level\n FROM \"Chat\" c \n JOIN ProjectHierarchy ph ON c.\"projectId\" = ph.id\n WHERE c.\"projectId\" IS NOT NULL AND c.\"deletedAt\" IS NULL\n UNION ALL\n SELECT ph.id AS item_id, 'project' AS item_type, ph.access_level \n FROM ProjectHierarchy ph\n ),\n UserAccessibleItems AS (\n SELECT DISTINCT ON (item_id, item_type) item_id, item_type\n FROM AllAccessGrants\n ORDER BY item_id, item_type, \n CASE access_level\n WHEN 'owner' THEN 4\n WHEN 'edit' THEN 3 \n WHEN 'comment' THEN 2\n WHEN 'view' THEN 1\n ELSE 0\n END DESC\n ),\n Combined AS (\n SELECT\n 'document' as \"item_type!\",\n d.id as \"id!\",\n CAST(COALESCE(di.id, db.id) as TEXT) as \"document_version_id\",\n d.owner as \"user_id!\",\n d.name as \"name!\",\n d.\"branchedFromId\" as \"branched_from_id\",\n d.\"branchedFromVersionId\" as \"branched_from_version_id\",\n d.\"documentFamilyId\" as \"document_family_id\",\n d.\"fileType\" as \"file_type\",\n d.\"createdAt\"::timestamptz as \"created_at!\",\n d.\"updatedAt\"::timestamptz as \"updated_at!\",\n d.\"projectId\" as \"project_id\",\n NULL as \"is_persistent\",\n di.sha as \"sha\",\n uh.\"updatedAt\"::timestamptz as \"viewed_at\",\n CASE $2\n WHEN 'viewed_updated' THEN COALESCE(uh.\"updatedAt\", d.\"updatedAt\")\n WHEN 'viewed_at' THEN COALESCE(uh.\"updatedAt\", '1970-01-01 00:00:00+00')\n WHEN 'created_at' THEN d.\"createdAt\"\n ELSE d.\"updatedAt\"\n END::timestamptz as \"sort_ts!\"\n FROM \"Document\" d\n INNER JOIN UserAccessibleItems uai ON uai.item_id = d.id AND uai.item_type = 'document'\n -- This MUST be a LEFT JOIN to support all three sort methods\n LEFT JOIN \"UserHistory\" uh ON uh.\"itemId\" = d.id AND uh.\"itemType\" = 'document' AND uh.\"userId\" = $1\n LEFT JOIN LATERAL (\n SELECT b.id \n FROM \"DocumentBom\" b \n WHERE b.\"documentId\" = d.id \n ORDER BY b.\"createdAt\" DESC \n LIMIT 1\n ) db ON true\n LEFT JOIN LATERAL (\n SELECT i.id, i.sha \n FROM \"DocumentInstance\" i \n WHERE i.\"documentId\" = d.id \n ORDER BY i.\"updatedAt\" DESC \n LIMIT 1\n ) di ON true\n WHERE d.\"deletedAt\" IS NULL\n\n UNION ALL\n \n SELECT\n 'chat' as \"item_type!\",\n c.id as \"id!\",\n NULL as \"document_version_id\",\n c.\"userId\" as \"user_id!\",\n c.name as \"name!\",\n NULL as \"branched_from_id\",\n NULL as \"branched_from_version_id\",\n NULL as \"document_family_id\",\n NULL as \"file_type\",\n c.\"createdAt\"::timestamptz as \"created_at!\",\n c.\"updatedAt\"::timestamptz as \"updated_at!\",\n c.\"projectId\" as \"project_id\",\n c.\"isPersistent\" as \"is_persistent\",\n NULL as \"sha\",\n uh.\"updatedAt\"::timestamptz as \"viewed_at\",\n CASE $2\n WHEN 'viewed_updated' THEN COALESCE(uh.\"updatedAt\", c.\"updatedAt\")\n WHEN 'viewed_at' THEN COALESCE(uh.\"updatedAt\", '1970-01-01 00:00:00+00')\n WHEN 'created_at' THEN c.\"createdAt\"\n ELSE c.\"updatedAt\"\n END::timestamptz as \"sort_ts!\"\n FROM \"Chat\" c\n INNER JOIN UserAccessibleItems uai ON uai.item_id = c.id AND uai.item_type = 'chat'\n LEFT JOIN \"UserHistory\" uh ON uh.\"itemId\" = c.id AND uh.\"itemType\" = 'chat' AND uh.\"userId\" = $1\n WHERE c.\"deletedAt\" IS NULL\n\n UNION ALL\n\n SELECT\n 'project' as \"item_type!\",\n p.id as \"id!\",\n NULL as \"document_version_id\",\n p.\"userId\" as \"user_id!\",\n p.name as \"name!\",\n NULL as \"branched_from_id\",\n NULL as \"branched_from_version_id\",\n NULL as \"document_family_id\",\n NULL as \"file_type\",\n p.\"createdAt\"::timestamptz as \"created_at!\",\n p.\"updatedAt\"::timestamptz as \"updated_at!\",\n p.\"parentId\" as \"project_id\",\n NULL as \"is_persistent\",\n NULL as \"sha\",\n uh.\"updatedAt\"::timestamptz as \"viewed_at\",\n CASE $2\n WHEN 'viewed_updated' THEN COALESCE(uh.\"updatedAt\", p.\"updatedAt\")\n WHEN 'viewed_at' THEN COALESCE(uh.\"updatedAt\", '1970-01-01 00:00:00+00')\n WHEN 'created_at' THEN p.\"createdAt\"\n ELSE p.\"updatedAt\"\n END::timestamptz as \"sort_ts!\"\n FROM \"Project\" p\n INNER JOIN UserAccessibleItems uai\n ON uai.item_id = p.id\n AND uai.item_type = 'project'\n LEFT JOIN \"UserHistory\" uh\n ON uh.\"itemId\" = p.id\n AND uh.\"itemType\" = 'project'\n AND uh.\"userId\" = $1\n WHERE p.\"deletedAt\" IS NULL\n )\n SELECT * FROM Combined\n WHERE\n ($4::timestamptz IS NULL)\n OR\n (\"sort_ts!\", \"id!\") < ($4, $5)\n ORDER BY \"sort_ts!\" DESC, \"updated_at!\" DESC\n LIMIT $3\n",
+ "query": " \n WITH RECURSIVE ProjectHierarchy AS (\n SELECT p.id, uia.access_level \n FROM \"Project\" p\n JOIN \"UserItemAccess\" uia ON p.id = uia.item_id AND uia.item_type = 'project'\n WHERE uia.user_id = $1 AND p.\"deletedAt\" IS NULL\n UNION ALL\n SELECT p.id, ph.access_level\n FROM \"Project\" p \n JOIN ProjectHierarchy ph ON p.\"parentId\" = ph.id\n WHERE p.\"deletedAt\" IS NULL\n ),\n AllAccessGrants AS (\n SELECT item_id, item_type, access_level \n FROM \"UserItemAccess\" \n WHERE user_id = $1\n UNION ALL\n SELECT d.id AS item_id, 'document' AS item_type, ph.access_level\n FROM \"Document\" d \n JOIN ProjectHierarchy ph ON d.\"projectId\" = ph.id\n WHERE d.\"projectId\" IS NOT NULL AND d.\"deletedAt\" IS NULL\n UNION ALL\n SELECT c.id AS item_id, 'chat' AS item_type, ph.access_level\n FROM \"Chat\" c \n JOIN ProjectHierarchy ph ON c.\"projectId\" = ph.id\n WHERE c.\"projectId\" IS NOT NULL AND c.\"deletedAt\" IS NULL\n UNION ALL\n SELECT ph.id AS item_id, 'project' AS item_type, ph.access_level \n FROM ProjectHierarchy ph\n ),\n UserAccessibleItems AS (\n SELECT DISTINCT ON (item_id, item_type) item_id, item_type\n FROM AllAccessGrants\n ORDER BY item_id, item_type, \n CASE access_level\n WHEN 'owner' THEN 4\n WHEN 'edit' THEN 3 \n WHEN 'comment' THEN 2\n WHEN 'view' THEN 1\n ELSE 0\n END DESC\n ),\n Combined AS (\n SELECT\n 'document' as \"item_type!\",\n d.id as \"id!\",\n CAST(COALESCE(di.id, db.id) as TEXT) as \"document_version_id\",\n d.owner as \"user_id!\",\n d.name as \"name!\",\n d.\"branchedFromId\" as \"branched_from_id\",\n d.\"branchedFromVersionId\" as \"branched_from_version_id\",\n d.\"documentFamilyId\" as \"document_family_id\",\n d.\"fileType\" as \"file_type\",\n d.\"createdAt\"::timestamptz as \"created_at!\",\n d.\"updatedAt\"::timestamptz as \"updated_at!\",\n d.\"projectId\" as \"project_id\",\n NULL as \"is_persistent\",\n di.sha as \"sha\",\n uh.\"updatedAt\"::timestamptz as \"viewed_at\",\n CASE $2\n WHEN 'viewed_updated' THEN COALESCE(uh.\"updatedAt\", d.\"updatedAt\")\n WHEN 'viewed_at' THEN COALESCE(uh.\"updatedAt\", '1970-01-01 00:00:00+00')\n WHEN 'created_at' THEN d.\"createdAt\"\n ELSE d.\"updatedAt\"\n END::timestamptz as \"sort_ts!\"\n FROM \"Document\" d\n INNER JOIN UserAccessibleItems uai ON uai.item_id = d.id AND uai.item_type = 'document'\n -- This MUST be a LEFT JOIN to support all three sort methods\n LEFT JOIN \"UserHistory\" uh ON uh.\"itemId\" = d.id AND uh.\"itemType\" = 'document' AND uh.\"userId\" = $1\n LEFT JOIN LATERAL (\n SELECT b.id \n FROM \"DocumentBom\" b \n WHERE b.\"documentId\" = d.id \n ORDER BY b.\"createdAt\" DESC \n LIMIT 1\n ) db ON true\n LEFT JOIN LATERAL (\n SELECT i.id, i.sha \n FROM \"DocumentInstance\" i \n WHERE i.\"documentId\" = d.id \n ORDER BY i.\"updatedAt\" DESC \n LIMIT 1\n ) di ON true\n WHERE d.\"deletedAt\" IS NULL\n\n UNION ALL\n \n SELECT\n 'chat' as \"item_type!\",\n c.id as \"id!\",\n NULL as \"document_version_id\",\n c.\"userId\" as \"user_id!\",\n c.name as \"name!\",\n NULL as \"branched_from_id\",\n NULL as \"branched_from_version_id\",\n NULL as \"document_family_id\",\n NULL as \"file_type\",\n c.\"createdAt\"::timestamptz as \"created_at!\",\n c.\"updatedAt\"::timestamptz as \"updated_at!\",\n c.\"projectId\" as \"project_id\",\n c.\"isPersistent\" as \"is_persistent\",\n NULL as \"sha\",\n uh.\"updatedAt\"::timestamptz as \"viewed_at\",\n CASE $2\n WHEN 'viewed_updated' THEN COALESCE(uh.\"updatedAt\", c.\"updatedAt\")\n WHEN 'viewed_at' THEN COALESCE(uh.\"updatedAt\", '1970-01-01 00:00:00+00')\n WHEN 'created_at' THEN c.\"createdAt\"\n ELSE c.\"updatedAt\"\n END::timestamptz as \"sort_ts!\"\n FROM \"Chat\" c\n INNER JOIN UserAccessibleItems uai ON uai.item_id = c.id AND uai.item_type = 'chat'\n LEFT JOIN \"UserHistory\" uh ON uh.\"itemId\" = c.id AND uh.\"itemType\" = 'chat' AND uh.\"userId\" = $1\n WHERE c.\"deletedAt\" IS NULL\n\n UNION ALL\n\n SELECT\n 'project' as \"item_type!\",\n p.id as \"id!\",\n NULL as \"document_version_id\",\n p.\"userId\" as \"user_id!\",\n p.name as \"name!\",\n NULL as \"branched_from_id\",\n NULL as \"branched_from_version_id\",\n NULL as \"document_family_id\",\n NULL as \"file_type\",\n p.\"createdAt\"::timestamptz as \"created_at!\",\n p.\"updatedAt\"::timestamptz as \"updated_at!\",\n p.\"parentId\" as \"project_id\",\n NULL as \"is_persistent\",\n NULL as \"sha\",\n uh.\"updatedAt\"::timestamptz as \"viewed_at\",\n CASE $2\n WHEN 'viewed_updated' THEN COALESCE(uh.\"updatedAt\", p.\"updatedAt\")\n WHEN 'viewed_at' THEN COALESCE(uh.\"updatedAt\", '1970-01-01 00:00:00+00')\n WHEN 'created_at' THEN p.\"createdAt\"\n ELSE p.\"updatedAt\"\n END::timestamptz as \"sort_ts!\"\n FROM \"Project\" p\n INNER JOIN UserAccessibleItems uai\n ON uai.item_id = p.id\n AND uai.item_type = 'project'\n LEFT JOIN \"UserHistory\" uh\n ON uh.\"itemId\" = p.id\n AND uh.\"itemType\" = 'project'\n AND uh.\"userId\" = $1\n WHERE p.\"deletedAt\" IS NULL\n )\n SELECT * FROM Combined\n WHERE\n ($4::timestamptz IS NULL)\n OR\n (\"sort_ts!\", \"id!\"::text) < ($4, $5)\n ORDER BY \"sort_ts!\" DESC, \"updated_at!\" DESC\n LIMIT $3\n",
"describe": {
"columns": [
{
@@ -112,5 +112,5 @@
null
]
},
- "hash": "ec3e5a2554914b75f30d1d9b86f90821830f9edc1ebdd060864c4aac24cedd2f"
+ "hash": "b8e7abd96ea80bb45986ebb8e36f62af3852fe34b25058b3e79425def0ea0ebe"
}
diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.toml
index 1b5e70d4d4..37aabd4867 100644
--- a/rust/cloud-storage/soup/Cargo.toml
+++ b/rust/cloud-storage/soup/Cargo.toml
@@ -13,9 +13,9 @@ axum = [
"models_pagination/axum",
"models_soup/schema",
]
-inbound = ["ports"]
+inbound = ["email/inbound", "ports"]
outbound = ["ports"]
-ports = ["frecency/ports"]
+ports = ["dep:tokio", "frecency/ports"]
[dependencies]
@@ -24,6 +24,7 @@ axum = { workspace = true, optional = true }
chrono = { workspace = true }
doppleganger = { workspace = true, features = ["chrono", "uuid"] }
either = { workspace = true }
+email = { path = "../email", features = ["ports"] }
filter_ast = { path = "../filter_ast" }
frecency = { path = "../frecency" }
item_filters = { path = "../item_filters" }
@@ -38,6 +39,7 @@ recursion = { workspace = true }
serde = { workspace = true }
sqlx = { workspace = true }
thiserror = { workspace = true }
+tokio = { workspace = true, features = ["macros"], optional = true }
tracing = { workspace = true }
utoipa = { workspace = true, optional = true }
uuid = { workspace = true }
@@ -51,7 +53,7 @@ http-body-util = { workspace = true }
item_filters = { path = "../item_filters", features = ["mock"] }
macro_db_migrator = { path = "../macro_db_migrator" }
mockall = { workspace = true }
-ordered-float = "5"
+ordered-float = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
tower = { workspace = true }
diff --git a/rust/cloud-storage/soup/src/domain/models.rs b/rust/cloud-storage/soup/src/domain/models.rs
index fe739e50cf..b741253472 100644
--- a/rust/cloud-storage/soup/src/domain/models.rs
+++ b/rust/cloud-storage/soup/src/domain/models.rs
@@ -1,12 +1,15 @@
+use email::domain::models::{GetEmailsRequest, PreviewView};
use frecency::domain::models::{AggregateFrecency, FrecencyQueryErr};
use item_filters::ast::EntityFilterAst;
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::Entity;
use models_pagination::{
- Cursor, CursorVal, Frecency, FrecencyValue, Identify, Query, SimpleSortMethod, SortOn,
+ Cursor, CursorVal, CursorWithValAndFilter, Frecency, FrecencyValue, Identify, Query,
+ SimpleSortMethod, SortOn,
};
use models_soup::item::SoupItem;
use thiserror::Error;
+use uuid::Uuid;
#[derive(Debug, Clone, Copy)]
pub enum SoupType {
@@ -28,19 +31,18 @@ pub struct SimpleSortRequest<'a> {
#[derive(Debug)]
pub(crate) enum SimpleSortQuery {
/// we dont have anything to filter out
- NoFilter(Query<String, SimpleSortMethod, ()>),
+ NoFilter(Query<Uuid, SimpleSortMethod, ()>),
/// we filter out items that DO have a [Frecency] record
- FilterFrecency(Query<String, SimpleSortMethod, Frecency>),
+ FilterFrecency(Query<Uuid, SimpleSortMethod, Frecency>),
/// we filter out items based on the input [EntityFilterAst]
- ItemsFilter(Query<String, SimpleSortMethod, EntityFilterAst>),
+ ItemsFilter(Query<Uuid, 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)>),
+ ItemsAndFrecencyFilter(Query<Uuid, SimpleSortMethod, (Frecency, EntityFilterAst)>),
}
impl SimpleSortQuery {
pub(crate) fn from_entity_cursor(
- cursor: Query<String, SimpleSortMethod, Option<EntityFilterAst>>,
+ cursor: Query<Uuid, SimpleSortMethod, Option<EntityFilterAst>>,
) -> Self {
match cursor {
Query::Sort(s, Some(f)) => SimpleSortQuery::ItemsFilter(Query::Sort(s, f)),
@@ -90,8 +92,8 @@ pub struct AdvancedSortParams<'a> {
}
pub enum SoupQuery {
- Simple(Query<String, SimpleSortMethod, Option<EntityFilterAst>>),
- Frecency(Query<String, Frecency, Option<EntityFilterAst>>),
+ Simple(Query<Uuid, SimpleSortMethod, Option<EntityFilterAst>>),
+ Frecency(Query<Uuid, Frecency, Option<EntityFilterAst>>),
}
impl SoupQuery {
@@ -108,6 +110,36 @@ pub struct SoupRequest {
pub limit: u16,
pub cursor: SoupQuery,
pub user: MacroUserIdStr<'static>,
+ pub email_preview_view: PreviewView,
+ pub link_id: Uuid,
+}
+
+impl SoupRequest {
+ pub(crate) fn build_email_request(&self) -> Option<GetEmailsRequest> {
+ Some(GetEmailsRequest {
+ view: self.email_preview_view.clone(),
+ link_id: self.link_id,
+ macro_id: self.user.clone(),
+ limit: Some(self.limit as u32),
+ query: match &self.cursor {
+ SoupQuery::Simple(Query::Sort(t, _f)) => Some(Query::Sort(*t, ())),
+ SoupQuery::Simple(Query::Cursor(CursorWithValAndFilter {
+ id,
+ limit,
+ val,
+ filter: _,
+ })) => Some(Query::Cursor(CursorWithValAndFilter {
+ id: *id,
+ limit: *limit,
+ val: val.clone(),
+ filter: (),
+ })),
+ // we don't yet have sort by frecency implemented for emails yet
+ // so we fallback to viewedupdated
+ SoupQuery::Frecency(_) => None,
+ }?,
+ })
+ }
}
/// a [SoupItem] with an associated frecency score
@@ -129,9 +161,7 @@ impl Identify for FrecencySoupItem {
}
impl SortOn<Frecency> for FrecencySoupItem {
- fn sort_on(
- sort_type: Frecency,
- ) -> impl FnOnce(&Self) -> models_pagination::CursorVal<Frecency> {
+ fn sort_on(sort_type: Frecency) -> impl FnMut(&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
@@ -144,8 +174,8 @@ impl SortOn<Frecency> for FrecencySoupItem {
}
impl SortOn<SimpleSortMethod> for FrecencySoupItem {
- fn sort_on(sort: SimpleSortMethod) -> impl FnOnce(&Self) -> CursorVal<SimpleSortMethod> {
- let cb = SoupItem::sort_on(sort);
+ fn sort_on(sort: SimpleSortMethod) -> impl FnMut(&Self) -> CursorVal<SimpleSortMethod> {
+ let mut cb = SoupItem::sort_on(sort);
move |v| cb(&v.item)
}
}
@@ -156,4 +186,6 @@ pub enum SoupErr {
FrecencyErr(#[from] FrecencyQueryErr),
#[error(transparent)]
SoupDbErr(#[from] anyhow::Error),
+ #[error(transparent)]
+ EmailErr(#[from] email::domain::models::EmailErr),
}
diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rs
index fdfe3aa122..f2537ee2e7 100644
--- a/rust/cloud-storage/soup/src/domain/service.rs
+++ b/rust/cloud-storage/soup/src/domain/service.rs
@@ -5,7 +5,9 @@ use crate::domain::{
},
ports::{SoupOutput, SoupRepo, SoupService},
};
+use doppleganger::Mirror;
use either::Either;
+use email::domain::{models::GetEmailsRequest, ports::EmailService};
use frecency::domain::{
models::{AggregateId, FrecencyPageRequest, JoinFrecency},
ports::FrecencyQueryService,
@@ -16,30 +18,35 @@ use model_entity::as_owned::ShallowClone;
use models_pagination::{
Cursor, CursorVal, Frecency, FrecencyValue, PaginateOn, Query, SimpleSortMethod,
};
-use models_soup::item::SoupItem;
+use models_soup::{email_thread::SoupEnrichedEmailThreadPreview, item::SoupItem};
use std::cmp::Ordering;
+use uuid::Uuid;
#[cfg(test)]
mod tests;
/// struct which handles the actual implementation of soup with abstracted interfaces for mocking
-pub struct SoupImpl<T, U> {
+pub struct SoupImpl<T, U, V> {
/// the interface for interacting with the db
soup_storage: T,
/// the interface for interacting with frecency
frecency: U,
+ /// the interface for interacting with email
+ email_service: V,
}
-impl<T, U> SoupImpl<T, U>
+impl<T, U, V> SoupImpl<T, U, V>
where
T: SoupRepo,
anyhow::Error: From<T::Err>,
U: FrecencyQueryService,
+ V: EmailService,
{
- pub fn new(soup_storage: T, frecency: U) -> Self {
+ pub fn new(soup_storage: T, frecency: U, email_service: V) -> Self {
SoupImpl {
soup_storage,
frecency,
+ email_service,
}
}
@@ -60,6 +67,7 @@ where
.await
.map_err(anyhow::Error::from)?,
};
+
Ok(res.into_iter().map(|item| FrecencySoupItem {
item,
frecency_score: None,
@@ -87,7 +95,6 @@ where
) -> Result<impl Iterator<Item = FrecencySoupItem>, SoupErr> {
let len = frecency_items.len();
let remainder_to_fetch = (limit as usize).saturating_sub(len);
- dbg!(remainder_to_fetch, len);
let updated_at_soup = self
.handle_simple_request(
@@ -107,7 +114,7 @@ where
async fn handle_advanced_sort(
&self,
- cursor: Query<String, Frecency, Option<EntityFilterAst>>,
+ cursor: Query<Uuid, Frecency, Option<EntityFilterAst>>,
soup_type: SoupType,
user: MacroUserIdStr<'static>,
limit: u16,
@@ -230,34 +237,70 @@ where
Ordering::Greater | Ordering::Equal => Either::Right(res),
})
}
+
+ async fn handle_email_request(
+ &self,
+ req: Option<GetEmailsRequest>,
+ ) -> Result<impl Iterator<Item = FrecencySoupItem>, SoupErr> {
+ let Some(req) = req else {
+ return Ok(Either::Left(None.into_iter()));
+ };
+
+ let emails = self
+ .email_service
+ .get_email_thread_previews(req)
+ .await?
+ .items
+ .into_iter()
+ .map(|mut f| {
+ let frecency_score = f.frecency_score.take();
+ let soup_email = SoupEnrichedEmailThreadPreview::mirror(f);
+ FrecencySoupItem {
+ item: SoupItem::EmailThread(soup_email),
+ frecency_score,
+ }
+ });
+ Ok(Either::Right(emails))
+ }
}
-impl<T, U> SoupService for SoupImpl<T, U>
+impl<T, U, V> SoupService for SoupImpl<T, U, V>
where
T: SoupRepo,
anyhow::Error: From<T::Err>,
U: FrecencyQueryService,
+ V: EmailService,
{
async fn get_user_soup(&self, req: SoupRequest) -> Result<SoupOutput, SoupErr> {
let limit = req.limit.clamp(20, 500);
let paginate_filter = req.cursor.filter().cloned();
+
+ let email_request = req.build_email_request();
+
match req.cursor {
SoupQuery::Simple(cursor) => {
let sort_method = *cursor.sort_method();
+ let main_soup_fut = self.handle_simple_request(
+ req.soup_type,
+ SimpleSortRequest {
+ limit,
+ cursor: SimpleSortQuery::from_entity_cursor(cursor),
+ user_id: req.user,
+ },
+ );
+
+ let email_soup_fut = self.handle_email_request(email_request);
+
+ let (main_soup, email_soup) = tokio::try_join!(main_soup_fut, email_soup_fut)?;
+
Ok(Either::Left(
- self.handle_simple_request(
- req.soup_type,
- SimpleSortRequest {
- limit,
- cursor: SimpleSortQuery::from_entity_cursor(cursor),
- user_id: req.user,
- },
- )
- .await?
- .paginate_on(limit.into(), sort_method)
- .filter_on(paginate_filter)
- .into_page(),
+ main_soup
+ .chain(email_soup)
+ .paginate_on(limit.into(), sort_method)
+ .filter_on(paginate_filter)
+ .ensure_sorted()
+ .into_page(),
))
}
SoupQuery::Frecency(cursor) => Ok(Either::Right(
diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rs
index 5767e041b9..60d366ef16 100644
--- a/rust/cloud-storage/soup/src/domain/service/tests.rs
+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs
@@ -1,12 +1,15 @@
use crate::domain::ports::MockSoupRepo;
use chrono::Days;
use cool_asserts::assert_matches;
+use email::domain::models::{EnrichedEmailThreadPreview, PreviewView};
use frecency::domain::models::FrecencyPageResponse;
use frecency::domain::ports::MockFrecencyQueryService;
use frecency::domain::services::FrecencyQueryServiceImpl;
use frecency::{domain::models::AggregateFrecency, outbound::mock::MockFrecencyStorage};
use model_entity::EntityType;
-use models_pagination::{Cursor, CursorVal, FrecencyValue, SimpleSortMethod, TypeEraseCursor};
+use models_pagination::{
+ Cursor, CursorVal, FrecencyValue, PaginatedCursor, SimpleSortMethod, TypeEraseCursor,
+};
use models_soup::document::SoupDocument;
use ordered_float::OrderedFloat;
use sqlx::types::chrono::{DateTime, Utc};
@@ -14,6 +17,23 @@ use uuid::Uuid;
use super::*;
+struct NoopEmailService;
+
+impl EmailService for NoopEmailService {
+ async fn get_email_thread_previews(
+ &self,
+ _req: email::domain::models::GetEmailsRequest,
+ ) -> Result<
+ PaginatedCursor<EnrichedEmailThreadPreview, Uuid, SimpleSortMethod, ()>,
+ email::domain::models::EmailErr,
+ > {
+ Ok(Option::<EnrichedEmailThreadPreview>::None
+ .into_iter()
+ .paginate_on(0, SimpleSortMethod::CreatedAt)
+ .into_page())
+ }
+}
+
fn soup_document(id: &str) -> SoupDocument {
// Create a deterministic UUID from the string ID
let uuid = Uuid::parse_str(id).unwrap_or_else(|_| {
@@ -96,8 +116,13 @@ async fn it_should_not_query_frecency() {
let res = SoupImpl::new(
soup_mock,
FrecencyQueryServiceImpl::new(MockFrecencyStorage::new()),
+ NoopEmailService,
)
.get_user_soup(SoupRequest {
+ email_preview_view: PreviewView::StandardLabel(
+ email::domain::models::PreviewViewStandardLabel::Inbox,
+ ),
+ link_id: Uuid::new_v4(),
soup_type: SoupType::UnExpanded,
limit: 0,
cursor: SoupQuery::Simple(Query::Sort(SimpleSortMethod::ViewedUpdated, None)),
@@ -165,16 +190,24 @@ async fn it_should_query_frecency() {
Box::pin(async move { res })
});
- let res = SoupImpl::new(soup_mock, FrecencyQueryServiceImpl::new(frecency_mock))
- .get_user_soup(SoupRequest {
- soup_type: SoupType::UnExpanded,
- limit: u16::MAX,
- cursor: SoupQuery::Frecency(Query::Sort(Frecency, None)),
- user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- })
- .await
- .unwrap()
- .type_erase();
+ let res = SoupImpl::new(
+ soup_mock,
+ FrecencyQueryServiceImpl::new(frecency_mock),
+ NoopEmailService,
+ )
+ .get_user_soup(SoupRequest {
+ email_preview_view: PreviewView::StandardLabel(
+ email::domain::models::PreviewViewStandardLabel::Inbox,
+ ),
+ link_id: Uuid::new_v4(),
+ soup_type: SoupType::UnExpanded,
+ limit: u16::MAX,
+ cursor: SoupQuery::Frecency(Query::Sort(Frecency, None)),
+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ })
+ .await
+ .unwrap()
+ .type_erase();
dbg!(&res);
@@ -234,16 +267,24 @@ async fn it_should_sort_frecency_descending() {
Box::pin(async move { res })
});
- let res = SoupImpl::new(soup_mock, FrecencyQueryServiceImpl::new(frecency_mock))
- .get_user_soup(SoupRequest {
- soup_type: SoupType::UnExpanded,
- limit: u16::MAX,
- cursor: SoupQuery::Frecency(Query::Sort(Frecency, None)),
- user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- })
- .await
- .unwrap()
- .type_erase();
+ let res = SoupImpl::new(
+ soup_mock,
+ FrecencyQueryServiceImpl::new(frecency_mock),
+ NoopEmailService,
+ )
+ .get_user_soup(SoupRequest {
+ email_preview_view: PreviewView::StandardLabel(
+ email::domain::models::PreviewViewStandardLabel::Inbox,
+ ),
+ link_id: Uuid::new_v4(),
+ soup_type: SoupType::UnExpanded,
+ limit: u16::MAX,
+ cursor: SoupQuery::Frecency(Query::Sort(Frecency, None)),
+ user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ })
+ .await
+ .unwrap()
+ .type_erase();
dbg!(&res);
@@ -270,7 +311,7 @@ async fn frecency_should_fallback() {
AggregateFrecency::new_mock(
EntityType::Document
.with_entity_string(uuid::Uuid::from_u128(v as u128).to_string()),
- v.into(),
+ v as f64,
)
});
let res = Ok(FrecencyPageResponse::new_mock(iter));
@@ -317,8 +358,12 @@ async fn frecency_should_fallback() {
Box::pin(async move { res })
});
- let res = SoupImpl::new(soup, frecency)
+ let res = SoupImpl::new(soup, frecency, NoopEmailService)
.get_user_soup(SoupRequest {
+ email_preview_view: PreviewView::StandardLabel(
+ email::domain::models::PreviewViewStandardLabel::Inbox,
+ ),
+ link_id: Uuid::new_v4(),
soup_type: SoupType::UnExpanded,
limit: 100,
cursor: SoupQuery::Frecency(Query::Sort(Frecency, None)),
@@ -383,8 +428,12 @@ async fn frecency_should_paginate() {
Box::pin(async move { Ok(vec) })
});
- let res = SoupImpl::new(soup, frecency)
+ let res = SoupImpl::new(soup, frecency, NoopEmailService)
.get_user_soup(SoupRequest {
+ email_preview_view: PreviewView::StandardLabel(
+ email::domain::models::PreviewViewStandardLabel::Inbox,
+ ),
+ link_id: Uuid::new_v4(),
soup_type: SoupType::UnExpanded,
limit: 100,
cursor: SoupQuery::Frecency(Query::Sort(Frecency, None)),
@@ -451,12 +500,16 @@ async fn frecency_should_resume_cursor() {
Box::pin(async move { Ok(vec) })
});
- let res = SoupImpl::new(soup, frecency)
+ let res = SoupImpl::new(soup, frecency, NoopEmailService)
.get_user_soup(SoupRequest {
+ email_preview_view: PreviewView::StandardLabel(
+ email::domain::models::PreviewViewStandardLabel::Inbox,
+ ),
+ link_id: Uuid::new_v4(),
soup_type: SoupType::UnExpanded,
limit: 100,
cursor: SoupQuery::Frecency(Query::Cursor(Cursor {
- id: Uuid::from_u128(5).to_string(),
+ id: Uuid::from_u128(5),
limit: 100,
val: CursorVal {
sort_type: Frecency,
@@ -515,8 +568,8 @@ async fn frecency_fallback_cursor_should_resume() {
} => {
let expected_time = <DateTime<Utc>>::default() + Days::new(5);
assert_eq!(last_val, &expected_time);
- let expected_uuid_str = Uuid::from_u128(100).to_string();
- assert_eq!(id, &expected_uuid_str);
+ let expected_uuid = Uuid::from_u128(100);
+ assert_eq!(id, &expected_uuid);
true
})
})
@@ -535,12 +588,16 @@ async fn frecency_fallback_cursor_should_resume() {
Box::pin(async move { res })
});
- let res = SoupImpl::new(soup, frecency)
+ let res = SoupImpl::new(soup, frecency, NoopEmailService)
.get_user_soup(SoupRequest {
+ email_preview_view: PreviewView::StandardLabel(
+ email::domain::models::PreviewViewStandardLabel::Inbox,
+ ),
+ link_id: Uuid::new_v4(),
soup_type: SoupType::UnExpanded,
limit: 100,
cursor: SoupQuery::Frecency(Query::Cursor(Cursor {
- id: Uuid::from_u128(100).to_string(),
+ id: Uuid::from_u128(100),
limit: 100,
val: CursorVal {
sort_type: Frecency,
@@ -595,8 +652,13 @@ async fn cursor_should_return_simple_sort() {
let res = SoupImpl::new(
soup_mock,
FrecencyQueryServiceImpl::new(MockFrecencyStorage::new()),
+ NoopEmailService,
)
.get_user_soup(SoupRequest {
+ email_preview_view: PreviewView::StandardLabel(
+ email::domain::models::PreviewViewStandardLabel::Inbox,
+ ),
+ link_id: Uuid::new_v4(),
soup_type: SoupType::UnExpanded,
limit: 0,
cursor: SoupQuery::Simple(Query::Sort(SimpleSortMethod::ViewedUpdated, None)),
@@ -649,8 +711,12 @@ async fn cursor_should_return_frecency() {
Box::pin(async move { Ok(vec) })
});
- let res = SoupImpl::new(soup, frecency)
+ let res = SoupImpl::new(soup, frecency, NoopEmailService)
.get_user_soup(SoupRequest {
+ email_preview_view: PreviewView::StandardLabel(
+ email::domain::models::PreviewViewStandardLabel::Inbox,
+ ),
+ link_id: Uuid::new_v4(),
soup_type: SoupType::UnExpanded,
limit: 100,
cursor: SoupQuery::Frecency(Query::Sort(Frecency, None)),
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router.rs b/rust/cloud-storage/soup/src/inbound/axum_router.rs
index 186cb47913..cbb029347b 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router.rs
@@ -9,6 +9,7 @@ use axum::{
response::IntoResponse,
routing::{get, post},
};
+use email::domain::models::PreviewView;
use item_filters::{
EntityFilters,
ast::{EntityFilterAst, ExpandErr},
@@ -25,6 +26,7 @@ use serde::{Deserialize, Serialize};
use std::sync::Arc;
use thiserror::Error;
use utoipa::{IntoParams, ToSchema};
+use uuid::Uuid;
#[cfg(test)]
mod tests;
@@ -139,6 +141,10 @@ where
limit: params.limit.unwrap_or(20),
cursor,
user: macro_user_id,
+ email_preview_view: PreviewView::StandardLabel(
+ email::domain::models::PreviewViewStandardLabel::Inbox,
+ ),
+ link_id: Uuid::nil(),
})
.await?;
@@ -245,8 +251,8 @@ pub struct PostSoupRequest {
}
type SoupCursor = EitherWrapper<
- CursorExtractor<String, SimpleSortMethod, Option<EntityFilterAst>>,
- CursorExtractor<String, Frecency, Option<EntityFilterAst>>,
+ CursorExtractor<Uuid, SimpleSortMethod, Option<EntityFilterAst>>,
+ CursorExtractor<Uuid, Frecency, Option<EntityFilterAst>>,
>;
/// Gets the items the user has access to
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.rs
index c67eb732e9..5a5be3e8fd 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
@@ -20,11 +20,12 @@ pub async fn expanded_generic_cursor_soup(
db: &PgPool,
user_id: MacroUserIdStr<'_>,
limit: u16,
- cursor: Query<String, SimpleSortMethod, ()>,
+ cursor: Query<Uuid, SimpleSortMethod, ()>,
) -> 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();
+ let cursor_id = cursor_id.as_ref().map(|u| u.to_string());
let items: Vec<SoupItem> = sqlx::query!(
r#"
@@ -179,7 +180,7 @@ r#"
WHERE
($4::timestamptz IS NULL)
OR
- ("sort_ts!", "id!") < ($4, $5)
+ ("sort_ts!", "id!"::text) < ($4, $5)
ORDER BY "sort_ts!" DESC, "updated_at!" DESC
LIMIT $3
"#,
@@ -203,11 +204,12 @@ pub async fn no_frecency_expanded_generic_soup(
db: &PgPool,
user_id: MacroUserIdStr<'_>,
limit: u16,
- cursor: Query<String, SimpleSortMethod, Frecency>,
+ cursor: Query<Uuid, SimpleSortMethod, Frecency>,
) -> 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();
+ let cursor_id = cursor_id.as_ref().map(|u| u.to_string());
let items: Vec<SoupItem> = sqlx::query!(
r#"
@@ -367,7 +369,7 @@ r#"
AND (
($4::timestamptz IS NULL)
OR
- (Combined."sort_ts!", Combined."id!") < ($4, $5)
+ (Combined."sort_ts!", Combined."id!"::text) < ($4, $5)
)
ORDER BY Combined."sort_ts!" DESC, Combined."updated_at!" DESC
LIMIT $3
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
index c85c9ca4b1..4af07b52d0 100644
--- 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
@@ -173,7 +173,7 @@ static SUFFIX: &str = r#"
WHERE
($4::timestamptz IS NULL)
OR
- ("sort_ts", "id") < ($4, $5)
+ ("sort_ts", "id"::text) < ($4, $5)
ORDER BY "sort_ts" DESC, "updated_at" DESC
LIMIT $3
"#;
@@ -188,7 +188,7 @@ static SUFFIX_NO_FRECENCY: &str = r#"
AND (
($4::timestamptz IS NULL)
OR
- (Combined."sort_ts", Combined."id") < ($4, $5)
+ (Combined."sort_ts", Combined."id"::text) < ($4, $5)
)
ORDER BY Combined."sort_ts" DESC, Combined."updated_at" DESC
LIMIT $3
@@ -461,7 +461,7 @@ pub(crate) struct ExpandedDynamicCursorArgs<'a> {
/// the limit of items we can return
pub limit: u16,
/// the Query that we are attempting to perform
- pub cursor: Query<String, SimpleSortMethod, EntityFilterAst>,
+ pub cursor: Query<Uuid, SimpleSortMethod, EntityFilterAst>,
/// whether or not the query should explicitly remove items that DO have
/// frecency records
pub exclude_frecency: bool,
@@ -481,6 +481,7 @@ pub(crate) async fn expanded_dynamic_cursor_soup(
let query_limit = limit as i64;
let sort_method_str = cursor.sort_method().to_string();
let (cursor_id, cursor_timestamp) = cursor.vals();
+ let cursor_id_str = cursor_id.as_ref().map(|u| u.to_string());
build_query(cursor.filter(), exclude_frecency)
.build()
@@ -488,7 +489,7 @@ pub(crate) async fn expanded_dynamic_cursor_soup(
.bind(sort_method_str)
.bind(query_limit)
.bind(cursor_timestamp)
- .bind(cursor_id)
+ .bind(cursor_id_str)
.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 0bfbc412aa..51b017c784 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
@@ -164,7 +164,7 @@ async fn test_get_user_items_expanded_cursor(pool: Pool<Postgres>) -> anyhow::Re
result.next_cursor.map(|s| {
let decoded = s.decode_json().unwrap();
models_pagination::Cursor {
- id: decoded.id.to_string(),
+ id: decoded.id,
limit: decoded.limit,
val: decoded.val,
filter: decoded.filter,
@@ -623,7 +623,7 @@ async fn test_no_frecency_expanded_cursor_pagination(pool: Pool<Postgres>) -> an
result.next_cursor.map(|s| {
let decoded = s.decode_json().unwrap();
models_pagination::Cursor {
- id: decoded.id.to_string(),
+ id: decoded.id,
limit: decoded.limit,
val: decoded.val,
filter: decoded.filter,
@@ -1603,7 +1603,7 @@ async fn test_cursor_pagination_with_document_filter(db: PgPool) -> anyhow::Resu
user_id: user_id.copied(),
limit: 3,
cursor: Query::Cursor(models_pagination::Cursor {
- id: cursor_decoded.id.to_string(),
+ id: cursor_decoded.id,
limit: cursor_decoded.limit,
val: cursor_decoded.val,
filter: filters_for_cursor,
@@ -1708,7 +1708,7 @@ async fn test_cursor_pagination_with_combined_filters(db: PgPool) -> anyhow::Res
user_id: user_id.copied(),
limit: 2,
cursor: Query::Cursor(models_pagination::Cursor {
- id: cursor_decoded.id.to_string(),
+ id: cursor_decoded.id,
limit: cursor_decoded.limit,
val: cursor_decoded.val,
filter: filters_for_cursor,
@@ -1803,7 +1803,7 @@ async fn test_cursor_pagination_filter_consistency(db: PgPool) -> anyhow::Result
let filters_for_cursor =
EntityFilterAst::new_from_filters(entity_filters.clone())?.unwrap();
current_query = Query::Cursor(models_pagination::Cursor {
- id: cursor_decoded.id.to_string(),
+ id: cursor_decoded.id,
limit: cursor_decoded.limit,
val: cursor_decoded.val,
filter: filters_for_cursor,
@@ -1911,7 +1911,7 @@ async fn test_cursor_pagination_with_single_item_filter(db: PgPool) -> anyhow::R
user_id: user_id.copied(),
limit: 5,
cursor: Query::Cursor(models_pagination::Cursor {
- id: cursor_decoded.id.to_string(),
+ id: cursor_decoded.id,
limit: cursor_decoded.limit,
val: cursor_decoded.val,
filter: filters_for_cursor,
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.rs
index af2b5f1ee6..3e61e9c645 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
@@ -18,11 +18,12 @@ pub async fn unexpanded_generic_cursor_soup(
db: &PgPool,
user_id: MacroUserIdStr<'_>,
limit: u16,
- cursor: Query<String, SimpleSortMethod, ()>,
+ cursor: Query<Uuid, SimpleSortMethod, ()>,
) -> 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();
+ let cursor_id = cursor_id.map(|u| u.to_string());
let items: Vec<SoupItem> = sqlx::query!(
r#"
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 1548804920..1b25e8b6ce 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
@@ -254,7 +254,7 @@ async fn test_get_user_items_unexpanded_cursor(pool: Pool<Postgres>) -> anyhow::
result.next_cursor.map(|s| {
let decoded = s.decode_json().unwrap();
models_pagination::Cursor {
- id: decoded.id.to_string(),
+ id: decoded.id,
limit: decoded.limit,
val: decoded.val,
filter: decoded.filter,