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.

20.0 KB
Raw Blame
//! Calendar-service HTTP adapter for the calendar mutation port.
//!
//! The calendar service is the calendar write authority: it holds the Google
//! provider client, token minting, and the per-inbox request gate. Hosts
//! that expose calendar mutations without those dependencies (the AI tool
//! hosts) implement [`CalendarMutationService`] through this client, so
//! every mutation flows through the same routes, validation, and error
//! mapping as user-initiated ones.
//!
//! The base URL points at the calendar service's `/calendar` gateway prefix,
//! so the request paths here are exactly the routes
//! [`crate::inbound::mutation_router::calendar_mutation_router`] serves
//! (`/calendars`, `/events`, `/events/{id}`, `/events/{id}/rsvp`).

#[cfg(all(test, feature = "inbound"))]
mod test;

use reqwest::StatusCode;
use serde::Deserialize;
use uuid::Uuid;

use crate::domain::{
    meeting_links::{CreateEventWithMacroCallError, MeetingLinkError},
    models::{
        AttendeeResponseStatus, CalendarAttendeeInput, CalendarEvent, CalendarEventDraft,
        CalendarEventPatch, VisibleCalendar,
    },
    ports::{
        CalendarDeletionScope, CalendarMacroCallService, CalendarMutationError,
        CalendarMutationService, CalendarRsvpScope, CalendarUpdateScope,
    },
};

/// Header carrying the shared key for internal service authorization.
const INTERNAL_API_KEY_HEADER: &str = "x-internal-auth-key";
/// Header carrying the acting Macro user for internal authorization.
const INTERNAL_MACRO_USER_ID_HEADER: &str = "x-internal-macro-user-id";

/// Calendar mutation client calling the calendar service with internal
/// authorization on behalf of the requesting user.
pub struct CalendarServiceMutations {
    base_url: String,
    internal_api_key: String,
    http: reqwest::Client,
}

impl CalendarServiceMutations {
    /// Construct the client for the calendar service at `base_url`.
    pub fn new(base_url: String, internal_api_key: String) -> Self {
        Self {
            base_url: base_url.trim_end_matches('/').to_string(),
            internal_api_key,
            http: reqwest::Client::builder()
                .timeout(std::time::Duration::from_secs(30))
                .build()
                .expect("static reqwest client configuration is valid"),
        }
    }

    fn request(
        &self,
        method: reqwest::Method,
        path: &str,
        requester_id: &str,
    ) -> reqwest::RequestBuilder {
        self.http
            .request(method, format!("{}{path}", self.base_url))
            .header(INTERNAL_API_KEY_HEADER, &self.internal_api_key)
            .header(INTERNAL_MACRO_USER_ID_HEADER, requester_id)
    }

    /// Send the request, keeping an error response's status and body for
    /// the caller to classify.
    async fn send_raw(
        &self,
        request: reqwest::RequestBuilder,
    ) -> Result<reqwest::Response, ResponseFailure> {
        let response = request.send().await.map_err(|error| {
            ResponseFailure::Transport(format!(
                "calendar mutation request failed to reach the calendar service: {error}"
            ))
        })?;
        let status = response.status();
        if status.is_success() {
            return Ok(response);
        }
        Err(ResponseFailure::Status(status, response.text().await.ok()))
    }

    async fn send(
        &self,
        request: reqwest::RequestBuilder,
    ) -> Result<reqwest::Response, CalendarMutationError> {
        self.send_raw(request)
            .await
            .map_err(|failure| match failure {
                ResponseFailure::Transport(message) => CalendarMutationError::Retryable(message),
                ResponseFailure::Status(status, body) => error_from_response(status, body),
            })
    }

    async fn event_from(
        &self,
        request: reqwest::RequestBuilder,
    ) -> Result<CalendarEvent, CalendarMutationError> {
        parse_event(self.send(request).await?).await
    }
}

