: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): implement webflow import source (#61145)
Tom Owers782a9050bc5c
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex aab033369e34..e27fe03356b5 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -110,6 +110,7 @@ the row lists both.| tiktok_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || typeform | HTTP | requests + `rest_source.RESTClient` | ✅ || vitally | HTTP | requests + `rest_source.RESTClient` | ✅ |+| webflow | HTTP | requests | ✅ || woocommerce | HTTP | requests + `rest_source.RESTClient` | ✅ || workos | HTTP | requests + `rest_source.RESTClient` | ✅ || zendesk | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -216,7 +217,6 @@ doesn't conflict with concurrent PRs.- trello- twilio- twitter_ads-- webflow- workday- wrike- xerodiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 29cc1b9cf6e4..bc91668337bc 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -879,7 +879,8 @@ class VitallySourceConfig(config.Config):@config.configclass WebflowSourceConfig(config.Config):- pass+ api_token: str+ site_id: str@config.configdiff --git a/posthog/temporal/data_imports/sources/webflow/settings.py b/posthog/temporal/data_imports/sources/webflow/settings.pynew file mode 100644index 000000000000..28421ff61b09--- /dev/null+++ b/posthog/temporal/data_imports/sources/webflow/settings.py@@ -0,0 +1,121 @@+from dataclasses import dataclass+from typing import Optional++# Webflow Data API v2. The legacy v1 API was deprecated on 2025-03-31, so this+# source only ever talks to v2 (Bearer token + scopes).+WEBFLOW_BASE_URL = "https://api.webflow.com/v2"++# Max page size accepted by every paginated v2 list endpoint.+DEFAULT_PAGE_SIZE = 100++# Dynamically discovered CMS collections are exposed as one schema per collection,+# named "{prefix}{collection_slug}". The prefix lets source_for_pipeline tell a+# collection-items schema apart from a static endpoint and resolve it back to a+# collection id at sync time.+COLLECTION_SCHEMA_PREFIX = "collection_"++# Path template for a single collection's items (staged/draft items).+COLLECTION_ITEMS_PATH = "/collections/{collection_id}/items"+++@dataclass+class WebflowEndpointConfig:+ name: str+ # Path appended to WEBFLOW_BASE_URL. May contain a "{site_id}" placeholder.+ path: str+ # Top-level key in the JSON envelope that holds the list of records. The+ # transport falls back to auto-detecting the first list-valued key when this+ # key is absent, so a wrong guess degrades gracefully rather than dropping rows.+ data_key: str+ primary_key: str = "id"+ # Stable, immutable datetime field used for partitioning. Never use a+ # "last updated"/"last seen" field here — partitions would rewrite every sync.+ partition_key: Optional[str] = None+ paginated: bool = True+ requires_site: bool = True+ # When set, the endpoint returns a single resource object (not a list envelope),+ # so the transport wraps it into a one-row page instead of looking for a list.+ single_object: bool = False+ # When set, the named nested object is merged up into the row root. Webflow's+ # products endpoint nests the product under a "product" key alongside "skus".+ flatten_key: Optional[str] = None+ # Explicit sort to keep offset pagination stable across a sync. Only set where+ # the endpoint is confirmed to accept it.+ sort_by: Optional[str] = None+ sort_order: str = "asc"+++# Static, site-scoped endpoints. The CMS collection-items endpoints are added+# dynamically per site (see WebflowSource.get_schemas), because every site has a+# different set of collections.+WEBFLOW_ENDPOINTS: dict[str, WebflowEndpointConfig] = {+ # Site-scoped to the configured site_id. The account-wide /sites endpoint would+ # leak metadata for every other site a broadly scoped token can reach, so we hit+ # /sites/{site_id} (a single site object) instead.+ "sites": WebflowEndpointConfig(+ name="sites",+ path="/sites/{site_id}",+ data_key="sites",+ partition_key="createdOn",+ paginated=False,+ single_object=True,+ ),+ "collections": WebflowEndpointConfig(+ name="collections",+ path="/sites/{site_id}/collections",+ data_key="collections",+ partition_key="createdOn",+ paginated=False,+ ),+ "pages": WebflowEndpointConfig(+ name="pages",+ path="/sites/{site_id}/pages",+ data_key="pages",+ partition_key="createdOn",+ ),+ "products": WebflowEndpointConfig(+ name="products",+ path="/sites/{site_id}/products",+ data_key="items",+ partition_key="createdOn",+ flatten_key="product",+ ),+ "orders": WebflowEndpointConfig(+ name="orders",+ path="/sites/{site_id}/orders",+ data_key="orders",+ primary_key="orderId",+ partition_key="acceptedOn",+ ),+ "users": WebflowEndpointConfig(+ name="users",+ path="/sites/{site_id}/users",+ data_key="users",+ partition_key="createdOn",+ ),+ "forms": WebflowEndpointConfig(+ name="forms",+ path="/sites/{site_id}/forms",+ data_key="forms",+ ),+}++STATIC_ENDPOINTS = tuple(WEBFLOW_ENDPOINTS.keys())+++def collection_items_endpoint_config(collection_id: str) -> WebflowEndpointConfig:+ """Build the endpoint config for a single CMS collection's items.++ Items are sorted by createdOn ascending so offset pagination stays stable —+ createdOn is immutable, so new items append to the end and don't shift pages+ that were already fetched mid-sync.+ """+ return WebflowEndpointConfig(+ name=f"{COLLECTION_SCHEMA_PREFIX}{collection_id}",+ path=COLLECTION_ITEMS_PATH.format(collection_id=collection_id),+ data_key="items",+ partition_key="createdOn",+ requires_site=False,+ sort_by="createdOn",+ sort_order="asc",+ )diff --git a/posthog/temporal/data_imports/sources/webflow/source.py b/posthog/temporal/data_imports/sources/webflow/source.pyindex fc45b6867013..1387fdb3fb86 100644--- a/posthog/temporal/data_imports/sources/webflow/source.py+++ b/posthog/temporal/data_imports/sources/webflow/source.py@@ -1,29 +1,152 @@-from typing import cast+from typing import Optional, cast++import structlogfrom 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, ResumableSourcefrom 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 SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import WebflowSourceConfig+from posthog.temporal.data_imports.sources.webflow.settings import COLLECTION_SCHEMA_PREFIX, STATIC_ENDPOINTS+from posthog.temporal.data_imports.sources.webflow.webflow import (+ WebflowResumeConfig,+ list_collections,+ validate_credentials as validate_webflow_credentials,+ webflow_source,+)from products.data_warehouse.backend.types import ExternalDataSourceType+logger = structlog.get_logger(__name__)+@SourceRegistry.register-class WebflowSource(SimpleSource[WebflowSourceConfig]):+class WebflowSource(ResumableSource[WebflowSourceConfig, WebflowResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.WEBFLOW+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your Webflow API token is invalid or expired. Please generate a new token and reconnect.",+ "403 Client Error": "Your Webflow API token is missing a required scope. Grant the read scopes for the resources you want to sync and reconnect.",+ }++ def get_schemas(+ self,+ config: WebflowSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Webflow has no verified server-side timestamp range filter on its list+ # endpoints (the createdOn/lastUpdated query params are exact-match, not+ # ranges), so every endpoint is full-refresh only for now.+ schemas = [+ SourceSchema(name=endpoint, supports_incremental=False, supports_append=False, incremental_fields=[])+ for endpoint in STATIC_ENDPOINTS+ ]++ # Each site exposes a different set of CMS collections, so discover them+ # dynamically and expose one schema per collection. Best-effort: if the+ # token can't list collections (missing scope, transient error) we still+ # return the static endpoints rather than failing the whole source.+ try:+ for collection in list_collections(config.api_token, config.site_id):+ slug = collection.get("slug")+ if not slug:+ continue+ schemas.append(+ SourceSchema(+ name=f"{COLLECTION_SCHEMA_PREFIX}{slug}",+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ label=collection.get("displayName"),+ )+ )+ except Exception as e:+ # Best-effort: a missing scope, transient network error, or schema-discovery+ # bug shouldn't fail the whole source. Log so the cause is debuggable.+ logger.debug("Webflow: failed to discover CMS collections, returning static endpoints only", exc_info=e)++ 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: WebflowSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_webflow_credentials(config.api_token, config.site_id, schema_name)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[WebflowResumeConfig]:+ return ResumableSourceManager[WebflowResumeConfig](inputs, WebflowResumeConfig)++ def source_for_pipeline(+ self,+ config: WebflowSourceConfig,+ resumable_source_manager: ResumableSourceManager[WebflowResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return webflow_source(+ api_token=config.api_token,+ site_id=config.site_id,+ schema_name=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.WEBFLOW,label="Webflow",+ caption="""Enter your Webflow v2 API token and Site ID to pull your Webflow site data into the PostHog Data warehouse.++Create a **Site API token** in Webflow under **Site settings → Apps & integrations → API access**, and copy the **Site ID** from the same page (or from your site's URL in the Designer).++Grant the read scopes for the resources you want to sync:+- `sites:read`+- `cms:read` (collections and collection items)+- `ecommerce:read` (products and orders)+- `pages:read`+- `users:read`+- `forms:read`+""",iconPath="/static/services/webflow.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/webflow",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="site_id",+ label="Site ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ ],+ ),)diff --git a/posthog/temporal/data_imports/sources/webflow/tests/test_webflow.py b/posthog/temporal/data_imports/sources/webflow/tests/test_webflow.pynew file mode 100644index 000000000000..6cf18977348b--- /dev/null+++ b/posthog/temporal/data_imports/sources/webflow/tests/test_webflow.py@@ -0,0 +1,272 @@+import json+from collections.abc import Iterable+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized+from requests import Response++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.webflow.settings import WEBFLOW_ENDPOINTS, collection_items_endpoint_config+from posthog.temporal.data_imports.sources.webflow.webflow import (+ WebflowResumeConfig,+ _build_url,+ _extract_items,+ _normalize,+ _resolve_collection_id,+ get_rows,+ validate_credentials,+ webflow_source,+)++TRANSPORT = "posthog.temporal.data_imports.sources.webflow.webflow.make_tracked_session"+++def _make_response(body: Any, status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ return resp+++class TestExtractItems:+ @parameterized.expand(+ [+ ("configured_key", {"items": [{"id": 1}]}, "items", [{"id": 1}]),+ ("named_envelope", {"sites": [{"id": 1}]}, "sites", [{"id": 1}]),+ ("bare_list", [{"id": 1}], "items", [{"id": 1}]),+ ("missing_key_fallback", {"weird": [{"id": 7}], "pagination": {}}, "items", [{"id": 7}]),+ ("pagination_skipped", {"pagination": [1, 2], "orders": [{"id": 9}]}, "orders", [{"id": 9}]),+ ("nothing", {"pagination": {}}, "items", []),+ ("not_a_dict", 5, "items", []),+ ]+ )+ def test_extract_items(self, _name: str, data: Any, data_key: str, expected: list[dict[str, Any]]) -> None:+ assert _extract_items(data, data_key) == expected+++class TestNormalize:+ def test_flattens_nested_product(self) -> None:+ config = WEBFLOW_ENDPOINTS["products"]+ item = {+ "product": {"id": "p1", "createdOn": "2026-01-01", "fieldData": {"name": "Shoe"}},+ "skus": [{"id": "s1"}],+ }+ normalized = _normalize(item, config)+ assert normalized["id"] == "p1"+ assert normalized["createdOn"] == "2026-01-01"+ assert normalized["skus"] == [{"id": "s1"}]++ def test_passthrough_without_flatten_key(self) -> None:+ config = WEBFLOW_ENDPOINTS["pages"]+ item = {"id": "page1", "createdOn": "2026-01-01"}+ assert _normalize(item, config) == item++ def test_passthrough_when_flatten_key_absent(self) -> None:+ config = WEBFLOW_ENDPOINTS["products"]+ item = {"id": "p1"} # no "product" key+ assert _normalize(item, config) == item+++class TestBuildUrl:+ def test_paginated_endpoint(self) -> None:+ url = _build_url(WEBFLOW_ENDPOINTS["pages"], "site-1", 100)+ assert url == "https://api.webflow.com/v2/sites/site-1/pages?limit=100&offset=100"++ def test_non_paginated_endpoint_has_no_query(self) -> None:+ url = _build_url(WEBFLOW_ENDPOINTS["collections"], "site-1", 0)+ assert url == "https://api.webflow.com/v2/sites/site-1/collections"++ def test_sites_endpoint_is_site_scoped(self) -> None:+ url = _build_url(WEBFLOW_ENDPOINTS["sites"], "site-1", 0)+ assert url == "https://api.webflow.com/v2/sites/site-1"++ def test_collection_items_includes_stable_sort(self) -> None:+ url = _build_url(collection_items_endpoint_config("col-99"), "site-1", 0)+ assert url == (+ "https://api.webflow.com/v2/collections/col-99/items?limit=100&offset=0&sortBy=createdOn&sortOrder=asc"+ )++ def test_site_id_with_path_delimiters_is_encoded_into_a_single_segment(self) -> None:+ # A site_id containing path/query delimiters must not redirect the request to+ # an account-level (or otherwise unintended) Webflow endpoint.+ url = _build_url(WEBFLOW_ENDPOINTS["pages"], "../../sites", 0)+ assert url == "https://api.webflow.com/v2/sites/..%2F..%2Fsites/pages?limit=100&offset=0"+++def _drive_rows(+ config: Any, manager: Any, responses: list[Response], schema_name: str = "pages"+) -> tuple[list[Any], list[str]]:+ sent_urls: list[str] = []+ response_iter = iter(responses)++ def fake_get(url: str, *_args: Any, **_kwargs: Any) -> Response:+ sent_urls.append(url)+ return next(response_iter)++ with patch(TRANSPORT) as MockSession:+ mock_session = MockSession.return_value+ mock_session.get.side_effect = fake_get+ rows = list(+ get_rows(+ api_token="token",+ site_id="site-1",+ schema_name=schema_name,+ config=config,+ logger=MagicMock(),+ resumable_source_manager=manager,+ )+ )+ return rows, sent_urls+++class TestGetRows:+ def test_fresh_run_paginates_until_total_and_saves_after_each_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ responses = [+ _make_response({"pages": [{"id": "a"}], "pagination": {"total": 250, "offset": 0}}),+ _make_response({"pages": [{"id": "b"}], "pagination": {"total": 250, "offset": 100}}),+ _make_response({"pages": [{"id": "c"}], "pagination": {"total": 250, "offset": 200}}),+ ]+ rows, sent_urls = _drive_rows(WEBFLOW_ENDPOINTS["pages"], manager, responses)++ assert rows == [[{"id": "a"}], [{"id": "b"}], [{"id": "c"}]]+ assert [u.split("offset=")[1].split("&")[0] for u in sent_urls] == ["0", "100", "200"]+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [WebflowResumeConfig(offset=100), WebflowResumeConfig(offset=200)]++ def test_resume_starts_from_saved_offset(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = WebflowResumeConfig(offset=200)+ responses = [_make_response({"pages": [{"id": "c"}], "pagination": {"total": 250, "offset": 200}})]++ rows, sent_urls = _drive_rows(WEBFLOW_ENDPOINTS["pages"], manager, responses)++ assert rows == [[{"id": "c"}]]+ assert "offset=200" in sent_urls[0]+ manager.load_state.assert_called_once()++ def test_terminates_on_short_page_without_pagination_block(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ responses = [_make_response({"pages": [{"id": "only"}]})]++ rows, _ = _drive_rows(WEBFLOW_ENDPOINTS["pages"], manager, responses)++ assert rows == [[{"id": "only"}]]+ manager.save_state.assert_not_called()++ def test_single_object_endpoint_wraps_one_row_and_fetches_once(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ # /sites/{site_id} returns a single site object, not a list envelope.+ responses = [_make_response({"id": "s1", "displayName": "My site"})]++ rows, sent_urls = _drive_rows(WEBFLOW_ENDPOINTS["sites"], manager, responses, schema_name="sites")++ assert rows == [[{"id": "s1", "displayName": "My site"}]]+ assert sent_urls == ["https://api.webflow.com/v2/sites/site-1"]+ manager.save_state.assert_not_called()++ def test_paginated_endpoint_with_bare_list_response_does_not_crash(self) -> None:+ # A paginated endpoint that returns a bare list (no pagination block) must+ # fall through to short-page termination instead of crashing on data.get(...).+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ responses = [_make_response([{"id": "a"}, {"id": "b"}])]++ rows, sent_urls = _drive_rows(WEBFLOW_ENDPOINTS["pages"], manager, responses)++ assert rows == [[{"id": "a"}, {"id": "b"}]]+ assert len(sent_urls) == 1+ manager.save_state.assert_not_called()++ def test_does_not_load_state_when_cannot_resume(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ responses = [_make_response({"pages": [{"id": "a"}]})]++ _drive_rows(WEBFLOW_ENDPOINTS["pages"], manager, responses)++ manager.load_state.assert_not_called()+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, None, True),+ ("bad_token", 401, None, False),+ ("missing_scope_at_create", 403, None, True),+ ("missing_scope_for_schema", 403, "products", False),+ ("site_not_found", 404, None, False),+ ("server_error", 500, None, False),+ ]+ )+ def test_status_mapping(self, _name: str, status_code: int, schema_name: str | None, expected_ok: bool) -> None:+ with patch(TRANSPORT) as MockSession:+ MockSession.return_value.get.return_value = _make_response({"message": "nope"}, status_code=status_code)+ ok, _error = validate_credentials("token", "site-1", schema_name)+ assert ok is expected_ok++ def test_request_exception_returns_error(self) -> None:+ with patch(TRANSPORT) as MockSession:+ MockSession.return_value.get.side_effect = requests.exceptions.ConnectionError("boom")+ ok, error = validate_credentials("token", "site-1")+ assert ok is False+ assert error == "boom"+++class TestResolveCollectionId:+ def test_resolves_by_slug(self) -> None:+ with patch(TRANSPORT) as MockSession:+ MockSession.return_value.get.return_value = _make_response(+ {"collections": [{"id": "c1", "slug": "blog"}, {"id": "c2", "slug": "authors"}]}+ )+ assert _resolve_collection_id("token", "site-1", "collection_authors") == "c2"++ def test_raises_when_collection_missing(self) -> None:+ with patch(TRANSPORT) as MockSession:+ MockSession.return_value.get.return_value = _make_response({"collections": [{"id": "c1", "slug": "blog"}]})+ with pytest.raises(ValueError):+ _resolve_collection_id("token", "site-1", "collection_missing")+++class TestWebflowSource:+ @parameterized.expand(+ [+ ("pages", "pages", ["id"]),+ ("orders", "orders", ["orderId"]),+ ("products", "products", ["id"]),+ ]+ )+ def test_source_response_primary_keys(self, _name: str, schema_name: str, expected_pks: list[str]) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ response = webflow_source("token", "site-1", schema_name, logger=MagicMock(), resumable_source_manager=manager)+ assert response.name == schema_name+ assert response.primary_keys == expected_pks+ assert response.partition_mode == "datetime"++ def test_collection_schema_resolves_collection_id(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ with patch(+ "posthog.temporal.data_imports.sources.webflow.webflow._resolve_collection_id", return_value="c1"+ ) as mock_resolve:+ response = webflow_source(+ "token", "site-1", "collection_blog", logger=MagicMock(), resumable_source_manager=manager+ )+ mock_resolve.assert_called_once_with("token", "site-1", "collection_blog")+ assert response.name == "collection_blog"+ assert response.primary_keys == ["id"]++ def test_items_callable_lazy(self) -> None:+ # Building the SourceResponse must not touch the network; only iterating items() should.+ manager = MagicMock(spec=ResumableSourceManager)+ response = webflow_source("token", "site-1", "pages", logger=MagicMock(), resumable_source_manager=manager)+ assert callable(response.items)+ assert isinstance(response.items(), Iterable)diff --git a/posthog/temporal/data_imports/sources/webflow/tests/test_webflow_source.py b/posthog/temporal/data_imports/sources/webflow/tests/test_webflow_source.pynew file mode 100644index 000000000000..49c4c8c11b43--- /dev/null+++ b/posthog/temporal/data_imports/sources/webflow/tests/test_webflow_source.py@@ -0,0 +1,115 @@+from unittest.mock import MagicMock, patch++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++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.generated_configs import WebflowSourceConfig+from posthog.temporal.data_imports.sources.webflow.settings import STATIC_ENDPOINTS+from posthog.temporal.data_imports.sources.webflow.source import WebflowSource+from posthog.temporal.data_imports.sources.webflow.webflow import WebflowResumeConfig++from products.data_warehouse.backend.types import ExternalDataSourceType++SOURCE_MODULE = "posthog.temporal.data_imports.sources.webflow.source"+++def _config() -> WebflowSourceConfig:+ return WebflowSource().parse_config({"api_token": "token", "site_id": "site-1"})+++def _inputs(schema_name: str = "pages") -> SourceInputs:+ return SourceInputs(+ 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=MagicMock(),+ reset_pipeline=False,+ )+++class TestWebflowSource:+ def test_source_type(self) -> None:+ assert WebflowSource().source_type == ExternalDataSourceType.WEBFLOW++ def test_source_config_fields_and_release_status(self) -> None:+ config = WebflowSource().get_source_config+ assert config.name == "Webflow"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is not True++ assert all(isinstance(field, SourceFieldInputConfig) for field in config.fields)+ fields = {field.name: field for field in config.fields if isinstance(field, SourceFieldInputConfig)}+ assert set(fields) == {"api_token", "site_id"}+ assert fields["api_token"].type == SourceFieldInputConfigType.PASSWORD+ assert fields["api_token"].secret is True+ assert fields["site_id"].type == SourceFieldInputConfigType.TEXT+ assert fields["site_id"].secret is False++ def test_get_non_retryable_errors(self) -> None:+ errors = WebflowSource().get_non_retryable_errors()+ assert "401 Client Error" in errors+ assert "403 Client Error" in errors++ def test_get_schemas_includes_static_and_dynamic_collections(self) -> None:+ with patch(+ f"{SOURCE_MODULE}.list_collections",+ return_value=[{"id": "c1", "slug": "blog", "displayName": "Blog"}, {"id": "c2", "slug": "authors"}],+ ):+ schemas = WebflowSource().get_schemas(_config(), team_id=1)++ names = {s.name for s in schemas}+ assert set(STATIC_ENDPOINTS).issubset(names)+ assert "collection_blog" in names+ assert "collection_authors" in names+ # No verified server-side range filter -> everything is full refresh.+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)++ def test_get_schemas_falls_back_to_static_when_discovery_fails(self) -> None:+ with patch(f"{SOURCE_MODULE}.list_collections", side_effect=Exception("no scope")):+ schemas = WebflowSource().get_schemas(_config(), team_id=1)++ assert {s.name for s in schemas} == set(STATIC_ENDPOINTS)++ def test_get_schemas_filters_by_names(self) -> None:+ with patch(+ f"{SOURCE_MODULE}.list_collections", return_value=[{"id": "c1", "slug": "blog", "displayName": "Blog"}]+ ):+ schemas = WebflowSource().get_schemas(_config(), team_id=1, names=["sites", "collection_blog"])++ assert {s.name for s in schemas} == {"sites", "collection_blog"}++ def test_validate_credentials_plumbs_through(self) -> None:+ with patch(f"{SOURCE_MODULE}.validate_webflow_credentials", return_value=(True, None)) as mock_validate:+ ok, error = WebflowSource().validate_credentials(_config(), team_id=1, schema_name="products")++ assert ok is True+ assert error is None+ mock_validate.assert_called_once_with("token", "site-1", "products")++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = WebflowSource().get_resumable_source_manager(_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is WebflowResumeConfig++ def test_source_for_pipeline_plumbs_through(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ inputs = _inputs(schema_name="collection_blog")+ with patch(f"{SOURCE_MODULE}.webflow_source") as mock_source:+ WebflowSource().source_for_pipeline(_config(), manager, inputs)++ mock_source.assert_called_once_with(+ api_token="token",+ site_id="site-1",+ schema_name="collection_blog",+ logger=inputs.logger,+ resumable_source_manager=manager,+ )diff --git a/posthog/temporal/data_imports/sources/webflow/webflow.py b/posthog/temporal/data_imports/sources/webflow/webflow.pynew file mode 100644index 000000000000..d04f6c741066--- /dev/null+++ b/posthog/temporal/data_imports/sources/webflow/webflow.py@@ -0,0 +1,245 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import quote, urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.webflow.settings import (+ COLLECTION_SCHEMA_PREFIX,+ DEFAULT_PAGE_SIZE,+ WEBFLOW_BASE_URL,+ WEBFLOW_ENDPOINTS,+ WebflowEndpointConfig,+ collection_items_endpoint_config,+)+++class WebflowRetryableError(Exception):+ pass+++class WebflowResumeConfig:+ offset: int+++def _get_headers(api_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_token}",+ "Accept": "application/json",+ }+++def _encode_path_segment(value: str) -> str:+ """Percent-encode a value before interpolating it into a URL path.++ ``site_id`` is a non-secret field a user can edit on an existing source while the+ saved ``api_token`` is preserved. Without encoding, a value containing ``/``, ``?``,+ or ``#`` could redirect the authenticated request to an unintended Webflow endpoint.+ Encoding with ``safe=""`` keeps every delimiter inside the single path segment.+ """+ return quote(value, safe="")+++def _extract_items(data: Any, data_key: str) -> list[dict[str, Any]]:+ """Pull the list of records out of a Webflow list envelope.++ Webflow uses a per-resource envelope key (``sites``, ``collections``, ``items``,+ ``orders``, …) rather than a single consistent key. We try the configured key+ first, then fall back to the first list-valued, non-``pagination`` key so an+ unverified envelope guess degrades gracefully instead of silently dropping rows.+ """+ if isinstance(data, list):+ return data+ if not isinstance(data, dict):+ return []++ value = data.get(data_key)+ if isinstance(value, list):+ return value++ for key, candidate in data.items():+ if key != "pagination" and isinstance(candidate, list):+ return candidate+ return []+++def _normalize(item: dict[str, Any], config: WebflowEndpointConfig) -> dict[str, Any]:+ """Merge a nested object up into the row root (e.g. products nest the product+ under a ``product`` key alongside ``skus``)."""+ if config.flatten_key and isinstance(item.get(config.flatten_key), dict):+ rest = {**item}+ flattened = rest.pop(config.flatten_key)+ return {**flattened, **rest}+ return item+++def validate_credentials(api_token: str, site_id: str, schema_name: Optional[str] = None) -> tuple[bool, str | None]:+ url = f"{WEBFLOW_BASE_URL}/sites/{_encode_path_segment(site_id)}"+ try:+ response = make_tracked_session(redact_values=(api_token,)).get(+ url, headers=_get_headers(api_token), timeout=10+ )+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None++ if response.status_code == 401:+ return False, "Invalid Webflow API token"++ # A 403 means the token is genuine but lacks the scope for this probe. Accept it+ # at source-create (schema_name is None) so users only need to grant scopes for+ # the resources they actually want to sync; sync-time 403s are caught by+ # get_non_retryable_errors instead.+ if response.status_code == 403:+ if schema_name is None:+ return True, None+ return False, "Your Webflow API token is missing the scope required for this resource"++ if response.status_code == 404:+ return False, f"Webflow site '{site_id}' was not found or is not accessible by this token"++ try:+ message = response.json().get("message", response.text)+ except ValueError:+ message = response.text+ return False, message+++def list_collections(api_token: str, site_id: str) -> list[dict[str, Any]]:+ url = f"{WEBFLOW_BASE_URL}/sites/{_encode_path_segment(site_id)}/collections"+ response = make_tracked_session(redact_values=(api_token,)).get(url, headers=_get_headers(api_token), timeout=30)+ response.raise_for_status()+ return _extract_items(response.json(), "collections")+++def _resolve_collection_id(api_token: str, site_id: str, schema_name: str) -> str:+ for collection in list_collections(api_token, site_id):+ slug = collection.get("slug")+ if slug and f"{COLLECTION_SCHEMA_PREFIX}{slug}" == schema_name:+ return collection["id"]+ raise ValueError(f"Webflow collection for schema '{schema_name}' was not found on site '{site_id}'")+++def _endpoint_config_for_schema(api_token: str, site_id: str, schema_name: str) -> WebflowEndpointConfig:+ if schema_name in WEBFLOW_ENDPOINTS:+ return WEBFLOW_ENDPOINTS[schema_name]+ if schema_name.startswith(COLLECTION_SCHEMA_PREFIX):+ collection_id = _resolve_collection_id(api_token, site_id, schema_name)+ return collection_items_endpoint_config(collection_id)+ raise ValueError(f"Unknown Webflow schema '{schema_name}'")+++def _build_url(config: WebflowEndpointConfig, site_id: str, offset: int) -> str:+ path = config.path.format(site_id=_encode_path_segment(site_id)) if config.requires_site else config.path+ params: dict[str, Any] = {}+ if config.paginated:+ params["limit"] = DEFAULT_PAGE_SIZE+ params["offset"] = offset+ if config.sort_by:+ params["sortBy"] = config.sort_by+ params["sortOrder"] = config.sort_order+ base_url = f"{WEBFLOW_BASE_URL}{path}"+ return f"{base_url}?{urlencode(params)}" if params else base_url+++def get_rows(+ api_token: str,+ site_id: str,+ schema_name: str,+ config: WebflowEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[WebflowResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ headers = _get_headers(api_token)+ session = make_tracked_session(headers=headers, redact_values=(api_token,))++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume_config.offset if resume_config else 0+ if resume_config:+ logger.debug(f"Webflow: resuming '{schema_name}' from offset {offset}")++ @retry(+ retry=retry_if_exception_type((WebflowRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def fetch_page(page_offset: int) -> Any:+ url = _build_url(config, site_id, page_offset)+ response = session.get(url, timeout=60)++ if response.status_code == 429 or response.status_code >= 500:+ raise WebflowRetryableError(f"Webflow API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Webflow API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()++ while True:+ data = fetch_page(offset)+ if config.single_object:+ items = [data] if isinstance(data, dict) else _extract_items(data, config.data_key)+ else:+ items = _extract_items(data, config.data_key)++ if items:+ yield [_normalize(item, config) for item in items]++ if not config.paginated:+ break++ # Pagination metadata only lives on a dict envelope; a bare-list (or otherwise+ # non-dict) response has no pagination block, so fall through to short-page+ # termination instead of crashing on data.get(...).+ pagination = data.get("pagination") if isinstance(data, dict) else None+ total = pagination.get("total") if isinstance(pagination, dict) else None+ next_offset = offset + DEFAULT_PAGE_SIZE++ if total is not None:+ if next_offset >= total:+ break+ elif len(items) < DEFAULT_PAGE_SIZE:+ break++ offset = next_offset+ # Save after yielding the current page so a resume restarts at the next page.+ resumable_source_manager.save_state(WebflowResumeConfig(offset=offset))+++def webflow_source(+ api_token: str,+ site_id: str,+ schema_name: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[WebflowResumeConfig],+) -> SourceResponse:+ config = _endpoint_config_for_schema(api_token, site_id, schema_name)++ return SourceResponse(+ name=schema_name,+ items=lambda: get_rows(+ api_token=api_token,+ site_id=site_id,+ schema_name=schema_name,+ config=config,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=[config.primary_key],+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )