: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement freshcaller import source (#67826)
Tom Owersf1e0547894e2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 120d5e1d4fc7..222da25da13c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -133,6 +133,7 @@ the row lists both.| e_conomic | HTTP | requests | ✅ || easypost | HTTP | requests | ✅ || easypromos | HTTP | requests | ✅ |+| freshcaller | HTTP | requests | ✅ || freshdesk | HTTP | requests | ✅ || freshsales | HTTP | requests | ✅ || freshservice | HTTP | requests | ✅ |@@ -448,7 +449,6 @@ doesn't conflict with concurrent PRs.- freeagent- freightview- freshbooks-- freshcaller- freshchat- freshservice- fulcrumdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshcaller/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshcaller/canonical_descriptions.pynew file mode 100644index 000000000000..4ac3facd7473--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshcaller/canonical_descriptions.py@@ -0,0 +1,94 @@+"""Canonical, documentation-sourced descriptions for Freshcaller endpoints and columns.++Sourced from the official Freshcaller API reference (https://developers.freshcaller.com/api/).+Keyed by the endpoint names in `settings.py` `FRESHCALLER_ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced Freshcaller table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "users": {+ "description": "An agent or admin in your Freshcaller account who can handle calls.",+ "docs_url": "https://developers.freshcaller.com/api/#users",+ "columns": {+ "id": "Unique identifier for the user.",+ "name": "The user's name.",+ "email": "The user's email address.",+ "phone": "The user's phone number.",+ "status": "Availability status (0 offline, 1 online, 2 busy, 3 after call work).",+ "last_call_time": "Time the user last handled a call.",+ "last_seen_time": "Time the user was last active.",+ "confirmed": "Whether the account has been activated via email.",+ "language": "The user's preferred conversational language.",+ "time_zone": "The user's selected time zone.",+ "deleted": "Whether the user's information has been deleted.",+ "role": "The user's role (Account Admin, Admin, Supervisor, or Agent).",+ "teams": "The teams the user belongs to.",+ },+ },+ "teams": {+ "description": "A group of agents in Freshcaller used to route and organize calls.",+ "docs_url": "https://developers.freshcaller.com/api/#teams",+ "columns": {+ "id": "Unique identifier for the team.",+ "name": "The team's name.",+ "description": "The team's description.",+ "users": "The users belonging to the team.",+ "omni_channel": "Whether omni-channel routing is enabled for the team.",+ },+ },+ "calls": {+ "description": "A phone call handled through Freshcaller, inbound or outbound.",+ "docs_url": "https://developers.freshcaller.com/api/#calls",+ "columns": {+ "id": "Unique identifier for the call.",+ "direction": "Whether the call was Incoming or Outgoing.",+ "parent_call_id": "Parent call identifier for transferred calls.",+ "root_call_id": "Source call identifier for child calls.",+ "phone_number_id": "Identifier of the Freshcaller number used.",+ "phone_number": "The Freshcaller number used for the call.",+ "assigned_agent_id": "Identifier of the primary agent on the call.",+ "assigned_agent_name": "Name of the primary agent on the call.",+ "assigned_team_id": "Team identifier for inbound calls.",+ "assigned_team_name": "Team name for inbound calls.",+ "assigned_call_queue_id": "Call queue identifier for inbound calls.",+ "assigned_call_queue_name": "Call queue name for inbound calls.",+ "assigned_ivr_id": "IVR menu identifier for inbound calls.",+ "assigned_ivr_name": "IVR menu name for inbound calls.",+ "call_notes": "Notes entered by an agent during or after the call.",+ "bill_duration": "Duration used to calculate the call cost.",+ "bill_duration_unit": "Time unit for bill_duration.",+ "created_time": "Time at which the call was initiated.",+ "updated_time": "Time at which the call's attributes were last updated.",+ "recording": "Recording details for the call (id, url, transcription, duration).",+ "integrated_resources": "Integration and resource details related to the call.",+ "participants": "The participants on the call.",+ },+ },+ "call_metrics": {+ "description": "Per-call performance metrics for a Freshcaller call (hold time, talk time, cost, etc.).",+ "docs_url": "https://developers.freshcaller.com/api/#call-metrics",+ "columns": {+ "id": "Unique identifier for the call metric.",+ "call_id": "Identifier of the associated call.",+ "created_time": "Time at which the metric object was created.",+ "updated_time": "Time at which the metric object was last updated.",+ "ivr_time": "Total time the customer spent in the IVR.",+ "hold_duration": "Total time the customer spent on hold.",+ "call_work_time": "Time the agent spent on post-call activities.",+ "total_ringing_time": "Ringing/wait time before the call was answered.",+ "talk_time": "Total talk time, excluding after-call work and hold.",+ "answering_speed": "Inbound wait time before the call was answered.",+ "recording_duration": "Duration for which the call was recorded.",+ "bill_duration": "Duration used to calculate the call cost.",+ "cost": "Cost associated with the call.",+ "cost_unit": "Currency (ISO code) for the cost.",+ "csat": "CSAT feedback details for the call.",+ "tags": "Labels associated with the call.",+ "life_cycle": "The sequence of call events (included via the life_cycle parameter).",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshcaller/freshcaller.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshcaller/freshcaller.pynew file mode 100644index 000000000000..7631e6f5b205--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshcaller/freshcaller.py@@ -0,0 +1,253 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, time+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import RetryCallState, 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.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.freshcaller.settings import (+ DEFAULT_START_DATETIME,+ FRESHCALLER_ENDPOINTS,+ PER_PAGE,+ FreshcallerEndpointConfig,+)++REQUEST_TIMEOUT = 60+VALIDATE_TIMEOUT = 10+MAX_RETRIES = 5+MAX_RETRY_WAIT = 60.0++_EXPONENTIAL_WAIT = wait_exponential_jitter(initial=1, max=MAX_RETRY_WAIT)+++class FreshcallerRetryableError(Exception):+ def __init__(self, message: str, retry_after: float | None = None) -> None:+ super().__init__(message)+ self.retry_after = retry_after+++def _parse_retry_after(value: str | None) -> float | None:+ """Parse a Retry-After header. Freshworks APIs send an integer number of seconds."""+ if not value:+ return None+ try:+ return float(value)+ except ValueError:+ return None+++def _retry_wait(retry_state: RetryCallState) -> float:+ """Honor a server-provided Retry-After (capped); otherwise fall back to exponential jitter."""+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, FreshcallerRetryableError) and exc.retry_after is not None:+ return min(exc.retry_after, MAX_RETRY_WAIT)+ return _EXPONENTIAL_WAIT(retry_state)+++class FreshcallerResumeConfig:+ # The next page number to fetch. Freshcaller uses page/per_page pagination, so a single+ # integer is enough to pick back up. The time window (by_time[from]/by_time[to]) is rebuilt+ # from the incremental watermark on resume — `from` is the stable DB watermark and `to` is+ # "now", so re-entering the same window and deduping on `id` is safe.+ page: int+++def normalize_subdomain(domain: str) -> str:+ """Accept either a bare account name ("acme") or a full host ("acme.freshcaller.com")."""+ domain = domain.strip().removeprefix("https://").removeprefix("http://")+ domain = domain.split("/")[0]+ return domain.removesuffix(".freshcaller.com")+++def _base_url(subdomain: str) -> str:+ return f"https://{normalize_subdomain(subdomain)}.freshcaller.com"+++def _get_headers(api_key: str) -> dict[str, str]:+ # Freshcaller authenticates with a single API key in the X-Api-Auth header. The Accept header+ # is required — the API 404s the route when it's `*/*`.+ return {"X-Api-Auth": api_key, "Accept": "application/json"}+++def _format_datetime(value: Any) -> str:+ """Format an incremental cursor value as the ISO 8601 UTC (Z-suffixed) string Freshcaller expects."""+ if isinstance(value, datetime):+ utc = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return utc.strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return datetime.combine(value, time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ return str(value)+++def build_base_params(+ config: FreshcallerEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> dict[str, str]:+ """Query params shared across every page of one sync (everything except `page`)."""+ params: dict[str, str] = {"per_page": str(PER_PAGE)}+ params.update(config.extra_params)++ if should_use_incremental_field and config.supports_incremental:+ # `by_time` requires both bounds together; window is [watermark, now]. Without a watermark+ # (first sync) fall back to the configured backfill floor instead of scanning all history.+ start = _format_datetime(db_incremental_field_last_value) if db_incremental_field_last_value else None+ params["by_time[from]"] = start or DEFAULT_START_DATETIME+ params["by_time[to]"] = _format_datetime(datetime.now(UTC))++ return params+++def extract_items(data: Any, config: FreshcallerEndpointConfig) -> list[dict]:+ """Freshcaller wraps each list under its plural resource key (e.g. {"users": [...]})."""+ if isinstance(data, dict):+ value = data.get(config.data_key)+ if isinstance(value, list):+ return value+ if isinstance(data, list):+ return data+ return []+++def extract_meta(data: Any) -> dict:+ if isinstance(data, dict) and isinstance(data.get("meta"), dict):+ return data["meta"]+ return {}+++def _has_next_page(meta: dict, items: list[dict], page: int) -> bool:+ if not items:+ return False+ total_pages = meta.get("total_pages")+ if isinstance(total_pages, int):+ current = meta.get("current")+ current_page = current if isinstance(current, int) else page+ return current_page < total_pages+ # No usable meta -> a full page implies there may be more.+ return len(items) >= PER_PAGE+++def get_rows(+ api_key: str,+ subdomain: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FreshcallerResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict]]:+ config = FRESHCALLER_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ base = _base_url(subdomain)+ base_params = build_base_params(config, should_use_incremental_field, db_incremental_field_last_value)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.page if resume is not None else 1+ if resume is not None:+ logger.debug(f"Freshcaller: resuming {endpoint} from page {page}")++ # One session reused across pages so urllib3 keeps the connection alive. `redact_values` masks+ # the API key from captured HTTP samples: it rides in the `X-Api-Auth` header, which the+ # name-based sample scrubbers don't recognise.+ session = make_tracked_session(redact_values=(api_key,))++ @retry(+ retry=retry_if_exception_type((FreshcallerRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=_retry_wait,+ reraise=True,+ )+ def fetch_page(page_url: str) -> Any:+ response = session.get(page_url, headers=headers, timeout=REQUEST_TIMEOUT)++ # Freshcaller throttles per plan tier with 429; honor Retry-After when present.+ if response.status_code == 429:+ raise FreshcallerRetryableError(+ f"Freshcaller API rate limited: url={page_url}",+ retry_after=_parse_retry_after(response.headers.get("Retry-After")),+ )++ if response.status_code >= 500:+ raise FreshcallerRetryableError(+ f"Freshcaller API error (retryable): status={response.status_code}, url={page_url}"+ )++ if not response.ok:+ logger.error(f"Freshcaller API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response.json()++ while True:+ params = {**base_params, "page": str(page)}+ url = f"{base}{config.path}?{urlencode(params)}"++ data = fetch_page(url)+ items = extract_items(data, config)+ if items:+ yield items++ if not _has_next_page(extract_meta(data), items, page):+ break++ # Advance and save AFTER yielding so the just-written page is durable before we bookmark+ # the next one; a crash re-fetches from `page` and merge dedupes on the primary key.+ page += 1+ resumable_source_manager.save_state(FreshcallerResumeConfig(page=page))+++def freshcaller_source(+ api_key: str,+ subdomain: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FreshcallerResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> SourceResponse:+ config = FRESHCALLER_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ subdomain=subdomain,+ 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=["id"],+ partition_count=1 if config.partition_key else None,+ partition_size=1 if config.partition_key else None,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ # Freshcaller list endpoints expose no sort param and don't document their default order.+ # For incremental endpoints we page the full [watermark, now] window each sync and dedupe+ # on `id`, so declaring "desc" defers the watermark commit to end-of-sync — keeping the+ # cursor correct regardless of the API's actual intra-window ordering. Full-refresh+ # endpoints carry no watermark, so the mode is irrelevant there.+ sort_mode="desc" if config.supports_incremental else "asc",+ )+++def validate_credentials(subdomain: str, api_key: str) -> Optional[int]:+ """Probe the Freshcaller API. Returns the HTTP status code, or ``None`` on a connection error."""+ url = f"{_base_url(subdomain)}/api/v1/users?per_page=1"+ try:+ response = make_tracked_session(redact_values=(api_key,)).get(+ url, headers=_get_headers(api_key), timeout=VALIDATE_TIMEOUT+ )+ except Exception:+ return None++ return response.status_codediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshcaller/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshcaller/settings.pynew file mode 100644index 000000000000..b2e0511b18e9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshcaller/settings.py@@ -0,0 +1,88 @@+"""Freshcaller source settings and endpoint catalog."""++from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Freshcaller allows up to 1000 records per page (default 10). Match Airbyte's connector,+# which pulls the max page size to keep the request count (and thus rate-limit pressure) low.+PER_PAGE = 1000++# Both required together; `by_time` filters Calls / Call Metrics on the stable `created_time`+# field. Absent an incremental watermark we bound the first backfill at this date rather than+# scanning all history — Freshcaller's own connectors default the backfill floor to 2022.+DEFAULT_START_DATETIME = "2022-01-01T00:00:00Z"+++@dataclass+class FreshcallerEndpointConfig:+ name: str+ path: str+ # Freshcaller wraps each list response in an object keyed by the plural resource name+ # (e.g. {"users": [...], "meta": {...}}); `data_key` is that key.+ data_key: str+ # `True` only where the list endpoint honors a genuine server-side `by_time` window on+ # `created_time`. `users`/`teams` expose no time filter -> full refresh only.+ supports_incremental: bool = False+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable datetime field used for partitioning. Always a creation timestamp, never a+ # mutable field (partitions must not rewrite on every sync).+ partition_key: Optional[str] = None+ # Extra static query params (e.g. `include=life_cycle` on call_metrics).+ extra_params: dict[str, str] = field(default_factory=dict)+++def _datetime_incremental_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++# Freshcaller v1 top-level endpoints.+#+# Incremental support (Calls, Call Metrics via `by_time[from]`/`by_time[to]` on `created_time`)+# follows Freshcaller's shipped Airbyte connector. The public API reference only documents the+# `by_time` filter on Call Metrics, so the Calls filter is unverified against a live account with+# credentials — if a curl smoke test shows Calls silently ignores `by_time`, flip `calls` to full+# refresh. Merge dedupes on `id` either way, so a silently-ignored filter degrades to full-refresh+# cost, never wrong data.+FRESHCALLER_ENDPOINTS: dict[str, FreshcallerEndpointConfig] = {+ "users": FreshcallerEndpointConfig(+ name="users",+ path="/api/v1/users",+ data_key="users",+ ),+ "teams": FreshcallerEndpointConfig(+ name="teams",+ path="/api/v1/teams",+ data_key="teams",+ ),+ "calls": FreshcallerEndpointConfig(+ name="calls",+ path="/api/v1/calls",+ data_key="calls",+ supports_incremental=True,+ incremental_fields=[_datetime_incremental_field("created_time")],+ partition_key="created_time",+ ),+ "call_metrics": FreshcallerEndpointConfig(+ name="call_metrics",+ path="/api/v1/call_metrics",+ data_key="call_metrics",+ supports_incremental=True,+ incremental_fields=[_datetime_incremental_field("created_time")],+ partition_key="created_time",+ # Pull the call lifecycle sub-resource alongside each metric row, matching Airbyte.+ extra_params={"include": "life_cycle"},+ ),+}++ENDPOINTS = tuple(FRESHCALLER_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in FRESHCALLER_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshcaller/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshcaller/source.pyindex a953e21435c6..ab88f988df6c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshcaller/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshcaller/source.py@@ -1,30 +1,180 @@-from typing import cast+import re+from typing import Optional, castfrom 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.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.freshcaller.freshcaller import (+ FreshcallerResumeConfig,+ freshcaller_source,+ normalize_subdomain,+ validate_credentials as validate_freshcaller_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.freshcaller.settings import FRESHCALLER_ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FreshcallerSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType+# This first cut covers Freshcaller's top-level v1 list endpoints (Users, Teams, Calls, Call+# Metrics). Account-level data export is an asynchronous request/poll job rather than a list+# endpoint, and recording download/delete are per-call side endpoints — both are intentionally+# left out of this first cut. There is no webhook management API.++_SUBDOMAIN_REGEX = re.compile(r"^[a-zA-Z0-9-]+$")++# User-facing auth/permission messages, shared between sync-time (get_non_retryable_errors) and+# connect-time (validate_credentials) so the two can't drift.+_ERR_AUTH_FAILED = "Freshcaller authentication failed. Please check your API key and account name."+_ERR_FORBIDDEN = "Your Freshcaller API key does not have permission for this resource. Check the agent's role/scope."+@SourceRegistry.register-class FreshcallerSource(SimpleSource[FreshcallerSourceConfig]):+class FreshcallerSource(ResumableSource[FreshcallerSourceConfig, FreshcallerResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.FRESHCALLER+ @property+ def connection_host_fields(self) -> list[str]:+ # Freshcaller's connection target is the account subdomain, not a `host` field. Editing it+ # on an existing source must force the API key to be re-entered.+ return ["subdomain"]++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.freshcaller.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": _ERR_AUTH_FAILED,+ "403 Client Error: Forbidden for url": _ERR_FORBIDDEN,+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.FRESHCALLER,category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,label="Freshcaller",+ caption="""Enter your Freshcaller account name and API key to pull your Freshcaller call-center data into the PostHog Data warehouse.++Your **account name** is the subdomain in your Freshcaller URL — e.g. `acme` for `acme.freshcaller.com`.++Your **API key** is on your Freshcaller profile settings page (click your profile picture → **Profile settings**; the API key is shown in the right sidebar).""",iconPath="/static/services/freshcaller.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/freshcaller",+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="subdomain",+ label="Freshcaller account name",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="acme",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: FreshcallerSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=name,+ # Only Calls / Call Metrics expose a server-side `by_time` window; the rest are+ # full refresh only.+ supports_incremental=endpoint.supports_incremental,+ supports_append=endpoint.supports_incremental,+ incremental_fields=endpoint.incremental_fields,+ detected_primary_keys=["id"],+ )+ for name, endpoint in FRESHCALLER_ENDPOINTS.items()+ ]+ 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: FreshcallerSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if not _SUBDOMAIN_REGEX.match(normalize_subdomain(config.subdomain)):+ return False, "Freshcaller account name is invalid"++ status = validate_freshcaller_credentials(config.subdomain, config.api_key)++ if status == 200:+ return True, None++ # A valid key that simply lacks scope for the probe endpoint returns 403. Accept it at+ # source-create (schema_name is None) — users may only grant the scopes they want to sync.+ if status == 403 and schema_name is None:+ return True, None++ if status == 403:+ return False, _ERR_FORBIDDEN++ if status == 401:+ return False, _ERR_AUTH_FAILED++ return False, "Could not connect to Freshcaller. Please check your account name and API key."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FreshcallerResumeConfig]:+ return ResumableSourceManager[FreshcallerResumeConfig](inputs, FreshcallerResumeConfig)++ def source_for_pipeline(+ self,+ config: FreshcallerSourceConfig,+ resumable_source_manager: ResumableSourceManager[FreshcallerResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return freshcaller_source(+ api_key=config.api_key,+ subdomain=config.subdomain,+ 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/products/warehouse_sources/backend/temporal/data_imports/sources/freshcaller/tests/test_freshcaller.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshcaller/tests/test_freshcaller.pynew file mode 100644index 000000000000..5ff6afd06194--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshcaller/tests/test_freshcaller.py@@ -0,0 +1,298 @@+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import parse_qs, urlparse++import pytest+from unittest import mock++import requests+import structlog++from products.warehouse_sources.backend.temporal.data_imports.sources.freshcaller.freshcaller import (+ FreshcallerResumeConfig,+ _format_datetime,+ _has_next_page,+ _parse_retry_after,+ build_base_params,+ extract_items,+ extract_meta,+ get_rows,+ normalize_subdomain,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.freshcaller.settings import (+ DEFAULT_START_DATETIME,+ FRESHCALLER_ENDPOINTS,+)++logger = structlog.get_logger()++PATCH_SESSION = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.freshcaller.freshcaller.make_tracked_session"+)+++class FakeResponse:+ def __init__(+ self,+ json_data: Any = None,+ status_code: int = 200,+ text: str = "",+ headers: Optional[dict] = None,+ ) -> None:+ self._json = json_data+ self.status_code = status_code+ self.ok = 200 <= status_code < 400+ self.text = text+ self.headers = headers or {}++ def json(self) -> Any:+ return self._json++ def raise_for_status(self) -> None:+ if not self.ok:+ real_response = requests.Response()+ real_response.status_code = self.status_code+ raise requests.HTTPError(f"{self.status_code} Client Error", response=real_response)+++class FakeResumableManager:+ def __init__(self, resume: Optional[FreshcallerResumeConfig] = None) -> None:+ self._resume = resume+ self.saved: list[FreshcallerResumeConfig] = []++ def can_resume(self) -> bool:+ return self._resume is not None++ def load_state(self) -> Optional[FreshcallerResumeConfig]:+ return self._resume++ def save_state(self, data: FreshcallerResumeConfig) -> None:+ self.saved.append(data)+++def _page(data_key: str, items: list[dict], current: int, total_pages: int) -> dict:+ return {data_key: items, "meta": {"current": current, "total_pages": total_pages, "total_count": 999}}+++class TestNormalizeSubdomain:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ ("acme", "acme"),+ ("acme.freshcaller.com", "acme"),+ ("https://acme.freshcaller.com", "acme"),+ ("http://acme.freshcaller.com/", "acme"),+ (" acme ", "acme"),+ ("acme.freshcaller.com/api/v1/calls", "acme"),+ ],+ )+ def test_normalize_subdomain(self, raw: str, expected: str) -> None:+ assert normalize_subdomain(raw) == expected+++class TestFormatDatetime:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),+ (date(2026, 3, 4), "2026-03-04T00:00:00Z"),+ ("2022-01-01T00:00:00Z", "2022-01-01T00:00:00Z"),+ ],+ )+ def test_format_datetime(self, value: Any, expected: str) -> None:+ assert _format_datetime(value) == expected++ def test_no_offset_suffix(self) -> None:+ # Freshcaller wants a Z suffix, never the +00:00 that isoformat() emits.+ assert "+00:00" not in _format_datetime(datetime(2026, 3, 4, tzinfo=UTC))+++class TestParseRetryAfter:+ @pytest.mark.parametrize(+ "value, expected",+ [("30", 30.0), ("0", 0.0), (None, None), ("", None), ("not-a-number", None)],+ )+ def test_parse_retry_after(self, value: Optional[str], expected: Optional[float]) -> None:+ assert _parse_retry_after(value) == expected+++class TestBuildBaseParams:+ def test_full_refresh_has_per_page_only(self) -> None:+ params = build_base_params(FRESHCALLER_ENDPOINTS["users"], False, None)+ assert params == {"per_page": "1000"}++ def test_incremental_calls_uses_by_time_window(self) -> None:+ params = build_base_params(FRESHCALLER_ENDPOINTS["calls"], True, datetime(2026, 3, 4, tzinfo=UTC))+ assert params["by_time[from]"] == "2026-03-04T00:00:00Z"+ # `to` is bounded at "now"; only assert the window is anchored at the watermark.+ assert "by_time[to]" in params++ def test_incremental_without_watermark_uses_default_floor(self) -> None:+ params = build_base_params(FRESHCALLER_ENDPOINTS["calls"], True, None)+ assert params["by_time[from]"] == DEFAULT_START_DATETIME++ def test_call_metrics_includes_life_cycle(self) -> None:+ params = build_base_params(FRESHCALLER_ENDPOINTS["call_metrics"], True, None)+ assert params["include"] == "life_cycle"+ assert "by_time[from]" in params++ def test_full_refresh_endpoint_ignores_incremental_flag(self) -> None:+ # `teams` exposes no server-side time filter, so it never gets a by_time window.+ params = build_base_params(FRESHCALLER_ENDPOINTS["teams"], True, datetime(2026, 3, 4, tzinfo=UTC))+ assert "by_time[from]" not in params+++class TestExtractItems:+ @pytest.mark.parametrize("endpoint", ["users", "teams", "calls", "call_metrics"])+ def test_wrapper_key(self, endpoint: str) -> None:+ config = FRESHCALLER_ENDPOINTS[endpoint]+ assert extract_items({config.data_key: [{"id": 1}]}, config) == [{"id": 1}]++ def test_wrong_wrapper_key_returns_empty(self) -> None:+ assert extract_items({"something_else": [{"id": 1}]}, FRESHCALLER_ENDPOINTS["users"]) == []++ def test_bare_array_fallback(self) -> None:+ assert extract_items([{"id": 1}], FRESHCALLER_ENDPOINTS["users"]) == [{"id": 1}]++ def test_unknown_shape_returns_empty(self) -> None:+ assert extract_items({"meta": {}}, FRESHCALLER_ENDPOINTS["users"]) == []+++class TestExtractMeta:+ def test_present(self) -> None:+ assert extract_meta({"users": [], "meta": {"current": 1}}) == {"current": 1}++ def test_absent(self) -> None:+ assert extract_meta({"users": []}) == {}+ assert extract_meta([{"id": 1}]) == {}+++class TestHasNextPage:+ @pytest.mark.parametrize(+ "meta, items, page, expected",+ [+ ({"current": 1, "total_pages": 3}, [{"id": 1}], 1, True),+ ({"current": 3, "total_pages": 3}, [{"id": 1}], 3, False),+ ({}, [{"id": i} for i in range(1000)], 1, True), # full page, no meta -> maybe more+ ({}, [{"id": 1}], 1, False), # short page, no meta -> done+ ({"current": 1, "total_pages": 2}, [], 1, False), # empty page always terminates+ ],+ )+ def test_has_next_page(self, meta: dict, items: list[dict], page: int, expected: bool) -> None:+ assert _has_next_page(meta, items, page) is expected+++class TestGetRows:+ def test_paginates_by_page_number_and_saves_state(self) -> None:+ responses = [+ FakeResponse(_page("calls", [{"id": 1}], current=1, total_pages=2)),+ FakeResponse(_page("calls", [{"id": 2}], current=2, total_pages=2)),+ ]+ manager = FakeResumableManager()+ session = mock.MagicMock()+ session.get.side_effect = responses++ with mock.patch(PATCH_SESSION, return_value=session):+ rows = list(get_rows("key", "acme", "calls", logger, manager)) # type: ignore[arg-type]++ assert rows == [[{"id": 1}], [{"id": 2}]]+ # State saved once, pointing at page 2 (the next page after the first was written).+ assert manager.saved == [FreshcallerResumeConfig(page=2)]+ # First request is page 1.+ first_url = session.get.call_args_list[0].args[0]+ assert parse_qs(urlparse(first_url).query)["page"] == ["1"]++ def test_single_page_saves_no_state(self) -> None:+ manager = FakeResumableManager()+ session = mock.MagicMock()+ session.get.side_effect = [FakeResponse(_page("users", [{"id": 1}], current=1, total_pages=1))]++ with mock.patch(PATCH_SESSION, return_value=session):+ rows = list(get_rows("key", "acme", "users", logger, manager)) # type: ignore[arg-type]++ assert rows == [[{"id": 1}]]+ assert manager.saved == []++ def test_session_redacts_api_key_from_samples(self) -> None:+ # The key rides in the X-Api-Auth header, which the name-based sample scrubbers don't+ # cover, so it must be value-redacted or it leaks into captured HTTP samples.+ manager = FakeResumableManager()+ session = mock.MagicMock()+ session.get.side_effect = [FakeResponse(_page("users", [{"id": 1}], current=1, total_pages=1))]++ with mock.patch(PATCH_SESSION, return_value=session) as mock_make:+ list(get_rows("secret-key", "acme", "users", logger, manager)) # type: ignore[arg-type]++ assert mock_make.call_args.kwargs.get("redact_values") == ("secret-key",)++ def test_resumes_from_saved_page(self) -> None:+ manager = FakeResumableManager(resume=FreshcallerResumeConfig(page=5))+ session = mock.MagicMock()+ session.get.side_effect = [FakeResponse(_page("calls", [{"id": 50}], current=5, total_pages=5))]++ with mock.patch(PATCH_SESSION, return_value=session):+ rows = list(get_rows("key", "acme", "calls", logger, manager)) # type: ignore[arg-type]++ assert rows == [[{"id": 50}]]+ # First request must hit the resumed page, not page 1.+ first_url = session.get.call_args_list[0].args[0]+ assert parse_qs(urlparse(first_url).query)["page"] == ["5"]++ def test_incremental_request_carries_by_time_window(self) -> None:+ manager = FakeResumableManager()+ session = mock.MagicMock()+ session.get.side_effect = [FakeResponse(_page("calls", [{"id": 1}], current=1, total_pages=1))]++ with mock.patch(PATCH_SESSION, return_value=session):+ list(+ get_rows(+ "key",+ "acme",+ "calls",+ logger,+ manager, # type: ignore[arg-type]+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ )+ )++ query = parse_qs(urlparse(session.get.call_args_list[0].args[0]).query)+ assert query["by_time[from]"] == ["2026-03-04T00:00:00Z"]++ @pytest.mark.parametrize("status_code", [401, 403, 404])+ def test_non_retryable_status_raises(self, status_code: int) -> None:+ manager = FakeResumableManager()+ session = mock.MagicMock()+ session.get.side_effect = [FakeResponse(status_code=status_code, text="boom")]++ with mock.patch(PATCH_SESSION, return_value=session):+ with pytest.raises(requests.HTTPError):+ list(get_rows("key", "acme", "calls", logger, manager)) # type: ignore[arg-type]+++class TestValidateCredentials:+ @pytest.mark.parametrize("status_code", [200, 401, 403])+ def test_returns_status_code(self, status_code: int) -> None:+ session = mock.MagicMock()+ session.get.return_value = FakeResponse(status_code=status_code)++ with mock.patch(PATCH_SESSION, return_value=session):+ assert validate_credentials("acme", "key") == status_code++ def test_connection_error_returns_none(self) -> None:+ session = mock.MagicMock()+ session.get.side_effect = requests.ConnectionError("nope")++ with mock.patch(PATCH_SESSION, return_value=session):+ assert validate_credentials("acme", "key") is None++ def test_session_redacts_api_key_from_samples(self) -> None:+ session = mock.MagicMock()+ session.get.return_value = FakeResponse(status_code=200)++ with mock.patch(PATCH_SESSION, return_value=session) as mock_make:+ validate_credentials("acme", "secret-key")++ assert mock_make.call_args.kwargs.get("redact_values") == ("secret-key",)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshcaller/tests/test_freshcaller_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshcaller/tests/test_freshcaller_source.pynew file mode 100644index 000000000000..e7d915a67bd1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshcaller/tests/test_freshcaller_source.py@@ -0,0 +1,166 @@+from typing import Optional++import pytest+from unittest import mock++import structlog++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.freshcaller.freshcaller import (+ FreshcallerResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.freshcaller.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.freshcaller.source import FreshcallerSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FreshcallerSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++PATCH_VALIDATE = "products.warehouse_sources.backend.temporal.data_imports.sources.freshcaller.source.validate_freshcaller_credentials"+++def _make_inputs(schema_name: str = "calls") -> SourceInputs:+ return SourceInputs(+ 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=structlog.get_logger(),+ reset_pipeline=False,+ )+++class TestFreshcallerSource:+ def setup_method(self) -> None:+ self.source = FreshcallerSource()+ self.team_id = 1+ self.config = FreshcallerSourceConfig(subdomain="acme", api_key="key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.FRESHCALLER++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Freshcaller"+ assert config.label == "Freshcaller"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # First cut ships hidden until validated end-to-end against a live account.+ assert config.unreleasedSource is True+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/freshcaller"++ fields = config.fields+ assert len(fields) == 2+ subdomain_field, api_key_field = fields+ assert isinstance(subdomain_field, SourceFieldInputConfig)+ assert subdomain_field.name == "subdomain"+ assert subdomain_field.type == SourceFieldInputConfigType.TEXT+ assert subdomain_field.secret is False+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.name == "api_key"+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog -> the public docs Supported-tables section can render.+ assert self.source.lists_tables_without_credentials is True++ def test_connection_host_fields(self) -> None:+ # The subdomain is where the stored key is sent; editing it must re-require the secret.+ assert self.source.connection_host_fields == ["subdomain"]++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error: Forbidden for url"])+ def test_non_retryable_errors(self, expected_key: str) -> None:+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_schemas_covers_all_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "name, supports_incremental",+ [+ ("calls", True),+ ("call_metrics", True),+ ("users", False),+ ("teams", False),+ ],+ )+ def test_schema_incremental_support(self, name: str, supports_incremental: bool) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ schema = schemas[name]+ assert schema.supports_incremental is supports_incremental+ assert schema.supports_append is supports_incremental+ if supports_incremental:+ assert [f["field"] for f in schema.incremental_fields] == ["created_time"]++ 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_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_canonical_descriptions_cover_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "subdomain, status, schema_name, expected_valid",+ [+ ("acme", 200, None, True),+ ("acme", 403, None, True), # missing scope at source-create is accepted+ ("acme", 403, "calls", False), # missing scope for a specific schema fails+ ("acme", 401, None, False),+ ("acme", None, None, False), # connection error+ ("invalid domain!", 200, None, False), # account-name regex rejects before probing+ ],+ )+ def test_validate_credentials(+ self, subdomain: str, status: Optional[int], schema_name: Optional[str], expected_valid: bool+ ) -> None:+ config = FreshcallerSourceConfig(subdomain=subdomain, api_key="key")+ with mock.patch(PATCH_VALIDATE, return_value=status) as mock_validate:+ is_valid, _ = self.source.validate_credentials(config, self.team_id, schema_name)++ assert is_valid is expected_valid+ if "!" in subdomain or " " in subdomain:+ mock_validate.assert_not_called()++ def test_get_resumable_source_manager_binds_data_class(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is FreshcallerResumeConfig++ def test_source_for_pipeline_incremental_endpoint_partitions_and_sorts_desc(self) -> None:+ inputs = _make_inputs("calls")+ manager = self.source.get_resumable_source_manager(inputs)++ response = self.source.source_for_pipeline(self.config, manager, inputs)++ assert response.name == "calls"+ assert response.primary_keys == ["id"]+ # Calls partition on the stable created_time field.+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_time"]+ # Full-window-per-sync + unknown API order -> defer the watermark commit via desc.+ assert response.sort_mode == "desc"++ def test_source_for_pipeline_full_refresh_endpoint_has_no_partition(self) -> None:+ inputs = _make_inputs("users")+ manager = self.source.get_resumable_source_manager(inputs)++ response = self.source.source_for_pipeline(self.config, manager, inputs)++ assert response.name == "users"+ assert response.partition_mode is None+ assert response.partition_keys is None+ assert response.sort_mode == "asc"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.pyindex b098a56295d1..d98013e7cb45 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@@ -1252,7 +1252,8 @@ class FreshBooksSourceConfig(config.Config):@config.configclass FreshcallerSourceConfig(config.Config):- pass+ subdomain: str+ api_key: str@config.config