Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(email): short-cadence inbox grant health probe and poll (#4132)
gbirmaneedef409fb95
diff --git a/infra/stacks/email-service/Pulumi.dev.yaml b/infra/stacks/email-service/Pulumi.dev.yamlindex 91c73463be..170b938010 100644--- a/infra/stacks/email-service/Pulumi.dev.yaml+++ b/infra/stacks/email-service/Pulumi.dev.yaml@@ -31,3 +31,4 @@ config:email-service:macro_db_secret_key: macro-db-devemail-service:delete_unused_after_days: 5000email-service:delete_inactive_after_days: 5000+ email-service:inbox_health_poll_interval_hours: 6diff --git a/infra/stacks/email-service/Pulumi.prod.yaml b/infra/stacks/email-service/Pulumi.prod.yamlindex c8646e84b3..b3c7bc75df 100644--- a/infra/stacks/email-service/Pulumi.prod.yaml+++ b/infra/stacks/email-service/Pulumi.prod.yaml@@ -31,3 +31,4 @@ config:email-service:macro_db_secret_key: macro-db-prodemail-service:delete_unused_after_days: 7email-service:delete_inactive_after_days: 60+ email-service:inbox_health_poll_interval_hours: 6diff --git a/infra/stacks/email-service/index.ts b/infra/stacks/email-service/index.tsindex ddd8eed201..a2c9913d80 100644--- a/infra/stacks/email-service/index.ts+++ b/infra/stacks/email-service/index.ts@@ -624,6 +624,9 @@ new EmailPubSubWorkers('email-pubsub-workers', {const DELETE_UNUSED_AFTER_DAYS = config.require(`delete_unused_after_days`);const DELETE_INACTIVE_AFTER_DAYS = config.require(`delete_inactive_after_days`);+const INBOX_HEALTH_POLL_INTERVAL_HOURS = config.require(+ `inbox_health_poll_interval_hours`+);const emailRefreshHandler = new EmailRefreshHandler('email-refresh-handler', {queueArns: [linkManagerQueueArn],@@ -635,6 +638,7 @@ const emailRefreshHandler = new EmailRefreshHandler('email-refresh-handler', {RUST_LOG: 'email_refresh_handler=info',DELETE_UNUSED_AFTER_DAYS: pulumi.interpolate`${DELETE_UNUSED_AFTER_DAYS}`,DELETE_INACTIVE_AFTER_DAYS: pulumi.interpolate`${DELETE_INACTIVE_AFTER_DAYS}`,+ INBOX_HEALTH_POLL_INTERVAL_HOURS: pulumi.interpolate`${INBOX_HEALTH_POLL_INTERVAL_HOURS}`,},tags,});diff --git a/infra/stacks/email-service/refresh_lambda.ts b/infra/stacks/email-service/refresh_lambda.tsindex 25245e1382..c15b72e959 100644--- a/infra/stacks/email-service/refresh_lambda.ts+++ b/infra/stacks/email-service/refresh_lambda.ts@@ -14,6 +14,7 @@ export type EnvVars = {RUST_LOG: pulumi.Output<string> | string;DELETE_UNUSED_AFTER_DAYS: pulumi.Output<string> | string;DELETE_INACTIVE_AFTER_DAYS: pulumi.Output<string> | string;+ INBOX_HEALTH_POLL_INTERVAL_HOURS: pulumi.Output<string> | string;};type Args = {diff --git a/js/app/packages/app/component/GmailReauthenticationPrompt.tsx b/js/app/packages/app/component/GmailReauthenticationPrompt.tsxindex f04e027d19..5d2a37199b 100644--- a/js/app/packages/app/component/GmailReauthenticationPrompt.tsx+++ b/js/app/packages/app/component/GmailReauthenticationPrompt.tsx@@ -1,6 +1,9 @@import { toast } from '@core/component/Toast/Toast';import { useAddInboxFlow } from '@core/email-link';-import { useEmailLinksQuery } from '@queries/email/link';+import {+ useEmailLinksQuery,+ useInboxHealthProbeQuery,+} from '@queries/email/link';import { createEffect, onCleanup } from 'solid-js';/**@@ -14,6 +17,10 @@ export function GmailReauthenticationPrompt() {const linksQuery = useEmailLinksQuery();const startAddInbox = useAddInboxFlow();+ // Probe inbox grants on mount and on window focus so a grant that died while the+ // user was away surfaces here instead of only after the daily refresh.+ useInboxHealthProbeQuery();+// One persistent toast per broken inbox, keyed by link id.const toastIds = new Map<string, number>();// Inboxes the user dismissed this session; not re-prompted until they recover.diff --git a/js/app/packages/queries/email/keys.ts b/js/app/packages/queries/email/keys.tsindex 11adf36b3c..95a44e73bc 100644--- a/js/app/packages/queries/email/keys.ts+++ b/js/app/packages/queries/email/keys.ts@@ -5,6 +5,7 @@ export const emailKeys = createQueryKeys('email', {all: null,labels: null,links: null,+ linksHealthProbe: null,threads: null,thread: (threadId: string) => ({queryKey: [threadId],diff --git a/js/app/packages/queries/email/link.ts b/js/app/packages/queries/email/link.tsindex d1b998282b..4ff0637c59 100644--- a/js/app/packages/queries/email/link.ts+++ b/js/app/packages/queries/email/link.ts@@ -12,6 +12,29 @@ import { emailKeys } from './keys';const LINK_STALE_TIME = 5 * 60 * 1000;+const HEALTH_PROBE_STALE_TIME = 15 * 60 * 1000;++/**+ * Asks the server to probe each linked inbox's grant against Google and record its+ * health, so a grant that died while the user was away surfaces soon after they return+ * rather than waiting on the daily refresh. Runs on mount and on window focus, throttled+ * to once per stale-time window (the server also throttles per inbox). Fire-and-forget:+ * the refreshed `needs_reauth` is read by `useEmailLinksQuery`, which drives the reconnect+ * prompt — nothing renders from this query.+ */+export function useInboxHealthProbeQuery() {+ return useQuery(() => ({+ queryKey: emailKeys.linksHealthProbe.queryKey,+ queryFn: async () => {+ await emailClient.healthCheckLinks();+ return null;+ },+ staleTime: HEALTH_PROBE_STALE_TIME,+ refetchOnWindowFocus: true,+ retry: false,+ }));+}+export function useEmailLinksQuery() {return useQuery(() => ({queryKey: emailKeys.links.queryKey,diff --git a/js/app/packages/service-clients/service-email/client.ts b/js/app/packages/service-clients/service-email/client.tsindex 27d3b1fcc6..37daeeb4da 100644--- a/js/app/packages/service-clients/service-email/client.ts+++ b/js/app/packages/service-clients/service-email/client.ts@@ -285,6 +285,14 @@ export const emailClient = {).map((result) => result);},+ async healthCheckLinks() {+ return (+ await emailFetch<EmptyResponse>('/email/links/health-check', {+ method: 'POST',+ })+ ).map((result) => result);+ },+async listContacts() {return (await emailFetch<ListContactsResponse>('/email/contacts', {diff --git a/js/app/packages/service-clients/service-email/generated/client.ts b/js/app/packages/service-clients/service-email/generated/client.tsindex 5953eca7c3..b4f0d77ea5 100644--- a/js/app/packages/service-clients/service-email/generated/client.ts+++ b/js/app/packages/service-clients/service-email/generated/client.ts@@ -1755,6 +1755,68 @@ export const listLinks = async (} as listLinksResponse;};+/**+ * Probes run in the background and the response returns immediately to stay off the+load path; each persisted flag is picked up by the next links read. Probes are+throttled per link in Redis so frequent calls — and many sharers of a shared inbox —+collapse to one refresh per window.+ * @summary Probes the live auth state of each of the caller's inboxes (owned and delegated)+against the auth service and records the result on each link. A grant that died+while the caller was inactive is detected here within minutes instead of waiting on+the daily refresh sweep; the side effects (clearing or setting the reauth flag, and+the one-time reauth fan-out) are handled by `fetch_token_or_mark_reauth_no_cache`.+ */+export type healthCheckLinksResponse202 = {+ data: EmptyResponse;+ status: 202;+};++export type healthCheckLinksResponse401 = {+ data: ErrorResponse;+ status: 401;+};++export type healthCheckLinksResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type healthCheckLinksResponseSuccess = healthCheckLinksResponse202 & {+ headers: Headers;+};+export type healthCheckLinksResponseError = (+ | healthCheckLinksResponse401+ | healthCheckLinksResponse500+) & {+ headers: Headers;+};++export type healthCheckLinksResponse =+ | healthCheckLinksResponseSuccess+ | healthCheckLinksResponseError;++export const getHealthCheckLinksUrl = () => {+ return `/email/links/health-check`;+};++export const healthCheckLinks = async (+ options?: RequestInit+): Promise<healthCheckLinksResponse> => {+ const res = await fetch(getHealthCheckLinksUrl(), {+ ...options,+ method: 'POST',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: healthCheckLinksResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as healthCheckLinksResponse;+};+/*** For an inbox the caller owns this enqueues a full cascade teardown(`LinkManagerMessage::DeleteLink`). For an inbox reached via delegation itdiff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.jsonindex f1cf3ce7ca..0aa4a1a3f5 100644--- a/js/app/packages/service-clients/service-email/openapi.json+++ b/js/app/packages/service-clients/service-email/openapi.json@@ -1595,6 +1595,46 @@}}},+ "/email/links/health-check": {+ "post": {+ "tags": ["Links"],+ "summary": "Probes the live auth state of each of the caller's inboxes (owned and delegated)\nagainst the auth service and records the result on each link. A grant that died\nwhile the caller was inactive is detected here within minutes instead of waiting on\nthe daily refresh sweep; the side effects (clearing or setting the reauth flag, and\nthe one-time reauth fan-out) are handled by `fetch_token_or_mark_reauth_no_cache`.",+ "description": "Probes run in the background and the response returns immediately to stay off the\nload path; each persisted flag is picked up by the next links read. Probes are\nthrottled per link in Redis so frequent calls — and many sharers of a shared inbox —\ncollapse to one refresh per window.",+ "operationId": "health_check_links",+ "responses": {+ "202": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/EmptyResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/email/links/{link_id}": {"delete": {"tags": ["Links"],diff --git a/rust/cloud-storage/.sqlx/query-62d3c0e100ac941fe7c3be123ffe9ae064691fd23807b6b86be0c1479f5339ae.json b/rust/cloud-storage/.sqlx/query-62d3c0e100ac941fe7c3be123ffe9ae064691fd23807b6b86be0c1479f5339ae.jsonnew file mode 100644index 0000000000..af25480fd3--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-62d3c0e100ac941fe7c3be123ffe9ae064691fd23807b6b86be0c1479f5339ae.json@@ -0,0 +1,33 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n id as \"link_id\"\n FROM email_links\n WHERE\n is_sync_active = TRUE\n AND provider = $1\n AND (abs(hashtext(id::text)::bigint) % $2::int4) = $3::int4\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "link_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ {+ "Custom": {+ "name": "email_user_provider_enum",+ "kind": {+ "Enum": [+ "GMAIL"+ ]+ }+ }+ },+ "Int4",+ "Int4"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "62d3c0e100ac941fe7c3be123ffe9ae064691fd23807b6b86be0c1479f5339ae"+}diff --git a/rust/cloud-storage/email_refresh_handler/src/config.rs b/rust/cloud-storage/email_refresh_handler/src/config.rsindex 7da5a96c8f..6171f64881 100644--- a/rust/cloud-storage/email_refresh_handler/src/config.rs+++ b/rust/cloud-storage/email_refresh_handler/src/config.rs@@ -18,6 +18,9 @@ pub struct Config {/// How many days to keep inactive links aroundpub delete_inactive_after_days: u32,++ /// How often (in hours) the background poll probes each link's grant health+ pub health_poll_interval_hours: u32,}impl Config {@@ -40,12 +43,18 @@ impl Config {.parse().context("DELETE_INACTIVE_AFTER_DAYS must be a valid u32")?;+ let health_poll_interval_hours = std::env::var("INBOX_HEALTH_POLL_INTERVAL_HOURS")+ .context("INBOX_HEALTH_POLL_INTERVAL_HOURS must be provided")?+ .parse()+ .context("INBOX_HEALTH_POLL_INTERVAL_HOURS must be a valid u32")?;+Ok(Config {database_url,link_manager_queue,environment,delete_unused_after_days,delete_inactive_after_days,+ health_poll_interval_hours,})}}diff --git a/rust/cloud-storage/email_refresh_handler/src/handler.rs b/rust/cloud-storage/email_refresh_handler/src/handler.rsindex 70c9a38850..0e7249dc28 100644--- a/rust/cloud-storage/email_refresh_handler/src/handler.rs+++ b/rust/cloud-storage/email_refresh_handler/src/handler.rs@@ -21,16 +21,74 @@ pub async fn handler(ctx: context::Context,_event: LambdaEvent<EventBridgeEvent>,) -> Result<(), Error> {- if matches!(ctx.config.environment, Environment::Production) {- // only send delete messages once daily, during the night- let current_hour = chrono::Utc::now().hour();- if current_hour == 5 {- tokio::try_join!(send_refresh_messages(&ctx), send_delete_messages(&ctx))?;- } else {- send_refresh_messages(&ctx).await?;+ tokio::try_join!(+ send_refresh_messages(&ctx),+ send_health_check_messages(&ctx)+ )?;++ // only send delete messages once daily, during the night+ if matches!(ctx.config.environment, Environment::Production) && chrono::Utc::now().hour() == 5 {+ send_delete_messages(&ctx).await?;+ }++ Ok(())+}++/// send health-check notifications for active links, bucketed by id hash so each link is+/// probed once per configured interval across the hourly runs+async fn send_health_check_messages(ctx: &context::Context) -> Result<(), Error> {+ let interval_hours = ctx.config.health_poll_interval_hours as i32;+ if interval_hours <= 0 {+ return Ok(());+ }++ let now = chrono::Utc::now();+ let current_hour = now.hour();+ // Bucket on hours since the epoch rather than hour-of-day, so every bucket stays+ // reachable even when the interval exceeds 24 hours.+ let bucket = (now.timestamp().div_euclid(3600) % i64::from(interval_hours)) as i32;+ let provider_filter = DbUserProvider::Gmail;++ // uses the index idx_links_active_provider_hash_bucket+ let link_ids = sqlx::query_scalar!(+ r#"+ SELECT+ id as "link_id"+ FROM email_links+ WHERE+ is_sync_active = TRUE+ AND provider = $1+ AND (abs(hashtext(id::text)::bigint) % $2::int4) = $3::int4+ "#,+ provider_filter as _,+ interval_hours,+ bucket+ )+ .fetch_all(&ctx.db)+ .await+ .unwrap_or_else(|e| {+ tracing::error!(error = ?e, "Error fetching links for health check");+ Vec::new()+ });++ if !link_ids.is_empty() {+ tracing::info!(+ "Hour {}. Sending health-check notifications for {} links (every {}h)",+ current_hour,+ link_ids.len(),+ interval_hours+ );++ for link_id in link_ids {+ let notif = LinkManagerMessage::HealthCheck { link_id };+ ctx.sqs_client+ .enqueue_link_manager_notification(notif)+ .await+ .inspect_err(|e| {+ tracing::error!(error=?e, link_id=%link_id, "Error enqueueing health-check notification for link");+ })+ .ok();}- } else {- send_refresh_messages(&ctx).await?;}Ok(())}diff --git a/rust/cloud-storage/email_service/src/api/email/links/health_check.rs b/rust/cloud-storage/email_service/src/api/email/links/health_check.rsnew file mode 100644index 0000000000..852fc7a4dc--- /dev/null+++ b/rust/cloud-storage/email_service/src/api/email/links/health_check.rs@@ -0,0 +1,124 @@+use crate::api::context::ApiContext;+use axum::Extension;+use axum::extract::State;+use axum::http::StatusCode;+use axum::response::{IntoResponse, Json, Response};+use email_service::util::gmail::auth::{+ fetch_token_or_mark_reauth_no_cache, is_reauth_required_error,+};+use model::response::{EmptyResponse, ErrorResponse};+use model::user::UserContext;+use models_email::email::service::pubsub::LinkManagerMessage;+use std::time::Duration;+use thiserror::Error;++/// How long a per-link probe window stands before another probe may run for it.+const HEALTH_PROBE_THROTTLE: Duration = Duration::from_secs(15 * 60);++#[derive(Debug, Error)]+pub enum HealthCheckError {+ #[error("Database error")]+ DatabaseError(#[source] anyhow::Error),+}++impl IntoResponse for HealthCheckError {+ fn into_response(self) -> Response {+ match self {+ HealthCheckError::DatabaseError(_) => (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(ErrorResponse {+ message: "internal error".into(),+ }),+ )+ .into_response(),+ }+ }+}++/// Probes the live auth state of each of the caller's inboxes (owned and delegated)+/// against the auth service and records the result on each link. A grant that died+/// while the caller was inactive is detected here within minutes instead of waiting on+/// the daily refresh sweep; the side effects (clearing or setting the reauth flag, and+/// the one-time reauth fan-out) are handled by `fetch_token_or_mark_reauth_no_cache`.+///+/// Probes run in the background and the response returns immediately to stay off the+/// load path; each persisted flag is picked up by the next links read. Probes are+/// throttled per link in Redis so frequent calls — and many sharers of a shared inbox —+/// collapse to one refresh per window.+#[utoipa::path(+ post,+ tag = "Links",+ path = "/email/links/health-check",+ operation_id = "health_check_links",+ responses(+ (status = 202, body=EmptyResponse),+ (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), err)]+pub async fn health_check_handler(+ State(ctx): State<ApiContext>,+ user_context: Extension<UserContext>,+) -> Result<Response, HealthCheckError> {+ let links =+ email_db_client::links::get::fetch_inboxes_for_macro_id(&ctx.db, &user_context.user_id)+ .await+ .map_err(HealthCheckError::DatabaseError)?;++ for link in links {+ if !link.is_sync_active {+ continue;+ }++ let ctx = ctx.clone();+ tokio::spawn(async move {+ if !ctx+ .redis_client+ .try_begin_health_probe(link.id, HEALTH_PROBE_THROTTLE)+ .await+ {+ return;+ }++ let probe = fetch_token_or_mark_reauth_no_cache(+ &link,+ &ctx.db,+ &ctx.redis_client,+ &ctx.auth_service_client,+ &ctx.sqs_client,+ )+ .await;++ let Err(e) = probe else { return };++ if !is_reauth_required_error(&e) {+ tracing::debug!(error=?e, link_id=%link.id, "Health probe token fetch failed");+ return;+ }++ // A revoked grant marks the link and fans out as a side effect of the probe.+ // If that mark did not persist, the signal would be lost on this fire-and-forget+ // path, so hand off to the link-manager queue, which retries until it sticks.+ let persisted = email_db_client::links::get::fetch_link_by_id(&ctx.db, link.id)+ .await+ .ok()+ .flatten()+ .is_some_and(|l| l.needs_reauth);++ if !persisted {+ ctx.sqs_client+ .enqueue_link_manager_notification(LinkManagerMessage::HealthCheck {+ link_id: link.id,+ })+ .await+ .inspect_err(|enqueue_err| {+ tracing::error!(error=?enqueue_err, link_id=%link.id, "Failed to enqueue health-check retry after unpersisted reauth");+ })+ .ok();+ }+ });+ }++ Ok(StatusCode::ACCEPTED.into_response())+}diff --git a/rust/cloud-storage/email_service/src/api/email/links/mod.rs b/rust/cloud-storage/email_service/src/api/email/links/mod.rsindex 6eb4469850..c29eeff4a2 100644--- a/rust/cloud-storage/email_service/src/api/email/links/mod.rs+++ b/rust/cloud-storage/email_service/src/api/email/links/mod.rs@@ -1,5 +1,6 @@pub(crate) mod access;pub(crate) mod delete;+pub(crate) mod health_check;pub(crate) mod list;pub(crate) mod resync;@@ -10,6 +11,7 @@ use axum::routing::{delete, get, post};pub fn router() -> Router<ApiContext> {Router::new().route("/", get(list::list_links_handler))+ .route("/health-check", post(health_check::health_check_handler)).route("/{link_id}", delete(delete::delete_link_handler)).route("/{link_id}/resync", post(resync::resync_link_handler))}diff --git a/rust/cloud-storage/email_service/src/api/swagger.rs b/rust/cloud-storage/email_service/src/api/swagger.rsindex b452e69e0a..9384b64934 100644--- a/rust/cloud-storage/email_service/src/api/swagger.rs+++ b/rust/cloud-storage/email_service/src/api/swagger.rs@@ -87,6 +87,7 @@ use utoipa::OpenApi;inbound::axum::get_thread_router::get_thread_handler,inbound::axum::thread_project_router::update_thread_project_handler,email::links::list::list_links_handler,+ email::links::health_check::health_check_handler,email::links::delete::delete_link_handler,email::links::resync::resync_link_handler,email::labels::create::handler,diff --git a/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rs b/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rsindex c70854cbc6..79c45e4c2d 100644--- a/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rs+++ b/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rs@@ -1,8 +1,8 @@use crate::pubsub::link_manager::context::LinkManagerContext;use crate::pubsub::util::{build_notification_recipients, cg_refresh_email};use crate::util::gmail::auth::{- fetch_gmail_access_token_from_link, fetch_token_or_mark_reauth, is_forbidden_error,- is_reauth_required_error,+ fetch_gmail_access_token_from_link, fetch_token_or_mark_reauth,+ fetch_token_or_mark_reauth_no_cache, is_forbidden_error, is_reauth_required_error,};use crate::util::sync_contacts::sync_contacts;use anyhow::{Context, anyhow};@@ -31,36 +31,37 @@ pub async fn process_message(let link = get_link_or_skip(&ctx, message, link_id).await?;let Some(link) = link else { return Ok(()) };- match fetch_token_or_mark_reauth(+ let result = fetch_token_or_mark_reauth(&link,&ctx.db,&ctx.redis_client,&ctx.auth_service_client,&ctx.sqs_client,)- .await- {- Ok(gmail_access_token) => {- handle_refresh(&ctx, &link, &gmail_access_token).await?;- }- // The grant is gone. There is nothing to refresh until the user- // reconnects, so drop the message rather than retrying a fetch that- // cannot succeed — but only once the reauth flag is actually- // persisted, otherwise retry so the health signal isn't lost when the- // mark write itself failed.- Err(e) if is_reauth_required_error(&e) => {- let persisted = email_db_client::links::get::fetch_link_by_id(&ctx.db, link.id)- .await- .context("Failed to verify needs_reauth state after token fetch failure")?- .is_some_and(|l| l.needs_reauth);+ .await;- if !persisted {- return Err(e.context("reauth required but needs_reauth not persisted"));- }- }- Err(e) => return Err(e),+ if let Some(gmail_access_token) = settle_reauth_fetch(&ctx, &link, result).await? {+ handle_refresh(&ctx, &link, &gmail_access_token).await?;}}+ LinkManagerMessage::HealthCheck { link_id } => {+ let link = get_link_or_skip(&ctx, message, link_id).await?;+ let Some(link) = link else { return Ok(()) };++ // Probe-only: the health side effects happen inside the fetch; a live token+ // needs no follow-up work here. No-cache so a just-revoked grant is observed+ // now rather than masked by a still-valid cached access token.+ let result = fetch_token_or_mark_reauth_no_cache(+ &link,+ &ctx.db,+ &ctx.redis_client,+ &ctx.auth_service_client,+ &ctx.sqs_client,+ )+ .await;++ settle_reauth_fetch(&ctx, &link, result).await?;+ }LinkManagerMessage::NotifyReauthRequired { link_id } => {let link = get_link_or_skip(&ctx, message, link_id).await?;let Some(link) = link else { return Ok(()) };@@ -86,6 +87,35 @@ pub async fn process_message(Ok(())}+/// Settles the outcome of a token fetch that records reauth health (the `*_or_mark_reauth`+/// family). Returns the token on success. When the grant is gone the link has already been+/// marked for reauth as a side effect, so the message is terminal — return `None` to let it+/// be dropped — but only once that mark is persisted; if the mark write itself failed,+/// propagate the error so the message retries and the health signal isn't lost. Other,+/// transient errors propagate to retry.+async fn settle_reauth_fetch(+ ctx: &LinkManagerContext,+ link: &Link,+ result: anyhow::Result<String>,+) -> anyhow::Result<Option<String>> {+ match result {+ Ok(token) => Ok(Some(token)),+ Err(e) if is_reauth_required_error(&e) => {+ let persisted = email_db_client::links::get::fetch_link_by_id(&ctx.db, link.id)+ .await+ .context("Failed to verify needs_reauth state after token fetch failure")?+ .is_some_and(|l| l.needs_reauth);++ if !persisted {+ return Err(e.context("reauth required but needs_reauth not persisted"));+ }++ Ok(None)+ }+ Err(e) => Err(e),+ }+}+/// Fetches a link by ID, cleaning up the message and returning `None` if not found.async fn get_link_or_skip(ctx: &LinkManagerContext,diff --git a/rust/cloud-storage/email_service/src/util/gmail/auth.rs b/rust/cloud-storage/email_service/src/util/gmail/auth.rsindex 5c5cc42966..c317721d5e 100644--- a/rust/cloud-storage/email_service/src/util/gmail/auth.rs+++ b/rust/cloud-storage/email_service/src/util/gmail/auth.rs@@ -32,7 +32,39 @@ pub async fn fetch_token_or_mark_reauth(auth_service_client: &AuthServiceClient,sqs_client: &SQS,) -> anyhow::Result<String> {- match fetch_gmail_access_token_from_link(link, redis_client, auth_service_client).await {+ let result = fetch_gmail_access_token_from_link(link, redis_client, auth_service_client).await;+ record_token_health(link, db, sqs_client, result).await+}++/// Like [`fetch_token_or_mark_reauth`] but bypasses the Redis token cache and forces a+/// fresh refresh against the auth service. A cached access token outlives a grant+/// revocation by up to its TTL — revocation invalidates the refresh token, not an+/// already-minted access token — so a cache-respecting fetch can miss a just-revoked+/// grant. Probes that must observe revocation promptly use this path.+#[tracing::instrument(skip(db, redis_client, auth_service_client, sqs_client))]+pub async fn fetch_token_or_mark_reauth_no_cache(+ link: &Link,+ db: &sqlx::PgPool,+ redis_client: &RedisClient,+ auth_service_client: &AuthServiceClient,+ sqs_client: &SQS,+) -> anyhow::Result<String> {+ let result =+ fetch_gmail_access_token_from_link_no_cache(link, redis_client, auth_service_client).await;+ record_token_health(link, db, sqs_client, result).await+}++/// Records a link's sync health from the outcome of a token fetch: clears the reauth+/// flag on success, marks the link as needing reauth on a revoked or missing grant+/// (enqueuing a one-time fan-out only on the first false->true transition), and leaves+/// health state untouched for transient failures. Returns the fetch result unchanged.+async fn record_token_health(+ link: &Link,+ db: &sqlx::PgPool,+ sqs_client: &SQS,+ result: anyhow::Result<String>,+) -> anyhow::Result<String> {+ match result {Ok(token) => {email_db_client::links::update::clear_link_needs_reauth(db, link.id).await@@ -118,6 +150,27 @@ pub async fn fetch_gmail_access_token_from_link(fetch_gmail_access_token(&key, redis_client, auth_service_client).await}+/// Like [`fetch_gmail_access_token_from_link`] but bypasses the Redis cache and forces a+/// fresh token from the auth service.+pub async fn fetch_gmail_access_token_from_link_no_cache(+ link: &Link,+ redis_client: &RedisClient,+ auth_service_client: &AuthServiceClient,+) -> anyhow::Result<String> {+ let key = TokenCacheKey::new(+ &link.fusionauth_user_id,+ link.email_address.0.as_ref(),+ link.provider.as_str(),+ );++ let conn = redis_client+ .inner+ .get_multiplexed_async_connection()+ .await+ .context("unable to connect to redis")?;+ email::outbound::fetch_gmail_access_token_no_cache(&key, &conn, auth_service_client).await+}+/// fetches a user's gmail token using the user_context from the API request./// This always resolves to the JWT subject's *primary* inbox — the email part of/// `user_context.user_id`. For multi-inbox callers that need a specific linkeddiff --git a/rust/cloud-storage/email_service/src/util/redis/health_probe.rs b/rust/cloud-storage/email_service/src/util/redis/health_probe.rsnew file mode 100644index 0000000000..9ac54f9bb7--- /dev/null+++ b/rust/cloud-storage/email_service/src/util/redis/health_probe.rs@@ -0,0 +1,45 @@+use crate::util::redis::RedisClient;+use std::time::Duration;+use uuid::Uuid;++impl RedisClient {+ /// Claims a per-link probe window with `SET health_probe:{link_id} 1 NX EX ttl`.+ ///+ /// Returns `true` when this caller acquired the window and should run a probe, and+ /// `false` when a probe already ran within `ttl`. The key is never deleted — it+ /// expires with its TTL, so the window stands for the full duration regardless of+ /// how the probe itself fares. Keying on `link_id` (not the caller) means every+ /// sharer of a shared link draws from one window.+ ///+ /// Redis errors fail open (returns `true`): a cache outage must not suppress+ /// detection, and the worst case is a few extra refreshes against the auth service.+ pub async fn try_begin_health_probe(&self, link_id: Uuid, ttl: Duration) -> bool {+ let key = format!("health_probe:{link_id}");++ let mut con = match self.inner.get_multiplexed_async_connection().await {+ Ok(con) => con,+ Err(e) => {+ tracing::warn!(error=?e, %link_id, "Failed to get Redis connection for health probe throttle");+ return true;+ }+ };++ let acquired: Option<String> = match redis::cmd("SET")+ .arg(&key)+ .arg("1")+ .arg("NX")+ .arg("EX")+ .arg(ttl.as_secs())+ .query_async(&mut con)+ .await+ {+ Ok(res) => res,+ Err(e) => {+ tracing::warn!(error=?e, %link_id, "Failed to claim health probe window");+ return true;+ }+ };++ acquired.is_some()+ }+}diff --git a/rust/cloud-storage/email_service/src/util/redis/mod.rs b/rust/cloud-storage/email_service/src/util/redis/mod.rsindex 2674d04191..c2230ded4a 100644--- a/rust/cloud-storage/email_service/src/util/redis/mod.rs+++ b/rust/cloud-storage/email_service/src/util/redis/mod.rs@@ -1,5 +1,6 @@pub mod access_token;pub mod backfill;+pub mod health_probe;pub mod lock;pub mod rate_limit;diff --git a/rust/cloud-storage/models_email/src/email/service/pubsub.rs b/rust/cloud-storage/models_email/src/email/service/pubsub.rsindex 599fe4035c..0675c9aac2 100644--- a/rust/cloud-storage/models_email/src/email/service/pubsub.rs+++ b/rust/cloud-storage/models_email/src/email/service/pubsub.rs@@ -79,6 +79,10 @@ pub enum LinkManagerMessage {/// its grant has gone dead and the inbox needs to be reconnected. Enqueued/// once, on the edge where a link first transitions into needs-reauth.NotifyReauthRequired { link_id: Uuid },+ /// Probe a single link's grant and record its sync health, without renewing the+ /// Gmail watch or syncing contacts. Enqueued by the periodic health poll so a dead+ /// grant surfaces between the daily full refreshes.+ HealthCheck { link_id: Uuid },}/// The message we send from the email_scheduled_handler lambda to the service via SQS to trigger