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(warehouse_sources): add Fourthwall product-templates table (#90080)

Tom Owers17dfc9264fcd
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 75b4dbee5537..dfe94292b409 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -3193,6 +3193,16 @@ Diffed against: <https://formbricks.com/docs/api-reference/openapi.json>
Note: The v1 management API spec (openapi.json, 23 paths) is fully covered - every GET-listable v1 resource is already synced. The remaining gaps come from the v2 organizations API, enumerated from https://formbricks.com/docs/llms.txt (api-v2-reference/organizations-api--\* and api-v2-reference/roles/get-roles). Displays and storage have no list endpoint.
+## Fourthwall — adequate
+
+Today (9): `collections`, `donations`, `mailing_list_entries`, `members`, `membership_tiers`, `orders`, `product_templates`, `products`, `promotions`
+
+Diffed against: <https://docs.fourthwall.com/api-reference/platform>
+
+- [x] `product-templates (GET /product-templates/page/{page})` — the catalog of base product templates a shop builds products from, added as a full-refresh table
+
+Note: The product-templates list pages by a 1-based path segment and returns only `{results, total}` (no `totalPages`), so it walks the path until a page is empty; rows are keyed by `productId` and carry no timestamps, so the table is full-refresh only.
+
## Freshcaller — gaps
Today (4): `call_metrics`, `calls`, `teams`, `users`
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/canonical_descriptions.py
index 63911c938f3f..9592a072f2a1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/canonical_descriptions.py
@@ -51,6 +51,20 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"updatedAt": "When the product was last changed.",
},
},
+ "product_templates": {
+ "description": "A base product template the shop can build products from, with its category, brand and base price.",
+ "docs_url": f"{_API_REFERENCE}/product-templates/list-product-templates-paged",
+ "columns": {
+ "productId": "Unique identifier of the product template.",
+ "name": "Product template name.",
+ "category": "Category path the template belongs to.",
+ "brand": "Brand the template is made by.",
+ "thumbnail": "Thumbnail image URL. Generated on demand, so it can change or expire.",
+ "basePrice": "Base price of the template, as an amount and currency.",
+ "productionMethod": "How the product is made, for example DTG, EMBROIDERY, DTFX, KNITTING or SUBLIMATION.",
+ "supportsBackendRendering": "Whether the template supports backend mockup rendering.",
+ },
+ },
"collections": {
"description": "A storefront collection grouping products together.",
"docs_url": f"{_API_REFERENCE}/collections/list-collections",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/fourthwall.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/fourthwall.py
index 4e4460ced7af..49cb0278fe53 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/fourthwall.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/fourthwall.py
@@ -6,7 +6,7 @@ import orjson
import pyarrow as pa
from asgiref.sync import async_to_sync
from dateutil import parser
-from requests import Session
+from requests import Request, Response, Session
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_list
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
@@ -24,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
rest_api_resource,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
PageNumberPaginator,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
@@ -89,12 +90,63 @@ def _client_config(username: str, password: str, api_version: str) -> ClientConf
}
+class ProductTemplatePaginator(BasePaginator):
+ """Page Fourthwall's product-templates list.
+
+ That list carries a 1-based page number in the path (`/product-templates/page/{page}`) and
+ returns only `{results, total}` — no `totalPages` and no page-size parameter. So advance the
+ trailing path segment until a page comes back empty.
+ """
+
+ def __init__(self, page: int = 1) -> None:
+ super().__init__()
+ self.page = page
+ self._page_base: Optional[str] = None
+
+ def _apply_page(self, request: Request) -> None:
+ if self._page_base is None:
+ # The first URL ends in the page number; keep everything before it as the base.
+ self._page_base = (request.url or "").rsplit("/", 1)[0]
+ request.url = f"{self._page_base}/{self.page}"
+
+ def init_request(self, request: Request) -> None:
+ self._apply_page(request)
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ if not data:
+ self._has_next_page = False
+ return
+ self.page += 1
+ self._has_next_page = True
+
+ def update_request(self, request: Request) -> None:
+ self._apply_page(request)
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ return {"page": self.page} if self._has_next_page else None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ page = state.get("page")
+ if page is not None:
+ self.page = int(page)
+ self._has_next_page = True
+
+ def __str__(self) -> str:
+ return f"ProductTemplatePaginator(page={self.page})"
+
+
def get_resource(endpoint: str, should_use_incremental_field: bool) -> EndpointResource:
config = FOURTHWALL_ENDPOINTS[endpoint]
endpoint_config: Endpoint = {"path": config.path}
- if config.paginated:
+ if config.page_in_path:
+ # First page is 1; the paginator rewrites the trailing segment for later pages.
+ endpoint_config["path"] = f"{config.path}/1"
+ endpoint_config["data_selector"] = "results"
+ endpoint_config["data_selector_required"] = True
+ endpoint_config["paginator"] = ProductTemplatePaginator()
+ elif config.paginated:
endpoint_config["params"] = {"size": PAGE_SIZE}
endpoint_config["data_selector"] = "results"
# `results` is a required field of Fourthwall's page envelope, so a response without it
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/settings.py
index 46448fecd938..763a48c635a6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/settings.py
@@ -13,7 +13,7 @@ BASE_URL = "https://api.fourthwall.com"
PAGE_SIZE = 100
-@dataclass
+@dataclass # nosemgrep: prefer-frozen-dataclasses -- pre-existing; new field shifts the backlog finding into diff
class FourthwallEndpointConfig:
name: str
# Path below `/open-api/{version}`; the version segment comes from the source's pin.
@@ -26,6 +26,9 @@ class FourthwallEndpointConfig:
# Most endpoints wrap rows in a `{results, total, page, size, totalPages}` envelope; a few
# return a bare JSON array with no pagination at all.
paginated: bool = True
+ # A few endpoints carry a 1-based page number in the path (`.../page/{page}`) and return an
+ # envelope without `totalPages`, so they walk the path until a page is empty.
+ page_in_path: bool = False
sort_mode: Literal["asc", "desc"] = "asc"
# Webhook event types whose payload carries this table's row.
webhook_events: tuple[str, ...] = ()
@@ -55,6 +58,17 @@ FOURTHWALL_ENDPOINTS: dict[str, FourthwallEndpointConfig] = {
# filter to sync incrementally against.
partition_key="createdAt",
),
+ "product_templates": FourthwallEndpointConfig(
+ name="product_templates",
+ # The page number is a 1-based path segment (`/product-templates/page/{page}`), so this
+ # `path` is the base the paginator appends the page number to.
+ path="/product-templates/page",
+ page_in_path=True,
+ # Rows are keyed by `productId`, not `id`.
+ primary_key=["productId"],
+ # The summary carries no timestamps and the endpoint takes no filter or sort parameter,
+ # so this table is full-refresh only with no partition key.
+ ),
"collections": FourthwallEndpointConfig(
name="collections",
path="/collections",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/source.py
index aad1e1bcac5b..a6ffa85dd1ad 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/source.py
@@ -201,8 +201,8 @@ class FourthwallSource(
category=DataWarehouseSourceCategory.E_COMMERCE,
label="Fourthwall",
caption=(
- "Sync your Fourthwall shop's orders, products, collections, donations, members, "
- "membership tiers, promotions and mailing list into PostHog.\n\n"
+ "Sync your Fourthwall shop's orders, products, product templates, collections, "
+ "donations, members, membership tiers, promotions and mailing list into PostHog.\n\n"
f"{DEVELOPER_SETTINGS_HELP}"
),
keywords=["merch", "memberships", "creator commerce"],
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/tests/test_fourthwall.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/tests/test_fourthwall.py
index 4327c79e116b..c298a6167184 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/tests/test_fourthwall.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/tests/test_fourthwall.py
@@ -119,7 +119,14 @@ def _endpoint_config(endpoint: str, should_use_incremental_field: bool = False)
class TestGetResource:
- @pytest.mark.parametrize("endpoint", [name for name in ENDPOINTS if FOURTHWALL_ENDPOINTS[name].paginated])
+ @pytest.mark.parametrize(
+ "endpoint",
+ [
+ name
+ for name in ENDPOINTS
+ if FOURTHWALL_ENDPOINTS[name].paginated and not FOURTHWALL_ENDPOINTS[name].page_in_path
+ ],
+ )
def test_paginated_endpoints_select_the_results_envelope(self, endpoint):
endpoint_config = _endpoint_config(endpoint)
@@ -196,6 +203,52 @@ class TestPagination:
assert len(requests_seen) == 1
+def _templates_page(results: list[dict[str, Any]]) -> Response:
+ response = Response()
+ response.status_code = 200
+ response._content = json.dumps({"results": results, "total": 3}).encode()
+ return response
+
+
+class TestProductTemplatePagination:
+ @mock.patch(SESSION_PATCH)
+ def test_walks_pages_by_path_until_empty(self, MockSession):
+ # product-templates pages by a 1-based path segment with no `totalPages`, so it must
+ # walk `/page/1`, `/page/2`, ... and stop only when a page returns no rows.
+ session = MockSession.return_value
+ requests_seen = _wire(
+ session,
+ [
+ _templates_page([{"productId": "pt_1"}, {"productId": "pt_2"}]),
+ _templates_page([{"productId": "pt_3"}]),
+ _templates_page([]),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source("product_templates", manager))
+
+ assert [row["productId"] for row in rows] == ["pt_1", "pt_2", "pt_3"]
+ assert [request["url"] for request in requests_seen] == [
+ f"{API_ROOT}/product-templates/page/1",
+ f"{API_ROOT}/product-templates/page/2",
+ f"{API_ROOT}/product-templates/page/3",
+ ]
+ # Checkpointed after each non-empty page while a next page remained; the empty page saves nothing.
+ assert manager.save_state.call_count == 2
+ assert manager.save_state.call_args.args[0] == FourthwallResumeConfig(paginator_state={"page": 3})
+
+ @mock.patch(SESSION_PATCH)
+ def test_resumes_from_saved_page(self, MockSession):
+ session = MockSession.return_value
+ requests_seen = _wire(session, [_templates_page([{"productId": "pt_9"}]), _templates_page([])])
+
+ rows = _rows(_source("product_templates", _make_manager(FourthwallResumeConfig(paginator_state={"page": 4}))))
+
+ assert [row["productId"] for row in rows] == ["pt_9"]
+ assert requests_seen[0]["url"] == f"{API_ROOT}/product-templates/page/4"
+
+
class TestIncrementalRequests:
@mock.patch(SESSION_PATCH)
def test_incremental_sync_sends_the_watermark_on_every_page(self, MockSession):
@@ -245,9 +298,9 @@ class TestSourceResponseMetadata:
response = _source(endpoint, _make_manager())
assert response.name == endpoint
- # Every table is a top-level list endpoint keyed by a globally unique id, so `id`
- # alone stays unique table-wide.
- assert response.primary_keys == ["id"]
+ # Every table is a top-level list endpoint keyed by a globally unique id, so the
+ # endpoint's primary key stays unique table-wide.
+ assert response.primary_keys == config.primary_key
assert response.sort_mode == config.sort_mode
assert response.partition_keys == ([config.partition_key] if config.partition_key else None)
assert response.partition_mode == ("datetime" if config.partition_key else None)