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
//! PostgreSQL implementation of the calendar repository port.
mod change_log;
mod changes;
mod details;
mod export;
mod guest_policy;
mod invitations;
mod join_requests;
#[cfg(feature = "outlook")]
mod outlook;
mod replacement;
mod source_access;
use change_log::ChangeLogBatch;
use std::collections::{HashMap, HashSet};
use chrono::{DateTime, NaiveDate, Utc};
use futures::try_join;
use rootcause::Report;
use serde::{Deserialize, Serialize};
use sqlx::{PgPool, Postgres, Transaction};
use uuid::Uuid;
use crate::domain::{
changes::CalendarChangeOp,
ics::{CalendarEventExport, content_without_macro_call},
labels::EventCopy,
models::{
ActorInboxes, AlignedGuestCopy, AppliedGoogleGrant, AttendeeResponseStatus,
CALENDAR_SYNC_FAILURE_BADGE_THRESHOLD, CalendarAttendee, CalendarBackfillClaim,
CalendarBackfillFailureDisposition, CalendarBackfillFailureOutcome, CalendarBackfillJob,
CalendarBackfillJobKey, CalendarBackfillKind, CalendarCapabilities, CalendarCreationTarget,
CalendarEvent, CalendarEventMutationTarget, CalendarEventOverride, CalendarEventSource,
CalendarEventSourceContent, CalendarEventUpsert, CalendarGrantBinding, CalendarGrantIntent,
CalendarLinkTokenIdentity, CalendarMentionEvent, CalendarMentionPreview,
CalendarMentionRequestItem, CalendarMentionViewerCopy, CalendarOccurrence,
CalendarOccurrenceCursor, CalendarProvider, CalendarReminderFiring, CalendarSyncStatus,
CalendarWatchRelease, ConferenceProvider, DisconnectedCalendar, DueCalendarReminder,
EventDetails, EventReminderOverride, EventReminders, EventStart, EventStatus, EventTime,
EventTransparency, EventType, EventVisibility, GOOGLE_CALENDAR_SCOPES,
GoogleCalendarSyncSnapshot, GoogleScopeSet, GoogleWatchChannel, GuestPolicy, MeetingCopy,
OccurrenceException, OccurrenceListing, OccurrenceRange, OwnedInbox, ProviderCalendar,
StoredGoogleCalendar, TeamOutOfOffice, ViewerCapabilities, VisibleCalendar,
is_system_calendar,
},
ports::{
CalendarBackfillRepository, CalendarEventChange, CalendarEventWrite,
CalendarEventWriteOutcome, CalendarReminderDispatchRepo, CalendarRepository,
GoogleCalendarSyncRepository, RetiredCalendarEvent,
},
};
/// PostgreSQL calendar repository.
#[derive(Clone)]
pub struct PgCalendarRepository {
pool: PgPool,
}
impl PgCalendarRepository {
/// Construct a repository from the shared MacroDB pool.
pub fn new(pool: PgPool) -> Self {
Self { pool }
}
async fn persist_google_backfill_failure(
&self,
key: CalendarBackfillJobKey,
lease_token: Option<Uuid>,
disposition: CalendarBackfillFailureDisposition,
message: &str,
) -> Result<CalendarBackfillFailureOutcome, Report> {
let (job_status, account_status, completed_at, link_needs_reauth) = match disposition {
CalendarBackfillFailureDisposition::Retry => ("pending", "pending", None, false),
CalendarBackfillFailureDisposition::Permanent => {
("failed", "error", Some(Utc::now()), false)
}
CalendarBackfillFailureDisposition::ReauthRequired => {
("failed", "reauth_required", Some(Utc::now()), true)
}
CalendarBackfillFailureDisposition::CalendarPermissionRequired => {
("failed", "reauth_required", Some(Utc::now()), false)
}
};
let required_scopes = GOOGLE_CALENDAR_SCOPES.map(str::to_owned);
let mut tx = self.pool.begin().await.map_err(report)?;
// Incremental grant application locks the inbox before its jobs. Keep
// the same order for reauth failure so concurrent consent and worker
// deliveries cannot deadlock.
let previous_link_reauth = if link_needs_reauth {
Some(
sqlx::query_scalar!(
r#"
SELECT needs_reauth
FROM email_links
WHERE id = $1
FOR UPDATE
"#,
key.email_link_id,
)
.fetch_one(&mut *tx)
.await
.map_err(report)?,
)
} else {
None
};
let updated = if let Some(lease_token) = lease_token {
sqlx::query!(
r#"
UPDATE calendar_backfill_jobs
SET status = $4,
lease_expires_at = NULL,
lease_token = NULL,
last_error = $2,
completed_at = $5,
updated_at = now()
WHERE id = $1
AND email_link_id = $3
AND kind = 'google_calendar'
AND status = 'running'
AND lease_token = $6
AND lease_expires_at > now()
AND EXISTS (
SELECT 1
FROM email_link_google_scopes scopes
WHERE scopes.link_id = calendar_backfill_jobs.email_link_id
AND scopes.grant_version = calendar_backfill_jobs.grant_version
AND scopes.granted_scopes @> $7::text[]
)
"#,
key.job_id,
message,
key.email_link_id,
job_status,
completed_at,
lease_token,
&required_scopes,
)
.execute(&mut *tx)
.await
.map_err(report)?
} else {
sqlx::query!(
r#"
UPDATE calendar_backfill_jobs
SET status = $4,
lease_expires_at = NULL,
lease_token = NULL,
last_error = $2,
completed_at = $5,
updated_at = now()
WHERE id = $1
AND email_link_id = $3
AND kind = 'google_calendar'
AND status NOT IN ('complete', 'failed')
AND lease_token IS NULL
AND EXISTS (
SELECT 1
FROM email_link_google_scopes scopes
WHERE scopes.link_id = calendar_backfill_jobs.email_link_id
AND scopes.grant_version = calendar_backfill_jobs.grant_version
AND scopes.granted_scopes @> $6::text[]
)
"#,
key.job_id,
message,
key.email_link_id,
job_status,
completed_at,
&required_scopes,
)
.execute(&mut *tx)
.await
.map_err(report)?
};
if updated.rows_affected() != 1 {
if lease_token.is_some() {
return Err(rootcause::report!(
"Google Calendar backfill lease was lost"
));
}
tx.commit().await.map_err(report)?;
return Ok(CalendarBackfillFailureOutcome {
job_transitioned: false,
link_reauth_transitioned: false,
});
}
sqlx::query!(
r#"
UPDATE calendar_accounts
SET sync_status = $2,
last_sync_error = $3,
updated_at = now()
WHERE email_link_id = $1
"#,
key.email_link_id,
account_status,
message,
)
.execute(&mut *tx)
.await
.map_err(report)?;
if link_needs_reauth {
sqlx::query!(
r#"
UPDATE email_links
SET needs_reauth = true,
last_sync_error_at = now(),
updated_at = now()
WHERE id = $1
"#,
key.email_link_id,
)
.execute(&mut *tx)
.await
.map_err(report)?;
}
tx.commit().await.map_err(report)?;
Ok(CalendarBackfillFailureOutcome {
job_transitioned: true,
link_reauth_transitioned: previous_link_reauth == Some(false),
})
}
#[cfg(test)]
async fn upsert_event_fixture(&self, upsert: CalendarEventUpsert) -> Result<Uuid, Report> {
self.upsert_event(CalendarEventWrite::Fixture(upsert))
.await
.map(|outcome| outcome.event_id)
}
#[cfg(test)]
async fn upsert_calendar_fixture(
&self,
account_id: Uuid,
calendar: ProviderCalendar,
) -> Result<Uuid, Report> {
let email_link_id = sqlx::query_scalar!(
"SELECT email_link_id FROM calendar_accounts WHERE id = $1",
account_id,
)
.fetch_one(&self.pool)
.await
.map_err(report)?;
let mut tx = self.pool.begin().await.map_err(report)?;
let mut log = ChangeLogBatch::default();
let id = upsert_calendar_tx(&mut tx, &mut log, email_link_id, account_id, calendar, None)
.await?
.0
.id;
log.commit(tx).await?;
Ok(id)
}
#[cfg(test)]
async fn upsert_google_account(&self, email_link_id: Uuid) -> Result<Uuid, Report> {
let mut tx = self.pool.begin().await.map_err(report)?;
let row = sqlx::query_as!(
GrantRow,
r#"
SELECT
l.macro_id,
l.email_address::text AS "email_address!",
COALESCE(g.granted_scopes, '{}') AS "granted_scopes!",
COALESCE(g.grant_version, 0) AS "grant_version!",
g.calendar_disabled_at
FROM email_links l
LEFT JOIN email_link_google_scopes g ON g.link_id = l.id
WHERE l.id = $1
"#,
email_link_id,
)
.fetch_one(&mut *tx)
.await
.map_err(report)?;
let id =
upsert_google_account_tx(&mut tx, email_link_id, &row.macro_id, &row.email_address)
.await?;
tx.commit().await.map_err(report)?;
Ok(id)
}
}
struct GrantRow {
macro_id: String,
email_address: String,
granted_scopes: Vec<String>,
grant_version: i64,
calendar_disabled_at: Option<DateTime<Utc>>,
}
struct StoredCalendarRow {
id: Uuid,
sync_token: Option<String>,
materialized_starts_at: Option<DateTime<Utc>>,
materialized_ends_at: Option<DateTime<Utc>>,
materialized_start_date: Option<NaiveDate>,
materialized_end_date: Option<NaiveDate>,
synced_at: Option<DateTime<Utc>>,
watch_expires_at: Option<DateTime<Utc>>,
watch_unsupported_at: Option<DateTime<Utc>>,
}
struct VisibleCalendarRow {
id: Uuid,
email_link_id: Uuid,
email_address: String,
name: String,
color: Option<String>,
is_primary: bool,
access_role: Option<String>,
provider_calendar_id: String,
default_reminders: serde_json::Value,
last_sync_error: Option<String>,
consecutive_sync_failures: i32,
unconfirmed_reply: bool,
provider: String,
online_meeting_providers: Vec<String>,
contributes_to_availability: bool,
}
fn visible_calendar(row: VisibleCalendarRow) -> VisibleCalendar {
let outlook = row.provider == "outlook";
VisibleCalendar {
provider: if outlook {
CalendarProvider::Outlook
} else {
CalendarProvider::Google
},
capabilities: if outlook {
CalendarCapabilities::outlook(
row.online_meeting_providers
.iter()
.any(|provider| provider == "teamsForBusiness"),
)
} else {
CalendarCapabilities::google()
},
id: row.id,
email_link_id: row.email_link_id,
email_address: row.email_address,
name: row.name,
color: row.color,
is_primary: row.is_primary,
is_writable: matches!(row.access_role.as_deref(), Some("owner" | "writer")),
is_subscription: is_system_calendar(&row.provider_calendar_id),
contributes_to_availability: row.contributes_to_availability,
sync_error: VisibleCalendar::sync_issue(
row.last_sync_error,
row.consecutive_sync_failures,
row.unconfirmed_reply,
),
default_reminders: serde_json::from_value(row.default_reminders)
.inspect_err(|e| {
tracing::error!(error = ?e, calendar_id = %row.id, "malformed calendar default_reminders json");
})
.unwrap_or_default(),
}
}
struct OccurrenceJoinRow {
event_id: Uuid,
source_link_id: Uuid,
occurrence_key: String,
recurrence_id: Option<String>,
occurrence_starts_at: Option<DateTime<Utc>>,
occurrence_ends_at: Option<DateTime<Utc>>,
occurrence_start_date: Option<NaiveDate>,
occurrence_end_date: Option<NaiveDate>,
is_cancelled: bool,
override_title: Option<String>,
override_description: Option<String>,
override_location: Option<String>,
override_status: Option<String>,
override_reminders: Option<serde_json::Value>,
owner_id: String,
ical_uid: String,
title: String,
description: Option<String>,
location: Option<String>,
status: String,
visibility: String,
transparency: String,
event_type: String,
starts_at: Option<DateTime<Utc>>,
ends_at: Option<DateTime<Utc>>,
start_date: Option<NaiveDate>,
end_date: Option<NaiveDate>,
time_zone: Option<String>,
recurrence_lines: Vec<String>,
organizer_email: Option<String>,
organizer_name: Option<String>,
creator_email: Option<String>,
creator_name: Option<String>,
conference_url: Option<String>,
conference_provider: Option<String>,
sequence: i32,
is_read_only: bool,
reminders_use_default: bool,
reminder_overrides: serde_json::Value,
guests_can_modify: bool,
guests_can_invite_others: bool,
guests_can_see_other_guests: bool,
is_snapshot: bool,
created_at: DateTime<Utc>,
updated_at: DateTime<Utc>,
}
/// A preview batch carries up to 100 events, so each description is capped
/// well above what the hover card shows; clients sanitize what arrives.
const MENTION_PREVIEW_DESCRIPTION_MAX_CHARS: u16 = 4000;
struct MentionPreviewRow {
mention_exists: bool,
resolved_event_id: Option<Uuid>,
viewer_calendar_ids: Option<Vec<Uuid>>,
is_channel_shared: Option<bool>,
is_snapshot: Option<bool>,
inbox_organizes: Option<bool>,
inbox_attends: Option<bool>,
title: Option<String>,
description: Option<String>,
location: Option<String>,
organizer_email: Option<String>,
organizer_name: Option<String>,
recurrence_lines: Option<Vec<String>>,
event_starts_at: Option<DateTime<Utc>>,
event_ends_at: Option<DateTime<Utc>>,
event_start_date: Option<NaiveDate>,
event_end_date: Option<NaiveDate>,
time_zone: Option<String>,
updated_at: Option<DateTime<Utc>>,
occurrence_key: Option<String>,
occurrence_starts_at: Option<DateTime<Utc>>,
occurrence_ends_at: Option<DateTime<Utc>>,
occurrence_start_date: Option<NaiveDate>,
occurrence_end_date: Option<NaiveDate>,
attendee_count: Option<i64>,
}
struct OverrideAttendeeRow {
event_id: Uuid,
recurrence_id: String,
email: Option<String>,
display_name: Option<String>,
response_status: Option<String>,
is_organizer: Option<bool>,
is_optional: Option<bool>,
is_self: Option<bool>,
comment: Option<String>,
}
struct AttendeeRow {
event_id: Uuid,
email: String,
display_name: Option<String>,
response_status: String,
is_organizer: bool,
is_optional: bool,
is_self: bool,
comment: Option<String>,
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct StoredSourceProjection {
#[serde(default, skip_serializing_if = "Option::is_none")]
automatic_decline: Option<crate::domain::models::AutomaticDeclinePolicy>,
#[serde(serialize_with = "serialize_stored_event")]
event: CalendarEvent,
overrides: Vec<CalendarEventOverride>,
occurrences: Vec<CalendarOccurrence>,
}
/// The entity as a source projection stores it: never the viewer's
/// capabilities, the guest policy only when it differs from Google's default,
/// and the snapshot flag only on a snapshot, so projections stored before
/// these were modeled still compare equal and an unchanged event is not
/// rewritten.
fn serialize_stored_event<S: serde::Serializer>(
event: &CalendarEvent,
serializer: S,
) -> Result<S::Ok, S::Error> {
let mut value = serde_json::to_value(event).map_err(serde::ser::Error::custom)?;
if let Some(fields) = value.as_object_mut() {
fields.remove("viewerCan");
if event.guest_policy.is_default() {
fields.remove("guestPolicy");
}
if !event.is_snapshot {
fields.remove("isSnapshot");
}
}
value.serialize(serializer)
}
impl From<&CalendarEventUpsert> for StoredSourceProjection {
fn from(upsert: &CalendarEventUpsert) -> Self {
Self {
automatic_decline: upsert.source.details().automatic_decline.clone(),
event: upsert.event.clone(),
overrides: upsert.overrides.clone(),
occurrences: upsert.occurrences.clone(),
}
}
}
impl CalendarRepository for PgCalendarRepository {
#[tracing::instrument(skip(self, scopes), err)]
async fn apply_google_grant(
&self,
email_link_id: Uuid,
scopes: GoogleScopeSet,
intent: CalendarGrantIntent,
) -> Result<AppliedGoogleGrant, Report> {
let mut tx = self.pool.begin().await.map_err(report)?;
// The email_links row remains the grant serialization point. Every
// production side-table write below occurs while holding this lock.
let row = sqlx::query_as!(
GrantRow,
r#"
SELECT
l.macro_id,
l.email_address::text AS "email_address!",
COALESCE(g.granted_scopes, '{}') AS "granted_scopes!",
COALESCE(g.grant_version, 0) AS "grant_version!",
g.calendar_disabled_at
FROM email_links l
LEFT JOIN email_link_google_scopes g ON g.link_id = l.id
WHERE l.id = $1
FOR UPDATE OF l
"#,
email_link_id,
)
.fetch_one(&mut *tx)
.await
.map_err(report)?;
// The user's own opt-out outranks whatever Google reports. Consent
// requests carry `include_granted_scopes=true`, so a plain Gmail
// reconnect hands back the calendar scopes of an earlier grant; only a
// flow that explicitly asked for calendar counts as re-enabling it.
let clear_opt_out = matches!(intent, CalendarGrantIntent::CalendarRequested);
let calendar_opted_out = row.calendar_disabled_at.is_some() && !clear_opt_out;
let scopes = if calendar_opted_out {
scopes.without_calendar()
} else {
scopes
};
let old_scopes = GoogleScopeSet::from_scopes(row.granted_scopes);
let had_calendar_capability = old_scopes.has_calendar_capability();
let changed = old_scopes != scopes;
if !changed {
if clear_opt_out {
clear_calendar_opt_out_tx(&mut tx, email_link_id).await?;
}
let jobs = if scopes.has_calendar_capability() {
retry_failed_backfills_tx(&mut tx, email_link_id, row.grant_version).await?
} else {
Vec::new()
};
tx.commit().await.map_err(report)?;
return Ok(AppliedGoogleGrant {
grant_version: row.grant_version,
changed: false,
jobs,
});
}
let grant_version = row.grant_version + 1;
let granted_scopes = scopes.clone().into_vec();
sqlx::query!(
r#"
INSERT INTO email_link_google_scopes (link_id, granted_scopes, grant_version)
VALUES ($1, $2, $3)
ON CONFLICT (link_id) DO UPDATE
SET granted_scopes = EXCLUDED.granted_scopes,
grant_version = EXCLUDED.grant_version,
calendar_disabled_at = CASE
WHEN $4 THEN NULL
ELSE email_link_google_scopes.calendar_disabled_at
END,
updated_at = now()
"#,
email_link_id,
&granted_scopes,
grant_version,
clear_opt_out,
)
.execute(&mut *tx)
.await
.map_err(report)?;
invalidate_stale_google_jobs_tx(&mut tx, email_link_id, grant_version).await?;
let mut jobs = Vec::new();
let mut log = ChangeLogBatch::default();
let has_calendar_capability = scopes.has_calendar_capability();
if had_calendar_capability && !has_calendar_capability {
disable_calendar_capability_tx(&mut tx, &mut log, email_link_id).await?;
}
if has_calendar_capability {
let account_id =
upsert_google_account_tx(&mut tx, email_link_id, &row.macro_id, &row.email_address)
.await?;
for kind in [CalendarBackfillKind::GoogleCalendar] {
let job_id = Uuid::now_v7();
let inserted = sqlx::query_scalar!(
r#"
INSERT INTO calendar_backfill_jobs (
id, email_link_id, account_id, kind, grant_version
)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (email_link_id, kind, grant_version) DO NOTHING
RETURNING id
"#,
job_id,
email_link_id,
account_id,
kind.as_str(),
grant_version,
)
.fetch_optional(&mut *tx)
.await
.map_err(report)?;
if let Some(job_id) = inserted {
sqlx::query!(
r#"
INSERT INTO calendar_sync_outbox (
id, backfill_job_id
)
VALUES ($1, $2)
"#,
Uuid::now_v7(),
job_id,
)
.execute(&mut *tx)
.await
.map_err(report)?;
jobs.push(CalendarBackfillJob {
id: job_id,
email_link_id,
account_id: Some(account_id),
kind,
grant_version,
});
}
}
}
log.commit(tx).await?;
Ok(AppliedGoogleGrant {
grant_version,
changed,
jobs,
})
}
#[tracing::instrument(skip(self, requester_id), err)]
async fn disconnect_provider_calendar(
&self,
requester_id: &str,
email_link_id: Uuid,
) -> Result<Option<DisconnectedCalendar>, Report> {
let mut tx = self.pool.begin().await.map_err(report)?;
// Same serialization point and lock order as grant application, so a
// consent landing concurrently either precedes or follows this removal.
// Only the inbox's owner may disconnect it: a delegate reads the
// owner's calendar and must not be able to delete the owner's data.
let row = sqlx::query!(
r#"
SELECT
l.fusionauth_user_id,
l.email_address::text AS "email_address!",
l.provider::text AS "provider!",l.id AS link_id,l.sync_generation,l.grant_generation,
COALESCE(g.granted_scopes, '{}') AS "granted_scopes!"
FROM email_links l
LEFT JOIN email_link_google_scopes g ON g.link_id = l.id
WHERE l.id = $1 AND l.macro_id = $2
FOR UPDATE OF l
"#,
email_link_id,
requester_id,
)
.fetch_optional(&mut *tx)
.await
.map_err(report)?;
let Some(row) = row else {
return Ok(None);
};
if row.provider == "OUTLOOK" {
sqlx::query!("UPDATE email_link_microsoft_scopes SET calendar_disabled_at=now(),updated_at=now() WHERE link_id=$1",email_link_id).execute(&mut *tx).await.map_err(report)?;
let mut log = ChangeLogBatch::default();
disable_calendar_capability_tx(&mut tx, &mut log, email_link_id).await?;
sqlx::query!(
"DELETE FROM calendar_accounts WHERE email_link_id=$1",
email_link_id
)
.execute(&mut *tx)
.await
.map_err(report)?;
log.commit(tx).await?;
return Ok(Some(DisconnectedCalendar {
token_identity: CalendarLinkTokenIdentity {
binding: Some(CalendarGrantBinding {
link_id: row.link_id,
sync_generation: row.sync_generation,
grant_generation: row.grant_generation,
}),
fusionauth_user_id: row.fusionauth_user_id,
email_address: row.email_address,
provider: CalendarProvider::Outlook,
},
watch_channels: vec![],
}));
}
// Read the open channels before the calendars go away; the caller
// closes them at Google once the local removal has committed.
let watch_channels = sqlx::query!(
r#"
SELECT
c.watch_channel_id AS "channel_id!",
c.watch_resource_id AS "resource_id!"
FROM calendars c
JOIN calendar_accounts a ON a.id = c.account_id
WHERE a.email_link_id = $1
AND c.watch_channel_id IS NOT NULL
AND c.watch_resource_id IS NOT NULL
"#,
email_link_id,
)
.fetch_all(&mut *tx)
.await
.map_err(report)?
.into_iter()
.map(|row| CalendarWatchRelease {
channel_id: row.channel_id,
resource_id: row.resource_id,
})
.collect();
let granted_scopes = GoogleScopeSet::from_scopes(row.granted_scopes)
.without_calendar()
.into_vec();
let grant_version = sqlx::query_scalar!(
r#"
INSERT INTO email_link_google_scopes (
link_id, granted_scopes, grant_version, calendar_disabled_at
)
VALUES ($1, $2, 1, now())
ON CONFLICT (link_id) DO UPDATE
SET granted_scopes = EXCLUDED.granted_scopes,
grant_version = email_link_google_scopes.grant_version + 1,
calendar_disabled_at = now(),
updated_at = now()
RETURNING grant_version AS "grant_version!"
"#,
email_link_id,
&granted_scopes,
)
.fetch_one(&mut *tx)
.await
.map_err(report)?;
// Fence anything mid-flight against the superseded grant, then tear
// the local projection down and drop the account itself, which
// cascades its calendars and backfill jobs.
invalidate_stale_google_jobs_tx(&mut tx, email_link_id, grant_version).await?;
let mut log = ChangeLogBatch::default();
disable_calendar_capability_tx(&mut tx, &mut log, email_link_id).await?;
sqlx::query!(
"DELETE FROM calendar_accounts WHERE email_link_id = $1",
email_link_id,
)
.execute(&mut *tx)
.await
.map_err(report)?;
log.commit(tx).await?;
Ok(Some(DisconnectedCalendar {
token_identity: CalendarLinkTokenIdentity {
binding: Some(CalendarGrantBinding {
link_id: row.link_id,
sync_generation: row.sync_generation,
grant_generation: row.grant_generation,
}),
fusionauth_user_id: row.fusionauth_user_id,
email_address: row.email_address,
provider: CalendarProvider::from_link(&row.provider)
.ok_or_else(|| rootcause::report!("unsupported calendar provider"))?,
},
watch_channels,
}))
}
#[tracing::instrument(skip(self, write), fields(meeting_content = tracing::field::Empty), err)]
async fn upsert_event(
&self,
write: CalendarEventWrite,
) -> Result<CalendarEventWriteOutcome, Report> {
let mut tx = self.pool.begin().await.map_err(report)?;
let user_mutation = matches!(write, CalendarEventWrite::UserMutation(_));
let provider_sync = matches!(write, CalendarEventWrite::GoogleBackfill { .. });
let mut upsert = match write {
#[cfg(feature = "outlook")]
CalendarEventWrite::OutlookSync { lease, upsert } => {
outlook::fence(&mut tx, &lease).await?;
if !matches!(&upsert.source, CalendarEventSource::Outlook(_))
|| upsert.source.details().binding != Some(lease.binding)
|| lease
.target
.as_ref()
.is_none_or(|t| t.calendar_id != upsert.source.details().calendar_id)
{
return Err(rootcause::report!(
"Outlook calendar projection does not match its lease"
));
}
upsert
}
CalendarEventWrite::GoogleBackfill {
key,
lease_token,
upsert,
} => {
if !matches!(&upsert.source, CalendarEventSource::Google(_)) {
return Err(rootcause::report!(
"calendar source does not match the Google backfill fence"
));
}
let source = upsert.source.details();
if source.email_link_id != key.email_link_id {
return Err(rootcause::report!(
"Google calendar event fence does not match its connected inbox"
));
}
fence_google_mutation_tx(&mut tx, key, lease_token, Some(source.account_id))
.await?;
upsert
}
CalendarEventWrite::UserMutation(upsert) => {
if matches!(&upsert.source, CalendarEventSource::Outlook(_)) {
#[cfg(feature = "outlook")]
outlook::fence_binding(
&mut tx,
upsert.source.details().binding.ok_or_else(|| {
rootcause::report!("Microsoft calendar echo requires its binding")
})?,
)
.await?;
#[cfg(not(feature = "outlook"))]
return Err(rootcause::report!(
"Microsoft calendar ingestion is disabled"
));
}
upsert
}
#[cfg(test)]
CalendarEventWrite::Fixture(upsert) => upsert,
};
let source = upsert.source.details();
let source_kind = upsert.source.kind();
let source_link_id = source.email_link_id;
let reconciliation_lock = event_reconciliation_lock(source_link_id, &upsert.event.ical_uid);
sqlx::query_scalar!(
r#"SELECT 1 AS "locked!" FROM pg_advisory_xact_lock($1)"#,
reconciliation_lock,
)
.fetch_one(&mut *tx)
.await
.map_err(report)?;
// Full snapshots re-upsert every event they observed, and a provider
// sync-token reset makes that happen wholesale. When the incoming
// Google projection is identical to the stored one, skip the write
// path entirely so rebuilds cost reads, not occurrence churn.
let existing = sqlx::query!(
r#"
SELECT event_id, normalized_payload, source_sequence
FROM calendar_event_sources
WHERE source_kind = $4
AND account_id = $1
AND calendar_id = $2
AND provider_event_id = $3
"#,
source.account_id,
source.calendar_id,
&source.provider_event_id,
source_kind,
)
.fetch_optional(&mut *tx)
.await
.map_err(report)?;
// The old source matters too: changing OOO to a regular event withdraws
// a status teammates may already have cached. Unknown legacy payloads
// cannot certify an unrelated update.
let team_ooo_changed = upsert.event.event_type == EventType::OutOfOffice
|| existing.as_ref().is_some_and(|row| {
row.normalized_payload
.get("event")
.and_then(serde_json::Value::as_object)
.is_none_or(|event| {
// Regular events omit eventType in stored projections.
event.get("eventType").is_some_and(|kind| {
serde_json::from_value::<EventType>(kind.clone())
.map_or(true, |kind| kind == EventType::OutOfOffice)
})
})
});
let mut became_seat = false;
if let Some(row) = &existing {
// A snapshot an invitation has reached is its owner's seat at the
// meeting. Answering can leave Google's copy looking like the
// import again, as when the meeting lists only them, so a copy
// stored as a seat stays one.
let stored_snapshot = row
.normalized_payload
.pointer("/event/isSnapshot")
.is_some_and(|value| value == true);
became_seat = stored_snapshot && !upsert.event.is_snapshot;
upsert.event.is_snapshot &= stored_snapshot;
let incoming =
serde_json::to_value(StoredSourceProjection::from(&upsert)).map_err(report)?;
if canonical_projection(&row.normalized_payload) == canonical_projection(&incoming) {
source_access::verify_source_access(&mut tx, source).await?;
tx.commit().await.map_err(report)?;
return Ok(CalendarEventWriteOutcome {
event_id: row.event_id,
owner_id: upsert.event.owner_id.clone(),
change: CalendarEventChange::Unchanged,
team_ooo_changed: false,
aligned_copies: Vec::new(),
});
}
}
let incoming_sequence = db_sequence(upsert.event.sequence)?;
let copy_advanced = existing
.as_ref()
.is_none_or(|row| incoming_sequence > row.source_sequence);
let (starts_at, ends_at, start_date, end_date, time_zone) = split_time(&upsert.event.time);
// The entity row is created by whichever source arrives first and
// carries that source's content until a better-ranked source claims
// it below. An existing row is left alone here: its content belongs
// to its canonical source, not to whichever copy synced last.
let inserted = sqlx::query_scalar!(
r#"
INSERT INTO calendar_events (
id, owner_id, source_link_id, ical_uid, title, description, location,
status, visibility, transparency, event_type,
starts_at, ends_at, start_date, end_date, time_zone,
recurrence_lines, organizer_email, organizer_name,
creator_email, creator_name,
conference_url, conference_provider, sequence, is_read_only,
canonical_source_kind,
reminders_use_default, reminder_overrides,
guests_can_modify, guests_can_invite_others, guests_can_see_other_guests,
is_snapshot,
created_at, updated_at, schedule_updated_at
)
VALUES (
$1, $2, $3, $4, $5, $6, $7,
$8, $9, $10, $30,
$11, $12, $13, $14, $15,
$16, $17, $18,
$28, $29,
$19, $27, $20, $21, $22,
$25, $26,
$31, $32, $33,
$34,
$23, $24, $24
)
ON CONFLICT (owner_id, source_link_id, ical_uid) DO NOTHING
RETURNING id
"#,
upsert.event.id,
&upsert.event.owner_id,
source_link_id,
&upsert.event.ical_uid,
&upsert.event.title,
upsert.event.description.as_deref(),
upsert.event.location.as_deref(),
upsert.event.status.as_str(),
upsert.event.visibility.as_str(),
upsert.event.transparency.as_str(),
starts_at,
ends_at,
start_date,
end_date,
time_zone,
&upsert.event.recurrence_lines,
upsert.event.organizer_email.as_deref(),
upsert.event.organizer_name.as_deref(),
upsert.event.conference_url.as_deref(),
incoming_sequence,
upsert.event.is_read_only,
source_kind,
upsert.event.created_at,
upsert.event.updated_at,
upsert.event.reminders.use_default,
serde_json::to_value(&upsert.event.reminders.overrides).map_err(report)?,
upsert
.event
.conference_provider
.map(ConferenceProvider::as_str),
upsert.event.creator_email.as_deref(),
upsert.event.creator_name.as_deref(),
upsert.event.event_type.as_str(),
upsert.event.guest_policy.can_modify,
upsert.event.guest_policy.can_invite_others,
upsert.event.guest_policy.can_see_other_guests,
upsert.event.is_snapshot,
)
.fetch_optional(&mut *tx)
.await
.map_err(report)?;
let (event_id, inserted) = match inserted {
Some(id) => (id, true),
None => (
sqlx::query_scalar!(
"SELECT id FROM calendar_events WHERE owner_id = $1 AND source_link_id = $2 AND ical_uid = $3",
&upsert.event.owner_id,
source_link_id,
&upsert.event.ical_uid,
)
.fetch_one(&mut *tx)
.await
.map_err(report)?,
false,
),
};
// The source row carries this copy's own content under its own
// freshness guard. A stale copy changes nothing at all.
let Some(source_id) = persist_source(&mut tx, event_id, &upsert).await? else {
tx.commit().await.map_err(report)?;
return Ok(CalendarEventWriteOutcome {
event_id,
owner_id: upsert.event.owner_id.clone(),
change: CalendarEventChange::Unchanged,
team_ooo_changed: false,
aligned_copies: Vec::new(),
});
};
if provider_sync {
source_access::invalidate_account_freshness(&mut tx, source.account_id).await?;
}
// Content follows the canonical copy. The schedule follows whichever
// copy last wrote it: the canonical copy takes it when that copy is
// new to Macro, advanced its own sequence, or is at least as fresh as
// the write it replaces, a user edit through another copy lands when
// it is at least that fresh, and the copy that wrote the schedule
// keeps writing it until then. The meeting's content (title,
// description, location, visibility) follows the same rule for the
// organizer's copy: Google applies the organizer's changes to the
// invitation on the primary calendar, the usual canonical copy, some
// seconds later, so a user edit through the organizer's copy lands at
// once, the canonical copy retakes the content once it is at least
// that fresh, and the organizer's copy keeps writing it until then.
// The organizer's copy holds the meeting's own guests, organizer, and
// conference, so the schedule it writes includes them.
let canonical = canonical_source(&mut tx, event_id).await?;
let schedule = schedule_owner(&mut tx, event_id).await?;
let projection = StoredSourceProjection::from(&upsert);
let is_canonical =
canonical.as_ref().map(|canonical| canonical.source_id) == Some(source_id);
let is_organizer_copy = !is_canonical
&& organizes_meeting(&mut tx, source_id, upsert.event.organizer_email.as_deref())
.await?;
let content_ahead = if is_canonical || is_organizer_copy {
content_ahead(&mut tx, event_id).await?
} else {
None
};
let takes_meeting_content = if is_canonical {
content_ahead.is_none_or(|ahead| upsert.event.updated_at >= ahead)
} else if is_organizer_copy && (user_mutation || content_ahead.is_some()) {
content_ahead
.or(canonical.as_ref().map(|canonical| canonical.updated_at))
.is_some_and(|fresh| upsert.event.updated_at >= fresh)
} else {
false
};
let meeting_content = match (takes_meeting_content, is_canonical) {
(true, false) => Some("organizer_copy"),
(true, true) if content_ahead.is_some() => Some("canonical_retook"),
(false, _) if content_ahead.is_some() => Some("kept_pending_edit"),
_ => None,
};
if let Some(meeting_content) = meeting_content {
tracing::Span::current().record("meeting_content", meeting_content);
}
// A canonical copy older than a pending edit through the organizer's
// copy leaves the schedule to it too, even when new to Macro or
// advanced: that edit's guests and time are the newer ones.
let owns_schedule = schedule.source_id == Some(source_id);
let writes_schedule = if is_canonical {
takes_meeting_content
&& (owns_schedule
|| copy_advanced
|| upsert.event.updated_at >= schedule.updated_at)
} else if user_mutation {
upsert.event.updated_at >= schedule.updated_at
} else {
owns_schedule
};
if is_canonical {
apply_content_projection(
&mut tx,
event_id,
source_id,
&projection,
source_kind,
takes_meeting_content,
)
.await?;
} else if takes_meeting_content {
apply_meeting_content(&mut tx, event_id, &projection).await?;
}
if writes_schedule {
if is_canonical || is_organizer_copy {
apply_schedule_projection(&mut tx, event_id, source_id, &projection).await?;
} else {
apply_time_projection(&mut tx, event_id, source_id, &projection).await?;
}
}
if is_canonical || writes_schedule {
rebuild_entity_reminder_firings(
&mut tx,
event_id,
canonical.map(|canonical| canonical.calendar_id),
)
.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,
"an invitation reached a snapshot, which is now its owner's seat"
);
}
Ok(CalendarEventWriteOutcome {
event_id,
owner_id: upsert.event.owner_id.clone(),
change: if inserted {
CalendarEventChange::Created
} else {
CalendarEventChange::Updated
},
team_ooo_changed,
aligned_copies: aligned,
})
}
#[tracing::instrument(skip(self, requester_id, range), err)]
async fn list_occurrences(
&self,
requester_id: &str,
range: OccurrenceRange,
cursor: Option<CalendarOccurrenceCursor>,
limit: u16,
) -> Result<Vec<OccurrenceListing>, Report> {
let cursor_starts_at = cursor.as_ref().map(|cursor| cursor.starts_at);
let cursor_event_id = cursor.as_ref().map(|cursor| cursor.event_id);
let cursor_occurrence_key = cursor.as_ref().map(|cursor| cursor.occurrence_key.as_str());
let rows = sqlx::query_as!(
OccurrenceJoinRow,
r#"
SELECT
occurrence.event_id,
event.source_link_id,
occurrence.occurrence_key,
occurrence.recurrence_id,
occurrence.starts_at AS occurrence_starts_at,
occurrence.ends_at AS occurrence_ends_at,
occurrence.start_date AS occurrence_start_date,
occurrence.end_date AS occurrence_end_date,
occurrence.is_cancelled,
override.title AS override_title,
override.description AS override_description,
override.location AS override_location,
override.status AS override_status,
override.reminders AS override_reminders,
event.owner_id,
event.ical_uid,
event.title,
event.description,
event.location,
event.status,
event.visibility,
event.transparency,
event.event_type,
event.starts_at,
event.ends_at,
event.start_date,
event.end_date,
event.time_zone,
event.recurrence_lines,
event.organizer_email,
event.organizer_name,
event.creator_email,
event.creator_name,
event.conference_url,
event.conference_provider,
event.sequence,
event.is_read_only,
event.reminders_use_default,
event.reminder_overrides,
event.guests_can_modify,
event.guests_can_invite_others,
event.guests_can_see_other_guests,
event.is_snapshot,
event.created_at,
event.updated_at
FROM calendar_event_occurrences occurrence
JOIN calendar_events event ON event.id = occurrence.event_id
LEFT JOIN calendar_event_overrides override
ON override.event_id = occurrence.event_id
AND override.recurrence_id = occurrence.recurrence_id
WHERE occurrence.owner_id IN (
SELECT $1::text
UNION
SELECT link.child_macro_id
FROM macro_user_links link
WHERE link.primary_macro_id = $1
)
AND event.status <> 'cancelled'
AND NOT occurrence.is_cancelled
AND (
event.owner_id = $1
OR EXISTS (
SELECT 1
FROM macro_user_links link
WHERE link.link_id = event.source_link_id
AND link.primary_macro_id = $1
)
)
AND (
occurrence.timed_span && tstzrange($2, $3, '[)')
OR (occurrence.starts_at = occurrence.ends_at
AND occurrence.starts_at >= $2 AND occurrence.starts_at < $3)
OR occurrence.day_span && daterange($4, $5, '[)')
)
AND (
$6::timestamptz IS NULL
OR (
COALESCE(
occurrence.starts_at,
occurrence.start_date::timestamp AT TIME ZONE 'UTC'
),
occurrence.event_id,
occurrence.occurrence_key
) > ($6, $7, $8)
)
ORDER BY
COALESCE(occurrence.starts_at, occurrence.start_date::timestamp AT TIME ZONE 'UTC'),
occurrence.event_id,
occurrence.occurrence_key
LIMIT $9
"#,
requester_id,
range.starts_at,
range.ends_at,
range.start_date,
range.end_date,
cursor_starts_at,
cursor_event_id,
cursor_occurrence_key,
i64::from(limit),
)
.fetch_all(&self.pool)
.await
.map_err(report)?;
let event_ids: Vec<_> = rows.iter().map(|row| row.event_id).collect();
let (attendees, override_attendees, source_contents) = try_join!(
fetch_attendees(&self.pool, &event_ids),
fetch_override_attendees(&self.pool, &event_ids),
fetch_source_contents(&self.pool, &event_ids),
)?;
rows.into_iter()
.map(|row| {
let event_id = row.event_id;
let link_id = row.source_link_id;
let occurrence = occurrence_from_join(&row)?;
// An exception's attendee list replaces the series list for
// that occurrence alone: Google records an instance-scoped
// RSVP there and never on the master.
let exception_attendees =
occurrence.recurrence_id.as_ref().and_then(|recurrence_id| {
override_attendees
.get(&(event_id, recurrence_id.clone()))
.cloned()
});
let series_attendees = attendees.get(&event_id).cloned().unwrap_or_default();
let sources = source_contents.get(&event_id).cloned().unwrap_or_default();
let mut row = row;
let mut exception = take_exception(&mut row);
exception.attendees = exception_attendees;
let event = series_event_from_join(row, series_attendees, sources)?;
Ok(OccurrenceListing {
event,
occurrence,
link_id,
exception,
})
})
.collect()
}
#[tracing::instrument(skip(self, requester_id, range), err)]
async fn list_team_out_of_office(
&self,
requester_id: &str,
range: OccurrenceRange,
limit: u16,
) -> Result<Vec<TeamOutOfOffice>, Report> {
// Compatibility OOO reads use the same verified source snapshots as
// team projections; canonical content never supplies private details.
super::pg_team::list_team_out_of_office(&self.pool, requester_id, range, limit).await
}
#[tracing::instrument(
skip(self, requester_id, items),
fields(channel_shared_count = tracing::field::Empty),
err
)]
async fn mention_previews(
&self,
requester_id: &str,
items: Vec<CalendarMentionRequestItem>,
now: DateTime<Utc>,
) -> Result<Vec<CalendarMentionPreview>, Report> {
let event_ids: Vec<Uuid> = items.iter().map(|item| item.event_id).collect();
let occurrence_keys: Vec<Option<String>> = items
.iter()
.map(|item| item.occurrence_key.clone())
.collect();
// The viewer lateral resolves the mentioned meeting to the
// requester's own projection through the shared iCalendar UID,
// preferring an owned copy over a delegated one and the mentioned
// row itself among ties. Only without such a copy does it fall back
// to the mentioned row, and only when that row was shared with a
// channel the requester currently belongs to and is still neither
// private nor confidential — the same rule entity access applies.
let rows = sqlx::query_as!(
MentionPreviewRow,
r#"
SELECT
(mentioned.id IS NOT NULL) AS "mention_exists!",
viewer_event.id AS "resolved_event_id?",
ARRAY(
SELECT viewer_source.calendar_id
FROM calendar_event_sources viewer_source
JOIN calendars viewer_calendar
ON viewer_calendar.id = viewer_source.calendar_id
JOIN calendar_accounts viewer_account
ON viewer_account.id = viewer_source.account_id
WHERE viewer_source.event_id = viewer_event.id
AND NOT viewer_calendar.is_deleted
AND viewer_account.sync_status <> 'disabled'
ORDER BY
viewer_source.id = calendar_event_canonical_source_id(viewer_event.id) DESC,
viewer_source.id
) AS "viewer_calendar_ids?",
viewer_event.is_channel_shared AS "is_channel_shared?",
viewer_event.is_snapshot AS "is_snapshot?",
viewer_event.inbox_organizes AS "inbox_organizes?",
viewer_event.inbox_attends AS "inbox_attends?",
COALESCE(occurrence_override.title, viewer_event.title) AS "title?",
-- A channel share is capped after its Macro call comes out,
-- since the join line closes the description.
CASE
WHEN viewer_event.is_channel_shared
THEN COALESCE(occurrence_override.description, viewer_event.description)
ELSE left(
COALESCE(occurrence_override.description, viewer_event.description),
$5
)
END AS "description?",
COALESCE(occurrence_override.location, viewer_event.location) AS "location?",
viewer_event.organizer_email AS "organizer_email?",
viewer_event.organizer_name AS "organizer_name?",
viewer_event.recurrence_lines AS "recurrence_lines?",
viewer_event.starts_at AS "event_starts_at?",
viewer_event.ends_at AS "event_ends_at?",
viewer_event.start_date AS "event_start_date?",
viewer_event.end_date AS "event_end_date?",
viewer_event.time_zone AS "time_zone?",
viewer_event.updated_at AS "updated_at?",
occurrence.occurrence_key AS "occurrence_key?",
occurrence.starts_at AS "occurrence_starts_at?",
occurrence.ends_at AS "occurrence_ends_at?",
occurrence.start_date AS "occurrence_start_date?",
occurrence.end_date AS "occurrence_end_date?",
attendees.attendee_count AS "attendee_count?"
FROM unnest($2::uuid[], $3::text[])
WITH ORDINALITY AS requested(event_id, occurrence_key, ord)
LEFT JOIN calendar_events mentioned
ON mentioned.id = requested.event_id
AND mentioned.status <> 'cancelled'
LEFT JOIN LATERAL (
SELECT resolved.*
FROM (
SELECT
candidate.id,
false AS is_channel_shared,
(candidate.owner_id = $1) AS is_owned,
(candidate.id = mentioned.id) AS is_mentioned,
candidate.is_snapshot,
-- The copy's own inbox decides how the requester
-- holds it, as it decides their capabilities: an
-- inbox they own that organizes it or is on it.
COALESCE(
lower(copy_inbox.email_address) = lower(candidate.organizer_email)
OR EXISTS (
SELECT 1
FROM calendar_event_attendees organizer
WHERE organizer.event_id = candidate.id
AND organizer.is_organizer
AND lower(organizer.email) = lower(copy_inbox.email_address)
)
-- A calendar the inbox can write organizes it,
-- as Google names a secondary calendar.
OR EXISTS (
SELECT 1
FROM calendar_accounts organizer_account
JOIN calendars organizer_calendar
ON organizer_calendar.account_id = organizer_account.id
WHERE organizer_account.email_link_id = copy_inbox.id
AND organizer_account.sync_status <> 'disabled'
AND NOT organizer_calendar.is_deleted
AND organizer_calendar.access_role IN ('owner', 'writer')
AND lower(organizer_calendar.provider_calendar_id)
= lower(candidate.organizer_email)
),
false
) AS inbox_organizes,
EXISTS (
SELECT 1
FROM calendar_event_attendees guest
WHERE guest.event_id = candidate.id
AND lower(guest.email) = lower(copy_inbox.email_address)
) AS inbox_attends,
candidate.title,
candidate.description,
candidate.location,
candidate.organizer_email,
candidate.organizer_name,
candidate.recurrence_lines,
candidate.starts_at,
candidate.ends_at,
candidate.start_date,
candidate.end_date,
candidate.time_zone,
candidate.updated_at
FROM calendar_events candidate
LEFT JOIN email_links copy_inbox
ON copy_inbox.id = candidate.source_link_id
AND copy_inbox.macro_id = $1
WHERE calendar_meeting_uid(candidate.ical_uid)
= calendar_meeting_uid(mentioned.ical_uid)
AND candidate.status <> 'cancelled'
AND (
candidate.owner_id = $1
OR EXISTS (
SELECT 1
FROM macro_user_links link
WHERE link.link_id = candidate.source_link_id
AND link.primary_macro_id = $1
)
)
UNION ALL
SELECT
mentioned.id,
true,
false,
true,
false,
false,
false,
mentioned.title,
mentioned.description,
mentioned.location,
mentioned.organizer_email,
mentioned.organizer_name,
mentioned.recurrence_lines,
mentioned.starts_at,
mentioned.ends_at,
mentioned.start_date,
mentioned.end_date,
mentioned.time_zone,
mentioned.updated_at
WHERE mentioned.visibility IN ('default', 'public')
AND EXISTS (
SELECT 1
FROM entity_access grant_row
JOIN comms_channel_participants participant
ON participant.channel_id::text = grant_row.source_id
AND participant.user_id = $1
AND participant.left_at IS NULL
WHERE grant_row.entity_id = mentioned.id
AND grant_row.entity_type = 'calendar_event'
AND grant_row.source_type = 'channel'
)
) resolved
ORDER BY
resolved.is_channel_shared,
resolved.is_owned DESC,
resolved.is_mentioned DESC,
resolved.updated_at DESC,
resolved.id
LIMIT 1
) viewer_event ON true
LEFT JOIN LATERAL (
SELECT
instance.occurrence_key,
instance.recurrence_id,
instance.starts_at,
instance.ends_at,
instance.start_date,
instance.end_date
FROM calendar_event_occurrences instance
CROSS JOIN LATERAL (
SELECT COALESCE(
instance.starts_at,
instance.start_date::timestamp AT TIME ZONE 'UTC'
) AS at
) instance_start
WHERE instance.event_id = viewer_event.id
AND NOT instance.is_cancelled
ORDER BY
(instance.occurrence_key
IS NOT DISTINCT FROM requested.occurrence_key) DESC,
(instance_start.at >= $4) DESC,
CASE WHEN instance_start.at >= $4 THEN instance_start.at END ASC,
instance_start.at DESC,
instance.occurrence_key
LIMIT 1
) occurrence ON true
-- An exception's content replaces the series content for the
-- previewed occurrence alone, as it does in the event view.
LEFT JOIN calendar_event_overrides occurrence_override
ON occurrence_override.event_id = viewer_event.id
AND occurrence_override.recurrence_id = occurrence.recurrence_id
LEFT JOIN LATERAL (
SELECT count(*) AS attendee_count
FROM calendar_event_attendees attendee
WHERE attendee.event_id = viewer_event.id
) attendees ON true
ORDER BY requested.ord
"#,
requester_id,
&event_ids,
&occurrence_keys as &[Option<String>],
now,
i32::from(MENTION_PREVIEW_DESCRIPTION_MAX_CHARS),
)
.fetch_all(&self.pool)
.await
.map_err(report)?;
tracing::Span::current().record(
"channel_shared_count",
rows.iter()
.filter(|row| row.is_channel_shared == Some(true))
.count(),
);
rows.into_iter().map(mention_preview_from_row).collect()
}
#[tracing::instrument(skip(self, requester_id), err)]
async fn meeting_copies(
&self,
requester_id: &str,
event_id: Uuid,
) -> Result<Vec<MeetingCopy>, Report> {
// The copy's own inbox decides how the requester holds it, as it
// decides their capabilities and the mention preview's `isOwned`.
let rows = sqlx::query!(
r#"
SELECT
candidate.id AS "event_id!",
copy_inbox.email_address AS "inbox!",
COALESCE(
lower(copy_inbox.email_address) = lower(candidate.organizer_email)
OR EXISTS (
SELECT 1
FROM calendar_event_attendees organizer
WHERE organizer.event_id = candidate.id
AND organizer.is_organizer
AND lower(organizer.email) = lower(copy_inbox.email_address)
)
OR EXISTS (
SELECT 1
FROM calendar_accounts organizer_account
JOIN calendars organizer_calendar
ON organizer_calendar.account_id = organizer_account.id
WHERE organizer_account.email_link_id = copy_inbox.id
AND organizer_account.sync_status <> 'disabled'
AND NOT organizer_calendar.is_deleted
AND organizer_calendar.access_role IN ('owner', 'writer')
AND lower(organizer_calendar.provider_calendar_id)
= lower(candidate.organizer_email)
),
false
) AS "organizes!",
EXISTS (
SELECT 1
FROM calendar_event_attendees guest
WHERE guest.event_id = candidate.id
AND lower(guest.email) = lower(copy_inbox.email_address)
) AS "attends!"
FROM calendar_events addressed
JOIN calendar_events candidate
ON calendar_meeting_uid(candidate.ical_uid)
= calendar_meeting_uid(addressed.ical_uid)
JOIN email_links copy_inbox
ON copy_inbox.id = candidate.source_link_id
AND copy_inbox.macro_id = $1
WHERE addressed.id = $2
AND candidate.owner_id = $1
AND candidate.status <> 'cancelled'
ORDER BY lower(copy_inbox.email_address), candidate.id
"#,
requester_id,
event_id,
)
.fetch_all(&self.pool)
.await
.map_err(report)?;
Ok(rows
.into_iter()
.map(|row| MeetingCopy {
event_id: row.event_id,
inbox: row.inbox,
organizes: row.organizes,
attends: row.attends,
})
.collect())
}
#[tracing::instrument(skip(self, requester_id), err)]
async fn event_export(
&self,
requester_id: &str,
event_id: Uuid,
) -> Result<Option<CalendarEventExport>, Report> {
export::event_export(&self.pool, requester_id, event_id).await
}
#[tracing::instrument(skip(self, requester_id), err)]
async fn forwarded_copy(
&self,
requester_id: &str,
event_id: Uuid,
) -> Result<Option<crate::domain::ics::ForwardedCopy>, Report> {
export::forwarded_copy(&self.pool, requester_id, event_id).await
}
#[tracing::instrument(skip(self, requester_id, requester_email), err)]
async fn open_join_request(
&self,
event_id: Uuid,
requester_id: &str,
requester_email: &str,
) -> Result<(crate::domain::join_requests::CalendarJoinRequest, bool), Report> {
join_requests::open_join_request(&self.pool, event_id, requester_id, requester_email).await
}
#[tracing::instrument(skip(self, requester_id), err)]
async fn find_join_request(
&self,
event_id: Uuid,
requester_id: &str,
) -> Result<Option<crate::domain::join_requests::CalendarJoinRequest>, Report> {
join_requests::find_join_request(&self.pool, event_id, requester_id).await
}
#[tracing::instrument(skip(self), err)]
async fn list_pending_join_requests(
&self,
event_id: Uuid,
) -> Result<Vec<crate::domain::join_requests::CalendarJoinRequest>, Report> {
join_requests::list_pending_join_requests(&self.pool, event_id).await
}
#[tracing::instrument(skip(self), err)]
async fn get_join_request(
&self,
request_id: Uuid,
) -> Result<Option<crate::domain::join_requests::CalendarJoinRequest>, Report> {
join_requests::get_join_request(&self.pool, request_id).await
}
#[tracing::instrument(skip(self), err)]
async fn resolve_join_request(
&self,
request_id: Uuid,
status: crate::domain::join_requests::CalendarJoinRequestStatus,
) -> Result<Option<crate::domain::join_requests::CalendarJoinRequest>, Report> {
join_requests::resolve_join_request(&self.pool, request_id, status).await
}
#[tracing::instrument(skip(self, requester_id), err)]
async fn sync_status(&self, requester_id: &str) -> Result<CalendarSyncStatus, Report> {
let is_syncing = sqlx::query_scalar!(
r#"
SELECT EXISTS (
SELECT 1
FROM calendar_accounts account
WHERE account.sync_status IN ('pending', 'syncing')
AND (
account.owner_id = $1
OR EXISTS (
SELECT 1
FROM macro_user_links link
WHERE link.link_id = account.email_link_id
AND link.primary_macro_id = $1
)
)
) AS "is_syncing!"
"#,
requester_id,
)
.fetch_one(&self.pool)
.await
.map_err(report)?;
Ok(if is_syncing {
CalendarSyncStatus::Syncing
} else {
CalendarSyncStatus::Ready
})
}
#[tracing::instrument(skip(self, calendar), fields(job_id = %key.job_id), err)]
async fn upsert_google_calendar(
&self,
key: CalendarBackfillJobKey,
lease_token: Uuid,
account_id: Uuid,
calendar: ProviderCalendar,
) -> Result<StoredGoogleCalendar, Report> {
let mut tx = self.pool.begin().await.map_err(report)?;
fence_google_mutation_tx(&mut tx, key, lease_token, Some(account_id)).await?;
let mut log = ChangeLogBatch::default();
let (calendar, team_ooo_changed) = upsert_calendar_tx(
&mut tx,
&mut log,
key.email_link_id,
account_id,
calendar,
Some(CalendarProvider::Google),
)
.await?;
log.commit(tx).await?;
stored_google_calendar(calendar, team_ooo_changed)
}
#[tracing::instrument(skip(self, sync), fields(job_id = %key.job_id), err)]
async fn commit_google_calendar_sync(
&self,
key: CalendarBackfillJobKey,
lease_token: Uuid,
account_id: Uuid,
sync: GoogleCalendarSyncSnapshot,
events_upserted: usize,
) -> Result<Vec<RetiredCalendarEvent>, Report> {
let mut retired = Vec::new();
let mut log = ChangeLogBatch::default();
let mut tx = self.pool.begin().await.map_err(report)?;
fence_google_mutation_tx(&mut tx, key, lease_token, Some(account_id)).await?;
let previously_verified =
source_access::snapshot_is_verified(&mut tx, account_id, sync.calendar_id).await?;
if events_upserted > 0 {
sqlx::query!(
r#"
UPDATE calendar_backfill_jobs
SET extracted_count = extracted_count + $3,
updated_at = now()
WHERE id = $1
AND email_link_id = $2
"#,
key.job_id,
key.email_link_id,
i64::try_from(events_upserted).map_err(|_| {
rootcause::report!(
"calendar backfill extracted count overflows the database representation"
)
})?,
)
.execute(&mut *tx)
.await
.map_err(report)?;
}
if !sync.cancelled_provider_event_ids.is_empty() {
// A cancelled recurring master retires its expanded instances via
// provider_recurring_event_id, matching Google's tombstone shape.
let removed = sqlx::query_as!(
RemovedSources,
r#"
WITH deleted_sources AS (
DELETE FROM calendar_event_sources source
WHERE source.source_kind = 'google'
AND source.account_id = $1
AND source.calendar_id = $2
AND (
source.provider_event_id = ANY($3::text[])
OR source.provider_recurring_event_id = ANY($3::text[])
)
RETURNING source.event_id, source.event_type
)
SELECT
event_id AS "event_id!",
bool_or(event_type = 'out_of_office') AS "out_of_office!"
FROM deleted_sources
GROUP BY event_id
"#,
account_id,
sync.calendar_id,
&sync.cancelled_provider_event_ids,
)
.fetch_all(&mut *tx)
.await
.map_err(report)?;
if !removed.is_empty() {
source_access::invalidate_account_freshness(&mut tx, account_id).await?;
}
retired.extend(retire_removed_sources(&mut tx, &mut log, removed).await?);
}
if let Some(observed_provider_event_ids) = &sync.observed_provider_event_ids {
let removed = sqlx::query_as!(
RemovedSources,
r#"
WITH deleted_sources AS (
DELETE FROM calendar_event_sources source
WHERE source.source_kind = 'google'
AND source.account_id = $1
AND source.calendar_id = $2
AND NOT (source.provider_event_id = ANY($3::text[]))
RETURNING source.event_id, source.event_type
)
SELECT
event_id AS "event_id!",
bool_or(event_type = 'out_of_office') AS "out_of_office!"
FROM deleted_sources
GROUP BY event_id
"#,
account_id,
sync.calendar_id,
observed_provider_event_ids,
)
.fetch_all(&mut *tx)
.await
.map_err(report)?;
if !removed.is_empty() {
source_access::invalidate_account_freshness(&mut tx, account_id).await?;
}
retired.extend(retire_removed_sources(&mut tx, &mut log, removed).await?);
}
let has_materialized_range = sync.materialized_range.is_some();
let materialized_starts_at = sync
.materialized_range
.as_ref()
.map(|range| range.starts_at);
let materialized_ends_at = sync.materialized_range.as_ref().map(|range| range.ends_at);
let materialized_start_date = sync
.materialized_range
.as_ref()
.map(|range| range.start_date);
let materialized_end_date = sync.materialized_range.as_ref().map(|range| range.end_date);
let badged = visible_calendar_sync_error_tx(&mut tx, sync.calendar_id).await?;
let updated = sqlx::query!(
r#"
UPDATE calendars
SET sync_token = $3,
synced_at = now(),
last_sync_error = NULL,
last_sync_error_at = NULL,
consecutive_sync_failures = 0,
materialized_starts_at = CASE
WHEN $4 THEN $5
ELSE materialized_starts_at
END,
materialized_ends_at = CASE
WHEN $4 THEN $6
ELSE materialized_ends_at
END,
materialized_start_date = CASE
WHEN $4 THEN $7
ELSE materialized_start_date
END,
materialized_end_date = CASE
WHEN $4 THEN $8
ELSE materialized_end_date
END,
updated_at = now()
WHERE id = $1
AND account_id = $2
AND NOT is_deleted
"#,
sync.calendar_id,
account_id,
sync.next_sync_token,
has_materialized_range,
materialized_starts_at,
materialized_ends_at,
materialized_start_date,
materialized_end_date,
)
.execute(&mut *tx)
.await
.map_err(report)?;
if updated.rows_affected() != 1 {
return Err(rootcause::report!(
"provider calendar disappeared before sync state was committed"
));
}
// The database trigger invalidates certification whenever snapshot
// state changes, including writes from a worker predating this code.
// Only a strict complete snapshot may upgrade an unverified calendar;
// ordinary strict incremental polls preserve an existing certificate.
if previously_verified
|| (has_materialized_range && sync.observed_provider_event_ids.is_some())
{
source_access::verify_calendar_snapshot(&mut tx, account_id, sync.calendar_id).await?;
}
if badged.is_some() {
log.record(
key.email_link_id,
CalendarChangeOp::UpsertCalendar(sync.calendar_id),
);
}
log.commit(tx).await?;
Ok(retired)
}
#[tracing::instrument(skip(self, message), fields(job_id = %key.job_id), err)]
async fn record_google_calendar_sync_error(
&self,
key: CalendarBackfillJobKey,
lease_token: Uuid,
account_id: Uuid,
calendar_id: Uuid,
message: &str,
) -> 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?;
let badged_before = visible_calendar_sync_error_tx(&mut tx, calendar_id).await?;
let failures = sqlx::query_scalar!(
r#"
UPDATE calendars
SET last_sync_error = $3,
last_sync_error_at = now(),
consecutive_sync_failures = consecutive_sync_failures + 1,
updated_at = now()
WHERE id = $1
AND account_id = $2
AND NOT is_deleted
RETURNING consecutive_sync_failures
"#,
calendar_id,
account_id,
message,
)
.fetch_optional(&mut *tx)
.await
.map_err(report)?;
// Clients see a calendar's error only once it crosses the badge
// threshold, so only a newly shown or reworded badge is a change.
let mut log = ChangeLogBatch::default();
if failures.is_some_and(|failures| {
failure_changes_sync_error_badge(badged_before.as_deref(), failures, message)
}) {
log.record(
key.email_link_id,
CalendarChangeOp::UpsertCalendar(calendar_id),
);
}
log.commit(tx).await
}
#[tracing::instrument(skip(self, channel), fields(job_id = %key.job_id), err)]
async fn record_watch_channel(
&self,
key: CalendarBackfillJobKey,
lease_token: Uuid,
account_id: Uuid,
calendar_id: Uuid,
channel: GoogleWatchChannel,
) -> 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_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
AND NOT is_deleted
"#,
calendar_id,
account_id,
channel.channel_id.to_string(),
channel.resource_id,
channel.expires_at,
)
.execute(&mut *tx)
.await
.map_err(report)?;
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,
channel_id: &str,
resource_id: &str,
) -> Result<Option<Uuid>, Report> {
sqlx::query_scalar!(
r#"
SELECT account.email_link_id
FROM calendars calendar
JOIN calendar_accounts account ON account.id = calendar.account_id
WHERE calendar.watch_channel_id = $1
AND calendar.watch_resource_id = $2
AND NOT calendar.is_deleted
AND account.sync_status <> 'disabled'
"#,
channel_id,
resource_id,
)
.fetch_optional(&self.pool)
.await
.map_err(report)
}
#[tracing::instrument(skip(self), err)]
async fn schedule_google_sync_for_link(&self, email_link_id: Uuid) -> Result<bool, Report> {
let required_scopes = GOOGLE_CALENDAR_SCOPES.map(str::to_owned);
let scheduled = sqlx::query_scalar!(
r#"
WITH due AS (
UPDATE calendar_backfill_jobs job
SET status = 'pending',
cursor = '{}',
last_error = NULL,
started_at = NULL,
completed_at = NULL,
lease_token = NULL,
lease_expires_at = NULL,
updated_at = now()
FROM calendar_accounts account, email_link_google_scopes scopes
WHERE job.email_link_id = $1
AND job.email_link_id = account.email_link_id
AND job.account_id = account.id
AND scopes.link_id = job.email_link_id
AND job.kind = 'google_calendar'
AND job.status = 'complete'
AND job.grant_version = scopes.grant_version
AND scopes.granted_scopes @> $2::text[]
AND account.sync_status = 'ready'
RETURNING job.id
),
republished AS (
UPDATE calendar_sync_outbox outbox
SET published_at = NULL
FROM due
WHERE outbox.backfill_job_id = due.id
)
SELECT count(*) > 0 AS "scheduled!" FROM due
"#,
email_link_id,
&required_scopes,
)
.fetch_one(&self.pool)
.await
.map_err(report)?;
Ok(scheduled)
}
#[tracing::instrument(skip(self, calendar_ids), fields(job_id = %key.job_id), err)]
async fn reconcile_google_calendar_list(
&self,
key: CalendarBackfillJobKey,
lease_token: Uuid,
account_id: Uuid,
calendar_ids: Vec<Uuid>,
) -> Result<Vec<RetiredCalendarEvent>, Report> {
let mut retired = Vec::new();
let mut log = ChangeLogBatch::default();
let mut tx = self.pool.begin().await.map_err(report)?;
fence_google_mutation_tx(&mut tx, key, lease_token, Some(account_id)).await?;
let removed = sqlx::query_as!(
RemovedSources,
r#"
WITH deleted_sources AS (
DELETE FROM calendar_event_sources source
WHERE source.source_kind = 'google'
AND source.account_id = $1
AND (
source.calendar_id IS NULL
OR NOT (source.calendar_id = ANY($2::uuid[]))
)
RETURNING source.event_id, source.event_type
)
SELECT
event_id AS "event_id!",
bool_or(event_type = 'out_of_office') AS "out_of_office!"
FROM deleted_sources
GROUP BY event_id
"#,
account_id,
&calendar_ids,
)
.fetch_all(&mut *tx)
.await
.map_err(report)?;
if !removed.is_empty() {
source_access::invalidate_account_freshness(&mut tx, account_id).await?;
}
retired.extend(retire_removed_sources(&mut tx, &mut log, removed).await?);
let flipped_calendars = sqlx::query!(
r#"
UPDATE calendars
SET is_deleted = NOT (id = ANY($2::uuid[])),
sync_token = CASE
WHEN id = ANY($2::uuid[]) THEN sync_token
ELSE NULL
END,
materialized_starts_at = CASE
WHEN id = ANY($2::uuid[]) THEN materialized_starts_at
ELSE NULL
END,
materialized_ends_at = CASE
WHEN id = ANY($2::uuid[]) THEN materialized_ends_at
ELSE NULL
END,
materialized_start_date = CASE
WHEN id = ANY($2::uuid[]) THEN materialized_start_date
ELSE NULL
END,
materialized_end_date = CASE
WHEN id = ANY($2::uuid[]) THEN materialized_end_date
ELSE NULL
END,
updated_at = now()
WHERE account_id = $1
AND is_deleted IS DISTINCT FROM NOT (id = ANY($2::uuid[]))
RETURNING id, is_deleted
"#,
account_id,
&calendar_ids,
)
.fetch_all(&mut *tx)
.await
.map_err(report)?;
if !flipped_calendars.is_empty() {
source_access::invalidate_account_freshness(&mut tx, account_id).await?;
}
for calendar in flipped_calendars {
log.record(
key.email_link_id,
if calendar.is_deleted {
CalendarChangeOp::DeleteCalendar(calendar.id)
} else {
CalendarChangeOp::UpsertCalendar(calendar.id)
},
);
}
// A copy's read-only flag mirrors its calendar's access role as of the
// event's last sync, and Google only resends events that changed, so a
// role change on the calendar list would otherwise leave every copy on
// that calendar stale. Refresh the copies from their calendars' live
// roles, including the stored projection a restore would replay, and
// the entities that mirror them.
let refreshed_copies = sqlx::query!(
r#"
UPDATE calendar_event_sources source
SET is_read_only = live.is_read_only,
normalized_payload = jsonb_set(
source.normalized_payload,
'{event,isReadOnly}',
to_jsonb(live.is_read_only)
)
FROM (
SELECT
calendar.id AS calendar_id,
NOT COALESCE(calendar.access_role IN ('owner', 'writer'), false)
AS is_read_only
FROM calendars calendar
WHERE calendar.account_id = $1
) live
WHERE source.calendar_id = live.calendar_id
AND source.is_read_only IS DISTINCT FROM live.is_read_only
RETURNING source.event_id, source.source_link_id
"#,
account_id,
)
.fetch_all(&mut *tx)
.await
.map_err(report)?;
if !refreshed_copies.is_empty() {
source_access::invalidate_account_freshness(&mut tx, account_id).await?;
}
for copy in refreshed_copies {
log.record(
copy.source_link_id,
CalendarChangeOp::UpsertEvent(copy.event_id),
);
}
let refreshed_events = sqlx::query!(
r#"
UPDATE calendar_events event
SET is_read_only = source.is_read_only
FROM calendar_event_sources source
WHERE source.id = event.content_source_id
AND source.account_id = $1
AND event.is_read_only IS DISTINCT FROM source.is_read_only
RETURNING event.id, event.owner_id, event.source_link_id
"#,
account_id,
)
.fetch_all(&mut *tx)
.await
.map_err(report)?;
// A calendar's access role or primary flag can change without any of
// its events changing, which moves the canonical copy without a source
// write. Re-project the entities whose content still mirrors another copy.
let reranked_event_ids = sqlx::query_scalar!(
r#"
SELECT event.id AS "id!"
FROM calendar_events event
WHERE event.id IN (
SELECT source.event_id
FROM calendar_event_sources source
WHERE source.account_id = $1
GROUP BY source.event_id
HAVING count(*) > 1
)
AND event.content_source_id
IS DISTINCT FROM calendar_event_canonical_source_id(event.id)
"#,
account_id,
)
.fetch_all(&mut *tx)
.await
.map_err(report)?;
for event_id in reranked_event_ids {
if let Some(outcome) =
restore_best_source_or_delete(&mut tx, &mut log, event_id).await?
{
retired.push(outcome);
}
}
retired.extend(refreshed_events.into_iter().map(|row| {
log.record(row.source_link_id, CalendarChangeOp::UpsertEvent(row.id));
RetiredCalendarEvent {
event_id: row.id,
owner_id: row.owner_id,
deleted: false,
team_ooo_changed: true,
}
}));
// One event can land here twice; either report can carry the hint.
let ooo_changed = retired
.iter()
.filter(|outcome| outcome.team_ooo_changed)
.map(|outcome| outcome.event_id)
.collect::<HashSet<_>>();
let mut announced = HashSet::new();
retired.retain_mut(|outcome| {
outcome.team_ooo_changed = ooo_changed.contains(&outcome.event_id);
announced.insert(outcome.event_id)
});
log.commit(tx).await?;
Ok(retired)
}
#[tracing::instrument(skip(self, requester_id), err)]
async fn get_event_mutation_target(
&self,
requester_id: &str,
event_id: Uuid,
calendar_id: Option<Uuid>,
) -> Result<Option<CalendarEventMutationTarget>, Report> {
// Without a calendar, address the canonical copy the entity is
// projected from. With one, address that calendar's copy, whose own
// access role decides whether it can be edited.
let row = sqlx::query!(
r#"
SELECT
event.id AS event_id,
event.owner_id,
event.organizer_email,
event.guests_can_modify,
event.guests_can_invite_others,
event.guests_can_see_other_guests,
-- A snapshot imported into one calendar can share its entity
-- with the real meeting on another, so the addressed copy's
-- own projection says whether it is a snapshot.
COALESCE(
source.normalized_payload->'event'->>'isSnapshot' = 'true',
false
) AS "is_snapshot!",
source.is_read_only,
source.provider_event_id AS "provider_event_id!",
source.provider_recurring_event_id,
source.account_id AS "account_id!",
source.calendar_id AS "calendar_id!",
calendar.provider_calendar_id,
calendar.access_role,
-- Google names the calendar an event was made on as its
-- organizer; the copy on it takes the organizer's changes.
(
SELECT organizer_source.calendar_id
FROM calendar_event_sources organizer_source
JOIN calendars organizer_calendar
ON organizer_calendar.id = organizer_source.calendar_id
AND organizer_calendar.account_id = organizer_source.account_id
WHERE organizer_source.event_id = event.id
AND organizer_source.source_kind IN ('google','outlook')
AND organizer_source.calendar_id <> source.calendar_id
AND NOT organizer_calendar.is_deleted
AND organizer_calendar.access_role IN ('owner', 'writer')
AND lower(organizer_calendar.provider_calendar_id)
= lower(event.organizer_email)
LIMIT 1
) AS organizer_copy_calendar_id,
account.email_link_id,
link.fusionauth_user_id,
link.email_address,
link.provider::text AS "provider!",link.sync_generation,link.grant_generation
FROM calendar_events event
JOIN calendar_event_sources source
ON source.event_id = event.id
AND source.source_kind IN ('google','outlook')
JOIN calendars calendar ON calendar.id = source.calendar_id
AND calendar.account_id = source.account_id
JOIN calendar_accounts account ON account.id = source.account_id
JOIN email_links link ON link.id = account.email_link_id
WHERE event.id = $1
AND NOT calendar.is_deleted
AND account.sync_status <> 'disabled'
AND CASE
WHEN $3::uuid IS NULL
THEN source.id = calendar_event_canonical_source_id(event.id)
ELSE source.calendar_id = $3
END
AND (
event.owner_id = $2
OR EXISTS (
SELECT 1
FROM macro_user_links delegation
WHERE delegation.link_id = event.source_link_id
AND delegation.primary_macro_id = $2
)
)
ORDER BY
source.source_sequence DESC,
source.source_updated_at DESC,
source.id DESC
LIMIT 1
"#,
event_id,
requester_id,
calendar_id,
)
.fetch_optional(&self.pool)
.await
.map_err(report)?;
let Some(row) = row else {
return Ok(None);
};
let actor = ActorInboxes::from_owned(self.owned_inboxes(requester_id).await?);
let token_identity = CalendarLinkTokenIdentity {
binding: Some(CalendarGrantBinding {
link_id: row.email_link_id,
sync_generation: row.sync_generation,
grant_generation: row.grant_generation,
}),
fusionauth_user_id: row.fusionauth_user_id,
email_address: row.email_address,
provider: CalendarProvider::from_link(&row.provider)
.ok_or_else(|| rootcause::report!("unsupported calendar provider"))?,
};
Ok(Some(CalendarEventMutationTarget {
event_id: row.event_id,
is_read_only: row.is_read_only,
provider_event_id: row.provider_event_id,
provider_recurring_event_id: row.provider_recurring_event_id,
owner_id: row.owner_id,
email_link_id: row.email_link_id,
account_id: row.account_id,
calendar_id: row.calendar_id,
provider_calendar_id: row.provider_calendar_id,
observed_access_role: row.access_role,
token_identity,
actor,
organizer_email: row.organizer_email,
guest_policy: 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,
},
is_snapshot: row.is_snapshot,
organizer_copy_calendar_id: row.organizer_copy_calendar_id,
}))
}
#[tracing::instrument(skip(self), err)]
async fn get_event_details(
&self,
event_id: Uuid,
occurrence_key: Option<&str>,
) -> Result<Option<EventDetails>, Report> {
details::event_details(&self.pool, event_id, occurrence_key).await
}
#[tracing::instrument(skip(self), err)]
async fn record_guest_policy(&self, event_id: Uuid, policy: GuestPolicy) -> Result<(), Report> {
let mut tx = self.pool.begin().await.map_err(report)?;
let source_link_id = sqlx::query_scalar!(
r#"
UPDATE calendar_events
SET guests_can_modify = $2,
guests_can_invite_others = $3,
guests_can_see_other_guests = $4
WHERE id = $1
RETURNING source_link_id
"#,
event_id,
policy.can_modify,
policy.can_invite_others,
policy.can_see_other_guests,
)
.fetch_optional(&mut *tx)
.await
.map_err(report)?;
let Some(source_link_id) = source_link_id else {
return Ok(());
};
// 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
SET normalized_payload = jsonb_set(normalized_payload, '{event,guestPolicy}', $2)
WHERE event_id = $1
AND normalized_payload ? 'event'
"#,
event_id,
serde_json::to_value(policy).map_err(report)?,
)
.execute(&mut *tx)
.await
.map_err(report)?;
let mut log = ChangeLogBatch::default();
log.record(source_link_id, CalendarChangeOp::UpsertEvent(event_id));
log.commit(tx).await
}
#[tracing::instrument(skip(self), err)]
async fn get_event_attendees(&self, event_id: Uuid) -> Result<Vec<CalendarAttendee>, Report> {
Ok(fetch_attendees(&self.pool, &[event_id])
.await?
.remove(&event_id)
.unwrap_or_default())
}
#[tracing::instrument(skip(self), err)]
async fn get_occurrence_override_attendees(
&self,
event_id: Uuid,
recurrence_id: &str,
) -> Result<Option<Vec<CalendarAttendee>>, Report> {
Ok(fetch_override_attendees(&self.pool, &[event_id])
.await?
.remove(&(event_id, recurrence_id.to_string())))
}
#[tracing::instrument(skip(self, requester_id), err)]
async fn get_creation_target(
&self,
requester_id: &str,
email_link_id: Option<Uuid>,
calendar_id: Option<Uuid>,
) -> Result<Option<CalendarCreationTarget>, Report> {
let row = sqlx::query!(
r#"
SELECT
link.macro_id AS owner_id,
link.id AS email_link_id,
account.id AS account_id,
calendar.id AS calendar_id,
calendar.provider_calendar_id,
calendar.access_role,
calendar.is_primary,
link.fusionauth_user_id,
link.email_address,
link.provider::text AS "provider!",link.sync_generation,link.grant_generation
FROM email_links link
JOIN calendar_accounts account ON account.email_link_id = link.id
JOIN calendars calendar ON calendar.account_id = account.id
WHERE NOT calendar.is_deleted
AND account.sync_status <> 'disabled'
AND (
($3::uuid IS NOT NULL AND calendar.id = $3)
OR ($3::uuid IS NULL AND calendar.is_primary)
)
AND ($2::uuid IS NULL OR link.id = $2)
AND (
link.macro_id = $1
OR EXISTS (
SELECT 1
FROM macro_user_links delegation
WHERE delegation.link_id = link.id
AND delegation.primary_macro_id = $1
)
)
ORDER BY
(link.macro_id = $1) DESC,
link.is_primary DESC,
link.created_at ASC
LIMIT 1
"#,
requester_id,
email_link_id,
calendar_id,
)
.fetch_optional(&self.pool)
.await
.map_err(report)?;
let Some(row) = row else {
return Ok(None);
};
let actor = ActorInboxes::from_owned(self.owned_inboxes(requester_id).await?);
let token_identity = CalendarLinkTokenIdentity {
binding: Some(CalendarGrantBinding {
link_id: row.email_link_id,
sync_generation: row.sync_generation,
grant_generation: row.grant_generation,
}),
fusionauth_user_id: row.fusionauth_user_id,
email_address: row.email_address,
provider: CalendarProvider::from_link(&row.provider)
.ok_or_else(|| rootcause::report!("unsupported calendar provider"))?,
};
Ok(Some(CalendarCreationTarget {
owner_id: row.owner_id,
email_link_id: row.email_link_id,
account_id: row.account_id,
calendar_id: row.calendar_id,
provider_calendar_id: row.provider_calendar_id,
is_read_only: !matches!(row.access_role.as_deref(), Some("owner" | "writer")),
observed_access_role: row.access_role,
is_primary: row.is_primary,
token_identity,
actor,
}))
}
#[tracing::instrument(skip(self, requester_id), err)]
async fn primary_time_zone(&self, requester_id: &str) -> Result<Option<String>, Report> {
let time_zone = sqlx::query_scalar!(
r#"
SELECT calendar.time_zone
FROM email_links link
JOIN calendar_accounts account ON account.email_link_id = link.id
JOIN calendars calendar ON calendar.account_id = account.id
WHERE NOT calendar.is_deleted
AND account.sync_status <> 'disabled'
AND calendar.is_primary
AND (
link.macro_id = $1
OR EXISTS (
SELECT 1
FROM macro_user_links delegation
WHERE delegation.link_id = link.id
AND delegation.primary_macro_id = $1
)
)
ORDER BY
(link.macro_id = $1) DESC,
link.is_primary DESC,
link.created_at ASC
LIMIT 1
"#,
requester_id,
)
.fetch_optional(&self.pool)
.await
.map_err(report)?;
Ok(time_zone.flatten())
}
#[tracing::instrument(skip(self, requester_id), err)]
async fn list_visible_calendars(
&self,
requester_id: &str,
) -> Result<Vec<VisibleCalendar>, Report> {
let rows = sqlx::query_as!(
VisibleCalendarRow,
r#"
SELECT
calendar.id,
link.id AS email_link_id,
link.email_address,
calendar.name,
calendar.color,
calendar.is_primary,
calendar.access_role,
calendar.provider_calendar_id,
calendar.default_reminders,
calendar.last_sync_error,
EXISTS(SELECT 1 FROM calendar_outlook_declines d
WHERE d.mailbox_key=calendar_outlook_mailbox_key(link.id) AND d.provider_calendar_id=calendar.provider_calendar_id AND d.confirmed_at IS NULL AND d.submitted_at<now()-interval '5 minutes') AS "unconfirmed_reply!",
calendar.consecutive_sync_failures,account.provider,calendar.online_meeting_providers,
COALESCE(preference.contributes_to_availability,
account.owner_id = $1 AND calendar.is_primary) AS "contributes_to_availability!"
FROM email_links link
JOIN calendar_accounts account ON account.email_link_id = link.id
JOIN calendars calendar ON calendar.account_id = account.id
LEFT JOIN calendar_availability_preferences preference
ON preference.calendar_id = calendar.id AND preference.user_id = $1
WHERE NOT calendar.is_deleted
AND account.sync_status <> 'disabled'
AND (
link.macro_id = $1
OR EXISTS (
SELECT 1
FROM macro_user_links delegation
WHERE delegation.link_id = link.id
AND delegation.primary_macro_id = $1
)
)
ORDER BY
(link.macro_id = $1) DESC,
link.is_primary DESC,
link.created_at ASC,
calendar.is_primary DESC,
(calendar.access_role IN ('owner', 'writer')) DESC,
calendar.name ASC
"#,
requester_id,
)
.fetch_all(&self.pool)
.await
.map_err(report)?;
Ok(rows.into_iter().map(visible_calendar).collect())
}
#[tracing::instrument(skip(self, event_ids), fields(event_count = event_ids.len()), err)]
async fn event_copies(&self, event_ids: &[Uuid]) -> Result<Vec<EventCopy>, Report> {
let rows = sqlx::query!(
r#"
SELECT
event.id,
event.source_link_id,
event.status,
event.organizer_email,
event.is_read_only,
event.is_snapshot,
event.guests_can_modify,
event.guests_can_invite_others,
event.guests_can_see_other_guests
FROM calendar_events event
WHERE event.id = ANY($1)
"#,
event_ids,
)
.fetch_all(&self.pool)
.await
.map_err(report)?;
let mut attendees = fetch_attendees(&self.pool, event_ids).await?;
let mut source_contents = fetch_source_contents(&self.pool, event_ids).await?;
Ok(rows
.into_iter()
.map(|row| EventCopy {
event_id: row.id,
link_id: row.source_link_id,
status: event_status(&row.status),
organizer_email: row.organizer_email,
is_read_only: row.is_read_only,
is_snapshot: row.is_snapshot,
guest_policy: 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,
},
attendees: attendees.remove(&row.id).unwrap_or_default(),
calendar_ids: source_contents
.remove(&row.id)
.unwrap_or_default()
.into_iter()
.map(|source| source.calendar_id)
.collect(),
})
.collect())
}
#[tracing::instrument(skip(self, requester_id), err)]
async fn owned_inboxes(&self, requester_id: &str) -> Result<Vec<OwnedInbox>, Report> {
sqlx::query!(
r#"
SELECT
link.id AS link_id,
link.email_address::text AS "email_address!",
link.provider::text AS "provider!",
ARRAY(
SELECT calendar.provider_calendar_id
FROM calendar_accounts account
JOIN calendars calendar ON calendar.account_id = account.id
WHERE account.email_link_id = link.id
AND account.sync_status <> 'disabled'
AND NOT calendar.is_deleted
AND calendar.access_role IN ('owner', 'writer')
) AS "writable_calendar_ids!"
FROM email_links link
WHERE link.macro_id = $1
"#,
requester_id,
)
.fetch_all(&self.pool)
.await
.map_err(report)?
.into_iter()
.map(|row| {
Ok(OwnedInbox {
link_id: row.link_id,
email: row.email_address,
provider: CalendarProvider::from_link(&row.provider)
.ok_or_else(|| rootcause::report!("unsupported calendar provider"))?,
writable_calendar_ids: row.writable_calendar_ids,
})
})
.collect()
}
#[tracing::instrument(skip(self), err)]
async fn remove_provider_source(
&self,
account_id: Uuid,
calendar_id: Uuid,
provider_event_id: &str,
) -> Result<Vec<RetiredCalendarEvent>, Report> {
let mut tx = self.pool.begin().await.map_err(report)?;
let mut log = ChangeLogBatch::default();
let cancelled = [provider_event_id.to_string()];
// A deleted recurring master retires its expanded instances via
// provider_recurring_event_id, matching Google's tombstone shape.
let removed = sqlx::query_as!(
RemovedSources,
r#"
WITH deleted_sources AS (
DELETE FROM calendar_event_sources source
WHERE source.source_kind IN ('google', 'outlook')
AND source.account_id = $1
AND source.calendar_id = $2
AND (
source.provider_event_id = ANY($3::text[])
OR source.provider_recurring_event_id = ANY($3::text[])
)
RETURNING source.event_id, source.event_type
)
SELECT
event_id AS "event_id!",
bool_or(event_type = 'out_of_office') AS "out_of_office!"
FROM deleted_sources
GROUP BY event_id
"#,
account_id,
calendar_id,
&cancelled,
)
.fetch_all(&mut *tx)
.await
.map_err(report)?;
let retired = retire_removed_sources(&mut tx, &mut log, removed).await?;
log.commit(tx).await?;
Ok(retired)
}
}
impl GoogleCalendarSyncRepository for PgCalendarRepository {
#[tracing::instrument(skip(self), err)]
async fn schedule_due_google_syncs(&self, due_before: DateTime<Utc>) -> Result<usize, Report> {
let required_scopes = GOOGLE_CALENDAR_SCOPES.map(str::to_owned);
let due_count = sqlx::query_scalar!(
r#"
WITH due AS (
UPDATE calendar_backfill_jobs job
SET status = 'pending',
cursor = '{}',
scanned_count = 0,
extracted_count = 0,
last_error = NULL,
started_at = NULL,
completed_at = NULL,
lease_token = NULL,
lease_expires_at = NULL,
updated_at = now()
FROM calendar_accounts account, email_link_google_scopes scopes
WHERE job.email_link_id = account.email_link_id
AND job.account_id = account.id
AND scopes.link_id = job.email_link_id
AND job.kind = 'google_calendar'
AND job.status = 'complete'
AND job.grant_version = scopes.grant_version
AND scopes.granted_scopes @> $2::text[]
AND account.sync_status = 'ready'
AND account.last_synced_at <= $1
RETURNING job.id
),
republished AS (
UPDATE calendar_sync_outbox outbox
SET published_at = NULL
FROM due
WHERE outbox.backfill_job_id = due.id
)
SELECT count(*) AS "due_count!" FROM due
"#,
due_before,
&required_scopes,
)
.fetch_one(&self.pool)
.await
.map_err(report)?;
Ok(due_count as usize)
}
#[tracing::instrument(skip(self), err)]
async fn reap_wedged_google_syncs(
&self,
stalled_before: DateTime<Utc>,
) -> Result<usize, Report> {
let required_scopes = GOOGLE_CALENDAR_SCOPES.map(str::to_owned);
let reaped = sqlx::query_scalar!(
r#"
WITH wedged AS (
UPDATE calendar_backfill_jobs job
SET status = 'pending',
last_error = NULL,
started_at = NULL,
completed_at = NULL,
lease_token = NULL,
lease_expires_at = NULL,
updated_at = now()
FROM calendar_sync_outbox outbox,
calendar_accounts account,
email_link_google_scopes scopes
WHERE outbox.backfill_job_id = job.id
AND account.id = job.account_id
AND account.email_link_id = job.email_link_id
AND scopes.link_id = job.email_link_id
AND job.kind = 'google_calendar'
AND job.grant_version = scopes.grant_version
AND scopes.granted_scopes @> $2::text[]
AND account.sync_status <> 'disabled'
AND (
-- Dead-lettered: a delivery reached a worker at least
-- once (started_at is set) and failed back to pending,
-- and nothing has touched the job since. started_at
-- separates this from a job merely waiting its turn in a
-- backed-up queue — the drain publishes that one without
-- ever claiming it, so republishing would only duplicate
-- the message still in flight.
(job.status = 'pending'
AND job.started_at IS NOT NULL
AND outbox.published_at IS NOT NULL
AND job.updated_at <= $1)
-- Abandoned: a worker claimed the job and died without
-- releasing or renewing the lease.
OR (job.status = 'running'
AND job.lease_expires_at IS NOT NULL
AND job.lease_expires_at <= $1)
)
RETURNING job.id
),
republished AS (
UPDATE calendar_sync_outbox outbox
SET published_at = NULL
FROM wedged
WHERE outbox.backfill_job_id = wedged.id
)
SELECT count(*) AS "reaped!" FROM wedged
"#,
stalled_before,
&required_scopes,
)
.fetch_one(&self.pool)
.await
.map_err(report)?;
Ok(reaped as usize)
}
}
async fn fence_google_mutation_tx(
tx: &mut Transaction<'_, Postgres>,
key: CalendarBackfillJobKey,
lease_token: Uuid,
account_id: Option<Uuid>,
) -> Result<(), Report> {
let required_scopes = GOOGLE_CALENDAR_SCOPES.map(str::to_owned);
let fenced_job = sqlx::query_scalar!(
r#"
SELECT job.id
FROM calendar_backfill_jobs job
WHERE job.id = $1
AND job.email_link_id = $2
AND job.kind = 'google_calendar'
AND job.status = 'running'
AND job.lease_token = $3
AND job.lease_expires_at > now()
AND EXISTS (
SELECT 1
FROM email_link_google_scopes scopes
WHERE scopes.link_id = job.email_link_id
AND scopes.grant_version = job.grant_version
AND scopes.granted_scopes @> $5::text[]
)
AND EXISTS (
SELECT 1
FROM calendar_accounts account
WHERE account.id = job.account_id
AND account.email_link_id = job.email_link_id
AND account.sync_status <> 'disabled'
AND ($4::uuid IS NULL OR account.id = $4)
)
FOR UPDATE OF job
"#,
key.job_id,
key.email_link_id,
lease_token,
account_id,
&required_scopes,
)
.fetch_optional(&mut **tx)
.await
.map_err(report)?;
if fenced_job.is_none() {
return Err(rootcause::report!(
"Google Calendar backfill lease was lost before provider mutation"
));
}
Ok(())
}
async fn upsert_calendar_tx(
tx: &mut Transaction<'_, Postgres>,
log: &mut ChangeLogBatch,
email_link_id: Uuid,
account_id: Uuid,
calendar: ProviderCalendar,
provider_sync: Option<CalendarProvider>,
) -> Result<(StoredCalendarRow, bool), Report> {
// Snapshot the reminder-relevant state before the upsert: a change to the
// default reminders or the zone that anchors all-day starts invalidates
// the firing schedule of every event that follows this calendar.
let previous = sqlx::query!(
r#"
SELECT
time_zone, default_reminders, name, color, access_role, is_primary, is_deleted,
(snapshot_normalization_version < 1 OR EXISTS (
SELECT 1 FROM calendar_event_sources source
WHERE source.calendar_id = calendars.id
AND source.provider_access_role IS DISTINCT FROM calendars.access_role
)) AS "needs_verification!"
FROM calendars
WHERE account_id = $1 AND provider_calendar_id = $2
"#,
account_id,
&calendar.provider_calendar_id,
)
.fetch_optional(&mut **tx)
.await
.map_err(report)?;
let default_reminders = serde_json::to_value(&calendar.default_reminders).map_err(report)?;
let reminders_invalidated = previous.as_ref().is_some_and(|previous| {
previous.default_reminders != default_reminders || previous.time_zone != calendar.time_zone
});
let visibly_changed = previous.as_ref().is_none_or(|previous| {
previous.is_deleted
|| previous.name != calendar.name
|| previous.color != calendar.color
|| previous.access_role != calendar.access_role
|| previous.is_primary != calendar.is_primary
|| previous.default_reminders != default_reminders
});
if provider_sync.is_some() && (visibly_changed || reminders_invalidated) {
source_access::invalidate_account_freshness(tx, account_id).await?;
}
let anchor_zone = calendar.time_zone.clone();
// Provider ACL changes and pre-migration snapshots need a full refresh
// even when no event's sequence changed or the calendar has no sources.
// The migration preserves old workers' incremental state; this strict
// worker invalidates it before requesting the verified snapshot.
// Old sources remain ineligible for team reads until verified.
// Outlook maintains its own cursor/coverage state and does not yet certify
// snapshots for team sharing. Do not erase its coverage on every discovery
// merely because its Google snapshot certificate remains unset.
let access_changed = previous.as_ref().is_some_and(|previous| {
previous.access_role != calendar.access_role
|| (provider_sync != Some(CalendarProvider::Outlook) && previous.needs_verification)
});
let row = sqlx::query_as!(
StoredCalendarRow,
r#"
INSERT INTO calendars (
id, account_id, provider_calendar_id, name, description,
time_zone, color, access_role, is_primary, is_selected,
default_reminders
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
ON CONFLICT (account_id, provider_calendar_id) DO UPDATE SET
name = EXCLUDED.name,
description = EXCLUDED.description,
time_zone = EXCLUDED.time_zone,
color = EXCLUDED.color,
access_role = EXCLUDED.access_role,
sync_token = CASE WHEN $12 THEN NULL ELSE calendars.sync_token END,
materialized_starts_at = CASE WHEN $12 THEN NULL ELSE calendars.materialized_starts_at END,
materialized_ends_at = CASE WHEN $12 THEN NULL ELSE calendars.materialized_ends_at END,
materialized_start_date = CASE WHEN $12 THEN NULL ELSE calendars.materialized_start_date END,
materialized_end_date = CASE WHEN $12 THEN NULL ELSE calendars.materialized_end_date END,
synced_at = CASE WHEN $12 THEN NULL ELSE calendars.synced_at END,
is_primary = EXCLUDED.is_primary,
is_selected = EXCLUDED.is_selected,
is_deleted = false,
default_reminders = EXCLUDED.default_reminders,
last_sync_error = CASE
WHEN calendars.is_deleted THEN NULL
ELSE calendars.last_sync_error
END,
last_sync_error_at = CASE
WHEN calendars.is_deleted THEN NULL
ELSE calendars.last_sync_error_at
END,
consecutive_sync_failures = CASE
WHEN calendars.is_deleted THEN 0
ELSE calendars.consecutive_sync_failures
END,
updated_at = now()
RETURNING
id,
sync_token,
materialized_starts_at,
materialized_ends_at,
materialized_start_date,
materialized_end_date,
synced_at,
watch_expires_at,
watch_unsupported_at
"#,
Uuid::now_v7(),
account_id,
calendar.provider_calendar_id,
calendar.name,
calendar.description,
calendar.time_zone,
calendar.color,
calendar.access_role,
calendar.is_primary,
calendar.is_selected,
&default_reminders,
access_changed,
)
.fetch_one(&mut **tx)
.await
.map_err(report)?;
if reminders_invalidated {
rebuild_calendar_reminder_firings(tx, row.id, anchor_zone.as_deref(), &default_reminders)
.await?;
}
if visibly_changed {
log.record(email_link_id, CalendarChangeOp::UpsertCalendar(row.id));
}
Ok((
row,
visibly_changed || reminders_invalidated || access_changed,
))
}
/// The sync error a calendar shows clients, if any, locking its row for the
/// rest of the transaction.
async fn visible_calendar_sync_error_tx(
tx: &mut Transaction<'_, Postgres>,
calendar_id: Uuid,
) -> Result<Option<String>, Report> {
let row = sqlx::query!(
r#"
SELECT last_sync_error, consecutive_sync_failures
FROM calendars
WHERE id = $1
FOR UPDATE
"#,
calendar_id,
)
.fetch_optional(&mut **tx)
.await
.map_err(report)?;
Ok(row.and_then(|row| {
row.last_sync_error
.filter(|_| row.consecutive_sync_failures >= CALENDAR_SYNC_FAILURE_BADGE_THRESHOLD)
}))
}
/// Whether a failure stored as `message`, leaving `failures` in a row, newly
/// shows or rewords the badge that `shown_before` held.
fn failure_changes_sync_error_badge(
shown_before: Option<&str>,
failures: i32,
message: &str,
) -> bool {
failures >= CALENDAR_SYNC_FAILURE_BADGE_THRESHOLD && shown_before != Some(message)
}
fn stored_google_calendar(
row: StoredCalendarRow,
team_ooo_changed: bool,
) -> Result<StoredGoogleCalendar, Report> {
let materialized_range = match (
row.materialized_starts_at,
row.materialized_ends_at,
row.materialized_start_date,
row.materialized_end_date,
) {
(Some(starts_at), Some(ends_at), Some(start_date), Some(end_date)) => {
Some(OccurrenceRange {
starts_at,
ends_at,
start_date,
end_date,
})
}
(None, None, None, None) => None,
_ => {
return Err(rootcause::report!(
"provider calendar has a partially persisted materialized range"
));
}
};
Ok(StoredGoogleCalendar {
id: row.id,
team_ooo_changed,
sync_token: row.sync_token,
materialized_range,
synced_at: row.synced_at,
watch_expires_at: row.watch_expires_at,
watch_unsupported_at: row.watch_unsupported_at,
})
}
impl CalendarBackfillRepository for PgCalendarRepository {
#[tracing::instrument(skip(self, message), err)]
async fn fail_unclaimed_google_backfill(
&self,
key: CalendarBackfillJobKey,
disposition: CalendarBackfillFailureDisposition,
message: &str,
) -> Result<CalendarBackfillFailureOutcome, Report> {
self.persist_google_backfill_failure(key, None, disposition, message)
.await
}
#[tracing::instrument(skip(self), err)]
async fn claim_google_backfill(
&self,
key: CalendarBackfillJobKey,
) -> Result<CalendarBackfillClaim, Report> {
let lease_token = Uuid::now_v7();
let required_scopes = GOOGLE_CALENDAR_SCOPES.map(str::to_owned);
let mut tx = self.pool.begin().await.map_err(report)?;
let claimed_account_id = sqlx::query_scalar!(
r#"
UPDATE calendar_backfill_jobs
SET status = 'running',
started_at = COALESCE(started_at, now()),
lease_token = $3,
lease_expires_at = now() + interval '2 minutes',
last_error = NULL,
updated_at = now()
WHERE id = $1
AND email_link_id = $2
AND kind = 'google_calendar'
AND EXISTS (
SELECT 1
FROM email_link_google_scopes scopes
WHERE scopes.link_id = calendar_backfill_jobs.email_link_id
AND scopes.grant_version = calendar_backfill_jobs.grant_version
AND scopes.granted_scopes @> $4::text[]
)
AND EXISTS (
SELECT 1
FROM calendar_accounts account
WHERE account.id = calendar_backfill_jobs.account_id
AND account.email_link_id = calendar_backfill_jobs.email_link_id
AND account.sync_status <> 'disabled'
)
AND (
status = 'pending'
OR (
status = 'running'
AND lease_expires_at < now()
)
)
RETURNING account_id
"#,
key.job_id,
key.email_link_id,
lease_token,
&required_scopes,
)
.fetch_optional(&mut *tx)
.await
.map_err(report)?;
if let Some(account_id) = claimed_account_id {
let Some(account_id) = account_id else {
tx.rollback().await.map_err(report)?;
return Err(rootcause::report!(
"Google Calendar backfill job has no calendar account"
));
};
tx.commit().await.map_err(report)?;
return Ok(CalendarBackfillClaim::Claimed {
lease_token,
account_id,
});
}
let state = sqlx::query!(
r#"
SELECT status, account_id
FROM calendar_backfill_jobs
WHERE id = $1
AND email_link_id = $2
AND kind = 'google_calendar'
"#,
key.job_id,
key.email_link_id,
)
.fetch_optional(&mut *tx)
.await
.map_err(report)?;
if state
.as_ref()
.is_some_and(|state| state.account_id.is_none())
{
tx.rollback().await.map_err(report)?;
return Err(rootcause::report!(
"Google Calendar backfill job has no calendar account"
));
}
let claim = match state.as_ref().map(|state| state.status.as_str()) {
Some("complete") => CalendarBackfillClaim::Complete,
Some("running" | "pending") => CalendarBackfillClaim::Busy,
Some("failed") => CalendarBackfillClaim::Failed,
_ => CalendarBackfillClaim::NotFound,
};
tx.commit().await.map_err(report)?;
Ok(claim)
}
#[tracing::instrument(skip(self), err)]
async fn mark_google_account_syncing(
&self,
key: CalendarBackfillJobKey,
lease_token: Uuid,
) -> Result<(), Report> {
let mut tx = self.pool.begin().await.map_err(report)?;
fence_google_mutation_tx(&mut tx, key, lease_token, None).await?;
// A ready, synced account has nothing a viewer should wait for, so the
// run leaves it ready, as on Outlook. That includes a re-grant that
// kept calendar access: its sync tokens survive. Every other state is
// still catching up: a first import, a retry, or a return from
// `disabled` or `reauth_required`.
sqlx::query!(
r#"
UPDATE calendar_accounts
SET sync_status = CASE
WHEN sync_status = 'ready' AND last_synced_at IS NOT NULL THEN 'ready'
ELSE 'syncing'
END,
updated_at = now()
WHERE email_link_id = $1
"#,
key.email_link_id,
)
.execute(&mut *tx)
.await
.map_err(report)?;
tx.commit().await.map_err(report)
}
#[tracing::instrument(skip(self), err)]
async fn maintain_google_backfill_lease(
&self,
key: CalendarBackfillJobKey,
lease_token: Uuid,
) -> Result<(), Report> {
let required_scopes = GOOGLE_CALENDAR_SCOPES.map(str::to_owned);
loop {
tokio::time::sleep(std::time::Duration::from_secs(30)).await;
let updated = sqlx::query!(
r#"
UPDATE calendar_backfill_jobs
SET lease_expires_at = now() + interval '2 minutes',
updated_at = now()
WHERE id = $1
AND email_link_id = $2
AND status = 'running'
AND lease_token = $3
AND lease_expires_at > now()
AND EXISTS (
SELECT 1
FROM email_link_google_scopes scopes
WHERE scopes.link_id = calendar_backfill_jobs.email_link_id
AND scopes.grant_version = calendar_backfill_jobs.grant_version
AND scopes.granted_scopes @> $4::text[]
)
"#,
key.job_id,
key.email_link_id,
lease_token,
&required_scopes,
)
.execute(&self.pool)
.await
.map_err(report)?;
if updated.rows_affected() != 1 {
return Err(rootcause::report!(
"Google Calendar backfill lease was lost"
));
}
}
}
#[tracing::instrument(skip(self), err)]
async fn complete_google_backfill(
&self,
key: CalendarBackfillJobKey,
lease_token: Uuid,
) -> Result<(), Report> {
let required_scopes = GOOGLE_CALENDAR_SCOPES.map(str::to_owned);
let mut tx = self.pool.begin().await.map_err(report)?;
let completed = sqlx::query!(
r#"
UPDATE calendar_backfill_jobs
SET status = 'complete',
completed_at = now(),
lease_token = NULL,
lease_expires_at = NULL,
updated_at = now()
WHERE id = $1
AND email_link_id = $2
AND kind = 'google_calendar'
AND status = 'running'
AND lease_token = $3
AND lease_expires_at > now()
AND EXISTS (
SELECT 1
FROM email_link_google_scopes scopes
WHERE scopes.link_id = calendar_backfill_jobs.email_link_id
AND scopes.grant_version = calendar_backfill_jobs.grant_version
AND scopes.granted_scopes @> $4::text[]
)
"#,
key.job_id,
key.email_link_id,
lease_token,
&required_scopes,
)
.execute(&mut *tx)
.await
.map_err(report)?;
if completed.rows_affected() != 1 {
return Err(rootcause::report!(
"Google Calendar backfill lease was lost"
));
}
sqlx::query!(
r#"
UPDATE calendar_accounts
SET sync_status = 'ready',
last_synced_at = now(),
last_sync_error = NULL,
updated_at = now()
WHERE email_link_id = $1
"#,
key.email_link_id,
)
.execute(&mut *tx)
.await
.map_err(report)?;
tx.commit().await.map_err(report)?;
Ok(())
}
#[tracing::instrument(skip(self, message), err)]
async fn fail_google_backfill(
&self,
key: CalendarBackfillJobKey,
lease_token: Uuid,
disposition: CalendarBackfillFailureDisposition,
message: &str,
) -> Result<CalendarBackfillFailureOutcome, Report> {
self.persist_google_backfill_failure(key, Some(lease_token), disposition, message)
.await
}
}
async fn invalidate_stale_google_jobs_tx(
tx: &mut Transaction<'_, Postgres>,
email_link_id: Uuid,
current_grant_version: i64,
) -> Result<(), Report> {
sqlx::query!(
r#"
WITH invalidated AS (
UPDATE calendar_backfill_jobs
SET status = 'failed',
completed_at = now(),
lease_token = NULL,
lease_expires_at = NULL,
last_error = 'superseded by a newer Google grant',
updated_at = now()
WHERE email_link_id = $1
AND kind = 'google_calendar'
AND grant_version <> $2
AND status IN ('pending', 'running')
RETURNING id
)
UPDATE calendar_sync_outbox outbox
SET published_at = COALESCE(outbox.published_at, now())
FROM invalidated
WHERE outbox.backfill_job_id = invalidated.id
"#,
email_link_id,
current_grant_version,
)
.execute(&mut **tx)
.await
.map_err(report)?;
Ok(())
}
async fn clear_calendar_opt_out_tx(
tx: &mut Transaction<'_, Postgres>,
email_link_id: Uuid,
) -> Result<(), Report> {
sqlx::query!(
r#"
UPDATE email_link_google_scopes
SET calendar_disabled_at = NULL,
updated_at = now()
WHERE link_id = $1 AND calendar_disabled_at IS NOT NULL
"#,
email_link_id,
)
.execute(&mut **tx)
.await
.map_err(report)?;
Ok(())
}
/// Retirements here are deliberately **not** returned for publication.
///
/// Both callers — a grant that lost its calendar scopes, and an explicit
/// disconnect — purge every event on the inbox at once, so per-event `Deleted`
/// topic messages would fan out to one message per event in the account.
/// Search documents for those events are consequently left stale; they are
/// invisible rather than leaked, because enrichment re-reads visibility from
/// Postgres and drops a hit whose row is gone. Removing them wants a
/// purge-by-owner operation, not this path.
async fn disable_calendar_capability_tx(
tx: &mut Transaction<'_, Postgres>,
log: &mut ChangeLogBatch,
email_link_id: Uuid,
) -> Result<(), Report> {
let account_id = sqlx::query_scalar!(
r#"
UPDATE calendar_accounts
SET sync_status = 'disabled',
last_sync_error = 'Calendar permission is no longer granted',
updated_at = now()
WHERE email_link_id = $1
RETURNING id
"#,
email_link_id,
)
.fetch_optional(&mut **tx)
.await
.map_err(report)?;
let Some(account_id) = account_id else {
return Ok(());
};
let removed_calendars = sqlx::query_scalar!(
r#"
UPDATE calendars
SET is_deleted = true,
sync_token = NULL,
materialized_starts_at = NULL,
materialized_ends_at = NULL,
materialized_start_date = NULL,
materialized_end_date = NULL,
updated_at = now()
WHERE account_id = $1
RETURNING id
"#,
account_id,
)
.fetch_all(&mut **tx)
.await
.map_err(report)?;
for calendar_id in removed_calendars {
log.record(email_link_id, CalendarChangeOp::DeleteCalendar(calendar_id));
}
let affected_event_ids = sqlx::query_scalar!(
r#"
WITH deleted_sources AS (
DELETE FROM calendar_event_sources
WHERE source_kind IN ('google','outlook')
AND account_id = $1
RETURNING event_id
)
SELECT DISTINCT event_id AS "event_id!"
FROM deleted_sources
"#,
account_id,
)
.fetch_all(&mut **tx)
.await
.map_err(report)?;
for event_id in &affected_event_ids {
restore_best_source_or_delete(tx, log, *event_id).await?;
}
// Reminder delivery claims are deliberately not foreign-keyed to
// occurrences, so an event that lost its last source takes its claims with
// it here rather than leaving them behind forever.
sqlx::query!(
r#"
DELETE FROM calendar_event_reminder_deliveries d
WHERE d.event_id = ANY($1)
AND NOT EXISTS (
SELECT 1 FROM calendar_events e WHERE e.id = d.event_id
)
"#,
&affected_event_ids,
)
.execute(&mut **tx)
.await
.map_err(report)?;
Ok(())
}
async fn upsert_google_account_tx(
tx: &mut Transaction<'_, Postgres>,
email_link_id: Uuid,
owner_id: &str,
email_address: &str,
) -> Result<Uuid, Report> {
sqlx::query_scalar!(
r#"
INSERT INTO calendar_accounts (
id, owner_id, email_link_id, provider, provider_account_id
)
VALUES ($1, $2, $3, 'google', $4)
ON CONFLICT (email_link_id) DO UPDATE SET
owner_id = EXCLUDED.owner_id,
provider_account_id = EXCLUDED.provider_account_id,
sync_status = CASE
WHEN calendar_accounts.sync_status = 'disabled' THEN 'pending'
ELSE calendar_accounts.sync_status
END,
last_sync_error = CASE
WHEN calendar_accounts.sync_status = 'disabled' THEN NULL
ELSE calendar_accounts.last_sync_error
END,
updated_at = now()
RETURNING id
"#,
Uuid::now_v7(),
owner_id,
email_link_id,
email_address,
)
.fetch_one(&mut **tx)
.await
.map_err(report)
}
async fn retry_failed_backfills_tx(
tx: &mut Transaction<'_, Postgres>,
email_link_id: Uuid,
grant_version: i64,
) -> Result<Vec<CalendarBackfillJob>, Report> {
struct FailedJobRow {
id: Uuid,
account_id: Option<Uuid>,
kind: String,
}
let failed = sqlx::query_as!(
FailedJobRow,
r#"
UPDATE calendar_backfill_jobs
SET status = 'pending',
cursor = '{}',
scanned_count = 0,
extracted_count = 0,
last_error = NULL,
started_at = NULL,
completed_at = NULL,
lease_expires_at = NULL,
updated_at = now()
WHERE email_link_id = $1
AND grant_version = $2
AND status = 'failed'
AND kind = 'google_calendar'
RETURNING id, account_id, kind
"#,
email_link_id,
grant_version,
)
.fetch_all(&mut **tx)
.await
.map_err(report)?;
let mut jobs = Vec::with_capacity(failed.len());
for row in failed {
sqlx::query!(
r#"
UPDATE calendar_sync_outbox
SET published_at = NULL
WHERE backfill_job_id = $1
"#,
row.id,
)
.execute(&mut **tx)
.await
.map_err(report)?;
let kind = match row.kind.as_str() {
"google_calendar" => CalendarBackfillKind::GoogleCalendar,
_ => return Err(rootcause::report!("invalid calendar backfill kind")),
};
jobs.push(CalendarBackfillJob {
id: row.id,
email_link_id,
account_id: row.account_id,
kind,
grant_version,
});
}
Ok(jobs)
}
/// Record one provider copy with its own content. Returns the source row's
/// id when the write landed, or `None` when the per-source freshness guard
/// rejected it as stale.
async fn persist_source(
tx: &mut Transaction<'_, Postgres>,
event_id: Uuid,
upsert: &CalendarEventUpsert,
) -> Result<Option<Uuid>, Report> {
let normalized_payload =
serde_json::to_value(StoredSourceProjection::from(upsert)).map_err(report)?;
let source = upsert.source.details();
let event = &upsert.event;
sqlx::query_scalar!(
r#"
INSERT INTO calendar_event_sources (
id, event_id, source_link_id, source_kind, account_id, calendar_id,
provider_event_id, provider_recurring_event_id,
provider_etag, raw_payload, source_sequence,
source_updated_at, normalized_payload, provider_access_role,
title, description, location, event_type, visibility, transparency,
is_read_only, reminders_use_default, reminder_overrides,
creator_email, creator_name, automatic_decline
)
VALUES (
$1, $2, $3, $24, $4, $5, $6, $7, $8, $9,
$10, $11, $12,
$26,
$13, $14, $15, $16, $17, $18,
$19, $20, $21,
$22, $23, $25
)
ON CONFLICT (account_id, calendar_id, provider_event_id)
DO UPDATE SET
event_id = EXCLUDED.event_id,
provider_recurring_event_id = EXCLUDED.provider_recurring_event_id,
provider_etag = EXCLUDED.provider_etag,
raw_payload = EXCLUDED.raw_payload,
automatic_decline = EXCLUDED.automatic_decline,
source_sequence = EXCLUDED.source_sequence,
source_updated_at = EXCLUDED.source_updated_at,
normalized_payload = EXCLUDED.normalized_payload,
provider_access_role = EXCLUDED.provider_access_role,
title = EXCLUDED.title,
description = EXCLUDED.description,
location = EXCLUDED.location,
event_type = EXCLUDED.event_type,
visibility = EXCLUDED.visibility,
transparency = EXCLUDED.transparency,
is_read_only = EXCLUDED.is_read_only,
reminders_use_default = EXCLUDED.reminders_use_default,
reminder_overrides = EXCLUDED.reminder_overrides,
creator_email = EXCLUDED.creator_email,
creator_name = EXCLUDED.creator_name,
last_seen_at = now()
WHERE
EXCLUDED.source_sequence > calendar_event_sources.source_sequence
OR (
EXCLUDED.source_sequence = calendar_event_sources.source_sequence
AND EXCLUDED.source_updated_at >= calendar_event_sources.source_updated_at
)
RETURNING id
"#,
Uuid::now_v7(),
event_id,
source.email_link_id,
source.account_id,
source.calendar_id,
&source.provider_event_id,
source.provider_recurring_event_id.as_deref(),
source.provider_etag.as_deref(),
&source.raw_payload,
db_sequence(event.sequence)?,
event.updated_at,
&normalized_payload,
&event.title,
event.description.as_deref(),
event.location.as_deref(),
event.event_type.as_str(),
event.visibility.as_str(),
event.transparency.as_str(),
event.is_read_only,
event.reminders.use_default,
serde_json::to_value(&event.reminders.overrides).map_err(report)?,
event.creator_email.as_deref(),
event.creator_name.as_deref(),
upsert.source.kind(),
source
.automatic_decline
.as_ref()
.map(serde_json::to_value)
.transpose()
.map_err(report)?,
source.observed_access_role.as_deref(),
)
.fetch_optional(&mut **tx)
.await
.map_err(report)
}
/// The copy whose content the entity carries, and its provider stamp.
struct CanonicalSource {
source_id: Uuid,
calendar_id: Uuid,
updated_at: DateTime<Utc>,
}
/// The source whose content the entity carries, ranked by
/// `calendar_event_canonical_source_id`: the primary calendar's copy, else a
/// copy the grant can write, else the freshest, on a live calendar of an
/// enabled account. Every ranking site goes through that function so the
/// entity, the mutation target, the reminder schedule, and the listing agree.
async fn canonical_source(
tx: &mut Transaction<'_, Postgres>,
event_id: Uuid,
) -> Result<Option<CanonicalSource>, Report> {
let row = sqlx::query!(
r#"
SELECT source.id, source.calendar_id AS "calendar_id!", source.source_updated_at
FROM calendar_event_sources source
WHERE source.id = calendar_event_canonical_source_id($1)
"#,
event_id,
)
.fetch_optional(&mut **tx)
.await
.map_err(report)?;
Ok(row.map(|row| CanonicalSource {
source_id: row.id,
calendar_id: row.calendar_id,
updated_at: row.source_updated_at,
}))
}
/// Whether a copy is the organizer's: the Google source on the calendar
/// Google names as the meeting's organizer (the address for a primary
/// calendar, the calendar id for a secondary one) that its inbox can write,
/// as `guest_policy::align_with_organizer` and the mutation target's
/// `organizer_copy_calendar_id` find it.
async fn organizes_meeting(
tx: &mut Transaction<'_, Postgres>,
source_id: Uuid,
organizer_email: Option<&str>,
) -> Result<bool, Report> {
let Some(organizer_email) = organizer_email else {
return Ok(false);
};
sqlx::query_scalar!(
r#"
SELECT EXISTS (
SELECT 1
FROM calendar_event_sources source
JOIN calendars calendar
ON calendar.id = source.calendar_id AND calendar.account_id = source.account_id
WHERE source.id = $1
AND source.source_kind = 'google'
AND NOT calendar.is_deleted
AND calendar.access_role IN ('owner', 'writer')
AND lower(calendar.provider_calendar_id) = lower($2)
) AS "organizes!"
"#,
source_id,
organizer_email,
)
.fetch_one(&mut **tx)
.await
.map_err(report)
}
/// The provider stamp of the user edit through the organizer's copy whose
/// content the entity carries ahead of its canonical copy, if any.
async fn content_ahead(
tx: &mut Transaction<'_, Postgres>,
event_id: Uuid,
) -> Result<Option<DateTime<Utc>>, Report> {
sqlx::query_scalar!(
r#"SELECT content_updated_at FROM calendar_events WHERE id = $1"#,
event_id,
)
.fetch_one(&mut **tx)
.await
.map_err(report)
}
/// The copy that last wrote the entity's schedule and that write's provider
/// stamp. The copy is absent when it has since been retired.
struct ScheduleOwner {
source_id: Option<Uuid>,
updated_at: DateTime<Utc>,
}
async fn schedule_owner(
tx: &mut Transaction<'_, Postgres>,
event_id: Uuid,
) -> Result<ScheduleOwner, Report> {
let row = sqlx::query!(
r#"SELECT schedule_source_id, schedule_updated_at FROM calendar_events WHERE id = $1"#,
event_id,
)
.fetch_one(&mut **tx)
.await
.map_err(report)?;
Ok(ScheduleOwner {
source_id: row.schedule_source_id,
updated_at: row.schedule_updated_at,
})
}
/// Rewrite the entity's copy-specific content from its canonical copy and
/// record which copy it now mirrors. The meeting's content (title,
/// description, location, visibility) comes along only when `meeting` is
/// set, which hands it back from a fresher edit through the organizer's copy.
async fn apply_content_projection(
tx: &mut Transaction<'_, Postgres>,
event_id: Uuid,
source_id: Uuid,
projection: &StoredSourceProjection,
source_kind: &str,
meeting: bool,
) -> Result<(), Report> {
sqlx::query!(
r#"
UPDATE calendar_events
SET content_source_id = $17,
title = CASE WHEN $22 THEN $2 ELSE title END,
description = CASE WHEN $22 THEN $3 ELSE description END,
location = CASE WHEN $22 THEN $4 ELSE location END,
visibility = CASE WHEN $22 THEN $5 ELSE visibility END,
content_updated_at = CASE WHEN $22 THEN NULL ELSE content_updated_at END,
transparency = $6,
event_type = $7,
creator_email = $8,
creator_name = $9,
sequence = $10,
is_read_only = $11,
canonical_source_kind = $12,
reminders_use_default = $13,
reminder_overrides = $14,
guests_can_modify = $18,
guests_can_invite_others = $19,
guests_can_see_other_guests = $20,
is_snapshot = $21,
created_at = $15,
updated_at = GREATEST(calendar_events.updated_at, $16)
WHERE id = $1
"#,
event_id,
&projection.event.title,
projection.event.description.as_deref(),
projection.event.location.as_deref(),
projection.event.visibility.as_str(),
projection.event.transparency.as_str(),
projection.event.event_type.as_str(),
projection.event.creator_email.as_deref(),
projection.event.creator_name.as_deref(),
db_sequence(projection.event.sequence)?,
projection.event.is_read_only,
source_kind,
projection.event.reminders.use_default,
serde_json::to_value(&projection.event.reminders.overrides).map_err(report)?,
projection.event.created_at,
projection.event.updated_at,
source_id,
projection.event.guest_policy.can_modify,
projection.event.guest_policy.can_invite_others,
projection.event.guest_policy.can_see_other_guests,
projection.event.is_snapshot,
meeting,
)
.execute(&mut **tx)
.await
.map_err(report)?;
Ok(())
}
/// Write the meeting's content (title, description, location, visibility)
/// from a user edit through the organizer's copy, ahead of the canonical copy
/// Google updates later, and record the edit's provider stamp so only a copy
/// at least that fresh replaces it.
async fn apply_meeting_content(
tx: &mut Transaction<'_, Postgres>,
event_id: Uuid,
projection: &StoredSourceProjection,
) -> Result<(), Report> {
sqlx::query!(
r#"
UPDATE calendar_events
SET title = $2,
description = $3,
location = $4,
visibility = $5,
content_updated_at = $6,
updated_at = GREATEST(calendar_events.updated_at, $6)
WHERE id = $1
"#,
event_id,
&projection.event.title,
projection.event.description.as_deref(),
projection.event.location.as_deref(),
projection.event.visibility.as_str(),
projection.event.updated_at,
)
.execute(&mut **tx)
.await
.map_err(report)?;
Ok(())
}
/// Rewrite the whole schedule the canonical copy, or the organizer's copy
/// after a user edit through it, owns: status, time, recurrence, organizer,
/// conference, attendees, overrides, and occurrences.
/// Records the copy as the schedule's writer with its provider stamp.
async fn apply_schedule_projection(
tx: &mut Transaction<'_, Postgres>,
event_id: Uuid,
source_id: Uuid,
projection: &StoredSourceProjection,
) -> Result<(), Report> {
let (starts_at, ends_at, start_date, end_date, time_zone) = split_time(&projection.event.time);
sqlx::query!(
r#"
UPDATE calendar_events
SET status = $2,
starts_at = $3,
ends_at = $4,
start_date = $5,
end_date = $6,
time_zone = $7,
recurrence_lines = $8,
organizer_email = $9,
organizer_name = $10,
conference_url = $11,
conference_provider = $12,
schedule_source_id = $13,
schedule_updated_at = $14,
updated_at = GREATEST(calendar_events.updated_at, $14)
WHERE id = $1
"#,
event_id,
projection.event.status.as_str(),
starts_at,
ends_at,
start_date,
end_date,
time_zone,
&projection.event.recurrence_lines,
projection.event.organizer_email.as_deref(),
projection.event.organizer_name.as_deref(),
projection.event.conference_url.as_deref(),
projection
.event
.conference_provider
.map(ConferenceProvider::as_str),
source_id,
projection.event.updated_at,
)
.execute(&mut **tx)
.await
.map_err(report)?;
replace_attendees(tx, event_id, &projection.event.attendees).await?;
replace_overrides(tx, event_id, &projection.overrides).await?;
replace_occurrences(
tx,
event_id,
&projection.event.owner_id,
&projection.occurrences,
)
.await
}
/// Rewrite the time shape a non-canonical copy carries for the meeting:
/// status, time, recurrence, overrides, and occurrences. Attendees,
/// organizer, and conference stay the canonical copy's. Records the copy as
/// the schedule's writer with its provider stamp.
async fn apply_time_projection(
tx: &mut Transaction<'_, Postgres>,
event_id: Uuid,
source_id: Uuid,
projection: &StoredSourceProjection,
) -> Result<(), Report> {
let (starts_at, ends_at, start_date, end_date, time_zone) = split_time(&projection.event.time);
sqlx::query!(
r#"
UPDATE calendar_events
SET status = $2,
starts_at = $3,
ends_at = $4,
start_date = $5,
end_date = $6,
time_zone = $7,
recurrence_lines = $8,
schedule_source_id = $9,
schedule_updated_at = $10,
updated_at = GREATEST(calendar_events.updated_at, $10)
WHERE id = $1
"#,
event_id,
projection.event.status.as_str(),
starts_at,
ends_at,
start_date,
end_date,
time_zone,
&projection.event.recurrence_lines,
source_id,
projection.event.updated_at,
)
.execute(&mut **tx)
.await
.map_err(report)?;
replace_overrides(tx, event_id, &projection.overrides).await?;
replace_occurrences(
tx,
event_id,
&projection.event.owner_id,
&projection.occurrences,
)
.await
}
/// Rebuild the entity's reminder firings from the content and occurrences it
/// now carries, resolving calendar defaults against the canonical copy's
/// calendar, so alerts follow the canonical copy's settings whichever copy
/// last moved the schedule.
async fn rebuild_entity_reminder_firings(
tx: &mut Transaction<'_, Postgres>,
event_id: Uuid,
canonical_calendar_id: Option<Uuid>,
) -> Result<(), Report> {
let entity = sqlx::query!(
r#"
SELECT status, event_type, reminders_use_default, reminder_overrides
FROM calendar_events
WHERE id = $1
"#,
event_id,
)
.fetch_one(&mut **tx)
.await
.map_err(report)?;
let reminders = EventReminders {
use_default: entity.reminders_use_default,
overrides: serde_json::from_value(entity.reminder_overrides)
.inspect_err(|e| {
tracing::error!(error = ?e, %event_id, "malformed event reminder_overrides json");
})
.unwrap_or_default(),
};
let calendar = fetch_calendar_reminder_context(tx, canonical_calendar_id).await?;
rebuild_event_reminder_firings(
tx,
event_id,
event_status(&entity.status),
event_type(&entity.event_type),
&reminders,
calendar.as_ref(),
)
.await
}
/// Rewrite the entity from the copy that inherits it after a retirement.
/// Content follows it, except the meeting's content from a fresher edit
/// through the organizer's copy. The schedule follows it unless another
/// surviving copy wrote a fresher one, which is how a user's edit made
/// through a copy outlives the retirement of an unrelated third copy.
async fn apply_canonical_projection(
tx: &mut Transaction<'_, Postgres>,
event_id: Uuid,
source_id: Uuid,
projection: &StoredSourceProjection,
source_kind: &str,
calendar_id: Option<Uuid>,
) -> Result<(), Report> {
let meeting = content_ahead(tx, event_id)
.await?
.is_none_or(|ahead| projection.event.updated_at >= ahead);
apply_content_projection(tx, event_id, source_id, projection, source_kind, meeting).await?;
let schedule = schedule_owner(tx, event_id).await?;
if schedule.source_id.is_none_or(|owner| owner == source_id)
|| projection.event.updated_at >= schedule.updated_at
{
apply_schedule_projection(tx, event_id, source_id, projection).await?;
}
rebuild_entity_reminder_firings(tx, event_id, calendar_id).await
}
/// Rewrite an event from its next-best remaining source, or delete it when no
/// source on a live calendar is left, reporting which happened.
///
/// `None` means the row was already gone before this call. The report cannot
/// tell what was removed, so it leaves the team hint uncertain.
async fn restore_best_source_or_delete(
tx: &mut Transaction<'_, Postgres>,
log: &mut ChangeLogBatch,
event_id: Uuid,
) -> Result<Option<RetiredCalendarEvent>, Report> {
let identity = sqlx::query!(
r#"
SELECT source_link_id, ical_uid, owner_id
FROM calendar_events
WHERE id = $1
"#,
event_id,
)
.fetch_optional(&mut **tx)
.await
.map_err(report)?;
let Some(identity) = identity else {
return Ok(None);
};
let reconciliation_lock =
event_reconciliation_lock(identity.source_link_id, &identity.ical_uid);
sqlx::query_scalar!(
r#"SELECT 1 AS "locked!" FROM pg_advisory_xact_lock($1)"#,
reconciliation_lock,
)
.fetch_one(&mut **tx)
.await
.map_err(report)?;
let source = sqlx::query!(
r#"
SELECT
source.id,
source.source_kind,
source.normalized_payload,
source.calendar_id
FROM calendar_event_sources source
WHERE source.id = calendar_event_canonical_source_id($1)
"#,
event_id,
)
.fetch_optional(&mut **tx)
.await
.map_err(report)?;
let Some(source) = source else {
sqlx::query!("DELETE FROM calendar_events WHERE id = $1", event_id)
.execute(&mut **tx)
.await
.map_err(report)?;
log.record(
identity.source_link_id,
CalendarChangeOp::DeleteEvent(event_id),
);
return Ok(Some(RetiredCalendarEvent {
event_id,
owner_id: identity.owner_id,
deleted: true,
team_ooo_changed: true,
}));
};
let projection: StoredSourceProjection =
serde_json::from_value(source.normalized_payload).map_err(report)?;
apply_canonical_projection(
tx,
event_id,
source.id,
&projection,
&source.source_kind,
source.calendar_id,
)
.await?;
log.record(
identity.source_link_id,
CalendarChangeOp::UpsertEvent(event_id),
);
Ok(Some(RetiredCalendarEvent {
event_id,
owner_id: identity.owner_id,
deleted: false,
team_ooo_changed: true,
}))
}
/// One event that lost sources, and whether any of them was out of office.
struct RemovedSources {
event_id: Uuid,
out_of_office: bool,
}
/// Settles the fate of each event that lost sources. The team overlay reads
/// sources by this same typed `event_type`, so only removing an out-of-office
/// source can withdraw a row teammates hold.
async fn retire_removed_sources(
tx: &mut Transaction<'_, Postgres>,
log: &mut ChangeLogBatch,
removed: Vec<RemovedSources>,
) -> Result<Vec<RetiredCalendarEvent>, Report> {
let mut retired = Vec::new();
for source in removed {
if let Some(outcome) = restore_best_source_or_delete(tx, log, source.event_id).await? {
retired.push(RetiredCalendarEvent {
team_ooo_changed: source.out_of_office,
..outcome
});
}
}
Ok(retired)
}
async fn replace_attendees(
tx: &mut Transaction<'_, Postgres>,
event_id: Uuid,
attendees: &[CalendarAttendee],
) -> Result<(), Report> {
sqlx::query!(
"DELETE FROM calendar_event_attendees WHERE event_id = $1",
event_id
)
.execute(&mut **tx)
.await
.map_err(report)?;
for attendee in attendees {
sqlx::query!(
r#"
INSERT INTO calendar_event_attendees (
event_id, email, display_name, response_status,
is_organizer, is_optional, is_self, comment
)
VALUES ($1, lower($2), $3, $4, $5, $6, $7, $8)
ON CONFLICT (event_id, email) DO UPDATE SET
display_name = EXCLUDED.display_name,
response_status = EXCLUDED.response_status,
is_organizer = EXCLUDED.is_organizer,
is_optional = EXCLUDED.is_optional,
is_self = EXCLUDED.is_self,
comment = EXCLUDED.comment
"#,
event_id,
&attendee.email,
attendee.display_name.as_deref(),
attendee.response_status.as_str(),
attendee.is_organizer,
attendee.is_optional,
attendee.is_self,
attendee.comment.as_deref(),
)
.execute(&mut **tx)
.await
.map_err(report)?;
}
Ok(())
}
async fn replace_overrides(
tx: &mut Transaction<'_, Postgres>,
event_id: Uuid,
overrides: &[CalendarEventOverride],
) -> Result<(), Report> {
sqlx::query!(
"DELETE FROM calendar_event_overrides WHERE event_id = $1",
event_id
)
.execute(&mut **tx)
.await
.map_err(report)?;
for event_override in overrides {
let (starts_at, ends_at, start_date, end_date, _time_zone) =
split_time(&event_override.time);
let (original_starts_at, original_start_date) = match event_override.original_time {
EventStart::Timed(value) => (Some(value), None),
EventStart::AllDay(value) => (None, Some(value)),
};
sqlx::query!(
r#"
INSERT INTO calendar_event_overrides (
event_id, recurrence_id, original_starts_at, original_start_date,
starts_at, ends_at, start_date, end_date,
title, description, location, status, attendees_overridden, sequence, source_updated_at, reminders, automatic_decline
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)
"#,
event_id,
&event_override.recurrence_id,
original_starts_at,
original_start_date,
starts_at,
ends_at,
start_date,
end_date,
event_override.title.as_deref(),
event_override.description.as_deref(),
event_override.location.as_deref(),
event_override.status.map(EventStatus::as_str),
event_override.attendees.is_some(),
event_override.sequence.map(db_sequence).transpose()?,
event_override.source_updated_at,
event_override.reminders.as_ref().map(serde_json::to_value).transpose().map_err(report)?,
event_override.automatic_decline.as_ref().map(serde_json::to_value).transpose().map_err(report)?,
)
.execute(&mut **tx)
.await
.map_err(report)?;
for attendee in event_override.attendees.iter().flatten() {
sqlx::query!(
r#"
INSERT INTO calendar_event_override_attendees (
event_id, recurrence_id, email, display_name, response_status,
is_organizer, is_optional, is_self, comment
)
VALUES ($1, $2, lower($3), $4, $5, $6, $7, $8, $9)
ON CONFLICT (event_id, recurrence_id, email) DO UPDATE SET
display_name = EXCLUDED.display_name,
response_status = EXCLUDED.response_status,
is_organizer = EXCLUDED.is_organizer,
is_optional = EXCLUDED.is_optional,
is_self = EXCLUDED.is_self,
comment = EXCLUDED.comment
"#,
event_id,
&event_override.recurrence_id,
&attendee.email,
attendee.display_name.as_deref(),
attendee.response_status.as_str(),
attendee.is_organizer,
attendee.is_optional,
attendee.is_self,
attendee.comment.as_deref(),
)
.execute(&mut **tx)
.await
.map_err(report)?;
}
}
Ok(())
}
async fn replace_occurrences(
tx: &mut Transaction<'_, Postgres>,
event_id: Uuid,
owner_id: &str,
occurrences: &[CalendarOccurrence],
) -> Result<(), Report> {
sqlx::query!(
"DELETE FROM calendar_event_occurrences WHERE event_id = $1",
event_id
)
.execute(&mut **tx)
.await
.map_err(report)?;
for occurrence in occurrences {
let (starts_at, ends_at, start_date, end_date, _time_zone) = split_time(&occurrence.time);
sqlx::query!(
r#"
INSERT INTO calendar_event_occurrences (
event_id, owner_id, occurrence_key, recurrence_id,
starts_at, ends_at, start_date, end_date, is_cancelled
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
ON CONFLICT (event_id, occurrence_key) DO UPDATE SET
owner_id = EXCLUDED.owner_id,
recurrence_id = EXCLUDED.recurrence_id,
starts_at = EXCLUDED.starts_at,
ends_at = EXCLUDED.ends_at,
start_date = EXCLUDED.start_date,
end_date = EXCLUDED.end_date,
is_cancelled = EXCLUDED.is_cancelled
"#,
event_id,
owner_id,
&occurrence.occurrence_key,
occurrence.recurrence_id.as_deref(),
starts_at,
ends_at,
start_date,
end_date,
occurrence.is_cancelled,
)
.execute(&mut **tx)
.await
.map_err(report)?;
}
Ok(())
}
/// Calendar state a reminder firing schedule depends on: the zone that
/// anchors all-day starts and the defaults `useDefault` events resolve to.
struct CalendarReminderContext {
provider: CalendarProvider,
time_zone: Option<String>,
default_reminders: Vec<EventReminderOverride>,
}
async fn fetch_calendar_reminder_context(
tx: &mut Transaction<'_, Postgres>,
calendar_id: Option<Uuid>,
) -> Result<Option<CalendarReminderContext>, Report> {
let Some(calendar_id) = calendar_id else {
return Ok(None);
};
let row = sqlx::query!(
r#"SELECT c.time_zone,c.default_reminders,a.provider FROM calendars c JOIN calendar_accounts a ON a.id=c.account_id WHERE c.id=$1"#,
calendar_id,
)
.fetch_optional(&mut **tx)
.await
.map_err(report)?;
Ok(row.map(|row| CalendarReminderContext {
provider: if row.provider=="outlook" {CalendarProvider::Outlook} else {CalendarProvider::Google},
time_zone: row.time_zone,
// This feeds the firing schedule: a malformed value silently drops
// every default reminder on the calendar, so it must leave a trace.
default_reminders: serde_json::from_value(row.default_reminders)
.inspect_err(|e| {
tracing::error!(error = ?e, %calendar_id, "malformed calendar default_reminders json");
})
.unwrap_or_default(),
}))
}
/// The zone that anchors an all-day occurrence's midnight, validated against
/// the server's own tzdata. Google resolves all-day reminders against the
/// calendar's zone; a zone the server does not know falls back to UTC rather
/// than failing the write. chrono-tz and Postgres carry independent IANA
/// copies, so client-side parsing alone cannot guarantee `AT TIME ZONE`
/// accepts the name.
async fn anchor_time_zone(
tx: &mut Transaction<'_, Postgres>,
zone: Option<&str>,
) -> Result<String, Report> {
let Some(zone) = zone.filter(|zone| *zone != "UTC") else {
return Ok("UTC".to_owned());
};
let known = sqlx::query_scalar!(
r#"SELECT EXISTS (SELECT 1 FROM pg_timezone_names WHERE name = $1) AS "known!""#,
zone,
)
.fetch_one(&mut **tx)
.await
.map_err(report)?;
if known {
Ok(zone.to_owned())
} else {
tracing::warn!(
zone,
"calendar time zone unknown to postgres, anchoring all-day reminders at UTC"
);
Ok("UTC".to_owned())
}
}
/// Rebuild one event's reminder firing schedule from its just-replaced
/// occurrences and resolved popup offsets. Runs inside the canonical
/// replacement transaction so the schedule can never disagree with the
/// projections it derives from. Recently past firings are kept so the sweep's
/// grace window still sees them; delivery claims live in the deliveries table
/// and survive this rebuild.
async fn rebuild_event_reminder_firings(
tx: &mut Transaction<'_, Postgres>,
event_id: Uuid,
status: EventStatus,
event_type: EventType,
reminders: &EventReminders,
calendar: Option<&CalendarReminderContext>,
) -> Result<(), Report> {
sqlx::query!(
"DELETE FROM calendar_event_reminder_firings WHERE event_id = $1",
event_id,
)
.execute(&mut **tx)
.await
.map_err(report)?;
if status == EventStatus::Cancelled {
return Ok(());
}
let defaults = if event_type.uses_calendar_default_reminders() {
calendar.map_or(&[] as &[_], |calendar| &calendar.default_reminders)
} else {
&[]
};
let resolved_reminders = serde_json::to_value(if reminders.use_default {
defaults
} else {
&reminders.overrides
})
.map_err(report)?;
let default_reminders = serde_json::to_value(defaults).map_err(report)?;
let delivers_email = calendar.is_some_and(|c| c.provider == CalendarProvider::Outlook);
let time_zone = anchor_time_zone(
tx,
calendar.and_then(|calendar| calendar.time_zone.as_deref()),
)
.await?;
sqlx::query!(
r#"
INSERT INTO calendar_event_reminder_firings (
event_id, occurrence_key, minutes_before, fire_at, method
)
SELECT
occurrence.event_id,
occurrence.occurrence_key,
offsets.minutes,
COALESCE(
occurrence.starts_at,
occurrence.start_date::timestamp AT TIME ZONE $3
) - make_interval(mins => offsets.minutes),
offsets.method
FROM calendar_event_occurrences occurrence
LEFT JOIN calendar_event_overrides override ON override.event_id=occurrence.event_id
AND override.recurrence_id=occurrence.recurrence_id
CROSS JOIN LATERAL (
SELECT DISTINCT (reminder.value->>'minutes')::int AS minutes, reminder.value->>'method' AS method
FROM jsonb_array_elements(CASE
WHEN override.reminders IS NULL THEN $2::jsonb
WHEN (override.reminders->>'useDefault')::bool THEN $5::jsonb
ELSE override.reminders->'overrides' END) reminder(value)
WHERE (reminder.value->>'method'='popup' OR ($4 AND reminder.value->>'method'='email'))
AND (reminder.value->>'minutes')::bigint BETWEEN 0 AND 2147483647
) offsets
WHERE occurrence.event_id = $1
AND NOT occurrence.is_cancelled
AND COALESCE(
occurrence.starts_at,
occurrence.start_date::timestamp AT TIME ZONE $3
) - make_interval(mins => offsets.minutes) > now() - interval '1 day'
"#,
event_id,
resolved_reminders,
time_zone,
delivers_email,
default_reminders,
)
.execute(&mut **tx)
.await
.map_err(report)?;
Ok(())
}
/// Rebuild the firing schedule for every event whose canonical source lives
/// on one calendar, after its default reminders or time zone changed.
/// Set-based because a defaults change fans out to every `useDefault` event
/// on the calendar. Both statements key on the canonical copy, so an event
/// that also holds a secondary copy on this calendar keeps the schedule its
/// canonical calendar derived and a shared calendar's defaults never reach a
/// member's own event.
async fn rebuild_calendar_reminder_firings(
tx: &mut Transaction<'_, Postgres>,
calendar_id: Uuid,
time_zone: Option<&str>,
default_reminders: &serde_json::Value,
) -> Result<(), Report> {
sqlx::query!(
r#"
DELETE FROM calendar_event_reminder_firings firing
USING calendar_event_sources source
WHERE source.event_id = firing.event_id
AND source.calendar_id = $1
AND (
SELECT canonical.calendar_id
FROM calendar_event_sources canonical
WHERE canonical.id = calendar_event_canonical_source_id(firing.event_id)
) = $1
"#,
calendar_id,
)
.execute(&mut **tx)
.await
.map_err(report)?;
let anchor_zone = anchor_time_zone(tx, time_zone).await?;
sqlx::query!(
r#"
INSERT INTO calendar_event_reminder_firings (
event_id, occurrence_key, minutes_before, fire_at, method
)
SELECT DISTINCT
occurrence.event_id,
occurrence.occurrence_key,
offsets.minutes,
COALESCE(
occurrence.starts_at,
occurrence.start_date::timestamp AT TIME ZONE $2
) - make_interval(mins => offsets.minutes),
offsets.method
FROM calendar_event_sources source
JOIN calendar_events event ON event.id = source.event_id
JOIN calendar_event_occurrences occurrence ON occurrence.event_id = event.id
LEFT JOIN calendar_event_overrides override ON override.event_id=event.id
AND override.recurrence_id=occurrence.recurrence_id
CROSS JOIN LATERAL (
SELECT (reminder.value ->> 'minutes')::int AS minutes, reminder.value ->> 'method' AS method
FROM jsonb_array_elements(
CASE
-- Status-style events never resolve the calendar
-- defaults, mirroring EventType::uses_calendar_default_reminders.
WHEN COALESCE((override.reminders->>'useDefault')::bool,event.reminders_use_default)
AND event.event_type IN ('default', 'from_gmail')
THEN $3::jsonb
WHEN COALESCE((override.reminders->>'useDefault')::bool,event.reminders_use_default) THEN '[]'::jsonb
ELSE COALESCE(override.reminders->'overrides',event.reminder_overrides)
END
) AS reminder(value)
WHERE (reminder.value ->> 'method' = 'popup' OR (reminder.value ->> 'method' = 'email'
AND EXISTS(SELECT 1 FROM calendar_accounts account WHERE account.id=source.account_id AND account.provider='outlook')))
AND (reminder.value ->> 'minutes')::bigint BETWEEN 0 AND 2147483647
) offsets
WHERE source.calendar_id = $1
AND (
SELECT canonical.calendar_id
FROM calendar_event_sources canonical
WHERE canonical.id = calendar_event_canonical_source_id(event.id)
) = $1
AND event.status <> 'cancelled'
AND NOT occurrence.is_cancelled
AND COALESCE(
occurrence.starts_at,
occurrence.start_date::timestamp AT TIME ZONE $2
) - make_interval(mins => offsets.minutes) > now() - interval '1 day'
ON CONFLICT (event_id, occurrence_key, minutes_before, method) DO NOTHING
"#,
calendar_id,
anchor_zone,
default_reminders,
)
.execute(&mut **tx)
.await
.map_err(report)?;
Ok(())
}
/// Every active copy of each event in canonical order, the same keys
/// `calendar_event_canonical_source_id` ranks by: the primary calendar's
/// copy, then writable copies, then the freshest. Copies on deleted calendars
/// or disabled accounts are omitted, mirroring what the calendar list shows.
/// A copy older than a user edit through the organizer's copy that Google has
/// yet to carry to it reads with the meeting content the entity took from
/// that edit, as Google will show it.
async fn fetch_source_contents(
pool: &PgPool,
event_ids: &[Uuid],
) -> Result<HashMap<Uuid, Vec<CalendarEventSourceContent>>, Report> {
if event_ids.is_empty() {
return Ok(HashMap::new());
}
let rows = sqlx::query!(
r#"
SELECT
source.event_id,
source.calendar_id AS "calendar_id!",
CASE WHEN ahead.id IS NULL THEN source.title ELSE ahead.title END AS "title!",
CASE WHEN ahead.id IS NULL THEN source.description ELSE ahead.description END
AS description,
CASE WHEN ahead.id IS NULL THEN source.location ELSE ahead.location END
AS location,
source.event_type,
CASE WHEN ahead.id IS NULL THEN source.visibility ELSE ahead.visibility END
AS "visibility!",
source.transparency,
source.is_read_only,
source.reminders_use_default,
source.reminder_overrides,
source.creator_email,
source.creator_name
FROM calendar_event_sources source
JOIN calendars calendar ON calendar.id = source.calendar_id
JOIN calendar_accounts account ON account.id = source.account_id
LEFT JOIN calendar_events ahead
ON ahead.id = source.event_id
AND source.source_updated_at < ahead.content_updated_at
WHERE source.event_id = ANY($1)
AND NOT calendar.is_deleted
AND account.sync_status <> 'disabled'
ORDER BY
source.event_id,
calendar.is_primary DESC,
(calendar.access_role IN ('owner', 'writer')) DESC NULLS LAST,
source.source_sequence DESC,
source.source_updated_at DESC,
source.id DESC
"#,
event_ids,
)
.fetch_all(pool)
.await
.map_err(report)?;
let mut grouped: HashMap<Uuid, Vec<CalendarEventSourceContent>> = HashMap::new();
for row in rows {
grouped
.entry(row.event_id)
.or_default()
.push(CalendarEventSourceContent {
calendar_id: row.calendar_id,
title: row.title,
description: row.description,
location: row.location,
event_type: event_type(&row.event_type),
visibility: event_visibility(&row.visibility),
transparency: event_transparency(&row.transparency),
is_read_only: row.is_read_only,
reminders: EventReminders {
use_default: row.reminders_use_default,
overrides: serde_json::from_value(row.reminder_overrides)
.inspect_err(|e| {
tracing::error!(error = ?e, event_id = %row.event_id, calendar_id = %row.calendar_id, "malformed source reminder_overrides json");
})
.unwrap_or_default(),
},
creator_email: row.creator_email,
creator_name: row.creator_name,
});
}
Ok(grouped)
}
async fn fetch_attendees(
pool: &PgPool,
event_ids: &[Uuid],
) -> Result<HashMap<Uuid, Vec<CalendarAttendee>>, Report> {
if event_ids.is_empty() {
return Ok(HashMap::new());
}
let rows = sqlx::query_as!(
AttendeeRow,
r#"
SELECT
event_id, email, display_name, response_status,
is_organizer, is_optional, is_self, comment
FROM calendar_event_attendees
WHERE event_id = ANY($1)
ORDER BY event_id, email
"#,
event_ids,
)
.fetch_all(pool)
.await
.map_err(report)?;
let mut by_event = HashMap::new();
for row in rows {
by_event
.entry(row.event_id)
.or_insert_with(Vec::new)
.push(CalendarAttendee {
email: row.email,
display_name: row.display_name,
response_status: attendee_status(&row.response_status),
is_organizer: row.is_organizer,
is_optional: row.is_optional,
is_self: row.is_self,
comment: row.comment,
});
}
Ok(by_event)
}
/// Per-occurrence attendee overrides for the supplied events, keyed by
/// `(event_id, recurrence_id)`.
async fn fetch_override_attendees(
pool: &PgPool,
event_ids: &[Uuid],
) -> Result<HashMap<(Uuid, String), Vec<CalendarAttendee>>, Report> {
if event_ids.is_empty() {
return Ok(HashMap::new());
}
// Driven from the overrides table so an explicitly-empty replacement
// list still produces a map entry: absence of an entry means "inherit
// the series attendees", never "the exception has no attendees".
let rows = sqlx::query_as!(
OverrideAttendeeRow,
r#"
SELECT
override.event_id,
override.recurrence_id,
attendee.email AS "email?",
attendee.display_name,
attendee.response_status AS "response_status?",
attendee.is_organizer AS "is_organizer?",
attendee.is_optional AS "is_optional?",
attendee.is_self AS "is_self?",
attendee.comment
FROM calendar_event_overrides override
LEFT JOIN calendar_event_override_attendees attendee
ON attendee.event_id = override.event_id
AND attendee.recurrence_id = override.recurrence_id
WHERE override.event_id = ANY($1)
AND override.attendees_overridden
ORDER BY override.event_id, override.recurrence_id, attendee.email
"#,
event_ids,
)
.fetch_all(pool)
.await
.map_err(report)?;
let mut by_occurrence: HashMap<(Uuid, String), Vec<CalendarAttendee>> = HashMap::new();
for row in rows {
let attendees = by_occurrence
.entry((row.event_id, row.recurrence_id))
.or_default();
if let (Some(email), Some(response_status)) = (row.email, row.response_status) {
attendees.push(CalendarAttendee {
email,
display_name: row.display_name,
response_status: attendee_status(&response_status),
is_organizer: row.is_organizer.unwrap_or_default(),
is_optional: row.is_optional.unwrap_or_default(),
is_self: row.is_self.unwrap_or_default(),
comment: row.comment,
});
}
}
Ok(by_occurrence)
}
type SplitTime = (
Option<DateTime<Utc>>,
Option<DateTime<Utc>>,
Option<NaiveDate>,
Option<NaiveDate>,
Option<String>,
);
fn split_time(time: &EventTime) -> SplitTime {
match time {
EventTime::Timed {
starts_at,
ends_at,
time_zone,
} => (
Some(*starts_at),
Some(*ends_at),
None,
None,
time_zone.clone(),
),
EventTime::AllDay {
start_date,
end_date,
} => (None, None, Some(*start_date), Some(*end_date), None),
}
}
fn row_time(
starts_at: Option<DateTime<Utc>>,
ends_at: Option<DateTime<Utc>>,
start_date: Option<NaiveDate>,
end_date: Option<NaiveDate>,
time_zone: Option<String>,
) -> Result<EventTime, Report> {
match (starts_at, ends_at, start_date, end_date) {
(Some(starts_at), Some(ends_at), None, None) => Ok(EventTime::Timed {
starts_at,
ends_at,
time_zone,
}),
(None, None, Some(start_date), Some(end_date)) => Ok(EventTime::AllDay {
start_date,
end_date,
}),
_ => Err(rootcause::report!(
"invalid calendar time shape in database"
)),
}
}
fn mention_preview_from_row(row: MentionPreviewRow) -> Result<CalendarMentionPreview, Report> {
if !row.mention_exists {
return Ok(CalendarMentionPreview::DoesNotExist);
}
let Some(resolved_event_id) = row.resolved_event_id else {
return Ok(CalendarMentionPreview::NoAccess);
};
let is_channel_shared = row.is_channel_shared.unwrap_or_default();
let (description, location) = if is_channel_shared {
let (description, location) = content_without_macro_call(row.description, row.location);
let description = description.map(|description| {
description
.chars()
.take(usize::from(MENTION_PREVIEW_DESCRIPTION_MAX_CHARS))
.collect()
});
(description, location)
} else {
(row.description, row.location)
};
let time = if row.occurrence_key.is_some() {
row_time(
row.occurrence_starts_at,
row.occurrence_ends_at,
row.occurrence_start_date,
row.occurrence_end_date,
row.time_zone,
)?
} else {
// No materialized instance (the event sits outside the maintained
// window) — the series' own span still gives the preview a time.
row_time(
row.event_starts_at,
row.event_ends_at,
row.event_start_date,
row.event_end_date,
row.time_zone,
)?
};
Ok(CalendarMentionPreview::Accessible(Box::new(
CalendarMentionEvent {
viewer_event_id: (!is_channel_shared).then_some(resolved_event_id),
viewer_calendar_ids: row
.viewer_calendar_ids
.filter(|_| !is_channel_shared)
.unwrap_or_default(),
viewer_copy: (!is_channel_shared).then(|| {
CalendarMentionViewerCopy::classify(
row.is_snapshot.unwrap_or_default(),
row.inbox_organizes.unwrap_or_default(),
row.inbox_attends.unwrap_or_default(),
)
}),
title: row.title.unwrap_or_default(),
description: description.filter(|description| !description.trim().is_empty()),
time,
occurrence_key: row.occurrence_key,
is_recurring: !row.recurrence_lines.unwrap_or_default().is_empty(),
location,
organizer_email: row.organizer_email,
organizer_name: row.organizer_name,
attendee_count: usize::try_from(row.attendee_count.unwrap_or_default())
.unwrap_or_default(),
updated_at: row.updated_at.unwrap_or(DateTime::<Utc>::MIN_UTC),
// The domain service fills the ask-to-join state in.
can_request_to_join: false,
join_request_status: None,
},
)))
}
fn event_from_join(
mut row: OccurrenceJoinRow,
attendees: Vec<CalendarAttendee>,
sources: Vec<CalendarEventSourceContent>,
) -> Result<CalendarEvent, Report> {
let exception = take_exception(&mut row);
let mut event = series_event_from_join(row, attendees, sources)?;
// An exception's content replaces the series content for that occurrence
// alone, the same way its attendee list shadows the series list.
event.apply_occurrence_content(exception.content());
Ok(event)
}
/// Move a joined occurrence row's exception content out of the row. The
/// exception's attendee list is left to the caller, which loads attendees in
/// bulk.
fn take_exception(row: &mut OccurrenceJoinRow) -> OccurrenceException {
OccurrenceException {
title: row.override_title.take(),
description: row.override_description.take(),
location: row.override_location.take(),
status: row.override_status.take().as_deref().map(event_status),
attendees: None,
}
}
/// The series event of a joined occurrence row, ignoring its exception.
/// A per-occurrence reminder override still replaces the series reminders.
fn series_event_from_join(
mut row: OccurrenceJoinRow,
attendees: Vec<CalendarAttendee>,
sources: Vec<CalendarEventSourceContent>,
) -> Result<CalendarEvent, Report> {
let override_reminders = row
.override_reminders
.take()
.map(serde_json::from_value::<EventReminders>)
.transpose()
.map_err(report)?;
let mut event = CalendarEvent {
id: row.event_id,
owner_id: row.owner_id,
ical_uid: row.ical_uid,
calendar_id: sources.first().map(|source| source.calendar_id),
sources,
title: row.title,
description: row.description,
location: row.location,
status: event_status(&row.status),
visibility: event_visibility(&row.visibility),
transparency: event_transparency(&row.transparency),
event_type: event_type(&row.event_type),
time: row_time(
row.starts_at,
row.ends_at,
row.start_date,
row.end_date,
row.time_zone,
)?,
recurrence_lines: row.recurrence_lines,
organizer_email: row.organizer_email,
organizer_name: row.organizer_name,
creator_email: row.creator_email,
creator_name: row.creator_name,
conference_url: row.conference_url,
conference_provider: row.conference_provider.as_deref().map(conference_provider),
sequence: u32::try_from(row.sequence).unwrap_or_default(),
is_read_only: row.is_read_only,
reminders: EventReminders {
use_default: row.reminders_use_default,
overrides: serde_json::from_value(row.reminder_overrides)
.inspect_err(|e| {
tracing::error!(error = ?e, event_id = %row.event_id, "malformed event reminder_overrides json");
})
.unwrap_or_default(),
},
attendees,
guest_policy: 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,
},
is_snapshot: row.is_snapshot,
viewer_can: ViewerCapabilities::NONE,
created_at: row.created_at,
updated_at: row.updated_at,
};
if let Some(reminders) = override_reminders {
event.reminders = reminders.clone();
for source in &mut event.sources {
source.reminders = reminders.clone();
}
}
Ok(event)
}
fn occurrence_from_join(row: &OccurrenceJoinRow) -> Result<CalendarOccurrence, Report> {
Ok(CalendarOccurrence {
event_id: row.event_id,
occurrence_key: row.occurrence_key.clone(),
recurrence_id: row.recurrence_id.clone(),
time: row_time(
row.occurrence_starts_at,
row.occurrence_ends_at,
row.occurrence_start_date,
row.occurrence_end_date,
None,
)?,
is_cancelled: row.is_cancelled,
})
}
fn event_status(value: &str) -> EventStatus {
match value {
"tentative" => EventStatus::Tentative,
"cancelled" => EventStatus::Cancelled,
_ => EventStatus::Confirmed,
}
}
fn event_visibility(value: &str) -> EventVisibility {
match value {
"public" => EventVisibility::Public,
"private" => EventVisibility::Private,
"confidential" => EventVisibility::Confidential,
_ => EventVisibility::Default,
}
}
/// Parse the stored provider, treating an unknown value as a third-party
/// conference so a row written by a newer deployment stays joinable and is
/// never mistaken for one Macro may detach.
fn conference_provider(value: &str) -> ConferenceProvider {
if value == "microsoft_teams" {
ConferenceProvider::MicrosoftTeams
} else if value == "google_meet" {
ConferenceProvider::GoogleMeet
} else {
ConferenceProvider::Other
}
}
fn event_transparency(value: &str) -> EventTransparency {
if value == "transparent" {
EventTransparency::Transparent
} else {
EventTransparency::Opaque
}
}
fn event_type(value: &str) -> EventType {
match value {
"out_of_office" => EventType::OutOfOffice,
"focus_time" => EventType::FocusTime,
"working_location" => EventType::WorkingLocation,
"birthday" => EventType::Birthday,
"from_gmail" => EventType::FromGmail,
_ => EventType::Default,
}
}
fn attendee_status(value: &str) -> AttendeeResponseStatus {
match value {
"accepted" => AttendeeResponseStatus::Accepted,
"declined" => AttendeeResponseStatus::Declined,
"tentative" => AttendeeResponseStatus::Tentative,
_ => AttendeeResponseStatus::NeedsAction,
}
}
/// Strip the volatile identifiers a fresh normalization mints (the proposed
/// entity id and its occurrence back-references) so two projections of the
/// same provider state compare equal.
fn canonical_projection(value: &serde_json::Value) -> serde_json::Value {
let mut value = value.clone();
if let Some(event) = value.get_mut("event").and_then(|event| event.get_mut("id")) {
*event = serde_json::Value::Null;
}
if let Some(occurrences) = value.get_mut("occurrences").and_then(|v| v.as_array_mut()) {
for occurrence in occurrences {
if let Some(id) = occurrence.get_mut("eventId") {
*id = serde_json::Value::Null;
}
}
}
value
}
fn report(error: impl std::error::Error + Send + Sync + 'static) -> Report {
rootcause::report!(error).into()
}
fn db_sequence(sequence: u32) -> Result<i32, Report> {
i32::try_from(sequence).map_err(|_| {
rootcause::report!(
"calendar event sequence {sequence} overflows the database representation"
)
})
}
/// How stale a firing may be and still alert. A late reminder for a meeting
/// already underway is noise; anything the dispatcher missed by more than
/// this window is silently dropped rather than delivered hours late.
const REMINDER_SWEEP_GRACE: chrono::Duration = chrono::Duration::minutes(30);
impl CalendarReminderDispatchRepo for PgCalendarRepository {
#[tracing::instrument(err, skip(self))]
async fn due_reminder_firings(
&self,
now: DateTime<Utc>,
after: Option<&CalendarReminderFiring>,
limit: i64,
) -> Result<Vec<CalendarReminderFiring>, Report> {
// Driven by `calendar_event_reminder_firings_due_idx`. A completed
// delivery claim is what makes a delivered firing stop being due; a
// held-but-unfinished claim still sweeps, and loses the claim race at
// delivery instead. The keyset resumes past `after` because nothing
// marks a swept firing — re-running the window from the top would
// return the same rows forever.
let rows = sqlx::query!(
r#"
SELECT firing.event_id, firing.occurrence_key, firing.minutes_before, firing.fire_at, firing.method
FROM calendar_event_reminder_firings firing
WHERE firing.fire_at <= $1
AND firing.fire_at > $2
AND (
$4::timestamptz IS NULL
OR (firing.fire_at, firing.event_id, firing.minutes_before, firing.occurrence_key, firing.method)
> ($4, $5, $6, $7, $8)
)
AND NOT EXISTS (
SELECT 1
FROM calendar_event_reminder_deliveries delivery
WHERE delivery.event_id = firing.event_id
AND delivery.occurrence_key = firing.occurrence_key
AND delivery.minutes_before = firing.minutes_before
AND delivery.fire_at = firing.fire_at
AND delivery.method = firing.method
AND delivery.sent_at IS NOT NULL
)
ORDER BY firing.fire_at, firing.event_id, firing.minutes_before, firing.occurrence_key, firing.method
LIMIT $3
"#,
now,
now - REMINDER_SWEEP_GRACE,
limit,
after.map(|firing| firing.fire_at),
after.map(|firing| firing.event_id),
after.map(|firing| firing.minutes_before),
after.map(|firing| firing.occurrence_key.as_str()),
after.map(|firing| firing.method.as_str()),
)
.fetch_all(&self.pool)
.await
.map_err(report)?;
Ok(rows
.into_iter()
.map(|row| CalendarReminderFiring {
method: if row.method == "email" {
crate::domain::models::ReminderDeliveryMethod::Email
} else {
crate::domain::models::ReminderDeliveryMethod::Popup
},
event_id: row.event_id,
occurrence_key: row.occurrence_key,
minutes_before: row.minutes_before,
fire_at: row.fire_at,
})
.collect())
}
#[tracing::instrument(err, skip(self))]
async fn find_due_reminder(
&self,
firing: &CalendarReminderFiring,
) -> Result<Option<DueCalendarReminder>, Report> {
// Matching the firing row exactly — including `fire_at` — is what
// makes a stale message safe: a moved event replaced its schedule
// rows, and this then finds nothing rather than alerting at a time
// that no longer exists. Joining the canonical copy through
// `calendar_event_canonical_source_id` skips deleted calendars and
// disabled accounts like the read path, so losing the calendar that
// owns the schedule stops its alerts.
// The grace bound is re-applied here because firing rows outlive the
// sweep window: a Deliver message that sat in the queue past the
// grace must drop, not alert hours late.
let stale_before = Utc::now() - REMINDER_SWEEP_GRACE;
let row = sqlx::query!(
r#"
SELECT
event.owner_id,
mailbox.email_address,
event.title,
event.time_zone AS "event_time_zone?",
occurrence.starts_at,
occurrence.ends_at,
occurrence.start_date,
occurrence.end_date,
canonical_calendar.time_zone AS "calendar_time_zone?",
CASE WHEN EXISTS (
SELECT 1
FROM calendar_event_overrides override
WHERE override.event_id = event.id
AND override.recurrence_id = occurrence.recurrence_id
AND override.attendees_overridden
)
THEN EXISTS (
SELECT 1
FROM calendar_event_override_attendees attendee
JOIN email_links owner_inbox
ON owner_inbox.macro_id = event.owner_id
AND lower(owner_inbox.email_address::text) = attendee.email
WHERE attendee.event_id = event.id
AND attendee.recurrence_id = occurrence.recurrence_id
AND attendee.response_status = 'declined'
)
ELSE EXISTS (
SELECT 1
FROM calendar_event_attendees attendee
JOIN email_links owner_inbox
ON owner_inbox.macro_id = event.owner_id
AND lower(owner_inbox.email_address::text) = attendee.email
WHERE attendee.event_id = event.id
AND attendee.response_status = 'declined'
)
END AS "declined!"
FROM calendar_event_reminder_firings firing
JOIN calendar_events event ON event.id = firing.event_id
JOIN calendar_event_occurrences occurrence
ON occurrence.event_id = firing.event_id
AND occurrence.occurrence_key = firing.occurrence_key
JOIN calendar_event_sources canonical_source
ON canonical_source.id = calendar_event_canonical_source_id(event.id)
JOIN calendars canonical_calendar
ON canonical_calendar.id = canonical_source.calendar_id
JOIN calendar_accounts account ON account.id=canonical_source.account_id
JOIN email_links mailbox ON mailbox.id=account.email_link_id
WHERE firing.event_id = $1
AND firing.occurrence_key = $2
AND firing.minutes_before = $3
AND firing.fire_at = $4
AND firing.fire_at > $5
AND firing.method = $6
AND event.status <> 'cancelled'
AND NOT occurrence.is_cancelled
"#,
firing.event_id,
&firing.occurrence_key,
firing.minutes_before,
firing.fire_at,
stale_before,
firing.method.as_str(),
)
.fetch_optional(&self.pool)
.await
.map_err(report)?;
let Some(row) = row else {
return Ok(None);
};
let time = row_time(
row.starts_at,
row.ends_at,
row.start_date,
row.end_date,
row.event_time_zone.clone(),
)?;
Ok(Some(DueCalendarReminder {
firing: firing.clone(),
owner_id: row.owner_id,
email_address: row.email_address,
title: row.title,
time,
display_time_zone: row.event_time_zone.or(row.calendar_time_zone),
declined: row.declined,
}))
}
#[tracing::instrument(err, skip(self))]
async fn claim_reminder_delivery(
&self,
firing: &CalendarReminderFiring,
retry_before: DateTime<Utc>,
) -> Result<bool, Report> {
// One statement covers both a first claim and a retry. The unique
// index on the firing identity makes the insert the claim; the
// conflict branch takes over a claim made before `retry_before` and
// never completed, so a dispatcher that died mid-flight does not
// strand the firing. Already sent or still fresh matches neither.
let claimed = sqlx::query_scalar!(
r#"
INSERT INTO calendar_event_reminder_deliveries (
id, event_id, occurrence_key, minutes_before, fire_at, method
)
VALUES ($1, $2, $3, $4, $5, $7)
ON CONFLICT (event_id, occurrence_key, minutes_before, fire_at, method) DO UPDATE
SET created_at = now()
WHERE calendar_event_reminder_deliveries.sent_at IS NULL
AND calendar_event_reminder_deliveries.created_at < $6
RETURNING id
"#,
Uuid::now_v7(),
firing.event_id,
&firing.occurrence_key,
firing.minutes_before,
firing.fire_at,
retry_before,
firing.method.as_str(),
)
.fetch_optional(&self.pool)
.await
.map_err(report)?;
Ok(claimed.is_some())
}
#[tracing::instrument(err, skip(self))]
async fn release_reminder_delivery(
&self,
firing: &CalendarReminderFiring,
) -> Result<(), Report> {
// `sent_at IS NULL` guards against releasing a firing that did go
// out: completion and release can only race if the same firing is
// handled twice, and the delivered one must win.
sqlx::query!(
r#"
DELETE FROM calendar_event_reminder_deliveries
WHERE event_id = $1
AND occurrence_key = $2
AND minutes_before = $3
AND fire_at = $4
AND method = $5
AND sent_at IS NULL
"#,
firing.event_id,
&firing.occurrence_key,
firing.minutes_before,
firing.fire_at,
firing.method.as_str(),
)
.execute(&self.pool)
.await
.map_err(report)?;
Ok(())
}
#[tracing::instrument(err, skip(self))]
async fn complete_reminder_delivery(
&self,
firing: &CalendarReminderFiring,
) -> Result<(), Report> {
sqlx::query!(
r#"
UPDATE calendar_event_reminder_deliveries
SET sent_at = now()
WHERE event_id = $1
AND occurrence_key = $2
AND minutes_before = $3
AND fire_at = $4
AND method = $5
"#,
firing.event_id,
&firing.occurrence_key,
firing.minutes_before,
firing.fire_at,
firing.method.as_str(),
)
.execute(&self.pool)
.await
.map_err(report)?;
Ok(())
}
#[tracing::instrument(err, skip(self))]
async fn record_reminder_fired(
&self,
event_id: Uuid,
fired_at: DateTime<Utc>,
) -> Result<(), Report> {
// GREATEST also covers the first delivery: it ignores the NULL.
sqlx::query!(
r#"
UPDATE calendar_events
SET last_reminder_fired_at = GREATEST(last_reminder_fired_at, $2)
WHERE id = $1
"#,
event_id,
fired_at,
)
.execute(&self.pool)
.await
.map_err(report)?;
Ok(())
}
}
fn event_reconciliation_lock(source_link_id: Uuid, ical_uid: &str) -> i64 {
// Stable FNV-1a produces the same advisory-lock key in every service
// process. A collision only adds harmless serialization.
let mut hash = 0xcbf2_9ce4_8422_2325_u64;
for byte in source_link_id
.as_bytes()
.iter()
.copied()
.chain(ical_uid.bytes())
{
hash ^= u64::from(byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
i64::from_ne_bytes(hash.to_ne_bytes())
}
#[cfg(test)]
mod test;