Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(calendar): apply an organizer's guest policy to the guest copies Macro holds (#8828)
gbirmanfbf38f6f2721
diff --git a/.sqlx/query-8a8cea9e22035c727ffc658160b81534f9892d2dfee23a908e9c229a8254e50a.json b/.sqlx/query-8a8cea9e22035c727ffc658160b81534f9892d2dfee23a908e9c229a8254e50a.jsonnew file mode 100644index 0000000000..2462d92620--- /dev/null+++ b/.sqlx/query-8a8cea9e22035c727ffc658160b81534f9892d2dfee23a908e9c229a8254e50a.json@@ -0,0 +1,38 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendar_events event\n SET guests_can_modify = $3,\n guests_can_invite_others = $4,\n guests_can_see_other_guests = $5\n WHERE calendar_meeting_uid(event.ical_uid) = $1\n AND lower(event.organizer_email) = $2\n AND event.status <> 'cancelled'\n AND NOT event.is_snapshot\n AND EXISTS (SELECT 1 FROM calendar_event_sources source\n WHERE source.event_id = event.id AND source.source_kind = 'google')\n AND (event.guests_can_modify, event.guests_can_invite_others,\n event.guests_can_see_other_guests) IS DISTINCT FROM ($3, $4, $5)\n RETURNING event.id, event.owner_id, event.source_link_id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "owner_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "source_link_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Bool",+ "Bool",+ "Bool"+ ]+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "8a8cea9e22035c727ffc658160b81534f9892d2dfee23a908e9c229a8254e50a"+}diff --git a/.sqlx/query-8c8bcc7cd2858540fdbd081ffd1fe7c36c67e568a6081e8dbbdc2e7f8a5262dd.json b/.sqlx/query-8c8bcc7cd2858540fdbd081ffd1fe7c36c67e568a6081e8dbbdc2e7f8a5262dd.jsonnew file mode 100644index 0000000000..3e15b47e22--- /dev/null+++ b/.sqlx/query-8c8bcc7cd2858540fdbd081ffd1fe7c36c67e568a6081e8dbbdc2e7f8a5262dd.json@@ -0,0 +1,40 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH written AS (\n SELECT calendar_meeting_uid(ical_uid) AS meeting, lower(organizer_email) AS organizer\n FROM calendar_events\n WHERE id = $1 AND organizer_email IS NOT NULL\n )\n SELECT source.id AS source_id,\n written.meeting AS \"meeting!\",\n written.organizer AS \"organizer!\",\n source.normalized_payload -> 'event' -> 'guestPolicy' AS policy\n FROM written\n JOIN calendar_events event\n ON calendar_meeting_uid(event.ical_uid) = written.meeting\n AND lower(event.organizer_email) = written.organizer\n JOIN calendar_event_sources source\n ON source.event_id = event.id AND source.source_kind = 'google'\n JOIN calendars calendar\n ON calendar.id = source.calendar_id AND calendar.account_id = source.account_id\n WHERE event.status <> 'cancelled'\n AND NOT event.is_snapshot\n AND NOT calendar.is_deleted\n AND calendar.access_role IN ('owner', 'writer')\n AND lower(calendar.provider_calendar_id) = written.organizer\n ORDER BY source.source_updated_at DESC NULLS LAST, source.id\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "source_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "meeting!",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "organizer!",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "policy",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ null,+ null,+ null+ ]+ },+ "hash": "8c8bcc7cd2858540fdbd081ffd1fe7c36c67e568a6081e8dbbdc2e7f8a5262dd"+}diff --git a/.sqlx/query-e2c6ce788ac84c8a60bf65ea1bc2c3d8324104cea0765df0e0d7261b813185f9.json b/.sqlx/query-e2c6ce788ac84c8a60bf65ea1bc2c3d8324104cea0765df0e0d7261b813185f9.jsonnew file mode 100644index 0000000000..a05d1914b0--- /dev/null+++ b/.sqlx/query-e2c6ce788ac84c8a60bf65ea1bc2c3d8324104cea0765df0e0d7261b813185f9.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendar_event_sources source\n SET normalized_payload = CASE WHEN $4::jsonb IS NULL\n THEN source.normalized_payload #- '{event,guestPolicy}'\n ELSE jsonb_set(source.normalized_payload, '{event,guestPolicy}', $4)\n END\n FROM calendar_events event\n WHERE source.event_id = event.id\n AND source.source_kind = 'google'\n AND source.id <> $3\n AND source.normalized_payload ? 'event'\n AND (source.normalized_payload -> 'event' -> 'guestPolicy') IS DISTINCT FROM $4::jsonb\n AND calendar_meeting_uid(event.ical_uid) = $1\n AND lower(event.organizer_email) = $2\n AND event.status <> 'cancelled'\n AND NOT event.is_snapshot\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Uuid",+ "Jsonb"+ ]+ },+ "nullable": []+ },+ "hash": "e2c6ce788ac84c8a60bf65ea1bc2c3d8324104cea0765df0e0d7261b813185f9"+}diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.mdindex 16e5f5ea55..144e53341f 100644--- a/crates/calendar_events/AGENTS.md+++ b/crates/calendar_events/AGENTS.md@@ -92,6 +92,23 @@ reminder dispatch, team availability, and provider/Postgres persistence.`InvalidInput`.`ViewerCapabilities::set_guest_policy` is therefore Google-only, and`organize` is the organizer signal clients read instead.+- The organizer's own copy decides the guest policy of every Macro-held copy+ of a Google meeting (`src/outbound/pg/guest_policy.rs`). Google takes 4 to+ 12 seconds to carry an organizer's change to its guests' copies, and a guest+ invite in that window gets a 200 while Google drops the guest and mails+ nobody. The organizer's copy is the Google source on the calendar Google+ names as the organizer (the address for a primary calendar, the calendar id+ for a secondary one) that its inbox can write: the copy+ `organizer_copy_calendar_id` routes organizer writes through. Every upsert+ reads that source's policy and writes it to each entity of the meeting with+ that organizer (the organizer's own, when its canonical copy is the+ primary-calendar invitation, included) and to every other Google source's+ projection, across users, so a guest-side write or an invitation read-back+ echoing Google's stale switches cannot reopen inviting. Copies pair by+ `calendar_meeting_uid` and organizer; Outlook copies and snapshots take no+ part. The aligned copies' inboxes get change-log entries and refresh nudges+ (`CalendarEventWriteOutcome::aligned_copies`). An organizer whose calendar+ no Macro inbox writes still reaches guests only through Google's sync.- Sharing an event into a channel writes an `entity_access` row on thesharer's copy. The `calendar_event_entity_access_cleanup` trigger deletes itwith the event row, which covers every way a copy goes away: a deletediff --git a/crates/calendar_events/src/domain/models.rs b/crates/calendar_events/src/domain/models.rsindex e6d7a99986..8e92c78c6f 100644--- a/crates/calendar_events/src/domain/models.rs+++ b/crates/calendar_events/src/domain/models.rs@@ -1852,8 +1852,20 @@ pub struct GoogleCalendarSyncSnapshot {pub cancelled_provider_event_ids: Vec<String>,}+/// A guest copy of a meeting whose stored guest policy changed to follow+/// the organizer's copy.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct AlignedGuestCopy {+ /// The copy's entity.+ pub event_id: Uuid,+ /// The copy's owner.+ pub owner_id: String,+ /// The inbox the copy syncs through.+ pub email_link_id: Uuid,+}+/// What one Google backfill run changed, for change-driven notifications.-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+#[derive(Clone, Debug, Default, PartialEq, Eq)]pub struct GoogleBackfillRunReport {/// A source, calendar, or failed coverage check may have changed OOO access.pub team_ooo_changed: bool,@@ -1865,6 +1877,9 @@ pub struct GoogleBackfillRunReport {/// retired: unobserved by a full snapshot, or on a calendar the account/// no longer lists.pub events_retired: usize,+ /// Guest copies in other inboxes whose guest policy changed to follow an+ /// organizer's copy this run wrote; their viewers need a refresh too.+ pub aligned_copies: Vec<AlignedGuestCopy>,}impl GoogleBackfillRunReport {diff --git a/crates/calendar_events/src/domain/mutations.rs b/crates/calendar_events/src/domain/mutations.rsindex d3c862f6c0..079100122a 100644--- a/crates/calendar_events/src/domain/mutations.rs+++ b/crates/calendar_events/src/domain/mutations.rs@@ -237,6 +237,11 @@ where.calendar_changed(&outcome.owner_id, email_link_id, outcome.team_ooo_changed).await;}+ for copy in &outcome.aligned_copies {+ self.refresh+ .calendar_changed(©.owner_id, copy.email_link_id, false)+ .await;+ }if let Some(viewer) = viewer {viewer.mark_event(&mut event, email_link_id);}diff --git a/crates/calendar_events/src/domain/mutations/test.rs b/crates/calendar_events/src/domain/mutations/test.rsindex f4191e827c..ac0fe37791 100644--- a/crates/calendar_events/src/domain/mutations/test.rs+++ b/crates/calendar_events/src/domain/mutations/test.rs@@ -202,6 +202,8 @@ struct FakeRepo {join_requests: Arc<Mutex<Vec<crate::domain::join_requests::CalendarJoinRequest>>>,/// The requester's copies of the addressed meeting.meeting_copies: Vec<crate::domain::models::MeetingCopy>,+ /// Guest copies a write reports aligning with its organizer's policy.+ aligned_copies: Vec<crate::domain::models::AlignedGuestCopy>,/// Copies on other calendars, addressed by their calendar id.copy_targets: Vec<CalendarEventMutationTarget>,}@@ -231,6 +233,7 @@ impl Default for FakeRepo {scheduled_syncs: Default::default(),join_requests: Default::default(),meeting_copies: Vec::new(),+ aligned_copies: Vec::new(),copy_targets: Vec::new(),}}@@ -273,6 +276,7 @@ impl CalendarRepository for FakeRepo {owner_id,change: self.write_change,team_ooo_changed,+ aligned_copies: self.aligned_copies.clone(),})}@@ -1287,6 +1291,37 @@ async fn a_persisted_mutation_nudges_the_links_calendar_viewers() {);}+#[tokio::test]+async fn a_policy_reaching_guest_copies_nudges_their_viewers() {+ let guest_link = Uuid::now_v7();+ let repo = FakeRepo {+ creation_target: Some(creation_target(false)),+ write_change: CalendarEventChange::Updated,+ aligned_copies: vec![crate::domain::models::AlignedGuestCopy {+ event_id: Uuid::now_v7(),+ owner_id: "macro|[email protected]".into(),+ email_link_id: guest_link,+ }],+ ..FakeRepo::default()+ };+ let refresh = RecordingRefreshNotifier::default();+ service_with_refresh(+ repo,+ FakeProvider::new(FakeProviderBehavior::Echo),+ FakeTokens::ok(),+ refresh.clone(),+ )+ .create_event("macro|user", None, None, draft())+ .await+ .unwrap();++ let notified = refresh.notified.lock().expect("notifier lock").clone();+ assert!(+ notified.contains(&("macro|[email protected]".to_string(), guest_link, false)),+ "{notified:?}"+ );+}+#[tokio::test]async fn a_write_that_changed_nothing_sends_no_refresh_nudge() {let repo = FakeRepo {diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rsindex 34ed2e1692..08c62a7dd0 100644--- a/crates/calendar_events/src/domain/ports.rs+++ b/crates/calendar_events/src/domain/ports.rs@@ -13,7 +13,7 @@ use super::meeting_links::{CreateEventWithMacroCallError, MeetingLink, MeetingLinkError, MeetingLinkRequest,};use super::models::{- ActorInboxes, AppliedGoogleGrant, AttendeeResponseStatus, CalendarAttendee,+ ActorInboxes, AlignedGuestCopy, AppliedGoogleGrant, AttendeeResponseStatus, CalendarAttendee,CalendarAttendeeInput, CalendarBackfillClaim, CalendarBackfillFailureDisposition,CalendarBackfillFailureOutcome, CalendarBackfillJobKey, CalendarCreationTarget, CalendarEvent,CalendarEventDraft, CalendarEventMutationTarget, CalendarEventPatch, CalendarEventUpsert,@@ -528,6 +528,10 @@ pub struct CalendarEventWriteOutcome {pub change: CalendarEventChange,/// A changed source was or is OOO; it may revoke a teammate's status/title.pub team_ooo_changed: bool,+ /// Guest copies of the same meeting, in any inbox Macro holds, whose+ /// guest policy changed to follow this copy's organizer. Their viewers+ /// need a refresh too.+ pub aligned_copies: Vec<AlignedGuestCopy>,}/// One event's fate after its sources were retired.diff --git a/crates/calendar_events/src/domain/service.rs b/crates/calendar_events/src/domain/service.rsindex 6440035c9b..33b1f60ba3 100644--- a/crates/calendar_events/src/domain/service.rs+++ b/crates/calendar_events/src/domain/service.rs@@ -902,6 +902,7 @@ where.await?;self.publish_write_outcome(&outcome);report.team_ooo_changed |= outcome.team_ooo_changed;+ report.aligned_copies.extend(outcome.aligned_copies);calendar_count += 1;}// The upserts above committed individually, so they count evendiff --git a/crates/calendar_events/src/domain/service/test.rs b/crates/calendar_events/src/domain/service/test.rsindex 36f601bd20..afc09467dc 100644--- a/crates/calendar_events/src/domain/service/test.rs+++ b/crates/calendar_events/src/domain/service/test.rs@@ -76,6 +76,7 @@ impl CalendarRepository for FakeRepo {owner_id,change: CalendarEventChange::Created,team_ooo_changed,+ aligned_copies: Vec::new(),})}diff --git a/crates/calendar_events/src/outbound/pg.rs b/crates/calendar_events/src/outbound/pg.rsindex 8184eaccff..1667c2cd05 100644--- a/crates/calendar_events/src/outbound/pg.rs+++ b/crates/calendar_events/src/outbound/pg.rs@@ -3,6 +3,7 @@ mod change_log;mod changes;mod details;mod export;+mod guest_policy;mod invitations;mod join_requests;#[cfg(feature = "outlook")]@@ -25,7 +26,7 @@ use crate::domain::{changes::CalendarChangeOp,ics::CalendarEventExport,models::{- ActorInboxes, AppliedGoogleGrant, AttendeeResponseStatus,+ ActorInboxes, AlignedGuestCopy, AppliedGoogleGrant, AttendeeResponseStatus,CALENDAR_SYNC_FAILURE_BADGE_THRESHOLD, CalendarAttendee, CalendarBackfillClaim,CalendarBackfillFailureDisposition, CalendarBackfillFailureOutcome, CalendarBackfillJob,CalendarBackfillJobKey, CalendarBackfillKind, CalendarCapabilities, CalendarCreationTarget,@@ -932,6 +933,7 @@ impl CalendarRepository for PgCalendarRepository {owner_id: upsert.event.owner_id.clone(),change: CalendarEventChange::Unchanged,team_ooo_changed: false,+ aligned_copies: Vec::new(),});}}@@ -1042,6 +1044,7 @@ impl CalendarRepository for PgCalendarRepository {owner_id: upsert.event.owner_id.clone(),change: CalendarEventChange::Unchanged,team_ooo_changed: false,+ aligned_copies: Vec::new(),});};if provider_sync {@@ -1087,9 +1090,26 @@ impl CalendarRepository for PgCalendarRepository {.await?;}+ let mut aligned = guest_policy::align_with_organizer(&mut tx, event_id).await?;+ // A guest copy that took its organizer's policy is the write itself,+ // already logged and refreshed below.+ aligned.retain(|copy| copy.event_id != event_id);let mut log = ChangeLogBatch::default();log.record(source_link_id, CalendarChangeOp::UpsertEvent(event_id));+ for copy in &aligned {+ log.record(+ copy.email_link_id,+ CalendarChangeOp::UpsertEvent(copy.event_id),+ );+ }log.commit(tx).await?;+ if !aligned.is_empty() {+ tracing::info!(+ %event_id,+ aligned = aligned.len(),+ "guest copies now follow their organizer's guest policy"+ );+ }if became_seat {tracing::info!(%event_id,@@ -1105,6 +1125,7 @@ impl CalendarRepository for PgCalendarRepository {CalendarEventChange::Updated},team_ooo_changed,+ aligned_copies: aligned,})}diff --git a/crates/calendar_events/src/outbound/pg/guest_policy.rs b/crates/calendar_events/src/outbound/pg/guest_policy.rsnew file mode 100644index 0000000000..bc49ee4308--- /dev/null+++ b/crates/calendar_events/src/outbound/pg/guest_policy.rs@@ -0,0 +1,140 @@+//! Keep every Macro-held copy of a Google meeting on the guest policy of the+//! organizer's own copy, when Macro holds that copy.+//!+//! Google takes 4 to 12 seconds to carry an organizer's policy change to its+//! guests' copies. A guest who invites someone in that window gets a 200+//! while Google drops the guest without telling anyone, so Macro applies the+//! organizer's change to every copy it holds as soon as it stores the+//! organizer's copy, and a copy written back meanwhile keeps the organizer's+//! switches instead of the stale ones Google echoes.+use super::*;++/// Align the copies of `event_id`'s meeting after it was stored.+///+/// The organizer's copy is the Google source on the calendar Google names as+/// the organizer, the user's address for a primary calendar or a secondary+/// calendar's id, which the syncing inbox can write; it is the copy+/// [`CalendarEventMutationTarget::organizer_copy_calendar_id`] routes the+/// organizer's writes through. Its policy goes to every entity of the meeting+/// with that organizer, the organizer's own included when its canonical copy+/// is an invitation, and to every other Google source's projection. Outlook+/// copies have no guest policy and snapshots grant nothing, so neither takes+/// part. Returns the entities whose stored policy changed.+#[tracing::instrument(+ name = "calendar.align_guest_policy",+ skip(tx),+ fields(aligned = tracing::field::Empty),+ err+)]+pub(super) async fn align_with_organizer(+ tx: &mut Transaction<'_, Postgres>,+ event_id: Uuid,+) -> Result<Vec<AlignedGuestCopy>, Report> {+ let organizer = sqlx::query!(+ r#"+ WITH written AS (+ SELECT calendar_meeting_uid(ical_uid) AS meeting, lower(organizer_email) AS organizer+ FROM calendar_events+ WHERE id = $1 AND organizer_email IS NOT NULL+ )+ SELECT source.id AS source_id,+ written.meeting AS "meeting!",+ written.organizer AS "organizer!",+ source.normalized_payload -> 'event' -> 'guestPolicy' AS policy+ FROM written+ JOIN calendar_events event+ ON calendar_meeting_uid(event.ical_uid) = written.meeting+ AND lower(event.organizer_email) = written.organizer+ JOIN calendar_event_sources source+ ON source.event_id = event.id AND source.source_kind = 'google'+ JOIN calendars calendar+ ON calendar.id = source.calendar_id AND calendar.account_id = source.account_id+ WHERE event.status <> 'cancelled'+ AND NOT event.is_snapshot+ AND NOT calendar.is_deleted+ AND calendar.access_role IN ('owner', 'writer')+ AND lower(calendar.provider_calendar_id) = written.organizer+ ORDER BY source.source_updated_at DESC NULLS LAST, source.id+ LIMIT 1+ "#,+ event_id,+ )+ .fetch_optional(&mut **tx)+ .await+ .map_err(report)?;+ let Some(organizer) = organizer else {+ tracing::Span::current().record("aligned", 0);+ return Ok(Vec::new());+ };+ // The projection omits Google's default, as a freshly synced one does.+ let policy = match organizer.policy {+ Some(policy) => serde_json::from_value::<GuestPolicy>(policy).map_err(report)?,+ None => GuestPolicy::default(),+ };+ let projected = (!policy.is_default())+ .then(|| serde_json::to_value(policy))+ .transpose()+ .map_err(report)?;+ let rows = sqlx::query!(+ r#"+ UPDATE calendar_events event+ SET guests_can_modify = $3,+ guests_can_invite_others = $4,+ guests_can_see_other_guests = $5+ WHERE calendar_meeting_uid(event.ical_uid) = $1+ AND lower(event.organizer_email) = $2+ AND event.status <> 'cancelled'+ AND NOT event.is_snapshot+ AND EXISTS (SELECT 1 FROM calendar_event_sources source+ WHERE source.event_id = event.id AND source.source_kind = 'google')+ AND (event.guests_can_modify, event.guests_can_invite_others,+ event.guests_can_see_other_guests) IS DISTINCT FROM ($3, $4, $5)+ RETURNING event.id, event.owner_id, event.source_link_id+ "#,+ organizer.meeting,+ organizer.organizer,+ policy.can_modify,+ policy.can_invite_others,+ policy.can_see_other_guests,+ )+ .fetch_all(&mut **tx)+ .await+ .map_err(report)?;+ // Each copy's stored projection carries the policy too, so a restore from+ // another copy cannot bring the stale switches back.+ sqlx::query!(+ r#"+ UPDATE calendar_event_sources source+ SET normalized_payload = CASE WHEN $4::jsonb IS NULL+ THEN source.normalized_payload #- '{event,guestPolicy}'+ ELSE jsonb_set(source.normalized_payload, '{event,guestPolicy}', $4)+ END+ FROM calendar_events event+ WHERE source.event_id = event.id+ AND source.source_kind = 'google'+ AND source.id <> $3+ AND source.normalized_payload ? 'event'+ AND (source.normalized_payload -> 'event' -> 'guestPolicy') IS DISTINCT FROM $4::jsonb+ AND calendar_meeting_uid(event.ical_uid) = $1+ AND lower(event.organizer_email) = $2+ AND event.status <> 'cancelled'+ AND NOT event.is_snapshot+ "#,+ organizer.meeting,+ organizer.organizer,+ organizer.source_id,+ projected,+ )+ .execute(&mut **tx)+ .await+ .map_err(report)?;+ tracing::Span::current().record("aligned", rows.len());+ Ok(rows+ .into_iter()+ .map(|row| AlignedGuestCopy {+ event_id: row.id,+ owner_id: row.owner_id,+ email_link_id: row.source_link_id,+ })+ .collect())+}diff --git a/crates/calendar_events/src/outbound/pg/test.rs b/crates/calendar_events/src/outbound/pg/test.rsindex b56d7550b3..03b208c43e 100644--- a/crates/calendar_events/src/outbound/pg/test.rs+++ b/crates/calendar_events/src/outbound/pg/test.rs@@ -7259,6 +7259,7 @@ mod changes;mod channel_grants;mod details;mod export;+mod guest_policy;mod invitations;mod join_requests;mod meeting_copies;diff --git a/crates/calendar_events/src/outbound/pg/test/guest_policy.rs b/crates/calendar_events/src/outbound/pg/test/guest_policy.rsnew file mode 100644index 0000000000..db864f7386--- /dev/null+++ b/crates/calendar_events/src/outbound/pg/test/guest_policy.rs@@ -0,0 +1,384 @@+use super::meeting_copies::link_email;+use super::*;++const MEETING: &str = "[email protected]";++/// The id Google gives a secondary calendar, which it names as the organizer+/// of the events made on it.+const SECONDARY: &str = "[email protected]";++const NO_INVITES: GuestPolicy = GuestPolicy {+ can_modify: false,+ can_invite_others: false,+ can_see_other_guests: true,+};++/// A calendar in `link_id`'s inbox with the id Google gives it: the inbox's+/// address for its primary calendar, or a secondary calendar's id.+async fn calendar(+ repo: &PgCalendarRepository,+ link_id: Uuid,+ provider_calendar_id: &str,+ access_role: &str,+) -> (Uuid, Uuid) {+ let account_id = repo.upsert_google_account(link_id).await.unwrap();+ let calendar_id = repo+ .upsert_calendar_fixture(+ account_id,+ ProviderCalendar {+ provider_calendar_id: provider_calendar_id.to_string(),+ name: provider_calendar_id.to_string(),+ description: None,+ time_zone: Some("UTC".to_string()),+ color: None,+ access_role: Some(access_role.to_string()),+ is_primary: provider_calendar_id != SECONDARY,+ is_selected: true,+ default_reminders: Vec::new(),+ },+ )+ .await+ .unwrap();+ (account_id, calendar_id)+}++/// A copy of one meeting organized by `organizer`, stored on `provider`.+fn copy_of(+ owner_id: &str,+ link_id: Uuid,+ provider: (Uuid, Uuid),+ organizer: &str,+ policy: GuestPolicy,+ sequence: u32,+) -> CalendarEventUpsert {+ let mut copy = timed_upsert(+ owner_id,+ link_id,+ provider,+ MEETING,+ "Weekly sync",+ sequence,+ );+ copy.event.organizer_email = Some(organizer.to_string());+ copy.event.guest_policy = policy;+ copy.event.title = format!("Weekly sync {sequence}");+ copy+}++/// The entity's switches and the guest policy each of its projections carries.+async fn stored_policy(+ pool: &PgPool,+ event_id: Uuid,+) -> (GuestPolicy, Vec<Option<serde_json::Value>>) {+ let row = sqlx::query!(+ r#"+ SELECT guests_can_modify, guests_can_invite_others, guests_can_see_other_guests+ FROM calendar_events+ WHERE id = $1+ "#,+ event_id,+ )+ .fetch_one(pool)+ .await+ .unwrap();+ let projected = sqlx::query_scalar!(+ r#"+ SELECT normalized_payload -> 'event' -> 'guestPolicy'+ FROM calendar_event_sources+ WHERE event_id = $1+ ORDER BY id+ "#,+ event_id,+ )+ .fetch_all(pool)+ .await+ .unwrap();+ (+ GuestPolicy {+ can_modify: row.guests_can_modify,+ can_invite_others: row.guests_can_invite_others,+ can_see_other_guests: row.guests_can_see_other_guests,+ },+ projected,+ )+}++async fn changes_for(pool: &PgPool, link_id: Uuid, event_id: Uuid) -> i64 {+ sqlx::query_scalar!(+ r#"SELECT count(*) AS "count!" FROM calendar_change_log WHERE link_id = $1 AND event_id = $2"#,+ link_id,+ event_id,+ )+ .fetch_one(pool)+ .await+ .unwrap()+}++fn no_invites_projection() -> Option<serde_json::Value> {+ Some(serde_json::json!({+ "canModify": false,+ "canInviteOthers": false,+ "canSeeOtherGuests": true,+ }))+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn an_organizers_policy_reaches_every_macro_held_guest_copy(pool: PgPool) {+ let organizer_id = "macro|[email protected]";+ let guest_id = "macro|[email protected]";+ let organizer_link = insert_link(&pool, organizer_id).await;+ let guest_link = insert_link(&pool, guest_id).await;+ let claiming_link = insert_link(&pool, guest_id).await;+ let other_link = insert_link(&pool, guest_id).await;+ let snapshot_link = insert_link(&pool, guest_id).await;+ let organizer = link_email(&pool, organizer_link).await;+ let repo = PgCalendarRepository::new(pool.clone());++ let guest = repo+ .upsert_event_fixture(copy_of(+ guest_id,+ guest_link,+ provider_ids(&repo, guest_link).await,+ &organizer,+ GuestPolicy::default(),+ 1,+ ))+ .await+ .unwrap();+ // A guest's copy reporting another policy is not the organizer's: it+ // changes no other copy.+ repo.upsert_event_fixture(copy_of(+ guest_id,+ claiming_link,+ provider_ids(&repo, claiming_link).await,+ &organizer,+ NO_INVITES,+ 1,+ ))+ .await+ .unwrap();+ assert_eq!(stored_policy(&pool, guest).await.0, GuestPolicy::default());+ let other = repo+ .upsert_event_fixture(copy_of(+ guest_id,+ other_link,+ provider_ids(&repo, other_link).await,+ "[email protected]",+ GuestPolicy::default(),+ 1,+ ))+ .await+ .unwrap();+ let mut snapshot_copy = copy_of(+ guest_id,+ snapshot_link,+ provider_ids(&repo, snapshot_link).await,+ &organizer,+ GuestPolicy::default(),+ 1,+ );+ snapshot_copy.event.is_snapshot = true;+ let snapshot = repo.upsert_event_fixture(snapshot_copy).await.unwrap();+ let changes_before = changes_for(&pool, guest_link, guest).await;++ // Google names the organizer's primary calendar by their address.+ let organized = repo+ .upsert_event(CalendarEventWrite::Fixture(copy_of(+ organizer_id,+ organizer_link,+ calendar(&repo, organizer_link, &organizer, "owner").await,+ &organizer,+ NO_INVITES,+ 1,+ )))+ .await+ .unwrap();++ assert_eq!(stored_policy(&pool, organized.event_id).await.0, NO_INVITES);+ assert_eq!(+ stored_policy(&pool, guest).await,+ (NO_INVITES, vec![no_invites_projection()])+ );+ assert!(+ organized+ .aligned_copies+ .iter()+ .any(|copy| copy.event_id == guest && copy.email_link_id == guest_link),+ "{:?}",+ organized.aligned_copies+ );+ assert_eq!(+ changes_for(&pool, guest_link, guest).await,+ changes_before + 1,+ "the guest's inbox is told its copy changed"+ );+ assert_eq!(stored_policy(&pool, other).await.0, GuestPolicy::default());+ assert_eq!(+ stored_policy(&pool, snapshot).await.0,+ GuestPolicy::default()+ );++ // Turning invites back on reaches the guests too, and their projections+ // drop the key again, as a fresh default one does.+ repo.upsert_event_fixture(copy_of(+ organizer_id,+ organizer_link,+ calendar(&repo, organizer_link, &organizer, "owner").await,+ &organizer,+ GuestPolicy::default(),+ 2,+ ))+ .await+ .unwrap();+ assert_eq!(+ stored_policy(&pool, guest).await,+ (GuestPolicy::default(), vec![None])+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_guest_copy_keeps_its_organizers_policy_over_a_stale_one(pool: PgPool) {+ let organizer_id = "macro|[email protected]";+ let guest_id = "macro|[email protected]";+ let organizer_link = insert_link(&pool, organizer_id).await;+ let guest_link = insert_link(&pool, guest_id).await;+ let organizer = link_email(&pool, organizer_link).await;+ let repo = PgCalendarRepository::new(pool.clone());+ repo.upsert_event_fixture(copy_of(+ organizer_id,+ organizer_link,+ calendar(&repo, organizer_link, &organizer, "owner").await,+ &organizer,+ NO_INVITES,+ 1,+ ))+ .await+ .unwrap();+ let guest_provider = provider_ids(&repo, guest_link).await;++ // Stored after its organizer's copy, a guest copy Google has not caught+ // up yet takes the organizer's policy.+ let outcome = repo+ .upsert_event(CalendarEventWrite::Fixture(copy_of(+ guest_id,+ guest_link,+ guest_provider,+ &organizer,+ GuestPolicy::default(),+ 1,+ )))+ .await+ .unwrap();+ let guest = outcome.event_id;+ assert_eq!(stored_policy(&pool, guest).await.0, NO_INVITES);+ assert!(+ outcome.aligned_copies.is_empty(),+ "the write itself is not reported as another copy to refresh"+ );++ // A guest-side write echoes Google's stale policy; the copy keeps the+ // organizer's.+ repo.upsert_event_fixture(copy_of(+ guest_id,+ guest_link,+ guest_provider,+ &organizer,+ GuestPolicy::default(),+ 2,+ ))+ .await+ .unwrap();+ assert_eq!(stored_policy(&pool, guest).await.0, NO_INVITES);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_secondary_calendars_copy_decides_the_policy_of_its_meeting(pool: PgPool) {+ let organizer_id = "macro|[email protected]";+ let guest_id = "macro|[email protected]";+ let organizer_link = insert_link(&pool, organizer_id).await;+ let guest_link = insert_link(&pool, guest_id).await;+ let organizer_inbox = link_email(&pool, organizer_link).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let (account_id, primary_id) = calendar(&repo, organizer_link, &organizer_inbox, "owner").await;+ let (_, secondary_id) = calendar(&repo, organizer_link, SECONDARY, "owner").await;+ let guest = repo+ .upsert_event_fixture(copy_of(+ guest_id,+ guest_link,+ provider_ids(&repo, guest_link).await,+ SECONDARY,+ GuestPolicy::default(),+ 1,+ ))+ .await+ .unwrap();++ // The organizer's copy lives on the secondary calendar; Google also+ // invites their primary calendar, whose copy shares the entity and still+ // shows the old policy.+ let own = repo+ .upsert_event_fixture(copy_of(+ organizer_id,+ organizer_link,+ (account_id, secondary_id),+ SECONDARY,+ NO_INVITES,+ 1,+ ))+ .await+ .unwrap();+ repo.upsert_event_fixture(copy_of(+ organizer_id,+ organizer_link,+ (account_id, primary_id),+ SECONDARY,+ GuestPolicy::default(),+ 1,+ ))+ .await+ .unwrap();++ let (own_policy, own_projections) = stored_policy(&pool, own).await;+ assert_eq!(+ own_policy, NO_INVITES,+ "the organizer's own entity follows its copy"+ );+ assert!(+ own_projections+ .iter()+ .all(|projected| *projected == no_invites_projection()),+ "{own_projections:?}"+ );+ assert_eq!(stored_policy(&pool, guest).await.0, NO_INVITES);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_calendar_the_inbox_only_reads_decides_nothing(pool: PgPool) {+ let reader_id = "macro|[email protected]";+ let guest_id = "macro|[email protected]";+ let reader_link = insert_link(&pool, reader_id).await;+ let guest_link = insert_link(&pool, guest_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let guest = repo+ .upsert_event_fixture(copy_of(+ guest_id,+ guest_link,+ provider_ids(&repo, guest_link).await,+ SECONDARY,+ GuestPolicy::default(),+ 1,+ ))+ .await+ .unwrap();+ repo.upsert_event_fixture(copy_of(+ reader_id,+ reader_link,+ calendar(&repo, reader_link, SECONDARY, "reader").await,+ SECONDARY,+ NO_INVITES,+ 1,+ ))+ .await+ .unwrap();+ assert_eq!(stored_policy(&pool, guest).await.0, GuestPolicy::default());+}diff --git a/crates/calendar_events/src/outbound/pg/test/meeting_copies.rs b/crates/calendar_events/src/outbound/pg/test/meeting_copies.rsindex b62e0bb173..78b449b603 100644--- a/crates/calendar_events/src/outbound/pg/test/meeting_copies.rs+++ b/crates/calendar_events/src/outbound/pg/test/meeting_copies.rs@@ -1,6 +1,6 @@use super::*;-async fn link_email(pool: &PgPool, link_id: Uuid) -> String {+pub(super) async fn link_email(pool: &PgPool, link_id: Uuid) -> String {sqlx::query_scalar!("SELECT email_address FROM email_links WHERE id = $1",link_iddiff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.mdindex 4afc125b7d..96779a7845 100644--- a/docs/agent-guide/calendar.md+++ b/docs/agent-guide/calendar.md@@ -618,7 +618,8 @@ disabled while a recurring edittargets `This event`, since the policy belongs to the whole series, and says so after theswitches (`Guest permissions apply to all events. Choose All events to change them.`);choosing `This event` returns it to the stored values. Save sends `guestPolicy` only when it-changed, and the guests' `viewerCan` follows once their copies sync: turning `Invite others`+changed. Guests whose copies Macro holds follow at once, since the organizer's stored copy+hands its policy to theirs; others follow once Google syncs their copies. Turning `Invite others`off replaces a guest's `Add guests` with `Only the organizer can invite guests.` The updaterefuses a policy change from anyone but the organizer with 403 `not_organizer`, and on anOutlook event withdiff --git a/services/calendar_service/src/calendar_backfill.rs b/services/calendar_service/src/calendar_backfill.rsindex b3a902f2ed..d5103a5648 100644--- a/services/calendar_service/src/calendar_backfill.rs+++ b/services/calendar_service/src/calendar_backfill.rs@@ -327,6 +327,26 @@ async fn run_coordinator().await;}+ // An organizer's policy change this run reached guest copies in other+ // inboxes; their viewers refetch as well.+ let mut aligned = report+ .aligned_copies+ .iter()+ .map(|copy| (copy.owner_id.as_str(), copy.email_link_id))+ .collect::<Vec<_>>();+ aligned.sort_unstable();+ aligned.dedup();+ for (owner_id, link_id) in aligned {+ cg_refresh_calendar(+ &ctx.connection_gateway_client,+ &ctx.db,+ owner_id,+ link_id,+ ctx.team_sharing_enabled,+ false,+ )+ .await;+ }match run_result {Ok(()) => Disposition::Ack,