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.

45.8 KB
Raw Blame
//! Calendar business policy.

use std::collections::HashMap;

use chrono::Utc;
use futures::future::{BoxFuture, Either, select};
use rootcause::Report;
use uuid::Uuid;

use crate::domain::events::{CalendarEventMetadata, CalendarMacroEvent, CalendarTopicEvent};
use macro_event_broker::MacroEventBroker;

use super::{
    ics::{
        CalendarEventExportAccess, CalendarEventForward, CalendarEventForwardKind,
        CalendarEventIcs, IcsParticipant, IcsPurpose, render_event_ics,
    },
    labels::{CalendarLabels, EventLabels},
    models::{
        ActorInboxes, AppliedGoogleGrant, CalendarBackfillClaim,
        CalendarBackfillFailureDisposition, CalendarBackfillFailureOutcome, CalendarBackfillJobKey,
        CalendarEventUpsert, CalendarGrantIntent, CalendarOccurrenceCursor,
        GoogleBackfillRunReport, GoogleCalendarSyncSnapshot, GoogleScopeSet, OccurrenceRange,
    },
    ports::{
        CalendarBackfillRepository, CalendarEventChange, CalendarEventForwardSource,
        CalendarEventLabelReader, CalendarEventWrite, CalendarEventWriteOutcome,
        CalendarOccurrenceService, CalendarProviderError, CalendarProviderErrorKind,
        CalendarReauthNotifier, CalendarRepository, GoogleCalendarProvider,
        GoogleCalendarSyncRepository, GoogleEventSyncContext, RetiredCalendarEvent,
    },
};

/// Domain validation failures.
#[derive(Debug, thiserror::Error)]
pub enum CalendarValidationError {
    /// Event identity was missing.
    #[error("calendar event requires a non-empty owner and iCalendar UID")]
    MissingIdentity,
    /// Event end was not after its start.
    #[error("calendar event end must be after its start")]
    InvalidTime,
    /// A query range was invalid or too large.
    #[error(
        "calendar occurrence range must be positive, no larger than 370 days, and inside the materialized one-year-history/two-year-future window"
    )]
    InvalidRange,
    /// A page size was outside the supported bound.
    #[error("calendar repository query limit must be between 1 and 2001")]
    InvalidLimit,
    /// A mention preview batch exceeded the supported size.
    #[error("calendar mention previews accept at most {MENTION_PREVIEWS_MAX} events per request")]
    TooManyMentions,
}

/// The most mentioned events one preview request resolves.
pub const MENTION_PREVIEWS_MAX: usize = 100;

/// Calendar use cases with provider and persistence details behind ports.
pub struct CalendarService<R> {
    repository: R,
    team_sharing_enabled: bool,
}

