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(data-warehouse): implement calendly import source (#61158)

Tom Owers038726cfcc3d
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index d8bc8dc1a74c..4bae2efc3af1 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -48,6 +48,7 @@ the row lists both.
| bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) |
| bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ |
| buildbetter | HTTP | requests | ✅ |
+| calendly | HTTP | requests | ✅ |
| chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ |
| clerk | HTTP | requests + `rest_source.RESTClient` | ✅ |
| clickhouse | DB protocol (HTTP-based) | clickhouse-connect / clickhouse-driver | ➖ |
@@ -121,7 +122,7 @@ These are registered in `__init__.py` with `unreleasedSource=True` and a stub `s
sync logic yet — picking up any of them means following the [implementing-warehouse-sources skill](/.agents/skills/implementing-warehouse-sources/SKILL.md).
active_campaign, adjust, aircall, airtable, amazon_ads, amplitude, apple_search_ads, appsflyer, asana,
-ashby, auth0, azure_blob, bamboohr, bigcommerce, box, braintree, braze, brevo, calendly, campaign_monitor,
+ashby, auth0, azure_blob, bamboohr, bigcommerce, box, braintree, braze, brevo, campaign_monitor,
chartmogul, circleci, clickup, close, cockroachdb, confluence, convertkit, copper, datadog,
dynamodb, elasticsearch, eventbrite, facebook_pages, firebase, freshdesk, freshsales, front,
fullstory, gitlab, gong, google_analytics, google_drive, gorgias, granola, greenhouse, helpscout,
diff --git a/posthog/temporal/data_imports/sources/calendly/api_inventory.md b/posthog/temporal/data_imports/sources/calendly/api_inventory.md
new file mode 100644
index 000000000000..40c6af56e194
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/calendly/api_inventory.md
@@ -0,0 +1,39 @@
+# Calendly API inventory
+
+Calendly REST API v2 — base URL `https://api.calendly.com`. Auth via a Personal Access Token
+(`Authorization: Bearer <token>`). Docs: <https://developer.calendly.com/api-docs>.
+
+## Conventions
+
+- **Response shape:** list endpoints return `{"collection": [...], "pagination": {"count", "next_page", "next_page_token"}}`.
+- **Pagination:** cursor-based. Follow `pagination.next_page` (a fully-formed URL carrying all query params); a `null` value ends pagination.
+- **Scoping:** every list endpoint below requires an `organization` URI, resolved once per sync from `GET /users/me` → `resource.current_organization`.
+- **Primary key:** every resource carries a stable `uri`.
+- **Partitioning:** all endpoints expose a stable `created_at`, used for datetime partitioning.
+
+## Endpoints synced
+
+| Endpoint | Path | Incremental | Notes |
+| -------------------------- | --------------------------- | ---------------------------------- | -------------------------- |
+| `event_types` | `/event_types` | full refresh | no server-side time filter |
+| `scheduled_events` | `/scheduled_events` | `min_start_time` (on `start_time`) | `sort=start_time:asc` |
+| `groups` | `/groups` | full refresh | no server-side time filter |
+| `organization_memberships` | `/organization_memberships` | full refresh | no server-side time filter |
+| `routing_forms` | `/routing_forms` | full refresh | no server-side time filter |
+
+## Verification status & caveats
+
+- The 401 response shape was confirmed against the live API (`{"title":"Unauthenticated", ...}`).
+- Endpoint params, pagination shape, and the `min_start_time` filter are taken from the published docs and
+ the Airbyte/Fivetran Calendly connectors. They were **not** curl-verified end to end here because no
+ Calendly token was available in the build environment.
+- `scheduled_events` incremental advances on `start_time` (the scheduled meeting time), not on
+ created/updated. A late-created event whose `start_time` is below the watermark can be missed on an
+ incremental run; the merge dedupes on `uri` for everything re-fetched. This mirrors the known limitation
+ of the Airbyte connector. Only `scheduled_events` is marked `supports_incremental` because it is the only
+ endpoint with a genuine server-side timestamp filter.
+
+## Not yet synced
+
+- `scheduled_events/{uuid}/invitees` — valuable (who booked) but requires per-event fan-out; deferred for the
+ initial alpha.
diff --git a/posthog/temporal/data_imports/sources/calendly/calendly.py b/posthog/temporal/data_imports/sources/calendly/calendly.py
new file mode 100644
index 000000000000..276834cdc7a7
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/calendly/calendly.py
@@ -0,0 +1,177 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.calendly.settings import CALENDLY_ENDPOINTS, CalendlyEndpointConfig
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+CALENDLY_BASE_URL = "https://api.calendly.com"
+PAGE_SIZE = 100
+REQUEST_TIMEOUT = 60
+
+
+class CalendlyRetryableError(Exception):
+ pass
+
+
+class CalendlyResumeConfig:
+ next_url: str
+
+
+def _format_datetime(value: Any) -> str:
+ """Format a datetime/date as an RFC 3339 UTC string, which Calendly's time filters expect."""
+ if isinstance(value, datetime):
+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return dt.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
+ return str(value)
+
+
+def _get_headers(token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {token}",
+ "Content-Type": "application/json",
+ }
+
+
+def validate_credentials(token: str) -> bool:
+ try:
+ response = make_tracked_session().get(f"{CALENDLY_BASE_URL}/users/me", headers=_get_headers(token), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def get_current_organization(token: str) -> str:
+ """Resolve the organization URI for the token via `/users/me`.
+
+ Every list endpoint we sync is scoped by this URI, so we access it directly and let a
+ malformed response surface immediately as a KeyError rather than degrading to None.
+ """
+ response = make_tracked_session().get(
+ f"{CALENDLY_BASE_URL}/users/me", headers=_get_headers(token), timeout=REQUEST_TIMEOUT
+ )
+ response.raise_for_status()
+ return response.json()["resource"]["current_organization"]
+
+
+def _build_initial_params(
+ config: CalendlyEndpointConfig,
+ organization: str | None,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {"count": PAGE_SIZE}
+
+ if config.scope_param and organization:
+ params[config.scope_param] = organization
+
+ if config.sort:
+ params["sort"] = config.sort
+
+ if config.incremental_filter_param and should_use_incremental_field and db_incremental_field_last_value:
+ params[config.incremental_filter_param] = _format_datetime(db_incremental_field_last_value)
+
+ return params
+
+
+def get_rows(
+ token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CalendlyResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[Any]:
+ config = CALENDLY_ENDPOINTS[endpoint]
+ headers = _get_headers(token)
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if resume_config is not None:
+ url = resume_config.next_url
+ logger.debug(f"Calendly: resuming from URL: {url}")
+ else:
+ organization = get_current_organization(token) if config.scope_param == "organization" else None
+ params = _build_initial_params(
+ config, organization, should_use_incremental_field, db_incremental_field_last_value
+ )
+ url = f"{CALENDLY_BASE_URL}{config.path}?{urlencode(params)}"
+
+ @retry(
+ retry=retry_if_exception_type((CalendlyRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def fetch_page(page_url: str) -> dict:
+ response = make_tracked_session().get(page_url, headers=headers, timeout=REQUEST_TIMEOUT)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise CalendlyRetryableError(
+ f"Calendly API error (retryable): status={response.status_code}, url={page_url}"
+ )
+
+ if not response.ok:
+ logger.error(f"Calendly API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ while True:
+ data = fetch_page(url)
+
+ items = data.get("collection", [])
+ if items:
+ yield items
+
+ # Keep paginating until the API signals completion with a null next_page, even if an
+ # individual page came back empty.
+ next_url = data.get("pagination", {}).get("next_page")
+ if not next_url:
+ break
+
+ # Save state after yielding so a crash re-yields the last page (merge dedupes on `uri`)
+ # rather than skipping it.
+ resumable_source_manager.save_state(CalendlyResumeConfig(next_url=next_url))
+ url = next_url
+
+
+def calendly_source(
+ token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CalendlyResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = CALENDLY_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ token=token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=["uri"],
+ 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,
+ sort_mode="asc",
+ )
diff --git a/posthog/temporal/data_imports/sources/calendly/settings.py b/posthog/temporal/data_imports/sources/calendly/settings.py
new file mode 100644
index 000000000000..858cfbc19d97
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/calendly/settings.py
@@ -0,0 +1,64 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class CalendlyEndpointConfig:
+ name: str
+ path: str
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Query param used to scope the request to the user's organization. Every Calendly v2
+ # list endpoint we sync requires this (an `organization` URI).
+ scope_param: Optional[str] = "organization"
+ # Stable field used for datetime partitioning. Never use `updated_at` (it changes).
+ partition_key: Optional[str] = "created_at"
+ # Server-side time filter param, only set where the API genuinely filters (see settings below).
+ incremental_filter_param: Optional[str] = None
+ # Sort value passed to keep pagination ordering stable/monotonic.
+ sort: Optional[str] = None
+
+
+CALENDLY_ENDPOINTS: dict[str, CalendlyEndpointConfig] = {
+ "event_types": CalendlyEndpointConfig(
+ name="event_types",
+ path="/event_types",
+ ),
+ # The only endpoint with a real server-side timestamp filter (`min_start_time`). It filters on
+ # `start_time` (the scheduled meeting time), so incremental syncs advance on `start_time`, not on
+ # created/updated. Late-created events with a `start_time` below the watermark can be missed; the
+ # merge dedupes on `uri` for everything re-fetched. Partitioning stays on the stable `created_at`.
+ "scheduled_events": CalendlyEndpointConfig(
+ name="scheduled_events",
+ path="/scheduled_events",
+ incremental_filter_param="min_start_time",
+ sort="start_time:asc",
+ incremental_fields=[
+ {
+ "label": "start_time",
+ "type": IncrementalFieldType.DateTime,
+ "field": "start_time",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "groups": CalendlyEndpointConfig(
+ name="groups",
+ path="/groups",
+ ),
+ "organization_memberships": CalendlyEndpointConfig(
+ name="organization_memberships",
+ path="/organization_memberships",
+ ),
+ "routing_forms": CalendlyEndpointConfig(
+ name="routing_forms",
+ path="/routing_forms",
+ ),
+}
+
+ENDPOINTS = tuple(CALENDLY_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in CALENDLY_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/calendly/source.py b/posthog/temporal/data_imports/sources/calendly/source.py
index 6b2ea9384bc3..260ff2242127 100644
--- a/posthog/temporal/data_imports/sources/calendly/source.py
+++ b/posthog/temporal/data_imports/sources/calendly/source.py
@@ -1,19 +1,31 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.calendly.calendly import (
+ CalendlyResumeConfig,
+ calendly_source,
+ validate_credentials as validate_calendly_credentials,
+)
+from posthog.temporal.data_imports.sources.calendly.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import CalendlySourceConfig
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class CalendlySource(SimpleSource[CalendlySourceConfig]):
+class CalendlySource(ResumableSource[CalendlySourceConfig, CalendlyResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CALENDLY
@@ -23,7 +35,79 @@ class CalendlySource(SimpleSource[CalendlySourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.CALENDLY,
label="Calendly",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Calendly personal access token to pull your Calendly data into the PostHog Data warehouse.
+
+You can create a personal access token in Calendly under **Integrations → API & Webhooks**. A personal access token requires a paid Calendly plan.""",
iconPath="/static/services/calendly.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/calendly",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="personal_access_token",
+ label="Personal access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: CalendlySourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,
+ supports_append=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: CalendlySourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_calendly_credentials(config.personal_access_token):
+ return True, None
+
+ return False, "Invalid Calendly personal access token"
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.calendly.com": "Your Calendly personal access token is invalid or expired. Please generate a new token and reconnect.",
+ "403 Client Error: Forbidden for url: https://api.calendly.com": "Your Calendly personal access token does not have the required permissions. Please check the token and try again.",
+ }
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CalendlyResumeConfig]:
+ return ResumableSourceManager[CalendlyResumeConfig](inputs, CalendlyResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: CalendlySourceConfig,
+ resumable_source_manager: ResumableSourceManager[CalendlyResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return calendly_source(
+ token=config.personal_access_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/posthog/temporal/data_imports/sources/calendly/tests/test_calendly.py b/posthog/temporal/data_imports/sources/calendly/tests/test_calendly.py
new file mode 100644
index 000000000000..a64b06ab777d
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/calendly/tests/test_calendly.py
@@ -0,0 +1,238 @@
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.temporal.data_imports.sources.calendly.calendly import (
+ CALENDLY_BASE_URL,
+ CalendlyResumeConfig,
+ _build_initial_params,
+ _format_datetime,
+ calendly_source,
+ get_current_organization,
+ get_rows,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.calendly.settings import CALENDLY_ENDPOINTS, ENDPOINTS
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+ORG_URI = "https://api.calendly.com/organizations/ABC123"
+
+
+class FakeResponse:
+ def __init__(self, status_code: int = 200, json_data: Optional[dict] = None):
+ self.status_code = status_code
+ self._json = json_data or {}
+ self.text = str(self._json)
+
+ @property
+ def ok(self) -> bool:
+ return self.status_code < 400
+
+ def json(self) -> dict:
+ return self._json
+
+ def raise_for_status(self) -> None:
+ if self.status_code >= 400:
+ raise Exception(f"{self.status_code} Client Error for url: {CALENDLY_BASE_URL}")
+
+
+class FakeSession:
+ """Returns queued responses in order for each .get() call."""
+
+ def __init__(self, responses: list[FakeResponse]):
+ self._responses = list(responses)
+ self.requested_urls: list[str] = []
+
+ def get(self, url: str, **_kwargs: Any) -> FakeResponse:
+ self.requested_urls.append(url)
+ return self._responses.pop(0)
+
+
+class StubResumeManager(ResumableSourceManager[CalendlyResumeConfig]):
+ # Overrides every method `get_rows` touches, so the Redis-bound base `__init__` is skipped.
+ def __init__(self, resume_state: Optional[CalendlyResumeConfig] = None):
+ self._resume_state = resume_state
+ self.saved_states: list[CalendlyResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._resume_state is not None
+
+ def load_state(self) -> Optional[CalendlyResumeConfig]:
+ return self._resume_state
+
+ def save_state(self, data: CalendlyResumeConfig) -> None:
+ self.saved_states.append(data)
+
+
+def _users_me_response() -> FakeResponse:
+ return FakeResponse(200, {"resource": {"current_organization": ORG_URI}})
+
+
+class TestFormatDatetime:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000000Z"),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000000Z"),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00.000000Z"),
+ ("string_passthrough", "2026-03-04T00:00:00.000000Z", "2026-03-04T00:00:00.000000Z"),
+ ]
+ )
+ def test_format_datetime(self, _name: str, value: object, expected: str) -> None:
+ assert _format_datetime(value) == expected
+
+ def test_no_plus_zero_offset_in_output(self) -> None:
+ assert "+00:00" not in _format_datetime(datetime(2026, 3, 4, tzinfo=UTC))
+
+
+class TestBuildInitialParams:
+ def test_scope_param_and_count_present(self) -> None:
+ params = _build_initial_params(CALENDLY_ENDPOINTS["event_types"], ORG_URI, False, None)
+
+ assert params["organization"] == ORG_URI
+ assert params["count"] == 100
+ assert "min_start_time" not in params
+
+ def test_scheduled_events_adds_sort_and_no_filter_without_incremental(self) -> None:
+ params = _build_initial_params(CALENDLY_ENDPOINTS["scheduled_events"], ORG_URI, False, None)
+
+ assert params["sort"] == "start_time:asc"
+ assert "min_start_time" not in params
+
+ def test_scheduled_events_adds_min_start_time_when_incremental(self) -> None:
+ params = _build_initial_params(
+ CALENDLY_ENDPOINTS["scheduled_events"],
+ ORG_URI,
+ True,
+ datetime(2026, 1, 1, tzinfo=UTC),
+ )
+
+ assert params["min_start_time"] == "2026-01-01T00:00:00.000000Z"
+
+ def test_non_incremental_endpoint_never_adds_filter(self) -> None:
+ params = _build_initial_params(
+ CALENDLY_ENDPOINTS["event_types"], ORG_URI, True, datetime(2026, 1, 1, tzinfo=UTC)
+ )
+
+ assert "min_start_time" not in params
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
+ def test_validate_credentials_status_mapping(self, _name: str, status_code: int, expected: bool) -> None:
+ session = FakeSession([FakeResponse(status_code)])
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.calendly.calendly.make_tracked_session", return_value=session
+ ):
+ assert validate_credentials("token") is expected
+
+ def test_validate_credentials_swallows_exceptions(self) -> None:
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.calendly.calendly.make_tracked_session",
+ side_effect=Exception("network down"),
+ ):
+ assert validate_credentials("token") is False
+
+
+class TestGetCurrentOrganization:
+ def test_parses_org_uri(self) -> None:
+ session = FakeSession([_users_me_response()])
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.calendly.calendly.make_tracked_session", return_value=session
+ ):
+ assert get_current_organization("token") == ORG_URI
+
+
+class TestGetRows:
+ def _run(self, session: FakeSession, manager: StubResumeManager, endpoint: str = "event_types", **kwargs):
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.calendly.calendly.make_tracked_session", return_value=session
+ ):
+ return list(
+ get_rows(
+ token="token",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ **kwargs,
+ )
+ )
+
+ def test_paginates_across_pages_following_next_page(self) -> None:
+ page1 = FakeResponse(
+ 200,
+ {
+ "collection": [{"uri": "a"}, {"uri": "b"}],
+ "pagination": {"next_page": f"{CALENDLY_BASE_URL}/event_types?page=2"},
+ },
+ )
+ page2 = FakeResponse(200, {"collection": [{"uri": "c"}], "pagination": {"next_page": None}})
+ session = FakeSession([_users_me_response(), page1, page2])
+ manager = StubResumeManager()
+
+ batches = self._run(session, manager)
+
+ assert batches == [[{"uri": "a"}, {"uri": "b"}], [{"uri": "c"}]]
+ # State saved after the first page yielded, pointing at page 2.
+ assert len(manager.saved_states) == 1
+ assert manager.saved_states[0].next_url == f"{CALENDLY_BASE_URL}/event_types?page=2"
+
+ def test_empty_collection_yields_nothing(self) -> None:
+ session = FakeSession([_users_me_response(), FakeResponse(200, {"collection": [], "pagination": {}})])
+
+ batches = self._run(session, StubResumeManager())
+
+ assert batches == []
+
+ def test_empty_page_mid_pagination_does_not_terminate_early(self) -> None:
+ # An empty page that still advertises a next_page must not end the sync.
+ empty_page = FakeResponse(
+ 200, {"collection": [], "pagination": {"next_page": f"{CALENDLY_BASE_URL}/event_types?page=2"}}
+ )
+ last_page = FakeResponse(200, {"collection": [{"uri": "a"}], "pagination": {"next_page": None}})
+ session = FakeSession([_users_me_response(), empty_page, last_page])
+
+ batches = self._run(session, StubResumeManager())
+
+ assert batches == [[{"uri": "a"}]]
+
+ def test_resume_skips_users_me_and_starts_from_saved_url(self) -> None:
+ resume_url = f"{CALENDLY_BASE_URL}/event_types?page=5"
+ session = FakeSession([FakeResponse(200, {"collection": [{"uri": "z"}], "pagination": {"next_page": None}})])
+ manager = StubResumeManager(resume_state=CalendlyResumeConfig(next_url=resume_url))
+
+ batches = self._run(session, manager)
+
+ assert batches == [[{"uri": "z"}]]
+ # No /users/me bootstrap call on resume; first request is the saved URL.
+ assert session.requested_urls == [resume_url]
+
+ def test_first_request_scopes_to_organization(self) -> None:
+ session = FakeSession(
+ [_users_me_response(), FakeResponse(200, {"collection": [{"uri": "a"}], "pagination": {}})]
+ )
+
+ self._run(session, StubResumeManager())
+
+ # users/me first, then the scoped list request carrying the org URI.
+ assert session.requested_urls[0] == f"{CALENDLY_BASE_URL}/users/me"
+ assert "organization=" in session.requested_urls[1]
+
+
+class TestCalendlySource:
+ @parameterized.expand([(name,) for name in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = calendly_source(
+ token="token",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=StubResumeManager(),
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == ["uri"]
+ assert response.sort_mode == "asc"
+ assert response.partition_keys == ["created_at"]
+ assert response.partition_mode == "datetime"
diff --git a/posthog/temporal/data_imports/sources/calendly/tests/test_calendly_source.py b/posthog/temporal/data_imports/sources/calendly/tests/test_calendly_source.py
new file mode 100644
index 000000000000..f5fa53352dba
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/calendly/tests/test_calendly_source.py
@@ -0,0 +1,163 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.calendly.calendly import CalendlyResumeConfig
+from posthog.temporal.data_imports.sources.calendly.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.calendly.source import CalendlySource
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import CalendlySourceConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+def _make_inputs(schema_name: str = "scheduled_events", **overrides):
+ defaults = {
+ "schema_name": schema_name,
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 1,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-1",
+ "logger": mock.MagicMock(),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return mock.MagicMock(**defaults)
+
+
+class TestCalendlySource:
+ def setup_method(self):
+ self.source = CalendlySource()
+ self.team_id = 123
+ self.config = CalendlySourceConfig(personal_access_token="cal_test_token")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.CALENDLY
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Calendly"
+ assert config.label == "Calendly"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is not True
+ assert config.iconPath == "/static/services/calendly.png"
+ assert len(config.fields) == 1
+
+ token_field = config.fields[0]
+ assert isinstance(token_field, SourceFieldInputConfig)
+ assert token_field.name == "personal_access_token"
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.required is True
+ assert token_field.secret is True
+
+ @pytest.mark.parametrize(
+ "expected_key",
+ [
+ "401 Client Error: Unauthorized for url: https://api.calendly.com",
+ "403 Client Error: Forbidden for url: https://api.calendly.com",
+ ],
+ )
+ def test_non_retryable_errors_includes_calendly_key(self, expected_key):
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_non_retryable_errors_matches_observed_error_message(self):
+ observed_error = "401 Client Error: Unauthorized for url: https://api.calendly.com/scheduled_events?count=100"
+
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_vendor_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "401 Client Error: Unauthorized for url: https://api.klaviyo.com/api/accounts",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_other_vendors(self, other_vendor_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_vendor_error for key in non_retryable_errors)
+
+ def test_get_schemas(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ by_name = {schema.name: schema for schema in schemas}
+ # Only scheduled_events has a genuine server-side time filter.
+ assert by_name["scheduled_events"].supports_incremental is True
+ assert by_name["scheduled_events"].supports_append is True
+ assert {f["field"] for f in by_name["scheduled_events"].incremental_fields} == {"start_time"}
+
+ for name in ("event_types", "groups", "organization_memberships", "routing_forms"):
+ assert by_name[name].supports_incremental is False
+ assert by_name[name].supports_append is False
+ assert by_name[name].incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["scheduled_events"])
+
+ assert len(schemas) == 1
+ assert schemas[0].name == "scheduled_events"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid Calendly personal access token"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.calendly.source.validate_calendly_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(self.config.personal_access_token)
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self):
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is CalendlyResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.calendly.source.calendly_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_calendly_source):
+ inputs = _make_inputs(
+ schema_name="scheduled_events",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01T00:00:00.000000Z",
+ )
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_calendly_source.assert_called_once()
+ kwargs = mock_calendly_source.call_args.kwargs
+ assert kwargs["token"] == "cal_test_token"
+ assert kwargs["endpoint"] == "scheduled_events"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00.000000Z"
+
+ @mock.patch("posthog.temporal.data_imports.sources.calendly.source.calendly_source")
+ def test_source_for_pipeline_drops_last_value_when_not_incremental(self, mock_calendly_source):
+ inputs = _make_inputs(
+ should_use_incremental_field=False,
+ db_incremental_field_last_value="2026-01-01T00:00:00.000000Z",
+ )
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_calendly_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 6037c00bcfb8..d81e31373f4a 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -202,7 +202,7 @@ class BuildBetterSourceConfig(config.Config):
@config.config
class CalendlySourceConfig(config.Config):
- pass
+ personal_access_token: str
@config.config