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 huntr import source (#68580)

Tom Owers8bf91ca310a2
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 56561df8323a..9a281dfecdae 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -188,6 +188,7 @@ the row lists both.
| hubplanner | HTTP | requests | ✅ |
| hubspot | HTTP | requests | ✅ |
| hugging_face | HTTP | requests | ✅ |
+| huntr | HTTP | requests | ✅ |
| incident_io | HTTP | requests | ✅ |
| inflowinventory | HTTP | requests | ✅ |
| insightly | HTTP | requests | ✅ |
@@ -493,7 +494,6 @@ doesn't conflict with concurrent PRs.
- hubplanner
- hugging_face
- humanitix
-- huntr
- ikas
- illumina_basespace
- imagga
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 49f6a314b790..79dc05236a9a 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
@@ -1581,7 +1581,7 @@ class HumanitixSourceConfig(config.Config):
@config.config
class HuntrSourceConfig(config.Config):
- pass
+ access_token: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/canonical_descriptions.py
new file mode 100644
index 000000000000..be72cff2b64b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/canonical_descriptions.py
@@ -0,0 +1,83 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Huntr Organization API docs (https://docs.huntr.co).
+# Partial coverage is fine — uncovered columns fall back to LLM enrichment. Huntr timestamps are
+# Unix seconds.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "members": {
+ "description": "A member (job seeker) whose job search the organization is following in Huntr.",
+ "docs_url": "https://docs.huntr.co",
+ "columns": {
+ "id": "The unique ID of the member.",
+ "firstName": "The member's first name.",
+ "lastName": "The member's last name.",
+ "email": "The member's email address.",
+ "createdAt": "When the member was created (Unix seconds).",
+ },
+ },
+ "advisors": {
+ "description": "An advisor — an organization team member who manages and supports job seekers.",
+ "docs_url": "https://docs.huntr.co",
+ "columns": {
+ "id": "The unique ID of the advisor.",
+ "firstName": "The advisor's first name.",
+ "lastName": "The advisor's last name.",
+ "email": "The advisor's email address.",
+ },
+ },
+ "candidates": {
+ "description": "A candidate profile managed within the organization.",
+ "docs_url": "https://docs.huntr.co",
+ "columns": {
+ "id": "The unique ID of the candidate.",
+ "firstName": "The candidate's first name.",
+ "lastName": "The candidate's last name.",
+ "email": "The candidate's email address.",
+ },
+ },
+ "jobs": {
+ "description": "A job a member is tracking on their board (a saved role and its application progress).",
+ "docs_url": "https://docs.huntr.co",
+ "columns": {
+ "id": "The unique ID of the job.",
+ "title": "The job title.",
+ "company": "The company the job is at.",
+ "createdAt": "When the job was created (Unix seconds).",
+ },
+ },
+ "job_posts": {
+ "description": "A job post published or shared by the organization to its members.",
+ "docs_url": "https://docs.huntr.co",
+ "columns": {
+ "id": "The unique ID of the job post.",
+ "title": "The job post title.",
+ "createdAt": "When the job post was created (Unix seconds).",
+ },
+ },
+ "employers": {
+ "description": "An employer tracked by the organization.",
+ "docs_url": "https://docs.huntr.co",
+ "columns": {
+ "id": "The unique ID of the employer.",
+ "name": "The employer's name.",
+ },
+ },
+ "activities": {
+ "description": "An activity — an interview, task, or event linked to a member's job search.",
+ "docs_url": "https://docs.huntr.co",
+ "columns": {
+ "id": "The unique ID of the activity.",
+ "createdAt": "When the activity was created (Unix seconds).",
+ },
+ },
+ "actions": {
+ "description": "An action recorded against a member or job (Huntr's successor to the deprecated events resource).",
+ "docs_url": "https://docs.huntr.co",
+ "columns": {
+ "id": "The unique ID of the action.",
+ "createdAt": "When the action was created (Unix seconds).",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/huntr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/huntr.py
new file mode 100644
index 000000000000..ef555586ff96
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/huntr.py
@@ -0,0 +1,163 @@
+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.huntr.settings import HUNTR_ENDPOINTS
+
+HUNTR_BASE_URL = "https://api.huntr.co/org"
+# The list endpoints accept a `limit`; the docs don't state a hard maximum, so 100 keeps each page
+# reasonably sized while minimising round trips.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+# Cheap endpoint used to confirm an access token is genuine. The org access token is account-wide, so
+# one probe validates access to every list endpoint.
+DEFAULT_PROBE_PATH = "/members"
+
+
+class HuntrRetryableError(Exception):
+ pass
+
+
+class HuntrResumeConfig:
+ # Cursor for the next page to fetch — Huntr returns the `id` of the last object on the page as
+ # `next`, and passing it back fetches the following page. Cursor pagination is deterministic, so a
+ # crashed full-refresh sync resumes from the page after the last one yielded; merge dedupes on `id`.
+ next: str | None = None
+
+
+def _headers(access_token: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {access_token}", "Accept": "application/json"}
+
+
+@retry(
+ retry=retry_if_exception_type((HuntrRetryableError, 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,
+ cursor: str | None,
+ limit: int,
+ logger: FilteringBoundLogger,
+) -> tuple[list[dict[str, Any]], str | None]:
+ params: dict[str, Any] = {"limit": limit}
+ # The first request omits `next`; subsequent requests pass the cursor from the previous page.
+ if cursor is not None:
+ params["next"] = cursor
+
+ response = session.get(
+ f"{HUNTR_BASE_URL}{path}",
+ params=params,
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise HuntrRetryableError(f"Huntr API error (retryable): status={response.status_code}, path={path}")
+
+ if not response.ok:
+ logger.error(f"Huntr API error: status={response.status_code}, body={response.text}, path={path}")
+ response.raise_for_status()
+
+ data = response.json()
+ # Huntr list endpoints wrap results in {"data": [...], "next": "<cursor>"}.
+ if not isinstance(data, dict):
+ raise HuntrRetryableError(f"Huntr returned an unexpected payload for {path}: {type(data).__name__}")
+
+ items = data.get("data")
+ if not isinstance(items, list):
+ raise HuntrRetryableError(f"Huntr returned an unexpected 'data' field for {path}: {type(items).__name__}")
+
+ next_cursor = data.get("next")
+ return items, next_cursor if isinstance(next_cursor, str) else None
+
+
+def get_rows(
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[HuntrResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = HUNTR_ENDPOINTS[endpoint]
+ session = make_tracked_session(headers=_headers(access_token), redact_values=(access_token,))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ cursor = resume.next if resume else None
+ if resume and resume.next is not None:
+ logger.debug(f"Huntr: resuming {endpoint} from cursor {cursor}")
+
+ while True:
+ items, next_cursor = _fetch_page(session, config.path, cursor, PAGE_SIZE, logger)
+ if items:
+ yield items
+
+ # A missing/null `next` cursor marks the end of the collection. An empty page also terminates
+ # defensively so a lingering cursor can never produce an infinite loop.
+ if not next_cursor or not items:
+ break
+
+ cursor = next_cursor
+ # 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(HuntrResumeConfig(next=cursor))
+
+
+def huntr_source(
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[HuntrResumeConfig],
+) -> SourceResponse:
+ config = HUNTR_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ access_token=access_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ )
+
+
+def check_access(access_token: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single endpoint to validate the access token.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise.
+ """
+ session = make_tracked_session(headers=_headers(access_token), redact_values=(access_token,))
+ try:
+ response = session.get(f"{HUNTR_BASE_URL}{path}", params={"limit": 1}, timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to Huntr: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"Huntr returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(access_token: str) -> tuple[bool, str | None]:
+ status, message = check_access(access_token)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid Huntr access token"
+ return False, message or "Could not validate Huntr access token"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/settings.py
new file mode 100644
index 000000000000..d16d3c92549c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/settings.py
@@ -0,0 +1,29 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class HuntrEndpointConfig:
+ name: str
+ path: str
+ # Huntr object IDs are globally unique within an organization, so `id` is a safe primary key.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+# Huntr Organization API list endpoints (https://docs.huntr.co). All are full-refresh only: only the
+# jobs endpoint documents a created_after/created_before filter, and no resource exposes a reliable
+# updated_after cursor, so there is no incremental cursor to advance safely across every stream (see
+# the implementing-warehouse-sources skill).
+HUNTR_ENDPOINTS: dict[str, HuntrEndpointConfig] = {
+ "members": HuntrEndpointConfig(name="members", path="/members"),
+ "advisors": HuntrEndpointConfig(name="advisors", path="/advisors"),
+ "candidates": HuntrEndpointConfig(name="candidates", path="/candidates"),
+ "jobs": HuntrEndpointConfig(name="jobs", path="/jobs"),
+ "job_posts": HuntrEndpointConfig(name="job_posts", path="/job-posts"),
+ "employers": HuntrEndpointConfig(name="employers", path="/employers"),
+ "activities": HuntrEndpointConfig(name="activities", path="/activities"),
+ "actions": HuntrEndpointConfig(name="actions", path="/actions"),
+}
+
+ENDPOINTS = tuple(HUNTR_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/source.py
index f7f23c6e6a2a..145bf8dd6718 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/source.py
@@ -1,19 +1,39 @@
-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 HuntrSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.huntr.huntr import (
+ HuntrResumeConfig,
+ huntr_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.huntr.settings import ENDPOINTS, HUNTR_ENDPOINTS
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class HuntrSource(SimpleSource[HuntrSourceConfig]):
+class HuntrSource(ResumableSource[HuntrSourceConfig, HuntrResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.HUNTR
@@ -24,7 +44,87 @@ class HuntrSource(SimpleSource[HuntrSourceConfig]):
name=SchemaExternalDataSourceType.HUNTR,
category=DataWarehouseSourceCategory.HR___RECRUITING,
label="Huntr",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Huntr organization access token to pull your Organization API data into the PostHog Data warehouse.
+
+You can generate an access token in your Huntr organization admin dashboard. The token grants read access to your members, advisors, candidates, jobs, job posts, employers, activities, and actions.
+""",
iconPath="/static/services/huntr.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/huntr",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="access_token",
+ label="Organization access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.huntr.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.huntr.co/org": "Your Huntr access token is invalid or has been revoked. Generate a new token in your Huntr organization admin dashboard, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.huntr.co/org": "Your Huntr access token does not have access to this data. Check the token's permissions in your organization admin dashboard, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: HuntrSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every endpoint is full refresh only — only Huntr's jobs endpoint exposes a documented
+ # created_after/created_before filter, and no resource exposes a reliable updated_after
+ # cursor, so there is no incremental cursor to advance across every stream.
+ 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: HuntrSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The access token is organization-wide, so a single probe validates access to every schema.
+ return validate_credentials(config.access_token)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HuntrResumeConfig]:
+ return ResumableSourceManager[HuntrResumeConfig](inputs, HuntrResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: HuntrSourceConfig,
+ resumable_source_manager: ResumableSourceManager[HuntrResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in HUNTR_ENDPOINTS:
+ raise ValueError(f"Unknown Huntr schema '{inputs.schema_name}'")
+
+ return huntr_source(
+ access_token=config.access_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/tests/test_huntr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/tests/test_huntr.py
new file mode 100644
index 000000000000..c276ba829e14
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/tests/test_huntr.py
@@ -0,0 +1,237 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.huntr import huntr
+from products.warehouse_sources.backend.temporal.data_imports.sources.huntr.huntr import (
+ PAGE_SIZE,
+ HuntrResumeConfig,
+ HuntrRetryableError,
+ check_access,
+ get_rows,
+ huntr_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.huntr.settings import ENDPOINTS, HUNTR_ENDPOINTS
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = huntr._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: HuntrResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[HuntrResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> HuntrResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: HuntrResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: dict[str | None, tuple[list[dict], str | None]],
+ endpoint: str = "members",
+ ) -> list[dict]:
+ def fake_fetch(
+ session: Any, path: str, cursor: str | None, limit: int, logger: Any
+ ) -> tuple[list[dict], str | None]:
+ return pages[cursor]
+
+ monkeypatch.setattr(huntr, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(huntr, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ access_token="huntr-token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows
+
+ def test_single_page_no_next_yields_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {None: ([{"id": "a"}, {"id": "b"}], None)})
+ assert rows == [{"id": "a"}, {"id": "b"}]
+ # `next` is null, so we stop without persisting resume state.
+ assert manager.saved == []
+
+ def test_follows_cursor_until_next_is_null(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {None: ([{"id": "a"}], "a"), "a": ([{"id": "b"}], None)}
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": "a"}, {"id": "b"}]
+ # State is saved after the first page (cursor advances to "a"), then the null cursor stops us.
+ assert [s.next for s in manager.saved] == ["a"]
+
+ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(HuntrResumeConfig(next="a"))
+ # The first (cursorless) page must never be fetched on resume.
+ pages: dict[str | None, tuple[list[dict], str | None]] = {"a": ([{"id": "b"}], None)}
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": "b"}]
+
+ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {None: ([], None)})
+ assert rows == []
+ assert manager.saved == []
+
+ def test_empty_page_with_next_terminates(self, monkeypatch: Any) -> None:
+ # A lingering cursor on an empty page must not loop forever.
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {None: ([], "a")})
+ 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 {"data": []}
+ 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(HuntrRetryableError):
+ _fetch_page_unwrapped(session, "/members", None, 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, "/members", None, PAGE_SIZE, MagicMock())
+
+ def test_success_returns_items_and_next_cursor(self) -> None:
+ session = self._session_returning(200, {"data": [{"id": "a"}], "next": "a"})
+ items, next_cursor = _fetch_page_unwrapped(session, "/members", None, PAGE_SIZE, MagicMock())
+ assert items == [{"id": "a"}]
+ assert next_cursor == "a"
+
+ def test_missing_next_key_yields_none_cursor(self) -> None:
+ session = self._session_returning(200, {"data": [{"id": "a"}]})
+ items, next_cursor = _fetch_page_unwrapped(session, "/members", None, PAGE_SIZE, MagicMock())
+ assert items == [{"id": "a"}]
+ assert next_cursor is None
+
+ def test_null_next_yields_none_cursor(self) -> None:
+ session = self._session_returning(200, {"data": [{"id": "a"}], "next": None})
+ _, next_cursor = _fetch_page_unwrapped(session, "/members", None, PAGE_SIZE, MagicMock())
+ assert next_cursor is None
+
+ def test_non_dict_body_is_retryable(self) -> None:
+ session = self._session_returning(200, [{"id": "a"}])
+ with pytest.raises(HuntrRetryableError):
+ _fetch_page_unwrapped(session, "/members", None, PAGE_SIZE, MagicMock())
+
+ def test_non_list_data_field_is_retryable(self) -> None:
+ session = self._session_returning(200, {"data": {"id": "a"}})
+ with pytest.raises(HuntrRetryableError):
+ _fetch_page_unwrapped(session, "/members", None, PAGE_SIZE, MagicMock())
+
+ def test_first_request_omits_next_param(self) -> None:
+ session = self._session_returning(200, {"data": []})
+ _fetch_page_unwrapped(session, "/jobs", None, PAGE_SIZE, MagicMock())
+ _, kwargs = session.get.call_args
+ assert kwargs["params"] == {"limit": PAGE_SIZE}
+
+ def test_subsequent_request_passes_next_cursor(self) -> None:
+ session = self._session_returning(200, {"data": []})
+ _fetch_page_unwrapped(session, "/jobs", "cursor-123", PAGE_SIZE, MagicMock())
+ _, kwargs = session.get.call_args
+ assert kwargs["params"] == {"limit": PAGE_SIZE, "next": "cursor-123"}
+
+
+class TestCheckAccess:
+ def _patch_session(self, monkeypatch: Any, response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ monkeypatch.setattr(huntr, "make_tracked_session", lambda **kwargs: session)
+ return session
+
+ @pytest.mark.parametrize(
+ "status, ok, expected_status, expected_message",
+ [
+ (200, True, 200, None),
+ (401, False, 401, None),
+ (403, False, 403, None),
+ (500, False, 500, "Huntr returned HTTP 500"),
+ ],
+ )
+ def test_status_mapping(
+ self, status: int, ok: bool, expected_status: int, expected_message: str | None, monkeypatch: Any
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ self._patch_session(monkeypatch, response)
+ assert check_access("huntr-token") == (expected_status, expected_message)
+
+ def test_connection_error_maps_to_zero(self, monkeypatch: Any) -> None:
+ self._patch_session(monkeypatch, requests.ConnectionError("boom"))
+ status, message = check_access("huntr-token")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+ @pytest.mark.parametrize(
+ "status, expected_valid, expected_message",
+ [
+ (200, True, None),
+ (401, False, "Invalid Huntr access token"),
+ (403, False, "Invalid Huntr access token"),
+ (500, False, "Huntr returned HTTP 500"),
+ ],
+ )
+ def test_validate_credentials(
+ self, status: int, expected_valid: bool, expected_message: str | None, monkeypatch: Any
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ self._patch_session(monkeypatch, response)
+ assert validate_credentials("huntr-token") == (expected_valid, expected_message)
+
+
+class TestHuntrSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = huntr_source(
+ access_token="huntr-token",
+ 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 HUNTR_ENDPOINTS.values())
+ assert set(HUNTR_ENDPOINTS) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/tests/test_huntr_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/tests/test_huntr_source.py
new file mode 100644
index 000000000000..ec8b9b0d1536
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/huntr/tests/test_huntr_source.py
@@ -0,0 +1,143 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HuntrSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.huntr.huntr import HuntrResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.huntr.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.huntr.source import HuntrSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestHuntrSource:
+ def setup_method(self) -> None:
+ self.source = HuntrSource()
+ self.team_id = 123
+ self.config = HuntrSourceConfig(access_token="huntr-token")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.HUNTR
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Huntr"
+ assert config.label == "Huntr"
+ 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/huntr"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["access_token"]
+
+ def test_access_token_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "access_token")
+ 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 access token; the base URL is hardcoded, so there is no
+ # non-secret field an editor could retarget to reuse a preserved token 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=["jobs"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "jobs"
+
+ 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)
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.huntr.co/org/members?limit=100",
+ "403 Client Error: Forbidden for url: https://api.huntr.co/org/jobs?limit=100",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @pytest.mark.parametrize(
+ "unrelated_error",
+ [
+ "500 Server Error: Internal Server Error for url: https://api.huntr.co/org/members",
+ "429 Client Error: Too Many Requests for url: https://api.huntr.co/org/jobs",
+ ],
+ )
+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @pytest.mark.parametrize(
+ "status, expected_valid, expected_message",
+ [
+ (200, True, None),
+ (401, False, "Invalid Huntr access token"),
+ (403, False, "Invalid Huntr access token"),
+ (500, False, "Huntr returned HTTP 500"),
+ (0, False, "Could not connect to Huntr: boom"),
+ ],
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.huntr.huntr.check_access")
+ def test_validate_credentials(
+ self,
+ mock_check: mock.MagicMock,
+ status: int,
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ message = (
+ "Huntr returned HTTP 500"
+ if status == 500
+ else ("Could not connect to Huntr: 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 HuntrResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.huntr.source.huntr_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "jobs"
+ 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["access_token"] == "huntr-token"
+ assert kwargs["endpoint"] == "jobs"
+ 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 Huntr schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)