impl<R> CalendarService<R>
where
    R: CalendarRepository,
{
    /// Construct the service.
    pub fn new(repository: R) -> Self {
        Self {
            repository,
            team_sharing_enabled: false,
        }
    }

    /// Enable legacy team status reads together with the team sharing rollout.
    pub fn with_team_sharing_enabled(mut self, enabled: bool) -> Self {
        self.team_sharing_enabled = enabled;
        self
    }

    /// Apply an OAuth grant using actual scopes returned by Google.
    ///
    /// The repository owns the transaction that increments the grant version
    /// and inserts the two idempotent backfill jobs. `intent` states whether
    /// the consent flow behind this grant explicitly asked for calendar
    /// access, which is what clears a standing calendar opt-out.
    #[tracing::instrument(skip(self, scopes), err)]
    pub async fn apply_google_grant(
        &self,
        email_link_id: Uuid,
        scopes: GoogleScopeSet,
        intent: CalendarGrantIntent,
    ) -> Result<AppliedGoogleGrant, Report> {
        self.repository
            .apply_google_grant(email_link_id, scopes, intent)
            .await
    }

    /// Query a bounded occurrence viewport.
    #[tracing::instrument(skip(self, requester_id, range), err)]
    pub async fn list_occurrences(
        &self,
        requester_id: &str,
        range: OccurrenceRange,
        cursor: Option<CalendarOccurrenceCursor>,
        limit: u16,
    ) -> Result<Vec<super::models::OccurrenceListing>, Report> {
        validate_query(&range, limit)?;
        let mut rows = self
            .repository
            .list_occurrences(requester_id, range, cursor, limit)
            .await?;
        if let Some(viewer) =
            ActorInboxes::from_owned(self.repository.owned_inboxes(requester_id).await?)
        {
            for listing in &mut rows {
                viewer.mark_event(&mut listing.event, listing.link_id);
                if let Some(attendees) = &mut listing.exception.attendees {
                    viewer.mark_attendees(attendees, listing.link_id);
                }
            }
        }
        Ok(rows)
    }

    /// Label events for a reader outside the calendar: one read of the
    /// requester's calendars and inboxes, whatever the number of events.
    #[tracing::instrument(
        name = "calendar.event_labels",
        skip(self, requester_id, event_ids),
        fields(event_count = event_ids.len()),
        err
    )]
    pub async fn event_labels(
        &self,
        requester_id: &str,
        event_ids: &[Uuid],
    ) -> Result<HashMap<Uuid, EventLabels>, Report> {
        if event_ids.is_empty() {
            return Ok(HashMap::new());
        }
        // One read at a time: search runs this on every keystroke with calendar
        // hits, and a burst of searches must not fan out across the read pool.
        let copies = self.repository.event_copies(event_ids).await?;
        let calendars = CalendarLabels::from_calendars(
            self.repository.list_visible_calendars(requester_id).await?,
        );
        let viewer = ActorInboxes::from_owned(self.repository.owned_inboxes(requester_id).await?);
        Ok(copies
            .into_iter()
            .map(|copy| {
                (
                    copy.event_id,
                    EventLabels::of(copy, viewer.as_ref(), &calendars),
                )
            })
            .collect())
    }

    /// Query teammates' out-of-office occurrences in a bounded viewport.
    ///
    /// Busy-only sharers' occurrences carry no title; only explicit detail
    /// sharing adds it, and `none` omits the sharer. Private and confidential
    /// events are omitted because even their out-of-office type would disclose
    /// metadata beyond a generic busy block. Provider copies synced through
    /// multiple connected inboxes collapse to one occurrence.
    #[tracing::instrument(skip(self, requester_id, range), err)]
    pub async fn list_team_out_of_office(
        &self,
        requester_id: &str,
        range: OccurrenceRange,
        limit: u16,
    ) -> Result<Vec<super::models::TeamOutOfOffice>, Report> {
        validate_query(&range, limit)?;
        if !self.team_sharing_enabled {
            return Ok(Vec::new());
        }
        let rows = self
            .repository
            .list_team_out_of_office(requester_id, range, limit)
            .await?;
        Ok(rows
            .into_iter()
            .map(|mut row| {
                if matches!(
                    row.visibility,
                    super::models::EventVisibility::Private
                        | super::models::EventVisibility::Confidential
                ) {
                    row.title = None;
                }
                row
            })
            .collect())
    }

    /// Return the aggregate ingestion state of the requester's visible accounts.
    #[tracing::instrument(skip(self, requester_id), err)]
    pub async fn sync_status(
        &self,
        requester_id: &str,
    ) -> Result<super::models::CalendarSyncStatus, Report> {
        self.repository.sync_status(requester_id).await
    }

    /// List every calendar visible to the requester.
    #[tracing::instrument(skip(self, requester_id), err)]
    pub async fn list_visible_calendars(
        &self,
        requester_id: &str,
    ) -> Result<Vec<super::models::VisibleCalendar>, Report> {
        self.repository.list_visible_calendars(requester_id).await
    }

    /// Resolve mentioned events to the requester's own projections.
    #[tracing::instrument(skip(self, requester_id, items), err)]
    pub async fn mention_previews(
        &self,
        requester_id: &str,
        items: Vec<super::models::CalendarMentionRequestItem>,
    ) -> Result<Vec<super::models::CalendarMentionPreview>, Report> {
        if items.len() > MENTION_PREVIEWS_MAX {
            return Err(rootcause::report!(CalendarValidationError::TooManyMentions).into());
        }
        if items.is_empty() {
            return Ok(Vec::new());
        }
        let mut previews = self
            .repository
            .mention_previews(requester_id, items.clone(), Utc::now())
            .await?;
        super::join_requests::annotate_join_state(
            &self.repository,
            requester_id,
            &items,
            &mut previews,
        )
        .await?;
        Ok(previews)
    }

    /// The IANA time zone of the requester's primary calendar.
    #[tracing::instrument(skip(self, requester_id), err)]
    pub async fn primary_time_zone(&self, requester_id: &str) -> Result<Option<String>, Report> {
        self.repository.primary_time_zone(requester_id).await
    }

    /// Every copy of `event_id`'s meeting the requester holds through one of
    /// their own inboxes.
    #[tracing::instrument(skip(self, requester_id), fields(copies), err)]
    pub async fn meeting_copies(
        &self,
        requester_id: &str,
        event_id: Uuid,
    ) -> Result<Vec<super::models::MeetingCopy>, Report> {
        let copies = self
            .repository
            .meeting_copies(requester_id, event_id)
            .await?;
        tracing::Span::current().record("copies", copies.len());
        Ok(copies)
    }

    /// Export an event the requester can see as an iCalendar document.
    #[tracing::instrument(skip(self, requester_id), err)]
    pub async fn event_ics(
        &self,
        requester_id: &str,
        event_id: Uuid,
    ) -> Result<Option<CalendarEventIcs>, Report> {
        let event = self.repository.event_export(requester_id, event_id).await?;
        Ok(event.map(|event| CalendarEventIcs {
            document: render_event_ics(&event, IcsPurpose::Share),
            title: event.title,
        }))
    }

    /// What a forward of the requester's own copy of an event to `invitees`
    /// sends, and that copy's inbox, which sends it. The copy decides the
    /// kind ([`ForwardedCopy::outside_organizer`]): an invitation naming
    /// `invitees` when its organizer is outside Google, else the
    /// shared-event file. Both carry the copy's join link. `None` unless
    /// `event_id` is a live copy held through one of the requester's own
    /// inboxes: a channel share or a delegated inbox's copy has no inbox of
    /// theirs to send from.
    ///
    /// [`ForwardedCopy::outside_organizer`]: super::ics::ForwardedCopy::outside_organizer
    #[tracing::instrument(
        skip(self, requester_id, invitees),
        fields(invitee_count = invitees.len(), kind = tracing::field::Empty),
        err
    )]
    pub async fn event_forward(
        &self,
        requester_id: &str,
        event_id: Uuid,
        invitees: &[IcsParticipant],
    ) -> Result<Option<CalendarEventForward>, Report> {
        let copies = self
            .repository
            .meeting_copies(requester_id, event_id)
            .await?;
        let Some(copy) = copies.into_iter().find(|copy| copy.event_id == event_id) else {
            return Ok(None);
        };
        let Some(event) = self
            .repository
            .event_export(requester_id, event_id)
            .await?
            .filter(|event| event.access == CalendarEventExportAccess::OwnCopy)
        else {
            return Ok(None);
        };
        let Some(forwarded) = self
            .repository
            .forwarded_copy(requester_id, event_id)
            .await?
        else {
            return Ok(None);
        };
        let kind = match forwarded.outside_organizer(&event) {
            Some(organizer) => CalendarEventForwardKind::Invitation { organizer },
            None => CalendarEventForwardKind::EventFile,
        };
        tracing::Span::current().record("kind", kind.as_str());
        let purpose = IcsPurpose::Forward {
            join_link: forwarded.join_link.as_ref(),
            invitees: matches!(kind, CalendarEventForwardKind::Invitation { .. })
                .then_some(invitees),
        };
        Ok(Some(CalendarEventForward {
            ics: CalendarEventIcs {
                document: render_event_ics(&event, purpose),
                title: event.title,
            },
            inbox: copy.inbox,
            kind,
        }))
    }

    /// Re-arm the watched inbox's sync job for a push notification whose
    /// channel token the adapter already verified. Returns whether the
    /// notification matched an active channel.
    #[tracing::instrument(skip(self, channel_id, resource_id), err)]
    pub async fn handle_watch_notification(
        &self,
        channel_id: &str,
        resource_id: &str,
    ) -> Result<bool, Report> {
        let Some(email_link_id) = self
            .repository
            .find_watch_target(channel_id, resource_id)
            .await?
        else {
            return Ok(false);
        };
        self.repository
            .schedule_google_sync_for_link(email_link_id)
            .await?;
        Ok(true)
    }
}

