Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement apollo import source (#62983)

Tom Owersbecf8984276b
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index e8cb9ac51a85..c83475fdbdea 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -49,6 +49,7 @@ the row lists both.
| airtable | HTTP | requests | ✅ |
| amazon_ads | HTTP | requests | ✅ |
| amplitude | HTTP | requests | ✅ |
+| apollo | HTTP | requests | ✅ |
| appsflyer | HTTP (CSV reports) | requests | ✅ |
| asana | HTTP | requests | ✅ |
| ashby | HTTP | requests | ✅ |
@@ -224,7 +225,6 @@ doesn't conflict with concurrent PRs.
- amazon_selling_partner
- amazon_sns
- amazon_sqs
-- apollo
- apple_search_ads
- attentive
- auth0
diff --git a/posthog/temporal/data_imports/sources/apollo/apollo.py b/posthog/temporal/data_imports/sources/apollo/apollo.py
new file mode 100644
index 000000000000..1bb84933aea4
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/apollo/apollo.py
@@ -0,0 +1,184 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+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.apollo.settings import APOLLO_ENDPOINTS
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+APOLLO_BASE_URL = "https://api.apollo.io/api/v1"
+# Search pages cap at 100 records and 500 pages (50k records per query).
+PAGE_SIZE = 100
+MAX_PAGES = 500
+REQUEST_TIMEOUT_SECONDS = 60
+# Rate limits are plan-dependent fixed windows; back off on 429.
+MAX_RETRY_ATTEMPTS = 5
+
+
+class ApolloRetryableError(Exception):
+ pass
+
+
+class ApolloResumeConfig:
+ # Search endpoints paginate with a 1-based page number; static body parts
+ # are rebuilt deterministically from job inputs on resume.
+ page: int
+
+
+def _get_session(api_key: str) -> requests.Session:
+ return make_tracked_session(headers={"X-Api-Key": api_key}, redact_values=(api_key,))
+
+
+def _parse_timestamp(value: Any) -> Optional[datetime]:
+ if isinstance(value, datetime):
+ return value if value.tzinfo else value.replace(tzinfo=UTC)
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ if isinstance(value, str):
+ try:
+ return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone(UTC)
+ except ValueError:
+ return None
+ return None
+
+
+def validate_credentials(api_key: str) -> bool:
+ """Confirm the API key is valid with Apollo's auth health endpoint."""
+ try:
+ response = _get_session(api_key).get(
+ f"{APOLLO_BASE_URL}/auth/health",
+ timeout=10,
+ )
+ return response.status_code == 200 and bool(response.json().get("is_logged_in"))
+ except Exception:
+ return False
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ApolloResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = APOLLO_ENDPOINTS[endpoint]
+ session = _get_session(api_key)
+ url = f"{APOLLO_BASE_URL}{config.path}"
+
+ watermark = _parse_timestamp(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
+ page = resume_config.page if resume_config is not None else 1
+ if resume_config is not None:
+ logger.debug(f"Apollo: resuming {endpoint} from page {page}")
+
+ @retry(
+ retry=retry_if_exception_type((ApolloRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=5, max=120),
+ reraise=True,
+ )
+ def fetch_page(page_number: int) -> dict[str, Any]:
+ body: dict[str, Any] = {"page": page_number, "per_page": PAGE_SIZE}
+ if config.sort_by_field is not None:
+ # Newest-first lets incremental runs stop at the watermark instead
+ # of paging through history (and keeps full scans deterministic).
+ body["sort_by_field"] = config.sort_by_field
+ body["sort_ascending"] = False
+ response = session.post(url, json=body, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise ApolloRetryableError(f"Apollo API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Apollo API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ while True:
+ data = fetch_page(page)
+ items = data.get(config.data_key, []) or []
+
+ crossed_watermark = False
+ if watermark is not None:
+ fresh: list[dict[str, Any]] = []
+ for item in items:
+ item_ts = _parse_timestamp(item.get("updated_at"))
+ if item_ts is None:
+ # No parseable updated_at: keep the record (the merge dedupes
+ # on primary key) rather than risk dropping a genuinely new
+ # row. It can't advance past the watermark, so it never
+ # triggers the early-exit on its own.
+ fresh.append(item)
+ continue
+ if item_ts <= watermark:
+ crossed_watermark = True
+ break
+ fresh.append(item)
+ items = fresh
+
+ if items:
+ yield items
+
+ if crossed_watermark or not items:
+ break
+
+ if page >= MAX_PAGES:
+ # Apollo hard-caps search results at 500 pages / 50k records per query.
+ # Checked before the total_pages break so the cap is never silent when
+ # the last reachable page coincides with the reported total.
+ logger.error(
+ f"Apollo: hit the 50,000-record search cap on {endpoint}; older records are not retrievable "
+ "without filter slicing"
+ )
+ break
+
+ total_pages = (data.get("pagination") or {}).get("total_pages")
+ if isinstance(total_pages, int) and page >= total_pages:
+ break
+
+ page += 1
+ # Save state AFTER yielding the page so a crash re-yields the last page
+ # (merge dedupes on primary key) rather than skipping it.
+ resumable_source_manager.save_state(ApolloResumeConfig(page=page))
+
+
+def apollo_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ApolloResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = APOLLO_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=[config.primary_key],
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ # Incremental streams walk newest-first; the pipeline commits desc
+ # watermarks only when a run completes.
+ sort_mode="desc" if config.sort_by_field else "asc",
+ )
diff --git a/posthog/temporal/data_imports/sources/apollo/settings.py b/posthog/temporal/data_imports/sources/apollo/settings.py
new file mode 100644
index 000000000000..ec511de45498
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/apollo/settings.py
@@ -0,0 +1,60 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+_UPDATED_AT_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+
+@dataclass
+class ApolloEndpointConfig:
+ name: str
+ # Search path under /api/v1 (search endpoints are POSTs with JSON bodies).
+ path: str
+ # Key the rows live under in the response body.
+ data_key: str
+ primary_key: str = "id"
+ # Apollo has no server-side timestamp filter; incremental streams sort
+ # descending on this field and stop at the persisted high-water mark
+ # (the same CDC emulation Fivetran uses on CONTACT/ACCOUNT).
+ sort_by_field: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ partition_key: Optional[str] = None
+
+
+APOLLO_ENDPOINTS: dict[str, ApolloEndpointConfig] = {
+ "contacts": ApolloEndpointConfig(
+ name="contacts",
+ path="/contacts/search",
+ data_key="contacts",
+ sort_by_field="contact_updated_at",
+ partition_key="created_at",
+ incremental_fields=list(_UPDATED_AT_INCREMENTAL_FIELDS),
+ ),
+ "accounts": ApolloEndpointConfig(
+ name="accounts",
+ path="/accounts/search",
+ data_key="accounts",
+ sort_by_field="account_updated_at",
+ partition_key="created_at",
+ incremental_fields=list(_UPDATED_AT_INCREMENTAL_FIELDS),
+ ),
+ "opportunities": ApolloEndpointConfig(
+ name="opportunities",
+ path="/opportunities/search",
+ data_key="opportunities",
+ ),
+}
+
+ENDPOINTS = tuple(APOLLO_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in APOLLO_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/posthog/temporal/data_imports/sources/apollo/source.py b/posthog/temporal/data_imports/sources/apollo/source.py
index d940d14b5ac5..8135e5b418ce 100644
--- a/posthog/temporal/data_imports/sources/apollo/source.py
+++ b/posthog/temporal/data_imports/sources/apollo/source.py
@@ -1,29 +1,115 @@
-from typing import cast
+from typing import Optional, cast
from 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.apollo.apollo import (
+ ApolloResumeConfig,
+ apollo_source,
+ validate_credentials as validate_apollo_credentials,
+)
+from posthog.temporal.data_imports.sources.apollo.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from 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 SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import ApolloSourceConfig
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ApolloSource(SimpleSource[ApolloSourceConfig]):
+class ApolloSource(ResumableSource[ApolloSourceConfig, ApolloResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.APOLLO
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.apollo.io": "Apollo authentication failed. Please check your API key.",
+ "403 Client Error: Forbidden for url: https://api.apollo.io": "Apollo denied access. API access requires a paid Apollo plan, and some endpoints need a master API key.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.APOLLO,
label="Apollo",
+ caption="""Enter your Apollo API key to pull your saved contacts, accounts, and deals into the PostHog Data warehouse.
+
+You can create an API key in Apollo under Settings > Integrations > API. API access requires a paid Apollo plan. Note that Apollo search results are capped at 50,000 records per stream.""",
iconPath="/static/services/apollo.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/apollo",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: ApolloSourceConfig,
+ 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: ApolloSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_apollo_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Apollo API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ApolloResumeConfig]:
+ return ResumableSourceManager[ApolloResumeConfig](inputs, ApolloResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ApolloSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ApolloResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return apollo_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/posthog/temporal/data_imports/sources/apollo/tests/test_apollo.py b/posthog/temporal/data_imports/sources/apollo/tests/test_apollo.py
new file mode 100644
index 000000000000..c12ce76d6a6f
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/apollo/tests/test_apollo.py
@@ -0,0 +1,230 @@
+from datetime import UTC, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.apollo.apollo import (
+ MAX_PAGES,
+ PAGE_SIZE,
+ ApolloResumeConfig,
+ _parse_timestamp,
+ apollo_source,
+ get_rows,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.apollo.settings import APOLLO_ENDPOINTS, ENDPOINTS
+
+_MODULE = "posthog.temporal.data_imports.sources.apollo.apollo"
+
+
+def _make_manager(resume_state: ApolloResumeConfig | 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(data_key: str, items: list[dict[str, Any]], total_pages: int = 1) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = {
+ data_key: items,
+ "pagination": {"page": 1, "per_page": PAGE_SIZE, "total_pages": total_pages},
+ }
+ resp.status_code = 200
+ resp.ok = True
+ return resp
+
+
+class TestParseTimestamp:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ ("2024-01-02T03:04:05Z", datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC)),
+ ("2024-01-02T03:04:05+00:00", datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC)),
+ (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC)),
+ ("not-a-date", None),
+ (None, None),
+ ],
+ )
+ def test_parse_values(self, value, expected):
+ assert _parse_timestamp(value) == expected
+
+
+class TestValidateCredentials:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_valid_when_logged_in(self, mock_session):
+ resp = mock.MagicMock()
+ resp.status_code = 200
+ resp.json.return_value = {"is_logged_in": True}
+ mock_session.return_value.get.return_value = resp
+
+ assert validate_credentials("key") is True
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_invalid_when_not_logged_in(self, mock_session):
+ resp = mock.MagicMock()
+ resp.status_code = 200
+ resp.json.return_value = {"is_logged_in": False}
+ mock_session.return_value.get.return_value = resp
+
+ assert validate_credentials("key") is False
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_invalid_on_error_status(self, mock_session):
+ resp = mock.MagicMock()
+ resp.status_code = 401
+ mock_session.return_value.get.return_value = resp
+
+ assert validate_credentials("key") is False
+
+
+class TestGetRows:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_paginates_until_total_pages(self, mock_session):
+ mock_session.return_value.post.side_effect = [
+ _response("contacts", [{"id": "c1", "updated_at": "2024-01-02T00:00:00Z"}], total_pages=2),
+ _response("contacts", [{"id": "c2", "updated_at": "2024-01-01T00:00:00Z"}], total_pages=2),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "contacts", mock.MagicMock(), manager))
+
+ assert [item["id"] for batch in batches for item in batch] == ["c1", "c2"]
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0].page == 2
+ bodies = [call.kwargs["json"] for call in mock_session.return_value.post.call_args_list]
+ assert bodies[0]["page"] == 1
+ assert bodies[1]["page"] == 2
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_incremental_sorts_desc_and_stops_at_watermark(self, mock_session):
+ page = [
+ {"id": "new", "updated_at": "2024-06-01T00:00:00Z"},
+ {"id": "old", "updated_at": "2024-01-01T00:00:00Z"},
+ ]
+ mock_session.return_value.post.return_value = _response("contacts", page, total_pages=5)
+
+ manager = _make_manager()
+ batches = list(
+ get_rows(
+ "key",
+ "contacts",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 3, 1, tzinfo=UTC),
+ )
+ )
+
+ # Only the newer row is yielded and the walk stops on crossing.
+ assert [item["id"] for batch in batches for item in batch] == ["new"]
+ assert mock_session.return_value.post.call_count == 1
+ body = mock_session.return_value.post.call_args.kwargs["json"]
+ assert body["sort_by_field"] == "contact_updated_at"
+ assert body["sort_ascending"] is False
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_opportunities_have_no_sort_fields(self, mock_session):
+ mock_session.return_value.post.return_value = _response("opportunities", [])
+
+ manager = _make_manager()
+ list(get_rows("key", "opportunities", mock.MagicMock(), manager))
+
+ body = mock_session.return_value.post.call_args.kwargs["json"]
+ assert "sort_by_field" not in body
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_resumes_from_saved_page(self, mock_session):
+ mock_session.return_value.post.return_value = _response("contacts", [])
+
+ manager = _make_manager(ApolloResumeConfig(page=7))
+ list(get_rows("key", "contacts", mock.MagicMock(), manager))
+
+ body = mock_session.return_value.post.call_args.kwargs["json"]
+ assert body["page"] == 7
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_search_cap_is_logged(self, mock_session):
+ mock_session.return_value.post.return_value = _response(
+ "contacts", [{"id": "c", "updated_at": "2024-01-01T00:00:00Z"}], total_pages=MAX_PAGES + 10
+ )
+
+ manager = _make_manager(ApolloResumeConfig(page=MAX_PAGES))
+ logger = mock.MagicMock()
+ batches = list(get_rows("key", "contacts", logger, manager))
+
+ assert len(batches) == 1
+ logger.error.assert_called_once()
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_search_cap_is_logged_when_total_pages_equals_cap(self, mock_session):
+ # Exactly at the cap: the final reachable page coincides with total_pages,
+ # so the cap must still be logged rather than swallowed by the total_pages break.
+ mock_session.return_value.post.return_value = _response(
+ "contacts", [{"id": "c", "updated_at": "2024-01-01T00:00:00Z"}], total_pages=MAX_PAGES
+ )
+
+ manager = _make_manager(ApolloResumeConfig(page=MAX_PAGES))
+ logger = mock.MagicMock()
+ batches = list(get_rows("key", "contacts", logger, manager))
+
+ assert len(batches) == 1
+ logger.error.assert_called_once()
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_incremental_keeps_records_without_parseable_updated_at(self, mock_session):
+ # A record with a missing updated_at must not be dropped, and must not stop
+ # the walk before a genuinely older record is reached.
+ page = [
+ {"id": "new", "updated_at": "2024-06-01T00:00:00Z"},
+ {"id": "no-ts"},
+ {"id": "old", "updated_at": "2024-01-01T00:00:00Z"},
+ ]
+ mock_session.return_value.post.return_value = _response("contacts", page, total_pages=5)
+
+ manager = _make_manager()
+ batches = list(
+ get_rows(
+ "key",
+ "contacts",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 3, 1, tzinfo=UTC),
+ )
+ )
+
+ assert [item["id"] for batch in batches for item in batch] == ["new", "no-ts"]
+ assert mock_session.return_value.post.call_count == 1
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_empty_response_stops_without_saving_state(self, mock_session):
+ mock_session.return_value.post.return_value = _response("contacts", [])
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "contacts", mock.MagicMock(), manager))
+
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+
+class TestApolloSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = APOLLO_ENDPOINTS[endpoint]
+ response = apollo_source("key", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == [config.primary_key]
+ assert response.sort_mode == ("desc" if config.sort_by_field else "asc")
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+
+ @pytest.mark.parametrize("config", list(APOLLO_ENDPOINTS.values()))
+ def test_partition_keys_are_stable_creation_fields(self, config):
+ if config.partition_key:
+ assert config.partition_key == "created_at"
diff --git a/posthog/temporal/data_imports/sources/apollo/tests/test_apollo_source.py b/posthog/temporal/data_imports/sources/apollo/tests/test_apollo_source.py
new file mode 100644
index 000000000000..1b5dd1d1c0f9
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/apollo/tests/test_apollo_source.py
@@ -0,0 +1,140 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.apollo.apollo import ApolloResumeConfig
+from posthog.temporal.data_imports.sources.apollo.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.apollo.source import ApolloSource
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import ApolloSourceConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestApolloSource:
+ def setup_method(self):
+ self.source = ApolloSource()
+ self.team_id = 123
+ self.config = ApolloSourceConfig(api_key="api-key")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.APOLLO
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Apollo"
+ assert config.label == "Apollo"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/apollo.png"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ def test_api_key_field_is_secret_password(self):
+ config = self.source.get_source_config
+ key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert key_field.secret is True
+ assert key_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.apollo.io/api/v1/contacts/search",
+ "403 Client Error: Forbidden for url: https://api.apollo.io/api/v1/accounts/search",
+ ],
+ )
+ 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.apollo.io/api/v1/contacts/search",
+ ],
+ )
+ 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)
+ incremental = {schema.name for schema in schemas if schema.supports_incremental}
+ # Contacts and accounts support sort-based CDC; opportunities don't.
+ assert incremental == {"contacts", "accounts"}
+
+ 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["contacts"].incremental_fields == INCREMENTAL_FIELDS["contacts"]
+ assert [f["field"] for f in schemas["contacts"].incremental_fields] == ["updated_at"]
+ assert schemas["opportunities"].incremental_fields == []
+ assert schemas["opportunities"].supports_append is False
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["contacts"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "contacts"
+
+ 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 Apollo API key"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.apollo.source.validate_apollo_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_key)
+
+ 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 ApolloResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.apollo.source.apollo_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_apollo_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "contacts"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_apollo_source.assert_called_once()
+ kwargs = mock_apollo_source.call_args.kwargs
+ assert kwargs["api_key"] == "api-key"
+ assert kwargs["endpoint"] == "contacts"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-01-02T03:04:05Z"
+
+ @mock.patch("posthog.temporal.data_imports.sources.apollo.source.apollo_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_apollo_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "opportunities"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_apollo_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 2ea5af6a75d7..f325d39d1f8e 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -207,7 +207,7 @@ class AmplitudeSourceConfig(config.Config):
@config.config
class ApolloSourceConfig(config.Config):
- pass
+ api_key: str
@config.config