Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(calendar): add GraphQL calendar read types and occurrence range queries (#7670)

gbirmaneb091eb92b4b
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 79718b43bf..8e5c7a0a3d 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -3454,6 +3454,7 @@
"crates/github_pull_requests",
"crates/google_token",
"crates/graphql_activity",
+ "crates/graphql_calendar",
"crates/graphql_channel",
"crates/graphql_common",
"crates/graphql_email",
@@ -4635,6 +4636,7 @@
"crates/github_pull_requests",
"crates/google_token",
"crates/graphql_activity",
+ "crates/graphql_calendar",
"crates/graphql_channel",
"crates/graphql_common",
"crates/graphql_email",
@@ -6480,6 +6482,50 @@
"crates/remote_env_var",
"crates/workspace-hack"
],
+ "graphql_calendar": [
+ "crates/ai_toolset",
+ "crates/bot_id",
+ "crates/bot_token",
+ "crates/broadcast",
+ "crates/calendar_events",
+ "crates/channel_sender",
+ "crates/cowlike",
+ "crates/document_sub_type",
+ "crates/filter_ast",
+ "crates/genai_telemetry",
+ "crates/graphql_calendar",
+ "crates/graphql_common",
+ "crates/harness_id",
+ "crates/harness_token",
+ "crates/invite_email",
+ "crates/item_filters",
+ "crates/kafka_util",
+ "crates/last_online_tracker",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_env",
+ "crates/macro_env_var",
+ "crates/macro_event_broker",
+ "crates/macro_event_topics",
+ "crates/macro_service_urls",
+ "crates/macro_user_id",
+ "crates/macro_uuid",
+ "crates/mention_utils",
+ "crates/model-entity",
+ "crates/model-error-response",
+ "crates/model_file_type",
+ "crates/model_notifications",
+ "crates/model_owner",
+ "crates/model_user",
+ "crates/models_pagination",
+ "crates/models_properties",
+ "crates/non_empty",
+ "crates/notification",
+ "crates/notification_state",
+ "crates/rate_limit",
+ "crates/remote_env_var",
+ "crates/workspace-hack"
+ ],
"graphql_channel": [
"crates/activity",
"crates/agent",
diff --git a/.sqlx/query-011685c3f1ce2931cb599481ebd7388d8ee0c96ffbaa51d6a43ad6dc5b9d40ff.json b/.sqlx/query-1fd7598ab3adbedd997125565b274d743814a4006e7abba1d646aa5cfe2b28b1.json
similarity index 56%
rename from .sqlx/query-011685c3f1ce2931cb599481ebd7388d8ee0c96ffbaa51d6a43ad6dc5b9d40ff.json
rename to .sqlx/query-1fd7598ab3adbedd997125565b274d743814a4006e7abba1d646aa5cfe2b28b1.json
index 885d770c8d..ea39d758cd 100644
--- a/.sqlx/query-011685c3f1ce2931cb599481ebd7388d8ee0c96ffbaa51d6a43ad6dc5b9d40ff.json
+++ b/.sqlx/query-1fd7598ab3adbedd997125565b274d743814a4006e7abba1d646aa5cfe2b28b1.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n occurrence.event_id,\n occurrence.occurrence_key,\n occurrence.recurrence_id,\n occurrence.starts_at AS occurrence_starts_at,\n occurrence.ends_at AS occurrence_ends_at,\n occurrence.start_date AS occurrence_start_date,\n occurrence.end_date AS occurrence_end_date,\n occurrence.is_cancelled,\n override.title AS override_title,\n override.description AS override_description,\n override.location AS override_location,\n override.status AS override_status,\n event.owner_id,\n event.ical_uid,\n event.title,\n event.description,\n event.location,\n event.status,\n event.visibility,\n event.transparency,\n event.event_type,\n event.starts_at,\n event.ends_at,\n event.start_date,\n event.end_date,\n event.time_zone,\n event.recurrence_lines,\n event.organizer_email,\n event.organizer_name,\n event.creator_email,\n event.creator_name,\n event.conference_url,\n event.conference_provider,\n event.sequence,\n event.is_read_only,\n event.reminders_use_default,\n event.reminder_overrides,\n event.created_at,\n event.updated_at\n FROM calendar_event_occurrences occurrence\n JOIN calendar_events event ON event.id = occurrence.event_id\n LEFT JOIN calendar_event_overrides override\n ON override.event_id = occurrence.event_id\n AND override.recurrence_id = occurrence.recurrence_id\n WHERE occurrence.owner_id IN (\n SELECT $1::text\n UNION\n SELECT link.child_macro_id\n FROM macro_user_links link\n WHERE link.primary_macro_id = $1\n )\n AND event.status <> 'cancelled'\n AND NOT occurrence.is_cancelled\n AND (\n event.owner_id = $1\n OR EXISTS (\n SELECT 1\n FROM macro_user_links link\n WHERE link.link_id = event.source_link_id\n AND link.primary_macro_id = $1\n )\n )\n AND (\n occurrence.timed_span && tstzrange($2, $3, '[)')\n OR occurrence.day_span && daterange($4, $5, '[)')\n )\n AND (\n $6::timestamptz IS NULL\n OR (\n COALESCE(\n occurrence.starts_at,\n occurrence.start_date::timestamp AT TIME ZONE 'UTC'\n ),\n occurrence.event_id,\n occurrence.occurrence_key\n ) > ($6, $7, $8)\n )\n ORDER BY\n COALESCE(occurrence.starts_at, occurrence.start_date::timestamp AT TIME ZONE 'UTC'),\n occurrence.event_id,\n occurrence.occurrence_key\n LIMIT $9\n ",
+ "query": "\n SELECT\n occurrence.event_id,\n event.source_link_id,\n occurrence.occurrence_key,\n occurrence.recurrence_id,\n occurrence.starts_at AS occurrence_starts_at,\n occurrence.ends_at AS occurrence_ends_at,\n occurrence.start_date AS occurrence_start_date,\n occurrence.end_date AS occurrence_end_date,\n occurrence.is_cancelled,\n override.title AS override_title,\n override.description AS override_description,\n override.location AS override_location,\n override.status AS override_status,\n event.owner_id,\n event.ical_uid,\n event.title,\n event.description,\n event.location,\n event.status,\n event.visibility,\n event.transparency,\n event.event_type,\n event.starts_at,\n event.ends_at,\n event.start_date,\n event.end_date,\n event.time_zone,\n event.recurrence_lines,\n event.organizer_email,\n event.organizer_name,\n event.creator_email,\n event.creator_name,\n event.conference_url,\n event.conference_provider,\n event.sequence,\n event.is_read_only,\n event.reminders_use_default,\n event.reminder_overrides,\n event.created_at,\n event.updated_at\n FROM calendar_event_occurrences occurrence\n JOIN calendar_events event ON event.id = occurrence.event_id\n LEFT JOIN calendar_event_overrides override\n ON override.event_id = occurrence.event_id\n AND override.recurrence_id = occurrence.recurrence_id\n WHERE occurrence.owner_id IN (\n SELECT $1::text\n UNION\n SELECT link.child_macro_id\n FROM macro_user_links link\n WHERE link.primary_macro_id = $1\n )\n AND event.status <> 'cancelled'\n AND NOT occurrence.is_cancelled\n AND (\n event.owner_id = $1\n OR EXISTS (\n SELECT 1\n FROM macro_user_links link\n WHERE link.link_id = event.source_link_id\n AND link.primary_macro_id = $1\n )\n )\n AND (\n occurrence.timed_span && tstzrange($2, $3, '[)')\n OR occurrence.day_span && daterange($4, $5, '[)')\n )\n AND (\n $6::timestamptz IS NULL\n OR (\n COALESCE(\n occurrence.starts_at,\n occurrence.start_date::timestamp AT TIME ZONE 'UTC'\n ),\n occurrence.event_id,\n occurrence.occurrence_key\n ) > ($6, $7, $8)\n )\n ORDER BY\n COALESCE(occurrence.starts_at, occurrence.start_date::timestamp AT TIME ZONE 'UTC'),\n occurrence.event_id,\n occurrence.occurrence_key\n LIMIT $9\n ",
"describe": {
"columns": [
{
@@ -10,191 +10,196 @@
},
{
"ordinal": 1,
+ "name": "source_link_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
"name": "occurrence_key",
"type_info": "Text"
},
{
- "ordinal": 2,
+ "ordinal": 3,
"name": "recurrence_id",
"type_info": "Text"
},
{
- "ordinal": 3,
+ "ordinal": 4,
"name": "occurrence_starts_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 4,
+ "ordinal": 5,
"name": "occurrence_ends_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 5,
+ "ordinal": 6,
"name": "occurrence_start_date",
"type_info": "Date"
},
{
- "ordinal": 6,
+ "ordinal": 7,
"name": "occurrence_end_date",
"type_info": "Date"
},
{
- "ordinal": 7,
+ "ordinal": 8,
"name": "is_cancelled",
"type_info": "Bool"
},
{
- "ordinal": 8,
+ "ordinal": 9,
"name": "override_title",
"type_info": "Text"
},
{
- "ordinal": 9,
+ "ordinal": 10,
"name": "override_description",
"type_info": "Text"
},
{
- "ordinal": 10,
+ "ordinal": 11,
"name": "override_location",
"type_info": "Text"
},
{
- "ordinal": 11,
+ "ordinal": 12,
"name": "override_status",
"type_info": "Text"
},
{
- "ordinal": 12,
+ "ordinal": 13,
"name": "owner_id",
"type_info": "Text"
},
{
- "ordinal": 13,
+ "ordinal": 14,
"name": "ical_uid",
"type_info": "Text"
},
{
- "ordinal": 14,
+ "ordinal": 15,
"name": "title",
"type_info": "Text"
},
{
- "ordinal": 15,
+ "ordinal": 16,
"name": "description",
"type_info": "Text"
},
{
- "ordinal": 16,
+ "ordinal": 17,
"name": "location",
"type_info": "Text"
},
{
- "ordinal": 17,
+ "ordinal": 18,
"name": "status",
"type_info": "Text"
},
{
- "ordinal": 18,
+ "ordinal": 19,
"name": "visibility",
"type_info": "Text"
},
{
- "ordinal": 19,
+ "ordinal": 20,
"name": "transparency",
"type_info": "Text"
},
{
- "ordinal": 20,
+ "ordinal": 21,
"name": "event_type",
"type_info": "Text"
},
{
- "ordinal": 21,
+ "ordinal": 22,
"name": "starts_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 22,
+ "ordinal": 23,
"name": "ends_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 23,
+ "ordinal": 24,
"name": "start_date",
"type_info": "Date"
},
{
- "ordinal": 24,
+ "ordinal": 25,
"name": "end_date",
"type_info": "Date"
},
{
- "ordinal": 25,
+ "ordinal": 26,
"name": "time_zone",
"type_info": "Text"
},
{
- "ordinal": 26,
+ "ordinal": 27,
"name": "recurrence_lines",
"type_info": "TextArray"
},
{
- "ordinal": 27,
+ "ordinal": 28,
"name": "organizer_email",
"type_info": "Text"
},
{
- "ordinal": 28,
+ "ordinal": 29,
"name": "organizer_name",
"type_info": "Text"
},
{
- "ordinal": 29,
+ "ordinal": 30,
"name": "creator_email",
"type_info": "Text"
},
{
- "ordinal": 30,
+ "ordinal": 31,
"name": "creator_name",
"type_info": "Text"
},
{
- "ordinal": 31,
+ "ordinal": 32,
"name": "conference_url",
"type_info": "Text"
},
{
- "ordinal": 32,
+ "ordinal": 33,
"name": "conference_provider",
"type_info": "Text"
},
{
- "ordinal": 33,
+ "ordinal": 34,
"name": "sequence",
"type_info": "Int4"
},
{
- "ordinal": 34,
+ "ordinal": 35,
"name": "is_read_only",
"type_info": "Bool"
},
{
- "ordinal": 35,
+ "ordinal": 36,
"name": "reminders_use_default",
"type_info": "Bool"
},
{
- "ordinal": 36,
+ "ordinal": 37,
"name": "reminder_overrides",
"type_info": "Jsonb"
},
{
- "ordinal": 37,
+ "ordinal": 38,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 38,
+ "ordinal": 39,
"name": "updated_at",
"type_info": "Timestamptz"
}
@@ -213,6 +218,7 @@
]
},
"nullable": [
+ false,
false,
false,
true,
@@ -254,5 +260,5 @@
false
]
},
- "hash": "011685c3f1ce2931cb599481ebd7388d8ee0c96ffbaa51d6a43ad6dc5b9d40ff"
+ "hash": "1fd7598ab3adbedd997125565b274d743814a4006e7abba1d646aa5cfe2b28b1"
}
diff --git a/.sqlx/query-71e0b73492a384d376d7b54cebe950e93398140d96f30e491a0008a591188792.json b/.sqlx/query-341970aa3de5e15886614551d3c08dd4d856c65e8f975a8a7028cba1050726cc.json
similarity index 64%
rename from .sqlx/query-71e0b73492a384d376d7b54cebe950e93398140d96f30e491a0008a591188792.json
rename to .sqlx/query-341970aa3de5e15886614551d3c08dd4d856c65e8f975a8a7028cba1050726cc.json
index 0fb3793df5..d683cfd413 100644
--- a/.sqlx/query-71e0b73492a384d376d7b54cebe950e93398140d96f30e491a0008a591188792.json
+++ b/.sqlx/query-341970aa3de5e15886614551d3c08dd4d856c65e8f975a8a7028cba1050726cc.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": " SELECT\n occurrence.event_id,\n occurrence.occurrence_key,\n occurrence.recurrence_id,\n occurrence.starts_at AS occurrence_starts_at,\n occurrence.ends_at AS occurrence_ends_at,\n occurrence.start_date AS occurrence_start_date,\n occurrence.end_date AS occurrence_end_date,\n occurrence.is_cancelled,\n override.title AS override_title,\n override.description AS override_description,\n override.location AS override_location,\n override.status AS override_status,\n event.owner_id,\n event.ical_uid,\n event.title,\n event.description,\n event.location,\n event.status,\n event.visibility,\n event.transparency,\n event.event_type,\n event.starts_at,\n event.ends_at,\n event.start_date,\n event.end_date,\n event.time_zone,\n event.recurrence_lines,\n event.organizer_email,\n event.organizer_name,\n event.creator_email,\n event.creator_name,\n event.conference_url,\n event.conference_provider,\n COALESCE(override.sequence, event.sequence) AS \"sequence!\",\n event.is_read_only,\n event.reminders_use_default,\n event.reminder_overrides,\n event.created_at,\n COALESCE(override.source_updated_at, event.updated_at) AS \"updated_at!\"\n FROM unnest($2::uuid[], $3::text[]) requested(event_id, occurrence_key)\n JOIN calendar_events event ON event.id = requested.event_id\n JOIN LATERAL (\n SELECT o.* FROM calendar_event_occurrences o\n WHERE o.event_id = event.id\n AND o.occurrence_key = requested.occurrence_key\n ORDER BY o.occurrence_key LIMIT 1\n ) occurrence ON true\n LEFT JOIN calendar_event_overrides override\n ON override.event_id = occurrence.event_id\n AND override.recurrence_id = occurrence.recurrence_id\n WHERE event.owner_id = $1\n",
+ "query": " SELECT\n occurrence.event_id,\n event.source_link_id,\n occurrence.occurrence_key,\n occurrence.recurrence_id,\n occurrence.starts_at AS occurrence_starts_at,\n occurrence.ends_at AS occurrence_ends_at,\n occurrence.start_date AS occurrence_start_date,\n occurrence.end_date AS occurrence_end_date,\n occurrence.is_cancelled,\n override.title AS override_title,\n override.description AS override_description,\n override.location AS override_location,\n override.status AS override_status,\n event.owner_id,\n event.ical_uid,\n event.title,\n event.description,\n event.location,\n event.status,\n event.visibility,\n event.transparency,\n event.event_type,\n event.starts_at,\n event.ends_at,\n event.start_date,\n event.end_date,\n event.time_zone,\n event.recurrence_lines,\n event.organizer_email,\n event.organizer_name,\n event.creator_email,\n event.creator_name,\n event.conference_url,\n event.conference_provider,\n COALESCE(override.sequence, event.sequence) AS \"sequence!\",\n event.is_read_only,\n event.reminders_use_default,\n event.reminder_overrides,\n event.created_at,\n COALESCE(override.source_updated_at, event.updated_at) AS \"updated_at!\"\n FROM unnest($2::uuid[], $3::text[]) requested(event_id, occurrence_key)\n JOIN calendar_events event ON event.id = requested.event_id\n JOIN LATERAL (\n SELECT o.* FROM calendar_event_occurrences o\n WHERE o.event_id = event.id\n AND o.occurrence_key = requested.occurrence_key\n ORDER BY o.occurrence_key LIMIT 1\n ) occurrence ON true\n LEFT JOIN calendar_event_overrides override\n ON override.event_id = occurrence.event_id\n AND override.recurrence_id = occurrence.recurrence_id\n WHERE event.owner_id = $1\n",
"describe": {
"columns": [
{
@@ -10,191 +10,196 @@
},
{
"ordinal": 1,
+ "name": "source_link_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
"name": "occurrence_key",
"type_info": "Text"
},
{
- "ordinal": 2,
+ "ordinal": 3,
"name": "recurrence_id",
"type_info": "Text"
},
{
- "ordinal": 3,
+ "ordinal": 4,
"name": "occurrence_starts_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 4,
+ "ordinal": 5,
"name": "occurrence_ends_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 5,
+ "ordinal": 6,
"name": "occurrence_start_date",
"type_info": "Date"
},
{
- "ordinal": 6,
+ "ordinal": 7,
"name": "occurrence_end_date",
"type_info": "Date"
},
{
- "ordinal": 7,
+ "ordinal": 8,
"name": "is_cancelled",
"type_info": "Bool"
},
{
- "ordinal": 8,
+ "ordinal": 9,
"name": "override_title",
"type_info": "Text"
},
{
- "ordinal": 9,
+ "ordinal": 10,
"name": "override_description",
"type_info": "Text"
},
{
- "ordinal": 10,
+ "ordinal": 11,
"name": "override_location",
"type_info": "Text"
},
{
- "ordinal": 11,
+ "ordinal": 12,
"name": "override_status",
"type_info": "Text"
},
{
- "ordinal": 12,
+ "ordinal": 13,
"name": "owner_id",
"type_info": "Text"
},
{
- "ordinal": 13,
+ "ordinal": 14,
"name": "ical_uid",
"type_info": "Text"
},
{
- "ordinal": 14,
+ "ordinal": 15,
"name": "title",
"type_info": "Text"
},
{
- "ordinal": 15,
+ "ordinal": 16,
"name": "description",
"type_info": "Text"
},
{
- "ordinal": 16,
+ "ordinal": 17,
"name": "location",
"type_info": "Text"
},
{
- "ordinal": 17,
+ "ordinal": 18,
"name": "status",
"type_info": "Text"
},
{
- "ordinal": 18,
+ "ordinal": 19,
"name": "visibility",
"type_info": "Text"
},
{
- "ordinal": 19,
+ "ordinal": 20,
"name": "transparency",
"type_info": "Text"
},
{
- "ordinal": 20,
+ "ordinal": 21,
"name": "event_type",
"type_info": "Text"
},
{
- "ordinal": 21,
+ "ordinal": 22,
"name": "starts_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 22,
+ "ordinal": 23,
"name": "ends_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 23,
+ "ordinal": 24,
"name": "start_date",
"type_info": "Date"
},
{
- "ordinal": 24,
+ "ordinal": 25,
"name": "end_date",
"type_info": "Date"
},
{
- "ordinal": 25,
+ "ordinal": 26,
"name": "time_zone",
"type_info": "Text"
},
{
- "ordinal": 26,
+ "ordinal": 27,
"name": "recurrence_lines",
"type_info": "TextArray"
},
{
- "ordinal": 27,
+ "ordinal": 28,
"name": "organizer_email",
"type_info": "Text"
},
{
- "ordinal": 28,
+ "ordinal": 29,
"name": "organizer_name",
"type_info": "Text"
},
{
- "ordinal": 29,
+ "ordinal": 30,
"name": "creator_email",
"type_info": "Text"
},
{
- "ordinal": 30,
+ "ordinal": 31,
"name": "creator_name",
"type_info": "Text"
},
{
- "ordinal": 31,
+ "ordinal": 32,
"name": "conference_url",
"type_info": "Text"
},
{
- "ordinal": 32,
+ "ordinal": 33,
"name": "conference_provider",
"type_info": "Text"
},
{
- "ordinal": 33,
+ "ordinal": 34,
"name": "sequence!",
"type_info": "Int4"
},
{
- "ordinal": 34,
+ "ordinal": 35,
"name": "is_read_only",
"type_info": "Bool"
},
{
- "ordinal": 35,
+ "ordinal": 36,
"name": "reminders_use_default",
"type_info": "Bool"
},
{
- "ordinal": 36,
+ "ordinal": 37,
"name": "reminder_overrides",
"type_info": "Jsonb"
},
{
- "ordinal": 37,
+ "ordinal": 38,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 38,
+ "ordinal": 39,
"name": "updated_at!",
"type_info": "Timestamptz"
}
@@ -207,6 +212,7 @@
]
},
"nullable": [
+ false,
false,
false,
true,
@@ -248,5 +254,5 @@
null
]
},
- "hash": "71e0b73492a384d376d7b54cebe950e93398140d96f30e491a0008a591188792"
+ "hash": "341970aa3de5e15886614551d3c08dd4d856c65e8f975a8a7028cba1050726cc"
}
diff --git a/.sqlx/query-f2f9657c67f343270a00e21cc7f073c3bdcc5f0ba844efe92f021de000315337.json b/.sqlx/query-97fd0f2e89afaf79048a3bb68662549fdf234b5716e83c7a972f9eaf4018852f.json
similarity index 59%
rename from .sqlx/query-f2f9657c67f343270a00e21cc7f073c3bdcc5f0ba844efe92f021de000315337.json
rename to .sqlx/query-97fd0f2e89afaf79048a3bb68662549fdf234b5716e83c7a972f9eaf4018852f.json
index 45a91184cb..0fcda6a58d 100644
--- a/.sqlx/query-f2f9657c67f343270a00e21cc7f073c3bdcc5f0ba844efe92f021de000315337.json
+++ b/.sqlx/query-97fd0f2e89afaf79048a3bb68662549fdf234b5716e83c7a972f9eaf4018852f.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT l.id as \"id!\", l.macro_id as \"macro_id!\",\n l.email_address as \"email_address!\",\n l.provider as \"provider!: _\",\n l.is_sync_active as \"is_sync_active!\",\n l.needs_reauth as \"needs_reauth!\",\n l.is_primary as \"is_primary!\",\n l.created_at as \"created_at!\",\n l.updated_at as \"updated_at!\",\n s.signature_on_replies_forwards as \"signature_on_replies_forwards?\",\n s.signature,\n bj.status as \"latest_backfill_status?: _\",\n c.sfs_photo_url as \"photo_url?\"\n FROM (\n SELECT el.id, el.macro_id, el.email_address, el.provider,\n el.is_sync_active, el.needs_reauth, el.is_primary,\n el.created_at, el.updated_at\n FROM email_links el\n WHERE el.macro_id = $1\n UNION\n SELECT el.id, el.macro_id, el.email_address, el.provider,\n el.is_sync_active, el.needs_reauth, el.is_primary,\n el.created_at, el.updated_at\n FROM email_links el\n JOIN macro_user_links mul ON el.id = mul.link_id\n WHERE mul.primary_macro_id = $1\n ) l\n LEFT JOIN email_settings s ON s.link_id = l.id\n LEFT JOIN LATERAL (\n SELECT status FROM email_backfill_jobs\n WHERE link_id = l.id\n ORDER BY created_at DESC\n LIMIT 1\n ) bj ON true\n LEFT JOIN email_contacts c\n ON c.link_id = l.id AND LOWER(c.email_address) = LOWER(l.email_address)\n ORDER BY l.created_at DESC\n ",
+ "query": "\n SELECT l.id as \"id!\", l.macro_id as \"macro_id!\",\n l.email_address as \"email_address!\",\n l.provider as \"provider!: _\",\n l.is_sync_active as \"is_sync_active!\",\n l.needs_reauth as \"needs_reauth!\",\n l.is_primary as \"is_primary!\",\n l.created_at as \"created_at!\",\n l.updated_at as \"updated_at!\",\n s.signature_on_replies_forwards as \"signature_on_replies_forwards?\",\n s.signature,\n bj.status as \"latest_backfill_status?: _\",\n c.sfs_photo_url as \"photo_url?\",\n COALESCE(g.granted_scopes, '{}') AS \"google_granted_scopes!\",\n (g.calendar_disabled_at IS NOT NULL) AS \"calendar_disabled!\",\n EXISTS (\n SELECT 1 FROM calendar_accounts ca WHERE ca.email_link_id = l.id\n ) AS \"has_calendar_data!\"\n FROM (\n SELECT el.id, el.macro_id, el.email_address, el.provider,\n el.is_sync_active, el.needs_reauth, el.is_primary,\n el.created_at, el.updated_at\n FROM email_links el\n WHERE el.macro_id = $1\n UNION\n SELECT el.id, el.macro_id, el.email_address, el.provider,\n el.is_sync_active, el.needs_reauth, el.is_primary,\n el.created_at, el.updated_at\n FROM email_links el\n JOIN macro_user_links mul ON el.id = mul.link_id\n WHERE mul.primary_macro_id = $1\n ) l\n LEFT JOIN email_link_google_scopes g ON g.link_id = l.id\n LEFT JOIN email_settings s ON s.link_id = l.id\n LEFT JOIN LATERAL (\n SELECT status FROM email_backfill_jobs\n WHERE link_id = l.id\n ORDER BY created_at DESC\n LIMIT 1\n ) bj ON true\n LEFT JOIN email_contacts c\n ON c.link_id = l.id AND LOWER(c.email_address) = LOWER(l.email_address)\n ORDER BY l.created_at DESC\n ",
"describe": {
"columns": [
{
@@ -89,6 +89,21 @@
"ordinal": 12,
"name": "photo_url?",
"type_info": "Text"
+ },
+ {
+ "ordinal": 13,
+ "name": "google_granted_scopes!",
+ "type_info": "TextArray"
+ },
+ {
+ "ordinal": 14,
+ "name": "calendar_disabled!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 15,
+ "name": "has_calendar_data!",
+ "type_info": "Bool"
}
],
"parameters": {
@@ -109,8 +124,11 @@
false,
true,
false,
- true
+ true,
+ null,
+ null,
+ null
]
},
- "hash": "f2f9657c67f343270a00e21cc7f073c3bdcc5f0ba844efe92f021de000315337"
+ "hash": "97fd0f2e89afaf79048a3bb68662549fdf234b5716e83c7a972f9eaf4018852f"
}
diff --git a/Cargo.lock b/Cargo.lock
index dae7c7a519..7284db5bca 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4461,12 +4461,14 @@ dependencies = [
"async-stream",
"axum",
"bots",
+ "calendar_events",
"chrono",
"email",
"entity_access",
"entity_mutation",
"favorites",
"graphql_activity",
+ "graphql_calendar",
"graphql_channel",
"graphql_common",
"graphql_email",
@@ -6244,6 +6246,7 @@ dependencies = [
"futures",
"github",
"github_pull_requests",
+ "graphql_calendar",
"graphql_initiative",
"graphql_scheduled_action",
"graphql_soup",
@@ -8517,6 +8520,25 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "graphql_calendar"
+version = "0.1.0"
+dependencies = [
+ "async-graphql",
+ "calendar_events",
+ "chrono",
+ "futures",
+ "graphql_common",
+ "macro_user_id",
+ "models_pagination",
+ "rootcause",
+ "serde_json",
+ "tokio",
+ "tracing",
+ "uuid",
+ "workspace-hack",
+]
+
[[package]]
name = "graphql_channel"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 725a5d921d..bd78bd4e5b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -58,6 +58,7 @@ members = [
"crates/gmail_client",
"crates/google_token",
"crates/graphql_activity",
+ "crates/graphql_calendar",
"crates/graphql_channel",
"crates/graphql_common",
"crates/graphql_email",
diff --git a/crates/calendar_events/src/domain/models.rs b/crates/calendar_events/src/domain/models.rs
index e8cdbfbec0..a1f36e5fd5 100644
--- a/crates/calendar_events/src/domain/models.rs
+++ b/crates/calendar_events/src/domain/models.rs
@@ -806,6 +806,68 @@ impl CalendarOccurrenceCursor {
}
}
+/// What an exception replaces on one listed occurrence of a series. A field
+/// left `None` inherits the series value.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct OccurrenceException {
+ /// Replacement title.
+ pub title: Option<String>,
+ /// Replacement description.
+ pub description: Option<String>,
+ /// Replacement location.
+ pub location: Option<String>,
+ /// Replacement status.
+ pub status: Option<EventStatus>,
+ /// Instance-scoped attendee list replacing the series list for this
+ /// occurrence alone.
+ pub attendees: Option<Vec<CalendarAttendee>>,
+}
+
+impl OccurrenceException {
+ /// The content this exception replaces on its occurrence.
+ pub fn content(&self) -> OccurrenceContent<'_> {
+ OccurrenceContent {
+ title: self.title.as_deref(),
+ description: self.description.as_deref(),
+ location: self.location.as_deref(),
+ status: self.status,
+ }
+ }
+}
+
+/// One occurrence of a viewport query: the series event as stored, the
+/// instance, the instance's exception, and the connected inbox the event
+/// syncs through.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct OccurrenceListing {
+ /// The series event, without the occurrence's exception applied.
+ pub event: CalendarEvent,
+ /// The materialized instance.
+ pub occurrence: CalendarOccurrence,
+ /// Connected inbox whose grant backs the event (`source_link_id`).
+ pub link_id: Uuid,
+ /// The instance's exception content, empty when it has none.
+ pub exception: OccurrenceException,
+}
+
+impl OccurrenceListing {
+ /// Read the series event as this occurrence: the exception's content and
+ /// attendee list replace the series values.
+ pub fn into_occurrence_event(self) -> (CalendarEvent, CalendarOccurrence) {
+ let Self {
+ mut event,
+ occurrence,
+ exception,
+ ..
+ } = self;
+ event.apply_occurrence_content(exception.content());
+ if let Some(attendees) = exception.attendees {
+ event.attendees = attendees;
+ }
+ (event, occurrence)
+ }
+}
+
/// One teammate's out-of-office occurrence, read from the projection their
/// own connected primary calendar synced.
#[derive(Clone, Debug, PartialEq, Eq)]
diff --git a/crates/calendar_events/src/domain/mutations/test.rs b/crates/calendar_events/src/domain/mutations/test.rs
index 216ce5760d..18e0f42ac3 100644
--- a/crates/calendar_events/src/domain/mutations/test.rs
+++ b/crates/calendar_events/src/domain/mutations/test.rs
@@ -2,11 +2,11 @@ use super::*;
use crate::domain::models::{
ActorInboxes, AppliedGoogleGrant, CalendarAttendee, CalendarAttendeeInput,
CalendarBackfillJobKey, CalendarCreationTarget, CalendarEventOverride, CalendarEventSource,
- CalendarLinkTokenIdentity, CalendarOccurrence, CalendarOccurrenceCursor, CalendarSyncStatus,
- CalendarWatchRelease, ConferenceChange, DisconnectedGoogleCalendar, EventStart, EventStatus,
- EventTransparency, EventType, EventVisibility, GoogleCalendarSyncSnapshot,
- GoogleCalendarTarget, GoogleEventSource, GoogleWatchChannel, OutOfOfficeAutoDeclineMode,
- OutOfOfficeProperties, ProviderCalendar, StoredGoogleCalendar, VisibleCalendar,
+ CalendarLinkTokenIdentity, CalendarOccurrenceCursor, CalendarSyncStatus, CalendarWatchRelease,
+ ConferenceChange, DisconnectedGoogleCalendar, EventStart, EventStatus, EventTransparency,
+ EventType, EventVisibility, GoogleCalendarSyncSnapshot, GoogleCalendarTarget,
+ GoogleEventSource, GoogleWatchChannel, OutOfOfficeAutoDeclineMode, OutOfOfficeProperties,
+ ProviderCalendar, StoredGoogleCalendar, VisibleCalendar,
};
use crate::domain::ports::RetiredCalendarEvent;
use chrono::{Duration, TimeZone};
@@ -226,7 +226,7 @@ impl CalendarRepository for FakeRepo {
_range: OccurrenceRange,
_cursor: Option<CalendarOccurrenceCursor>,
_limit: u16,
- ) -> Result<Vec<(CalendarEvent, CalendarOccurrence)>, rootcause::Report> {
+ ) -> Result<Vec<crate::domain::models::OccurrenceListing>, rootcause::Report> {
unreachable!()
}
diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rs
index 553e9de2b8..91d31cfd95 100644
--- a/crates/calendar_events/src/domain/ports.rs
+++ b/crates/calendar_events/src/domain/ports.rs
@@ -12,12 +12,12 @@ use super::models::{
CalendarBackfillJobKey, CalendarCreationTarget, CalendarEvent, CalendarEventDraft,
CalendarEventMutationTarget, CalendarEventPatch, CalendarEventUpsert, CalendarGrantIntent,
CalendarLinkTokenIdentity, CalendarMentionPreview, CalendarMentionRequestItem,
- CalendarOccurrence, CalendarOccurrenceCursor, CalendarReminderDeliveryOutcome,
- CalendarReminderDispatchMessage, CalendarReminderFiring, CalendarReminderSweepSummary,
- CalendarSyncStatus, DisconnectedGoogleCalendar, DueCalendarReminder,
- GoogleCalendarSyncSnapshot, GoogleCalendarTarget, GoogleEventSyncBatch, GoogleScopeSet,
- GoogleSyncPlan, GoogleWatchChannel, GoogleWatchConfig, OccurrenceRange, ProviderCalendar,
- StoredGoogleCalendar, TeamOutOfOffice, VisibleCalendar,
+ CalendarOccurrenceCursor, CalendarReminderDeliveryOutcome, CalendarReminderDispatchMessage,
+ CalendarReminderFiring, CalendarReminderSweepSummary, CalendarSyncStatus,
+ DisconnectedGoogleCalendar, DueCalendarReminder, GoogleCalendarSyncSnapshot,
+ GoogleCalendarTarget, GoogleEventSyncBatch, GoogleScopeSet, GoogleSyncPlan, GoogleWatchChannel,
+ GoogleWatchConfig, OccurrenceListing, OccurrenceRange, ProviderCalendar, StoredGoogleCalendar,
+ TeamOutOfOffice, VisibleCalendar,
};
/// Classification supplied by provider adapters to backfill policy.
@@ -312,7 +312,7 @@ pub trait CalendarOccurrenceService: Send + Sync + 'static {
range: OccurrenceRange,
cursor: Option<CalendarOccurrenceCursor>,
limit: u16,
- ) -> impl Future<Output = Result<Vec<(CalendarEvent, CalendarOccurrence)>, Report>> + Send;
+ ) -> impl Future<Output = Result<Vec<OccurrenceListing>, Report>> + Send;
/// Return the aggregate ingestion state of the requester's visible accounts.
fn sync_status(
@@ -320,6 +320,13 @@ pub trait CalendarOccurrenceService: Send + Sync + 'static {
requester_id: &str,
) -> impl Future<Output = Result<CalendarSyncStatus, Report>> + Send;
+ /// List every calendar visible to the requester across owned and
+ /// delegated inboxes, primaries and writables first.
+ fn list_visible_calendars(
+ &self,
+ requester_id: &str,
+ ) -> impl Future<Output = Result<Vec<VisibleCalendar>, Report>> + Send;
+
/// Resolve mentioned events to the requester's own projections, one
/// result per requested item in order.
fn mention_previews(
@@ -430,7 +437,7 @@ pub trait CalendarRepository: Send + Sync + 'static {
range: OccurrenceRange,
cursor: Option<CalendarOccurrenceCursor>,
limit: u16,
- ) -> impl Future<Output = Result<Vec<(CalendarEvent, CalendarOccurrence)>, Report>> + Send;
+ ) -> impl Future<Output = Result<Vec<OccurrenceListing>, Report>> + Send;
/// Return the aggregate ingestion state across the requester's visible accounts.
fn sync_status(
diff --git a/crates/calendar_events/src/domain/service.rs b/crates/calendar_events/src/domain/service.rs
index 328033ebd9..3a6dbad103 100644
--- a/crates/calendar_events/src/domain/service.rs
+++ b/crates/calendar_events/src/domain/service.rs
@@ -88,13 +88,7 @@ where
range: OccurrenceRange,
cursor: Option<CalendarOccurrenceCursor>,
limit: u16,
- ) -> Result<
- Vec<(
- super::models::CalendarEvent,
- super::models::CalendarOccurrence,
- )>,
- Report,
- > {
+ ) -> Result<Vec<super::models::OccurrenceListing>, Report> {
validate_query(&range, limit)?;
let mut rows = self
.repository
@@ -103,8 +97,11 @@ where
if let Some(viewer) =
ActorInboxes::from_owned(self.repository.owned_inbox_emails(requester_id).await?)
{
- for (event, _) in &mut rows {
- viewer.mark_attendees(&mut event.attendees);
+ for listing in &mut rows {
+ viewer.mark_attendees(&mut listing.event.attendees);
+ if let Some(attendees) = &mut listing.exception.attendees {
+ viewer.mark_attendees(attendees);
+ }
}
}
Ok(rows)
@@ -153,6 +150,15 @@ where
self.repository.sync_status(requester_id).await
}
+ /// List every calendar visible to the requester.
+ #[tracing::instrument(skip(self, requester_id), err)]
+ pub async fn list_visible_calendars(
+ &self,
+ requester_id: &str,
+ ) -> Result<Vec<super::models::VisibleCalendar>, Report> {
+ self.repository.list_visible_calendars(requester_id).await
+ }
+
/// Resolve mentioned events to the requester's own projections.
#[tracing::instrument(skip(self, requester_id, items), err)]
pub async fn mention_previews(
@@ -210,15 +216,7 @@ where
range: OccurrenceRange,
cursor: Option<CalendarOccurrenceCursor>,
limit: u16,
- ) -> impl Future<
- Output = Result<
- Vec<(
- super::models::CalendarEvent,
- super::models::CalendarOccurrence,
- )>,
- Report,
- >,
- > + Send {
+ ) -> impl Future<Output = Result<Vec<super::models::OccurrenceListing>, Report>> + Send {
CalendarService::list_occurrences(self, requester_id, range, cursor, limit)
}
@@ -229,6 +227,13 @@ where
CalendarService::sync_status(self, requester_id)
}
+ fn list_visible_calendars(
+ &self,
+ requester_id: &str,
+ ) -> impl Future<Output = Result<Vec<super::models::VisibleCalendar>, Report>> + Send {
+ CalendarService::list_visible_calendars(self, requester_id)
+ }
+
fn mention_previews(
&self,
requester_id: &str,
diff --git a/crates/calendar_events/src/domain/service/test.rs b/crates/calendar_events/src/domain/service/test.rs
index 48c2de26d4..f1294e0018 100644
--- a/crates/calendar_events/src/domain/service/test.rs
+++ b/crates/calendar_events/src/domain/service/test.rs
@@ -76,7 +76,7 @@ impl CalendarRepository for FakeRepo {
_range: OccurrenceRange,
_cursor: Option<CalendarOccurrenceCursor>,
_limit: u16,
- ) -> Result<Vec<(CalendarEvent, CalendarOccurrence)>, Report> {
+ ) -> Result<Vec<crate::domain::models::OccurrenceListing>, Report> {
Ok(Vec::new())
}
diff --git a/crates/calendar_events/src/inbound/axum_router.rs b/crates/calendar_events/src/inbound/axum_router.rs
index d8ef32c595..41c6f497e0 100644
--- a/crates/calendar_events/src/inbound/axum_router.rs
+++ b/crates/calendar_events/src/inbound/axum_router.rs
@@ -224,13 +224,18 @@ where
let next_cursor = has_more
.then(|| occurrences.last())
.flatten()
- .map(|(_, occurrence)| {
- Base64Str::encode_json(CalendarOccurrenceCursor::from_occurrence(occurrence))
- .type_erase()
+ .map(|listing| {
+ Base64Str::encode_json(CalendarOccurrenceCursor::from_occurrence(
+ &listing.occurrence,
+ ))
+ .type_erase()
});
let items = occurrences
.into_iter()
- .map(|(event, occurrence)| CalendarOccurrenceItem { event, occurrence })
+ .map(|listing| {
+ let (event, occurrence) = listing.into_occurrence_event();
+ CalendarOccurrenceItem { event, occurrence }
+ })
.collect();
Ok(Json(CalendarOccurrenceResponse {
diff --git a/crates/calendar_events/src/inbound/toolset/list_calendar_events.rs b/crates/calendar_events/src/inbound/toolset/list_calendar_events.rs
index af3caf4f5b..1fbf9a5cd2 100644
--- a/crates/calendar_events/src/inbound/toolset/list_calendar_events.rs
+++ b/crates/calendar_events/src/inbound/toolset/list_calendar_events.rs
@@ -12,7 +12,7 @@ use serde::{Deserialize, Serialize};
use super::{CalendarToolContext, ToolEventAttendee, description_preview, time_fields};
use crate::domain::{
- models::{CalendarOccurrenceCursor, CalendarSyncStatus, OccurrenceRange},
+ models::{CalendarOccurrenceCursor, CalendarSyncStatus, OccurrenceListing, OccurrenceRange},
ports::{CalendarMutationService, CalendarOccurrenceService},
service::CalendarValidationError,
};
@@ -184,10 +184,11 @@ where
let full_page = rows.len() > usize::from(OCCURRENCES_MAX);
cursor = rows
.last()
- .map(|(_, occurrence)| CalendarOccurrenceCursor::from_occurrence(occurrence));
+ .map(|listing| CalendarOccurrenceCursor::from_occurrence(&listing.occurrence));
occurrences.extend(
rows.into_iter()
- .filter(|(_, occurrence)| !occurrence.is_cancelled),
+ .filter(|listing| !listing.occurrence.is_cancelled)
+ .map(OccurrenceListing::into_occurrence_event),
);
if !full_page {
exhausted = true;
diff --git a/crates/calendar_events/src/inbound/toolset/test.rs b/crates/calendar_events/src/inbound/toolset/test.rs
index 42000f1068..f5a5c86539 100644
--- a/crates/calendar_events/src/inbound/toolset/test.rs
+++ b/crates/calendar_events/src/inbound/toolset/test.rs
@@ -239,8 +239,7 @@ impl CalendarOccurrenceService for MockOccurrences {
_range: OccurrenceRange,
cursor: Option<crate::domain::models::CalendarOccurrenceCursor>,
limit: u16,
- ) -> Result<Vec<(crate::domain::models::CalendarEvent, CalendarOccurrence)>, rootcause::Report>
- {
+ ) -> Result<Vec<crate::domain::models::OccurrenceListing>, rootcause::Report> {
let rows = self.rows.lock().unwrap().clone();
let start = cursor
.map(|cursor| {
@@ -249,7 +248,18 @@ impl CalendarOccurrenceService for MockOccurrences {
.map_or(rows.len(), |position| position + 1)
})
.unwrap_or(0);
- let mut page: Vec<_> = rows.into_iter().skip(start).collect();
+ let mut page: Vec<_> = rows
+ .into_iter()
+ .skip(start)
+ .map(
+ |(event, occurrence)| crate::domain::models::OccurrenceListing {
+ event,
+ occurrence,
+ link_id: uuid::Uuid::nil(),
+ exception: Default::default(),
+ },
+ )
+ .collect();
page.truncate(usize::from(limit));
Ok(page)
}
@@ -261,6 +271,13 @@ impl CalendarOccurrenceService for MockOccurrences {
Ok(self.status)
}
+ async fn list_visible_calendars(
+ &self,
+ _requester_id: &str,
+ ) -> Result<Vec<crate::domain::models::VisibleCalendar>, rootcause::Report> {
+ unreachable!("calendar tools list calendars through the mutation service")
+ }
+
async fn mention_previews(
&self,
_requester_id: &str,
diff --git a/crates/calendar_events/src/outbound/pg.rs b/crates/calendar_events/src/outbound/pg.rs
index 61c256d355..d4991a93b6 100644
--- a/crates/calendar_events/src/outbound/pg.rs
+++ b/crates/calendar_events/src/outbound/pg.rs
@@ -24,8 +24,8 @@ use crate::domain::{
DisconnectedGoogleCalendar, DueCalendarReminder, EventReminderOverride, EventReminders,
EventStart, EventStatus, EventTime, EventTransparency, EventType, EventVisibility,
GOOGLE_CALENDAR_SCOPES, GoogleCalendarSyncSnapshot, GoogleScopeSet, GoogleWatchChannel,
- OccurrenceContent, OccurrenceRange, ProviderCalendar, StoredGoogleCalendar,
- TeamOutOfOffice, VisibleCalendar, is_system_calendar,
+ OccurrenceException, OccurrenceListing, OccurrenceRange, ProviderCalendar,
+ StoredGoogleCalendar, TeamOutOfOffice, VisibleCalendar, is_system_calendar,
},
ports::{
CalendarBackfillRepository, CalendarEventChange, CalendarEventWrite,
@@ -280,6 +280,7 @@ struct StoredCalendarRow {
struct OccurrenceJoinRow {
event_id: Uuid,
+ source_link_id: Uuid,
occurrence_key: String,
recurrence_id: Option<String>,
occurrence_starts_at: Option<DateTime<Utc>>,
@@ -875,7 +876,7 @@ impl CalendarRepository for PgCalendarRepository {
range: OccurrenceRange,
cursor: Option<CalendarOccurrenceCursor>,
limit: u16,
- ) -> Result<Vec<(CalendarEvent, CalendarOccurrence)>, Report> {
+ ) -> 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());
@@ -884,6 +885,7 @@ impl CalendarRepository for PgCalendarRepository {
r#"
SELECT
occurrence.event_id,
+ event.source_link_id,
occurrence.occurrence_key,
occurrence.recurrence_id,
occurrence.starts_at AS occurrence_starts_at,
@@ -988,22 +990,28 @@ impl CalendarRepository for PgCalendarRepository {
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 effective = occurrence
- .recurrence_id
- .as_ref()
- .and_then(|recurrence_id| {
- override_attendees.get(&(event_id, recurrence_id.clone()))
- })
- .or_else(|| attendees.get(&event_id))
- .cloned()
- .unwrap_or_default();
+ 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 event = event_from_join(row, effective, sources)?;
- Ok((event, occurrence))
+ let (event, mut exception) =
+ series_event_from_join(row, series_attendees, sources)?;
+ exception.attendees = exception_attendees;
+ Ok(OccurrenceListing {
+ event,
+ occurrence,
+ link_id,
+ exception,
+ })
})
.collect()
}
@@ -4071,15 +4079,33 @@ fn mention_preview_from_row(row: MentionPreviewRow) -> Result<CalendarMentionPre
}
fn event_from_join(
- mut row: OccurrenceJoinRow,
+ row: OccurrenceJoinRow,
attendees: Vec<CalendarAttendee>,
sources: Vec<CalendarEventSourceContent>,
) -> Result<CalendarEvent, Report> {
- let override_title = row.override_title.take();
- let override_description = row.override_description.take();
- let override_location = row.override_location.take();
- let override_status = row.override_status.take();
- let mut event = CalendarEvent {
+ let (mut event, exception) = 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)
+}
+
+/// Split a joined occurrence row into its series event and the occurrence's
+/// exception content. The exception's attendee list is left to the caller,
+/// which loads attendees in bulk.
+fn series_event_from_join(
+ mut row: OccurrenceJoinRow,
+ attendees: Vec<CalendarAttendee>,
+ sources: Vec<CalendarEventSourceContent>,
+) -> Result<(CalendarEvent, OccurrenceException), Report> {
+ let exception = 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,
+ };
+ let event = CalendarEvent {
id: row.event_id,
owner_id: row.owner_id,
ical_uid: row.ical_uid,
@@ -4120,15 +4146,7 @@ fn event_from_join(
created_at: row.created_at,
updated_at: row.updated_at,
};
- // 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(OccurrenceContent {
- title: override_title.as_deref(),
- description: override_description.as_deref(),
- location: override_location.as_deref(),
- status: override_status.as_deref().map(event_status),
- });
- Ok(event)
+ Ok((event, exception))
}
fn occurrence_from_join(row: &OccurrenceJoinRow) -> Result<CalendarOccurrence, Report> {
diff --git a/crates/calendar_events/src/outbound/pg/invitations.rs b/crates/calendar_events/src/outbound/pg/invitations.rs
index 0dcb6eb422..b52b451fb6 100644
--- a/crates/calendar_events/src/outbound/pg/invitations.rs
+++ b/crates/calendar_events/src/outbound/pg/invitations.rs
@@ -56,6 +56,7 @@ impl CalendarInvitationRepository for PgCalendarRepository {
OccurrenceJoinRow,
r#" SELECT
occurrence.event_id,
+ event.source_link_id,
occurrence.occurrence_key,
occurrence.recurrence_id,
occurrence.starts_at AS occurrence_starts_at,
diff --git a/crates/calendar_events/src/outbound/pg/test.rs b/crates/calendar_events/src/outbound/pg/test.rs
index 3fa3d0194a..3fb601ea03 100644
--- a/crates/calendar_events/src/outbound/pg/test.rs
+++ b/crates/calendar_events/src/outbound/pg/test.rs
@@ -1,7 +1,7 @@
use super::*;
use crate::domain::models::{
GOOGLE_CALENDAR_SCOPES, GoogleCalendarSyncSnapshot, GoogleEventSource, GoogleWatchChannel,
- REMINDER_METHOD_EMAIL, REMINDER_METHOD_POPUP,
+ OccurrenceException, OccurrenceListing, REMINDER_METHOD_EMAIL, REMINDER_METHOD_POPUP,
};
use crate::domain::ports::GoogleCalendarSyncRepository;
use crate::domain::service::{CalendarService, GoogleCalendarBackfillFailureService};
@@ -1008,7 +1008,10 @@ async fn fenced_google_snapshot_removes_deleted_events_and_calendars(pool: PgPoo
100,
)
.await
- .unwrap();
+ .unwrap()
+ .into_iter()
+ .map(OccurrenceListing::into_occurrence_event)
+ .collect::<Vec<_>>();
assert!(occurrences.is_empty());
assert_eq!(
repo.sync_status(owner_id).await.unwrap(),
@@ -1400,7 +1403,10 @@ async fn occurrence_range_uses_overlap_indexes_and_preserves_attendees(pool: PgP
100,
)
.await
- .unwrap();
+ .unwrap()
+ .into_iter()
+ .map(OccurrenceListing::into_occurrence_event)
+ .collect::<Vec<_>>();
assert_eq!(result.len(), 2);
assert!(result.iter().all(|(event, _)| event.attendees.len() == 1));
@@ -1414,6 +1420,104 @@ async fn occurrence_range_uses_overlap_indexes_and_preserves_attendees(pool: PgP
/// instance and never on the series master, so the occurrence carrying that
/// exception must project the exception's attendees while its siblings keep
/// the series answer.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn listing_keeps_the_series_event_beside_the_exception_and_its_link(pool: PgPool) {
+ let owner_id = "macro|[email protected]";
+ let link_id = insert_link(&pool, owner_id).await;
+ let repo = PgCalendarRepository::new(pool);
+ let provider = provider_ids(&repo, link_id).await;
+ let mut upsert = timed_upsert(
+ owner_id,
+ link_id,
+ provider,
+ "Series title",
+ 1,
+ );
+ let attendee = CalendarAttendee {
+ email: "[email protected]".to_string(),
+ display_name: None,
+ response_status: AttendeeResponseStatus::Accepted,
+ is_organizer: false,
+ is_optional: false,
+ is_self: false,
+ comment: None,
+ };
+ upsert.event.attendees.push(attendee.clone());
+ let edited_start = Utc.with_ymd_and_hms(2026, 7, 25, 14, 0, 0).unwrap();
+ let recurrence_id = edited_start.to_rfc3339();
+ upsert.occurrences[1].recurrence_id = Some(recurrence_id.clone());
+ upsert.overrides = vec![CalendarEventOverride {
+ sequence: None,
+ source_updated_at: None,
+ recurrence_id: recurrence_id.clone(),
+ original_time: EventStart::Timed(edited_start),
+ time: EventTime::Timed {
+ starts_at: edited_start,
+ ends_at: edited_start + Duration::hours(1),
+ time_zone: Some("UTC".to_string()),
+ },
+ title: Some("Edited title".to_string()),
+ description: None,
+ location: None,
+ status: Some(EventStatus::Tentative),
+ attendees: Some(vec![CalendarAttendee {
+ response_status: AttendeeResponseStatus::Declined,
+ ..attendee
+ }]),
+ }];
+ repo.upsert_event_fixture(upsert).await.unwrap();
+
+ let starts_at = Utc.with_ymd_and_hms(2026, 7, 24, 0, 0, 0).unwrap();
+ let ends_at = Utc.with_ymd_and_hms(2026, 7, 26, 0, 0, 0).unwrap();
+ let listings = repo
+ .list_occurrences(
+ owner_id,
+ OccurrenceRange {
+ starts_at,
+ ends_at,
+ start_date: starts_at.date_naive(),
+ end_date: ends_at.date_naive(),
+ },
+ None,
+ 100,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(listings.len(), 2);
+ for listing in &listings {
+ assert_eq!(listing.link_id, link_id);
+ assert_eq!(listing.event.title, "Series title");
+ assert_eq!(listing.event.status, EventStatus::Confirmed);
+ assert_eq!(
+ listing.event.attendees[0].response_status,
+ AttendeeResponseStatus::Accepted,
+ "the series event is never rewritten by an exception"
+ );
+ }
+ let exception = listings
+ .iter()
+ .find(|listing| listing.occurrence.occurrence_key == recurrence_id)
+ .map(|listing| &listing.exception)
+ .expect("the exception occurrence is listed");
+ assert_eq!(exception.title.as_deref(), Some("Edited title"));
+ assert_eq!(exception.status, Some(EventStatus::Tentative));
+ assert_eq!(
+ exception
+ .attendees
+ .as_ref()
+ .map(|attendees| attendees[0].response_status),
+ Some(AttendeeResponseStatus::Declined)
+ );
+ let sibling = listings
+ .iter()
+ .find(|listing| listing.occurrence.occurrence_key != recurrence_id)
+ .map(|listing| &listing.exception)
+ .expect("the sibling occurrence is listed");
+ assert_eq!(*sibling, OccurrenceException::default());
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn occurrence_attendee_override_shadows_the_series_response(pool: PgPool) {
let owner_id = "macro|[email protected]";
@@ -1480,7 +1584,10 @@ async fn occurrence_attendee_override_shadows_the_series_response(pool: PgPool)
100,
)
.await
- .unwrap();
+ .unwrap()
+ .into_iter()
+ .map(OccurrenceListing::into_occurrence_event)
+ .collect::<Vec<_>>();
assert_eq!(result.len(), 2);
let response_at = |key: &str| {
@@ -1558,7 +1665,10 @@ async fn occurrence_content_override_shadows_the_series_content(pool: PgPool) {
100,
)
.await
- .unwrap();
+ .unwrap()
+ .into_iter()
+ .map(OccurrenceListing::into_occurrence_event)
+ .collect::<Vec<_>>();
assert_eq!(result.len(), 2);
let content_at = |key: &str| {
@@ -1748,7 +1858,10 @@ async fn explicitly_empty_override_attendees_do_not_inherit_the_series_list(pool
100,
)
.await
- .unwrap();
+ .unwrap()
+ .into_iter()
+ .map(OccurrenceListing::into_occurrence_event)
+ .collect::<Vec<_>>();
assert_eq!(result.len(), 2);
let attendees_at = |key: &str| {
@@ -1792,13 +1905,19 @@ async fn occurrence_cursor_is_stable_when_occurrences_share_a_start(pool: PgPool
let first_page = repo
.list_occurrences(owner_id, range.clone(), None, 2)
.await
- .unwrap();
+ .unwrap()
+ .into_iter()
+ .map(OccurrenceListing::into_occurrence_event)
+ .collect::<Vec<_>>();
assert_eq!(first_page.len(), 2);
let cursor = CalendarOccurrenceCursor::from_occurrence(&first_page[1].1);
let second_page = repo
.list_occurrences(owner_id, range, Some(cursor), 2)
.await
- .unwrap();
+ .unwrap()
+ .into_iter()
+ .map(OccurrenceListing::into_occurrence_event)
+ .collect::<Vec<_>>();
assert_eq!(second_page.len(), 1);
let mut event_ids: Vec<_> = first_page
@@ -2132,6 +2251,9 @@ async fn delegated_inbox_source_grants_calendar_visibility(pool: PgPool) {
repo.list_occurrences(primary_id, range.clone(), None, 100)
.await
.unwrap()
+ .into_iter()
+ .map(OccurrenceListing::into_occurrence_event)
+ .collect::<Vec<_>>()
.len(),
2
);
@@ -2139,6 +2261,9 @@ async fn delegated_inbox_source_grants_calendar_visibility(pool: PgPool) {
repo.list_occurrences("macro|[email protected]", range, None, 100)
.await
.unwrap()
+ .into_iter()
+ .map(OccurrenceListing::into_occurrence_event)
+ .collect::<Vec<_>>()
.is_empty()
);
}
@@ -2203,7 +2328,10 @@ async fn identical_uids_from_distinct_inboxes_remain_distinct_and_link_scoped(po
100,
)
.await
- .unwrap();
+ .unwrap()
+ .into_iter()
+ .map(OccurrenceListing::into_occurrence_event)
+ .collect::<Vec<_>>();
assert_eq!(result.len(), 2);
assert!(
@@ -3832,7 +3960,10 @@ async fn conference_provider_round_trips_through_persistence(pool: PgPool) {
100,
)
.await
- .unwrap();
+ .unwrap()
+ .into_iter()
+ .map(OccurrenceListing::into_occurrence_event)
+ .collect::<Vec<_>>();
let (event, _) = occurrences.first().expect("the event is in range");
assert_eq!(
@@ -5039,7 +5170,10 @@ async fn shared_calendar_copy_records_its_content_without_touching_the_primary_e
let rows = repo
.list_occurrences(member, range_around(starts_at), None, 10)
.await
- .unwrap();
+ .unwrap()
+ .into_iter()
+ .map(OccurrenceListing::into_occurrence_event)
+ .collect::<Vec<_>>();
let (event, _) = rows.first().expect("the merged event lists once");
assert_eq!(rows.len(), 1);
assert_eq!(event.calendar_id, Some(primary_calendar_id));
@@ -5168,7 +5302,10 @@ async fn a_late_primary_sync_reclaims_the_entity_from_a_shared_copy(pool: PgPool
let rows = repo
.list_occurrences(member, range_around(starts_at), None, 10)
.await
- .unwrap();
+ .unwrap()
+ .into_iter()
+ .map(OccurrenceListing::into_occurrence_event)
+ .collect::<Vec<_>>();
assert_eq!(rows[0].0.calendar_id, Some(primary_calendar_id));
assert_eq!(
rows[0]
@@ -5559,7 +5696,10 @@ async fn a_user_edit_through_the_shared_copy_moves_the_schedule_but_keeps_primar
let rows = repo
.list_occurrences(member, range_around(moved_start), None, 10)
.await
- .unwrap();
+ .unwrap()
+ .into_iter()
+ .map(OccurrenceListing::into_occurrence_event)
+ .collect::<Vec<_>>();
let (event, occurrence) = rows.first().expect("the moved occurrence lists");
assert_eq!(rows.len(), 1);
assert_eq!(
@@ -5668,7 +5808,10 @@ async fn canonical_selection_skips_copies_on_deleted_calendars(pool: PgPool) {
let rows = repo
.list_occurrences(member, range_around(starts_at), None, 10)
.await
- .unwrap();
+ .unwrap()
+ .into_iter()
+ .map(OccurrenceListing::into_occurrence_event)
+ .collect::<Vec<_>>();
assert_eq!(rows[0].0.calendar_id, Some(shared_calendar_id));
assert_eq!(
rows[0]
@@ -5759,7 +5902,10 @@ async fn an_older_canonical_resync_cannot_undo_a_user_edit_made_through_another_
let rows = repo
.list_occurrences(member, range_around(moved_start), None, 10)
.await
- .unwrap();
+ .unwrap()
+ .into_iter()
+ .map(OccurrenceListing::into_occurrence_event)
+ .collect::<Vec<_>>();
let (event, occurrence) = rows.first().expect("the moved occurrence lists");
assert_eq!(rows.len(), 1);
assert_eq!(
@@ -5797,7 +5943,10 @@ async fn an_older_canonical_resync_cannot_undo_a_user_edit_made_through_another_
let rows = repo
.list_occurrences(member, range_around(moved_start), None, 10)
.await
- .unwrap();
+ .unwrap()
+ .into_iter()
+ .map(OccurrenceListing::into_occurrence_event)
+ .collect::<Vec<_>>();
assert_eq!(
rows[0].1.time,
EventTime::Timed {
@@ -5833,7 +5982,10 @@ async fn listed_event(
let rows = repo
.list_occurrences(member, range_around(around), None, 10)
.await
- .unwrap();
+ .unwrap()
+ .into_iter()
+ .map(OccurrenceListing::into_occurrence_event)
+ .collect::<Vec<_>>();
assert_eq!(rows.len(), 1, "one occurrence lists");
rows.into_iter().next().unwrap()
}
diff --git a/crates/calendar_scheduling/src/outbound/macro_services.rs b/crates/calendar_scheduling/src/outbound/macro_services.rs
index 746a4c1acf..d82c413533 100644
--- a/crates/calendar_scheduling/src/outbound/macro_services.rs
+++ b/crates/calendar_scheduling/src/outbound/macro_services.rs
@@ -86,10 +86,10 @@ impl<O: CalendarOccurrenceService, M: CalendarCreationRecoveryService> Calendars
if rows.len() > 2000 {
return Err(Error::CalendarUnavailable);
}
- events.extend(
- rows.into_iter()
- .map(|(event, occurrence)| (host.clone(), event, occurrence)),
- );
+ events.extend(rows.into_iter().map(|listing| {
+ let (event, occurrence) = listing.into_occurrence_event();
+ (host.clone(), event, occurrence)
+ }));
}
let excluded_uid = events
.iter()
diff --git a/crates/complete_graph/Cargo.toml b/crates/complete_graph/Cargo.toml
index 76aca34cbf..88a6ccea69 100644
--- a/crates/complete_graph/Cargo.toml
+++ b/crates/complete_graph/Cargo.toml
@@ -25,6 +25,7 @@ entity_access = { path = "../entity_access", default-features = false, features
entity_mutation = { path = "../entity_mutation" }
favorites = { path = "../favorites", default-features = false, features = ["ports"] }
graphql_activity = { path = "../graphql_activity" }
+graphql_calendar = { path = "../graphql_calendar" }
graphql_channel = { path = "../graphql_channel" }
graphql_common = { path = "../graphql_common" }
graphql_email = { path = "../graphql_email" }
@@ -58,6 +59,7 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
activity = { path = "../activity", default-features = false, features = ["realtime"] }
agent_runtime_protocol = { path = "../agent_runtime_protocol" }
apollo-compiler = { workspace = true }
+calendar_events = { path = "../calendar_events" }
chrono = { workspace = true }
model_owner = { path = "../model_owner" }
model_user = { path = "../model_user" }
diff --git a/crates/complete_graph/src/schema.rs b/crates/complete_graph/src/schema.rs
index 40c7e3ca1a..d1174bc326 100644
--- a/crates/complete_graph/src/schema.rs
+++ b/crates/complete_graph/src/schema.rs
@@ -22,6 +22,7 @@ use graphql_activity::{
resolve_activity_feed, resolve_activity_overview, resolve_database_activity,
resolve_form_activity,
};
+use graphql_calendar::GraphqlCalendarQuery;
use graphql_channel::{
ChannelActivityAuthorizer, ChannelActivityMutationService, ChannelMutationRoot,
NoOpChannelActivityMutationService,
@@ -788,6 +789,12 @@ where
resolve_activity_overview::<AcR>(ctx, &self.user_id, input).await
}
+ /// Authenticated user calendar fields supplied by `graphql_calendar`.
+ #[graphql(flatten)]
+ async fn calendar(&self) -> GraphqlCalendarQuery {
+ GraphqlCalendarQuery::new(self.user_id.clone())
+ }
+
/// Authenticated user email catalog fields supplied by `graphql_email`.
#[graphql(flatten)]
async fn email(&self, ctx: &Context<'_>) -> async_graphql::Result<GraphqlEmailQuery<E>> {
diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rs
index 283cf0da16..c2ccc1c35a 100644
--- a/crates/complete_graph/src/schema/test.rs
+++ b/crates/complete_graph/src/schema/test.rs
@@ -44,6 +44,7 @@ use uuid::Uuid;
use super::*;
+mod calendar;
mod database_activity;
mod database_row;
mod email_archive;
@@ -412,6 +413,9 @@ impl EmailUserService for CountingEmailService {
signature: Some("<p>Regards</p>".to_owned()),
},
is_primary: true,
+ needs_calendar_permission: false,
+ calendar_disabled: false,
+ has_calendar_data: true,
created_at: Default::default(),
updated_at: Default::default(),
}])
diff --git a/crates/complete_graph/src/schema/test/calendar.rs b/crates/complete_graph/src/schema/test/calendar.rs
new file mode 100644
index 0000000000..e4dbd21bc1
--- /dev/null
+++ b/crates/complete_graph/src/schema/test/calendar.rs
@@ -0,0 +1,193 @@
+use std::sync::{Arc, Mutex};
+
+use calendar_events::domain::{
+ models::{
+ CalendarEvent, CalendarMentionPreview, CalendarMentionRequestItem, CalendarOccurrence,
+ CalendarOccurrenceCursor, CalendarSyncStatus, EventReminders, EventStatus, EventTime,
+ EventTransparency, EventType, EventVisibility, OccurrenceException, OccurrenceListing,
+ OccurrenceRange, TeamOutOfOffice, VisibleCalendar,
+ },
+ ports::CalendarOccurrenceService,
+};
+use chrono::TimeZone;
+use graphql_calendar::CalendarGraphqlContext;
+use rootcause::Report;
+
+use super::*;
+
+const EVENT_ID: Uuid = Uuid::from_u128(0xe1);
+const LINK_ID: Uuid = Uuid::from_u128(0x11);
+
+#[derive(Default)]
+struct RecordingCalendarReads {
+ viewers: Mutex<Vec<String>>,
+}
+
+fn listing() -> OccurrenceListing {
+ let starts_at = chrono::Utc.with_ymd_and_hms(2026, 10, 6, 15, 0, 0).unwrap();
+ let time = EventTime::Timed {
+ starts_at,
+ ends_at: starts_at + chrono::Duration::hours(1),
+ time_zone: None,
+ };
+ OccurrenceListing {
+ event: CalendarEvent {
+ id: EVENT_ID,
+ owner_id: VALID_USER_ID.to_owned(),
+ ical_uid: "[email protected]".to_owned(),
+ calendar_id: None,
+ sources: Vec::new(),
+ title: "Planning".to_owned(),
+ description: None,
+ location: None,
+ status: EventStatus::Confirmed,
+ visibility: EventVisibility::Default,
+ transparency: EventTransparency::Opaque,
+ event_type: EventType::Default,
+ time: time.clone(),
+ recurrence_lines: Vec::new(),
+ organizer_email: None,
+ organizer_name: None,
+ creator_email: None,
+ creator_name: None,
+ conference_url: None,
+ conference_provider: None,
+ sequence: 0,
+ is_read_only: false,
+ attendees: Vec::new(),
+ reminders: EventReminders::default(),
+ created_at: starts_at,
+ updated_at: starts_at,
+ },
+ occurrence: CalendarOccurrence {
+ event_id: EVENT_ID,
+ occurrence_key: time.occurrence_key(),
+ recurrence_id: None,
+ time,
+ is_cancelled: false,
+ },
+ link_id: LINK_ID,
+ exception: OccurrenceException::default(),
+ }
+}
+
+impl CalendarOccurrenceService for RecordingCalendarReads {
+ async fn list_occurrences(
+ &self,
+ requester_id: &str,
+ _range: OccurrenceRange,
+ _cursor: Option<CalendarOccurrenceCursor>,
+ _limit: u16,
+ ) -> Result<Vec<OccurrenceListing>, Report> {
+ self.viewers.lock().unwrap().push(requester_id.to_owned());
+ Ok(vec![listing()])
+ }
+
+ async fn sync_status(&self, _requester_id: &str) -> Result<CalendarSyncStatus, Report> {
+ Ok(CalendarSyncStatus::Ready)
+ }
+
+ async fn list_visible_calendars(
+ &self,
+ requester_id: &str,
+ ) -> Result<Vec<VisibleCalendar>, Report> {
+ self.viewers.lock().unwrap().push(requester_id.to_owned());
+ Ok(vec![VisibleCalendar {
+ id: Uuid::from_u128(0xca),
+ email_link_id: LINK_ID,
+ email_address: "[email protected]".to_owned(),
+ name: "Work".to_owned(),
+ color: None,
+ is_primary: true,
+ is_writable: true,
+ is_subscription: false,
+ sync_error: None,
+ default_reminders: Vec::new(),
+ }])
+ }
+
+ async fn mention_previews(
+ &self,
+ _requester_id: &str,
+ _items: Vec<CalendarMentionRequestItem>,
+ ) -> Result<Vec<CalendarMentionPreview>, Report> {
+ unreachable!("not part of the calendar user fields")
+ }
+
+ async fn list_team_out_of_office(
+ &self,
+ _requester_id: &str,
+ _range: OccurrenceRange,
+ _limit: u16,
+ ) -> Result<Vec<TeamOutOfOffice>, Report> {
+ unreachable!("not part of the calendar user fields")
+ }
+
+ async fn primary_time_zone(&self, _requester_id: &str) -> Result<Option<String>, Report> {
+ unreachable!("not part of the calendar user fields")
+ }
+}
+
+#[tokio::test]
+async fn calendar_fields_read_through_request_data_for_the_viewer() {
+ let harness = harness();
+ let reads = Arc::new(RecordingCalendarReads::default());
+ let context = CalendarGraphqlContext::new(Arc::clone(&reads));
+
+ let id_only = harness
+ .schema
+ .execute(
+ harness
+ .request("{ user { id } }", authenticated_parts())
+ .data(context.clone()),
+ )
+ .await;
+ assert!(id_only.errors.is_empty(), "{:?}", id_only.errors);
+ assert!(reads.viewers.lock().unwrap().is_empty());
+
+ let response = harness
+ .schema
+ .execute(
+ harness
+ .request(
+ r#"{ user {
+ id
+ calendars { id linkId }
+ calendarOccurrences(input: {
+ start: "2026-10-05T00:00:00Z", end: "2026-10-12T00:00:00Z"
+ }) {
+ nodes { id eventId linkId event { id title } }
+ hasNextPage syncStatus
+ }
+ } }"#,
+ authenticated_parts(),
+ )
+ .data(context),
+ )
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let data = response.data.into_json().unwrap();
+ let user = &data["user"];
+ assert_eq!(user["calendars"][0]["linkId"], LINK_ID.to_string());
+ let node = &user["calendarOccurrences"]["nodes"][0];
+ assert_eq!(node["id"], format!("{EVENT_ID}:2026-10-06T15:00:00+00:00"));
+ assert_eq!(node["event"]["title"], "Planning");
+ assert_eq!(user["calendarOccurrences"]["syncStatus"], "READY");
+ assert_eq!(
+ *reads.viewers.lock().unwrap(),
+ vec![VALID_USER_ID.to_owned(), VALID_USER_ID.to_owned()]
+ );
+}
+
+#[tokio::test]
+async fn calendar_fields_fail_without_the_calendar_context() {
+ let harness = harness();
+
+ let response = harness
+ .schema
+ .execute(harness.request("{ user { id calendars { id } } }", authenticated_parts()))
+ .await;
+
+ assert_eq!(response.errors.len(), 1);
+}
diff --git a/crates/complete_graph/src/sdl_test.rs b/crates/complete_graph/src/sdl_test.rs
index 2e86a2d907..3f14904080 100644
--- a/crates/complete_graph/src/sdl_test.rs
+++ b/crates/complete_graph/src/sdl_test.rs
@@ -710,6 +710,54 @@ fn scheduled_actions_hang_off_the_authenticated_user() {
);
}
+#[test]
+fn calendar_reads_hang_off_the_authenticated_user() {
+ use apollo_compiler::schema::ExtendedType;
+
+ let sdl = crate::build_schema().sdl();
+ for expected in [
+ "calendars: [GraphqlCalendar!]!",
+ "calendarOccurrences(input: CalendarRangeInput!): GraphqlCalendarOccurrencePage!",
+ "union GraphqlEventTime = GraphqlTimedEventTime | GraphqlAllDayEventTime",
+ "watermark: [GraphqlCalendarLinkWatermark!]!",
+ "needsCalendarPermission: Boolean!",
+ "calendarDisabled: Boolean!",
+ "hasCalendarData: Boolean!",
+ ] {
+ assert_sdl_line(&sdl, expected);
+ }
+
+ let schema = apollo_compiler::Schema::parse_and_validate(sdl.as_str(), "schema.graphql")
+ .expect("generated SDL is valid");
+ let ExtendedType::Object(occurrence) = schema
+ .types
+ .get("GraphqlCalendarOccurrence")
+ .expect("occurrence type")
+ else {
+ panic!("GraphqlCalendarOccurrence must be an object");
+ };
+ for scalar in ["id", "eventId", "linkId"] {
+ assert_eq!(occurrence.fields[scalar].ty.to_string(), "ID!");
+ }
+ assert_eq!(
+ occurrence.fields["event"].ty.to_string(),
+ "GraphqlCalendarEvent!"
+ );
+ for entity in ["GraphqlCalendarEvent", "GraphqlCalendar"] {
+ let ExtendedType::Object(object) = schema.types.get(entity).expect("entity type") else {
+ panic!("{entity} must be an object");
+ };
+ assert_eq!(object.fields["id"].ty.to_string(), "ID!");
+ assert_eq!(object.fields["linkId"].ty.to_string(), "ID!");
+ }
+
+ let ExtendedType::Object(root) = schema.types.get("SoupQueryRoot").expect("query root") else {
+ panic!("SoupQueryRoot must be an object");
+ };
+ assert!(!root.fields.contains_key("calendars"));
+ assert!(!root.fields.contains_key("calendarOccurrences"));
+}
+
/// The exported SDL is a frontend contract: `schema.graphql` feeds the client
/// codegen and the normalized-cache metadata. Splitting the schema across
/// crates must never change it silently — regenerate with
diff --git a/crates/email/Cargo.toml b/crates/email/Cargo.toml
index 17b9441d11..34be3ea1cf 100644
--- a/crates/email/Cargo.toml
+++ b/crates/email/Cargo.toml
@@ -38,7 +38,7 @@ axum = [
gmail_token = ["dep:authentication_service_client", "dep:google_token", "dep:redis", "ports"]
http_client = ["dep:reqwest", "ports"]
inbound = ["ports"]
-outbound = ["dep:sqlx", "ports"]
+outbound = ["dep:calendar_events", "dep:sqlx", "ports"]
ports = ["crm/ports", "dep:tokio", "frecency/ports"]
[dependencies]
diff --git a/crates/email/src/domain/models/link.rs b/crates/email/src/domain/models/link.rs
index 156ecf9662..9bfb0884d0 100644
--- a/crates/email/src/domain/models/link.rs
+++ b/crates/email/src/domain/models/link.rs
@@ -107,6 +107,12 @@ pub struct EmailInboxDetails {
pub is_primary: bool,
/// Latest initial backfill status, when one exists.
pub latest_backfill_status: Option<EmailBackfillStatus>,
+ /// Whether the recorded Google grant lacks the calendar capability.
+ pub needs_calendar_permission: bool,
+ /// Whether the owner turned the inbox's calendar off.
+ pub calendar_disabled: bool,
+ /// Whether a calendar account has been provisioned for the inbox.
+ pub has_calendar_data: bool,
/// Link creation timestamp.
pub created_at: DateTime<Utc>,
/// Link last-updated timestamp.
@@ -141,6 +147,12 @@ pub struct UserEmailLink {
pub settings: UserEmailLinkSettings,
/// Whether this is the owner's primary inbox.
pub is_primary: bool,
+ /// Whether the recorded Google grant lacks the calendar capability.
+ pub needs_calendar_permission: bool,
+ /// Whether the owner turned the inbox's calendar off.
+ pub calendar_disabled: bool,
+ /// Whether a calendar account has been provisioned for the inbox.
+ pub has_calendar_data: bool,
/// Link creation timestamp.
pub created_at: DateTime<Utc>,
/// Link last-updated timestamp.
@@ -167,6 +179,9 @@ impl UserEmailLink {
needs_reauth: details.needs_reauth,
settings: details.settings,
is_primary: details.is_primary,
+ needs_calendar_permission: details.needs_calendar_permission,
+ calendar_disabled: details.calendar_disabled,
+ has_calendar_data: details.has_calendar_data,
created_at: details.created_at,
updated_at: details.updated_at,
}
diff --git a/crates/email/src/domain/service/user/test.rs b/crates/email/src/domain/service/user/test.rs
index c142040bb6..cac3e19924 100644
--- a/crates/email/src/domain/service/user/test.rs
+++ b/crates/email/src/domain/service/user/test.rs
@@ -158,6 +158,9 @@ async fn links_are_scoped_to_the_user_and_enriched_by_domain_policy() {
},
is_primary: true,
latest_backfill_status: Some(EmailBackfillStatus::InProgress),
+ needs_calendar_permission: true,
+ calendar_disabled: true,
+ has_calendar_data: true,
created_at: now,
updated_at: now,
}],
diff --git a/crates/email/src/outbound/email_pg_repo/link.rs b/crates/email/src/outbound/email_pg_repo/link.rs
index 6974960bee..b81bfd98cb 100644
--- a/crates/email/src/outbound/email_pg_repo/link.rs
+++ b/crates/email/src/outbound/email_pg_repo/link.rs
@@ -1,6 +1,7 @@
use crate::domain::models::{
EmailBackfillStatus, EmailInboxDetails, Link, UserEmailLinkSettings, UserProvider,
};
+use calendar_events::domain::models::GoogleScopeSet;
use chrono::{DateTime, Utc};
use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};
use sqlx::PgPool;
@@ -221,6 +222,12 @@ struct DbInboxDetailsRow {
latest_backfill_status: Option<DbEmailBackfillStatus>,
/// SFS URL of the inbox's self-contact photo.
photo_url: Option<String>,
+ /// Google scopes recorded for the link's grant.
+ google_granted_scopes: Vec<String>,
+ /// Whether the owner turned the inbox's calendar off.
+ calendar_disabled: bool,
+ /// Whether a calendar account has been provisioned for the inbox.
+ has_calendar_data: bool,
}
impl DbInboxDetailsRow {
@@ -248,6 +255,10 @@ impl DbInboxDetailsRow {
DbEmailBackfillStatus::Cancelled => EmailBackfillStatus::Cancelled,
DbEmailBackfillStatus::Failed => EmailBackfillStatus::Failed,
}),
+ needs_calendar_permission: !GoogleScopeSet::from_scopes(self.google_granted_scopes)
+ .has_calendar_capability(),
+ calendar_disabled: self.calendar_disabled,
+ has_calendar_data: self.has_calendar_data,
created_at: self.created_at,
updated_at: self.updated_at,
})
@@ -275,7 +286,12 @@ pub(super) async fn inbox_details_for_macro_id(
s.signature_on_replies_forwards as "signature_on_replies_forwards?",
s.signature,
bj.status as "latest_backfill_status?: _",
- c.sfs_photo_url as "photo_url?"
+ c.sfs_photo_url as "photo_url?",
+ COALESCE(g.granted_scopes, '{}') AS "google_granted_scopes!",
+ (g.calendar_disabled_at IS NOT NULL) AS "calendar_disabled!",
+ EXISTS (
+ SELECT 1 FROM calendar_accounts ca WHERE ca.email_link_id = l.id
+ ) AS "has_calendar_data!"
FROM (
SELECT el.id, el.macro_id, el.email_address, el.provider,
el.is_sync_active, el.needs_reauth, el.is_primary,
@@ -290,6 +306,7 @@ pub(super) async fn inbox_details_for_macro_id(
JOIN macro_user_links mul ON el.id = mul.link_id
WHERE mul.primary_macro_id = $1
) l
+ LEFT JOIN email_link_google_scopes g ON g.link_id = l.id
LEFT JOIN email_settings s ON s.link_id = l.id
LEFT JOIN LATERAL (
SELECT status FROM email_backfill_jobs
diff --git a/crates/email/src/outbound/email_pg_repo/test/link.rs b/crates/email/src/outbound/email_pg_repo/test/link.rs
index d5835e2791..69b3ca6ed1 100644
--- a/crates/email/src/outbound/email_pg_repo/test/link.rs
+++ b/crates/email/src/outbound/email_pg_repo/test/link.rs
@@ -227,6 +227,38 @@ async fn user_inbox_details_maps_enriched_owned_inbox(pool: Pool<Postgres>) -> a
inbox.photo_url.as_deref(),
Some("https://example.com/inbox.png")
);
+ assert!(inbox.needs_calendar_permission);
+ assert!(!inbox.calendar_disabled);
+ assert!(!inbox.has_calendar_data);
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn user_inbox_details_reports_the_calendar_grant(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let scopes = calendar_events::domain::models::GOOGLE_CALENDAR_SCOPES.map(str::to_owned);
+ sqlx::query!(
+ r#"
+ INSERT INTO email_link_google_scopes (link_id, granted_scopes, calendar_disabled_at)
+ VALUES ($1, $2, now())
+ "#,
+ link_id,
+ &scopes,
+ )
+ .execute(&pool)
+ .await?;
+
+ let details = EmailPgRepo::new(pool)
+ .user_inbox_details(MacroUserIdStr::parse_from_str("macro|[email protected]")?)
+ .await?;
+
+ let inbox = &details[0];
+ assert!(!inbox.needs_calendar_permission);
+ assert!(inbox.calendar_disabled);
+ assert!(!inbox.has_calendar_data);
Ok(())
}
diff --git a/crates/graphql_calendar/Cargo.toml b/crates/graphql_calendar/Cargo.toml
new file mode 100644
index 0000000000..7681ab993d
--- /dev/null
+++ b/crates/graphql_calendar/Cargo.toml
@@ -0,0 +1,22 @@
+[package]
+name = "graphql_calendar"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[dependencies]
+async-graphql = { workspace = true }
+calendar_events = { path = "../calendar_events" }
+chrono = { workspace = true }
+futures = { workspace = true }
+graphql_common = { path = "../graphql_common" }
+macro_user_id = { path = "../macro_user_id" }
+models_pagination = { path = "../models_pagination" }
+rootcause = { workspace = true }
+tracing = { workspace = true }
+uuid = { workspace = true }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[dev-dependencies]
+serde_json = { workspace = true }
+tokio = { workspace = true, features = ["macros", "rt"] }
diff --git a/crates/graphql_calendar/src/inputs.rs b/crates/graphql_calendar/src/inputs.rs
new file mode 100644
index 0000000000..4d8ff6b2dd
--- /dev/null
+++ b/crates/graphql_calendar/src/inputs.rs
@@ -0,0 +1,108 @@
+use async_graphql::InputObject;
+use calendar_events::domain::models::{CalendarOccurrenceCursor, OccurrenceRange};
+use chrono::{DateTime, NaiveDate, NaiveTime, Utc};
+use models_pagination::Base64Str;
+
+use crate::bad_input;
+
+#[cfg(test)]
+mod test;
+
+/// Largest page `calendarOccurrences` returns.
+const MAX_PAGE_SIZE: u16 = 2000;
+/// Page size when `first` is omitted.
+const DEFAULT_PAGE_SIZE: u16 = 1000;
+
+/// A bounded occurrence viewport and page request.
+#[derive(InputObject, Clone, Debug)]
+pub struct CalendarRangeInput {
+ /// Inclusive UTC viewport start in RFC 3339 format.
+ pub start: String,
+ /// Exclusive UTC viewport end in RFC 3339 format.
+ pub end: String,
+ /// Inclusive local date boundary for all-day events (`YYYY-MM-DD`).
+ /// Defaults to the date of `start`.
+ pub start_date: Option<String>,
+ /// Exclusive local date boundary for all-day events (`YYYY-MM-DD`).
+ /// Defaults to the first date at or after `end`.
+ pub end_date: Option<String>,
+ /// Page size, from 1 through 2,000. Defaults to 1,000.
+ pub first: Option<i32>,
+ /// `endCursor` of the previous page.
+ pub after: Option<String>,
+}
+
+/// A validated occurrence page request.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct OccurrencePageRequest {
+ pub(crate) range: OccurrenceRange,
+ pub(crate) cursor: Option<CalendarOccurrenceCursor>,
+ pub(crate) page_size: u16,
+}
+
+impl CalendarRangeInput {
+ pub(crate) fn into_page_request(self) -> async_graphql::Result<OccurrencePageRequest> {
+ let starts_at = parse_instant(&self.start, "start")?;
+ let ends_at = parse_instant(&self.end, "end")?;
+ let start_date = match self.start_date {
+ Some(value) => parse_date(&value, "startDate")?,
+ None => starts_at.date_naive(),
+ };
+ let end_date = match self.end_date {
+ Some(value) => parse_date(&value, "endDate")?,
+ None => default_end_date(ends_at)
+ .ok_or_else(|| bad_input("calendar end is outside the supported date range"))?,
+ };
+ Ok(OccurrencePageRequest {
+ range: OccurrenceRange {
+ starts_at,
+ ends_at,
+ start_date,
+ end_date,
+ },
+ cursor: self.after.map(decode_cursor).transpose()?,
+ page_size: page_size(self.first)?,
+ })
+ }
+}
+
+pub(crate) fn encode_cursor(cursor: CalendarOccurrenceCursor) -> String {
+ Base64Str::encode_json(cursor).type_erase()
+}
+
+fn decode_cursor(cursor: String) -> async_graphql::Result<CalendarOccurrenceCursor> {
+ Base64Str::new_from_string(cursor)
+ .decode_json()
+ .map_err(|_| bad_input("calendar cursor is invalid"))
+}
+
+fn page_size(first: Option<i32>) -> async_graphql::Result<u16> {
+ let Some(first) = first else {
+ return Ok(DEFAULT_PAGE_SIZE);
+ };
+ u16::try_from(first)
+ .ok()
+ .filter(|size| (1..=MAX_PAGE_SIZE).contains(size))
+ .ok_or_else(|| bad_input("calendar page size must be between 1 and 2000"))
+}
+
+fn parse_instant(value: &str, field: &str) -> async_graphql::Result<DateTime<Utc>> {
+ DateTime::parse_from_rfc3339(value)
+ .map(|instant| instant.with_timezone(&Utc))
+ .map_err(|_| bad_input(format!("{field} must be an RFC 3339 instant")))
+}
+
+fn parse_date(value: &str, field: &str) -> async_graphql::Result<NaiveDate> {
+ NaiveDate::parse_from_str(value, "%Y-%m-%d")
+ .map_err(|_| bad_input(format!("{field} must be a YYYY-MM-DD date")))
+}
+
+/// The all-day boundary that covers every instant before `end`: its own date
+/// at midnight, else the following date.
+fn default_end_date(end: DateTime<Utc>) -> Option<NaiveDate> {
+ if end.time() == NaiveTime::MIN {
+ Some(end.date_naive())
+ } else {
+ end.date_naive().succ_opt()
+ }
+}
diff --git a/crates/graphql_calendar/src/inputs/test.rs b/crates/graphql_calendar/src/inputs/test.rs
new file mode 100644
index 0000000000..59071c1a5f
--- /dev/null
+++ b/crates/graphql_calendar/src/inputs/test.rs
@@ -0,0 +1,125 @@
+use calendar_events::domain::models::CalendarOccurrenceCursor;
+use chrono::{NaiveDate, TimeZone, Utc};
+use uuid::Uuid;
+
+use super::*;
+
+fn input(start: &str, end: &str) -> CalendarRangeInput {
+ CalendarRangeInput {
+ start: start.to_owned(),
+ end: end.to_owned(),
+ start_date: None,
+ end_date: None,
+ first: None,
+ after: None,
+ }
+}
+
+fn error_code(error: async_graphql::Error) -> String {
+ let extensions = error.extensions.expect("extensions");
+ extensions.get("code").expect("code").to_string()
+}
+
+#[test]
+fn defaults_dates_and_page_size_from_the_instants() {
+ let request = input("2026-10-05T04:00:00Z", "2026-10-12T04:00:00Z")
+ .into_page_request()
+ .unwrap();
+
+ assert_eq!(request.page_size, 1000);
+ assert_eq!(request.cursor, None);
+ assert_eq!(
+ request.range.starts_at,
+ Utc.with_ymd_and_hms(2026, 10, 5, 4, 0, 0).unwrap()
+ );
+ assert_eq!(
+ request.range.start_date,
+ NaiveDate::from_ymd_opt(2026, 10, 5).unwrap()
+ );
+ assert_eq!(
+ request.range.end_date,
+ NaiveDate::from_ymd_opt(2026, 10, 13).unwrap()
+ );
+}
+
+#[test]
+fn a_midnight_end_keeps_its_own_date_as_the_exclusive_bound() {
+ let request = input("2026-10-05T00:00:00Z", "2026-10-12T00:00:00Z")
+ .into_page_request()
+ .unwrap();
+
+ assert_eq!(
+ request.range.end_date,
+ NaiveDate::from_ymd_opt(2026, 10, 12).unwrap()
+ );
+}
+
+#[test]
+fn explicit_local_dates_win_and_offsets_normalize_to_utc() {
+ let mut range = input("2026-10-05T00:00:00-04:00", "2026-10-12T00:00:00-04:00");
+ range.start_date = Some("2026-10-05".to_owned());
+ range.end_date = Some("2026-10-12".to_owned());
+
+ let request = range.into_page_request().unwrap();
+
+ assert_eq!(
+ request.range.starts_at,
+ Utc.with_ymd_and_hms(2026, 10, 5, 4, 0, 0).unwrap()
+ );
+ assert_eq!(
+ request.range.end_date,
+ NaiveDate::from_ymd_opt(2026, 10, 12).unwrap()
+ );
+}
+
+#[test]
+fn page_size_is_bounded() {
+ for first in [0, -1, 2001] {
+ let mut range = input("2026-10-05T00:00:00Z", "2026-10-12T00:00:00Z");
+ range.first = Some(first);
+ let error = range.into_page_request().unwrap_err();
+ assert_eq!(error_code(error), "\"BAD_USER_INPUT\"");
+ }
+ let mut range = input("2026-10-05T00:00:00Z", "2026-10-12T00:00:00Z");
+ range.first = Some(2000);
+ assert_eq!(range.into_page_request().unwrap().page_size, 2000);
+}
+
+#[test]
+fn malformed_values_are_user_errors() {
+ for (start, end, end_date, after) in [
+ ("yesterday", "2026-10-12T00:00:00Z", None, None),
+ ("2026-10-05T00:00:00Z", "2026-10-12", None, None),
+ (
+ "2026-10-05T00:00:00Z",
+ "2026-10-12T00:00:00Z",
+ Some("10/12/2026"),
+ None,
+ ),
+ (
+ "2026-10-05T00:00:00Z",
+ "2026-10-12T00:00:00Z",
+ None,
+ Some("not-a-cursor"),
+ ),
+ ] {
+ let mut range = input(start, end);
+ range.end_date = end_date.map(str::to_owned);
+ range.after = after.map(str::to_owned);
+ let error = range.into_page_request().unwrap_err();
+ assert_eq!(error_code(error), "\"BAD_USER_INPUT\"");
+ }
+}
+
+#[test]
+fn cursor_round_trips() {
+ let cursor = CalendarOccurrenceCursor {
+ starts_at: Utc.with_ymd_and_hms(2026, 10, 6, 15, 0, 0).unwrap(),
+ event_id: Uuid::from_u128(9),
+ occurrence_key: "2026-10-06T15:00:00+00:00".to_owned(),
+ };
+ let mut range = input("2026-10-05T00:00:00Z", "2026-10-12T00:00:00Z");
+ range.after = Some(encode_cursor(cursor.clone()));
+
+ assert_eq!(range.into_page_request().unwrap().cursor, Some(cursor));
+}
diff --git a/crates/graphql_calendar/src/lib.rs b/crates/graphql_calendar/src/lib.rs
new file mode 100644
index 0000000000..522c9776a6
--- /dev/null
+++ b/crates/graphql_calendar/src/lib.rs
@@ -0,0 +1,38 @@
+//! GraphQL inbound adapter for calendars: typed calendar, event, and
+//! occurrence objects and the authenticated user's calendar read fields.
+#![deny(missing_docs)]
+
+mod inputs;
+mod objects;
+mod reads;
+#[cfg(test)]
+mod test_fixtures;
+mod user_query;
+
+pub use inputs::CalendarRangeInput;
+pub use objects::{
+ GraphqlAllDayEventTime, GraphqlCalendar, GraphqlCalendarAttendee,
+ GraphqlCalendarAttendeeResponseStatus, GraphqlCalendarConferenceProvider, GraphqlCalendarEvent,
+ GraphqlCalendarEventSource, GraphqlCalendarEventStatus, GraphqlCalendarEventTransparency,
+ GraphqlCalendarEventType, GraphqlCalendarEventVisibility, GraphqlCalendarLinkWatermark,
+ GraphqlCalendarOccurrence, GraphqlCalendarOccurrencePage, GraphqlCalendarReminderOverride,
+ GraphqlCalendarReminders, GraphqlCalendarSyncStatus, GraphqlEventTime, GraphqlTimedEventTime,
+};
+pub use reads::CalendarGraphqlContext;
+pub use user_query::GraphqlCalendarQuery;
+
+use async_graphql::ErrorExtensions;
+use rootcause::Report;
+
+pub(crate) fn bad_input(message: impl Into<String>) -> async_graphql::Error {
+ async_graphql::Error::new(message.into()).extend_with(|_, extensions| {
+ extensions.set("code", "BAD_USER_INPUT");
+ })
+}
+
+pub(crate) fn unavailable(error: Report, message: &'static str) -> async_graphql::Error {
+ tracing::error!(error = ?error, "{message}");
+ async_graphql::Error::new(message).extend_with(|_, extensions| {
+ extensions.set("code", "INTERNAL_SERVER_ERROR");
+ })
+}
diff --git a/crates/graphql_calendar/src/objects.rs b/crates/graphql_calendar/src/objects.rs
new file mode 100644
index 0000000000..355bb45d78
--- /dev/null
+++ b/crates/graphql_calendar/src/objects.rs
@@ -0,0 +1,576 @@
+use async_graphql::{Enum, ID, SimpleObject, Union};
+use calendar_events::domain::models::{
+ AttendeeResponseStatus, CalendarAttendee, CalendarEvent, CalendarEventSourceContent,
+ CalendarOccurrence, CalendarSyncStatus, ConferenceProvider, EventReminderOverride,
+ EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility,
+ OccurrenceListing, VisibleCalendar,
+};
+use uuid::Uuid;
+
+#[cfg(test)]
+mod test;
+
+/// Event status.
+#[derive(Enum, Copy, Clone, Debug, Eq, PartialEq)]
+pub enum GraphqlCalendarEventStatus {
+ /// The event is confirmed.
+ Confirmed,
+ /// The event is tentatively confirmed.
+ Tentative,
+ /// The event was cancelled.
+ Cancelled,
+}
+
+impl From<EventStatus> for GraphqlCalendarEventStatus {
+ fn from(status: EventStatus) -> Self {
+ match status {
+ EventStatus::Confirmed => Self::Confirmed,
+ EventStatus::Tentative => Self::Tentative,
+ EventStatus::Cancelled => Self::Cancelled,
+ }
+ }
+}
+
+/// Event visibility.
+#[derive(Enum, Copy, Clone, Debug, Eq, PartialEq)]
+pub enum GraphqlCalendarEventVisibility {
+ /// The calendar's default visibility.
+ Default,
+ /// Visible to everyone with access to the calendar.
+ Public,
+ /// Details visible only to attendees.
+ Private,
+ /// Treated as private.
+ Confidential,
+}
+
+impl From<EventVisibility> for GraphqlCalendarEventVisibility {
+ fn from(visibility: EventVisibility) -> Self {
+ match visibility {
+ EventVisibility::Default => Self::Default,
+ EventVisibility::Public => Self::Public,
+ EventVisibility::Private => Self::Private,
+ EventVisibility::Confidential => Self::Confidential,
+ }
+ }
+}
+
+/// Whether the event blocks time on the calendar.
+#[derive(Enum, Copy, Clone, Debug, Eq, PartialEq)]
+pub enum GraphqlCalendarEventTransparency {
+ /// The event blocks time.
+ Opaque,
+ /// The event does not block time.
+ Transparent,
+}
+
+impl From<EventTransparency> for GraphqlCalendarEventTransparency {
+ fn from(transparency: EventTransparency) -> Self {
+ match transparency {
+ EventTransparency::Opaque => Self::Opaque,
+ EventTransparency::Transparent => Self::Transparent,
+ }
+ }
+}
+
+/// Provider event type.
+#[derive(Enum, Copy, Clone, Debug, Eq, PartialEq)]
+pub enum GraphqlCalendarEventType {
+ /// A regular event.
+ Default,
+ /// An out-of-office block.
+ OutOfOffice,
+ /// A focus-time block.
+ FocusTime,
+ /// A working-location marker.
+ WorkingLocation,
+ /// A contact's birthday.
+ Birthday,
+ /// An event Gmail created from an email.
+ FromGmail,
+}
+
+impl From<EventType> for GraphqlCalendarEventType {
+ fn from(event_type: EventType) -> Self {
+ match event_type {
+ EventType::Default => Self::Default,
+ EventType::OutOfOffice => Self::OutOfOffice,
+ EventType::FocusTime => Self::FocusTime,
+ EventType::WorkingLocation => Self::WorkingLocation,
+ EventType::Birthday => Self::Birthday,
+ EventType::FromGmail => Self::FromGmail,
+ }
+ }
+}
+
+/// Conferencing system backing an event's join URL.
+#[derive(Enum, Copy, Clone, Debug, Eq, PartialEq)]
+pub enum GraphqlCalendarConferenceProvider {
+ /// Google Meet.
+ GoogleMeet,
+ /// Any other conferencing system.
+ Other,
+}
+
+impl From<ConferenceProvider> for GraphqlCalendarConferenceProvider {
+ fn from(provider: ConferenceProvider) -> Self {
+ match provider {
+ ConferenceProvider::GoogleMeet => Self::GoogleMeet,
+ ConferenceProvider::Other => Self::Other,
+ }
+ }
+}
+
+/// An attendee's RSVP.
+#[derive(Enum, Copy, Clone, Debug, Eq, PartialEq)]
+pub enum GraphqlCalendarAttendeeResponseStatus {
+ /// The attendee has not responded.
+ NeedsAction,
+ /// The attendee accepted.
+ Accepted,
+ /// The attendee declined.
+ Declined,
+ /// The attendee tentatively accepted.
+ Tentative,
+}
+
+impl From<AttendeeResponseStatus> for GraphqlCalendarAttendeeResponseStatus {
+ fn from(status: AttendeeResponseStatus) -> Self {
+ match status {
+ AttendeeResponseStatus::NeedsAction => Self::NeedsAction,
+ AttendeeResponseStatus::Accepted => Self::Accepted,
+ AttendeeResponseStatus::Declined => Self::Declined,
+ AttendeeResponseStatus::Tentative => Self::Tentative,
+ }
+ }
+}
+
+/// Aggregate ingestion state across every calendar account visible to the
+/// viewer.
+#[derive(Enum, Copy, Clone, Debug, Eq, PartialEq)]
+pub enum GraphqlCalendarSyncStatus {
+ /// At least one visible calendar account is still ingesting.
+ Syncing,
+ /// Every visible calendar account has finished its latest sync.
+ Ready,
+}
+
+impl From<CalendarSyncStatus> for GraphqlCalendarSyncStatus {
+ fn from(status: CalendarSyncStatus) -> Self {
+ match status {
+ CalendarSyncStatus::Syncing => Self::Syncing,
+ CalendarSyncStatus::Ready => Self::Ready,
+ }
+ }
+}
+
+/// A span with absolute instants.
+#[derive(SimpleObject, Clone, Debug, PartialEq, Eq)]
+pub struct GraphqlTimedEventTime {
+ /// Inclusive start instant in RFC 3339 format.
+ starts_at: String,
+ /// Exclusive end instant in RFC 3339 format.
+ ends_at: String,
+ /// Original IANA time-zone identifier, when supplied.
+ time_zone: Option<String>,
+}
+
+/// An all-day span using RFC 5545's exclusive end date.
+#[derive(SimpleObject, Clone, Debug, PartialEq, Eq)]
+pub struct GraphqlAllDayEventTime {
+ /// Inclusive local start date (`YYYY-MM-DD`).
+ start_date: String,
+ /// Exclusive local end date (`YYYY-MM-DD`).
+ end_date: String,
+}
+
+/// The mutually exclusive time shape of an event or occurrence.
+#[derive(Union, Clone, Debug, PartialEq, Eq)]
+pub enum GraphqlEventTime {
+ /// A span with absolute instants.
+ Timed(GraphqlTimedEventTime),
+ /// An all-day span.
+ AllDay(GraphqlAllDayEventTime),
+}
+
+impl From<EventTime> for GraphqlEventTime {
+ fn from(time: EventTime) -> Self {
+ match time {
+ EventTime::Timed {
+ starts_at,
+ ends_at,
+ time_zone,
+ } => Self::Timed(GraphqlTimedEventTime {
+ starts_at: starts_at.to_rfc3339(),
+ ends_at: ends_at.to_rfc3339(),
+ time_zone,
+ }),
+ EventTime::AllDay {
+ start_date,
+ end_date,
+ } => Self::AllDay(GraphqlAllDayEventTime {
+ start_date: start_date.to_string(),
+ end_date: end_date.to_string(),
+ }),
+ }
+ }
+}
+
+/// One event attendee.
+#[derive(SimpleObject, Clone, Debug, PartialEq, Eq)]
+pub struct GraphqlCalendarAttendee {
+ /// Attendee email address.
+ email: String,
+ /// Attendee display name.
+ display_name: Option<String>,
+ /// The attendee's RSVP.
+ response_status: GraphqlCalendarAttendeeResponseStatus,
+ /// Whether the attendee organizes the event.
+ is_organizer: bool,
+ /// Whether the attendee is optional.
+ is_optional: bool,
+ /// Whether the attendee is one of the viewer's own connected inboxes.
+ is_self: bool,
+ /// The attendee's RSVP comment.
+ comment: Option<String>,
+}
+
+impl From<CalendarAttendee> for GraphqlCalendarAttendee {
+ fn from(attendee: CalendarAttendee) -> Self {
+ Self {
+ email: attendee.email,
+ display_name: attendee.display_name,
+ response_status: attendee.response_status.into(),
+ is_organizer: attendee.is_organizer,
+ is_optional: attendee.is_optional,
+ is_self: attendee.is_self,
+ comment: attendee.comment,
+ }
+ }
+}
+
+/// One reminder override.
+#[derive(SimpleObject, Clone, Debug, PartialEq, Eq)]
+pub struct GraphqlCalendarReminderOverride {
+ /// Delivery method (`popup` or `email`).
+ method: String,
+ /// Minutes before the start the reminder fires.
+ minutes: i32,
+}
+
+impl From<EventReminderOverride> for GraphqlCalendarReminderOverride {
+ fn from(reminder: EventReminderOverride) -> Self {
+ Self {
+ method: reminder.method,
+ minutes: i32::try_from(reminder.minutes).unwrap_or(i32::MAX),
+ }
+ }
+}
+
+/// An event's reminder configuration.
+#[derive(SimpleObject, Clone, Debug, PartialEq, Eq)]
+pub struct GraphqlCalendarReminders {
+ /// Whether the calendar's default reminders apply.
+ use_default: bool,
+ /// Explicit reminders, used when `useDefault` is false.
+ overrides: Vec<GraphqlCalendarReminderOverride>,
+}
+
+impl From<EventReminders> for GraphqlCalendarReminders {
+ fn from(reminders: EventReminders) -> Self {
+ Self {
+ use_default: reminders.use_default,
+ overrides: reminders.overrides.into_iter().map(Into::into).collect(),
+ }
+ }
+}
+
+/// Content of one calendar's copy of an event.
+#[derive(SimpleObject, Clone, Debug, PartialEq, Eq)]
+pub struct GraphqlCalendarEventSource {
+ /// Calendar this copy lives on.
+ calendar_id: ID,
+ /// Display title.
+ title: String,
+ /// Optional event body.
+ description: Option<String>,
+ /// Optional physical or virtual location label.
+ location: Option<String>,
+ /// Provider event type.
+ event_type: GraphqlCalendarEventType,
+ /// Event visibility.
+ visibility: GraphqlCalendarEventVisibility,
+ /// Availability behavior.
+ transparency: GraphqlCalendarEventTransparency,
+ /// Whether the calendar's access role prohibits editing this copy.
+ is_read_only: bool,
+ /// Reminder configuration of this copy.
+ reminders: GraphqlCalendarReminders,
+ /// Provider-reported creator email.
+ creator_email: Option<String>,
+ /// Provider-reported creator display name.
+ creator_name: Option<String>,
+}
+
+impl From<CalendarEventSourceContent> for GraphqlCalendarEventSource {
+ fn from(source: CalendarEventSourceContent) -> Self {
+ Self {
+ calendar_id: id(source.calendar_id),
+ title: source.title,
+ description: source.description,
+ location: source.location,
+ event_type: source.event_type.into(),
+ visibility: source.visibility.into(),
+ transparency: source.transparency.into(),
+ is_read_only: source.is_read_only,
+ reminders: source.reminders.into(),
+ creator_email: source.creator_email,
+ creator_name: source.creator_name,
+ }
+ }
+}
+
+/// A calendar event entity: the series content shared by every occurrence.
+#[derive(SimpleObject, Clone, Debug, PartialEq, Eq)]
+pub struct GraphqlCalendarEvent {
+ /// Macro event identifier.
+ id: ID,
+ /// Macro user who owns this event projection.
+ owner_id: String,
+ /// Connected inbox whose grant backs the event.
+ link_id: ID,
+ /// RFC 5545 UID used to reconcile provider and email sources.
+ ical_uid: String,
+ /// Calendar the canonical source belongs to, when known.
+ calendar_id: Option<ID>,
+ /// Content of every active copy of this event, canonical first.
+ sources: Vec<GraphqlCalendarEventSource>,
+ /// Display title.
+ title: String,
+ /// Optional event body.
+ description: Option<String>,
+ /// Optional physical or virtual location label.
+ location: Option<String>,
+ /// Event status.
+ status: GraphqlCalendarEventStatus,
+ /// Event visibility.
+ visibility: GraphqlCalendarEventVisibility,
+ /// Availability behavior.
+ transparency: GraphqlCalendarEventTransparency,
+ /// Provider event type.
+ event_type: GraphqlCalendarEventType,
+ /// The series time span.
+ time: GraphqlEventTime,
+ /// Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`).
+ recurrence_lines: Vec<String>,
+ /// Organizer email.
+ organizer_email: Option<String>,
+ /// Organizer display name.
+ organizer_name: Option<String>,
+ /// Provider-reported creator email.
+ creator_email: Option<String>,
+ /// Provider-reported creator display name.
+ creator_name: Option<String>,
+ /// Direct join URL when known.
+ conference_url: Option<String>,
+ /// Which conferencing system backs `conferenceUrl`.
+ conference_provider: Option<GraphqlCalendarConferenceProvider>,
+ /// Provider/iCalendar sequence number.
+ sequence: i32,
+ /// Whether the canonical source's calendar prohibits editing it.
+ is_read_only: bool,
+ /// Series attendees.
+ attendees: Vec<GraphqlCalendarAttendee>,
+ /// Reminder configuration.
+ reminders: GraphqlCalendarReminders,
+ /// Entity creation time in RFC 3339 format.
+ created_at: String,
+ /// Entity update time in RFC 3339 format.
+ updated_at: String,
+}
+
+impl GraphqlCalendarEvent {
+ /// Map a series event synced through `link_id`.
+ pub fn new(event: CalendarEvent, link_id: Uuid) -> Self {
+ Self {
+ id: id(event.id),
+ owner_id: event.owner_id,
+ link_id: id(link_id),
+ ical_uid: event.ical_uid,
+ calendar_id: event.calendar_id.map(id),
+ sources: event.sources.into_iter().map(Into::into).collect(),
+ title: event.title,
+ description: event.description,
+ location: event.location,
+ status: event.status.into(),
+ visibility: event.visibility.into(),
+ transparency: event.transparency.into(),
+ event_type: event.event_type.into(),
+ time: event.time.into(),
+ recurrence_lines: event.recurrence_lines,
+ organizer_email: event.organizer_email,
+ organizer_name: event.organizer_name,
+ creator_email: event.creator_email,
+ creator_name: event.creator_name,
+ conference_url: event.conference_url,
+ conference_provider: event.conference_provider.map(Into::into),
+ sequence: i32::try_from(event.sequence).unwrap_or(i32::MAX),
+ is_read_only: event.is_read_only,
+ attendees: event.attendees.into_iter().map(Into::into).collect(),
+ reminders: event.reminders.into(),
+ created_at: event.created_at.to_rfc3339(),
+ updated_at: event.updated_at.to_rfc3339(),
+ }
+ }
+}
+
+/// One materialized instance of a calendar event.
+///
+/// `eventId` and `linkId` repeat the event's identity as scalars so a client
+/// range index can project occurrences without dereferencing the event.
+#[derive(SimpleObject, Clone, Debug, PartialEq, Eq)]
+pub struct GraphqlCalendarOccurrence {
+ /// `{eventId}:{occurrenceKey}`.
+ id: ID,
+ /// Owning event identifier.
+ event_id: ID,
+ /// Connected inbox whose grant backs the event.
+ link_id: ID,
+ /// The series event.
+ event: GraphqlCalendarEvent,
+ /// Stable key within the event.
+ occurrence_key: String,
+ /// Provider recurrence identifier, when applicable.
+ recurrence_id: Option<String>,
+ /// Instance time.
+ time: GraphqlEventTime,
+ /// Whether the instance was cancelled.
+ is_cancelled: bool,
+ /// Title replacing the series title on this instance alone.
+ override_title: Option<String>,
+ /// Description replacing the series description on this instance alone.
+ override_description: Option<String>,
+ /// Location replacing the series location on this instance alone.
+ override_location: Option<String>,
+ /// Status replacing the series status on this instance alone.
+ override_status: Option<GraphqlCalendarEventStatus>,
+ /// Attendee list replacing the series list on this instance alone, where
+ /// an instance-scoped RSVP is recorded.
+ override_attendees: Option<Vec<GraphqlCalendarAttendee>>,
+}
+
+impl From<OccurrenceListing> for GraphqlCalendarOccurrence {
+ fn from(listing: OccurrenceListing) -> Self {
+ let OccurrenceListing {
+ event,
+ occurrence,
+ link_id,
+ exception,
+ } = listing;
+ let CalendarOccurrence {
+ event_id,
+ occurrence_key,
+ recurrence_id,
+ time,
+ is_cancelled,
+ } = occurrence;
+ Self {
+ id: occurrence_id(event_id, &occurrence_key),
+ event_id: id(event_id),
+ link_id: id(link_id),
+ event: GraphqlCalendarEvent::new(event, link_id),
+ occurrence_key,
+ recurrence_id,
+ time: time.into(),
+ is_cancelled,
+ override_title: exception.title,
+ override_description: exception.description,
+ override_location: exception.location,
+ override_status: exception.status.map(Into::into),
+ override_attendees: exception
+ .attendees
+ .map(|attendees| attendees.into_iter().map(Into::into).collect()),
+ }
+ }
+}
+
+/// A calendar visible to the viewer.
+#[derive(SimpleObject, Clone, Debug, PartialEq, Eq)]
+pub struct GraphqlCalendar {
+ /// Macro calendar identifier.
+ id: ID,
+ /// Connected inbox that syncs this calendar.
+ link_id: ID,
+ /// Connected inbox address.
+ email_address: String,
+ /// Provider display name.
+ name: String,
+ /// Provider color.
+ color: Option<String>,
+ /// Whether this is its account's primary calendar.
+ is_primary: bool,
+ /// Whether the grant can create and modify events on this calendar.
+ is_writable: bool,
+ /// Whether this is a shared system calendar (holidays, birthdays).
+ is_subscription: bool,
+ /// A persistent sync failure isolated to this calendar.
+ sync_error: Option<String>,
+ /// Default reminders applied to events that keep `useDefault`.
+ default_reminders: Vec<GraphqlCalendarReminderOverride>,
+}
+
+impl From<VisibleCalendar> for GraphqlCalendar {
+ fn from(calendar: VisibleCalendar) -> Self {
+ Self {
+ id: id(calendar.id),
+ link_id: id(calendar.email_link_id),
+ email_address: calendar.email_address,
+ name: calendar.name,
+ color: calendar.color,
+ is_primary: calendar.is_primary,
+ is_writable: calendar.is_writable,
+ is_subscription: calendar.is_subscription,
+ sync_error: calendar.sync_error,
+ default_reminders: calendar
+ .default_reminders
+ .into_iter()
+ .map(Into::into)
+ .collect(),
+ }
+ }
+}
+
+/// How far the viewer's client has read one connected inbox's calendar
+/// change log.
+#[derive(SimpleObject, Clone, Debug, PartialEq, Eq)]
+pub struct GraphqlCalendarLinkWatermark {
+ /// Connected inbox identifier.
+ pub(crate) link_id: ID,
+ /// Last change-log sequence covered, as a decimal string.
+ pub(crate) seq: String,
+}
+
+/// One page of occurrences overlapping a viewport.
+#[derive(SimpleObject, Clone, Debug, PartialEq, Eq)]
+pub struct GraphqlCalendarOccurrencePage {
+ /// Occurrences ordered by start, event, and occurrence key.
+ pub(crate) nodes: Vec<GraphqlCalendarOccurrence>,
+ /// Whether another page follows.
+ pub(crate) has_next_page: bool,
+ /// Cursor for the next page, present when `hasNextPage` is true.
+ pub(crate) end_cursor: Option<String>,
+ /// Aggregate ingestion state; clients render a skeleton while syncing.
+ pub(crate) sync_status: GraphqlCalendarSyncStatus,
+ /// Change-log position of every visible connected inbox, captured before
+ /// the page was read.
+ pub(crate) watermark: Vec<GraphqlCalendarLinkWatermark>,
+}
+
+/// The cache identity of one occurrence.
+pub(crate) fn occurrence_id(event_id: Uuid, occurrence_key: &str) -> ID {
+ ID(format!("{event_id}:{occurrence_key}"))
+}
+
+fn id(value: Uuid) -> ID {
+ ID(value.to_string())
+}
diff --git a/crates/graphql_calendar/src/objects/test.rs b/crates/graphql_calendar/src/objects/test.rs
new file mode 100644
index 0000000000..4370d3b05d
--- /dev/null
+++ b/crates/graphql_calendar/src/objects/test.rs
@@ -0,0 +1,114 @@
+use async_graphql::ID;
+use calendar_events::domain::models::{
+ AttendeeResponseStatus, EventStatus, EventTime, OccurrenceException,
+};
+use chrono::NaiveDate;
+
+use super::*;
+use crate::test_fixtures::{EVENT_ID, LINK_ID, attendee, timed_listing};
+
+#[test]
+fn occurrence_identity_composes_event_id_and_occurrence_key() {
+ let listing = timed_listing(7);
+ let key = listing.occurrence.occurrence_key.clone();
+
+ let occurrence = GraphqlCalendarOccurrence::from(listing);
+
+ assert_eq!(occurrence.id, ID(format!("{EVENT_ID}:{key}")));
+ assert_eq!(occurrence.event_id, ID(EVENT_ID.to_string()));
+ assert_eq!(occurrence.link_id, ID(LINK_ID.to_string()));
+ assert_eq!(occurrence.event.id, ID(EVENT_ID.to_string()));
+ assert_eq!(occurrence.event.link_id, ID(LINK_ID.to_string()));
+}
+
+#[test]
+fn exception_stays_on_the_occurrence_and_the_event_keeps_series_content() {
+ let mut listing = timed_listing(7);
+ listing.exception = OccurrenceException {
+ title: Some("Moved standup".to_owned()),
+ description: Some("Room B".to_owned()),
+ location: None,
+ status: Some(EventStatus::Tentative),
+ attendees: Some(vec![attendee(
+ AttendeeResponseStatus::Declined,
+ )]),
+ };
+
+ let occurrence = GraphqlCalendarOccurrence::from(listing);
+
+ assert_eq!(occurrence.event.title, "Standup");
+ assert_eq!(
+ occurrence.event.attendees[0].response_status,
+ GraphqlCalendarAttendeeResponseStatus::Accepted
+ );
+ assert_eq!(occurrence.override_title.as_deref(), Some("Moved standup"));
+ assert_eq!(occurrence.override_description.as_deref(), Some("Room B"));
+ assert_eq!(occurrence.override_location, None);
+ assert_eq!(
+ occurrence.override_status,
+ Some(GraphqlCalendarEventStatus::Tentative)
+ );
+ let override_attendees = occurrence.override_attendees.expect("override attendees");
+ assert_eq!(
+ override_attendees[0].response_status,
+ GraphqlCalendarAttendeeResponseStatus::Declined
+ );
+}
+
+#[test]
+fn occurrence_without_exception_inherits_everything() {
+ let occurrence = GraphqlCalendarOccurrence::from(timed_listing(8));
+
+ assert_eq!(occurrence.override_title, None);
+ assert_eq!(occurrence.override_status, None);
+ assert_eq!(occurrence.override_attendees, None);
+}
+
+#[test]
+fn time_union_maps_both_shapes() {
+ let timed = GraphqlEventTime::from(timed_listing(7).occurrence.time);
+ assert_eq!(
+ timed,
+ GraphqlEventTime::Timed(GraphqlTimedEventTime {
+ starts_at: "2026-10-07T15:00:00+00:00".to_owned(),
+ ends_at: "2026-10-07T15:30:00+00:00".to_owned(),
+ time_zone: None,
+ })
+ );
+
+ let all_day = GraphqlEventTime::from(EventTime::AllDay {
+ start_date: NaiveDate::from_ymd_opt(2026, 10, 7).unwrap(),
+ end_date: NaiveDate::from_ymd_opt(2026, 10, 9).unwrap(),
+ });
+ assert_eq!(
+ all_day,
+ GraphqlEventTime::AllDay(GraphqlAllDayEventTime {
+ start_date: "2026-10-07".to_owned(),
+ end_date: "2026-10-09".to_owned(),
+ })
+ );
+}
+
+#[test]
+fn visible_calendar_maps_its_link() {
+ let calendar = GraphqlCalendar::from(VisibleCalendar {
+ id: uuid::Uuid::from_u128(5),
+ email_link_id: LINK_ID,
+ email_address: "[email protected]".to_owned(),
+ name: "Work".to_owned(),
+ color: Some("#0b8043".to_owned()),
+ is_primary: true,
+ is_writable: true,
+ is_subscription: false,
+ sync_error: None,
+ default_reminders: vec![EventReminderOverride {
+ method: "popup".to_owned(),
+ minutes: 10,
+ }],
+ });
+
+ assert_eq!(calendar.id, ID(uuid::Uuid::from_u128(5).to_string()));
+ assert_eq!(calendar.link_id, ID(LINK_ID.to_string()));
+ assert_eq!(calendar.default_reminders[0].minutes, 10);
+}
diff --git a/crates/graphql_calendar/src/reads.rs b/crates/graphql_calendar/src/reads.rs
new file mode 100644
index 0000000000..ecb0108438
--- /dev/null
+++ b/crates/graphql_calendar/src/reads.rs
@@ -0,0 +1,71 @@
+use std::{future::Future, pin::Pin, sync::Arc};
+
+use calendar_events::domain::{
+ models::{
+ CalendarOccurrenceCursor, CalendarSyncStatus, OccurrenceListing, OccurrenceRange,
+ VisibleCalendar,
+ },
+ ports::CalendarOccurrenceService,
+};
+use rootcause::Report;
+
+pub(crate) type ReadFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, Report>> + Send + 'a>>;
+
+/// Object-safe view of the calendar read service, so request data does not
+/// carry the service's type parameters.
+pub(crate) trait CalendarGraphqlReads: Send + Sync {
+ fn list_occurrences(
+ &self,
+ viewer: String,
+ range: OccurrenceRange,
+ cursor: Option<CalendarOccurrenceCursor>,
+ limit: u16,
+ ) -> ReadFuture<'_, Vec<OccurrenceListing>>;
+
+ fn sync_status(&self, viewer: String) -> ReadFuture<'_, CalendarSyncStatus>;
+
+ fn list_visible_calendars(&self, viewer: String) -> ReadFuture<'_, Vec<VisibleCalendar>>;
+}
+
+/// Type-erased calendar read service stored in GraphQL request data.
+#[derive(Clone)]
+pub struct CalendarGraphqlContext {
+ pub(crate) reads: Arc<dyn CalendarGraphqlReads>,
+}
+
+impl CalendarGraphqlContext {
+ /// Erase `service` so request data does not carry its type parameters.
+ pub fn new<S: CalendarOccurrenceService>(service: Arc<S>) -> Self {
+ Self {
+ reads: Arc::new(OccurrenceServiceReads { service }),
+ }
+ }
+}
+
+struct OccurrenceServiceReads<S> {
+ service: Arc<S>,
+}
+
+impl<S: CalendarOccurrenceService> CalendarGraphqlReads for OccurrenceServiceReads<S> {
+ fn list_occurrences(
+ &self,
+ viewer: String,
+ range: OccurrenceRange,
+ cursor: Option<CalendarOccurrenceCursor>,
+ limit: u16,
+ ) -> ReadFuture<'_, Vec<OccurrenceListing>> {
+ Box::pin(async move {
+ self.service
+ .list_occurrences(&viewer, range, cursor, limit)
+ .await
+ })
+ }
+
+ fn sync_status(&self, viewer: String) -> ReadFuture<'_, CalendarSyncStatus> {
+ Box::pin(async move { self.service.sync_status(&viewer).await })
+ }
+
+ fn list_visible_calendars(&self, viewer: String) -> ReadFuture<'_, Vec<VisibleCalendar>> {
+ Box::pin(async move { self.service.list_visible_calendars(&viewer).await })
+ }
+}
diff --git a/crates/graphql_calendar/src/test_fixtures.rs b/crates/graphql_calendar/src/test_fixtures.rs
new file mode 100644
index 0000000000..8cf4dde45e
--- /dev/null
+++ b/crates/graphql_calendar/src/test_fixtures.rs
@@ -0,0 +1,83 @@
+use calendar_events::domain::models::{
+ AttendeeResponseStatus, CalendarAttendee, CalendarEvent, CalendarOccurrence, EventReminders,
+ EventStatus, EventTime, EventTransparency, EventType, EventVisibility, OccurrenceException,
+ OccurrenceListing,
+};
+use chrono::{TimeZone, Utc};
+use uuid::Uuid;
+
+pub(crate) const EVENT_ID: Uuid = Uuid::from_u128(0x11);
+pub(crate) const LINK_ID: Uuid = Uuid::from_u128(0x22);
+pub(crate) const CALENDAR_ID: Uuid = Uuid::from_u128(0x33);
+
+pub(crate) fn attendee(email: &str, status: AttendeeResponseStatus) -> CalendarAttendee {
+ CalendarAttendee {
+ email: email.to_owned(),
+ display_name: None,
+ response_status: status,
+ is_organizer: false,
+ is_optional: false,
+ is_self: false,
+ comment: None,
+ }
+}
+
+pub(crate) fn series_event() -> CalendarEvent {
+ let starts_at = Utc.with_ymd_and_hms(2026, 10, 6, 15, 0, 0).unwrap();
+ CalendarEvent {
+ id: EVENT_ID,
+ owner_id: "macro|[email protected]".to_owned(),
+ ical_uid: "[email protected]".to_owned(),
+ calendar_id: Some(CALENDAR_ID),
+ sources: Vec::new(),
+ title: "Standup".to_owned(),
+ description: None,
+ location: None,
+ status: EventStatus::Confirmed,
+ visibility: EventVisibility::Default,
+ transparency: EventTransparency::Opaque,
+ event_type: EventType::Default,
+ time: EventTime::Timed {
+ starts_at,
+ ends_at: starts_at + chrono::Duration::minutes(30),
+ time_zone: Some("America/New_York".to_owned()),
+ },
+ recurrence_lines: vec!["RRULE:FREQ=DAILY".to_owned()],
+ organizer_email: Some("[email protected]".to_owned()),
+ organizer_name: None,
+ creator_email: None,
+ creator_name: None,
+ conference_url: None,
+ conference_provider: None,
+ sequence: 2,
+ is_read_only: false,
+ attendees: vec![attendee(
+ AttendeeResponseStatus::Accepted,
+ )],
+ reminders: EventReminders::default(),
+ created_at: starts_at,
+ updated_at: starts_at,
+ }
+}
+
+pub(crate) fn timed_listing(day: u32) -> OccurrenceListing {
+ let starts_at = Utc.with_ymd_and_hms(2026, 10, day, 15, 0, 0).unwrap();
+ let time = EventTime::Timed {
+ starts_at,
+ ends_at: starts_at + chrono::Duration::minutes(30),
+ time_zone: None,
+ };
+ OccurrenceListing {
+ event: series_event(),
+ occurrence: CalendarOccurrence {
+ event_id: EVENT_ID,
+ occurrence_key: time.occurrence_key(),
+ recurrence_id: Some(format!("{EVENT_ID}_{day}")),
+ time,
+ is_cancelled: false,
+ },
+ link_id: LINK_ID,
+ exception: OccurrenceException::default(),
+ }
+}
diff --git a/crates/graphql_calendar/src/user_query.rs b/crates/graphql_calendar/src/user_query.rs
new file mode 100644
index 0000000000..66eff77f69
--- /dev/null
+++ b/crates/graphql_calendar/src/user_query.rs
@@ -0,0 +1,99 @@
+use async_graphql::{Context, Object};
+use calendar_events::domain::{models::CalendarOccurrenceCursor, service::CalendarValidationError};
+use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::Report;
+
+use crate::{
+ CalendarGraphqlContext, bad_input,
+ inputs::{CalendarRangeInput, encode_cursor},
+ objects::{GraphqlCalendar, GraphqlCalendarOccurrence, GraphqlCalendarOccurrencePage},
+ unavailable,
+};
+
+#[cfg(test)]
+mod test;
+
+/// Flattenable calendar fields of the authenticated user.
+pub struct GraphqlCalendarQuery {
+ user_id: MacroUserIdStr<'static>,
+}
+
+impl GraphqlCalendarQuery {
+ /// Calendar fields scoped to the authenticated `user_id`. The read service
+ /// is resolved from request data per field.
+ pub fn new(user_id: MacroUserIdStr<'static>) -> Self {
+ Self { user_id }
+ }
+
+ fn viewer(&self) -> String {
+ self.user_id.as_ref().to_owned()
+ }
+}
+
+/// Calendar fields of the authenticated user.
+#[Object]
+impl GraphqlCalendarQuery {
+ /// Every calendar visible across owned and delegated inboxes, primaries
+ /// and writables first.
+ #[tracing::instrument(skip_all, err(Debug))]
+ async fn calendars(&self, ctx: &Context<'_>) -> async_graphql::Result<Vec<GraphqlCalendar>> {
+ let reads = &ctx.data::<CalendarGraphqlContext>()?.reads;
+ let calendars = reads
+ .list_visible_calendars(self.viewer())
+ .await
+ .map_err(|error| unavailable(error, "calendars are unavailable"))?;
+ Ok(calendars.into_iter().map(Into::into).collect())
+ }
+
+ /// One page of occurrences overlapping the viewport, across owned and
+ /// delegated inboxes, ordered by start.
+ #[tracing::instrument(skip_all, err(Debug))]
+ async fn calendar_occurrences(
+ &self,
+ ctx: &Context<'_>,
+ input: CalendarRangeInput,
+ ) -> async_graphql::Result<GraphqlCalendarOccurrencePage> {
+ let reads = &ctx.data::<CalendarGraphqlContext>()?.reads;
+ let request = input.into_page_request()?;
+ let page_size = usize::from(request.page_size);
+ let (mut rows, sync_status) = futures::try_join!(
+ reads.list_occurrences(
+ self.viewer(),
+ request.range,
+ request.cursor,
+ request.page_size + 1,
+ ),
+ reads.sync_status(self.viewer()),
+ )
+ .map_err(occurrences_error)?;
+ let has_next_page = rows.len() > page_size;
+ rows.truncate(page_size);
+ let end_cursor = has_next_page.then(|| rows.last()).flatten().map(|listing| {
+ encode_cursor(CalendarOccurrenceCursor::from_occurrence(
+ &listing.occurrence,
+ ))
+ });
+ Ok(GraphqlCalendarOccurrencePage {
+ nodes: rows
+ .into_iter()
+ .map(GraphqlCalendarOccurrence::from)
+ .collect(),
+ has_next_page,
+ end_cursor,
+ sync_status: sync_status.into(),
+ watermark: Vec::new(),
+ })
+ }
+}
+
+fn occurrences_error(error: Report) -> async_graphql::Error {
+ if error
+ .downcast_current_context::<CalendarValidationError>()
+ .is_some()
+ {
+ return bad_input(
+ "calendar range must be positive, at most 370 days, and inside the maintained one-year-history/two-year-future window",
+ );
+ }
+ unavailable(error, "calendar occurrences are unavailable")
+}
diff --git a/crates/graphql_calendar/src/user_query/test.rs b/crates/graphql_calendar/src/user_query/test.rs
new file mode 100644
index 0000000000..d69ec552e1
--- /dev/null
+++ b/crates/graphql_calendar/src/user_query/test.rs
@@ -0,0 +1,273 @@
+use std::sync::{Arc, Mutex};
+
+use async_graphql::{EmptyMutation, EmptySubscription, Schema};
+use calendar_events::domain::{
+ models::{
+ CalendarMentionPreview, CalendarMentionRequestItem, CalendarOccurrenceCursor,
+ CalendarSyncStatus, OccurrenceListing, OccurrenceRange, TeamOutOfOffice, VisibleCalendar,
+ },
+ ports::CalendarOccurrenceService,
+ service::CalendarValidationError,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::Report;
+use serde_json::Value;
+
+use super::GraphqlCalendarQuery;
+use crate::{
+ CalendarGraphqlContext,
+ test_fixtures::{EVENT_ID, LINK_ID, timed_listing},
+};
+
+#[derive(Clone, Copy, Default)]
+enum Failure {
+ #[default]
+ None,
+ Validation,
+ Internal,
+}
+
+#[derive(Default)]
+struct FakeReads {
+ listings: Vec<OccurrenceListing>,
+ calendars: Vec<VisibleCalendar>,
+ failure: Failure,
+ requests: Mutex<Vec<(String, Option<CalendarOccurrenceCursor>, u16)>>,
+}
+
+impl FakeReads {
+ fn fail(&self) -> Result<(), Report> {
+ match self.failure {
+ Failure::None => Ok(()),
+ Failure::Validation => {
+ Err(rootcause::report!(CalendarValidationError::InvalidRange).into())
+ }
+ Failure::Internal => Err(rootcause::report!("database host db-7 refused").into()),
+ }
+ }
+}
+
+impl CalendarOccurrenceService for FakeReads {
+ async fn list_occurrences(
+ &self,
+ requester_id: &str,
+ _range: OccurrenceRange,
+ cursor: Option<CalendarOccurrenceCursor>,
+ limit: u16,
+ ) -> Result<Vec<OccurrenceListing>, Report> {
+ self.requests
+ .lock()
+ .unwrap()
+ .push((requester_id.to_owned(), cursor, limit));
+ self.fail()?;
+ Ok(self
+ .listings
+ .iter()
+ .take(usize::from(limit))
+ .cloned()
+ .collect())
+ }
+
+ async fn sync_status(&self, _requester_id: &str) -> Result<CalendarSyncStatus, Report> {
+ Ok(CalendarSyncStatus::Syncing)
+ }
+
+ async fn list_visible_calendars(
+ &self,
+ requester_id: &str,
+ ) -> Result<Vec<VisibleCalendar>, Report> {
+ self.requests
+ .lock()
+ .unwrap()
+ .push((requester_id.to_owned(), None, 0));
+ self.fail()?;
+ Ok(self.calendars.clone())
+ }
+
+ async fn mention_previews(
+ &self,
+ _requester_id: &str,
+ _items: Vec<CalendarMentionRequestItem>,
+ ) -> Result<Vec<CalendarMentionPreview>, Report> {
+ unreachable!("calendar GraphQL reads never resolve mention previews")
+ }
+
+ async fn list_team_out_of_office(
+ &self,
+ _requester_id: &str,
+ _range: OccurrenceRange,
+ _limit: u16,
+ ) -> Result<Vec<TeamOutOfOffice>, Report> {
+ unreachable!("calendar GraphQL reads never list team out-of-office")
+ }
+
+ async fn primary_time_zone(&self, _requester_id: &str) -> Result<Option<String>, Report> {
+ unreachable!("calendar GraphQL reads never resolve the primary time zone")
+ }
+}
+
+const VIEWER: &str = "macro|[email protected]";
+
+async fn execute(reads: Arc<FakeReads>, query: &str) -> async_graphql::Response {
+ let schema = Schema::build(
+ GraphqlCalendarQuery::new(MacroUserIdStr::parse_from_str(VIEWER).unwrap()),
+ EmptyMutation,
+ EmptySubscription,
+ )
+ .data(CalendarGraphqlContext::new(reads))
+ .finish();
+ schema.execute(query).await
+}
+
+const PAGE_QUERY: &str = r#"{
+ calendarOccurrences(input: {
+ start: "2026-10-05T00:00:00Z", end: "2026-10-12T00:00:00Z", first: 2
+ }) {
+ nodes {
+ __typename id eventId linkId occurrenceKey
+ time { __typename ... on GraphqlTimedEventTime { startsAt endsAt } }
+ event { __typename id linkId title }
+ }
+ hasNextPage endCursor syncStatus watermark { linkId seq }
+ }
+}"#;
+
+#[tokio::test]
+async fn a_full_page_reports_a_cursor_and_requests_one_extra_row() {
+ let reads = Arc::new(FakeReads {
+ listings: vec![timed_listing(6), timed_listing(7), timed_listing(8)],
+ ..Default::default()
+ });
+
+ let response = execute(Arc::clone(&reads), PAGE_QUERY).await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let data = response.data.into_json().unwrap();
+ let page = &data["calendarOccurrences"];
+ let nodes = page["nodes"].as_array().unwrap();
+ assert_eq!(nodes.len(), 2);
+ assert_eq!(nodes[0]["__typename"], "GraphqlCalendarOccurrence");
+ assert_eq!(
+ nodes[0]["id"],
+ format!("{EVENT_ID}:2026-10-06T15:00:00+00:00")
+ );
+ assert_eq!(nodes[0]["eventId"], EVENT_ID.to_string());
+ assert_eq!(nodes[0]["linkId"], LINK_ID.to_string());
+ assert_eq!(nodes[0]["time"]["__typename"], "GraphqlTimedEventTime");
+ assert_eq!(nodes[0]["event"]["__typename"], "GraphqlCalendarEvent");
+ assert_eq!(nodes[0]["event"]["linkId"], LINK_ID.to_string());
+ assert_eq!(page["hasNextPage"], true);
+ assert_eq!(page["syncStatus"], "SYNCING");
+ assert_eq!(page["watermark"], Value::Array(Vec::new()));
+
+ let cursor = page["endCursor"].as_str().unwrap().to_owned();
+ let requests = reads.requests.lock().unwrap().clone();
+ assert_eq!(requests, vec![(VIEWER.to_owned(), None, 3)]);
+
+ let next = PAGE_QUERY.replace("first: 2", &format!("first: 2, after: \"{cursor}\""));
+ let response = execute(Arc::clone(&reads), &next).await;
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let requests = reads.requests.lock().unwrap().clone();
+ let resumed = requests[1].1.as_ref().expect("decoded cursor");
+ assert_eq!(resumed.event_id, EVENT_ID);
+ assert_eq!(resumed.occurrence_key, "2026-10-07T15:00:00+00:00");
+}
+
+#[tokio::test]
+async fn a_short_page_has_no_cursor() {
+ let reads = Arc::new(FakeReads {
+ listings: vec![timed_listing(6)],
+ ..Default::default()
+ });
+
+ let response = execute(reads, PAGE_QUERY).await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let data = response.data.into_json().unwrap();
+ assert_eq!(data["calendarOccurrences"]["hasNextPage"], false);
+ assert_eq!(data["calendarOccurrences"]["endCursor"], Value::Null);
+}
+
+#[tokio::test]
+async fn calendars_are_listed_for_the_viewer() {
+ let reads = Arc::new(FakeReads {
+ calendars: vec![VisibleCalendar {
+ id: uuid::Uuid::from_u128(5),
+ email_link_id: LINK_ID,
+ email_address: "[email protected]".to_owned(),
+ name: "Work".to_owned(),
+ color: None,
+ is_primary: true,
+ is_writable: true,
+ is_subscription: false,
+ sync_error: None,
+ default_reminders: Vec::new(),
+ }],
+ ..Default::default()
+ });
+
+ let response = execute(
+ Arc::clone(&reads),
+ "{ calendars { __typename id linkId name isWritable } }",
+ )
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let data = response.data.into_json().unwrap();
+ assert_eq!(data["calendars"][0]["__typename"], "GraphqlCalendar");
+ assert_eq!(data["calendars"][0]["linkId"], LINK_ID.to_string());
+ assert_eq!(reads.requests.lock().unwrap()[0].0, VIEWER);
+}
+
+#[tokio::test]
+async fn validation_failures_are_user_errors() {
+ let reads = Arc::new(FakeReads {
+ failure: Failure::Validation,
+ ..Default::default()
+ });
+
+ let response = execute(reads, PAGE_QUERY).await;
+
+ let error = &response.errors[0];
+ assert!(error.message.contains("370 days"), "{}", error.message);
+ assert_eq!(
+ error
+ .extensions
+ .as_ref()
+ .unwrap()
+ .get("code")
+ .unwrap()
+ .to_string(),
+ "\"BAD_USER_INPUT\""
+ );
+}
+
+#[tokio::test]
+async fn infrastructure_failures_are_masked() {
+ let reads = Arc::new(FakeReads {
+ failure: Failure::Internal,
+ ..Default::default()
+ });
+
+ let occurrences = execute(Arc::clone(&reads), PAGE_QUERY).await;
+ let calendars = execute(reads, "{ calendars { id } }").await;
+
+ for (response, message) in [
+ (occurrences, "calendar occurrences are unavailable"),
+ (calendars, "calendars are unavailable"),
+ ] {
+ let error = &response.errors[0];
+ assert_eq!(error.message, message);
+ assert!(!error.message.contains("db-7"));
+ assert_eq!(
+ error
+ .extensions
+ .as_ref()
+ .unwrap()
+ .get("code")
+ .unwrap()
+ .to_string(),
+ "\"INTERNAL_SERVER_ERROR\""
+ );
+ }
+}
diff --git a/crates/graphql_email/src/user_objects.rs b/crates/graphql_email/src/user_objects.rs
index 765a1c0dec..543d21cce5 100644
--- a/crates/graphql_email/src/user_objects.rs
+++ b/crates/graphql_email/src/user_objects.rs
@@ -165,6 +165,12 @@ pub struct GraphqlEmailLink {
settings: GraphqlEmailLinkSettings,
/// Whether this is the owner's primary inbox.
is_primary: bool,
+ /// Whether the recorded Google grant lacks the calendar capability.
+ needs_calendar_permission: bool,
+ /// Whether the owner turned the inbox's calendar off.
+ calendar_disabled: bool,
+ /// Whether a calendar account has been provisioned for the inbox.
+ has_calendar_data: bool,
/// Link creation timestamp in RFC 3339 format.
created_at: String,
/// Link last-updated timestamp in RFC 3339 format.
@@ -185,6 +191,9 @@ impl From<UserEmailLink> for GraphqlEmailLink {
needs_reauth: link.needs_reauth,
settings: link.settings.into(),
is_primary: link.is_primary,
+ needs_calendar_permission: link.needs_calendar_permission,
+ calendar_disabled: link.calendar_disabled,
+ has_calendar_data: link.has_calendar_data,
created_at: link.created_at.to_rfc3339(),
updated_at: link.updated_at.to_rfc3339(),
}
diff --git a/crates/graphql_email/src/user_query/test.rs b/crates/graphql_email/src/user_query/test.rs
index 40754bd747..16592f07da 100644
--- a/crates/graphql_email/src/user_query/test.rs
+++ b/crates/graphql_email/src/user_query/test.rs
@@ -81,6 +81,9 @@ fn link() -> UserEmailLink {
signature: Some("<p>Regards</p>".to_owned()),
},
is_primary: false,
+ needs_calendar_permission: true,
+ calendar_disabled: false,
+ has_calendar_data: true,
created_at: Utc.with_ymd_and_hms(2025, 1, 2, 3, 4, 5).unwrap(),
updated_at: Utc.with_ymd_and_hms(2025, 2, 3, 4, 5, 6).unwrap(),
}
@@ -106,7 +109,8 @@ async fn resolves_labels_and_links_for_the_bound_authenticated_user() {
emailLinks {
id macroId emailAddress photoUrl provider isSyncActive syncStatus
needsReauth settings { signatureOnRepliesForwards signature }
- isPrimary createdAt updatedAt
+ isPrimary needsCalendarPermission calendarDisabled hasCalendarData
+ createdAt updatedAt
}
}"#,
)
@@ -130,6 +134,9 @@ async fn resolves_labels_and_links_for_the_bound_authenticated_user() {
assert_eq!(link["needsReauth"], true);
assert_eq!(link["settings"]["signatureOnRepliesForwards"], true);
assert_eq!(link["settings"]["signature"], "<p>Regards</p>");
+ assert_eq!(link["needsCalendarPermission"], true);
+ assert_eq!(link["calendarDisabled"], false);
+ assert_eq!(link["hasCalendarData"], true);
assert_eq!(
*service.requested_users.lock().unwrap(),
vec![user_id(), user_id()]
diff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.toml
index f2c434ae85..20185816a6 100644
--- a/services/document_storage_service/Cargo.toml
+++ b/services/document_storage_service/Cargo.toml
@@ -145,6 +145,7 @@ github_pull_requests = { path = "../../crates/github_pull_requests", default-fea
] }
graphql_soup = { path = "../../crates/graphql_soup" }
graphql_initiative = { path = "../../crates/graphql_initiative" }
+graphql_calendar = { path = "../../crates/graphql_calendar" }
graphql_scheduled_action = { path = "../../crates/graphql_scheduled_action" }
harnesses = { path = "../../crates/harnesses" }
hex = { workspace = true }
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index 9f03a83e66..1cf062b6cd 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -815,6 +815,7 @@ pub(crate) struct ApiContext {
pub initiative_state: DssInitiativeState,
pub graphql_initiative_context: graphql_initiative::InitiativeGraphqlContext,
pub graphql_scheduled_action_context: graphql_scheduled_action::ScheduledActionGraphqlContext,
+ pub graphql_calendar_context: graphql_calendar::CalendarGraphqlContext,
pub graphql_initiative_entity_loader: graphql_initiative::InitiativeEntityLoader,
pub graphql_agent_session_entity_loader: graphql_soup::AgentSessionEntityLoader,
pub databases_state: DssDatabasesState,
diff --git a/services/document_storage_service/src/api/graphql_soup.rs b/services/document_storage_service/src/api/graphql_soup.rs
index dc84f45364..f18df15aa1 100644
--- a/services/document_storage_service/src/api/graphql_soup.rs
+++ b/services/document_storage_service/src/api/graphql_soup.rs
@@ -171,6 +171,7 @@ fn insert_graphql_context_data(
data.insert(state.channel_service.clone());
data.insert(state.graphql_initiative_context.clone());
data.insert(state.graphql_scheduled_action_context.clone());
+ data.insert(state.graphql_calendar_context.clone());
data.insert(state.graphql_initiative_entity_loader.clone());
data.insert(state.graphql_agent_session_entity_loader.clone());
data.insert(graphql_initiative::initiative_detail_loader(
diff --git a/services/document_storage_service/src/server.rs b/services/document_storage_service/src/server.rs
index 3cfa3a66a9..c3156e4d01 100644
--- a/services/document_storage_service/src/server.rs
+++ b/services/document_storage_service/src/server.rs
@@ -1731,12 +1731,13 @@ pub async fn run() -> anyhow::Result<()> {
let user_api_key_service = Arc::new(UserApiKeyServiceImpl::new(PgUserApiKeysRepo::new(
db.clone(),
)));
- let calendar_state = CalendarRouterState::new(
- Arc::new(calendar_events::domain::service::CalendarService::new(
- calendar_events::outbound::pg::PgCalendarRepository::new(readonly_db.clone()),
- )),
- authorization_state.clone(),
- );
+ let calendar_read_service = Arc::new(calendar_events::domain::service::CalendarService::new(
+ calendar_events::outbound::pg::PgCalendarRepository::new(readonly_db.clone()),
+ ));
+ let graphql_calendar_context =
+ graphql_calendar::CalendarGraphqlContext::new(calendar_read_service.clone());
+ let calendar_state =
+ CalendarRouterState::new(calendar_read_service, authorization_state.clone());
// Reminder dispatch. An EventBridge rule drops a sweep tick on this queue
// every minute; the sweep fans one message out per due firing, onto the
@@ -1912,6 +1913,7 @@ pub async fn run() -> anyhow::Result<()> {
graphql_scheduled_action_context: ScheduledActionGraphqlContext::new(
scheduled_action_read_service,
),
+ graphql_calendar_context,
initiative_state: InitiativeRouterState::new(
initiative_service,
entity_access_service.clone(),
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index 98c4f0bd5a..99c70ef430 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -23,6 +23,38 @@ input ActivityOverviewInput {
timeZone: String
}
+"""
+A bounded occurrence viewport and page request.
+"""
+input CalendarRangeInput {
+ """
+ Inclusive UTC viewport start in RFC 3339 format.
+ """
+ start: String!
+ """
+ Exclusive UTC viewport end in RFC 3339 format.
+ """
+ end: String!
+ """
+ Inclusive local date boundary for all-day events (`YYYY-MM-DD`).
+ Defaults to the date of `start`.
+ """
+ startDate: String
+ """
+ Exclusive local date boundary for all-day events (`YYYY-MM-DD`).
+ Defaults to the first date at or after `end`.
+ """
+ endDate: String
+ """
+ Page size, from 1 through 2,000. Defaults to 1,000.
+ """
+ first: Int
+ """
+ `endCursor` of the previous page.
+ """
+ after: String
+}
+
"""
Channel activity operation exposed by GraphQL.
"""
@@ -933,6 +965,20 @@ type GraphqlAiResponseMetadata {
messageId: String!
}
+"""
+An all-day span using RFC 5545's exclusive end date.
+"""
+type GraphqlAllDayEventTime {
+ """
+ Inclusive local start date (`YYYY-MM-DD`).
+ """
+ startDate: String!
+ """
+ Exclusive local end date (`YYYY-MM-DD`).
+ """
+ endDate: String!
+}
+
"""
A Boolean property value.
"""
@@ -957,6 +1003,236 @@ type GraphqlCacheDeletion {
entityId: ID!
}
+"""
+A calendar visible to the viewer.
+"""
+type GraphqlCalendar {
+ """
+ Macro calendar identifier.
+ """
+ id: ID!
+ """
+ Connected inbox that syncs this calendar.
+ """
+ linkId: ID!
+ """
+ Connected inbox address.
+ """
+ emailAddress: String!
+ """
+ Provider display name.
+ """
+ name: String!
+ """
+ Provider color.
+ """
+ color: String
+ """
+ Whether this is its account's primary calendar.
+ """
+ isPrimary: Boolean!
+ """
+ Whether the grant can create and modify events on this calendar.
+ """
+ isWritable: Boolean!
+ """
+ Whether this is a shared system calendar (holidays, birthdays).
+ """
+ isSubscription: Boolean!
+ """
+ A persistent sync failure isolated to this calendar.
+ """
+ syncError: String
+ """
+ Default reminders applied to events that keep `useDefault`.
+ """
+ defaultReminders: [GraphqlCalendarReminderOverride!]!
+}
+
+"""
+One event attendee.
+"""
+type GraphqlCalendarAttendee {
+ """
+ Attendee email address.
+ """
+ email: String!
+ """
+ Attendee display name.
+ """
+ displayName: String
+ """
+ The attendee's RSVP.
+ """
+ responseStatus: GraphqlCalendarAttendeeResponseStatus!
+ """
+ Whether the attendee organizes the event.
+ """
+ isOrganizer: Boolean!
+ """
+ Whether the attendee is optional.
+ """
+ isOptional: Boolean!
+ """
+ Whether the attendee is one of the viewer's own connected inboxes.
+ """
+ isSelf: Boolean!
+ """
+ The attendee's RSVP comment.
+ """
+ comment: String
+}
+
+"""
+An attendee's RSVP.
+"""
+enum GraphqlCalendarAttendeeResponseStatus {
+ """
+ The attendee has not responded.
+ """
+ NEEDS_ACTION
+ """
+ The attendee accepted.
+ """
+ ACCEPTED
+ """
+ The attendee declined.
+ """
+ DECLINED
+ """
+ The attendee tentatively accepted.
+ """
+ TENTATIVE
+}
+
+"""
+Conferencing system backing an event's join URL.
+"""
+enum GraphqlCalendarConferenceProvider {
+ """
+ Google Meet.
+ """
+ GOOGLE_MEET
+ """
+ Any other conferencing system.
+ """
+ OTHER
+}
+
+"""
+A calendar event entity: the series content shared by every occurrence.
+"""
+type GraphqlCalendarEvent {
+ """
+ Macro event identifier.
+ """
+ id: ID!
+ """
+ Macro user who owns this event projection.
+ """
+ ownerId: String!
+ """
+ Connected inbox whose grant backs the event.
+ """
+ linkId: ID!
+ """
+ RFC 5545 UID used to reconcile provider and email sources.
+ """
+ icalUid: String!
+ """
+ Calendar the canonical source belongs to, when known.
+ """
+ calendarId: ID
+ """
+ Content of every active copy of this event, canonical first.
+ """
+ sources: [GraphqlCalendarEventSource!]!
+ """
+ Display title.
+ """
+ title: String!
+ """
+ Optional event body.
+ """
+ description: String
+ """
+ Optional physical or virtual location label.
+ """
+ location: String
+ """
+ Event status.
+ """
+ status: GraphqlCalendarEventStatus!
+ """
+ Event visibility.
+ """
+ visibility: GraphqlCalendarEventVisibility!
+ """
+ Availability behavior.
+ """
+ transparency: GraphqlCalendarEventTransparency!
+ """
+ Provider event type.
+ """
+ eventType: GraphqlCalendarEventType!
+ """
+ The series time span.
+ """
+ time: GraphqlEventTime!
+ """
+ Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`).
+ """
+ recurrenceLines: [String!]!
+ """
+ Organizer email.
+ """
+ organizerEmail: String
+ """
+ Organizer display name.
+ """
+ organizerName: String
+ """
+ Provider-reported creator email.
+ """
+ creatorEmail: String
+ """
+ Provider-reported creator display name.
+ """
+ creatorName: String
+ """
+ Direct join URL when known.
+ """
+ conferenceUrl: String
+ """
+ Which conferencing system backs `conferenceUrl`.
+ """
+ conferenceProvider: GraphqlCalendarConferenceProvider
+ """
+ Provider/iCalendar sequence number.
+ """
+ sequence: Int!
+ """
+ Whether the canonical source's calendar prohibits editing it.
+ """
+ isReadOnly: Boolean!
+ """
+ Series attendees.
+ """
+ attendees: [GraphqlCalendarAttendee!]!
+ """
+ Reminder configuration.
+ """
+ reminders: GraphqlCalendarReminders!
+ """
+ Entity creation time in RFC 3339 format.
+ """
+ createdAt: String!
+ """
+ Entity update time in RFC 3339 format.
+ """
+ updatedAt: String!
+}
+
"""
The two operands of a recursive `CalendarEventFilterExpr` binary expression.
"""
@@ -1065,6 +1341,287 @@ type GraphqlCalendarEventReminderMetadata {
minutesBefore: Int!
}
+"""
+Content of one calendar's copy of an event.
+"""
+type GraphqlCalendarEventSource {
+ """
+ Calendar this copy lives on.
+ """
+ calendarId: ID!
+ """
+ Display title.
+ """
+ title: String!
+ """
+ Optional event body.
+ """
+ description: String
+ """
+ Optional physical or virtual location label.
+ """
+ location: String
+ """
+ Provider event type.
+ """
+ eventType: GraphqlCalendarEventType!
+ """
+ Event visibility.
+ """
+ visibility: GraphqlCalendarEventVisibility!
+ """
+ Availability behavior.
+ """
+ transparency: GraphqlCalendarEventTransparency!
+ """
+ Whether the calendar's access role prohibits editing this copy.
+ """
+ isReadOnly: Boolean!
+ """
+ Reminder configuration of this copy.
+ """
+ reminders: GraphqlCalendarReminders!
+ """
+ Provider-reported creator email.
+ """
+ creatorEmail: String
+ """
+ Provider-reported creator display name.
+ """
+ creatorName: String
+}
+
+"""
+Event status.
+"""
+enum GraphqlCalendarEventStatus {
+ """
+ The event is confirmed.
+ """
+ CONFIRMED
+ """
+ The event is tentatively confirmed.
+ """
+ TENTATIVE
+ """
+ The event was cancelled.
+ """
+ CANCELLED
+}
+
+"""
+Whether the event blocks time on the calendar.
+"""
+enum GraphqlCalendarEventTransparency {
+ """
+ The event blocks time.
+ """
+ OPAQUE
+ """
+ The event does not block time.
+ """
+ TRANSPARENT
+}
+
+"""
+Provider event type.
+"""
+enum GraphqlCalendarEventType {
+ """
+ A regular event.
+ """
+ DEFAULT
+ """
+ An out-of-office block.
+ """
+ OUT_OF_OFFICE
+ """
+ A focus-time block.
+ """
+ FOCUS_TIME
+ """
+ A working-location marker.
+ """
+ WORKING_LOCATION
+ """
+ A contact's birthday.
+ """
+ BIRTHDAY
+ """
+ An event Gmail created from an email.
+ """
+ FROM_GMAIL
+}
+
+"""
+Event visibility.
+"""
+enum GraphqlCalendarEventVisibility {
+ """
+ The calendar's default visibility.
+ """
+ DEFAULT
+ """
+ Visible to everyone with access to the calendar.
+ """
+ PUBLIC
+ """
+ Details visible only to attendees.
+ """
+ PRIVATE
+ """
+ Treated as private.
+ """
+ CONFIDENTIAL
+}
+
+"""
+How far the viewer's client has read one connected inbox's calendar
+change log.
+"""
+type GraphqlCalendarLinkWatermark {
+ """
+ Connected inbox identifier.
+ """
+ linkId: ID!
+ """
+ Last change-log sequence covered, as a decimal string.
+ """
+ seq: String!
+}
+
+"""
+One materialized instance of a calendar event.
+
+`eventId` and `linkId` repeat the event's identity as scalars so a client
+range index can project occurrences without dereferencing the event.
+"""
+type GraphqlCalendarOccurrence {
+ """
+ `{eventId}:{occurrenceKey}`.
+ """
+ id: ID!
+ """
+ Owning event identifier.
+ """
+ eventId: ID!
+ """
+ Connected inbox whose grant backs the event.
+ """
+ linkId: ID!
+ """
+ The series event.
+ """
+ event: GraphqlCalendarEvent!
+ """
+ Stable key within the event.
+ """
+ occurrenceKey: String!
+ """
+ Provider recurrence identifier, when applicable.
+ """
+ recurrenceId: String
+ """
+ Instance time.
+ """
+ time: GraphqlEventTime!
+ """
+ Whether the instance was cancelled.
+ """
+ isCancelled: Boolean!
+ """
+ Title replacing the series title on this instance alone.
+ """
+ overrideTitle: String
+ """
+ Description replacing the series description on this instance alone.
+ """
+ overrideDescription: String
+ """
+ Location replacing the series location on this instance alone.
+ """
+ overrideLocation: String
+ """
+ Status replacing the series status on this instance alone.
+ """
+ overrideStatus: GraphqlCalendarEventStatus
+ """
+ Attendee list replacing the series list on this instance alone, where
+ an instance-scoped RSVP is recorded.
+ """
+ overrideAttendees: [GraphqlCalendarAttendee!]
+}
+
+"""
+One page of occurrences overlapping a viewport.
+"""
+type GraphqlCalendarOccurrencePage {
+ """
+ Occurrences ordered by start, event, and occurrence key.
+ """
+ nodes: [GraphqlCalendarOccurrence!]!
+ """
+ Whether another page follows.
+ """
+ hasNextPage: Boolean!
+ """
+ Cursor for the next page, present when `hasNextPage` is true.
+ """
+ endCursor: String
+ """
+ Aggregate ingestion state; clients render a skeleton while syncing.
+ """
+ syncStatus: GraphqlCalendarSyncStatus!
+ """
+ Change-log position of every visible connected inbox, captured before
+ the page was read.
+ """
+ watermark: [GraphqlCalendarLinkWatermark!]!
+}
+
+"""
+One reminder override.
+"""
+type GraphqlCalendarReminderOverride {
+ """
+ Delivery method (`popup` or `email`).
+ """
+ method: String!
+ """
+ Minutes before the start the reminder fires.
+ """
+ minutes: Int!
+}
+
+"""
+An event's reminder configuration.
+"""
+type GraphqlCalendarReminders {
+ """
+ Whether the calendar's default reminders apply.
+ """
+ useDefault: Boolean!
+ """
+ Explicit reminders, used when `useDefault` is false.
+ """
+ overrides: [GraphqlCalendarReminderOverride!]!
+}
+
+"""
+Aggregate ingestion state across every calendar account visible to the
+viewer.
+"""
+enum GraphqlCalendarSyncStatus {
+ """
+ At least one visible calendar account is still ingesting.
+ """
+ SYNCING
+ """
+ Every visible calendar account has finished its latest sync.
+ """
+ READY
+}
+
"""
The two operands of a recursive `CallFilterExpr` binary expression.
"""
@@ -2260,6 +2817,18 @@ type GraphqlEmailLink {
"""
isPrimary: Boolean!
"""
+ Whether the recorded Google grant lacks the calendar capability.
+ """
+ needsCalendarPermission: Boolean!
+ """
+ Whether the owner turned the inbox's calendar off.
+ """
+ calendarDisabled: Boolean!
+ """
+ Whether a calendar account has been provisioned for the inbox.
+ """
+ hasCalendarData: Boolean!
+ """
Link creation timestamp in RFC 3339 format.
"""
createdAt: String!
@@ -2752,6 +3321,11 @@ enum GraphqlEntityType {
FORM
}
+"""
+The mutually exclusive time shape of an event or occurrence.
+"""
+union GraphqlEventTime = GraphqlTimedEventTime | GraphqlAllDayEventTime
+
"""
GraphQL fields for an ordered favorite.
"""
@@ -7142,6 +7716,24 @@ type GraphqlTeamRolePermission {
role: GraphqlTeamRole!
}
+"""
+A span with absolute instants.
+"""
+type GraphqlTimedEventTime {
+ """
+ Inclusive start instant in RFC 3339 format.
+ """
+ startsAt: String!
+ """
+ Exclusive end instant in RFC 3339 format.
+ """
+ endsAt: String!
+ """
+ Original IANA time-zone identifier, when supplied.
+ """
+ timeZone: String
+}
+
"""
An update to an existing notification.
"""
@@ -7208,6 +7800,16 @@ type GraphqlUser {
"""
activityOverview(input: ActivityOverviewInput!): GraphqlActivityOverview!
"""
+ Every calendar visible across owned and delegated inboxes, primaries
+ and writables first.
+ """
+ calendars: [GraphqlCalendar!]!
+ """
+ One page of occurrences overlapping the viewport, across owned and
+ delegated inboxes, ordered by start.
+ """
+ calendarOccurrences(input: CalendarRangeInput!): GraphqlCalendarOccurrencePage!
+ """
Labels across every owned or delegated inbox accessible to the authenticated user.
"""
emailLabels: [GraphqlSoupEmailLabel!]!