impl<R> CalendarEventForwardSource for CalendarService<R>
where
    R: CalendarRepository,
{
    fn event_forward(
        &self,
        requester_id: &str,
        event_id: Uuid,
        invitees: &[IcsParticipant],
    ) -> impl Future<Output = Result<Option<CalendarEventForward>, Report>> + Send {
        CalendarService::event_forward(self, requester_id, event_id, invitees)
    }
}

impl<R> CalendarEventLabelReader for CalendarService<R>
where
    R: CalendarRepository,
{
    fn event_labels<'a>(
        &'a self,
        requester_id: &'a str,
        event_ids: &'a [Uuid],
    ) -> BoxFuture<'a, Result<HashMap<Uuid, EventLabels>, Report>> {
        Box::pin(CalendarService::event_labels(self, requester_id, event_ids))
    }
}

impl<R> CalendarOccurrenceService for CalendarService<R>
where
    R: CalendarRepository,
{
    fn list_occurrences(
        &self,
        requester_id: &str,
        range: OccurrenceRange,
        cursor: Option<CalendarOccurrenceCursor>,
        limit: u16,
    ) -> impl Future<Output = Result<Vec<super::models::OccurrenceListing>, Report>> + Send {
        CalendarService::list_occurrences(self, requester_id, range, cursor, limit)
    }

    fn sync_status(
        &self,
        requester_id: &str,
    ) -> impl Future<Output = Result<super::models::CalendarSyncStatus, Report>> + Send {
        CalendarService::sync_status(self, requester_id)
    }

    fn list_visible_calendars(
        &self,
        requester_id: &str,
    ) -> impl Future<Output = Result<Vec<super::models::VisibleCalendar>, Report>> + Send {
        CalendarService::list_visible_calendars(self, requester_id)
    }

    fn mention_previews(
        &self,
        requester_id: &str,
        items: Vec<super::models::CalendarMentionRequestItem>,
    ) -> impl Future<Output = Result<Vec<super::models::CalendarMentionPreview>, Report>> + Send
    {
        CalendarService::mention_previews(self, requester_id, items)
    }

    fn list_team_out_of_office(
        &self,
        requester_id: &str,
        range: OccurrenceRange,
        limit: u16,
    ) -> impl Future<Output = Result<Vec<super::models::TeamOutOfOffice>, Report>> + Send {
        CalendarService::list_team_out_of_office(self, requester_id, range, limit)
    }

    fn primary_time_zone(
        &self,
        requester_id: &str,
    ) -> impl Future<Output = Result<Option<String>, Report>> + Send {
        CalendarService::primary_time_zone(self, requester_id)
    }

    fn meeting_copies(
        &self,
        requester_id: &str,
        event_id: Uuid,
    ) -> impl Future<Output = Result<Vec<super::models::MeetingCopy>, Report>> + Send {
        CalendarService::meeting_copies(self, requester_id, event_id)
    }

    fn event_ics(
        &self,
        requester_id: &str,
        event_id: Uuid,
    ) -> impl Future<Output = Result<Option<CalendarEventIcs>, Report>> + Send {
        CalendarService::event_ics(self, requester_id, event_id)
    }
}