/// A request that produced no successful response.
enum ResponseFailure {
    /// The calendar service could not be reached.
    Transport(String),
    /// The calendar service answered with an error status and body.
    Status(StatusCode, Option<String>),
}

/// Parse the event echo of a successful mutation response.
async fn parse_event(response: reqwest::Response) -> Result<CalendarEvent, CalendarMutationError> {
    response.json::<CalendarEvent>().await.map_err(|error| {
        CalendarMutationError::PersistFailed(format!(
            "calendar mutation succeeded but its echo could not be parsed: {error}"
        ))
    })
}

/// Wire body for the calendars listing.
#[derive(Deserialize)]
struct ListCalendarsWire {
    calendars: Vec<VisibleCalendar>,
}

/// Wire body of a mutation error response.
#[derive(Deserialize)]
struct MutationErrorWire {
    code: String,
    message: String,
}

/// Map an error response to the domain failure its code encodes.
fn error_from_response(status: StatusCode, body: Option<String>) -> CalendarMutationError {
    let parsed = body
        .as_deref()
        .and_then(|body| serde_json::from_str::<MutationErrorWire>(body).ok());
    let Some(error) = parsed else {
        return fallback_error(
            status,
            format!(
                "the calendar service API returned status {status} with no mutation \
                 error body"
            ),
        );
    };
    match error.code.as_str() {
        "not_found" => CalendarMutationError::NotFound,
        "occurrence_not_found" => CalendarMutationError::OccurrenceNotFound,
        "read_only" => CalendarMutationError::ReadOnly,
        "no_writable_calendar" => CalendarMutationError::NoWritableCalendar,
        "not_attendee" => CalendarMutationError::NotAttendee,
        "not_organizer" => CalendarMutationError::NotOrganizer,
        "guests_cannot_invite" => CalendarMutationError::GuestsCannotInvite,
        "guest_list_hidden" => CalendarMutationError::GuestListHidden,
        "guests_cannot_modify" => CalendarMutationError::GuestsCannotModify,
        "already_on_calendar" => CalendarMutationError::AlreadyOnCalendar,
        "join_request_open" => CalendarMutationError::JoinRequestOpen,
        "copy_refused" => CalendarMutationError::CopyRefused(error.message),
        "snapshot" => CalendarMutationError::Snapshot,
        "invalid_input" => CalendarMutationError::InvalidInput(error.message),
        "reauth_required" => CalendarMutationError::ReauthRequired(error.message),
        "provider_rejected" => CalendarMutationError::ProviderRejected(error.message),
        "retryable" => CalendarMutationError::Retryable(error.message),
        "persist_failed" => CalendarMutationError::PersistFailed(error.message),
        _ => fallback_error(status, error.message),
    }
}

/// Classify an unrecognized failure by its status. Marking a client error
/// retryable would invite a duplicate non-idempotent write (a retried create
/// makes a second event and re-invites its attendees), so only statuses that
/// genuinely signal a transient condition stay [`CalendarMutationError::Retryable`].
fn fallback_error(status: StatusCode, message: String) -> CalendarMutationError {
    match status {
        StatusCode::NOT_FOUND => CalendarMutationError::NotFound,
        StatusCode::REQUEST_TIMEOUT | StatusCode::TOO_MANY_REQUESTS => {
            CalendarMutationError::Retryable(message)
        }
        _ if status.is_client_error() => CalendarMutationError::InvalidInput(message),
        _ => CalendarMutationError::Retryable(message),
    }
}

/// Map an error response of a create carrying a Macro call. The calendar
/// service reports a meeting it could not mint under its own code; every
/// other failure is the calendar write's.
fn macro_call_error_from_response(
    status: StatusCode,
    body: Option<String>,
) -> CreateEventWithMacroCallError {
    let parsed = body
        .as_deref()
        .and_then(|body| serde_json::from_str::<MutationErrorWire>(body).ok());
    match parsed {
        Some(error) if error.code == "macro_call_failed" => {
            CreateEventWithMacroCallError::MeetingLink(MeetingLinkError::Failed(error.message))
        }
        _ => CreateEventWithMacroCallError::Calendar(error_from_response(status, body)),
    }
}

