Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(email): bypass Redis cache for Gmail token on init endpoint (#2120)

Evan Hutnik875399449bbd
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 6bc0b01921..1f2132804a 100644
--- a/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs
@@ -167,6 +167,13 @@ pub trait GmailTokenProvider: Send + Sync + 'static {
&self,
link: &Link,
) -> impl Future<Output = Result<String, EmailErr>> + Send;
+
+ /// Fetch a Gmail OAuth access token directly from the auth service,
+ /// bypassing the Redis cache for reads but still caching the result.
+ fn fetch_gmail_access_token_no_cache(
+ &self,
+ link: &Link,
+ ) -> impl Future<Output = Result<String, EmailErr>> + Send;
}
/// Axum state wrapper for a [`GmailTokenProvider`] implementation.
diff --git a/rust/cloud-storage/email/src/outbound/gmail_token_provider.rs b/rust/cloud-storage/email/src/outbound/gmail_token_provider.rs
index 79c121d62d..ad26c3f8ce 100644
--- a/rust/cloud-storage/email/src/outbound/gmail_token_provider.rs
+++ b/rust/cloud-storage/email/src/outbound/gmail_token_provider.rs
@@ -43,6 +43,18 @@ impl GmailTokenProvider for GmailTokenProviderImpl {
.await
.map_err(EmailErr::ProviderErr)
}
+
+ #[tracing::instrument(skip(self, link), err)]
+ async fn fetch_gmail_access_token_no_cache(&self, link: &Link) -> Result<String, EmailErr> {
+ let key = TokenCacheKey::new(
+ &link.fusionauth_user_id,
+ link.macro_id.0.as_ref(),
+ link.provider.as_str(),
+ );
+ fetch_gmail_access_token_no_cache(&key, &self.redis_conn, &self.auth_service_client)
+ .await
+ .map_err(EmailErr::ProviderErr)
+ }
}
/// Fetches a Gmail access token, first checking the Redis cache then falling back to the auth
@@ -68,34 +80,59 @@ pub async fn fetch_gmail_access_token(
let access_token = if let Some(token) = token_from_redis {
token
} else {
- let fetched_token = auth_service_client
- .get_google_access_token(&key.fusion_user_id, &key.macro_id)
- .await
- .with_context(|| {
- format!(
- "Failed to get Google access token from auth service. TokenCacheKey: {:?}",
- key
- )
- })?;
-
- // Cache newly fetched token
- if let Err(cache_err) = conn
- .set_ex::<&str, &str, ()>(
- &redis_key,
- &fetched_token.access_token,
- GMAIL_ACCESS_TOKEN_EXPIRY_SECONDS,
- )
- .await
- {
- tracing::warn!(
- error = ?cache_err,
- token_cache_key = ?key,
- "Failed to cache fetched access token in Redis"
- );
- }
-
- fetched_token.access_token
+ let token = fetch_token_from_auth_service(key, auth_service_client).await?;
+ cache_token_in_redis(&mut conn, key, &token).await;
+ token
};
Ok(access_token)
}
+
+/// Fetches a Gmail access token directly from the auth service, bypassing the Redis cache for
+/// reads but still caching the newly fetched token.
+#[tracing::instrument(skip(key, redis_conn, auth_service_client), err)]
+pub async fn fetch_gmail_access_token_no_cache(
+ key: &TokenCacheKey,
+ redis_conn: &MultiplexedConnection,
+ auth_service_client: &AuthServiceClient,
+) -> anyhow::Result<String> {
+ let token = fetch_token_from_auth_service(key, auth_service_client).await?;
+ let mut conn = redis_conn.clone();
+ cache_token_in_redis(&mut conn, key, &token).await;
+ Ok(token)
+}
+
+/// Best-effort cache write. Logs a warning on failure but never errors.
+#[tracing::instrument(skip(conn, key, token))]
+async fn cache_token_in_redis(conn: &mut MultiplexedConnection, key: &TokenCacheKey, token: &str) {
+ let redis_key = key.to_redis_key();
+ if let Err(cache_err) = conn
+ .set_ex::<&str, &str, ()>(&redis_key, token, GMAIL_ACCESS_TOKEN_EXPIRY_SECONDS)
+ .await
+ {
+ tracing::warn!(
+ error = ?cache_err,
+ token_cache_key = ?key,
+ "Failed to cache fetched access token in Redis"
+ );
+ }
+}
+
+/// Fetches a Gmail access token from the auth service.
+#[tracing::instrument(skip(key, auth_service_client), err)]
+async fn fetch_token_from_auth_service(
+ key: &TokenCacheKey,
+ auth_service_client: &AuthServiceClient,
+) -> anyhow::Result<String> {
+ let fetched_token = auth_service_client
+ .get_google_access_token(&key.fusion_user_id, &key.macro_id)
+ .await
+ .with_context(|| {
+ format!(
+ "Failed to get Google access token from auth service. TokenCacheKey: {:?}",
+ key
+ )
+ })?;
+
+ Ok(fetched_token.access_token)
+}
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 2db6136246..3b98d8dcc7 100644
--- a/rust/cloud-storage/email_service/src/api/email/init.rs
+++ b/rust/cloud-storage/email_service/src/api/email/init.rs
@@ -201,7 +201,7 @@ pub async fn enable_gmail_sync(
) -> 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(
+ None => email_service::util::gmail::auth::fetch_gmail_token_no_cache(
user_context,
&ctx.redis_client,
&ctx.auth_service_client,
diff --git a/rust/cloud-storage/email_service/src/api/email/mod.rs b/rust/cloud-storage/email_service/src/api/email/mod.rs
index 8920eb725f..233b1436b5 100644
--- a/rust/cloud-storage/email_service/src/api/email/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/mod.rs
@@ -35,7 +35,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
"/init",
post(init::handler).layer(axum::middleware::from_fn_with_state(
state,
- crate::api::middleware::gmail_token::attach_gmail_token,
+ crate::api::middleware::gmail_token::attach_gmail_token_no_cache,
)),
)
}
diff --git a/rust/cloud-storage/email_service/src/api/middleware/gmail_token.rs b/rust/cloud-storage/email_service/src/api/middleware/gmail_token.rs
index badc158a88..596f0ad534 100644
--- a/rust/cloud-storage/email_service/src/api/middleware/gmail_token.rs
+++ b/rust/cloud-storage/email_service/src/api/middleware/gmail_token.rs
@@ -3,7 +3,9 @@ use axum::{Extension, extract::Request, middleware::Next, response::Response};
use model::user::UserContext;
use crate::api::context::ApiContext;
-use email_service::util::gmail::auth::fetch_gmail_token_usercontext_response;
+use email_service::util::gmail::auth::{
+ fetch_gmail_token_no_cache, fetch_gmail_token_usercontext_response,
+};
pub(in crate::api) async fn attach_gmail_token(
State(ctx): State<ApiContext>,
@@ -21,3 +23,20 @@ pub(in crate::api) async fn attach_gmail_token(
req.extensions_mut().insert(gmail_token);
Ok(next.run(req).await)
}
+
+/// Like [`attach_gmail_token`] but always fetches a fresh token from the auth service,
+/// bypassing the Redis cache. Used only by the `/email/init` endpoint.
+#[tracing::instrument(skip(ctx, user_context, req, next))]
+pub(in crate::api) async fn attach_gmail_token_no_cache(
+ State(ctx): State<ApiContext>,
+ user_context: Extension<UserContext>,
+ mut req: Request,
+ next: Next,
+) -> Result<Response, Response> {
+ let gmail_token =
+ fetch_gmail_token_no_cache(&user_context, &ctx.redis_client, &ctx.auth_service_client)
+ .await?;
+
+ req.extensions_mut().insert(gmail_token);
+ Ok(next.run(req).await)
+}
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 e9c200d391..c9235555c9 100644
--- a/rust/cloud-storage/email_service/src/util/gmail/auth.rs
+++ b/rust/cloud-storage/email_service/src/util/gmail/auth.rs
@@ -105,6 +105,49 @@ pub async fn fetch_gmail_token_usercontext_response(
})
}
+/// Fetches a user's gmail token directly from the auth service, bypassing the Redis cache.
+/// Used by the init endpoint where we always want a fresh token.
+#[tracing::instrument(skip(user_context, redis_client, auth_service_client))]
+pub async fn fetch_gmail_token_no_cache(
+ user_context: &UserContext,
+ redis_client: &RedisClient,
+ auth_service_client: &AuthServiceClient,
+) -> Result<String, Response> {
+ let key = TokenCacheKey::new(
+ &user_context.fusion_user_id,
+ &user_context.user_id,
+ UserProvider::Gmail.as_str(),
+ );
+
+ let conn = redis_client
+ .inner
+ .get_multiplexed_async_connection()
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "unable to connect to redis");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "unable to get gmail access token",
+ }),
+ )
+ .into_response()
+ })?;
+
+ email::outbound::fetch_gmail_access_token_no_cache(&key, &conn, auth_service_client)
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "unable to get gmail access token from auth service");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "unable to get gmail access token",
+ }),
+ )
+ .into_response()
+ })
+}
+
/// Fetches the gmail access token, first looking in the redis cache then hitting the auth service.
///
/// Delegates to [`email::outbound::fetch_gmail_access_token`].