/// Orchestrates a Google account backfill while keeping HTTP and SQL behind ports.
pub struct GoogleCalendarBackfillService<R, G, B> {
    repository: R,
    provider: G,
    macro_event_broker: B,
    watch: Option<super::models::GoogleWatchConfig>,
}

/// Periodically makes completed provider jobs eligible for another incremental poll.
pub struct GoogleCalendarSyncScheduler<R> {
    repository: R,
}

/// How long a backfill job may sit off the queue — pending after a delivery
/// dead-lettered, or running behind a dead worker's lease — before the reaper
/// republishes it. Comfortably past the SQS retry budget so an actively
/// retrying delivery is never duplicated.
const WEDGED_SYNC_STALL_THRESHOLD: chrono::Duration = chrono::Duration::minutes(15);

impl<R> GoogleCalendarSyncScheduler<R>
where
    R: GoogleCalendarSyncRepository,
{
    /// Construct the scheduler from its persistence port.
    pub fn new(repository: R) -> Self {
        Self { repository }
    }

    /// Schedule current-grant accounts that have not been polled recently.
    #[tracing::instrument(skip(self), err)]
    pub async fn run_once(&self, now: chrono::DateTime<Utc>) -> Result<usize, Report> {
        self.repository
            .schedule_due_google_syncs(now - chrono::Duration::minutes(5))
            .await
    }

    /// Re-arm jobs stranded off the queue by a dead-lettered delivery or a
    /// dead worker's lease, so they recover without a grant change.
    #[tracing::instrument(skip(self), err)]
    pub async fn reap_once(&self, now: chrono::DateTime<Utc>) -> Result<usize, Report> {
        self.repository
            .reap_wedged_google_syncs(now - WEDGED_SYNC_STALL_THRESHOLD)
            .await
    }
}

/// Applies terminal Google Calendar failures that happen before lease claim.
pub struct GoogleCalendarBackfillFailureService<L> {
    lifecycle: L,
}

impl<L> GoogleCalendarBackfillFailureService<L>
where
    L: CalendarBackfillRepository,
{
    /// Construct the failure application service from its persistence port.
    pub fn new(lifecycle: L) -> Self {
        Self { lifecycle }
    }

    /// Atomically terminate an unclaimed job and update its account and inbox health.
    #[tracing::instrument(skip(self, message), err)]
    pub async fn fail_unclaimed(
        &self,
        key: CalendarBackfillJobKey,
        disposition: CalendarBackfillFailureDisposition,
        message: &str,
    ) -> Result<CalendarBackfillFailureOutcome, Report> {
        if disposition == CalendarBackfillFailureDisposition::Retry {
            return Err(rootcause::report!(
                "unclaimed Google Calendar failures must be terminal"
            ));
        }
        self.lifecycle
            .fail_unclaimed_google_backfill(key, disposition, message)
            .await
    }
}

/// Queue-visible outcome of executing a fenced Google Calendar backfill.
#[derive(Debug, thiserror::Error)]
pub enum GoogleCalendarBackfillRunError {
    /// Another delivery owns the durable lease.
    #[error("Google Calendar backfill is already leased")]
    Busy,
    /// The durable job does not exist for the supplied inbox.
    #[error("Google Calendar backfill job was not found")]
    NotFound,
    /// The job previously ended with a permanent failure.
    #[error("Google Calendar backfill is already failed")]
    AlreadyFailed,
    /// Lease ownership was lost while provider work was running.
    #[error("Google Calendar backfill lease was lost")]
    LeaseLost,
    /// The provider grant must be refreshed by the user.
    #[error("Google Calendar grant requires reauthorization: {message}")]
    ReauthRequired {
        /// Provider failure detail.
        message: String,
        /// Whether this failure consumed the inbox's healthy-to-reauth edge.
        link_reauth_transitioned: bool,
    },
    /// Google rejected the request permanently.
    #[error("Google Calendar rejected the backfill request: {0}")]
    Permanent(String),
    /// The job can be retried without user action.
    #[error("Google Calendar backfill failed transiently: {0}")]
    Retryable(String),
}

/// Application service that owns Google backfill claim, lease, and terminal policy.
pub struct GoogleCalendarBackfillCoordinator<R, G, L, B> {
    repository: R,
    provider: G,
    lifecycle: L,
    macro_event_broker: B,
    watch: Option<super::models::GoogleWatchConfig>,
}

