Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(calendar): add calendar event foundation (stack 1/3) (#5202)
teof24f2cf1a302
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 8150cc8bea..c28c90d407 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -572,6 +572,21 @@"crates/model-error-response","crates/workspace-hack"],+ "calendar_events": [+ "crates/bot_id",+ "crates/calendar_events",+ "crates/cowlike",+ "crates/macro_auth",+ "crates/macro_authorization",+ "crates/macro_env",+ "crates/macro_env_var",+ "crates/macro_user_id",+ "crates/model-error-response",+ "crates/model_user",+ "crates/models_pagination",+ "crates/remote_env_var",+ "crates/workspace-hack"+ ],"call": ["crates/agent","crates/ai_toolset",@@ -1521,6 +1536,7 @@"crates/bots","crates/broadcast","crates/cal",+ "crates/calendar_events","crates/call","crates/channel_bots","crates/channel_sender",diff --git a/.sqlx/query-014857853dbc87a9f72cecef3a01d4310c17ec7bbaccfc9e0458e7ca090ebb3b.json b/.sqlx/query-014857853dbc87a9f72cecef3a01d4310c17ec7bbaccfc9e0458e7ca090ebb3b.jsonnew file mode 100644index 0000000000..7d1107a2a8--- /dev/null+++ b/.sqlx/query-014857853dbc87a9f72cecef3a01d4310c17ec7bbaccfc9e0458e7ca090ebb3b.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH deleted_sources AS (\n DELETE FROM calendar_event_sources source\n WHERE source.source_kind = 'google'\n AND source.account_id = $1\n AND (\n source.calendar_id IS NULL\n OR NOT (source.calendar_id = ANY($2::uuid[]))\n )\n RETURNING source.event_id\n )\n SELECT DISTINCT event_id AS \"event_id!\"\n FROM deleted_sources\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "event_id!",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "UuidArray"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "014857853dbc87a9f72cecef3a01d4310c17ec7bbaccfc9e0458e7ca090ebb3b"+}diff --git a/.sqlx/query-02066775ff34eaeb9b6b6cfb52b9d85411aa5f22242c8b4587235c5da1ff12a2.json b/.sqlx/query-02066775ff34eaeb9b6b6cfb52b9d85411aa5f22242c8b4587235c5da1ff12a2.jsonnew file mode 100644index 0000000000..1b9a17ec1d--- /dev/null+++ b/.sqlx/query-02066775ff34eaeb9b6b6cfb52b9d85411aa5f22242c8b4587235c5da1ff12a2.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM calendar_event_occurrences WHERE event_id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "02066775ff34eaeb9b6b6cfb52b9d85411aa5f22242c8b4587235c5da1ff12a2"+}diff --git a/.sqlx/query-02bb9efa7e82c246202a616f863f4eff8a2a363af3672d17c4f11c133fde8c59.json b/.sqlx/query-02bb9efa7e82c246202a616f863f4eff8a2a363af3672d17c4f11c133fde8c59.jsonnew file mode 100644index 0000000000..6d0f944a32--- /dev/null+++ b/.sqlx/query-02bb9efa7e82c246202a616f863f4eff8a2a363af3672d17c4f11c133fde8c59.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM calendar_events WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "02bb9efa7e82c246202a616f863f4eff8a2a363af3672d17c4f11c133fde8c59"+}diff --git a/.sqlx/query-271758757a6ddfc04a2f5491ce9c33009589c65ec82f5b0714c7cb62da10a31b.json b/.sqlx/query-271758757a6ddfc04a2f5491ce9c33009589c65ec82f5b0714c7cb62da10a31b.jsonnew file mode 100644index 0000000000..2641ceef1b--- /dev/null+++ b/.sqlx/query-271758757a6ddfc04a2f5491ce9c33009589c65ec82f5b0714c7cb62da10a31b.json@@ -0,0 +1,35 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendar_backfill_jobs\n SET status = 'pending',\n cursor = '{}',\n scanned_count = 0,\n extracted_count = 0,\n last_error = NULL,\n started_at = NULL,\n completed_at = NULL,\n lease_expires_at = NULL,\n updated_at = now()\n WHERE email_link_id = $1\n AND grant_version = $2\n AND status = 'failed'\n RETURNING id, account_id, kind\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "account_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "kind",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Int8"+ ]+ },+ "nullable": [+ false,+ true,+ false+ ]+ },+ "hash": "271758757a6ddfc04a2f5491ce9c33009589c65ec82f5b0714c7cb62da10a31b"+}diff --git a/.sqlx/query-2c86898008635070716de7fdbcbbcab822deaf422c400722f74fc7a586955421.json b/.sqlx/query-2c86898008635070716de7fdbcbbcab822deaf422c400722f74fc7a586955421.jsonnew file mode 100644index 0000000000..a717c9b91d--- /dev/null+++ b/.sqlx/query-2c86898008635070716de7fdbcbbcab822deaf422c400722f74fc7a586955421.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendar_accounts\n SET sync_status = 'syncing',\n last_sync_error = NULL,\n updated_at = now()\n WHERE email_link_id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "2c86898008635070716de7fdbcbbcab822deaf422c400722f74fc7a586955421"+}diff --git a/.sqlx/query-3144ce757f86017ac9c97db6c0cb01d98d21234f8ef36e9ba6b90ac1a02f6ba7.json b/.sqlx/query-3144ce757f86017ac9c97db6c0cb01d98d21234f8ef36e9ba6b90ac1a02f6ba7.jsonnew file mode 100644index 0000000000..317392c953--- /dev/null+++ b/.sqlx/query-3144ce757f86017ac9c97db6c0cb01d98d21234f8ef36e9ba6b90ac1a02f6ba7.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM calendar_event_attendees WHERE event_id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "3144ce757f86017ac9c97db6c0cb01d98d21234f8ef36e9ba6b90ac1a02f6ba7"+}diff --git a/.sqlx/query-3d30393b7a33dc18e4de1e08a59bcd83110ca2ef5c786c62e3600bc666d3798f.json b/.sqlx/query-3d30393b7a33dc18e4de1e08a59bcd83110ca2ef5c786c62e3600bc666d3798f.jsonnew file mode 100644index 0000000000..6bc26a9b85--- /dev/null+++ b/.sqlx/query-3d30393b7a33dc18e4de1e08a59bcd83110ca2ef5c786c62e3600bc666d3798f.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH due AS (\n UPDATE calendar_backfill_jobs job\n SET status = 'pending',\n cursor = '{}',\n scanned_count = 0,\n extracted_count = 0,\n last_error = NULL,\n started_at = NULL,\n completed_at = NULL,\n lease_token = NULL,\n lease_expires_at = NULL,\n updated_at = now()\n FROM calendar_accounts account, email_links link\n WHERE job.email_link_id = account.email_link_id\n AND job.account_id = account.id\n AND link.id = job.email_link_id\n AND job.kind = 'google_calendar'\n AND job.status = 'complete'\n AND job.grant_version = link.google_grant_version\n AND link.google_granted_scopes @> $2::text[]\n AND account.sync_status = 'ready'\n AND account.last_synced_at <= $1\n RETURNING job.id\n ),\n republished AS (\n UPDATE calendar_sync_outbox outbox\n SET published_at = NULL\n FROM due\n WHERE outbox.backfill_job_id = due.id\n )\n SELECT count(*) AS \"due_count!\" FROM due\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "due_count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Timestamptz",+ "TextArray"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "3d30393b7a33dc18e4de1e08a59bcd83110ca2ef5c786c62e3600bc666d3798f"+}diff --git a/.sqlx/query-4bfde0b8d8c595488386d439b699996f1c5bf4a8169decb1e7f31dac474f875a.json b/.sqlx/query-4bfde0b8d8c595488386d439b699996f1c5bf4a8169decb1e7f31dac474f875a.jsonnew file mode 100644index 0000000000..2bdcc6e557--- /dev/null+++ b/.sqlx/query-4bfde0b8d8c595488386d439b699996f1c5bf4a8169decb1e7f31dac474f875a.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM calendar_accounts account\n WHERE account.sync_status IN ('pending', 'syncing')\n AND (\n account.owner_id = $1\n OR EXISTS (\n SELECT 1\n FROM macro_user_links link\n WHERE link.link_id = account.email_link_id\n AND link.primary_macro_id = $1\n )\n )\n ) AS \"is_syncing!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "is_syncing!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "4bfde0b8d8c595488386d439b699996f1c5bf4a8169decb1e7f31dac474f875a"+}diff --git a/.sqlx/query-52f1475a6789f0edeccf8775d240f75af28d42c8aa16518bbfe103feabddc788.json b/.sqlx/query-52f1475a6789f0edeccf8775d240f75af28d42c8aa16518bbfe103feabddc788.jsonnew file mode 100644index 0000000000..1ab1134cfd--- /dev/null+++ b/.sqlx/query-52f1475a6789f0edeccf8775d240f75af28d42c8aa16518bbfe103feabddc788.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendar_accounts\n SET sync_status = $2,\n last_sync_error = $3,\n updated_at = now()\n WHERE email_link_id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "52f1475a6789f0edeccf8775d240f75af28d42c8aa16518bbfe103feabddc788"+}diff --git a/.sqlx/query-58590b2ea830ad78615b548409a61101cf215e4f3871293c46d5af67886bf483.json b/.sqlx/query-58590b2ea830ad78615b548409a61101cf215e4f3871293c46d5af67886bf483.jsonnew file mode 100644index 0000000000..e9d24e9734--- /dev/null+++ b/.sqlx/query-58590b2ea830ad78615b548409a61101cf215e4f3871293c46d5af67886bf483.json@@ -0,0 +1,19 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendar_backfill_jobs\n SET status = $4,\n lease_expires_at = NULL,\n lease_token = NULL,\n last_error = $2,\n completed_at = $5,\n updated_at = now()\n WHERE id = $1\n AND email_link_id = $3\n AND kind = 'google_calendar'\n AND status NOT IN ('complete', 'failed')\n AND lease_token IS NULL\n AND EXISTS (\n SELECT 1\n FROM email_links link\n WHERE link.id = calendar_backfill_jobs.email_link_id\n AND link.google_grant_version = calendar_backfill_jobs.grant_version\n AND link.google_granted_scopes @> $6::text[]\n )\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Uuid",+ "Text",+ "Timestamptz",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "58590b2ea830ad78615b548409a61101cf215e4f3871293c46d5af67886bf483"+}diff --git a/.sqlx/query-5f8bfcd300cac264e4d3d710c9cc53d60babea1c8d9d1b4c04d6eb8bb5b022a0.json b/.sqlx/query-5f8bfcd300cac264e4d3d710c9cc53d60babea1c8d9d1b4c04d6eb8bb5b022a0.jsonnew file mode 100644index 0000000000..2126195c9e--- /dev/null+++ b/.sqlx/query-5f8bfcd300cac264e4d3d710c9cc53d60babea1c8d9d1b4c04d6eb8bb5b022a0.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE email_links\n SET needs_reauth = true,\n last_sync_error_at = now(),\n updated_at = now()\n WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "5f8bfcd300cac264e4d3d710c9cc53d60babea1c8d9d1b4c04d6eb8bb5b022a0"+}diff --git a/.sqlx/query-67eae087e054d9ee6b69e62afc257ca564634573b6755705471f760ca6a5d7cc.json b/.sqlx/query-67eae087e054d9ee6b69e62afc257ca564634573b6755705471f760ca6a5d7cc.jsonnew file mode 100644index 0000000000..476922371c--- /dev/null+++ b/.sqlx/query-67eae087e054d9ee6b69e62afc257ca564634573b6755705471f760ca6a5d7cc.json@@ -0,0 +1,25 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO calendar_event_sources (\n id, event_id, source_link_id, source_kind, account_id, calendar_id,\n provider_event_id, provider_recurring_event_id,\n provider_etag, raw_payload, source_sequence,\n source_updated_at, normalized_payload\n )\n VALUES (\n $1, $2, $3, 'google', $4, $5, $6, $7, $8, $9,\n $10, $11, $12\n )\n ON CONFLICT (account_id, calendar_id, provider_event_id)\n WHERE source_kind = 'google'\n DO UPDATE SET\n event_id = EXCLUDED.event_id,\n provider_recurring_event_id = EXCLUDED.provider_recurring_event_id,\n provider_etag = EXCLUDED.provider_etag,\n raw_payload = EXCLUDED.raw_payload,\n source_sequence = EXCLUDED.source_sequence,\n source_updated_at = EXCLUDED.source_updated_at,\n normalized_payload = EXCLUDED.normalized_payload,\n last_seen_at = now()\n WHERE\n EXCLUDED.source_sequence > calendar_event_sources.source_sequence\n OR (\n EXCLUDED.source_sequence = calendar_event_sources.source_sequence\n AND EXCLUDED.source_updated_at >= calendar_event_sources.source_updated_at\n )\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Uuid",+ "Uuid",+ "Uuid",+ "Text",+ "Text",+ "Text",+ "Jsonb",+ "Int4",+ "Timestamptz",+ "Jsonb"+ ]+ },+ "nullable": []+ },+ "hash": "67eae087e054d9ee6b69e62afc257ca564634573b6755705471f760ca6a5d7cc"+}diff --git a/.sqlx/query-6f5bf99afcee1c1a58ee3019d2f7adcede67b10ef449bb438ca0326904fe7b76.json b/.sqlx/query-6f5bf99afcee1c1a58ee3019d2f7adcede67b10ef449bb438ca0326904fe7b76.jsonnew file mode 100644index 0000000000..e26752cb55--- /dev/null+++ b/.sqlx/query-6f5bf99afcee1c1a58ee3019d2f7adcede67b10ef449bb438ca0326904fe7b76.json@@ -0,0 +1,26 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO calendar_backfill_jobs (\n id, email_link_id, account_id, kind, grant_version\n )\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (email_link_id, kind, grant_version) DO NOTHING\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Uuid",+ "Text",+ "Int8"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "6f5bf99afcee1c1a58ee3019d2f7adcede67b10ef449bb438ca0326904fe7b76"+}diff --git a/.sqlx/query-7352a4e38f94ff4966822f67d54e7199a7b089264a0d632501aa73e13807df87.json b/.sqlx/query-7352a4e38f94ff4966822f67d54e7199a7b089264a0d632501aa73e13807df87.jsonnew file mode 100644index 0000000000..658f935476--- /dev/null+++ b/.sqlx/query-7352a4e38f94ff4966822f67d54e7199a7b089264a0d632501aa73e13807df87.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendars\n SET is_deleted = true,\n sync_token = NULL,\n materialized_starts_at = NULL,\n materialized_ends_at = NULL,\n materialized_start_date = NULL,\n materialized_end_date = NULL,\n updated_at = now()\n WHERE account_id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "7352a4e38f94ff4966822f67d54e7199a7b089264a0d632501aa73e13807df87"+}diff --git a/.sqlx/query-7df4af241ff7b68d6545c4ebfb75a6e15d89b5892d16f96b30fe345d68fe9692.json b/.sqlx/query-7df4af241ff7b68d6545c4ebfb75a6e15d89b5892d16f96b30fe345d68fe9692.jsonnew file mode 100644index 0000000000..a3c1323911--- /dev/null+++ b/.sqlx/query-7df4af241ff7b68d6545c4ebfb75a6e15d89b5892d16f96b30fe345d68fe9692.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO calendar_sync_outbox (\n id, backfill_job_id\n )\n VALUES ($1, $2)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "7df4af241ff7b68d6545c4ebfb75a6e15d89b5892d16f96b30fe345d68fe9692"+}diff --git a/.sqlx/query-7ed816413df9e27798a8b60c203ec09b698d3bcb1445310de3b1eb115978c506.json b/.sqlx/query-7ed816413df9e27798a8b60c203ec09b698d3bcb1445310de3b1eb115978c506.jsonnew file mode 100644index 0000000000..99ff8dac9a--- /dev/null+++ b/.sqlx/query-7ed816413df9e27798a8b60c203ec09b698d3bcb1445310de3b1eb115978c506.json@@ -0,0 +1,25 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO calendar_accounts (\n id, owner_id, email_link_id, provider, provider_account_id\n )\n VALUES ($1, $2, $3, 'google', $4)\n ON CONFLICT (email_link_id) DO UPDATE SET\n owner_id = EXCLUDED.owner_id,\n provider_account_id = EXCLUDED.provider_account_id,\n sync_status = CASE\n WHEN calendar_accounts.sync_status = 'disabled' THEN 'pending'\n ELSE calendar_accounts.sync_status\n END,\n last_sync_error = CASE\n WHEN calendar_accounts.sync_status = 'disabled' THEN NULL\n ELSE calendar_accounts.last_sync_error\n END,\n updated_at = now()\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "7ed816413df9e27798a8b60c203ec09b698d3bcb1445310de3b1eb115978c506"+}diff --git a/.sqlx/query-84ede6396597a4b9a9177f8e1bf34ec18a79cd437e09a9b07e0557ad8ab84a10.json b/.sqlx/query-84ede6396597a4b9a9177f8e1bf34ec18a79cd437e09a9b07e0557ad8ab84a10.jsonnew file mode 100644index 0000000000..4a6e7b464f--- /dev/null+++ b/.sqlx/query-84ede6396597a4b9a9177f8e1bf34ec18a79cd437e09a9b07e0557ad8ab84a10.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendar_accounts\n SET sync_status = 'disabled',\n last_sync_error = 'Google Calendar permission is no longer granted',\n updated_at = now()\n WHERE email_link_id = $1\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "84ede6396597a4b9a9177f8e1bf34ec18a79cd437e09a9b07e0557ad8ab84a10"+}diff --git a/.sqlx/query-85b80545ac8b54f59d866d1df979c399454a20f0985229d2c6bd423f9aa8d305.json b/.sqlx/query-85b80545ac8b54f59d866d1df979c399454a20f0985229d2c6bd423f9aa8d305.jsonnew file mode 100644index 0000000000..81d133e22f--- /dev/null+++ b/.sqlx/query-85b80545ac8b54f59d866d1df979c399454a20f0985229d2c6bd423f9aa8d305.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendar_accounts\n SET sync_status = 'ready',\n last_synced_at = now(),\n last_sync_error = NULL,\n updated_at = now()\n WHERE email_link_id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "85b80545ac8b54f59d866d1df979c399454a20f0985229d2c6bd423f9aa8d305"+}diff --git a/.sqlx/query-89463db6b747da3ef34bd6025b5559f8b880a8024c0faf3fd5b08eb342b1db67.json b/.sqlx/query-89463db6b747da3ef34bd6025b5559f8b880a8024c0faf3fd5b08eb342b1db67.jsonnew file mode 100644index 0000000000..6de6a09bbb--- /dev/null+++ b/.sqlx/query-89463db6b747da3ef34bd6025b5559f8b880a8024c0faf3fd5b08eb342b1db67.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO calendar_event_occurrences (\n event_id, owner_id, occurrence_key, recurrence_id,\n starts_at, ends_at, start_date, end_date, is_cancelled\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Text",+ "Timestamptz",+ "Timestamptz",+ "Date",+ "Date",+ "Bool"+ ]+ },+ "nullable": []+ },+ "hash": "89463db6b747da3ef34bd6025b5559f8b880a8024c0faf3fd5b08eb342b1db67"+}diff --git a/.sqlx/query-8a9ec56cfa14540348c10d84ca4dece2ebb721e91dda88b42162771b407d302d.json b/.sqlx/query-8a9ec56cfa14540348c10d84ca4dece2ebb721e91dda88b42162771b407d302d.jsonnew file mode 100644index 0000000000..d6b8d6537c--- /dev/null+++ b/.sqlx/query-8a9ec56cfa14540348c10d84ca4dece2ebb721e91dda88b42162771b407d302d.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendar_backfill_jobs\n SET lease_expires_at = now() + interval '2 minutes',\n updated_at = now()\n WHERE id = $1\n AND email_link_id = $2\n AND status = 'running'\n AND lease_token = $3\n AND lease_expires_at > now()\n AND EXISTS (\n SELECT 1\n FROM email_links link\n WHERE link.id = calendar_backfill_jobs.email_link_id\n AND link.google_grant_version = calendar_backfill_jobs.grant_version\n AND link.google_granted_scopes @> $4::text[]\n )\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "8a9ec56cfa14540348c10d84ca4dece2ebb721e91dda88b42162771b407d302d"+}diff --git a/.sqlx/query-922047410f05e4563b8589bfcbbc8b3d9eae022fdd11c07989b0b31a1a504159.json b/.sqlx/query-922047410f05e4563b8589bfcbbc8b3d9eae022fdd11c07989b0b31a1a504159.jsonnew file mode 100644index 0000000000..dd5d6bcc5c--- /dev/null+++ b/.sqlx/query-922047410f05e4563b8589bfcbbc8b3d9eae022fdd11c07989b0b31a1a504159.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendar_sync_outbox\n SET published_at = NULL\n WHERE backfill_job_id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "922047410f05e4563b8589bfcbbc8b3d9eae022fdd11c07989b0b31a1a504159"+}diff --git a/.sqlx/query-9b61a81388b53e93e441a043db317e32e912688bb5c04a8de2331ae24265bd20.json b/.sqlx/query-9b61a81388b53e93e441a043db317e32e912688bb5c04a8de2331ae24265bd20.jsonnew file mode 100644index 0000000000..35bc784ef5--- /dev/null+++ b/.sqlx/query-9b61a81388b53e93e441a043db317e32e912688bb5c04a8de2331ae24265bd20.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH deleted_sources AS (\n DELETE FROM calendar_event_sources source\n WHERE source.source_kind = 'google'\n AND source.account_id = $1\n AND source.calendar_id = $2\n AND (\n source.provider_event_id = ANY($3::text[])\n OR source.provider_recurring_event_id = ANY($3::text[])\n )\n RETURNING source.event_id\n )\n SELECT DISTINCT event_id AS \"event_id!\"\n FROM deleted_sources\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "event_id!",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "9b61a81388b53e93e441a043db317e32e912688bb5c04a8de2331ae24265bd20"+}diff --git a/.sqlx/query-a67a9d4ba9add6dbedaff410fba31c7c2320baefd11df560e9c4ef0e1160c20e.json b/.sqlx/query-a67a9d4ba9add6dbedaff410fba31c7c2320baefd11df560e9c4ef0e1160c20e.jsonnew file mode 100644index 0000000000..d24209d33c--- /dev/null+++ b/.sqlx/query-a67a9d4ba9add6dbedaff410fba31c7c2320baefd11df560e9c4ef0e1160c20e.json@@ -0,0 +1,26 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT job.id\n FROM calendar_backfill_jobs job\n WHERE job.id = $1\n AND job.email_link_id = $2\n AND job.kind = 'google_calendar'\n AND job.status = 'running'\n AND job.lease_token = $3\n AND job.lease_expires_at > now()\n AND EXISTS (\n SELECT 1\n FROM email_links link\n WHERE link.id = job.email_link_id\n AND link.google_grant_version = job.grant_version\n AND link.google_granted_scopes @> $5::text[]\n )\n AND EXISTS (\n SELECT 1\n FROM calendar_accounts account\n WHERE account.id = job.account_id\n AND account.email_link_id = job.email_link_id\n AND account.sync_status <> 'disabled'\n AND ($4::uuid IS NULL OR account.id = $4)\n )\n FOR UPDATE OF job\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Uuid",+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "a67a9d4ba9add6dbedaff410fba31c7c2320baefd11df560e9c4ef0e1160c20e"+}diff --git a/.sqlx/query-adb83ca0fd4a69e6129b89df6a740e705b5fa34381265d81403a44a776919439.json b/.sqlx/query-adb83ca0fd4a69e6129b89df6a740e705b5fa34381265d81403a44a776919439.jsonnew file mode 100644index 0000000000..deaed3af2e--- /dev/null+++ b/.sqlx/query-adb83ca0fd4a69e6129b89df6a740e705b5fa34381265d81403a44a776919439.json@@ -0,0 +1,61 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO calendars (\n id, account_id, provider_calendar_id, name, description,\n time_zone, color, access_role, is_primary, is_selected\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n ON CONFLICT (account_id, provider_calendar_id) DO UPDATE SET\n name = EXCLUDED.name,\n description = EXCLUDED.description,\n time_zone = EXCLUDED.time_zone,\n color = EXCLUDED.color,\n access_role = EXCLUDED.access_role,\n is_primary = EXCLUDED.is_primary,\n is_selected = EXCLUDED.is_selected,\n is_deleted = false,\n updated_at = now()\n RETURNING\n id,\n sync_token,\n materialized_starts_at,\n materialized_ends_at,\n materialized_start_date,\n materialized_end_date\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "sync_token",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "materialized_starts_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 3,+ "name": "materialized_ends_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 4,+ "name": "materialized_start_date",+ "type_info": "Date"+ },+ {+ "ordinal": 5,+ "name": "materialized_end_date",+ "type_info": "Date"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Bool",+ "Bool"+ ]+ },+ "nullable": [+ false,+ true,+ true,+ true,+ true,+ true+ ]+ },+ "hash": "adb83ca0fd4a69e6129b89df6a740e705b5fa34381265d81403a44a776919439"+}diff --git a/.sqlx/query-afa4f92ec00bda91b89bf08dcc20fcb96bf29248f9ec8c39e178c126c0b653e4.json b/.sqlx/query-afa4f92ec00bda91b89bf08dcc20fcb96bf29248f9ec8c39e178c126c0b653e4.jsonnew file mode 100644index 0000000000..075fbe90e2--- /dev/null+++ b/.sqlx/query-afa4f92ec00bda91b89bf08dcc20fcb96bf29248f9ec8c39e178c126c0b653e4.json@@ -0,0 +1,64 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n event_id, email, display_name, response_status,\n is_organizer, is_optional, is_self, comment\n FROM calendar_event_attendees\n WHERE event_id = ANY($1)\n ORDER BY event_id, email\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "event_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "email",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "display_name",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "response_status",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "is_organizer",+ "type_info": "Bool"+ },+ {+ "ordinal": 5,+ "name": "is_optional",+ "type_info": "Bool"+ },+ {+ "ordinal": 6,+ "name": "is_self",+ "type_info": "Bool"+ },+ {+ "ordinal": 7,+ "name": "comment",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ false,+ false,+ false,+ false,+ true+ ]+ },+ "hash": "afa4f92ec00bda91b89bf08dcc20fcb96bf29248f9ec8c39e178c126c0b653e4"+}diff --git a/.sqlx/query-b6e979bed8e80a7ca84683f2e88b210d5076f7dbdcb0047e6ab5bdbdfafab839.json b/.sqlx/query-b6e979bed8e80a7ca84683f2e88b210d5076f7dbdcb0047e6ab5bdbdfafab839.jsonnew file mode 100644index 0000000000..6a4ec09096--- /dev/null+++ b/.sqlx/query-b6e979bed8e80a7ca84683f2e88b210d5076f7dbdcb0047e6ab5bdbdfafab839.json@@ -0,0 +1,25 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendar_backfill_jobs\n SET status = 'running',\n started_at = COALESCE(started_at, now()),\n lease_token = $3,\n lease_expires_at = now() + interval '2 minutes',\n last_error = NULL,\n updated_at = now()\n WHERE id = $1\n AND email_link_id = $2\n AND kind = 'google_calendar'\n AND EXISTS (\n SELECT 1\n FROM email_links link\n WHERE link.id = calendar_backfill_jobs.email_link_id\n AND link.google_grant_version = calendar_backfill_jobs.grant_version\n AND link.google_granted_scopes @> $4::text[]\n )\n AND EXISTS (\n SELECT 1\n FROM calendar_accounts account\n WHERE account.id = calendar_backfill_jobs.account_id\n AND account.email_link_id = calendar_backfill_jobs.email_link_id\n AND account.sync_status <> 'disabled'\n )\n AND (\n status = 'pending'\n OR (\n status = 'running'\n AND lease_expires_at < now()\n )\n )\n RETURNING account_id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "account_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "b6e979bed8e80a7ca84683f2e88b210d5076f7dbdcb0047e6ab5bdbdfafab839"+}diff --git a/.sqlx/query-c1c5a087a867d385bdbc0788af416a65a1d34ad733f48280e6f817ae6590b57e.json b/.sqlx/query-c1c5a087a867d385bdbc0788af416a65a1d34ad733f48280e6f817ae6590b57e.jsonnew file mode 100644index 0000000000..77f4c51245--- /dev/null+++ b/.sqlx/query-c1c5a087a867d385bdbc0788af416a65a1d34ad733f48280e6f817ae6590b57e.json@@ -0,0 +1,18 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendar_backfill_jobs\n SET status = 'complete',\n extracted_count = $2,\n completed_at = now(),\n lease_token = NULL,\n lease_expires_at = NULL,\n updated_at = now()\n WHERE id = $1\n AND email_link_id = $3\n AND kind = 'google_calendar'\n AND status = 'running'\n AND lease_token = $4\n AND lease_expires_at > now()\n AND EXISTS (\n SELECT 1\n FROM email_links link\n WHERE link.id = calendar_backfill_jobs.email_link_id\n AND link.google_grant_version = calendar_backfill_jobs.grant_version\n AND link.google_granted_scopes @> $5::text[]\n )\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Int8",+ "Uuid",+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "c1c5a087a867d385bdbc0788af416a65a1d34ad733f48280e6f817ae6590b57e"+}diff --git a/.sqlx/query-c1e3f6c64b310c965b6fefabd5ca8a62fc49058fdd1fd475a737b0a9c50eb304.json b/.sqlx/query-c1e3f6c64b310c965b6fefabd5ca8a62fc49058fdd1fd475a737b0a9c50eb304.jsonnew file mode 100644index 0000000000..0317dcf36e--- /dev/null+++ b/.sqlx/query-c1e3f6c64b310c965b6fefabd5ca8a62fc49058fdd1fd475a737b0a9c50eb304.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT needs_reauth\n FROM email_links\n WHERE id = $1\n FOR UPDATE\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "needs_reauth",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "c1e3f6c64b310c965b6fefabd5ca8a62fc49058fdd1fd475a737b0a9c50eb304"+}diff --git a/.sqlx/query-c63bed5edd67aa1ac135d71c40965db9013e54b7d32491a64293d15cbc6fe654.json b/.sqlx/query-c63bed5edd67aa1ac135d71c40965db9013e54b7d32491a64293d15cbc6fe654.jsonnew file mode 100644index 0000000000..16aecde5b9--- /dev/null+++ b/.sqlx/query-c63bed5edd67aa1ac135d71c40965db9013e54b7d32491a64293d15cbc6fe654.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH deleted_sources AS (\n DELETE FROM calendar_event_sources source\n WHERE source.source_kind = 'google'\n AND source.account_id = $1\n AND source.calendar_id = $2\n AND NOT (source.provider_event_id = ANY($3::text[]))\n RETURNING source.event_id\n )\n SELECT DISTINCT event_id AS \"event_id!\"\n FROM deleted_sources\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "event_id!",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "c63bed5edd67aa1ac135d71c40965db9013e54b7d32491a64293d15cbc6fe654"+}diff --git a/.sqlx/query-c65dbb2fce28734477e2c1e40d3a0f0b49e75e41bceb0133b74794fbe2144ce7.json b/.sqlx/query-c65dbb2fce28734477e2c1e40d3a0f0b49e75e41bceb0133b74794fbe2144ce7.jsonnew file mode 100644index 0000000000..554d3124f4--- /dev/null+++ b/.sqlx/query-c65dbb2fce28734477e2c1e40d3a0f0b49e75e41bceb0133b74794fbe2144ce7.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO calendar_event_sources (\n id, event_id, source_link_id, source_kind, email_link_id, email_thread_id,\n email_message_id, email_attachment_id, content_hash,\n raw_payload, source_sequence, source_updated_at, normalized_payload\n )\n VALUES (\n $1, $2, $3, 'email_ics', $3, $4, $5, $6, $7, $8,\n $9, $10, $11\n )\n ON CONFLICT (\n email_link_id,\n email_message_id,\n COALESCE(email_attachment_id, ''),\n content_hash,\n event_id\n ) WHERE source_kind = 'email_ics'\n DO UPDATE SET\n raw_payload = EXCLUDED.raw_payload,\n source_sequence = EXCLUDED.source_sequence,\n source_updated_at = EXCLUDED.source_updated_at,\n normalized_payload = EXCLUDED.normalized_payload,\n last_seen_at = now()\n WHERE\n EXCLUDED.source_sequence > calendar_event_sources.source_sequence\n OR (\n EXCLUDED.source_sequence = calendar_event_sources.source_sequence\n AND EXCLUDED.source_updated_at >= calendar_event_sources.source_updated_at\n )\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Uuid",+ "Uuid",+ "Uuid",+ "Text",+ "Text",+ "Jsonb",+ "Int4",+ "Timestamptz",+ "Jsonb"+ ]+ },+ "nullable": []+ },+ "hash": "c65dbb2fce28734477e2c1e40d3a0f0b49e75e41bceb0133b74794fbe2144ce7"+}diff --git a/.sqlx/query-c7e67578aa4f0140f493efc82b170abf0e14fa343fb22a13cf4ffc54caf27cce.json b/.sqlx/query-c7e67578aa4f0140f493efc82b170abf0e14fa343fb22a13cf4ffc54caf27cce.jsonnew file mode 100644index 0000000000..51f56e661c--- /dev/null+++ b/.sqlx/query-c7e67578aa4f0140f493efc82b170abf0e14fa343fb22a13cf4ffc54caf27cce.json@@ -0,0 +1,21 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendars\n SET sync_token = $3,\n materialized_starts_at = CASE\n WHEN $4 THEN $5\n ELSE materialized_starts_at\n END,\n materialized_ends_at = CASE\n WHEN $4 THEN $6\n ELSE materialized_ends_at\n END,\n materialized_start_date = CASE\n WHEN $4 THEN $7\n ELSE materialized_start_date\n END,\n materialized_end_date = CASE\n WHEN $4 THEN $8\n ELSE materialized_end_date\n END,\n updated_at = now()\n WHERE id = $1\n AND account_id = $2\n AND NOT is_deleted\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Text",+ "Bool",+ "Timestamptz",+ "Timestamptz",+ "Date",+ "Date"+ ]+ },+ "nullable": []+ },+ "hash": "c7e67578aa4f0140f493efc82b170abf0e14fa343fb22a13cf4ffc54caf27cce"+}diff --git a/.sqlx/query-c7eb1a0ad7368e30d78b27d81884e96846e1fdf6adf018274c3df850a7592d2c.json b/.sqlx/query-c7eb1a0ad7368e30d78b27d81884e96846e1fdf6adf018274c3df850a7592d2c.jsonnew file mode 100644index 0000000000..78e7bc70ce--- /dev/null+++ b/.sqlx/query-c7eb1a0ad7368e30d78b27d81884e96846e1fdf6adf018274c3df850a7592d2c.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT source_kind, source_updated_at, normalized_payload\n FROM calendar_event_sources\n WHERE event_id = $1\n ORDER BY\n CASE source_kind WHEN 'google' THEN 0 ELSE 1 END,\n source_sequence DESC,\n source_updated_at DESC,\n last_seen_at DESC,\n id DESC\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "source_kind",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "source_updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 2,+ "name": "normalized_payload",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "c7eb1a0ad7368e30d78b27d81884e96846e1fdf6adf018274c3df850a7592d2c"+}diff --git a/.sqlx/query-cbd7fc8fc7f1e6115f065b2a52c656b81d0afbcba06b24ce33da49e66b45657d.json b/.sqlx/query-cbd7fc8fc7f1e6115f065b2a52c656b81d0afbcba06b24ce33da49e66b45657d.jsonnew file mode 100644index 0000000000..3ea560cf3a--- /dev/null+++ b/.sqlx/query-cbd7fc8fc7f1e6115f065b2a52c656b81d0afbcba06b24ce33da49e66b45657d.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT source_link_id, ical_uid\n FROM calendar_events\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "source_link_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "ical_uid",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "cbd7fc8fc7f1e6115f065b2a52c656b81d0afbcba06b24ce33da49e66b45657d"+}diff --git a/.sqlx/query-d34ab0c8dd9fb917c9978a4b861ee510d52c4b7d3d71b995888e0948ec570e86.json b/.sqlx/query-d34ab0c8dd9fb917c9978a4b861ee510d52c4b7d3d71b995888e0948ec570e86.jsonnew file mode 100644index 0000000000..2ead3f42da--- /dev/null+++ b/.sqlx/query-d34ab0c8dd9fb917c9978a4b861ee510d52c4b7d3d71b995888e0948ec570e86.json@@ -0,0 +1,46 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO calendar_events (\n id, owner_id, source_link_id, ical_uid, title, description, location,\n status, visibility, transparency,\n starts_at, ends_at, start_date, end_date, time_zone,\n recurrence_lines, organizer_email, organizer_name,\n conference_url, sequence, is_read_only, canonical_source_kind,\n canonical_source_updated_at,\n created_at, updated_at\n )\n VALUES (\n $1, $2, $3, $4, $5, $6, $7,\n $8, $9, $10,\n $11, $12, $13, $14, $15,\n $16, $17, $18,\n $19, $20, $21, $22, $24,\n $23, $24\n )\n ON CONFLICT (owner_id, source_link_id, ical_uid) DO UPDATE SET\n title = EXCLUDED.title,\n description = EXCLUDED.description,\n location = EXCLUDED.location,\n status = EXCLUDED.status,\n visibility = EXCLUDED.visibility,\n transparency = EXCLUDED.transparency,\n starts_at = EXCLUDED.starts_at,\n ends_at = EXCLUDED.ends_at,\n start_date = EXCLUDED.start_date,\n end_date = EXCLUDED.end_date,\n time_zone = EXCLUDED.time_zone,\n recurrence_lines = EXCLUDED.recurrence_lines,\n organizer_email = EXCLUDED.organizer_email,\n organizer_name = EXCLUDED.organizer_name,\n conference_url = EXCLUDED.conference_url,\n sequence = EXCLUDED.sequence,\n is_read_only = EXCLUDED.is_read_only,\n canonical_source_kind = EXCLUDED.canonical_source_kind,\n canonical_source_updated_at = EXCLUDED.canonical_source_updated_at,\n updated_at = GREATEST(calendar_events.updated_at, EXCLUDED.updated_at)\n WHERE\n (\n $25 = 'google'\n AND (\n EXCLUDED.sequence > calendar_events.sequence\n OR (\n EXCLUDED.sequence = calendar_events.sequence\n AND EXCLUDED.canonical_source_updated_at\n >= calendar_events.canonical_source_updated_at\n )\n OR calendar_events.canonical_source_kind <> 'google'\n )\n )\n OR (\n $25 = 'email_ics'\n AND calendar_events.canonical_source_kind <> 'google'\n AND (\n EXCLUDED.sequence > calendar_events.sequence\n OR (\n EXCLUDED.sequence = calendar_events.sequence\n AND EXCLUDED.canonical_source_updated_at\n >= calendar_events.canonical_source_updated_at\n )\n )\n )\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Uuid",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Timestamptz",+ "Timestamptz",+ "Date",+ "Date",+ "Text",+ "TextArray",+ "Text",+ "Text",+ "Text",+ "Int4",+ "Bool",+ "Text",+ "Timestamptz",+ "Timestamptz",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "d34ab0c8dd9fb917c9978a4b861ee510d52c4b7d3d71b995888e0948ec570e86"+}diff --git a/.sqlx/query-d71c629aa3f531f6ad22ffd006f2852898830658d1ef06d7be7bdb736d83d46d.json b/.sqlx/query-d71c629aa3f531f6ad22ffd006f2852898830658d1ef06d7be7bdb736d83d46d.jsonnew file mode 100644index 0000000000..4e9fa7d8af--- /dev/null+++ b/.sqlx/query-d71c629aa3f531f6ad22ffd006f2852898830658d1ef06d7be7bdb736d83d46d.json@@ -0,0 +1,35 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendar_events\n SET title = $2,\n description = $3,\n location = $4,\n status = $5,\n visibility = $6,\n transparency = $7,\n starts_at = $8,\n ends_at = $9,\n start_date = $10,\n end_date = $11,\n time_zone = $12,\n recurrence_lines = $13,\n organizer_email = $14,\n organizer_name = $15,\n conference_url = $16,\n sequence = $17,\n is_read_only = $18,\n canonical_source_kind = $19,\n canonical_source_updated_at = $20,\n created_at = $21,\n updated_at = GREATEST(calendar_events.updated_at, $22)\n WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Timestamptz",+ "Timestamptz",+ "Date",+ "Date",+ "Text",+ "TextArray",+ "Text",+ "Text",+ "Text",+ "Int4",+ "Bool",+ "Text",+ "Timestamptz",+ "Timestamptz",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "d71c629aa3f531f6ad22ffd006f2852898830658d1ef06d7be7bdb736d83d46d"+}diff --git a/.sqlx/query-d8bb7e654b69ee69dd579096504df3a45fb102e38798780ad9a5a965d94dee97.json b/.sqlx/query-d8bb7e654b69ee69dd579096504df3a45fb102e38798780ad9a5a965d94dee97.jsonnew file mode 100644index 0000000000..c84cd70294--- /dev/null+++ b/.sqlx/query-d8bb7e654b69ee69dd579096504df3a45fb102e38798780ad9a5a965d94dee97.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH deleted_sources AS (\n DELETE FROM calendar_event_sources\n WHERE source_kind = 'google'\n AND account_id = $1\n RETURNING event_id\n )\n SELECT DISTINCT event_id AS \"event_id!\"\n FROM deleted_sources\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "event_id!",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "d8bb7e654b69ee69dd579096504df3a45fb102e38798780ad9a5a965d94dee97"+}diff --git a/.sqlx/query-d8e61f549341543d75ad10109e43b825dddbc00924d8f8ee72d2bc5e15438b58.json b/.sqlx/query-d8e61f549341543d75ad10109e43b825dddbc00924d8f8ee72d2bc5e15438b58.jsonnew file mode 100644index 0000000000..6df3f107a8--- /dev/null+++ b/.sqlx/query-d8e61f549341543d75ad10109e43b825dddbc00924d8f8ee72d2bc5e15438b58.json@@ -0,0 +1,198 @@+{+ "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 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.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.conference_url,\n event.sequence,\n event.is_read_only,\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 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": [+ {+ "ordinal": 0,+ "name": "event_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "occurrence_key",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "recurrence_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "occurrence_starts_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 4,+ "name": "occurrence_ends_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "occurrence_start_date",+ "type_info": "Date"+ },+ {+ "ordinal": 6,+ "name": "occurrence_end_date",+ "type_info": "Date"+ },+ {+ "ordinal": 7,+ "name": "is_cancelled",+ "type_info": "Bool"+ },+ {+ "ordinal": 8,+ "name": "owner_id",+ "type_info": "Text"+ },+ {+ "ordinal": 9,+ "name": "ical_uid",+ "type_info": "Text"+ },+ {+ "ordinal": 10,+ "name": "title",+ "type_info": "Text"+ },+ {+ "ordinal": 11,+ "name": "description",+ "type_info": "Text"+ },+ {+ "ordinal": 12,+ "name": "location",+ "type_info": "Text"+ },+ {+ "ordinal": 13,+ "name": "status",+ "type_info": "Text"+ },+ {+ "ordinal": 14,+ "name": "visibility",+ "type_info": "Text"+ },+ {+ "ordinal": 15,+ "name": "transparency",+ "type_info": "Text"+ },+ {+ "ordinal": 16,+ "name": "starts_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 17,+ "name": "ends_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 18,+ "name": "start_date",+ "type_info": "Date"+ },+ {+ "ordinal": 19,+ "name": "end_date",+ "type_info": "Date"+ },+ {+ "ordinal": 20,+ "name": "time_zone",+ "type_info": "Text"+ },+ {+ "ordinal": 21,+ "name": "recurrence_lines",+ "type_info": "TextArray"+ },+ {+ "ordinal": 22,+ "name": "organizer_email",+ "type_info": "Text"+ },+ {+ "ordinal": 23,+ "name": "organizer_name",+ "type_info": "Text"+ },+ {+ "ordinal": 24,+ "name": "conference_url",+ "type_info": "Text"+ },+ {+ "ordinal": 25,+ "name": "sequence",+ "type_info": "Int4"+ },+ {+ "ordinal": 26,+ "name": "is_read_only",+ "type_info": "Bool"+ },+ {+ "ordinal": 27,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 28,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Timestamptz",+ "Timestamptz",+ "Date",+ "Date",+ "Timestamptz",+ "Uuid",+ "Text",+ "Int8"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ true,+ true,+ true,+ true,+ false,+ false,+ false,+ false,+ true,+ true,+ false,+ false,+ false,+ true,+ true,+ true,+ true,+ true,+ false,+ true,+ true,+ true,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "d8e61f549341543d75ad10109e43b825dddbc00924d8f8ee72d2bc5e15438b58"+}diff --git a/.sqlx/query-daac011d66f30c46eb10381b31908081e0fb33e3f9440213579bbf84303d2665.json b/.sqlx/query-daac011d66f30c46eb10381b31908081e0fb33e3f9440213579bbf84303d2665.jsonnew file mode 100644index 0000000000..95e5cee0cc--- /dev/null+++ b/.sqlx/query-daac011d66f30c46eb10381b31908081e0fb33e3f9440213579bbf84303d2665.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM calendar_event_overrides WHERE event_id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "daac011d66f30c46eb10381b31908081e0fb33e3f9440213579bbf84303d2665"+}diff --git a/.sqlx/query-dacac4b0000bb86fb72bb443c79829f2e6b4f255720467b5b7d25a9dc26e3443.json b/.sqlx/query-dacac4b0000bb86fb72bb443c79829f2e6b4f255720467b5b7d25a9dc26e3443.jsonnew file mode 100644index 0000000000..99407ec873--- /dev/null+++ b/.sqlx/query-dacac4b0000bb86fb72bb443c79829f2e6b4f255720467b5b7d25a9dc26e3443.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT id FROM calendar_events WHERE owner_id = $1 AND source_link_id = $2 AND ical_uid = $3",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "dacac4b0000bb86fb72bb443c79829f2e6b4f255720467b5b7d25a9dc26e3443"+}diff --git a/.sqlx/query-db9bf75ccc15d4c0f0956829f55a8379a7f4d67f2065dd012ea8811fdf3ca791.json b/.sqlx/query-db9bf75ccc15d4c0f0956829f55a8379a7f4d67f2065dd012ea8811fdf3ca791.jsonnew file mode 100644index 0000000000..b7c664b592--- /dev/null+++ b/.sqlx/query-db9bf75ccc15d4c0f0956829f55a8379a7f4d67f2065dd012ea8811fdf3ca791.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH invalidated AS (\n UPDATE calendar_backfill_jobs\n SET status = 'failed',\n completed_at = now(),\n lease_token = NULL,\n lease_expires_at = NULL,\n last_error = 'superseded by a newer Google grant',\n updated_at = now()\n WHERE email_link_id = $1\n AND kind = 'google_calendar'\n AND grant_version <> $2\n AND status IN ('pending', 'running')\n RETURNING id\n )\n UPDATE calendar_sync_outbox outbox\n SET published_at = COALESCE(outbox.published_at, now())\n FROM invalidated\n WHERE outbox.backfill_job_id = invalidated.id\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Int8"+ ]+ },+ "nullable": []+ },+ "hash": "db9bf75ccc15d4c0f0956829f55a8379a7f4d67f2065dd012ea8811fdf3ca791"+}diff --git a/.sqlx/query-dc0f28b38858b03db61690952a29e9e04d06c7ab2660e747ac5e516b2609b722.json b/.sqlx/query-dc0f28b38858b03db61690952a29e9e04d06c7ab2660e747ac5e516b2609b722.jsonnew file mode 100644index 0000000000..3012a2d35a--- /dev/null+++ b/.sqlx/query-dc0f28b38858b03db61690952a29e9e04d06c7ab2660e747ac5e516b2609b722.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT 1 AS \"locked!\" FROM pg_advisory_xact_lock($1)",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "locked!",+ "type_info": "Int4"+ }+ ],+ "parameters": {+ "Left": [+ "Int8"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "dc0f28b38858b03db61690952a29e9e04d06c7ab2660e747ac5e516b2609b722"+}diff --git a/.sqlx/query-e05feaac668af3aeba4463d38e8b453dadb4a7563a2a1a65778fdf3364d85361.json b/.sqlx/query-e05feaac668af3aeba4463d38e8b453dadb4a7563a2a1a65778fdf3364d85361.jsonnew file mode 100644index 0000000000..845af0c791--- /dev/null+++ b/.sqlx/query-e05feaac668af3aeba4463d38e8b453dadb4a7563a2a1a65778fdf3364d85361.json@@ -0,0 +1,40 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n macro_id,\n email_address::text AS \"email_address!\",\n google_granted_scopes,\n google_grant_version\n FROM email_links\n WHERE id = $1\n FOR UPDATE\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "macro_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "email_address!",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "google_granted_scopes",+ "type_info": "TextArray"+ },+ {+ "ordinal": 3,+ "name": "google_grant_version",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ null,+ false,+ false+ ]+ },+ "hash": "e05feaac668af3aeba4463d38e8b453dadb4a7563a2a1a65778fdf3364d85361"+}diff --git a/.sqlx/query-e267121515338ddbae34ddcd2caf2907fbf5f1ae7c231b38a18255203124c3d2.json b/.sqlx/query-e267121515338ddbae34ddcd2caf2907fbf5f1ae7c231b38a18255203124c3d2.jsonnew file mode 100644index 0000000000..f1279d8bf6--- /dev/null+++ b/.sqlx/query-e267121515338ddbae34ddcd2caf2907fbf5f1ae7c231b38a18255203124c3d2.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT status, account_id\n FROM calendar_backfill_jobs\n WHERE id = $1\n AND email_link_id = $2\n AND kind = 'google_calendar'\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "status",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "account_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ false,+ true+ ]+ },+ "hash": "e267121515338ddbae34ddcd2caf2907fbf5f1ae7c231b38a18255203124c3d2"+}diff --git a/.sqlx/query-e3dfcc391adcbf41491a0db4f0939cf523addb7ff5d7c29e5ba37467f74f2ff8.json b/.sqlx/query-e3dfcc391adcbf41491a0db4f0939cf523addb7ff5d7c29e5ba37467f74f2ff8.jsonnew file mode 100644index 0000000000..e22a5c05bb--- /dev/null+++ b/.sqlx/query-e3dfcc391adcbf41491a0db4f0939cf523addb7ff5d7c29e5ba37467f74f2ff8.json@@ -0,0 +1,21 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO calendar_event_attendees (\n event_id, email, display_name, response_status,\n is_organizer, is_optional, is_self, comment\n )\n VALUES ($1, lower($2), $3, $4, $5, $6, $7, $8)\n ON CONFLICT (event_id, email) DO UPDATE SET\n display_name = EXCLUDED.display_name,\n response_status = EXCLUDED.response_status,\n is_organizer = EXCLUDED.is_organizer,\n is_optional = EXCLUDED.is_optional,\n is_self = EXCLUDED.is_self,\n comment = EXCLUDED.comment\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Text",+ "Bool",+ "Bool",+ "Bool",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "e3dfcc391adcbf41491a0db4f0939cf523addb7ff5d7c29e5ba37467f74f2ff8"+}diff --git a/.sqlx/query-eb6dbbf51c037743d063b5b7a1002d9bf794f6907df2cc49584b741798ab508b.json b/.sqlx/query-eb6dbbf51c037743d063b5b7a1002d9bf794f6907df2cc49584b741798ab508b.jsonnew file mode 100644index 0000000000..3e0eaee8fa--- /dev/null+++ b/.sqlx/query-eb6dbbf51c037743d063b5b7a1002d9bf794f6907df2cc49584b741798ab508b.json@@ -0,0 +1,20 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendar_backfill_jobs\n SET status = $4,\n lease_expires_at = NULL,\n lease_token = NULL,\n last_error = $2,\n completed_at = $5,\n updated_at = now()\n WHERE id = $1\n AND email_link_id = $3\n AND kind = 'google_calendar'\n AND status = 'running'\n AND lease_token = $6\n AND lease_expires_at > now()\n AND EXISTS (\n SELECT 1\n FROM email_links link\n WHERE link.id = calendar_backfill_jobs.email_link_id\n AND link.google_grant_version = calendar_backfill_jobs.grant_version\n AND link.google_granted_scopes @> $7::text[]\n )\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Uuid",+ "Text",+ "Timestamptz",+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "eb6dbbf51c037743d063b5b7a1002d9bf794f6907df2cc49584b741798ab508b"+}diff --git a/.sqlx/query-ef9d633f5ed4b99d7861b675347a25fa83810ab374f1a893dfbd29ada20e2553.json b/.sqlx/query-ef9d633f5ed4b99d7861b675347a25fa83810ab374f1a893dfbd29ada20e2553.jsonnew file mode 100644index 0000000000..c1e08c4fb6--- /dev/null+++ b/.sqlx/query-ef9d633f5ed4b99d7861b675347a25fa83810ab374f1a893dfbd29ada20e2553.json@@ -0,0 +1,25 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO calendar_event_overrides (\n event_id, recurrence_id, original_starts_at, original_start_date,\n starts_at, ends_at, start_date, end_date,\n title, description, location, status\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Timestamptz",+ "Date",+ "Timestamptz",+ "Timestamptz",+ "Date",+ "Date",+ "Text",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "ef9d633f5ed4b99d7861b675347a25fa83810ab374f1a893dfbd29ada20e2553"+}diff --git a/.sqlx/query-fd5ef49ce49df5ac1fbec8580a60a212664a563f1eb0bc4d61062b696cf9c320.json b/.sqlx/query-fd5ef49ce49df5ac1fbec8580a60a212664a563f1eb0bc4d61062b696cf9c320.jsonnew file mode 100644index 0000000000..ea1f2bdf08--- /dev/null+++ b/.sqlx/query-fd5ef49ce49df5ac1fbec8580a60a212664a563f1eb0bc4d61062b696cf9c320.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calendars\n SET is_deleted = NOT (id = ANY($2::uuid[])),\n sync_token = CASE\n WHEN id = ANY($2::uuid[]) THEN sync_token\n ELSE NULL\n END,\n materialized_starts_at = CASE\n WHEN id = ANY($2::uuid[]) THEN materialized_starts_at\n ELSE NULL\n END,\n materialized_ends_at = CASE\n WHEN id = ANY($2::uuid[]) THEN materialized_ends_at\n ELSE NULL\n END,\n materialized_start_date = CASE\n WHEN id = ANY($2::uuid[]) THEN materialized_start_date\n ELSE NULL\n END,\n materialized_end_date = CASE\n WHEN id = ANY($2::uuid[]) THEN materialized_end_date\n ELSE NULL\n END,\n updated_at = now()\n WHERE account_id = $1\n AND is_deleted IS DISTINCT FROM NOT (id = ANY($2::uuid[]))\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "UuidArray"+ ]+ },+ "nullable": []+ },+ "hash": "fd5ef49ce49df5ac1fbec8580a60a212664a563f1eb0bc4d61062b696cf9c320"+}diff --git a/.sqlx/query-ff945bb9f03892418e5c80fa89048f731bbbe7ea1eef8dcbad0cc1eaf365cf75.json b/.sqlx/query-ff945bb9f03892418e5c80fa89048f731bbbe7ea1eef8dcbad0cc1eaf365cf75.jsonnew file mode 100644index 0000000000..dd0f89c32b--- /dev/null+++ b/.sqlx/query-ff945bb9f03892418e5c80fa89048f731bbbe7ea1eef8dcbad0cc1eaf365cf75.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE email_links\n SET google_granted_scopes = $2,\n google_grant_version = $3,\n updated_at = now()\n WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray",+ "Int8"+ ]+ },+ "nullable": []+ },+ "hash": "ff945bb9f03892418e5c80fa89048f731bbbe7ea1eef8dcbad0cc1eaf365cf75"+}diff --git a/Cargo.lock b/Cargo.lockindex 44a26b4e57..1645a16898 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2513,6 +2513,28 @@ dependencies = ["workspace-hack",]+[[package]]+name = "calendar_events"+version = "0.1.0"+dependencies = [+ "axum",+ "chrono",+ "futures",+ "macro_authorization",+ "macro_db_migrator",+ "models_pagination",+ "rootcause",+ "serde",+ "serde_json",+ "sqlx",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+ "utoipa",+ "uuid",+ "workspace-hack",+]+[[package]]name = "call"version = "0.1.0"@@ -2844,9 +2866,9 @@ dependencies = [[[package]]name = "chrono"-version = "0.4.44"+version = "0.4.45"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0"+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"dependencies = ["iana-time-zone","js-sys",@@ -4397,6 +4419,7 @@ dependencies = ["bytes","bzip2","cal",+ "calendar_events","call","channel_bots","channels",diff --git a/Cargo.toml b/Cargo.tomlindex 7ce8074dae..d33cf816aa 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -9,6 +9,7 @@ members = ["crates/bot_id","crates/bots","crates/broadcast",+ "crates/calendar_events","crates/channel_bots","crates/client/cache-core","crates/client/cache-idb",diff --git a/apps/web/biome.jsonc b/apps/web/biome.jsoncindex ab523b24f8..e02728c156 100644--- a/apps/web/biome.jsonc+++ b/apps/web/biome.jsonc@@ -6,6 +6,8 @@"root": "../.."},"files": {+ // orval's zod.ts crossed biome's 1 MiB default once calendar schemas landed+ "maxSize": 2097152,"includes": ["**/*.{ts,tsx,js,jsx}","**/openapi.json",diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/attendeeResponseStatus.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/attendeeResponseStatus.tsnew file mode 100644index 0000000000..b5764c0bad--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/attendeeResponseStatus.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * RSVP state for an attendee.+ */+export type AttendeeResponseStatus =+ (typeof AttendeeResponseStatus)[keyof typeof AttendeeResponseStatus];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const AttendeeResponseStatus = {+ needs_action: 'needs_action',+ accepted: 'accepted',+ declined: 'declined',+ tentative: 'tentative',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarAttendee.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarAttendee.tsnew file mode 100644index 0000000000..473617618f--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarAttendee.ts@@ -0,0 +1,30 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++import type { AttendeeResponseStatus } from './attendeeResponseStatus';+import type { CalendarAttendeeComment } from './calendarAttendeeComment';+import type { CalendarAttendeeDisplayName } from './calendarAttendeeDisplayName';++/**+ * An attendee on a calendar event.+ */+export interface CalendarAttendee {+ /** Optional attendee comment. */+ comment?: CalendarAttendeeComment;+ /** Provider display name. */+ displayName?: CalendarAttendeeDisplayName;+ /** Normalized email address. */+ email: string;+ /** Whether attendance is optional. */+ isOptional: boolean;+ /** Whether this attendee is the organizer. */+ isOrganizer: boolean;+ /** Whether this attendee represents the connected account. */+ isSelf: boolean;+ /** RSVP state. */+ responseStatus: AttendeeResponseStatus;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarAttendeeComment.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarAttendeeComment.tsnew file mode 100644index 0000000000..4c2d755102--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarAttendeeComment.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional attendee comment.+ */+export type CalendarAttendeeComment = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarAttendeeDisplayName.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarAttendeeDisplayName.tsnew file mode 100644index 0000000000..22e38b11bd--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarAttendeeDisplayName.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Provider display name.+ */+export type CalendarAttendeeDisplayName = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEvent.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEvent.tsnew file mode 100644index 0000000000..6f5ac4a17d--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEvent.ts@@ -0,0 +1,63 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { CalendarAttendee } from './calendarAttendee';+import type { CalendarEventConferenceUrl } from './calendarEventConferenceUrl';+import type { CalendarEventDescription } from './calendarEventDescription';+import type { CalendarEventLocation } from './calendarEventLocation';+import type { CalendarEventOrganizerEmail } from './calendarEventOrganizerEmail';+import type { CalendarEventOrganizerName } from './calendarEventOrganizerName';+import type { EventStatus } from './eventStatus';+import type { EventTime } from './eventTime';+import type { EventTransparency } from './eventTransparency';+import type { EventVisibility } from './eventVisibility';++/**+ * A stable, first-class Macro calendar event entity.+ */+export interface CalendarEvent {+ /** Attendees, keyed by email during persistence. */+ attendees: CalendarAttendee[];+ /** Direct join URL when known. */+ conferenceUrl?: CalendarEventConferenceUrl;+ /** Entity creation time. */+ createdAt: string;+ /** Optional event body. */+ description?: CalendarEventDescription;+ /** RFC 5545 UID used to reconcile provider and email sources. */+ icalUid: string;+ /** Macro entity identifier. */+ id: string;+ /** Whether the current user can edit the canonical source. */+ isReadOnly: boolean;+ /** Optional physical or virtual location label. */+ location?: CalendarEventLocation;+ /** Organizer email. */+ organizerEmail?: CalendarEventOrganizerEmail;+ /** Organizer display name. */+ organizerName?: CalendarEventOrganizerName;+ /** Macro user who owns this event entity. */+ ownerId: string;+ /** Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`). */+ recurrenceLines: string[];+ /**+ * Provider/iCalendar sequence number.+ * @minimum 0+ */+ sequence: number;+ /** Event status. */+ status: EventStatus;+ /** Timed or all-day shape. */+ time: EventTime;+ /** Display title. */+ title: string;+ /** Availability behavior. */+ transparency: EventTransparency;+ /** Entity update time. */+ updatedAt: string;+ /** Event visibility. */+ visibility: EventVisibility;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEventConferenceUrl.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEventConferenceUrl.tsnew file mode 100644index 0000000000..b6fed6e35e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEventConferenceUrl.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Direct join URL when known.+ */+export type CalendarEventConferenceUrl = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEventDescription.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEventDescription.tsnew file mode 100644index 0000000000..808fa08019--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEventDescription.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional event body.+ */+export type CalendarEventDescription = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEventLocation.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEventLocation.tsnew file mode 100644index 0000000000..91ed3a4c87--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEventLocation.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional physical or virtual location label.+ */+export type CalendarEventLocation = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEventOrganizerEmail.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEventOrganizerEmail.tsnew file mode 100644index 0000000000..bc242782f9--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEventOrganizerEmail.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Organizer email.+ */+export type CalendarEventOrganizerEmail = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEventOrganizerName.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEventOrganizerName.tsnew file mode 100644index 0000000000..f737d50123--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarEventOrganizerName.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Organizer display name.+ */+export type CalendarEventOrganizerName = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarOccurrence.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarOccurrence.tsnew file mode 100644index 0000000000..3f0b0c3856--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarOccurrence.ts@@ -0,0 +1,24 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { CalendarOccurrenceRecurrenceId } from './calendarOccurrenceRecurrenceId';+import type { EventTime } from './eventTime';++/**+ * A materialized recurrence instance optimized for range queries.+ */+export interface CalendarOccurrence {+ /** Owning event entity. */+ eventId: string;+ /** Whether the instance was cancelled. */+ isCancelled: boolean;+ /** Stable key within the event. */+ occurrenceKey: string;+ /** Provider recurrence identifier, when applicable. */+ recurrenceId?: CalendarOccurrenceRecurrenceId;+ /** Instance time. */+ time: EventTime;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarOccurrenceItem.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarOccurrenceItem.tsnew file mode 100644index 0000000000..d5bdacd6ce--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarOccurrenceItem.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { CalendarEvent } from './calendarEvent';+import type { CalendarOccurrence } from './calendarOccurrence';++/**+ * One materialized occurrence paired with its stable calendar event entity.+ */+export interface CalendarOccurrenceItem {+ event: CalendarEvent;+ occurrence: CalendarOccurrence;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarOccurrenceRecurrenceId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarOccurrenceRecurrenceId.tsnew file mode 100644index 0000000000..b3440ea126--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarOccurrenceRecurrenceId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Provider recurrence identifier, when applicable.+ */+export type CalendarOccurrenceRecurrenceId = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarOccurrenceResponse.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarOccurrenceResponse.tsnew file mode 100644index 0000000000..f72bf8b339--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarOccurrenceResponse.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { CalendarOccurrenceItem } from './calendarOccurrenceItem';+import type { CalendarOccurrenceResponseNextCursor } from './calendarOccurrenceResponseNextCursor';+import type { CalendarSyncStatus } from './calendarSyncStatus';++/**+ * Paginated calendar occurrence viewport response.+ */+export interface CalendarOccurrenceResponse {+ hasMore: boolean;+ items: CalendarOccurrenceItem[];+ nextCursor?: CalendarOccurrenceResponseNextCursor;+ /** Aggregate ingestion state; clients render a skeleton while `syncing`. */+ syncStatus: CalendarSyncStatus;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarOccurrenceResponseNextCursor.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarOccurrenceResponseNextCursor.tsnew file mode 100644index 0000000000..402beb31f6--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarOccurrenceResponseNextCursor.ts@@ -0,0 +1,8 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type CalendarOccurrenceResponseNextCursor = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarSyncStatus.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarSyncStatus.tsnew file mode 100644index 0000000000..a0b2fc6d51--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarSyncStatus.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Aggregate ingestion state across every calendar account visible to a+requester, letting clients render progressively while sources build.+ */+export type CalendarSyncStatus =+ (typeof CalendarSyncStatus)[keyof typeof CalendarSyncStatus];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const CalendarSyncStatus = {+ syncing: 'syncing',+ ready: 'ready',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventStatus.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventStatus.tsnew file mode 100644index 0000000000..a2c1adf29f--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventStatus.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Canonical event status.+ */+export type EventStatus = (typeof EventStatus)[keyof typeof EventStatus];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const EventStatus = {+ confirmed: 'confirmed',+ tentative: 'tentative',+ cancelled: 'cancelled',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTime.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTime.tsnew file mode 100644index 0000000000..85bc126ff9--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTime.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { EventTimeOneOf } from './eventTimeOneOf';+import type { EventTimeOneOfFour } from './eventTimeOneOfFour';++/**+ * The mutually exclusive time shape of a calendar event.++Fields are renamed per variant rather than with `rename_all_fields`+because utoipa only honors variant-level serde renames when it+derives the OpenAPI schema.+ */+export type EventTime = EventTimeOneOf | EventTimeOneOfFour;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTimeOneOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTimeOneOf.tsnew file mode 100644index 0000000000..ab7d93436b--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTimeOneOf.ts@@ -0,0 +1,21 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { EventTimeOneOfKind } from './eventTimeOneOfKind';+import type { EventTimeOneOfTimeZone } from './eventTimeOneOfTimeZone';++/**+ * An event with absolute instants.+ */+export type EventTimeOneOf = {+ /** Exclusive end instant. */+ endsAt: string;+ kind: EventTimeOneOfKind;+ /** Inclusive start instant. */+ startsAt: string;+ /** Original IANA time-zone identifier, when supplied. */+ timeZone?: EventTimeOneOfTimeZone;+};diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTimeOneOfFour.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTimeOneOfFour.tsnew file mode 100644index 0000000000..6050cdc1f6--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTimeOneOfFour.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { EventTimeOneOfFourKind } from './eventTimeOneOfFourKind';++/**+ * An all-day event using RFC 5545's exclusive end date.+ */+export type EventTimeOneOfFour = {+ /** Exclusive local end date. */+ endDate: string;+ kind: EventTimeOneOfFourKind;+ /** Inclusive local start date. */+ startDate: string;+};diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTimeOneOfFourKind.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTimeOneOfFourKind.tsnew file mode 100644index 0000000000..7c1a34954a--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTimeOneOfFourKind.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type EventTimeOneOfFourKind =+ (typeof EventTimeOneOfFourKind)[keyof typeof EventTimeOneOfFourKind];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const EventTimeOneOfFourKind = {+ allDay: 'allDay',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTimeOneOfKind.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTimeOneOfKind.tsnew file mode 100644index 0000000000..2c6acc5259--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTimeOneOfKind.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type EventTimeOneOfKind =+ (typeof EventTimeOneOfKind)[keyof typeof EventTimeOneOfKind];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const EventTimeOneOfKind = {+ timed: 'timed',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTimeOneOfTimeZone.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTimeOneOfTimeZone.tsnew file mode 100644index 0000000000..0e650ffba8--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTimeOneOfTimeZone.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Original IANA time-zone identifier, when supplied.+ */+export type EventTimeOneOfTimeZone = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTransparency.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTransparency.tsnew file mode 100644index 0000000000..cd842fc63e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventTransparency.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Whether an event blocks availability.+ */+export type EventTransparency =+ (typeof EventTransparency)[keyof typeof EventTransparency];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const EventTransparency = {+ opaque: 'opaque',+ transparent: 'transparent',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventVisibility.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventVisibility.tsnew file mode 100644index 0000000000..8282721234--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/eventVisibility.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Visibility of event details.+ */+export type EventVisibility =+ (typeof EventVisibility)[keyof typeof EventVisibility];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const EventVisibility = {+ default: 'default',+ public: 'public',+ private: 'private',+ confidential: 'confidential',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.tsindex 7193199afd..efe6cd7385 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts@@ -118,6 +118,7 @@ export * from './apiThreadInfo';export * from './apiThreadInfoLatestReplyAt';export * from './apiThreadReply';export * from './apiThreadReplyEditedAt';+export * from './attendeeResponseStatus';export * from './basicDocument';export * from './basicDocumentBranchedFromId';export * from './basicDocumentBranchedFromVersionId';@@ -161,6 +162,21 @@ export * from './branchNameResponse';export * from './bTreeMap';export * from './bulkWakeupRequest';export * from './bulkWakeupResponse';+export * from './calendarAttendee';+export * from './calendarAttendeeComment';+export * from './calendarAttendeeDisplayName';+export * from './calendarEvent';+export * from './calendarEventConferenceUrl';+export * from './calendarEventDescription';+export * from './calendarEventLocation';+export * from './calendarEventOrganizerEmail';+export * from './calendarEventOrganizerName';+export * from './calendarOccurrence';+export * from './calendarOccurrenceItem';+export * from './calendarOccurrenceRecurrenceId';+export * from './calendarOccurrenceResponse';+export * from './calendarOccurrenceResponseNextCursor';+export * from './calendarSyncStatus';export * from './callActiveResponse';export * from './callFilters';export * from './callFiltersAttended';@@ -536,6 +552,15 @@ export * from './entityReference';export * from './entityReferenceSpecificMessageId';export * from './entityType';export * from './errorResponse';+export * from './eventStatus';+export * from './eventTime';+export * from './eventTimeOneOf';+export * from './eventTimeOneOfFour';+export * from './eventTimeOneOfFourKind';+export * from './eventTimeOneOfKind';+export * from './eventTimeOneOfTimeZone';+export * from './eventTransparency';+export * from './eventVisibility';export * from './excludeDefaultViewRequest';export * from './excludedDefaultView';export * from './exportDocumentResponse';@@ -677,6 +702,7 @@ export * from './latestMessage';export * from './latestMessageLatestMessage';export * from './latestMessageLatestNonThreadMessage';export * from './leaveCallResponse';+export * from './listOccurrencesParams';export * from './listWebhooksResponse';export * from './locationResponseData';export * from './locationResponseDataOneOf';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/listOccurrencesParams.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listOccurrencesParams.tsnew file mode 100644index 0000000000..f87b266ef6--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listOccurrencesParams.ts@@ -0,0 +1,35 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type ListOccurrencesParams = {+ /**+ * Inclusive UTC viewport start.+ */+ start: string;+ /**+ * Exclusive UTC viewport end.+ */+ end: string;+ /**+ * Inclusive local date boundary for all-day events.+ */+ startDate?: string;+ /**+ * Exclusive local date boundary for all-day events.+ */+ endDate?: string;+ /**+ * Maximum number of occurrences, from 1 through 2,000.+ * @minimum 1+ * @maximum 2000+ */+ limit?: number;+ /**+ * Opaque continuation cursor returned by the previous page.+ */+ cursor?: string;+};diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.tsindex a233509d85..5ac5987b2d 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts@@ -893,6 +893,240 @@ export const removeBotFromChannelByBotParams = zod.object({channel_id: zod.uuid().describe('Channel ID'),});+/**+ * @summary Return calendar occurrences visible to the authenticated requester.+ */+export const listOccurrencesQueryLimitMax = 2000;++export const listOccurrencesQueryParams = zod.object({+ start: zod.iso.datetime({}).describe('Inclusive UTC viewport start.'),+ end: zod.iso.datetime({}).describe('Exclusive UTC viewport end.'),+ startDate: zod.iso+ .date()+ .optional()+ .describe('Inclusive local date boundary for all-day events.'),+ endDate: zod.iso+ .date()+ .optional()+ .describe('Exclusive local date boundary for all-day events.'),+ limit: zod+ .number()+ .min(1)+ .max(listOccurrencesQueryLimitMax)+ .optional()+ .describe('Maximum number of occurrences, from 1 through 2,000.'),+ cursor: zod+ .string()+ .optional()+ .describe('Opaque continuation cursor returned by the previous page.'),+});++export const listOccurrencesResponseItemsItemEventSequenceMin = 0;++export const listOccurrencesResponse = zod+ .object({+ hasMore: zod.boolean(),+ items: zod.array(+ zod+ .object({+ event: zod+ .object({+ attendees: zod+ .array(+ zod+ .object({+ comment: zod+ .string()+ .nullish()+ .describe('Optional attendee comment.'),+ displayName: zod+ .string()+ .nullish()+ .describe('Provider display name.'),+ email: zod.string().describe('Normalized email address.'),+ isOptional: zod+ .boolean()+ .describe('Whether attendance is optional.'),+ isOrganizer: zod+ .boolean()+ .describe('Whether this attendee is the organizer.'),+ isSelf: zod+ .boolean()+ .describe(+ 'Whether this attendee represents the connected account.'+ ),+ responseStatus: zod+ .enum([+ 'needs_action',+ 'accepted',+ 'declined',+ 'tentative',+ ])+ .describe('RSVP state for an attendee.'),+ })+ .describe('An attendee on a calendar event.')+ )+ .describe('Attendees, keyed by email during persistence.'),+ conferenceUrl: zod+ .string()+ .nullish()+ .describe('Direct join URL when known.'),+ createdAt: zod.iso.datetime({}).describe('Entity creation time.'),+ description: zod+ .string()+ .nullish()+ .describe('Optional event body.'),+ icalUid: zod+ .string()+ .describe(+ 'RFC 5545 UID used to reconcile provider and email sources.'+ ),+ id: zod.uuid().describe('Macro entity identifier.'),+ isReadOnly: zod+ .boolean()+ .describe(+ 'Whether the current user can edit the canonical source.'+ ),+ location: zod+ .string()+ .nullish()+ .describe('Optional physical or virtual location label.'),+ organizerEmail: zod+ .string()+ .nullish()+ .describe('Organizer email.'),+ organizerName: zod+ .string()+ .nullish()+ .describe('Organizer display name.'),+ ownerId: zod+ .string()+ .describe('Macro user who owns this event entity.'),+ recurrenceLines: zod+ .array(zod.string())+ .describe(+ 'Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`).'+ ),+ sequence: zod+ .number()+ .min(listOccurrencesResponseItemsItemEventSequenceMin)+ .describe('Provider\/iCalendar sequence number.'),+ status: zod+ .enum(['confirmed', 'tentative', 'cancelled'])+ .describe('Canonical event status.'),+ time: zod+ .union([+ zod+ .object({+ endsAt: zod.iso+ .datetime({})+ .describe('Exclusive end instant.'),+ kind: zod.enum(['timed']),+ startsAt: zod.iso+ .datetime({})+ .describe('Inclusive start instant.'),+ timeZone: zod+ .string()+ .nullish()+ .describe(+ 'Original IANA time-zone identifier, when supplied.'+ ),+ })+ .describe('An event with absolute instants.'),+ zod+ .object({+ endDate: zod.iso+ .date()+ .describe('Exclusive local end date.'),+ kind: zod.enum(['allDay']),+ startDate: zod.iso+ .date()+ .describe('Inclusive local start date.'),+ })+ .describe(+ "An all-day event using RFC 5545's exclusive end date."+ ),+ ])+ .describe(+ 'The mutually exclusive time shape of a calendar event.\n\nFields are renamed per variant rather than with `rename_all_fields`\nbecause utoipa only honors variant-level serde renames when it\nderives the OpenAPI schema.'+ ),+ title: zod.string().describe('Display title.'),+ transparency: zod+ .enum(['opaque', 'transparent'])+ .describe('Whether an event blocks availability.'),+ updatedAt: zod.iso.datetime({}).describe('Entity update time.'),+ visibility: zod+ .enum(['default', 'public', 'private', 'confidential'])+ .describe('Visibility of event details.'),+ })+ .describe('A stable, first-class Macro calendar event entity.'),+ occurrence: zod+ .object({+ eventId: zod.uuid().describe('Owning event entity.'),+ isCancelled: zod+ .boolean()+ .describe('Whether the instance was cancelled.'),+ occurrenceKey: zod+ .string()+ .describe('Stable key within the event.'),+ recurrenceId: zod+ .string()+ .nullish()+ .describe('Provider recurrence identifier, when applicable.'),+ time: zod+ .union([+ zod+ .object({+ endsAt: zod.iso+ .datetime({})+ .describe('Exclusive end instant.'),+ kind: zod.enum(['timed']),+ startsAt: zod.iso+ .datetime({})+ .describe('Inclusive start instant.'),+ timeZone: zod+ .string()+ .nullish()+ .describe(+ 'Original IANA time-zone identifier, when supplied.'+ ),+ })+ .describe('An event with absolute instants.'),+ zod+ .object({+ endDate: zod.iso+ .date()+ .describe('Exclusive local end date.'),+ kind: zod.enum(['allDay']),+ startDate: zod.iso+ .date()+ .describe('Inclusive local start date.'),+ })+ .describe(+ "An all-day event using RFC 5545's exclusive end date."+ ),+ ])+ .describe(+ 'The mutually exclusive time shape of a calendar event.\n\nFields are renamed per variant rather than with `rename_all_fields`\nbecause utoipa only honors variant-level serde renames when it\nderives the OpenAPI schema.'+ ),+ })+ .describe(+ 'A materialized recurrence instance optimized for range queries.'+ ),+ })+ .describe(+ 'One materialized occurrence paired with its stable calendar event entity.'+ )+ ),+ nextCursor: zod.string().nullish(),+ syncStatus: zod+ .enum(['syncing', 'ready'])+ .describe(+ 'Aggregate ingestion state across every calendar account visible to a\nrequester, letting clients render progressively while sources build.'+ ),+ })+ .describe('Paginated calendar occurrence viewport response.');+/*** Batch-fetches lightweight previews for a list of call ids. Mirrors the`POST /documents/preview` endpoint: no per-id access checks, duplicatediff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex bc2e18819b..064ca7bdb3 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -779,6 +779,97 @@}}},+ "/calendar-events": {+ "get": {+ "tags": ["calendar_events"],+ "summary": "Return calendar occurrences visible to the authenticated requester.",+ "operationId": "list_occurrences",+ "parameters": [+ {+ "name": "start",+ "in": "query",+ "description": "Inclusive UTC viewport start.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "date-time"+ }+ },+ {+ "name": "end",+ "in": "query",+ "description": "Exclusive UTC viewport end.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "date-time"+ }+ },+ {+ "name": "startDate",+ "in": "query",+ "description": "Inclusive local date boundary for all-day events.",+ "required": false,+ "schema": {+ "type": "string",+ "format": "date"+ }+ },+ {+ "name": "endDate",+ "in": "query",+ "description": "Exclusive local date boundary for all-day events.",+ "required": false,+ "schema": {+ "type": "string",+ "format": "date"+ }+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Maximum number of occurrences, from 1 through 2,000.",+ "required": false,+ "schema": {+ "type": "integer",+ "format": "int32",+ "maximum": 2000,+ "minimum": 1+ }+ },+ {+ "name": "cursor",+ "in": "query",+ "description": "Opaque continuation cursor returned by the previous page.",+ "required": false,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Calendar occurrences in the requested viewport",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarOccurrenceResponse"+ }+ }+ }+ },+ "400": {+ "description": "Invalid or unsupported calendar viewport"+ },+ "401": {+ "description": "Authentication required"+ },+ "500": {+ "description": "Calendar query failed"+ }+ }+ }+ },"/call/record/preview": {"post": {"tags": ["call::inbound::axum_router"],@@ -11823,6 +11914,11 @@}}},+ "AttendeeResponseStatus": {+ "type": "string",+ "description": "RSVP state for an attendee.",+ "enum": ["needs_action", "accepted", "declined", "tentative"]+ },"BTreeMap": {"type": "object","additionalProperties": {@@ -12179,6 +12275,225 @@}}},+ "CalendarAttendee": {+ "type": "object",+ "description": "An attendee on a calendar event.",+ "required": [+ "email",+ "responseStatus",+ "isOrganizer",+ "isOptional",+ "isSelf"+ ],+ "properties": {+ "comment": {+ "type": ["string", "null"],+ "description": "Optional attendee comment."+ },+ "displayName": {+ "type": ["string", "null"],+ "description": "Provider display name."+ },+ "email": {+ "type": "string",+ "description": "Normalized email address."+ },+ "isOptional": {+ "type": "boolean",+ "description": "Whether attendance is optional."+ },+ "isOrganizer": {+ "type": "boolean",+ "description": "Whether this attendee is the organizer."+ },+ "isSelf": {+ "type": "boolean",+ "description": "Whether this attendee represents the connected account."+ },+ "responseStatus": {+ "$ref": "#/components/schemas/AttendeeResponseStatus",+ "description": "RSVP state."+ }+ }+ },+ "CalendarEvent": {+ "type": "object",+ "description": "A stable, first-class Macro calendar event entity.",+ "required": [+ "id",+ "ownerId",+ "icalUid",+ "title",+ "status",+ "visibility",+ "transparency",+ "time",+ "recurrenceLines",+ "sequence",+ "isReadOnly",+ "attendees",+ "createdAt",+ "updatedAt"+ ],+ "properties": {+ "attendees": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CalendarAttendee"+ },+ "description": "Attendees, keyed by email during persistence."+ },+ "conferenceUrl": {+ "type": ["string", "null"],+ "description": "Direct join URL when known."+ },+ "createdAt": {+ "type": "string",+ "format": "date-time",+ "description": "Entity creation time."+ },+ "description": {+ "type": ["string", "null"],+ "description": "Optional event body."+ },+ "icalUid": {+ "type": "string",+ "description": "RFC 5545 UID used to reconcile provider and email sources."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Macro entity identifier."+ },+ "isReadOnly": {+ "type": "boolean",+ "description": "Whether the current user can edit the canonical source."+ },+ "location": {+ "type": ["string", "null"],+ "description": "Optional physical or virtual location label."+ },+ "organizerEmail": {+ "type": ["string", "null"],+ "description": "Organizer email."+ },+ "organizerName": {+ "type": ["string", "null"],+ "description": "Organizer display name."+ },+ "ownerId": {+ "type": "string",+ "description": "Macro user who owns this event entity."+ },+ "recurrenceLines": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`)."+ },+ "sequence": {+ "type": "integer",+ "format": "int32",+ "description": "Provider/iCalendar sequence number.",+ "minimum": 0+ },+ "status": {+ "$ref": "#/components/schemas/EventStatus",+ "description": "Event status."+ },+ "time": {+ "$ref": "#/components/schemas/EventTime",+ "description": "Timed or all-day shape."+ },+ "title": {+ "type": "string",+ "description": "Display title."+ },+ "transparency": {+ "$ref": "#/components/schemas/EventTransparency",+ "description": "Availability behavior."+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time",+ "description": "Entity update time."+ },+ "visibility": {+ "$ref": "#/components/schemas/EventVisibility",+ "description": "Event visibility."+ }+ }+ },+ "CalendarOccurrence": {+ "type": "object",+ "description": "A materialized recurrence instance optimized for range queries.",+ "required": ["eventId", "occurrenceKey", "time", "isCancelled"],+ "properties": {+ "eventId": {+ "type": "string",+ "format": "uuid",+ "description": "Owning event entity."+ },+ "isCancelled": {+ "type": "boolean",+ "description": "Whether the instance was cancelled."+ },+ "occurrenceKey": {+ "type": "string",+ "description": "Stable key within the event."+ },+ "recurrenceId": {+ "type": ["string", "null"],+ "description": "Provider recurrence identifier, when applicable."+ },+ "time": {+ "$ref": "#/components/schemas/EventTime",+ "description": "Instance time."+ }+ }+ },+ "CalendarOccurrenceItem": {+ "type": "object",+ "description": "One materialized occurrence paired with its stable calendar event entity.",+ "required": ["event", "occurrence"],+ "properties": {+ "event": {+ "$ref": "#/components/schemas/CalendarEvent"+ },+ "occurrence": {+ "$ref": "#/components/schemas/CalendarOccurrence"+ }+ }+ },+ "CalendarOccurrenceResponse": {+ "type": "object",+ "description": "Paginated calendar occurrence viewport response.",+ "required": ["items", "hasMore", "syncStatus"],+ "properties": {+ "hasMore": {+ "type": "boolean"+ },+ "items": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CalendarOccurrenceItem"+ }+ },+ "nextCursor": {+ "type": ["string", "null"]+ },+ "syncStatus": {+ "$ref": "#/components/schemas/CalendarSyncStatus",+ "description": "Aggregate ingestion state; clients render a skeleton while `syncing`."+ }+ }+ },+ "CalendarSyncStatus": {+ "type": "string",+ "description": "Aggregate ingestion state across every calendar account visible to a\nrequester, letting clients render progressively while sources build.",+ "enum": ["syncing", "ready"]+ },"CallActiveResponse": {"type": "object","description": "Response indicating whether an active call exists for a channel.",@@ -16626,6 +16941,72 @@}}},+ "EventStatus": {+ "type": "string",+ "description": "Canonical event status.",+ "enum": ["confirmed", "tentative", "cancelled"]+ },+ "EventTime": {+ "oneOf": [+ {+ "type": "object",+ "description": "An event with absolute instants.",+ "required": ["startsAt", "endsAt", "kind"],+ "properties": {+ "endsAt": {+ "type": "string",+ "format": "date-time",+ "description": "Exclusive end instant."+ },+ "kind": {+ "type": "string",+ "enum": ["timed"]+ },+ "startsAt": {+ "type": "string",+ "format": "date-time",+ "description": "Inclusive start instant."+ },+ "timeZone": {+ "type": ["string", "null"],+ "description": "Original IANA time-zone identifier, when supplied."+ }+ }+ },+ {+ "type": "object",+ "description": "An all-day event using RFC 5545's exclusive end date.",+ "required": ["startDate", "endDate", "kind"],+ "properties": {+ "endDate": {+ "type": "string",+ "format": "date",+ "description": "Exclusive local end date."+ },+ "kind": {+ "type": "string",+ "enum": ["allDay"]+ },+ "startDate": {+ "type": "string",+ "format": "date",+ "description": "Inclusive local start date."+ }+ }+ }+ ],+ "description": "The mutually exclusive time shape of a calendar event.\n\nFields are renamed per variant rather than with `rename_all_fields`\nbecause utoipa only honors variant-level serde renames when it\nderives the OpenAPI schema."+ },+ "EventTransparency": {+ "type": "string",+ "description": "Whether an event blocks availability.",+ "enum": ["opaque", "transparent"]+ },+ "EventVisibility": {+ "type": "string",+ "description": "Visibility of event details.",+ "enum": ["default", "public", "private", "confidential"]+ },"ExcludeDefaultViewRequest": {"type": "object","required": ["defaultViewId"],diff --git a/crates/calendar_events/Cargo.toml b/crates/calendar_events/Cargo.tomlnew file mode 100644index 0000000000..30fdee08eb--- /dev/null+++ b/crates/calendar_events/Cargo.toml@@ -0,0 +1,39 @@+[package]+edition = "2024"+name = "calendar_events"+publish = false+version = "0.1.0"++[features]+default = []+inbound = [+ "dep:axum",+ "dep:macro_authorization",+ "dep:models_pagination",+ "schema",+]+postgres = ["dep:sqlx", "dep:tokio"]+schema = ["dep:utoipa"]++[dependencies]+axum = { workspace = true, optional = true }+chrono = { workspace = true }+futures = { workspace = true }+macro_authorization = { path = "../macro_authorization", default-features = false, features = [+ "axum",+], optional = true }+models_pagination = { path = "../models_pagination", optional = true }+rootcause = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+sqlx = { workspace = true, optional = true }+thiserror = { workspace = true }+tokio = { workspace = true, optional = true }+tracing = { workspace = true }+utoipa = { workspace = true, optional = true }+uuid = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }++[dev-dependencies]+macro_db_migrator = { path = "../macro_db_migrator" }+tokio = { workspace = true }diff --git a/crates/calendar_events/src/domain/mod.rs b/crates/calendar_events/src/domain/mod.rsnew file mode 100644index 0000000000..810bb6ecda--- /dev/null+++ b/crates/calendar_events/src/domain/mod.rs@@ -0,0 +1,8 @@+//! Calendar domain layer.++/// Domain models.+pub mod models;+/// Domain ports.+pub mod ports;+/// Calendar business policy.+pub mod service;diff --git a/crates/calendar_events/src/domain/models.rs b/crates/calendar_events/src/domain/models.rsnew file mode 100644index 0000000000..03c7d3959f--- /dev/null+++ b/crates/calendar_events/src/domain/models.rs@@ -0,0 +1,797 @@+//! Calendar domain models.++use std::collections::BTreeSet;++use chrono::{DateTime, NaiveDate, Utc};+use serde::{Deserialize, Serialize};+use uuid::Uuid;++/// Top-level Google scope granting the complete calendar capability,+/// mirroring how email requests the single broad `gmail.modify` scope.+pub const GOOGLE_CALENDAR_SCOPE: &str = "https://www.googleapis.com/auth/calendar";++/// The Google Calendar scopes Macro requests for the calendar capability.+pub const GOOGLE_CALENDAR_SCOPES: [&str; 1] = [GOOGLE_CALENDAR_SCOPE];+/// Build the space-delimited calendar scope fragment for an OAuth authorization URL.+pub fn google_calendar_scope_parameter() -> String {+ GOOGLE_CALENDAR_SCOPES.join(" ")+}++/// A normalized, deterministic set of OAuth scopes.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct GoogleScopeSet(BTreeSet<String>);++impl GoogleScopeSet {+ /// Parse the space-delimited `scope` field returned by Google.+ pub fn parse(value: &str) -> Self {+ Self(+ value+ .split_ascii_whitespace()+ .map(ToOwned::to_owned)+ .collect(),+ )+ }++ /// Construct a scope set from stored values.+ pub fn from_scopes(scopes: impl IntoIterator<Item = String>) -> Self {+ Self(scopes.into_iter().collect())+ }++ /// Return the sorted scope values for durable storage.+ pub fn into_vec(self) -> Vec<String> {+ self.0.into_iter().collect()+ }++ /// Return whether a particular scope is present.+ pub fn contains(&self, scope: &str) -> bool {+ self.0.contains(scope)+ }++ /// Return whether the complete Macro calendar capability is present.+ pub fn has_calendar_capability(&self) -> bool {+ GOOGLE_CALENDAR_SCOPES+ .iter()+ .all(|scope| self.contains(scope))+ }+}++/// The mutually exclusive time shape of a calendar event.+///+/// Fields are renamed per variant rather than with `rename_all_fields`+/// because utoipa only honors variant-level serde renames when it+/// derives the OpenAPI schema.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase", tag = "kind")]+pub enum EventTime {+ /// An event with absolute instants.+ #[serde(rename_all = "camelCase")]+ Timed {+ /// Inclusive start instant.+ starts_at: DateTime<Utc>,+ /// Exclusive end instant.+ ends_at: DateTime<Utc>,+ /// Original IANA time-zone identifier, when supplied.+ time_zone: Option<String>,+ },+ /// An all-day event using RFC 5545's exclusive end date.+ #[serde(rename_all = "camelCase")]+ AllDay {+ /// Inclusive local start date.+ start_date: NaiveDate,+ /// Exclusive local end date.+ end_date: NaiveDate,+ },+}++impl EventTime {+ /// Validate the exclusive end is later than the start.+ pub fn is_valid(&self) -> bool {+ match self {+ Self::Timed {+ starts_at, ends_at, ..+ } => ends_at > starts_at,+ Self::AllDay {+ start_date,+ end_date,+ } => end_date > start_date,+ }+ }++ /// Return the stable occurrence key derived from this span's start.+ pub fn occurrence_key(&self) -> String {+ match self {+ Self::Timed { starts_at, .. } => starts_at.to_rfc3339(),+ Self::AllDay { start_date, .. } => start_date.to_string(),+ }+ }++ /// Return whether this span overlaps an occurrence query range.+ pub fn overlaps(&self, range: &OccurrenceRange) -> bool {+ match self {+ Self::Timed {+ starts_at, ends_at, ..+ } => starts_at < &range.ends_at && ends_at > &range.starts_at,+ Self::AllDay {+ start_date,+ end_date,+ } => start_date < &range.end_date && end_date > &range.start_date,+ }+ }+}++/// Canonical event status.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "snake_case")]+pub enum EventStatus {+ /// Confirmed event.+ #[default]+ Confirmed,+ /// Tentatively accepted event.+ Tentative,+ /// Cancelled event retained for reconciliation.+ Cancelled,+}++impl EventStatus {+ /// Database representation.+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Confirmed => "confirmed",+ Self::Tentative => "tentative",+ Self::Cancelled => "cancelled",+ }+ }+}++/// Visibility of event details.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "snake_case")]+pub enum EventVisibility {+ /// Provider or calendar default.+ #[default]+ Default,+ /// Public event.+ Public,+ /// Private event.+ Private,+ /// Confidential event.+ Confidential,+}++impl EventVisibility {+ /// Database representation.+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Default => "default",+ Self::Public => "public",+ Self::Private => "private",+ Self::Confidential => "confidential",+ }+ }+}++/// Whether an event blocks availability.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "snake_case")]+pub enum EventTransparency {+ /// Event blocks availability.+ #[default]+ Opaque,+ /// Event does not block availability.+ Transparent,+}++impl EventTransparency {+ /// Database representation.+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Opaque => "opaque",+ Self::Transparent => "transparent",+ }+ }+}++/// An attendee on a calendar event.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct CalendarAttendee {+ /// Normalized email address.+ pub email: String,+ /// Provider display name.+ pub display_name: Option<String>,+ /// RSVP state.+ pub response_status: AttendeeResponseStatus,+ /// Whether this attendee is the organizer.+ pub is_organizer: bool,+ /// Whether attendance is optional.+ pub is_optional: bool,+ /// Whether this attendee represents the connected account.+ pub is_self: bool,+ /// Optional attendee comment.+ pub comment: Option<String>,+}++/// RSVP state for an attendee.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "snake_case")]+pub enum AttendeeResponseStatus {+ /// No response has been made.+ #[default]+ NeedsAction,+ /// Invitation accepted.+ Accepted,+ /// Invitation declined.+ Declined,+ /// Invitation tentatively accepted.+ Tentative,+}++impl AttendeeResponseStatus {+ /// Database representation.+ pub fn as_str(self) -> &'static str {+ match self {+ Self::NeedsAction => "needs_action",+ Self::Accepted => "accepted",+ Self::Declined => "declined",+ Self::Tentative => "tentative",+ }+ }+}++/// A stable, first-class Macro calendar event entity.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct CalendarEvent {+ /// Macro entity identifier.+ pub id: Uuid,+ /// Macro user who owns this event entity.+ pub owner_id: String,+ /// RFC 5545 UID used to reconcile provider and email sources.+ pub ical_uid: String,+ /// Display title.+ pub title: String,+ /// Optional event body.+ pub description: Option<String>,+ /// Optional physical or virtual location label.+ pub location: Option<String>,+ /// Event status.+ pub status: EventStatus,+ /// Event visibility.+ pub visibility: EventVisibility,+ /// Availability behavior.+ pub transparency: EventTransparency,+ /// Timed or all-day shape.+ pub time: EventTime,+ /// Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`).+ pub recurrence_lines: Vec<String>,+ /// Organizer email.+ pub organizer_email: Option<String>,+ /// Organizer display name.+ pub organizer_name: Option<String>,+ /// Direct join URL when known.+ pub conference_url: Option<String>,+ /// Provider/iCalendar sequence number.+ pub sequence: u32,+ /// Whether the current user can edit the canonical source.+ pub is_read_only: bool,+ /// Attendees, keyed by email during persistence.+ pub attendees: Vec<CalendarAttendee>,+ /// Entity creation time.+ pub created_at: DateTime<Utc>,+ /// Entity update time.+ pub updated_at: DateTime<Utc>,+}++/// An exception to one instance of a recurring event.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct CalendarEventOverride {+ /// Stable recurrence identifier from the source.+ pub recurrence_id: String,+ /// Original occurrence start.+ pub original_time: EventStart,+ /// Replacement time.+ pub time: EventTime,+ /// Optional replacement title.+ pub title: Option<String>,+ /// Optional replacement description.+ pub description: Option<String>,+ /// Optional replacement location.+ pub location: Option<String>,+ /// Optional replacement status.+ pub status: Option<EventStatus>,+}++/// A start-only value used to identify an overridden occurrence.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum EventStart {+ /// Absolute start instant.+ Timed(DateTime<Utc>),+ /// Local all-day start.+ AllDay(NaiveDate),+}++impl EventStart {+ /// Return the stable recurrence key derived from this start.+ pub fn occurrence_key(&self) -> String {+ match self {+ Self::Timed(starts_at) => starts_at.to_rfc3339(),+ Self::AllDay(start_date) => start_date.to_string(),+ }+ }+}++/// A materialized recurrence instance optimized for range queries.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct CalendarOccurrence {+ /// Owning event entity.+ pub event_id: Uuid,+ /// Stable key within the event.+ pub occurrence_key: String,+ /// Provider recurrence identifier, when applicable.+ pub recurrence_id: Option<String>,+ /// Instance time.+ pub time: EventTime,+ /// Whether the instance was cancelled.+ pub is_cancelled: bool,+}++/// Opaque keyset position for a deterministic occurrence page.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct CalendarOccurrenceCursor {+ /// Normalized UTC occurrence start used by the database ordering.+ pub starts_at: DateTime<Utc>,+ /// Event tie-breaker.+ pub event_id: Uuid,+ /// Stable occurrence tie-breaker within the event.+ pub occurrence_key: String,+}++impl CalendarOccurrenceCursor {+ /// Build the database ordering position for an occurrence.+ pub fn from_occurrence(occurrence: &CalendarOccurrence) -> Self {+ let starts_at = match occurrence.time {+ EventTime::Timed { starts_at, .. } => starts_at,+ EventTime::AllDay { start_date, .. } => start_date+ .and_hms_opt(0, 0, 0)+ .expect("midnight is a valid time")+ .and_utc(),+ };+ Self {+ starts_at,+ event_id: occurrence.event_id,+ occurrence_key: occurrence.occurrence_key.clone(),+ }+ }+}++/// Inclusive/exclusive viewport range for occurrence queries.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OccurrenceRange {+ /// Inclusive UTC start.+ pub starts_at: DateTime<Utc>,+ /// Exclusive UTC end.+ pub ends_at: DateTime<Utc>,+ /// Inclusive local date start used for all-day overlap.+ pub start_date: NaiveDate,+ /// Exclusive local date end used for all-day overlap.+ pub end_date: NaiveDate,+}++/// Aggregate ingestion state across every calendar account visible to a+/// requester, letting clients render progressively while sources build.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub enum CalendarSyncStatus {+ /// At least one visible calendar account is still ingesting.+ Syncing,+ /// Every visible calendar account has finished its latest sync.+ Ready,+}++impl OccurrenceRange {+ /// Construct the bounded history/future window maintained by sync jobs.+ pub fn historical_sync(now: DateTime<Utc>) -> Self {+ let starts_at = now - chrono::Duration::days(365);+ let ends_at = now + chrono::Duration::days(730);+ Self {+ starts_at,+ ends_at,+ start_date: starts_at.date_naive(),+ end_date: ends_at.date_naive(),+ }+ }++ /// Construct the quantized window sync jobs maintain.+ ///+ /// The future edge rounds `now + 730d` up to the next month boundary, so+ /// the requested horizon only advances once a month instead of drifting+ /// with every poll and forcing needless coverage work. It always covers+ /// [`Self::historical_sync`], the window the read path accepts.+ pub fn maintenance_horizon(now: DateTime<Utc>) -> Self {+ let starts_at = now - chrono::Duration::days(365);+ let ends_at = month_ceil(now + chrono::Duration::days(730));+ Self {+ starts_at,+ ends_at,+ start_date: starts_at.date_naive(),+ end_date: ends_at.date_naive(),+ }+ }++ /// Return whether this viewport is covered by the occurrence window+ /// materialized by the ingestion pipelines.+ pub fn is_materialized_at(&self, now: DateTime<Utc>) -> bool {+ let materialized = Self::historical_sync(now);+ self.starts_at >= materialized.starts_at+ && self.ends_at <= materialized.ends_at+ && self.start_date >= materialized.start_date+ && self.end_date <= materialized.end_date+ }++ /// Validate the range and cap it to prevent accidental unbounded scans.+ pub fn is_valid(&self) -> bool {+ self.ends_at > self.starts_at+ && self.end_date > self.start_date+ && self.ends_at - self.starts_at <= chrono::Duration::days(370)+ && self.end_date - self.start_date <= chrono::Duration::days(370)+ }++ /// Validate the larger bounded window maintained by historical sync,+ /// including the month of quantization padding on the future edge.+ pub fn is_valid_for_backfill(&self) -> bool {+ self.ends_at > self.starts_at+ && self.end_date > self.start_date+ && self.ends_at - self.starts_at <= chrono::Duration::days(1130)+ && self.end_date - self.start_date <= chrono::Duration::days(1130)+ }+}++fn month_ceil(instant: DateTime<Utc>) -> DateTime<Utc> {+ use chrono::Datelike;++ let date = instant.date_naive();+ let (year, month) = if date.month() == 12 {+ (date.year() + 1, 1)+ } else {+ (date.year(), date.month() + 1)+ };+ NaiveDate::from_ymd_opt(year, month, 1)+ .expect("first day of a month is valid")+ .and_hms_opt(0, 0, 0)+ .expect("midnight is a valid time")+ .and_utc()+}++#[cfg(test)]+mod test;++/// Email attachment/message identity for an iCalendar source.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct EmailIcsSource {+ /// Connected inbox.+ pub email_link_id: Uuid,+ /// Email thread containing the invitation.+ pub email_thread_id: Option<Uuid>,+ /// Email message containing the invitation.+ pub email_message_id: Uuid,+ /// Provider attachment identifier, or `None` for inline calendar MIME parts.+ pub email_attachment_id: Option<String>,+ /// SHA-256 of the source bytes.+ pub content_hash: String,+ /// Source payload retained for reconciliation/debugging.+ pub raw_payload: serde_json::Value,+}++/// Google provider identity for an event source.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct GoogleEventSource {+ /// Connected inbox whose grant exposed this event.+ pub email_link_id: Uuid,+ /// Calendar account.+ pub account_id: Uuid,+ /// Calendar containing the source event.+ pub calendar_id: Uuid,+ /// Google event identifier.+ pub provider_event_id: String,+ /// Google recurring master identifier for an instance.+ pub provider_recurring_event_id: Option<String>,+ /// Google entity tag.+ pub provider_etag: Option<String>,+ /// Raw provider payload.+ pub raw_payload: serde_json::Value,+}++/// Source-specific metadata attached to a canonical event.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum CalendarEventSource {+ /// Event found in an email iCalendar part.+ EmailIcs(EmailIcsSource),+ /// Event fetched from Google Calendar.+ Google(GoogleEventSource),+}++/// Event plus source and materialized projections to persist atomically.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct CalendarEventUpsert {+ /// Canonical event.+ pub event: CalendarEvent,+ /// Source that produced the update.+ pub source: CalendarEventSource,+ /// Recurrence overrides.+ pub overrides: Vec<CalendarEventOverride>,+ /// Materialized instances within the maintained horizon.+ pub occurrences: Vec<CalendarOccurrence>,+}++/// Persisted state needed to choose an incremental or full provider sync.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct StoredGoogleCalendar {+ /// Persisted Macro calendar identifier.+ pub id: Uuid,+ /// Last provider continuation token successfully committed for this calendar.+ pub sync_token: Option<String>,+ /// Exact recurrence window materialized by the last full snapshot.+ pub materialized_range: Option<OccurrenceRange>,+}++/// How the provider adapter must reconcile one calendar this run.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum GoogleSyncPlan {+ /// Rebuild the complete bounded snapshot: no continuation token was+ /// committed or persisted coverage misses requested history.+ FullSnapshot,+ /// Apply the change feed, then materialize only the uncovered tail.+ ExtendTail {+ /// Exclusive instant where persisted coverage ends.+ from: DateTime<Utc>,+ /// Exclusive local date where persisted all-day coverage ends.+ from_date: NaiveDate,+ },+ /// Apply the change feed; persisted coverage already spans the request.+ Incremental,+}++impl StoredGoogleCalendar {+ /// Choose how the adapter must reconcile this calendar for a requested+ /// window, keeping full rebuilds for lost tokens or uncovered history+ /// and extending decayed future coverage incrementally.+ pub fn sync_plan(&self, requested: &OccurrenceRange) -> GoogleSyncPlan {+ let Some(materialized) = &self.materialized_range else {+ return GoogleSyncPlan::FullSnapshot;+ };+ if self.sync_token.is_none()+ || materialized.starts_at > requested.starts_at+ || materialized.start_date > requested.start_date+ {+ return GoogleSyncPlan::FullSnapshot;+ }+ if materialized.ends_at < requested.ends_at || materialized.end_date < requested.end_date {+ return GoogleSyncPlan::ExtendTail {+ from: materialized.ends_at,+ from_date: materialized.end_date,+ };+ }+ GoogleSyncPlan::Incremental+ }+}++/// Normalized result of one provider calendar's incremental poll.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct GoogleEventSyncBatch {+ /// Valid events normalized from the current bounded snapshot.+ pub upserts: Vec<CalendarEventUpsert>,+ /// Provider master identifiers observed in a complete bounded snapshot.+ ///+ /// `None` means the continuation token reported no relevant change and no+ /// destructive snapshot reconciliation may run.+ pub observed_provider_event_ids: Option<Vec<String>>,+ /// Provider continuation token to persist only with the fenced sync.+ pub next_sync_token: String,+ /// Range rebuilt by this batch, or `None` for a token-only no-op poll.+ pub materialized_range: Option<OccurrenceRange>,+ /// Provider event identifiers the change feed reported cancelled.+ ///+ /// Applied even when no full snapshot ran, so incremental polls can+ /// retire sources without a destructive account sweep. A recurring+ /// master's identifier also retires its expanded instances.+ pub cancelled_provider_event_ids: Vec<String>,+}++/// Durable state committed for one calendar as soon as its poll completes,+/// so a later calendar's failure cannot discard this calendar's progress.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct GoogleCalendarSyncSnapshot {+ /// Persisted Macro calendar identifier.+ pub calendar_id: Uuid,+ /// Provider continuation token returned by the successful poll.+ pub next_sync_token: String,+ /// Provider event identifiers observed when a full snapshot ran.+ pub observed_provider_event_ids: Option<Vec<String>>,+ /// Exact occurrence range rebuilt by a full snapshot.+ pub materialized_range: Option<OccurrenceRange>,+ /// Provider event identifiers the change feed reported cancelled.+ pub cancelled_provider_event_ids: Vec<String>,+}++/// Kind of idempotent historical work triggered by a Google grant.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum CalendarBackfillKind {+ /// Fetch calendars and canonical provider events.+ GoogleCalendar,+ /// Re-scan existing email for iCalendar MIME parts.+ EmailIcs,+}++impl CalendarBackfillKind {+ /// Database representation.+ pub fn as_str(self) -> &'static str {+ match self {+ Self::GoogleCalendar => "google_calendar",+ Self::EmailIcs => "email_ics",+ }+ }+}++/// Backfill work created by a grant update.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct CalendarBackfillJob {+ /// Job identifier.+ pub id: Uuid,+ /// Connected email link.+ pub email_link_id: Uuid,+ /// Calendar account, when already provisioned.+ pub account_id: Option<Uuid>,+ /// Work type.+ pub kind: CalendarBackfillKind,+ /// Grant version this work covers.+ pub grant_version: i64,+}++/// Stable identity of one calendar backfill queue job.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct CalendarBackfillJobKey {+ /// Durable calendar job identifier.+ pub job_id: Uuid,+ /// Connected inbox the job belongs to.+ pub email_link_id: Uuid,+}++/// Result of trying to fence a Google Calendar backfill delivery.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum CalendarBackfillClaim {+ /// This delivery owns the returned fencing token.+ Claimed {+ /// Token required by every subsequent lifecycle transition.+ lease_token: Uuid,+ /// Calendar account provisioned by the grant transaction.+ account_id: Uuid,+ },+ /// The durable job already completed.+ Complete,+ /// Another delivery currently owns the lease.+ Busy,+ /// The durable job already failed permanently.+ Failed,+ /// No matching Google Calendar job exists.+ NotFound,+}++/// Durable action to take after Google provider or persistence failure.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum CalendarBackfillFailureDisposition {+ /// Release the lease and allow queue retry.+ Retry,+ /// Finish the job as a permanent provider failure.+ Permanent,+ /// Finish the job and mark the entire connected inbox for reauthorization.+ ReauthRequired,+ /// Finish the job because the calendar capability, but not necessarily the+ /// Gmail grant, needs incremental consent.+ CalendarPermissionRequired,+}++/// Durable effects applied while failing a Google Calendar backfill.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct CalendarBackfillFailureOutcome {+ /// Whether an active calendar job transitioned to its requested failure state.+ pub job_transitioned: bool,+ /// Whether the associated inbox newly transitioned to require reauthorization.+ pub link_reauth_transitioned: bool,+}++/// Durable state of the email scan associated with calendar extraction.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum EmailCalendarScanStatus {+ /// The email scan is created but has not begun listing threads.+ Init,+ /// The email scan is actively processing messages.+ InProgress,+ /// The scan and calendar extraction completed.+ Complete,+ /// The scan ended before calendar extraction completed.+ Failed,+}++/// Minimal email scan identity needed by calendar backfill policy.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct EmailCalendarScanJob {+ /// Durable email backfill job identifier.+ pub id: Uuid,+ /// Current scan lifecycle state.+ pub status: EmailCalendarScanStatus,+ /// Whether the scan covers the entire mailbox rather than a bounded subset.+ pub is_full_scan: bool,+}++/// Durable state of an email-ICS calendar backfill.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum EmailCalendarBackfillState {+ /// No email scan has been associated yet.+ Unassociated,+ /// A scan is already durably associated.+ Associated {+ /// Durable email scan identifier.+ email_job_id: Uuid,+ },+ /// Calendar extraction already completed.+ Complete,+ /// No matching email-ICS calendar job exists.+ NotFound,+}++/// Result of atomically associating an email scan with calendar extraction.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum EmailCalendarScanAssociation {+ /// The scan was associated at its current safe state.+ Associated(EmailCalendarScanStatus),+ /// An unrelated scan is already in progress and cannot provide a full rescan.+ Busy,+ /// The email scan no longer exists.+ NotFound,+}++/// Result of applying an OAuth grant.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct AppliedGoogleGrant {+ /// Monotonic version of the stored grant.+ pub grant_version: i64,+ /// Whether the durable set of scopes changed.+ pub changed: bool,+ /// Newly scheduled idempotent work.+ pub jobs: Vec<CalendarBackfillJob>,+}++/// A calendar in a provider account.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct ProviderCalendar {+ /// Provider calendar identifier.+ pub provider_calendar_id: String,+ /// Display name.+ pub name: String,+ /// Description.+ pub description: Option<String>,+ /// IANA timezone.+ pub time_zone: Option<String>,+ /// Provider color.+ pub color: Option<String>,+ /// Provider access role.+ pub access_role: Option<String>,+ /// Whether this is the account's primary calendar.+ pub is_primary: bool,+ /// Whether Macro should display/sync it by default.+ pub is_selected: bool,+}diff --git a/crates/calendar_events/src/domain/models/test.rs b/crates/calendar_events/src/domain/models/test.rsnew file mode 100644index 0000000000..d679419f41--- /dev/null+++ b/crates/calendar_events/src/domain/models/test.rs@@ -0,0 +1,135 @@+use super::*;+use chrono::TimeZone;++fn range(starts_at: DateTime<Utc>, ends_at: DateTime<Utc>) -> OccurrenceRange {+ OccurrenceRange {+ starts_at,+ ends_at,+ start_date: starts_at.date_naive(),+ end_date: ends_at.date_naive(),+ }+}++#[test]+fn materialized_range_accepts_supported_viewports() {+ let now = Utc.with_ymd_and_hms(2026, 7, 24, 12, 0, 0).unwrap();+ let viewport = range(+ now - chrono::Duration::days(30),+ now + chrono::Duration::days(30),+ );++ assert!(viewport.is_materialized_at(now));+}++#[test]+fn materialized_range_rejects_viewports_outside_the_sync_horizon() {+ let now = Utc.with_ymd_and_hms(2026, 7, 24, 12, 0, 0).unwrap();+ let too_old = range(+ now - chrono::Duration::days(366),+ now - chrono::Duration::days(360),+ );+ let too_far_ahead = range(+ now + chrono::Duration::days(725),+ now + chrono::Duration::days(731),+ );++ assert!(!too_old.is_materialized_at(now));+ assert!(!too_far_ahead.is_materialized_at(now));+}++#[test]+fn sync_plan_extends_only_the_uncovered_tail() {+ let now = Utc.with_ymd_and_hms(2026, 7, 25, 12, 0, 0).unwrap();+ let materialized = OccurrenceRange::historical_sync(now);+ let stored = StoredGoogleCalendar {+ id: Uuid::now_v7(),+ sync_token: Some("token".to_string()),+ materialized_range: Some(materialized.clone()),+ };++ assert_eq!(+ stored.sync_plan(&OccurrenceRange::historical_sync(now)),+ GoogleSyncPlan::Incremental+ );+ assert_eq!(+ stored.sync_plan(&OccurrenceRange::historical_sync(+ now + chrono::Duration::hours(12)+ )),+ GoogleSyncPlan::ExtendTail {+ from: materialized.ends_at,+ from_date: materialized.end_date,+ }+ );++ let more_history = OccurrenceRange {+ starts_at: materialized.starts_at - chrono::Duration::days(1),+ ..materialized.clone()+ };+ assert_eq!(+ stored.sync_plan(&more_history),+ GoogleSyncPlan::FullSnapshot+ );++ let uninitialized = StoredGoogleCalendar {+ id: Uuid::now_v7(),+ sync_token: None,+ materialized_range: Some(materialized.clone()),+ };+ assert_eq!(+ uninitialized.sync_plan(&OccurrenceRange::historical_sync(now)),+ GoogleSyncPlan::FullSnapshot+ );++ let unmaterialized = StoredGoogleCalendar {+ id: Uuid::now_v7(),+ sync_token: Some("token".to_string()),+ materialized_range: None,+ };+ assert_eq!(+ unmaterialized.sync_plan(&OccurrenceRange::historical_sync(now)),+ GoogleSyncPlan::FullSnapshot+ );+}++#[test]+fn maintenance_horizon_is_stable_within_a_month_and_covers_reads() {+ let early = Utc.with_ymd_and_hms(2026, 7, 2, 8, 0, 0).unwrap();+ let late = Utc.with_ymd_and_hms(2026, 7, 30, 22, 0, 0).unwrap();+ let next_month = Utc.with_ymd_and_hms(2026, 8, 3, 8, 0, 0).unwrap();++ let horizon = OccurrenceRange::maintenance_horizon(early);+ assert_eq!(+ horizon.ends_at,+ OccurrenceRange::maintenance_horizon(late).ends_at+ );+ assert!(horizon.ends_at < OccurrenceRange::maintenance_horizon(next_month).ends_at);++ for now in [early, late, next_month] {+ let horizon = OccurrenceRange::maintenance_horizon(now);+ let readable = OccurrenceRange::historical_sync(now);+ assert!(horizon.starts_at <= readable.starts_at);+ assert!(horizon.start_date <= readable.start_date);+ assert!(horizon.ends_at >= readable.ends_at);+ assert!(horizon.end_date >= readable.end_date);+ assert!(horizon.is_valid_for_backfill());+ }+}++#[test]+fn event_time_serializes_nested_fields_as_camel_case() {+ let starts_at = Utc.with_ymd_and_hms(2026, 7, 24, 12, 0, 0).unwrap();+ let ends_at = Utc.with_ymd_and_hms(2026, 7, 24, 13, 0, 0).unwrap();++ let value = serde_json::to_value(EventTime::Timed {+ starts_at,+ ends_at,+ time_zone: Some("America/New_York".to_owned()),+ })+ .unwrap();++ assert_eq!(value["kind"], "timed");+ assert_eq!(value["startsAt"], "2026-07-24T12:00:00Z");+ assert_eq!(value["endsAt"], "2026-07-24T13:00:00Z");+ assert_eq!(value["timeZone"], "America/New_York");+ assert!(value.get("starts_at").is_none());+}diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rsnew file mode 100644index 0000000000..704cef1fa4--- /dev/null+++ b/crates/calendar_events/src/domain/ports.rs@@ -0,0 +1,301 @@+//! Ports implemented by calendar adapters.++use std::future::Future;++use chrono::{DateTime, Utc};+use rootcause::Report;+use uuid::Uuid;++use super::models::{+ AppliedGoogleGrant, CalendarBackfillClaim, CalendarBackfillFailureDisposition,+ CalendarBackfillFailureOutcome, CalendarBackfillJobKey, CalendarEvent, CalendarEventUpsert,+ CalendarOccurrence, CalendarOccurrenceCursor, CalendarSyncStatus, EmailCalendarBackfillState,+ EmailCalendarScanAssociation, EmailCalendarScanJob, GoogleCalendarSyncSnapshot,+ GoogleEventSyncBatch, GoogleScopeSet, GoogleSyncPlan, OccurrenceRange, ProviderCalendar,+ StoredGoogleCalendar,+};++/// Classification supplied by provider adapters to backfill policy.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum GoogleProviderErrorKind {+ /// Transport, throttling, timeout, or server failure that may recover.+ Transient,+ /// A permanent request failure unrelated to grant health.+ Permanent,+ /// The connected grant is invalid, revoked, or insufficient.+ ReauthRequired,+ /// The provider continuation token expired and requires a full resync.+ SyncTokenExpired,+}++/// Typed Google Calendar failure returned across the provider port.+#[derive(Debug, thiserror::Error)]+#[error("Google Calendar provider request failed: {message}")]+pub struct GoogleProviderError {+ kind: GoogleProviderErrorKind,+ message: String,+}++impl GoogleProviderError {+ /// Construct a classified provider failure.+ pub fn new(kind: GoogleProviderErrorKind, message: impl Into<String>) -> Self {+ Self {+ kind,+ message: message.into(),+ }+ }++ /// Return the retry/reauthorization classification.+ pub fn kind(&self) -> GoogleProviderErrorKind {+ self.kind+ }+}++/// Stable identifiers and sync policy for one provider calendar fetch.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct GoogleEventSyncContext {+ /// Macro user who owns the resulting entities.+ pub owner_id: String,+ /// Connected inbox whose grant authorizes the request.+ pub email_link_id: Uuid,+ /// Calendar account persisted for the connected inbox.+ pub account_id: Uuid,+ /// Persisted Macro calendar identifier.+ pub calendar_id: Uuid,+ /// Provider calendar identifier used in Google API paths.+ pub provider_calendar_id: String,+ /// Whether the provider role prohibits event mutation.+ pub is_read_only: bool,+ /// Occurrence window to materialize.+ pub range: OccurrenceRange,+ /// Last continuation token committed for this provider calendar.+ pub sync_token: Option<String>,+ /// Domain-chosen reconciliation mode for this run.+ pub plan: GoogleSyncPlan,+}++/// Authorized ingestion command for one normalized calendar event.+pub enum CalendarEventWrite {+ /// Event extracted from a connected inbox's RFC 5545 content.+ EmailIcs(CalendarEventUpsert),+ /// Google event written while holding a durable backfill lease.+ GoogleBackfill {+ /// Durable job and connected-inbox identity.+ key: CalendarBackfillJobKey,+ /// Current lease token held by the worker.+ lease_token: Uuid,+ /// Normalized provider event.+ upsert: CalendarEventUpsert,+ },+ /// Unfenced persistence used only by PostgreSQL adapter fixtures.+ #[cfg(test)]+ Fixture(CalendarEventUpsert),+}++/// Inbound service port for querying calendar occurrence projections.+pub trait CalendarOccurrenceService: Send + Sync + 'static {+ /// Return occurrences visible to a requester in a bounded viewport.+ fn list_occurrences(+ &self,+ requester_id: &str,+ range: OccurrenceRange,+ cursor: Option<CalendarOccurrenceCursor>,+ limit: u16,+ ) -> impl Future<Output = Result<Vec<(CalendarEvent, CalendarOccurrence)>, Report>> + Send;++ /// Return the aggregate ingestion state of the requester's visible accounts.+ fn sync_status(+ &self,+ requester_id: &str,+ ) -> impl Future<Output = Result<CalendarSyncStatus, Report>> + Send;+}++/// Persistence operations used by calendar business logic.+pub trait CalendarRepository: Send + Sync + 'static {+ /// Apply the actual scopes returned by Google and atomically schedule any+ /// newly unlocked historical work.+ fn apply_google_grant(+ &self,+ email_link_id: Uuid,+ scopes: GoogleScopeSet,+ ) -> impl Future<Output = Result<AppliedGoogleGrant, Report>> + Send;++ /// Upsert an event through an explicit, source-matched ingestion authority.+ fn upsert_event(+ &self,+ write: CalendarEventWrite,+ ) -> impl Future<Output = Result<Uuid, Report>> + Send;++ /// Return occurrences visible to a requester across owned and delegated inboxes.+ fn list_occurrences(+ &self,+ requester_id: &str,+ range: OccurrenceRange,+ cursor: Option<CalendarOccurrenceCursor>,+ limit: u16,+ ) -> impl Future<Output = Result<Vec<(CalendarEvent, CalendarOccurrence)>, Report>> + Send;++ /// Return the aggregate ingestion state across the requester's visible accounts.+ fn sync_status(+ &self,+ requester_id: &str,+ ) -> impl Future<Output = Result<CalendarSyncStatus, Report>> + Send;++ /// Upsert one provider calendar while holding the current backfill fence.+ fn upsert_google_calendar(+ &self,+ key: CalendarBackfillJobKey,+ lease_token: Uuid,+ account_id: Uuid,+ calendar: ProviderCalendar,+ ) -> impl Future<Output = Result<StoredGoogleCalendar, Report>> + Send;++ /// Durably commit one calendar's poll under the backfill's fencing token:+ /// prune sources a full snapshot no longer observed, then advance the+ /// calendar's continuation token and materialized range.+ fn commit_google_calendar_sync(+ &self,+ key: CalendarBackfillJobKey,+ lease_token: Uuid,+ account_id: Uuid,+ sync: GoogleCalendarSyncSnapshot,+ ) -> impl Future<Output = Result<(), Report>> + Send;++ /// Reconcile the provider's calendar list under the backfill's fencing+ /// token, removing calendars and sources no longer returned by Google.+ fn reconcile_google_calendar_list(+ &self,+ key: CalendarBackfillJobKey,+ lease_token: Uuid,+ account_id: Uuid,+ calendar_ids: Vec<Uuid>,+ ) -> impl Future<Output = Result<(), Report>> + Send;+}++/// Provider API operations used by the Google backfill adapter.+pub trait GoogleCalendarProvider: Send + Sync + 'static {+ /// List every calendar visible to the grant.+ fn list_calendars(+ &self,+ access_token: &str,+ ) -> impl Future<Output = Result<Vec<ProviderCalendar>, GoogleProviderError>> + Send;++ /// Poll provider changes and, when needed, rebuild the bounded event snapshot.+ fn sync_events(+ &self,+ access_token: &str,+ context: GoogleEventSyncContext,+ ) -> impl Future<Output = Result<GoogleEventSyncBatch, GoogleProviderError>> + Send;+}++/// Durable scheduling operations for periodic provider maintenance.+pub trait GoogleCalendarSyncRepository: Send + Sync + 'static {+ /// Reset completed current-grant jobs that are due for another incremental poll.+ fn schedule_due_google_syncs(+ &self,+ due_before: DateTime<Utc>,+ ) -> impl Future<Output = Result<usize, Report>> + Send;+}++/// Durable lifecycle and lease operations for calendar backfill jobs.+pub trait CalendarBackfillRepository: Send + Sync + 'static {+ /// Persist a terminal failure that happened before a lease was acquired.+ fn fail_unclaimed_google_backfill(+ &self,+ key: CalendarBackfillJobKey,+ disposition: CalendarBackfillFailureDisposition,+ message: &str,+ ) -> impl Future<Output = Result<CalendarBackfillFailureOutcome, Report>> + Send;++ /// Claim a Google Calendar job, fencing all later writes with a new token.+ fn claim_google_backfill(+ &self,+ key: CalendarBackfillJobKey,+ ) -> impl Future<Output = Result<CalendarBackfillClaim, Report>> + Send;++ /// Mark the account as actively syncing after a successful claim.+ fn mark_google_account_syncing(+ &self,+ key: CalendarBackfillJobKey,+ lease_token: Uuid,+ ) -> impl Future<Output = Result<(), Report>> + Send;++ /// Maintain the fenced lease until cancelled or ownership is lost.+ fn maintain_google_backfill_lease(+ &self,+ key: CalendarBackfillJobKey,+ lease_token: Uuid,+ ) -> impl Future<Output = Result<(), Report>> + Send;++ /// Atomically complete the job and mark its account ready.+ fn complete_google_backfill(+ &self,+ key: CalendarBackfillJobKey,+ lease_token: Uuid,+ extracted_count: usize,+ ) -> impl Future<Output = Result<(), Report>> + Send;++ /// Persist a classified failure, releasing or terminating the job.+ fn fail_google_backfill(+ &self,+ key: CalendarBackfillJobKey,+ lease_token: Uuid,+ disposition: CalendarBackfillFailureDisposition,+ message: &str,+ ) -> impl Future<Output = Result<CalendarBackfillFailureOutcome, Report>> + Send;+}++/// Durable email-scan operations used by calendar extraction policy.+pub trait EmailCalendarBackfillRepository: Send + Sync + 'static {+ /// Load the calendar job and any scan already associated with it.+ fn get_email_calendar_backfill_state(+ &self,+ key: CalendarBackfillJobKey,+ ) -> impl Future<Output = Result<EmailCalendarBackfillState, Report>> + Send;++ /// Load one associated email scan.+ fn get_email_scan_job(+ &self,+ email_link_id: Uuid,+ email_job_id: Uuid,+ ) -> impl Future<Output = Result<Option<EmailCalendarScanJob>, Report>> + Send;++ /// Return the active email scan for an inbox, if one exists.+ fn get_active_email_scan_job(+ &self,+ email_link_id: Uuid,+ ) -> impl Future<Output = Result<Option<EmailCalendarScanJob>, Report>> + Send;++ /// Create a full email scan, returning the winner of any concurrent insert.+ fn create_email_scan_job(+ &self,+ email_link_id: Uuid,+ fusionauth_user_id: &str,+ ) -> impl Future<Output = Result<EmailCalendarScanJob, Report>> + Send;++ /// Atomically associate a scan, optionally accepting an already-started+ /// scan only when it was associated by an earlier delivery.+ fn associate_email_scan(+ &self,+ key: CalendarBackfillJobKey,+ email_job_id: Uuid,+ allow_in_progress: bool,+ ) -> impl Future<Output = Result<EmailCalendarScanAssociation, Report>> + Send;++ /// Atomically terminate an active email-ICS job and its unpublished scan.+ fn fail_email_calendar_backfill(+ &self,+ key: CalendarBackfillJobKey,+ message: &str,+ ) -> impl Future<Output = Result<bool, Report>> + Send;+}++/// Queue publication required to begin a newly associated email scan.+pub trait EmailCalendarBackfillPublisher: Send + Sync + 'static {+ /// Publish the idempotent email scan initialization message.+ fn publish_email_scan_init(+ &self,+ email_link_id: Uuid,+ email_job_id: Uuid,+ ) -> impl Future<Output = Result<(), Report>> + Send;+}diff --git a/crates/calendar_events/src/domain/service.rs b/crates/calendar_events/src/domain/service.rsnew file mode 100644index 0000000000..34eac6972c--- /dev/null+++ b/crates/calendar_events/src/domain/service.rs@@ -0,0 +1,664 @@+//! Calendar business policy.++use chrono::Utc;+use futures::future::{Either, select};+use rootcause::Report;+use uuid::Uuid;++use super::{+ models::{+ AppliedGoogleGrant, CalendarBackfillClaim, CalendarBackfillFailureDisposition,+ CalendarBackfillFailureOutcome, CalendarBackfillJobKey, CalendarEventUpsert,+ CalendarOccurrenceCursor, EmailCalendarBackfillState, EmailCalendarScanAssociation,+ EmailCalendarScanStatus, GoogleCalendarSyncSnapshot, GoogleScopeSet, OccurrenceRange,+ },+ ports::{+ CalendarBackfillRepository, CalendarEventWrite, CalendarOccurrenceService,+ CalendarRepository, EmailCalendarBackfillPublisher, EmailCalendarBackfillRepository,+ GoogleCalendarProvider, GoogleCalendarSyncRepository, GoogleEventSyncContext,+ GoogleProviderError, GoogleProviderErrorKind,+ },+};++/// Domain validation failures.+#[derive(Debug, thiserror::Error)]+pub enum CalendarValidationError {+ /// Event identity was missing.+ #[error("calendar event requires a non-empty owner and iCalendar UID")]+ MissingIdentity,+ /// Event end was not after its start.+ #[error("calendar event end must be after its start")]+ InvalidTime,+ /// A query range was invalid or too large.+ #[error(+ "calendar occurrence range must be positive, no larger than 370 days, and inside the materialized one-year-history/two-year-future window"+ )]+ InvalidRange,+ /// A page size was outside the supported bound.+ #[error("calendar repository query limit must be between 1 and 2001")]+ InvalidLimit,+}++/// Queue-visible outcome of scheduling a full email rescan for ICS extraction.+#[derive(Debug, thiserror::Error)]+pub enum EmailCalendarBackfillRunError {+ /// An unrelated email scan is already in progress.+ #[error("email calendar extraction is waiting for the active email backfill")]+ Busy,+ /// The calendar job or its associated email scan was not found.+ #[error("email calendar extraction job was not found")]+ NotFound,+ /// The associated email scan already failed.+ #[error("email calendar extraction scan failed")]+ ScanFailed,+ /// Persistence or queue publication can be retried.+ #[error("email calendar extraction failed transiently: {0}")]+ Retryable(String),+}++/// Application service that associates a complete email scan with ICS extraction.+pub struct EmailCalendarBackfillCoordinator<R, P> {+ repository: R,+ publisher: P,+}++impl<R, P> EmailCalendarBackfillCoordinator<R, P>+where+ R: EmailCalendarBackfillRepository,+ P: EmailCalendarBackfillPublisher,+{+ /// Construct the coordinator from persistence and queue ports.+ pub fn new(repository: R, publisher: P) -> Self {+ Self {+ repository,+ publisher,+ }+ }++ /// Start or resume one durable email-ICS calendar backfill.+ #[tracing::instrument(skip(self, fusionauth_user_id), fields(job_id = %key.job_id), err)]+ pub async fn run(+ &self,+ key: CalendarBackfillJobKey,+ fusionauth_user_id: &str,+ ) -> Result<(), EmailCalendarBackfillRunError> {+ let state = self+ .repository+ .get_email_calendar_backfill_state(key)+ .await+ .map_err(retryable_email_backfill)?;+ let (email_job, allow_in_progress) = match state {+ EmailCalendarBackfillState::Complete => return Ok(()),+ EmailCalendarBackfillState::NotFound => {+ return Err(EmailCalendarBackfillRunError::NotFound);+ }+ EmailCalendarBackfillState::Associated { email_job_id } => {+ let job = self+ .repository+ .get_email_scan_job(key.email_link_id, email_job_id)+ .await+ .map_err(retryable_email_backfill)?+ .ok_or(EmailCalendarBackfillRunError::NotFound)?;+ if !job.is_full_scan {+ return Err(EmailCalendarBackfillRunError::ScanFailed);+ }+ (job, true)+ }+ EmailCalendarBackfillState::Unassociated => {+ let job = match self+ .repository+ .get_active_email_scan_job(key.email_link_id)+ .await+ .map_err(retryable_email_backfill)?+ {+ Some(job) => job,+ None => self+ .repository+ .create_email_scan_job(key.email_link_id, fusionauth_user_id)+ .await+ .map_err(retryable_email_backfill)?,+ };+ if !job.is_full_scan || job.status == EmailCalendarScanStatus::InProgress {+ return Err(EmailCalendarBackfillRunError::Busy);+ }+ (job, false)+ }+ };++ let association = self+ .repository+ .associate_email_scan(key, email_job.id, allow_in_progress)+ .await+ .map_err(retryable_email_backfill)?;+ let status = match association {+ EmailCalendarScanAssociation::Associated(status) => status,+ EmailCalendarScanAssociation::Busy => {+ return Err(EmailCalendarBackfillRunError::Busy);+ }+ EmailCalendarScanAssociation::NotFound => {+ return Err(EmailCalendarBackfillRunError::NotFound);+ }+ };+ match status {+ EmailCalendarScanStatus::Complete => Ok(()),+ EmailCalendarScanStatus::Failed => Err(EmailCalendarBackfillRunError::ScanFailed),+ EmailCalendarScanStatus::InProgress => Ok(()),+ EmailCalendarScanStatus::Init => self+ .publisher+ .publish_email_scan_init(key.email_link_id, email_job.id)+ .await+ .map_err(retryable_email_backfill),+ }+ }++ /// Apply a terminal queue failure through the calendar lifecycle port.+ #[tracing::instrument(skip(self, message), fields(job_id = %key.job_id), err)]+ pub async fn fail_terminal(+ &self,+ key: CalendarBackfillJobKey,+ message: &str,+ ) -> Result<(), EmailCalendarBackfillRunError> {+ self.repository+ .fail_email_calendar_backfill(key, message)+ .await+ .map_err(retryable_email_backfill)?;+ Ok(())+ }+}++fn retryable_email_backfill(error: Report) -> EmailCalendarBackfillRunError {+ EmailCalendarBackfillRunError::Retryable(format!("{error:?}"))+}++/// Calendar use cases with provider and persistence details behind ports.+pub struct CalendarService<R> {+ repository: R,+}++impl<R> CalendarService<R>+where+ R: CalendarRepository,+{+ /// Construct the service.+ pub fn new(repository: R) -> Self {+ Self { repository }+ }++ /// Apply an OAuth grant using actual scopes returned by Google.+ ///+ /// The repository owns the transaction that increments the grant version+ /// and inserts the two idempotent backfill jobs.+ #[tracing::instrument(skip(self, scopes), err)]+ pub async fn apply_google_grant(+ &self,+ email_link_id: Uuid,+ scopes: GoogleScopeSet,+ ) -> Result<AppliedGoogleGrant, Report> {+ self.repository+ .apply_google_grant(email_link_id, scopes)+ .await+ }++ /// Validate and atomically reconcile a provider or email source.+ #[tracing::instrument(skip(self, upsert), fields(ical_uid = %upsert.event.ical_uid), err)]+ pub async fn upsert_email_event(&self, upsert: CalendarEventUpsert) -> Result<Uuid, Report> {+ validate_upsert(&upsert)?;+ if !matches!(+ upsert.source,+ super::models::CalendarEventSource::EmailIcs(_)+ ) {+ return Err(rootcause::report!(+ "unfenced calendar ingestion only accepts email ICS sources"+ ));+ }+ self.repository+ .upsert_event(CalendarEventWrite::EmailIcs(upsert))+ .await+ }++ /// Query a bounded occurrence viewport.+ #[tracing::instrument(skip(self, requester_id, range), err)]+ pub async fn list_occurrences(+ &self,+ requester_id: &str,+ range: OccurrenceRange,+ cursor: Option<CalendarOccurrenceCursor>,+ limit: u16,+ ) -> Result<+ Vec<(+ super::models::CalendarEvent,+ super::models::CalendarOccurrence,+ )>,+ Report,+ > {+ validate_query(&range, limit)?;+ self.repository+ .list_occurrences(requester_id, range, cursor, limit)+ .await+ }++ /// Return the aggregate ingestion state of the requester's visible accounts.+ #[tracing::instrument(skip(self, requester_id), err)]+ pub async fn sync_status(+ &self,+ requester_id: &str,+ ) -> Result<super::models::CalendarSyncStatus, Report> {+ self.repository.sync_status(requester_id).await+ }+}++impl<R> CalendarOccurrenceService for CalendarService<R>+where+ R: CalendarRepository,+{+ fn list_occurrences(+ &self,+ requester_id: &str,+ range: OccurrenceRange,+ cursor: Option<CalendarOccurrenceCursor>,+ limit: u16,+ ) -> impl Future<+ Output = Result<+ Vec<(+ super::models::CalendarEvent,+ super::models::CalendarOccurrence,+ )>,+ Report,+ >,+ > + Send {+ CalendarService::list_occurrences(self, requester_id, range, cursor, limit)+ }++ fn sync_status(+ &self,+ requester_id: &str,+ ) -> impl Future<Output = Result<super::models::CalendarSyncStatus, Report>> + Send {+ CalendarService::sync_status(self, requester_id)+ }+}++/// Orchestrates a Google account backfill while keeping HTTP and SQL behind ports.+pub struct GoogleCalendarBackfillService<R, G> {+ repository: R,+ provider: G,+}++/// Periodically makes completed provider jobs eligible for another incremental poll.+pub struct GoogleCalendarSyncScheduler<R> {+ repository: R,+}++impl<R> GoogleCalendarSyncScheduler<R>+where+ R: GoogleCalendarSyncRepository,+{+ /// Construct the scheduler from its persistence port.+ pub fn new(repository: R) -> Self {+ Self { repository }+ }++ /// Schedule current-grant accounts that have not been polled recently.+ #[tracing::instrument(skip(self), err)]+ pub async fn run_once(&self, now: chrono::DateTime<Utc>) -> Result<usize, Report> {+ self.repository+ .schedule_due_google_syncs(now - chrono::Duration::minutes(5))+ .await+ }+}++/// Applies terminal Google Calendar failures that happen before lease claim.+pub struct GoogleCalendarBackfillFailureService<L> {+ lifecycle: L,+}++impl<L> GoogleCalendarBackfillFailureService<L>+where+ L: CalendarBackfillRepository,+{+ /// Construct the failure application service from its persistence port.+ pub fn new(lifecycle: L) -> Self {+ Self { lifecycle }+ }++ /// Atomically terminate an unclaimed job and update its account and inbox health.+ #[tracing::instrument(skip(self, message), err)]+ pub async fn fail_unclaimed(+ &self,+ key: CalendarBackfillJobKey,+ disposition: CalendarBackfillFailureDisposition,+ message: &str,+ ) -> Result<CalendarBackfillFailureOutcome, Report> {+ if disposition == CalendarBackfillFailureDisposition::Retry {+ return Err(rootcause::report!(+ "unclaimed Google Calendar failures must be terminal"+ ));+ }+ self.lifecycle+ .fail_unclaimed_google_backfill(key, disposition, message)+ .await+ }+}++/// Queue-visible outcome of executing a fenced Google Calendar backfill.+#[derive(Debug, thiserror::Error)]+pub enum GoogleCalendarBackfillRunError {+ /// Another delivery owns the durable lease.+ #[error("Google Calendar backfill is already leased")]+ Busy,+ /// The durable job does not exist for the supplied inbox.+ #[error("Google Calendar backfill job was not found")]+ NotFound,+ /// The job previously ended with a permanent failure.+ #[error("Google Calendar backfill is already failed")]+ AlreadyFailed,+ /// Lease ownership was lost while provider work was running.+ #[error("Google Calendar backfill lease was lost")]+ LeaseLost,+ /// The provider grant must be refreshed by the user.+ #[error("Google Calendar grant requires reauthorization: {message}")]+ ReauthRequired {+ /// Provider failure detail.+ message: String,+ /// Whether this failure consumed the inbox's healthy-to-reauth edge.+ link_reauth_transitioned: bool,+ },+ /// Google rejected the request permanently.+ #[error("Google Calendar rejected the backfill request: {0}")]+ Permanent(String),+ /// The job can be retried without user action.+ #[error("Google Calendar backfill failed transiently: {0}")]+ Retryable(String),+}++/// Application service that owns Google backfill claim, lease, and terminal policy.+pub struct GoogleCalendarBackfillCoordinator<R, G, L> {+ repository: R,+ provider: G,+ lifecycle: L,+}++impl<R, G, L> GoogleCalendarBackfillCoordinator<R, G, L>+where+ R: CalendarRepository + Clone,+ G: GoogleCalendarProvider + Clone,+ L: CalendarBackfillRepository,+{+ /// Construct a coordinator from domain ports.+ pub fn new(repository: R, provider: G, lifecycle: L) -> Self {+ Self {+ repository,+ provider,+ lifecycle,+ }+ }++ /// Execute one idempotent queue delivery under a fenced renewable lease.+ #[tracing::instrument(skip(self, owner_id, access_token, range), fields(job_id = %key.job_id), err)]+ pub async fn run(+ &self,+ key: CalendarBackfillJobKey,+ owner_id: &str,+ access_token: &str,+ range: OccurrenceRange,+ ) -> Result<usize, GoogleCalendarBackfillRunError> {+ let (lease_token, account_id) = match self+ .lifecycle+ .claim_google_backfill(key)+ .await+ .map_err(|error| GoogleCalendarBackfillRunError::Retryable(format!("{error:?}")))?+ {+ CalendarBackfillClaim::Claimed {+ lease_token,+ account_id,+ } => (lease_token, account_id),+ CalendarBackfillClaim::Complete => return Ok(0),+ CalendarBackfillClaim::Busy => return Err(GoogleCalendarBackfillRunError::Busy),+ CalendarBackfillClaim::Failed => {+ return Err(GoogleCalendarBackfillRunError::AlreadyFailed);+ }+ CalendarBackfillClaim::NotFound => {+ return Err(GoogleCalendarBackfillRunError::NotFound);+ }+ };++ if let Err(error) = self+ .lifecycle+ .mark_google_account_syncing(key, lease_token)+ .await+ {+ let message = format!("{error:?}");+ self.persist_failure(+ key,+ lease_token,+ CalendarBackfillFailureDisposition::Retry,+ &message,+ )+ .await?;+ return Err(GoogleCalendarBackfillRunError::Retryable(message));+ }++ let backfill =+ GoogleCalendarBackfillService::new(self.repository.clone(), self.provider.clone());+ let work = backfill.backfill(key, lease_token, account_id, owner_id, access_token, range);+ let lease = self+ .lifecycle+ .maintain_google_backfill_lease(key, lease_token);+ futures::pin_mut!(work);+ futures::pin_mut!(lease);+ let result = match select(work, lease).await {+ Either::Left((result, _lease)) => result,+ Either::Right((_lease_result, _work)) => {+ return Err(GoogleCalendarBackfillRunError::LeaseLost);+ }+ };++ match result {+ Ok(count) => {+ self.lifecycle+ .complete_google_backfill(key, lease_token, count)+ .await+ .map_err(|_| GoogleCalendarBackfillRunError::LeaseLost)?;+ Ok(count)+ }+ Err(error) => {+ let provider_error = error+ .as_ref()+ .downcast_current_context::<GoogleProviderError>();+ let disposition = match provider_error.map(GoogleProviderError::kind) {+ Some(GoogleProviderErrorKind::ReauthRequired) => {+ CalendarBackfillFailureDisposition::CalendarPermissionRequired+ }+ Some(GoogleProviderErrorKind::Permanent) => {+ CalendarBackfillFailureDisposition::Permanent+ }+ Some(+ GoogleProviderErrorKind::Transient+ | GoogleProviderErrorKind::SyncTokenExpired,+ )+ | None => CalendarBackfillFailureDisposition::Retry,+ };+ let message = format!("{error:?}");+ let outcome = self+ .persist_failure(key, lease_token, disposition, &message)+ .await?;+ Err(match disposition {+ CalendarBackfillFailureDisposition::ReauthRequired+ | CalendarBackfillFailureDisposition::CalendarPermissionRequired => {+ GoogleCalendarBackfillRunError::ReauthRequired {+ message,+ link_reauth_transitioned: outcome.link_reauth_transitioned,+ }+ }+ CalendarBackfillFailureDisposition::Permanent => {+ GoogleCalendarBackfillRunError::Permanent(message)+ }+ CalendarBackfillFailureDisposition::Retry => {+ GoogleCalendarBackfillRunError::Retryable(message)+ }+ })+ }+ }+ }++ async fn persist_failure(+ &self,+ key: CalendarBackfillJobKey,+ lease_token: Uuid,+ disposition: CalendarBackfillFailureDisposition,+ message: &str,+ ) -> Result<CalendarBackfillFailureOutcome, GoogleCalendarBackfillRunError> {+ self.lifecycle+ .fail_google_backfill(key, lease_token, disposition, message)+ .await+ .map_err(|_| GoogleCalendarBackfillRunError::LeaseLost)+ }+}++impl<R, G> GoogleCalendarBackfillService<R, G>+where+ R: CalendarRepository,+ G: GoogleCalendarProvider,+{+ /// Construct the provider backfill service.+ pub fn new(repository: R, provider: G) -> Self {+ Self {+ repository,+ provider,+ }+ }++ /// Fetch and reconcile calendars and events for a connected inbox.+ #[tracing::instrument(skip(self, owner_id, access_token, range), err)]+ pub async fn backfill(+ &self,+ key: CalendarBackfillJobKey,+ lease_token: Uuid,+ account_id: Uuid,+ owner_id: &str,+ access_token: &str,+ range: OccurrenceRange,+ ) -> Result<usize, Report> {+ if !range.is_valid_for_backfill() {+ return Err(rootcause::report!(CalendarValidationError::InvalidRange).into());+ }+ let calendars = self+ .provider+ .list_calendars(access_token)+ .await+ .map_err(|error| -> Report { rootcause::report!(error).into() })?;+ let mut count = 0;+ let mut calendar_ids = Vec::with_capacity(calendars.len());++ for provider_calendar in calendars {+ let provider_calendar_id = provider_calendar.provider_calendar_id.clone();+ let is_read_only = !matches!(+ provider_calendar.access_role.as_deref(),+ Some("owner" | "writer")+ );+ let stored_calendar = self+ .repository+ .upsert_google_calendar(key, lease_token, account_id, provider_calendar)+ .await?;+ let calendar_id = stored_calendar.id;+ calendar_ids.push(calendar_id);+ let plan = stored_calendar.sync_plan(&range);+ let batch = self+ .provider+ .sync_events(+ access_token,+ GoogleEventSyncContext {+ owner_id: owner_id.to_string(),+ email_link_id: key.email_link_id,+ account_id,+ calendar_id,+ provider_calendar_id,+ is_read_only,+ range: range.clone(),+ sync_token: stored_calendar.sync_token,+ plan,+ },+ )+ .await+ .map_err(|error| -> Report { rootcause::report!(error).into() })?;+ for upsert in batch.upserts {+ if let Err(error) = validate_upsert(&upsert) {+ tracing::warn!(+ error=?error,+ calendar_id=%calendar_id,+ ical_uid=%upsert.event.ical_uid,+ "skipping invalid normalized Google Calendar event"+ );+ continue;+ }+ if let super::models::CalendarEventSource::Google(source) = &upsert.source {+ debug_assert_eq!(source.calendar_id, calendar_id);+ }+ self.repository+ .upsert_event(CalendarEventWrite::GoogleBackfill {+ key,+ lease_token,+ upsert,+ })+ .await?;+ count += 1;+ }+ // Committing per calendar keeps earlier calendars' sync tokens+ // durable when a later calendar's poll fails, so the retry only+ // re-pulls what never committed.+ self.repository+ .commit_google_calendar_sync(+ key,+ lease_token,+ account_id,+ GoogleCalendarSyncSnapshot {+ calendar_id,+ next_sync_token: batch.next_sync_token,+ observed_provider_event_ids: batch.observed_provider_event_ids,+ materialized_range: batch.materialized_range,+ cancelled_provider_event_ids: batch.cancelled_provider_event_ids,+ },+ )+ .await?;+ }++ self.repository+ .reconcile_google_calendar_list(key, lease_token, account_id, calendar_ids)+ .await?;++ Ok(count)+ }+}++fn validate_upsert(upsert: &CalendarEventUpsert) -> Result<(), Report> {+ if upsert.event.owner_id.trim().is_empty() || upsert.event.ical_uid.trim().is_empty() {+ return Err(rootcause::report!(CalendarValidationError::MissingIdentity).into());+ }+ if !upsert.event.time.is_valid()+ || upsert+ .occurrences+ .iter()+ .any(|occurrence| !occurrence.time.is_valid())+ || upsert+ .overrides+ .iter()+ .any(|event_override| !event_override.time.is_valid())+ {+ return Err(rootcause::report!(CalendarValidationError::InvalidTime).into());+ }+ Ok(())+}++fn validate_query(range: &OccurrenceRange, limit: u16) -> Result<(), Report> {+ if !range.is_valid() || !range.is_materialized_at(Utc::now()) {+ return Err(rootcause::report!(CalendarValidationError::InvalidRange).into());+ }+ // One extra row lets the HTTP adapter report truncation accurately while+ // preserving its public maximum page size of 2,000.+ if !(1..=2001).contains(&limit) {+ return Err(rootcause::report!(CalendarValidationError::InvalidLimit).into());+ }+ Ok(())+}++#[cfg(test)]+mod test;diff --git a/crates/calendar_events/src/domain/service/test.rs b/crates/calendar_events/src/domain/service/test.rsnew file mode 100644index 0000000000..46776699bd--- /dev/null+++ b/crates/calendar_events/src/domain/service/test.rs@@ -0,0 +1,604 @@+use super::*;+use crate::domain::{+ models::{+ AttendeeResponseStatus, CalendarAttendee, CalendarBackfillClaim,+ CalendarBackfillFailureDisposition, CalendarBackfillJobKey, CalendarEvent,+ CalendarEventSource, CalendarOccurrence, CalendarSyncStatus, EmailCalendarBackfillState,+ EmailCalendarScanAssociation, EmailCalendarScanJob, EmailCalendarScanStatus,+ EmailIcsSource, EventStatus, EventTime, EventTransparency, EventVisibility,+ GOOGLE_CALENDAR_SCOPES, GoogleCalendarSyncSnapshot, GoogleEventSyncBatch, ProviderCalendar,+ StoredGoogleCalendar,+ },+ ports::{+ CalendarBackfillRepository, CalendarEventWrite, CalendarRepository,+ EmailCalendarBackfillPublisher, EmailCalendarBackfillRepository, GoogleCalendarProvider,+ GoogleEventSyncContext, GoogleProviderError,+ },+};+use chrono::{TimeZone, Utc};+use std::sync::{Arc, Mutex};++#[derive(Clone, Default)]+struct FakeRepo {+ upserts: Arc<Mutex<Vec<CalendarEventUpsert>>>,+}++impl CalendarRepository for FakeRepo {+ async fn apply_google_grant(+ &self,+ _email_link_id: Uuid,+ _scopes: GoogleScopeSet,+ ) -> Result<AppliedGoogleGrant, Report> {+ unreachable!()+ }++ async fn upsert_event(&self, write: CalendarEventWrite) -> Result<Uuid, Report> {+ let upsert = match write {+ CalendarEventWrite::EmailIcs(upsert)+ | CalendarEventWrite::GoogleBackfill { upsert, .. }+ | CalendarEventWrite::Fixture(upsert) => upsert,+ };+ let id = upsert.event.id;+ self.upserts.lock().unwrap().push(upsert);+ Ok(id)+ }++ async fn list_occurrences(+ &self,+ _owner_id: &str,+ _range: OccurrenceRange,+ _cursor: Option<CalendarOccurrenceCursor>,+ _limit: u16,+ ) -> Result<Vec<(CalendarEvent, CalendarOccurrence)>, Report> {+ Ok(Vec::new())+ }++ async fn sync_status(&self, _requester_id: &str) -> Result<CalendarSyncStatus, Report> {+ Ok(CalendarSyncStatus::Ready)+ }++ async fn upsert_google_calendar(+ &self,+ _key: CalendarBackfillJobKey,+ _lease_token: Uuid,+ _account_id: Uuid,+ _calendar: ProviderCalendar,+ ) -> Result<StoredGoogleCalendar, Report> {+ Ok(StoredGoogleCalendar {+ id: Uuid::nil(),+ sync_token: None,+ materialized_range: None,+ })+ }++ async fn commit_google_calendar_sync(+ &self,+ _key: CalendarBackfillJobKey,+ _lease_token: Uuid,+ _account_id: Uuid,+ _sync: GoogleCalendarSyncSnapshot,+ ) -> Result<(), Report> {+ Ok(())+ }++ async fn reconcile_google_calendar_list(+ &self,+ _key: CalendarBackfillJobKey,+ _lease_token: Uuid,+ _account_id: Uuid,+ _calendar_ids: Vec<Uuid>,+ ) -> Result<(), Report> {+ Ok(())+ }+}++fn valid_upsert() -> CalendarEventUpsert {+ let event_id = Uuid::now_v7();+ let starts_at = Utc.with_ymd_and_hms(2026, 7, 24, 14, 0, 0).unwrap();+ let ends_at = Utc.with_ymd_and_hms(2026, 7, 24, 15, 0, 0).unwrap();+ CalendarEventUpsert {+ event: CalendarEvent {+ id: event_id,+ owner_id: "macro|[email protected]".to_string(),+ ical_uid: "[email protected]".to_string(),+ title: "Meeting".to_string(),+ description: None,+ location: None,+ status: EventStatus::Confirmed,+ visibility: EventVisibility::Default,+ transparency: EventTransparency::Opaque,+ time: EventTime::Timed {+ starts_at,+ ends_at,+ time_zone: Some("UTC".to_string()),+ },+ recurrence_lines: Vec::new(),+ organizer_email: None,+ organizer_name: None,+ conference_url: None,+ sequence: 0,+ is_read_only: true,+ attendees: vec![CalendarAttendee {+ email: "[email protected]".to_string(),+ display_name: None,+ response_status: AttendeeResponseStatus::Accepted,+ is_organizer: false,+ is_optional: false,+ is_self: true,+ comment: None,+ }],+ created_at: starts_at,+ updated_at: starts_at,+ },+ source: CalendarEventSource::EmailIcs(EmailIcsSource {+ email_link_id: Uuid::now_v7(),+ email_thread_id: None,+ email_message_id: Uuid::now_v7(),+ email_attachment_id: None,+ content_hash: "hash".to_string(),+ raw_payload: serde_json::json!({}),+ }),+ overrides: Vec::new(),+ occurrences: vec![CalendarOccurrence {+ event_id,+ occurrence_key: starts_at.to_rfc3339(),+ recurrence_id: None,+ time: EventTime::Timed {+ starts_at,+ ends_at,+ time_zone: Some("UTC".to_string()),+ },+ is_cancelled: false,+ }],+ }+}++#[tokio::test]+async fn accepts_valid_event() {+ let repo = FakeRepo::default();+ let service = CalendarService::new(repo.clone());+ let upsert = valid_upsert();++ service.upsert_email_event(upsert).await.unwrap();++ assert_eq!(repo.upserts.lock().unwrap().len(), 1);+}++#[tokio::test]+async fn rejects_invalid_occurrence_time() {+ let repo = FakeRepo::default();+ let service = CalendarService::new(repo.clone());+ let mut upsert = valid_upsert();+ let starts_at = Utc.with_ymd_and_hms(2026, 7, 24, 14, 0, 0).unwrap();+ upsert.occurrences[0].time = EventTime::Timed {+ starts_at,+ ends_at: starts_at,+ time_zone: None,+ };++ assert!(service.upsert_email_event(upsert).await.is_err());+ assert!(repo.upserts.lock().unwrap().is_empty());+}++#[test]+fn complete_scope_capability_requires_top_level_scope() {+ let complete = GoogleScopeSet::parse(&GOOGLE_CALENDAR_SCOPES.join(" "));+ assert!(complete.has_calendar_capability());++ let partial = GoogleScopeSet::parse("https://www.googleapis.com/auth/calendar.events");+ assert!(!partial.has_calendar_capability());+}++#[derive(Clone)]+struct FakeGoogleProvider;++impl GoogleCalendarProvider for FakeGoogleProvider {+ async fn list_calendars(+ &self,+ _access_token: &str,+ ) -> Result<Vec<ProviderCalendar>, GoogleProviderError> {+ Ok(Vec::new())+ }++ async fn sync_events(+ &self,+ _access_token: &str,+ context: GoogleEventSyncContext,+ ) -> Result<GoogleEventSyncBatch, GoogleProviderError> {+ Ok(GoogleEventSyncBatch {+ upserts: Vec::new(),+ observed_provider_event_ids: Some(Vec::new()),+ next_sync_token: "next".to_string(),+ materialized_range: Some(context.range),+ cancelled_provider_event_ids: Vec::new(),+ })+ }+}++#[derive(Clone)]+struct ReauthGoogleProvider;++impl GoogleCalendarProvider for ReauthGoogleProvider {+ async fn list_calendars(+ &self,+ _access_token: &str,+ ) -> Result<Vec<ProviderCalendar>, GoogleProviderError> {+ Err(GoogleProviderError::new(+ GoogleProviderErrorKind::ReauthRequired,+ "insufficient permissions",+ ))+ }++ async fn sync_events(+ &self,+ _access_token: &str,+ _context: GoogleEventSyncContext,+ ) -> Result<GoogleEventSyncBatch, GoogleProviderError> {+ unreachable!("calendar listing fails first")+ }+}++#[derive(Clone)]+struct FakeLifecycle {+ claim: CalendarBackfillClaim,+ completions: Arc<Mutex<Vec<usize>>>,+ failures: Arc<Mutex<Vec<CalendarBackfillFailureDisposition>>>,+ failure_outcome: CalendarBackfillFailureOutcome,+ lease_lost: bool,+}++impl FakeLifecycle {+ fn claimed() -> Self {+ Self {+ claim: CalendarBackfillClaim::Claimed {+ lease_token: Uuid::nil(),+ account_id: Uuid::nil(),+ },+ completions: Arc::new(Mutex::new(Vec::new())),+ failures: Arc::new(Mutex::new(Vec::new())),+ failure_outcome: CalendarBackfillFailureOutcome {+ job_transitioned: true,+ link_reauth_transitioned: false,+ },+ lease_lost: false,+ }+ }++ fn lease_lost() -> Self {+ Self {+ lease_lost: true,+ ..Self::claimed()+ }+ }+}++impl CalendarBackfillRepository for FakeLifecycle {+ async fn fail_unclaimed_google_backfill(+ &self,+ _key: CalendarBackfillJobKey,+ _disposition: CalendarBackfillFailureDisposition,+ _message: &str,+ ) -> Result<CalendarBackfillFailureOutcome, Report> {+ Ok(self.failure_outcome)+ }++ async fn claim_google_backfill(+ &self,+ _key: CalendarBackfillJobKey,+ ) -> Result<CalendarBackfillClaim, Report> {+ Ok(self.claim)+ }++ async fn mark_google_account_syncing(+ &self,+ _key: CalendarBackfillJobKey,+ _lease_token: Uuid,+ ) -> Result<(), Report> {+ Ok(())+ }++ async fn maintain_google_backfill_lease(+ &self,+ _key: CalendarBackfillJobKey,+ _lease_token: Uuid,+ ) -> Result<(), Report> {+ if self.lease_lost {+ return Ok(());+ }+ std::future::pending().await+ }++ async fn complete_google_backfill(+ &self,+ _key: CalendarBackfillJobKey,+ _lease_token: Uuid,+ extracted_count: usize,+ ) -> Result<(), Report> {+ self.completions.lock().unwrap().push(extracted_count);+ Ok(())+ }++ async fn fail_google_backfill(+ &self,+ _key: CalendarBackfillJobKey,+ _lease_token: Uuid,+ disposition: CalendarBackfillFailureDisposition,+ _message: &str,+ ) -> Result<CalendarBackfillFailureOutcome, Report> {+ self.failures.lock().unwrap().push(disposition);+ Ok(self.failure_outcome)+ }+}++#[tokio::test]+async fn google_coordinator_owns_claim_and_completion_lifecycle() {+ let lifecycle = FakeLifecycle::claimed();+ let coordinator = GoogleCalendarBackfillCoordinator::new(+ FakeRepo::default(),+ FakeGoogleProvider,+ lifecycle.clone(),+ );++ let count = coordinator+ .run(+ CalendarBackfillJobKey {+ job_id: Uuid::now_v7(),+ email_link_id: Uuid::now_v7(),+ },+ "macro|[email protected]",+ "secret",+ OccurrenceRange::historical_sync(Utc::now()),+ )+ .await+ .unwrap();++ assert_eq!(count, 0);+ assert_eq!(lifecycle.completions.lock().unwrap().as_slice(), &[0]);+}++#[derive(Clone)]+struct HangingGoogleProvider;++impl GoogleCalendarProvider for HangingGoogleProvider {+ async fn list_calendars(+ &self,+ _access_token: &str,+ ) -> Result<Vec<ProviderCalendar>, GoogleProviderError> {+ std::future::pending().await+ }++ async fn sync_events(+ &self,+ _access_token: &str,+ _context: GoogleEventSyncContext,+ ) -> Result<GoogleEventSyncBatch, GoogleProviderError> {+ unreachable!("provider hangs before syncing events")+ }+}++#[tokio::test]+async fn google_coordinator_surfaces_lease_loss_while_work_is_running() {+ let lifecycle = FakeLifecycle::lease_lost();+ let coordinator = GoogleCalendarBackfillCoordinator::new(+ FakeRepo::default(),+ HangingGoogleProvider,+ lifecycle.clone(),+ );++ let error = coordinator+ .run(+ CalendarBackfillJobKey {+ job_id: Uuid::now_v7(),+ email_link_id: Uuid::now_v7(),+ },+ "macro|[email protected]",+ "secret",+ OccurrenceRange::historical_sync(Utc::now()),+ )+ .await+ .unwrap_err();++ assert!(matches!(error, GoogleCalendarBackfillRunError::LeaseLost));+ assert!(lifecycle.completions.lock().unwrap().is_empty());+ assert!(lifecycle.failures.lock().unwrap().is_empty());+}++#[tokio::test]+async fn google_coordinator_keeps_calendar_permission_health_separate_from_gmail() {+ let lifecycle = FakeLifecycle::claimed();+ let coordinator = GoogleCalendarBackfillCoordinator::new(+ FakeRepo::default(),+ ReauthGoogleProvider,+ lifecycle.clone(),+ );++ let error = coordinator+ .run(+ CalendarBackfillJobKey {+ job_id: Uuid::now_v7(),+ email_link_id: Uuid::now_v7(),+ },+ "macro|[email protected]",+ "secret",+ OccurrenceRange::historical_sync(Utc::now()),+ )+ .await+ .unwrap_err();++ assert!(matches!(+ error,+ GoogleCalendarBackfillRunError::ReauthRequired {+ link_reauth_transitioned: false,+ ..+ }+ ));+ assert_eq!(+ lifecycle.failures.lock().unwrap().as_slice(),+ &[CalendarBackfillFailureDisposition::CalendarPermissionRequired]+ );+}++#[derive(Clone)]+struct FakeEmailLifecycle {+ state: EmailCalendarBackfillState,+ active: Option<EmailCalendarScanJob>,+ associations: Arc<Mutex<usize>>,+ failures: Arc<Mutex<usize>>,+}++impl EmailCalendarBackfillRepository for FakeEmailLifecycle {+ async fn get_email_calendar_backfill_state(+ &self,+ _key: CalendarBackfillJobKey,+ ) -> Result<EmailCalendarBackfillState, Report> {+ Ok(self.state)+ }++ async fn get_email_scan_job(+ &self,+ _email_link_id: Uuid,+ _email_job_id: Uuid,+ ) -> Result<Option<EmailCalendarScanJob>, Report> {+ Ok(self.active)+ }++ async fn get_active_email_scan_job(+ &self,+ _email_link_id: Uuid,+ ) -> Result<Option<EmailCalendarScanJob>, Report> {+ Ok(self.active)+ }++ async fn create_email_scan_job(+ &self,+ _email_link_id: Uuid,+ _fusionauth_user_id: &str,+ ) -> Result<EmailCalendarScanJob, Report> {+ self.active+ .ok_or_else(|| rootcause::report!("test scan was not configured"))+ }++ async fn associate_email_scan(+ &self,+ _key: CalendarBackfillJobKey,+ _email_job_id: Uuid,+ _allow_in_progress: bool,+ ) -> Result<EmailCalendarScanAssociation, Report> {+ *self.associations.lock().unwrap() += 1;+ Ok(EmailCalendarScanAssociation::Associated(+ self.active.expect("configured scan").status,+ ))+ }++ async fn fail_email_calendar_backfill(+ &self,+ _key: CalendarBackfillJobKey,+ _message: &str,+ ) -> Result<bool, Report> {+ *self.failures.lock().unwrap() += 1;+ Ok(true)+ }+}++#[derive(Clone, Default)]+struct FakeEmailPublisher {+ publications: Arc<Mutex<usize>>,+}++impl EmailCalendarBackfillPublisher for FakeEmailPublisher {+ async fn publish_email_scan_init(+ &self,+ _email_link_id: Uuid,+ _email_job_id: Uuid,+ ) -> Result<(), Report> {+ *self.publications.lock().unwrap() += 1;+ Ok(())+ }+}++#[tokio::test]+async fn email_coordinator_waits_instead_of_joining_a_partial_scan() {+ let repository = FakeEmailLifecycle {+ state: EmailCalendarBackfillState::Unassociated,+ active: Some(EmailCalendarScanJob {+ id: Uuid::now_v7(),+ status: EmailCalendarScanStatus::InProgress,+ is_full_scan: true,+ }),+ associations: Arc::new(Mutex::new(0)),+ failures: Arc::new(Mutex::new(0)),+ };+ let publisher = FakeEmailPublisher::default();+ let coordinator = EmailCalendarBackfillCoordinator::new(repository.clone(), publisher.clone());++ let error = coordinator+ .run(+ CalendarBackfillJobKey {+ job_id: Uuid::now_v7(),+ email_link_id: Uuid::now_v7(),+ },+ "fusion-user",+ )+ .await+ .unwrap_err();++ assert!(matches!(error, EmailCalendarBackfillRunError::Busy));+ assert_eq!(*repository.associations.lock().unwrap(), 0);+ assert_eq!(*publisher.publications.lock().unwrap(), 0);+}++#[tokio::test]+async fn email_coordinator_rejects_a_bounded_scan() {+ let repository = FakeEmailLifecycle {+ state: EmailCalendarBackfillState::Unassociated,+ active: Some(EmailCalendarScanJob {+ id: Uuid::now_v7(),+ status: EmailCalendarScanStatus::Init,+ is_full_scan: false,+ }),+ associations: Arc::new(Mutex::new(0)),+ failures: Arc::new(Mutex::new(0)),+ };+ let publisher = FakeEmailPublisher::default();+ let coordinator = EmailCalendarBackfillCoordinator::new(repository.clone(), publisher.clone());++ let error = coordinator+ .run(+ CalendarBackfillJobKey {+ job_id: Uuid::now_v7(),+ email_link_id: Uuid::now_v7(),+ },+ "fusion-user",+ )+ .await+ .unwrap_err();++ assert!(matches!(error, EmailCalendarBackfillRunError::Busy));+ assert_eq!(*repository.associations.lock().unwrap(), 0);+ assert_eq!(*publisher.publications.lock().unwrap(), 0);+}++#[tokio::test]+async fn email_coordinator_applies_terminal_failure_through_its_repository() {+ let repository = FakeEmailLifecycle {+ state: EmailCalendarBackfillState::NotFound,+ active: None,+ associations: Arc::new(Mutex::new(0)),+ failures: Arc::new(Mutex::new(0)),+ };+ let coordinator =+ EmailCalendarBackfillCoordinator::new(repository.clone(), FakeEmailPublisher::default());++ coordinator+ .fail_terminal(+ CalendarBackfillJobKey {+ job_id: Uuid::now_v7(),+ email_link_id: Uuid::now_v7(),+ },+ "invalid calendar data",+ )+ .await+ .unwrap();++ assert_eq!(*repository.failures.lock().unwrap(), 1);+}diff --git a/crates/calendar_events/src/inbound/axum_router.rs b/crates/calendar_events/src/inbound/axum_router.rsnew file mode 100644index 0000000000..2a534ca1b2--- /dev/null+++ b/crates/calendar_events/src/inbound/axum_router.rs@@ -0,0 +1,266 @@+//! Axum router for calendar occurrence queries.++#[cfg(test)]+mod test;++use std::sync::Arc;++use axum::{+ Json, Router,+ extract::{FromRef, Query, State},+ http::StatusCode,+ response::{IntoResponse, Response},+ routing::get,+};+use chrono::{DateTime, NaiveDate, NaiveTime, Utc};+use macro_authorization::{+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,+};+use models_pagination::Base64Str;+use serde::{Deserialize, Serialize};++use crate::domain::{+ models::{+ CalendarEvent, CalendarOccurrence, CalendarOccurrenceCursor, CalendarSyncStatus,+ OccurrenceRange,+ },+ ports::CalendarOccurrenceService,+ service::CalendarValidationError,+};++/// Router state for authenticated calendar occurrence queries.+pub struct CalendarRouterState<S, Auth> {+ service: Arc<S>,+ authorization_state: MacroAuthorizationState<Auth>,+}++impl<S, Auth> Clone for CalendarRouterState<S, Auth> {+ fn clone(&self) -> Self {+ Self {+ service: Arc::clone(&self.service),+ authorization_state: self.authorization_state.clone(),+ }+ }+}++impl<S, Auth> CalendarRouterState<S, Auth> {+ /// Create router state from a shared calendar service and authorization state.+ pub fn new(service: Arc<S>, authorization_state: MacroAuthorizationState<Auth>) -> Self {+ Self {+ service,+ authorization_state,+ }+ }+}++impl<S, Auth> FromRef<CalendarRouterState<S, Auth>> for MacroAuthorizationState<Auth> {+ fn from_ref(state: &CalendarRouterState<S, Auth>) -> Self {+ state.authorization_state.clone()+ }+}++/// Build the authenticated calendar occurrence router.+pub fn calendar_router<S, Auth, T>(state: CalendarRouterState<S, Auth>) -> Router<T>+where+ S: CalendarOccurrenceService,+ Auth: MacroAuthorizationService,+ T: Send + Sync + 'static,+{+ Router::new()+ .route("/calendar-events", get(list_occurrences::<S, Auth>))+ .route("/calendar-events/", get(list_occurrences::<S, Auth>))+ .with_state(state)+}++/// Query parameters for a calendar occurrence viewport.+#[derive(Debug, Deserialize, utoipa::IntoParams)]+#[into_params(parameter_in = Query)]+#[serde(rename_all = "camelCase")]+pub struct CalendarOccurrenceQuery {+ /// Inclusive UTC viewport start.+ start: DateTime<Utc>,+ /// Exclusive UTC viewport end.+ end: DateTime<Utc>,+ /// Inclusive local date boundary for all-day events.+ start_date: Option<NaiveDate>,+ /// Exclusive local date boundary for all-day events.+ end_date: Option<NaiveDate>,+ /// Maximum number of occurrences, from 1 through 2,000.+ #[param(minimum = 1, maximum = 2000)]+ limit: Option<u16>,+ /// Opaque continuation cursor returned by the previous page.+ cursor: Option<String>,+}++/// One materialized occurrence paired with its stable calendar event entity.+#[derive(Serialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct CalendarOccurrenceItem {+ event: CalendarEvent,+ occurrence: CalendarOccurrence,+}++/// Paginated calendar occurrence viewport response.+#[derive(Serialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct CalendarOccurrenceResponse {+ items: Vec<CalendarOccurrenceItem>,+ has_more: bool,+ next_cursor: Option<String>,+ /// Aggregate ingestion state; clients render a skeleton while `syncing`.+ sync_status: CalendarSyncStatus,+}++/// HTTP error returned by the calendar occurrence adapter.+#[derive(Debug)]+pub struct CalendarApiError {+ status: StatusCode,+ message: &'static str,+}++impl std::fmt::Display for CalendarApiError {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter.write_str(self.message)+ }+}++impl IntoResponse for CalendarApiError {+ fn into_response(self) -> Response {+ (+ self.status,+ Json(serde_json::json!({ "message": self.message })),+ )+ .into_response()+ }+}++/// Return calendar occurrences visible to the authenticated requester.+#[tracing::instrument(skip_all, err)]+#[utoipa::path(+ get,+ path = "/calendar-events",+ tag = "calendar_events",+ params(CalendarOccurrenceQuery),+ responses(+ (status = 200, description = "Calendar occurrences in the requested viewport", body = CalendarOccurrenceResponse),+ (status = 400, description = "Invalid or unsupported calendar viewport"),+ (status = 401, description = "Authentication required"),+ (status = 500, description = "Calendar query failed"),+ )+)]+pub async fn list_occurrences<S, Auth>(+ State(state): State<CalendarRouterState<S, Auth>>,+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ Query(query): Query<CalendarOccurrenceQuery>,+) -> Result<Json<CalendarOccurrenceResponse>, CalendarApiError>+where+ S: CalendarOccurrenceService,+ Auth: MacroAuthorizationService,+{+ let default_end_date = default_end_date(query.end);+ let range = OccurrenceRange {+ starts_at: query.start,+ ends_at: query.end,+ start_date: query.start_date.unwrap_or_else(|| query.start.date_naive()),+ end_date: query+ .end_date+ .or(default_end_date)+ .ok_or(CalendarApiError {+ status: StatusCode::BAD_REQUEST,+ message: "calendar end is outside the supported date range",+ })?,+ };+ let (limit, repository_limit) = query_limits(query.limit)?;+ let cursor = decode_cursor(query.cursor)?;+ let mut occurrences = state+ .service+ .list_occurrences(+ user.authorization.user.macro_user_id.as_ref(),+ range,+ cursor,+ repository_limit,+ )+ .await+ .map_err(|error| {+ if error+ .as_ref()+ .downcast_current_context::<CalendarValidationError>()+ .is_some()+ {+ return CalendarApiError {+ status: StatusCode::BAD_REQUEST,+ message: "calendar range must be positive, at most 370 days, inside the maintained one-year-history/two-year-future window, with limit 1–2000",+ };+ }+ tracing::error!(error = ?error, "failed to query calendar occurrences");+ CalendarApiError {+ status: StatusCode::INTERNAL_SERVER_ERROR,+ message: "unable to query calendar occurrences",+ }+ })?;+ let sync_status = state+ .service+ .sync_status(user.authorization.user.macro_user_id.as_ref())+ .await+ .map_err(|error| {+ tracing::error!(error = ?error, "failed to query calendar sync status");+ CalendarApiError {+ status: StatusCode::INTERNAL_SERVER_ERROR,+ message: "unable to query calendar occurrences",+ }+ })?;+ let has_more = occurrences.len() > usize::from(limit);+ occurrences.truncate(usize::from(limit));+ let next_cursor = has_more+ .then(|| occurrences.last())+ .flatten()+ .map(|(_, occurrence)| {+ Base64Str::encode_json(CalendarOccurrenceCursor::from_occurrence(occurrence))+ .type_erase()+ });+ let items = occurrences+ .into_iter()+ .map(|(event, occurrence)| CalendarOccurrenceItem { event, occurrence })+ .collect();++ Ok(Json(CalendarOccurrenceResponse {+ items,+ has_more,+ next_cursor,+ sync_status,+ }))+}++fn decode_cursor(+ cursor: Option<String>,+) -> Result<Option<CalendarOccurrenceCursor>, CalendarApiError> {+ cursor+ .map(|cursor| {+ Base64Str::new_from_string(cursor)+ .decode_json()+ .map_err(|_| CalendarApiError {+ status: StatusCode::BAD_REQUEST,+ message: "calendar cursor is invalid",+ })+ })+ .transpose()+}++fn query_limits(requested: Option<u16>) -> Result<(u16, u16), CalendarApiError> {+ let limit = requested.unwrap_or(1000);+ if !(1..=2000).contains(&limit) {+ return Err(CalendarApiError {+ status: StatusCode::BAD_REQUEST,+ message: "calendar limit must be between 1 and 2000",+ });+ }+ Ok((limit, limit + 1))+}++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/calendar_events/src/inbound/axum_router/test.rs b/crates/calendar_events/src/inbound/axum_router/test.rsnew file mode 100644index 0000000000..b50418a83f--- /dev/null+++ b/crates/calendar_events/src/inbound/axum_router/test.rs@@ -0,0 +1,41 @@+use super::*;+use chrono::TimeZone;++#[test]+fn midnight_end_uses_the_same_exclusive_date() {+ let end = Utc.with_ymd_and_hms(2026, 7, 25, 0, 0, 0).unwrap();++ assert_eq!(default_end_date(end), NaiveDate::from_ymd_opt(2026, 7, 25));+}++#[test]+fn timed_end_includes_the_end_day_for_all_day_overlap() {+ let end = Utc.with_ymd_and_hms(2026, 7, 25, 18, 30, 0).unwrap();++ assert_eq!(default_end_date(end), NaiveDate::from_ymd_opt(2026, 7, 26));+}++#[test]+fn occurrence_limit_rejects_zero_and_values_above_the_public_maximum() {+ assert!(query_limits(Some(0)).is_err());+ assert!(query_limits(Some(2001)).is_err());+}++#[test]+fn occurrence_limit_reserves_one_repository_row_for_truncation_detection() {+ assert_eq!(query_limits(Some(2000)).unwrap(), (2000, 2001));+ assert_eq!(query_limits(None).unwrap(), (1000, 1001));+}++#[test]+fn occurrence_cursor_round_trips_equal_start_tie_breakers() {+ let cursor = CalendarOccurrenceCursor {+ starts_at: Utc.with_ymd_and_hms(2026, 7, 25, 12, 0, 0).unwrap(),+ event_id: uuid::Uuid::now_v7(),+ occurrence_key: "same-start-instance".to_string(),+ };+ let encoded = Base64Str::encode_json(cursor.clone()).type_erase();++ assert_eq!(decode_cursor(Some(encoded)).unwrap(), Some(cursor));+ assert!(decode_cursor(Some("not-base64".to_string())).is_err());+}diff --git a/crates/calendar_events/src/inbound/mod.rs b/crates/calendar_events/src/inbound/mod.rsnew file mode 100644index 0000000000..a1c6982abb--- /dev/null+++ b/crates/calendar_events/src/inbound/mod.rs@@ -0,0 +1,4 @@+//! Inbound calendar adapters.++/// Axum routes for authenticated calendar queries.+pub mod axum_router;diff --git a/crates/calendar_events/src/lib.rs b/crates/calendar_events/src/lib.rsnew file mode 100644index 0000000000..fab2e0bd6e--- /dev/null+++ b/crates/calendar_events/src/lib.rs@@ -0,0 +1,15 @@+#![deny(missing_docs)]+//! Calendar event domain and persistence adapter.+//!+//! A [`domain::models::CalendarEvent`] is the stable Macro entity. External+//! calendars and email invitations are sources of that entity, while+//! recurrence instances are stored as queryable occurrence projections.++/// Calendar business models, ports, and services.+pub mod domain;+/// Inbound adapters that expose calendar use cases.+#[cfg(feature = "inbound")]+pub mod inbound;+/// Database adapters used by service composition roots.+#[cfg(feature = "postgres")]+pub mod outbound;diff --git a/crates/calendar_events/src/outbound/mod.rs b/crates/calendar_events/src/outbound/mod.rsnew file mode 100644index 0000000000..a0424b0e7e--- /dev/null+++ b/crates/calendar_events/src/outbound/mod.rs@@ -0,0 +1,5 @@+//! Outbound calendar adapters.++/// PostgreSQL calendar repository.+#[cfg(feature = "postgres")]+pub mod pg;diff --git a/crates/calendar_events/src/outbound/pg.rs b/crates/calendar_events/src/outbound/pg.rsnew file mode 100644index 0000000000..61c5305039--- /dev/null+++ b/crates/calendar_events/src/outbound/pg.rs@@ -0,0 +1,2192 @@+//! PostgreSQL implementation of the calendar repository port.++use std::collections::HashMap;++use chrono::{DateTime, NaiveDate, Utc};+use rootcause::Report;+use serde::{Deserialize, Serialize};+use sqlx::{PgPool, Postgres, Transaction};+use uuid::Uuid;++use crate::domain::{+ models::{+ AppliedGoogleGrant, AttendeeResponseStatus, CalendarAttendee, CalendarBackfillClaim,+ CalendarBackfillFailureDisposition, CalendarBackfillFailureOutcome, CalendarBackfillJob,+ CalendarBackfillJobKey, CalendarBackfillKind, CalendarEvent, CalendarEventOverride,+ CalendarEventSource, CalendarEventUpsert, CalendarOccurrence, CalendarOccurrenceCursor,+ CalendarSyncStatus, EventStart, EventStatus, EventTime, EventTransparency, EventVisibility,+ GOOGLE_CALENDAR_SCOPES, GoogleCalendarSyncSnapshot, GoogleScopeSet, OccurrenceRange,+ ProviderCalendar, StoredGoogleCalendar,+ },+ ports::{+ CalendarBackfillRepository, CalendarEventWrite, CalendarRepository,+ GoogleCalendarSyncRepository,+ },+};++/// PostgreSQL calendar repository.+#[derive(Clone)]+pub struct PgCalendarRepository {+ pool: PgPool,+}++impl PgCalendarRepository {+ /// Construct a repository from the shared MacroDB pool.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }++ async fn persist_google_backfill_failure(+ &self,+ key: CalendarBackfillJobKey,+ lease_token: Option<Uuid>,+ disposition: CalendarBackfillFailureDisposition,+ message: &str,+ ) -> Result<CalendarBackfillFailureOutcome, Report> {+ let (job_status, account_status, completed_at, link_needs_reauth) = match disposition {+ CalendarBackfillFailureDisposition::Retry => ("pending", "pending", None, false),+ CalendarBackfillFailureDisposition::Permanent => {+ ("failed", "error", Some(Utc::now()), false)+ }+ CalendarBackfillFailureDisposition::ReauthRequired => {+ ("failed", "reauth_required", Some(Utc::now()), true)+ }+ CalendarBackfillFailureDisposition::CalendarPermissionRequired => {+ ("failed", "reauth_required", Some(Utc::now()), false)+ }+ };+ let required_scopes = GOOGLE_CALENDAR_SCOPES.map(str::to_owned);+ let mut tx = self.pool.begin().await.map_err(report)?;++ // Incremental grant application locks the inbox before its jobs. Keep+ // the same order for reauth failure so concurrent consent and worker+ // deliveries cannot deadlock.+ let previous_link_reauth = if link_needs_reauth {+ Some(+ sqlx::query_scalar!(+ r#"+ SELECT needs_reauth+ FROM email_links+ WHERE id = $1+ FOR UPDATE+ "#,+ key.email_link_id,+ )+ .fetch_one(&mut *tx)+ .await+ .map_err(report)?,+ )+ } else {+ None+ };++ let updated = if let Some(lease_token) = lease_token {+ sqlx::query!(+ r#"+ UPDATE calendar_backfill_jobs+ SET status = $4,+ lease_expires_at = NULL,+ lease_token = NULL,+ last_error = $2,+ completed_at = $5,+ updated_at = now()+ WHERE id = $1+ AND email_link_id = $3+ AND kind = 'google_calendar'+ AND status = 'running'+ AND lease_token = $6+ AND lease_expires_at > now()+ AND EXISTS (+ SELECT 1+ FROM email_links link+ WHERE link.id = calendar_backfill_jobs.email_link_id+ AND link.google_grant_version = calendar_backfill_jobs.grant_version+ AND link.google_granted_scopes @> $7::text[]+ )+ "#,+ key.job_id,+ message,+ key.email_link_id,+ job_status,+ completed_at,+ lease_token,+ &required_scopes,+ )+ .execute(&mut *tx)+ .await+ .map_err(report)?+ } else {+ sqlx::query!(+ r#"+ UPDATE calendar_backfill_jobs+ SET status = $4,+ lease_expires_at = NULL,+ lease_token = NULL,+ last_error = $2,+ completed_at = $5,+ updated_at = now()+ WHERE id = $1+ AND email_link_id = $3+ AND kind = 'google_calendar'+ AND status NOT IN ('complete', 'failed')+ AND lease_token IS NULL+ AND EXISTS (+ SELECT 1+ FROM email_links link+ WHERE link.id = calendar_backfill_jobs.email_link_id+ AND link.google_grant_version = calendar_backfill_jobs.grant_version+ AND link.google_granted_scopes @> $6::text[]+ )+ "#,+ key.job_id,+ message,+ key.email_link_id,+ job_status,+ completed_at,+ &required_scopes,+ )+ .execute(&mut *tx)+ .await+ .map_err(report)?+ };+ if updated.rows_affected() != 1 {+ if lease_token.is_some() {+ return Err(rootcause::report!(+ "Google Calendar backfill lease was lost"+ ));+ }+ tx.commit().await.map_err(report)?;+ return Ok(CalendarBackfillFailureOutcome {+ job_transitioned: false,+ link_reauth_transitioned: false,+ });+ }++ sqlx::query!(+ r#"+ UPDATE calendar_accounts+ SET sync_status = $2,+ last_sync_error = $3,+ updated_at = now()+ WHERE email_link_id = $1+ "#,+ key.email_link_id,+ account_status,+ message,+ )+ .execute(&mut *tx)+ .await+ .map_err(report)?;+ if link_needs_reauth {+ sqlx::query!(+ r#"+ UPDATE email_links+ SET needs_reauth = true,+ last_sync_error_at = now(),+ updated_at = now()+ WHERE id = $1+ "#,+ key.email_link_id,+ )+ .execute(&mut *tx)+ .await+ .map_err(report)?;+ }++ tx.commit().await.map_err(report)?;+ Ok(CalendarBackfillFailureOutcome {+ job_transitioned: true,+ link_reauth_transitioned: previous_link_reauth == Some(false),+ })+ }++ #[cfg(test)]+ async fn upsert_event_fixture(&self, upsert: CalendarEventUpsert) -> Result<Uuid, Report> {+ self.upsert_event(CalendarEventWrite::Fixture(upsert)).await+ }++ #[cfg(test)]+ async fn upsert_calendar_fixture(+ &self,+ account_id: Uuid,+ calendar: ProviderCalendar,+ ) -> Result<Uuid, Report> {+ let mut tx = self.pool.begin().await.map_err(report)?;+ let id = upsert_calendar_tx(&mut tx, account_id, calendar).await?.id;+ tx.commit().await.map_err(report)?;+ Ok(id)+ }++ #[cfg(test)]+ async fn upsert_google_account(&self, email_link_id: Uuid) -> Result<Uuid, Report> {+ let mut tx = self.pool.begin().await.map_err(report)?;+ let row = sqlx::query_as!(+ GrantRow,+ r#"+ SELECT+ macro_id,+ email_address::text AS "email_address!",+ google_granted_scopes,+ google_grant_version+ FROM email_links+ WHERE id = $1+ "#,+ email_link_id,+ )+ .fetch_one(&mut *tx)+ .await+ .map_err(report)?;+ let id =+ upsert_google_account_tx(&mut tx, email_link_id, &row.macro_id, &row.email_address)+ .await?;+ tx.commit().await.map_err(report)?;+ Ok(id)+ }+}++struct GrantRow {+ macro_id: String,+ email_address: String,+ google_granted_scopes: Vec<String>,+ google_grant_version: i64,+}++struct StoredCalendarRow {+ id: Uuid,+ sync_token: Option<String>,+ materialized_starts_at: Option<DateTime<Utc>>,+ materialized_ends_at: Option<DateTime<Utc>>,+ materialized_start_date: Option<NaiveDate>,+ materialized_end_date: Option<NaiveDate>,+}++struct OccurrenceJoinRow {+ event_id: Uuid,+ occurrence_key: String,+ recurrence_id: Option<String>,+ occurrence_starts_at: Option<DateTime<Utc>>,+ occurrence_ends_at: Option<DateTime<Utc>>,+ occurrence_start_date: Option<NaiveDate>,+ occurrence_end_date: Option<NaiveDate>,+ is_cancelled: bool,+ owner_id: String,+ ical_uid: String,+ title: String,+ description: Option<String>,+ location: Option<String>,+ status: String,+ visibility: String,+ transparency: String,+ starts_at: Option<DateTime<Utc>>,+ ends_at: Option<DateTime<Utc>>,+ start_date: Option<NaiveDate>,+ end_date: Option<NaiveDate>,+ time_zone: Option<String>,+ recurrence_lines: Vec<String>,+ organizer_email: Option<String>,+ organizer_name: Option<String>,+ conference_url: Option<String>,+ sequence: i32,+ is_read_only: bool,+ created_at: DateTime<Utc>,+ updated_at: DateTime<Utc>,+}++struct AttendeeRow {+ event_id: Uuid,+ email: String,+ display_name: Option<String>,+ response_status: String,+ is_organizer: bool,+ is_optional: bool,+ is_self: bool,+ comment: Option<String>,+}++#[derive(Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+struct StoredSourceProjection {+ event: CalendarEvent,+ overrides: Vec<CalendarEventOverride>,+ occurrences: Vec<CalendarOccurrence>,+}++impl From<&CalendarEventUpsert> for StoredSourceProjection {+ fn from(upsert: &CalendarEventUpsert) -> Self {+ Self {+ event: upsert.event.clone(),+ overrides: upsert.overrides.clone(),+ occurrences: upsert.occurrences.clone(),+ }+ }+}++impl CalendarRepository for PgCalendarRepository {+ #[tracing::instrument(skip(self, scopes), err)]+ async fn apply_google_grant(+ &self,+ email_link_id: Uuid,+ scopes: GoogleScopeSet,+ ) -> Result<AppliedGoogleGrant, Report> {+ let mut tx = self.pool.begin().await.map_err(report)?;+ let row = sqlx::query_as!(+ GrantRow,+ r#"+ SELECT+ macro_id,+ email_address::text AS "email_address!",+ google_granted_scopes,+ google_grant_version+ FROM email_links+ WHERE id = $1+ FOR UPDATE+ "#,+ email_link_id,+ )+ .fetch_one(&mut *tx)+ .await+ .map_err(report)?;++ let old_scopes = GoogleScopeSet::from_scopes(row.google_granted_scopes);+ let had_calendar_capability = old_scopes.has_calendar_capability();+ let changed = old_scopes != scopes;+ if !changed {+ let jobs = if scopes.has_calendar_capability() {+ retry_failed_backfills_tx(&mut tx, email_link_id, row.google_grant_version).await?+ } else {+ Vec::new()+ };+ tx.commit().await.map_err(report)?;+ return Ok(AppliedGoogleGrant {+ grant_version: row.google_grant_version,+ changed: false,+ jobs,+ });+ }++ let grant_version = row.google_grant_version + 1;+ let granted_scopes = scopes.clone().into_vec();+ sqlx::query!(+ r#"+ UPDATE email_links+ SET google_granted_scopes = $2,+ google_grant_version = $3,+ updated_at = now()+ WHERE id = $1+ "#,+ email_link_id,+ &granted_scopes,+ grant_version,+ )+ .execute(&mut *tx)+ .await+ .map_err(report)?;+ invalidate_stale_google_jobs_tx(&mut tx, email_link_id, grant_version).await?;++ let mut jobs = Vec::new();+ let has_calendar_capability = scopes.has_calendar_capability();+ if had_calendar_capability && !has_calendar_capability {+ disable_google_calendar_capability_tx(&mut tx, email_link_id).await?;+ }+ if has_calendar_capability {+ let account_id =+ upsert_google_account_tx(&mut tx, email_link_id, &row.macro_id, &row.email_address)+ .await?;+ for kind in [+ CalendarBackfillKind::GoogleCalendar,+ CalendarBackfillKind::EmailIcs,+ ] {+ let job_id = Uuid::now_v7();+ let inserted = sqlx::query_scalar!(+ r#"+ INSERT INTO calendar_backfill_jobs (+ id, email_link_id, account_id, kind, grant_version+ )+ VALUES ($1, $2, $3, $4, $5)+ ON CONFLICT (email_link_id, kind, grant_version) DO NOTHING+ RETURNING id+ "#,+ job_id,+ email_link_id,+ account_id,+ kind.as_str(),+ grant_version,+ )+ .fetch_optional(&mut *tx)+ .await+ .map_err(report)?;++ if let Some(job_id) = inserted {+ sqlx::query!(+ r#"+ INSERT INTO calendar_sync_outbox (+ id, backfill_job_id+ )+ VALUES ($1, $2)+ "#,+ Uuid::now_v7(),+ job_id,+ )+ .execute(&mut *tx)+ .await+ .map_err(report)?;++ jobs.push(CalendarBackfillJob {+ id: job_id,+ email_link_id,+ account_id: Some(account_id),+ kind,+ grant_version,+ });+ }+ }+ }++ tx.commit().await.map_err(report)?;+ Ok(AppliedGoogleGrant {+ grant_version,+ changed,+ jobs,+ })+ }++ #[tracing::instrument(skip(self, write), err)]+ async fn upsert_event(&self, write: CalendarEventWrite) -> Result<Uuid, Report> {+ let mut tx = self.pool.begin().await.map_err(report)?;+ let upsert = match write {+ CalendarEventWrite::EmailIcs(upsert) => {+ if !matches!(upsert.source, CalendarEventSource::EmailIcs(_)) {+ return Err(rootcause::report!(+ "email ICS ingestion requires an email ICS source"+ ));+ }+ upsert+ }+ CalendarEventWrite::GoogleBackfill {+ key,+ lease_token,+ upsert,+ } => {+ let CalendarEventSource::Google(source) = &upsert.source else {+ return Err(rootcause::report!(+ "Google backfill ingestion requires a Google source"+ ));+ };+ if source.email_link_id != key.email_link_id {+ return Err(rootcause::report!(+ "Google calendar event fence does not match its connected inbox"+ ));+ }+ fence_google_mutation_tx(&mut tx, key, lease_token, Some(source.account_id))+ .await?;+ upsert+ }+ #[cfg(test)]+ CalendarEventWrite::Fixture(upsert) => upsert,+ };+ let source_kind = match &upsert.source {+ CalendarEventSource::Google(_) => "google",+ CalendarEventSource::EmailIcs(_) => "email_ics",+ };+ let source_link_id = match &upsert.source {+ CalendarEventSource::Google(source) => source.email_link_id,+ CalendarEventSource::EmailIcs(source) => source.email_link_id,+ };+ let reconciliation_lock = event_reconciliation_lock(source_link_id, &upsert.event.ical_uid);+ sqlx::query_scalar!(+ r#"SELECT 1 AS "locked!" FROM pg_advisory_xact_lock($1)"#,+ reconciliation_lock,+ )+ .fetch_one(&mut *tx)+ .await+ .map_err(report)?;+ let (starts_at, ends_at, start_date, end_date, time_zone) = split_time(&upsert.event.time);+ let proposed_id = upsert.event.id;++ // Google is the authoritative source when the same RFC UID was first+ // discovered in email. Email can still create/update entities that do+ // not yet have a Google source.+ let applied_id = sqlx::query_scalar!(+ r#"+ INSERT INTO calendar_events (+ id, owner_id, source_link_id, ical_uid, title, description, location,+ status, visibility, transparency,+ starts_at, ends_at, start_date, end_date, time_zone,+ recurrence_lines, organizer_email, organizer_name,+ conference_url, sequence, is_read_only, canonical_source_kind,+ canonical_source_updated_at,+ created_at, updated_at+ )+ VALUES (+ $1, $2, $3, $4, $5, $6, $7,+ $8, $9, $10,+ $11, $12, $13, $14, $15,+ $16, $17, $18,+ $19, $20, $21, $22, $24,+ $23, $24+ )+ ON CONFLICT (owner_id, source_link_id, ical_uid) DO UPDATE SET+ title = EXCLUDED.title,+ description = EXCLUDED.description,+ location = EXCLUDED.location,+ status = EXCLUDED.status,+ visibility = EXCLUDED.visibility,+ transparency = EXCLUDED.transparency,+ starts_at = EXCLUDED.starts_at,+ ends_at = EXCLUDED.ends_at,+ start_date = EXCLUDED.start_date,+ end_date = EXCLUDED.end_date,+ time_zone = EXCLUDED.time_zone,+ recurrence_lines = EXCLUDED.recurrence_lines,+ organizer_email = EXCLUDED.organizer_email,+ organizer_name = EXCLUDED.organizer_name,+ conference_url = EXCLUDED.conference_url,+ sequence = EXCLUDED.sequence,+ is_read_only = EXCLUDED.is_read_only,+ canonical_source_kind = EXCLUDED.canonical_source_kind,+ canonical_source_updated_at = EXCLUDED.canonical_source_updated_at,+ updated_at = GREATEST(calendar_events.updated_at, EXCLUDED.updated_at)+ WHERE+ (+ $25 = 'google'+ AND (+ EXCLUDED.sequence > calendar_events.sequence+ OR (+ EXCLUDED.sequence = calendar_events.sequence+ AND EXCLUDED.canonical_source_updated_at+ >= calendar_events.canonical_source_updated_at+ )+ OR calendar_events.canonical_source_kind <> 'google'+ )+ )+ OR (+ $25 = 'email_ics'+ AND calendar_events.canonical_source_kind <> 'google'+ AND (+ EXCLUDED.sequence > calendar_events.sequence+ OR (+ EXCLUDED.sequence = calendar_events.sequence+ AND EXCLUDED.canonical_source_updated_at+ >= calendar_events.canonical_source_updated_at+ )+ )+ )+ RETURNING id+ "#,+ proposed_id,+ &upsert.event.owner_id,+ source_link_id,+ &upsert.event.ical_uid,+ &upsert.event.title,+ upsert.event.description.as_deref(),+ upsert.event.location.as_deref(),+ upsert.event.status.as_str(),+ upsert.event.visibility.as_str(),+ upsert.event.transparency.as_str(),+ starts_at,+ ends_at,+ start_date,+ end_date,+ time_zone,+ &upsert.event.recurrence_lines,+ upsert.event.organizer_email.as_deref(),+ upsert.event.organizer_name.as_deref(),+ upsert.event.conference_url.as_deref(),+ db_sequence(upsert.event.sequence)?,+ upsert.event.is_read_only,+ source_kind,+ upsert.event.created_at,+ upsert.event.updated_at,+ source_kind,+ )+ .fetch_optional(&mut *tx)+ .await+ .map_err(report)?;++ let event_id = match applied_id {+ Some(id) => id,+ None => sqlx::query_scalar!(+ "SELECT id FROM calendar_events WHERE owner_id = $1 AND source_link_id = $2 AND ical_uid = $3",+ &upsert.event.owner_id,+ source_link_id,+ &upsert.event.ical_uid,+ )+ .fetch_one(&mut *tx)+ .await+ .map_err(report)?,+ };++ persist_source(&mut tx, event_id, &upsert).await?;++ // Only the source selected as canonical replaces projections and+ // attendees. Lower-sequence/stale sources are still recorded above.+ if applied_id.is_some() {+ replace_attendees(&mut tx, event_id, &upsert.event.attendees).await?;+ replace_overrides(&mut tx, event_id, &upsert.overrides).await?;+ replace_occurrences(+ &mut tx,+ event_id,+ &upsert.event.owner_id,+ &upsert.occurrences,+ )+ .await?;+ }++ tx.commit().await.map_err(report)?;+ Ok(event_id)+ }++ #[tracing::instrument(skip(self, requester_id, range), err)]+ async fn list_occurrences(+ &self,+ requester_id: &str,+ range: OccurrenceRange,+ cursor: Option<CalendarOccurrenceCursor>,+ limit: u16,+ ) -> Result<Vec<(CalendarEvent, CalendarOccurrence)>, Report> {+ let cursor_starts_at = cursor.as_ref().map(|cursor| cursor.starts_at);+ let cursor_event_id = cursor.as_ref().map(|cursor| cursor.event_id);+ let cursor_occurrence_key = cursor.as_ref().map(|cursor| cursor.occurrence_key.as_str());+ let rows = sqlx::query_as!(+ OccurrenceJoinRow,+ r#"+ SELECT+ occurrence.event_id,+ occurrence.occurrence_key,+ occurrence.recurrence_id,+ occurrence.starts_at AS occurrence_starts_at,+ occurrence.ends_at AS occurrence_ends_at,+ occurrence.start_date AS occurrence_start_date,+ occurrence.end_date AS occurrence_end_date,+ occurrence.is_cancelled,+ event.owner_id,+ event.ical_uid,+ event.title,+ event.description,+ event.location,+ event.status,+ event.visibility,+ event.transparency,+ event.starts_at,+ event.ends_at,+ event.start_date,+ event.end_date,+ event.time_zone,+ event.recurrence_lines,+ event.organizer_email,+ event.organizer_name,+ event.conference_url,+ event.sequence,+ event.is_read_only,+ event.created_at,+ event.updated_at+ FROM calendar_event_occurrences occurrence+ JOIN calendar_events event ON event.id = occurrence.event_id+ WHERE occurrence.owner_id IN (+ SELECT $1::text+ UNION+ SELECT link.child_macro_id+ FROM macro_user_links link+ WHERE link.primary_macro_id = $1+ )+ AND event.status <> 'cancelled'+ AND NOT occurrence.is_cancelled+ AND (+ event.owner_id = $1+ OR EXISTS (+ SELECT 1+ FROM macro_user_links link+ WHERE link.link_id = event.source_link_id+ AND link.primary_macro_id = $1+ )+ )+ AND (+ occurrence.timed_span && tstzrange($2, $3, '[)')+ OR occurrence.day_span && daterange($4, $5, '[)')+ )+ AND (+ $6::timestamptz IS NULL+ OR (+ COALESCE(+ occurrence.starts_at,+ occurrence.start_date::timestamp AT TIME ZONE 'UTC'+ ),+ occurrence.event_id,+ occurrence.occurrence_key+ ) > ($6, $7, $8)+ )+ ORDER BY+ COALESCE(occurrence.starts_at, occurrence.start_date::timestamp AT TIME ZONE 'UTC'),+ occurrence.event_id,+ occurrence.occurrence_key+ LIMIT $9+ "#,+ requester_id,+ range.starts_at,+ range.ends_at,+ range.start_date,+ range.end_date,+ cursor_starts_at,+ cursor_event_id,+ cursor_occurrence_key,+ i64::from(limit),+ )+ .fetch_all(&self.pool)+ .await+ .map_err(report)?;+ let event_ids: Vec<_> = rows.iter().map(|row| row.event_id).collect();+ let attendees = fetch_attendees(&self.pool, &event_ids).await?;+ rows.into_iter()+ .map(|row| {+ let event_id = row.event_id;+ let occurrence = occurrence_from_join(&row)?;+ let event =+ event_from_join(row, attendees.get(&event_id).cloned().unwrap_or_default())?;+ Ok((event, occurrence))+ })+ .collect()+ }++ #[tracing::instrument(skip(self, requester_id), err)]+ async fn sync_status(&self, requester_id: &str) -> Result<CalendarSyncStatus, Report> {+ let is_syncing = sqlx::query_scalar!(+ r#"+ SELECT EXISTS (+ SELECT 1+ FROM calendar_accounts account+ WHERE account.sync_status IN ('pending', 'syncing')+ AND (+ account.owner_id = $1+ OR EXISTS (+ SELECT 1+ FROM macro_user_links link+ WHERE link.link_id = account.email_link_id+ AND link.primary_macro_id = $1+ )+ )+ ) AS "is_syncing!"+ "#,+ requester_id,+ )+ .fetch_one(&self.pool)+ .await+ .map_err(report)?;+ Ok(if is_syncing {+ CalendarSyncStatus::Syncing+ } else {+ CalendarSyncStatus::Ready+ })+ }++ #[tracing::instrument(skip(self, calendar), fields(job_id = %key.job_id), err)]+ async fn upsert_google_calendar(+ &self,+ key: CalendarBackfillJobKey,+ lease_token: Uuid,+ account_id: Uuid,+ calendar: ProviderCalendar,+ ) -> Result<StoredGoogleCalendar, Report> {+ let mut tx = self.pool.begin().await.map_err(report)?;+ fence_google_mutation_tx(&mut tx, key, lease_token, Some(account_id)).await?;+ let calendar = upsert_calendar_tx(&mut tx, account_id, calendar).await?;+ tx.commit().await.map_err(report)?;+ stored_google_calendar(calendar)+ }++ #[tracing::instrument(skip(self, sync), fields(job_id = %key.job_id), err)]+ async fn commit_google_calendar_sync(+ &self,+ key: CalendarBackfillJobKey,+ lease_token: Uuid,+ account_id: Uuid,+ sync: GoogleCalendarSyncSnapshot,+ ) -> Result<(), Report> {+ let mut tx = self.pool.begin().await.map_err(report)?;+ fence_google_mutation_tx(&mut tx, key, lease_token, Some(account_id)).await?;++ if !sync.cancelled_provider_event_ids.is_empty() {+ // A cancelled recurring master retires its expanded instances via+ // provider_recurring_event_id, matching Google's tombstone shape.+ let affected_event_ids = sqlx::query_scalar!(+ r#"+ WITH deleted_sources AS (+ DELETE FROM calendar_event_sources source+ WHERE source.source_kind = 'google'+ AND source.account_id = $1+ AND source.calendar_id = $2+ AND (+ source.provider_event_id = ANY($3::text[])+ OR source.provider_recurring_event_id = ANY($3::text[])+ )+ RETURNING source.event_id+ )+ SELECT DISTINCT event_id AS "event_id!"+ FROM deleted_sources+ "#,+ account_id,+ sync.calendar_id,+ &sync.cancelled_provider_event_ids,+ )+ .fetch_all(&mut *tx)+ .await+ .map_err(report)?;+ for event_id in affected_event_ids {+ restore_best_source_or_delete(&mut tx, event_id).await?;+ }+ }++ if let Some(observed_provider_event_ids) = &sync.observed_provider_event_ids {+ let affected_event_ids = sqlx::query_scalar!(+ r#"+ WITH deleted_sources AS (+ DELETE FROM calendar_event_sources source+ WHERE source.source_kind = 'google'+ AND source.account_id = $1+ AND source.calendar_id = $2+ AND NOT (source.provider_event_id = ANY($3::text[]))+ RETURNING source.event_id+ )+ SELECT DISTINCT event_id AS "event_id!"+ FROM deleted_sources+ "#,+ account_id,+ sync.calendar_id,+ observed_provider_event_ids,+ )+ .fetch_all(&mut *tx)+ .await+ .map_err(report)?;+ for event_id in affected_event_ids {+ restore_best_source_or_delete(&mut tx, event_id).await?;+ }+ }++ let has_materialized_range = sync.materialized_range.is_some();+ let materialized_starts_at = sync+ .materialized_range+ .as_ref()+ .map(|range| range.starts_at);+ let materialized_ends_at = sync.materialized_range.as_ref().map(|range| range.ends_at);+ let materialized_start_date = sync+ .materialized_range+ .as_ref()+ .map(|range| range.start_date);+ let materialized_end_date = sync.materialized_range.as_ref().map(|range| range.end_date);+ let updated = sqlx::query!(+ r#"+ UPDATE calendars+ SET sync_token = $3,+ materialized_starts_at = CASE+ WHEN $4 THEN $5+ ELSE materialized_starts_at+ END,+ materialized_ends_at = CASE+ WHEN $4 THEN $6+ ELSE materialized_ends_at+ END,+ materialized_start_date = CASE+ WHEN $4 THEN $7+ ELSE materialized_start_date+ END,+ materialized_end_date = CASE+ WHEN $4 THEN $8+ ELSE materialized_end_date+ END,+ updated_at = now()+ WHERE id = $1+ AND account_id = $2+ AND NOT is_deleted+ "#,+ sync.calendar_id,+ account_id,+ sync.next_sync_token,+ has_materialized_range,+ materialized_starts_at,+ materialized_ends_at,+ materialized_start_date,+ materialized_end_date,+ )+ .execute(&mut *tx)+ .await+ .map_err(report)?;+ if updated.rows_affected() != 1 {+ return Err(rootcause::report!(+ "provider calendar disappeared before sync state was committed"+ ));+ }++ tx.commit().await.map_err(report)+ }++ #[tracing::instrument(skip(self, calendar_ids), fields(job_id = %key.job_id), err)]+ async fn reconcile_google_calendar_list(+ &self,+ key: CalendarBackfillJobKey,+ lease_token: Uuid,+ account_id: Uuid,+ calendar_ids: Vec<Uuid>,+ ) -> Result<(), Report> {+ let mut tx = self.pool.begin().await.map_err(report)?;+ fence_google_mutation_tx(&mut tx, key, lease_token, Some(account_id)).await?;++ let affected_event_ids = sqlx::query_scalar!(+ r#"+ WITH deleted_sources AS (+ DELETE FROM calendar_event_sources source+ WHERE source.source_kind = 'google'+ AND source.account_id = $1+ AND (+ source.calendar_id IS NULL+ OR NOT (source.calendar_id = ANY($2::uuid[]))+ )+ RETURNING source.event_id+ )+ SELECT DISTINCT event_id AS "event_id!"+ FROM deleted_sources+ "#,+ account_id,+ &calendar_ids,+ )+ .fetch_all(&mut *tx)+ .await+ .map_err(report)?;+ for event_id in affected_event_ids {+ restore_best_source_or_delete(&mut tx, event_id).await?;+ }++ sqlx::query!(+ r#"+ UPDATE calendars+ SET is_deleted = NOT (id = ANY($2::uuid[])),+ sync_token = CASE+ WHEN id = ANY($2::uuid[]) THEN sync_token+ ELSE NULL+ END,+ materialized_starts_at = CASE+ WHEN id = ANY($2::uuid[]) THEN materialized_starts_at+ ELSE NULL+ END,+ materialized_ends_at = CASE+ WHEN id = ANY($2::uuid[]) THEN materialized_ends_at+ ELSE NULL+ END,+ materialized_start_date = CASE+ WHEN id = ANY($2::uuid[]) THEN materialized_start_date+ ELSE NULL+ END,+ materialized_end_date = CASE+ WHEN id = ANY($2::uuid[]) THEN materialized_end_date+ ELSE NULL+ END,+ updated_at = now()+ WHERE account_id = $1+ AND is_deleted IS DISTINCT FROM NOT (id = ANY($2::uuid[]))+ "#,+ account_id,+ &calendar_ids,+ )+ .execute(&mut *tx)+ .await+ .map_err(report)?;++ tx.commit().await.map_err(report)+ }+}++impl GoogleCalendarSyncRepository for PgCalendarRepository {+ #[tracing::instrument(skip(self), err)]+ async fn schedule_due_google_syncs(&self, due_before: DateTime<Utc>) -> Result<usize, Report> {+ let required_scopes = GOOGLE_CALENDAR_SCOPES.map(str::to_owned);+ let due_count = sqlx::query_scalar!(+ r#"+ WITH due AS (+ UPDATE calendar_backfill_jobs job+ SET status = 'pending',+ cursor = '{}',+ scanned_count = 0,+ extracted_count = 0,+ last_error = NULL,+ started_at = NULL,+ completed_at = NULL,+ lease_token = NULL,+ lease_expires_at = NULL,+ updated_at = now()+ FROM calendar_accounts account, email_links link+ WHERE job.email_link_id = account.email_link_id+ AND job.account_id = account.id+ AND link.id = job.email_link_id+ AND job.kind = 'google_calendar'+ AND job.status = 'complete'+ AND job.grant_version = link.google_grant_version+ AND link.google_granted_scopes @> $2::text[]+ AND account.sync_status = 'ready'+ AND account.last_synced_at <= $1+ RETURNING job.id+ ),+ republished AS (+ UPDATE calendar_sync_outbox outbox+ SET published_at = NULL+ FROM due+ WHERE outbox.backfill_job_id = due.id+ )+ SELECT count(*) AS "due_count!" FROM due+ "#,+ due_before,+ &required_scopes,+ )+ .fetch_one(&self.pool)+ .await+ .map_err(report)?;+ Ok(due_count as usize)+ }+}++async fn fence_google_mutation_tx(+ tx: &mut Transaction<'_, Postgres>,+ key: CalendarBackfillJobKey,+ lease_token: Uuid,+ account_id: Option<Uuid>,+) -> Result<(), Report> {+ let required_scopes = GOOGLE_CALENDAR_SCOPES.map(str::to_owned);+ let fenced_job = sqlx::query_scalar!(+ r#"+ SELECT job.id+ FROM calendar_backfill_jobs job+ WHERE job.id = $1+ AND job.email_link_id = $2+ AND job.kind = 'google_calendar'+ AND job.status = 'running'+ AND job.lease_token = $3+ AND job.lease_expires_at > now()+ AND EXISTS (+ SELECT 1+ FROM email_links link+ WHERE link.id = job.email_link_id+ AND link.google_grant_version = job.grant_version+ AND link.google_granted_scopes @> $5::text[]+ )+ AND EXISTS (+ SELECT 1+ FROM calendar_accounts account+ WHERE account.id = job.account_id+ AND account.email_link_id = job.email_link_id+ AND account.sync_status <> 'disabled'+ AND ($4::uuid IS NULL OR account.id = $4)+ )+ FOR UPDATE OF job+ "#,+ key.job_id,+ key.email_link_id,+ lease_token,+ account_id,+ &required_scopes,+ )+ .fetch_optional(&mut **tx)+ .await+ .map_err(report)?;+ if fenced_job.is_none() {+ return Err(rootcause::report!(+ "Google Calendar backfill lease was lost before provider mutation"+ ));+ }+ Ok(())+}++async fn upsert_calendar_tx(+ tx: &mut Transaction<'_, Postgres>,+ account_id: Uuid,+ calendar: ProviderCalendar,+) -> Result<StoredCalendarRow, Report> {+ sqlx::query_as!(+ StoredCalendarRow,+ r#"+ INSERT INTO calendars (+ id, account_id, provider_calendar_id, name, description,+ time_zone, color, access_role, is_primary, is_selected+ )+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)+ ON CONFLICT (account_id, provider_calendar_id) DO UPDATE SET+ name = EXCLUDED.name,+ description = EXCLUDED.description,+ time_zone = EXCLUDED.time_zone,+ color = EXCLUDED.color,+ access_role = EXCLUDED.access_role,+ is_primary = EXCLUDED.is_primary,+ is_selected = EXCLUDED.is_selected,+ is_deleted = false,+ updated_at = now()+ RETURNING+ id,+ sync_token,+ materialized_starts_at,+ materialized_ends_at,+ materialized_start_date,+ materialized_end_date+ "#,+ Uuid::now_v7(),+ account_id,+ calendar.provider_calendar_id,+ calendar.name,+ calendar.description,+ calendar.time_zone,+ calendar.color,+ calendar.access_role,+ calendar.is_primary,+ calendar.is_selected,+ )+ .fetch_one(&mut **tx)+ .await+ .map_err(report)+}++fn stored_google_calendar(row: StoredCalendarRow) -> Result<StoredGoogleCalendar, Report> {+ let materialized_range = match (+ row.materialized_starts_at,+ row.materialized_ends_at,+ row.materialized_start_date,+ row.materialized_end_date,+ ) {+ (Some(starts_at), Some(ends_at), Some(start_date), Some(end_date)) => {+ Some(OccurrenceRange {+ starts_at,+ ends_at,+ start_date,+ end_date,+ })+ }+ (None, None, None, None) => None,+ _ => {+ return Err(rootcause::report!(+ "provider calendar has a partially persisted materialized range"+ ));+ }+ };+ Ok(StoredGoogleCalendar {+ id: row.id,+ sync_token: row.sync_token,+ materialized_range,+ })+}++impl CalendarBackfillRepository for PgCalendarRepository {+ #[tracing::instrument(skip(self, message), err)]+ async fn fail_unclaimed_google_backfill(+ &self,+ key: CalendarBackfillJobKey,+ disposition: CalendarBackfillFailureDisposition,+ message: &str,+ ) -> Result<CalendarBackfillFailureOutcome, Report> {+ self.persist_google_backfill_failure(key, None, disposition, message)+ .await+ }++ #[tracing::instrument(skip(self), err)]+ async fn claim_google_backfill(+ &self,+ key: CalendarBackfillJobKey,+ ) -> Result<CalendarBackfillClaim, Report> {+ let lease_token = Uuid::now_v7();+ let required_scopes = GOOGLE_CALENDAR_SCOPES.map(str::to_owned);+ let mut tx = self.pool.begin().await.map_err(report)?;+ let claimed_account_id = sqlx::query_scalar!(+ r#"+ UPDATE calendar_backfill_jobs+ SET status = 'running',+ started_at = COALESCE(started_at, now()),+ lease_token = $3,+ lease_expires_at = now() + interval '2 minutes',+ last_error = NULL,+ updated_at = now()+ WHERE id = $1+ AND email_link_id = $2+ AND kind = 'google_calendar'+ AND EXISTS (+ SELECT 1+ FROM email_links link+ WHERE link.id = calendar_backfill_jobs.email_link_id+ AND link.google_grant_version = calendar_backfill_jobs.grant_version+ AND link.google_granted_scopes @> $4::text[]+ )+ AND EXISTS (+ SELECT 1+ FROM calendar_accounts account+ WHERE account.id = calendar_backfill_jobs.account_id+ AND account.email_link_id = calendar_backfill_jobs.email_link_id+ AND account.sync_status <> 'disabled'+ )+ AND (+ status = 'pending'+ OR (+ status = 'running'+ AND lease_expires_at < now()+ )+ )+ RETURNING account_id+ "#,+ key.job_id,+ key.email_link_id,+ lease_token,+ &required_scopes,+ )+ .fetch_optional(&mut *tx)+ .await+ .map_err(report)?;+ if let Some(account_id) = claimed_account_id {+ let Some(account_id) = account_id else {+ tx.rollback().await.map_err(report)?;+ return Err(rootcause::report!(+ "Google Calendar backfill job has no calendar account"+ ));+ };+ tx.commit().await.map_err(report)?;+ return Ok(CalendarBackfillClaim::Claimed {+ lease_token,+ account_id,+ });+ }++ let state = sqlx::query!(+ r#"+ SELECT status, account_id+ FROM calendar_backfill_jobs+ WHERE id = $1+ AND email_link_id = $2+ AND kind = 'google_calendar'+ "#,+ key.job_id,+ key.email_link_id,+ )+ .fetch_optional(&mut *tx)+ .await+ .map_err(report)?;+ if state+ .as_ref()+ .is_some_and(|state| state.account_id.is_none())+ {+ tx.rollback().await.map_err(report)?;+ return Err(rootcause::report!(+ "Google Calendar backfill job has no calendar account"+ ));+ }+ let claim = match state.as_ref().map(|state| state.status.as_str()) {+ Some("complete") => CalendarBackfillClaim::Complete,+ Some("running" | "pending") => CalendarBackfillClaim::Busy,+ Some("failed") => CalendarBackfillClaim::Failed,+ _ => CalendarBackfillClaim::NotFound,+ };+ tx.commit().await.map_err(report)?;+ Ok(claim)+ }++ #[tracing::instrument(skip(self), err)]+ async fn mark_google_account_syncing(+ &self,+ key: CalendarBackfillJobKey,+ lease_token: Uuid,+ ) -> Result<(), Report> {+ let mut tx = self.pool.begin().await.map_err(report)?;+ fence_google_mutation_tx(&mut tx, key, lease_token, None).await?;+ sqlx::query!(+ r#"+ UPDATE calendar_accounts+ SET sync_status = 'syncing',+ last_sync_error = NULL,+ updated_at = now()+ WHERE email_link_id = $1+ "#,+ key.email_link_id,+ )+ .execute(&mut *tx)+ .await+ .map_err(report)?;+ tx.commit().await.map_err(report)+ }++ #[tracing::instrument(skip(self), err)]+ async fn maintain_google_backfill_lease(+ &self,+ key: CalendarBackfillJobKey,+ lease_token: Uuid,+ ) -> Result<(), Report> {+ let required_scopes = GOOGLE_CALENDAR_SCOPES.map(str::to_owned);+ loop {+ tokio::time::sleep(std::time::Duration::from_secs(30)).await;+ let updated = sqlx::query!(+ r#"+ UPDATE calendar_backfill_jobs+ SET lease_expires_at = now() + interval '2 minutes',+ updated_at = now()+ WHERE id = $1+ AND email_link_id = $2+ AND status = 'running'+ AND lease_token = $3+ AND lease_expires_at > now()+ AND EXISTS (+ SELECT 1+ FROM email_links link+ WHERE link.id = calendar_backfill_jobs.email_link_id+ AND link.google_grant_version = calendar_backfill_jobs.grant_version+ AND link.google_granted_scopes @> $4::text[]+ )+ "#,+ key.job_id,+ key.email_link_id,+ lease_token,+ &required_scopes,+ )+ .execute(&self.pool)+ .await+ .map_err(report)?;+ if updated.rows_affected() != 1 {+ return Err(rootcause::report!(+ "Google Calendar backfill lease was lost"+ ));+ }+ }+ }++ #[tracing::instrument(skip(self), err)]+ async fn complete_google_backfill(+ &self,+ key: CalendarBackfillJobKey,+ lease_token: Uuid,+ extracted_count: usize,+ ) -> Result<(), Report> {+ let required_scopes = GOOGLE_CALENDAR_SCOPES.map(str::to_owned);+ let mut tx = self.pool.begin().await.map_err(report)?;+ let completed = sqlx::query!(+ r#"+ UPDATE calendar_backfill_jobs+ SET status = 'complete',+ extracted_count = $2,+ completed_at = now(),+ lease_token = NULL,+ lease_expires_at = NULL,+ updated_at = now()+ WHERE id = $1+ AND email_link_id = $3+ AND kind = 'google_calendar'+ AND status = 'running'+ AND lease_token = $4+ AND lease_expires_at > now()+ AND EXISTS (+ SELECT 1+ FROM email_links link+ WHERE link.id = calendar_backfill_jobs.email_link_id+ AND link.google_grant_version = calendar_backfill_jobs.grant_version+ AND link.google_granted_scopes @> $5::text[]+ )+ "#,+ key.job_id,+ i64::try_from(extracted_count).map_err(|_| {+ rootcause::report!(+ "calendar backfill extracted count overflows the database representation"+ )+ })?,+ key.email_link_id,+ lease_token,+ &required_scopes,+ )+ .execute(&mut *tx)+ .await+ .map_err(report)?;+ if completed.rows_affected() != 1 {+ return Err(rootcause::report!(+ "Google Calendar backfill lease was lost"+ ));+ }+ sqlx::query!(+ r#"+ UPDATE calendar_accounts+ SET sync_status = 'ready',+ last_synced_at = now(),+ last_sync_error = NULL,+ updated_at = now()+ WHERE email_link_id = $1+ "#,+ key.email_link_id,+ )+ .execute(&mut *tx)+ .await+ .map_err(report)?;+ tx.commit().await.map_err(report)?;+ Ok(())+ }++ #[tracing::instrument(skip(self, message), err)]+ async fn fail_google_backfill(+ &self,+ key: CalendarBackfillJobKey,+ lease_token: Uuid,+ disposition: CalendarBackfillFailureDisposition,+ message: &str,+ ) -> Result<CalendarBackfillFailureOutcome, Report> {+ self.persist_google_backfill_failure(key, Some(lease_token), disposition, message)+ .await+ }+}++async fn invalidate_stale_google_jobs_tx(+ tx: &mut Transaction<'_, Postgres>,+ email_link_id: Uuid,+ current_grant_version: i64,+) -> Result<(), Report> {+ sqlx::query!(+ r#"+ WITH invalidated AS (+ UPDATE calendar_backfill_jobs+ SET status = 'failed',+ completed_at = now(),+ lease_token = NULL,+ lease_expires_at = NULL,+ last_error = 'superseded by a newer Google grant',+ updated_at = now()+ WHERE email_link_id = $1+ AND kind = 'google_calendar'+ AND grant_version <> $2+ AND status IN ('pending', 'running')+ RETURNING id+ )+ UPDATE calendar_sync_outbox outbox+ SET published_at = COALESCE(outbox.published_at, now())+ FROM invalidated+ WHERE outbox.backfill_job_id = invalidated.id+ "#,+ email_link_id,+ current_grant_version,+ )+ .execute(&mut **tx)+ .await+ .map_err(report)?;+ Ok(())+}++async fn disable_google_calendar_capability_tx(+ tx: &mut Transaction<'_, Postgres>,+ email_link_id: Uuid,+) -> Result<(), Report> {+ let account_id = sqlx::query_scalar!(+ r#"+ UPDATE calendar_accounts+ SET sync_status = 'disabled',+ last_sync_error = 'Google Calendar permission is no longer granted',+ updated_at = now()+ WHERE email_link_id = $1+ RETURNING id+ "#,+ email_link_id,+ )+ .fetch_optional(&mut **tx)+ .await+ .map_err(report)?;+ let Some(account_id) = account_id else {+ return Ok(());+ };++ sqlx::query!(+ r#"+ UPDATE calendars+ SET is_deleted = true,+ sync_token = NULL,+ materialized_starts_at = NULL,+ materialized_ends_at = NULL,+ materialized_start_date = NULL,+ materialized_end_date = NULL,+ updated_at = now()+ WHERE account_id = $1+ "#,+ account_id,+ )+ .execute(&mut **tx)+ .await+ .map_err(report)?;++ let affected_event_ids = sqlx::query_scalar!(+ r#"+ WITH deleted_sources AS (+ DELETE FROM calendar_event_sources+ WHERE source_kind = 'google'+ AND account_id = $1+ RETURNING event_id+ )+ SELECT DISTINCT event_id AS "event_id!"+ FROM deleted_sources+ "#,+ account_id,+ )+ .fetch_all(&mut **tx)+ .await+ .map_err(report)?;+ for event_id in affected_event_ids {+ restore_best_source_or_delete(tx, event_id).await?;+ }+ Ok(())+}++async fn upsert_google_account_tx(+ tx: &mut Transaction<'_, Postgres>,+ email_link_id: Uuid,+ owner_id: &str,+ email_address: &str,+) -> Result<Uuid, Report> {+ sqlx::query_scalar!(+ r#"+ INSERT INTO calendar_accounts (+ id, owner_id, email_link_id, provider, provider_account_id+ )+ VALUES ($1, $2, $3, 'google', $4)+ ON CONFLICT (email_link_id) DO UPDATE SET+ owner_id = EXCLUDED.owner_id,+ provider_account_id = EXCLUDED.provider_account_id,+ sync_status = CASE+ WHEN calendar_accounts.sync_status = 'disabled' THEN 'pending'+ ELSE calendar_accounts.sync_status+ END,+ last_sync_error = CASE+ WHEN calendar_accounts.sync_status = 'disabled' THEN NULL+ ELSE calendar_accounts.last_sync_error+ END,+ updated_at = now()+ RETURNING id+ "#,+ Uuid::now_v7(),+ owner_id,+ email_link_id,+ email_address,+ )+ .fetch_one(&mut **tx)+ .await+ .map_err(report)+}++async fn retry_failed_backfills_tx(+ tx: &mut Transaction<'_, Postgres>,+ email_link_id: Uuid,+ grant_version: i64,+) -> Result<Vec<CalendarBackfillJob>, Report> {+ struct FailedJobRow {+ id: Uuid,+ account_id: Option<Uuid>,+ kind: String,+ }++ let failed = sqlx::query_as!(+ FailedJobRow,+ r#"+ UPDATE calendar_backfill_jobs+ SET status = 'pending',+ cursor = '{}',+ scanned_count = 0,+ extracted_count = 0,+ last_error = NULL,+ started_at = NULL,+ completed_at = NULL,+ lease_expires_at = NULL,+ updated_at = now()+ WHERE email_link_id = $1+ AND grant_version = $2+ AND status = 'failed'+ RETURNING id, account_id, kind+ "#,+ email_link_id,+ grant_version,+ )+ .fetch_all(&mut **tx)+ .await+ .map_err(report)?;++ let mut jobs = Vec::with_capacity(failed.len());+ for row in failed {+ sqlx::query!(+ r#"+ UPDATE calendar_sync_outbox+ SET published_at = NULL+ WHERE backfill_job_id = $1+ "#,+ row.id,+ )+ .execute(&mut **tx)+ .await+ .map_err(report)?;++ let kind = match row.kind.as_str() {+ "google_calendar" => CalendarBackfillKind::GoogleCalendar,+ "email_ics" => CalendarBackfillKind::EmailIcs,+ _ => return Err(rootcause::report!("invalid calendar backfill kind")),+ };+ jobs.push(CalendarBackfillJob {+ id: row.id,+ email_link_id,+ account_id: row.account_id,+ kind,+ grant_version,+ });+ }+ Ok(jobs)+}++async fn persist_source(+ tx: &mut Transaction<'_, Postgres>,+ event_id: Uuid,+ upsert: &CalendarEventUpsert,+) -> Result<(), Report> {+ let normalized_payload =+ serde_json::to_value(StoredSourceProjection::from(upsert)).map_err(report)?;+ let source = &upsert.source;+ match source {+ CalendarEventSource::Google(source) => {+ sqlx::query!(+ r#"+ INSERT INTO calendar_event_sources (+ id, event_id, source_link_id, source_kind, account_id, calendar_id,+ provider_event_id, provider_recurring_event_id,+ provider_etag, raw_payload, source_sequence,+ source_updated_at, normalized_payload+ )+ VALUES (+ $1, $2, $3, 'google', $4, $5, $6, $7, $8, $9,+ $10, $11, $12+ )+ ON CONFLICT (account_id, calendar_id, provider_event_id)+ WHERE source_kind = 'google'+ DO UPDATE SET+ event_id = EXCLUDED.event_id,+ provider_recurring_event_id = EXCLUDED.provider_recurring_event_id,+ provider_etag = EXCLUDED.provider_etag,+ raw_payload = EXCLUDED.raw_payload,+ source_sequence = EXCLUDED.source_sequence,+ source_updated_at = EXCLUDED.source_updated_at,+ normalized_payload = EXCLUDED.normalized_payload,+ last_seen_at = now()+ WHERE+ EXCLUDED.source_sequence > calendar_event_sources.source_sequence+ OR (+ EXCLUDED.source_sequence = calendar_event_sources.source_sequence+ AND EXCLUDED.source_updated_at >= calendar_event_sources.source_updated_at+ )+ "#,+ Uuid::now_v7(),+ event_id,+ source.email_link_id,+ source.account_id,+ source.calendar_id,+ &source.provider_event_id,+ source.provider_recurring_event_id.as_deref(),+ source.provider_etag.as_deref(),+ &source.raw_payload,+ db_sequence(upsert.event.sequence)?,+ upsert.event.updated_at,+ &normalized_payload,+ )+ .execute(&mut **tx)+ .await+ .map_err(report)?;+ }+ CalendarEventSource::EmailIcs(source) => {+ sqlx::query!(+ r#"+ INSERT INTO calendar_event_sources (+ id, event_id, source_link_id, source_kind, email_link_id, email_thread_id,+ email_message_id, email_attachment_id, content_hash,+ raw_payload, source_sequence, source_updated_at, normalized_payload+ )+ VALUES (+ $1, $2, $3, 'email_ics', $3, $4, $5, $6, $7, $8,+ $9, $10, $11+ )+ ON CONFLICT (+ email_link_id,+ email_message_id,+ COALESCE(email_attachment_id, ''),+ content_hash,+ event_id+ ) WHERE source_kind = 'email_ics'+ DO UPDATE SET+ raw_payload = EXCLUDED.raw_payload,+ source_sequence = EXCLUDED.source_sequence,+ source_updated_at = EXCLUDED.source_updated_at,+ normalized_payload = EXCLUDED.normalized_payload,+ last_seen_at = now()+ WHERE+ EXCLUDED.source_sequence > calendar_event_sources.source_sequence+ OR (+ EXCLUDED.source_sequence = calendar_event_sources.source_sequence+ AND EXCLUDED.source_updated_at >= calendar_event_sources.source_updated_at+ )+ "#,+ Uuid::now_v7(),+ event_id,+ source.email_link_id,+ source.email_thread_id,+ source.email_message_id,+ source.email_attachment_id.as_deref(),+ &source.content_hash,+ &source.raw_payload,+ db_sequence(upsert.event.sequence)?,+ upsert.event.updated_at,+ &normalized_payload,+ )+ .execute(&mut **tx)+ .await+ .map_err(report)?;+ }+ }+ Ok(())+}++async fn restore_best_source_or_delete(+ tx: &mut Transaction<'_, Postgres>,+ event_id: Uuid,+) -> Result<(), Report> {+ let identity = sqlx::query!(+ r#"+ SELECT source_link_id, ical_uid+ FROM calendar_events+ WHERE id = $1+ "#,+ event_id,+ )+ .fetch_optional(&mut **tx)+ .await+ .map_err(report)?;+ let Some(identity) = identity else {+ return Ok(());+ };+ let reconciliation_lock =+ event_reconciliation_lock(identity.source_link_id, &identity.ical_uid);+ sqlx::query_scalar!(+ r#"SELECT 1 AS "locked!" FROM pg_advisory_xact_lock($1)"#,+ reconciliation_lock,+ )+ .fetch_one(&mut **tx)+ .await+ .map_err(report)?;++ let source = sqlx::query!(+ r#"+ SELECT source_kind, source_updated_at, normalized_payload+ FROM calendar_event_sources+ WHERE event_id = $1+ ORDER BY+ CASE source_kind WHEN 'google' THEN 0 ELSE 1 END,+ source_sequence DESC,+ source_updated_at DESC,+ last_seen_at DESC,+ id DESC+ LIMIT 1+ "#,+ event_id,+ )+ .fetch_optional(&mut **tx)+ .await+ .map_err(report)?;+ let Some(source) = source else {+ sqlx::query!("DELETE FROM calendar_events WHERE id = $1", event_id)+ .execute(&mut **tx)+ .await+ .map_err(report)?;+ return Ok(());+ };++ let projection: StoredSourceProjection =+ serde_json::from_value(source.normalized_payload).map_err(report)?;+ let (starts_at, ends_at, start_date, end_date, time_zone) = split_time(&projection.event.time);+ sqlx::query!(+ r#"+ UPDATE calendar_events+ SET title = $2,+ description = $3,+ location = $4,+ status = $5,+ visibility = $6,+ transparency = $7,+ starts_at = $8,+ ends_at = $9,+ start_date = $10,+ end_date = $11,+ time_zone = $12,+ recurrence_lines = $13,+ organizer_email = $14,+ organizer_name = $15,+ conference_url = $16,+ sequence = $17,+ is_read_only = $18,+ canonical_source_kind = $19,+ canonical_source_updated_at = $20,+ created_at = $21,+ updated_at = GREATEST(calendar_events.updated_at, $22)+ WHERE id = $1+ "#,+ event_id,+ &projection.event.title,+ projection.event.description.as_deref(),+ projection.event.location.as_deref(),+ projection.event.status.as_str(),+ projection.event.visibility.as_str(),+ projection.event.transparency.as_str(),+ starts_at,+ ends_at,+ start_date,+ end_date,+ time_zone,+ &projection.event.recurrence_lines,+ projection.event.organizer_email.as_deref(),+ projection.event.organizer_name.as_deref(),+ projection.event.conference_url.as_deref(),+ db_sequence(projection.event.sequence)?,+ projection.event.is_read_only,+ &source.source_kind,+ source.source_updated_at,+ projection.event.created_at,+ projection.event.updated_at,+ )+ .execute(&mut **tx)+ .await+ .map_err(report)?;+ replace_attendees(tx, event_id, &projection.event.attendees).await?;+ replace_overrides(tx, event_id, &projection.overrides).await?;+ replace_occurrences(+ tx,+ event_id,+ &projection.event.owner_id,+ &projection.occurrences,+ )+ .await+}++async fn replace_attendees(+ tx: &mut Transaction<'_, Postgres>,+ event_id: Uuid,+ attendees: &[CalendarAttendee],+) -> Result<(), Report> {+ sqlx::query!(+ "DELETE FROM calendar_event_attendees WHERE event_id = $1",+ event_id+ )+ .execute(&mut **tx)+ .await+ .map_err(report)?;+ for attendee in attendees {+ sqlx::query!(+ r#"+ INSERT INTO calendar_event_attendees (+ event_id, email, display_name, response_status,+ is_organizer, is_optional, is_self, comment+ )+ VALUES ($1, lower($2), $3, $4, $5, $6, $7, $8)+ ON CONFLICT (event_id, email) DO UPDATE SET+ display_name = EXCLUDED.display_name,+ response_status = EXCLUDED.response_status,+ is_organizer = EXCLUDED.is_organizer,+ is_optional = EXCLUDED.is_optional,+ is_self = EXCLUDED.is_self,+ comment = EXCLUDED.comment+ "#,+ event_id,+ &attendee.email,+ attendee.display_name.as_deref(),+ attendee.response_status.as_str(),+ attendee.is_organizer,+ attendee.is_optional,+ attendee.is_self,+ attendee.comment.as_deref(),+ )+ .execute(&mut **tx)+ .await+ .map_err(report)?;+ }+ Ok(())+}++async fn replace_overrides(+ tx: &mut Transaction<'_, Postgres>,+ event_id: Uuid,+ overrides: &[CalendarEventOverride],+) -> Result<(), Report> {+ sqlx::query!(+ "DELETE FROM calendar_event_overrides WHERE event_id = $1",+ event_id+ )+ .execute(&mut **tx)+ .await+ .map_err(report)?;+ for event_override in overrides {+ let (starts_at, ends_at, start_date, end_date, _time_zone) =+ split_time(&event_override.time);+ let (original_starts_at, original_start_date) = match event_override.original_time {+ EventStart::Timed(value) => (Some(value), None),+ EventStart::AllDay(value) => (None, Some(value)),+ };+ sqlx::query!(+ r#"+ INSERT INTO calendar_event_overrides (+ event_id, recurrence_id, original_starts_at, original_start_date,+ starts_at, ends_at, start_date, end_date,+ title, description, location, status+ )+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)+ "#,+ event_id,+ &event_override.recurrence_id,+ original_starts_at,+ original_start_date,+ starts_at,+ ends_at,+ start_date,+ end_date,+ event_override.title.as_deref(),+ event_override.description.as_deref(),+ event_override.location.as_deref(),+ event_override.status.map(EventStatus::as_str),+ )+ .execute(&mut **tx)+ .await+ .map_err(report)?;+ }+ Ok(())+}++async fn replace_occurrences(+ tx: &mut Transaction<'_, Postgres>,+ event_id: Uuid,+ owner_id: &str,+ occurrences: &[CalendarOccurrence],+) -> Result<(), Report> {+ sqlx::query!(+ "DELETE FROM calendar_event_occurrences WHERE event_id = $1",+ event_id+ )+ .execute(&mut **tx)+ .await+ .map_err(report)?;+ for occurrence in occurrences {+ let (starts_at, ends_at, start_date, end_date, _time_zone) = split_time(&occurrence.time);+ sqlx::query!(+ r#"+ INSERT INTO calendar_event_occurrences (+ event_id, owner_id, occurrence_key, recurrence_id,+ starts_at, ends_at, start_date, end_date, is_cancelled+ )+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)+ "#,+ event_id,+ owner_id,+ &occurrence.occurrence_key,+ occurrence.recurrence_id.as_deref(),+ starts_at,+ ends_at,+ start_date,+ end_date,+ occurrence.is_cancelled,+ )+ .execute(&mut **tx)+ .await+ .map_err(report)?;+ }+ Ok(())+}++async fn fetch_attendees(+ pool: &PgPool,+ event_ids: &[Uuid],+) -> Result<HashMap<Uuid, Vec<CalendarAttendee>>, Report> {+ if event_ids.is_empty() {+ return Ok(HashMap::new());+ }+ let rows = sqlx::query_as!(+ AttendeeRow,+ r#"+ SELECT+ event_id, email, display_name, response_status,+ is_organizer, is_optional, is_self, comment+ FROM calendar_event_attendees+ WHERE event_id = ANY($1)+ ORDER BY event_id, email+ "#,+ event_ids,+ )+ .fetch_all(pool)+ .await+ .map_err(report)?;+ let mut by_event = HashMap::new();+ for row in rows {+ by_event+ .entry(row.event_id)+ .or_insert_with(Vec::new)+ .push(CalendarAttendee {+ email: row.email,+ display_name: row.display_name,+ response_status: attendee_status(&row.response_status),+ is_organizer: row.is_organizer,+ is_optional: row.is_optional,+ is_self: row.is_self,+ comment: row.comment,+ });+ }+ Ok(by_event)+}++type SplitTime = (+ Option<DateTime<Utc>>,+ Option<DateTime<Utc>>,+ Option<NaiveDate>,+ Option<NaiveDate>,+ Option<String>,+);++fn split_time(time: &EventTime) -> SplitTime {+ match time {+ EventTime::Timed {+ starts_at,+ ends_at,+ time_zone,+ } => (+ Some(*starts_at),+ Some(*ends_at),+ None,+ None,+ time_zone.clone(),+ ),+ EventTime::AllDay {+ start_date,+ end_date,+ } => (None, None, Some(*start_date), Some(*end_date), None),+ }+}++fn row_time(+ starts_at: Option<DateTime<Utc>>,+ ends_at: Option<DateTime<Utc>>,+ start_date: Option<NaiveDate>,+ end_date: Option<NaiveDate>,+ time_zone: Option<String>,+) -> Result<EventTime, Report> {+ match (starts_at, ends_at, start_date, end_date) {+ (Some(starts_at), Some(ends_at), None, None) => Ok(EventTime::Timed {+ starts_at,+ ends_at,+ time_zone,+ }),+ (None, None, Some(start_date), Some(end_date)) => Ok(EventTime::AllDay {+ start_date,+ end_date,+ }),+ _ => Err(rootcause::report!(+ "invalid calendar time shape in database"+ )),+ }+}++fn event_from_join(+ row: OccurrenceJoinRow,+ attendees: Vec<CalendarAttendee>,+) -> Result<CalendarEvent, Report> {+ Ok(CalendarEvent {+ id: row.event_id,+ owner_id: row.owner_id,+ ical_uid: row.ical_uid,+ title: row.title,+ description: row.description,+ location: row.location,+ status: event_status(&row.status),+ visibility: event_visibility(&row.visibility),+ transparency: event_transparency(&row.transparency),+ time: row_time(+ row.starts_at,+ row.ends_at,+ row.start_date,+ row.end_date,+ row.time_zone,+ )?,+ recurrence_lines: row.recurrence_lines,+ organizer_email: row.organizer_email,+ organizer_name: row.organizer_name,+ conference_url: row.conference_url,+ sequence: u32::try_from(row.sequence).unwrap_or_default(),+ is_read_only: row.is_read_only,+ attendees,+ created_at: row.created_at,+ updated_at: row.updated_at,+ })+}++fn occurrence_from_join(row: &OccurrenceJoinRow) -> Result<CalendarOccurrence, Report> {+ Ok(CalendarOccurrence {+ event_id: row.event_id,+ occurrence_key: row.occurrence_key.clone(),+ recurrence_id: row.recurrence_id.clone(),+ time: row_time(+ row.occurrence_starts_at,+ row.occurrence_ends_at,+ row.occurrence_start_date,+ row.occurrence_end_date,+ None,+ )?,+ is_cancelled: row.is_cancelled,+ })+}++fn event_status(value: &str) -> EventStatus {+ match value {+ "tentative" => EventStatus::Tentative,+ "cancelled" => EventStatus::Cancelled,+ _ => EventStatus::Confirmed,+ }+}++fn event_visibility(value: &str) -> EventVisibility {+ match value {+ "public" => EventVisibility::Public,+ "private" => EventVisibility::Private,+ "confidential" => EventVisibility::Confidential,+ _ => EventVisibility::Default,+ }+}++fn event_transparency(value: &str) -> EventTransparency {+ if value == "transparent" {+ EventTransparency::Transparent+ } else {+ EventTransparency::Opaque+ }+}++fn attendee_status(value: &str) -> AttendeeResponseStatus {+ match value {+ "accepted" => AttendeeResponseStatus::Accepted,+ "declined" => AttendeeResponseStatus::Declined,+ "tentative" => AttendeeResponseStatus::Tentative,+ _ => AttendeeResponseStatus::NeedsAction,+ }+}++fn report(error: impl std::error::Error + Send + Sync + 'static) -> Report {+ rootcause::report!(error).into()+}++fn db_sequence(sequence: u32) -> Result<i32, Report> {+ i32::try_from(sequence).map_err(|_| {+ rootcause::report!(+ "calendar event sequence {sequence} overflows the database representation"+ )+ })+}++fn event_reconciliation_lock(source_link_id: Uuid, ical_uid: &str) -> i64 {+ // Stable FNV-1a produces the same advisory-lock key in every service+ // process. A collision only adds harmless serialization.+ let mut hash = 0xcbf2_9ce4_8422_2325_u64;+ for byte in source_link_id+ .as_bytes()+ .iter()+ .copied()+ .chain(ical_uid.bytes())+ {+ hash ^= u64::from(byte);+ hash = hash.wrapping_mul(0x0000_0100_0000_01b3);+ }+ i64::from_ne_bytes(hash.to_ne_bytes())+}++#[cfg(test)]+mod test;diff --git a/crates/calendar_events/src/outbound/pg/test.rs b/crates/calendar_events/src/outbound/pg/test.rsnew file mode 100644index 0000000000..e2afa8867c--- /dev/null+++ b/crates/calendar_events/src/outbound/pg/test.rs@@ -0,0 +1,1826 @@+use super::*;+use crate::domain::models::{+ EmailIcsSource, GOOGLE_CALENDAR_SCOPES, GoogleCalendarSyncSnapshot, GoogleEventSource,+};+use crate::domain::ports::GoogleCalendarSyncRepository;+use crate::domain::service::GoogleCalendarBackfillFailureService;+use chrono::{Duration, SubsecRound, TimeZone};+use macro_db_migrator::MACRO_DB_MIGRATIONS;++fn complete_grant() -> GoogleScopeSet {+ GoogleScopeSet::parse(&GOOGLE_CALENDAR_SCOPES.join(" "))+}++async fn persist_complete_grant(pool: &PgPool, link_id: Uuid, grant_version: i64) {+ let scopes = GOOGLE_CALENDAR_SCOPES.map(str::to_owned);+ sqlx::query!(+ r#"+ UPDATE email_links+ SET google_granted_scopes = $2,+ google_grant_version = $3+ WHERE id = $1+ "#,+ link_id,+ &scopes,+ grant_version,+ )+ .execute(pool)+ .await+ .unwrap();+}++async fn insert_link(pool: &PgPool, owner_id: &str) -> Uuid {+ let id = Uuid::now_v7();+ let email_address = format!("calendar-{id}@example.com");+ sqlx::query!(+ r#"+ INSERT INTO email_links (+ id, macro_id, fusionauth_user_id, email_address, provider+ )+ VALUES ($1, $2, $2, $3, 'GMAIL')+ "#,+ id,+ owner_id,+ email_address,+ )+ .execute(pool)+ .await+ .unwrap();+ id+}++async fn insert_user(pool: &PgPool, id: &str) {+ let macro_user_id = Uuid::now_v7();+ let stripe_customer_id = format!("cus_{macro_user_id}");+ sqlx::query!(+ r#"+ INSERT INTO macro_user (id, username, email, stripe_customer_id)+ VALUES ($1, $2, $3, $4)+ "#,+ macro_user_id,+ id,+ id,+ stripe_customer_id,+ )+ .execute(pool)+ .await+ .unwrap();+ let email = id.rsplit_once('|').map(|(_, email)| email).unwrap_or(id);+ sqlx::query!(+ r#"+ INSERT INTO "User" (id, email, macro_user_id)+ VALUES ($1, $2, $3)+ "#,+ id,+ email,+ macro_user_id,+ )+ .execute(pool)+ .await+ .unwrap();+}++fn timed_upsert(+ owner_id: &str,+ link_id: Uuid,+ uid: &str,+ title: &str,+ sequence: u32,+) -> CalendarEventUpsert {+ let id = Uuid::now_v7();+ let starts_at = Utc.with_ymd_and_hms(2026, 7, 24, 14, 0, 0).unwrap();+ let ends_at = starts_at + Duration::hours(1);+ let second_start = starts_at + Duration::days(1);+ CalendarEventUpsert {+ event: CalendarEvent {+ id,+ owner_id: owner_id.to_string(),+ ical_uid: uid.to_string(),+ title: title.to_string(),+ description: None,+ location: None,+ status: EventStatus::Confirmed,+ visibility: EventVisibility::Default,+ transparency: EventTransparency::Opaque,+ time: EventTime::Timed {+ starts_at,+ ends_at,+ time_zone: Some("UTC".to_string()),+ },+ recurrence_lines: vec!["RRULE:FREQ=DAILY;COUNT=2".to_string()],+ organizer_email: Some("[email protected]".to_string()),+ organizer_name: Some("Organizer".to_string()),+ conference_url: None,+ sequence,+ is_read_only: true,+ attendees: vec![CalendarAttendee {+ email: "[email protected]".to_string(),+ display_name: Some("Guest".to_string()),+ response_status: AttendeeResponseStatus::Accepted,+ is_organizer: false,+ is_optional: false,+ is_self: false,+ comment: None,+ }],+ created_at: starts_at,+ updated_at: starts_at + Duration::minutes(i64::from(sequence)),+ },+ source: CalendarEventSource::EmailIcs(EmailIcsSource {+ email_link_id: link_id,+ email_thread_id: None,+ email_message_id: Uuid::now_v7(),+ email_attachment_id: Some("invite.ics".to_string()),+ content_hash: format!("hash-{sequence}"),+ raw_payload: serde_json::json!({}),+ }),+ overrides: Vec::new(),+ occurrences: vec![+ CalendarOccurrence {+ event_id: id,+ occurrence_key: starts_at.to_rfc3339(),+ recurrence_id: None,+ time: EventTime::Timed {+ starts_at,+ ends_at,+ time_zone: Some("UTC".to_string()),+ },+ is_cancelled: false,+ },+ CalendarOccurrence {+ event_id: id,+ occurrence_key: second_start.to_rfc3339(),+ recurrence_id: None,+ time: EventTime::Timed {+ starts_at: second_start,+ ends_at: second_start + Duration::hours(1),+ time_zone: Some("UTC".to_string()),+ },+ is_cancelled: false,+ },+ ],+ }+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn calendar_capability_transition_schedules_once_and_failed_jobs_can_retry(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());++ let partial = repo+ .apply_google_grant(+ link_id,+ GoogleScopeSet::parse("https://www.googleapis.com/auth/gmail.modify"),+ )+ .await+ .unwrap();+ assert!(partial.changed);+ assert!(partial.jobs.is_empty());++ let enabled = repo+ .apply_google_grant(link_id, complete_grant())+ .await+ .unwrap();+ assert!(enabled.changed);+ assert_eq!(enabled.jobs.len(), 2);++ let duplicate = repo+ .apply_google_grant(link_id, complete_grant())+ .await+ .unwrap();+ assert!(!duplicate.changed);+ assert!(duplicate.jobs.is_empty());++ let failed_job = enabled.jobs[0].id;+ sqlx::query!(+ "UPDATE calendar_backfill_jobs SET status = 'failed' WHERE id = $1",+ failed_job+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!(+ "UPDATE calendar_sync_outbox SET published_at = now() WHERE backfill_job_id = $1",+ failed_job+ )+ .execute(&pool)+ .await+ .unwrap();++ let retried = repo+ .apply_google_grant(link_id, complete_grant())+ .await+ .unwrap();+ assert!(!retried.changed);+ assert_eq!(retried.jobs.len(), 1);+ assert_eq!(retried.jobs[0].id, failed_job);++ let status = sqlx::query_scalar!(+ "SELECT status FROM calendar_backfill_jobs WHERE id = $1",+ failed_job+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ let published_at = sqlx::query_scalar!(+ "SELECT published_at FROM calendar_sync_outbox WHERE backfill_job_id = $1",+ failed_job+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(status, "pending");+ assert!(published_at.is_none());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn removing_calendar_scope_disables_sources_and_fences_the_running_job(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let enabled = repo+ .apply_google_grant(link_id, complete_grant())+ .await+ .unwrap();+ let google_job = enabled+ .jobs+ .iter()+ .find(|job| job.kind == CalendarBackfillKind::GoogleCalendar)+ .unwrap();+ let email_job = enabled+ .jobs+ .iter()+ .find(|job| job.kind == CalendarBackfillKind::EmailIcs)+ .unwrap();+ let account_id = google_job.account_id.unwrap();+ let key = CalendarBackfillJobKey {+ job_id: google_job.id,+ email_link_id: link_id,+ };+ let CalendarBackfillClaim::Claimed { lease_token, .. } =+ repo.claim_google_backfill(key).await.unwrap()+ else {+ panic!("Google job should be claimable");+ };+ let calendar_id = repo+ .upsert_google_calendar(+ key,+ lease_token,+ account_id,+ ProviderCalendar {+ provider_calendar_id: "primary".to_string(),+ name: "Primary".to_string(),+ description: None,+ time_zone: Some("UTC".to_string()),+ color: None,+ access_role: Some("owner".to_string()),+ is_primary: true,+ is_selected: true,+ },+ )+ .await+ .unwrap()+ .id;+ let mut google = timed_upsert(+ owner_id,+ link_id,+ "[email protected]",+ "Removed with scope",+ 1,+ );+ google.source = CalendarEventSource::Google(GoogleEventSource {+ email_link_id: link_id,+ account_id,+ calendar_id,+ provider_event_id: "provider-event".to_string(),+ provider_recurring_event_id: None,+ provider_etag: None,+ raw_payload: serde_json::json!({}),+ });+ let event_id = repo+ .upsert_event(CalendarEventWrite::GoogleBackfill {+ key,+ lease_token,+ upsert: google,+ })+ .await+ .unwrap();++ let downgraded = repo+ .apply_google_grant(+ link_id,+ GoogleScopeSet::parse("https://www.googleapis.com/auth/gmail.modify"),+ )+ .await+ .unwrap();+ assert!(downgraded.changed);+ assert!(downgraded.jobs.is_empty());++ let state = sqlx::query!(+ r#"+ SELECT+ account.sync_status,+ calendar.is_deleted,+ google_job.status AS google_job_status,+ google_job.lease_token,+ email_job.status AS email_job_status,+ (SELECT count(*) FROM calendar_event_sources WHERE event_id = $4) AS "source_count!",+ (SELECT count(*) FROM calendar_events WHERE id = $4) AS "event_count!"+ FROM calendar_accounts account+ JOIN calendars calendar ON calendar.account_id = account.id+ JOIN calendar_backfill_jobs google_job ON google_job.id = $2+ JOIN calendar_backfill_jobs email_job ON email_job.id = $3+ WHERE account.id = $1+ "#,+ account_id,+ google_job.id,+ email_job.id,+ event_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(state.sync_status, "disabled");+ assert!(state.is_deleted);+ assert_eq!(state.google_job_status, "failed");+ assert!(state.lease_token.is_none());+ assert_eq!(state.email_job_status, "pending");+ assert_eq!(state.source_count, 0);+ assert_eq!(state.event_count, 0);+ assert!(matches!(+ repo.claim_google_backfill(key).await.unwrap(),+ CalendarBackfillClaim::Failed+ ));++ let reenabled = repo+ .apply_google_grant(link_id, complete_grant())+ .await+ .unwrap();+ assert_eq!(reenabled.jobs.len(), 2);+ assert_eq!(+ sqlx::query_scalar!(+ r#"SELECT sync_status FROM calendar_accounts WHERE id = $1"#,+ account_id+ )+ .fetch_one(&pool)+ .await+ .unwrap(),+ "pending"+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn completed_google_job_is_rearmed_and_reuses_calendar_sync_state(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let enabled = repo+ .apply_google_grant(link_id, complete_grant())+ .await+ .unwrap();+ let google_job = enabled+ .jobs+ .into_iter()+ .find(|job| job.kind == CalendarBackfillKind::GoogleCalendar)+ .unwrap();+ let account_id = google_job.account_id.unwrap();+ let key = CalendarBackfillJobKey {+ job_id: google_job.id,+ email_link_id: link_id,+ };+ let CalendarBackfillClaim::Claimed { lease_token, .. } =+ repo.claim_google_backfill(key).await.unwrap()+ else {+ panic!("Google job should be claimable");+ };+ let provider_calendar = ProviderCalendar {+ provider_calendar_id: "primary".to_string(),+ name: "Primary".to_string(),+ description: None,+ time_zone: Some("UTC".to_string()),+ color: None,+ access_role: Some("owner".to_string()),+ is_primary: true,+ is_selected: true,+ };+ let calendar_id = repo+ .upsert_google_calendar(key, lease_token, account_id, provider_calendar.clone())+ .await+ .unwrap()+ .id;+ // Postgres stores timestamptz at microsecond precision, so the+ // round-tripped range only compares equal from a truncated instant.+ let range = OccurrenceRange::historical_sync(Utc::now().trunc_subsecs(6));+ repo.commit_google_calendar_sync(+ key,+ lease_token,+ account_id,+ GoogleCalendarSyncSnapshot {+ calendar_id,+ next_sync_token: "next-sync-token".to_string(),+ observed_provider_event_ids: Some(Vec::new()),+ materialized_range: Some(range.clone()),+ cancelled_provider_event_ids: Vec::new(),+ },+ )+ .await+ .unwrap();+ repo.reconcile_google_calendar_list(key, lease_token, account_id, vec![calendar_id])+ .await+ .unwrap();+ repo.complete_google_backfill(key, lease_token, 0)+ .await+ .unwrap();+ sqlx::query!(+ r#"+ UPDATE calendar_accounts+ SET last_synced_at = now() - interval '10 minutes'+ WHERE id = $1+ "#,+ account_id,+ )+ .execute(&pool)+ .await+ .unwrap();++ assert_eq!(+ repo.schedule_due_google_syncs(Utc::now() - Duration::minutes(5))+ .await+ .unwrap(),+ 1+ );+ assert_eq!(+ repo.schedule_due_google_syncs(Utc::now() - Duration::minutes(5))+ .await+ .unwrap(),+ 0+ );+ let CalendarBackfillClaim::Claimed {+ lease_token: next_lease,+ ..+ } = repo.claim_google_backfill(key).await.unwrap()+ else {+ panic!("scheduled Google job should be claimable");+ };+ let stored = repo+ .upsert_google_calendar(key, next_lease, account_id, provider_calendar)+ .await+ .unwrap();+ assert_eq!(stored.sync_token.as_deref(), Some("next-sync-token"));+ assert_eq!(stored.materialized_range, Some(range));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn google_claim_rejects_a_job_without_its_grant_provisioned_account(pool: PgPool) {+ let link_id = insert_link(&pool, "macro|[email protected]").await;+ let job_id = Uuid::now_v7();+ sqlx::query!(+ r#"+ INSERT INTO calendar_backfill_jobs (+ id, email_link_id, kind, grant_version, status+ )+ VALUES ($1, $2, 'google_calendar', 1, 'pending')+ "#,+ job_id,+ link_id,+ )+ .execute(&pool)+ .await+ .unwrap();++ let result = PgCalendarRepository::new(pool.clone())+ .claim_google_backfill(CalendarBackfillJobKey {+ job_id,+ email_link_id: link_id,+ })+ .await;+ assert!(result.is_err());++ let state = sqlx::query!(+ r#"+ SELECT status, lease_token+ FROM calendar_backfill_jobs+ WHERE id = $1+ "#,+ job_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(state.status, "pending");+ assert!(state.lease_token.is_none());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn google_source_reconciles_email_invite_into_one_canonical_entity(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let email = timed_upsert(+ owner_id,+ link_id,+ "[email protected]",+ "Email title",+ 7,+ );+ let canonical_id = repo.upsert_event_fixture(email.clone()).await.unwrap();++ repo.apply_google_grant(link_id, complete_grant())+ .await+ .unwrap();+ let account_id = repo.upsert_google_account(link_id).await.unwrap();+ let calendar_id = repo+ .upsert_calendar_fixture(+ account_id,+ ProviderCalendar {+ provider_calendar_id: "primary".to_string(),+ name: "Primary".to_string(),+ description: None,+ time_zone: Some("UTC".to_string()),+ color: None,+ access_role: Some("owner".to_string()),+ is_primary: true,+ is_selected: true,+ },+ )+ .await+ .unwrap();++ let mut google = timed_upsert(+ owner_id,+ link_id,+ "[email protected]",+ "Google title",+ 1,+ );+ google.source = CalendarEventSource::Google(GoogleEventSource {+ email_link_id: link_id,+ account_id,+ calendar_id,+ provider_event_id: "google-event".to_string(),+ provider_recurring_event_id: None,+ provider_etag: Some("\"etag\"".to_string()),+ raw_payload: serde_json::json!({}),+ });+ google.event.is_read_only = false;+ let reconciled_id = repo.upsert_event_fixture(google).await.unwrap();++ assert_eq!(reconciled_id, canonical_id);+ let row = sqlx::query!(+ r#"+ SELECT+ (SELECT count(*) FROM calendar_events WHERE owner_id = $1) AS "event_count!",+ (SELECT title FROM calendar_events WHERE id = $2) AS "title!",+ (SELECT count(*) FROM calendar_event_sources WHERE event_id = $2) AS "source_count!"+ "#,+ owner_id,+ canonical_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(+ (row.event_count, row.title, row.source_count),+ (1, "Google title".to_string(), 2)+ );++ let mut later_email = timed_upsert(+ owner_id,+ link_id,+ "[email protected]",+ "Stale email title",+ 99,+ );+ later_email.event.updated_at += Duration::days(1);+ repo.upsert_event_fixture(later_email).await.unwrap();+ let title = sqlx::query_scalar!(+ "SELECT title FROM calendar_events WHERE id = $1",+ canonical_id+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(title, "Google title");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn canonical_precedence_uses_the_selected_source_clock(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let source_clock = Utc.with_ymd_and_hms(2026, 7, 24, 14, 0, 0).unwrap();+ let google_t1 = source_clock + Duration::hours(1);+ let google_t2 = source_clock + Duration::hours(2);+ let email_t3 = source_clock + Duration::hours(3);++ let mut email = timed_upsert(+ owner_id,+ link_id,+ "[email protected]",+ "Email at T3",+ 1,+ );+ email.event.updated_at = email_t3;+ let event_id = repo.upsert_event_fixture(email).await.unwrap();++ repo.apply_google_grant(link_id, complete_grant())+ .await+ .unwrap();+ let account_id = repo.upsert_google_account(link_id).await.unwrap();+ let calendar_id = repo+ .upsert_calendar_fixture(+ account_id,+ ProviderCalendar {+ provider_calendar_id: "primary".to_string(),+ name: "Primary".to_string(),+ description: None,+ time_zone: Some("UTC".to_string()),+ color: None,+ access_role: Some("owner".to_string()),+ is_primary: true,+ is_selected: true,+ },+ )+ .await+ .unwrap();++ let mut first_google = timed_upsert(+ owner_id,+ link_id,+ "[email protected]",+ "Google at T1",+ 1,+ );+ first_google.event.updated_at = google_t1;+ first_google.source = CalendarEventSource::Google(GoogleEventSource {+ email_link_id: link_id,+ account_id,+ calendar_id,+ provider_event_id: "source-clock-google-event".to_string(),+ provider_recurring_event_id: None,+ provider_etag: Some("\"t1\"".to_string()),+ raw_payload: serde_json::json!({}),+ });+ repo.upsert_event_fixture(first_google).await.unwrap();++ let mut second_google = timed_upsert(+ owner_id,+ link_id,+ "[email protected]",+ "Google at T2",+ 1,+ );+ second_google.event.updated_at = google_t2;+ second_google.source = CalendarEventSource::Google(GoogleEventSource {+ email_link_id: link_id,+ account_id,+ calendar_id,+ provider_event_id: "source-clock-google-event".to_string(),+ provider_recurring_event_id: None,+ provider_etag: Some("\"t2\"".to_string()),+ raw_payload: serde_json::json!({}),+ });+ repo.upsert_event_fixture(second_google).await.unwrap();++ let canonical = sqlx::query!(+ r#"+ SELECT title, canonical_source_updated_at, updated_at+ FROM calendar_events+ WHERE id = $1+ "#,+ event_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(canonical.title, "Google at T2");+ assert_eq!(canonical.canonical_source_updated_at, google_t2);+ assert_eq!(canonical.updated_at, email_t3);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn fenced_google_snapshot_removes_deleted_events_and_calendars(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let enabled = repo+ .apply_google_grant(link_id, complete_grant())+ .await+ .unwrap();+ let account_id = repo.upsert_google_account(link_id).await.unwrap();+ let calendar_id = repo+ .upsert_calendar_fixture(+ account_id,+ ProviderCalendar {+ provider_calendar_id: "removed-calendar".to_string(),+ name: "Removed Calendar".to_string(),+ description: None,+ time_zone: Some("UTC".to_string()),+ color: None,+ access_role: Some("owner".to_string()),+ is_primary: false,+ is_selected: true,+ },+ )+ .await+ .unwrap();+ let mut google = timed_upsert(+ owner_id,+ link_id,+ "[email protected]",+ "Deleted Google event",+ 1,+ );+ google.source = CalendarEventSource::Google(GoogleEventSource {+ email_link_id: link_id,+ account_id,+ calendar_id,+ provider_event_id: "deleted-provider-event".to_string(),+ provider_recurring_event_id: None,+ provider_etag: Some("\"old\"".to_string()),+ raw_payload: serde_json::json!({}),+ });+ let event_id = repo.upsert_event_fixture(google).await.unwrap();+ let google_job = enabled+ .jobs+ .into_iter()+ .find(|job| job.kind == CalendarBackfillKind::GoogleCalendar)+ .unwrap();+ let key = CalendarBackfillJobKey {+ job_id: google_job.id,+ email_link_id: link_id,+ };+ let CalendarBackfillClaim::Claimed {+ lease_token,+ account_id: claimed_account_id,+ } = repo.claim_google_backfill(key).await.unwrap()+ else {+ panic!("Google job should be claimable");+ };+ assert_eq!(claimed_account_id, account_id);+ assert!(+ repo.reconcile_google_calendar_list(key, Uuid::new_v4(), account_id, Vec::new())+ .await+ .is_err()+ );+ assert_eq!(+ sqlx::query_scalar!(+ r#"SELECT count(*) AS "count!" FROM calendar_events WHERE id = $1"#,+ event_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap(),+ 1+ );++ repo.reconcile_google_calendar_list(key, lease_token, account_id, Vec::new())+ .await+ .unwrap();+ assert_eq!(+ sqlx::query_scalar!(+ r#"SELECT count(*) AS "count!" FROM calendar_events WHERE id = $1"#,+ event_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap(),+ 0+ );+ assert!(+ sqlx::query_scalar!(+ r#"SELECT is_deleted AS "is_deleted!" FROM calendars WHERE id = $1"#,+ calendar_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap()+ );++ let outside_start = Utc.with_ymd_and_hms(2026, 8, 2, 0, 0, 0).unwrap();+ let outside_end = Utc.with_ymd_and_hms(2026, 8, 3, 0, 0, 0).unwrap();+ let occurrences = repo+ .list_occurrences(+ owner_id,+ OccurrenceRange {+ starts_at: outside_start,+ ends_at: outside_end,+ start_date: outside_start.date_naive(),+ end_date: outside_end.date_naive(),+ },+ None,+ 100,+ )+ .await+ .unwrap();+ assert!(occurrences.is_empty());+ assert_eq!(+ repo.sync_status(owner_id).await.unwrap(),+ CalendarSyncStatus::Syncing+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn expired_google_worker_cannot_resurrect_reconciled_provider_data(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let enabled = repo+ .apply_google_grant(link_id, complete_grant())+ .await+ .unwrap();+ let account_id = repo.upsert_google_account(link_id).await.unwrap();+ let google_job = enabled+ .jobs+ .into_iter()+ .find(|job| job.kind == CalendarBackfillKind::GoogleCalendar)+ .unwrap();+ let key = CalendarBackfillJobKey {+ job_id: google_job.id,+ email_link_id: link_id,+ };+ let CalendarBackfillClaim::Claimed {+ lease_token: stale_lease,+ ..+ } = repo.claim_google_backfill(key).await.unwrap()+ else {+ panic!("Google job should be claimable");+ };+ let provider_calendar = ProviderCalendar {+ provider_calendar_id: "primary".to_string(),+ name: "Primary".to_string(),+ description: None,+ time_zone: Some("UTC".to_string()),+ color: None,+ access_role: Some("owner".to_string()),+ is_primary: true,+ is_selected: true,+ };+ let calendar_id = repo+ .upsert_google_calendar(key, stale_lease, account_id, provider_calendar.clone())+ .await+ .unwrap()+ .id;+ let mut google = timed_upsert(+ owner_id,+ link_id,+ "[email protected]",+ "Stale worker event",+ 1,+ );+ google.source = CalendarEventSource::Google(GoogleEventSource {+ email_link_id: link_id,+ account_id,+ calendar_id,+ provider_event_id: "stale-worker-provider-event".to_string(),+ provider_recurring_event_id: None,+ provider_etag: Some("\"stale\"".to_string()),+ raw_payload: serde_json::json!({}),+ });+ repo.upsert_event(CalendarEventWrite::GoogleBackfill {+ key,+ lease_token: stale_lease,+ upsert: google.clone(),+ })+ .await+ .unwrap();++ sqlx::query!(+ r#"+ UPDATE calendar_backfill_jobs+ SET lease_expires_at = now() - interval '1 second'+ WHERE id = $1+ "#,+ key.job_id,+ )+ .execute(&pool)+ .await+ .unwrap();+ let CalendarBackfillClaim::Claimed {+ lease_token: current_lease,+ ..+ } = repo.claim_google_backfill(key).await.unwrap()+ else {+ panic!("expired Google job should be reclaimable");+ };+ repo.reconcile_google_calendar_list(key, current_lease, account_id, Vec::new())+ .await+ .unwrap();+ repo.complete_google_backfill(key, current_lease, 0)+ .await+ .unwrap();++ assert!(+ repo.mark_google_account_syncing(key, stale_lease)+ .await+ .is_err()+ );+ assert_eq!(+ sqlx::query_scalar!(+ r#"SELECT sync_status FROM calendar_accounts WHERE id = $1"#,+ account_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap(),+ "ready"+ );+ assert!(+ repo.upsert_google_calendar(key, stale_lease, account_id, provider_calendar)+ .await+ .is_err()+ );+ assert!(+ repo.upsert_event(CalendarEventWrite::GoogleBackfill {+ key,+ lease_token: stale_lease,+ upsert: google,+ })+ .await+ .is_err()+ );+ assert!(+ sqlx::query_scalar!(+ r#"SELECT is_deleted AS "is_deleted!" FROM calendars WHERE id = $1"#,+ calendar_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap()+ );+ assert_eq!(+ sqlx::query_scalar!(+ r#"+ SELECT count(*) AS "count!"+ FROM calendar_events+ WHERE owner_id = $1+ AND ical_uid = '[email protected]'+ "#,+ owner_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap(),+ 0+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn google_snapshot_deletion_restores_the_surviving_email_source(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let email = timed_upsert(+ owner_id,+ link_id,+ "[email protected]",+ "Email fallback",+ 1,+ );+ let event_id = repo.upsert_event_fixture(email).await.unwrap();+ let enabled = repo+ .apply_google_grant(link_id, complete_grant())+ .await+ .unwrap();+ let account_id = repo.upsert_google_account(link_id).await.unwrap();+ let calendar_id = repo+ .upsert_calendar_fixture(+ account_id,+ ProviderCalendar {+ provider_calendar_id: "primary".to_string(),+ name: "Primary".to_string(),+ description: None,+ time_zone: Some("UTC".to_string()),+ color: None,+ access_role: Some("owner".to_string()),+ is_primary: true,+ is_selected: true,+ },+ )+ .await+ .unwrap();+ let mut google = timed_upsert(+ owner_id,+ link_id,+ "[email protected]",+ "Google canonical",+ 2,+ );+ google.source = CalendarEventSource::Google(GoogleEventSource {+ email_link_id: link_id,+ account_id,+ calendar_id,+ provider_event_id: "google-fallback-event".to_string(),+ provider_recurring_event_id: None,+ provider_etag: Some("\"etag\"".to_string()),+ raw_payload: serde_json::json!({}),+ });+ repo.upsert_event_fixture(google).await.unwrap();++ let google_job = enabled+ .jobs+ .into_iter()+ .find(|job| job.kind == CalendarBackfillKind::GoogleCalendar)+ .unwrap();+ let key = CalendarBackfillJobKey {+ job_id: google_job.id,+ email_link_id: link_id,+ };+ let CalendarBackfillClaim::Claimed { lease_token, .. } =+ repo.claim_google_backfill(key).await.unwrap()+ else {+ panic!("Google job should be claimable");+ };+ repo.commit_google_calendar_sync(+ key,+ lease_token,+ account_id,+ GoogleCalendarSyncSnapshot {+ calendar_id,+ next_sync_token: "next".to_string(),+ observed_provider_event_ids: Some(Vec::new()),+ materialized_range: Some(OccurrenceRange::historical_sync(Utc::now())),+ cancelled_provider_event_ids: Vec::new(),+ },+ )+ .await+ .unwrap();+ repo.reconcile_google_calendar_list(key, lease_token, account_id, vec![calendar_id])+ .await+ .unwrap();++ let restored = sqlx::query!(+ r#"+ SELECT title, canonical_source_kind,+ (SELECT count(*) FROM calendar_event_sources WHERE event_id = $1) AS "source_count!"+ FROM calendar_events+ WHERE id = $1+ "#,+ event_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(restored.title, "Email fallback");+ assert_eq!(restored.canonical_source_kind, "email_ics");+ assert_eq!(restored.source_count, 1);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn incremental_cancellation_tombstones_retire_sources_without_a_snapshot(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let email = timed_upsert(+ owner_id,+ link_id,+ "[email protected]",+ "Email fallback",+ 1,+ );+ let event_id = repo.upsert_event_fixture(email).await.unwrap();+ let enabled = repo+ .apply_google_grant(link_id, complete_grant())+ .await+ .unwrap();+ let account_id = repo.upsert_google_account(link_id).await.unwrap();+ let calendar_id = repo+ .upsert_calendar_fixture(+ account_id,+ ProviderCalendar {+ provider_calendar_id: "primary".to_string(),+ name: "Primary".to_string(),+ description: None,+ time_zone: Some("UTC".to_string()),+ color: None,+ access_role: Some("owner".to_string()),+ is_primary: true,+ is_selected: true,+ },+ )+ .await+ .unwrap();+ let mut google = timed_upsert(+ owner_id,+ link_id,+ "[email protected]",+ "Google canonical",+ 2,+ );+ google.source = CalendarEventSource::Google(GoogleEventSource {+ email_link_id: link_id,+ account_id,+ calendar_id,+ provider_event_id: "cancelled-event".to_string(),+ provider_recurring_event_id: None,+ provider_etag: Some("\"etag\"".to_string()),+ raw_payload: serde_json::json!({}),+ });+ repo.upsert_event_fixture(google).await.unwrap();+ let mut instance = timed_upsert(+ owner_id,+ link_id,+ "[email protected]",+ "Series instance",+ 1,+ );+ instance.source = CalendarEventSource::Google(GoogleEventSource {+ email_link_id: link_id,+ account_id,+ calendar_id,+ provider_event_id: "series-instance".to_string(),+ provider_recurring_event_id: Some("cancelled-master".to_string()),+ provider_etag: Some("\"etag\"".to_string()),+ raw_payload: serde_json::json!({}),+ });+ let instance_event_id = repo.upsert_event_fixture(instance).await.unwrap();++ let google_job = enabled+ .jobs+ .into_iter()+ .find(|job| job.kind == CalendarBackfillKind::GoogleCalendar)+ .unwrap();+ let key = CalendarBackfillJobKey {+ job_id: google_job.id,+ email_link_id: link_id,+ };+ let CalendarBackfillClaim::Claimed { lease_token, .. } =+ repo.claim_google_backfill(key).await.unwrap()+ else {+ panic!("Google job should be claimable");+ };+ repo.commit_google_calendar_sync(+ key,+ lease_token,+ account_id,+ GoogleCalendarSyncSnapshot {+ calendar_id,+ next_sync_token: "incremental-next".to_string(),+ observed_provider_event_ids: None,+ materialized_range: None,+ cancelled_provider_event_ids: vec![+ "cancelled-event".to_string(),+ "cancelled-master".to_string(),+ ],+ },+ )+ .await+ .unwrap();++ let restored = sqlx::query!(+ r#"+ SELECT title, canonical_source_kind,+ (SELECT count(*) FROM calendar_event_sources WHERE event_id = $1) AS "source_count!"+ FROM calendar_events+ WHERE id = $1+ "#,+ event_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(restored.title, "Email fallback");+ assert_eq!(restored.canonical_source_kind, "email_ics");+ assert_eq!(restored.source_count, 1);++ assert_eq!(+ sqlx::query_scalar!(+ r#"SELECT count(*) AS "count!" FROM calendar_events WHERE id = $1"#,+ instance_event_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap(),+ 0+ );+ assert_eq!(+ sqlx::query_scalar!(+ r#"SELECT sync_token FROM calendars WHERE id = $1"#,+ calendar_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap()+ .as_deref(),+ Some("incremental-next")+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn occurrence_range_uses_overlap_indexes_and_preserves_attendees(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool);+ let upsert = timed_upsert(owner_id, link_id, "[email protected]", "Range test", 1);+ repo.upsert_event_fixture(upsert).await.unwrap();++ let starts_at = Utc.with_ymd_and_hms(2026, 7, 24, 14, 30, 0).unwrap();+ let ends_at = Utc.with_ymd_and_hms(2026, 7, 26, 0, 0, 0).unwrap();+ let result = 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!(result.len(), 2);+ assert!(result.iter().all(|(event, _)| event.attendees.len() == 1));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn occurrence_cursor_is_stable_when_occurrences_share_a_start(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool);+ for ordinal in 1..=3 {+ repo.upsert_event_fixture(timed_upsert(+ owner_id,+ link_id,+ &format!("pagination-{ordinal}@example.com"),+ &format!("Pagination event {ordinal}"),+ ordinal,+ ))+ .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, 25, 0, 0, 0).unwrap();+ let range = OccurrenceRange {+ starts_at,+ ends_at,+ start_date: starts_at.date_naive(),+ end_date: ends_at.date_naive(),+ };+ let first_page = repo+ .list_occurrences(owner_id, range.clone(), None, 2)+ .await+ .unwrap();+ 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();+ assert_eq!(second_page.len(), 1);++ let mut event_ids: Vec<_> = first_page+ .iter()+ .chain(&second_page)+ .map(|(event, _)| event.id)+ .collect();+ event_ids.sort_unstable();+ event_ids.dedup();+ assert_eq!(event_ids.len(), 3);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn sync_status_reflects_visible_account_ingestion_state(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let repo = PgCalendarRepository::new(pool.clone());+ assert_eq!(+ repo.sync_status(owner_id).await.unwrap(),+ CalendarSyncStatus::Ready+ );++ let link_id = insert_link(&pool, owner_id).await;+ repo.apply_google_grant(link_id, complete_grant())+ .await+ .unwrap();+ let account_id = repo.upsert_google_account(link_id).await.unwrap();+ assert_eq!(+ repo.sync_status(owner_id).await.unwrap(),+ CalendarSyncStatus::Syncing+ );++ sqlx::query!(+ "UPDATE calendar_accounts SET sync_status = 'ready' WHERE id = $1",+ account_id,+ )+ .execute(&pool)+ .await+ .unwrap();+ assert_eq!(+ repo.sync_status(owner_id).await.unwrap(),+ CalendarSyncStatus::Ready+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn delegated_inbox_source_grants_calendar_visibility(pool: PgPool) {+ let child_id = "macro|[email protected]";+ let primary_id = "macro|[email protected]";+ insert_user(&pool, child_id).await;+ insert_user(&pool, primary_id).await;+ let link_id = insert_link(&pool, child_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ repo.upsert_event_fixture(timed_upsert(+ child_id,+ link_id,+ "[email protected]",+ "Delegated event",+ 1,+ ))+ .await+ .unwrap();+ sqlx::query!(+ r#"+ INSERT INTO macro_user_links (primary_macro_id, child_macro_id, link_id)+ VALUES ($1, $2, $3)+ "#,+ primary_id,+ child_id,+ link_id,+ )+ .execute(&pool)+ .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 range = OccurrenceRange {+ starts_at,+ ends_at,+ start_date: starts_at.date_naive(),+ end_date: ends_at.date_naive(),+ };+ assert_eq!(+ repo.list_occurrences(primary_id, range.clone(), None, 100)+ .await+ .unwrap()+ .len(),+ 2+ );+ assert!(+ repo.list_occurrences("macro|[email protected]", range, None, 100)+ .await+ .unwrap()+ .is_empty()+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn identical_uids_from_distinct_inboxes_remain_distinct_and_link_scoped(pool: PgPool) {+ let child_id = "macro|[email protected]";+ let primary_id = "macro|[email protected]";+ insert_user(&pool, child_id).await;+ insert_user(&pool, primary_id).await;+ let delegated_link_id = insert_link(&pool, child_id).await;+ let private_link_id = insert_link(&pool, child_id).await;+ let repo = PgCalendarRepository::new(pool.clone());++ repo.upsert_event_fixture(timed_upsert(+ child_id,+ delegated_link_id,+ "[email protected]",+ "Delegated inbox",+ 1,+ ))+ .await+ .unwrap();+ repo.upsert_event_fixture(timed_upsert(+ child_id,+ private_link_id,+ "[email protected]",+ "Private inbox",+ 1,+ ))+ .await+ .unwrap();+ sqlx::query!(+ r#"+ INSERT INTO macro_user_links (primary_macro_id, child_macro_id, link_id)+ VALUES ($1, $2, $3)+ "#,+ primary_id,+ child_id,+ delegated_link_id,+ )+ .execute(&pool)+ .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 result = repo+ .list_occurrences(+ primary_id,+ OccurrenceRange {+ starts_at,+ ends_at,+ start_date: starts_at.date_naive(),+ end_date: ends_at.date_naive(),+ },+ None,+ 100,+ )+ .await+ .unwrap();++ assert_eq!(result.len(), 2);+ assert!(+ result+ .iter()+ .all(|(event, _)| event.title == "Delegated inbox")+ );+ let event_count = sqlx::query_scalar!(+ r#"SELECT count(*) AS "count!" FROM calendar_events WHERE owner_id = $1"#,+ child_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(event_count, 2);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn equal_sequence_cannot_replace_a_newer_projection(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let mut latest = timed_upsert(owner_id, link_id, "[email protected]", "Latest", 4);+ latest.event.updated_at += Duration::days(2);+ let event_id = repo.upsert_event_fixture(latest).await.unwrap();++ let mut stale = timed_upsert(owner_id, link_id, "[email protected]", "Stale", 4);+ stale.event.updated_at -= Duration::days(2);+ repo.upsert_event_fixture(stale).await.unwrap();++ let title = sqlx::query_scalar!("SELECT title FROM calendar_events WHERE id = $1", event_id)+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(title, "Latest");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn stale_google_source_projection_cannot_resurface_during_reconciliation(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let enabled = repo+ .apply_google_grant(link_id, complete_grant())+ .await+ .unwrap();+ let account_id = repo.upsert_google_account(link_id).await.unwrap();+ let primary_calendar_id = repo+ .upsert_calendar_fixture(+ account_id,+ ProviderCalendar {+ provider_calendar_id: "primary".to_string(),+ name: "Primary".to_string(),+ description: None,+ time_zone: Some("UTC".to_string()),+ color: None,+ access_role: Some("owner".to_string()),+ is_primary: true,+ is_selected: true,+ },+ )+ .await+ .unwrap();+ let sibling_calendar_id = repo+ .upsert_calendar_fixture(+ account_id,+ ProviderCalendar {+ provider_calendar_id: "sibling".to_string(),+ name: "Sibling".to_string(),+ description: None,+ time_zone: Some("UTC".to_string()),+ color: None,+ access_role: Some("owner".to_string()),+ is_primary: false,+ is_selected: true,+ },+ )+ .await+ .unwrap();++ let mut latest = timed_upsert(+ owner_id,+ link_id,+ "[email protected]",+ "Latest",+ 4,+ );+ latest.event.updated_at += Duration::days(2);+ latest.source = CalendarEventSource::Google(GoogleEventSource {+ email_link_id: link_id,+ account_id,+ calendar_id: primary_calendar_id,+ provider_event_id: "primary-event".to_string(),+ provider_recurring_event_id: None,+ provider_etag: Some("\"latest\"".to_string()),+ raw_payload: serde_json::json!({}),+ });+ let event_id = repo.upsert_event_fixture(latest).await.unwrap();++ let mut sibling = timed_upsert(+ owner_id,+ link_id,+ "[email protected]",+ "Sibling",+ 1,+ );+ sibling.source = CalendarEventSource::Google(GoogleEventSource {+ email_link_id: link_id,+ account_id,+ calendar_id: sibling_calendar_id,+ provider_event_id: "sibling-event".to_string(),+ provider_recurring_event_id: None,+ provider_etag: Some("\"sibling\"".to_string()),+ raw_payload: serde_json::json!({}),+ });+ repo.upsert_event_fixture(sibling).await.unwrap();++ let mut stale = timed_upsert(+ owner_id,+ link_id,+ "[email protected]",+ "Stale",+ 4,+ );+ stale.event.updated_at -= Duration::days(2);+ stale.source = CalendarEventSource::Google(GoogleEventSource {+ email_link_id: link_id,+ account_id,+ calendar_id: primary_calendar_id,+ provider_event_id: "primary-event".to_string(),+ provider_recurring_event_id: None,+ provider_etag: Some("\"stale\"".to_string()),+ raw_payload: serde_json::json!({}),+ });+ repo.upsert_event_fixture(stale).await.unwrap();++ let google_job = enabled+ .jobs+ .into_iter()+ .find(|job| job.kind == CalendarBackfillKind::GoogleCalendar)+ .unwrap();+ let key = CalendarBackfillJobKey {+ job_id: google_job.id,+ email_link_id: link_id,+ };+ let CalendarBackfillClaim::Claimed { lease_token, .. } =+ repo.claim_google_backfill(key).await.unwrap()+ else {+ panic!("Google job should be claimable");+ };+ repo.commit_google_calendar_sync(+ key,+ lease_token,+ account_id,+ GoogleCalendarSyncSnapshot {+ calendar_id: primary_calendar_id,+ next_sync_token: "primary-next".to_string(),+ observed_provider_event_ids: Some(vec!["primary-event".to_string()]),+ materialized_range: Some(OccurrenceRange::historical_sync(Utc::now())),+ cancelled_provider_event_ids: Vec::new(),+ },+ )+ .await+ .unwrap();+ repo.commit_google_calendar_sync(+ key,+ lease_token,+ account_id,+ GoogleCalendarSyncSnapshot {+ calendar_id: sibling_calendar_id,+ next_sync_token: "sibling-next".to_string(),+ observed_provider_event_ids: Some(Vec::new()),+ materialized_range: Some(OccurrenceRange::historical_sync(Utc::now())),+ cancelled_provider_event_ids: Vec::new(),+ },+ )+ .await+ .unwrap();+ repo.reconcile_google_calendar_list(+ key,+ lease_token,+ account_id,+ vec![primary_calendar_id, sibling_calendar_id],+ )+ .await+ .unwrap();++ let restored = sqlx::query!(+ r#"+ SELECT title,+ (SELECT count(*) FROM calendar_event_sources WHERE event_id = $1) AS "source_count!"+ FROM calendar_events+ WHERE id = $1+ "#,+ event_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(restored.title, "Latest");+ assert_eq!(restored.source_count, 1);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn unclaimed_google_reauth_failure_is_atomic_and_edge_triggered(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ persist_complete_grant(&pool, link_id, 1).await;+ let account_id = Uuid::now_v7();+ let job_id = Uuid::now_v7();+ sqlx::query!(+ r#"+ INSERT INTO calendar_accounts (+ id, owner_id, email_link_id, provider, provider_account_id+ )+ VALUES ($1, $2, $3, 'google', $4)+ "#,+ account_id,+ owner_id,+ link_id,+ "[email protected]",+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!(+ r#"+ INSERT INTO calendar_backfill_jobs (+ id, email_link_id, account_id, kind, grant_version, status+ )+ VALUES ($1, $2, $3, 'google_calendar', 1, 'pending')+ "#,+ job_id,+ link_id,+ account_id,+ )+ .execute(&pool)+ .await+ .unwrap();++ let repo = PgCalendarRepository::new(pool.clone());+ let key = CalendarBackfillJobKey {+ job_id,+ email_link_id: link_id,+ };+ let failure_service = GoogleCalendarBackfillFailureService::new(repo);+ let outcome = failure_service+ .fail_unclaimed(+ key,+ CalendarBackfillFailureDisposition::ReauthRequired,+ "grant expired",+ )+ .await+ .unwrap();+ assert!(outcome.job_transitioned);+ assert!(outcome.link_reauth_transitioned);++ let state = sqlx::query!(+ r#"+ SELECT+ job.status AS job_status,+ account.sync_status AS account_status,+ link.needs_reauth,+ link.last_sync_error_at+ FROM calendar_backfill_jobs job+ JOIN calendar_accounts account ON account.id = job.account_id+ JOIN email_links link ON link.id = job.email_link_id+ WHERE job.id = $1+ "#,+ job_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(state.job_status, "failed");+ assert_eq!(state.account_status, "reauth_required");+ assert!(state.needs_reauth);+ assert!(state.last_sync_error_at.is_some());++ let duplicate = failure_service+ .fail_unclaimed(+ key,+ CalendarBackfillFailureDisposition::ReauthRequired,+ "duplicate",+ )+ .await+ .unwrap();+ assert!(!duplicate.job_transitioned);+ assert!(!duplicate.link_reauth_transitioned);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn calendar_permission_failure_does_not_mark_the_gmail_link_for_reauth(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let enabled = repo+ .apply_google_grant(link_id, complete_grant())+ .await+ .unwrap();+ let job = enabled+ .jobs+ .into_iter()+ .find(|job| job.kind == CalendarBackfillKind::GoogleCalendar)+ .unwrap();+ let outcome = GoogleCalendarBackfillFailureService::new(repo)+ .fail_unclaimed(+ CalendarBackfillJobKey {+ job_id: job.id,+ email_link_id: link_id,+ },+ CalendarBackfillFailureDisposition::CalendarPermissionRequired,+ "calendar consent is missing",+ )+ .await+ .unwrap();++ assert!(outcome.job_transitioned);+ assert!(!outcome.link_reauth_transitioned);+ let state = sqlx::query!(+ r#"+ SELECT account.sync_status, link.needs_reauth+ FROM calendar_accounts account+ JOIN email_links link ON link.id = account.email_link_id+ WHERE account.id = $1+ "#,+ job.account_id.unwrap(),+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(state.sync_status, "reauth_required");+ assert!(!state.needs_reauth);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn unclaimed_permanent_google_failure_marks_account_error(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ persist_complete_grant(&pool, link_id, 1).await;+ let account_id = Uuid::now_v7();+ let job_id = Uuid::now_v7();+ sqlx::query!(+ r#"+ INSERT INTO calendar_accounts (+ id, owner_id, email_link_id, provider, provider_account_id+ )+ VALUES ($1, $2, $3, 'google', $4)+ "#,+ account_id,+ owner_id,+ link_id,+ "[email protected]",+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!(+ r#"+ INSERT INTO calendar_backfill_jobs (+ id, email_link_id, account_id, kind, grant_version, status+ )+ VALUES ($1, $2, $3, 'google_calendar', 1, 'pending')+ "#,+ job_id,+ link_id,+ account_id,+ )+ .execute(&pool)+ .await+ .unwrap();++ let outcome =+ GoogleCalendarBackfillFailureService::new(PgCalendarRepository::new(pool.clone()))+ .fail_unclaimed(+ CalendarBackfillJobKey {+ job_id,+ email_link_id: link_id,+ },+ CalendarBackfillFailureDisposition::Permanent,+ "provider rejected data",+ )+ .await+ .unwrap();+ assert!(outcome.job_transitioned);+ assert!(!outcome.link_reauth_transitioned);++ let account = sqlx::query!(+ "SELECT sync_status, last_sync_error FROM calendar_accounts WHERE id = $1",+ account_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(account.sync_status, "error");+ assert_eq!(+ account.last_sync_error.as_deref(),+ Some("provider rejected data")+ );+}diff --git a/crates/macro_db_client/migrations/20260725014930_calendar_entities.sql b/crates/macro_db_client/migrations/20260725014930_calendar_entities.sqlnew file mode 100644index 0000000000..607bb46ec9--- /dev/null+++ b/crates/macro_db_client/migrations/20260725014930_calendar_entities.sql@@ -0,0 +1,420 @@+-- CalendarEvent is a canonical Macro entity. Provider and email records are+-- sources of that entity; recurring instances are query projections.++CREATE EXTENSION IF NOT EXISTS btree_gist;++ALTER TABLE in_progress_user_link+ ADD COLUMN IF NOT EXISTS requested_google_scopes text[] NOT NULL DEFAULT '{}',+ ADD COLUMN IF NOT EXISTS granted_google_scopes text[] NOT NULL DEFAULT '{}';++ALTER TABLE email_links+ ADD COLUMN IF NOT EXISTS google_granted_scopes text[] NOT NULL DEFAULT '{}',+ ADD COLUMN IF NOT EXISTS google_grant_version bigint NOT NULL DEFAULT 0+ CHECK (google_grant_version >= 0);++CREATE TABLE IF NOT EXISTS calendar_accounts (+ id uuid PRIMARY KEY,+ owner_id text NOT NULL,+ email_link_id uuid NOT NULL UNIQUE+ REFERENCES email_links(id) ON DELETE CASCADE,+ provider text NOT NULL CHECK (provider IN ('google')),+ provider_account_id text NOT NULL,+ sync_status text NOT NULL DEFAULT 'pending'+ CHECK (sync_status IN (+ 'pending', 'syncing', 'ready', 'error', 'reauth_required', 'disabled'+ )),+ last_synced_at timestamptz,+ last_sync_error text,+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now(),+ UNIQUE (owner_id, provider, provider_account_id)+);++CREATE INDEX IF NOT EXISTS calendar_accounts_owner_idx+ ON calendar_accounts (owner_id);++CREATE TABLE IF NOT EXISTS calendars (+ id uuid PRIMARY KEY,+ account_id uuid NOT NULL+ REFERENCES calendar_accounts(id) ON DELETE CASCADE,+ provider_calendar_id text NOT NULL,+ name text NOT NULL,+ description text,+ time_zone text,+ color text,+ access_role text,+ is_primary boolean NOT NULL DEFAULT false,+ is_selected boolean NOT NULL DEFAULT true,+ is_deleted boolean NOT NULL DEFAULT false,+ sync_token text,+ watch_channel_id text,+ watch_resource_id text,+ watch_expires_at timestamptz,+ materialized_starts_at timestamptz,+ materialized_ends_at timestamptz,+ materialized_start_date date,+ materialized_end_date date,+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now(),+ UNIQUE (account_id, provider_calendar_id),+ CONSTRAINT calendars_materialized_range CHECK (+ (+ materialized_starts_at IS NULL+ AND materialized_ends_at IS NULL+ AND materialized_start_date IS NULL+ AND materialized_end_date IS NULL+ )+ OR+ (+ materialized_starts_at IS NOT NULL+ AND materialized_ends_at IS NOT NULL+ AND materialized_start_date IS NOT NULL+ AND materialized_end_date IS NOT NULL+ AND materialized_ends_at > materialized_starts_at+ AND materialized_end_date > materialized_start_date+ )+ )+);++CREATE INDEX IF NOT EXISTS calendars_account_selected_idx+ ON calendars (account_id, is_selected)+ WHERE NOT is_deleted;++CREATE INDEX IF NOT EXISTS calendars_watch_expiring_idx+ ON calendars (watch_expires_at)+ WHERE watch_channel_id IS NOT NULL;++CREATE TABLE IF NOT EXISTS calendar_events (+ id uuid PRIMARY KEY,+ owner_id text NOT NULL,+ source_link_id uuid NOT NULL+ REFERENCES email_links(id) ON DELETE CASCADE,+ ical_uid text NOT NULL,+ title text NOT NULL DEFAULT '',+ description text,+ location text,+ status text NOT NULL DEFAULT 'confirmed'+ CHECK (status IN ('confirmed', 'tentative', 'cancelled')),+ visibility text NOT NULL DEFAULT 'default'+ CHECK (visibility IN ('default', 'public', 'private', 'confidential')),+ transparency text NOT NULL DEFAULT 'opaque'+ CHECK (transparency IN ('opaque', 'transparent')),+ starts_at timestamptz,+ ends_at timestamptz,+ start_date date,+ end_date date,+ time_zone text,+ recurrence_lines text[] NOT NULL DEFAULT '{}',+ organizer_email text,+ organizer_name text,+ conference_url text,+ sequence integer NOT NULL DEFAULT 0 CHECK (sequence >= 0),+ is_read_only boolean NOT NULL DEFAULT false,+ canonical_source_kind text NOT NULL+ CHECK (canonical_source_kind IN ('google', 'email_ics')),+ canonical_source_updated_at timestamptz NOT NULL,+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now(),+ UNIQUE (owner_id, source_link_id, ical_uid),+ UNIQUE (id, owner_id),+ UNIQUE (id, source_link_id),+ CONSTRAINT calendar_events_time_shape CHECK (+ (+ starts_at IS NOT NULL+ AND ends_at IS NOT NULL+ AND start_date IS NULL+ AND end_date IS NULL+ AND ends_at > starts_at+ )+ OR+ (+ starts_at IS NULL+ AND ends_at IS NULL+ AND start_date IS NOT NULL+ AND end_date IS NOT NULL+ AND end_date > start_date+ )+ )+);++CREATE INDEX IF NOT EXISTS calendar_events_owner_updated_idx+ ON calendar_events (owner_id, updated_at DESC, id DESC);++CREATE INDEX IF NOT EXISTS calendar_events_owner_created_idx+ ON calendar_events (owner_id, created_at DESC, id DESC);++CREATE INDEX IF NOT EXISTS calendar_events_source_link_idx+ ON calendar_events (source_link_id);++CREATE TABLE IF NOT EXISTS calendar_event_sources (+ id uuid PRIMARY KEY,+ event_id uuid NOT NULL,+ source_link_id uuid NOT NULL+ REFERENCES email_links(id) ON DELETE CASCADE,+ source_kind text NOT NULL+ CHECK (source_kind IN ('google', 'email_ics')),+ account_id uuid+ REFERENCES calendar_accounts(id) ON DELETE CASCADE,+ calendar_id uuid+ REFERENCES calendars(id) ON DELETE CASCADE,+ provider_event_id text,+ provider_recurring_event_id text,+ provider_etag text,+ email_link_id uuid+ REFERENCES email_links(id) ON DELETE CASCADE,+ email_thread_id uuid,+ email_message_id uuid,+ email_attachment_id text,+ content_hash text,+ parser_version integer NOT NULL DEFAULT 1 CHECK (parser_version > 0),+ raw_payload jsonb NOT NULL DEFAULT '{}',+ source_sequence integer NOT NULL CHECK (source_sequence >= 0),+ source_updated_at timestamptz NOT NULL,+ normalized_payload jsonb NOT NULL,+ first_seen_at timestamptz NOT NULL DEFAULT now(),+ last_seen_at timestamptz NOT NULL DEFAULT now(),+ CONSTRAINT calendar_event_sources_event_link_fkey+ FOREIGN KEY (event_id, source_link_id)+ REFERENCES calendar_events(id, source_link_id) ON DELETE CASCADE,+ CONSTRAINT calendar_event_sources_shape CHECK (+ (+ source_kind = 'google'+ AND account_id IS NOT NULL+ AND calendar_id IS NOT NULL+ AND provider_event_id IS NOT NULL+ AND email_link_id IS NULL+ )+ OR+ (+ source_kind = 'email_ics'+ AND email_link_id IS NOT NULL+ AND email_message_id IS NOT NULL+ AND content_hash IS NOT NULL+ AND account_id IS NULL+ AND calendar_id IS NULL+ AND provider_event_id IS NULL+ )+ )+);++CREATE UNIQUE INDEX IF NOT EXISTS calendar_event_sources_google_idx+ ON calendar_event_sources (account_id, calendar_id, provider_event_id)+ WHERE source_kind = 'google';++CREATE UNIQUE INDEX IF NOT EXISTS calendar_event_sources_email_idx+ ON calendar_event_sources (+ email_link_id,+ email_message_id,+ COALESCE(email_attachment_id, ''),+ content_hash,+ event_id+ )+ WHERE source_kind = 'email_ics';++CREATE INDEX IF NOT EXISTS calendar_event_sources_event_idx+ ON calendar_event_sources (event_id);++CREATE INDEX IF NOT EXISTS calendar_event_sources_source_link_idx+ ON calendar_event_sources (source_link_id);++CREATE INDEX IF NOT EXISTS calendar_event_sources_email_link_idx+ ON calendar_event_sources (email_link_id)+ WHERE email_link_id IS NOT NULL;++CREATE INDEX IF NOT EXISTS calendar_event_sources_account_idx+ ON calendar_event_sources (account_id)+ WHERE account_id IS NOT NULL;++CREATE INDEX IF NOT EXISTS calendar_event_sources_calendar_idx+ ON calendar_event_sources (calendar_id)+ WHERE calendar_id IS NOT NULL;++CREATE TABLE IF NOT EXISTS calendar_event_attendees (+ event_id uuid NOT NULL+ REFERENCES calendar_events(id) ON DELETE CASCADE,+ email text NOT NULL,+ display_name text,+ response_status text NOT NULL DEFAULT 'needs_action'+ CHECK (response_status IN ('needs_action', 'accepted', 'declined', 'tentative')),+ is_organizer boolean NOT NULL DEFAULT false,+ is_optional boolean NOT NULL DEFAULT false,+ is_self boolean NOT NULL DEFAULT false,+ comment text,+ PRIMARY KEY (event_id, email)+);++CREATE INDEX IF NOT EXISTS calendar_event_attendees_email_idx+ ON calendar_event_attendees (lower(email));++CREATE TABLE IF NOT EXISTS calendar_event_overrides (+ event_id uuid NOT NULL+ REFERENCES calendar_events(id) ON DELETE CASCADE,+ recurrence_id text NOT NULL,+ original_starts_at timestamptz,+ original_start_date date,+ starts_at timestamptz,+ ends_at timestamptz,+ start_date date,+ end_date date,+ title text,+ description text,+ location text,+ status text+ CHECK (status IS NULL OR status IN ('confirmed', 'tentative', 'cancelled')),+ updated_at timestamptz NOT NULL DEFAULT now(),+ PRIMARY KEY (event_id, recurrence_id),+ CONSTRAINT calendar_event_overrides_original_shape CHECK (+ (original_starts_at IS NOT NULL) <> (original_start_date IS NOT NULL)+ ),+ CONSTRAINT calendar_event_overrides_time_shape CHECK (+ (+ starts_at IS NOT NULL+ AND ends_at IS NOT NULL+ AND start_date IS NULL+ AND end_date IS NULL+ AND ends_at > starts_at+ )+ OR+ (+ starts_at IS NULL+ AND ends_at IS NULL+ AND start_date IS NOT NULL+ AND end_date IS NOT NULL+ AND end_date > start_date+ )+ )+);++CREATE TABLE IF NOT EXISTS calendar_event_occurrences (+ event_id uuid NOT NULL,+ owner_id text NOT NULL,+ occurrence_key text NOT NULL,+ recurrence_id text,+ starts_at timestamptz,+ ends_at timestamptz,+ start_date date,+ end_date date,+ is_cancelled boolean NOT NULL DEFAULT false,+ timed_span tstzrange GENERATED ALWAYS AS (+ CASE+ WHEN starts_at IS NOT NULL+ THEN tstzrange(starts_at, ends_at, '[)')+ END+ ) STORED,+ day_span daterange GENERATED ALWAYS AS (+ CASE+ WHEN start_date IS NOT NULL+ THEN daterange(start_date, end_date, '[)')+ END+ ) STORED,+ generated_at timestamptz NOT NULL DEFAULT now(),+ PRIMARY KEY (event_id, occurrence_key),+ CONSTRAINT calendar_event_occurrences_event_owner_fkey+ FOREIGN KEY (event_id, owner_id)+ REFERENCES calendar_events(id, owner_id) ON DELETE CASCADE,+ CONSTRAINT calendar_event_occurrences_time_shape CHECK (+ (+ starts_at IS NOT NULL+ AND ends_at IS NOT NULL+ AND start_date IS NULL+ AND end_date IS NULL+ AND ends_at > starts_at+ )+ OR+ (+ starts_at IS NULL+ AND ends_at IS NULL+ AND start_date IS NOT NULL+ AND end_date IS NOT NULL+ AND end_date > start_date+ )+ )+);++CREATE INDEX IF NOT EXISTS calendar_event_occurrences_timed_span_idx+ ON calendar_event_occurrences USING gist (owner_id, timed_span)+ WHERE NOT is_cancelled AND timed_span IS NOT NULL;++CREATE INDEX IF NOT EXISTS calendar_event_occurrences_day_span_idx+ ON calendar_event_occurrences USING gist (owner_id, day_span)+ WHERE NOT is_cancelled AND day_span IS NOT NULL;++CREATE INDEX IF NOT EXISTS calendar_event_occurrences_event_start_idx+ ON calendar_event_occurrences (owner_id, event_id, starts_at, start_date)+ WHERE NOT is_cancelled;++ALTER TABLE email_backfill_jobs+ ADD COLUMN IF NOT EXISTS init_lease_token uuid,+ ADD COLUMN IF NOT EXISTS init_lease_expires_at timestamptz,+ ADD COLUMN IF NOT EXISTS initialized_at timestamptz;++CREATE TABLE IF NOT EXISTS email_backfill_init_outbox (+ id uuid PRIMARY KEY,+ backfill_job_id uuid NOT NULL UNIQUE+ REFERENCES email_backfill_jobs(id) ON DELETE CASCADE,+ created_at timestamptz NOT NULL DEFAULT now(),+ published_at timestamptz+);++CREATE INDEX IF NOT EXISTS email_backfill_init_outbox_unpublished_idx+ ON email_backfill_init_outbox (created_at, id)+ WHERE published_at IS NULL;++CREATE TABLE IF NOT EXISTS email_backfill_completion_outbox (+ id uuid PRIMARY KEY,+ backfill_job_id uuid NOT NULL UNIQUE+ REFERENCES email_backfill_jobs(id) ON DELETE CASCADE,+ created_at timestamptz NOT NULL DEFAULT now(),+ published_at timestamptz,+ completed_at timestamptz,+ effects_lease_token uuid,+ effects_lease_expires_at timestamptz+);++CREATE INDEX IF NOT EXISTS email_backfill_completion_outbox_unpublished_idx+ ON email_backfill_completion_outbox (created_at, id)+ WHERE published_at IS NULL;++CREATE TABLE IF NOT EXISTS calendar_backfill_jobs (+ id uuid PRIMARY KEY,+ email_link_id uuid NOT NULL+ REFERENCES email_links(id) ON DELETE CASCADE,+ account_id uuid+ REFERENCES calendar_accounts(id) ON DELETE CASCADE,+ kind text NOT NULL+ CHECK (kind IN ('google_calendar', 'email_ics')),+ grant_version bigint NOT NULL CHECK (grant_version > 0),+ status text NOT NULL DEFAULT 'pending'+ CHECK (status IN ('pending', 'running', 'complete', 'failed')),+ cursor jsonb NOT NULL DEFAULT '{}',+ scanned_count bigint NOT NULL DEFAULT 0 CHECK (scanned_count >= 0),+ extracted_count bigint NOT NULL DEFAULT 0 CHECK (extracted_count >= 0),+ last_error text,+ created_at timestamptz NOT NULL DEFAULT now(),+ started_at timestamptz,+ completed_at timestamptz,+ lease_token uuid,+ lease_expires_at timestamptz,+ updated_at timestamptz NOT NULL DEFAULT now(),+ UNIQUE (email_link_id, kind, grant_version)+);++CREATE INDEX IF NOT EXISTS calendar_backfill_jobs_pending_idx+ ON calendar_backfill_jobs (created_at, id)+ WHERE status IN ('pending', 'running');++CREATE INDEX IF NOT EXISTS calendar_backfill_jobs_account_idx+ ON calendar_backfill_jobs (account_id)+ WHERE account_id IS NOT NULL;++CREATE TABLE IF NOT EXISTS calendar_sync_outbox (+ id uuid PRIMARY KEY,+ backfill_job_id uuid NOT NULL UNIQUE+ REFERENCES calendar_backfill_jobs(id) ON DELETE CASCADE,+ created_at timestamptz NOT NULL DEFAULT now(),+ published_at timestamptz+);++CREATE INDEX IF NOT EXISTS calendar_sync_outbox_unpublished_idx+ ON calendar_sync_outbox (created_at, id)+ WHERE published_at IS NULL;diff --git a/infra/stacks/fusionauth-instance/Pulumi.dev.yaml b/infra/stacks/fusionauth-instance/Pulumi.dev.yamlindex 036a358861..e552bcc9b9 100644--- a/infra/stacks/fusionauth-instance/Pulumi.dev.yaml+++ b/infra/stacks/fusionauth-instance/Pulumi.dev.yaml@@ -15,6 +15,7 @@ config:fusionauth-instance:fusionauth-google-gmail-idp-id: b99932ac-bce5-4f1d-99a1-e64760aae811fusionauth-instance:google-client-id-secret-key: google-client-id-devfusionauth-instance:google-client-secret-secret-key: google-client-secret-dev+ fusionauth-instance:enable-google-calendar: truefusionauth:host: https://fusionauth-dev.macro.comfusionauth:apiKey:secure: AAABAGgKVJijjzcGu5lYU2bdn90Xhj6JcMl0mfKwaLTvNccxRKljjFRHrLaXY63ZLseAxo39MMakTB8SyYbebCvHBDv/zkCV5tnFjx4UBZozo4ABYRLgoQ==diff --git a/infra/stacks/fusionauth-instance/Pulumi.local.yaml b/infra/stacks/fusionauth-instance/Pulumi.local.yamlindex 28ea8b401a..d299b72af4 100644--- a/infra/stacks/fusionauth-instance/Pulumi.local.yaml+++ b/infra/stacks/fusionauth-instance/Pulumi.local.yaml@@ -11,3 +11,4 @@ config:fusionauth-instance:google-client-id-secret-key: google-client-id-devfusionauth-instance:google-client-secret-secret-key: google-client-secret-devfusionauth:apiKey: bf69486b-4733-4954-a44e-2e1b5f2c8a91+ fusionauth-instance:enable-google-calendar: truediff --git a/infra/stacks/fusionauth-instance/Pulumi.prod.yaml b/infra/stacks/fusionauth-instance/Pulumi.prod.yamlindex ded7fa2377..77e81731f1 100644--- a/infra/stacks/fusionauth-instance/Pulumi.prod.yaml+++ b/infra/stacks/fusionauth-instance/Pulumi.prod.yaml@@ -16,5 +16,6 @@ config:fusionauth-instance:google-client-id-secret-key: google-client-id-prodfusionauth-instance:google-client-secret-secret-key: google-client-secret-prodfusionauth:host: https://auth.macro.com+ fusionauth-instance:enable-google-calendar: falsefusionauth:apiKey:secure: AAABANOJD8AOmyME2/j2t2nmudnPjYIszfItHGubEm2ZmKaErrrrqRydP7udMstGDgi0inuUCRj819+S1tXXVZF0E7BP9bL1cTxmhf0+nMbO6CHkdyRycQ==diff --git a/infra/stacks/fusionauth-instance/index.ts b/infra/stacks/fusionauth-instance/index.tsindex f6c4bed79c..fabab690e7 100644--- a/infra/stacks/fusionauth-instance/index.ts+++ b/infra/stacks/fusionauth-instance/index.ts@@ -385,6 +385,27 @@ new FusionAuthIdpOpenIdConnect(});+const enableGoogleCalendarIntegration = config.requireBoolean(+ 'enable-google-calendar'+);+const GOOGLE_CALENDAR_SCOPES = ['https://www.googleapis.com/auth/calendar'];++const GOOGLE_GMAIL_OAUTH_SCOPES = [+ 'openid',+ 'profile',+ 'email',+ 'https://www.googleapis.com/auth/gmail.modify',+ 'https://www.googleapis.com/auth/contacts.readonly',+ 'https://www.googleapis.com/auth/contacts.other.readonly',+ 'https://www.googleapis.com/auth/gmail.settings.basic',+];++let googleOauth2Scope = GOOGLE_GMAIL_OAUTH_SCOPES.join(' ');++if (enableGoogleCalendarIntegration) {+ googleOauth2Scope = `${googleOauth2Scope} ${GOOGLE_CALENDAR_SCOPES.join(' ')}`;+}+// The google gmail identity providernew FusionAuthIdpOpenIdConnect('google-gmail-idp',@@ -400,8 +421,7 @@ new FusionAuthIdpOpenIdConnect(oauth2TokenEndpoint: 'https://oauth2.googleapis.com/token',oauth2UserInfoEndpoint: 'https://openidconnect.googleapis.com/v1/userinfo',buttonText: 'GoogleGmail',- oauth2Scope:- 'openid profile email https://www.googleapis.com/auth/gmail.modify https://www.googleapis.com/auth/contacts.readonly https://www.googleapis.com/auth/contacts.other.readonly https://www.googleapis.com/auth/gmail.settings.basic',+ oauth2Scope: googleOauth2Scope,oauth2UniqueIdClaim: 'sub',linkingStrategy: 'LinkByEmail',debug: stack !== 'prod',diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.tsindex b1d85a97b6..e29241a4d4 100644--- a/packages/sdk/generated/storage/index.ts+++ b/packages/sdk/generated/storage/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessLevel, Activity, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClientOptions, CloudStorageItemType, Comment, CommentThread, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EntityFilters, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActivitiesResponse, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetRecentActivityHandlerData, GetRecentActivityHandlerError, GetRecentActivityHandlerErrors, GetRecentActivityHandlerResponse, GetRecentActivityHandlerResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, Mentions, NewChannelAttachment, NotificationFilters, Params, ParticipantRole, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupAttachment, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, String, SuccessResponse, SyncServiceVersionId, TagFilterMode, TaskFilters, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserActivitiesResponse, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';+export type { AccessLevel, Activity, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClientOptions, CloudStorageItemType, Comment, CommentThread, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EntityFilters, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventStatus, EventTime, EventTransparency, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActivitiesResponse, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetRecentActivityHandlerData, GetRecentActivityHandlerError, GetRecentActivityHandlerErrors, GetRecentActivityHandlerResponse, GetRecentActivityHandlerResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, Mentions, NewChannelAttachment, NotificationFilters, Params, ParticipantRole, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupAttachment, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, String, SuccessResponse, SyncServiceVersionId, TagFilterMode, TaskFilters, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserActivitiesResponse, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.tsindex 0cfc84c078..0a0f49fb1d 100644--- a/packages/sdk/generated/storage/sdk.gen.ts+++ b/packages/sdk/generated/storage/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCommentData, CreateCommentErrors, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentErrors, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentErrors, DeleteCrmCommentResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageErrors, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditCommentData, EditCommentErrors, EditCommentResponses, EditCrmCommentData, EditCrmCommentErrors, EditCrmCommentResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesErrors, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsErrors, GetDocumentCommentsResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextErrors, GetMessageWithContextResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetRecentActivityHandlerData, GetRecentActivityHandlerErrors, GetRecentActivityHandlerResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetThreadRepliesData, GetThreadRepliesErrors, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsErrors, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchMessageData, PatchMessageErrors, PatchMessageResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesErrors, PostChannelMessagesResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PostMessageData, PostMessageErrors, PostMessageResponses, PostReactionData, PostReactionErrors, PostReactionResponses, PostTypingData, PostTypingErrors, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageErrors, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';+import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCommentData, CreateCommentErrors, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentErrors, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentErrors, DeleteCrmCommentResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageErrors, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditCommentData, EditCommentErrors, EditCommentResponses, EditCrmCommentData, EditCrmCommentErrors, EditCrmCommentResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesErrors, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsErrors, GetDocumentCommentsResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextErrors, GetMessageWithContextResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetRecentActivityHandlerData, GetRecentActivityHandlerErrors, GetRecentActivityHandlerResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetThreadRepliesData, GetThreadRepliesErrors, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsErrors, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchMessageData, PatchMessageErrors, PatchMessageResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesErrors, PostChannelMessagesResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PostMessageData, PostMessageErrors, PostMessageResponses, PostReactionData, PostReactionErrors, PostReactionResponses, PostTypingData, PostTypingErrors, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageErrors, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -188,6 +188,13 @@ export class Sdk extends HeyApiClient {return (options.client ?? this.client).delete<RemoveBotFromChannelByBotResponses, RemoveBotFromChannelByBotErrors, ThrowOnError>({ url: '/bots/{bot_id}/channels/{channel_id}', ...options });}+ /**+ * Return calendar occurrences visible to the authenticated requester.+ */+ public listOccurrences<ThrowOnError extends boolean = false>(options: Options<ListOccurrencesData, ThrowOnError>): RequestResult<ListOccurrencesResponses, ListOccurrencesErrors, ThrowOnError> {+ return (options.client ?? this.client).get<ListOccurrencesResponses, ListOccurrencesErrors, ThrowOnError>({ url: '/calendar-events', ...options });+ }+/*** Handler for `POST /call/record/preview`.*diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex bf019de03e..3a03e39917 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -891,6 +891,11 @@ export type ApiThreadReply = {updated_at: string;};+/**+ * RSVP state for an attendee.+ */+export type AttendeeResponseStatus = 'needs_action' | 'accepted' | 'declined' | 'tentative';+export type BTreeMap = {[key: string]: string;};@@ -1145,6 +1150,175 @@ export type BulkWakeupResponse = {dispatched: number;};+/**+ * An attendee on a calendar event.+ */+export type CalendarAttendee = {+ /**+ * Optional attendee comment.+ */+ comment?: string | null;+ /**+ * Provider display name.+ */+ displayName?: string | null;+ /**+ * Normalized email address.+ */+ email: string;+ /**+ * Whether attendance is optional.+ */+ isOptional: boolean;+ /**+ * Whether this attendee is the organizer.+ */+ isOrganizer: boolean;+ /**+ * Whether this attendee represents the connected account.+ */+ isSelf: boolean;+ /**+ * RSVP state.+ */+ responseStatus: AttendeeResponseStatus;+};++/**+ * A stable, first-class Macro calendar event entity.+ */+export type CalendarEvent = {+ /**+ * Attendees, keyed by email during persistence.+ */+ attendees: Array<CalendarAttendee>;+ /**+ * Direct join URL when known.+ */+ conferenceUrl?: string | null;+ /**+ * Entity creation time.+ */+ createdAt: string;+ /**+ * Optional event body.+ */+ description?: string | null;+ /**+ * RFC 5545 UID used to reconcile provider and email sources.+ */+ icalUid: string;+ /**+ * Macro entity identifier.+ */+ id: string;+ /**+ * Whether the current user can edit the canonical source.+ */+ isReadOnly: boolean;+ /**+ * Optional physical or virtual location label.+ */+ location?: string | null;+ /**+ * Organizer email.+ */+ organizerEmail?: string | null;+ /**+ * Organizer display name.+ */+ organizerName?: string | null;+ /**+ * Macro user who owns this event entity.+ */+ ownerId: string;+ /**+ * Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`).+ */+ recurrenceLines: Array<string>;+ /**+ * Provider/iCalendar sequence number.+ */+ sequence: number;+ /**+ * Event status.+ */+ status: EventStatus;+ /**+ * Timed or all-day shape.+ */+ time: EventTime;+ /**+ * Display title.+ */+ title: string;+ /**+ * Availability behavior.+ */+ transparency: EventTransparency;+ /**+ * Entity update time.+ */+ updatedAt: string;+ /**+ * Event visibility.+ */+ visibility: EventVisibility;+};++/**+ * A materialized recurrence instance optimized for range queries.+ */+export type CalendarOccurrence = {+ /**+ * Owning event entity.+ */+ eventId: string;+ /**+ * Whether the instance was cancelled.+ */+ isCancelled: boolean;+ /**+ * Stable key within the event.+ */+ occurrenceKey: string;+ /**+ * Provider recurrence identifier, when applicable.+ */+ recurrenceId?: string | null;+ /**+ * Instance time.+ */+ time: EventTime;+};++/**+ * One materialized occurrence paired with its stable calendar event entity.+ */+export type CalendarOccurrenceItem = {+ event: CalendarEvent;+ occurrence: CalendarOccurrence;+};++/**+ * Paginated calendar occurrence viewport response.+ */+export type CalendarOccurrenceResponse = {+ hasMore: boolean;+ items: Array<CalendarOccurrenceItem>;+ nextCursor?: string | null;+ /**+ * Aggregate ingestion state; clients render a skeleton while `syncing`.+ */+ syncStatus: CalendarSyncStatus;+};++/**+ * Aggregate ingestion state across every calendar account visible to a+ * requester, letting clients render progressively while sources build.+ */+export type CalendarSyncStatus = 'syncing' | 'ready';+/*** Response indicating whether an active call exists for a channel.*/@@ -4127,6 +4301,54 @@ export type ErrorResponse = {message: string;};+/**+ * Canonical event status.+ */+export type EventStatus = 'confirmed' | 'tentative' | 'cancelled';++/**+ * The mutually exclusive time shape of a calendar event.+ *+ * Fields are renamed per variant rather than with `rename_all_fields`+ * because utoipa only honors variant-level serde renames when it+ * derives the OpenAPI schema.+ */+export type EventTime = {+ /**+ * Exclusive end instant.+ */+ endsAt: string;+ kind: 'timed';+ /**+ * Inclusive start instant.+ */+ startsAt: string;+ /**+ * Original IANA time-zone identifier, when supplied.+ */+ timeZone?: string | null;+} | {+ /**+ * Exclusive local end date.+ */+ endDate: string;+ kind: 'allDay';+ /**+ * Inclusive local start date.+ */+ startDate: string;+};++/**+ * Whether an event blocks availability.+ */+export type EventTransparency = 'opaque' | 'transparent';++/**+ * Visibility of event details.+ */+export type EventVisibility = 'default' | 'public' | 'private' | 'confidential';+export type ExcludeDefaultViewRequest = {defaultViewId: string;};@@ -7735,6 +7957,62 @@ export type RemoveBotFromChannelByBotResponses = {export type RemoveBotFromChannelByBotResponse = RemoveBotFromChannelByBotResponses[keyof RemoveBotFromChannelByBotResponses];+export type ListOccurrencesData = {+ body?: never;+ path?: never;+ query: {+ /**+ * Inclusive UTC viewport start.+ */+ start: string;+ /**+ * Exclusive UTC viewport end.+ */+ end: string;+ /**+ * Inclusive local date boundary for all-day events.+ */+ startDate?: string;+ /**+ * Exclusive local date boundary for all-day events.+ */+ endDate?: string;+ /**+ * Maximum number of occurrences, from 1 through 2,000.+ */+ limit?: number;+ /**+ * Opaque continuation cursor returned by the previous page.+ */+ cursor?: string;+ };+ url: '/calendar-events';+};++export type ListOccurrencesErrors = {+ /**+ * Invalid or unsupported calendar viewport+ */+ 400: unknown;+ /**+ * Authentication required+ */+ 401: unknown;+ /**+ * Calendar query failed+ */+ 500: unknown;+};++export type ListOccurrencesResponses = {+ /**+ * Calendar occurrences in the requested viewport+ */+ 200: CalendarOccurrenceResponse;+};++export type ListOccurrencesResponse = ListOccurrencesResponses[keyof ListOccurrencesResponses];+export type GetBatchCallRecordPreviewData = {body: GetBatchCallRecordPreviewRequest;path?: never;diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex bc2e18819b..064ca7bdb3 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -779,6 +779,97 @@}}},+ "/calendar-events": {+ "get": {+ "tags": ["calendar_events"],+ "summary": "Return calendar occurrences visible to the authenticated requester.",+ "operationId": "list_occurrences",+ "parameters": [+ {+ "name": "start",+ "in": "query",+ "description": "Inclusive UTC viewport start.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "date-time"+ }+ },+ {+ "name": "end",+ "in": "query",+ "description": "Exclusive UTC viewport end.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "date-time"+ }+ },+ {+ "name": "startDate",+ "in": "query",+ "description": "Inclusive local date boundary for all-day events.",+ "required": false,+ "schema": {+ "type": "string",+ "format": "date"+ }+ },+ {+ "name": "endDate",+ "in": "query",+ "description": "Exclusive local date boundary for all-day events.",+ "required": false,+ "schema": {+ "type": "string",+ "format": "date"+ }+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Maximum number of occurrences, from 1 through 2,000.",+ "required": false,+ "schema": {+ "type": "integer",+ "format": "int32",+ "maximum": 2000,+ "minimum": 1+ }+ },+ {+ "name": "cursor",+ "in": "query",+ "description": "Opaque continuation cursor returned by the previous page.",+ "required": false,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Calendar occurrences in the requested viewport",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CalendarOccurrenceResponse"+ }+ }+ }+ },+ "400": {+ "description": "Invalid or unsupported calendar viewport"+ },+ "401": {+ "description": "Authentication required"+ },+ "500": {+ "description": "Calendar query failed"+ }+ }+ }+ },"/call/record/preview": {"post": {"tags": ["call::inbound::axum_router"],@@ -11823,6 +11914,11 @@}}},+ "AttendeeResponseStatus": {+ "type": "string",+ "description": "RSVP state for an attendee.",+ "enum": ["needs_action", "accepted", "declined", "tentative"]+ },"BTreeMap": {"type": "object","additionalProperties": {@@ -12179,6 +12275,225 @@}}},+ "CalendarAttendee": {+ "type": "object",+ "description": "An attendee on a calendar event.",+ "required": [+ "email",+ "responseStatus",+ "isOrganizer",+ "isOptional",+ "isSelf"+ ],+ "properties": {+ "comment": {+ "type": ["string", "null"],+ "description": "Optional attendee comment."+ },+ "displayName": {+ "type": ["string", "null"],+ "description": "Provider display name."+ },+ "email": {+ "type": "string",+ "description": "Normalized email address."+ },+ "isOptional": {+ "type": "boolean",+ "description": "Whether attendance is optional."+ },+ "isOrganizer": {+ "type": "boolean",+ "description": "Whether this attendee is the organizer."+ },+ "isSelf": {+ "type": "boolean",+ "description": "Whether this attendee represents the connected account."+ },+ "responseStatus": {+ "$ref": "#/components/schemas/AttendeeResponseStatus",+ "description": "RSVP state."+ }+ }+ },+ "CalendarEvent": {+ "type": "object",+ "description": "A stable, first-class Macro calendar event entity.",+ "required": [+ "id",+ "ownerId",+ "icalUid",+ "title",+ "status",+ "visibility",+ "transparency",+ "time",+ "recurrenceLines",+ "sequence",+ "isReadOnly",+ "attendees",+ "createdAt",+ "updatedAt"+ ],+ "properties": {+ "attendees": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CalendarAttendee"+ },+ "description": "Attendees, keyed by email during persistence."+ },+ "conferenceUrl": {+ "type": ["string", "null"],+ "description": "Direct join URL when known."+ },+ "createdAt": {+ "type": "string",+ "format": "date-time",+ "description": "Entity creation time."+ },+ "description": {+ "type": ["string", "null"],+ "description": "Optional event body."+ },+ "icalUid": {+ "type": "string",+ "description": "RFC 5545 UID used to reconcile provider and email sources."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Macro entity identifier."+ },+ "isReadOnly": {+ "type": "boolean",+ "description": "Whether the current user can edit the canonical source."+ },+ "location": {+ "type": ["string", "null"],+ "description": "Optional physical or virtual location label."+ },+ "organizerEmail": {+ "type": ["string", "null"],+ "description": "Organizer email."+ },+ "organizerName": {+ "type": ["string", "null"],+ "description": "Organizer display name."+ },+ "ownerId": {+ "type": "string",+ "description": "Macro user who owns this event entity."+ },+ "recurrenceLines": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`)."+ },+ "sequence": {+ "type": "integer",+ "format": "int32",+ "description": "Provider/iCalendar sequence number.",+ "minimum": 0+ },+ "status": {+ "$ref": "#/components/schemas/EventStatus",+ "description": "Event status."+ },+ "time": {+ "$ref": "#/components/schemas/EventTime",+ "description": "Timed or all-day shape."+ },+ "title": {+ "type": "string",+ "description": "Display title."+ },+ "transparency": {+ "$ref": "#/components/schemas/EventTransparency",+ "description": "Availability behavior."+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time",+ "description": "Entity update time."+ },+ "visibility": {+ "$ref": "#/components/schemas/EventVisibility",+ "description": "Event visibility."+ }+ }+ },+ "CalendarOccurrence": {+ "type": "object",+ "description": "A materialized recurrence instance optimized for range queries.",+ "required": ["eventId", "occurrenceKey", "time", "isCancelled"],+ "properties": {+ "eventId": {+ "type": "string",+ "format": "uuid",+ "description": "Owning event entity."+ },+ "isCancelled": {+ "type": "boolean",+ "description": "Whether the instance was cancelled."+ },+ "occurrenceKey": {+ "type": "string",+ "description": "Stable key within the event."+ },+ "recurrenceId": {+ "type": ["string", "null"],+ "description": "Provider recurrence identifier, when applicable."+ },+ "time": {+ "$ref": "#/components/schemas/EventTime",+ "description": "Instance time."+ }+ }+ },+ "CalendarOccurrenceItem": {+ "type": "object",+ "description": "One materialized occurrence paired with its stable calendar event entity.",+ "required": ["event", "occurrence"],+ "properties": {+ "event": {+ "$ref": "#/components/schemas/CalendarEvent"+ },+ "occurrence": {+ "$ref": "#/components/schemas/CalendarOccurrence"+ }+ }+ },+ "CalendarOccurrenceResponse": {+ "type": "object",+ "description": "Paginated calendar occurrence viewport response.",+ "required": ["items", "hasMore", "syncStatus"],+ "properties": {+ "hasMore": {+ "type": "boolean"+ },+ "items": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/CalendarOccurrenceItem"+ }+ },+ "nextCursor": {+ "type": ["string", "null"]+ },+ "syncStatus": {+ "$ref": "#/components/schemas/CalendarSyncStatus",+ "description": "Aggregate ingestion state; clients render a skeleton while `syncing`."+ }+ }+ },+ "CalendarSyncStatus": {+ "type": "string",+ "description": "Aggregate ingestion state across every calendar account visible to a\nrequester, letting clients render progressively while sources build.",+ "enum": ["syncing", "ready"]+ },"CallActiveResponse": {"type": "object","description": "Response indicating whether an active call exists for a channel.",@@ -16626,6 +16941,72 @@}}},+ "EventStatus": {+ "type": "string",+ "description": "Canonical event status.",+ "enum": ["confirmed", "tentative", "cancelled"]+ },+ "EventTime": {+ "oneOf": [+ {+ "type": "object",+ "description": "An event with absolute instants.",+ "required": ["startsAt", "endsAt", "kind"],+ "properties": {+ "endsAt": {+ "type": "string",+ "format": "date-time",+ "description": "Exclusive end instant."+ },+ "kind": {+ "type": "string",+ "enum": ["timed"]+ },+ "startsAt": {+ "type": "string",+ "format": "date-time",+ "description": "Inclusive start instant."+ },+ "timeZone": {+ "type": ["string", "null"],+ "description": "Original IANA time-zone identifier, when supplied."+ }+ }+ },+ {+ "type": "object",+ "description": "An all-day event using RFC 5545's exclusive end date.",+ "required": ["startDate", "endDate", "kind"],+ "properties": {+ "endDate": {+ "type": "string",+ "format": "date",+ "description": "Exclusive local end date."+ },+ "kind": {+ "type": "string",+ "enum": ["allDay"]+ },+ "startDate": {+ "type": "string",+ "format": "date",+ "description": "Inclusive local start date."+ }+ }+ }+ ],+ "description": "The mutually exclusive time shape of a calendar event.\n\nFields are renamed per variant rather than with `rename_all_fields`\nbecause utoipa only honors variant-level serde renames when it\nderives the OpenAPI schema."+ },+ "EventTransparency": {+ "type": "string",+ "description": "Whether an event blocks availability.",+ "enum": ["opaque", "transparent"]+ },+ "EventVisibility": {+ "type": "string",+ "description": "Visibility of event details.",+ "enum": ["default", "public", "private", "confidential"]+ },"ExcludeDefaultViewRequest": {"type": "object","required": ["defaultViewId"],diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex 0ec194eb71..f0ea694ebe 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -296,6 +296,7 @@ export const storageBacklog = ['getProjectPermissionsV2','getProjectUserAccessLevel','getRecentActivityHandler',+ 'listOccurrences','postActivity','presaveDocumentHandler','saveDocumentHandler',diff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.tomlindex 6198953c71..df0f5750bb 100644--- a/services/document_storage_service/Cargo.toml+++ b/services/document_storage_service/Cargo.toml@@ -48,6 +48,7 @@ axum-extra = { workspace = true }base64 = { workspace = true }bots = { path = "../../crates/bots" }bytes = { workspace = true }+calendar_events = { path = "../../crates/calendar_events", features = ["inbound", "postgres"] }bzip2 = { workspace = true, default-features = false, features = ["libbz2-rs-sys",] }diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rsindex c77c69d331..ad5c2d8c1e 100644--- a/services/document_storage_service/src/api/context.rs+++ b/services/document_storage_service/src/api/context.rs@@ -12,6 +12,10 @@ use cal::{domain::service::CalWebhookServiceImpl, inbound::cal_webhook_router::CalWebhookRouterState,outbound::analytics_client::AnalyticsClientSink,};+use calendar_events::{+ domain::service::CalendarService, inbound::axum_router::CalendarRouterState,+ outbound::pg::PgCalendarRepository,+};use call::{domain::service::CallServiceImpl,inbound::axum_router::{CallRouterState, InternalCallRouterState, WebhookRouterState},@@ -191,6 +195,12 @@ pub(crate) type PropertiesHandlerState =/// Type alias for the entity access service.pub(crate) type EntityAccessService = EntityAccessServiceImpl<PgAccessRepository>;+/// Calendar occurrence query service.+pub(crate) type DssCalendarService = CalendarService<PgCalendarRepository>;++/// Calendar occurrence router state.+pub(crate) type DssCalendarState = CalendarRouterState<DssCalendarService, AuthorizationService>;+/// Adapter implementing [`TaskPropertiesPort`] for the system properties service.pub(crate) struct TaskPropertiesAdapter {pub system_properties: Arc<SystemPropertiesService>,@@ -469,6 +479,7 @@ pub(crate) struct ApiContext {/// Legacy channel list router state.pub channel_list_state: DssChannelListState,pub entity_access_service: Arc<EntityAccessService>,+ pub calendar_state: DssCalendarState,pub documents_state: DocumentsState,pub projects_state: ProjectsState,pub channels_state: DssChannelsState,diff --git a/services/document_storage_service/src/api/mod.rs b/services/document_storage_service/src/api/mod.rsindex 959cfe6887..007227e249 100644--- a/services/document_storage_service/src/api/mod.rs+++ b/services/document_storage_service/src/api/mod.rs@@ -203,6 +203,9 @@ fn api_router(state: ApiContext) -> Router {channels::inbound::list_router::channel_list_router(state.channel_list_state.clone()),).nest("/entity", entity::router())+ .merge(calendar_events::inbound::axum_router::calendar_router(+ state.calendar_state.clone(),+ )).nest("/channels",channels::inbound::axum_router::channels_router(state.channels_state.clone()),diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rsindex 95cd658250..6165fbe17d 100644--- a/services/document_storage_service/src/api/swagger.rs+++ b/services/document_storage_service/src/api/swagger.rs@@ -140,6 +140,7 @@ use utoipa::OpenApi;),paths(health::health_handler,+ calendar_events::inbound::axum_router::list_occurrences,// activityactivity::get_recent_activity::get_recent_activity_handler,@@ -419,6 +420,9 @@ use utoipa::OpenApi;DocumentPermissionsTokenRequest,ExportDocumentResponse,SyncServiceVersionID,+ calendar_events::inbound::axum_router::CalendarOccurrenceItem,+ calendar_events::inbound::axum_router::CalendarOccurrenceResponse,+ calendar_events::domain::models::CalendarSyncStatus,SoupItemWithProperties,SoupApiItem,SoupDocument<SoupPropertiesField>,diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rsindex ec849b1883..5b3cada917 100644--- a/services/document_storage_service/src/main.rs+++ b/services/document_storage_service/src/main.rs@@ -20,6 +20,7 @@ use cal::{inbound::cal_webhook_router::CalWebhookRouterState,outbound::analytics_client::AnalyticsClientSink,};+use calendar_events::inbound::axum_router::CalendarRouterState;use call::{domain::service::CallServiceImpl,inbound::axum_router::{CallRouterState, InternalCallRouterState, WebhookRouterState},@@ -981,6 +982,12 @@ async fn main() -> anyhow::Result<()> {});let favorites_service = Arc::new(FavoritesServiceImpl::new(PgFavoritesRepo::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 redis_sha_client = Arc::new(Redis::new(redis_client));@@ -1048,6 +1055,7 @@ async fn main() -> anyhow::Result<()> {frecency_storage,channel_list_state,entity_access_service: entity_access_service.clone(),+ calendar_state,projects_state: ProjectRouterState {service: project_service,access_service: entity_access_service.clone(),diff --git a/tooling/just/rust.just b/tooling/just/rust.justindex 7c0df453a2..05ffcac20a 100644--- a/tooling/just/rust.just+++ b/tooling/just/rust.just@@ -117,6 +117,7 @@ setup_test_envs:echo "DATABASE_URL={{ DATABASE_URL }}" >> ./crates/ai_projections/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./services/ai_projections_refresh_handler/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./crates/webhook/.env+ echo "DATABASE_URL={{ DATABASE_URL }}" >> ./crates/calendar_events/.envsetup_macrodb:just crates/macro_db_client/create_dbdiff --git a/tooling/xtask/crates/xtask_local/src/local/kickstart.rs b/tooling/xtask/crates/xtask_local/src/local/kickstart.rsindex ad91a9e920..0f2cfe430a 100644--- a/tooling/xtask/crates/xtask_local/src/local/kickstart.rs+++ b/tooling/xtask/crates/xtask_local/src/local/kickstart.rs@@ -324,7 +324,7 @@ pub fn build("buttonText": "GoogleGmail","linkingStrategy": "LinkByEmail","lambdaConfiguration": { "reconcileId": identity::RECONCILE_LAMBDA_ID },- "oauth2": oauth2_base("openid profile email https://www.googleapis.com/auth/gmail.modify https://www.googleapis.com/auth/contacts.readonly https://www.googleapis.com/auth/contacts.other.readonly https://www.googleapis.com/auth/gmail.settings.basic"),+ "oauth2": oauth2_base("openid profile email https://www.googleapis.com/auth/gmail.modify https://www.googleapis.com/auth/contacts.readonly https://www.googleapis.com/auth/contacts.other.readonly https://www.googleapis.com/auth/gmail.settings.basic https://www.googleapis.com/auth/calendar"),"applicationConfiguration": app_config,}}}));