Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(calendar): push refresh_calendar to viewers after provider syncs (#5515)
gbirmana4e252587d24
diff --git a/.sqlx/query-77097dc488f95c654012e22950f5c905dcb578bc041ed2a501c208b4bf9fc097.json b/.sqlx/query-77097dc488f95c654012e22950f5c905dcb578bc041ed2a501c208b4bf9fc097.jsonnew file mode 100644index 0000000000..a61f9f0cbf--- /dev/null+++ b/.sqlx/query-77097dc488f95c654012e22950f5c905dcb578bc041ed2a501c208b4bf9fc097.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT primary_macro_id FROM macro_user_links WHERE link_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "primary_macro_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "77097dc488f95c654012e22950f5c905dcb578bc041ed2a501c208b4bf9fc097"+}diff --git a/apps/web/src/lib/queries/calendar/sync.ts b/apps/web/src/lib/queries/calendar/sync.tsnew file mode 100644index 0000000000..fcdc77de5a--- /dev/null+++ b/apps/web/src/lib/queries/calendar/sync.ts@@ -0,0 +1,27 @@+import { queryClient } from '@queries/client';+import { calendarKeys } from './keys';+import { invalidateCalendarOccurrences } from './occurrences';++/**+ * Handles `refresh_calendar` websocket events: a sync run committed+ * provider-side changes for one of the viewer's (owned or delegated)+ * inboxes, so mounted calendar viewports refetch. The calendar list is+ * invalidated too, since the same sync discovers new calendars and+ * renames/recolors existing ones.+ *+ * Macro-originated mutations don't need this signal in the acting tab —+ * they persist the provider echo synchronously — but their sync echo+ * flows through here, which is what keeps other tabs and devices fresh.+ */+export function handleRefreshCalendar(payload: unknown): void {+ const event =+ typeof payload === 'object' && payload !== null+ ? (payload as { event?: unknown; link_id?: unknown })+ : undefined;+ if (event?.event !== 'synced' || typeof event.link_id !== 'string') return;++ invalidateCalendarOccurrences();+ queryClient.invalidateQueries({+ queryKey: calendarKeys.visibleCalendars.queryKey,+ });+}diff --git a/apps/web/src/lib/queries/calendar/tests/sync.test.ts b/apps/web/src/lib/queries/calendar/tests/sync.test.tsnew file mode 100644index 0000000000..eef39123a9--- /dev/null+++ b/apps/web/src/lib/queries/calendar/tests/sync.test.ts@@ -0,0 +1,47 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { calendarKeys } from '../keys';+import { handleRefreshCalendar } from '../sync';++const invalidateQueriesMock = vi.hoisted(() => vi.fn());+const invalidateCalendarOccurrencesMock = vi.hoisted(() => vi.fn());++vi.mock('../../client', () => ({+ queryClient: { invalidateQueries: invalidateQueriesMock },+}));++vi.mock('../occurrences', () => ({+ invalidateCalendarOccurrences: invalidateCalendarOccurrencesMock,+}));++describe('handleRefreshCalendar', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('refetches occurrence viewports and the calendar list on synced', () => {+ handleRefreshCalendar({+ event: 'synced',+ link_id: '019fdd65-dcc1-74fb-a9c6-8162c11c5854',+ });++ expect(invalidateCalendarOccurrencesMock).toHaveBeenCalledTimes(1);+ expect(invalidateQueriesMock).toHaveBeenCalledWith({+ queryKey: calendarKeys.visibleCalendars.queryKey,+ });+ });++ it('ignores malformed or unknown payloads', () => {+ handleRefreshCalendar(undefined);+ handleRefreshCalendar('synced');+ handleRefreshCalendar({ event: 42 });+ handleRefreshCalendar({+ event: 'unknown_kind',+ link_id: '019fdd65-dcc1-74fb-a9c6-8162c11c5854',+ });+ handleRefreshCalendar({ event: 'synced' });+ handleRefreshCalendar({ event: 'synced', link_id: 42 });++ expect(invalidateCalendarOccurrencesMock).not.toHaveBeenCalled();+ expect(invalidateQueriesMock).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/lib/queries/sync/SyncProvider.tsx b/apps/web/src/lib/queries/sync/SyncProvider.tsxindex 11b699e7e4..c6e1c651c9 100644--- a/apps/web/src/lib/queries/sync/SyncProvider.tsx+++ b/apps/web/src/lib/queries/sync/SyncProvider.tsx@@ -14,6 +14,7 @@ import {import { invalidateAllProperties } from '@queries/properties/tags';import { invalidateAllSoup } from '@queries/soup/normalized-cache';import { handleTaskDuplicateMatchesUpdated } from '@queries/storage/task-duplicates';+import { handleRefreshCalendar } from '../calendar/sync';// Side-effect import: registers the scheduled-action live-update websocket// listener. Must be imported somewhere that always loads on app start — this// provider is guaranteed to mount alongside the other sync handlers.@@ -82,6 +83,9 @@ export function QuerySyncProvider(props: SyncProviderProps) {.with({ type: 'refresh_email' }, () => {withParsedWebsocketPayload(data.type, data.data, handleRefreshEmail);})+ .with({ type: 'refresh_calendar' }, () => {+ withParsedWebsocketPayload(data.type, data.data, handleRefreshCalendar);+ })// Signup seeding is fire-and-forget, so refresh Soup and the provisioned// properties and favorites when it finishes..with({ type: 'starter_docs_initialized' }, () => {diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/index.tsindex 8f53cc78b0..9a8d550081 100644--- a/apps/web/src/lib/service-clients/service-email/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/index.ts@@ -258,6 +258,9 @@ export * from './patchSettingsResponse';export * from './previewsInboxCursorParams';export * from './previewView';export * from './previewViewStandardLabel';+export * from './refreshCalendarEvent';+export * from './refreshCalendarEventOneOf';+export * from './refreshCalendarEventOneOfEvent';export * from './refreshEmailEvent';export * from './refreshEmailEventOneOf';export * from './refreshEmailEventOneOfEvent';diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/refreshCalendarEvent.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/refreshCalendarEvent.tsnew file mode 100644index 0000000000..3c9645bb11--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/refreshCalendarEvent.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { RefreshCalendarEventOneOf } from './refreshCalendarEventOneOf';++/**+ * Realtime signal that a connected inbox's calendar projection changed.+ */+export type RefreshCalendarEvent = RefreshCalendarEventOneOf;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/refreshCalendarEventOneOf.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/refreshCalendarEventOneOf.tsnew file mode 100644index 0000000000..2e5c6edf27--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/refreshCalendarEventOneOf.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { RefreshCalendarEventOneOfEvent } from './refreshCalendarEventOneOfEvent';++/**+ * A sync run committed changes for `link_id`; viewers should refetch.+ */+export type RefreshCalendarEventOneOf = {+ event: RefreshCalendarEventOneOfEvent;+ /** Connected inbox whose calendars changed. */+ link_id: string;+};diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/refreshCalendarEventOneOfEvent.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/refreshCalendarEventOneOfEvent.tsnew file mode 100644index 0000000000..c5ece5ee16--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/refreshCalendarEventOneOfEvent.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++export type RefreshCalendarEventOneOfEvent =+ (typeof RefreshCalendarEventOneOfEvent)[keyof typeof RefreshCalendarEventOneOfEvent];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const RefreshCalendarEventOneOfEvent = {+ synced: 'synced',+} as const;diff --git a/apps/web/src/lib/service-clients/service-email/openapi.json b/apps/web/src/lib/service-clients/service-email/openapi.jsonindex f3320ff972..5dd2f739e0 100644--- a/apps/web/src/lib/service-clients/service-email/openapi.json+++ b/apps/web/src/lib/service-clients/service-email/openapi.json@@ -5417,6 +5417,27 @@"other"]},+ "RefreshCalendarEvent": {+ "oneOf": [+ {+ "type": "object",+ "description": "A sync run committed changes for `link_id`; viewers should refetch.",+ "required": ["link_id", "event"],+ "properties": {+ "event": {+ "type": "string",+ "enum": ["synced"]+ },+ "link_id": {+ "type": "string",+ "format": "uuid",+ "description": "Connected inbox whose calendars changed."+ }+ }+ }+ ],+ "description": "Realtime signal that a connected inbox's calendar projection changed."+ },"RefreshEmailEvent": {"oneOf": [{diff --git a/crates/calendar_events/src/domain/models.rs b/crates/calendar_events/src/domain/models.rsindex 242aef1081..00a86a3ad8 100644--- a/crates/calendar_events/src/domain/models.rs+++ b/crates/calendar_events/src/domain/models.rs@@ -851,6 +851,36 @@ pub struct GoogleCalendarSyncSnapshot {pub cancelled_provider_event_ids: Vec<String>,}+/// What one Google backfill run changed, for change-driven notifications.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct GoogleBackfillRunReport {+ /// Events written through the ingestion upsert this run.+ pub events_upserted: usize,+ /// Cancellation tombstones the change feed reported this run.+ pub cancellations_observed: usize,+}++impl GoogleBackfillRunReport {+ /// Whether the run plausibly changed the local projection. Quiet+ /// token-only polls report nothing and skip client notifications.+ pub fn changed(&self) -> bool {+ self.events_upserted > 0 || self.cancellations_observed > 0+ }+}++/// Realtime signal that a connected inbox's calendar projection changed.+#[derive(Clone, Debug, Serialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(tag = "event", rename_all = "snake_case")]+pub enum RefreshCalendarEvent {+ /// A sync run committed changes for `link_id`; viewers should refetch.+ #[serde(rename_all = "snake_case")]+ Synced {+ /// Connected inbox whose calendars changed.+ link_id: Uuid,+ },+}+/// Kind of idempotent historical work triggered by a Google grant.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum CalendarBackfillKind {diff --git a/crates/calendar_events/src/domain/service.rs b/crates/calendar_events/src/domain/service.rsindex bad6e504fa..b387944602 100644--- a/crates/calendar_events/src/domain/service.rs+++ b/crates/calendar_events/src/domain/service.rs@@ -9,7 +9,8 @@ use super::{models::{AppliedGoogleGrant, CalendarBackfillClaim, CalendarBackfillFailureDisposition,CalendarBackfillFailureOutcome, CalendarBackfillJobKey, CalendarEventUpsert,- CalendarOccurrenceCursor, GoogleCalendarSyncSnapshot, GoogleScopeSet, OccurrenceRange,+ CalendarOccurrenceCursor, GoogleBackfillRunReport, GoogleCalendarSyncSnapshot,+ GoogleScopeSet, OccurrenceRange,},ports::{CalendarBackfillRepository, CalendarEventWrite, CalendarOccurrenceService,@@ -278,14 +279,19 @@ where}/// Execute one idempotent queue delivery under a fenced renewable lease.- #[tracing::instrument(skip(self, owner_id, access_token, range), fields(job_id = %key.job_id), err)]+ ///+ /// `report` accumulates durable progress and remains meaningful on+ /// failure: per-calendar commits that landed before the error survive+ /// the retry, so callers should act on the report either way.+ #[tracing::instrument(skip(self, owner_id, access_token, range, report), fields(job_id = %key.job_id), err)]pub async fn run(&self,key: CalendarBackfillJobKey,owner_id: &str,access_token: &str,range: OccurrenceRange,- ) -> Result<usize, GoogleCalendarBackfillRunError> {+ report: &mut GoogleBackfillRunReport,+ ) -> Result<(), GoogleCalendarBackfillRunError> {let (lease_token, account_id) = match self.lifecycle.claim_google_backfill(key)@@ -296,7 +302,7 @@ wherelease_token,account_id,} => (lease_token, account_id),- CalendarBackfillClaim::Complete => return Ok(0),+ CalendarBackfillClaim::Complete => return Ok(()),CalendarBackfillClaim::Busy => return Err(GoogleCalendarBackfillRunError::Busy),CalendarBackfillClaim::Failed => {return Err(GoogleCalendarBackfillRunError::AlreadyFailed);@@ -327,7 +333,15 @@ whereself.provider.clone(),self.watch.clone(),);- let work = backfill.backfill(key, lease_token, account_id, owner_id, access_token, range);+ let work = backfill.backfill(+ key,+ lease_token,+ account_id,+ owner_id,+ access_token,+ range,+ report,+ );let lease = self.lifecycle.maintain_google_backfill_lease(key, lease_token);@@ -341,12 +355,12 @@ where};match result {- Ok(count) => {+ Ok(()) => {self.lifecycle.complete_google_backfill(key, lease_token).await.map_err(|_| GoogleCalendarBackfillRunError::LeaseLost)?;- Ok(count)+ Ok(())}Err(error) => {let provider_error = error@@ -421,7 +435,13 @@ where}/// Fetch and reconcile calendars and events for a connected inbox.- #[tracing::instrument(skip(self, owner_id, access_token, range), err)]+ ///+ /// Progress accumulates into `report` as each calendar commits, so a+ /// caller observes durable partial progress even when a later calendar+ /// fails the run: those commits survive the retry, whose quiet re-run+ /// would never report them again.+ #[allow(clippy::too_many_arguments)]+ #[tracing::instrument(skip(self, owner_id, access_token, range, report), err)]pub async fn backfill(&self,key: CalendarBackfillJobKey,@@ -430,7 +450,8 @@ whereowner_id: &str,access_token: &str,range: OccurrenceRange,- ) -> Result<usize, Report> {+ report: &mut GoogleBackfillRunReport,+ ) -> Result<(), Report> {if !range.is_valid_for_backfill() {return Err(rootcause::report!(CalendarValidationError::InvalidRange).into());}@@ -439,7 +460,6 @@ where.list_calendars(access_token, key.email_link_id).await.map_err(|error| -> Report { rootcause::report!(error).into() })?;- let mut count = 0;let mut calendar_ids = Vec::with_capacity(calendars.len());for provider_calendar in calendars {@@ -505,7 +525,10 @@ where.await?;calendar_count += 1;}- count += calendar_count;+ // The upserts above committed individually, so they count even+ // if this calendar's snapshot commit below fails.+ report.events_upserted += calendar_count;+ let cancellation_count = batch.cancelled_provider_event_ids.len();// Committing per calendar keeps earlier calendars' sync tokens// durable when a later calendar's poll fails, so the retry only// re-pulls what never committed.@@ -524,6 +547,9 @@ wherecalendar_count,).await?;+ // Tombstones only apply inside the snapshot commit, so they+ // count once it succeeds.+ report.cancellations_observed += cancellation_count;// Channel upkeep is best-effort: the poll remains the backstop,// so a failed watch call must not fail the sync that just@@ -579,7 +605,7 @@ where.reconcile_google_calendar_list(key, lease_token, account_id, calendar_ids).await?;- Ok(count)+ Ok(())}}diff --git a/crates/calendar_events/src/domain/service/test.rs b/crates/calendar_events/src/domain/service/test.rsindex 3e065280eb..b89196d3ce 100644--- a/crates/calendar_events/src/domain/service/test.rs+++ b/crates/calendar_events/src/domain/service/test.rs@@ -5,9 +5,9 @@ use crate::domain::{CalendarBackfillFailureDisposition, CalendarBackfillJobKey, CalendarCreationTarget,CalendarEvent, CalendarEventMutationTarget, CalendarEventSource, CalendarOccurrence,CalendarSyncStatus, EventStatus, EventTime, EventTransparency, EventVisibility,- GOOGLE_CALENDAR_SCOPES, GoogleCalendarSyncSnapshot, GoogleEventSource,- GoogleEventSyncBatch, GoogleWatchChannel, GoogleWatchConfig, ProviderCalendar,- StoredGoogleCalendar,+ GOOGLE_CALENDAR_SCOPES, GoogleBackfillRunReport, GoogleCalendarSyncSnapshot,+ GoogleEventSource, GoogleEventSyncBatch, GoogleWatchChannel, GoogleWatchConfig,+ ProviderCalendar, StoredGoogleCalendar,},ports::{CalendarBackfillRepository, CalendarEventWrite, CalendarRepository, GoogleCalendarProvider,@@ -405,6 +405,100 @@ impl CalendarBackfillRepository for FakeLifecycle {}}+/// Syncs the first calendar with one change, then fails the second.+#[derive(Clone)]+struct PartialFailureGoogleProvider;++impl GoogleCalendarProvider for PartialFailureGoogleProvider {+ async fn list_calendars(+ &self,+ _access_token: &str,+ _email_link_id: Uuid,+ ) -> Result<Vec<ProviderCalendar>, GoogleProviderError> {+ let calendar = |id: &str, primary: bool| ProviderCalendar {+ provider_calendar_id: id.to_string(),+ name: id.to_string(),+ description: None,+ time_zone: Some("UTC".to_string()),+ color: None,+ access_role: Some("owner".to_string()),+ is_primary: primary,+ is_selected: true,+ };+ Ok(vec![calendar("primary", true), calendar("team", false)])+ }++ async fn sync_events(+ &self,+ _access_token: &str,+ context: GoogleEventSyncContext,+ ) -> Result<GoogleEventSyncBatch, GoogleProviderError> {+ if context.target.provider_calendar_id == "team" {+ return Err(GoogleProviderError::new(+ GoogleProviderErrorKind::Transient,+ "the second calendar's poll failed",+ ));+ }+ let mut upsert = valid_upsert();+ let CalendarEventSource::Google(source) = &mut upsert.source;+ source.calendar_id = Uuid::nil();+ Ok(GoogleEventSyncBatch {+ upserts: vec![upsert],+ observed_provider_event_ids: Some(vec!["provider-event".to_string()]),+ next_sync_token: "next".to_string(),+ materialized_range: Some(context.target.range),+ cancelled_provider_event_ids: Vec::new(),+ })+ }++ async fn watch_calendar(+ &self,+ _access_token: &str,+ _email_link_id: Uuid,+ _provider_calendar_id: &str,+ _channel_id: Uuid,+ _config: &GoogleWatchConfig,+ ) -> Result<GoogleWatchChannel, GoogleProviderError> {+ unreachable!("watch is disabled in these tests")+ }+}++#[tokio::test]+async fn partial_progress_reports_changes_when_a_later_calendar_fails() {+ let lifecycle = FakeLifecycle::claimed();+ let coordinator = GoogleCalendarBackfillCoordinator::new(+ FakeRepo::default(),+ PartialFailureGoogleProvider,+ lifecycle.clone(),+ None,+ );++ let mut report = GoogleBackfillRunReport::default();+ let error = coordinator+ .run(+ CalendarBackfillJobKey {+ job_id: Uuid::now_v7(),+ email_link_id: Uuid::now_v7(),+ },+ "macro|[email protected]",+ "secret",+ OccurrenceRange::maintenance_horizon(Utc::now()),+ &mut report,+ )+ .await+ .unwrap_err();++ assert!(matches!(+ error,+ GoogleCalendarBackfillRunError::Retryable(_)+ ));+ assert_eq!(+ report.events_upserted, 1,+ "the first calendar's durable commit must surface through the failed run"+ );+ assert!(report.changed());+}+#[tokio::test]async fn google_coordinator_owns_claim_and_completion_lifecycle() {let lifecycle = FakeLifecycle::claimed();@@ -415,7 +509,8 @@ async fn google_coordinator_owns_claim_and_completion_lifecycle() {None,);- let count = coordinator+ let mut report = GoogleBackfillRunReport::default();+ coordinator.run(CalendarBackfillJobKey {job_id: Uuid::now_v7(),@@ -424,11 +519,12 @@ async fn google_coordinator_owns_claim_and_completion_lifecycle() {"macro|[email protected]","secret",OccurrenceRange::historical_sync(Utc::now()),+ &mut report,).await.unwrap();- assert_eq!(count, 0);+ assert_eq!(report, GoogleBackfillRunReport::default());assert_eq!(lifecycle.completions.lock().unwrap().len(), 1);}@@ -487,7 +583,8 @@ async fn freshly_synced_system_calendars_are_skipped() {None,);- let count = coordinator+ let mut report = GoogleBackfillRunReport::default();+ coordinator.run(CalendarBackfillJobKey {job_id: Uuid::now_v7(),@@ -496,11 +593,12 @@ async fn freshly_synced_system_calendars_are_skipped() {"macro|[email protected]","secret",OccurrenceRange::maintenance_horizon(Utc::now()),+ &mut report,).await.unwrap();- assert_eq!(count, 0);+ assert_eq!(report, GoogleBackfillRunReport::default());assert_eq!(lifecycle.completions.lock().unwrap().len(), 1);}@@ -555,6 +653,7 @@ async fn google_coordinator_surfaces_lease_loss_while_work_is_running() {"macro|[email protected]","secret",OccurrenceRange::historical_sync(Utc::now()),+ &mut GoogleBackfillRunReport::default(),).await.unwrap_err();@@ -583,6 +682,7 @@ async fn google_coordinator_keeps_calendar_permission_health_separate_from_gmail"macro|[email protected]","secret",OccurrenceRange::historical_sync(Utc::now()),+ &mut GoogleBackfillRunReport::default(),).await.unwrap_err();diff --git a/crates/connection_gateway_client/src/client/calendar.rs b/crates/connection_gateway_client/src/client/calendar.rsnew file mode 100644index 0000000000..7d0c80430e--- /dev/null+++ b/crates/connection_gateway_client/src/client/calendar.rs@@ -0,0 +1,20 @@+use super::ConnectionGatewayClient;+use connection_gateway_models::MessageReceipt;+use model_entity::EntityType;++impl ConnectionGatewayClient {+ /// Trigger refresh of the user's calendar views.+ #[tracing::instrument(skip(self, event))]+ pub async fn refresh_calendar(+ &self,+ user_id: &str,+ event: serde_json::Value,+ ) -> anyhow::Result<Vec<MessageReceipt>> {+ self.send_message(+ EntityType::User.with_entity_str(user_id),+ "refresh_calendar".to_string(),+ event,+ )+ .await+ }+}diff --git a/crates/connection_gateway_client/src/client/mod.rs b/crates/connection_gateway_client/src/client/mod.rsindex 47a04fd121..8e0536ed74 100644--- a/crates/connection_gateway_client/src/client/mod.rs+++ b/crates/connection_gateway_client/src/client/mod.rs@@ -7,6 +7,7 @@ use connection_gateway_models::{use model_entity::Entity;+mod calendar;mod email;/// HTTP client for communicating with the connection gateway service.diff --git a/packages/sdk/generated/email/index.ts b/packages/sdk/generated/email/index.tsindex 10928acce9..74fe03b4a4 100644--- a/packages/sdk/generated/email/index.ts+++ b/packages/sdk/generated/email/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessLevel, AddDraftAttachmentData, AddDraftAttachmentError, AddDraftAttachmentErrors, AddDraftAttachmentRequest, AddDraftAttachmentResponse, AddDraftAttachmentResponse2, AddDraftAttachmentResponses, AddForwardedAttachmentData, AddForwardedAttachmentError, AddForwardedAttachmentErrors, AddForwardedAttachmentRequest, AddForwardedAttachmentResponse, AddForwardedAttachmentResponse2, AddForwardedAttachmentResponses, AddRemoveLabelData, AddRemoveLabelError, AddRemoveLabelErrors, AddRemoveLabelResponse, AddRemoveLabelResponses, AddRemoveThreadLabelData, AddRemoveThreadLabelError, AddRemoveThreadLabelErrors, AddRemoveThreadLabelResponse, AddRemoveThreadLabelResponses, ApiAttachment, ApiAttachmentDraft, ApiAttachmentForwarded, ApiContact, ApiContactInfo, ApiDraftContactInfo, ApiDraftInput, ApiDraftOutput, ApiEmailFilter, ApiLabel, ApiLabelListVisibility, ApiLabelType, ApiMessage, ApiMessageAttachment, ApiMessageLabel, ApiMessageListVisibility, ApiPaginatedThreadCursor, ApiSortMethod, ApiThread, ApiThreadPreviewCursor, ApiThreadPreviewCursorInner, ArchiveThreadData, ArchiveThreadError, ArchiveThreadErrors, ArchiveThreadRequest, ArchiveThreadResponse, ArchiveThreadResponses, Attachment, AttachmentDraft, AttachmentForwarded, AttendeeResponseStatus, BackfillJob, BackfillJobStatus, BackfillStatus, BlockSenderData, BlockSenderError, BlockSenderErrors, BlockSenderRequest, BlockSenderResponses, CalendarAttendee, CalendarAttendeeInputBody, CalendarDeletionScopeParam, CalendarEvent, CalendarMutationApiError, CalendarMutationErrorCode, CancelBackfillGmailData, CancelBackfillGmailError, CancelBackfillGmailErrors, CancelBackfillGmailResponse, CancelBackfillGmailResponses, CancelBackfillParams, ClientOptions, Contact, ContactInfo, ContactInfoLegacy, ContactInfoWithInteraction, CreateCalendarEventData, CreateCalendarEventError, CreateCalendarEventErrors, CreateCalendarEventRequest, CreateCalendarEventResponse, CreateCalendarEventResponses, CreateDraftData, CreateDraftError, CreateDraftErrors, CreateDraftRequest, CreateDraftResponse, CreateDraftResponse2, CreateDraftResponses, CreateLabelData, CreateLabelError, CreateLabelErrors, CreateLabelRequest, CreateLabelResponse, CreateLabelResponse2, CreateLabelResponses, DeleteCalendarEventData, DeleteCalendarEventError, DeleteCalendarEventErrors, DeleteCalendarEventResponse, DeleteCalendarEventResponses, DeleteDraftData, DeleteDraftError, DeleteDraftErrors, DeleteDraftResponse, DeleteDraftResponses, DeleteEmailFilterData, DeleteEmailFilterError, DeleteEmailFilterErrors, DeleteEmailFilterResponse, DeleteEmailFilterResponses, DeleteLabelData, DeleteLabelError, DeleteLabelErrors, DeleteLabelResponse, DeleteLabelResponses, DeleteLinkData, DeleteLinkError, DeleteLinkErrors, DeleteLinkResponse, DeleteLinkResponses, DeleteScheduledDraftData, DeleteScheduledDraftError, DeleteScheduledDraftErrors, DeleteScheduledDraftResponse, DeleteScheduledDraftResponses, DisableSyncData, DisableSyncError, DisableSyncErrors, DisableSyncResponse, DisableSyncResponses, EmptyResponse, ErrorResponse, EventStatus, EventTime, EventTransparency, EventVisibility, GetActiveBackfillJobResponse, GetAttachmentData, GetAttachmentDocumentIdData, GetAttachmentDocumentIdError, GetAttachmentDocumentIdErrors, GetAttachmentDocumentIdResponse, GetAttachmentDocumentIdResponse2, GetAttachmentDocumentIdResponses, GetAttachmentError, GetAttachmentErrors, GetAttachmentResponse, GetAttachmentResponse2, GetAttachmentResponses, GetBackfillGmailActiveData, GetBackfillGmailActiveError, GetBackfillGmailActiveErrors, GetBackfillGmailActiveResponse, GetBackfillGmailActiveResponses, GetBackfillGmailData, GetBackfillGmailError, GetBackfillGmailErrors, GetBackfillGmailResponse, GetBackfillGmailResponses, GetBackfillJobResponse, GetMessageData, GetMessageError, GetMessageErrors, GetMessageResponse, GetMessageResponses, GetMessagesBatchData, GetMessagesBatchError, GetMessagesBatchErrors, GetMessagesBatchResponse, GetMessagesBatchResponses, GetPreviewsCursorParams, GetScheduledMessagesData, GetScheduledMessagesError, GetScheduledMessagesErrors, GetScheduledMessagesResponse, GetScheduledMessagesResponses, GetScheduledResponse, GetThreadData, GetThreadError, GetThreadErrors, GetThreadMessagesHandlerData, GetThreadMessagesHandlerError, GetThreadMessagesHandlerErrors, GetThreadMessagesHandlerResponse, GetThreadMessagesHandlerResponses, GetThreadResponse, GetThreadResponse2, GetThreadResponses, HealthCheckLinksData, HealthCheckLinksError, HealthCheckLinksErrors, HealthCheckLinksResponse, HealthCheckLinksResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitErrorCodeResponse, InitResponse, InitUserData, InitUserError, InitUserErrors, InitUserResponse, InitUserResponses, Label, LabelInfo, LabelListVisibility, LabelType, Link, ListBackfillGmailData, ListBackfillGmailError, ListBackfillGmailErrors, ListBackfillGmailResponse, ListBackfillGmailResponses, ListBackfillJobsResponse, ListBlockedResponse, ListBlockedSendersData, ListBlockedSendersError, ListBlockedSendersErrors, ListBlockedSendersResponse, ListBlockedSendersResponses, ListCalendarsData, ListCalendarsError, ListCalendarsErrors, ListCalendarsResponse, ListCalendarsResponse2, ListCalendarsResponses, ListContactsData, ListContactsError, ListContactsErrors, ListContactsResponse, ListContactsResponse2, ListContactsResponses, ListEmailFiltersData, ListEmailFiltersError, ListEmailFiltersErrors, ListEmailFiltersResponse, ListEmailFiltersResponse2, ListEmailFiltersResponses, ListLabelsData, ListLabelsError, ListLabelsErrors, ListLabelsResponse, ListLabelsResponse2, ListLabelsResponses, ListLinksData, ListLinksError, ListLinksErrors, ListLinksResponse, ListLinksResponse2, ListLinksResponses, Message, MessageListVisibility, ParsedMessage, PatchSettingsData, PatchSettingsError, PatchSettingsErrors, PatchSettingsRequest, PatchSettingsResponse, PatchSettingsResponse2, PatchSettingsResponses, PreviewsInboxCursorData, PreviewsInboxCursorError, PreviewsInboxCursorErrors, PreviewsInboxCursorResponse, PreviewsInboxCursorResponses, PreviewView, PreviewViewStandardLabel, RefreshEmailEvent, RemoveDraftAttachmentData, RemoveDraftAttachmentError, RemoveDraftAttachmentErrors, RemoveDraftAttachmentResponse, RemoveDraftAttachmentResponses, RemoveForwardedAttachmentData, RemoveForwardedAttachmentError, RemoveForwardedAttachmentErrors, RemoveForwardedAttachmentResponse, RemoveForwardedAttachmentResponses, ResyncLinkData, ResyncLinkError, ResyncLinkErrors, ResyncLinkResponse, ResyncLinkResponses, ResyncResponse, RsvpCalendarEventData, RsvpCalendarEventError, RsvpCalendarEventErrors, RsvpCalendarEventRequest, RsvpCalendarEventResponse, RsvpCalendarEventResponses, SendMessageData, SendMessageError, SendMessageErrors, SendMessageRequest, SendMessageResponse, SendMessageResponse2, SendMessageResponses, Settings, SharedInboxConflictResponse, SyncStatus, Thread, ThreadList, ThreadPreviewCursor, ThreadSeenData, ThreadSeenError, ThreadSeenErrors, ThreadSeenResponse, ThreadSeenResponses, ThreadSummary, UnblockSenderData, UnblockSenderError, UnblockSenderErrors, UnblockSenderRequest, UnblockSenderResponse, UnblockSenderResponses, UnresolvedSignatureImagesError, UpdateCalendarEventData, UpdateCalendarEventError, UpdateCalendarEventErrors, UpdateCalendarEventRequest, UpdateCalendarEventResponse, UpdateCalendarEventResponses, UpdateLabelBatchRequest, UpdateLabelBatchResponse, UpdateThreadLabelRequest, UpdateThreadLabelsResponse, UpdateThreadProjectData, UpdateThreadProjectError, UpdateThreadProjectErrors, UpdateThreadProjectRequest, UpdateThreadProjectResponse, UpdateThreadProjectResponse2, UpdateThreadProjectResponses, UpsertEmailFilterData, UpsertEmailFilterError, UpsertEmailFilterErrors, UpsertEmailFilterRequest, UpsertEmailFilterResponse, UpsertEmailFilterResponse2, UpsertEmailFilterResponses, UpsertScheduledMessageData, UpsertScheduledMessageError, UpsertScheduledMessageErrors, UpsertScheduledMessageResponse, UpsertScheduledMessageResponses, UpsertScheduledRequest, UpsertScheduledResponse, UserProvider, Value, VisibleCalendar } from './types.gen';+export type { AccessLevel, AddDraftAttachmentData, AddDraftAttachmentError, AddDraftAttachmentErrors, AddDraftAttachmentRequest, AddDraftAttachmentResponse, AddDraftAttachmentResponse2, AddDraftAttachmentResponses, AddForwardedAttachmentData, AddForwardedAttachmentError, AddForwardedAttachmentErrors, AddForwardedAttachmentRequest, AddForwardedAttachmentResponse, AddForwardedAttachmentResponse2, AddForwardedAttachmentResponses, AddRemoveLabelData, AddRemoveLabelError, AddRemoveLabelErrors, AddRemoveLabelResponse, AddRemoveLabelResponses, AddRemoveThreadLabelData, AddRemoveThreadLabelError, AddRemoveThreadLabelErrors, AddRemoveThreadLabelResponse, AddRemoveThreadLabelResponses, ApiAttachment, ApiAttachmentDraft, ApiAttachmentForwarded, ApiContact, ApiContactInfo, ApiDraftContactInfo, ApiDraftInput, ApiDraftOutput, ApiEmailFilter, ApiLabel, ApiLabelListVisibility, ApiLabelType, ApiMessage, ApiMessageAttachment, ApiMessageLabel, ApiMessageListVisibility, ApiPaginatedThreadCursor, ApiSortMethod, ApiThread, ApiThreadPreviewCursor, ApiThreadPreviewCursorInner, ArchiveThreadData, ArchiveThreadError, ArchiveThreadErrors, ArchiveThreadRequest, ArchiveThreadResponse, ArchiveThreadResponses, Attachment, AttachmentDraft, AttachmentForwarded, AttendeeResponseStatus, BackfillJob, BackfillJobStatus, BackfillStatus, BlockSenderData, BlockSenderError, BlockSenderErrors, BlockSenderRequest, BlockSenderResponses, CalendarAttendee, CalendarAttendeeInputBody, CalendarDeletionScopeParam, CalendarEvent, CalendarMutationApiError, CalendarMutationErrorCode, CancelBackfillGmailData, CancelBackfillGmailError, CancelBackfillGmailErrors, CancelBackfillGmailResponse, CancelBackfillGmailResponses, CancelBackfillParams, ClientOptions, Contact, ContactInfo, ContactInfoLegacy, ContactInfoWithInteraction, CreateCalendarEventData, CreateCalendarEventError, CreateCalendarEventErrors, CreateCalendarEventRequest, CreateCalendarEventResponse, CreateCalendarEventResponses, CreateDraftData, CreateDraftError, CreateDraftErrors, CreateDraftRequest, CreateDraftResponse, CreateDraftResponse2, CreateDraftResponses, CreateLabelData, CreateLabelError, CreateLabelErrors, CreateLabelRequest, CreateLabelResponse, CreateLabelResponse2, CreateLabelResponses, DeleteCalendarEventData, DeleteCalendarEventError, DeleteCalendarEventErrors, DeleteCalendarEventResponse, DeleteCalendarEventResponses, DeleteDraftData, DeleteDraftError, DeleteDraftErrors, DeleteDraftResponse, DeleteDraftResponses, DeleteEmailFilterData, DeleteEmailFilterError, DeleteEmailFilterErrors, DeleteEmailFilterResponse, DeleteEmailFilterResponses, DeleteLabelData, DeleteLabelError, DeleteLabelErrors, DeleteLabelResponse, DeleteLabelResponses, DeleteLinkData, DeleteLinkError, DeleteLinkErrors, DeleteLinkResponse, DeleteLinkResponses, DeleteScheduledDraftData, DeleteScheduledDraftError, DeleteScheduledDraftErrors, DeleteScheduledDraftResponse, DeleteScheduledDraftResponses, DisableSyncData, DisableSyncError, DisableSyncErrors, DisableSyncResponse, DisableSyncResponses, EmptyResponse, ErrorResponse, EventStatus, EventTime, EventTransparency, EventVisibility, GetActiveBackfillJobResponse, GetAttachmentData, GetAttachmentDocumentIdData, GetAttachmentDocumentIdError, GetAttachmentDocumentIdErrors, GetAttachmentDocumentIdResponse, GetAttachmentDocumentIdResponse2, GetAttachmentDocumentIdResponses, GetAttachmentError, GetAttachmentErrors, GetAttachmentResponse, GetAttachmentResponse2, GetAttachmentResponses, GetBackfillGmailActiveData, GetBackfillGmailActiveError, GetBackfillGmailActiveErrors, GetBackfillGmailActiveResponse, GetBackfillGmailActiveResponses, GetBackfillGmailData, GetBackfillGmailError, GetBackfillGmailErrors, GetBackfillGmailResponse, GetBackfillGmailResponses, GetBackfillJobResponse, GetMessageData, GetMessageError, GetMessageErrors, GetMessageResponse, GetMessageResponses, GetMessagesBatchData, GetMessagesBatchError, GetMessagesBatchErrors, GetMessagesBatchResponse, GetMessagesBatchResponses, GetPreviewsCursorParams, GetScheduledMessagesData, GetScheduledMessagesError, GetScheduledMessagesErrors, GetScheduledMessagesResponse, GetScheduledMessagesResponses, GetScheduledResponse, GetThreadData, GetThreadError, GetThreadErrors, GetThreadMessagesHandlerData, GetThreadMessagesHandlerError, GetThreadMessagesHandlerErrors, GetThreadMessagesHandlerResponse, GetThreadMessagesHandlerResponses, GetThreadResponse, GetThreadResponse2, GetThreadResponses, HealthCheckLinksData, HealthCheckLinksError, HealthCheckLinksErrors, HealthCheckLinksResponse, HealthCheckLinksResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitErrorCodeResponse, InitResponse, InitUserData, InitUserError, InitUserErrors, InitUserResponse, InitUserResponses, Label, LabelInfo, LabelListVisibility, LabelType, Link, ListBackfillGmailData, ListBackfillGmailError, ListBackfillGmailErrors, ListBackfillGmailResponse, ListBackfillGmailResponses, ListBackfillJobsResponse, ListBlockedResponse, ListBlockedSendersData, ListBlockedSendersError, ListBlockedSendersErrors, ListBlockedSendersResponse, ListBlockedSendersResponses, ListCalendarsData, ListCalendarsError, ListCalendarsErrors, ListCalendarsResponse, ListCalendarsResponse2, ListCalendarsResponses, ListContactsData, ListContactsError, ListContactsErrors, ListContactsResponse, ListContactsResponse2, ListContactsResponses, ListEmailFiltersData, ListEmailFiltersError, ListEmailFiltersErrors, ListEmailFiltersResponse, ListEmailFiltersResponse2, ListEmailFiltersResponses, ListLabelsData, ListLabelsError, ListLabelsErrors, ListLabelsResponse, ListLabelsResponse2, ListLabelsResponses, ListLinksData, ListLinksError, ListLinksErrors, ListLinksResponse, ListLinksResponse2, ListLinksResponses, Message, MessageListVisibility, ParsedMessage, PatchSettingsData, PatchSettingsError, PatchSettingsErrors, PatchSettingsRequest, PatchSettingsResponse, PatchSettingsResponse2, PatchSettingsResponses, PreviewsInboxCursorData, PreviewsInboxCursorError, PreviewsInboxCursorErrors, PreviewsInboxCursorResponse, PreviewsInboxCursorResponses, PreviewView, PreviewViewStandardLabel, RefreshCalendarEvent, RefreshEmailEvent, RemoveDraftAttachmentData, RemoveDraftAttachmentError, RemoveDraftAttachmentErrors, RemoveDraftAttachmentResponse, RemoveDraftAttachmentResponses, RemoveForwardedAttachmentData, RemoveForwardedAttachmentError, RemoveForwardedAttachmentErrors, RemoveForwardedAttachmentResponse, RemoveForwardedAttachmentResponses, ResyncLinkData, ResyncLinkError, ResyncLinkErrors, ResyncLinkResponse, ResyncLinkResponses, ResyncResponse, RsvpCalendarEventData, RsvpCalendarEventError, RsvpCalendarEventErrors, RsvpCalendarEventRequest, RsvpCalendarEventResponse, RsvpCalendarEventResponses, SendMessageData, SendMessageError, SendMessageErrors, SendMessageRequest, SendMessageResponse, SendMessageResponse2, SendMessageResponses, Settings, SharedInboxConflictResponse, SyncStatus, Thread, ThreadList, ThreadPreviewCursor, ThreadSeenData, ThreadSeenError, ThreadSeenErrors, ThreadSeenResponse, ThreadSeenResponses, ThreadSummary, UnblockSenderData, UnblockSenderError, UnblockSenderErrors, UnblockSenderRequest, UnblockSenderResponse, UnblockSenderResponses, UnresolvedSignatureImagesError, UpdateCalendarEventData, UpdateCalendarEventError, UpdateCalendarEventErrors, UpdateCalendarEventRequest, UpdateCalendarEventResponse, UpdateCalendarEventResponses, UpdateLabelBatchRequest, UpdateLabelBatchResponse, UpdateThreadLabelRequest, UpdateThreadLabelsResponse, UpdateThreadProjectData, UpdateThreadProjectError, UpdateThreadProjectErrors, UpdateThreadProjectRequest, UpdateThreadProjectResponse, UpdateThreadProjectResponse2, UpdateThreadProjectResponses, UpsertEmailFilterData, UpsertEmailFilterError, UpsertEmailFilterErrors, UpsertEmailFilterRequest, UpsertEmailFilterResponse, UpsertEmailFilterResponse2, UpsertEmailFilterResponses, UpsertScheduledMessageData, UpsertScheduledMessageError, UpsertScheduledMessageErrors, UpsertScheduledMessageResponse, UpsertScheduledMessageResponses, UpsertScheduledRequest, UpsertScheduledResponse, UserProvider, Value, VisibleCalendar } from './types.gen';diff --git a/packages/sdk/generated/email/types.gen.ts b/packages/sdk/generated/email/types.gen.tsindex 0f74603b5c..0c881ec6fe 100644--- a/packages/sdk/generated/email/types.gen.ts+++ b/packages/sdk/generated/email/types.gen.ts@@ -1137,6 +1137,17 @@ export type PreviewView = 'inbox' | 'sent' | 'drafts' | 'starred' | 'all' | 'impexport type PreviewViewStandardLabel = 'inbox' | 'sent' | 'drafts' | 'starred' | 'all' | 'important' | 'other';+/**+ * A sync run committed changes for `link_id`; viewers should refetch.+ */+export type RefreshCalendarEvent = {+ event: 'synced';+ /**+ * Connected inbox whose calendars changed.+ */+ link_id: string;+};+/*** Payload for the `refresh_email` connection gateway event: identifies the* inbox that changed and the kind of change.diff --git a/packages/sdk/specs/email.json b/packages/sdk/specs/email.jsonindex f3320ff972..5dd2f739e0 100644--- a/packages/sdk/specs/email.json+++ b/packages/sdk/specs/email.json@@ -5417,6 +5417,27 @@"other"]},+ "RefreshCalendarEvent": {+ "oneOf": [+ {+ "type": "object",+ "description": "A sync run committed changes for `link_id`; viewers should refetch.",+ "required": ["link_id", "event"],+ "properties": {+ "event": {+ "type": "string",+ "enum": ["synced"]+ },+ "link_id": {+ "type": "string",+ "format": "uuid",+ "description": "Connected inbox whose calendars changed."+ }+ }+ }+ ],+ "description": "Realtime signal that a connected inbox's calendar projection changed."+ },"RefreshEmailEvent": {"oneOf": [{diff --git a/services/email_service/src/api/swagger.rs b/services/email_service/src/api/swagger.rsindex 8a4e9b3791..c73486b856 100644--- a/services/email_service/src/api/swagger.rs+++ b/services/email_service/src/api/swagger.rs@@ -208,7 +208,8 @@ use utoipa::OpenApi;calendar_events::domain::models::EventTime,calendar_events::domain::models::EventStatus,calendar_events::domain::models::EventVisibility,- calendar_events::domain::models::EventTransparency+ calendar_events::domain::models::EventTransparency,+ calendar_events::domain::models::RefreshCalendarEvent),),tags(diff --git a/services/email_service/src/pubsub/backfill/calendar_google_backfill.rs b/services/email_service/src/pubsub/backfill/calendar_google_backfill.rsindex fd9bc53d55..72d6536a37 100644--- a/services/email_service/src/pubsub/backfill/calendar_google_backfill.rs+++ b/services/email_service/src/pubsub/backfill/calendar_google_backfill.rs@@ -1,6 +1,7 @@use crate::pubsub::context::PubSubContext;+use crate::pubsub::util::cg_refresh_calendar;use calendar_events::domain::{- models::{CalendarBackfillJobKey, OccurrenceRange},+ models::{CalendarBackfillJobKey, GoogleBackfillRunReport, OccurrenceRange},service::GoogleCalendarBackfillRunError,};use chrono::Utc;@@ -18,7 +19,9 @@ pub async fn calendar_google_backfill(link: &Link,payload: &CalendarBackfillPayload,) -> Result<(), ProcessingError> {- ctx.calendar_backfills+ let mut report = GoogleBackfillRunReport::default();+ let run_result = ctx+ .calendar_backfills.run(CalendarBackfillJobKey {@@ -28,10 +31,23 @@ pub async fn calendar_google_backfill(link.macro_id.as_ref(),access_token,OccurrenceRange::maintenance_horizon(Utc::now()),+ &mut report,)- .await- .map(|_| ())- .map_err(map_run_error)+ .await;+ // Quiet token-only polls change nothing; only real changes nudge+ // active viewers to refetch. The nudge goes out even when the run+ // ultimately failed: per-calendar commits before the error are+ // durable, and the retry's quiet re-run would never report them.+ if report.changed() {+ cg_refresh_calendar(+ &ctx.connection_gateway_client,+ &ctx.db,+ link.macro_id.as_ref(),+ link.id,+ )+ .await;+ }+ run_result.map_err(map_run_error)}fn map_run_error(error: GoogleCalendarBackfillRunError) -> ProcessingError {diff --git a/services/email_service/src/pubsub/util.rs b/services/email_service/src/pubsub/util.rsindex 79d903b3a2..f6bda06c14 100644--- a/services/email_service/src/pubsub/util.rs+++ b/services/email_service/src/pubsub/util.rs@@ -149,6 +149,48 @@ pub async fn cg_refresh_email(}}+/// Signal every viewer of a connected inbox's calendars — the link owner+/// plus its delegated users — that the calendar projection changed. Best+/// effort: an inactive or unreachable viewer only misses a refresh nudge.+#[tracing::instrument(skip(client, db), level = "debug")]+pub async fn cg_refresh_calendar(+ client: &ConnectionGatewayClient,+ db: &sqlx::PgPool,+ owner_macro_id: &str,+ link_id: uuid::Uuid,+) {+ if !cfg!(feature = "connection_gateway") {+ return;+ }+ let payload = serde_json::to_value(+ calendar_events::domain::models::RefreshCalendarEvent::Synced { link_id },+ )+ .unwrap_or_default();+ let mut recipients = vec![owner_macro_id.to_string()];+ match sqlx::query_scalar!(+ "SELECT primary_macro_id FROM macro_user_links WHERE link_id = $1",+ link_id,+ )+ .fetch_all(db)+ .await+ {+ Ok(delegates) => recipients.extend(delegates),+ Err(error) => {+ tracing::warn!(error=?error, %link_id, "failed to resolve calendar refresh delegates");+ }+ }+ recipients.sort();+ recipients.dedup();+ for macro_id in recipients {+ let _ = client+ .refresh_calendar(¯o_id, payload.clone())+ .await+ .inspect_err(+ |e| tracing::error!(macro_id = %macro_id, "Failed to refresh calendar: {e}"),+ );+ }+}+/// Shared filter/dedup pass for the CRM populate + depopulate enqueue/// helpers. Returns each input email, lowercased and trimmed, with/// malformed addresses and the caller's own address dropped, and