/// Wire body for event creation, matching `CreateCalendarEventRequest`.
fn create_body(
    email_link_id: Option<Uuid>,
    calendar_id: Option<Uuid>,
    draft: &CalendarEventDraft,
    macro_call: bool,
) -> serde_json::Value {
    serde_json::json!({
        "emailLinkId": email_link_id,
        "calendarId": calendar_id,
        "title": draft.title,
        "description": draft.description,
        "location": draft.location,
        "time": draft.time,
        "attendees": attendees_body(&draft.attendees),
        "recurrenceLines": draft.recurrence_lines,
        "visibility": draft.visibility,
        "transparency": draft.transparency,
        "reminders": draft.reminders,
        "conference": draft.conference,
        "outOfOffice": draft.out_of_office,
        "guestPolicy": draft.guest_policy,
        "idempotencyKey": draft.idempotency_key,
        "macroCall": macro_call,
    })
}

/// Wire body for an event patch, matching `UpdateCalendarEventRequest`.
fn update_body(
    calendar_id: Option<Uuid>,
    patch: &CalendarEventPatch,
    scope: &CalendarUpdateScope,
) -> serde_json::Value {
    let (scope_name, recurrence_id) = match scope {
        CalendarUpdateScope::All => ("all", None),
        CalendarUpdateScope::ThisEvent { recurrence_id } => {
            ("this_event", Some(recurrence_id.as_str()))
        }
    };
    serde_json::json!({
        "calendarId": calendar_id,
        "title": patch.title,
        "description": patch.description,
        "location": patch.location,
        "time": patch.time,
        "attendees": patch
            .attendees
            .as_deref()
            .map(attendees_body),
        "recurrenceLines": patch.recurrence_lines,
        "visibility": patch.visibility,
        "transparency": patch.transparency,
        "reminders": patch.reminders,
        "conference": patch.conference,
        "outOfOffice": patch.out_of_office,
        "guestPolicy": patch.guest_policy,
        "scope": scope_name,
        "recurrenceId": recurrence_id,
    })
}

fn attendees_body(attendees: &[CalendarAttendeeInput]) -> Vec<serde_json::Value> {
    attendees
        .iter()
        .map(|attendee| {
            serde_json::json!({
                "email": attendee.email,
                "isOptional": attendee.is_optional,
            })
        })
        .collect()
}

/// Wire query for a deletion scope, matching `DeleteCalendarEventQuery`.
fn delete_query(
    calendar_id: Option<Uuid>,
    scope: &CalendarDeletionScope,
) -> Vec<(&'static str, String)> {
    let mut query = match scope {
        CalendarDeletionScope::All => vec![("scope", "all".to_string())],
        CalendarDeletionScope::ThisEvent { recurrence_id } => vec![
            ("scope", "this_event".to_string()),
            ("recurrenceId", recurrence_id.clone()),
        ],
        CalendarDeletionScope::ThisAndFollowing { recurrence_id } => vec![
            ("scope", "this_and_following".to_string()),
            ("recurrenceId", recurrence_id.clone()),
        ],
    };
    if let Some(calendar_id) = calendar_id {
        query.push(("calendarId", calendar_id.to_string()));
    }
    query
}

/// Wire body adding guests, matching `InviteCalendarEventGuestsRequest`.
fn invite_body(
    calendar_id: Option<Uuid>,
    guests: &[CalendarAttendeeInput],
    scope: &CalendarUpdateScope,
) -> serde_json::Value {
    let (scope_name, recurrence_id) = match scope {
        CalendarUpdateScope::All => ("all", None),
        CalendarUpdateScope::ThisEvent { recurrence_id } => {
            ("this_event", Some(recurrence_id.as_str()))
        }
    };
    let guests: Vec<serde_json::Value> = guests
        .iter()
        .map(|guest| {
            serde_json::json!({
                "email": guest.email,
                "optional": guest.is_optional,
            })
        })
        .collect();
    serde_json::json!({
        "calendarId": calendar_id,
        "guests": guests,
        "scope": scope_name,
        "recurrenceId": recurrence_id,
    })
}