impl<R, G, L, B> GoogleCalendarBackfillCoordinator<R, G, L, B>
where
    R: CalendarRepository + Clone,
    G: GoogleCalendarProvider + Clone,
    L: CalendarBackfillRepository,
    B: MacroEventBroker + Clone,
{
    /// Construct a coordinator from domain ports; supplying a watch config
    /// makes every backfill maintain push notification channels.
    pub fn new(
        repository: R,
        provider: G,
        lifecycle: L,
        macro_event_broker: B,
        watch: Option<super::models::GoogleWatchConfig>,
    ) -> Self {
        Self {
            repository,
            provider,
            lifecycle,
            macro_event_broker,
            watch,
        }
    }

    /// Execute one idempotent queue delivery under a fenced renewable lease.
    ///
    /// `report` accumulates durable progress and remains meaningful on
    /// failure: per-calendar commits that landed before the error survive
    /// the retry, so callers should act on the report either way.
    #[tracing::instrument(skip(self, owner_id, access_token, range, report), fields(job_id = %key.job_id), err)]
    pub async fn run(
        &self,
        key: CalendarBackfillJobKey,
        owner_id: &str,
        access_token: &str,
        range: OccurrenceRange,
        report: &mut GoogleBackfillRunReport,
    ) -> Result<(), GoogleCalendarBackfillRunError> {
        let (lease_token, account_id) = match self
            .lifecycle
            .claim_google_backfill(key)
            .await
            .map_err(|error| GoogleCalendarBackfillRunError::Retryable(format!("{error:?}")))?
        {
            CalendarBackfillClaim::Claimed {
                lease_token,
                account_id,
            } => (lease_token, account_id),
            CalendarBackfillClaim::Complete => return Ok(()),
            CalendarBackfillClaim::Busy => return Err(GoogleCalendarBackfillRunError::Busy),
            CalendarBackfillClaim::Failed => {
                return Err(GoogleCalendarBackfillRunError::AlreadyFailed);
            }
            CalendarBackfillClaim::NotFound => {
                return Err(GoogleCalendarBackfillRunError::NotFound);
            }
        };

        if let Err(error) = self
            .lifecycle
            .mark_google_account_syncing(key, lease_token)
            .await
        {
            let message = format!("{error:?}");
            self.persist_failure(
                key,
                lease_token,
                CalendarBackfillFailureDisposition::Retry,
                &message,
            )
            .await?;
            return Err(GoogleCalendarBackfillRunError::Retryable(message));
        }

        let backfill = GoogleCalendarBackfillService::new(
            self.repository.clone(),
            self.provider.clone(),
            self.macro_event_broker.clone(),
            self.watch.clone(),
        );
        let work = backfill.backfill(
            key,
            lease_token,
            account_id,
            owner_id,
            access_token,
            range,
            report,
        );
        let lease = self
            .lifecycle
            .maintain_google_backfill_lease(key, lease_token);
        futures::pin_mut!(work);
        futures::pin_mut!(lease);
        let result = match select(work, lease).await {
            Either::Left((result, _lease)) => result,
            Either::Right((_lease_result, _work)) => {
                return Err(GoogleCalendarBackfillRunError::LeaseLost);
            }
        };

        match result {
            Ok(()) => {
                self.lifecycle
                    .complete_google_backfill(key, lease_token)
                    .await
                    .map_err(|_| GoogleCalendarBackfillRunError::LeaseLost)?;
                Ok(())
            }
            Err(error) => {
                let provider_error = error
                    .as_ref()
                    .downcast_current_context::<CalendarProviderError>();
                let disposition = match provider_error.map(CalendarProviderError::kind) {
                    Some(CalendarProviderErrorKind::ReauthRequired) => {
                        CalendarBackfillFailureDisposition::CalendarPermissionRequired
                    }
                    Some(
                        CalendarProviderErrorKind::Permanent
                        | CalendarProviderErrorKind::PushUnsupported,
                    ) => CalendarBackfillFailureDisposition::Permanent,
                    Some(
                        CalendarProviderErrorKind::Transient
                        | CalendarProviderErrorKind::SyncTokenExpired,
                    )
                    | None => CalendarBackfillFailureDisposition::Retry,
                };
                let message = format!("{error:?}");
                let outcome = self
                    .persist_failure(key, lease_token, disposition, &message)
                    .await?;
                Err(match disposition {
                    CalendarBackfillFailureDisposition::ReauthRequired
                    | CalendarBackfillFailureDisposition::CalendarPermissionRequired => {
                        GoogleCalendarBackfillRunError::ReauthRequired {
                            message,
                            link_reauth_transitioned: outcome.link_reauth_transitioned,
                        }
                    }
                    CalendarBackfillFailureDisposition::Permanent => {
                        GoogleCalendarBackfillRunError::Permanent(message)
                    }
                    CalendarBackfillFailureDisposition::Retry => {
                        GoogleCalendarBackfillRunError::Retryable(message)
                    }
                })
            }
        }
    }

    async fn persist_failure(
        &self,
        key: CalendarBackfillJobKey,
        lease_token: Uuid,
        disposition: CalendarBackfillFailureDisposition,
        message: &str,
    ) -> Result<CalendarBackfillFailureOutcome, GoogleCalendarBackfillRunError> {
        self.lifecycle
            .fail_google_backfill(key, lease_token, disposition, message)
            .await
            .map_err(|_| GoogleCalendarBackfillRunError::LeaseLost)
    }
}

