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 callrail import source (#66736)

Tom Owers772b09018299
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 4985c7ff5c0e..b239fb8ffff5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -80,6 +80,7 @@ the row lists both.
| bunny | HTTP | requests | ✅ |
| buzzsprout | HTTP | requests | ✅ |
| calendly | HTTP | requests | ✅ |
+| callrail | HTTP | requests | ✅ |
| campaign_monitor | HTTP | requests | ✅ |
| campayn | HTTP | requests | ✅ |
| canny | HTTP | requests | ✅ |
@@ -337,7 +338,6 @@ doesn't conflict with concurrent PRs.
- branch
- breezy_hr
- cal_com
-- callrail
- campaign_manager_360
- capsule_crm
- captain_data
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/callrail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/callrail.py
new file mode 100644
index 000000000000..8f9145ec9ddd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/callrail.py
@@ -0,0 +1,221 @@
+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 products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.callrail.settings import (
+ CALLRAIL_ENDPOINTS,
+ CallRailEndpointConfig,
+)
+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.resumable import ResumableSourceManager
+
+CALLRAIL_BASE_URL = "https://api.callrail.com/v3"
+
+# Max allowed by the API. Larger pages mean fewer requests against the per-account hourly/daily
+# rate limits.
+PER_PAGE = 250
+
+# Hard cap so a runaway pagination loop (e.g. the API never signaling the last page) can't scan
+# forever. 250 rows/page * this cap bounds a single endpoint sync.
+MAX_PAGES = 100_000
+
+
+class CallRailRetryableError(Exception):
+ pass
+
+
+class CallRailResumeConfig:
+ # The resolved account whose data we're pulling. Pinned across a resume so re-resolution can't
+ # silently switch accounts mid-sync (an API key can see more than one account).
+ account_id: str
+ # Next 1-indexed page to fetch.
+ page: int
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ # CallRail expects the token wrapped in token="..." per its v3 docs.
+ return {
+ "Authorization": f'Token token="{api_key}"',
+ "Accept": "application/json",
+ }
+
+
+def _format_start_date(value: Any) -> str | None:
+ """Format an incremental cursor value as the YYYY-MM-DD `start_date` the API filters on.
+
+ We deliberately drop the time component: CallRail's date filters are interpreted in the
+ account's own timezone, so pinning to the date avoids off-by-one drift at the boundary. We may
+ re-fetch the watermark day's rows, but the merge dedupes them on the primary key.
+ """
+ if isinstance(value, datetime):
+ return value.astimezone(UTC).date().isoformat()
+ if isinstance(value, date):
+ return value.isoformat()
+ if isinstance(value, str) and value:
+ return value[:10]
+ return None
+
+
+@retry(
+ retry=retry_if_exception_type((CallRailRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+)
+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> dict:
+ response = session.get(url, headers=headers, timeout=60)
+
+ # 429 is the per-account rate limit (1,000/hour, 10,000/day). Back off and retry rather than
+ # failing the sync. 5xx are transient server errors.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise CallRailRetryableError(f"CallRail API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"CallRail API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _build_url(base: str, params: dict[str, Any]) -> str:
+ clean = {k: v for k, v in params.items() if v is not None}
+ return f"{base}?{urlencode(clean)}" if clean else base
+
+
+def resolve_account_id(
+ session: requests.Session, api_key: str, logger: FilteringBoundLogger, account_id: str | None = None
+) -> str:
+ """Return the account id to scope data requests to.
+
+ CallRail data endpoints are all nested under /v3/a/{account_id}/, so we must resolve one first.
+ If the user supplied one we trust it; otherwise we use the first account the key can see.
+ """
+ if account_id:
+ return account_id
+
+ # We only ever read the first account, so request a single row like validate_credentials does.
+ url = _build_url(f"{CALLRAIL_BASE_URL}/a.json", {"per_page": 1})
+ data = _fetch_page(session, url, _get_headers(api_key), logger)
+ accounts = data.get("accounts", [])
+ if not accounts:
+ raise ValueError("No CallRail accounts are accessible with this API key.")
+ return str(accounts[0]["id"])
+
+
+def validate_credentials(api_key: str) -> bool:
+ """Confirm the API key is genuine by hitting the accounts endpoint."""
+ url = _build_url(f"{CALLRAIL_BASE_URL}/a.json", {"per_page": 1})
+ try:
+ response = make_tracked_session().get(url, headers=_get_headers(api_key), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _build_params(
+ config: CallRailEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {"per_page": PER_PAGE}
+
+ if config.sort_field:
+ # Ascending on the cursor field so the pipeline watermark advances safely and full-refresh
+ # pages don't skip/duplicate rows inserted mid-sync.
+ params["sort"] = config.sort_field
+ params["order"] = "asc"
+
+ if config.supports_incremental and should_use_incremental_field:
+ start_date = _format_start_date(db_incremental_field_last_value)
+ if start_date:
+ params["start_date"] = start_date
+
+ return params
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CallRailResumeConfig],
+ account_id: str | None = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = CALLRAIL_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ # One session reused across pages so urllib3 keeps the connection alive.
+ session = make_tracked_session()
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None:
+ resolved_account_id = resume.account_id
+ page = resume.page
+ logger.debug(f"CallRail: resuming {endpoint} from page={page}, account_id={resolved_account_id}")
+ else:
+ resolved_account_id = resolve_account_id(session, api_key, logger, account_id)
+ page = 1
+
+ base = f"{CALLRAIL_BASE_URL}/a/{resolved_account_id}{config.path}"
+ params = _build_params(config, should_use_incremental_field, db_incremental_field_last_value)
+
+ while page <= MAX_PAGES:
+ url = _build_url(base, {**params, "page": page})
+ data = _fetch_page(session, url, headers, logger)
+
+ rows = data.get(config.response_key, [])
+ if not rows:
+ break
+
+ yield rows
+
+ total_pages = data.get("total_pages")
+ page += 1
+ if total_pages is not None and page > total_pages:
+ break
+
+ # Save AFTER yielding so a crash re-pulls from the next page rather than losing the page we
+ # just handed off; the merge dedupes any overlap on the primary key.
+ resumable_source_manager.save_state(CallRailResumeConfig(account_id=resolved_account_id, page=page))
+ else:
+ logger.warning(f"CallRail: hit MAX_PAGES={MAX_PAGES} for {endpoint}, stopping pagination")
+
+
+def callrail_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CallRailResumeConfig],
+ account_id: str | None = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = CALLRAIL_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ account_id=account_id,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ 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,
+ sort_mode="asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/canonical_descriptions.py
new file mode 100644
index 000000000000..b1ce9f7cf33f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/canonical_descriptions.py
@@ -0,0 +1,111 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from CallRail's public v3 API docs (https://apidocs.callrail.com). Keyed by
+# the endpoint name from ENDPOINTS / get_schemas. Partial coverage is fine — anything not listed
+# here falls back to LLM enrichment using the docs_url and column data types.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "calls": {
+ "description": "Tracked phone calls captured by CallRail, including caller details, attribution source, and outcome.",
+ "docs_url": "https://apidocs.callrail.com/#calls",
+ "columns": {
+ "id": "Unique identifier for the call.",
+ "answered": "Whether the call was answered.",
+ "business_phone_number": "The business phone number that received the call.",
+ "customer_city": "City of the caller, derived from their phone number.",
+ "customer_country": "Country of the caller.",
+ "customer_name": "Name of the caller, when known.",
+ "customer_phone_number": "Phone number of the caller.",
+ "customer_state": "State/region of the caller.",
+ "direction": "Whether the call was inbound or outbound.",
+ "duration": "Length of the call in seconds.",
+ "start_time": "When the call started (ISO 8601). Stable, used for incremental sync.",
+ "created_at": "When CallRail created the call record (ISO 8601).",
+ "tracking_phone_number": "The CallRail tracking number that was dialed.",
+ "source_name": "Marketing source attributed to the call.",
+ "first_call": "Whether this was the caller's first tracked call.",
+ "recording": "URL to the call recording, when available.",
+ "voicemail": "Whether the call went to voicemail.",
+ "company_id": "Identifier of the company the call belongs to.",
+ },
+ },
+ "companies": {
+ "description": "Companies configured in the CallRail account. A company groups trackers, calls, and form submissions.",
+ "docs_url": "https://apidocs.callrail.com/#companies",
+ "columns": {
+ "id": "Unique identifier for the company.",
+ "name": "Display name of the company.",
+ "status": "Whether the company is active or disabled.",
+ "time_zone": "Time zone configured for the company.",
+ "created_at": "When the company was created (ISO 8601).",
+ "callscribe_enabled": "Whether call transcription is enabled.",
+ },
+ },
+ "form_submissions": {
+ "description": "Form submissions captured by CallRail Form Tracking, with attribution to the originating marketing source.",
+ "docs_url": "https://apidocs.callrail.com/#form-submissions",
+ "columns": {
+ "id": "Unique identifier for the form submission.",
+ "company_id": "Identifier of the company the submission belongs to.",
+ "person_id": "Identifier of the person who submitted the form.",
+ "form_data": "The submitted form field values.",
+ "submitted_at": "When the form was submitted (ISO 8601). Stable, used for incremental sync.",
+ "source": "Marketing source attributed to the submission.",
+ "landing_page_url": "Page the visitor landed on before submitting.",
+ "form_url": "URL of the page containing the form.",
+ "first_form": "Whether this was the person's first form submission.",
+ },
+ },
+ "text_messages": {
+ "description": "SMS conversations between callers and the business, captured by CallRail.",
+ "docs_url": "https://apidocs.callrail.com/#text-messages",
+ "columns": {
+ "id": "Unique identifier for the conversation.",
+ "company_id": "Identifier of the company the conversation belongs to.",
+ "initial_tracker_id": "Tracker the conversation started on.",
+ "customer_phone_number": "Phone number of the customer.",
+ "customer_name": "Name of the customer, when known.",
+ "last_message_at": "Timestamp of the most recent message in the conversation.",
+ "messages": "The individual text messages in the conversation.",
+ },
+ },
+ "trackers": {
+ "description": "Tracking phone numbers and form trackers used to attribute calls and submissions to marketing sources.",
+ "docs_url": "https://apidocs.callrail.com/#trackers",
+ "columns": {
+ "id": "Unique identifier for the tracker.",
+ "name": "Display name of the tracker.",
+ "type": "Tracker type (e.g. source, session).",
+ "status": "Whether the tracker is active or disabled.",
+ "destination_number": "Number calls are forwarded to.",
+ "tracking_numbers": "The tracking phone numbers assigned to this tracker.",
+ "company_id": "Identifier of the company the tracker belongs to.",
+ },
+ },
+ "users": {
+ "description": "Users with access to the CallRail account.",
+ "docs_url": "https://apidocs.callrail.com/#users",
+ "columns": {
+ "id": "Unique identifier for the user.",
+ "email": "Email address of the user.",
+ "first_name": "First name of the user.",
+ "last_name": "Last name of the user.",
+ "name": "Full name of the user.",
+ "role": "Account role assigned to the user.",
+ "created_at": "When the user was created (ISO 8601).",
+ },
+ },
+ "tags": {
+ "description": "Tags available in the CallRail account for categorizing calls and conversations.",
+ "docs_url": "https://apidocs.callrail.com/#tags",
+ "columns": {
+ "id": "Unique identifier for the tag.",
+ "name": "Display name of the tag.",
+ "color": "Color associated with the tag in the UI.",
+ "status": "Whether the tag is enabled.",
+ "company_id": "Identifier of the company the tag belongs to.",
+ "created_at": "When the tag was created (ISO 8601).",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/settings.py
new file mode 100644
index 000000000000..401424948154
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/settings.py
@@ -0,0 +1,108 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class CallRailEndpointConfig:
+ name: str
+ # Path under the account-scoped base (https://api.callrail.com/v3/a/{account_id}).
+ path: str
+ # Key the list lives under in the JSON envelope, e.g. {"calls": [...], "total_pages": N}.
+ response_key: str
+ incremental_fields: list[IncrementalField]
+ # Stable datetime field used for datetime partitioning. Only set where we are confident the
+ # field is present on every row (never `updated_at` / `last_*` — those rewrite partitions).
+ partition_key: Optional[str] = None
+ # Field passed to the API's `sort=` param (ascending) and, for incremental endpoints, the field
+ # the `start_date` server-side filter narrows on. Required when supports_incremental is True so
+ # rows arrive in ascending cursor order and the watermark advances correctly.
+ sort_field: Optional[str] = None
+ # True only where CallRail exposes a genuine server-side date filter (`start_date`) on this
+ # resource. Everything else is full refresh.
+ supports_incremental: bool = False
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ should_sync_default: bool = True
+
+
+# CallRail v3 REST API. All data endpoints are nested under /v3/a/{account_id}/.
+#
+# Incremental support is set only for resources whose list endpoint documents a server-side
+# `start_date` date filter that narrows on a stable timestamp (Calls -> start_time,
+# Form submissions -> submitted_at). For those we advertise exactly that one field as the
+# incremental cursor so the cursor, the `sort=` field, and the `start_date` filter all agree.
+# The remaining resources are mutable configuration objects or lack a usable server-side date
+# filter, so they ship full refresh only.
+CALLRAIL_ENDPOINTS: dict[str, CallRailEndpointConfig] = {
+ "calls": CallRailEndpointConfig(
+ name="calls",
+ path="/calls.json",
+ response_key="calls",
+ partition_key="start_time",
+ sort_field="start_time",
+ supports_incremental=True,
+ incremental_fields=[
+ {
+ "label": "start_time",
+ "type": IncrementalFieldType.DateTime,
+ "field": "start_time",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "companies": CallRailEndpointConfig(
+ name="companies",
+ path="/companies.json",
+ response_key="companies",
+ partition_key="created_at",
+ incremental_fields=[],
+ ),
+ "form_submissions": CallRailEndpointConfig(
+ name="form_submissions",
+ path="/form_submissions.json",
+ response_key="form_submissions",
+ partition_key="submitted_at",
+ sort_field="submitted_at",
+ supports_incremental=True,
+ incremental_fields=[
+ {
+ "label": "submitted_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "submitted_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "text_messages": CallRailEndpointConfig(
+ name="text_messages",
+ # Returns SMS conversations under the "conversations" key.
+ path="/text-messages.json",
+ response_key="conversations",
+ incremental_fields=[],
+ ),
+ "trackers": CallRailEndpointConfig(
+ name="trackers",
+ path="/trackers.json",
+ response_key="trackers",
+ incremental_fields=[],
+ ),
+ "users": CallRailEndpointConfig(
+ name="users",
+ path="/users.json",
+ response_key="users",
+ incremental_fields=[],
+ ),
+ "tags": CallRailEndpointConfig(
+ name="tags",
+ path="/tags.json",
+ response_key="tags",
+ incremental_fields=[],
+ ),
+}
+
+ENDPOINTS = tuple(CALLRAIL_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in CALLRAIL_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/source.py
index 386b00e6f808..409441b676c6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/source.py
@@ -1,30 +1,157 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.callrail.callrail import (
+ CallRailResumeConfig,
+ callrail_source,
+ validate_credentials as validate_callrail_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.callrail.settings import (
+ CALLRAIL_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+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 (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CallRailSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class CallRailSource(SimpleSource[CallRailSourceConfig]):
+class CallRailSource(ResumableSource[CallRailSourceConfig, CallRailResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CALLRAIL
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # account_id selects which CallRail account the stored API key is used against; changing it
+ # must require re-entering the secret so a preserved key can't be retargeted at another
+ # account the key happens to have access to.
+ return ["account_id"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.CALL_RAIL,
category=DataWarehouseSourceCategory.ANALYTICS,
label="CallRail",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your CallRail API key to automatically pull your CallRail call-tracking data into the PostHog Data warehouse.
+
+You can create an API key under **Account settings → Integrations → API Keys** in CallRail. API keys are scoped to the creating user, so the key only sees data that user can access.
+
+Leave **Account ID** blank to use the first account your key can access, or set it to sync a specific account.""",
iconPath="/static/services/callrail.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/callrail",
unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="account_id",
+ label="Account ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.callrail.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # A bad or revoked key surfaces as an HTTPError when `_fetch_page` calls
+ # `raise_for_status()`. Retrying can never fix a credential problem, so stop the sync.
+ # Match the stable status text and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://api.callrail.com": "Your CallRail API key is invalid or has been revoked. Create a new key under Account settings → Integrations → API Keys, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.callrail.com": "Your CallRail API key does not have access to this data. The key only sees what its creating user can access — check the user's permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: CallRailSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = CALLRAIL_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=endpoint_config.supports_incremental,
+ supports_append=endpoint_config.supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.should_sync_default,
+ )
+
+ schemas = [_build_schema(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: CallRailSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_callrail_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid CallRail API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CallRailResumeConfig]:
+ return ResumableSourceManager[CallRailResumeConfig](inputs, CallRailResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: CallRailSourceConfig,
+ resumable_source_manager: ResumableSourceManager[CallRailResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return callrail_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ account_id=config.account_id or None,
+ 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/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/tests/test_callrail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/tests/test_callrail.py
new file mode 100644
index 000000000000..ed4d82dece04
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/tests/test_callrail.py
@@ -0,0 +1,270 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.callrail.callrail import (
+ CallRailResumeConfig,
+ _build_params,
+ _build_url,
+ _format_start_date,
+ callrail_source,
+ get_rows,
+ resolve_account_id,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.callrail.settings import (
+ CALLRAIL_ENDPOINTS,
+ ENDPOINTS,
+)
+
+
+def _make_manager(resume_state: CallRailResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _page(response_key: str, items: list[dict[str, Any]], total_pages: int) -> dict[str, Any]:
+ return {response_key: items, "total_pages": total_pages, "total_records": 999}
+
+
+def _response(body: dict[str, Any]) -> mock.MagicMock:
+ resp = mock.MagicMock(status_code=200, ok=True)
+ resp.json.return_value = body
+ return resp
+
+
+class TestFormatStartDate:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (None, None),
+ (datetime(2026, 3, 4, 22, 13, 20, tzinfo=UTC), "2026-03-04"),
+ (date(2026, 3, 4), "2026-03-04"),
+ ("2026-03-04T22:13:20Z", "2026-03-04"),
+ ("", None),
+ ],
+ )
+ def test_format_start_date(self, value: Any, expected: str | None) -> None:
+ assert _format_start_date(value) == expected
+
+ def test_naive_datetime_returns_a_date_string(self) -> None:
+ # No tzinfo -> astimezone(UTC) localizes against the host timezone, so we can only assert
+ # that a date string is returned without verifying the specific value.
+ assert _format_start_date(datetime(2026, 3, 4, 12, 0, 0)) is not None
+
+
+class TestBuildParams:
+ def test_incremental_endpoint_requests_ascending_sort(self) -> None:
+ params = _build_params(
+ CALLRAIL_ENDPOINTS["calls"], should_use_incremental_field=False, db_incremental_field_last_value=None
+ )
+ assert params["sort"] == "start_time"
+ assert params["order"] == "asc"
+ assert params["per_page"] == 250
+ assert "start_date" not in params
+
+ def test_start_date_included_only_when_incremental_and_value_present(self) -> None:
+ params = _build_params(
+ CALLRAIL_ENDPOINTS["calls"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ )
+ assert params["start_date"] == "2026-03-04"
+
+ def test_start_date_omitted_when_not_using_incremental(self) -> None:
+ params = _build_params(
+ CALLRAIL_ENDPOINTS["calls"],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ )
+ assert "start_date" not in params
+
+ def test_full_refresh_endpoint_has_no_sort_or_start_date(self) -> None:
+ params = _build_params(
+ CALLRAIL_ENDPOINTS["users"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime.now(UTC),
+ )
+ assert "sort" not in params
+ assert "order" not in params
+ assert "start_date" not in params
+
+
+class TestBuildUrl:
+ def test_no_params(self) -> None:
+ assert _build_url("https://api.callrail.com/v3/a/A/calls.json", {}) == (
+ "https://api.callrail.com/v3/a/A/calls.json"
+ )
+
+ def test_drops_none_values_and_encodes(self) -> None:
+ url = _build_url("https://x/calls.json", {"per_page": 250, "start_date": None, "page": 2})
+ assert url == "https://x/calls.json?per_page=250&page=2"
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected",
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ (500, False),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.callrail.callrail.make_tracked_session"
+ )
+ def test_validate_credentials_status_mapping(
+ self, mock_session: mock.MagicMock, status_code: int, expected: bool
+ ) -> None:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ assert validate_credentials("key") is expected
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.callrail.callrail.make_tracked_session"
+ )
+ def test_validate_credentials_swallows_exceptions(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("key") is False
+
+
+class TestResolveAccountId:
+ def test_returns_provided_account_id_without_request(self) -> None:
+ session = mock.MagicMock()
+ assert resolve_account_id(session, "key", mock.MagicMock(), account_id="ACC123") == "ACC123"
+ session.get.assert_not_called()
+
+ def test_resolves_first_account_when_unset(self) -> None:
+ session = mock.MagicMock()
+ session.get.return_value = _response({"accounts": [{"id": "ACC1"}, {"id": "ACC2"}]})
+ assert resolve_account_id(session, "key", mock.MagicMock()) == "ACC1"
+ # Only the first account is used, so we request a single row rather than a full page.
+ assert "per_page=1" in session.get.call_args.args[0]
+
+ def test_raises_when_no_accounts(self) -> None:
+ session = mock.MagicMock()
+ session.get.return_value = _response({"accounts": []})
+ with pytest.raises(ValueError):
+ resolve_account_id(session, "key", mock.MagicMock())
+
+
+class TestGetRows:
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.callrail.callrail.make_tracked_session"
+ )
+ def test_paginates_by_page_number(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.side_effect = [
+ _response(_page("calls", [{"id": "1"}, {"id": "2"}], total_pages=2)),
+ _response(_page("calls", [{"id": "3"}], total_pages=2)),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "calls", mock.MagicMock(), manager, account_id="ACC"))
+
+ assert [item["id"] for batch in batches for item in batch] == ["1", "2", "3"]
+ # State saved once (after page 1, pointing at page 2); page 2 is the last so no save after it.
+ manager.save_state.assert_called_once()
+ saved = manager.save_state.call_args.args[0]
+ assert saved.page == 2
+ assert saved.account_id == "ACC"
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.callrail.callrail.make_tracked_session"
+ )
+ def test_resumes_from_saved_page(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _response(_page("calls", [{"id": "9"}], total_pages=5))
+
+ manager = _make_manager(CallRailResumeConfig(account_id="ACC9", page=5))
+ list(get_rows("key", "calls", mock.MagicMock(), manager, account_id="ACC"))
+
+ # Resumes at the saved page and pinned account, ignoring the passed account_id.
+ url = mock_session.return_value.get.call_args_list[0].args[0]
+ assert "page=5" in url
+ assert "/a/ACC9/" in url
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.callrail.callrail.make_tracked_session"
+ )
+ def test_resolves_account_when_not_resuming(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.side_effect = [
+ _response({"accounts": [{"id": "RESOLVED"}]}),
+ _response(_page("users", [{"id": "u1"}], total_pages=1)),
+ ]
+
+ manager = _make_manager()
+ list(get_rows("key", "users", mock.MagicMock(), manager))
+
+ data_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert "/a/RESOLVED/users.json" in data_url
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.callrail.callrail.make_tracked_session"
+ )
+ def test_empty_page_stops_without_saving(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _response(_page("calls", [], total_pages=0))
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "calls", mock.MagicMock(), manager, account_id="ACC"))
+
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.callrail.callrail.make_tracked_session"
+ )
+ def test_incremental_request_carries_start_date(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _response(_page("calls", [{"id": "1"}], total_pages=1))
+
+ manager = _make_manager()
+ list(
+ get_rows(
+ "key",
+ "calls",
+ mock.MagicMock(),
+ manager,
+ account_id="ACC",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+ )
+
+ url = mock_session.return_value.get.call_args_list[0].args[0]
+ assert "start_date=2026-01-01" in url
+ assert "sort=start_time" in url
+
+
+class TestCallRailSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint: str) -> None:
+ config = CALLRAIL_ENDPOINTS[endpoint]
+ response = callrail_source("key", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ assert response.sort_mode == "asc"
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ @pytest.mark.parametrize("config", list(CALLRAIL_ENDPOINTS.values()))
+ def test_partition_keys_are_stable_creation_fields(self, config: Any) -> None:
+ # Never partition on a mutable field; only stable creation/start timestamps are allowed.
+ if config.partition_key:
+ assert config.partition_key in {"start_time", "submitted_at", "created_at"}
+
+ @pytest.mark.parametrize("config", list(CALLRAIL_ENDPOINTS.values()))
+ def test_incremental_endpoints_have_a_sort_field(self, config: Any) -> None:
+ # An incremental endpoint must sort ascending on its cursor so the watermark advances.
+ if config.supports_incremental:
+ assert config.sort_field is not None
+ assert config.incremental_fields
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/tests/test_callrail_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/tests/test_callrail_source.py
new file mode 100644
index 000000000000..055b6ded85eb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/callrail/tests/test_callrail_source.py
@@ -0,0 +1,181 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.callrail.callrail import CallRailResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.callrail.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.callrail.source import CallRailSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CallRailSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestCallRailSource:
+ def setup_method(self) -> None:
+ self.source = CallRailSource()
+ self.team_id = 123
+ self.config = CallRailSourceConfig(api_key="key", account_id=None)
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.CALLRAIL
+
+ def test_connection_host_fields_includes_account_id(self) -> None:
+ # Changing account_id retargets the stored API key, so editing it must require re-entering secrets.
+ assert self.source.connection_host_fields == ["account_id"]
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "CallRail"
+ assert config.label == "CallRail"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/callrail"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key", "account_id"]
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert key_field.secret is True
+ assert key_field.required is True
+
+ def test_account_id_field_is_optional_text(self) -> None:
+ config = self.source.get_source_config
+ acc_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "account_id")
+ assert acc_field.type == SourceFieldInputConfigType.TEXT
+ assert acc_field.required is False
+ assert acc_field.secret is False
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+ assert len(self.source.get_documented_tables()) == len(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.callrail.com/v3/a/123/calls.json?page=1",
+ "403 Client Error: Forbidden for url: https://api.callrail.com/v3/a/123/companies.json",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ 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_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.callrail.com/v3/a/123/calls.json",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas_covers_all_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ def test_only_documented_filter_endpoints_are_incremental(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ incremental = {name for name, s in schemas.items() if s.supports_incremental}
+ # Only calls and form_submissions expose CallRail's server-side `start_date` filter.
+ assert incremental == {"calls", "form_submissions"}
+
+ def test_incremental_schemas_advertise_their_fields(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["calls"].incremental_fields == INCREMENTAL_FIELDS["calls"]
+ assert schemas["form_submissions"].incremental_fields == INCREMENTAL_FIELDS["form_submissions"]
+ assert schemas["users"].incremental_fields == []
+ assert schemas["users"].supports_append is False
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["calls"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "calls"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_get_canonical_descriptions_keys_match_endpoints(self) -> None:
+ canonical = self.source.get_canonical_descriptions()
+ assert set(canonical).issubset(set(ENDPOINTS))
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid CallRail API key"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.callrail.source.validate_callrail_credentials"
+ )
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ mock_return: bool,
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ 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.api_key)
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is CallRailResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.callrail.source.callrail_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_callrail_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "calls"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1700000000
+ config = CallRailSourceConfig(api_key="key", account_id="ACC1")
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(config, manager, inputs)
+
+ kwargs = mock_callrail_source.call_args.kwargs
+ assert kwargs["api_key"] == "key"
+ assert kwargs["account_id"] == "ACC1"
+ assert kwargs["endpoint"] == "calls"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1700000000
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.callrail.source.callrail_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_callrail_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "users"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = 1700000000
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_callrail_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.callrail.source.callrail_source")
+ def test_source_for_pipeline_blank_account_id_becomes_none(self, mock_callrail_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "calls"
+ inputs.should_use_incremental_field = False
+ config = CallRailSourceConfig(api_key="key", account_id="")
+
+ self.source.source_for_pipeline(config, mock.MagicMock(), inputs)
+
+ assert mock_callrail_source.call_args.kwargs["account_id"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 4bb434717038..ff7719a473e0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -544,7 +544,8 @@ class CalendlySourceConfig(config.Config):
@config.config
class CallRailSourceConfig(config.Config):
- pass
+ api_key: str
+ account_id: str | None = None
@config.config