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 salesflare import source (#68553)

Tom Owers4eb0a9aca97b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 80cc586911a8..703c1fa765c8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -297,6 +297,7 @@ the row lists both.
| rootly | HTTP | requests | ✅ |
| ruddr | HTTP | requests | ✅ |
| salesforce | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| salesflare | HTTP | requests | ✅ |
| salesloft | HTTP | requests | ✅ |
| secoda | HTTP | requests | ✅ |
| segment | HTTP | requests | ✅ |
@@ -636,7 +637,6 @@ doesn't conflict with concurrent PRs.
- sage_hr
- sage_intacct
- sailthru
-- salesflare
- salesforce_marketing_cloud
- sanity
- sap_concur
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.py
index df933356148c..ae6de1e248d0 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
@@ -2856,7 +2856,7 @@ class SalesLoftSourceConfig(config.Config):
@config.config
class SalesflareSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/salesflare/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/salesflare/canonical_descriptions.py
new file mode 100644
index 000000000000..2251fbab0406
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/salesflare/canonical_descriptions.py
@@ -0,0 +1,81 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Salesflare REST API docs (https://api.salesflare.com/docs).
+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "contacts": {
+ "description": "A person in your Salesflare CRM — a lead, prospect, or customer contact.",
+ "docs_url": "https://api.salesflare.com/docs",
+ "columns": {
+ "id": "The unique ID of the contact.",
+ "email": "The contact's primary email address.",
+ "name": "The contact's full name.",
+ "firstname": "The contact's first name.",
+ "lastname": "The contact's last name.",
+ "phone_number": "The contact's phone number.",
+ "creation_date": "When the contact was created.",
+ "modification_date": "When the contact was last modified.",
+ },
+ },
+ "accounts": {
+ "description": "A company or organisation tracked in Salesflare.",
+ "docs_url": "https://api.salesflare.com/docs",
+ "columns": {
+ "id": "The unique ID of the account.",
+ "name": "The account (company) name.",
+ "website": "The account's website URL.",
+ "email": "The account's primary email address.",
+ "creation_date": "When the account was created.",
+ "modification_date": "When the account was last modified.",
+ },
+ },
+ "opportunities": {
+ "description": "A sales opportunity (deal) in a pipeline.",
+ "docs_url": "https://api.salesflare.com/docs",
+ "columns": {
+ "id": "The unique ID of the opportunity.",
+ "name": "The name of the opportunity.",
+ "value": "The monetary value of the opportunity.",
+ "pipeline": "The pipeline the opportunity belongs to.",
+ "stage": "The current stage of the opportunity.",
+ "close_date": "The expected or actual close date.",
+ "creation_date": "When the opportunity was created.",
+ },
+ },
+ "pipelines": {
+ "description": "A sales pipeline that opportunities move through.",
+ "docs_url": "https://api.salesflare.com/docs",
+ "columns": {
+ "id": "The unique ID of the pipeline.",
+ "name": "The name of the pipeline.",
+ },
+ },
+ "tasks": {
+ "description": "A to-do or reminder linked to a contact, account, or opportunity.",
+ "docs_url": "https://api.salesflare.com/docs",
+ "columns": {
+ "id": "The unique ID of the task.",
+ "description": "The task description.",
+ "reminder_date": "When the task is due.",
+ "completed": "Whether the task has been completed.",
+ },
+ },
+ "tags": {
+ "description": "A label used to categorise contacts and accounts.",
+ "docs_url": "https://api.salesflare.com/docs",
+ "columns": {
+ "id": "The unique ID of the tag.",
+ "name": "The tag name.",
+ },
+ },
+ "workflows": {
+ "description": "An automated email workflow (campaign) configured in Salesflare.",
+ "docs_url": "https://api.salesflare.com/docs",
+ "columns": {
+ "id": "The unique ID of the workflow.",
+ "name": "The name of the workflow.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/salesflare/salesflare.py b/products/warehouse_sources/backend/temporal/data_imports/sources/salesflare/salesflare.py
new file mode 100644
index 000000000000..c64baca2ff56
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/salesflare/salesflare.py
@@ -0,0 +1,151 @@
+import dataclasses
+from collections.abc import Iterator
+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 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.salesflare.settings import SALESFLARE_ENDPOINTS
+
+SALESFLARE_BASE_URL = "https://api.salesflare.com"
+# The list endpoints accept a `limit` of up to 100; the largest page minimises round trips.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+# Cheap endpoint used to confirm an API key is genuine. The key is account-wide, so one probe
+# validates access to every list endpoint.
+DEFAULT_PROBE_PATH = "/me"
+
+
+class SalesflareRetryableError(Exception):
+ pass
+
+
+class SalesflareResumeConfig:
+ # Offset of the next page to fetch. Offset pagination is deterministic, so a crashed
+ # full-refresh sync resumes from the page after the last one yielded; merge dedupes on `id`.
+ offset: int = 0
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}
+
+
+@retry(
+ retry=retry_if_exception_type((SalesflareRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ path: str,
+ offset: int,
+ limit: int,
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ response = session.get(
+ f"{SALESFLARE_BASE_URL}{path}",
+ params={"limit": limit, "offset": offset},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise SalesflareRetryableError(f"Salesflare API error (retryable): status={response.status_code}, path={path}")
+
+ if not response.ok:
+ # Don't log the raw body: Salesflare error payloads can echo CRM records or request context,
+ # which would copy third-party data into our logs. Status and path are enough to triage.
+ logger.error(f"Salesflare API error: status={response.status_code}, path={path}")
+ response.raise_for_status()
+
+ data = response.json()
+ # Salesflare list endpoints return a bare JSON array of records.
+ if not isinstance(data, list):
+ raise SalesflareRetryableError(f"Salesflare returned an unexpected payload for {path}: {type(data).__name__}")
+ return data
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SalesflareResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = SALESFLARE_ENDPOINTS[endpoint]
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ offset = resume.offset if resume else 0
+ if resume and resume.offset > 0:
+ logger.debug(f"Salesflare: resuming {endpoint} from offset {offset}")
+
+ while True:
+ items = _fetch_page(session, config.path, offset, PAGE_SIZE, logger)
+ if items:
+ yield items
+
+ # A short page (or an empty one) means we've reached the end of the collection.
+ if len(items) < PAGE_SIZE:
+ break
+
+ offset += PAGE_SIZE
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are
+ # persisted); merge dedupes the re-pulled page on the primary key.
+ resumable_source_manager.save_state(SalesflareResumeConfig(offset=offset))
+
+
+def salesflare_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SalesflareResumeConfig],
+) -> SourceResponse:
+ config = SALESFLARE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ )
+
+
+def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single endpoint to validate the API key.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise.
+ """
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+ try:
+ response = session.get(f"{SALESFLARE_BASE_URL}{path}", timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to Salesflare: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"Salesflare returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ status, message = check_access(api_key)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid Salesflare API key"
+ return False, message or "Could not validate Salesflare API key"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/salesflare/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/salesflare/settings.py
new file mode 100644
index 000000000000..a5744c906f4f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/salesflare/settings.py
@@ -0,0 +1,27 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class SalesflareEndpointConfig:
+ path: str
+ # Salesflare object IDs are globally unique within an account, so `id` is a safe primary key.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+# Salesflare Core API list endpoints. All are full-refresh only: while a few objects expose a
+# `modification_after` filter, the API's ordering guarantees for that filter aren't documented
+# well enough to advance an incremental cursor safely, so a client-side scan would cost the same
+# as a full refresh (see the implementing-warehouse-sources skill).
+SALESFLARE_ENDPOINTS: dict[str, SalesflareEndpointConfig] = {
+ "contacts": SalesflareEndpointConfig(path="/contacts"),
+ "accounts": SalesflareEndpointConfig(path="/accounts"),
+ "opportunities": SalesflareEndpointConfig(path="/opportunities"),
+ "pipelines": SalesflareEndpointConfig(path="/pipelines"),
+ "tasks": SalesflareEndpointConfig(path="/tasks"),
+ "tags": SalesflareEndpointConfig(path="/tags"),
+ "workflows": SalesflareEndpointConfig(path="/workflows"),
+}
+
+ENDPOINTS = tuple(SALESFLARE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/salesflare/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/salesflare/source.py
index 3997d55b8c54..bd1f7eb8d4c4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/salesflare/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/salesflare/source.py
@@ -1,19 +1,42 @@
-from typing import cast
+from typing import Optional, cast
from 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.generated_configs import SalesflareSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.salesflare.salesflare import (
+ SalesflareResumeConfig,
+ salesflare_source,
+ validate_credentials as _validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.salesflare.settings import (
+ ENDPOINTS,
+ SALESFLARE_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SalesflareSource(SimpleSource[SalesflareSourceConfig]):
+class SalesflareSource(ResumableSource[SalesflareSourceConfig, SalesflareResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SALESFLARE
@@ -24,7 +47,86 @@ class SalesflareSource(SimpleSource[SalesflareSourceConfig]):
name=SchemaExternalDataSourceType.SALESFLARE,
category=DataWarehouseSourceCategory.CRM,
label="Salesflare",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Salesflare API key to pull your CRM data into the PostHog Data warehouse.
+
+You can create an API key under **Settings → API keys** in [Salesflare](https://app.salesflare.com/#/settings/apikeys). The key grants read access to your contacts, accounts, opportunities, pipelines, tasks, tags, and workflows.
+""",
iconPath="/static/services/salesflare.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/salesflare",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.salesflare.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.salesflare.com": "Your Salesflare API key is invalid or has been revoked. Generate a new key under Settings → API keys, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.salesflare.com": "Your Salesflare API key does not have access to this data. Check the key's permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: SalesflareSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every endpoint is full refresh only — Salesflare's list endpoints expose no reliably
+ # ordered server-side timestamp filter, so there is no incremental cursor to advance.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ 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: SalesflareSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The API key is account-wide, so a single probe validates access to every schema.
+ return _validate_credentials(config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SalesflareResumeConfig]:
+ return ResumableSourceManager[SalesflareResumeConfig](inputs, SalesflareResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SalesflareSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SalesflareResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in SALESFLARE_ENDPOINTS:
+ raise ValueError(f"Unknown Salesflare schema '{inputs.schema_name}'")
+
+ return salesflare_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/salesflare/tests/test_salesflare.py b/products/warehouse_sources/backend/temporal/data_imports/sources/salesflare/tests/test_salesflare.py
new file mode 100644
index 000000000000..d8f64078ded6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/salesflare/tests/test_salesflare.py
@@ -0,0 +1,223 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+from unittest.mock import MagicMock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.salesflare import salesflare
+from products.warehouse_sources.backend.temporal.data_imports.sources.salesflare.salesflare import (
+ PAGE_SIZE,
+ SalesflareResumeConfig,
+ SalesflareRetryableError,
+ check_access,
+ get_rows,
+ salesflare_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.salesflare.settings import (
+ ENDPOINTS,
+ SALESFLARE_ENDPOINTS,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = salesflare._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: SalesflareResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[SalesflareResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> SalesflareResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: SalesflareResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _full_page(start_id: int) -> list[dict]:
+ return [{"id": start_id + i} for i in range(PAGE_SIZE)]
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[int, list[dict]], endpoint: str = "contacts"
+ ) -> list[dict]:
+ def fake_fetch(session: Any, path: str, offset: int, limit: int, logger: Any) -> list[dict]:
+ return pages[offset]
+
+ monkeypatch.setattr(salesflare, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(salesflare, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_key="sf-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows
+
+ def test_single_short_page_yields_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {0: [{"id": 1}, {"id": 2}]})
+ assert rows == [{"id": 1}, {"id": 2}]
+ # The page is short (< PAGE_SIZE), so we stop without persisting resume state.
+ assert manager.saved == []
+
+ def test_follows_offset_pagination_until_short_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {0: _full_page(0), PAGE_SIZE: [{"id": 999}]}
+ rows = self._collect(manager, monkeypatch, pages)
+ assert len(rows) == PAGE_SIZE + 1
+ # State is saved after the first full page (offset advances to PAGE_SIZE), then we stop.
+ assert [s.offset for s in manager.saved] == [PAGE_SIZE]
+
+ def test_resumes_from_saved_offset(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(SalesflareResumeConfig(offset=PAGE_SIZE))
+ # Offset 0 must never be fetched on resume.
+ pages = {PAGE_SIZE: [{"id": 5}]}
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": 5}]
+
+ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {0: []})
+ assert rows == []
+ assert manager.saved == []
+
+
+class TestFetchPage:
+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else []
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(SalesflareRetryableError):
+ _fetch_page_unwrapped(session, "/contacts", 0, PAGE_SIZE, MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(session, "/contacts", 0, PAGE_SIZE, MagicMock())
+
+ def test_success_returns_list_body(self) -> None:
+ body = [{"id": 1}]
+ session = self._session_returning(200, body)
+ result = _fetch_page_unwrapped(session, "/contacts", 0, PAGE_SIZE, MagicMock())
+ assert result == body
+
+ def test_non_list_body_is_retryable(self) -> None:
+ session = self._session_returning(200, {"error": "nope"})
+ with pytest.raises(SalesflareRetryableError):
+ _fetch_page_unwrapped(session, "/contacts", 0, PAGE_SIZE, MagicMock())
+
+ def test_request_uses_limit_and_offset_params(self) -> None:
+ session = self._session_returning(200, [])
+ _fetch_page_unwrapped(session, "/accounts", 200, PAGE_SIZE, MagicMock())
+ _, kwargs = session.get.call_args
+ assert kwargs["params"] == {"limit": PAGE_SIZE, "offset": 200}
+
+
+class TestCheckAccess:
+ @staticmethod
+ def _session(response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, 200, None),
+ ("unauthorized", 401, False, 401, None),
+ ("forbidden", 403, False, 403, None),
+ ("server_error", 500, False, 500, "Salesflare returned HTTP 500"),
+ ]
+ )
+ @mock.patch.object(salesflare, "make_tracked_session")
+ def test_status_mapping(
+ self,
+ _name: str,
+ status: int,
+ ok: bool,
+ expected_status: int,
+ expected_message: str | None,
+ mock_make_session: MagicMock,
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ mock_make_session.return_value = self._session(response)
+ assert check_access("sf-key") == (expected_status, expected_message)
+
+ @mock.patch.object(salesflare, "make_tracked_session")
+ def test_connection_error_maps_to_zero(self, mock_make_session: MagicMock) -> None:
+ mock_make_session.return_value = self._session(requests.ConnectionError("boom"))
+ status, message = check_access("sf-key")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, None),
+ ("unauthorized", 401, False, "Invalid Salesflare API key"),
+ ("forbidden", 403, False, "Invalid Salesflare API key"),
+ ("server_error", 500, False, "Salesflare returned HTTP 500"),
+ ]
+ )
+ @mock.patch.object(salesflare, "make_tracked_session")
+ def test_validate_credentials(
+ self,
+ _name: str,
+ status: int,
+ expected_valid: bool,
+ expected_message: str | None,
+ mock_make_session: MagicMock,
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ mock_make_session.return_value = self._session(response)
+ assert validate_credentials("sf-key") == (expected_valid, expected_message)
+
+
+class TestSalesflareSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = salesflare_source(
+ api_key="sf-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ # No stable creation timestamp is guaranteed across every object, so we don't partition.
+ assert response.partition_mode is None
+
+ def test_every_endpoint_uses_id_primary_key(self) -> None:
+ assert all(config.primary_keys == ["id"] for config in SALESFLARE_ENDPOINTS.values())
+ assert set(SALESFLARE_ENDPOINTS) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/salesflare/tests/test_salesflare_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/salesflare/tests/test_salesflare_source.py
new file mode 100644
index 000000000000..5675994d91c3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/salesflare/tests/test_salesflare_source.py
@@ -0,0 +1,151 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+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.generated_configs import SalesflareSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.salesflare.salesflare import (
+ SalesflareResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.salesflare.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.salesflare.source import SalesflareSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestSalesflareSource:
+ def setup_method(self) -> None:
+ self.source = SalesflareSource()
+ self.team_id = 123
+ self.config = SalesflareSourceConfig(api_key="sf-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.SALESFLARE
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Salesflare"
+ assert config.label == "Salesflare"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # A finished source is visible — it must not carry the scaffolding flag.
+ assert not config.unreleasedSource
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/salesflare"
+
+ 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) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_no_connection_host_fields(self) -> None:
+ # The only field is the secret API key; the base URL is hardcoded, so there is no non-secret
+ # field an editor could retarget to reuse a preserved key against another account.
+ assert self.source.connection_host_fields == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["accounts"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "accounts"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://api.salesflare.com/contacts?limit=100&offset=0",
+ ),
+ (
+ "forbidden",
+ "403 Client Error: Forbidden for url: https://api.salesflare.com/accounts?limit=100&offset=0",
+ ),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.salesflare.com/contacts"),
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.salesflare.com/accounts"),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, None),
+ ("unauthorized", 401, False, "Invalid Salesflare API key"),
+ ("forbidden", 403, False, "Invalid Salesflare API key"),
+ ("server_error", 500, False, "Salesflare returned HTTP 500"),
+ ("connection_error", 0, False, "Could not connect to Salesflare: boom"),
+ ]
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.salesflare.salesflare.check_access")
+ def test_validate_credentials(
+ self,
+ _name: str,
+ status: int,
+ expected_valid: bool,
+ expected_message: str | None,
+ mock_check: mock.MagicMock,
+ ) -> None:
+ message = (
+ "Salesflare returned HTTP 500"
+ if status == 500
+ else ("Could not connect to Salesflare: boom" if status == 0 else None)
+ )
+ mock_check.return_value = (status, message)
+ is_valid, returned = self.source.validate_credentials(self.config, self.team_id)
+ assert is_valid is expected_valid
+ assert returned == expected_message
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is SalesflareResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.salesflare.source.salesflare_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "contacts"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "sf-key"
+ assert kwargs["endpoint"] == "contacts"
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown Salesflare schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)