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): return emails from api (#343)

Sean Ayeb727feeb1212
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index e448da7056..aace85f8ca 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2832,6 +2832,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"axum",
+ "axum-extra",
"chrono",
"doppleganger",
"frecency",
@@ -2860,9 +2861,11 @@ version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
+ "doppleganger",
"email_utils",
"futures",
"macro_db_migrator",
+ "macro_user_id",
"macro_uuid",
"models_email",
"models_pagination",
@@ -2922,11 +2925,13 @@ dependencies = [
"aws-sdk-secretsmanager",
"aws-sdk-sqs",
"axum",
+ "axum-extra",
"base64 0.22.1",
"bytes",
"cloudfront_sign",
"connection_gateway",
"document_storage_service_client",
+ "doppleganger",
"ego-tree",
"email",
"email_db_client",
@@ -5399,9 +5404,12 @@ dependencies = [
"anyhow",
"base64 0.22.1",
"chrono",
+ "doppleganger",
"ego-tree",
+ "email",
"html2text",
"lazy_static",
+ "macro_user_id",
"macro_uuid",
"models_pagination",
"regex",
@@ -7980,6 +7988,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"axum",
+ "axum-extra",
"chrono",
"cool_asserts",
"doppleganger",
diff --git a/rust/cloud-storage/comms_service/src/api/channels/get_channels.rs b/rust/cloud-storage/comms_service/src/api/channels/get_channels.rs
index fe54a9df38..4b2b851e72 100644
--- a/rust/cloud-storage/comms_service/src/api/channels/get_channels.rs
+++ b/rust/cloud-storage/comms_service/src/api/channels/get_channels.rs
@@ -34,7 +34,7 @@ pub enum GetChannelsError {
#[error(transparent)]
Sqlx(#[from] sqlx::Error),
#[error("Invalid user id")]
- Id(#[from] macro_user_id::user_id::ParseErr),
+ Id(#[from] macro_user_id::error::ParseErr),
}
impl IntoResponse for GetChannelsError {
diff --git a/rust/cloud-storage/deny.toml b/rust/cloud-storage/deny.toml
index 0ab49613d5..65e2e0f2f1 100644
--- a/rust/cloud-storage/deny.toml
+++ b/rust/cloud-storage/deny.toml
@@ -100,6 +100,7 @@ allow = [
"BSD-2-Clause",
"BSD-3-Clause",
"BSL-1.0",
+ "CDLA-Permissive-2.0",
"ISC",
"MIT",
"MPL-2.0",
@@ -107,7 +108,6 @@ allow = [
"Unicode-3.0",
"Zlib",
"bzip2-1.0.6",
- "CDLA-Permissive-2.0",
]
# The confidence threshold for detecting a license from license text.
# The higher the value, the more closely the license text must be to the
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 8d7d212d25..f1d342ac16 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -27,6 +27,7 @@ type DssSoupState = SoupRouterState<
FrecencyQueryServiceImpl<FrecencyPgStorage>,
EmailServiceImpl<EmailPgRepo, FrecencyQueryServiceImpl<FrecencyPgStorage>>,
>,
+ EmailServiceImpl<EmailPgRepo, FrecencyQueryServiceImpl<FrecencyPgStorage>>,
>;
#[derive(Clone, FromRef)]
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 2efb2def49..51f653249b 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -182,12 +182,17 @@ async fn main() -> anyhow::Result<()> {
.await?;
let frecency_service = FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone()));
+ let email_service =
+ EmailServiceImpl::new(EmailPgRepo::new(db.clone()), frecency_service.clone());
let api_context = ApiContext {
- soup_router_state: SoupRouterState::new(SoupImpl::new(
- PgSoupRepo::new(db.clone()),
- frecency_service.clone(),
- EmailServiceImpl::new(EmailPgRepo::new(db.clone()), frecency_service),
- )),
+ soup_router_state: SoupRouterState::new(
+ SoupImpl::new(
+ PgSoupRepo::new(db.clone()),
+ frecency_service,
+ email_service.clone(),
+ ),
+ email_service,
+ ),
db,
redis_client: Arc::new(Redis::new(redis_client)),
s3_client: Arc::new(S3::new(
diff --git a/rust/cloud-storage/email/.sqlx/query-f3037d59872cb8e1e2921a05cbd4b0e5b5a9a48ee90e22ab1824611688854692.json b/rust/cloud-storage/email/.sqlx/query-f3037d59872cb8e1e2921a05cbd4b0e5b5a9a48ee90e22ab1824611688854692.json
new file mode 100644
index 0000000000..adfb9780cf
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-f3037d59872cb8e1e2921a05cbd4b0e5b5a9a48ee90e22ab1824611688854692.json
@@ -0,0 +1,84 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, macro_id, fusionauth_user_id, email_address, provider as \"provider: _\",\n is_sync_active, created_at, updated_at\n FROM email_links\n WHERE fusionauth_user_id = $1 AND macro_id = $2 AND provider = $3\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "macro_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "fusionauth_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "email_address",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 4,
+ "name": "provider: _",
+ "type_info": {
+ "Custom": {
+ "name": "email_user_provider_enum",
+ "kind": {
+ "Enum": [
+ "GMAIL"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 5,
+ "name": "is_sync_active",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ {
+ "Custom": {
+ "name": "email_user_provider_enum",
+ "kind": {
+ "Enum": [
+ "GMAIL"
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "f3037d59872cb8e1e2921a05cbd4b0e5b5a9a48ee90e22ab1824611688854692"
+}
diff --git a/rust/cloud-storage/email/Cargo.toml b/rust/cloud-storage/email/Cargo.toml
index 4a053952eb..7f2c51c742 100644
--- a/rust/cloud-storage/email/Cargo.toml
+++ b/rust/cloud-storage/email/Cargo.toml
@@ -8,6 +8,7 @@ version = "0.1.0"
ai_schema = ["dep:schemars"]
axum = [
"dep:axum",
+ "dep:axum-extra",
"dep:model-error-response",
"dep:model_user",
"dep:utoipa",
@@ -21,6 +22,7 @@ ports = ["dep:tokio", "frecency/ports"]
[dependencies]
anyhow = { workspace = true }
axum = { workspace = true, optional = true }
+axum-extra = { workspace = true, optional = true }
chrono = { workspace = true, features = ["serde"] }
doppleganger = { workspace = true, features = ["chrono", "uuid"] }
frecency = { path = "../frecency" }
diff --git a/rust/cloud-storage/email/src/domain/models.rs b/rust/cloud-storage/email/src/domain/models.rs
index 993d0ebec3..689f153e89 100644
--- a/rust/cloud-storage/email/src/domain/models.rs
+++ b/rust/cloud-storage/email/src/domain/models.rs
@@ -1,6 +1,6 @@
use chrono::{DateTime, Utc};
use frecency::domain::models::{AggregateFrecency, FrecencyQueryErr};
-use macro_user_id::user_id::MacroUserIdStr;
+use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};
use models_pagination::{Identify, Query, SimpleSortMethod, SortOn};
use serde_with::{DeserializeFromStr, SerializeDisplay};
use std::str::FromStr;
@@ -226,3 +226,29 @@ pub struct Label {
pub label_list_visibility: LabelListVisibility,
pub type_: LabelType,
}
+
+/// The provider of this email
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum UserProvider {
+ Gmail,
+}
+
+impl UserProvider {
+ pub fn as_str(&self) -> &'static str {
+ match self {
+ UserProvider::Gmail => "GMAIL",
+ }
+ }
+}
+
+#[derive(Clone)]
+pub struct Link {
+ pub id: Uuid,
+ pub macro_id: MacroUserIdStr<'static>,
+ pub fusionauth_user_id: String,
+ pub email_address: EmailStr<'static>,
+ pub provider: UserProvider,
+ pub is_sync_active: bool,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+}
diff --git a/rust/cloud-storage/email/src/domain/ports.rs b/rust/cloud-storage/email/src/domain/ports.rs
index 732f99662a..3e76e85259 100644
--- a/rust/cloud-storage/email/src/domain/ports.rs
+++ b/rust/cloud-storage/email/src/domain/ports.rs
@@ -1,6 +1,6 @@
use crate::domain::models::{
Attachment, AttachmentMacro, Contact, EmailErr, EmailThreadPreview, EnrichedEmailThreadPreview,
- GetEmailsRequest, Label, PreviewCursorQuery,
+ GetEmailsRequest, Label, Link, PreviewCursorQuery, UserProvider,
};
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{PaginatedCursor, SimpleSortMethod};
@@ -28,10 +28,18 @@ pub trait EmailRepo: Send + Sync + 'static {
&self,
thread_ids: &[Uuid],
) -> impl Future<Output = Result<Vec<Contact>, Self::Err>> + Send;
+
fn labels_by_thread_ids(
&self,
thread_ids: &[Uuid],
) -> impl Future<Output = Result<Vec<Label>, Self::Err>> + Send;
+
+ fn link_by_fusionauth_and_macro_id(
+ &self,
+ fusionauth_user_id: &str,
+ macro_id: MacroUserIdStr<'_>,
+ provider: UserProvider,
+ ) -> impl Future<Output = Result<Option<Link>, Self::Err>> + Send;
}
pub trait EmailService: Send + Sync + 'static {
@@ -44,4 +52,10 @@ pub trait EmailService: Send + Sync + 'static {
EmailErr,
>,
> + Send;
+
+ fn get_link_by_auth_id_and_macro_id(
+ &self,
+ auth_id: &str,
+ macro_id: MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Option<Link>, EmailErr>> + Send;
}
diff --git a/rust/cloud-storage/email/src/domain/service.rs b/rust/cloud-storage/email/src/domain/service.rs
index 5a9baeb393..6cc52d3e3b 100644
--- a/rust/cloud-storage/email/src/domain/service.rs
+++ b/rust/cloud-storage/email/src/domain/service.rs
@@ -1,5 +1,7 @@
use crate::domain::{
- models::{EmailErr, EnrichedEmailThreadPreview, GetEmailsRequest, PreviewCursorQuery},
+ models::{
+ EmailErr, EnrichedEmailThreadPreview, GetEmailsRequest, PreviewCursorQuery, UserProvider,
+ },
ports::{EmailRepo, EmailService},
};
use frecency::domain::{
@@ -12,6 +14,7 @@ use models_pagination::{CollectBy, PaginateOn, PaginatedCursor, SimpleSortMethod
use std::collections::HashMap;
use uuid::Uuid;
+#[derive(Clone)]
pub struct EmailServiceImpl<T, U> {
email_repo: T,
frecency_service: U,
@@ -137,4 +140,16 @@ where
.paginate_on(limit as usize, sort_method)
.into_page())
}
+
+ async fn get_link_by_auth_id_and_macro_id(
+ &self,
+ auth_id: &str,
+ macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,
+ ) -> Result<Option<super::models::Link>, EmailErr> {
+ Ok(self
+ .email_repo
+ .link_by_fusionauth_and_macro_id(auth_id, macro_id, UserProvider::Gmail)
+ .await
+ .map_err(anyhow::Error::from)?)
+ }
}
diff --git a/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs b/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs
index 1da9f8de16..ed7d84d660 100644
--- a/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs
@@ -1,19 +1,21 @@
-use std::str::FromStr;
-
+use crate::{
+ domain::{
+ models::{EmailErr, Link, PreviewView},
+ ports::EmailService,
+ },
+ inbound::{ApiSortMethod, EmailPreviewState},
+};
use axum::{
RequestPartsExt, async_trait,
- extract::{FromRequestParts, Path, rejection::PathRejection},
+ extract::{FromRef, FromRequestParts, Path, rejection::PathRejection},
http::{StatusCode, request::Parts},
response::{IntoResponse, Response},
};
+use axum_extra::extract::Cached;
+use model_user::axum_extractor::{MacroUserExtractor, UserExtractorErr};
+use std::{marker::PhantomData, str::FromStr};
use thiserror::Error;
use utoipa::{IntoParams, ToSchema};
-use uuid::Uuid;
-
-use crate::{
- domain::models::{EmailErr, PreviewView},
- inbound::ApiSortMethod,
-};
#[derive(Debug, Error)]
pub enum GetPreviewsCursorError {
@@ -42,9 +44,6 @@ impl IntoResponse for GetPreviewsCursorError {
}
}
-#[derive(Debug, Clone)]
-pub struct LinkUuid(pub Uuid);
-
pub(crate) struct PreviewViewExtractor(pub PreviewView);
#[async_trait]
@@ -68,3 +67,59 @@ pub struct GetPreviewsCursorParams {
/// Sort method. Options are viewed_at, created_at, updated_at, viewed_updated. Defaults to viewed_updated.
pub sort_method: Option<ApiSortMethod>,
}
+
+pub struct EmailLinkExtractor<U>(pub Link, pub PhantomData<U>);
+
+impl<U> Clone for EmailLinkExtractor<U> {
+ fn clone(&self) -> Self {
+ Self(self.0.clone(), PhantomData)
+ }
+}
+
+#[derive(Debug, Error)]
+pub enum EmailLinkErr {
+ #[error("Internal server error")]
+ DbErr(#[from] crate::domain::models::EmailErr),
+ #[error("Email link not found")]
+ NotFound,
+ #[error(transparent)]
+ UserErr(#[from] UserExtractorErr),
+}
+
+impl IntoResponse for EmailLinkErr {
+ fn into_response(self) -> Response {
+ if let EmailLinkErr::UserErr(u) = self {
+ return u.into_response();
+ }
+ let status = match &self {
+ EmailLinkErr::DbErr(_) | EmailLinkErr::UserErr(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ EmailLinkErr::NotFound => StatusCode::NOT_FOUND,
+ };
+
+ (status, self.to_string()).into_response()
+ }
+}
+
+#[async_trait]
+impl<S, U> FromRequestParts<S> for EmailLinkExtractor<U>
+where
+ EmailPreviewState<U>: FromRef<S>,
+ U: EmailService,
+ S: Send + Sync + 'static,
+{
+ type Rejection = EmailLinkErr;
+
+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
+ let Cached(MacroUserExtractor {
+ macro_user_id,
+ user_context,
+ ..
+ }) = parts.extract_with_state(state).await?;
+ let res = <EmailPreviewState<U>>::from_ref(state)
+ .inner
+ .get_link_by_auth_id_and_macro_id(&user_context.fusion_user_id, macro_user_id)
+ .await?
+ .ok_or(EmailLinkErr::NotFound)?;
+ Ok(Self(res, PhantomData))
+ }
+}
diff --git a/rust/cloud-storage/email/src/inbound/axum/router.rs b/rust/cloud-storage/email/src/inbound/axum/router.rs
index 86d0595587..79abdbb4eb 100644
--- a/rust/cloud-storage/email/src/inbound/axum/router.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/router.rs
@@ -1,8 +1,9 @@
use axum::{
- Extension, Json, Router,
+ Json, Router,
extract::{self, State},
routing::get,
};
+use axum_extra::extract::Cached;
use model_error_response::ErrorResponse;
use model_user::axum_extractor::MacroUserExtractor;
use models_pagination::{CursorExtractor, SimpleSortMethod, TypeEraseCursor};
@@ -12,15 +13,13 @@ use uuid::Uuid;
use crate::{
domain::{models::GetEmailsRequest, ports::EmailService},
inbound::{
- ApiPaginatedThreadCursor,
- axum::axum_impls::{
- GetPreviewsCursorError, GetPreviewsCursorParams, LinkUuid, PreviewViewExtractor,
- },
+ ApiPaginatedThreadCursor, EmailLinkExtractor,
+ axum::axum_impls::{GetPreviewsCursorError, GetPreviewsCursorParams, PreviewViewExtractor},
},
};
pub struct EmailPreviewState<T> {
- inner: Arc<T>,
+ pub(crate) inner: Arc<T>,
}
impl<T> Clone for EmailPreviewState<T> {
@@ -70,11 +69,11 @@ where
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(link_id, macro_user, service), fields(user_id=macro_user.macro_user_id.as_ref(), fusionauth_user_id=macro_user.user_context.fusion_user_id))]
+#[tracing::instrument(skip(link, macro_user, service), fields(user_id=macro_user.macro_user_id.as_ref(), fusionauth_user_id=macro_user.user_context.fusion_user_id))]
async fn cursor_handler<T: EmailService>(
State(service): State<EmailPreviewState<T>>,
- macro_user: MacroUserExtractor,
- Extension(LinkUuid(link_id)): Extension<LinkUuid>,
+ Cached(macro_user): Cached<MacroUserExtractor>,
+ Cached(EmailLinkExtractor(link, _)): Cached<EmailLinkExtractor<T>>,
PreviewViewExtractor(preview_view): PreviewViewExtractor,
extract::Query(params): extract::Query<GetPreviewsCursorParams>,
cursor: CursorExtractor<Uuid, SimpleSortMethod, ()>,
@@ -84,7 +83,7 @@ async fn cursor_handler<T: EmailService>(
.inner
.get_email_thread_previews(GetEmailsRequest {
view: preview_view,
- link_id,
+ link_id: link.id,
macro_id: macro_user.macro_user_id,
limit: params.limit,
query: cursor.into_query(
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo.rs
index 2a35ef36bf..73c0dacfb5 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo.rs
@@ -1,8 +1,8 @@
use crate::domain::models::Label;
use crate::domain::{
models::{
- Attachment, AttachmentMacro, Contact, EmailThreadPreview, PreviewCursorQuery, PreviewView,
- PreviewViewStandardLabel,
+ Attachment, AttachmentMacro, Contact, EmailThreadPreview, Link, PreviewCursorQuery,
+ PreviewView, PreviewViewStandardLabel, UserProvider,
},
ports::EmailRepo,
};
@@ -227,4 +227,37 @@ impl EmailRepo for EmailPgRepo {
.map(LabelDbRow::mirror)
.collect())
}
+
+ #[tracing::instrument(err, skip(self))]
+ async fn link_by_fusionauth_and_macro_id(
+ &self,
+ fusionauth_user_id: &str,
+ macro_id: MacroUserIdStr<'_>,
+ provider: UserProvider,
+ ) -> Result<Option<Link>, Self::Err> {
+ let provider: DbUserProvider = match provider {
+ UserProvider::Gmail => DbUserProvider::Gmail,
+ };
+
+ let db_link = sqlx::query_as!(
+ db_types::DbLink,
+ r#"
+ SELECT id, macro_id, fusionauth_user_id, email_address, provider as "provider: _",
+ is_sync_active, created_at, updated_at
+ FROM email_links
+ WHERE fusionauth_user_id = $1 AND macro_id = $2 AND provider = $3
+ LIMIT 1
+ "#,
+ fusionauth_user_id,
+ macro_id.as_ref(),
+ provider as _
+ )
+ .fetch_optional(&self.pool)
+ .await?;
+
+ db_link
+ .map(|v| v.try_into_model())
+ .transpose()
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))
+ }
}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs
index 86b38b78b2..3fce6da3bf 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs
@@ -1,10 +1,11 @@
use crate::domain::models::{
- Attachment, AttachmentMacro, EmailThreadPreview, Label, LabelListVisibility, LabelType,
+ Attachment, AttachmentMacro, EmailThreadPreview, Label, LabelListVisibility, LabelType, Link,
MessageListVisibility,
};
use chrono::{DateTime, Utc};
-use doppleganger::Doppleganger;
-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use doppleganger::{Doppleganger, Mirror};
+use macro_user_id::{cowlike::CowLike, email::EmailStr, user_id::MacroUserIdStr};
+use sqlx::Type;
use uuid::Uuid;
#[derive(Doppleganger)]
@@ -147,3 +148,48 @@ impl ThreadPreviewCursorDbRow {
}
}
}
+
+#[derive(Type, Debug, Clone, Copy, Doppleganger)]
+#[sqlx(type_name = "email_user_provider_enum", rename_all = "UPPERCASE")]
+#[dg(forward = crate::domain::models::UserProvider)]
+pub enum DbUserProvider {
+ Gmail,
+}
+
+#[derive(Debug, Clone)]
+pub(crate) struct DbLink {
+ pub id: Uuid,
+ pub macro_id: String,
+ pub fusionauth_user_id: String,
+ pub email_address: String,
+ pub provider: DbUserProvider,
+ pub is_sync_active: bool,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+}
+
+impl DbLink {
+ pub(crate) fn try_into_model(self) -> Result<Link, macro_user_id::error::ParseErr> {
+ let DbLink {
+ id,
+ macro_id,
+ fusionauth_user_id,
+ email_address,
+ provider,
+ is_sync_active,
+ created_at,
+ updated_at,
+ } = self;
+
+ Ok(Link {
+ id,
+ macro_id: MacroUserIdStr::parse_from_str(&macro_id)?.into_owned(),
+ fusionauth_user_id,
+ email_address: EmailStr::try_from(email_address)?,
+ provider: DbUserProvider::mirror(provider),
+ is_sync_active,
+ created_at,
+ updated_at,
+ })
+ }
+}
diff --git a/rust/cloud-storage/email_db_client/Cargo.toml b/rust/cloud-storage/email_db_client/Cargo.toml
index 57dcae0566..b6e1f486a9 100644
--- a/rust/cloud-storage/email_db_client/Cargo.toml
+++ b/rust/cloud-storage/email_db_client/Cargo.toml
@@ -7,8 +7,10 @@ version = "0.1.0"
[dependencies]
anyhow = { workspace = true }
chrono = { workspace = true }
-email_utils = { path = "../email_utils"}
+doppleganger = { workspace = true }
+email_utils = { path = "../email_utils" }
futures = { workspace = true }
+macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
models_email = { path = "../models_email" }
models_pagination = { path = "../models_pagination" }
@@ -20,4 +22,4 @@ tokio = { workspace = true }
tracing = { workspace = true }
[dev-dependencies]
-macro_db_migrator = { path = "../macro_db_migrator" }
\ No newline at end of file
+macro_db_migrator = { path = "../macro_db_migrator" }
diff --git a/rust/cloud-storage/email_db_client/src/histories/mod.rs b/rust/cloud-storage/email_db_client/src/histories/mod.rs
index c0a47611f2..7454b2b032 100644
--- a/rust/cloud-storage/email_db_client/src/histories/mod.rs
+++ b/rust/cloud-storage/email_db_client/src/histories/mod.rs
@@ -1,20 +1,23 @@
use anyhow::{Context, anyhow};
-use models_email::email::db::link::UserProvider;
+use doppleganger::Mirror;
use models_email::gmail::history::{GmailHistory, GmailHistoryDb};
use sqlx::PgPool;
use sqlx::types::Uuid;
+use crate::links::types::DbUserProvider;
+
#[tracing::instrument(skip(pool), level = "info")]
pub async fn fetch_history_id_for_link(
pool: &PgPool,
email_address: &str,
- provider: UserProvider,
+ provider: models_email::service::link::UserProvider,
) -> anyhow::Result<Option<String>> {
if email_address.is_empty() {
return Err(anyhow!("Email address cannot be empty"));
}
let normalized_email = email_address.to_lowercase();
+ let db_provider = DbUserProvider::mirror(provider);
let result = sqlx::query!(
r#"
@@ -24,7 +27,7 @@ pub async fn fetch_history_id_for_link(
WHERE l.email_address = $1 AND l.provider = $2
"#,
normalized_email,
- provider as _
+ db_provider as _
)
.fetch_optional(pool)
.await
@@ -32,7 +35,7 @@ pub async fn fetch_history_id_for_link(
format!(
"Failed to fetch history_id for email {} and provider {}",
email_address,
- provider.as_str()
+ db_provider.as_str()
)
})?;
diff --git a/rust/cloud-storage/email_db_client/src/links/get.rs b/rust/cloud-storage/email_db_client/src/links/get.rs
index e513746e69..f44e95424f 100644
--- a/rust/cloud-storage/email_db_client/src/links/get.rs
+++ b/rust/cloud-storage/email_db_client/src/links/get.rs
@@ -1,56 +1,17 @@
use anyhow::{Context, anyhow};
-use models_email::email::db;
+use doppleganger::Mirror;
use models_email::email::service::link;
+use models_email::service;
use sqlx::PgPool;
use sqlx::types::Uuid;
-/// fetches a link given a fusionauth_user_id macro_id and provider.
-pub async fn fetch_link_by_fusionauth_and_macro_id(
- pool: &PgPool,
- fusionauth_user_id: &str,
- macro_id: &str,
- provider: db::link::UserProvider,
-) -> anyhow::Result<Option<link::Link>> {
- if fusionauth_user_id.is_empty() {
- return Err(anyhow!("Fusion Auth user ID cannot be empty"));
- }
-
- if macro_id.is_empty() {
- return Err(anyhow!("Macro ID cannot be empty"));
- }
-
- let provider_display = provider.as_str();
-
- let db_link = sqlx::query_as!(
- db::link::Link,
- r#"
- SELECT id, macro_id, fusionauth_user_id, email_address, provider as "provider: _",
- is_sync_active, created_at, updated_at
- FROM email_links
- WHERE fusionauth_user_id = $1 AND macro_id = $2 AND provider = $3
- LIMIT 1
- "#,
- fusionauth_user_id,
- macro_id,
- provider as _
- )
- .fetch_optional(pool)
- .await
- .with_context(|| {
- format!(
- "Failed to fetch link for fusionauth_user_id {}, macro_id {} and provider {}",
- fusionauth_user_id, macro_id, provider_display
- )
- })?;
-
- Ok(db_link.map(Into::into))
-}
+use crate::links::types::{DbLink, DbUserProvider};
/// fetches a link given an email address and provider.
pub async fn fetch_link_by_email(
pool: &PgPool,
email_address: &str,
- provider: db::link::UserProvider,
+ provider: service::link::UserProvider,
) -> anyhow::Result<Option<link::Link>> {
if email_address.is_empty() {
return Err(anyhow!("Email address cannot be empty"));
@@ -59,7 +20,7 @@ pub async fn fetch_link_by_email(
let provider_display = provider.as_str();
let db_link = sqlx::query_as!(
- db::link::Link,
+ DbLink,
r#"
SELECT id, macro_id, fusionauth_user_id, email_address, provider as "provider: _",
is_sync_active, created_at, updated_at
@@ -68,7 +29,7 @@ pub async fn fetch_link_by_email(
LIMIT 1
"#,
email_address,
- provider as _
+ DbUserProvider::mirror(provider) as _
)
.fetch_optional(pool)
.await
@@ -79,7 +40,7 @@ pub async fn fetch_link_by_email(
)
})?;
- Ok(db_link.map(Into::into))
+ Ok(db_link.map(service::link::Link::try_from).transpose()?)
}
/// fetches email_links given a macro_id.
@@ -93,7 +54,7 @@ pub async fn fetch_link_by_macro_id(
}
let db_link = sqlx::query_as!(
- db::link::Link,
+ DbLink,
r#"
SELECT id, macro_id, fusionauth_user_id, email_address, provider as "provider: _",
is_sync_active, created_at, updated_at
@@ -109,7 +70,7 @@ pub async fn fetch_link_by_macro_id(
.with_context(|| format!("Failed to fetch link for macro_id {}", macro_id))?;
// Convert DB link to service link if it exists
- Ok(db_link.map(Into::into))
+ Ok(db_link.map(service::link::Link::try_from).transpose()?)
}
/// fetches email_links given a fusionauth_user_id. a fusionauth_user_id can have multiple email_links, each with a unique macro_id
@@ -123,7 +84,7 @@ pub async fn fetch_links_by_fusionauth_user_id(
}
let db_links = sqlx::query_as!(
- db::link::Link,
+ DbLink,
r#"
SELECT id, fusionauth_user_id, macro_id, email_address, provider as "provider: _",
is_sync_active, created_at, updated_at
@@ -143,9 +104,12 @@ pub async fn fetch_links_by_fusionauth_user_id(
})?;
// Convert DB email_links to service email_links
- let service_links = db_links.into_iter().map(Into::into).collect();
+ let service_links: Result<Vec<_>, _> = db_links
+ .into_iter()
+ .map(service::link::Link::try_from)
+ .collect();
- Ok(service_links)
+ Ok(service_links?)
}
/// Fetches a link by its ID.
@@ -153,7 +117,7 @@ pub async fn fetch_links_by_fusionauth_user_id(
#[tracing::instrument(skip(pool), level = "info")]
pub async fn fetch_link_by_id(pool: &PgPool, link_id: Uuid) -> anyhow::Result<Option<link::Link>> {
let db_link = sqlx::query_as!(
- db::link::Link,
+ DbLink,
r#"
SELECT id, macro_id, fusionauth_user_id, email_address, provider as "provider: _",
is_sync_active, created_at, updated_at
@@ -166,5 +130,5 @@ pub async fn fetch_link_by_id(pool: &PgPool, link_id: Uuid) -> anyhow::Result<Op
.await
.with_context(|| format!("Failed to fetch link with ID {}", link_id))?;
- Ok(db_link.map(Into::into))
+ Ok(db_link.map(link::Link::try_from).transpose()?)
}
diff --git a/rust/cloud-storage/email_db_client/src/links/insert.rs b/rust/cloud-storage/email_db_client/src/links/insert.rs
index 126c24e8a0..cd6d7add54 100644
--- a/rust/cloud-storage/email_db_client/src/links/insert.rs
+++ b/rust/cloud-storage/email_db_client/src/links/insert.rs
@@ -1,8 +1,11 @@
use anyhow::anyhow;
-use models_email::email::{db, service};
+use doppleganger::Mirror;
+use models_email::email::service;
use sqlx::PgPool;
use sqlx::types::Uuid;
+use crate::links::types::DbUserProvider;
+
struct LinkId {
id: Uuid,
}
@@ -19,11 +22,19 @@ pub async fn upsert_link(
if service_link.fusionauth_user_id.is_empty() {
return Err(anyhow!("FusionAuth User ID cannot be empty"));
}
- if service_link.email_address.is_empty() {
- return Err(anyhow!("Email address cannot be empty"));
- }
- let db_link: db::link::Link = service_link.into();
+ let service::link::Link {
+ id,
+ macro_id,
+ fusionauth_user_id,
+ email_address,
+ provider,
+ is_sync_active,
+ created_at,
+ updated_at,
+ } = service_link;
+
+ let db_provider = DbUserProvider::mirror(provider);
let result = sqlx::query_as!(
LinkId,
@@ -36,18 +47,26 @@ pub async fn upsert_link(
updated_at = NOW()
RETURNING id
"#,
- db_link.id,
- db_link.macro_id,
- db_link.fusionauth_user_id,
- db_link.email_address,
- db_link.provider as _,
- db_link.is_sync_active
+ id,
+ macro_id.as_ref(),
+ fusionauth_user_id,
+ email_address.0.as_ref(),
+ db_provider as _,
+ is_sync_active
)
.fetch_one(pool)
.await?;
- let mut service_link: service::link::Link = db_link.into();
- service_link.id = result.id;
+ let service_link = service::link::Link {
+ id: result.id,
+ macro_id,
+ fusionauth_user_id,
+ email_address,
+ provider,
+ is_sync_active,
+ created_at,
+ updated_at,
+ };
let _ = sqlx::query!(
r#"
diff --git a/rust/cloud-storage/email_db_client/src/links/mod.rs b/rust/cloud-storage/email_db_client/src/links/mod.rs
index 04505fb2b2..6ef93eeb6f 100644
--- a/rust/cloud-storage/email_db_client/src/links/mod.rs
+++ b/rust/cloud-storage/email_db_client/src/links/mod.rs
@@ -1,4 +1,5 @@
pub mod delete;
pub mod get;
pub mod insert;
+pub(crate) mod types;
pub mod update;
diff --git a/rust/cloud-storage/email_db_client/src/links/types.rs b/rust/cloud-storage/email_db_client/src/links/types.rs
new file mode 100644
index 0000000000..8f65e69093
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/src/links/types.rs
@@ -0,0 +1,83 @@
+use chrono::{DateTime, Utc};
+use doppleganger::Doppleganger;
+use macro_user_id::{email::EmailStr, error::ParseErr, user_id::MacroUserIdStr};
+use models_email::service::link::UserProvider;
+use sqlx::{Type, types::Uuid};
+
+#[derive(Type, Debug, Clone, Copy, Doppleganger)]
+#[sqlx(type_name = "email_user_provider_enum", rename_all = "UPPERCASE")]
+#[dg(backward = models_email::email::service::link::UserProvider)]
+pub enum DbUserProvider {
+ Gmail,
+}
+
+impl DbUserProvider {
+ pub fn as_str(&self) -> &'static str {
+ match self {
+ DbUserProvider::Gmail => "GMAIL",
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct DbLink {
+ pub id: Uuid,
+ pub macro_id: String,
+ pub fusionauth_user_id: String,
+ pub email_address: String,
+ pub provider: DbUserProvider,
+ pub is_sync_active: bool,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+}
+
+impl From<models_email::email::service::link::Link> for DbLink {
+ fn from(service_link: models_email::email::service::link::Link) -> Self {
+ Self {
+ id: service_link.id,
+ macro_id: service_link.macro_id.to_string(),
+ fusionauth_user_id: service_link.fusionauth_user_id,
+ email_address: service_link
+ .email_address
+ .0
+ .lowercase()
+ .as_ref()
+ .to_string(),
+ provider: match service_link.provider {
+ models_email::service::link::UserProvider::Gmail => DbUserProvider::Gmail,
+ },
+ is_sync_active: service_link.is_sync_active,
+ created_at: service_link.created_at,
+ updated_at: service_link.updated_at,
+ }
+ }
+}
+
+impl TryFrom<DbLink> for models_email::email::service::link::Link {
+ type Error = ParseErr;
+
+ fn try_from(value: DbLink) -> Result<Self, Self::Error> {
+ let DbLink {
+ id,
+ macro_id,
+ fusionauth_user_id,
+ email_address,
+ provider,
+ is_sync_active,
+ created_at,
+ updated_at,
+ } = value;
+ Ok(models_email::email::service::link::Link {
+ id,
+ macro_id: MacroUserIdStr::try_from(macro_id)?,
+ fusionauth_user_id,
+ email_address: EmailStr::try_from(email_address)?,
+ provider: match provider {
+ DbUserProvider::Gmail => UserProvider::Gmail,
+ },
+ is_sync_active,
+ created_at,
+ updated_at,
+ })
+ }
+}
diff --git a/rust/cloud-storage/email_refresh_handler/src/handler.rs b/rust/cloud-storage/email_refresh_handler/src/handler.rs
index 16b361671c..02ee9f7181 100644
--- a/rust/cloud-storage/email_refresh_handler/src/handler.rs
+++ b/rust/cloud-storage/email_refresh_handler/src/handler.rs
@@ -5,8 +5,14 @@ use lambda_runtime::{
Error, LambdaEvent,
tracing::{self},
};
-use models_email::email::db::link::UserProvider;
use models_email::email::service::pubsub::RefreshMessage;
+use sqlx::Type;
+
+#[derive(Type, Debug, Clone, Copy)]
+#[sqlx(type_name = "email_user_provider_enum", rename_all = "UPPERCASE")]
+pub enum DbUserProvider {
+ Gmail,
+}
#[tracing::instrument(skip(ctx, _event))]
pub async fn handler(
@@ -14,7 +20,7 @@ pub async fn handler(
_event: LambdaEvent<EventBridgeEvent>,
) -> Result<(), Error> {
let current_hour = chrono::Utc::now().hour() as i32;
- let provider_filter = UserProvider::Gmail;
+ let provider_filter = DbUserProvider::Gmail;
// uses the index idx_links_active_provider_hash_bucket
let notifications = sqlx::query_as!(
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.toml
index 3fea55dba9..e2fee9d326 100644
--- a/rust/cloud-storage/email_service/Cargo.toml
+++ b/rust/cloud-storage/email_service/Cargo.toml
@@ -24,9 +24,9 @@ path = "src/bin/backfill_search/backfill_search.rs"
[features]
disable_attachment_upload = []
disable_connection_gateway = []
+disable_contacts_sync = []
disable_gmail_webhook_auth = []
disable_sfs_map = []
-disable_contacts_sync = []
local_queue = []
[dependencies]
@@ -37,15 +37,17 @@ aws-sdk-s3 = { workspace = true }
aws-sdk-secretsmanager = { workspace = true }
aws-sdk-sqs = { workspace = true }
axum = { workspace = true }
+axum-extra = { workspace = true }
base64 = { workspace = true }
bytes = { workspace = true }
cloudfront_sign = { workspace = true }
connection_gateway = { path = "../connection_gateway" }
document_storage_service_client = { path = "../document_storage_service_client" }
+doppleganger = { workspace = true }
ego-tree = { workspace = true }
email = { path = "../email", features = ["axum", "inbound", "outbound"] }
email_db_client = { path = "../email_db_client" }
-email_utils = { path = "../email_utils"}
+email_utils = { path = "../email_utils" }
frecency = { path = "../frecency", features = ["postgres"] }
futures = { workspace = true }
gmail_client = { path = "../gmail_client" }
@@ -70,6 +72,7 @@ model = { path = "../model" }
model-entity = { path = "../model-entity" }
model_notifications = { path = "../model_notifications" }
models_email = { path = "../models_email" }
+models_opensearch = { path = "../models_opensearch" }
models_pagination = { path = "../models_pagination", features = ["axum"] }
models_permissions = { path = "../models_permissions" }
redis = { workspace = true, features = [
@@ -106,7 +109,6 @@ urlencoding = { workspace = true }
utoipa = { workspace = true }
utoipa-swagger-ui = { workspace = true }
uuid = { workspace = true }
-models_opensearch = { path = "../models_opensearch" }
[dev-dependencies]
macro_auth = { path = "../macro_auth", features = ["testing"] }
diff --git a/rust/cloud-storage/email_service/src/api/context.rs b/rust/cloud-storage/email_service/src/api/context.rs
index c6268adf88..2795ba0481 100644
--- a/rust/cloud-storage/email_service/src/api/context.rs
+++ b/rust/cloud-storage/email_service/src/api/context.rs
@@ -22,7 +22,7 @@ pub(crate) struct ApiContext {
pub jwt_args: JwtValidationArgs,
pub config: Arc<Config>,
pub internal_auth_key: LocalOrRemoteSecret<InternalApiSecretKey>,
- pub email_cursor_service: EmailPreviewState<
+ pub email_service: EmailPreviewState<
EmailServiceImpl<EmailPgRepo, FrecencyQueryServiceImpl<FrecencyPgStorage>>,
>,
}
diff --git a/rust/cloud-storage/email_service/src/api/email/attachments/mod.rs b/rust/cloud-storage/email_service/src/api/email/attachments/mod.rs
index 95ff0fedd0..9fb5b16147 100644
--- a/rust/cloud-storage/email_service/src/api/email/attachments/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/attachments/mod.rs
@@ -14,7 +14,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
.layer(
ServiceBuilder::new()
.layer(axum::middleware::from_fn_with_state(
- state.clone(),
+ state.email_service.clone(),
crate::api::middleware::link::attach_link_context,
))
.layer(axum::middleware::from_fn_with_state(
diff --git a/rust/cloud-storage/email_service/src/api/email/backfill/mod.rs b/rust/cloud-storage/email_service/src/api/email/backfill/mod.rs
index bdb0c46534..63ea0e2f89 100644
--- a/rust/cloud-storage/email_service/src/api/email/backfill/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/backfill/mod.rs
@@ -12,7 +12,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
.route("/gmail/:id", get(get::handler))
.route("/gmail/active", get(get::active_handler))
.layer(axum::middleware::from_fn_with_state(
- state,
+ state.email_service,
crate::api::middleware::link::attach_link_context,
))
}
diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/create.rs b/rust/cloud-storage/email_service/src/api/email/drafts/create.rs
index 4258bea83c..fdfeb75e84 100644
--- a/rust/cloud-storage/email_service/src/api/email/drafts/create.rs
+++ b/rust/cloud-storage/email_service/src/api/email/drafts/create.rs
@@ -94,7 +94,7 @@ pub async fn handler(
validation::validate_replying_to_id(&ctx.db, &mut draft, &link).await?;
- let from_email = link.email_address.as_str();
+ let from_email = link.email_address.0.as_ref();
let mut tx = ctx.db.begin().await?;
diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs b/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs
index 9991274c19..d18f895502 100644
--- a/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs
@@ -11,7 +11,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
.route("/", post(create::handler))
.route("/:id", delete(delete::handler))
.layer(axum::middleware::from_fn_with_state(
- state,
+ state.email_service,
crate::api::middleware::link::attach_link_context,
))
}
diff --git a/rust/cloud-storage/email_service/src/api/email/init.rs b/rust/cloud-storage/email_service/src/api/email/init.rs
index 86b88eda4c..3c1eeb2dbc 100644
--- a/rust/cloud-storage/email_service/src/api/email/init.rs
+++ b/rust/cloud-storage/email_service/src/api/email/init.rs
@@ -7,11 +7,13 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Json, Response},
};
-use model::{response::ErrorResponse, user::UserContext};
+use email::domain::models::UserProvider;
+use email::domain::ports::EmailRepo;
+use model::response::ErrorResponse;
+use model::user::axum_extractor::MacroUserExtractor;
use models_email::email::service::backfill::{
BackfillJobStatus, BackfillOperation, BackfillPubsubMessage,
};
-use models_email::email::service::link::UserProvider;
use strum_macros::AsRefStr;
use thiserror::Error;
use utoipa::ToSchema;
@@ -88,19 +90,24 @@ pub struct InitResponse {
#[tracing::instrument(skip(ctx, user_context, gmail_token), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
- user_context: Extension<UserContext>,
+ MacroUserExtractor {
+ macro_user_id,
+ user_context,
+ ..
+ }: MacroUserExtractor,
gmail_token: Extension<String>,
) -> Result<Response, InitError> {
tracing::info!(user_id = %user_context.user_id, "Init called");
// Fetch the existing link for the user
- let existing_link = email_db_client::links::get::fetch_link_by_fusionauth_and_macro_id(
- &ctx.db,
- &user_context.fusion_user_id,
- &user_context.user_id,
- UserProvider::Gmail,
- )
- .await
- .context("Failed to fetch existing link")?;
+ let pg_repo = email::outbound::EmailPgRepo::new(ctx.db.clone());
+ let existing_link = pg_repo
+ .link_by_fusionauth_and_macro_id(
+ &user_context.fusion_user_id,
+ macro_user_id,
+ UserProvider::Gmail,
+ )
+ .await
+ .context("Failed to fetch existing link")?;
// Handle different cases based on the existing link's state
match &existing_link {
@@ -120,7 +127,7 @@ pub async fn handler(
.await
.context("Failed to fetch jobs by macro id")?;
- if recent_jobs.len() >= 3 && !link.email_address.ends_with("@macro.com") {
+ if recent_jobs.len() >= 3 && !link.email_address.0.as_ref().ends_with("@macro.com") {
tracing::info!(user_id = %user_context.user_id, "Too many jobs error");
email_db_client::links::delete::delete_link_by_id(&ctx.db, link.id)
.await
diff --git a/rust/cloud-storage/email_service/src/api/email/labels/mod.rs b/rust/cloud-storage/email_service/src/api/email/labels/mod.rs
index 7a0f9e200d..8b1c28ddc3 100644
--- a/rust/cloud-storage/email_service/src/api/email/labels/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/labels/mod.rs
@@ -17,7 +17,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
))
.route("/", get(list::handler))
.layer(axum::middleware::from_fn_with_state(
- state,
+ state.email_service,
crate::api::middleware::link::attach_link_context,
))
}
diff --git a/rust/cloud-storage/email_service/src/api/email/links/list.rs b/rust/cloud-storage/email_service/src/api/email/links/list.rs
index fc27573378..9888b0a14e 100644
--- a/rust/cloud-storage/email_service/src/api/email/links/list.rs
+++ b/rust/cloud-storage/email_service/src/api/email/links/list.rs
@@ -83,7 +83,7 @@ pub async fn list_links_handler(
let signature = ctx
.gmail_client
- .get_email_signature(&access_token, &link.email_address)
+ .get_email_signature(&access_token, link.email_address.0.as_ref())
.await
.unwrap_or(None);
diff --git a/rust/cloud-storage/email_service/src/api/email/messages/mod.rs b/rust/cloud-storage/email_service/src/api/email/messages/mod.rs
index c0d3049a34..fc9230db31 100644
--- a/rust/cloud-storage/email_service/src/api/email/messages/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/messages/mod.rs
@@ -13,40 +13,22 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
Router::new()
.route(
"/",
- post(send::send_handler)
- .layer(axum::middleware::from_fn_with_state(
- state.clone(),
- crate::api::middleware::gmail_token::attach_gmail_token,
- ))
- .layer(axum::middleware::from_fn_with_state(
- state.clone(),
- crate::api::middleware::link::attach_link_context,
- )),
- )
- .route(
- "/labels",
- patch(labels::handler)
- .layer(axum::middleware::from_fn_with_state(
- state.clone(),
- crate::api::middleware::gmail_token::attach_gmail_token,
- ))
- .layer(axum::middleware::from_fn_with_state(
- state.clone(),
- crate::api::middleware::link::attach_link_context,
- )),
- )
- .route(
- "/:id",
- get(get::handler).layer(axum::middleware::from_fn_with_state(
+ post(send::send_handler).layer(axum::middleware::from_fn_with_state(
state.clone(),
- crate::api::middleware::link::attach_link_context,
+ crate::api::middleware::gmail_token::attach_gmail_token,
)),
)
.route(
- "/batch",
- post(get::batch_handler).layer(axum::middleware::from_fn_with_state(
- state,
- crate::api::middleware::link::attach_link_context,
+ "/labels",
+ patch(labels::handler).layer(axum::middleware::from_fn_with_state(
+ state.clone(),
+ crate::api::middleware::gmail_token::attach_gmail_token,
)),
)
+ .route("/batch", post(get::batch_handler))
+ .layer(axum::middleware::from_fn_with_state(
+ state.email_service,
+ crate::api::middleware::link::attach_link_context,
+ ))
+ .route("/:id", get(get::handler))
}
diff --git a/rust/cloud-storage/email_service/src/api/email/messages/send.rs b/rust/cloud-storage/email_service/src/api/email/messages/send.rs
index 88f4c290fc..d7267d1585 100644
--- a/rust/cloud-storage/email_service/src/api/email/messages/send.rs
+++ b/rust/cloud-storage/email_service/src/api/email/messages/send.rs
@@ -111,13 +111,13 @@ pub async fn send_handler(
let sender_contact = email_db_client::contacts::get::fetch_contact_by_email(
&ctx.db,
link.id,
- &link.email_address,
+ link.email_address.0.as_ref(),
)
.await?
.ok_or(SendMessageError::SenderContactNotFound)?;
let from_contact = ContactInfo {
- email: link.email_address.clone(),
+ email: link.email_address.0.as_ref().to_string(),
name: sender_contact.name,
photo_url: sender_contact.photo_url,
};
@@ -188,43 +188,46 @@ async fn insert_sent_message(
let link_id = message_to_send.link_id;
// if there isn't already a thread associated with this message, create one
- if thread_db_id.is_none() {
- let thread = thread::Thread {
- db_id: None,
- provider_id: Some(thread_provider_id.clone().unwrap()), // safe bc it always gets populated in gmail_client
- link_id,
- // if we're creating a thread with a sent message, it's not visible in the inbox
- inbox_visible: true,
- is_read: true,
- latest_inbound_message_ts: None,
- latest_outbound_message_ts: Some(before_send_ts),
- latest_non_spam_message_ts: Some(before_send_ts),
- created_at: now,
- updated_at: now,
- messages: Vec::new(),
- };
-
- thread_db_id = Option::from(
- email_db_client::threads::insert::insert_thread(&mut *tx, &thread, link_id)
- .await
- .context("unable to insert thread")?,
- );
- message_to_send.thread_db_id = thread_db_id;
- } else {
- // need to upsert the thread's provider_id in case it doesn't exist already (e.g. if we are
- // sending a previously existing draft that is the first message in the thread)
- email_db_client::threads::update::update_thread_provider_id(
- tx,
- thread_db_id.unwrap(),
- link_id,
- &thread_provider_id.clone().unwrap(),
- )
- .await
- .context(format!(
- "Failed to update provider id to {} for thread {}",
- thread_provider_id.clone().unwrap(),
- thread_db_id.unwrap()
- ))?;
+ match thread_db_id {
+ None => {
+ let thread = thread::Thread {
+ db_id: None,
+ provider_id: Some(thread_provider_id.clone().unwrap()), // safe bc it always gets populated in gmail_client
+ link_id,
+ // if we're creating a thread with a sent message, it's not visible in the inbox
+ inbox_visible: true,
+ is_read: true,
+ latest_inbound_message_ts: None,
+ latest_outbound_message_ts: Some(before_send_ts),
+ latest_non_spam_message_ts: Some(before_send_ts),
+ created_at: now,
+ updated_at: now,
+ messages: Vec::new(),
+ };
+
+ thread_db_id = Option::from(
+ email_db_client::threads::insert::insert_thread(&mut *tx, &thread, link_id)
+ .await
+ .context("unable to insert thread")?,
+ );
+ message_to_send.thread_db_id = thread_db_id;
+ }
+ Some(id) => {
+ // need to upsert the thread's provider_id in case it doesn't exist already (e.g. if we are
+ // sending a previously existing draft that is the first message in the thread)
+ email_db_client::threads::update::update_thread_provider_id(
+ tx,
+ id,
+ link_id,
+ &thread_provider_id.clone().unwrap(),
+ )
+ .await
+ .context(format!(
+ "Failed to update provider id to {} for thread {}",
+ thread_provider_id.clone().unwrap(),
+ id
+ ))?;
+ }
}
let from_email_id =
diff --git a/rust/cloud-storage/email_service/src/api/email/settings/mod.rs b/rust/cloud-storage/email_service/src/api/email/settings/mod.rs
index 39e38d01d2..5b84935f16 100644
--- a/rust/cloud-storage/email_service/src/api/email/settings/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/settings/mod.rs
@@ -9,7 +9,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
Router::new()
.route("/", patch(patch_settings_handler))
.layer(axum::middleware::from_fn_with_state(
- state,
+ state.email_service,
crate::api::middleware::link::attach_link_context,
))
}
diff --git a/rust/cloud-storage/email_service/src/api/email/sync/disable.rs b/rust/cloud-storage/email_service/src/api/email/sync/disable.rs
index 3faa1c0d3b..1c477635d8 100644
--- a/rust/cloud-storage/email_service/src/api/email/sync/disable.rs
+++ b/rust/cloud-storage/email_service/src/api/email/sync/disable.rs
@@ -81,7 +81,7 @@ pub async fn disable_handler(
.redis_client
.delete_gmail_access_token(&TokenCacheKey {
fusion_user_id: link.fusionauth_user_id.clone(),
- macro_id: link.macro_id.clone(),
+ macro_id: link.macro_id.to_string(),
provider: UserProvider::Gmail,
})
.await
@@ -122,7 +122,7 @@ pub async fn disable_handler(
.send_message_to_search_event_queue(SearchQueueMessage::RemoveEmailLink(
EmailLinkMessage {
link_id: link_context_cloned.id.to_string(),
- macro_user_id: link_context_cloned.macro_id.clone(),
+ macro_user_id: link_context_cloned.macro_id.to_string(),
},
))
.await
@@ -135,11 +135,11 @@ pub async fn disable_handler(
let email_info = EmailInfo::LinkDeleted(LinkDeletedPayload {
link_id: link_context_cloned.id.to_string(),
- email_address: link_context_cloned.email_address.clone(),
+ email_address: link_context_cloned.email_address.0.as_ref().to_string(),
});
let insights_message = GenerateEmailInsightContext {
- macro_user_id: link_context_cloned.macro_id.clone(),
+ macro_user_id: link_context_cloned.macro_id.to_string(),
info: email_info,
};
diff --git a/rust/cloud-storage/email_service/src/api/email/sync/enable.rs b/rust/cloud-storage/email_service/src/api/email/sync/enable.rs
index 8444f545a0..e2950430d0 100644
--- a/rust/cloud-storage/email_service/src/api/email/sync/enable.rs
+++ b/rust/cloud-storage/email_service/src/api/email/sync/enable.rs
@@ -1,15 +1,19 @@
use crate::api::context::ApiContext;
use crate::utils::extract_email_with_response;
use anyhow::Context;
+use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
-use axum::{Extension, Json};
+use email::domain::models::UserProvider;
+use email::domain::ports::EmailRepo;
+use macro_user_id::email::EmailStr;
+use macro_user_id::user_id::MacroUserIdStr;
use model::response::{EmptyResponse, ErrorResponse};
use model::user::UserContext;
+use model::user::axum_extractor::MacroUserExtractor;
use models_email::email::service::link;
use models_email::email::service::link::Link;
-use models_email::email::service::link::UserProvider;
use strum_macros::AsRefStr;
use thiserror::Error;
@@ -26,14 +30,17 @@ pub enum EnableSyncError {
#[error("Bad request")]
BadRequest(String),
+
+ #[error("Invalid input")]
+ Parse(#[from] macro_user_id::error::ParseErr),
}
impl IntoResponse for EnableSyncError {
fn into_response(self) -> Response {
let status_code = match &self {
- EnableSyncError::SyncAlreadyEnabled | EnableSyncError::BadRequest(_) => {
- StatusCode::BAD_REQUEST
- }
+ EnableSyncError::SyncAlreadyEnabled
+ | EnableSyncError::BadRequest(_)
+ | EnableSyncError::Parse(_) => StatusCode::BAD_REQUEST,
EnableSyncError::RegisterWatchError(_) | EnableSyncError::QueryError(_) => {
StatusCode::INTERNAL_SERVER_ERROR
}
@@ -67,17 +74,22 @@ impl IntoResponse for EnableSyncError {
#[tracing::instrument(skip(ctx, user_context), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id))]
pub async fn enable_handler(
State(ctx): State<ApiContext>,
- user_context: Extension<UserContext>,
+ MacroUserExtractor {
+ macro_user_id,
+ user_context,
+ ..
+ }: MacroUserExtractor,
) -> Result<Response, EnableSyncError> {
// if link exists already and syncing is already enabled, return error
- let existing_link = email_db_client::links::get::fetch_link_by_fusionauth_and_macro_id(
- &ctx.db,
- &user_context.fusion_user_id,
- &user_context.user_id,
- UserProvider::Gmail,
- )
- .await
- .context("Failed to fetch link")?;
+ let pg_repo = email::outbound::EmailPgRepo::new(ctx.db.clone());
+ let existing_link = pg_repo
+ .link_by_fusionauth_and_macro_id(
+ &user_context.fusion_user_id,
+ macro_user_id,
+ UserProvider::Gmail,
+ )
+ .await
+ .context("Failed to fetch link")?;
if let Some(link) = existing_link
&& link.is_sync_active
@@ -121,10 +133,10 @@ pub async fn enable_gmail_sync(
let mut link = link::Link {
id: macro_uuid::generate_uuid_v7(), // will get ignored for existing links
- macro_id: user_context.user_id.clone(),
+ macro_id: MacroUserIdStr::try_from(user_context.user_id.clone())?,
fusionauth_user_id: user_context.fusion_user_id.clone(),
- email_address: email,
- provider: UserProvider::Gmail,
+ email_address: EmailStr::try_from(email)?,
+ provider: models_email::service::link::UserProvider::Gmail,
is_sync_active: true,
created_at: Default::default(),
updated_at: Default::default(),
diff --git a/rust/cloud-storage/email_service/src/api/email/sync/mod.rs b/rust/cloud-storage/email_service/src/api/email/sync/mod.rs
index 0e6b66cfcb..b9ee3ee244 100644
--- a/rust/cloud-storage/email_service/src/api/email/sync/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/sync/mod.rs
@@ -18,7 +18,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
crate::api::middleware::gmail_token::attach_gmail_token,
))
.layer(axum::middleware::from_fn_with_state(
- state,
+ state.email_service,
crate::api::middleware::link::attach_link_context,
)),
),
diff --git a/rust/cloud-storage/email_service/src/api/email/threads/get.rs b/rust/cloud-storage/email_service/src/api/email/threads/get.rs
index 7c05c2aacc..d00cd14bef 100644
--- a/rust/cloud-storage/email_service/src/api/email/threads/get.rs
+++ b/rust/cloud-storage/email_service/src/api/email/threads/get.rs
@@ -132,7 +132,7 @@ pub async fn get_thread_handler(
let access_level = if thread.link_id != link.id {
// call will fail if user doesn't have an access level. otherwise, we can return the thread
ctx.dss_client
- .get_thread_access_level(&link.macro_id, &thread.db_id.unwrap().to_string())
+ .get_thread_access_level(link.macro_id.as_ref(), &thread.db_id.unwrap().to_string())
.await
.map_err(|e| {
tracing::error!(error=?e, "unable to get access level for thread for user");
diff --git a/rust/cloud-storage/email_service/src/api/email/threads/mod.rs b/rust/cloud-storage/email_service/src/api/email/threads/mod.rs
index 2bbe0b8bd8..504d63aad2 100644
--- a/rust/cloud-storage/email_service/src/api/email/threads/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/threads/mod.rs
@@ -1,6 +1,5 @@
pub(crate) mod archived;
pub(crate) mod get;
-pub(crate) mod previews;
pub(crate) mod seen;
use axum::Router;
@@ -13,46 +12,28 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
Router::new()
.nest(
"/previews",
- previews::router(state.email_cursor_service.clone(), state.clone()),
+ email::inbound::router(state.email_service.clone()),
)
+ .route("/:id", get(get::get_thread_handler))
.route(
- "/:id",
- get(get::get_thread_handler).layer(axum::middleware::from_fn_with_state(
+ "/:id/seen",
+ post(seen::seen_handler).layer(axum::middleware::from_fn_with_state(
state.clone(),
- crate::api::middleware::link::attach_link_context,
+ crate::api::middleware::gmail_token::attach_gmail_token,
)),
)
+ .route("/:id/messages", get(get::get_thread_messages_handler))
.route(
- "/:id/seen",
- post(seen::seen_handler)
- .layer(axum::middleware::from_fn_with_state(
+ "/:id/archived",
+ patch(archived::archived_handler).layer(ServiceBuilder::new().layer(
+ axum::middleware::from_fn_with_state(
state.clone(),
crate::api::middleware::gmail_token::attach_gmail_token,
- ))
- .layer(axum::middleware::from_fn_with_state(
- state.clone(),
- crate::api::middleware::link::attach_link_context,
- )),
- )
- .route(
- "/:id/messages",
- get(get::get_thread_messages_handler).layer(axum::middleware::from_fn_with_state(
- state.clone(),
- crate::api::middleware::link::attach_link_context,
+ ),
)),
)
- .route(
- "/:id/archived",
- patch(archived::archived_handler).layer(
- ServiceBuilder::new()
- .layer(axum::middleware::from_fn_with_state(
- state.clone(),
- crate::api::middleware::gmail_token::attach_gmail_token,
- ))
- .layer(axum::middleware::from_fn_with_state(
- state.clone(),
- crate::api::middleware::link::attach_link_context,
- )),
- ),
- )
+ .layer(axum::middleware::from_fn_with_state(
+ state.email_service,
+ crate::api::middleware::link::attach_link_context,
+ ))
}
diff --git a/rust/cloud-storage/email_service/src/api/email/threads/previews/mod.rs b/rust/cloud-storage/email_service/src/api/email/threads/previews/mod.rs
deleted file mode 100644
index d6b8a2e465..0000000000
--- a/rust/cloud-storage/email_service/src/api/email/threads/previews/mod.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-use axum::extract::Request;
-use axum::middleware::Next;
-use axum::response::Response;
-use axum::{Extension, Router};
-use email::domain::ports::EmailService;
-use email::inbound::EmailPreviewState;
-use tower::ServiceBuilder;
-
-use crate::api::ApiContext;
-
-pub fn router<S, T>(state: EmailPreviewState<T>, api_context: ApiContext) -> Router<S>
-where
- S: Send + Sync + Clone + 'static,
- T: EmailService,
-{
- email::inbound::router(state).layer(
- ServiceBuilder::new()
- .layer(axum::middleware::from_fn_with_state(
- api_context,
- crate::api::middleware::link::attach_link_context,
- ))
- .layer(axum::middleware::from_fn(link_to_link_uuid_extension)),
- )
-}
-
-/// the email inbound router currently depends on a [email::inbound::LinkUuid] extension
-/// the service itself should be able to extract this but thats too much of a rework for right now
-/// this middleware is used to take a [models_email::service::link::Link] extension and create a [email::inbound::LinkUuid] extension
-async fn link_to_link_uuid_extension(
- link: Extension<models_email::service::link::Link>,
- mut req: Request,
- next: Next,
-) -> Response {
- let link_uuid = link.0.id;
- req.extensions_mut()
- .insert(email::inbound::LinkUuid(link_uuid));
- next.run(req).await
-}
diff --git a/rust/cloud-storage/email_service/src/api/internal/delete_user.rs b/rust/cloud-storage/email_service/src/api/internal/delete_user.rs
index bc8b687e8d..9b63722f5e 100644
--- a/rust/cloud-storage/email_service/src/api/internal/delete_user.rs
+++ b/rust/cloud-storage/email_service/src/api/internal/delete_user.rs
@@ -76,7 +76,7 @@ pub async fn handler(
.send_message_to_search_event_queue(SearchQueueMessage::RemoveEmailLink(
EmailLinkMessage {
link_id: link.id.to_string(),
- macro_user_id,
+ macro_user_id: macro_user_id.to_string(),
},
))
.await
diff --git a/rust/cloud-storage/email_service/src/api/middleware/link.rs b/rust/cloud-storage/email_service/src/api/middleware/link.rs
index 5f5a85d92e..a64456eaa7 100644
--- a/rust/cloud-storage/email_service/src/api/middleware/link.rs
+++ b/rust/cloud-storage/email_service/src/api/middleware/link.rs
@@ -1,52 +1,14 @@
-use axum::{
- Extension, Json,
- extract::{Request, State},
- http::StatusCode,
- middleware::Next,
- response::{IntoResponse, Response},
-};
-use model::response::ErrorResponse;
-use model::user::UserContext;
-use models_email::email::service::link::UserProvider;
-use tracing::instrument;
+use axum::{extract::Request, middleware::Next, response::Response};
+use axum_extra::extract::Cached;
+use doppleganger::Mirror;
+use email::{domain::ports::EmailService, inbound::EmailLinkExtractor};
-use crate::api::context::ApiContext;
-#[instrument(skip_all, fields(macro_id = %user_context.user_id, fusion_user_id = %user_context.fusion_user_id))]
-pub(in crate::api) async fn attach_link_context(
- State(ctx): State<ApiContext>,
- user_context: Extension<UserContext>,
+pub(in crate::api) async fn attach_link_context<U: EmailService>(
+ Cached(EmailLinkExtractor(link, _)): Cached<EmailLinkExtractor<U>>,
mut req: Request,
next: Next,
) -> Result<Response, Response> {
- let link = email_db_client::links::get::fetch_link_by_fusionauth_and_macro_id(
- &ctx.db,
- &user_context.fusion_user_id,
- &user_context.user_id,
- UserProvider::Gmail,
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to fetch link");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "unable to fetch link",
- }),
- )
- .into_response()
- })?;
-
- let link = link.ok_or_else(|| {
- (
- StatusCode::NOT_FOUND,
- Json(ErrorResponse {
- message: "No email link found for user",
- }),
- )
- .into_response()
- })?;
-
- let service_link = link;
- req.extensions_mut().insert(service_link);
+ req.extensions_mut()
+ .insert(models_email::email::service::link::Link::mirror(link));
Ok(next.run(req).await)
}
diff --git a/rust/cloud-storage/email_service/src/bin/backfill_contacts/process.rs b/rust/cloud-storage/email_service/src/bin/backfill_contacts/process.rs
index 5af7ade479..12c4641951 100644
--- a/rust/cloud-storage/email_service/src/bin/backfill_contacts/process.rs
+++ b/rust/cloud-storage/email_service/src/bin/backfill_contacts/process.rs
@@ -23,7 +23,7 @@ pub async fn process_macro_id(
return Ok(());
}
- let mut users = vec![link.macro_id.clone()];
+ let mut users = vec![link.macro_id.to_string()];
users.extend(
contact_emails
.iter()
diff --git a/rust/cloud-storage/email_service/src/main.rs b/rust/cloud-storage/email_service/src/main.rs
index a68945645a..e0f318dbb6 100644
--- a/rust/cloud-storage/email_service/src/main.rs
+++ b/rust/cloud-storage/email_service/src/main.rs
@@ -330,7 +330,7 @@ async fn main() -> anyhow::Result<()> {
dss_client: Arc::new(dss_client),
jwt_args,
internal_auth_key: LocalOrRemoteSecret::Local(internal_auth_key),
- email_cursor_service: EmailPreviewState::new(EmailServiceImpl::new(
+ email_service: EmailPreviewState::new(EmailServiceImpl::new(
EmailPgRepo::new(db.clone()),
FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db)),
)),
diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs
index 20c91058c7..99fc830d13 100644
--- a/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/increment_counters.rs
@@ -123,7 +123,9 @@ async fn handle_attachment_upload(
job_id: Uuid,
) -> Result<(), ProcessingError> {
// temporarily only enabling for macro emails for testing
- if !link.macro_id.ends_with("@macro.com") || cfg!(feature = "disable_attachment_upload") {
+ if !link.macro_id.as_ref().ends_with("@macro.com")
+ || cfg!(feature = "disable_attachment_upload")
+ {
return Ok(());
}
@@ -172,7 +174,7 @@ async fn handle_contacts_sync(ctx: &PubSubContext, link: &Link) -> Result<(), Pr
link.macro_id
);
- let mut users = vec![link.macro_id.clone()];
+ let mut users = vec![link.macro_id.to_string()];
users.extend(
email_addresses
.iter()
@@ -235,7 +237,9 @@ async fn handle_thread_completed(
})?;
// temporarily only for macro emails, for testing
- if link.macro_id.ends_with("@macro.com") && !cfg!(feature = "disable_attachment_upload") {
+ if link.macro_id.as_ref().ends_with("@macro.com")
+ && !cfg!(feature = "disable_attachment_upload")
+ {
let attachments =
email_db_client::attachments::provider::upload::fetch_thread_attachments_for_backfill(
&ctx.db,
diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/update_metadata.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/update_metadata.rs
index ce6cec0aff..178c3d736e 100644
--- a/rust/cloud-storage/email_service/src/pubsub/backfill/update_metadata.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/update_metadata.rs
@@ -85,7 +85,7 @@ pub async fn update_thread_metadata(
// notify search-service about the new thread
let search_message = SearchQueueMessage::ExtractEmailThreadMessage(EmailThreadMessage {
thread_id: p.thread_db_id.clone().to_string(),
- macro_user_id: link.macro_id.clone(),
+ macro_user_id: link.macro_id.to_string(),
});
ctx.sqs_client
diff --git a/rust/cloud-storage/email_service/src/pubsub/util.rs b/rust/cloud-storage/email_service/src/pubsub/util.rs
index 5a76989afd..7f34ee7986 100644
--- a/rust/cloud-storage/email_service/src/pubsub/util.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/util.rs
@@ -86,7 +86,7 @@ pub async fn fetch_access_token_for_link(
) -> anyhow::Result<String> {
let cache_key = TokenCacheKey {
fusion_user_id: link.fusionauth_user_id.clone(),
- macro_id: link.macro_id.clone(),
+ macro_id: link.macro_id.to_string(),
provider: link.provider,
};
diff --git a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/delete_message.rs b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/delete_message.rs
index 4ebd04226a..55a0e92986 100644
--- a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/delete_message.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/delete_message.rs
@@ -84,7 +84,7 @@ pub async fn delete_message(
// tell FE to refresh user's inbox
cg_refresh_email(
&ctx.connection_gateway_client,
- &link.macro_id,
+ link.macro_id.as_ref(),
"delete_message",
)
.await;
@@ -95,7 +95,7 @@ pub async fn delete_message(
.bulk_send_message_to_search_event_queue(vec![SearchQueueMessage::RemoveEmailMessage(
EmailMessage {
message_id: message.db_id.to_string(),
- macro_user_id: link.macro_id.clone(),
+ macro_user_id: link.macro_id.to_string(),
},
)])
.await
diff --git a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/gmail_message.rs b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/gmail_message.rs
index 9ba41c680a..0719bba98f 100644
--- a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/gmail_message.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/gmail_message.rs
@@ -2,14 +2,13 @@ use crate::pubsub::context::PubSubContext;
use crate::pubsub::util::check_gmail_rate_limit;
use crate::pubsub::webhook::process::fetch_pubsub_gmail_token;
use crate::util::process_pre_insert::sync_labels::sync_labels;
-use models_email::db::link::UserProvider;
use models_email::gmail::history::InboxChanges;
use models_email::gmail::operations::GmailApiOperation;
use models_email::gmail::webhook::{
DeleteMessagePayload, GmailMessagePayload, UpdateLabelsPayload, UpsertMessagePayload,
WebhookOperation, WebhookPubsubMessage,
};
-use models_email::service::link::Link;
+use models_email::service::link::{Link, UserProvider};
use models_email::service::pubsub::{DetailedError, FailureReason, ProcessingError};
use std::result;
use uuid::Uuid;
@@ -28,7 +27,7 @@ pub async fn gmail_message(
// if it's GTE this message's history id, do nothing - db is already updated or being updated
let db_history_id = email_db_client::histories::fetch_history_id_for_link(
&ctx.db,
- &link.email_address,
+ link.email_address.0.as_ref(),
UserProvider::Gmail,
)
.await
diff --git a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/update_labels.rs b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/update_labels.rs
index 5ee3730d36..ea4ac00598 100644
--- a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/update_labels.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/update_labels.rs
@@ -125,7 +125,7 @@ pub async fn update_labels(
// tell FE to refresh user's inbox
cg_refresh_email(
&ctx.connection_gateway_client,
- &link.macro_id,
+ link.macro_id.as_ref(),
"update_labels",
)
.await;
diff --git a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs
index e9bfda820b..96c2ddfce2 100644
--- a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs
@@ -141,7 +141,7 @@ pub async fn upsert_message(
// trigger FE inbox refresh
cg_refresh_email(
&ctx.connection_gateway_client,
- &link.macro_id,
+ link.macro_id.as_ref(),
"upsert_message",
)
.await;
@@ -179,7 +179,7 @@ async fn handle_attachment_upload(
message_attachment_count: usize,
) -> result::Result<(), ProcessingError> {
// temporarily only for macro emails, for testing purposes
- if !link.macro_id.ends_with("@macro.com")
+ if !link.macro_id.0.as_ref().ends_with("@macro.com")
|| cfg!(feature = "disable_attachment_upload")
|| message_attachment_count == 0
{
@@ -249,7 +249,7 @@ async fn handle_contacts_sync(
);
// Create users list starting with the sender, then all recipients
- let mut users = vec![link.macro_id.clone()];
+ let mut users = vec![link.macro_id.to_string()];
users.extend(
recipient_emails
.iter()
@@ -295,12 +295,12 @@ async fn generate_email_insights_for_new_messages(
// Use the correct macro_user_id for each message
let macro_user_id = link.macro_id.clone();
user_messages
- .entry(macro_user_id)
+ .entry(macro_user_id.to_string())
.or_default()
.push(NewMessagePayload {
thread_id,
message_id,
- user_email: link.email_address.clone(),
+ user_email: link.email_address.0.as_ref().to_string(),
});
}
@@ -509,7 +509,7 @@ async fn notify_for_new_messages(
.map(|(message_id, _thread_id)| {
SearchQueueMessage::ExtractEmailMessage(EmailMessage {
message_id: message_id.to_string(),
- macro_user_id: link.macro_id.clone(),
+ macro_user_id: link.macro_id.to_string(),
})
})
.collect(),
@@ -576,7 +576,7 @@ async fn send_notifications(
let notification_metadata = NewEmailMetadata {
sender,
- to_email: link.email_address.to_string(),
+ to_email: link.email_address.0.as_ref().to_string(),
thread_id: message.thread_db_id.to_string(),
subject: message.subject.unwrap_or_default(),
snippet: message.snippet.unwrap_or_default(),
@@ -585,8 +585,8 @@ async fn send_notifications(
let notification_queue_message = NotificationQueueMessage {
notification_entity: NotificationEntity::new_email(message.db_id.to_string()),
notification_event: NotificationEvent::NewEmail(notification_metadata),
- sender_id: Some(link.macro_id.clone()),
- recipient_ids: Some(vec![link.macro_id.clone()]),
+ sender_id: Some(link.macro_id.to_string()),
+ recipient_ids: Some(vec![link.macro_id.to_string()]),
is_important_v0: Some(false),
};
diff --git a/rust/cloud-storage/email_service/src/pubsub/webhook/process.rs b/rust/cloud-storage/email_service/src/pubsub/webhook/process.rs
index af4cd86b00..1d7bd5cfd5 100644
--- a/rust/cloud-storage/email_service/src/pubsub/webhook/process.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/webhook/process.rs
@@ -130,7 +130,7 @@ pub async fn fetch_pubsub_gmail_token(
) -> result::Result<String, ProcessingError> {
let cache_key = cache::TokenCacheKey::new(
&link.fusionauth_user_id,
- &link.macro_id,
+ link.macro_id.0.as_ref(),
UserProvider::Gmail,
);
diff --git a/rust/cloud-storage/email_service/src/util/backfill/backfill_insights.rs b/rust/cloud-storage/email_service/src/util/backfill/backfill_insights.rs
index 4ebc63d763..39cd3db896 100644
--- a/rust/cloud-storage/email_service/src/util/backfill/backfill_insights.rs
+++ b/rust/cloud-storage/email_service/src/util/backfill/backfill_insights.rs
@@ -59,9 +59,12 @@ pub async fn backfill_email_insights(
tracing::debug!(
"user {} has email account {} linked",
user_id,
- link.email_address
+ link.email_address.0.as_ref()
+ );
+ user_emails_map.insert(
+ user_id.clone(),
+ vec![link.email_address.0.as_ref().to_string()],
);
- user_emails_map.insert(user_id.clone(), vec![link.email_address]);
}
let mut user_offsets: std::collections::HashMap<String, i64> =
diff --git a/rust/cloud-storage/email_service/src/util/gmail/auth.rs b/rust/cloud-storage/email_service/src/util/gmail/auth.rs
index 9efe31515b..c7b0799bd6 100644
--- a/rust/cloud-storage/email_service/src/util/gmail/auth.rs
+++ b/rust/cloud-storage/email_service/src/util/gmail/auth.rs
@@ -46,7 +46,11 @@ pub async fn fetch_gmail_access_token_from_link(
auth_service_client: &AuthServiceClient,
) -> anyhow::Result<String> {
// Create the cache key using the extracted email
- let key = TokenCacheKey::new(&link.fusionauth_user_id, &link.macro_id, link.provider);
+ let key = TokenCacheKey::new(
+ &link.fusionauth_user_id,
+ link.macro_id.0.as_ref(),
+ link.provider,
+ );
fetch_gmail_access_token(&key, redis_client, auth_service_client).await
}
diff --git a/rust/cloud-storage/email_service/src/util/upload_attachment.rs b/rust/cloud-storage/email_service/src/util/upload_attachment.rs
index a62f1da88a..9c4a32003b 100644
--- a/rust/cloud-storage/email_service/src/util/upload_attachment.rs
+++ b/rust/cloud-storage/email_service/src/util/upload_attachment.rs
@@ -132,7 +132,7 @@ async fn create_dss_document_record(
};
dss_client
- .create_document_internal(request, &link.macro_id)
+ .create_document_internal(request, link.macro_id.0.as_ref())
.await
.context("Failed to create document record in DSS")
}
diff --git a/rust/cloud-storage/frecency/src/domain/models.rs b/rust/cloud-storage/frecency/src/domain/models.rs
index 9bd64f2e85..d118dbfed0 100644
--- a/rust/cloud-storage/frecency/src/domain/models.rs
+++ b/rust/cloud-storage/frecency/src/domain/models.rs
@@ -1,10 +1,7 @@
//! This crate provides the utilities to compute aggregate frecency scores from some input event
use chrono::{DateTime, Utc};
use item_filters::ast::EntityFilterAst;
-use macro_user_id::{
- cowlike::CowLike,
- user_id::{MacroUserIdStr, ParseErr},
-};
+use macro_user_id::{cowlike::CowLike, error::ParseErr, user_id::MacroUserIdStr};
use model_entity::{
Entity, TrackAction, TrackingData,
as_owned::{IntoOwned, ShallowClone},
diff --git a/rust/cloud-storage/frecency/src/outbound/postgres.rs b/rust/cloud-storage/frecency/src/outbound/postgres.rs
index bc9ed251f0..56e6a2e0f8 100644
--- a/rust/cloud-storage/frecency/src/outbound/postgres.rs
+++ b/rust/cloud-storage/frecency/src/outbound/postgres.rs
@@ -8,10 +8,7 @@ use crate::domain::{
};
use chrono::{DateTime, Utc};
use item_filters::ast::EntityFilterAst;
-use macro_user_id::{
- cowlike::CowLike,
- user_id::{MacroUserIdStr, ParseErr},
-};
+use macro_user_id::{cowlike::CowLike, error::ParseErr, user_id::MacroUserIdStr};
use model_entity::{Entity, EntityType, TrackAction, TrackingData};
use sqlx::{PgPool, Postgres, QueryBuilder, Row, Transaction, prelude::FromRow};
use std::{borrow::Cow, collections::VecDeque, str::FromStr};
diff --git a/rust/cloud-storage/item_filters/src/ast.rs b/rust/cloud-storage/item_filters/src/ast.rs
index 1d2685cd5d..88dbc04c7b 100644
--- a/rust/cloud-storage/item_filters/src/ast.rs
+++ b/rust/cloud-storage/item_filters/src/ast.rs
@@ -52,7 +52,7 @@ pub enum ExpandErr {
Uuid(#[from] uuid::Error),
/// invalid macro user id
#[error(transparent)]
- MacroIdErr(#[from] macro_user_id::user_id::ParseErr),
+ MacroIdErr(#[from] macro_user_id::error::ParseErr),
}
/// Describes a bundle of filters that should be applied across different entity types
diff --git a/rust/cloud-storage/macro_user_id/src/email.rs b/rust/cloud-storage/macro_user_id/src/email.rs
index bed8a7f702..2da73bb0ce 100644
--- a/rust/cloud-storage/macro_user_id/src/email.rs
+++ b/rust/cloud-storage/macro_user_id/src/email.rs
@@ -2,6 +2,7 @@
use crate::{
byte_range::ByteRange,
cowlike::{ArcCowStr, CowLike},
+ error::ParseErr,
lowercased::Lowercase,
};
use nom::{
@@ -12,6 +13,7 @@ use nom::{
multi::separated_list1,
sequence::delimited,
};
+use serde::{Deserialize, Serialize};
#[cfg(test)]
mod tests;
@@ -103,6 +105,42 @@ pub struct Email<T> {
email: T,
}
+/// The standard wrapper type for a [Email]
+/// This is a value which is guaranteed to be unmodified from its original input
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(try_from = "String", into = "String")]
+pub struct EmailStr<'a>(pub Email<ArcCowStr<'a>>);
+
+impl<'a> doppleganger::Primitive for EmailStr<'a> {}
+
+impl TryFrom<String> for EmailStr<'static> {
+ type Error = ParseErr;
+
+ fn try_from(value: String) -> Result<Self, Self::Error> {
+ Ok(<Email<ArcCowStr<'_>>>::parse_from_str(&value)
+ .map(CowLike::into_owned)
+ .map(EmailStr)?)
+ }
+}
+
+impl<'a> From<EmailStr<'a>> for String {
+ fn from(value: EmailStr<'a>) -> Self {
+ value.0.as_ref().to_string()
+ }
+}
+
+impl<'a> CowLike<'a> for EmailStr<'a> {
+ type Owned<'b> = EmailStr<'b>;
+
+ fn into_owned(self) -> Self::Owned<'static> {
+ EmailStr(self.0.into_owned())
+ }
+
+ fn copied(&'a self) -> Self {
+ EmailStr(self.0.copied())
+ }
+}
+
impl<T> Email<T> {
pub(crate) fn map<F, U>(self, f: F) -> Email<U>
where
diff --git a/rust/cloud-storage/macro_user_id/src/error.rs b/rust/cloud-storage/macro_user_id/src/error.rs
new file mode 100644
index 0000000000..23ac86cca0
--- /dev/null
+++ b/rust/cloud-storage/macro_user_id/src/error.rs
@@ -0,0 +1,7 @@
+//! This module exposes a commonly used error type across this crate
+use thiserror::Error;
+
+/// describes the error that occurred while parsing a [MacroUserId]
+#[derive(Debug, Error)]
+#[error(transparent)]
+pub struct ParseErr(#[from] nom::error::Error<String>);
diff --git a/rust/cloud-storage/macro_user_id/src/lib.rs b/rust/cloud-storage/macro_user_id/src/lib.rs
index e3301e4503..9f4ee7d240 100644
--- a/rust/cloud-storage/macro_user_id/src/lib.rs
+++ b/rust/cloud-storage/macro_user_id/src/lib.rs
@@ -5,5 +5,6 @@
pub(crate) mod byte_range;
pub mod cowlike;
pub mod email;
+pub mod error;
pub mod lowercased;
pub mod user_id;
diff --git a/rust/cloud-storage/macro_user_id/src/user_id.rs b/rust/cloud-storage/macro_user_id/src/user_id.rs
index 98c0446501..6d320cc854 100644
--- a/rust/cloud-storage/macro_user_id/src/user_id.rs
+++ b/rust/cloud-storage/macro_user_id/src/user_id.rs
@@ -1,14 +1,13 @@
//! Module defines the [MacroUserId] and the methods to read the email
-use std::ops::Deref;
-
use crate::{
cowlike::{ArcCowStr, CowLike},
email::{Email, email},
+ error::ParseErr,
lowercased::Lowercase,
};
use nom::{Finish, IResult, Parser, bytes::complete::tag, character::char};
use serde::{Deserialize, Serialize};
-use thiserror::Error;
+use std::ops::Deref;
#[cfg(test)]
mod tests;
@@ -171,11 +170,6 @@ where
}
}
-/// describes the error that occurred while parsing a [MacroUserId]
-#[derive(Debug, Error)]
-#[error(transparent)]
-pub struct ParseErr(#[from] nom::error::Error<String>);
-
impl<'a> MacroUserId<ArcCowStr<'a>> {
/// attempt to create a borrowed version of self from an input string
pub fn parse_from_str(input: &'a str) -> Result<Self, ParseErr> {
diff --git a/rust/cloud-storage/model_user/src/axum_extractor.rs b/rust/cloud-storage/model_user/src/axum_extractor.rs
index fe22f72920..ead0c946c8 100644
--- a/rust/cloud-storage/model_user/src/axum_extractor.rs
+++ b/rust/cloud-storage/model_user/src/axum_extractor.rs
@@ -4,10 +4,7 @@ use axum::{
http::{StatusCode, request::Parts},
response::IntoResponse,
};
-use macro_user_id::{
- cowlike::CowLike,
- user_id::{MacroUserIdStr, ParseErr},
-};
+use macro_user_id::{cowlike::CowLike, error::ParseErr, user_id::MacroUserIdStr};
use thiserror::Error;
use crate::UserContext;
@@ -30,6 +27,7 @@ impl IntoResponse for UserExtractorErr {
}
#[non_exhaustive]
+#[derive(Clone)]
pub struct MacroUserExtractor {
pub macro_user_id: MacroUserIdStr<'static>,
pub user_context: UserContext,
diff --git a/rust/cloud-storage/models_email/Cargo.toml b/rust/cloud-storage/models_email/Cargo.toml
index 8bd7b44acd..b743bb9cd8 100644
--- a/rust/cloud-storage/models_email/Cargo.toml
+++ b/rust/cloud-storage/models_email/Cargo.toml
@@ -8,9 +8,12 @@ version = "0.1.0"
anyhow = { workspace = true }
base64 = { workspace = true }
chrono = { workspace = true }
+doppleganger = { workspace = true, features = ["chrono", "uuid"] }
ego-tree = { workspace = true }
+email = { path = "../email" }
html2text = "0.15.1"
lazy_static = { workspace = true }
+macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
models_pagination = { path = "../models_pagination" }
regex = { workspace = true }
diff --git a/rust/cloud-storage/models_email/src/email/api/link.rs b/rust/cloud-storage/models_email/src/email/api/link.rs
index e4cec4f5b4..9993bdd0b9 100644
--- a/rust/cloud-storage/models_email/src/email/api/link.rs
+++ b/rust/cloud-storage/models_email/src/email/api/link.rs
@@ -1,6 +1,7 @@
use crate::api::settings::Settings;
use crate::service;
use chrono::{DateTime, Utc};
+use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid;
@@ -25,10 +26,10 @@ impl std::fmt::Display for UserProvider {
}
}
-impl From<crate::email::db::link::UserProvider> for UserProvider {
- fn from(provider: crate::email::db::link::UserProvider) -> Self {
+impl From<crate::email::service::link::UserProvider> for UserProvider {
+ fn from(provider: crate::email::service::link::UserProvider) -> Self {
match provider {
- crate::email::db::link::UserProvider::Gmail => UserProvider::Gmail,
+ crate::email::service::link::UserProvider::Gmail => UserProvider::Gmail,
}
}
}
@@ -36,9 +37,11 @@ impl From<crate::email::db::link::UserProvider> for UserProvider {
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct Link {
pub id: Uuid,
- pub macro_id: String,
+ #[schema(value_type = String)]
+ pub macro_id: MacroUserIdStr<'static>,
pub fusionauth_user_id: String,
- pub email_address: String,
+ #[schema(value_type = String)]
+ pub email_address: EmailStr<'static>,
pub provider: UserProvider,
pub is_sync_active: bool,
pub signature: Option<String>,
diff --git a/rust/cloud-storage/models_email/src/email/db/link.rs b/rust/cloud-storage/models_email/src/email/db/link.rs
index 4ee67ef17f..8b13789179 100644
--- a/rust/cloud-storage/models_email/src/email/db/link.rs
+++ b/rust/cloud-storage/models_email/src/email/db/link.rs
@@ -1,46 +1 @@
-use chrono::{DateTime, Utc};
-use serde::{Deserialize, Serialize};
-use sqlx::Type;
-use utoipa::ToSchema;
-use uuid::Uuid;
-#[derive(Serialize, Deserialize, Type, Debug, Clone, Copy, PartialEq, Eq, ToSchema)]
-#[sqlx(type_name = "email_user_provider_enum", rename_all = "UPPERCASE")]
-pub enum UserProvider {
- Gmail,
-}
-
-impl UserProvider {
- pub fn as_str(&self) -> &'static str {
- match self {
- UserProvider::Gmail => "GMAIL",
- }
- }
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct Link {
- pub id: Uuid,
- pub macro_id: String,
- pub fusionauth_user_id: String,
- pub email_address: String,
- pub provider: UserProvider,
- pub is_sync_active: bool,
- pub created_at: DateTime<Utc>,
- pub updated_at: DateTime<Utc>,
-}
-
-impl From<crate::email::service::link::Link> for Link {
- fn from(service_link: crate::email::service::link::Link) -> Self {
- Self {
- id: service_link.id,
- macro_id: service_link.macro_id,
- fusionauth_user_id: service_link.fusionauth_user_id,
- email_address: service_link.email_address.to_lowercase(),
- provider: service_link.provider,
- is_sync_active: service_link.is_sync_active,
- created_at: service_link.created_at,
- updated_at: service_link.updated_at,
- }
- }
-}
diff --git a/rust/cloud-storage/models_email/src/email/service/cache.rs b/rust/cloud-storage/models_email/src/email/service/cache.rs
index ceea77d1a4..5b20420c84 100644
--- a/rust/cloud-storage/models_email/src/email/service/cache.rs
+++ b/rust/cloud-storage/models_email/src/email/service/cache.rs
@@ -1,4 +1,4 @@
-use crate::email::db::link::UserProvider;
+use crate::email::service::link::UserProvider;
/// A key for caching OAuth tokens in Redis
#[derive(Debug, Clone, PartialEq, Eq)]
diff --git a/rust/cloud-storage/models_email/src/email/service/link.rs b/rust/cloud-storage/models_email/src/email/service/link.rs
index 664065cb74..470db342d3 100644
--- a/rust/cloud-storage/models_email/src/email/service/link.rs
+++ b/rust/cloud-storage/models_email/src/email/service/link.rs
@@ -1,32 +1,35 @@
-pub use crate::email::db::link::UserProvider;
use chrono::{DateTime, Utc};
+use doppleganger::Doppleganger;
+use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid;
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, Doppleganger)]
+#[dg(backward = email::domain::models::Link)]
pub struct Link {
pub id: Uuid,
- pub macro_id: String,
+ #[schema(value_type = String)]
+ pub macro_id: MacroUserIdStr<'static>,
pub fusionauth_user_id: String,
- pub email_address: String,
+ #[schema(value_type = String)]
+ pub email_address: EmailStr<'static>,
pub provider: UserProvider,
pub is_sync_active: bool,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
-impl From<crate::email::db::link::Link> for Link {
- fn from(db_link: crate::email::db::link::Link) -> Self {
- Self {
- id: db_link.id,
- macro_id: db_link.macro_id,
- fusionauth_user_id: db_link.fusionauth_user_id,
- email_address: db_link.email_address,
- provider: db_link.provider,
- is_sync_active: db_link.is_sync_active,
- created_at: db_link.created_at,
- updated_at: db_link.updated_at,
+#[derive(Debug, Clone, Copy, ToSchema, Doppleganger, Serialize, Deserialize, PartialEq, Eq)]
+#[dg(backward = email::domain::models::UserProvider)]
+pub enum UserProvider {
+ Gmail,
+}
+
+impl UserProvider {
+ pub fn as_str(&self) -> &'static str {
+ match self {
+ UserProvider::Gmail => "GMAIL",
}
}
}
diff --git a/rust/cloud-storage/models_pagination/src/cursor.rs b/rust/cloud-storage/models_pagination/src/cursor.rs
index 4e5c077cea..a707d654e3 100644
--- a/rust/cloud-storage/models_pagination/src/cursor.rs
+++ b/rust/cloud-storage/models_pagination/src/cursor.rs
@@ -68,6 +68,11 @@ pub trait Sortable: std::fmt::Debug {
type Value: std::fmt::Debug + std::cmp::Ord;
}
+enum Direction {
+ Asc,
+ Desc,
+}
+
/// Intermediary struct which holds information about the page we are going to create.
/// The only use for this struct is to call [Paginator::into_page]
pub struct Paginator<Iter, Cb, S, F> {
@@ -76,7 +81,7 @@ pub struct Paginator<Iter, Cb, S, F> {
cb: Cb,
sort_on: PhantomData<S>,
filter_on: F,
- ensure_sort: bool,
+ ensure_sort: Option<Direction>,
}
impl<Iter, Cb, S> Paginator<Iter, Cb, S, ()> {
@@ -154,7 +159,7 @@ where
cb,
sort_on: PhantomData,
filter_on: (),
- ensure_sort: false,
+ ensure_sort: None,
}
}
}
@@ -200,8 +205,20 @@ where
/// 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;
+ ///
+ /// This will sort the entries in ascending order
+ pub fn sort_asc(mut self) -> Self {
+ self.ensure_sort = Some(Direction::Asc);
+ self
+ }
+ /// 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.
+ ///
+ /// This will sort the entries in descending order
+ pub fn sort_desc(mut self) -> Self {
+ self.ensure_sort = Some(Direction::Desc);
self
}
/// Turn self into a [PaginatedTypedCursor].
@@ -218,10 +235,13 @@ where
let mut res: Vec<_> = iter.take(limit).collect();
- if ensure_sort {
+ if let Some(sort) = ensure_sort {
res.sort_by_key(|r| {
let cursor = cb(r);
- cursor.last_val
+ match sort {
+ Direction::Asc => Either::Left(cursor.last_val),
+ Direction::Desc => Either::Right(std::cmp::Reverse(cursor.last_val)),
+ }
});
}
diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.toml
index 37aabd4867..28aaf48cbb 100644
--- a/rust/cloud-storage/soup/Cargo.toml
+++ b/rust/cloud-storage/soup/Cargo.toml
@@ -7,9 +7,11 @@ version = "0.1.0"
[features]
axum = [
"dep:axum",
+ "dep:axum-extra",
"dep:model-error-response",
"dep:model_user",
"dep:utoipa",
+ "email/axum",
"models_pagination/axum",
"models_soup/schema",
]
@@ -21,6 +23,7 @@ ports = ["dep:tokio", "frecency/ports"]
[dependencies]
anyhow = { workspace = true }
axum = { workspace = true, optional = true }
+axum-extra = { workspace = true, optional = true }
chrono = { workspace = true }
doppleganger = { workspace = true, features = ["chrono", "uuid"] }
either = { workspace = true }
diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rs
index f2537ee2e7..1a7a910f15 100644
--- a/rust/cloud-storage/soup/src/domain/service.rs
+++ b/rust/cloud-storage/soup/src/domain/service.rs
@@ -299,7 +299,7 @@ where
.chain(email_soup)
.paginate_on(limit.into(), sort_method)
.filter_on(paginate_filter)
- .ensure_sorted()
+ .sort_desc()
.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 60d366ef16..56188b7125 100644
--- a/rust/cloud-storage/soup/src/domain/service/tests.rs
+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs
@@ -1,7 +1,7 @@
use crate::domain::ports::MockSoupRepo;
use chrono::Days;
use cool_asserts::assert_matches;
-use email::domain::models::{EnrichedEmailThreadPreview, PreviewView};
+use email::domain::models::{EmailErr, EnrichedEmailThreadPreview, PreviewView};
use frecency::domain::models::FrecencyPageResponse;
use frecency::domain::ports::MockFrecencyQueryService;
use frecency::domain::services::FrecencyQueryServiceImpl;
@@ -32,6 +32,14 @@ impl EmailService for NoopEmailService {
.paginate_on(0, SimpleSortMethod::CreatedAt)
.into_page())
}
+
+ async fn get_link_by_auth_id_and_macro_id(
+ &self,
+ _auth_id: &str,
+ _macro_id: MacroUserIdStr<'_>,
+ ) -> Result<Option<email::domain::models::Link>, email::domain::models::EmailErr> {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("not implemented")))
+ }
}
fn soup_document(id: &str) -> SoupDocument {
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router.rs b/rust/cloud-storage/soup/src/inbound/axum_router.rs
index cbb029347b..36b1ee04fb 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router.rs
@@ -4,12 +4,19 @@ use crate::domain::{
};
use axum::{
Json, Router,
- extract::{Query, State},
+ extract::{FromRef, Query, State},
http::StatusCode,
response::IntoResponse,
routing::{get, post},
};
-use email::domain::models::PreviewView;
+use axum_extra::extract::Cached;
+use email::{
+ domain::{
+ models::{Link, PreviewView},
+ ports::EmailService,
+ },
+ inbound::{EmailLinkExtractor, EmailPreviewState},
+};
use item_filters::{
EntityFilters,
ast::{EntityFilterAst, ExpandErr},
@@ -73,31 +80,42 @@ pub struct SoupPage {
next_cursor: Option<String>,
}
-pub struct SoupRouterState<T> {
+pub struct SoupRouterState<T, U> {
service: Arc<T>,
+ email: EmailPreviewState<U>,
}
-impl<T> Clone for SoupRouterState<T> {
+impl<T, U> Clone for SoupRouterState<T, U> {
fn clone(&self) -> Self {
Self {
service: self.service.clone(),
+ email: self.email.clone(),
}
}
}
-impl<T> SoupRouterState<T>
+impl<T, U> FromRef<SoupRouterState<T, U>> for EmailPreviewState<U> {
+ fn from_ref(input: &SoupRouterState<T, U>) -> Self {
+ input.email.clone()
+ }
+}
+
+impl<T, U> SoupRouterState<T, U>
where
T: SoupService,
+ U: EmailService,
{
- pub fn new(service: T) -> Self {
+ pub fn new(service: T, email: U) -> Self {
SoupRouterState {
service: Arc::new(service),
+ email: EmailPreviewState::new(email),
}
}
async fn handle(
&self,
macro_user_id: MacroUserIdStr<'static>,
+ email_link: Link,
PostSoupRequest { filters, params }: PostSoupRequest,
cursor: SoupCursor,
) -> Result<Json<PaginatedOpaqueCursor<SoupApiItem>>, SoupHandlerErr> {
@@ -144,7 +162,7 @@ where
email_preview_view: PreviewView::StandardLabel(
email::domain::models::PreviewViewStandardLabel::Inbox,
),
- link_id: Uuid::nil(),
+ link_id: email_link.id,
})
.await?;
@@ -154,9 +172,10 @@ where
}
}
-pub fn soup_router<T, S>(state: SoupRouterState<T>) -> Router<S>
+pub fn soup_router<T, U, S>(state: SoupRouterState<T, U>) -> Router<S>
where
T: SoupService,
+ U: EmailService,
S: Send + Sync,
{
Router::new()
@@ -221,18 +240,21 @@ impl IntoResponse for SoupHandlerErr {
(status = 500, body=ErrorResponse),
)
)]
-pub async fn get_soup_handler<T>(
- State(service): State<SoupRouterState<T>>,
- MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
+pub async fn get_soup_handler<T, U>(
+ State(service): State<SoupRouterState<T, U>>,
+ Cached(MacroUserExtractor { macro_user_id, .. }): Cached<MacroUserExtractor>,
+ Cached(EmailLinkExtractor(link, _)): Cached<EmailLinkExtractor<U>>,
Query(params): Query<Params>,
cursor: SoupCursor,
) -> Result<Json<PaginatedOpaqueCursor<SoupApiItem>>, SoupHandlerErr>
where
T: SoupService,
+ U: EmailService,
{
service
.handle(
macro_user_id,
+ link,
PostSoupRequest {
params,
filters: Default::default(),
@@ -268,16 +290,18 @@ type SoupCursor = EitherWrapper<
(status = 500, body=ErrorResponse),
)
)]
-pub async fn post_soup_handler<T>(
- State(service): State<SoupRouterState<T>>,
- MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
+pub async fn post_soup_handler<T, U>(
+ State(service): State<SoupRouterState<T, U>>,
+ Cached(MacroUserExtractor { macro_user_id, .. }): Cached<MacroUserExtractor>,
+ Cached(EmailLinkExtractor(link, _)): Cached<EmailLinkExtractor<U>>,
cursor: SoupCursor,
Json(post_soup_request): Json<PostSoupRequest>,
) -> Result<Json<PaginatedOpaqueCursor<SoupApiItem>>, SoupHandlerErr>
where
T: SoupService,
+ U: EmailService,
{
service
- .handle(macro_user_id, post_soup_request, cursor)
+ .handle(macro_user_id, link, post_soup_request, cursor)
.await
}
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
index 466d7e3a82..4c33cb2f83 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
@@ -2,10 +2,16 @@ use axum::{
Extension, Router,
http::{Request, StatusCode},
};
+use email::domain::{
+ models::{EmailErr, UserProvider},
+ ports::EmailService,
+};
use http_body_util::BodyExt;
+use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};
use model_user::UserContext;
use serde_json::json;
use tower::util::ServiceExt;
+use uuid::Uuid;
use crate::{
domain::{
@@ -28,8 +34,44 @@ impl SoupService for MockSoup {
}
}
+struct MockEmail;
+
+impl EmailService for MockEmail {
+ async fn get_email_thread_previews(
+ &self,
+ _req: email::domain::models::GetEmailsRequest,
+ ) -> Result<
+ models_pagination::PaginatedCursor<
+ email::domain::models::EnrichedEmailThreadPreview,
+ uuid::Uuid,
+ models_pagination::SimpleSortMethod,
+ (),
+ >,
+ email::domain::models::EmailErr,
+ > {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
+ }
+
+ async fn get_link_by_auth_id_and_macro_id(
+ &self,
+ _auth_id: &str,
+ _macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,
+ ) -> Result<Option<email::domain::models::Link>, email::domain::models::EmailErr> {
+ Ok(Some(email::domain::models::Link {
+ id: Uuid::new_v4(),
+ macro_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ fusionauth_user_id: String::new(),
+ email_address: EmailStr::try_from("[email protected]".to_string()).unwrap(),
+ provider: UserProvider::Gmail,
+ is_sync_active: true,
+ created_at: Default::default(),
+ updated_at: Default::default(),
+ }))
+ }
+}
+
fn mock_router() -> Router {
- soup_router(SoupRouterState::new(MockSoup)).layer(Extension(UserContext {
+ soup_router(SoupRouterState::new(MockSoup, MockEmail)).layer(Extension(UserContext {
user_id: "macro|[email protected]".to_string(),
fusion_user_id: "1234".to_string(),
permissions: None,
diff --git a/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip
index 5816a9aecf..f21040db78 100644
Binary files a/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip differ