/// Fires the reauth-required notification on exactly the healthy-to-reauth edge
/// a backfill failure consumed, and never on any other failure.
///
/// The edge is decided in the failure transaction, not here:
/// `link_reauth_transitioned` is `true` only when this failure was the one that
/// first flipped the inbox into needs-reauth, which only the `ReauthRequired`
/// disposition does — a `CalendarPermissionRequired` failure never sets it, so
/// a missing calendar scope on an otherwise healthy Gmail grant stays quiet.
/// This service owns only the policy that such a consumed edge is what warrants
/// a notification, forwarding it to the notifier port and leaving the single
/// notification implementation to email_service's link-manager consumer.
///
/// Best effort: a notifier failure is logged and swallowed. The failure the
/// notification describes is already durably recorded, so the caller's delivery
/// must still ack; a lost enqueue means that link never notifies, matching
/// email_service's own calendar branch rather than diverging from it.
pub struct CalendarReauthAnnouncer<N> {
    notifier: N,
}

impl<N> CalendarReauthAnnouncer<N>
where
    N: CalendarReauthNotifier,
{
    /// Construct the announcer over its notifier port.
    pub fn new(notifier: N) -> Self {
        Self { notifier }
    }

    /// Announce after an unclaimed job's terminal failure, iff that failure
    /// newly transitioned the inbox into needs-reauth.
    pub async fn announce_unclaimed(
        &self,
        email_link_id: Uuid,
        outcome: &CalendarBackfillFailureOutcome,
    ) {
        if outcome.link_reauth_transitioned {
            self.fire(email_link_id).await;
        }
    }

    /// Announce after a fenced run failed, iff the failure was a grant
    /// reauthorization failure that newly transitioned the inbox into
    /// needs-reauth. Every other run error — including a `ReauthRequired`
    /// carrying `link_reauth_transitioned: false`, which a
    /// `CalendarPermissionRequired` disposition or a lost race produces — stays
    /// quiet.
    pub async fn announce_run_error(
        &self,
        email_link_id: Uuid,
        error: &GoogleCalendarBackfillRunError,
    ) {
        if let GoogleCalendarBackfillRunError::ReauthRequired {
            link_reauth_transitioned: true,
            ..
        } = error
        {
            self.fire(email_link_id).await;
        }
    }

    async fn fire(&self, email_link_id: Uuid) {
        if let Err(error) = self.notifier.notify_reauth_required(email_link_id).await {
            tracing::warn!(
                ?error,
                %email_link_id,
                "failed to enqueue calendar reauth-required notification"
            );
        }
    }
}

