Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(cal_com): sync memberships, attendees, users and routing forms (#100172)

Tom Owers9253e6f88886
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index f618c2944c0b..064c502670d6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -1119,15 +1119,15 @@ Note: The vendor's official API repo (github.com/Buzzsprout/buzzsprout-api) cont
## CalCom — gaps
-Today (6): `bookings`, `event_types`, `me`, `schedules`, `teams`, `webhooks`
+Today (12): `booking_attendees`, `bookings`, `event_types`, `me`, `organization_memberships`, `organization_users`, `routing_form_responses`, `routing_forms`, `schedules`, `team_memberships`, `teams`, `webhooks`
Diffed against: <https://cal.com/docs/api-reference/v2/openapi.json>
-- [ ] `/v2/organizations/{orgId}/memberships and /v2/teams/{teamId}/memberships` — membership tables joining users to the teams we already sync — currently no way to attribute a booking to a team member (high)
-- [ ] `/v2/organizations/{orgId}/users` — lookup table resolving the user/host IDs carried on bookings and event types (high)
-- [ ] `/v2/bookings/{bookingUid}/attendees` — attendee-level rows for each booking — the grain needed for no-show and guest analysis (high)
-- [ ] `/v2/organizations/{orgId}/routing-forms/{routingFormId}/responses` — routing form submissions, the lead-qualification data that explains which bookings came from which route (high)
-- [ ] `/v2/organizations/{orgId}/routing-forms` — lookup resolving the routing form IDs on responses and routed bookings (medium)
+- [x] `/v2/organizations/{orgId}/memberships and /v2/teams/{teamId}/memberships` — membership tables joining users to the teams we already sync — currently no way to attribute a booking to a team member (high)
+- [x] `/v2/organizations/{orgId}/users` — lookup table resolving the user/host IDs carried on bookings and event types (high)
+- [x] `/v2/bookings/{bookingUid}/attendees` — attendee-level rows for each booking — the grain needed for no-show and guest analysis (high)
+- [x] `/v2/organizations/{orgId}/routing-forms/{routingFormId}/responses` — routing form submissions, the lead-qualification data that explains which bookings came from which route (high)
+- [x] `/v2/organizations/{orgId}/routing-forms` — lookup resolving the routing form IDs on responses and routed bookings (medium)
- [ ] `/v2/organizations/{orgId}/teams` — org-level team list; the existing teams table is the personal-scope one and misses org teams (medium)
- [ ] `/v2/organizations/{orgId}/attributes and /attributes/{attributeId}/options` — lookup tables for the org attributes used to segment and route users (medium)
- [ ] `/v2/me/ooo and /v2/organizations/{orgId}/users/{userId}/ooo` — out-of-office entries, needed to interpret availability and booking gaps (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/cal_com.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/cal_com.py
index e620644736ee..8d19d6da6647 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/cal_com.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/cal_com.py
@@ -1,23 +1,39 @@
-import dataclasses
+from collections.abc import Iterable, Iterator
from datetime import UTC, date, datetime
-from typing import Any, Optional
+from functools import partial
+from typing import Any, Optional, cast
+from urllib.parse import quote
+
+from posthog.dataclasses import frozen
from products.warehouse_sources.backend.temporal.data_imports.sources.cal_com.settings import (
+ BOOKING_ATTENDEES_ENDPOINT,
+ BOOKING_ATTENDEES_PARENT,
CAL_COM_ENDPOINTS,
CAL_COM_HOSTS,
+ ORG_PATH_PLACEHOLDER,
CalComEndpointConfig,
+ endpoint_requires_organization,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
BasePaginator,
JSONResponseCursorPaginator,
OffsetPaginator,
SinglePagePaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+ IncrementalConfig,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -26,15 +42,30 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
# one probe validates access to every list endpoint.
DEFAULT_PROBE_PATH = "/me"
DEFAULT_REGION = "us"
+REQUEST_TIMEOUT_SECONDS = 30
+
+# Seed for the afterCreatedAt/afterUpdatedAt filters before a table has a watermark.
+EPOCH_INCREMENTAL_VALUE = "1970-01-01T00:00:00.000Z"
+
+ORGANIZATION_REQUIRED_ERROR = (
+ "This Cal.com table holds organization data, but the account the API key belongs to is not in "
+ "a Cal.com organization. Deselect the organization tables, or reconnect with a key from an "
+ "account that has organization admin access."
+)
+@frozen
class CalComResumeConfig:
# Opaque `pagination.nextCursor` for cursor-paginated endpoints (bookings). A crashed sync
# resumes from the page after the last one yielded; merge dedupes the re-pulled page on `id`.
cursor: str | None = None
# `skip` offset for offset-paginated endpoints (webhooks).
skip: int | None = None
+ # Fan-out endpoints resume per parent — see
+ # `common.rest_source.__init__._make_paginate_dependent_resource`.
+ completed: list[str] | None = None
+ current: str | None = None
+ child_state: dict[str, Any] | None = None
def _host(region: str) -> str:
@@ -54,6 +85,28 @@ def _headers(config: CalComEndpointConfig) -> dict[str, str]:
return headers
+def _client_config(region: str, api_key: str, config: CalComEndpointConfig) -> ClientConfig:
+ return {
+ "base_url": _host(region),
+ "headers": _headers(config),
+ "auth": {"type": "bearer", "token": api_key},
+ # Rows carry contact details and free text the name-based sample scrubbers can't spot.
+ "capture": False,
+ }
+
+
+def _path_format_values(organization_id: int | None) -> dict[str, str]:
+ return {} if organization_id is None else {"orgId": str(organization_id)}
+
+
+def _format_path(path: str, organization_id: int | None) -> str:
+ if ORG_PATH_PLACEHOLDER not in path:
+ return path
+ if organization_id is None:
+ raise ValueError(ORGANIZATION_REQUIRED_ERROR)
+ return path.replace(ORG_PATH_PLACEHOLDER, str(organization_id))
+
+
def _format_incremental_value(value: Any) -> str:
# Cal.com's afterUpdatedAt/afterCreatedAt filters take ISO 8601 date strings; normalize to UTC
# with a Z suffix to avoid timezone ambiguity.
@@ -65,6 +118,10 @@ def _format_incremental_value(value: Any) -> str:
return str(value)
+def _resolve_incremental_field(config: CalComEndpointConfig, incremental_field: str | None) -> str | None:
+ return incremental_field or config.default_incremental_field
+
+
def _build_incremental_params(
config: CalComEndpointConfig,
should_use_incremental_field: bool,
@@ -74,7 +131,7 @@ def _build_incremental_params(
if not should_use_incremental_field or db_incremental_field_last_value is None:
return {}
- field = incremental_field or config.default_incremental_field
+ field = _resolve_incremental_field(config, incremental_field)
if field is None:
return {}
@@ -85,6 +142,32 @@ def _build_incremental_params(
return {param: _format_incremental_value(db_incremental_field_last_value)}
+def _build_sort_params(
+ config: CalComEndpointConfig,
+ should_use_incremental_field: bool,
+ incremental_field: str | None,
+) -> dict[str, Any]:
+ """Ask for the sort that matches the cursor, so the pipeline's watermark advances in order."""
+ param = config.default_sort_param
+ if should_use_incremental_field:
+ field = _resolve_incremental_field(config, incremental_field)
+ if field is not None:
+ param = config.sort_param_by_field.get(field, param)
+ return {param: "asc"} if param else {}
+
+
+def _incremental_window(config: CalComEndpointConfig, cursor_path: str) -> IncrementalConfig | None:
+ param = config.incremental_param_by_field.get(cursor_path)
+ if param is None:
+ return None
+ return {
+ "cursor_path": cursor_path,
+ "start_param": param,
+ "initial_value": EPOCH_INCREMENTAL_VALUE,
+ "convert": _format_incremental_value,
+ }
+
+
def _make_paginator(config: CalComEndpointConfig) -> BasePaginator:
if config.pagination == "cursor":
# Bookings pages carry {"pagination": {"nextCursor": ..., "hasMore": ...}}; a null/absent
@@ -101,39 +184,37 @@ def _make_paginator(config: CalComEndpointConfig) -> BasePaginator:
return SinglePagePaginator()
-def cal_com_source(
+def _top_level_items(
+ config: CalComEndpointConfig,
api_key: str,
- endpoint: str,
+ region: str,
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[CalComResumeConfig],
- region: str = DEFAULT_REGION,
- should_use_incremental_field: bool = False,
- db_incremental_field_last_value: Optional[Any] = None,
- incremental_field: str | None = None,
-) -> SourceResponse:
- config = CAL_COM_ENDPOINTS[endpoint]
-
+ organization_id: int | None,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+ incremental_field: str | None,
+) -> Iterable[Any]:
params: dict[str, Any] = _build_incremental_params(
config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
)
+ params.update(_build_sort_params(config, should_use_incremental_field, incremental_field))
if config.pagination == "cursor":
# Bookings `limit` maxes at 100; a larger value is rejected with 400 Bad Request. The
# offset paginator injects its own `take`/`skip` pair.
params["limit"] = config.page_size
+ client_config = _client_config(region, api_key, config)
+ client_config["paginator"] = _make_paginator(config)
+
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": _host(region),
- "headers": _headers(config),
- "auth": {"type": "bearer", "token": api_key},
- "paginator": _make_paginator(config),
- },
+ "client": client_config,
"resources": [
{
- "name": endpoint,
+ "name": config.name,
"endpoint": {
- "path": config.path,
+ "path": _format_path(config.path, organization_id),
"params": params,
# Every v2 endpoint wraps its payload as {"status": "success", "data": ...}.
# A 200 body without `data` means the response shape changed — fail loud
@@ -165,7 +246,7 @@ def cal_com_source(
elif config.pagination == "offset" and state.get("offset") is not None:
resumable_source_manager.save_state(CalComResumeConfig(skip=int(state["offset"])))
- resource = rest_api_resource(
+ return rest_api_resource(
rest_config,
team_id,
job_id,
@@ -174,21 +255,272 @@ def cal_com_source(
initial_paginator_state=initial_paginator_state,
)
+
+def _fanout_items(
+ config: CalComEndpointConfig,
+ api_key: str,
+ region: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[CalComResumeConfig],
+ organization_id: int | None,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+ incremental_field: str | None,
+) -> Iterable[Any]:
+ fanout = config.fanout
+ assert fanout is not None
+ parent_config = CAL_COM_ENDPOINTS[fanout.parent_name]
+
+ initial_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None and (resume.completed or resume.current):
+ initial_state = {
+ "completed": resume.completed or [],
+ "current": resume.current,
+ "child_state": resume.child_state,
+ }
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state is not None:
+ resumable_source_manager.save_state(
+ CalComResumeConfig(
+ completed=state.get("completed"),
+ current=state.get("current"),
+ child_state=state.get("child_state"),
+ )
+ )
+
+ # A 200 without the `data` envelope means the shape changed, on either hop.
+ parent_endpoint: Endpoint = {
+ "paginator": _make_paginator(parent_config),
+ "data_selector": "data",
+ "data_selector_required": True,
+ }
+ child_endpoint: Endpoint = {
+ "paginator": _make_paginator(config),
+ "data_selector": "data",
+ "data_selector_required": True,
+ }
+
+ return cast(
+ Iterable[Any],
+ build_dependent_resource(
+ endpoint_configs=CAL_COM_ENDPOINTS,
+ child_endpoint=config.name,
+ fanout=fanout,
+ client_config=_client_config(region, api_key, config),
+ path_format_values=_path_format_values(organization_id),
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field,
+ incremental_config_factory=lambda cursor_path: _incremental_window(config, cursor_path),
+ # The offset paginators inject their own `take`/`skip`.
+ page_size_param=None,
+ parent_endpoint_extra=parent_endpoint,
+ child_endpoint_extra=child_endpoint,
+ child_params_extra=_build_sort_params(config, should_use_incremental_field, incremental_field) or None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_state,
+ ),
+ )
+
+
+def _booking_attendees_items(
+ config: CalComEndpointConfig,
+ api_key: str,
+ region: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[CalComResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+ incremental_field: str | None,
+) -> Iterator[list[dict[str, Any]]]:
+ """Yield one batch of attendee rows per page of bookings.
+
+ Hand-rolled rather than a dependent resource because the two hops need different
+ `cal-api-version` headers and a dependent resource sends one set of client headers for both.
+ """
+ parent_config = CAL_COM_ENDPOINTS[BOOKING_ATTENDEES_PARENT]
+
+ # Bounding the bookings walk is what keeps an incremental sync off every booking ever made.
+ parent_params: dict[str, Any] = _build_incremental_params(
+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
+ )
+ parent_params["limit"] = parent_config.page_size
+
+ parent_client_config = _client_config(region, api_key, parent_config)
+ parent_client_config["paginator"] = _make_paginator(parent_config)
+
+ parent_rest_config: RESTAPIConfig = {
+ "client": parent_client_config,
+ "resources": [
+ {
+ "name": BOOKING_ATTENDEES_PARENT,
+ "endpoint": {
+ "path": parent_config.path,
+ "params": parent_params,
+ "data_selector": "data",
+ "data_selector_required": True,
+ },
+ }
+ ],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None and resume.cursor is not None:
+ initial_paginator_state = {"cursor": resume.cursor}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # The hook runs when this generator asks for the next page, so after its rows are out.
+ if state and state.get("cursor") is not None:
+ resumable_source_manager.save_state(CalComResumeConfig(cursor=state["cursor"]))
+
+ bookings = rest_api_resource(
+ parent_rest_config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ # capture=False for the same reason as `_client_config`: attendee rows are contact details.
+ session = make_tracked_session(redact_values=(api_key,), capture=False)
+ headers = {**_headers(config), "Authorization": f"Bearer {api_key}"}
+ base_url = _host(region)
+
+ for page in bookings:
+ rows: list[dict[str, Any]] = []
+ for booking in page:
+ uid = booking.get("uid")
+ if uid is None:
+ continue
+ response = session.get(
+ f"{base_url}/bookings/{quote(str(uid), safe='')}/attendees",
+ headers=headers,
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ if response.status_code == 404:
+ # The booking went away between the listing and this fetch.
+ continue
+ response.raise_for_status()
+ body = response.json()
+ attendees = body.get("data") if isinstance(body, dict) else None
+ if not isinstance(attendees, list):
+ raise ValueError(f"Cal.com attendees response for booking '{uid}' matched nothing for `data`")
+ for attendee in attendees:
+ rows.append(
+ {
+ **attendee,
+ "bookingUid": uid,
+ "bookingCreatedAt": booking.get("createdAt"),
+ "bookingUpdatedAt": booking.get("updatedAt"),
+ }
+ )
+ if rows:
+ yield rows
+
+
+def cal_com_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[CalComResumeConfig],
+ region: str = DEFAULT_REGION,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+ organization_id: int | None = None,
+) -> SourceResponse:
+ config = CAL_COM_ENDPOINTS[endpoint]
+ if organization_id is None and endpoint_requires_organization(endpoint):
+ raise ValueError(ORGANIZATION_REQUIRED_ERROR)
+
+ items: Any
+ if endpoint == BOOKING_ATTENDEES_ENDPOINT:
+ items = partial(
+ _booking_attendees_items,
+ config,
+ api_key,
+ region,
+ team_id,
+ job_id,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ incremental_field,
+ )
+ else:
+ builder = _fanout_items if config.fanout is not None else _top_level_items
+ resource = builder(
+ config,
+ api_key,
+ region,
+ team_id,
+ job_id,
+ resumable_source_manager,
+ organization_id,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ incremental_field,
+ )
+ items = lambda: resource # noqa: E731
+
return SourceResponse(
name=endpoint,
- items=lambda: resource,
+ items=items,
primary_keys=config.primary_keys,
partition_count=1,
partition_size=1,
partition_mode="datetime" if config.partition_key else None,
partition_format="month" if config.partition_key else None,
partition_keys=[config.partition_key] if config.partition_key else None,
- # Bookings walk `Booking.uuid DESC` (newest-created first) when no status filter is passed,
- # and the opaque cursor doesn't honor sortUpdatedAt/sortCreated. "desc" makes the pipeline
- # commit the incremental watermark only after a complete sync, which stays correct
- # regardless of arrival order.
- sort_mode="desc" if config.incremental_fields else "asc",
+ # "desc" holds the watermark until a sync completes, for the newest-first endpoints.
+ sort_mode=config.sort_mode,
+ )
+
+
+def resolve_organization_id(api_key: str, region: str = DEFAULT_REGION) -> int | None:
+ """The id of the Cal.com organization the API key's account belongs to, or None if it has none.
+
+ Organization-scoped paths carry the id, and Cal.com does not expose it anywhere the user can
+ read it off, so it is resolved from the key's own profile rather than asked for on the form.
+ """
+ session = make_tracked_session(redact_values=(api_key,))
+ response = session.get(
+ f"{_host(region)}{DEFAULT_PROBE_PATH}",
+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ response.raise_for_status()
+ data = response.json().get("data") or {}
+ organization_id = data.get("organizationId")
+ return int(organization_id) if organization_id is not None else None
+
+
+def check_organization_access(api_key: str, organization_id: int, region: str = DEFAULT_REGION) -> str | None:
+ """None when the key can read organization data, otherwise why it cannot."""
+ ok, status = validate_via_probe(
+ lambda: make_tracked_session(redact_values=(api_key,)),
+ f"{_host(region)}/organizations/{organization_id}/memberships",
+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
)
+ if ok:
+ return None
+ if status == 403:
+ return (
+ "This API key belongs to an organization member without admin access, so Cal.com will "
+ "not return organization data. Reconnect with a key from an organization admin."
+ )
+ return None
def validate_credentials(api_key: str, region: str = DEFAULT_REGION) -> tuple[bool, str | None]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/canonical_descriptions.py
index a4f39fae012a..2373cdea1c39 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/canonical_descriptions.py
@@ -102,6 +102,109 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"payloadTemplate": "The template of the payload sent to the subscriber URL.",
},
},
+ "organization_memberships": {
+ "description": "A membership joining a user to the Cal.com organization the API key's account belongs to.",
+ "docs_url": "https://cal.com/docs/api-reference/v2/orgs-memberships/get-all-memberships",
+ "columns": {
+ "id": "The unique numeric ID of the membership.",
+ "userId": "The ID of the user the membership belongs to.",
+ "teamId": "The ID of the organization the membership is in.",
+ "accepted": "Whether the user has accepted the invitation to the organization.",
+ "role": "The user's role in the organization (MEMBER, ADMIN, or OWNER).",
+ "disableImpersonation": "Whether organization admins are blocked from impersonating the user.",
+ "user": "The profile of the user the membership belongs to.",
+ "attributes": "The organization attributes assigned to the user, used to segment and route them.",
+ },
+ },
+ "team_memberships": {
+ "description": "A membership joining a user to one of the teams in the teams table.",
+ "docs_url": "https://cal.com/docs/api-reference/v2/teams-memberships/get-all-memberships",
+ "columns": {
+ "id": "The unique numeric ID of the membership.",
+ "userId": "The ID of the user the membership belongs to.",
+ "teamId": "The ID of the team the membership is in.",
+ "accepted": "Whether the user has accepted the invitation to the team.",
+ "role": "The user's role in the team (MEMBER, ADMIN, or OWNER).",
+ "disableImpersonation": "Whether team admins are blocked from impersonating the user.",
+ "user": "The profile of the user the membership belongs to.",
+ },
+ },
+ "organization_users": {
+ "description": "A user in the Cal.com organization. Resolves the user and host IDs carried on bookings and event types.",
+ "docs_url": "https://cal.com/docs/api-reference/v2/orgs-users/get-all-users",
+ "columns": {
+ "id": "The ID of the user.",
+ "username": "The username of the user.",
+ "name": "The name of the user.",
+ "email": "The email of the user.",
+ "emailVerified": "The date when the email was verified.",
+ "bio": "The bio of the user.",
+ "avatarUrl": "The URL of the user's avatar.",
+ "timeZone": "The time zone of the user.",
+ "weekStart": "The week start day of the user.",
+ "appTheme": "The app theme of the user.",
+ "theme": "The theme of the user.",
+ "defaultScheduleId": "The ID of the default schedule for the user.",
+ "locale": "The locale of the user.",
+ "timeFormat": "The time format of the user.",
+ "hideBranding": "Whether to hide branding for the user.",
+ "brandColor": "The brand color of the user.",
+ "darkBrandColor": "The dark brand color of the user.",
+ "allowDynamicBooking": "Whether dynamic booking is allowed for the user.",
+ "createdDate": "The date when the user was created.",
+ "verified": "Whether the user is verified.",
+ "invitedTo": "The ID of the user who invited this user.",
+ "metadata": "Custom metadata attached to the user.",
+ "profile": "The user's profile within the organization context.",
+ },
+ },
+ "booking_attendees": {
+ "description": "One row per attendee of a booking, the grain needed for no-show and guest analysis. The booking columns are copied from the parent booking.",
+ "docs_url": "https://cal.com/docs/api-reference/v2/bookings-attendees/get-all-attendees-for-a-booking",
+ "columns": {
+ "id": "The unique numeric ID of the attendee.",
+ "name": "The name of the attendee.",
+ "email": "The email address of the attendee.",
+ "displayEmail": "The attendee's email, cleaned up for display.",
+ "timeZone": "The time zone of the attendee.",
+ "language": "The attendee's preferred language.",
+ "absent": "Whether the attendee was marked as a no-show for the booking.",
+ "phoneNumber": "The phone number of the attendee.",
+ "bookingUid": "The UID of the booking the attendee belongs to. Joins to the bookings table's uid.",
+ "bookingCreatedAt": "When the booking was created.",
+ "bookingUpdatedAt": "When the booking was last updated.",
+ },
+ },
+ "routing_forms": {
+ "description": "A routing form in the organization, which qualifies a lead and sends them to the right event type.",
+ "docs_url": "https://cal.com/docs/api-reference/v2/orgs-routing-forms/get-organization-routing-forms",
+ "columns": {
+ "id": "The unique ID of the routing form.",
+ "name": "The name of the routing form.",
+ "description": "The description of the routing form.",
+ "position": "The position of the routing form in the owner's list.",
+ "routes": "The routing rules that decide where a submission is sent.",
+ "fields": "The questions the routing form asks.",
+ "settings": "The settings of the routing form.",
+ "userId": "The ID of the user who owns the routing form.",
+ "teamId": "The ID of the team the routing form belongs to.",
+ "disabled": "Whether the routing form is disabled.",
+ "createdAt": "When the routing form was created.",
+ "updatedAt": "When the routing form was last updated.",
+ },
+ },
+ "routing_form_responses": {
+ "description": "A submission of a routing form, including the answers given and the booking it routed to.",
+ "docs_url": "https://cal.com/docs/api-reference/v2/orgs-routing-forms/get-routing-form-responses",
+ "columns": {
+ "id": "The unique numeric ID of the response.",
+ "formId": "The ID of the routing form that was submitted.",
+ "formFillerId": "The ID Cal.com assigns to the person who filled in the form.",
+ "routedToBookingUid": "The UID of the booking this submission routed to. Joins to the bookings table's uid.",
+ "response": "The answers given to the routing form's questions, keyed by field ID.",
+ "createdAt": "When the routing form was submitted.",
+ },
+ },
"me": {
"description": "The profile of the user the API key belongs to.",
"docs_url": "https://cal.com/docs/api-reference/v2/me/get-my-profile",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/settings.py
index 01d3559cb72e..ad5cb51bf728 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/settings.py
@@ -1,6 +1,10 @@
from dataclasses import dataclass, field
from typing import Literal, Optional
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
PaginationStyle = Literal["cursor", "offset", "none"]
@@ -13,6 +17,9 @@ CAL_COM_HOSTS: dict[str, str] = {
"eu": "https://api.cal.eu/v2",
}
+# Cal.com's organization endpoints page with `skip`/`take`, and document 250 as the largest page.
+ORG_PAGE_SIZE = 250
+
_BOOKING_INCREMENTAL_FIELDS: list[IncrementalField] = [
{
"label": "updatedAt",
@@ -29,7 +36,14 @@ _BOOKING_INCREMENTAL_FIELDS: list[IncrementalField] = [
]
-@dataclass
+# Bound from the API key's own profile (`/me`), not from a connection-form field.
+ORG_PATH_PLACEHOLDER = "{orgId}"
+
+
+# Mutable by choice, not oversight: instances flow into `build_dependent_resource`'s
+# `endpoint_configs: Mapping[str, FanoutEndpointLike]`, and mypy treats a frozen dataclass's fields
+# as read-only, which is incompatible with that Protocol's plain (read-write) attributes.
+@dataclass(frozen=False)
class CalComEndpointConfig:
name: str
path: str
@@ -47,14 +61,26 @@ class CalComEndpointConfig:
# Maps an incremental field name to the server-side query param that filters on it.
incremental_param_by_field: dict[str, str] = field(default_factory=dict)
default_incremental_field: Optional[str] = None
+ # Sorting on the cursor field is what makes the watermark advance correctly.
+ sort_param_by_field: dict[str, str] = field(default_factory=dict)
+ # Keeps offset pagination stable while rows are inserted mid-sync.
+ default_sort_param: Optional[str] = None
+ # Order rows actually arrive in, which the pipeline trusts to checkpoint the watermark.
+ sort_mode: Literal["asc", "desc"] = "asc"
# Max items per page. Cal.com caps this per endpoint and rejects larger values with 400: the
# bookings `limit` maxes at 100, while the webhooks `take` allows up to 250.
page_size: int = 100
+ fanout: Optional[DependentEndpointConfig] = None
+ @property
+ def requires_organization(self) -> bool:
+ return ORG_PATH_PLACEHOLDER in self.path
-# Cal.com API v2 list endpoints (https://cal.com/docs/api-reference/v2/introduction). Only bookings
-# exposes server-side timestamp filters (afterUpdatedAt / afterCreatedAt), so it is the only
-# incremental-capable endpoint; the rest are small, unpaginated catalogs synced via full refresh.
+
+# Cal.com API v2 endpoints (https://cal.com/docs/api-reference/v2/introduction). Only bookings and
+# the routing-form endpoints expose server-side timestamp filters (afterUpdatedAt /
+# afterCreatedAt), so they are the incremental-capable ones; the rest are catalogs and membership
+# lists synced via full refresh.
CAL_COM_ENDPOINTS: dict[str, CalComEndpointConfig] = {
"bookings": CalComEndpointConfig(
name="bookings",
@@ -68,6 +94,8 @@ CAL_COM_ENDPOINTS: dict[str, CalComEndpointConfig] = {
"createdAt": "afterCreatedAt",
},
default_incremental_field="updatedAt",
+ # Bookings walk `Booking.uuid DESC`, and the cursor ignores sortUpdatedAt/sortCreated.
+ sort_mode="desc",
),
"event_types": CalComEndpointConfig(
name="event_types",
@@ -94,8 +122,102 @@ CAL_COM_ENDPOINTS: dict[str, CalComEndpointConfig] = {
path="/me",
single_object=True,
),
+ "organization_memberships": CalComEndpointConfig(
+ name="organization_memberships",
+ path="/organizations/{orgId}/memberships",
+ pagination="offset",
+ page_size=ORG_PAGE_SIZE,
+ ),
+ "organization_users": CalComEndpointConfig(
+ name="organization_users",
+ path="/organizations/{orgId}/users",
+ pagination="offset",
+ page_size=ORG_PAGE_SIZE,
+ partition_key="createdDate",
+ ),
+ # The docs never call the membership id unique beyond its team, so `teamId` stays in the key.
+ "team_memberships": CalComEndpointConfig(
+ name="team_memberships",
+ path="/teams/{teamId}/memberships",
+ pagination="offset",
+ page_size=ORG_PAGE_SIZE,
+ primary_keys=["teamId", "id"],
+ fanout=DependentEndpointConfig(
+ parent_name="teams",
+ resolve_param="teamId",
+ resolve_field="id",
+ include_from_parent=[],
+ # A team removed between the parent listing and this fetch must not fail the sync.
+ child_response_actions=[{"status_code": 404, "action": "ignore"}],
+ ),
+ ),
+ "routing_forms": CalComEndpointConfig(
+ name="routing_forms",
+ path="/organizations/{orgId}/routing-forms",
+ pagination="offset",
+ page_size=ORG_PAGE_SIZE,
+ partition_key="createdAt",
+ incremental_fields=[incremental_field("updatedAt"), incremental_field("createdAt")],
+ incremental_param_by_field={"updatedAt": "afterUpdatedAt", "createdAt": "afterCreatedAt"},
+ default_incremental_field="updatedAt",
+ sort_param_by_field={"updatedAt": "sortUpdatedAt", "createdAt": "sortCreatedAt"},
+ default_sort_param="sortCreatedAt",
+ ),
+ # A response carries `createdAt` but no update timestamp, so `createdAt` is the only cursor.
+ "routing_form_responses": CalComEndpointConfig(
+ name="routing_form_responses",
+ path="/organizations/{orgId}/routing-forms/{routingFormId}/responses",
+ pagination="offset",
+ page_size=ORG_PAGE_SIZE,
+ primary_keys=["formId", "id"],
+ partition_key="createdAt",
+ incremental_fields=[incremental_field("createdAt")],
+ incremental_param_by_field={"createdAt": "afterCreatedAt"},
+ default_incremental_field="createdAt",
+ sort_param_by_field={"createdAt": "sortCreatedAt"},
+ default_sort_param="sortCreatedAt",
+ fanout=DependentEndpointConfig(
+ parent_name="routing_forms",
+ resolve_param="routingFormId",
+ resolve_field="id",
+ include_from_parent=[],
+ parent_params={"sortCreatedAt": "asc"},
+ child_response_actions=[{"status_code": 404, "action": "ignore"}],
+ ),
+ ),
+ # An attendee row has no timestamp of its own, so the booking's are projected onto it and
+ # `incremental_param_by_field` names params on the PARENT request, bounding the bookings walk.
+ "booking_attendees": CalComEndpointConfig(
+ name="booking_attendees",
+ path="/bookings/{bookingUid}/attendees",
+ api_version="2024-08-13",
+ primary_keys=["bookingUid", "id"],
+ partition_key="bookingCreatedAt",
+ incremental_fields=[incremental_field("bookingUpdatedAt"), incremental_field("bookingCreatedAt")],
+ incremental_param_by_field={
+ "bookingUpdatedAt": "afterUpdatedAt",
+ "bookingCreatedAt": "afterCreatedAt",
+ },
+ default_incremental_field="bookingUpdatedAt",
+ sort_mode="desc",
+ ),
}
+# The one fan-out the shared dependent-resource helper cannot serve: the child requires
+# `cal-api-version: 2024-08-13`, its bookings parent 2026-05-01, and a dependent resource sends
+# one set of client headers for both hops.
+BOOKING_ATTENDEES_ENDPOINT = "booking_attendees"
+BOOKING_ATTENDEES_PARENT = "bookings"
+
+
+def endpoint_requires_organization(name: str) -> bool:
+ """Whether syncing ``name`` needs the API key's organization id, directly or via its parent."""
+ config = CAL_COM_ENDPOINTS[name]
+ if config.requires_organization:
+ return True
+ return config.fanout is not None and CAL_COM_ENDPOINTS[config.fanout.parent_name].requires_organization
+
+
ENDPOINTS = tuple(CAL_COM_ENDPOINTS.keys())
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/source.py
index 5ce556010d54..48b90f887705 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/source.py
@@ -12,14 +12,18 @@ from posthog.schema import (
)
from products.warehouse_sources.backend.temporal.data_imports.sources.cal_com.cal_com import (
+ ORGANIZATION_REQUIRED_ERROR,
CalComResumeConfig,
cal_com_source,
+ check_organization_access,
+ resolve_organization_id,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.cal_com.settings import (
CAL_COM_ENDPOINTS,
ENDPOINTS,
INCREMENTAL_FIELDS,
+ endpoint_requires_organization,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
@@ -56,7 +60,9 @@ class CalComSource(ResumableSource[CalComSourceConfig, CalComResumeConfig]):
releaseStatus=ReleaseStatus.ALPHA,
caption="""Enter your Cal.com API key to pull your scheduling data into the PostHog Data warehouse.
-You can create an API key under **Settings → Security → API keys** in [Cal.com](https://app.cal.com/settings/developer/api-keys). The key grants read access to your bookings, event types, schedules, teams, and webhooks.
+You can create an API key under **Settings → Security → API keys** in [Cal.com](https://app.cal.com/settings/developer/api-keys). The key grants read access to your bookings, attendees, event types, schedules, teams, and webhooks.
+
+The organization tables (memberships, users, and routing forms) need a key from a Cal.com organization admin. If your account isn't in an organization, leave those tables unselected.
Pick the region your Cal.com account lives in. Choose EU if you sign in at cal.eu, since a key from one region is not valid in the other.
""",
@@ -100,6 +106,8 @@ Pick the region your Cal.com account lives in. Choose EU if you sign in at cal.e
return {
"401 Client Error: Unauthorized": "Your Cal.com API key is invalid, has been revoked, or belongs to Cal.com's other region. Check the selected region, or create a new API key under Settings → Security → API keys in Cal.com, then reconnect.",
"403 Client Error: Forbidden": "Your Cal.com API key does not have access to this data. Check the key owner's permissions in Cal.com, then reconnect.",
+ # Retrying cannot conjure an organization for an account that has none.
+ "is not in a Cal.com organization": ORGANIZATION_REQUIRED_ERROR,
}
def get_schemas(
@@ -111,10 +119,30 @@ Pick the region your Cal.com account lives in. Choose EU if you sign in at cal.e
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- # Only bookings exposes server-side timestamp filters (afterUpdatedAt / afterCreatedAt), so
- # it is the only endpoint that supports incremental sync.
return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+ def get_endpoint_permissions(
+ self, config: CalComSourceConfig, team_id: int, endpoints: list[str], api_version: str | None = None
+ ) -> dict[str, str | None]:
+ # Report a table that can only fail here, rather than letting the user pick it.
+ org_endpoints = {
+ name for name in endpoints if name in CAL_COM_ENDPOINTS and endpoint_requires_organization(name)
+ }
+ if not org_endpoints:
+ return dict.fromkeys(endpoints)
+
+ try:
+ organization_id = resolve_organization_id(config.api_key, config.region)
+ reason = (
+ ORGANIZATION_REQUIRED_ERROR
+ if organization_id is None
+ else check_organization_access(config.api_key, organization_id, config.region)
+ )
+ except Exception: # noqa: BLE001 — an unreachable probe must not hide the tables
+ reason = None
+
+ return {name: reason if name in org_endpoints else None for name in endpoints}
+
def validate_credentials(
self,
config: CalComSourceConfig,
@@ -137,6 +165,13 @@ Pick the region your Cal.com account lives in. Choose EU if you sign in at cal.e
if inputs.schema_name not in CAL_COM_ENDPOINTS:
raise ValueError(f"Unknown Cal.com schema '{inputs.schema_name}'")
+ # Resolved in sync source-build context, not from the pipeline's iterator threads.
+ organization_id = (
+ resolve_organization_id(config.api_key, config.region)
+ if endpoint_requires_organization(inputs.schema_name)
+ else None
+ )
+
return cal_com_source(
api_key=config.api_key,
endpoint=inputs.schema_name,
@@ -149,4 +184,5 @@ Pick the region your Cal.com account lives in. Choose EU if you sign in at cal.e
if inputs.should_use_incremental_field
else None,
incremental_field=inputs.incremental_field,
+ organization_id=organization_id,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/tests/test_cal_com.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/tests/test_cal_com.py
index 1bd427b30753..5b4ba5c08080 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/tests/test_cal_com.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/tests/test_cal_com.py
@@ -12,15 +12,19 @@ from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.cal_com.cal_com import (
CalComResumeConfig,
cal_com_source,
+ check_organization_access,
+ resolve_organization_id,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.cal_com.settings import (
+ BOOKING_ATTENDEES_ENDPOINT,
CAL_COM_ENDPOINTS,
CAL_COM_HOSTS,
ENDPOINTS,
)
US_BASE_URL = CAL_COM_HOSTS["us"]
+ORG_ID = 77
REJECTED_MESSAGE = (
"Cal.com rejected this API key. Check the key, and check that the selected region matches your Cal.com account."
)
@@ -388,11 +392,11 @@ class TestValidateCredentials:
class TestCalComSourceResponse:
@parameterized.expand([(e,) for e in ENDPOINTS])
@mock.patch(CLIENT_SESSION_PATCH)
- def test_source_response_shape(self, endpoint: str, MockSession) -> None:
+ def test_every_endpoint_builds_a_response_named_after_its_schema(self, endpoint: str, MockSession) -> None:
+ # The name is the Delta subdirectory: a wrong one writes where nothing reads.
MockSession.return_value.headers = {}
- response = _source(endpoint)
+ response = _source(endpoint, organization_id=ORG_ID)
assert response.name == endpoint
- assert response.primary_keys == ["id"]
@mock.patch(CLIENT_SESSION_PATCH)
def test_bookings_partitions_on_stable_created_at(self, MockSession) -> None:
@@ -403,10 +407,314 @@ class TestCalComSourceResponse:
# Bookings arrive newest-first, so the watermark must only commit after a complete sync.
assert response.sort_mode == "desc"
- @parameterized.expand([(e,) for e in ENDPOINTS if e != "bookings"])
+ def test_partition_keys_are_creation_timestamps(self) -> None:
+ # Partitioning on an updated-at style field rewrites every partition on every sync.
+ keys = [config.partition_key for config in CAL_COM_ENDPOINTS.values() if config.partition_key]
+ assert [key for key in keys if "updated" in key.lower()] == []
+
+ def test_fanned_out_endpoints_key_on_their_parent_too(self) -> None:
+ # A key unique only within one parent seeds duplicates every later merge multi-matches.
+ children = [name for name, config in CAL_COM_ENDPOINTS.items() if config.fanout] + [BOOKING_ATTENDEES_ENDPOINT]
+ assert [name for name in children if len(CAL_COM_ENDPOINTS[name].primary_keys) < 2] == []
+
+
+class TestOrganizationEndpoints:
+ @parameterized.expand(
+ [
+ ("organization_memberships", f"{US_BASE_URL}/organizations/{ORG_ID}/memberships"),
+ ("organization_users", f"{US_BASE_URL}/organizations/{ORG_ID}/users"),
+ ("routing_forms", f"{US_BASE_URL}/organizations/{ORG_ID}/routing-forms"),
+ ]
+ )
@mock.patch(CLIENT_SESSION_PATCH)
- def test_full_refresh_endpoints_do_not_partition(self, endpoint: str, MockSession) -> None:
- MockSession.return_value.headers = {}
- response = _source(endpoint)
- assert response.partition_mode is None
- assert response.sort_mode == "asc"
+ def test_resolved_org_id_replaces_the_path_placeholder(self, endpoint: str, expected_url: str, MockSession) -> None:
+ session = MockSession.return_value
+ requested_urls: list[str] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ requested_urls.append(request.url)
+ return mock.MagicMock()
+
+ session.headers = {}
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = [_response({"data": [{"id": 1}]})]
+
+ assert _rows(_source(endpoint, organization_id=ORG_ID)) == [{"id": 1}]
+ assert requested_urls == [expected_url]
+
+ @parameterized.expand(
+ [
+ ("organization_memberships",),
+ ("organization_users",),
+ ("routing_forms",),
+ # Reached through an organization-scoped parent rather than its own path.
+ ("routing_form_responses",),
+ ]
+ )
+ def test_organization_tables_refuse_to_sync_without_one(self, endpoint: str) -> None:
+ with pytest.raises(ValueError, match="not in a Cal.com organization"):
+ _source(endpoint)
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_org_listings_walk_skip_and_take(self, MockSession) -> None:
+ session = MockSession.return_value
+ page_size = CAL_COM_ENDPOINTS["organization_users"].page_size
+ full_page = [{"id": i} for i in range(page_size)]
+ params = _wire(session, [_response({"data": full_page}), _response({"data": [{"id": "last"}]})])
+
+ rows = _rows(_source("organization_users", organization_id=ORG_ID))
+
+ assert len(rows) == page_size + 1
+ assert [p["skip"] for p in params] == [0, page_size]
+ assert params[0]["take"] == page_size
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_routing_forms_sort_matches_the_chosen_cursor(self, MockSession) -> None:
+ # A sort that disagrees with the cursor corrupts the watermark.
+ session = MockSession.return_value
+ params = _wire(session, [_response({"data": [{"id": "f1"}]})])
+
+ _rows(
+ _source(
+ "routing_forms",
+ organization_id=ORG_ID,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),
+ incremental_field="updatedAt",
+ )
+ )
+
+ assert params[0]["sortUpdatedAt"] == "asc"
+ assert params[0]["afterUpdatedAt"] == "2026-01-02T03:04:05.000Z"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_routing_forms_sort_by_creation_on_a_full_refresh(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_response({"data": [{"id": "f1"}]})])
+
+ _rows(_source("routing_forms", organization_id=ORG_ID))
+
+ assert params[0]["sortCreatedAt"] == "asc"
+ assert "afterCreatedAt" not in params[0]
+
+
+class TestFanoutEndpoints:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_team_memberships_fetch_once_per_team(self, MockSession) -> None:
+ session = MockSession.return_value
+ requested_urls: list[str] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ requested_urls.append(request.url)
+ return mock.MagicMock()
+
+ session.headers = {}
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = [
+ _response({"data": [{"id": 10}, {"id": 11}]}),
+ _response({"data": [{"id": 1, "teamId": 10}]}),
+ _response({"data": [{"id": 2, "teamId": 11}]}),
+ ]
+
+ rows = _rows(_source("team_memberships"))
+
+ assert rows == [{"id": 1, "teamId": 10}, {"id": 2, "teamId": 11}]
+ assert requested_urls == [
+ f"{US_BASE_URL}/teams",
+ f"{US_BASE_URL}/teams/10/memberships",
+ f"{US_BASE_URL}/teams/11/memberships",
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_a_team_removed_mid_sync_does_not_fail_the_run(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response({"data": [{"id": 10}, {"id": 11}]}),
+ _response({}, status_code=404, reason="Not Found"),
+ _response({"data": [{"id": 2, "teamId": 11}]}),
+ ],
+ )
+
+ assert _rows(_source("team_memberships")) == [{"id": 2, "teamId": 11}]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_routing_form_responses_filter_each_form_at_the_watermark(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(
+ session,
+ [
+ _response({"data": [{"id": "f1"}]}),
+ _response({"data": [{"id": 1, "formId": "f1"}]}),
+ ],
+ )
+
+ rows = _rows(
+ _source(
+ "routing_form_responses",
+ organization_id=ORG_ID,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),
+ incremental_field="createdAt",
+ )
+ )
+
+ assert rows == [{"id": 1, "formId": "f1"}]
+ # The parent listing takes no watermark of its own; only the child is windowed.
+ assert params[1]["afterCreatedAt"] == "2026-01-02T03:04:05.000Z"
+ assert params[1]["sortCreatedAt"] == "asc"
+
+
+class TestBookingAttendees:
+ BOOKING = {"uid": "bk1", "createdAt": "2026-01-01T00:00:00.000Z", "updatedAt": "2026-01-05T00:00:00.000Z"}
+
+ def _attendee_session(self, *responses: Response) -> mock.MagicMock:
+ session = mock.MagicMock()
+ session.get.side_effect = list(responses)
+ return session
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ @mock.patch(CAL_COM_SESSION_PATCH)
+ def test_attendee_rows_carry_the_booking_they_belong_to(self, MockCalSession, MockClientSession) -> None:
+ # Without these the table cannot be joined to bookings or synced incrementally.
+ _wire(MockClientSession.return_value, [_page([self.BOOKING])])
+ MockCalSession.return_value = self._attendee_session(
+ _response({"data": [{"id": 5, "email": "[email protected]", "absent": True}]})
+ )
+
+ rows = _rows(_source(BOOKING_ATTENDEES_ENDPOINT))
+
+ assert rows == [
+ {
+ "id": 5,
+ "email": "[email protected]",
+ "absent": True,
+ "bookingUid": "bk1",
+ "bookingCreatedAt": "2026-01-01T00:00:00.000Z",
+ "bookingUpdatedAt": "2026-01-05T00:00:00.000Z",
+ }
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ @mock.patch(CAL_COM_SESSION_PATCH)
+ def test_each_hop_sends_the_version_that_endpoint_requires(self, MockCalSession, MockClientSession) -> None:
+ # Attendees 404 without 2024-08-13; the bookings listing needs 2026-05-01.
+ client_session = MockClientSession.return_value
+ _wire(client_session, [_page([self.BOOKING])])
+ attendee_session = self._attendee_session(_response({"data": []}))
+ MockCalSession.return_value = attendee_session
+
+ _rows(_source(BOOKING_ATTENDEES_ENDPOINT))
+
+ assert client_session.headers["cal-api-version"] == "2026-05-01"
+ assert attendee_session.get.call_args.kwargs["headers"]["cal-api-version"] == "2024-08-13"
+ assert attendee_session.get.call_args.args[0] == f"{US_BASE_URL}/bookings/bk1/attendees"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ @mock.patch(CAL_COM_SESSION_PATCH)
+ def test_a_booking_removed_mid_sync_does_not_fail_the_run(self, MockCalSession, MockClientSession) -> None:
+ _wire(MockClientSession.return_value, [_page([self.BOOKING, {**self.BOOKING, "uid": "bk2"}])])
+ MockCalSession.return_value = self._attendee_session(
+ _response({}, status_code=404, reason="Not Found"),
+ _response({"data": [{"id": 6}]}),
+ )
+
+ assert [row["bookingUid"] for row in _rows(_source(BOOKING_ATTENDEES_ENDPOINT))] == ["bk2"]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ @mock.patch(CAL_COM_SESSION_PATCH)
+ def test_incremental_sync_bounds_the_bookings_walk(self, MockCalSession, MockClientSession) -> None:
+ # Without the window every sync re-reads every booking's attendees, one request each.
+ params = _wire(MockClientSession.return_value, [_page([self.BOOKING])])
+ MockCalSession.return_value = self._attendee_session(_response({"data": [{"id": 5}]}))
+
+ _rows(
+ _source(
+ BOOKING_ATTENDEES_ENDPOINT,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),
+ incremental_field="bookingUpdatedAt",
+ )
+ )
+
+ assert params[0]["afterUpdatedAt"] == "2026-01-02T03:04:05.000Z"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ @mock.patch(CAL_COM_SESSION_PATCH)
+ def test_resumes_at_the_bookings_page_it_stopped_on(self, MockCalSession, MockClientSession) -> None:
+ params = _wire(MockClientSession.return_value, [_page([self.BOOKING])])
+ MockCalSession.return_value = self._attendee_session(_response({"data": [{"id": 5}]}))
+
+ manager = _make_manager(CalComResumeConfig(cursor="c2"))
+ _rows(_source(BOOKING_ATTENDEES_ENDPOINT, manager))
+
+ assert params[0]["cursor"] == "c2"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ @mock.patch(CAL_COM_SESSION_PATCH)
+ def test_checkpoints_only_after_a_pages_attendees_are_yielded(self, MockCalSession, MockClientSession) -> None:
+ # Saving before the fan-out would skip a page's attendees entirely after a crash.
+ _wire(
+ MockClientSession.return_value,
+ [_page([self.BOOKING], next_cursor="c2", has_more=True), _page([{**self.BOOKING, "uid": "bk2"}])],
+ )
+ MockCalSession.return_value = self._attendee_session(
+ _response({"data": [{"id": 5}]}),
+ _response({"data": [{"id": 6}]}),
+ )
+
+ manager = _make_manager()
+ saved_at: list[list[str]] = []
+ yielded: list[str] = []
+ manager.save_state.side_effect = lambda state: saved_at.append(list(yielded))
+
+ for page in _source(BOOKING_ATTENDEES_ENDPOINT, manager).items():
+ yielded.extend(row["bookingUid"] for row in page)
+
+ assert saved_at == [["bk1"]]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ @mock.patch(CAL_COM_SESSION_PATCH)
+ def test_unexpected_payload_shape_fails_loudly(self, MockCalSession, MockClientSession) -> None:
+ _wire(MockClientSession.return_value, [_page([self.BOOKING])])
+ MockCalSession.return_value = self._attendee_session(_response({"status": "success"}))
+
+ with pytest.raises(ValueError, match="matched nothing"):
+ _rows(_source(BOOKING_ATTENDEES_ENDPOINT))
+
+
+class TestOrganizationLookup:
+ def _session(self, response: Any) -> mock.MagicMock:
+ session = mock.MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand(
+ [
+ ("in_an_organization", {"id": 1, "organizationId": 77}, 77),
+ ("personal_account", {"id": 1}, None),
+ ("explicit_null", {"id": 1, "organizationId": None}, None),
+ ]
+ )
+ def test_organization_id_comes_from_the_keys_own_profile(
+ self, _name: str, profile: dict[str, Any], expected: int | None
+ ) -> None:
+ session = self._session(_response({"data": profile}))
+ with mock.patch(CAL_COM_SESSION_PATCH, return_value=session):
+ assert resolve_organization_id("cal_live_key") == expected
+
+ @parameterized.expand(
+ [
+ ("admin", 200, None),
+ # A plain org member gets a valid-key 403; the fix is a different key, not a retry.
+ ("member", 403, "organization member without admin access"),
+ ]
+ )
+ def test_organization_access_probe(self, _name: str, status: int, expected: str | None) -> None:
+ session = self._session(mock.MagicMock(status_code=status))
+ with mock.patch(CAL_COM_SESSION_PATCH, return_value=session):
+ reason = check_organization_access("cal_live_key", ORG_ID)
+
+ assert (reason is None) if expected is None else (expected in (reason or ""))
+ assert session.get.call_args.args[0] == f"{US_BASE_URL}/organizations/{ORG_ID}/memberships"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/tests/test_cal_com_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/tests/test_cal_com_source.py
index f3c91a203d82..cae70a20e169 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/tests/test_cal_com_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cal_com/tests/test_cal_com_source.py
@@ -8,6 +8,8 @@ from posthog.schema import SourceFieldSelectConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.cal_com.source import CalComSource
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.calcom import CalComSourceConfig
+SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.cal_com.source"
+
class TestCalComSource:
def setup_method(self) -> None:
@@ -50,7 +52,7 @@ class TestCalComSource:
non_retryable = self.source.get_non_retryable_errors()
assert not any(key in unrelated_error for key in non_retryable)
- @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.cal_com.source.cal_com_source")
+ @mock.patch(f"{SOURCE_MODULE}.cal_com_source")
def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
inputs = mock.MagicMock()
inputs.schema_name = "bookings"
@@ -71,7 +73,7 @@ class TestCalComSource:
assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
assert kwargs["incremental_field"] == "updatedAt"
- @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.cal_com.source.cal_com_source")
+ @mock.patch(f"{SOURCE_MODULE}.cal_com_source")
def test_source_for_pipeline_drops_incremental_value_when_disabled(self, mock_source: mock.MagicMock) -> None:
inputs = mock.MagicMock()
inputs.schema_name = "bookings"
@@ -88,3 +90,62 @@ class TestCalComSource:
inputs.schema_name = "not_a_table"
with pytest.raises(ValueError, match="Unknown Cal.com schema 'not_a_table'"):
self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ @parameterized.expand(
+ [
+ ("organization_users", True),
+ ("routing_form_responses", True),
+ ("bookings", False),
+ ]
+ )
+ @mock.patch(f"{SOURCE_MODULE}.cal_com_source")
+ @mock.patch(f"{SOURCE_MODULE}.resolve_organization_id", return_value=77)
+ def test_source_for_pipeline_resolves_the_org_only_where_a_path_needs_it(
+ self, schema_name: str, needs_org: bool, mock_resolve: mock.MagicMock, mock_source: mock.MagicMock
+ ) -> None:
+ # An org lookup is an extra request per sync; a path with no {orgId} must not pay it.
+ inputs = mock.MagicMock()
+ inputs.schema_name = schema_name
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_source.call_args.kwargs["organization_id"] == (77 if needs_org else None)
+ assert mock_resolve.called is needs_org
+
+
+class TestCalComEndpointPermissions:
+ def setup_method(self) -> None:
+ self.source = CalComSource()
+ self.config = CalComSourceConfig(api_key="cal_live_key", region="us")
+ self.endpoints = ["bookings", "organization_users", "routing_form_responses"]
+
+ @mock.patch(f"{SOURCE_MODULE}.resolve_organization_id", return_value=None)
+ def test_org_tables_are_flagged_for_a_personal_account(self, _mock_resolve: mock.MagicMock) -> None:
+ permissions = self.source.get_endpoint_permissions(self.config, 1, self.endpoints)
+
+ assert permissions["bookings"] is None
+ assert "not in a Cal.com organization" in (permissions["organization_users"] or "")
+ assert "not in a Cal.com organization" in (permissions["routing_form_responses"] or "")
+
+ @mock.patch(f"{SOURCE_MODULE}.check_organization_access", return_value="needs an admin key")
+ @mock.patch(f"{SOURCE_MODULE}.resolve_organization_id", return_value=77)
+ def test_org_tables_are_flagged_for_a_non_admin_member(
+ self, _mock_resolve: mock.MagicMock, _mock_access: mock.MagicMock
+ ) -> None:
+ permissions = self.source.get_endpoint_permissions(self.config, 1, self.endpoints)
+
+ assert permissions == {
+ "bookings": None,
+ "organization_users": "needs an admin key",
+ "routing_form_responses": "needs an admin key",
+ }
+
+ @mock.patch(f"{SOURCE_MODULE}.resolve_organization_id", side_effect=Exception("boom"))
+ def test_an_unreachable_probe_leaves_every_table_selectable(self, _mock_resolve: mock.MagicMock) -> None:
+ # The table picker must never be blocked by a failed probe.
+ assert self.source.get_endpoint_permissions(self.config, 1, self.endpoints) == dict.fromkeys(self.endpoints)
+
+ @mock.patch(f"{SOURCE_MODULE}.resolve_organization_id")
+ def test_no_probe_when_no_org_table_is_requested(self, mock_resolve: mock.MagicMock) -> None:
+ assert self.source.get_endpoint_permissions(self.config, 1, ["bookings"]) == {"bookings": None}
+ mock_resolve.assert_not_called()