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.

chore(email-service): Delete the enable sync endpoint (#1122)

Evan Hutnik553c3bd92ce3
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 3c1eeb2dbc..b0d91959b3 100644
--- a/rust/cloud-storage/email_service/src/api/email/init.rs
+++ b/rust/cloud-storage/email_service/src/api/email/init.rs
@@ -1,5 +1,5 @@
use crate::api::ApiContext;
-use crate::api::email::sync::enable::{EnableSyncError, enable_gmail_sync};
+use crate::utils::extract_email_with_response;
use anyhow::Context;
use axum::{
Extension,
@@ -9,11 +9,16 @@ use axum::{
};
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::ErrorResponse;
+use model::user::UserContext;
use model::user::axum_extractor::MacroUserExtractor;
use models_email::email::service::backfill::{
BackfillJobStatus, BackfillOperation, BackfillPubsubMessage,
};
+use models_email::service::link;
+use models_email::service::link::Link;
use strum_macros::AsRefStr;
use thiserror::Error;
use utoipa::ToSchema;
@@ -30,41 +35,29 @@ pub enum InitError {
#[error("Failed to enqueue backfill message")]
EnqueueError,
- #[error("Enable sync error")]
- EnableSync(#[from] EnableSyncError),
-
#[error("Database query error")]
- QueryError(#[from] anyhow::Error),
+ DatabaseError(#[from] anyhow::Error),
+
+ #[error("Bad request")]
+ BadRequest(String),
+
+ #[error("Invalid input")]
+ Parse(#[from] macro_user_id::error::ParseErr),
}
impl IntoResponse for InitError {
fn into_response(self) -> Response {
- match self {
- InitError::EnableSync(e) => {
- // Delegate to EnableSyncError's IntoResponse
- e.into_response()
+ let status_code = match &self {
+ InitError::AlreadyInitialized | InitError::BadRequest(_) | InitError::Parse(_) => {
+ StatusCode::BAD_REQUEST
}
- _ => {
- let status_code = match &self {
- InitError::AlreadyInitialized => StatusCode::BAD_REQUEST,
- InitError::TooManyJobs => StatusCode::TOO_MANY_REQUESTS,
- InitError::EnqueueError | InitError::QueryError(_) => {
- StatusCode::INTERNAL_SERVER_ERROR
- }
- InitError::EnableSync(_) => unreachable!(),
- };
-
- if status_code.is_server_error() {
- tracing::error!(
- nested_error = ?self,
- error_type = "InitError",
- variant = self.as_ref(),
- "Internal server error");
- }
-
- (status_code, self.to_string()).into_response()
+ InitError::TooManyJobs => StatusCode::TOO_MANY_REQUESTS,
+ InitError::EnqueueError | InitError::DatabaseError(_) => {
+ StatusCode::INTERNAL_SERVER_ERROR
}
- }
+ };
+
+ (status_code, self.to_string()).into_response()
}
}
@@ -194,3 +187,56 @@ pub async fn handler(
}
}
}
+
+/// Enables Gmail sync for a user by A) registering a watch with Gmail API B) updating the link record
+/// to is_sync_active = true and C) updating gmail_histories entry with the current history value.
+#[tracing::instrument(skip(ctx, user_context, gmail_access_token))]
+pub async fn enable_gmail_sync(
+ ctx: &ApiContext,
+ user_context: &UserContext,
+ gmail_access_token: Option<&str>,
+) -> Result<Link, InitError> {
+ let token = match gmail_access_token {
+ Some(token) => token.to_string(),
+ None => email_service::util::gmail::auth::fetch_gmail_token_usercontext_response(
+ user_context,
+ &ctx.redis_client,
+ &ctx.auth_service_client,
+ )
+ .await
+ .map_err(|_| InitError::BadRequest("Failed to fetch Gmail token".to_string()))?,
+ };
+
+ // Register watch with Gmail
+ let watch_response = ctx
+ .gmail_client
+ .register_watch(&token)
+ .await
+ .context("Gmail call to register watch failed")?;
+
+ let email = extract_email_with_response(&user_context.user_id)
+ .map_err(|_| InitError::BadRequest("Failed to extract email".to_string()))?;
+
+ let mut link = link::Link {
+ id: macro_uuid::generate_uuid_v7(), // will get ignored for existing links
+ macro_id: MacroUserIdStr::try_from(user_context.user_id.clone())?,
+ fusionauth_user_id: user_context.fusion_user_id.clone(),
+ 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(),
+ };
+
+ // either create new link for user or update is_sync_active to true
+ link = email_db_client::links::insert::upsert_link(&ctx.db, link)
+ .await
+ .context("Failed to upsert link")?;
+
+ // either create gmail_histories value or update history_id to current value
+ email_db_client::histories::upsert_gmail_history(&ctx.db, link.id, &watch_response.history_id)
+ .await
+ .context("Failed to upsert gmail history")?;
+
+ Ok(link)
+}
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
deleted file mode 100644
index d006564a38..0000000000
--- a/rust/cloud-storage/email_service/src/api/email/sync/enable.rs
+++ /dev/null
@@ -1,156 +0,0 @@
-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 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 strum_macros::AsRefStr;
-use thiserror::Error;
-
-#[derive(Debug, Error, AsRefStr)]
-pub enum EnableSyncError {
- #[error("Syncing is already enabled")]
- SyncAlreadyEnabled,
-
- #[error("Failed to register Gmail watch")]
- RegisterWatchError(#[from] anyhow::Error),
-
- #[error("Database query error")]
- QueryError(#[from] sqlx::Error),
-
- #[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(_)
- | EnableSyncError::Parse(_) => StatusCode::BAD_REQUEST,
- EnableSyncError::RegisterWatchError(_) | EnableSyncError::QueryError(_) => {
- StatusCode::INTERNAL_SERVER_ERROR
- }
- };
-
- if status_code.is_server_error() {
- tracing::error!(
- nested_error = ?self,
- error_type = "EnableSyncError",
- variant = self.as_ref(),
- "Internal server error");
- }
-
- (status_code, self.to_string()).into_response()
- }
-}
-
-/// Enables inbox syncing for user.
-#[utoipa::path(
- post,
- tag = "Sync",
- path = "/email/sync",
- operation_id = "enable_sync",
- responses(
- (status = 201, body=EmptyResponse),
- (status = 400, body=ErrorResponse),
- (status = 401, body=ErrorResponse),
- (status = 500, body=ErrorResponse),
- )
-)]
-#[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>,
- MacroUserExtractor {
- macro_user_id,
- user_context,
- ..
- }: MacroUserExtractor,
-) -> Result<Response, EnableSyncError> {
- // if link exists already and syncing is already enabled, return error
- 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
- {
- return Err(EnableSyncError::SyncAlreadyEnabled);
- }
-
- enable_gmail_sync(&ctx, &user_context, None).await?;
-
- Ok((StatusCode::CREATED, Json(EmptyResponse::default())).into_response())
-}
-
-/// Enables Gmail sync for a user by A) registering a watch with Gmail API B) updating the link record
-/// to is_sync_active = true and C) updating gmail_histories entry with the current history value.
-#[tracing::instrument(skip(ctx, user_context, gmail_access_token), level = "info")]
-pub async fn enable_gmail_sync(
- ctx: &ApiContext,
- user_context: &UserContext,
- gmail_access_token: Option<&str>,
-) -> Result<Link, EnableSyncError> {
- let token = match gmail_access_token {
- Some(token) => token.to_string(),
- None => email_service::util::gmail::auth::fetch_gmail_token_usercontext_response(
- user_context,
- &ctx.redis_client,
- &ctx.auth_service_client,
- )
- .await
- .map_err(|_| EnableSyncError::BadRequest("Failed to fetch Gmail token".to_string()))?,
- };
-
- // Register watch with Gmail
- let watch_response = ctx
- .gmail_client
- .register_watch(&token)
- .await
- .context("Gmail call to register watch failed")?;
-
- let email = extract_email_with_response(&user_context.user_id)
- .map_err(|_| EnableSyncError::BadRequest("Failed to extract email".to_string()))?;
-
- let mut link = link::Link {
- id: macro_uuid::generate_uuid_v7(), // will get ignored for existing links
- macro_id: MacroUserIdStr::try_from(user_context.user_id.clone())?,
- fusionauth_user_id: user_context.fusion_user_id.clone(),
- 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(),
- };
-
- // either create new link for user or update is_sync_active to true
- link = email_db_client::links::insert::upsert_link(&ctx.db, link)
- .await
- .context("Failed to upsert link")?;
-
- // either create gmail_histories value or update history_id to current value
- email_db_client::histories::upsert_gmail_history(&ctx.db, link.id, &watch_response.history_id)
- .await
- .context("Failed to upsert gmail history")?;
-
- Ok(link)
-}
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 b9ee3ee244..c7a9c00c14 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
@@ -1,15 +1,13 @@
use crate::api::ApiContext;
use crate::api::email::sync::disable::disable_handler;
-use crate::api::email::sync::enable::enable_handler;
use axum::Router;
-use axum::routing::{delete, post};
+use axum::routing::delete;
use tower::ServiceBuilder;
pub(crate) mod disable;
-pub(crate) mod enable;
pub fn router(state: ApiContext) -> Router<ApiContext> {
- Router::new().route("/", post(enable_handler)).route(
+ Router::new().route(
"/",
delete(disable_handler).layer(
ServiceBuilder::new()
diff --git a/rust/cloud-storage/email_service/src/api/swagger.rs b/rust/cloud-storage/email_service/src/api/swagger.rs
index 44141264e0..d420c54565 100644
--- a/rust/cloud-storage/email_service/src/api/swagger.rs
+++ b/rust/cloud-storage/email_service/src/api/swagger.rs
@@ -66,7 +66,6 @@ use utoipa::OpenApi;
email::labels::delete::handler,
email::labels::list::handler,
email::contacts::list::list_contacts_handler,
- email::sync::enable::enable_handler,
email::sync::disable::disable_handler,
email::settings::patch::patch_settings_handler,
),