: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 pipedrive import source (#61592)
Tom Owers04ededb733f8
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 810ee94bd51d..407fd319bc9c 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -92,6 +92,7 @@ the row lists both.| paddle | HTTP | requests | ✅ || pagerduty | HTTP | requests | ✅ || pinterest_ads | HTTP | requests | ✅ |+| pipedrive | HTTP | requests | ✅ || plain | HTTP | requests | ✅ || polar | HTTP | requests | ✅ || postgres | DB protocol | psycopg | ➖ |@@ -205,7 +206,6 @@ doesn't conflict with concurrent PRs.- pardot- paypal- pendo-- pipedrive- plaid- productboard- quickbooksdiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 5a4ec0028ea0..c6dde91d67f8 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -646,7 +646,8 @@ class PinterestAdsSourceConfig(config.Config):@config.configclass PipedriveSourceConfig(config.Config):- pass+ company_domain: str+ api_token: str@config.configdiff --git a/posthog/temporal/data_imports/sources/pipedrive/api_inventory.md b/posthog/temporal/data_imports/sources/pipedrive/api_inventory.mdnew file mode 100644index 000000000000..bf3179382f9a--- /dev/null+++ b/posthog/temporal/data_imports/sources/pipedrive/api_inventory.md@@ -0,0 +1,48 @@+# Pipedrive API inventory++Reference: <https://developers.pipedrive.com/docs/api/v1>++## Auth++- API token, passed via the `x-api-token` request header (the query-param form leaks the+ token into logged URLs, so we use the header instead).+- All requests go to the company domain: `https://{company_domain}.pipedrive.com`.+ v1 resources live under `/api/v1/...`, v2 resources under `/api/v2/...`.++## Pagination++- **v2 (cursor):** `?limit=500&cursor=<cursor>`. Response carries+ `additional_data.next_cursor`; a falsy/absent cursor ends the chain.+- **v1 (offset):** `?start=<n>&limit=500`. Response carries+ `additional_data.pagination.{more_items_in_collection,next_start}`; pagination object is+ absent for single-page endpoints (e.g. `users`).+- Both wire styles return rows under the top-level `data` key.++## Endpoints synced++| Schema | Path | Pagination | Primary key | Partition key |+| ------------------- | ---------------------------- | ---------- | ----------- | ------------- |+| deals | `/api/v2/deals` | cursor | id | add_time |+| persons | `/api/v2/persons` | cursor | id | add_time |+| organizations | `/api/v2/organizations` | cursor | id | add_time |+| products | `/api/v2/products` | cursor | id | add_time |+| pipelines | `/api/v2/pipelines` | cursor | id | add_time |+| stages | `/api/v2/stages` | cursor | id | add_time |+| activities | `/api/v1/activities` | offset | id | add_time |+| notes | `/api/v1/notes` | offset | id | add_time |+| leads | `/api/v1/leads` | offset | id | add_time |+| users | `/api/v1/users` | offset | id | — |+| deal_fields | `/api/v1/dealFields` | offset | id | — |+| person_fields | `/api/v1/personFields` | offset | id | — |+| organization_fields | `/api/v1/organizationFields` | offset | id | — |++## Incremental sync++Shipped as **full refresh for every endpoint**. Pipedrive's v2 collection endpoints+document an `updated_since` (RFC 3339) server-side filter plus `sort_by=update_time`, which+would make those endpoints incremental — but the implementing-warehouse-sources skill+requires a live curl smoke test (future-date cutoff) to confirm the filter actually filters+before enabling it, and no Pipedrive credentials were available at implementation time. The+v1 collection endpoints have no per-resource `updated_after` filter at all (only the 30-day+`/recents` endpoint), so they would stay full refresh regardless. Enabling incremental on the+v2 endpoints is a verified follow-up.diff --git a/posthog/temporal/data_imports/sources/pipedrive/pipedrive.py b/posthog/temporal/data_imports/sources/pipedrive/pipedrive.pynew file mode 100644index 000000000000..bf7694206ad7--- /dev/null+++ b/posthog/temporal/data_imports/sources/pipedrive/pipedrive.py@@ -0,0 +1,191 @@+import re+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 posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.pipedrive.settings import PIPEDRIVE_ENDPOINTS, PipedriveEndpointConfig++# Pipedrive caps list pages at 500 items (default 100).+PAGE_SIZE = 500+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5++_SUBDOMAIN_RE = re.compile(r"^[a-z0-9-]+$")+++class PipedriveRetryableError(Exception):+ pass+++class PipedriveResumeConfig:+ # Full URL (query string included, token is sent via header so never present here) of the+ # next page to fetch. Unifies cursor (v2) and offset (v1) pagination behind one resume key.+ next_url: str+++def normalize_company_domain(raw: str) -> str:+ """Reduce whatever the user typed to the bare Pipedrive subdomain.++ Accepts ``mycompany``, ``mycompany.pipedrive.com`` or ``https://mycompany.pipedrive.com``.+ Raises ``ValueError`` if the result isn't a plain subdomain, which also pins outbound+ traffic to ``*.pipedrive.com`` (no SSRF to arbitrary hosts).+ """+ domain = raw.strip().lower()+ domain = domain.removeprefix("https://").removeprefix("http://")+ domain = domain.split("/")[0]+ domain = domain.removesuffix(".pipedrive.com")+ if not _SUBDOMAIN_RE.match(domain):+ raise ValueError(f"Invalid Pipedrive company domain: {raw!r}")+ return domain+++def base_url(company_domain: str) -> str:+ return f"https://{normalize_company_domain(company_domain)}.pipedrive.com"+++def _get_headers(api_token: str) -> dict[str, str]:+ return {"x-api-token": api_token, "Accept": "application/json"}+++def _build_url(company_domain: str, path: str, params: dict[str, Any]) -> str:+ clean_params = {key: value for key, value in params.items() if value is not None}+ url = f"{base_url(company_domain)}{path}"+ if not clean_params:+ return url+ return f"{url}?{urlencode(clean_params)}"+++def _initial_url(company_domain: str, config: PipedriveEndpointConfig) -> str:+ params: dict[str, Any] = {"limit": PAGE_SIZE}+ if config.pagination == "offset":+ params["start"] = 0+ return _build_url(company_domain, config.path, params)+++def _next_url(company_domain: str, config: PipedriveEndpointConfig, response: dict[str, Any]) -> Optional[str]:+ additional_data = response.get("additional_data") or {}++ if config.pagination == "cursor":+ next_cursor = additional_data.get("next_cursor")+ if not next_cursor:+ return None+ return _build_url(company_domain, config.path, {"limit": PAGE_SIZE, "cursor": next_cursor})++ pagination = additional_data.get("pagination") or {}+ if not pagination.get("more_items_in_collection"):+ return None+ next_start = pagination.get("next_start")+ if next_start is None:+ return None+ return _build_url(company_domain, config.path, {"limit": PAGE_SIZE, "start": next_start})+++def validate_credentials(company_domain: str, api_token: str) -> Optional[int]:+ """Return the status code of a cheap authenticated probe, or ``None`` on transport error.++ ``/api/v1/users/me`` resolves the token's own user and is reachable by any valid token.+ """+ # Built outside the `try` so an invalid-domain `ValueError` from `_build_url` propagates to+ # the caller rather than being swallowed into `None` by the broad transport-error handler.+ url = _build_url(company_domain, "/api/v1/users/me", {})+ try:+ session = make_tracked_session(headers=_get_headers(api_token), redact_values=(api_token,))+ response = session.get(url, timeout=10)+ return response.status_code+ except Exception:+ return None+++def get_rows(+ company_domain: str,+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PipedriveResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = PIPEDRIVE_ENDPOINTS[endpoint]+ # `redact_values` masks the token (sent via the custom `x-api-token` header, which the+ # name-based denylist can't catch) in logged URLs and captured HTTP samples.+ session = make_tracked_session(headers=_get_headers(api_token), redact_values=(api_token,))++ 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"Pipedrive: resuming {endpoint} from URL: {url}")+ else:+ url = _initial_url(company_domain, config)++ @retry(+ retry=retry_if_exception_type((PipedriveRetryableError, 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 = session.get(page_url, timeout=REQUEST_TIMEOUT_SECONDS)++ # Pipedrive uses token-based rate limiting; 429s and transient 5xx are retried with+ # exponential backoff.+ if response.status_code == 429 or response.status_code >= 500:+ raise PipedriveRetryableError(+ f"Pipedrive API error (retryable): status={response.status_code}, url={page_url}"+ )++ if not response.ok:+ logger.error(f"Pipedrive API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response.json()++ while True:+ data = fetch_page(url)+ items = data.get("data") or []++ if items:+ yield items++ next_url = _next_url(company_domain, config, data)+ if not next_url:+ break++ # Save the next-page pointer only after the current page has been processed (yielded+ # above when it had rows), so a crash resumes at this page rather than past it. Merge+ # dedupes on primary key any rows re-yielded on resume.+ resumable_source_manager.save_state(PipedriveResumeConfig(next_url=next_url))+ url = next_url+++def pipedrive_source(+ company_domain: str,+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PipedriveResumeConfig],+) -> SourceResponse:+ config = PIPEDRIVE_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ company_domain=company_domain,+ api_token=api_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=[config.primary_key],+ 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/pipedrive/settings.py b/posthog/temporal/data_imports/sources/pipedrive/settings.pynew file mode 100644index 000000000000..da8ea48e91ab--- /dev/null+++ b/posthog/temporal/data_imports/sources/pipedrive/settings.py@@ -0,0 +1,42 @@+from dataclasses import dataclass+from typing import Literal, Optional++PaginationStyle = Literal["cursor", "offset"]+++@dataclass+class PipedriveEndpointConfig:+ name: str+ path: str+ # v2 endpoints use cursor pagination; v1 endpoints use start/limit offset pagination.+ pagination: PaginationStyle+ primary_key: str = "id"+ # Stable creation-time field used for datetime partitioning. Never an update_time-style+ # field, which would rewrite partitions on every sync. `None` disables partitioning for+ # endpoints (users, *_fields) whose rows have no stable creation timestamp.+ partition_key: Optional[str] = "add_time"+++PIPEDRIVE_ENDPOINTS: dict[str, PipedriveEndpointConfig] = {+ "deals": PipedriveEndpointConfig(name="deals", path="/api/v2/deals", pagination="cursor"),+ "persons": PipedriveEndpointConfig(name="persons", path="/api/v2/persons", pagination="cursor"),+ "organizations": PipedriveEndpointConfig(name="organizations", path="/api/v2/organizations", pagination="cursor"),+ "products": PipedriveEndpointConfig(name="products", path="/api/v2/products", pagination="cursor"),+ "pipelines": PipedriveEndpointConfig(name="pipelines", path="/api/v2/pipelines", pagination="cursor"),+ "stages": PipedriveEndpointConfig(name="stages", path="/api/v2/stages", pagination="cursor"),+ "activities": PipedriveEndpointConfig(name="activities", path="/api/v1/activities", pagination="offset"),+ "notes": PipedriveEndpointConfig(name="notes", path="/api/v1/notes", pagination="offset"),+ "leads": PipedriveEndpointConfig(name="leads", path="/api/v1/leads", pagination="offset"),+ "users": PipedriveEndpointConfig(name="users", path="/api/v1/users", pagination="offset", partition_key=None),+ "deal_fields": PipedriveEndpointConfig(+ name="deal_fields", path="/api/v1/dealFields", pagination="offset", partition_key=None+ ),+ "person_fields": PipedriveEndpointConfig(+ name="person_fields", path="/api/v1/personFields", pagination="offset", partition_key=None+ ),+ "organization_fields": PipedriveEndpointConfig(+ name="organization_fields", path="/api/v1/organizationFields", pagination="offset", partition_key=None+ ),+}++ENDPOINTS = tuple(PIPEDRIVE_ENDPOINTS.keys())diff --git a/posthog/temporal/data_imports/sources/pipedrive/source.py b/posthog/temporal/data_imports/sources/pipedrive/source.pyindex 5f5d1e1c81c3..4421cd537322 100644--- a/posthog/temporal/data_imports/sources/pipedrive/source.py+++ b/posthog/temporal/data_imports/sources/pipedrive/source.py@@ -1,29 +1,132 @@-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.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 PipedriveSourceConfig+from posthog.temporal.data_imports.sources.pipedrive.pipedrive import (+ PipedriveResumeConfig,+ normalize_company_domain,+ pipedrive_source,+ validate_credentials as validate_pipedrive_credentials,+)+from posthog.temporal.data_imports.sources.pipedrive.settings import ENDPOINTSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class PipedriveSource(SimpleSource[PipedriveSourceConfig]):+class PipedriveSource(ResumableSource[PipedriveSourceConfig, PipedriveResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PIPEDRIVE+ @property+ def connection_host_fields(self) -> list[str]:+ # The stored API token is sent to `{company_domain}.pipedrive.com`; retargeting the+ # domain must re-require the token.+ return ["company_domain"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.PIPEDRIVE,label="Pipedrive",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Pipedrive API token to sync your Pipedrive CRM data into the PostHog Data warehouse.++You can find your personal API token in Pipedrive under **Settings > Personal preferences > API**. The token inherits your user's permissions, so make sure your user can access the data you want to sync.""",iconPath="/static/services/pipedrive.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/pipedrive",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="company_domain",+ label="Company domain",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="mycompany",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid Pipedrive API token. Please check your token and reconnect.",+ "403 Client Error": "Your Pipedrive user lacks permission for this data. Please check your access and reconnect.",+ }++ def get_schemas(+ self,+ config: PipedriveSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Full refresh only: Pipedrive's v1 collections have no server-side updated_after+ # filter, and the v2 `updated_since` filter is unverified (no credentials to curl with).+ schemas = [+ SourceSchema(name=endpoint, supports_incremental=False, supports_append=False, incremental_fields=[])+ 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: PipedriveSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ status = validate_pipedrive_credentials(config.company_domain, config.api_token)+ except ValueError as e:+ return False, str(e)++ if status == 200:+ return True, None+ # A valid token may lack scope for some endpoints; accept that at source-create+ # (schema_name is None) and only reject when validating a specific schema.+ if status == 403 and schema_name is None:+ return True, None+ if status in (401, 403):+ return False, "Invalid Pipedrive API token or insufficient permissions"+ return False, "Could not validate Pipedrive credentials"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PipedriveResumeConfig]:+ return ResumableSourceManager[PipedriveResumeConfig](inputs, PipedriveResumeConfig)++ def source_for_pipeline(+ self,+ config: PipedriveSourceConfig,+ resumable_source_manager: ResumableSourceManager[PipedriveResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return pipedrive_source(+ company_domain=normalize_company_domain(config.company_domain),+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/posthog/temporal/data_imports/sources/pipedrive/tests/test_pipedrive.py b/posthog/temporal/data_imports/sources/pipedrive/tests/test_pipedrive.pynew file mode 100644index 000000000000..174c4406e92d--- /dev/null+++ b/posthog/temporal/data_imports/sources/pipedrive/tests/test_pipedrive.py@@ -0,0 +1,210 @@+from typing import Any++import pytest+from unittest import mock++from posthog.temporal.data_imports.sources.pipedrive.pipedrive import (+ PAGE_SIZE,+ PipedriveResumeConfig,+ _initial_url,+ _next_url,+ base_url,+ get_rows,+ normalize_company_domain,+ pipedrive_source,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.pipedrive.settings import PIPEDRIVE_ENDPOINTS+++class TestNormalizeCompanyDomain:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ ("mycompany", "mycompany"),+ ("MyCompany", "mycompany"),+ ("mycompany.pipedrive.com", "mycompany"),+ ("https://mycompany.pipedrive.com", "mycompany"),+ ("http://mycompany.pipedrive.com/", "mycompany"),+ (" mycompany ", "mycompany"),+ ("my-company-123", "my-company-123"),+ ],+ )+ def test_normalizes_valid_domains(self, raw: str, expected: str) -> None:+ assert normalize_company_domain(raw) == expected++ @pytest.mark.parametrize(+ "raw",+ [+ "",+ "my company",+ "evil.com",+ "mycompany.pipedrive.com.evil.com",+ "http://169.254.169.254",+ "foo_bar",+ ],+ )+ def test_rejects_invalid_domains(self, raw: str) -> None:+ with pytest.raises(ValueError):+ normalize_company_domain(raw)++ def test_base_url_is_pinned_to_pipedrive(self) -> None:+ assert base_url("mycompany") == "https://mycompany.pipedrive.com"+ assert base_url("https://MyCompany.pipedrive.com") == "https://mycompany.pipedrive.com"+++class TestInitialUrl:+ def test_cursor_endpoint_only_sets_limit(self) -> None:+ url = _initial_url("acme", PIPEDRIVE_ENDPOINTS["deals"])+ assert url == f"https://acme.pipedrive.com/api/v2/deals?limit={PAGE_SIZE}"++ def test_offset_endpoint_sets_start_and_limit(self) -> None:+ url = _initial_url("acme", PIPEDRIVE_ENDPOINTS["activities"])+ assert url == f"https://acme.pipedrive.com/api/v1/activities?limit={PAGE_SIZE}&start=0"+++class TestNextUrl:+ def test_cursor_returns_next_page_url(self) -> None:+ config = PIPEDRIVE_ENDPOINTS["deals"]+ response = {"data": [{"id": 1}], "additional_data": {"next_cursor": "abc123"}}+ assert _next_url("acme", config, response) == (+ f"https://acme.pipedrive.com/api/v2/deals?limit={PAGE_SIZE}&cursor=abc123"+ )++ @pytest.mark.parametrize(+ "additional_data",+ [+ {},+ {"next_cursor": None},+ {"next_cursor": ""},+ ],+ )+ def test_cursor_terminates_when_no_next_cursor(self, additional_data: dict[str, Any]) -> None:+ config = PIPEDRIVE_ENDPOINTS["deals"]+ assert _next_url("acme", config, {"data": [], "additional_data": additional_data}) is None++ def test_offset_returns_next_page_url(self) -> None:+ config = PIPEDRIVE_ENDPOINTS["activities"]+ response = {+ "data": [{"id": 1}],+ "additional_data": {"pagination": {"more_items_in_collection": True, "next_start": 500}},+ }+ assert _next_url("acme", config, response) == (+ f"https://acme.pipedrive.com/api/v1/activities?limit={PAGE_SIZE}&start=500"+ )++ @pytest.mark.parametrize(+ "additional_data",+ [+ {},+ {"pagination": {"more_items_in_collection": False, "next_start": 500}},+ {"pagination": {"more_items_in_collection": True}},+ ],+ )+ def test_offset_terminates(self, additional_data: dict[str, Any]) -> None:+ config = PIPEDRIVE_ENDPOINTS["activities"]+ assert _next_url("acme", config, {"data": [], "additional_data": additional_data}) is None+++class TestValidateCredentials:+ @pytest.mark.parametrize("status_code", [200, 401, 403, 500])+ @mock.patch("posthog.temporal.data_imports.sources.pipedrive.pipedrive.make_tracked_session")+ def test_returns_status_code(self, mock_session: mock.MagicMock, status_code: int) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)+ assert validate_credentials("acme", "token") == status_code+ called_url = mock_session.return_value.get.call_args.args[0]+ assert called_url == "https://acme.pipedrive.com/api/v1/users/me"+ # Auth header and token redaction are configured on the session, not the request.+ assert mock_session.call_args.kwargs["headers"]["x-api-token"] == "token"+ assert mock_session.call_args.kwargs["redact_values"] == ("token",)++ @mock.patch("posthog.temporal.data_imports.sources.pipedrive.pipedrive.make_tracked_session")+ def test_returns_none_on_transport_error(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("acme", "token") is None++ def test_propagates_invalid_domain(self) -> None:+ with pytest.raises(ValueError):+ validate_credentials("evil.com", "token")+++class TestGetRows:+ def _manager(self, resume_state: PipedriveResumeConfig | 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++ @mock.patch("posthog.temporal.data_imports.sources.pipedrive.pipedrive.make_tracked_session")+ def test_paginates_cursor_endpoint_and_saves_state_after_yield(self, mock_session: mock.MagicMock) -> None:+ page1 = mock.MagicMock(status_code=200, ok=True)+ page1.json.return_value = {"data": [{"id": 1}], "additional_data": {"next_cursor": "c2"}}+ page2 = mock.MagicMock(status_code=200, ok=True)+ page2.json.return_value = {"data": [{"id": 2}], "additional_data": {"next_cursor": None}}+ mock_session.return_value.get.side_effect = [page1, page2]++ manager = self._manager()+ batches = list(get_rows("acme", "token", "deals", mock.MagicMock(), manager))++ assert batches == [[{"id": 1}], [{"id": 2}]]+ # The session masks the token in logged URLs and captured samples.+ assert mock_session.call_args.kwargs["redact_values"] == ("token",)+ # State is saved once: after the first page is yielded, pointing at page 2.+ manager.save_state.assert_called_once_with(+ PipedriveResumeConfig(next_url=f"https://acme.pipedrive.com/api/v2/deals?limit={PAGE_SIZE}&cursor=c2")+ )++ @mock.patch("posthog.temporal.data_imports.sources.pipedrive.pipedrive.make_tracked_session")+ def test_resumes_from_saved_state(self, mock_session: mock.MagicMock) -> None:+ page = mock.MagicMock(status_code=200, ok=True)+ page.json.return_value = {"data": [{"id": 9}], "additional_data": {"next_cursor": None}}+ mock_session.return_value.get.return_value = page++ resume_url = f"https://acme.pipedrive.com/api/v2/deals?limit={PAGE_SIZE}&cursor=resume-me"+ manager = self._manager(PipedriveResumeConfig(next_url=resume_url))++ batches = list(get_rows("acme", "token", "deals", mock.MagicMock(), manager))++ assert batches == [[{"id": 9}]]+ assert mock_session.return_value.get.call_args.args[0] == resume_url++ @mock.patch("posthog.temporal.data_imports.sources.pipedrive.pipedrive.make_tracked_session")+ def test_single_page_endpoint_without_pagination(self, mock_session: mock.MagicMock) -> None:+ page = mock.MagicMock(status_code=200, ok=True)+ page.json.return_value = {"data": [{"id": 1}, {"id": 2}]}+ mock_session.return_value.get.return_value = page++ manager = self._manager()+ batches = list(get_rows("acme", "token", "users", mock.MagicMock(), manager))++ assert batches == [[{"id": 1}, {"id": 2}]]+ manager.save_state.assert_not_called()++ @mock.patch("posthog.temporal.data_imports.sources.pipedrive.pipedrive.make_tracked_session")+ def test_raises_on_non_retryable_error(self, mock_session: mock.MagicMock) -> None:+ page = mock.MagicMock(status_code=401, ok=False, text="unauthorized")+ page.raise_for_status.side_effect = Exception("401 Client Error")+ mock_session.return_value.get.return_value = page++ with pytest.raises(Exception, match="401 Client Error"):+ list(get_rows("acme", "token", "deals", mock.MagicMock(), self._manager()))+++class TestPipedriveSource:+ @pytest.mark.parametrize(+ "endpoint, expected_partition_keys, expected_mode",+ [+ ("deals", ["add_time"], "datetime"),+ ("activities", ["add_time"], "datetime"),+ ("users", None, None),+ ("deal_fields", None, None),+ ],+ )+ def test_source_response_partitioning(+ self, endpoint: str, expected_partition_keys: list[str] | None, expected_mode: str | None+ ) -> None:+ response = pipedrive_source("acme", "token", endpoint, mock.MagicMock(), mock.MagicMock())+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.partition_keys == expected_partition_keys+ assert response.partition_mode == expected_modediff --git a/posthog/temporal/data_imports/sources/pipedrive/tests/test_pipedrive_source.py b/posthog/temporal/data_imports/sources/pipedrive/tests/test_pipedrive_source.pynew file mode 100644index 000000000000..f4aa3136c2d3--- /dev/null+++ b/posthog/temporal/data_imports/sources/pipedrive/tests/test_pipedrive_source.py@@ -0,0 +1,155 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import PipedriveSourceConfig+from posthog.temporal.data_imports.sources.pipedrive.pipedrive import PipedriveResumeConfig+from posthog.temporal.data_imports.sources.pipedrive.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.pipedrive.source import PipedriveSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestPipedriveSource:+ def setup_method(self) -> None:+ self.source = PipedriveSource()+ self.team_id = 123+ self.config = PipedriveSourceConfig(company_domain="acme", api_token="token")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.PIPEDRIVE++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Pipedrive"+ assert config.label == "Pipedrive"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/pipedrive.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["company_domain", "api_token"]++ def test_api_token_field_is_secret_password(self) -> None:+ 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++ def test_company_domain_is_connection_host_field(self) -> None:+ assert self.source.connection_host_fields == ["company_domain"]++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://acme.pipedrive.com/api/v2/deals?limit=500",+ "403 Client Error: Forbidden for url: https://acme.pipedrive.com/api/v1/activities?limit=500&start=0",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "429 Client Error: Too Many Requests for url: https://acme.pipedrive.com/api/v2/deals",+ "500 Server Error for url: https://acme.pipedrive.com/api/v1/notes",+ ],+ )+ def test_non_retryable_errors_does_not_match_transient(self, other_error: str) -> None:+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_lists_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ assert all(not schema.supports_incremental for schema in schemas)+ assert all(not schema.supports_append for schema in schemas)+ assert all(schema.incremental_fields == [] for schema in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["deals"])+ assert len(schemas) == 1+ assert schemas[0].name == "deals"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "status, schema_name, expected_valid, expected_message",+ [+ (200, None, True, None),+ (200, "deals", True, None),+ (403, None, True, None),+ (403, "deals", False, "Invalid Pipedrive API token or insufficient permissions"),+ (401, None, False, "Invalid Pipedrive API token or insufficient permissions"),+ (500, None, False, "Could not validate Pipedrive credentials"),+ (None, None, False, "Could not validate Pipedrive credentials"),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.pipedrive.source.validate_pipedrive_credentials")+ def test_validate_credentials(+ self,+ mock_validate: mock.MagicMock,+ status: int | None,+ schema_name: str | None,+ expected_valid: bool,+ expected_message: str | None,+ ) -> None:+ mock_validate.return_value = status++ is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name)++ assert is_valid is expected_valid+ assert message == expected_message+ mock_validate.assert_called_once_with("acme", "token")++ @mock.patch("posthog.temporal.data_imports.sources.pipedrive.source.validate_pipedrive_credentials")+ def test_validate_credentials_rejects_invalid_domain(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.side_effect = ValueError("Invalid Pipedrive company domain: 'evil.com'")+ is_valid, message = self.source.validate_credentials(+ PipedriveSourceConfig(company_domain="evil.com", api_token="token"), self.team_id+ )+ assert is_valid is False+ assert message is not None and "Invalid Pipedrive company domain" in message++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is PipedriveResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.pipedrive.source.pipedrive_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_pipedrive_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "deals"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_pipedrive_source.assert_called_once()+ kwargs = mock_pipedrive_source.call_args.kwargs+ assert kwargs["company_domain"] == "acme"+ assert kwargs["api_token"] == "token"+ assert kwargs["endpoint"] == "deals"+ assert kwargs["resumable_source_manager"] is manager++ @mock.patch("posthog.temporal.data_imports.sources.pipedrive.source.pipedrive_source")+ def test_source_for_pipeline_normalizes_company_domain(self, mock_pipedrive_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "deals"++ self.source.source_for_pipeline(+ PipedriveSourceConfig(company_domain="https://Acme.pipedrive.com", api_token="token"),+ mock.MagicMock(),+ inputs,+ )++ assert mock_pipedrive_source.call_args.kwargs["company_domain"] == "acme"