impl<R, G, B> GoogleCalendarBackfillService<R, G, B>
where
    R: CalendarRepository,
    G: GoogleCalendarProvider,
    B: MacroEventBroker,
{
    /// Construct the provider backfill service.
    pub fn new(
        repository: R,
        provider: G,
        macro_event_broker: B,
        watch: Option<super::models::GoogleWatchConfig>,
    ) -> Self {
        Self {
            repository,
            provider,
            macro_event_broker,
            watch,
        }
    }

    /// Publish one calendar topic event. Sync progress is already committed by
    /// the time this runs, so a publish failure is logged and dropped rather
    /// than failing the run — the search backfill re-enumerates present rows.
    fn publish_calendar_event(&self, event: CalendarTopicEvent) {
        let _ = self
            .macro_event_broker
            .send_event(&CalendarMacroEvent::for_change(event))
            .inspect_err(|error| {
                tracing::error!(error=?error, "failed to publish calendar event");
            });
    }

    /// Announce what a write did to the canonical row. A write that changed
    /// nothing publishes nothing, so a full snapshot re-observing thousands of
    /// unchanged events stays off the topic.
    fn publish_write_outcome(&self, outcome: &CalendarEventWriteOutcome) {
        let metadata = CalendarEventMetadata {
            event_id: outcome.event_id,
            owner_id: outcome.owner_id.clone(),
        };
        match outcome.change {
            CalendarEventChange::Created => {
                self.publish_calendar_event(CalendarTopicEvent::Created(metadata));
            }
            CalendarEventChange::Updated => {
                self.publish_calendar_event(CalendarTopicEvent::Updated(metadata));
            }
            CalendarEventChange::Unchanged => {}
        }
    }

    /// Announce every event a source retirement touched. Retiring a source
    /// does not necessarily remove the event — the row survives, rewritten
    /// from its next-best remaining source — so each event reports its own
    /// fate. Without this a provider-side deletion would leave a permanently
    /// stale search document: the row is gone, so the backfill can never
    /// re-enumerate it.
    fn publish_retirements(&self, retired: Vec<RetiredCalendarEvent>) {
        for event in retired {
            let metadata = CalendarEventMetadata {
                event_id: event.event_id,
                owner_id: event.owner_id,
            };
            self.publish_calendar_event(if event.deleted {
                CalendarTopicEvent::Deleted(metadata)
            } else {
                CalendarTopicEvent::Updated(metadata)
            });
        }
    }

    /// Fetch and reconcile calendars and events for a connected inbox.
    ///
    /// Progress accumulates into `report` as each calendar commits, so a
    /// caller observes durable partial progress even when a later calendar
    /// fails the run: those commits survive the retry, whose quiet re-run
    /// would never report them again.
    #[allow(clippy::too_many_arguments)]
    #[tracing::instrument(skip(self, owner_id, access_token, range, report), err)]
    pub async fn backfill(
        &self,
        key: CalendarBackfillJobKey,
        lease_token: Uuid,
        account_id: Uuid,
        owner_id: &str,
        access_token: &str,
        range: OccurrenceRange,
        report: &mut GoogleBackfillRunReport,
    ) -> Result<(), Report> {
        if !range.is_valid_for_backfill() {
            return Err(rootcause::report!(CalendarValidationError::InvalidRange).into());
        }
        let calendars = self
            .provider
            .list_calendars(access_token, key.email_link_id)
            .await
            .map_err(|error| -> Report { rootcause::report!(error).into() })?;
        let mut calendar_ids = Vec::with_capacity(calendars.len());
        // One calendar's provider failure is recorded and skipped rather than
        // failing the account. The run fails only when no calendar is healthy,
        // so the coordinator can still classify a wholesale outage.
        let mut any_calendar_healthy = false;
        let mut isolated_failures: Vec<(Uuid, String)> = Vec::new();
        let mut last_isolated_error: Option<CalendarProviderError> = None;

        for provider_calendar in calendars {
            let provider_calendar_id = provider_calendar.provider_calendar_id.clone();
            let watch_provider_calendar_id = provider_calendar.provider_calendar_id.clone();
            let observed_access_role = provider_calendar.access_role.clone();
            let is_read_only = !matches!(
                provider_calendar.access_role.as_deref(),
                Some("owner" | "writer")
            );
            let stored_calendar = self
                .repository
                .upsert_google_calendar(key, lease_token, account_id, provider_calendar)
                .await?;
            let calendar_id = stored_calendar.id;
            report.team_ooo_changed |= stored_calendar.team_ooo_changed;
            calendar_ids.push(calendar_id);
            if super::models::is_system_calendar(&provider_calendar_id)
                && stored_calendar.synced_at.is_some_and(|synced_at| {
                    synced_at > Utc::now() - super::models::SYSTEM_CALENDAR_SYNC_INTERVAL
                })
            {
                any_calendar_healthy = true;
                continue;
            }
            let plan = stored_calendar.sync_plan(&range);
            let batch = match self
                .provider
                .sync_events(
                    access_token,
                    GoogleEventSyncContext {
                        target: super::models::ProviderCalendarTarget {
                            binding: None,
                            provider: super::models::CalendarProvider::Google,
                            owner_id: owner_id.to_string(),
                            email_link_id: key.email_link_id,
                            account_id,
                            calendar_id,
                            provider_calendar_id,
                            observed_access_role,
                            is_read_only,
                            range: range.clone(),
                        },
                        sync_token: stored_calendar.sync_token.clone(),
                        plan,
                    },
                )
                .await
                .and_then(|batch| {
                    // Coverage is trustworthy only if every normalized event
                    // is usable. Reject before committing any part of this
                    // calendar so its token cannot skip an omitted event.
                    for upsert in &batch.upserts {
                        validate_upsert(upsert).map_err(|error| {
                            tracing::warn!(
                                error=?error,
                                calendar_id=%calendar_id,
                                ical_uid=%upsert.event.ical_uid,
                                "rejecting incomplete normalized Google Calendar batch"
                            );
                            CalendarProviderError::new(
                                CalendarProviderErrorKind::Transient,
                                "Google Calendar returned an invalid normalized event",
                            )
                        })?;
                    }
                    Ok(batch)
                }) {
                Ok(batch) => batch,
                Err(error) => {
                    // A bad or insufficient grant is account-wide, not
                    // calendar-local: surface it immediately so the coordinator
                    // prompts reauthorization rather than marking the account
                    // ready off the calendars that happened to sync.
                    if error.kind() == CalendarProviderErrorKind::ReauthRequired {
                        return Err(rootcause::report!(error).into());
                    }
                    tracing::warn!(
                        error=?error,
                        calendar_id=%calendar_id,
                        "isolating a failed Google Calendar and continuing the account sync"
                    );
                    isolated_failures.push((calendar_id, error.message().to_owned()));
                    report.team_ooo_changed = true;
                    // A retryable failure outranks a permanent one so a total
                    // failure still surfaces as retryable.
                    last_isolated_error = Some(match last_isolated_error {
                        Some(previous)
                            if previous.kind() != CalendarProviderErrorKind::Permanent =>
                        {
                            previous
                        }
                        _ => error,
                    });
                    continue;
                }
            };
            any_calendar_healthy = true;
            let mut calendar_count = 0;
            for upsert in batch.upserts {
                let source = upsert.source.details();
                debug_assert_eq!(source.calendar_id, calendar_id);
                let outcome = self
                    .repository
                    .upsert_event(CalendarEventWrite::GoogleBackfill {
                        key,
                        lease_token,
                        upsert,
                    })
                    .await?;
                self.publish_write_outcome(&outcome);
                report.team_ooo_changed |= outcome.team_ooo_changed;
                report.aligned_copies.extend(outcome.aligned_copies);
                calendar_count += 1;
            }
            // The upserts above committed individually, so they count even
            // if this calendar's snapshot commit below fails.
            report.events_upserted += calendar_count;
            let cancellation_count = batch.cancelled_provider_event_ids.len();
            // Committing per calendar keeps earlier calendars' sync tokens
            // durable when a later calendar's poll fails, so the retry only
            // re-pulls what never committed.
            let retired = self
                .repository
                .commit_google_calendar_sync(
                    key,
                    lease_token,
                    account_id,
                    GoogleCalendarSyncSnapshot {
                        calendar_id,
                        next_sync_token: batch.next_sync_token,
                        observed_provider_event_ids: batch.observed_provider_event_ids,
                        materialized_range: batch.materialized_range,
                        cancelled_provider_event_ids: batch.cancelled_provider_event_ids,
                    },
                    calendar_count,
                )
                .await?;
            // A provider-side deletion reaches search only here: the row is
            // gone once the commit lands, so nothing downstream can rediscover
            // it by re-reading Postgres.
            report.events_retired += retired.len();
            report.team_ooo_changed |= retired.iter().any(|event| event.team_ooo_changed);
            self.publish_retirements(retired);
            // Tombstones only apply inside the snapshot commit, so they
            // count once it succeeds.
            report.cancellations_observed += cancellation_count;

            // Channel upkeep is best-effort: the poll remains the backstop,
            // so a failed watch call must not fail the sync that just
            // committed durable progress.
            if let Some(watch) = &self.watch
                && stored_calendar.needs_watch_renewal(Utc::now())
            {
                let channel_id = Uuid::new_v4();
                match self
                    .provider
                    .watch_calendar(
                        access_token,
                        key.email_link_id,
                        &watch_provider_calendar_id,
                        channel_id,
                        watch,
                    )
                    .await
                {
                    Ok(channel) => {
                        self.repository
                            .record_watch_channel(
                                key,
                                lease_token,
                                account_id,
                                calendar_id,
                                channel,
                            )
                            .await
                            .inspect_err(|error| {
                                tracing::warn!(
                                    error=?error,
                                    calendar_id=%calendar_id,
                                    "failed to record Google Calendar watch channel"
                                );
                            })
                            .ok();
                    }
                    Err(error) if error.kind() == CalendarProviderErrorKind::PushUnsupported => {
                        tracing::info!(
                            calendar_id=%calendar_id,
                            "Google Calendar does not support push for this calendar; relying on polling"
                        );
                        self.repository
                            .record_watch_unsupported(key, lease_token, account_id, calendar_id)
                            .await
                            .inspect_err(|error| {
                                tracing::warn!(
                                    error=?error,
                                    calendar_id=%calendar_id,
                                    "failed to record unsupported Google Calendar watch"
                                );
                            })
                            .ok();
                    }
                    Err(error) => {
                        tracing::warn!(
                            error=?error,
                            calendar_id=%calendar_id,
                            "failed to open Google Calendar watch channel"
                        );
                    }
                }
            }
        }

        // No calendar is healthy: a wholesale outage the coordinator classifies
        // for retry. The account-level failure carries it, so no calendar is
        // badged for it.
        if !any_calendar_healthy && let Some(error) = last_isolated_error {
            return Err(rootcause::report!(error).into());
        }

        // Record each isolated failure for the settings badge, leaving the
        // calendar's sync state untouched so the next poll retries it. This
        // write must succeed before the account can report healthy coverage.
        for (calendar_id, message) in isolated_failures {
            self.repository
                .record_google_calendar_sync_error(
                    key,
                    lease_token,
                    account_id,
                    calendar_id,
                    &message,
                )
                .await?;
        }

        // A calendar dropped from the provider's list retires its sources, so
        // the events it backed announce their own fate here too.
        let retired = self
            .repository
            .reconcile_google_calendar_list(key, lease_token, account_id, calendar_ids)
            .await?;
        report.events_retired += retired.len();
        report.team_ooo_changed |= retired.iter().any(|event| event.team_ooo_changed);
        self.publish_retirements(retired);

        Ok(())
    }
}

fn validate_upsert(upsert: &CalendarEventUpsert) -> Result<(), Report> {
    if upsert.event.owner_id.trim().is_empty() || upsert.event.ical_uid.trim().is_empty() {
        return Err(rootcause::report!(CalendarValidationError::MissingIdentity).into());
    }
    if !upsert.event.time.is_valid()
        || upsert
            .occurrences
            .iter()
            .any(|occurrence| !occurrence.time.is_valid())
        || upsert
            .overrides
            .iter()
            .any(|event_override| !event_override.time.is_valid())
    {
        return Err(rootcause::report!(CalendarValidationError::InvalidTime).into());
    }
    Ok(())
}

fn validate_query(range: &OccurrenceRange, limit: u16) -> Result<(), Report> {
    if !range.is_valid() || !range.is_materialized_at(Utc::now()) {
        return Err(rootcause::report!(CalendarValidationError::InvalidRange).into());
    }
    // One extra row lets the HTTP adapter report truncation accurately while
    // preserving its public maximum page size of 2,000.
    if !(1..=2001).contains(&limit) {
        return Err(rootcause::report!(CalendarValidationError::InvalidLimit).into());
    }
    Ok(())
}

#[cfg(test)]
mod test;