: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 customerly import source (#71212)
Tom Owers5623d8976ba0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex a1bb0bbf0cc1..efc0d5a3f29c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -140,6 +140,7 @@ the row lists both.| culture_amp | HTTP | requests | ✅ || cursor | HTTP | requests | ✅ || customer_io | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (App API) / ➖ (webhook) |+| customerly | HTTP | requests | ✅ || datadog | HTTP | requests | ✅ || dbt | HTTP | requests | ✅ || decagon | HTTP | requests | ✅ |@@ -594,7 +595,6 @@ doesn't conflict with concurrent PRs.- criteo- cronitor- curve-- customerly- dagster_cloud- databricks- datahubdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/customerly/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/customerly/canonical_descriptions.pynew file mode 100644index 000000000000..67aece243c7a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/customerly/canonical_descriptions.py@@ -0,0 +1,105 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++DOCS_URL = "https://documenter.getpostman.com/view/11487813/2s9Y5Wx3QG"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "users": {+ "description": "Registered users of your product — contacts identified with a user_id or email who have signed up.",+ "docs_url": DOCS_URL,+ "columns": {+ "crmhero_user_id": "Customerly's internal unique identifier for the contact.",+ "app_id": "Identifier of the Customerly project the contact belongs to.",+ "user_id": "Your own identifier for the user, as sent to Customerly.",+ "email": "Email address of the user.",+ "name": "Display name of the user.",+ "is_user": "1 when the contact is a registered user, 0 when they are a lead.",+ "was_lead": "1 when the user was previously a lead before converting.",+ "first_seen_at": "UNIX timestamp of when the contact was first seen.",+ "last_activity": "UNIX timestamp of the contact's most recent activity.",+ "last_update": "Datetime of the last change to the contact's profile.",+ "attributes": "Custom attributes set on the contact.",+ "unsubscribe": "1 when the contact has unsubscribed from emails.",+ "bounce": "1 when emails to the contact have bounced.",+ "spam": "1 when the contact marked an email as spam.",+ "last_page_viewed": "URL of the last page the contact viewed.",+ "last_page_viewed_at": "UNIX timestamp of the last page view.",+ "browser_name": "Browser the contact last used.",+ "os": "Operating system the contact last used.",+ "country": "Country resolved from the contact's IP address.",+ "city": "City resolved from the contact's IP address.",+ "timezone": "Timezone resolved from the contact's IP address.",+ "utm_source": "UTM source captured for the contact.",+ "utm_medium": "UTM medium captured for the contact.",+ "utm_campaign": "UTM campaign captured for the contact.",+ "nps_vote": "The contact's most recent NPS survey vote.",+ "rating": "The contact's most recent conversation rating.",+ },+ },+ "leads": {+ "description": "Leads — contacts who have shown interest (e.g. via live chat) but have not yet converted into registered users.",+ "docs_url": DOCS_URL,+ "columns": {+ "crmhero_user_id": "Customerly's internal unique identifier for the contact.",+ "app_id": "Identifier of the Customerly project the contact belongs to.",+ "email": "Email address of the lead.",+ "name": "Display name of the lead.",+ "is_user": "1 when the contact is a registered user, 0 when they are a lead.",+ "was_lead": "1 for contacts that are (or were) leads.",+ "first_seen_at": "UNIX timestamp of when the lead was first seen.",+ "last_activity": "UNIX timestamp of the lead's most recent activity.",+ "last_update": "Datetime of the last change to the lead's profile.",+ "attributes": "Custom attributes set on the lead.",+ "unsubscribe": "1 when the lead has unsubscribed from emails.",+ "bounce": "1 when emails to the lead have bounced.",+ "spam": "1 when the lead marked an email as spam.",+ "utm_source": "UTM source captured for the lead.",+ "utm_medium": "UTM medium captured for the lead.",+ "utm_campaign": "UTM campaign captured for the lead.",+ },+ },+ "tags": {+ "description": "Tags defined in the Customerly project, usable to segment users and leads.",+ "docs_url": DOCS_URL,+ "columns": {+ "name": "Name of the tag.",+ },+ },+ "knowledge_base_collections": {+ "description": "Knowledge base collections — groups of help center articles.",+ "docs_url": DOCS_URL,+ "columns": {+ "knowledge_base_collection_id": "Unique identifier of the collection.",+ "app_id": "Identifier of the Customerly project the collection belongs to.",+ "title": "Title of the collection.",+ "description": "Description of the collection.",+ "slug": "URL slug of the collection.",+ "icon": "Icon assigned to the collection.",+ "sort": "Sort position of the collection in the help center.",+ "locale": "Locale of the collection's content.",+ },+ },+ "knowledge_base_articles": {+ "description": "Knowledge base articles published in the help center, listed per collection.",+ "docs_url": DOCS_URL,+ "columns": {+ "knowledge_base_article_id": "Unique identifier of the article.",+ "knowledge_base_collection_id": "Identifier of the collection the article belongs to.",+ "app_id": "Identifier of the Customerly project the article belongs to.",+ "title": "Title of the article.",+ "description": "Short description of the article.",+ "body": "HTML body of the article.",+ "slug": "URL slug of the article.",+ "status": "Publication status of the article.",+ "written_by": "Identifier of the teammate who wrote the article.",+ "created_at": "UNIX timestamp of when the article was created.",+ "updated_at": "UNIX timestamp of the article's last update.",+ "num_visits": "Number of visits the article has received.",+ "num_positive_reactions": "Number of positive reactions on the article.",+ "num_neutral_reactions": "Number of neutral reactions on the article.",+ "num_negative_reactions": "Number of negative reactions on the article.",+ "keywords": "Keywords attached to the article.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/customerly/customerly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/customerly/customerly.pynew file mode 100644index 000000000000..c882a84b8fde--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/customerly/customerly.py@@ -0,0 +1,262 @@+import dataclasses+from collections.abc import Iterator+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.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.customerly.settings import (+ CUSTOMERLY_ENDPOINTS,+ CustomerlyEndpointConfig,+)++CUSTOMERLY_BASE_URL = "https://api.customerly.io/v1"+PAGE_SIZE = 50+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5++AUTH_ERROR_MARKERS = (+ "Access token not found",+ "You must provide a valid header",+)+++class CustomerlyRetryableError(Exception):+ pass+++class CustomerlyAuthenticationError(Exception):+ pass+++class CustomerlyResumeConfig:+ page: int+ # Set while walking the knowledge base articles fan-out: collections with a lower id+ # have already been fully synced and are skipped on resume.+ collection_id: Optional[int] = None+++def _get_headers(access_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {access_token}",+ "Accept": "application/json",+ }+++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"{CUSTOMERLY_BASE_URL}{path}"+ return f"{CUSTOMERLY_BASE_URL}{path}?{urlencode(clean_params)}"+++def _is_auth_error_body(body: str) -> bool:+ return any(marker in body for marker in AUTH_ERROR_MARKERS)+++def _make_fetch_page(headers: dict[str, str], logger: FilteringBoundLogger):+ @retry(+ retry=retry_if_exception_type((CustomerlyRetryableError, 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)++ # Customerly reports missing/invalid access tokens as HTTP 500 with an error body,+ # so auth failures must be detected before the generic retryable-5xx handling.+ if response.status_code in (401, 403, 500) and _is_auth_error_body(response.text):+ raise CustomerlyAuthenticationError(+ f"Customerly authentication failed: invalid or expired access token (url={page_url})"+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise CustomerlyRetryableError(+ f"Customerly API error (retryable): status={response.status_code}, url={page_url}"+ )++ if not response.ok:+ logger.error(f"Customerly API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response.json()++ return fetch_page+++def _extract_items(data: dict[str, Any], config: CustomerlyEndpointConfig) -> list[Any]:+ payload = data.get("data")+ if config.data_key is not None:+ if not isinstance(payload, dict):+ return []+ return payload.get(config.data_key) or []+ if isinstance(payload, list):+ return payload+ return []+++def _normalize_tags(items: list[Any]) -> list[dict[str, Any]]:+ # /v1/tags returns a bare list of tag names; shape them into rows.+ return [{"name": tag} for tag in items if isinstance(tag, str)]+++def validate_credentials(access_token: str) -> bool:+ """Confirm the access token is valid. /v1/tags is a cheap single-request probe."""+ try:+ response = make_tracked_session().get(+ f"{CUSTOMERLY_BASE_URL}/tags",+ headers=_get_headers(access_token),+ timeout=10,+ )+ return response.ok+ except Exception:+ return False+++def _paginate(+ fetch_page,+ path: str,+ base_params: dict[str, Any],+ config: CustomerlyEndpointConfig,+ start_page: int,+ on_page_complete,+) -> Iterator[list[dict[str, Any]]]:+ """Walk a page-number paginated endpoint from `start_page` until a short/empty page.++ `on_page_complete(next_page)` is called after each full page has been yielded so the+ caller can persist resume state (re-yielding the last page on crash is fine — merge+ dedupes on primary key).+ """+ page = start_page+ while True:+ url = _build_url(path, {**base_params, "page": page, "per_page": PAGE_SIZE})+ data = fetch_page(url)+ items = _extract_items(data, config)++ if items:+ yield items++ # The API signals the end of the list only by returning a short or empty page.+ if len(items) < PAGE_SIZE:+ break++ page += 1+ on_page_complete(page)+++def get_rows(+ access_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CustomerlyResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = CUSTOMERLY_ENDPOINTS[endpoint]+ fetch_page = _make_fetch_page(_get_headers(access_token), logger)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None:+ logger.debug(f"Customerly: resuming {endpoint} from page={resume_config.page}")++ if config.fan_out_by_collection:+ yield from _get_article_rows(fetch_page, config, resumable_source_manager, resume_config, logger)+ return++ if not config.paginated:+ data = fetch_page(_build_url(config.path, {}))+ items = _extract_items(data, config)+ if endpoint == "tags":+ items = _normalize_tags(items)+ if items:+ yield items+ return++ start_page = resume_config.page if resume_config is not None else 0+ # Sort params match the documented example for the users/leads lists; an explicit sort+ # keeps page boundaries stable while paginating (merge on primary key dedupes any+ # rows that shift across pages mid-sync).+ base_params = {"sort": "name", "sort_direction": "asc"}++ yield from _paginate(+ fetch_page,+ config.path,+ base_params,+ config,+ start_page,+ lambda next_page: resumable_source_manager.save_state(CustomerlyResumeConfig(page=next_page)),+ )+++def _get_article_rows(+ fetch_page,+ config: CustomerlyEndpointConfig,+ resumable_source_manager: ResumableSourceManager[CustomerlyResumeConfig],+ resume_config: Optional[CustomerlyResumeConfig],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Articles are listed per knowledge base collection, so fan out over the collections+ (walked in ascending id order to make resume deterministic)."""+ collections_config = CUSTOMERLY_ENDPOINTS["knowledge_base_collections"]+ collections_data = fetch_page(_build_url(collections_config.path, {}))+ collections = _extract_items(collections_data, collections_config)++ collection_ids = sorted(+ cid+ for cid in (collection.get("knowledge_base_collection_id") for collection in collections)+ if isinstance(cid, int)+ )++ for collection_id in collection_ids:+ start_page = 0+ if resume_config is not None and resume_config.collection_id is not None:+ if collection_id < resume_config.collection_id:+ continue+ if collection_id == resume_config.collection_id:+ start_page = resume_config.page++ logger.debug(f"Customerly: fetching articles for collection_id={collection_id} from page={start_page}")++ yield from _paginate(+ fetch_page,+ config.path,+ {"knowledge_base_collection_id": collection_id},+ config,+ start_page,+ lambda next_page, cid=collection_id: resumable_source_manager.save_state(+ CustomerlyResumeConfig(page=next_page, collection_id=cid)+ ),+ )++ # Checkpoint the next collection so a resume doesn't rewalk this one from page 0.+ resumable_source_manager.save_state(CustomerlyResumeConfig(page=0, collection_id=collection_id + 1))+++def customerly_source(+ access_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CustomerlyResumeConfig],+) -> SourceResponse:+ config = CUSTOMERLY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ access_token=access_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=[config.primary_key],+ 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="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/customerly/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/customerly/settings.pynew file mode 100644index 000000000000..dbb4b56badb1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/customerly/settings.py@@ -0,0 +1,67 @@+from dataclasses import dataclass+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField+++@dataclass+class CustomerlyEndpointConfig:+ name: str+ path: str+ # Key the list of objects is nested under in the response body. `None` means the+ # `data` payload is the list itself (e.g. knowledge base collections/articles).+ data_key: Optional[str] = None+ primary_key: str = "crmhero_user_id"+ paginated: bool = False+ # Stable creation-time field used for datetime partitioning (UNIX epoch seconds).+ # Never an updated_at-style field, which would rewrite partitions on every sync.+ partition_key: Optional[str] = None+ # Set when rows are fetched per knowledge base collection (parent fan-out).+ fan_out_by_collection: bool = False+++# The Customerly public API exposes no server-side timestamp filter (`since` /+# `updated_after`) on any list endpoint, so every table is full refresh. Pagination is+# page-number based (`page` starting at 0, `per_page`) on the users/leads/articles lists;+# tags and knowledge base collections return the full list in one response.+CUSTOMERLY_ENDPOINTS: dict[str, CustomerlyEndpointConfig] = {+ "users": CustomerlyEndpointConfig(+ name="users",+ path="/users/list",+ data_key="users",+ primary_key="crmhero_user_id",+ paginated=True,+ partition_key="first_seen_at",+ ),+ "leads": CustomerlyEndpointConfig(+ name="leads",+ path="/leads/list",+ data_key="leads",+ primary_key="crmhero_user_id",+ paginated=True,+ partition_key="first_seen_at",+ ),+ "tags": CustomerlyEndpointConfig(+ name="tags",+ path="/tags",+ primary_key="name",+ ),+ "knowledge_base_collections": CustomerlyEndpointConfig(+ name="knowledge_base_collections",+ path="/knowledge/collections",+ primary_key="knowledge_base_collection_id",+ ),+ "knowledge_base_articles": CustomerlyEndpointConfig(+ name="knowledge_base_articles",+ path="/knowledge/articles/",+ primary_key="knowledge_base_article_id",+ paginated=True,+ partition_key="created_at",+ fan_out_by_collection=True,+ ),+}++ENDPOINTS = tuple(CUSTOMERLY_ENDPOINTS.keys())++# No endpoint exposes a genuine server-side incremental filter — advertise nothing.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/customerly/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/customerly/source.pyindex 097fc942df47..8d26c0ed76e7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/customerly/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/customerly/source.py@@ -1,30 +1,131 @@-from typing import cast+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.customerly.customerly import (+ CustomerlyResumeConfig,+ customerly_source,+ validate_credentials as validate_customerly_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.customerly.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CustomerlySourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CustomerlySource(SimpleSource[CustomerlySourceConfig]):+class CustomerlySource(ResumableSource[CustomerlySourceConfig, CustomerlyResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CUSTOMERLY+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "Customerly authentication failed": "Your Customerly access token is invalid or expired. Please generate a new token in Project Settings > Installation > Public API and reconnect.",+ "401 Client Error: Unauthorized for url: https://api.customerly.io": "Your Customerly access token is invalid or expired. Please generate a new token in Project Settings > Installation > Public API and reconnect.",+ "403 Client Error: Forbidden for url: https://api.customerly.io": "Your Customerly access token does not have the required permissions. Please check the token and try again.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.CUSTOMERLY,category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,label="Customerly",+ caption="""Enter your Customerly access token to pull your Customerly data into the PostHog Data warehouse.++You can find your access token in your Customerly project under **Project Settings** > **Installation** > **Public API** — see the [Customerly guide](https://docs.customerly.io/en/api/how-to-obtain-your-api-access-token-in-customerly).""",iconPath="/static/services/customerly.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/customerly",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="access_token",+ label="Access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.customerly.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: CustomerlySourceConfig,+ 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) is not None,+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ for endpoint in ENDPOINTS+ ]++ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]++ return schemas++ def validate_credentials(+ self, config: CustomerlySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_customerly_credentials(config.access_token):+ return True, None++ return False, "Invalid Customerly access token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CustomerlyResumeConfig]:+ return ResumableSourceManager[CustomerlyResumeConfig](inputs, CustomerlyResumeConfig)++ def source_for_pipeline(+ self,+ config: CustomerlySourceConfig,+ resumable_source_manager: ResumableSourceManager[CustomerlyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return customerly_source(+ access_token=config.access_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/customerly/tests/test_customerly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/customerly/tests/test_customerly.pynew file mode 100644index 000000000000..a1c78bb8029b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/customerly/tests/test_customerly.py@@ -0,0 +1,235 @@+from typing import Any++import pytest+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.customerly.customerly import (+ PAGE_SIZE,+ CustomerlyAuthenticationError,+ CustomerlyResumeConfig,+ _build_url,+ _is_auth_error_body,+ customerly_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.customerly.settings import (+ CUSTOMERLY_ENDPOINTS,+ ENDPOINTS,+)++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.customerly.customerly"+++def _make_manager(resume_state: CustomerlyResumeConfig | 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 _response(body: dict[str, Any] | None = None, status_code: int = 200, text: str = "") -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.status_code = status_code+ resp.ok = status_code < 400+ resp.text = text+ resp.json.return_value = body or {}+ return resp+++def _users_page(count: int, start: int = 0) -> dict[str, Any]:+ return {"data": {"users": [{"crmhero_user_id": start + i} for i in range(count)]}}+++class TestBuildUrl:+ def test_no_params(self):+ assert _build_url("/tags", {}) == "https://api.customerly.io/v1/tags"++ def test_drops_none_values_and_encodes(self):+ url = _build_url("/users/list", {"page": 0, "per_page": 50, "sort": None})+ assert url == "https://api.customerly.io/v1/users/list?page=0&per_page=50"+++class TestAuthErrorDetection:+ @pytest.mark.parametrize(+ "body, expected",+ [+ ('{"error":{"message":"Access token not found.","code":0}}', True),+ ('{"error":{"message":"You must provide a valid header Authorization: Bearer <TOKEN>","code":0}}', True),+ ('{"error":{"message":"Internal server error","code":0}}', False),+ ("", False),+ ],+ )+ def test_is_auth_error_body(self, body, expected):+ assert _is_auth_error_body(body) is expected++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_auth_failure_masquerading_as_500_is_not_retried(self, mock_session):+ # Customerly reports bad tokens as HTTP 500; treating that as a retryable server+ # error would retry a permanent credential failure forever.+ mock_session.return_value.get.return_value = _response(+ status_code=500, text='{"error":{"message":"Access token not found.","code":0}}'+ )++ with pytest.raises(CustomerlyAuthenticationError):+ list(get_rows("bad-token", "users", mock.MagicMock(), _make_manager()))++ assert mock_session.return_value.get.call_count == 1+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected",+ [+ (200, True),+ (401, False),+ (403, False),+ (500, False),+ ],+ )+ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_status_mapping(self, mock_session, status_code, expected):+ mock_session.return_value.get.return_value = _response(status_code=status_code)+ assert validate_credentials("token") is expected++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_swallows_exceptions(self, mock_session):+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("token") is False+++class TestGetRows:+ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_paginates_until_short_page(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response(_users_page(PAGE_SIZE)),+ _response(_users_page(3, start=PAGE_SIZE)),+ ]++ manager = _make_manager()+ batches = list(get_rows("token", "users", mock.MagicMock(), manager))++ assert [len(batch) for batch in batches] == [PAGE_SIZE, 3]+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert "page=0" in urls[0]+ assert "page=1" in urls[1]+ # State is saved only after a full page, pointing at the next page to fetch.+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0] == CustomerlyResumeConfig(page=1)++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_empty_first_page_yields_nothing(self, mock_session):+ mock_session.return_value.get.return_value = _response(_users_page(0))++ manager = _make_manager()+ batches = list(get_rows("token", "users", mock.MagicMock(), manager))++ assert batches == []+ manager.save_state.assert_not_called()++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_resumes_from_saved_page(self, mock_session):+ mock_session.return_value.get.return_value = _response(_users_page(1))++ manager = _make_manager(CustomerlyResumeConfig(page=7))+ list(get_rows("token", "users", mock.MagicMock(), manager))++ assert "page=7" in mock_session.return_value.get.call_args_list[0].args[0]++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_leads_read_from_leads_data_key(self, mock_session):+ mock_session.return_value.get.return_value = _response({"data": {"leads": [{"crmhero_user_id": 5}]}})++ batches = list(get_rows("token", "leads", mock.MagicMock(), _make_manager()))++ assert batches == [[{"crmhero_user_id": 5}]]++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_tags_are_normalized_into_rows(self, mock_session):+ mock_session.return_value.get.return_value = _response({"data": ["onboarding", "remarketing"]})++ batches = list(get_rows("token", "tags", mock.MagicMock(), _make_manager()))++ assert batches == [[{"name": "onboarding"}, {"name": "remarketing"}]]+ assert mock_session.return_value.get.call_count == 1++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_collections_returned_as_is(self, mock_session):+ collections = [{"knowledge_base_collection_id": 4517, "title": "Getting Started"}]+ mock_session.return_value.get.return_value = _response({"data": collections})++ batches = list(get_rows("token", "knowledge_base_collections", mock.MagicMock(), _make_manager()))++ assert batches == [collections]+++class TestArticlesFanOut:+ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_fans_out_over_collections_in_ascending_id_order(self, mock_session):+ collections = {"data": [{"knowledge_base_collection_id": 6050}, {"knowledge_base_collection_id": 4517}]}+ articles_4517 = {"data": [{"knowledge_base_article_id": 1, "knowledge_base_collection_id": 4517}]}+ articles_6050 = {"data": [{"knowledge_base_article_id": 2, "knowledge_base_collection_id": 6050}]}+ mock_session.return_value.get.side_effect = [+ _response(collections),+ _response(articles_4517),+ _response(articles_6050),+ ]++ manager = _make_manager()+ batches = list(get_rows("token", "knowledge_base_articles", mock.MagicMock(), manager))++ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert "knowledge/collections" in urls[0]+ assert "knowledge_base_collection_id=4517" in urls[1]+ assert "knowledge_base_collection_id=6050" in urls[2]+ assert [item["knowledge_base_article_id"] for batch in batches for item in batch] == [1, 2]++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_checkpoints_next_collection_after_each_collection(self, mock_session):+ collections = {"data": [{"knowledge_base_collection_id": 4517}]}+ mock_session.return_value.get.side_effect = [+ _response(collections),+ _response({"data": [{"knowledge_base_article_id": 1}]}),+ ]++ manager = _make_manager()+ list(get_rows("token", "knowledge_base_articles", mock.MagicMock(), manager))++ manager.save_state.assert_called_with(CustomerlyResumeConfig(page=0, collection_id=4518))++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_resume_skips_completed_collections_and_starts_at_saved_page(self, mock_session):+ collections = {"data": [{"knowledge_base_collection_id": 4517}, {"knowledge_base_collection_id": 6050}]}+ mock_session.return_value.get.side_effect = [+ _response(collections),+ _response({"data": [{"knowledge_base_article_id": 9}]}),+ ]++ manager = _make_manager(CustomerlyResumeConfig(page=3, collection_id=6050))+ list(get_rows("token", "knowledge_base_articles", mock.MagicMock(), manager))++ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert len(urls) == 2+ assert "knowledge_base_collection_id=6050" in urls[1]+ assert "page=3" in urls[1]+++class TestCustomerlySourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = CUSTOMERLY_ENDPOINTS[endpoint]+ response = customerly_source("token", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == [config.primary_key]+ 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(CUSTOMERLY_ENDPOINTS.values()))+ def test_partition_keys_are_stable_creation_fields(self, config):+ if config.partition_key:+ assert config.partition_key in {"first_seen_at", "created_at"}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/customerly/tests/test_customerly_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/customerly/tests/test_customerly_source.pynew file mode 100644index 000000000000..445acab82246--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/customerly/tests/test_customerly_source.py@@ -0,0 +1,118 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.customerly.customerly import (+ CustomerlyResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.customerly.settings import (+ CUSTOMERLY_ENDPOINTS,+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.customerly.source import CustomerlySource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CustomerlySourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestCustomerlySource:+ def setup_method(self):+ self.source = CustomerlySource()+ self.team_id = 123+ self.config = CustomerlySourceConfig(access_token="token")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.CUSTOMERLY++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Customerly"+ assert config.label == "Customerly"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/customerly.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["access_token"]++ def test_access_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 == "access_token"+ )+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "Customerly authentication failed: invalid or expired access token (url=https://api.customerly.io/v1/users/list)",+ "401 Client Error: Unauthorized for url: https://api.customerly.io/v1/tags",+ "403 Client Error: Forbidden for url: https://api.customerly.io/v1/leads/list",+ ],+ )+ 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_error",+ [+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",+ "Customerly API error (retryable): status=503, url=https://api.customerly.io/v1/users/list",+ ],+ )+ def test_non_retryable_errors_does_not_match_unrelated(self, other_error):+ 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_are_full_refresh_only(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ # The Customerly API has no server-side timestamp filter, so nothing may advertise incremental.+ assert not any(schema.supports_incremental for schema in schemas)+ assert all(schema.incremental_fields == [] for schema in schemas)++ def test_get_schemas_filters_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["users", "tags"])+ assert {schema.name for schema in schemas} == {"users", "tags"}++ @pytest.mark.parametrize("is_valid", [True, False])+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.customerly.source.validate_customerly_credentials"+ )+ def test_validate_credentials(self, mock_validate, is_valid):+ mock_validate.return_value = is_valid++ result, error = self.source.validate_credentials(self.config, self.team_id)++ assert result is is_valid+ assert (error is None) is is_valid+ mock_validate.assert_called_once_with("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 CustomerlyResumeConfig++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_source_for_pipeline_plumbs_schema_name(self, endpoint):+ inputs = mock.MagicMock()+ inputs.schema_name = endpoint++ response = self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert response.name == endpoint+ assert response.primary_keys == [CUSTOMERLY_ENDPOINTS[endpoint].primary_key]++ def test_documented_tables_render_without_credentials(self):+ # `lists_tables_without_credentials` feeds the public docs' Supported tables section.+ assert self.source.lists_tables_without_credentials is True+ tables = self.source.get_documented_tables()+ assert {table["name"] for table in tables} == set(ENDPOINTS)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 ac8d7edd30b2..0027ae55deb7 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@@ -1096,7 +1096,7 @@ class CustomerIOSourceConfig(config.Config):@config.configclass CustomerlySourceConfig(config.Config):- pass+ access_token: str@config.config