:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add Faire import source (#84362)
Tom Owers5e3ea9f7ac12
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/faire/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/faire/canonical_descriptions.pynew file mode 100644index 000000000000..43a9905fe11b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/faire/canonical_descriptions.py@@ -0,0 +1,65 @@+"""Canonical, documentation-sourced descriptions for Faire External API v2 endpoints and columns.++Keyed by the endpoint names in `settings.py` `FAIRE_ENDPOINTS`, which match the `ExternalDataSchema.name`+of a synced Faire table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Orders": {+ "description": "A wholesale order placed by a retailer against your Faire brand.",+ "docs_url": "https://developers.faire.com/docs",+ "columns": {+ "id": "Unique identifier for the order.",+ "display_id": "Human-readable order number shown in the Faire brand portal.",+ "created_at": "Time at which the order was created.",+ "updated_at": "Time at which the order was last updated.",+ "state": "Current fulfillment state of the order (e.g. NEW, PROCESSING, DELIVERED).",+ "retailer_id": "Identifier of the retailer that placed the order.",+ "source": "Where the order originated (e.g. the Faire marketplace).",+ "ship_after": "Earliest date the order is allowed to ship.",+ "expected_ship_date": "Date the brand expects to ship the order.",+ "requested_ship_date": "Ship date requested by the retailer.",+ "processing_at": "Time at which the order moved into the processing state.",+ "payment_initiated_at": "Time at which payment for the order was initiated.",+ "estimated_payout_at": "Estimated date the brand will be paid out for the order.",+ "original_order_id": "Identifier of the original order, if this order is a reorder or split.",+ "is_free_shipping": "Whether the order qualifies for free shipping.",+ "is_fulfilled_by_faire": "Whether Faire handles fulfillment for this order.",+ "purchase_order_number": "Retailer-provided purchase order number, if any.",+ "notes": "Free-text notes attached to the order.",+ },+ },+ "Products": {+ "description": "A product listed by your Faire brand, including its variants and merchandising details.",+ "docs_url": "https://developers.faire.com/docs",+ "columns": {+ "id": "Unique identifier for the product.",+ "brand_id": "Identifier of the brand the product belongs to.",+ "name": "The product's display name.",+ "description": "Full product description.",+ "short_description": "Short product description shown in listings.",+ "created_at": "Time at which the product was created.",+ "updated_at": "Time at which the product was last updated.",+ "sale_state": "Whether the product is for sale or sales are paused.",+ "lifecycle_state": "Publication state of the product (draft, published, unpublished, deleted).",+ "variants": "The product's purchasable variants, including SKU, price, and available quantity.",+ "unit_multiplier": "Number of units contained in a single sellable unit of the product.",+ "minimum_order_quantity": "Minimum quantity of the product a retailer must order.",+ "made_in_country": "Country the product is manufactured in.",+ },+ },+ "Brand": {+ "description": "Your Faire brand's profile.",+ "docs_url": "https://developers.faire.com/docs",+ "columns": {+ "brand_id": "Unique identifier for the brand.",+ "name": "The brand's display name.",+ "currency": "Currency the brand sells in.",+ "locale": "The brand's configured locale.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/faire/faire.py b/products/warehouse_sources/backend/temporal/data_imports/sources/faire/faire.pynew file mode 100644index 000000000000..0d2e5161ecc9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/faire/faire.py@@ -0,0 +1,211 @@+from typing import Any, Optional++from requests import Request, Response++from posthog.dataclasses import frozen++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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import Endpoint+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.faire.settings import (+ BASE_URL,+ FAIRE_ENDPOINTS,+ FaireEndpointConfig,+)+++@frozen+class FaireResumeConfig:+ """Immutable resume-cursor state passed between incremental sync runs."""++ cursor: str+++def incremental_param(field_name: str) -> dict[str, Any]:+ return {+ "type": "incremental",+ "cursor_path": field_name,+ "initial_value": None,+ }+++class FairePaginator(BasePaginator):+ """Faire pages the first request with `limit` (plus any static filters); once a response+ returns a `cursor`, every later request must carry only `cursor`/`limit` — Faire's docs say+ the cursor and the original filter params (`updated_at_min`, `sku`, `sort_by`, ...) can't be+ combined in the same request, so they're dropped as soon as a cursor shows up. Absence of a+ `cursor` in the response means there's no next page.+ """++ def __init__(self, limit: int, filter_params: tuple[str, ...]) -> None:+ super().__init__()+ self._limit = limit+ self._filter_params = filter_params+ self._cursor: Optional[str] = None++ def init_request(self, request: Request) -> None:+ if request.params is None:+ request.params = {}+ request.params["limit"] = self._limit+ if self._cursor is not None:+ self._apply_cursor(request)++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ try:+ body = response.json()+ except ValueError:+ body = None+ cursor = body.get("cursor") if isinstance(body, dict) else None+ if cursor:+ self._cursor = cursor+ self._has_next_page = True+ else:+ self._cursor = None+ self._has_next_page = False++ def update_request(self, request: Request) -> None:+ self._apply_cursor(request)++ def _apply_cursor(self, request: Request) -> None:+ if request.params is None:+ request.params = {}+ for key in self._filter_params:+ request.params.pop(key, None)+ request.params.pop("page", None)+ request.params["cursor"] = self._cursor+ request.params["limit"] = self._limit++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ return {"cursor": self._cursor} if self._has_next_page and self._cursor else None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ cursor = state.get("cursor")+ if cursor:+ self._cursor = str(cursor)+ self._has_next_page = True++ def __str__(self) -> str:+ return f"FairePaginator(limit={self._limit})"+++def _build_params(config: FaireEndpointConfig, should_use_incremental_field: bool) -> dict[str, Any]:+ params: dict[str, Any] = dict(config.static_params)+ if config.supports_incremental and should_use_incremental_field:+ params[config.incremental_param] = incremental_param("updated_at")+ return params+++def faire_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[FaireResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = FAIRE_ENDPOINTS[endpoint]++ endpoint_def: Endpoint+ if config.is_single_object:+ # `/brands/profile` returns a single object rather than a paginated list.+ endpoint_def = {+ "path": config.path,+ "data_selector": "$",+ "paginator": SinglePagePaginator(),+ }+ else:+ endpoint_def = {+ "path": config.path,+ "params": _build_params(config, should_use_incremental_field),+ "data_selector": config.response_key,+ "paginator": FairePaginator(limit=config.page_size, filter_params=config.filter_params),+ }++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": BASE_URL,+ "headers": {"Accept": "application/json"},+ "auth": {+ "type": "api_key",+ "api_key": api_key,+ "name": "X-FAIRE-ACCESS-TOKEN",+ "location": "header",+ },+ # The token rides in a custom header, not Authorization; don't let a redirect+ # replay it to a different host.+ "allow_redirects": False,+ },+ "resource_defaults": {+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ }+ if should_use_incremental_field+ else "replace",+ },+ "resources": [+ {+ "name": endpoint,+ "table_name": endpoint.lower(),+ "endpoint": endpoint_def,+ "table_format": "delta",+ }+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if not config.is_single_object and resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and resume.cursor:+ initial_paginator_state = {"cursor": resume.cursor}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's a next page to resume to; save AFTER a page is yielded so a+ # crash re-yields the last page (merge dedupes on the primary key) rather than skipping it.+ if state and state.get("cursor"):+ resumable_source_manager.save_state(FaireResumeConfig(cursor=str(state["cursor"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value if config.supports_incremental else None,+ resume_hook=None if config.is_single_object else save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=config.primary_keys,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ column_hints=resource.column_hints,+ )+++def validate_credentials(api_key: str) -> tuple[bool, int | None]:+ """Probe `/brands/profile` to confirm the access token is genuine.++ Returns ``(ok, status_code)``. ``status_code`` is ``None`` on a transport error.+ """+ return validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ f"{BASE_URL}/brands/profile",+ headers={"X-FAIRE-ACCESS-TOKEN": api_key, "Accept": "application/json"},+ # The token rides in a custom header, not Authorization — don't let a redirect replay it+ # to a different host.+ allow_redirects=False,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/faire/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/faire/settings.pynew file mode 100644index 000000000000..fb0b32f6852e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/faire/settings.py@@ -0,0 +1,89 @@+from dataclasses import field+from typing import Any, Optional++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++BASE_URL = "https://www.faire.com/external-api/v2"+++def _updated_at_incremental_fields() -> list[IncrementalField]:+ return [+ {+ "label": "updated_at",+ "type": IncrementalFieldType.DateTime,+ "field": "updated_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ]+++@frozen+class FaireEndpointConfig:+ name: str+ path: str+ # Root key of the list in the JSON response body. Ignored (and left blank) for a single-object+ # endpoint, where the whole body is the row.+ response_key: str = ""+ is_single_object: bool = False+ supports_incremental: bool = False+ # Query param the API filters on when incremental syncing is enabled.+ incremental_param: str = "updated_at_min"+ # Params always sent on the first (non-cursor) page, e.g. a sort order.+ static_params: dict[str, Any] = field(default_factory=dict)+ # Query params the API rejects once a page carries a `cursor` — the first page sets these to+ # pick the initial window (filters, sort), later pages continue purely by cursor.+ filter_params: tuple[str, ...] = ()+ page_size: int = 50+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation-time field to partition by. None for the single-row Brand endpoint.+ partition_key: Optional[str] = "created_at"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++FAIRE_ENDPOINTS: dict[str, FaireEndpointConfig] = {+ "Orders": FaireEndpointConfig(+ name="Orders",+ path="/orders",+ response_key="orders",+ supports_incremental=True,+ incremental_param="updated_at_min",+ # Faire's default order isn't documented explicitly; pin it so pagination is stable+ # regardless.+ static_params={"sort_by": "UPDATED_AT"},+ filter_params=(+ "updated_at_min",+ "created_at_min",+ "excluded_states",+ "ship_after_max",+ "sort_by",+ "original_order_id",+ ),+ page_size=50, # Faire caps the orders page size at 50.+ incremental_fields=_updated_at_incremental_fields(),+ ),+ "Products": FaireEndpointConfig(+ name="Products",+ path="/products",+ response_key="products",+ supports_incremental=True,+ incremental_param="updated_at_min",+ filter_params=("updated_at_min", "sku", "include_deleted"),+ page_size=250,+ incremental_fields=_updated_at_incremental_fields(),+ ),+ "Brand": FaireEndpointConfig(+ name="Brand",+ path="/brands/profile",+ is_single_object=True,+ primary_keys=["brand_id"],+ partition_key=None,+ ),+}++ENDPOINTS = tuple(FAIRE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in FAIRE_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/faire/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/faire/source.pyindex 2608d0092a61..4fdbe0f28ea5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/faire/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/faire/source.py@@ -1,19 +1,48 @@-from typing import cast+from typing import Optional, castfrom 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.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,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.faire.faire import (+ FaireResumeConfig,+ faire_source,+ validate_credentials as validate_faire_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.faire.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.faire import FaireSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class FaireSource(SimpleSource[FaireSourceConfig]):+class FaireSource(ResumableSource[FaireSourceConfig, FaireResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs++ # Faire migrated integration partners from External API v1 to v2; this source is built+ # against v2, the current generally-available version.+ supported_versions = ("v2",)+ default_version = "v2"+ api_docs_url = "https://developers.faire.com/docs"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.FAIRE@@ -23,8 +52,83 @@ class FaireSource(SimpleSource[FaireSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.FAIRE,category=DataWarehouseSourceCategory.E_COMMERCE,- label="Faire (Faire Wholesale, Inc.)",+ label="Faire",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="Enter your Faire API access token to sync your brand's orders and product "+ "catalog into the PostHog Data warehouse.\n\nGenerate a token from the developer or "+ "API access settings in your Faire Brand Portal.",iconPath="/static/services/faire.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/faire",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API 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.faire.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized": "Your Faire access token is invalid or has been "+ "revoked. Generate a new token in your Faire Brand Portal, then reconnect.",+ }++ def get_schemas(+ self,+ config: FaireSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: FaireSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ ok, status_code = validate_faire_credentials(config.api_key)+ if ok:+ return True, None+ if status_code == 401:+ return False, "Invalid Faire API access token"+ return False, "Could not connect to Faire with the provided API access token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FaireResumeConfig]:+ return ResumableSourceManager[FaireResumeConfig](inputs, FaireResumeConfig)++ def source_for_pipeline(+ self,+ config: FaireSourceConfig,+ resumable_source_manager: ResumableSourceManager[FaireResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return faire_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ 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/products/warehouse_sources/backend/temporal/data_imports/sources/faire/tests/test_faire.py b/products/warehouse_sources/backend/temporal/data_imports/sources/faire/tests/test_faire.pynew file mode 100644index 000000000000..3a667d2c77d6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/faire/tests/test_faire.py@@ -0,0 +1,346 @@+import json+from typing import Any++from unittest import mock++from parameterized import parameterized+from requests import PreparedRequest, Request, Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.faire.faire import (+ FairePaginator,+ FaireResumeConfig,+ faire_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.faire.settings import FAIRE_ENDPOINTS++# RESTClient builds its session via make_tracked_session in the rest_client module.+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+# validate_credentials builds its own tracked session in the faire module.+FAIRE_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.faire.faire.make_tracked_session"+)+++def _response(body: dict[str, Any]) -> Response:+ resp = Response()+ resp.status_code = 200+ resp._content = json.dumps(body).encode()+ return resp+++def _make_manager(resume_state: FaireResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and return a list that captures each request AT SEND TIME.++ ``request.params`` is a single dict mutated in place across pages, so inspecting it after the+ run shows only the final state — snapshot a copy when each request is prepared instead.+ """+ session.headers = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append({"url": request.url, "params": dict(request.params or {}), "auth": request.auth})+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any):+ return faire_source(+ api_key="token",+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ **kwargs,+ )+++def _rows(source_response: Any) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++class TestFairePaginator:+ def test_init_request_sets_limit(self) -> None:+ paginator = FairePaginator(limit=50, filter_params=("updated_at_min",))+ request = Request(params={"updated_at_min": "2026-01-01"})++ paginator.init_request(request)++ assert request.params == {"updated_at_min": "2026-01-01", "limit": 50}++ def test_init_request_applies_seeded_cursor(self) -> None:+ paginator = FairePaginator(limit=50, filter_params=("updated_at_min", "sort_by"))+ paginator.set_resume_state({"cursor": "resume-cursor"})+ request = Request(params={"updated_at_min": "2026-01-01", "sort_by": "UPDATED_AT"})++ paginator.init_request(request)++ assert request.params == {"cursor": "resume-cursor", "limit": 50}++ @parameterized.expand(+ [+ ("cursor_present", {"cursor": "next-page"}, True),+ ("cursor_absent", {"orders": []}, False),+ ("cursor_empty_string", {"cursor": ""}, False),+ ]+ )+ def test_update_state_reads_cursor(self, _name: str, body: dict[str, Any], expected_has_next: bool) -> None:+ paginator = FairePaginator(limit=50, filter_params=())++ paginator.update_state(_response(body))++ assert paginator.has_next_page is expected_has_next++ def test_update_request_drops_filter_params_and_sets_cursor(self) -> None:+ paginator = FairePaginator(limit=50, filter_params=("updated_at_min", "sku"))+ paginator.update_state(_response({"cursor": "abc"}))+ request = Request(params={"updated_at_min": "2026-01-01", "sku": "SKU1", "page": 1})++ paginator.update_request(request)++ assert request.params == {"cursor": "abc", "limit": 50}++ def test_resume_state_round_trips(self) -> None:+ paginator = FairePaginator(limit=50, filter_params=())+ paginator.update_state(_response({"cursor": "abc"}))++ state = paginator.get_resume_state()+ assert state == {"cursor": "abc"}++ resumed = FairePaginator(limit=50, filter_params=())+ resumed.set_resume_state(state or {})+ assert resumed.has_next_page is True++ def test_no_resume_state_once_exhausted(self) -> None:+ paginator = FairePaginator(limit=50, filter_params=())+ paginator.update_state(_response({"orders": []}))++ assert paginator.get_resume_state() is None+++class TestFaireSourceOrdersAndProducts:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_paginates_until_cursor_disappears(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(+ session,+ [+ _response({"orders": [{"id": "1"}, {"id": "2"}], "cursor": "page-2"}),+ _response({"orders": [{"id": "3"}]}),+ ],+ )++ rows = _rows(_source("Orders", _make_manager()))++ assert [r["id"] for r in rows] == ["1", "2", "3"]+ assert session.send.call_count == 2+ assert snapshots[0]["url"] == "https://www.faire.com/external-api/v2/orders"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_first_page_carries_sort_by_and_limit(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response({"orders": [{"id": "1"}]})])++ _rows(_source("Orders", _make_manager()))++ assert snapshots[0]["params"] == {"sort_by": "UPDATED_AT", "limit": 50}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_second_page_drops_filters_and_keeps_only_cursor(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(+ session,+ [+ _response({"orders": [{"id": "1"}], "cursor": "next"}),+ _response({"orders": [{"id": "2"}]}),+ ],+ )++ _rows(_source("Orders", _make_manager()))++ assert snapshots[1]["params"] == {"cursor": "next", "limit": 50}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_products_uses_its_own_page_size_and_filters(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response({"products": [{"id": "p1"}]})])++ rows = _rows(_source("Products", _make_manager()))++ assert [r["id"] for r in rows] == ["p1"]+ assert snapshots[0]["params"] == {"limit": 250}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_incremental_field_adds_updated_at_min(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response({"orders": [{"id": "1"}]})])++ _rows(+ _source(+ "Orders",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ )+ )++ assert snapshots[0]["params"]["updated_at_min"] == "2026-01-01T00:00:00Z"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_non_incremental_sync_omits_updated_at_min(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response({"orders": [{"id": "1"}]})])++ _rows(_source("Orders", _make_manager(), should_use_incremental_field=False))++ assert "updated_at_min" not in snapshots[0]["params"]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_sync_client_does_not_follow_redirects(self, MockSession) -> None:+ # The token rides in a custom header requests preserves across cross-origin redirects, so+ # the sync client must pin allow_redirects off. RESTClient forwards the client config's+ # value into every send().+ session = MockSession.return_value+ send_kwargs: list[dict[str, Any]] = []+ response_iter = iter([_response({"orders": [{"id": "1"}]})])++ def _prepare(request: Any) -> mock.MagicMock:+ return mock.MagicMock()++ def _send(request: Any, **kwargs: Any) -> Response:+ send_kwargs.append(kwargs)+ return next(response_iter)++ session.headers = {}+ session.prepare_request.side_effect = _prepare+ session.send.side_effect = _send++ _rows(_source("Orders", _make_manager()))++ assert send_kwargs and all(kw.get("allow_redirects") is False for kw in send_kwargs)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_auth_uses_faire_access_token_header(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response({"orders": [{"id": "1"}]})])++ _rows(_source("Orders", _make_manager()))++ auth = snapshots[0]["auth"]+ assert isinstance(auth, APIKeyAuth)+ assert auth.api_key == "token"+ assert auth.name == "X-FAIRE-ACCESS-TOKEN"+ assert auth.location == "header"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_saves_resume_state_only_while_pages_remain(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _response({"orders": [{"id": "1"}], "cursor": "page-2"}),+ _response({"orders": [{"id": "2"}]}),+ ],+ )++ manager = _make_manager()+ _rows(_source("Orders", manager))++ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0] == FaireResumeConfig(cursor="page-2")++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_cursor(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response({"orders": [{"id": "2"}]})])++ rows = _rows(_source("Orders", _make_manager(FaireResumeConfig(cursor="page-2"))))++ assert [r["id"] for r in rows] == ["2"]+ assert session.send.call_count == 1+ assert snapshots[0]["params"] == {"cursor": "page-2", "limit": 50}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_stops_on_empty_page_without_cursor(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response({"orders": []})])++ manager = _make_manager()+ rows = _rows(_source("Orders", manager))++ assert rows == []+ assert session.send.call_count == 1+ manager.save_state.assert_not_called()+++class TestFaireSourceBrand:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_returns_single_row_from_root_object(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response({"brand_id": "b1", "name": "Acme Co"})])++ rows = _rows(_source("Brand", _make_manager()))++ assert rows == [{"brand_id": "b1", "name": "Acme Co"}]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_never_saves_resume_state(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response({"brand_id": "b1"})])++ manager = _make_manager()+ _rows(_source("Brand", manager))++ manager.save_state.assert_not_called()++ def test_returned_source_response_uses_brand_id_primary_key(self) -> None:+ assert FAIRE_ENDPOINTS["Brand"].primary_keys == ["brand_id"]+ assert FAIRE_ENDPOINTS["Brand"].partition_key is None+++class TestValidateCredentials:+ @mock.patch(FAIRE_SESSION_PATCH)+ def test_ok(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ assert validate_credentials("token") == (True, 200)++ @mock.patch(FAIRE_SESSION_PATCH)+ def test_unauthorized(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=401)+ assert validate_credentials("token") == (False, 401)++ @mock.patch(FAIRE_SESSION_PATCH)+ def test_swallows_transport_errors(self, mock_session) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("token") == (False, None)++ @mock.patch(FAIRE_SESSION_PATCH)+ def test_probes_brand_profile_with_access_token_header(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ validate_credentials("token")++ call = mock_session.return_value.get.call_args+ assert call.args[0] == "https://www.faire.com/external-api/v2/brands/profile"+ assert call.kwargs["headers"]["X-FAIRE-ACCESS-TOKEN"] == "token"+ assert call.kwargs["allow_redirects"] is False+++def test_prepared_request_type_is_used_for_auth() -> None:+ # Sanity check that APIKeyAuth is callable against a PreparedRequest, matching how the+ # framework applies auth — guards against a signature mismatch going unnoticed.+ auth = APIKeyAuth(api_key="token", name="X-FAIRE-ACCESS-TOKEN", location="header")+ prepared = PreparedRequest()+ prepared.headers = {} # type: ignore[assignment] # ty: ignore[invalid-assignment]+ auth(prepared)+ assert prepared.headers["X-FAIRE-ACCESS-TOKEN"] == "token"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/faire/tests/test_faire_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/faire/tests/test_faire_source.pynew file mode 100644index 000000000000..b023e50b89af--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/faire/tests/test_faire_source.py@@ -0,0 +1,157 @@+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.faire.faire import FaireResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.faire.settings import ENDPOINTS, FAIRE_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.faire.source import FaireSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.faire import FaireSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++_INCREMENTAL_ENDPOINTS = {"Orders", "Products"}+_FULL_REFRESH_ENDPOINTS = {"Brand"}+++class TestFaireSource:+ def setup_method(self):+ self.source = FaireSource()+ self.team_id = 123+ self.config = FaireSourceConfig(api_key="token")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.FAIRE++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Faire"+ assert config.category is not None+ assert config.category.value == "E-commerce"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/faire.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/faire"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ def test_api_version(self):+ assert self.source.default_version == "v2"+ assert self.source.default_version in self.source.supported_versions+ assert self.source.api_docs_url is not None+ assert self.source.api_docs_url.startswith("https://")++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://www.faire.com/external-api/v2/orders?limit=50",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "429 Client Error: Too Many Requests for url: https://www.faire.com/external-api/v2/orders",+ "500 Server Error: Internal Server Error for url: https://www.faire.com/external-api/v2/orders",+ "HTTPSConnectionPool(host='www.faire.com', port=443): Read timed out.",+ ],+ )+ def test_non_retryable_errors_do_not_match_transient(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_match_endpoints_with_correct_sync_modes(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ for name in _INCREMENTAL_ENDPOINTS:+ assert schemas[name].supports_incremental is True+ assert schemas[name].supports_append is True+ assert [f["field"] for f in schemas[name].incremental_fields] == ["updated_at"]+ for name in _FULL_REFRESH_ENDPOINTS:+ assert schemas[name].supports_incremental is False+ assert schemas[name].supports_append is False+ assert schemas[name].incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Orders"])+ assert len(schemas) == 1+ assert schemas[0].name == "Orders"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_lists_tables_without_credentials_publishes_catalog(self):+ assert self.source.lists_tables_without_credentials is True+ documented = self.source.get_documented_tables()+ assert {table["name"] for table in documented} == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self):+ canonical = self.source.get_canonical_descriptions()+ assert set(canonical) == set(FAIRE_ENDPOINTS)++ @parameterized.expand(+ [+ ((True, 200), True, None),+ ((False, 401), False, "Invalid Faire API access token"),+ ((False, 403), False, "Could not connect to Faire with the provided API access token"),+ ((False, None), False, "Could not connect to Faire with the provided API access token"),+ ]+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.faire.source.validate_faire_credentials"+ )+ def test_validate_credentials(self, mock_return, expected_valid, expected_message, mock_validate):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("token")++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is FaireResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.faire.source.faire_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_faire_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "Orders"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_faire_source.assert_called_once()+ kwargs = mock_faire_source.call_args.kwargs+ assert kwargs["api_key"] == "token"+ assert kwargs["endpoint"] == "Orders"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.faire.source.faire_source")+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_faire_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "Brand"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_faire_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/faire.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/faire.pyindex b842af4d4afa..73a447ee3ef5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/faire.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/faire.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass FaireSourceConfig(config.Config):- pass+ api_key: str