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 front import source (#61599)

Tom Owersc04339ada20d
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 537d09c2eb5e..7adfad885824 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -73,6 +73,7 @@ the row lists both.
| freshdesk | HTTP | requests | ✅ |
| freshsales | HTTP | requests | ✅ |
| eventbrite | HTTP | requests | ✅ |
+| front | HTTP | requests | ✅ |
| github | HTTP | requests | ✅ |
| google_ads | gRPC | google-ads (googleads.client) | ✅ |
| google_sheets | HTTP (vendor SDK) | gspread | ✅ |
@@ -188,7 +189,6 @@ doesn't conflict with concurrent PRs.
- elasticsearch
- facebook_pages
- firebase
-- front
- fullstory
- gitlab
- gong
diff --git a/posthog/temporal/data_imports/sources/front/front.py b/posthog/temporal/data_imports/sources/front/front.py
new file mode 100644
index 000000000000..c308f6edd685
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/front/front.py
@@ -0,0 +1,224 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.front.settings import FRONT_ENDPOINTS, FrontEndpointConfig
+
+FRONT_BASE_URL = "https://api2.frontapp.com"
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 6
+MAX_RETRY_WAIT_SECONDS = 60
+
+
+class FrontRetryableError(Exception):
+ """Raised for retryable Front responses (429 rate limiting, 5xx)."""
+
+ def __init__(self, message: str, retry_after: Optional[float] = None):
+ super().__init__(message)
+ self.retry_after = retry_after
+
+
+class FrontResumeConfig:
+ next_url: str
+
+
+def _get_headers(api_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_token}",
+ "Accept": "application/json",
+ }
+
+
+def _to_unix_seconds(value: Any) -> Any:
+ """Coerce an incremental cursor value into Unix epoch seconds for Front's q[after] filter.
+
+ Front stores timestamps as Unix epoch seconds; the warehouse may hand the value back as a
+ datetime/date or as the raw numeric column, so normalize both into something urlencode can
+ serialize as a number.
+ """
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return dt.timestamp()
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp()
+ return value
+
+
+def _resolve_after_value(
+ config: FrontEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Any:
+ if not should_use_incremental_field:
+ return None
+ if db_incremental_field_last_value is not None:
+ return _to_unix_seconds(db_incremental_field_last_value)
+ if config.default_lookback_days is not None:
+ return (datetime.now(UTC) - timedelta(days=config.default_lookback_days)).timestamp()
+ return None
+
+
+def _build_initial_params(
+ config: FrontEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {}
+
+ if config.limit is not None:
+ params["limit"] = config.limit
+ if config.sort_by is not None:
+ params["sort_by"] = config.sort_by
+ if config.sort_order is not None:
+ params["sort_order"] = config.sort_order
+
+ if config.supports_incremental and config.incremental_query_property:
+ after_value = _resolve_after_value(config, should_use_incremental_field, db_incremental_field_last_value)
+ if after_value is not None:
+ params[f"q[{config.incremental_query_property}]"] = after_value
+
+ return params
+
+
+def _build_url(base_url: str, params: dict[str, Any]) -> str:
+ if not params:
+ return base_url
+ return f"{base_url}?{urlencode(params)}"
+
+
+def _parse_retry_after(value: Optional[str]) -> Optional[float]:
+ if not value:
+ return None
+ try:
+ return float(value)
+ except ValueError:
+ return None
+
+
+def _retry_wait(retry_state: RetryCallState) -> float:
+ """Honor Front's retry-after header on 429 when present; fall back to exponential backoff."""
+ exc = retry_state.outcome.exception() if retry_state.outcome else None
+ if isinstance(exc, FrontRetryableError) and exc.retry_after is not None:
+ return min(exc.retry_after, MAX_RETRY_WAIT_SECONDS)
+ return wait_exponential_jitter(initial=1, max=30)(retry_state)
+
+
+def validate_credentials(api_token: str, path: str, require_scope: bool) -> tuple[bool, str | None]:
+ """Probe a Front endpoint with the token.
+
+ 401 always fails (bad token). 403 means the token is valid but lacks scope for that endpoint:
+ we accept it at source-create (``require_scope=False``) and only reject it when validating a
+ specific schema (``require_scope=True``).
+ """
+ try:
+ response = make_tracked_session().get(f"{FRONT_BASE_URL}{path}", headers=_get_headers(api_token), timeout=10)
+ except Exception as e:
+ return False, f"Could not connect to Front: {e}"
+
+ if response.status_code == 401:
+ return False, "Invalid Front API token. Please reconnect with a valid token."
+ if response.status_code == 403 and require_scope:
+ return False, "Your Front API token does not have permission to access this resource."
+ return True, None
+
+
+def get_rows(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FrontResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = FRONT_ENDPOINTS[endpoint]
+ headers = _get_headers(api_token)
+
+ params = _build_initial_params(config, should_use_incremental_field, db_incremental_field_last_value)
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None:
+ url: str | None = resume_config.next_url
+ logger.debug(f"Front: resuming {endpoint} from URL: {url}")
+ else:
+ url = _build_url(f"{FRONT_BASE_URL}{config.path}", params)
+
+ @retry(
+ retry=retry_if_exception_type((FrontRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=_retry_wait,
+ reraise=True,
+ )
+ def fetch_page(page_url: str) -> dict[str, Any]:
+ response = make_tracked_session().get(page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429:
+ raise FrontRetryableError(
+ f"Front rate limited: url={page_url}",
+ retry_after=_parse_retry_after(response.headers.get("retry-after")),
+ )
+ if response.status_code >= 500:
+ raise FrontRetryableError(f"Front server error: status={response.status_code}, url={page_url}")
+ if not response.ok:
+ logger.error(f"Front API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ while url:
+ data = fetch_page(url)
+
+ results = data.get("_results") or []
+ # Never infer the end from an empty/short page — deleted resources can shrink a page
+ # while more pages remain. Only `_pagination.next == null` terminates the cursor.
+ next_url = (data.get("_pagination") or {}).get("next")
+
+ if results:
+ yield results
+
+ if not next_url:
+ break
+
+ # 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(FrontResumeConfig(next_url=next_url))
+ url = next_url
+
+
+def front_source(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FrontResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = FRONT_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_token,
+ 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_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format=config.partition_format if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ sort_mode="asc",
+ )
diff --git a/posthog/temporal/data_imports/sources/front/settings.py b/posthog/temporal/data_imports/sources/front/settings.py
new file mode 100644
index 000000000000..2587511a5d90
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/front/settings.py
@@ -0,0 +1,105 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import PartitionFormat
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class FrontEndpointConfig:
+ name: str
+ path: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable creation-time field to partition by (never a mutable field like updated_at).
+ # Front timestamps are Unix epoch seconds (e.g. 1453770984.123), partitioned as datetime.
+ partition_key: Optional[str] = None
+ partition_format: PartitionFormat = "month"
+ supports_incremental: bool = False
+ # Per-page size. ``None`` means don't send a ``limit`` param (endpoint takes no query params).
+ limit: Optional[int] = None
+ sort_by: Optional[str] = None
+ sort_order: Optional[str] = None # "asc" / "desc"
+ # ``q`` sub-property used as the server-side "after" time filter (e.g. "after" -> q[after]).
+ # Only set where Front documents a genuine server-side timestamp filter.
+ incremental_query_property: Optional[str] = None
+ # Bound the first incremental sync to the last N days (None = full history).
+ default_lookback_days: Optional[int] = None
+
+
+def _datetime_incremental_field(field_name: str) -> IncrementalField:
+ # Front timestamps are Unix epoch seconds, surfaced to users as a datetime cursor but
+ # stored/compared as a numeric column (mirrors how Stripe handles its `created` field).
+ return {
+ "label": field_name,
+ "type": IncrementalFieldType.DateTime,
+ "field": field_name,
+ "field_type": IncrementalFieldType.Integer,
+ }
+
+
+FRONT_ENDPOINTS: dict[str, FrontEndpointConfig] = {
+ # Events expose a genuine server-side time filter via q[after]/q[before] (Unix seconds) and
+ # are append-only, so this is the one incremental endpoint. Front caps the events page size
+ # at 15. The initial sync is bounded to the last 365 days to avoid an unbounded backfill.
+ "events": FrontEndpointConfig(
+ name="events",
+ path="/events",
+ partition_key="emitted_at",
+ partition_format="week",
+ supports_incremental=True,
+ limit=15,
+ sort_by="created_at",
+ sort_order="asc",
+ incremental_query_property="after",
+ default_lookback_days=365,
+ incremental_fields=[_datetime_incremental_field("emitted_at")],
+ ),
+ # Contacts have no created_at/updated_at in the response object (only sortable server-side),
+ # so we can't partition on a stable field. Full refresh.
+ "contacts": FrontEndpointConfig(
+ name="contacts",
+ path="/contacts",
+ limit=100,
+ sort_by="created_at",
+ sort_order="asc",
+ ),
+ # The list endpoint exposes no server-side time filter (only status filters), so full refresh.
+ "conversations": FrontEndpointConfig(
+ name="conversations",
+ path="/conversations",
+ partition_key="created_at",
+ limit=100,
+ sort_by="date",
+ sort_order="asc",
+ ),
+ "accounts": FrontEndpointConfig(
+ name="accounts",
+ path="/accounts",
+ partition_key="created_at",
+ limit=100,
+ sort_by="created_at",
+ sort_order="asc",
+ ),
+ "tags": FrontEndpointConfig(
+ name="tags",
+ path="/tags",
+ partition_key="created_at",
+ limit=100,
+ sort_by="id",
+ sort_order="asc",
+ ),
+ # The remaining endpoints take no query params and have no stable creation timestamp in the
+ # response, so they're plain full-refresh listings.
+ "teammates": FrontEndpointConfig(name="teammates", path="/teammates"),
+ "inboxes": FrontEndpointConfig(name="inboxes", path="/inboxes"),
+ "channels": FrontEndpointConfig(name="channels", path="/channels"),
+ "teams": FrontEndpointConfig(name="teams", path="/teams"),
+}
+
+ENDPOINTS = tuple(FRONT_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in FRONT_ENDPOINTS.items() if config.supports_incremental
+}
diff --git a/posthog/temporal/data_imports/sources/front/source.py b/posthog/temporal/data_imports/sources/front/source.py
index 07e1a894d388..432f01203fe5 100644
--- a/posthog/temporal/data_imports/sources/front/source.py
+++ b/posthog/temporal/data_imports/sources/front/source.py
@@ -1,19 +1,31 @@
-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.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.front.front import (
+ FrontResumeConfig,
+ front_source,
+ validate_credentials as validate_front_credentials,
+)
+from posthog.temporal.data_imports.sources.front.settings import ENDPOINTS, FRONT_ENDPOINTS, INCREMENTAL_FIELDS
from posthog.temporal.data_imports.sources.generated_configs import FrontSourceConfig
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class FrontSource(SimpleSource[FrontSourceConfig]):
+class FrontSource(ResumableSource[FrontSourceConfig, FrontResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.FRONT
@@ -23,7 +35,87 @@ class FrontSource(SimpleSource[FrontSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.FRONT,
label="Front",
- iconPath="/static/services/front.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Front API token to sync your Front data into the PostHog Data warehouse.
+
+You can create an API token in your [Front settings](https://app.frontapp.com/settings/tools/api) under **Developers > API tokens**.
+
+Grant read scopes for the resources you want to sync (e.g. `shared_resources:read`, `contacts:read`, `tags:read`).""",
+ iconPath="/static/services/front.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/front",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Invalid Front API token. Please reconnect with a valid token.",
+ "403 Client Error": "Your Front API token does not have the required scope for this resource.",
+ }
+
+ def get_schemas(
+ self,
+ config: FrontSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=FRONT_ENDPOINTS[endpoint].supports_incremental,
+ supports_append=FRONT_ENDPOINTS[endpoint].supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ description="Only syncs the last 365 days on initial sync" if endpoint == "events" else None,
+ )
+ 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: FrontSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if schema_name is None:
+ # Source-create probe: any non-401 response means the token is genuine. Accept 403 here
+ # so a scope-limited token still connects (the user grants scopes per resource).
+ return validate_front_credentials(config.api_token, "/teammates", require_scope=False)
+
+ endpoint_config = FRONT_ENDPOINTS.get(schema_name)
+ path = endpoint_config.path if endpoint_config else "/teammates"
+ return validate_front_credentials(config.api_token, path, require_scope=True)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FrontResumeConfig]:
+ return ResumableSourceManager[FrontResumeConfig](inputs, FrontResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: FrontSourceConfig,
+ resumable_source_manager: ResumableSourceManager[FrontResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return front_source(
+ api_token=config.api_token,
+ 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/front/tests/test_front.py b/posthog/temporal/data_imports/sources/front/tests/test_front.py
new file mode 100644
index 000000000000..9808d997e8be
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/front/tests/test_front.py
@@ -0,0 +1,282 @@
+import json
+from collections.abc import Iterator
+from contextlib import contextmanager
+from datetime import UTC, datetime
+from types import SimpleNamespace
+from typing import Any, Optional
+
+from unittest.mock import MagicMock, patch
+
+import structlog
+from parameterized import parameterized
+from requests import Response
+
+from posthog.temporal.data_imports.sources.front import front as front_module
+from posthog.temporal.data_imports.sources.front.front import (
+ FrontResumeConfig,
+ FrontRetryableError,
+ _build_initial_params,
+ _build_url,
+ _parse_retry_after,
+ _resolve_after_value,
+ _retry_wait,
+ _to_unix_seconds,
+ front_source,
+ get_rows,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.front.settings import FRONT_ENDPOINTS
+
+logger = structlog.get_logger()
+
+
+def _response(
+ status_code: int = 200,
+ json_body: Optional[dict[str, Any]] = None,
+ headers: Optional[dict[str, str]] = None,
+) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp.headers["Content-Type"] = "application/json"
+ if headers:
+ resp.headers.update(headers)
+ resp._content = json.dumps(json_body or {}).encode()
+ return resp
+
+
+class _FakeSession:
+ def __init__(self, responses: list[Response]):
+ self._responses = list(responses)
+ self.requested_urls: list[str] = []
+
+ def get(self, url: str, **kwargs: Any) -> Response:
+ self.requested_urls.append(url)
+ return self._responses.pop(0)
+
+
+@contextmanager
+def _patched_session(session: Any) -> Iterator[None]:
+ with patch.object(front_module, "make_tracked_session", return_value=session):
+ yield
+
+
+class TestBuildUrl:
+ def test_no_params_returns_base(self) -> None:
+ assert _build_url("https://api2.frontapp.com/tags", {}) == "https://api2.frontapp.com/tags"
+
+ def test_encodes_params(self) -> None:
+ url = _build_url("https://api2.frontapp.com/events", {"limit": 15, "sort_order": "asc"})
+ assert url.startswith("https://api2.frontapp.com/events?")
+ assert "limit=15" in url
+ assert "sort_order=asc" in url
+
+ def test_encodes_bracketed_query_filter(self) -> None:
+ url = _build_url("https://api2.frontapp.com/events", {"q[after]": 1700000000})
+ # urlencode percent-encodes brackets; Front decodes them server-side.
+ assert "q%5Bafter%5D=1700000000" in url
+
+
+class TestToUnixSeconds:
+ def test_aware_datetime(self) -> None:
+ dt = datetime(2023, 1, 1, tzinfo=UTC)
+ assert _to_unix_seconds(dt) == dt.timestamp()
+
+ def test_naive_datetime_assumed_utc(self) -> None:
+ assert _to_unix_seconds(datetime(2023, 1, 1)) == datetime(2023, 1, 1, tzinfo=UTC).timestamp()
+
+ @parameterized.expand([("int", 1700000000), ("float", 1700000000.123)])
+ def test_numeric_passthrough(self, _name: str, value: Any) -> None:
+ assert _to_unix_seconds(value) == value
+
+
+class TestResolveAfterValue:
+ def test_not_incremental_returns_none(self) -> None:
+ assert _resolve_after_value(FRONT_ENDPOINTS["events"], False, 1700000000) is None
+
+ def test_last_value_used(self) -> None:
+ assert _resolve_after_value(FRONT_ENDPOINTS["events"], True, 1700000000) == 1700000000
+
+ def test_lookback_used_when_no_last_value(self) -> None:
+ result = _resolve_after_value(FRONT_ENDPOINTS["events"], True, None)
+ # events has a 365-day lookback, so a float timestamp in the past is returned
+ assert isinstance(result, float)
+ assert result < datetime.now(UTC).timestamp()
+
+ def test_no_lookback_no_last_value_returns_none(self) -> None:
+ # A config without a lookback (and not incremental) yields no "after" value
+ assert _resolve_after_value(FRONT_ENDPOINTS["contacts"], True, None) is None
+
+
+class TestBuildInitialParams:
+ def test_events_incremental_sets_q_after(self) -> None:
+ params = _build_initial_params(FRONT_ENDPOINTS["events"], True, 1700000000)
+ assert params["q[after]"] == 1700000000
+ assert params["limit"] == 15
+ assert params["sort_by"] == "created_at"
+ assert params["sort_order"] == "asc"
+
+ def test_events_non_incremental_omits_q_after(self) -> None:
+ params = _build_initial_params(FRONT_ENDPOINTS["events"], False, None)
+ assert "q[after]" not in params
+
+ def test_tags_full_refresh_params(self) -> None:
+ params = _build_initial_params(FRONT_ENDPOINTS["tags"], False, None)
+ assert params == {"limit": 100, "sort_by": "id", "sort_order": "asc"}
+
+ def test_teammates_sends_no_params(self) -> None:
+ # teammates takes no documented query params
+ assert _build_initial_params(FRONT_ENDPOINTS["teammates"], False, None) == {}
+
+
+class TestParseRetryAfter:
+ @parameterized.expand([("seconds", "5", 5.0), ("none", None, None), ("non_numeric", "abc", None)])
+ def test_parse(self, _name: str, value: Optional[str], expected: Optional[float]) -> None:
+ assert _parse_retry_after(value) == expected
+
+
+class TestRetryWait:
+ def test_honors_retry_after(self) -> None:
+ state = SimpleNamespace(outcome=SimpleNamespace(exception=lambda: FrontRetryableError("x", retry_after=10)))
+ assert _retry_wait(state) == 10.0 # type: ignore[arg-type]
+
+ def test_caps_retry_after(self) -> None:
+ state = SimpleNamespace(outcome=SimpleNamespace(exception=lambda: FrontRetryableError("x", retry_after=120)))
+ assert _retry_wait(state) == 60.0 # type: ignore[arg-type]
+
+ def test_falls_back_to_backoff(self) -> None:
+ state = SimpleNamespace(
+ attempt_number=1,
+ outcome=SimpleNamespace(exception=lambda: FrontRetryableError("x")),
+ )
+ assert _retry_wait(state) >= 0 # type: ignore[arg-type]
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("unauthorized", 401, True, False),
+ ("forbidden_with_scope", 403, True, False),
+ ("forbidden_without_scope", 403, False, True),
+ ("ok", 200, True, True),
+ ("not_found_token_valid", 404, False, True),
+ ]
+ )
+ def test_status_mapping(self, _name: str, status: int, require_scope: bool, expected_ok: bool) -> None:
+ with _patched_session(_FakeSession([_response(status_code=status)])):
+ ok, _msg = validate_credentials("tok", "/teammates", require_scope=require_scope)
+ assert ok is expected_ok
+
+ def test_connection_error_fails(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = Exception("boom")
+ with _patched_session(session):
+ ok, msg = validate_credentials("tok", "/teammates", require_scope=False)
+ assert ok is False
+ assert msg is not None
+
+
+class TestGetRows:
+ def _manager(self, resume: Optional[FrontResumeConfig] = None) -> MagicMock:
+ manager = MagicMock()
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+ def test_paginates_and_saves_state(self) -> None:
+ session = _FakeSession(
+ [
+ _response(
+ json_body={
+ "_results": [{"id": "evt_1"}],
+ "_pagination": {"next": "https://api2.frontapp.com/events?page_token=p2"},
+ }
+ ),
+ _response(json_body={"_results": [{"id": "evt_2"}], "_pagination": {"next": None}}),
+ ]
+ )
+ manager = self._manager()
+
+ with _patched_session(session):
+ batches = list(get_rows("tok", "events", logger, manager))
+
+ assert batches == [[{"id": "evt_1"}], [{"id": "evt_2"}]]
+ manager.save_state.assert_called_once_with(
+ FrontResumeConfig(next_url="https://api2.frontapp.com/events?page_token=p2")
+ )
+ assert session.requested_urls[1] == "https://api2.frontapp.com/events?page_token=p2"
+
+ def test_resumes_from_saved_state(self) -> None:
+ resume_url = "https://api2.frontapp.com/events?page_token=resume"
+ session = _FakeSession([_response(json_body={"_results": [{"id": "evt_9"}], "_pagination": {"next": None}})])
+ manager = self._manager(resume=FrontResumeConfig(next_url=resume_url))
+
+ with _patched_session(session):
+ batches = list(get_rows("tok", "events", logger, manager))
+
+ assert batches == [[{"id": "evt_9"}]]
+ assert session.requested_urls[0] == resume_url
+
+ def test_empty_page_does_not_terminate(self) -> None:
+ # An empty `_results` page with a next link must keep paginating (deleted resources can
+ # leave a page short without it being the last page).
+ session = _FakeSession(
+ [
+ _response(
+ json_body={
+ "_results": [],
+ "_pagination": {"next": "https://api2.frontapp.com/tags?page_token=p2"},
+ }
+ ),
+ _response(json_body={"_results": [{"id": "tag_1"}], "_pagination": {"next": None}}),
+ ]
+ )
+ manager = self._manager()
+
+ with _patched_session(session):
+ batches = list(get_rows("tok", "tags", logger, manager))
+
+ assert batches == [[{"id": "tag_1"}]]
+ assert len(session.requested_urls) == 2
+
+ def test_retries_on_429(self) -> None:
+ session = _FakeSession(
+ [
+ _response(status_code=429, headers={"retry-after": "0"}),
+ _response(json_body={"_results": [{"id": "tag_1"}], "_pagination": {"next": None}}),
+ ]
+ )
+ manager = self._manager()
+
+ with _patched_session(session):
+ batches = list(get_rows("tok", "tags", logger, manager))
+
+ assert batches == [[{"id": "tag_1"}]]
+ assert len(session.requested_urls) == 2
+
+
+class TestFrontSourceResponse:
+ @parameterized.expand(
+ [
+ ("events", "emitted_at", "week", "asc"),
+ ("conversations", "created_at", "month", "asc"),
+ ("accounts", "created_at", "month", "asc"),
+ ("tags", "created_at", "month", "asc"),
+ ]
+ )
+ def test_partitioned_endpoints(
+ self, endpoint: str, partition_key: str, partition_format: str, sort_mode: str
+ ) -> None:
+ response = front_source("tok", endpoint, logger, MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
+ assert response.partition_format == partition_format
+ assert response.sort_mode == sort_mode
+
+ @parameterized.expand([("contacts",), ("teammates",), ("inboxes",), ("channels",), ("teams",)])
+ def test_non_partitioned_endpoints(self, endpoint: str) -> None:
+ response = front_source("tok", endpoint, logger, MagicMock())
+ assert response.primary_keys == ["id"]
+ assert response.partition_mode is None
+ assert response.partition_keys is None
diff --git a/posthog/temporal/data_imports/sources/front/tests/test_front_source.py b/posthog/temporal/data_imports/sources/front/tests/test_front_source.py
new file mode 100644
index 000000000000..e1beacc5163a
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/front/tests/test_front_source.py
@@ -0,0 +1,143 @@
+from typing import Any, Optional
+
+from unittest.mock import MagicMock, patch
+
+import structlog
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.front import source as source_module
+from posthog.temporal.data_imports.sources.front.front import FrontResumeConfig
+from posthog.temporal.data_imports.sources.front.source import FrontSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+logger = structlog.get_logger()
+
+
+def _config(api_token: str = "tok") -> Any:
+ return FrontSource().parse_config({"api_token": api_token})
+
+
+def _inputs(schema_name: str = "events", **overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": schema_name,
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 1,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-1",
+ "logger": logger,
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestFrontSource:
+ def test_source_type(self) -> None:
+ assert FrontSource().source_type == ExternalDataSourceType.FRONT
+
+ def test_source_config(self) -> None:
+ config = FrontSource().get_source_config
+ assert config.label == "Front"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # Shipped behind unreleasedSource while the source is still alpha
+ assert config.unreleasedSource is True
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["api_token"]
+ api_token_field = config.fields[0]
+ assert isinstance(api_token_field, SourceFieldInputConfig)
+ assert api_token_field.type == "password"
+ assert api_token_field.required is True
+
+ def test_get_schemas_lists_all_endpoints(self) -> None:
+ schemas = FrontSource().get_schemas(_config(), team_id=1)
+ names = {s.name for s in schemas}
+ assert {
+ "events",
+ "contacts",
+ "conversations",
+ "accounts",
+ "tags",
+ "teammates",
+ "inboxes",
+ "channels",
+ "teams",
+ } == names
+
+ def test_only_events_supports_incremental(self) -> None:
+ schemas = {s.name: s for s in FrontSource().get_schemas(_config(), team_id=1)}
+ assert schemas["events"].supports_incremental is True
+ assert schemas["events"].incremental_fields[0]["field"] == "emitted_at"
+ for name in ("contacts", "conversations", "accounts", "tags", "teammates"):
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].incremental_fields == []
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = FrontSource().get_schemas(_config(), team_id=1, names=["tags"])
+ assert [s.name for s in schemas] == ["tags"]
+
+ def test_non_retryable_errors(self) -> None:
+ errors = FrontSource().get_non_retryable_errors()
+ assert "401 Client Error" in errors
+ assert "403 Client Error" in errors
+
+ @parameterized.expand(
+ [
+ # (status_at_create, expected_ok) — source-create probe accepts everything but 401
+ ("valid", True, None),
+ ("invalid", False, "Invalid Front API token. Please reconnect with a valid token."),
+ ]
+ )
+ def test_validate_credentials_at_source_create(self, _name: str, ok: bool, msg: Optional[str]) -> None:
+ with patch.object(source_module, "validate_front_credentials", return_value=(ok, msg)) as mock_validate:
+ result = FrontSource().validate_credentials(_config(), team_id=1, schema_name=None)
+ assert result == (ok, msg)
+ # source-create probes /teammates with require_scope=False
+ mock_validate.assert_called_once_with("tok", "/teammates", require_scope=False)
+
+ def test_validate_credentials_for_schema_requires_scope(self) -> None:
+ with patch.object(source_module, "validate_front_credentials", return_value=(True, None)) as mock_validate:
+ FrontSource().validate_credentials(_config(), team_id=1, schema_name="tags")
+ mock_validate.assert_called_once_with("tok", "/tags", require_scope=True)
+
+ def test_resumable_manager_bound_to_resume_config(self) -> None:
+ manager = FrontSource().get_resumable_source_manager(_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is FrontResumeConfig
+
+ def test_source_for_pipeline_passes_arguments(self) -> None:
+ manager = MagicMock()
+ inputs = _inputs(
+ schema_name="events",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1700000000,
+ incremental_field="emitted_at",
+ )
+ sentinel = MagicMock()
+ with patch.object(source_module, "front_source", return_value=sentinel) as mock_source:
+ result = FrontSource().source_for_pipeline(_config(), manager, inputs)
+
+ assert result is sentinel
+ _args, kwargs = mock_source.call_args
+ assert kwargs["api_token"] == "tok"
+ assert kwargs["endpoint"] == "events"
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1700000000
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_source_for_pipeline_drops_last_value_when_not_incremental(self) -> None:
+ manager = MagicMock()
+ inputs = _inputs(should_use_incremental_field=False, db_incremental_field_last_value=1700000000)
+ with patch.object(source_module, "front_source", return_value="response") as mock_source:
+ FrontSource().source_for_pipeline(_config(), manager, inputs)
+ _args, kwargs = mock_source.call_args
+ assert 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 326ccc701cde..8fc22b09d9d8 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -378,7 +378,7 @@ class FreshsalesSourceConfig(config.Config):
@config.config
class FrontSourceConfig(config.Config):
- pass
+ api_token: str
@config.config