/// Wire body for an RSVP, matching `RsvpCalendarEventRequest`.
fn rsvp_body(
    calendar_id: Option<Uuid>,
    response: AttendeeResponseStatus,
    scope: &CalendarRsvpScope,
    responding_email: Option<&str>,
) -> serde_json::Value {
    match scope {
        CalendarRsvpScope::All => serde_json::json!({
            "calendarId": calendar_id,
            "response": response,
            "respondingEmail": responding_email,
            "scope": "all",
        }),
        CalendarRsvpScope::ThisEvent { recurrence_id } => serde_json::json!({
            "calendarId": calendar_id,
            "response": response,
            "respondingEmail": responding_email,
            "scope": "this_event",
            "recurrenceId": recurrence_id,
        }),
    }
}

impl CalendarMacroCallService for CalendarServiceMutations {
    #[tracing::instrument(skip(self, requester_id, draft), err)]
    async fn create_event_with_macro_call(
        &self,
        requester_id: &str,
        email_link_id: Option<Uuid>,
        calendar_id: Option<Uuid>,
        draft: CalendarEventDraft,
    ) -> Result<CalendarEvent, CreateEventWithMacroCallError> {
        let response = self
            .send_raw(
                self.request(reqwest::Method::POST, "/events", requester_id)
                    .json(&create_body(email_link_id, calendar_id, &draft, true)),
            )
            .await
            .map_err(|failure| match failure {
                ResponseFailure::Transport(message) => {
                    CalendarMutationError::Retryable(message).into()
                }
                ResponseFailure::Status(status, body) => {
                    macro_call_error_from_response(status, body)
                }
            })?;
        parse_event(response).await.map_err(Into::into)
    }
}

impl CalendarMutationService for CalendarServiceMutations {
    #[tracing::instrument(skip(self, requester_id, draft), err)]
    async fn create_event(
        &self,
        requester_id: &str,
        email_link_id: Option<Uuid>,
        calendar_id: Option<Uuid>,
        draft: CalendarEventDraft,
    ) -> Result<CalendarEvent, CalendarMutationError> {
        self.event_from(
            self.request(reqwest::Method::POST, "/events", requester_id)
                .json(&create_body(email_link_id, calendar_id, &draft, false)),
        )
        .await
    }

    #[tracing::instrument(skip(self, requester_id), err)]
    async fn list_visible_calendars(
        &self,
        requester_id: &str,
    ) -> Result<Vec<VisibleCalendar>, CalendarMutationError> {
        self.send(self.request(reqwest::Method::GET, "/calendars", requester_id))
            .await?
            .json::<ListCalendarsWire>()
            .await
            .map(|wire| wire.calendars)
            .map_err(|error| {
                CalendarMutationError::Retryable(format!(
                    "the calendars listing could not be parsed: {error}"
                ))
            })
    }

    #[tracing::instrument(skip(self, requester_id, patch), err)]
    async fn update_event(
        &self,
        requester_id: &str,
        event_id: Uuid,
        calendar_id: Option<Uuid>,
        patch: CalendarEventPatch,
        scope: CalendarUpdateScope,
    ) -> Result<CalendarEvent, CalendarMutationError> {
        self.event_from(
            self.request(
                reqwest::Method::PATCH,
                &format!("/events/{event_id}"),
                requester_id,
            )
            .json(&update_body(calendar_id, &patch, &scope)),
        )
        .await
    }

