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.

fix(calendar): stop retrying watches Google refuses to push for (#6824)

gbirman1697abd2127e
diff --git a/.sqlx/query-f1107131b8da606d041af545e43099dd73cecd1a3b55c7cc12814db807baf8ed.json b/.sqlx/query-5304abc6555d1d641d913a0f29bbab17d495a6794c038e8eb5638f85ac6f737a.json
similarity index 53%
rename from .sqlx/query-f1107131b8da606d041af545e43099dd73cecd1a3b55c7cc12814db807baf8ed.json
rename to .sqlx/query-5304abc6555d1d641d913a0f29bbab17d495a6794c038e8eb5638f85ac6f737a.json
index 066830d62b..f0c3c21c6f 100644
--- a/.sqlx/query-f1107131b8da606d041af545e43099dd73cecd1a3b55c7cc12814db807baf8ed.json
+++ b/.sqlx/query-5304abc6555d1d641d913a0f29bbab17d495a6794c038e8eb5638f85ac6f737a.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE calendars\n SET watch_channel_id = $3,\n watch_resource_id = $4,\n watch_expires_at = $5,\n updated_at = now()\n WHERE id = $1\n AND account_id = $2\n AND NOT is_deleted\n ",
+ "query": "\n UPDATE calendars\n SET watch_channel_id = $3,\n watch_resource_id = $4,\n watch_expires_at = $5,\n watch_unsupported_at = NULL,\n updated_at = now()\n WHERE id = $1\n AND account_id = $2\n AND NOT is_deleted\n ",
"describe": {
"columns": [],
"parameters": {
@@ -14,5 +14,5 @@
},
"nullable": []
},
- "hash": "f1107131b8da606d041af545e43099dd73cecd1a3b55c7cc12814db807baf8ed"
+ "hash": "5304abc6555d1d641d913a0f29bbab17d495a6794c038e8eb5638f85ac6f737a"
}
diff --git a/.sqlx/query-579009b8a97c81ee796f1109588b2b1e914ad489c967fa77ab8343ef969527d8.json b/.sqlx/query-67d7e1d8c8fbdb033d85f41e6afbe24ab1ec1e99c282c8b3a95e62d50ee034af.json
similarity index 91%
rename from .sqlx/query-579009b8a97c81ee796f1109588b2b1e914ad489c967fa77ab8343ef969527d8.json
rename to .sqlx/query-67d7e1d8c8fbdb033d85f41e6afbe24ab1ec1e99c282c8b3a95e62d50ee034af.json
index a471001026..ecb815a57f 100644
--- a/.sqlx/query-579009b8a97c81ee796f1109588b2b1e914ad489c967fa77ab8343ef969527d8.json
+++ b/.sqlx/query-67d7e1d8c8fbdb033d85f41e6afbe24ab1ec1e99c282c8b3a95e62d50ee034af.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO calendars (\n id, account_id, provider_calendar_id, name, description,\n time_zone, color, access_role, is_primary, is_selected,\n default_reminders\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)\n ON CONFLICT (account_id, provider_calendar_id) DO UPDATE SET\n name = EXCLUDED.name,\n description = EXCLUDED.description,\n time_zone = EXCLUDED.time_zone,\n color = EXCLUDED.color,\n access_role = EXCLUDED.access_role,\n is_primary = EXCLUDED.is_primary,\n is_selected = EXCLUDED.is_selected,\n is_deleted = false,\n default_reminders = EXCLUDED.default_reminders,\n last_sync_error = CASE\n WHEN calendars.is_deleted THEN NULL\n ELSE calendars.last_sync_error\n END,\n last_sync_error_at = CASE\n WHEN calendars.is_deleted THEN NULL\n ELSE calendars.last_sync_error_at\n END,\n consecutive_sync_failures = CASE\n WHEN calendars.is_deleted THEN 0\n ELSE calendars.consecutive_sync_failures\n END,\n updated_at = now()\n RETURNING\n id,\n sync_token,\n materialized_starts_at,\n materialized_ends_at,\n materialized_start_date,\n materialized_end_date,\n synced_at,\n watch_expires_at\n ",
+ "query": "\n INSERT INTO calendars (\n id, account_id, provider_calendar_id, name, description,\n time_zone, color, access_role, is_primary, is_selected,\n default_reminders\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)\n ON CONFLICT (account_id, provider_calendar_id) DO UPDATE SET\n name = EXCLUDED.name,\n description = EXCLUDED.description,\n time_zone = EXCLUDED.time_zone,\n color = EXCLUDED.color,\n access_role = EXCLUDED.access_role,\n is_primary = EXCLUDED.is_primary,\n is_selected = EXCLUDED.is_selected,\n is_deleted = false,\n default_reminders = EXCLUDED.default_reminders,\n last_sync_error = CASE\n WHEN calendars.is_deleted THEN NULL\n ELSE calendars.last_sync_error\n END,\n last_sync_error_at = CASE\n WHEN calendars.is_deleted THEN NULL\n ELSE calendars.last_sync_error_at\n END,\n consecutive_sync_failures = CASE\n WHEN calendars.is_deleted THEN 0\n ELSE calendars.consecutive_sync_failures\n END,\n updated_at = now()\n RETURNING\n id,\n sync_token,\n materialized_starts_at,\n materialized_ends_at,\n materialized_start_date,\n materialized_end_date,\n synced_at,\n watch_expires_at,\n watch_unsupported_at\n ",
"describe": {
"columns": [
{
@@ -42,6 +42,11 @@
"ordinal": 7,
"name": "watch_expires_at",
"type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "watch_unsupported_at",
+ "type_info": "Timestamptz"
}
],
"parameters": {
@@ -67,8 +72,9 @@
true,
true,
true,
+ true,
true
]
},
- "hash": "579009b8a97c81ee796f1109588b2b1e914ad489c967fa77ab8343ef969527d8"
+ "hash": "67d7e1d8c8fbdb033d85f41e6afbe24ab1ec1e99c282c8b3a95e62d50ee034af"
}
diff --git a/.sqlx/query-d2757bbf252fdca55b1d9c15c55ee4bc09be6ba4225469f68eee9cef80299833.json b/.sqlx/query-d2757bbf252fdca55b1d9c15c55ee4bc09be6ba4225469f68eee9cef80299833.json
new file mode 100644
index 0000000000..0f4ba939e8
--- /dev/null
+++ b/.sqlx/query-d2757bbf252fdca55b1d9c15c55ee4bc09be6ba4225469f68eee9cef80299833.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE calendars\n SET watch_unsupported_at = now(),\n updated_at = now()\n WHERE id = $1\n AND account_id = $2\n AND NOT is_deleted\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "d2757bbf252fdca55b1d9c15c55ee4bc09be6ba4225469f68eee9cef80299833"
+}
diff --git a/crates/calendar_events/src/domain/models.rs b/crates/calendar_events/src/domain/models.rs
index 649fdcb143..f068114dd6 100644
--- a/crates/calendar_events/src/domain/models.rs
+++ b/crates/calendar_events/src/domain/models.rs
@@ -1261,8 +1261,20 @@ pub struct StoredGoogleCalendar {
pub synced_at: Option<DateTime<Utc>>,
/// Expiry of the active push notification channel, when one exists.
pub watch_expires_at: Option<DateTime<Utc>>,
+ /// When the provider last refused a push channel for this calendar.
+ pub watch_unsupported_at: Option<DateTime<Utc>>,
}
+/// Renew a channel whenever less than this much lifetime remains, so every
+/// poll cycle has several chances before expiry.
+pub const WATCH_RENEWAL_THRESHOLD: chrono::Duration = chrono::Duration::hours(12);
+
+/// How long a provider refusal to push for a calendar suppresses further
+/// watch attempts. Google refuses read-only feeds such as holiday and shared
+/// group calendars on every call, so retrying each poll only produces noise;
+/// the occasional re-probe notices a calendar that has since become watchable.
+pub const WATCH_UNSUPPORTED_RETRY_INTERVAL: chrono::Duration = chrono::Duration::days(7);
+
/// How often Google's own read-only system calendars (holidays, birthdays)
/// are synced. Their content changes on the order of once a year, and Google
/// chronically resets their sync tokens, turning every poll into a full
@@ -1329,6 +1341,18 @@ pub enum GoogleSyncPlan {
}
impl StoredGoogleCalendar {
+ /// Whether this calendar's push channel should be opened or renewed now.
+ pub fn needs_watch_renewal(&self, now: DateTime<Utc>) -> bool {
+ if self
+ .watch_unsupported_at
+ .is_some_and(|refused_at| refused_at > now - WATCH_UNSUPPORTED_RETRY_INTERVAL)
+ {
+ return false;
+ }
+ self.watch_expires_at
+ .is_none_or(|expires_at| expires_at < now + WATCH_RENEWAL_THRESHOLD)
+ }
+
/// Choose how the adapter must reconcile this calendar for a requested
/// window, keeping full rebuilds for lost tokens or uncovered history
/// and extending decayed future coverage incrementally.
diff --git a/crates/calendar_events/src/domain/models/test.rs b/crates/calendar_events/src/domain/models/test.rs
index fb24161900..1a85316245 100644
--- a/crates/calendar_events/src/domain/models/test.rs
+++ b/crates/calendar_events/src/domain/models/test.rs
@@ -47,6 +47,7 @@ fn sync_plan_extends_only_the_uncovered_tail() {
materialized_range: Some(materialized.clone()),
synced_at: None,
watch_expires_at: None,
+ watch_unsupported_at: None,
};
assert_eq!(
@@ -78,6 +79,7 @@ fn sync_plan_extends_only_the_uncovered_tail() {
materialized_range: Some(materialized.clone()),
synced_at: None,
watch_expires_at: None,
+ watch_unsupported_at: None,
};
assert_eq!(
uninitialized.sync_plan(&OccurrenceRange::historical_sync(now)),
@@ -90,6 +92,7 @@ fn sync_plan_extends_only_the_uncovered_tail() {
materialized_range: None,
synced_at: None,
watch_expires_at: None,
+ watch_unsupported_at: None,
};
assert_eq!(
unmaterialized.sync_plan(&OccurrenceRange::historical_sync(now)),
@@ -97,6 +100,44 @@ fn sync_plan_extends_only_the_uncovered_tail() {
);
}
+#[test]
+fn watch_renewal_skips_calendars_that_recently_refused_push() {
+ let now = Utc.with_ymd_and_hms(2026, 9, 23, 12, 0, 0).unwrap();
+ let calendar = StoredGoogleCalendar {
+ id: Uuid::now_v7(),
+ sync_token: None,
+ materialized_range: None,
+ synced_at: None,
+ watch_expires_at: None,
+ watch_unsupported_at: None,
+ };
+ assert!(calendar.needs_watch_renewal(now));
+
+ let healthy = StoredGoogleCalendar {
+ watch_expires_at: Some(now + chrono::Duration::days(3)),
+ ..calendar.clone()
+ };
+ assert!(!healthy.needs_watch_renewal(now));
+
+ let expiring = StoredGoogleCalendar {
+ watch_expires_at: Some(now + chrono::Duration::hours(1)),
+ ..calendar.clone()
+ };
+ assert!(expiring.needs_watch_renewal(now));
+
+ let refused = StoredGoogleCalendar {
+ watch_unsupported_at: Some(now - chrono::Duration::days(1)),
+ ..calendar.clone()
+ };
+ assert!(!refused.needs_watch_renewal(now));
+
+ let refusal_aged_out = StoredGoogleCalendar {
+ watch_unsupported_at: Some(now - chrono::Duration::days(8)),
+ ..calendar
+ };
+ assert!(refusal_aged_out.needs_watch_renewal(now));
+}
+
#[test]
fn maintenance_horizon_is_stable_within_a_month_and_covers_reads() {
let early = Utc.with_ymd_and_hms(2026, 7, 2, 8, 0, 0).unwrap();
diff --git a/crates/calendar_events/src/domain/mutations.rs b/crates/calendar_events/src/domain/mutations.rs
index c4479647cd..cc0f037868 100644
--- a/crates/calendar_events/src/domain/mutations.rs
+++ b/crates/calendar_events/src/domain/mutations.rs
@@ -775,7 +775,7 @@ fn provider_error(error: GoogleProviderError) -> CalendarMutationError {
GoogleProviderErrorKind::Transient | GoogleProviderErrorKind::SyncTokenExpired => {
CalendarMutationError::Retryable(error.to_string())
}
- GoogleProviderErrorKind::Permanent => {
+ GoogleProviderErrorKind::Permanent | GoogleProviderErrorKind::PushUnsupported => {
CalendarMutationError::ProviderRejected(error.to_string())
}
}
diff --git a/crates/calendar_events/src/domain/mutations/test.rs b/crates/calendar_events/src/domain/mutations/test.rs
index 8158a08390..775caf40c8 100644
--- a/crates/calendar_events/src/domain/mutations/test.rs
+++ b/crates/calendar_events/src/domain/mutations/test.rs
@@ -297,6 +297,16 @@ impl CalendarRepository for FakeRepo {
unreachable!()
}
+ async fn record_watch_unsupported(
+ &self,
+ _key: CalendarBackfillJobKey,
+ _lease_token: Uuid,
+ _account_id: Uuid,
+ _calendar_id: Uuid,
+ ) -> Result<(), rootcause::Report> {
+ unreachable!()
+ }
+
async fn find_watch_target(
&self,
_channel_id: &str,
diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rs
index a631bc07ee..be63a9b829 100644
--- a/crates/calendar_events/src/domain/ports.rs
+++ b/crates/calendar_events/src/domain/ports.rs
@@ -31,6 +31,9 @@ pub enum GoogleProviderErrorKind {
ReauthRequired,
/// The provider continuation token expired and requires a full resync.
SyncTokenExpired,
+ /// The provider will not open push channels for this resource; only
+ /// polling can keep it in sync.
+ PushUnsupported,
}
/// Typed Google Calendar failure returned across the provider port.
@@ -511,6 +514,16 @@ pub trait CalendarRepository: Send + Sync + 'static {
channel: GoogleWatchChannel,
) -> impl Future<Output = Result<(), Report>> + Send;
+ /// Record that the provider refused a push channel for one calendar,
+ /// under the backfill's fencing token.
+ fn record_watch_unsupported(
+ &self,
+ key: CalendarBackfillJobKey,
+ lease_token: Uuid,
+ account_id: Uuid,
+ calendar_id: Uuid,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+
/// Resolve a push notification to the inbox whose calendar it watches.
fn find_watch_target(
&self,
diff --git a/crates/calendar_events/src/domain/service.rs b/crates/calendar_events/src/domain/service.rs
index 0dc73bb84b..328033ebd9 100644
--- a/crates/calendar_events/src/domain/service.rs
+++ b/crates/calendar_events/src/domain/service.rs
@@ -263,10 +263,6 @@ pub struct GoogleCalendarBackfillService<R, G, B> {
watch: Option<super::models::GoogleWatchConfig>,
}
-/// Renew a channel whenever less than this much lifetime remains, so every
-/// poll cycle has several chances before expiry.
-const WATCH_RENEWAL_THRESHOLD: chrono::Duration = chrono::Duration::hours(12);
-
/// Periodically makes completed provider jobs eligible for another incremental poll.
pub struct GoogleCalendarSyncScheduler<R> {
repository: R,
@@ -496,9 +492,10 @@ where
Some(GoogleProviderErrorKind::ReauthRequired) => {
CalendarBackfillFailureDisposition::CalendarPermissionRequired
}
- Some(GoogleProviderErrorKind::Permanent) => {
- CalendarBackfillFailureDisposition::Permanent
- }
+ Some(
+ GoogleProviderErrorKind::Permanent
+ | GoogleProviderErrorKind::PushUnsupported,
+ ) => CalendarBackfillFailureDisposition::Permanent,
Some(
GoogleProviderErrorKind::Transient
| GoogleProviderErrorKind::SyncTokenExpired,
@@ -756,7 +753,7 @@ where
is_read_only,
range: range.clone(),
},
- sync_token: stored_calendar.sync_token,
+ sync_token: stored_calendar.sync_token.clone(),
plan,
},
)
@@ -848,9 +845,7 @@ where
// so a failed watch call must not fail the sync that just
// committed durable progress.
if let Some(watch) = &self.watch
- && stored_calendar
- .watch_expires_at
- .is_none_or(|expires_at| expires_at < Utc::now() + WATCH_RENEWAL_THRESHOLD)
+ && stored_calendar.needs_watch_renewal(Utc::now())
{
let channel_id = Uuid::new_v4();
match self
@@ -883,6 +878,23 @@ where
})
.ok();
}
+ Err(error) if error.kind() == GoogleProviderErrorKind::PushUnsupported => {
+ tracing::info!(
+ calendar_id=%calendar_id,
+ "Google Calendar does not support push for this calendar; relying on polling"
+ );
+ self.repository
+ .record_watch_unsupported(key, lease_token, account_id, calendar_id)
+ .await
+ .inspect_err(|error| {
+ tracing::warn!(
+ error=?error,
+ calendar_id=%calendar_id,
+ "failed to record unsupported Google Calendar watch"
+ );
+ })
+ .ok();
+ }
Err(error) => {
tracing::warn!(
error=?error,
diff --git a/crates/calendar_events/src/domain/service/test.rs b/crates/calendar_events/src/domain/service/test.rs
index 3dab0bd994..48c2de26d4 100644
--- a/crates/calendar_events/src/domain/service/test.rs
+++ b/crates/calendar_events/src/domain/service/test.rs
@@ -29,6 +29,8 @@ struct FakeRepo {
sync_retirements: Vec<RetiredCalendarEvent>,
/// Provider calendars whose isolated sync failure was recorded, in order.
recorded_sync_errors: Arc<Mutex<Vec<String>>>,
+ /// Calendars recorded as refusing push channels, in order.
+ recorded_watch_unsupported: Arc<Mutex<Vec<Uuid>>>,
}
impl CalendarRepository for FakeRepo {
@@ -170,6 +172,8 @@ impl CalendarRepository for FakeRepo {
materialized_range: None,
synced_at: self.stored_synced_at,
watch_expires_at: None,
+ watch_unsupported_at: (!self.recorded_watch_unsupported.lock().unwrap().is_empty())
+ .then(Utc::now),
})
}
@@ -220,6 +224,20 @@ impl CalendarRepository for FakeRepo {
Ok(())
}
+ async fn record_watch_unsupported(
+ &self,
+ _key: CalendarBackfillJobKey,
+ _lease_token: Uuid,
+ _account_id: Uuid,
+ calendar_id: Uuid,
+ ) -> Result<(), Report> {
+ self.recorded_watch_unsupported
+ .lock()
+ .unwrap()
+ .push(calendar_id);
+ Ok(())
+ }
+
async fn find_watch_target(
&self,
_channel_id: &str,
@@ -720,6 +738,97 @@ impl GoogleCalendarProvider for MixedTotalFailureGoogleProvider {
}
}
+/// Syncs one calendar whose watch call Google refuses as push-unsupported.
+#[derive(Clone, Default)]
+struct PushUnsupportedGoogleProvider {
+ watch_calls: Arc<Mutex<usize>>,
+}
+
+impl GoogleCalendarProvider for PushUnsupportedGoogleProvider {
+ async fn list_calendars(
+ &self,
+ _access_token: &str,
+ _email_link_id: Uuid,
+ ) -> Result<Vec<ProviderCalendar>, GoogleProviderError> {
+ Ok(vec![provider_calendar("holidays", false)])
+ }
+
+ async fn sync_events(
+ &self,
+ access_token: &str,
+ context: GoogleEventSyncContext,
+ ) -> Result<GoogleEventSyncBatch, GoogleProviderError> {
+ FakeGoogleProvider.sync_events(access_token, context).await
+ }
+
+ async fn watch_calendar(
+ &self,
+ _access_token: &str,
+ _email_link_id: Uuid,
+ _provider_calendar_id: &str,
+ _channel_id: Uuid,
+ _config: &GoogleWatchConfig,
+ ) -> Result<GoogleWatchChannel, GoogleProviderError> {
+ *self.watch_calls.lock().unwrap() += 1;
+ Err(GoogleProviderError::new(
+ GoogleProviderErrorKind::PushUnsupported,
+ "Push notifications are not supported by this resource.",
+ ))
+ }
+}
+
+#[tokio::test]
+async fn push_unsupported_watch_is_recorded_and_the_account_completes() {
+ let lifecycle = FakeLifecycle::claimed();
+ let repository = FakeRepo::default();
+ let recorded_watch_unsupported = repository.recorded_watch_unsupported.clone();
+ let recorded_sync_errors = repository.recorded_sync_errors.clone();
+ let provider = PushUnsupportedGoogleProvider::default();
+ let watch_calls = provider.watch_calls.clone();
+ let coordinator = GoogleCalendarBackfillCoordinator::new(
+ repository,
+ provider,
+ lifecycle.clone(),
+ NoopMacroEventBroker,
+ Some(GoogleWatchConfig {
+ address: "https://gateway.example.com/calendar/notifications".to_string(),
+ token: "token".to_string(),
+ }),
+ );
+
+ let key = CalendarBackfillJobKey {
+ job_id: Uuid::now_v7(),
+ email_link_id: Uuid::now_v7(),
+ };
+ for _ in 0..2 {
+ let mut report = GoogleBackfillRunReport::default();
+ coordinator
+ .run(
+ key,
+ "secret",
+ OccurrenceRange::maintenance_horizon(Utc::now()),
+ &mut report,
+ )
+ .await
+ .expect("a calendar Google will not push for still syncs by polling");
+ }
+
+ assert_eq!(
+ *recorded_watch_unsupported.lock().unwrap(),
+ vec![Uuid::nil()],
+ "the refusal is recorded once"
+ );
+ assert_eq!(
+ *watch_calls.lock().unwrap(),
+ 1,
+ "the recorded refusal stops the next run from re-watching"
+ );
+ assert!(recorded_sync_errors.lock().unwrap().is_empty());
+ assert_eq!(lifecycle.completions.lock().unwrap().len(), 2);
+ assert!(lifecycle.failures.lock().unwrap().is_empty());
+}
+
#[tokio::test]
async fn one_failed_calendar_is_isolated_and_the_account_completes() {
let lifecycle = FakeLifecycle::claimed();
diff --git a/crates/calendar_events/src/outbound/google.rs b/crates/calendar_events/src/outbound/google.rs
index 952668bfd5..999a0d548d 100644
--- a/crates/calendar_events/src/outbound/google.rs
+++ b/crates/calendar_events/src/outbound/google.rs
@@ -381,7 +381,9 @@ fn provider_response_error(
.collect()
})
.unwrap_or_default();
- let kind = if status == StatusCode::GONE || reasons.contains(&"fullSyncRequired") {
+ let kind = if reasons.contains(&"pushNotSupportedForRequestedResource") {
+ GoogleProviderErrorKind::PushUnsupported
+ } else if status == StatusCode::GONE || reasons.contains(&"fullSyncRequired") {
GoogleProviderErrorKind::SyncTokenExpired
} else if reasons.contains(&"insufficientPermissions") {
GoogleProviderErrorKind::ReauthRequired
@@ -560,7 +562,7 @@ impl<G: GoogleRequestGate> GoogleCalendarProvider for GoogleCalendarClient<G> {
})
}
- #[tracing::instrument(skip(self, access_token, config), err)]
+ #[tracing::instrument(skip(self, access_token, config))]
async fn watch_calendar(
&self,
access_token: &str,
@@ -1540,7 +1542,9 @@ fn non_retryable_after_write(error: GoogleProviderError) -> GoogleProviderError
),
)
}
- GoogleProviderErrorKind::Permanent | GoogleProviderErrorKind::ReauthRequired => error,
+ GoogleProviderErrorKind::Permanent
+ | GoogleProviderErrorKind::ReauthRequired
+ | GoogleProviderErrorKind::PushUnsupported => error,
}
}
diff --git a/crates/calendar_events/src/outbound/google/test.rs b/crates/calendar_events/src/outbound/google/test.rs
index f95a2e8e68..7e4bd09038 100644
--- a/crates/calendar_events/src/outbound/google/test.rs
+++ b/crates/calendar_events/src/outbound/google/test.rs
@@ -335,6 +335,23 @@ fn quota_forbidden_response_is_retryable() {
assert_eq!(error.kind(), GoogleProviderErrorKind::Transient);
}
+#[test]
+fn push_unsupported_watch_is_classified_apart_from_other_rejections() {
+ let error = provider_response_error(
+ GoogleRequestKind::Mutation,
+ StatusCode::BAD_REQUEST,
+ r#"{"error":{"code":400,"message":"Push notifications are not supported by this resource.","errors":[{"domain":"global","reason":"pushNotSupportedForRequestedResource","message":"Push notifications are not supported by this resource."}]}}"#,
+ );
+ assert_eq!(error.kind(), GoogleProviderErrorKind::PushUnsupported);
+
+ let other = provider_response_error(
+ GoogleRequestKind::Mutation,
+ StatusCode::BAD_REQUEST,
+ r#"{"error":{"code":400,"message":"Invalid channel","errors":[{"reason":"invalid"}]}}"#,
+ );
+ assert_eq!(other.kind(), GoogleProviderErrorKind::Permanent);
+}
+
#[test]
fn insufficient_permissions_require_reauthorization() {
let error = provider_response_error(
diff --git a/crates/calendar_events/src/outbound/pg.rs b/crates/calendar_events/src/outbound/pg.rs
index ad55e8ec89..46c9cafd8d 100644
--- a/crates/calendar_events/src/outbound/pg.rs
+++ b/crates/calendar_events/src/outbound/pg.rs
@@ -274,6 +274,7 @@ struct StoredCalendarRow {
materialized_end_date: Option<NaiveDate>,
synced_at: Option<DateTime<Utc>>,
watch_expires_at: Option<DateTime<Utc>>,
+ watch_unsupported_at: Option<DateTime<Utc>>,
}
struct OccurrenceJoinRow {
@@ -1491,6 +1492,7 @@ impl CalendarRepository for PgCalendarRepository {
SET watch_channel_id = $3,
watch_resource_id = $4,
watch_expires_at = $5,
+ watch_unsupported_at = NULL,
updated_at = now()
WHERE id = $1
AND account_id = $2
@@ -1508,6 +1510,34 @@ impl CalendarRepository for PgCalendarRepository {
tx.commit().await.map_err(report)
}
+ #[tracing::instrument(skip(self), fields(job_id = %key.job_id), err)]
+ async fn record_watch_unsupported(
+ &self,
+ key: CalendarBackfillJobKey,
+ lease_token: Uuid,
+ account_id: Uuid,
+ calendar_id: Uuid,
+ ) -> Result<(), Report> {
+ let mut tx = self.pool.begin().await.map_err(report)?;
+ fence_google_mutation_tx(&mut tx, key, lease_token, Some(account_id)).await?;
+ sqlx::query!(
+ r#"
+ UPDATE calendars
+ SET watch_unsupported_at = now(),
+ updated_at = now()
+ WHERE id = $1
+ AND account_id = $2
+ AND NOT is_deleted
+ "#,
+ calendar_id,
+ account_id,
+ )
+ .execute(&mut *tx)
+ .await
+ .map_err(report)?;
+ tx.commit().await.map_err(report)
+ }
+
#[tracing::instrument(skip(self, channel_id, resource_id), err)]
async fn find_watch_target(
&self,
@@ -2311,7 +2341,8 @@ async fn upsert_calendar_tx(
materialized_start_date,
materialized_end_date,
synced_at,
- watch_expires_at
+ watch_expires_at,
+ watch_unsupported_at
"#,
Uuid::now_v7(),
account_id,
@@ -2363,6 +2394,7 @@ fn stored_google_calendar(row: StoredCalendarRow) -> Result<StoredGoogleCalendar
materialized_range,
synced_at: row.synced_at,
watch_expires_at: row.watch_expires_at,
+ watch_unsupported_at: row.watch_unsupported_at,
})
}
diff --git a/crates/calendar_events/src/outbound/pg/test.rs b/crates/calendar_events/src/outbound/pg/test.rs
index 1bdbf07cf3..1acf664c2f 100644
--- a/crates/calendar_events/src/outbound/pg/test.rs
+++ b/crates/calendar_events/src/outbound/pg/test.rs
@@ -1766,6 +1766,22 @@ async fn watch_channels_round_trip_from_recording_to_targeted_rearm(pool: PgPool
.unwrap()
.id;
+ assert!(
+ repo.record_watch_unsupported(key, Uuid::new_v4(), account_id, calendar_id)
+ .await
+ .is_err(),
+ "a stale lease must not record push refusals"
+ );
+ repo.record_watch_unsupported(key, lease_token, account_id, calendar_id)
+ .await
+ .unwrap();
+ let refused = repo
+ .upsert_google_calendar(key, lease_token, account_id, provider_calendar.clone())
+ .await
+ .unwrap();
+ assert!(refused.watch_unsupported_at.is_some());
+ assert!(!refused.needs_watch_renewal(Utc::now()));
+
let channel = GoogleWatchChannel {
channel_id: Uuid::new_v4(),
resource_id: "resource-1".to_string(),
@@ -1793,6 +1809,10 @@ async fn watch_channels_round_trip_from_recording_to_targeted_rearm(pool: PgPool
.await
.unwrap();
assert_eq!(stored.watch_expires_at, Some(channel.expires_at));
+ assert_eq!(
+ stored.watch_unsupported_at, None,
+ "an opened channel clears an earlier push refusal"
+ );
// Notifications resolve the channel to its inbox; unknown or mismatched
// identifiers resolve to nothing.
diff --git a/crates/macro_db_client/migrations/20260923032706_calendar_watch_unsupported.sql b/crates/macro_db_client/migrations/20260923032706_calendar_watch_unsupported.sql
new file mode 100644
index 0000000000..5f4e153abc
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260923032706_calendar_watch_unsupported.sql
@@ -0,0 +1,4 @@
+-- When Google last refused a push channel for this calendar
+-- (pushNotSupportedForRequestedResource). Watch renewal skips the calendar
+-- until the refusal ages out; the poller keeps it in sync meanwhile.
+ALTER TABLE calendars ADD COLUMN IF NOT EXISTS watch_unsupported_at timestamptz;