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.

feat(calendar): add GraphQL calendar mutations with typed error codes (#7690)

gbirman8f630fce5f63
diff --git a/crates/calendar_events/src/domain/changes.rs b/crates/calendar_events/src/domain/changes.rs
index 70f78abe20..157b09aadc 100644
--- a/crates/calendar_events/src/domain/changes.rs
+++ b/crates/calendar_events/src/domain/changes.rs
@@ -241,6 +241,15 @@ pub trait CalendarChangeQueryService: Send + Sync + 'static {
viewer: &str,
since: CalendarWatermark,
) -> impl Future<Output = Result<CalendarChangesPage, Report>> + Send;
+
+ /// The current state of one event with its complete set of visible
+ /// occurrences, or `None` when the viewer cannot see it or it has no
+ /// visible occurrence left.
+ fn event_change(
+ &self,
+ viewer: &str,
+ event_id: Uuid,
+ ) -> impl Future<Output = Result<Option<CalendarEventChange>, Report>> + Send;
}
/// Change-log reads with the delta policy applied.
@@ -341,16 +350,45 @@ impl<R: CalendarChangeRepository> CalendarChangeService<R> {
ActorInboxes::from_owned(self.repository.owned_inbox_emails(viewer).await?)
{
for change in &mut page.events {
- viewer.mark_attendees(&mut change.event.attendees);
- for instance in &mut change.occurrences {
- if let Some(attendees) = &mut instance.exception.attendees {
- viewer.mark_attendees(attendees);
- }
- }
+ mark_viewer_attendees(&viewer, change);
}
}
Ok(page)
}
+
+ /// The current state of one event with its complete set of visible
+ /// occurrences.
+ #[tracing::instrument(skip(self, viewer), err)]
+ pub async fn event_change(
+ &self,
+ viewer: &str,
+ event_id: Uuid,
+ ) -> Result<Option<CalendarEventChange>, Report> {
+ let Some(mut change) = self
+ .repository
+ .load_event_changes(viewer, &[event_id], MAX_DELTA_OCCURRENCES)
+ .await?
+ .events
+ .pop()
+ else {
+ return Ok(None);
+ };
+ if let Some(viewer) =
+ ActorInboxes::from_owned(self.repository.owned_inbox_emails(viewer).await?)
+ {
+ mark_viewer_attendees(&viewer, &mut change);
+ }
+ Ok(Some(change))
+ }
+}
+
+fn mark_viewer_attendees(viewer: &ActorInboxes, change: &mut CalendarEventChange) {
+ viewer.mark_attendees(&mut change.event.attendees);
+ for instance in &mut change.occurrences {
+ if let Some(attendees) = &mut instance.exception.attendees {
+ viewer.mark_attendees(attendees);
+ }
+ }
}
impl<R: CalendarChangeRepository> CalendarChangeQueryService for CalendarChangeService<R> {
@@ -368,6 +406,14 @@ impl<R: CalendarChangeRepository> CalendarChangeQueryService for CalendarChangeS
) -> impl Future<Output = Result<CalendarChangesPage, Report>> + Send {
CalendarChangeService::changes_since(self, viewer, since)
}
+
+ fn event_change(
+ &self,
+ viewer: &str,
+ event_id: Uuid,
+ ) -> impl Future<Output = Result<Option<CalendarEventChange>, Report>> + Send {
+ CalendarChangeService::event_change(self, viewer, event_id)
+ }
}
/// A client must reset when it fell behind retention on any link, or when a
diff --git a/crates/calendar_events/src/domain/changes/test.rs b/crates/calendar_events/src/domain/changes/test.rs
index 7174b744c1..9dac41ad6d 100644
--- a/crates/calendar_events/src/domain/changes/test.rs
+++ b/crates/calendar_events/src/domain/changes/test.rs
@@ -484,6 +484,22 @@ async fn nothing_is_hydrated_when_no_event_was_upserted() {
assert!(service.repository.loads.lock().unwrap().is_empty());
}
+#[tokio::test]
+async fn one_event_is_read_with_the_viewers_attendee_flags() {
+ let service = CalendarChangeService::new(FakeChanges {
+ events: HashMap::from([(id(1), event_change(id(1), LINK_A, 2))]),
+ owned_inboxes: vec!["[email protected]".to_owned()],
+ ..Default::default()
+ });
+
+ let change = service.event_change(VIEWER, id(1)).await.unwrap().unwrap();
+ let missing = service.event_change(VIEWER, id(2)).await.unwrap();
+
+ assert_eq!(change.occurrences.len(), 2);
+ assert!(change.event.attendees[0].is_self);
+ assert_eq!(missing, None);
+}
+
#[test]
fn a_duplicated_link_keeps_its_lowest_position() {
let watermark = since(&[(LINK_A, 7), (LINK_A, 3)]);
diff --git a/crates/complete_graph/src/schema.rs b/crates/complete_graph/src/schema.rs
index d1174bc326..c81e3cca8c 100644
--- a/crates/complete_graph/src/schema.rs
+++ b/crates/complete_graph/src/schema.rs
@@ -22,7 +22,7 @@ use graphql_activity::{
resolve_activity_feed, resolve_activity_overview, resolve_database_activity,
resolve_form_activity,
};
-use graphql_calendar::GraphqlCalendarQuery;
+use graphql_calendar::{CalendarMutationRoot, GraphqlCalendarQuery};
use graphql_channel::{
ChannelActivityAuthorizer, ChannelActivityMutationService, ChannelMutationRoot,
NoOpChannelActivityMutationService,
@@ -96,6 +96,7 @@ pub struct CompleteMutationRoot<
NotificationMutationRoot<N>,
GraphqlEmailMutation<ES, SoupEmailThreadMutationOutput<E>>,
InitiativeMutationRoot<E>,
+ CalendarMutationRoot,
);
impl<
@@ -119,6 +120,7 @@ impl<
NotificationMutationRoot::<N>::new(),
GraphqlEmailMutation::<ES, SoupEmailThreadMutationOutput<E>>::new(),
InitiativeMutationRoot::<E>::default(),
+ CalendarMutationRoot,
)
}
}
diff --git a/crates/complete_graph/src/schema/test/calendar.rs b/crates/complete_graph/src/schema/test/calendar.rs
index c975dc99ce..fce6df3b5c 100644
--- a/crates/complete_graph/src/schema/test/calendar.rs
+++ b/crates/complete_graph/src/schema/test/calendar.rs
@@ -146,6 +146,13 @@ impl CalendarChangeQueryService for RecordingCalendarReads {
..CalendarChangesPage::default()
})
}
+ async fn event_change(
+ &self,
+ _requester_id: &str,
+ _event_id: Uuid,
+ ) -> Result<Option<calendar_events::domain::changes::CalendarEventChange>, Report> {
+ Ok(None)
+ }
}
#[tokio::test]
@@ -212,3 +219,106 @@ async fn calendar_fields_fail_without_the_calendar_context() {
assert_eq!(response.errors.len(), 1);
}
+
+#[derive(Default)]
+struct RecordingCalendarMutations {
+ deleted: Mutex<Vec<(String, Uuid)>>,
+}
+
+impl calendar_events::domain::ports::CalendarMutationService for RecordingCalendarMutations {
+ async fn create_event(
+ &self,
+ _requester_id: &str,
+ _email_link_id: Option<Uuid>,
+ _calendar_id: Option<Uuid>,
+ _draft: calendar_events::domain::models::CalendarEventDraft,
+ ) -> Result<CalendarEvent, calendar_events::domain::ports::CalendarMutationError> {
+ unreachable!("only deletion is exercised")
+ }
+
+ async fn list_visible_calendars(
+ &self,
+ _requester_id: &str,
+ ) -> Result<Vec<VisibleCalendar>, calendar_events::domain::ports::CalendarMutationError> {
+ unreachable!("only deletion is exercised")
+ }
+
+ async fn update_event(
+ &self,
+ _requester_id: &str,
+ _event_id: Uuid,
+ _calendar_id: Option<Uuid>,
+ _patch: calendar_events::domain::models::CalendarEventPatch,
+ _scope: calendar_events::domain::ports::CalendarUpdateScope,
+ ) -> Result<CalendarEvent, calendar_events::domain::ports::CalendarMutationError> {
+ unreachable!("only deletion is exercised")
+ }
+
+ async fn delete_event(
+ &self,
+ requester_id: &str,
+ event_id: Uuid,
+ _calendar_id: Option<Uuid>,
+ _scope: calendar_events::domain::ports::CalendarDeletionScope,
+ ) -> Result<(), calendar_events::domain::ports::CalendarMutationError> {
+ self.deleted
+ .lock()
+ .unwrap()
+ .push((requester_id.to_owned(), event_id));
+ Ok(())
+ }
+
+ async fn respond_to_event(
+ &self,
+ _requester_id: &str,
+ _event_id: Uuid,
+ _calendar_id: Option<Uuid>,
+ _response: calendar_events::domain::models::AttendeeResponseStatus,
+ _scope: calendar_events::domain::ports::CalendarRsvpScope,
+ _responding_email: Option<String>,
+ ) -> Result<CalendarEvent, calendar_events::domain::ports::CalendarMutationError> {
+ unreachable!("only deletion is exercised")
+ }
+
+ async fn disconnect_calendar(
+ &self,
+ _requester_id: &str,
+ _email_link_id: Uuid,
+ ) -> Result<(), calendar_events::domain::ports::CalendarMutationError> {
+ unreachable!("only deletion is exercised")
+ }
+}
+
+#[tokio::test]
+async fn calendar_mutations_run_for_the_authenticated_viewer() {
+ let harness = harness();
+ let mutations = Arc::new(RecordingCalendarMutations::default());
+ let reads = Arc::new(RecordingCalendarReads::default());
+ let context =
+ graphql_calendar::CalendarGraphqlMutationContext::new(Arc::clone(&mutations), reads);
+
+ let response = harness
+ .schema
+ .execute(
+ harness
+ .request(
+ &format!(
+ r#"mutation {{ deleteCalendarEvent(input: {{ eventId: "{EVENT_ID}" }}) {{ deletedEventId }} }}"#
+ ),
+ authenticated_parts(),
+ )
+ .data(MacroUserIdStr::parse_from_str(VALID_USER_ID).unwrap())
+ .data(context),
+ )
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ assert_eq!(
+ response.data.into_json().unwrap()["deleteCalendarEvent"]["deletedEventId"],
+ EVENT_ID.to_string()
+ );
+ assert_eq!(
+ *mutations.deleted.lock().unwrap(),
+ vec![(VALID_USER_ID.to_owned(), EVENT_ID)]
+ );
+}
diff --git a/crates/complete_graph/src/sdl_test.rs b/crates/complete_graph/src/sdl_test.rs
index ec0410b75d..e7438ba624 100644
--- a/crates/complete_graph/src/sdl_test.rs
+++ b/crates/complete_graph/src/sdl_test.rs
@@ -724,6 +724,12 @@ fn calendar_reads_hang_off_the_authenticated_user() {
"since: [CalendarLinkWatermarkInput!]!",
"newWatermark: [GraphqlCalendarLinkWatermark!]!",
"occurrences: [GraphqlCalendarOccurrence!]!",
+ "createCalendarEvent(input: CreateCalendarEventInput!): GraphqlCalendarMutationPayload!",
+ "updateCalendarEvent(input: UpdateCalendarEventInput!): GraphqlCalendarMutationPayload!",
+ "deleteCalendarEvent(input: DeleteCalendarEventInput!): GraphqlCalendarMutationPayload!",
+ "respondToCalendarEvent(input: RespondToCalendarEventInput!): GraphqlCalendarMutationPayload!",
+ "input CalendarEventTimeInput @oneOf {",
+ "deletedEventId: ID",
"needsCalendarPermission: Boolean!",
"calendarDisabled: Boolean!",
"hasCalendarData: Boolean!",
diff --git a/crates/graphql_calendar/src/inputs.rs b/crates/graphql_calendar/src/inputs.rs
index d600035cde..fe5c94031a 100644
--- a/crates/graphql_calendar/src/inputs.rs
+++ b/crates/graphql_calendar/src/inputs.rs
@@ -90,13 +90,13 @@ fn page_size(first: Option<i32>) -> async_graphql::Result<u16> {
.ok_or_else(|| bad_input("calendar page size must be between 1 and 2000"))
}
-fn parse_instant(value: &str, field: &str) -> async_graphql::Result<DateTime<Utc>> {
+pub(crate) fn parse_instant(value: &str, field: &str) -> async_graphql::Result<DateTime<Utc>> {
DateTime::parse_from_rfc3339(value)
.map(|instant| instant.with_timezone(&Utc))
.map_err(|_| bad_input(format!("{field} must be an RFC 3339 instant")))
}
-fn parse_date(value: &str, field: &str) -> async_graphql::Result<NaiveDate> {
+pub(crate) fn parse_date(value: &str, field: &str) -> async_graphql::Result<NaiveDate> {
NaiveDate::parse_from_str(value, "%Y-%m-%d")
.map_err(|_| bad_input(format!("{field} must be a YYYY-MM-DD date")))
}
diff --git a/crates/graphql_calendar/src/lib.rs b/crates/graphql_calendar/src/lib.rs
index 767dc44cac..0bbd8d576f 100644
--- a/crates/graphql_calendar/src/lib.rs
+++ b/crates/graphql_calendar/src/lib.rs
@@ -3,24 +3,36 @@
#![deny(missing_docs)]
mod inputs;
+mod mutation;
mod objects;
mod reads;
#[cfg(test)]
mod test_fixtures;
mod user_query;
+mod writes;
pub use inputs::{CalendarChangesInput, CalendarLinkWatermarkInput, CalendarRangeInput};
+pub use mutation::{
+ AllDayEventTimeInput, CalendarEventTimeInput, CalendarMutationRoot, CalendarOutOfOfficeInput,
+ CalendarReminderOverrideInput, CalendarRemindersInput, CreateCalendarEventInput,
+ DeleteCalendarEventInput, GraphqlCalendarAttendeeInput, GraphqlCalendarConferenceChange,
+ GraphqlCalendarDeletionScope, GraphqlCalendarOutOfOfficeAutoDeclineMode,
+ GraphqlCalendarRsvpScope, GraphqlCalendarUpdateScope, RespondToCalendarEventInput,
+ TimedEventTimeInput, UpdateCalendarEventInput,
+};
pub use objects::{
GraphqlAllDayEventTime, GraphqlCalendar, GraphqlCalendarAttendee,
GraphqlCalendarAttendeeResponseStatus, GraphqlCalendarChanges,
GraphqlCalendarConferenceProvider, GraphqlCalendarEvent, GraphqlCalendarEventChange,
GraphqlCalendarEventSource, GraphqlCalendarEventStatus, GraphqlCalendarEventTransparency,
GraphqlCalendarEventType, GraphqlCalendarEventVisibility, GraphqlCalendarLinkWatermark,
- GraphqlCalendarOccurrence, GraphqlCalendarOccurrencePage, GraphqlCalendarReminderOverride,
- GraphqlCalendarReminders, GraphqlCalendarSyncStatus, GraphqlEventTime, GraphqlTimedEventTime,
+ GraphqlCalendarMutationPayload, GraphqlCalendarOccurrence, GraphqlCalendarOccurrencePage,
+ GraphqlCalendarReminderOverride, GraphqlCalendarReminders, GraphqlCalendarSyncStatus,
+ GraphqlEventTime, GraphqlTimedEventTime,
};
pub use reads::CalendarGraphqlContext;
pub use user_query::GraphqlCalendarQuery;
+pub use writes::CalendarGraphqlMutationContext;
use async_graphql::ErrorExtensions;
use rootcause::Report;
diff --git a/crates/graphql_calendar/src/mutation.rs b/crates/graphql_calendar/src/mutation.rs
new file mode 100644
index 0000000000..f32af72c73
--- /dev/null
+++ b/crates/graphql_calendar/src/mutation.rs
@@ -0,0 +1,219 @@
+use async_graphql::{Context, ErrorExtensions, Object};
+use calendar_events::domain::{changes::CalendarEventChange, ports::CalendarMutationError};
+use graphql_common::require_authenticated_user;
+use uuid::Uuid;
+
+use crate::{
+ objects::GraphqlCalendarMutationPayload,
+ writes::{CalendarGraphqlMutationContext, CalendarGraphqlWrites},
+};
+
+mod inputs;
+#[cfg(test)]
+mod test;
+
+pub use inputs::{
+ AllDayEventTimeInput, CalendarEventTimeInput, CalendarOutOfOfficeInput,
+ CalendarReminderOverrideInput, CalendarRemindersInput, CreateCalendarEventInput,
+ DeleteCalendarEventInput, GraphqlCalendarAttendeeInput, GraphqlCalendarConferenceChange,
+ GraphqlCalendarDeletionScope, GraphqlCalendarOutOfOfficeAutoDeclineMode,
+ GraphqlCalendarRsvpScope, GraphqlCalendarUpdateScope, RespondToCalendarEventInput,
+ TimedEventTimeInput, UpdateCalendarEventInput,
+};
+
+/// Calendar event mutations. Each answers with the event's committed state:
+/// the series event and every visible occurrence, or the id of an event the
+/// write removed.
+#[derive(Default)]
+pub struct CalendarMutationRoot;
+
+#[Object]
+impl CalendarMutationRoot {
+ /// Create an event on one of the viewer's writable calendars.
+ #[tracing::instrument(skip_all, err(Debug))]
+ async fn create_calendar_event(
+ &self,
+ ctx: &Context<'_>,
+ input: CreateCalendarEventInput,
+ ) -> async_graphql::Result<GraphqlCalendarMutationPayload> {
+ let viewer = require_authenticated_user(ctx)?.as_ref().to_owned();
+ let writes = &ctx.data::<CalendarGraphqlMutationContext>()?.writes;
+ let request = input.into_request().map_err(invalid_input)?;
+ let event = writes
+ .create_event(
+ viewer.clone(),
+ request.email_link_id,
+ request.calendar_id,
+ request.draft,
+ )
+ .await
+ .map_err(mutation_error)?;
+ committed_state(writes.as_ref(), viewer, event.id, None).await
+ }
+
+ /// Patch an event, the whole series or one occurrence.
+ #[tracing::instrument(skip_all, err(Debug))]
+ async fn update_calendar_event(
+ &self,
+ ctx: &Context<'_>,
+ input: UpdateCalendarEventInput,
+ ) -> async_graphql::Result<GraphqlCalendarMutationPayload> {
+ let viewer = require_authenticated_user(ctx)?.as_ref().to_owned();
+ let writes = &ctx.data::<CalendarGraphqlMutationContext>()?.writes;
+ let request = input.into_request().map_err(invalid_input)?;
+ let before = state_before(writes.as_ref(), viewer.clone(), request.event_id).await;
+ writes
+ .update_event(
+ viewer.clone(),
+ request.event_id,
+ request.calendar_id,
+ request.patch,
+ request.scope,
+ )
+ .await
+ .map_err(mutation_error)?;
+ committed_state(writes.as_ref(), viewer, request.event_id, before).await
+ }
+
+ /// Delete an event, one occurrence, or an occurrence onward.
+ #[tracing::instrument(skip_all, err(Debug))]
+ async fn delete_calendar_event(
+ &self,
+ ctx: &Context<'_>,
+ input: DeleteCalendarEventInput,
+ ) -> async_graphql::Result<GraphqlCalendarMutationPayload> {
+ let viewer = require_authenticated_user(ctx)?.as_ref().to_owned();
+ let writes = &ctx.data::<CalendarGraphqlMutationContext>()?.writes;
+ let request = input.into_request().map_err(invalid_input)?;
+ let before = state_before(writes.as_ref(), viewer.clone(), request.event_id).await;
+ writes
+ .delete_event(
+ viewer.clone(),
+ request.event_id,
+ request.calendar_id,
+ request.scope,
+ )
+ .await
+ .map_err(mutation_error)?;
+ committed_state(writes.as_ref(), viewer, request.event_id, before).await
+ }
+
+ /// Set the viewer's RSVP on an event, the whole series or one occurrence.
+ #[tracing::instrument(skip_all, err(Debug))]
+ async fn respond_to_calendar_event(
+ &self,
+ ctx: &Context<'_>,
+ input: RespondToCalendarEventInput,
+ ) -> async_graphql::Result<GraphqlCalendarMutationPayload> {
+ let viewer = require_authenticated_user(ctx)?.as_ref().to_owned();
+ let writes = &ctx.data::<CalendarGraphqlMutationContext>()?.writes;
+ let request = input.into_request().map_err(invalid_input)?;
+ let before = state_before(writes.as_ref(), viewer.clone(), request.event_id).await;
+ writes
+ .respond_to_event(
+ viewer.clone(),
+ request.event_id,
+ request.calendar_id,
+ request.response,
+ request.scope,
+ request.responding_email,
+ )
+ .await
+ .map_err(mutation_error)?;
+ committed_state(writes.as_ref(), viewer, request.event_id, before).await
+ }
+}
+
+/// The event as it stood before a write, so the answer can name the
+/// occurrences the write removed. Best effort: without it the answer still
+/// carries the committed state, and the change log removes the rest.
+async fn state_before(
+ writes: &dyn CalendarGraphqlWrites,
+ viewer: String,
+ event_id: Uuid,
+) -> Option<CalendarEventChange> {
+ writes
+ .event_change(viewer, event_id)
+ .await
+ .inspect_err(|error| {
+ tracing::warn!(error = ?error, %event_id, "failed to read a calendar event before writing it");
+ })
+ .ok()
+ .flatten()
+}
+
+/// Read the event back from the primary database once the write committed.
+/// A failed read after a successful write is reported like a lagging
+/// persistence: the change is at the provider and the next sync shows it.
+async fn committed_state(
+ writes: &dyn CalendarGraphqlWrites,
+ viewer: String,
+ event_id: Uuid,
+ before: Option<CalendarEventChange>,
+) -> async_graphql::Result<GraphqlCalendarMutationPayload> {
+ let after = writes
+ .event_change(viewer, event_id)
+ .await
+ .map_err(|error| {
+ mutation_error(CalendarMutationError::PersistFailed(format!("{error:?}")))
+ })?;
+ Ok(GraphqlCalendarMutationPayload::new(event_id, before, after))
+}
+
+/// Map a mutation failure to the REST error's message and snake_case `code`.
+/// `retryable` marks the failures a client may retry unchanged; provider and
+/// infrastructure details stay in the logs.
+pub(crate) fn mutation_error(error: CalendarMutationError) -> async_graphql::Error {
+ let (code, message): (&str, String) = match &error {
+ CalendarMutationError::NotFound => ("not_found", "calendar event was not found".into()),
+ CalendarMutationError::OccurrenceNotFound => (
+ "occurrence_not_found",
+ "the targeted occurrence was not found on the recurring event; the calendar was \
+ out of date and has been refreshed"
+ .into(),
+ ),
+ CalendarMutationError::ReadOnly => ("read_only", "this calendar is read-only".into()),
+ CalendarMutationError::NoWritableCalendar => (
+ "no_writable_calendar",
+ "no connected calendar can accept new events".into(),
+ ),
+ CalendarMutationError::NotAttendee => (
+ "not_attendee",
+ "the connected account is not an attendee of this event".into(),
+ ),
+ CalendarMutationError::InvalidInput(message) => ("invalid_input", message.clone()),
+ CalendarMutationError::ReauthRequired(_) => (
+ "reauth_required",
+ "calendar access must be re-authorized".into(),
+ ),
+ CalendarMutationError::ProviderRejected(message) => ("provider_rejected", message.clone()),
+ CalendarMutationError::Retryable(_) => (
+ "retryable",
+ "the calendar mutation failed transiently; try again".into(),
+ ),
+ CalendarMutationError::PersistFailed(_) => (
+ "persist_failed",
+ "the change reached the calendar provider; refresh to see it".into(),
+ ),
+ };
+ let retryable = matches!(error, CalendarMutationError::Retryable(_));
+ if matches!(
+ error,
+ CalendarMutationError::Retryable(_) | CalendarMutationError::PersistFailed(_)
+ ) {
+ tracing::error!(error = ?error, "calendar mutation failed");
+ }
+ async_graphql::Error::new(message).extend_with(|_, extensions| {
+ extensions.set("code", code);
+ extensions.set("retryable", retryable);
+ })
+}
+
+/// Tag a malformed input with the same `invalid_input` code the calendar
+/// service reports for invalid fields.
+fn invalid_input(error: async_graphql::Error) -> async_graphql::Error {
+ error.extend_with(|_, extensions| {
+ extensions.set("code", "invalid_input");
+ extensions.set("retryable", false);
+ })
+}
diff --git a/crates/graphql_calendar/src/mutation/inputs.rs b/crates/graphql_calendar/src/mutation/inputs.rs
new file mode 100644
index 0000000000..10a3516118
--- /dev/null
+++ b/crates/graphql_calendar/src/mutation/inputs.rs
@@ -0,0 +1,509 @@
+use async_graphql::{Enum, ID, InputObject, OneofObject};
+use calendar_events::domain::{
+ models::{
+ AttendeeResponseStatus, CalendarAttendeeInput, CalendarEventDraft, CalendarEventPatch,
+ ConferenceChange, EventReminderOverride, EventReminders, EventTime, EventTransparency,
+ EventVisibility, OutOfOfficeAutoDeclineMode, OutOfOfficeProperties,
+ },
+ ports::{CalendarDeletionScope, CalendarRsvpScope, CalendarUpdateScope},
+};
+use graphql_common::parse_id;
+use uuid::Uuid;
+
+use crate::{
+ bad_input,
+ inputs::{parse_date, parse_instant},
+ objects::{
+ GraphqlCalendarAttendeeResponseStatus, GraphqlCalendarEventTransparency,
+ GraphqlCalendarEventVisibility,
+ },
+};
+
+/// A span with absolute instants.
+#[derive(InputObject, Clone, Debug)]
+pub struct TimedEventTimeInput {
+ /// Inclusive start instant in RFC 3339 format.
+ pub starts_at: String,
+ /// Exclusive end instant in RFC 3339 format.
+ pub ends_at: String,
+ /// IANA time-zone identifier the event is anchored to.
+ pub time_zone: Option<String>,
+}
+
+/// An all-day span with an exclusive end date.
+#[derive(InputObject, Clone, Debug)]
+pub struct AllDayEventTimeInput {
+ /// Inclusive local start date (`YYYY-MM-DD`).
+ pub start_date: String,
+ /// Exclusive local end date (`YYYY-MM-DD`).
+ pub end_date: String,
+}
+
+/// The time shape of an event.
+#[derive(OneofObject, Clone, Debug)]
+pub enum CalendarEventTimeInput {
+ /// A span with absolute instants.
+ Timed(TimedEventTimeInput),
+ /// An all-day span.
+ AllDay(AllDayEventTimeInput),
+}
+
+impl CalendarEventTimeInput {
+ fn into_time(self) -> async_graphql::Result<EventTime> {
+ Ok(match self {
+ Self::Timed(time) => EventTime::Timed {
+ starts_at: parse_instant(&time.starts_at, "time.timed.startsAt")?,
+ ends_at: parse_instant(&time.ends_at, "time.timed.endsAt")?,
+ time_zone: time.time_zone,
+ },
+ Self::AllDay(time) => EventTime::AllDay {
+ start_date: parse_date(&time.start_date, "time.allDay.startDate")?,
+ end_date: parse_date(&time.end_date, "time.allDay.endDate")?,
+ },
+ })
+ }
+}
+
+/// An attendee to invite.
+#[derive(InputObject, Clone, Debug)]
+#[graphql(name = "CalendarAttendeeInput")]
+pub struct GraphqlCalendarAttendeeInput {
+ /// Attendee email address.
+ pub email: String,
+ /// Whether attendance is optional.
+ #[graphql(default)]
+ pub is_optional: bool,
+}
+
+impl From<GraphqlCalendarAttendeeInput> for CalendarAttendeeInput {
+ fn from(input: GraphqlCalendarAttendeeInput) -> Self {
+ Self {
+ email: input.email,
+ is_optional: input.is_optional,
+ response_status: None,
+ }
+ }
+}
+
+/// One reminder.
+#[derive(InputObject, Clone, Debug)]
+pub struct CalendarReminderOverrideInput {
+ /// Delivery method (`popup` or `email`).
+ pub method: String,
+ /// Minutes before the start the reminder fires.
+ pub minutes: i32,
+}
+
+/// An event's reminder configuration.
+#[derive(InputObject, Clone, Debug)]
+pub struct CalendarRemindersInput {
+ /// Whether the calendar's default reminders apply.
+ pub use_default: bool,
+ /// Explicit reminders, used when `useDefault` is false.
+ #[graphql(default)]
+ pub overrides: Vec<CalendarReminderOverrideInput>,
+}
+
+impl CalendarRemindersInput {
+ fn into_reminders(self) -> async_graphql::Result<EventReminders> {
+ Ok(EventReminders {
+ use_default: self.use_default,
+ overrides: self
+ .overrides
+ .into_iter()
+ .map(|reminder| {
+ Ok(EventReminderOverride {
+ method: reminder.method,
+ minutes: u32::try_from(reminder.minutes)
+ .map_err(|_| bad_input("reminder minutes must not be negative"))?,
+ })
+ })
+ .collect::<async_graphql::Result<_>>()?,
+ })
+ }
+}
+
+/// A change to an event's conference.
+#[derive(Enum, Copy, Clone, Debug, Eq, PartialEq)]
+pub enum GraphqlCalendarConferenceChange {
+ /// Generate a new Google Meet conference and attach it.
+ GoogleMeet,
+ /// Detach whatever conference is currently attached.
+ #[graphql(name = "NONE")]
+ Detach,
+}
+
+impl From<GraphqlCalendarConferenceChange> for ConferenceChange {
+ fn from(change: GraphqlCalendarConferenceChange) -> Self {
+ match change {
+ GraphqlCalendarConferenceChange::GoogleMeet => Self::GoogleMeet,
+ GraphqlCalendarConferenceChange::Detach => Self::Removed,
+ }
+ }
+}
+
+/// How an out-of-office event answers conflicting invitations.
+#[derive(Enum, Copy, Clone, Debug, Eq, PartialEq)]
+pub enum GraphqlCalendarOutOfOfficeAutoDeclineMode {
+ /// Leave conflicting invitations alone.
+ DeclineNone,
+ /// Decline every conflicting invitation, existing and new.
+ DeclineAllConflictingInvitations,
+ /// Decline only invitations that arrive after the event is created.
+ DeclineOnlyNewConflictingInvitations,
+}
+
+impl From<GraphqlCalendarOutOfOfficeAutoDeclineMode> for OutOfOfficeAutoDeclineMode {
+ fn from(mode: GraphqlCalendarOutOfOfficeAutoDeclineMode) -> Self {
+ match mode {
+ GraphqlCalendarOutOfOfficeAutoDeclineMode::DeclineNone => Self::DeclineNone,
+ GraphqlCalendarOutOfOfficeAutoDeclineMode::DeclineAllConflictingInvitations => {
+ Self::DeclineAllConflictingInvitations
+ }
+ GraphqlCalendarOutOfOfficeAutoDeclineMode::DeclineOnlyNewConflictingInvitations => {
+ Self::DeclineOnlyNewConflictingInvitations
+ }
+ }
+ }
+}
+
+/// Out-of-office properties. Present to create or edit an out-of-office
+/// status event.
+#[derive(InputObject, Clone, Debug)]
+pub struct CalendarOutOfOfficeInput {
+ /// How conflicting invitations are handled while the user is out.
+ #[graphql(default_with = "GraphqlCalendarOutOfOfficeAutoDeclineMode::DeclineNone")]
+ pub auto_decline_mode: GraphqlCalendarOutOfOfficeAutoDeclineMode,
+ /// Message returned to organizers whose invitations are auto-declined.
+ pub decline_message: Option<String>,
+}
+
+impl From<CalendarOutOfOfficeInput> for OutOfOfficeProperties {
+ fn from(input: CalendarOutOfOfficeInput) -> Self {
+ Self {
+ auto_decline_mode: input.auto_decline_mode.into(),
+ decline_message: input.decline_message,
+ }
+ }
+}
+
+impl From<GraphqlCalendarEventVisibility> for EventVisibility {
+ fn from(visibility: GraphqlCalendarEventVisibility) -> Self {
+ match visibility {
+ GraphqlCalendarEventVisibility::Default => Self::Default,
+ GraphqlCalendarEventVisibility::Public => Self::Public,
+ GraphqlCalendarEventVisibility::Private => Self::Private,
+ GraphqlCalendarEventVisibility::Confidential => Self::Confidential,
+ }
+ }
+}
+
+impl From<GraphqlCalendarEventTransparency> for EventTransparency {
+ fn from(transparency: GraphqlCalendarEventTransparency) -> Self {
+ match transparency {
+ GraphqlCalendarEventTransparency::Opaque => Self::Opaque,
+ GraphqlCalendarEventTransparency::Transparent => Self::Transparent,
+ }
+ }
+}
+
+impl From<GraphqlCalendarAttendeeResponseStatus> for AttendeeResponseStatus {
+ fn from(status: GraphqlCalendarAttendeeResponseStatus) -> Self {
+ match status {
+ GraphqlCalendarAttendeeResponseStatus::NeedsAction => Self::NeedsAction,
+ GraphqlCalendarAttendeeResponseStatus::Accepted => Self::Accepted,
+ GraphqlCalendarAttendeeResponseStatus::Declined => Self::Declined,
+ GraphqlCalendarAttendeeResponseStatus::Tentative => Self::Tentative,
+ }
+ }
+}
+
+/// Create an event on one of the viewer's writable calendars.
+#[derive(InputObject, Clone, Debug)]
+pub struct CreateCalendarEventInput {
+ /// Stable retry identity, scoped to the authenticated organizer.
+ pub idempotency_key: Option<ID>,
+ /// Exact calendar to create the event on; takes precedence over the
+ /// inbox default.
+ pub calendar_id: Option<ID>,
+ /// Connected inbox whose primary calendar receives the event; defaults
+ /// to the viewer's primary inbox.
+ pub email_link_id: Option<ID>,
+ /// Display title.
+ pub title: String,
+ /// Optional event body.
+ pub description: Option<String>,
+ /// Optional location label.
+ pub location: Option<String>,
+ /// Timed or all-day shape.
+ pub time: CalendarEventTimeInput,
+ /// Invited attendees.
+ #[graphql(default)]
+ pub attendees: Vec<GraphqlCalendarAttendeeInput>,
+ /// Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`).
+ #[graphql(default)]
+ pub recurrence_lines: Vec<String>,
+ /// Event visibility.
+ pub visibility: Option<GraphqlCalendarEventVisibility>,
+ /// Availability behavior.
+ pub transparency: Option<GraphqlCalendarEventTransparency>,
+ /// Reminder configuration; omit to keep the calendar defaults.
+ pub reminders: Option<CalendarRemindersInput>,
+ /// Conference to attach; omit to create the event without one.
+ pub conference: Option<GraphqlCalendarConferenceChange>,
+ /// Present to create an out-of-office status event (primary calendar
+ /// only, timed, no attendees).
+ pub out_of_office: Option<CalendarOutOfOfficeInput>,
+}
+
+pub(crate) struct CreateRequest {
+ pub(crate) email_link_id: Option<Uuid>,
+ pub(crate) calendar_id: Option<Uuid>,
+ pub(crate) draft: CalendarEventDraft,
+}
+
+impl CreateCalendarEventInput {
+ pub(crate) fn into_request(self) -> async_graphql::Result<CreateRequest> {
+ Ok(CreateRequest {
+ email_link_id: optional_id(self.email_link_id, "emailLinkId")?,
+ calendar_id: optional_id(self.calendar_id, "calendarId")?,
+ draft: CalendarEventDraft {
+ idempotency_key: optional_id(self.idempotency_key, "idempotencyKey")?,
+ title: self.title,
+ description: self.description,
+ location: self.location,
+ time: self.time.into_time()?,
+ attendees: self.attendees.into_iter().map(Into::into).collect(),
+ recurrence_lines: self.recurrence_lines,
+ visibility: self.visibility.map(Into::into),
+ transparency: self.transparency.map(Into::into),
+ reminders: self
+ .reminders
+ .map(CalendarRemindersInput::into_reminders)
+ .transpose()?,
+ conference: self.conference.map(Into::into),
+ out_of_office: self.out_of_office.map(Into::into),
+ },
+ })
+ }
+}
+
+/// How much of a recurring series an update applies to.
+#[derive(Enum, Copy, Clone, Debug, Eq, PartialEq)]
+pub enum GraphqlCalendarUpdateScope {
+ /// The entire event or series.
+ All,
+ /// One occurrence.
+ ThisEvent,
+}
+
+/// Patch an event; omitted fields are left untouched.
+#[derive(InputObject, Clone, Debug)]
+pub struct UpdateCalendarEventInput {
+ /// Event to patch.
+ pub event_id: ID,
+ /// Calendar whose copy of the event is patched, for an event synced from
+ /// more than one calendar. Omit to patch the canonical copy.
+ pub calendar_id: Option<ID>,
+ /// Replacement title; an empty string clears it.
+ pub title: Option<String>,
+ /// Replacement description; an empty string clears it.
+ pub description: Option<String>,
+ /// Replacement location; an empty string clears it.
+ pub location: Option<String>,
+ /// Replacement time.
+ pub time: Option<CalendarEventTimeInput>,
+ /// Replacement attendee list.
+ pub attendees: Option<Vec<GraphqlCalendarAttendeeInput>>,
+ /// Replacement recurrence properties; an empty list clears them.
+ pub recurrence_lines: Option<Vec<String>>,
+ /// Replacement visibility.
+ pub visibility: Option<GraphqlCalendarEventVisibility>,
+ /// Replacement transparency.
+ pub transparency: Option<GraphqlCalendarEventTransparency>,
+ /// Replacement reminder configuration.
+ pub reminders: Option<CalendarRemindersInput>,
+ /// Conference change; omit to leave the conference untouched.
+ pub conference: Option<GraphqlCalendarConferenceChange>,
+ /// Replacement out-of-office properties, applied only to an event that is
+ /// already out-of-office.
+ pub out_of_office: Option<CalendarOutOfOfficeInput>,
+ /// How much of a recurring series the update covers. Omit to let
+ /// `recurrenceId` decide: the identified occurrence alone when one is
+ /// supplied, otherwise the whole event or series.
+ pub scope: Option<GraphqlCalendarUpdateScope>,
+ /// Original-start key of the occurrence the update targets.
+ pub recurrence_id: Option<String>,
+}
+
+pub(crate) struct UpdateRequest {
+ pub(crate) event_id: Uuid,
+ pub(crate) calendar_id: Option<Uuid>,
+ pub(crate) patch: CalendarEventPatch,
+ pub(crate) scope: CalendarUpdateScope,
+}
+
+impl UpdateCalendarEventInput {
+ pub(crate) fn into_request(self) -> async_graphql::Result<UpdateRequest> {
+ let scope = match (self.scope, self.recurrence_id) {
+ (Some(GraphqlCalendarUpdateScope::All), None) | (None, None) => {
+ CalendarUpdateScope::All
+ }
+ (Some(GraphqlCalendarUpdateScope::ThisEvent), Some(recurrence_id))
+ | (None, Some(recurrence_id)) => CalendarUpdateScope::ThisEvent { recurrence_id },
+ (Some(GraphqlCalendarUpdateScope::ThisEvent), None) => {
+ return Err(bad_input("a this-event update requires recurrenceId"));
+ }
+ (Some(GraphqlCalendarUpdateScope::All), Some(_)) => {
+ return Err(bad_input(
+ "recurrenceId only applies to a this_event update",
+ ));
+ }
+ };
+ Ok(UpdateRequest {
+ event_id: parse_id(self.event_id, "eventId")?,
+ calendar_id: optional_id(self.calendar_id, "calendarId")?,
+ patch: CalendarEventPatch {
+ title: self.title,
+ description: self.description,
+ location: self.location,
+ time: self
+ .time
+ .map(CalendarEventTimeInput::into_time)
+ .transpose()?,
+ attendees: self
+ .attendees
+ .map(|attendees| attendees.into_iter().map(Into::into).collect()),
+ recurrence_lines: self.recurrence_lines,
+ visibility: self.visibility.map(Into::into),
+ transparency: self.transparency.map(Into::into),
+ reminders: self
+ .reminders
+ .map(CalendarRemindersInput::into_reminders)
+ .transpose()?,
+ conference: self.conference.map(Into::into),
+ out_of_office: self.out_of_office.map(Into::into),
+ },
+ scope,
+ })
+ }
+}
+
+/// How much of a recurring series a deletion removes.
+#[derive(Enum, Copy, Clone, Debug, Eq, PartialEq)]
+pub enum GraphqlCalendarDeletionScope {
+ /// The entire event or series.
+ All,
+ /// One occurrence.
+ ThisEvent,
+ /// One occurrence and everything after it.
+ ThisAndFollowing,
+}
+
+/// Delete an event, one occurrence, or an occurrence onward.
+#[derive(InputObject, Clone, Debug)]
+pub struct DeleteCalendarEventInput {
+ /// Event to delete.
+ pub event_id: ID,
+ /// Calendar whose copy of the event is deleted, for an event synced from
+ /// more than one calendar. Omit to delete the canonical copy.
+ pub calendar_id: Option<ID>,
+ /// Deletion scope; defaults to the entire event or series.
+ #[graphql(default_with = "GraphqlCalendarDeletionScope::All")]
+ pub scope: GraphqlCalendarDeletionScope,
+ /// Original-start key of the occurrence a scoped deletion targets.
+ pub recurrence_id: Option<String>,
+}
+
+pub(crate) struct DeleteRequest {
+ pub(crate) event_id: Uuid,
+ pub(crate) calendar_id: Option<Uuid>,
+ pub(crate) scope: CalendarDeletionScope,
+}
+
+impl DeleteCalendarEventInput {
+ pub(crate) fn into_request(self) -> async_graphql::Result<DeleteRequest> {
+ let scoped_occurrence = |kind: &str| {
+ self.recurrence_id
+ .clone()
+ .ok_or_else(|| bad_input(format!("a {kind} deletion requires recurrenceId")))
+ };
+ let scope = match self.scope {
+ GraphqlCalendarDeletionScope::All => CalendarDeletionScope::All,
+ GraphqlCalendarDeletionScope::ThisEvent => CalendarDeletionScope::ThisEvent {
+ recurrence_id: scoped_occurrence("this-event")?,
+ },
+ GraphqlCalendarDeletionScope::ThisAndFollowing => {
+ CalendarDeletionScope::ThisAndFollowing {
+ recurrence_id: scoped_occurrence("this-and-following")?,
+ }
+ }
+ };
+ Ok(DeleteRequest {
+ event_id: parse_id(self.event_id, "eventId")?,
+ calendar_id: optional_id(self.calendar_id, "calendarId")?,
+ scope,
+ })
+ }
+}
+
+/// How much of a recurring series an RSVP applies to.
+#[derive(Enum, Copy, Clone, Debug, Eq, PartialEq)]
+pub enum GraphqlCalendarRsvpScope {
+ /// The entire series.
+ All,
+ /// One occurrence.
+ ThisEvent,
+}
+
+/// Set the viewer's RSVP on an event.
+#[derive(InputObject, Clone, Debug)]
+pub struct RespondToCalendarEventInput {
+ /// Event to answer.
+ pub event_id: ID,
+ /// Calendar whose copy of the event is answered, for an event synced
+ /// from more than one calendar. Omit to answer on the canonical copy.
+ pub calendar_id: Option<ID>,
+ /// The response to record.
+ pub response: GraphqlCalendarAttendeeResponseStatus,
+ /// How much of a recurring series the response covers. Omit to let
+ /// `recurrenceId` decide: the identified occurrence alone when one is
+ /// supplied, otherwise the whole series.
+ pub scope: Option<GraphqlCalendarRsvpScope>,
+ /// Original-start key of the occurrence the response targets.
+ pub recurrence_id: Option<String>,
+ /// The owned connected address whose attendance is changed.
+ pub responding_email: Option<String>,
+}
+
+pub(crate) struct RsvpRequest {
+ pub(crate) event_id: Uuid,
+ pub(crate) calendar_id: Option<Uuid>,
+ pub(crate) response: AttendeeResponseStatus,
+ pub(crate) scope: CalendarRsvpScope,
+ pub(crate) responding_email: Option<String>,
+}
+
+impl RespondToCalendarEventInput {
+ pub(crate) fn into_request(self) -> async_graphql::Result<RsvpRequest> {
+ let scope = match (self.scope, self.recurrence_id) {
+ (Some(GraphqlCalendarRsvpScope::All), _) | (None, None) => CalendarRsvpScope::All,
+ (Some(GraphqlCalendarRsvpScope::ThisEvent), Some(recurrence_id))
+ | (None, Some(recurrence_id)) => CalendarRsvpScope::ThisEvent { recurrence_id },
+ (Some(GraphqlCalendarRsvpScope::ThisEvent), None) => {
+ return Err(bad_input("a this-event response requires recurrenceId"));
+ }
+ };
+ Ok(RsvpRequest {
+ event_id: parse_id(self.event_id, "eventId")?,
+ calendar_id: optional_id(self.calendar_id, "calendarId")?,
+ response: self.response.into(),
+ scope,
+ responding_email: self.responding_email,
+ })
+ }
+}
+
+fn optional_id(id: Option<ID>, field: &str) -> async_graphql::Result<Option<Uuid>> {
+ id.map(|id| parse_id(id, field)).transpose()
+}
diff --git a/crates/graphql_calendar/src/mutation/test.rs b/crates/graphql_calendar/src/mutation/test.rs
new file mode 100644
index 0000000000..f61355c627
--- /dev/null
+++ b/crates/graphql_calendar/src/mutation/test.rs
@@ -0,0 +1,684 @@
+use std::sync::{Arc, Mutex};
+
+use async_graphql::{EmptySubscription, Schema};
+use calendar_events::domain::{
+ changes::{
+ CalendarChangeQueryService, CalendarChangesPage, CalendarEventChange, CalendarWatermark,
+ EventOccurrence,
+ },
+ models::{
+ AttendeeResponseStatus, CalendarEvent, CalendarEventDraft, CalendarEventPatch,
+ ConferenceChange, EventTime, EventVisibility, OutOfOfficeAutoDeclineMode, VisibleCalendar,
+ },
+ ports::{
+ CalendarDeletionScope, CalendarMutationError, CalendarMutationService, CalendarRsvpScope,
+ CalendarUpdateScope,
+ },
+};
+use chrono::{NaiveDate, TimeZone, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::Report;
+use serde_json::Value;
+use uuid::Uuid;
+
+use super::CalendarMutationRoot;
+use crate::{
+ CalendarGraphqlMutationContext, GraphqlCalendarQuery,
+ test_fixtures::{EVENT_ID, LINK_ID, series_event, timed_listing},
+};
+
+const VIEWER: &str = "macro|[email protected]";
+
+#[derive(Debug, PartialEq)]
+enum Call {
+ Create(Option<Uuid>, Option<Uuid>, CalendarEventDraft),
+ Update(Uuid, Option<Uuid>, CalendarEventPatch, CalendarUpdateScope),
+ Delete(Uuid, Option<Uuid>, CalendarDeletionScope),
+ Rsvp(
+ Uuid,
+ Option<Uuid>,
+ AttendeeResponseStatus,
+ CalendarRsvpScope,
+ Option<String>,
+ ),
+}
+
+#[derive(Default)]
+struct FakeMutations {
+ calls: Mutex<Vec<(String, Call)>>,
+ failure: Mutex<Option<CalendarMutationError>>,
+}
+
+impl FakeMutations {
+ fn record(&self, viewer: &str, call: Call) -> Result<(), CalendarMutationError> {
+ self.calls.lock().unwrap().push((viewer.to_owned(), call));
+ match self.failure.lock().unwrap().take() {
+ Some(error) => Err(error),
+ None => Ok(()),
+ }
+ }
+}
+
+impl CalendarMutationService for FakeMutations {
+ async fn create_event(
+ &self,
+ requester_id: &str,
+ email_link_id: Option<Uuid>,
+ calendar_id: Option<Uuid>,
+ draft: CalendarEventDraft,
+ ) -> Result<CalendarEvent, CalendarMutationError> {
+ self.record(
+ requester_id,
+ Call::Create(email_link_id, calendar_id, draft),
+ )?;
+ Ok(series_event())
+ }
+
+ async fn list_visible_calendars(
+ &self,
+ _requester_id: &str,
+ ) -> Result<Vec<VisibleCalendar>, CalendarMutationError> {
+ unreachable!("calendars are read through the query fields")
+ }
+
+ async fn update_event(
+ &self,
+ requester_id: &str,
+ event_id: Uuid,
+ calendar_id: Option<Uuid>,
+ patch: CalendarEventPatch,
+ scope: CalendarUpdateScope,
+ ) -> Result<CalendarEvent, CalendarMutationError> {
+ self.record(
+ requester_id,
+ Call::Update(event_id, calendar_id, patch, scope),
+ )?;
+ Ok(series_event())
+ }
+
+ async fn delete_event(
+ &self,
+ requester_id: &str,
+ event_id: Uuid,
+ calendar_id: Option<Uuid>,
+ scope: CalendarDeletionScope,
+ ) -> Result<(), CalendarMutationError> {
+ self.record(requester_id, Call::Delete(event_id, calendar_id, scope))
+ }
+
+ 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.record(
+ requester_id,
+ Call::Rsvp(event_id, calendar_id, response, scope, responding_email),
+ )?;
+ Ok(series_event())
+ }
+
+ async fn disconnect_calendar(
+ &self,
+ _requester_id: &str,
+ _email_link_id: Uuid,
+ ) -> Result<(), CalendarMutationError> {
+ unreachable!("disconnecting a calendar is not a GraphQL mutation")
+ }
+}
+
+#[derive(Default)]
+struct FakeCommitted {
+ change: Option<CalendarEventChange>,
+ /// Answers for successive reads, before falling back to `change`.
+ sequence: Mutex<std::collections::VecDeque<Option<CalendarEventChange>>>,
+ fail: bool,
+ reads: Mutex<Vec<(String, Uuid)>>,
+}
+
+impl CalendarChangeQueryService for FakeCommitted {
+ async fn current_watermark(&self, _viewer: &str) -> Result<CalendarWatermark, Report> {
+ unreachable!("mutations read no watermark")
+ }
+
+ async fn changes_since(
+ &self,
+ _viewer: &str,
+ _since: CalendarWatermark,
+ ) -> Result<CalendarChangesPage, Report> {
+ unreachable!("mutations read no change pages")
+ }
+
+ async fn event_change(
+ &self,
+ viewer: &str,
+ event_id: Uuid,
+ ) -> Result<Option<CalendarEventChange>, Report> {
+ self.reads
+ .lock()
+ .unwrap()
+ .push((viewer.to_owned(), event_id));
+ if self.fail {
+ return Err(rootcause::report!("replica db-3 unreachable").into());
+ }
+ Ok(self
+ .sequence
+ .lock()
+ .unwrap()
+ .pop_front()
+ .unwrap_or_else(|| self.change.clone()))
+ }
+}
+
+fn committed_change() -> CalendarEventChange {
+ change_on(6)
+}
+
+fn change_on(day: u32) -> CalendarEventChange {
+ let listing = timed_listing(day);
+ CalendarEventChange {
+ event: listing.event,
+ link_id: LINK_ID,
+ occurrences: vec![EventOccurrence {
+ occurrence: listing.occurrence,
+ exception: listing.exception,
+ }],
+ }
+}
+
+async fn execute(
+ mutations: Arc<FakeMutations>,
+ committed: Arc<FakeCommitted>,
+ query: &str,
+ authenticated: bool,
+) -> async_graphql::Response {
+ let schema = Schema::build(
+ GraphqlCalendarQuery::new(MacroUserIdStr::parse_from_str(VIEWER).unwrap()),
+ CalendarMutationRoot,
+ EmptySubscription,
+ )
+ .data(CalendarGraphqlMutationContext::new(mutations, committed))
+ .finish();
+ let request = async_graphql::Request::new(query);
+ let request = if authenticated {
+ request.data(MacroUserIdStr::parse_from_str(VIEWER).unwrap())
+ } else {
+ request
+ };
+ schema.execute(request).await
+}
+
+fn error_extensions(response: &async_graphql::Response) -> (String, Value, Value) {
+ let error = &response.errors[0];
+ let extensions = error.extensions.as_ref().expect("extensions");
+ (
+ error.message.clone(),
+ extensions.get("code").unwrap().clone().into_json().unwrap(),
+ extensions
+ .get("retryable")
+ .map(|value| value.clone().into_json().unwrap())
+ .unwrap_or(Value::Null),
+ )
+}
+
+const PAYLOAD: &str =
+ "event { id linkId title } occurrences { id eventId event { id } } deletedEventId";
+
+#[tokio::test]
+async fn create_maps_the_input_and_answers_with_the_committed_event() {
+ let mutations = Arc::new(FakeMutations::default());
+ let committed = Arc::new(FakeCommitted {
+ change: Some(committed_change()),
+ ..Default::default()
+ });
+ let calendar = Uuid::from_u128(0xca);
+ let key = Uuid::from_u128(0x1d);
+
+ let response = execute(
+ Arc::clone(&mutations),
+ Arc::clone(&committed),
+ &format!(
+ r#"mutation {{ createCalendarEvent(input: {{
+ idempotencyKey: "{key}", calendarId: "{calendar}", title: "Lunch",
+ time: {{ allDay: {{ startDate: "2026-10-06", endDate: "2026-10-07" }} }},
+ attendees: [{{ email: "[email protected]" }}],
+ visibility: PRIVATE, conference: NONE,
+ reminders: {{ useDefault: false, overrides: [{{ method: "popup", minutes: 10 }}] }},
+ outOfOffice: {{ declineMessage: "away" }}
+ }}) {{ {PAYLOAD} }} }}"#
+ ),
+ true,
+ )
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let data = response.data.into_json().unwrap();
+ let payload = &data["createCalendarEvent"];
+ assert_eq!(payload["event"]["id"], EVENT_ID.to_string());
+ assert_eq!(payload["event"]["linkId"], LINK_ID.to_string());
+ assert_eq!(
+ payload["occurrences"][0]["event"]["id"],
+ EVENT_ID.to_string()
+ );
+ assert_eq!(payload["deletedEventId"], Value::Null);
+
+ let calls = mutations.calls.lock().unwrap();
+ let (viewer, Call::Create(email_link_id, calendar_id, draft)) = &calls[0] else {
+ panic!("expected a create, got {calls:?}");
+ };
+ assert_eq!(viewer, VIEWER);
+ assert_eq!(*email_link_id, None);
+ assert_eq!(*calendar_id, Some(calendar));
+ assert_eq!(draft.idempotency_key, Some(key));
+ assert_eq!(
+ draft.time,
+ EventTime::AllDay {
+ start_date: NaiveDate::from_ymd_opt(2026, 10, 6).unwrap(),
+ end_date: NaiveDate::from_ymd_opt(2026, 10, 7).unwrap(),
+ }
+ );
+ assert!(!draft.attendees[0].is_optional);
+ assert_eq!(draft.attendees[0].response_status, None);
+ assert_eq!(draft.visibility, Some(EventVisibility::Private));
+ assert_eq!(draft.conference, Some(ConferenceChange::Removed));
+ let reminders = draft.reminders.as_ref().unwrap();
+ assert!(!reminders.use_default);
+ assert_eq!(reminders.overrides[0].minutes, 10);
+ let out_of_office = draft.out_of_office.as_ref().unwrap();
+ assert_eq!(
+ out_of_office.auto_decline_mode,
+ OutOfOfficeAutoDeclineMode::DeclineNone
+ );
+ assert_eq!(
+ *committed.reads.lock().unwrap(),
+ vec![(VIEWER.to_owned(), EVENT_ID)]
+ );
+}
+
+#[tokio::test]
+async fn update_scopes_resolve_like_the_rest_endpoint() {
+ let start = Utc.with_ymd_and_hms(2026, 10, 6, 15, 0, 0).unwrap();
+ let cases: [(&str, Result<CalendarUpdateScope, &str>); 5] = [
+ ("", Ok(CalendarUpdateScope::All)),
+ ("scope: ALL", Ok(CalendarUpdateScope::All)),
+ (
+ r#"recurrenceId: "r1""#,
+ Ok(CalendarUpdateScope::ThisEvent {
+ recurrence_id: "r1".to_owned(),
+ }),
+ ),
+ (
+ r#"scope: THIS_EVENT, recurrenceId: "r1""#,
+ Ok(CalendarUpdateScope::ThisEvent {
+ recurrence_id: "r1".to_owned(),
+ }),
+ ),
+ (
+ "scope: THIS_EVENT",
+ Err("a this-event update requires recurrenceId"),
+ ),
+ ];
+ for (scope, expected) in cases {
+ let mutations = Arc::new(FakeMutations::default());
+ let response = execute(
+ Arc::clone(&mutations),
+ Arc::new(FakeCommitted::default()),
+ &format!(
+ r#"mutation {{ updateCalendarEvent(input: {{
+ eventId: "{EVENT_ID}", title: "Renamed",
+ time: {{ timed: {{ startsAt: "{}", endsAt: "{}" }} }}
+ {}{scope}
+ }}) {{ deletedEventId }} }}"#,
+ start.to_rfc3339(),
+ (start + chrono::Duration::hours(1)).to_rfc3339(),
+ if scope.is_empty() { "" } else { ", " },
+ ),
+ true,
+ )
+ .await;
+ match expected {
+ Ok(expected_scope) => {
+ assert!(response.errors.is_empty(), "{scope}: {:?}", response.errors);
+ let calls = mutations.calls.lock().unwrap();
+ let (_, Call::Update(event_id, _, patch, scope)) = &calls[0] else {
+ panic!("expected an update");
+ };
+ assert_eq!(*event_id, EVENT_ID);
+ assert_eq!(patch.title.as_deref(), Some("Renamed"));
+ assert_eq!(*scope, expected_scope);
+ }
+ Err(message) => {
+ assert_eq!(
+ error_extensions(&response),
+ (
+ message.to_owned(),
+ Value::from("invalid_input"),
+ Value::Bool(false)
+ )
+ );
+ assert!(mutations.calls.lock().unwrap().is_empty());
+ }
+ }
+ }
+}
+
+#[tokio::test]
+async fn an_update_with_a_series_scope_and_an_occurrence_is_rejected() {
+ let mutations = Arc::new(FakeMutations::default());
+
+ let response = execute(
+ Arc::clone(&mutations),
+ Arc::new(FakeCommitted::default()),
+ &format!(
+ r#"mutation {{ updateCalendarEvent(input: {{
+ eventId: "{EVENT_ID}", scope: ALL, recurrenceId: "r1"
+ }}) {{ deletedEventId }} }}"#
+ ),
+ true,
+ )
+ .await;
+
+ assert_eq!(error_extensions(&response).1, Value::from("invalid_input"));
+ assert!(mutations.calls.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn deleting_the_last_occurrence_reports_the_event_gone() {
+ let mutations = Arc::new(FakeMutations::default());
+
+ let response = execute(
+ Arc::clone(&mutations),
+ Arc::new(FakeCommitted::default()),
+ &format!(
+ r#"mutation {{ deleteCalendarEvent(input: {{ eventId: "{EVENT_ID}" }}) {{ {PAYLOAD} }} }}"#
+ ),
+ true,
+ )
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let data = response.data.into_json().unwrap();
+ let payload = &data["deleteCalendarEvent"];
+ assert_eq!(payload["event"], Value::Null);
+ assert_eq!(payload["occurrences"], Value::Array(Vec::new()));
+ assert_eq!(payload["deletedEventId"], EVENT_ID.to_string());
+ assert_eq!(
+ mutations.calls.lock().unwrap()[0].1,
+ Call::Delete(EVENT_ID, None, CalendarDeletionScope::All)
+ );
+}
+
+#[tokio::test]
+async fn a_scoped_deletion_needs_its_occurrence() {
+ let mutations = Arc::new(FakeMutations::default());
+
+ let missing = execute(
+ Arc::clone(&mutations),
+ Arc::new(FakeCommitted::default()),
+ &format!(
+ r#"mutation {{ deleteCalendarEvent(input: {{
+ eventId: "{EVENT_ID}", scope: THIS_AND_FOLLOWING
+ }}) {{ deletedEventId }} }}"#
+ ),
+ true,
+ )
+ .await;
+ let scoped = execute(
+ Arc::clone(&mutations),
+ Arc::new(FakeCommitted {
+ change: Some(committed_change()),
+ ..Default::default()
+ }),
+ &format!(
+ r#"mutation {{ deleteCalendarEvent(input: {{
+ eventId: "{EVENT_ID}", scope: THIS_AND_FOLLOWING, recurrenceId: "r2"
+ }}) {{ event {{ id }} occurrences {{ id }} }} }}"#
+ ),
+ true,
+ )
+ .await;
+
+ assert_eq!(
+ error_extensions(&missing).0,
+ "a this-and-following deletion requires recurrenceId"
+ );
+ assert!(scoped.errors.is_empty(), "{:?}", scoped.errors);
+ assert_eq!(
+ mutations.calls.lock().unwrap()[0].1,
+ Call::Delete(
+ EVENT_ID,
+ None,
+ CalendarDeletionScope::ThisAndFollowing {
+ recurrence_id: "r2".to_owned()
+ }
+ )
+ );
+}
+
+#[tokio::test]
+async fn an_rsvp_maps_its_response_and_ignores_an_occurrence_on_a_series_scope() {
+ let mutations = Arc::new(FakeMutations::default());
+ let calendar = Uuid::from_u128(0xca);
+
+ let response = execute(
+ Arc::clone(&mutations),
+ Arc::new(FakeCommitted {
+ change: Some(committed_change()),
+ ..Default::default()
+ }),
+ &format!(
+ r#"mutation {{ respondToCalendarEvent(input: {{
+ eventId: "{EVENT_ID}", calendarId: "{calendar}", response: DECLINED,
+ scope: ALL, recurrenceId: "r1", respondingEmail: "[email protected]"
+ }}) {{ event {{ id }} }} }}"#
+ ),
+ true,
+ )
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ assert_eq!(
+ mutations.calls.lock().unwrap()[0].1,
+ Call::Rsvp(
+ EVENT_ID,
+ Some(calendar),
+ AttendeeResponseStatus::Declined,
+ CalendarRsvpScope::All,
+ Some("[email protected]".to_owned()),
+ )
+ );
+}
+
+#[tokio::test]
+async fn every_failure_carries_its_rest_code_and_hides_provider_details() {
+ let cases = [
+ (CalendarMutationError::NotFound, "not_found", false),
+ (
+ CalendarMutationError::OccurrenceNotFound,
+ "occurrence_not_found",
+ false,
+ ),
+ (CalendarMutationError::ReadOnly, "read_only", false),
+ (
+ CalendarMutationError::NoWritableCalendar,
+ "no_writable_calendar",
+ false,
+ ),
+ (CalendarMutationError::NotAttendee, "not_attendee", false),
+ (
+ CalendarMutationError::InvalidInput("end before start".to_owned()),
+ "invalid_input",
+ false,
+ ),
+ (
+ CalendarMutationError::ReauthRequired("token revoked at 10.0.0.4".to_owned()),
+ "reauth_required",
+ false,
+ ),
+ (
+ CalendarMutationError::ProviderRejected("Bad attendee".to_owned()),
+ "provider_rejected",
+ false,
+ ),
+ (
+ CalendarMutationError::Retryable("upstream 10.0.0.4 timed out".to_owned()),
+ "retryable",
+ true,
+ ),
+ (
+ CalendarMutationError::PersistFailed("db 10.0.0.4 down".to_owned()),
+ "persist_failed",
+ false,
+ ),
+ ];
+ for (error, code, retryable) in cases {
+ let mutations = Arc::new(FakeMutations::default());
+ *mutations.failure.lock().unwrap() = Some(error);
+
+ let response = execute(
+ mutations,
+ Arc::new(FakeCommitted::default()),
+ &format!(
+ r#"mutation {{ deleteCalendarEvent(input: {{ eventId: "{EVENT_ID}" }}) {{ deletedEventId }} }}"#
+ ),
+ true,
+ )
+ .await;
+
+ let (message, actual_code, actual_retryable) = error_extensions(&response);
+ assert_eq!(actual_code, Value::from(code));
+ assert_eq!(actual_retryable, Value::Bool(retryable), "{code}");
+ assert!(!message.contains("10.0.0.4"), "{code}: {message}");
+ }
+}
+
+#[tokio::test]
+async fn a_failed_read_back_is_reported_as_lagging_persistence() {
+ let mutations = Arc::new(FakeMutations::default());
+
+ let response = execute(
+ Arc::clone(&mutations),
+ Arc::new(FakeCommitted {
+ fail: true,
+ ..Default::default()
+ }),
+ &format!(
+ r#"mutation {{ deleteCalendarEvent(input: {{ eventId: "{EVENT_ID}" }}) {{ deletedEventId }} }}"#
+ ),
+ true,
+ )
+ .await;
+
+ let (message, code, retryable) = error_extensions(&response);
+ assert_eq!(code, Value::from("persist_failed"));
+ assert_eq!(retryable, Value::Bool(false));
+ assert!(!message.contains("db-3"));
+ assert_eq!(mutations.calls.lock().unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn mutations_require_an_authenticated_viewer() {
+ let mutations = Arc::new(FakeMutations::default());
+
+ let response = execute(
+ Arc::clone(&mutations),
+ Arc::new(FakeCommitted::default()),
+ &format!(
+ r#"mutation {{ deleteCalendarEvent(input: {{ eventId: "{EVENT_ID}" }}) {{ deletedEventId }} }}"#
+ ),
+ false,
+ )
+ .await;
+
+ assert_eq!(response.errors[0].message, "authentication required");
+ assert!(mutations.calls.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn malformed_times_are_invalid_input() {
+ let mutations = Arc::new(FakeMutations::default());
+
+ let response = execute(
+ Arc::clone(&mutations),
+ Arc::new(FakeCommitted::default()),
+ r#"mutation { createCalendarEvent(input: {
+ title: "Bad", time: { timed: { startsAt: "tomorrow", endsAt: "later" } }
+ }) { deletedEventId } }"#,
+ true,
+ )
+ .await;
+
+ assert_eq!(error_extensions(&response).1, Value::from("invalid_input"));
+ assert!(mutations.calls.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn occurrences_a_write_removed_come_back_cancelled() {
+ let mutations = Arc::new(FakeMutations::default());
+ let committed = Arc::new(FakeCommitted {
+ sequence: Mutex::new([Some(change_on(6)), Some(change_on(9))].into()),
+ ..Default::default()
+ });
+
+ let response = execute(
+ Arc::clone(&mutations),
+ Arc::clone(&committed),
+ &format!(
+ r#"mutation {{ updateCalendarEvent(input: {{
+ eventId: "{EVENT_ID}",
+ time: {{ timed: {{ startsAt: "2026-10-09T15:00:00Z", endsAt: "2026-10-09T15:30:00Z" }} }}
+ }}) {{ event {{ id }} occurrences {{ id isCancelled }} deletedEventId }} }}"#
+ ),
+ true,
+ )
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let data = response.data.into_json().unwrap();
+ assert_eq!(
+ data["updateCalendarEvent"]["occurrences"],
+ serde_json::json!([
+ { "id": format!("{EVENT_ID}:2026-10-09T15:00:00+00:00"), "isCancelled": false },
+ { "id": format!("{EVENT_ID}:2026-10-06T15:00:00+00:00"), "isCancelled": true },
+ ])
+ );
+ assert_eq!(
+ committed.reads.lock().unwrap().len(),
+ 2,
+ "read before and after"
+ );
+}
+
+#[tokio::test]
+async fn deleting_returns_every_removed_occurrence_cancelled() {
+ let committed = Arc::new(FakeCommitted {
+ sequence: Mutex::new([Some(change_on(6)), None].into()),
+ ..Default::default()
+ });
+
+ let response = execute(
+ Arc::new(FakeMutations::default()),
+ committed,
+ &format!(
+ r#"mutation {{ deleteCalendarEvent(input: {{ eventId: "{EVENT_ID}" }}) {{
+ event {{ id }} occurrences {{ id isCancelled event {{ id }} }} deletedEventId
+ }} }}"#
+ ),
+ true,
+ )
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let payload = &response.data.into_json().unwrap()["deleteCalendarEvent"];
+ assert_eq!(payload["event"], Value::Null);
+ assert_eq!(payload["deletedEventId"], EVENT_ID.to_string());
+ assert_eq!(payload["occurrences"][0]["isCancelled"], true);
+ assert_eq!(
+ payload["occurrences"][0]["event"]["id"],
+ EVENT_ID.to_string()
+ );
+}
diff --git a/crates/graphql_calendar/src/objects.rs b/crates/graphql_calendar/src/objects.rs
index 346365f45c..cd469eefbb 100644
--- a/crates/graphql_calendar/src/objects.rs
+++ b/crates/graphql_calendar/src/objects.rs
@@ -1,8 +1,11 @@
-use std::{collections::HashMap, sync::Arc};
+use std::{
+ collections::{HashMap, HashSet},
+ sync::Arc,
+};
use async_graphql::{Enum, ID, SimpleObject, Union};
use calendar_events::domain::{
- changes::{CalendarChangesPage, CalendarEventChange, CalendarWatermark},
+ changes::{CalendarChangesPage, CalendarEventChange, CalendarWatermark, EventOccurrence},
models::{
AttendeeResponseStatus, CalendarAttendee, CalendarEvent, CalendarEventSourceContent,
CalendarOccurrence, CalendarSyncStatus, ConferenceProvider, EventReminderOverride,
@@ -624,6 +627,71 @@ impl From<CalendarEventChange> for GraphqlCalendarEventChange {
}
}
+/// An event's committed state after a calendar mutation.
+#[derive(SimpleObject, Clone, Debug, PartialEq, Eq)]
+pub struct GraphqlCalendarMutationPayload {
+ /// The series event after the write; null when it no longer exists or
+ /// has no visible occurrence left.
+ event: Option<Arc<GraphqlCalendarEvent>>,
+ /// Every visible occurrence of the event after the write, then each
+ /// occurrence the write removed, returned with `isCancelled: true` so a
+ /// normalized cache hides it as the response lands. Clients replace
+ /// everything they hold for the event with the uncancelled ones.
+ occurrences: Vec<GraphqlCalendarOccurrence>,
+ /// Set to the event's id when the write removed it.
+ deleted_event_id: Option<ID>,
+}
+
+impl GraphqlCalendarMutationPayload {
+ pub(crate) fn new(
+ event_id: Uuid,
+ before: Option<CalendarEventChange>,
+ after: Option<CalendarEventChange>,
+ ) -> Self {
+ let Some(after) = after else {
+ let occurrences = before
+ .map(|before| {
+ GraphqlCalendarEventChange::from(CalendarEventChange {
+ occurrences: before.occurrences.into_iter().map(cancelled).collect(),
+ ..before
+ })
+ .occurrences
+ })
+ .unwrap_or_default();
+ return Self {
+ event: None,
+ occurrences,
+ deleted_event_id: Some(id(event_id)),
+ };
+ };
+ let kept: HashSet<String> = after
+ .occurrences
+ .iter()
+ .map(|instance| instance.occurrence.occurrence_key.clone())
+ .collect();
+ let removed = before
+ .into_iter()
+ .flat_map(|before| before.occurrences)
+ .filter(|instance| !kept.contains(&instance.occurrence.occurrence_key))
+ .map(cancelled);
+ let GraphqlCalendarEventChange { event, occurrences } = CalendarEventChange {
+ occurrences: after.occurrences.into_iter().chain(removed).collect(),
+ ..after
+ }
+ .into();
+ Self {
+ event: Some(event),
+ occurrences,
+ deleted_event_id: None,
+ }
+ }
+}
+
+fn cancelled(mut instance: EventOccurrence) -> EventOccurrence {
+ instance.occurrence.is_cancelled = true;
+ instance
+}
+
/// One bounded page of calendar changes after a watermark.
#[derive(SimpleObject, Clone, Debug, PartialEq, Eq)]
pub struct GraphqlCalendarChanges {
diff --git a/crates/graphql_calendar/src/user_query/test.rs b/crates/graphql_calendar/src/user_query/test.rs
index 2b660d3277..bf08c6ef3b 100644
--- a/crates/graphql_calendar/src/user_query/test.rs
+++ b/crates/graphql_calendar/src/user_query/test.rs
@@ -130,6 +130,13 @@ impl CalendarChangeQueryService for FakeReads {
self.fail()?;
Ok(self.changes.clone())
}
+ async fn event_change(
+ &self,
+ _viewer: &str,
+ _event_id: uuid::Uuid,
+ ) -> Result<Option<CalendarEventChange>, Report> {
+ unreachable!("queries never read one event's committed state")
+ }
}
const VIEWER: &str = "macro|[email protected]";
diff --git a/crates/graphql_calendar/src/writes.rs b/crates/graphql_calendar/src/writes.rs
new file mode 100644
index 0000000000..8f4d183177
--- /dev/null
+++ b/crates/graphql_calendar/src/writes.rs
@@ -0,0 +1,170 @@
+use std::{future::Future, pin::Pin, sync::Arc};
+
+use calendar_events::domain::{
+ changes::{CalendarChangeQueryService, CalendarEventChange},
+ models::{AttendeeResponseStatus, CalendarEvent, CalendarEventDraft, CalendarEventPatch},
+ ports::{
+ CalendarDeletionScope, CalendarMutationError, CalendarMutationService, CalendarRsvpScope,
+ CalendarUpdateScope,
+ },
+};
+use uuid::Uuid;
+
+use crate::reads::ReadFuture;
+
+pub(crate) type WriteFuture<'a, T> =
+ Pin<Box<dyn Future<Output = Result<T, CalendarMutationError>> + Send + 'a>>;
+
+/// Object-safe view of the calendar mutation service and the primary-pool
+/// read that answers each mutation with the event's committed state.
+pub(crate) trait CalendarGraphqlWrites: Send + Sync {
+ fn create_event(
+ &self,
+ viewer: String,
+ email_link_id: Option<Uuid>,
+ calendar_id: Option<Uuid>,
+ draft: CalendarEventDraft,
+ ) -> WriteFuture<'_, CalendarEvent>;
+
+ fn update_event(
+ &self,
+ viewer: String,
+ event_id: Uuid,
+ calendar_id: Option<Uuid>,
+ patch: CalendarEventPatch,
+ scope: CalendarUpdateScope,
+ ) -> WriteFuture<'_, CalendarEvent>;
+
+ fn delete_event(
+ &self,
+ viewer: String,
+ event_id: Uuid,
+ calendar_id: Option<Uuid>,
+ scope: CalendarDeletionScope,
+ ) -> WriteFuture<'_, ()>;
+
+ fn respond_to_event(
+ &self,
+ viewer: String,
+ event_id: Uuid,
+ calendar_id: Option<Uuid>,
+ response: AttendeeResponseStatus,
+ scope: CalendarRsvpScope,
+ responding_email: Option<String>,
+ ) -> WriteFuture<'_, CalendarEvent>;
+
+ fn event_change(
+ &self,
+ viewer: String,
+ event_id: Uuid,
+ ) -> ReadFuture<'_, Option<CalendarEventChange>>;
+}
+
+/// Type-erased calendar mutation service stored in GraphQL request data.
+#[derive(Clone)]
+pub struct CalendarGraphqlMutationContext {
+ pub(crate) writes: Arc<dyn CalendarGraphqlWrites>,
+}
+
+impl CalendarGraphqlMutationContext {
+ /// Erase `mutations`, which performs provider writes, and
+ /// `committed_changes`, which must read the primary database so each
+ /// mutation answers with the state its write committed.
+ pub fn new<M, C>(mutations: Arc<M>, committed_changes: Arc<C>) -> Self
+ where
+ M: CalendarMutationService,
+ C: CalendarChangeQueryService,
+ {
+ Self {
+ writes: Arc::new(ServiceWrites {
+ mutations,
+ committed_changes,
+ }),
+ }
+ }
+}
+
+struct ServiceWrites<M, C> {
+ mutations: Arc<M>,
+ committed_changes: Arc<C>,
+}
+
+impl<M, C> CalendarGraphqlWrites for ServiceWrites<M, C>
+where
+ M: CalendarMutationService,
+ C: CalendarChangeQueryService,
+{
+ fn create_event(
+ &self,
+ viewer: String,
+ email_link_id: Option<Uuid>,
+ calendar_id: Option<Uuid>,
+ draft: CalendarEventDraft,
+ ) -> WriteFuture<'_, CalendarEvent> {
+ Box::pin(async move {
+ self.mutations
+ .create_event(&viewer, email_link_id, calendar_id, draft)
+ .await
+ })
+ }
+
+ fn update_event(
+ &self,
+ viewer: String,
+ event_id: Uuid,
+ calendar_id: Option<Uuid>,
+ patch: CalendarEventPatch,
+ scope: CalendarUpdateScope,
+ ) -> WriteFuture<'_, CalendarEvent> {
+ Box::pin(async move {
+ self.mutations
+ .update_event(&viewer, event_id, calendar_id, patch, scope)
+ .await
+ })
+ }
+
+ fn delete_event(
+ &self,
+ viewer: String,
+ event_id: Uuid,
+ calendar_id: Option<Uuid>,
+ scope: CalendarDeletionScope,
+ ) -> WriteFuture<'_, ()> {
+ Box::pin(async move {
+ self.mutations
+ .delete_event(&viewer, event_id, calendar_id, scope)
+ .await
+ })
+ }
+
+ fn respond_to_event(
+ &self,
+ viewer: String,
+ event_id: Uuid,
+ calendar_id: Option<Uuid>,
+ response: AttendeeResponseStatus,
+ scope: CalendarRsvpScope,
+ responding_email: Option<String>,
+ ) -> WriteFuture<'_, CalendarEvent> {
+ Box::pin(async move {
+ self.mutations
+ .respond_to_event(
+ &viewer,
+ event_id,
+ calendar_id,
+ response,
+ scope,
+ responding_email,
+ )
+ .await
+ })
+ }
+
+ fn event_change(
+ &self,
+ viewer: String,
+ event_id: Uuid,
+ ) -> ReadFuture<'_, Option<CalendarEventChange>> {
+ Box::pin(async move { self.committed_changes.event_change(&viewer, event_id).await })
+ }
+}
diff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.toml
index 20185816a6..bbf69caafa 100644
--- a/services/document_storage_service/Cargo.toml
+++ b/services/document_storage_service/Cargo.toml
@@ -58,7 +58,7 @@ base64 = { workspace = true }
bots = { path = "../../crates/bots" }
bot_id = { path = "../../crates/bot_id" }
bytes = { workspace = true }
-calendar_events = { path = "../../crates/calendar_events", features = ["dispatch-sqs", "inbound", "notify", "postgres"] }
+calendar_events = { path = "../../crates/calendar_events", features = ["dispatch-sqs", "inbound", "mutation-client", "notify", "postgres"] }
bzip2 = { workspace = true, default-features = false, features = [
"libbz2-rs-sys",
] }
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index 1cf062b6cd..6c002ada39 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -816,6 +816,7 @@ pub(crate) struct ApiContext {
pub graphql_initiative_context: graphql_initiative::InitiativeGraphqlContext,
pub graphql_scheduled_action_context: graphql_scheduled_action::ScheduledActionGraphqlContext,
pub graphql_calendar_context: graphql_calendar::CalendarGraphqlContext,
+ pub graphql_calendar_mutation_context: graphql_calendar::CalendarGraphqlMutationContext,
pub graphql_initiative_entity_loader: graphql_initiative::InitiativeEntityLoader,
pub graphql_agent_session_entity_loader: graphql_soup::AgentSessionEntityLoader,
pub databases_state: DssDatabasesState,
diff --git a/services/document_storage_service/src/api/graphql_soup.rs b/services/document_storage_service/src/api/graphql_soup.rs
index f18df15aa1..6ff0ae62c1 100644
--- a/services/document_storage_service/src/api/graphql_soup.rs
+++ b/services/document_storage_service/src/api/graphql_soup.rs
@@ -172,6 +172,7 @@ fn insert_graphql_context_data(
data.insert(state.graphql_initiative_context.clone());
data.insert(state.graphql_scheduled_action_context.clone());
data.insert(state.graphql_calendar_context.clone());
+ data.insert(state.graphql_calendar_mutation_context.clone());
data.insert(state.graphql_initiative_entity_loader.clone());
data.insert(state.graphql_agent_session_entity_loader.clone());
data.insert(graphql_initiative::initiative_detail_loader(
diff --git a/services/document_storage_service/src/server.rs b/services/document_storage_service/src/server.rs
index ea2b141460..4edd080e35 100644
--- a/services/document_storage_service/src/server.rs
+++ b/services/document_storage_service/src/server.rs
@@ -1744,6 +1744,23 @@ pub async fn run() -> anyhow::Result<()> {
);
let calendar_state =
CalendarRouterState::new(calendar_read_service, authorization_state.clone());
+ // Calendar writes belong to calendar_service; each GraphQL mutation then
+ // answers from the primary so it reads the state its write committed.
+ let graphql_calendar_mutation_context = graphql_calendar::CalendarGraphqlMutationContext::new(
+ Arc::new(
+ calendar_events::outbound::calendar_service_mutations::CalendarServiceMutations::new(
+ macro_service_urls::CalendarServiceUrl::new()
+ .context("calendar service url")?
+ .to_string(),
+ config.internal_api_key.to_string(),
+ ),
+ ),
+ Arc::new(
+ calendar_events::domain::changes::CalendarChangeService::new(
+ calendar_events::outbound::pg::PgCalendarRepository::new(db.clone()),
+ ),
+ ),
+ );
// Reminder dispatch. An EventBridge rule drops a sweep tick on this queue
// every minute; the sweep fans one message out per due firing, onto the
@@ -1920,6 +1937,7 @@ pub async fn run() -> anyhow::Result<()> {
scheduled_action_read_service,
),
graphql_calendar_context,
+ graphql_calendar_mutation_context,
initiative_state: InitiativeRouterState::new(
initiative_service,
entity_access_service.clone(),
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index f2cd7c5a25..99b398ca81 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -23,6 +23,34 @@ input ActivityOverviewInput {
timeZone: String
}
+"""
+An all-day span with an exclusive end date.
+"""
+input AllDayEventTimeInput {
+ """
+ Inclusive local start date (`YYYY-MM-DD`).
+ """
+ startDate: String!
+ """
+ Exclusive local end date (`YYYY-MM-DD`).
+ """
+ endDate: String!
+}
+
+"""
+An attendee to invite.
+"""
+input CalendarAttendeeInput {
+ """
+ Attendee email address.
+ """
+ email: String!
+ """
+ Whether attendance is optional.
+ """
+ isOptional: Boolean! = false
+}
+
"""
A request for calendar changes after a watermark.
"""
@@ -34,6 +62,20 @@ input CalendarChangesInput {
since: [CalendarLinkWatermarkInput!]!
}
+"""
+The time shape of an event.
+"""
+input CalendarEventTimeInput @oneOf {
+ """
+ A span with absolute instants.
+ """
+ timed: TimedEventTimeInput
+ """
+ An all-day span.
+ """
+ allDay: AllDayEventTimeInput
+}
+
"""
How far the client has applied one connected inbox's change log.
"""
@@ -48,6 +90,21 @@ input CalendarLinkWatermarkInput {
seq: String!
}
+"""
+Out-of-office properties. Present to create or edit an out-of-office
+status event.
+"""
+input CalendarOutOfOfficeInput {
+ """
+ How conflicting invitations are handled while the user is out.
+ """
+ autoDeclineMode: GraphqlCalendarOutOfOfficeAutoDeclineMode! = DECLINE_NONE
+ """
+ Message returned to organizers whose invitations are auto-declined.
+ """
+ declineMessage: String
+}
+
"""
A bounded occurrence viewport and page request.
"""
@@ -80,6 +137,34 @@ input CalendarRangeInput {
after: String
}
+"""
+One reminder.
+"""
+input CalendarReminderOverrideInput {
+ """
+ Delivery method (`popup` or `email`).
+ """
+ method: String!
+ """
+ Minutes before the start the reminder fires.
+ """
+ minutes: Int!
+}
+
+"""
+An event's reminder configuration.
+"""
+input CalendarRemindersInput {
+ """
+ Whether the calendar's default reminders apply.
+ """
+ useDefault: Boolean!
+ """
+ Explicit reminders, used when `useDefault` is false.
+ """
+ overrides: [CalendarReminderOverrideInput!]! = []
+}
+
"""
Channel activity operation exposed by GraphQL.
"""
@@ -228,6 +313,22 @@ type CompleteMutationRoot {
Delete an initiative after its owner capability has been verified.
"""
deleteInitiative(initiativeId: ID!): Boolean!
+ """
+ Create an event on one of the viewer's writable calendars.
+ """
+ createCalendarEvent(input: CreateCalendarEventInput!): GraphqlCalendarMutationPayload!
+ """
+ Patch an event, the whole series or one occurrence.
+ """
+ updateCalendarEvent(input: UpdateCalendarEventInput!): GraphqlCalendarMutationPayload!
+ """
+ Delete an event, one occurrence, or an occurrence onward.
+ """
+ deleteCalendarEvent(input: DeleteCalendarEventInput!): GraphqlCalendarMutationPayload!
+ """
+ Set the viewer's RSVP on an event, the whole series or one occurrence.
+ """
+ respondToCalendarEvent(input: RespondToCalendarEventInput!): GraphqlCalendarMutationPayload!
}
"""
@@ -257,6 +358,71 @@ type CompleteSubscriptionRoot {
activityUpdates: GraphqlActivityPatch!
}
+"""
+Create an event on one of the viewer's writable calendars.
+"""
+input CreateCalendarEventInput {
+ """
+ Stable retry identity, scoped to the authenticated organizer.
+ """
+ idempotencyKey: ID
+ """
+ Exact calendar to create the event on; takes precedence over the
+ inbox default.
+ """
+ calendarId: ID
+ """
+ Connected inbox whose primary calendar receives the event; defaults
+ to the viewer's primary inbox.
+ """
+ emailLinkId: ID
+ """
+ Display title.
+ """
+ title: String!
+ """
+ Optional event body.
+ """
+ description: String
+ """
+ Optional location label.
+ """
+ location: String
+ """
+ Timed or all-day shape.
+ """
+ time: CalendarEventTimeInput!
+ """
+ Invited attendees.
+ """
+ attendees: [CalendarAttendeeInput!]! = []
+ """
+ Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`).
+ """
+ recurrenceLines: [String!]! = []
+ """
+ Event visibility.
+ """
+ visibility: GraphqlCalendarEventVisibility
+ """
+ Availability behavior.
+ """
+ transparency: GraphqlCalendarEventTransparency
+ """
+ Reminder configuration; omit to keep the calendar defaults.
+ """
+ reminders: CalendarRemindersInput
+ """
+ Conference to attach; omit to create the event without one.
+ """
+ conference: GraphqlCalendarConferenceChange
+ """
+ Present to create an out-of-office status event (primary calendar
+ only, timed, no attendees).
+ """
+ outOfOffice: CalendarOutOfOfficeInput
+}
+
"""
Create an initiative owned by the authenticated viewer.
"""
@@ -283,6 +449,29 @@ input CreateInitiativeInput {
propertyValues: [InitialPropertyValueInput!]
}
+"""
+Delete an event, one occurrence, or an occurrence onward.
+"""
+input DeleteCalendarEventInput {
+ """
+ Event to delete.
+ """
+ eventId: ID!
+ """
+ Calendar whose copy of the event is deleted, for an event synced from
+ more than one calendar. Omit to delete the canonical copy.
+ """
+ calendarId: ID
+ """
+ Deletion scope; defaults to the entire event or series.
+ """
+ scope: GraphqlCalendarDeletionScope! = ALL
+ """
+ Original-start key of the occurrence a scoped deletion targets.
+ """
+ recurrenceId: String
+}
+
"""
Input for deleting an email draft.
"""
@@ -1167,6 +1356,20 @@ type GraphqlCalendarChanges {
resetRequired: Boolean!
}
+"""
+A change to an event's conference.
+"""
+enum GraphqlCalendarConferenceChange {
+ """
+ Generate a new Google Meet conference and attach it.
+ """
+ GOOGLE_MEET
+ """
+ Detach whatever conference is currently attached.
+ """
+ NONE
+}
+
"""
Conferencing system backing an event's join URL.
"""
@@ -1181,6 +1384,24 @@ enum GraphqlCalendarConferenceProvider {
OTHER
}
+"""
+How much of a recurring series a deletion removes.
+"""
+enum GraphqlCalendarDeletionScope {
+ """
+ The entire event or series.
+ """
+ ALL
+ """
+ One occurrence.
+ """
+ THIS_EVENT
+ """
+ One occurrence and everything after it.
+ """
+ THIS_AND_FOLLOWING
+}
+
"""
A calendar event entity: the series content shared by every occurrence.
"""
@@ -1567,6 +1788,28 @@ type GraphqlCalendarLinkWatermark {
seq: String!
}
+"""
+An event's committed state after a calendar mutation.
+"""
+type GraphqlCalendarMutationPayload {
+ """
+ The series event after the write; null when it no longer exists or
+ has no visible occurrence left.
+ """
+ event: GraphqlCalendarEvent
+ """
+ Every visible occurrence of the event after the write, then each
+ occurrence the write removed, returned with `isCancelled: true` so a
+ normalized cache hides it as the response lands. Clients replace
+ everything they hold for the event with the uncancelled ones.
+ """
+ occurrences: [GraphqlCalendarOccurrence!]!
+ """
+ Set to the event's id when the write removed it.
+ """
+ deletedEventId: ID
+}
+
"""
One materialized instance of a calendar event.
@@ -1656,6 +1899,24 @@ type GraphqlCalendarOccurrencePage {
watermark: [GraphqlCalendarLinkWatermark!]!
}
+"""
+How an out-of-office event answers conflicting invitations.
+"""
+enum GraphqlCalendarOutOfOfficeAutoDeclineMode {
+ """
+ Leave conflicting invitations alone.
+ """
+ DECLINE_NONE
+ """
+ Decline every conflicting invitation, existing and new.
+ """
+ DECLINE_ALL_CONFLICTING_INVITATIONS
+ """
+ Decline only invitations that arrive after the event is created.
+ """
+ DECLINE_ONLY_NEW_CONFLICTING_INVITATIONS
+}
+
"""
One reminder override.
"""
@@ -1684,6 +1945,20 @@ type GraphqlCalendarReminders {
overrides: [GraphqlCalendarReminderOverride!]!
}
+"""
+How much of a recurring series an RSVP applies to.
+"""
+enum GraphqlCalendarRsvpScope {
+ """
+ The entire series.
+ """
+ ALL
+ """
+ One occurrence.
+ """
+ THIS_EVENT
+}
+
"""
Aggregate ingestion state across every calendar account visible to the
viewer.
@@ -1699,6 +1974,20 @@ enum GraphqlCalendarSyncStatus {
READY
}
+"""
+How much of a recurring series an update applies to.
+"""
+enum GraphqlCalendarUpdateScope {
+ """
+ The entire event or series.
+ """
+ ALL
+ """
+ One occurrence.
+ """
+ THIS_EVENT
+}
+
"""
The two operands of a recursive `CallFilterExpr` binary expression.
"""
@@ -8272,6 +8561,39 @@ input ReorderFavoritesInput {
favorites: [EntityRefInput!]!
}
+"""
+Set the viewer's RSVP on an event.
+"""
+input RespondToCalendarEventInput {
+ """
+ Event to answer.
+ """
+ eventId: ID!
+ """
+ Calendar whose copy of the event is answered, for an event synced
+ from more than one calendar. Omit to answer on the canonical copy.
+ """
+ calendarId: ID
+ """
+ The response to record.
+ """
+ response: GraphqlCalendarAttendeeResponseStatus!
+ """
+ How much of a recurring series the response covers. Omit to let
+ `recurrenceId` decide: the identified occurrence alone when one is
+ supplied, otherwise the whole series.
+ """
+ scope: GraphqlCalendarRsvpScope
+ """
+ Original-start key of the occurrence the response targets.
+ """
+ recurrenceId: String
+ """
+ The owned connected address whose attendance is changed.
+ """
+ respondingEmail: String
+}
+
"""
One recipient of an email draft.
"""
@@ -8554,6 +8876,94 @@ type SoupUpdated {
item: GraphqlSoupEntity!
}
+"""
+A span with absolute instants.
+"""
+input TimedEventTimeInput {
+ """
+ Inclusive start instant in RFC 3339 format.
+ """
+ startsAt: String!
+ """
+ Exclusive end instant in RFC 3339 format.
+ """
+ endsAt: String!
+ """
+ IANA time-zone identifier the event is anchored to.
+ """
+ timeZone: String
+}
+
+"""
+Patch an event; omitted fields are left untouched.
+"""
+input UpdateCalendarEventInput {
+ """
+ Event to patch.
+ """
+ eventId: ID!
+ """
+ Calendar whose copy of the event is patched, for an event synced from
+ more than one calendar. Omit to patch the canonical copy.
+ """
+ calendarId: ID
+ """
+ Replacement title; an empty string clears it.
+ """
+ title: String
+ """
+ Replacement description; an empty string clears it.
+ """
+ description: String
+ """
+ Replacement location; an empty string clears it.
+ """
+ location: String
+ """
+ Replacement time.
+ """
+ time: CalendarEventTimeInput
+ """
+ Replacement attendee list.
+ """
+ attendees: [CalendarAttendeeInput!]
+ """
+ Replacement recurrence properties; an empty list clears them.
+ """
+ recurrenceLines: [String!]
+ """
+ Replacement visibility.
+ """
+ visibility: GraphqlCalendarEventVisibility
+ """
+ Replacement transparency.
+ """
+ transparency: GraphqlCalendarEventTransparency
+ """
+ Replacement reminder configuration.
+ """
+ reminders: CalendarRemindersInput
+ """
+ Conference change; omit to leave the conference untouched.
+ """
+ conference: GraphqlCalendarConferenceChange
+ """
+ Replacement out-of-office properties, applied only to an event that is
+ already out-of-office.
+ """
+ outOfOffice: CalendarOutOfOfficeInput
+ """
+ How much of a recurring series the update covers. Omit to let
+ `recurrenceId` decide: the identified occurrence alone when one is
+ supplied, otherwise the whole event or series.
+ """
+ scope: GraphqlCalendarUpdateScope
+ """
+ Original-start key of the occurrence the update targets.
+ """
+ recurrenceId: String
+}
+
"""
Input for adding or removing a label from an email thread.
"""