    #[tracing::instrument(skip(self, requester_id), err)]
    async fn delete_event(
        &self,
        requester_id: &str,
        event_id: Uuid,
        calendar_id: Option<Uuid>,
        scope: CalendarDeletionScope,
    ) -> Result<(), CalendarMutationError> {
        self.send(
            self.request(
                reqwest::Method::DELETE,
                &format!("/events/{event_id}"),
                requester_id,
            )
            .query(&delete_query(calendar_id, &scope)),
        )
        .await
        .map(|_| ())
    }

    #[tracing::instrument(skip(self, requester_id, responding_email), err)]
    async fn respond_to_event(
        &self,
        requester_id: &str,
        event_id: Uuid,
        calendar_id: Option<Uuid>,
        response: AttendeeResponseStatus,
        scope: CalendarRsvpScope,
        responding_email: Option<String>,
    ) -> Result<CalendarEvent, CalendarMutationError> {
        self.event_from(
            self.request(
                reqwest::Method::PUT,
                &format!("/events/{event_id}/rsvp"),
                requester_id,
            )
            .json(&rsvp_body(
                calendar_id,
                response,
                &scope,
                responding_email.as_deref(),
            )),
        )
        .await
    }

    #[tracing::instrument(skip(self, requester_id, guests), err)]
    async fn invite_guests(
        &self,
        requester_id: &str,
        event_id: Uuid,
        calendar_id: Option<Uuid>,
        guests: Vec<CalendarAttendeeInput>,
        scope: CalendarUpdateScope,
    ) -> Result<CalendarEvent, CalendarMutationError> {
        self.event_from(
            self.request(
                reqwest::Method::POST,
                &format!("/events/{event_id}/guests"),
                requester_id,
            )
            .json(&invite_body(calendar_id, &guests, &scope)),
        )
        .await
    }

    #[tracing::instrument(skip(self, requester_id), err)]
    async fn copy_shared_event(
        &self,
        requester_id: &str,
        event_id: Uuid,
        calendar_id: Option<Uuid>,
    ) -> Result<CalendarEvent, CalendarMutationError> {
        self.event_from(
            self.request(
                reqwest::Method::POST,
                &format!("/events/{event_id}/copy"),
                requester_id,
            )
            .json(&serde_json::json!({ "calendarId": calendar_id })),
        )
        .await
    }

    #[tracing::instrument(skip(self, requester_id), err)]
    async fn respond_to_join_request(
        &self,
        requester_id: &str,
        request_id: Uuid,
        accept: bool,
    ) -> Result<crate::domain::join_requests::CalendarJoinRequest, CalendarMutationError> {
        self.send(
            self.request(
                reqwest::Method::PUT,
                &format!("/join-requests/{request_id}"),
                requester_id,
            )
            .json(&serde_json::json!({
                "decision": if accept { "accept" } else { "decline" },
            })),
        )
        .await?
        .json()
        .await
        .map_err(|error| {
            CalendarMutationError::PersistFailed(format!(
                "the join request was answered but its response could not be parsed: {error}"
            ))
        })
    }

    /// Not reachable over this transport. Disconnecting a calendar is part of
    /// an inbox's link lifecycle, served by the email service at
    /// `DELETE /email/links/{link_id}/calendar` (see
    /// `email_service::api::email::links::calendar`) — a route the calendar
    /// service does not mount, and one that stays on the email service after
    /// the calendar cutover. The AI-tool hosts that construct this client
    /// never disconnect calendars (the toolset exposes no such tool), so this
    /// arm exists only to satisfy [`CalendarMutationService`]; issuing the
    /// request against the calendar service base would 404. It returns a
    /// domain error instead of firing a request that cannot succeed.
    async fn disconnect_calendar(
        &self,
        _requester_id: &str,
        _email_link_id: Uuid,
    ) -> Result<(), CalendarMutationError> {
        Err(CalendarMutationError::InvalidInput(
            "disconnecting a calendar is not available through the calendar-service mutation \
             client; it is served by the email service's inbox link lifecycle"
                .to_string(),
        ))
    }
}