: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 aircall import source (#61162)
Tom Owersa28798fb8933
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 93460e245a73..e97597d6bd3f 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -44,6 +44,7 @@ the row lists both.| Source | Comm method | Primary library | Tracked transport || ------------- | --------------------------- | --------------------------------------------------------------- | --------------------------- |+| aircall | HTTP | requests | ✅ || attio | HTTP | requests + `rest_source.RESTClient` | ✅ || bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) || bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ |@@ -134,7 +135,6 @@ doesn't conflict with concurrent PRs.- active_campaign- adjust-- aircall- airtable- amazon_ads- amplitudediff --git a/posthog/temporal/data_imports/sources/aircall/aircall.py b/posthog/temporal/data_imports/sources/aircall/aircall.pynew file mode 100644index 000000000000..c8d2955a0982--- /dev/null+++ b/posthog/temporal/data_imports/sources/aircall/aircall.py@@ -0,0 +1,217 @@+import base64+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.aircall.settings import AIRCALL_ENDPOINTS, AircallEndpointConfig+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager++AIRCALL_BASE_URL = "https://api.aircall.io/v1"+# Aircall caps list pages at 50 items.+PAGE_SIZE = 50+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+++class AircallRetryableError(Exception):+ pass+++class AircallResumeConfig:+ next_url: str+++def _basic_auth_token(api_id: str, api_token: str) -> str:+ return base64.b64encode(f"{api_id}:{api_token}".encode("ascii")).decode("ascii")+++def _get_headers(api_id: str, api_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Basic {_basic_auth_token(api_id, api_token)}",+ "Accept": "application/json",+ }+++def _to_epoch(value: Any) -> Optional[int]:+ """Coerce an incremental cursor value to a UNIX timestamp for Aircall's `from` filter.++ Aircall stores and filters timestamps as epoch seconds, so the persisted watermark is+ already an int in the common case; datetimes are accepted defensively.+ """+ if value is None:+ return None+ if isinstance(value, bool):+ return None+ if isinstance(value, int):+ return value+ if isinstance(value, float):+ return int(value)+ if isinstance(value, datetime):+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return int(dt.timestamp())+ if isinstance(value, date):+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp())+ try:+ return int(value)+ except (TypeError, ValueError):+ return None+++def _build_url(path: str, params: dict[str, Any]) -> str:+ clean_params = {key: value for key, value in params.items() if value is not None}+ if not clean_params:+ return f"{AIRCALL_BASE_URL}{path}"+ return f"{AIRCALL_BASE_URL}{path}?{urlencode(clean_params)}"+++def _build_params(config: AircallEndpointConfig, from_value: Optional[int]) -> dict[str, Any]:+ params: dict[str, Any] = {"per_page": PAGE_SIZE}+ # Ascending creation order keeps already-fetched pages stable and lets the incremental+ # watermark advance monotonically. `from` filters on the resource creation date.+ if config.incremental_fields or config.reanchor_field:+ params["order"] = "asc"+ if from_value is not None:+ params["from"] = from_value+ return params+++def validate_credentials(api_id: str, api_token: str) -> bool:+ """Confirm the API key pair is valid. /v1/ping is a cheap authenticated probe."""+ try:+ response = make_tracked_session().get(+ f"{AIRCALL_BASE_URL}/ping",+ headers=_get_headers(api_id, api_token),+ timeout=10,+ )+ return response.status_code == 200+ except Exception:+ return False+++def get_rows(+ api_id: str,+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AircallResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = AIRCALL_ENDPOINTS[endpoint]+ headers = _get_headers(api_id, api_token)++ cursor_field = incremental_field or config.reanchor_field+ from_value = _to_epoch(db_incremental_field_last_value) if should_use_incremental_field else None++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None:+ url: str = resume_config.next_url+ logger.debug(f"Aircall: resuming from URL: {url}")+ else:+ url = _build_url(config.path, _build_params(config, from_value))++ @retry(+ retry=retry_if_exception_type((AircallRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+ )+ def fetch_page(page_url: str) -> dict[str, Any]:+ response = make_tracked_session().get(page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ # Aircall rate-limits at 120 req/min; 429s carry a reset header but exponential+ # backoff is sufficient here.+ if response.status_code == 429 or response.status_code >= 500:+ raise AircallRetryableError(f"Aircall API error (retryable): status={response.status_code}, url={page_url}")++ if not response.ok:+ logger.error(f"Aircall API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response.json()++ # Latest value of the re-anchor field seen across the whole run. Used to step `from`+ # past Aircall's hard 10k-record-per-query cap on calls/contacts once a page chain ends.+ max_cursor: Optional[int] = None++ while True:+ data = fetch_page(url)+ items = data.get(config.data_key, []) or []++ if items:+ yield items++ if cursor_field is not None:+ page_max = max(+ (cursor for cursor in (_to_epoch(item.get(cursor_field)) for item in items) if cursor is not None),+ default=None,+ )+ if page_max is not None and (max_cursor is None or page_max > max_cursor):+ max_cursor = page_max++ next_url = (data.get("meta") or {}).get("next_page_link")++ if next_url:+ resumable_source_manager.save_state(AircallResumeConfig(next_url=next_url))+ url = next_url+ continue++ # Page chain ended. For capped endpoints, re-anchor on the latest cursor value to+ # fetch records beyond the 10k window. The strict-advance guard prevents an infinite+ # loop when many records share the boundary timestamp.+ if (+ config.reanchor_field is not None+ and max_cursor is not None+ and (from_value is None or max_cursor > from_value)+ ):+ from_value = max_cursor+ url = _build_url(config.path, _build_params(config, from_value))+ resumable_source_manager.save_state(AircallResumeConfig(next_url=url))+ logger.debug(f"Aircall: re-anchoring {endpoint} from={from_value} to page around the 10k cap")+ continue++ break+++def aircall_source(+ api_id: str,+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AircallResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = AIRCALL_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_id=api_id,+ api_token=api_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,+ incremental_field=incremental_field,+ ),+ primary_keys=[config.primary_key],+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ 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,+ )diff --git a/posthog/temporal/data_imports/sources/aircall/settings.py b/posthog/temporal/data_imports/sources/aircall/settings.pynew file mode 100644index 000000000000..21602b507943--- /dev/null+++ b/posthog/temporal/data_imports/sources/aircall/settings.py@@ -0,0 +1,89 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class AircallEndpointConfig:+ name: str+ path: str+ # Key the list of objects is nested under in the response body (e.g. {"calls": [...]}).+ data_key: str+ primary_key: str = "id"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable creation-time field used for datetime partitioning. Never an updated_at-style+ # field, which would rewrite partitions on every sync.+ partition_key: Optional[str] = None+ # When set, the transport re-anchors the `from` query param to the latest value of this+ # field once a page chain ends, to page around Aircall's hard 10k-record-per-query cap on+ # calls/contacts. Must be the same stable creation-time field the API's `from` filter+ # applies to.+ reanchor_field: Optional[str] = None+++# Aircall timestamps are UNIX epoch seconds, so candidate incremental fields are stored as+# integers even though the UI presents them as datetimes. The `from`/`to` list filters take+# UNIX timestamps and filter on the resource's creation date, so incremental sync is only+# enabled where the cursor field lines up with what `from` actually filters on (calls ->+# started_at, contacts -> created_at). Everything else is full refresh.+AIRCALL_ENDPOINTS: dict[str, AircallEndpointConfig] = {+ "calls": AircallEndpointConfig(+ name="calls",+ path="/calls",+ data_key="calls",+ partition_key="started_at",+ reanchor_field="started_at",+ incremental_fields=[+ {+ "label": "started_at",+ "type": IncrementalFieldType.DateTime,+ "field": "started_at",+ "field_type": IncrementalFieldType.Integer,+ },+ ],+ ),+ "contacts": AircallEndpointConfig(+ name="contacts",+ path="/contacts",+ data_key="contacts",+ partition_key="created_at",+ reanchor_field="created_at",+ incremental_fields=[+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.Integer,+ },+ ],+ ),+ "users": AircallEndpointConfig(+ name="users",+ path="/users",+ data_key="users",+ partition_key="created_at",+ ),+ "teams": AircallEndpointConfig(+ name="teams",+ path="/teams",+ data_key="teams",+ ),+ "numbers": AircallEndpointConfig(+ name="numbers",+ path="/numbers",+ data_key="numbers",+ partition_key="created_at",+ ),+ "tags": AircallEndpointConfig(+ name="tags",+ path="/tags",+ data_key="tags",+ ),+}++ENDPOINTS = tuple(AIRCALL_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in AIRCALL_ENDPOINTS.items() if config.incremental_fields+}diff --git a/posthog/temporal/data_imports/sources/aircall/source.py b/posthog/temporal/data_imports/sources/aircall/source.pyindex 82793ba60a3a..bc25cf40c819 100644--- a/posthog/temporal/data_imports/sources/aircall/source.py+++ b/posthog/temporal/data_imports/sources/aircall/source.py@@ -1,29 +1,125 @@-from typing import cast+from typing import Optional, castfrom 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.aircall.aircall import (+ AircallResumeConfig,+ aircall_source,+ validate_credentials as validate_aircall_credentials,+)+from posthog.temporal.data_imports.sources.aircall.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom 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 SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import AircallSourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class AircallSource(SimpleSource[AircallSourceConfig]):+class AircallSource(ResumableSource[AircallSourceConfig, AircallResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.AIRCALL+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.aircall.io": "Aircall authentication failed. Please check your API ID and API token.",+ "403 Client Error: Forbidden for url: https://api.aircall.io": "Aircall denied access. Please check that your API key has the required permissions.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.AIRCALL,label="Aircall",+ caption="""Enter your Aircall API credentials to pull your Aircall data into the PostHog Data warehouse.++You can create an API key (API ID + API token) in your [Aircall dashboard](https://dashboard.aircall.io/integrations/api-keys). The key has read access to all of your company's data.""",iconPath="/static/services/aircall.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/aircall",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_id",+ label="API ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: AircallSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint, None) is not None,+ supports_append=INCREMENTAL_FIELDS.get(endpoint, None) is not None,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ for endpoint in list(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: AircallSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_aircall_credentials(config.api_id, config.api_token):+ return True, None++ return False, "Invalid Aircall API credentials"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AircallResumeConfig]:+ return ResumableSourceManager[AircallResumeConfig](inputs, AircallResumeConfig)++ def source_for_pipeline(+ self,+ config: AircallSourceConfig,+ resumable_source_manager: ResumableSourceManager[AircallResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return aircall_source(+ api_id=config.api_id,+ api_token=config.api_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,+ incremental_field=inputs.incremental_field,)diff --git a/posthog/temporal/data_imports/sources/aircall/tests/test_aircall.py b/posthog/temporal/data_imports/sources/aircall/tests/test_aircall.pynew file mode 100644index 000000000000..31c8995a2b8e--- /dev/null+++ b/posthog/temporal/data_imports/sources/aircall/tests/test_aircall.py@@ -0,0 +1,203 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest import mock++from posthog.temporal.data_imports.sources.aircall.aircall import (+ AircallResumeConfig,+ _build_params,+ _build_url,+ _to_epoch,+ aircall_source,+ get_rows,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.aircall.settings import AIRCALL_ENDPOINTS, ENDPOINTS+++def _make_manager(resume_state: AircallResumeConfig | 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(items_key: str, items: list[dict[str, Any]], next_link: str | None) -> dict[str, Any]:+ return {"meta": {"next_page_link": next_link}, items_key: items}+++class TestToEpoch:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (None, None),+ (1700000000, 1700000000),+ (1700000000.9, 1700000000),+ ("1700000000", 1700000000),+ (datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC), 1700000000),+ (date(2023, 11, 15), int(datetime(2023, 11, 15, tzinfo=UTC).timestamp())),+ ("not-a-number", None),+ (True, None),+ ],+ )+ def test_to_epoch_values(self, value, expected):+ assert _to_epoch(value) == expected+++class TestBuildParams:+ def test_incremental_endpoint_requests_ascending_order(self):+ params = _build_params(AIRCALL_ENDPOINTS["calls"], from_value=None)+ assert params["order"] == "asc"+ assert params["per_page"] == 50+ assert "from" not in params++ def test_from_value_included_when_set(self):+ params = _build_params(AIRCALL_ENDPOINTS["calls"], from_value=1700000000)+ assert params["from"] == 1700000000++ def test_full_refresh_endpoint_without_cursor_has_no_order(self):+ params = _build_params(AIRCALL_ENDPOINTS["teams"], from_value=None)+ assert "order" not in params+ assert "from" not in params+++class TestBuildUrl:+ def test_no_params(self):+ assert _build_url("/calls", {}) == "https://api.aircall.io/v1/calls"++ def test_drops_none_values_and_encodes(self):+ url = _build_url("/calls", {"per_page": 50, "from": None, "order": "asc"})+ assert url == "https://api.aircall.io/v1/calls?per_page=50&order=asc"+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected",+ [+ (200, True),+ (401, False),+ (403, False),+ (500, False),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.aircall.aircall.make_tracked_session")+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):+ response = mock.MagicMock()+ response.status_code = status_code+ mock_session.return_value.get.return_value = response++ assert validate_credentials("id", "token") is expected++ @mock.patch("posthog.temporal.data_imports.sources.aircall.aircall.make_tracked_session")+ def test_validate_credentials_swallows_exceptions(self, mock_session):+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("id", "token") is False+++class TestGetRows:+ @mock.patch("posthog.temporal.data_imports.sources.aircall.aircall.make_tracked_session")+ def test_paginates_via_next_page_link(self, mock_session):+ pages = [+ _page("users", [{"id": 1}, {"id": 2}], "https://api.aircall.io/v1/users?page=2"),+ _page("users", [{"id": 3}], None),+ ]+ responses = []+ for page in pages:+ resp = mock.MagicMock()+ resp.json.return_value = page+ resp.status_code = 200+ resp.ok = True+ responses.append(resp)+ mock_session.return_value.get.side_effect = responses++ manager = _make_manager()+ batches = list(get_rows("id", "token", "users", mock.MagicMock(), manager))++ assert [item["id"] for batch in batches for item in batch] == [1, 2, 3]+ # State is saved only while a next page exists.+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0].next_url == "https://api.aircall.io/v1/users?page=2"++ @mock.patch("posthog.temporal.data_imports.sources.aircall.aircall.make_tracked_session")+ def test_resumes_from_saved_state(self, mock_session):+ resp = mock.MagicMock()+ resp.json.return_value = _page("users", [{"id": 9}], None)+ resp.status_code = 200+ resp.ok = True+ mock_session.return_value.get.return_value = resp++ resume_url = "https://api.aircall.io/v1/users?page=5"+ manager = _make_manager(AircallResumeConfig(next_url=resume_url))++ list(get_rows("id", "token", "users", mock.MagicMock(), manager))++ assert mock_session.return_value.get.call_args_list[0].args[0] == resume_url++ @mock.patch("posthog.temporal.data_imports.sources.aircall.aircall.make_tracked_session")+ def test_reanchors_from_cursor_to_page_around_cap(self, mock_session):+ # First window ends without a next link; the latest started_at is used to issue a+ # fresh `from`-anchored request, then that window ends with no new advancement.+ first_window = _page("calls", [{"id": 1, "started_at": 100}, {"id": 2, "started_at": 200}], None)+ second_window = _page("calls", [{"id": 2, "started_at": 200}], None)++ resp1 = mock.MagicMock(status_code=200, ok=True)+ resp1.json.return_value = first_window+ resp2 = mock.MagicMock(status_code=200, ok=True)+ resp2.json.return_value = second_window+ mock_session.return_value.get.side_effect = [resp1, resp2]++ manager = _make_manager()+ batches = list(get_rows("id", "token", "calls", mock.MagicMock(), manager))++ # Two requests: original window + one re-anchored window.+ assert mock_session.return_value.get.call_count == 2+ second_url = mock_session.return_value.get.call_args_list[1].args[0]+ assert "from=200" in second_url+ # Boundary row re-emitted; merge on primary key dedupes downstream.+ assert [item["id"] for batch in batches for item in batch] == [1, 2, 2]++ @mock.patch("posthog.temporal.data_imports.sources.aircall.aircall.make_tracked_session")+ def test_no_reanchor_for_full_refresh_endpoint(self, mock_session):+ resp = mock.MagicMock(status_code=200, ok=True)+ resp.json.return_value = _page("teams", [{"id": 1}], None)+ mock_session.return_value.get.return_value = resp++ manager = _make_manager()+ list(get_rows("id", "token", "teams", mock.MagicMock(), manager))++ assert mock_session.return_value.get.call_count == 1++ @mock.patch("posthog.temporal.data_imports.sources.aircall.aircall.make_tracked_session")+ def test_empty_response_stops(self, mock_session):+ resp = mock.MagicMock(status_code=200, ok=True)+ resp.json.return_value = _page("calls", [], None)+ mock_session.return_value.get.return_value = resp++ manager = _make_manager()+ batches = list(get_rows("id", "token", "calls", mock.MagicMock(), manager))++ assert batches == []+ manager.save_state.assert_not_called()+++class TestAircallSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = AIRCALL_ENDPOINTS[endpoint]+ response = aircall_source("id", "token", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == [config.primary_key]+ 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(AIRCALL_ENDPOINTS.values()))+ def test_partition_keys_are_stable_creation_fields(self, config):+ if config.partition_key:+ assert config.partition_key in {"started_at", "created_at"}diff --git a/posthog/temporal/data_imports/sources/aircall/tests/test_aircall_source.py b/posthog/temporal/data_imports/sources/aircall/tests/test_aircall_source.pynew file mode 100644index 000000000000..5f1f3e1dccc5--- /dev/null+++ b/posthog/temporal/data_imports/sources/aircall/tests/test_aircall_source.py@@ -0,0 +1,144 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.aircall.aircall import AircallResumeConfig+from posthog.temporal.data_imports.sources.aircall.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.aircall.source import AircallSource+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import AircallSourceConfig++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestAircallSource:+ def setup_method(self):+ self.source = AircallSource()+ self.team_id = 123+ self.config = AircallSourceConfig(api_id="api-id", api_token="api-token")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.AIRCALL++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Aircall"+ assert config.label == "Aircall"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/aircall.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_id", "api_token"]++ def test_api_token_field_is_secret_password(self):+ config = self.source.get_source_config+ token_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.aircall.io/v1/calls?per_page=50",+ "403 Client Error: Forbidden for url: https://api.aircall.io/v1/contacts",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ 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",+ "500 Server Error for url: https://api.aircall.io/v1/calls",+ ],+ )+ def test_non_retryable_errors_does_not_match_unrelated(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 for schema in schemas if schema.supports_incremental}+ # Only calls and contacts expose Aircall's server-side `from` timestamp filter.+ assert by_name == {"calls", "contacts"}++ def test_incremental_schemas_advertise_their_fields(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas["calls"].incremental_fields == INCREMENTAL_FIELDS["calls"]+ assert schemas["contacts"].incremental_fields == INCREMENTAL_FIELDS["contacts"]+ assert schemas["users"].incremental_fields == []+ assert schemas["users"].supports_append is False++ def test_get_schemas_filtered_by_names(self):+ 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):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ (True, True, None),+ (False, False, "Invalid Aircall API credentials"),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.aircall.source.validate_aircall_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.api_id, self.config.api_token)++ def test_get_resumable_source_manager_binds_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is AircallResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.aircall.source.aircall_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_aircall_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "calls"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = 1700000000+ inputs.incremental_field = "started_at"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_aircall_source.assert_called_once()+ kwargs = mock_aircall_source.call_args.kwargs+ assert kwargs["api_id"] == "api-id"+ assert kwargs["api_token"] == "api-token"+ 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+ assert kwargs["incremental_field"] == "started_at"++ @mock.patch("posthog.temporal.data_imports.sources.aircall.source.aircall_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_aircall_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "users"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = 1700000000+ inputs.incremental_field = None++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_aircall_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 27d517ef71a4..b248b2b7ab02 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -95,7 +95,8 @@ class AdjustSourceConfig(config.Config):@config.configclass AircallSourceConfig(config.Config):- pass+ api_id: str+ api_token: str@config.config