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): add Fourthwall source (#77121)

Tom Owersb893e80d2f34
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 7b435dd2f0a1..1a11afab7f64 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -229,6 +229,7 @@ the row lists both.
| elevenlabs | HTTP | requests | ✅ |
| eppo | HTTP | requests + `rest_source.RESTClient` | ✅ |
| etsy | HTTP | requests | ✅ |
+| fourthwall | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| freshcaller | HTTP | requests | ✅ |
| freshchat | HTTP | requests | ✅ |
| freshdesk | HTTP | requests | ✅ |
@@ -945,7 +946,6 @@ doesn't conflict with concurrent PRs.
- fly_io
- formbricks
- fortnox
-- fourthwall
- fred
- freeagent
- freightview
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
new file mode 100644
index 000000000000..63911c938f3f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/canonical_descriptions.py
@@ -0,0 +1,128 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_API_REFERENCE = "https://docs.fourthwall.com/api-reference/platform"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "orders": {
+ "description": "A paid order placed in the shop, with its line items, amounts and fulfillment status.",
+ "docs_url": f"{_API_REFERENCE}/orders/list-orders",
+ "columns": {
+ "id": "Unique identifier of the order.",
+ "shopId": "Identifier of the shop the order belongs to.",
+ "friendlyId": "Human-readable order number shown to the supporter.",
+ "checkoutId": "Identifier of the checkout the order was created from.",
+ "promotionId": "Identifier of the promotion applied to the order, if any.",
+ "status": "Fulfillment state: CONFIRMED, PARTIALLY_IN_PRODUCTION, IN_PRODUCTION, PARTIALLY_SHIPPED, SHIPPED, PARTIALLY_DELIVERED, DELIVERED, CANCELLED or COMPLETED.",
+ "email": "Email address of the supporter who placed the order.",
+ "emailMarketingOptIn": "Whether the supporter opted in to marketing emails at checkout.",
+ "username": "Display name of the supporter who placed the order.",
+ "message": "Message the supporter left with the order.",
+ "amounts": "Order totals: subtotal, shipping, tax, donation, discount, total and any gift cards.",
+ "billing": "Billing address supplied at checkout.",
+ "shipping": "Shipping address supplied at checkout.",
+ "offers": "Products bought in this order, each with the purchased variant and quantity.",
+ "source": "How the order was created: ORDER, SAMPLES_ORDER, GIVEAWAY_LINKS or TWITCH_GIFT_REDEMPTION.",
+ "trackingParams": "Marketing attribution captured at checkout (utm_source, utm_medium, utm_campaign, utm_content, utm_term, fbc, fbp).",
+ "metadata": "Custom key-value pairs attached when the cart was created.",
+ "createdAt": "When the order was placed.",
+ "updatedAt": "When the order was last changed.",
+ },
+ },
+ "products": {
+ "description": "A product (offer) in the shop, with its variants, pricing, images and availability.",
+ "docs_url": f"{_API_REFERENCE}/products/list-products",
+ "columns": {
+ "id": "Unique identifier of the product.",
+ "name": "Product name.",
+ "slug": "URL slug of the product in the storefront.",
+ "description": "Product description.",
+ "type": "Product type: STANDARD, GIFT_CARD or UNKNOWN.",
+ "state": "Stock state of the product: available or sold out.",
+ "access": "Storefront visibility: public, hidden, private or archived.",
+ "thumbnailImage": "Primary image shown in listings.",
+ "images": "All images attached to the product.",
+ "variants": "Purchasable variants, each with its own SKU, price, colour and size.",
+ "additionalInformation": "Extra product details shown on the product page.",
+ "sizeGuide": "Size guide attached to the product.",
+ "digitalFiles": "Files delivered to the buyer. Only present for digital products.",
+ "createdAt": "When the product was created.",
+ "updatedAt": "When the product was last changed.",
+ },
+ },
+ "collections": {
+ "description": "A storefront collection grouping products together.",
+ "docs_url": f"{_API_REFERENCE}/collections/list-collections",
+ "columns": {
+ "id": "Unique identifier of the collection.",
+ "shopId": "Identifier of the shop the collection belongs to.",
+ "name": "Collection name.",
+ "slug": "URL slug of the collection in the storefront.",
+ "description": "Collection description.",
+ "available": "Whether the collection is currently available in the storefront.",
+ "state": "Storefront visibility: PUBLIC, HIDDEN, PRIVATE or ARCHIVED.",
+ },
+ },
+ "donations": {
+ "description": "A tip or donation made to the shop.",
+ "docs_url": f"{_API_REFERENCE}/donations/list-donations",
+ "columns": {
+ "id": "Unique identifier of the donation.",
+ "shopId": "Identifier of the shop that received the donation.",
+ "status": "Donation state: OPEN, COMPLETED, ABANDONED, CANCELLED or FAILED.",
+ "email": "Email address of the donor.",
+ "username": "Display name of the donor.",
+ "message": "Message the donor left with the donation.",
+ "amounts": "Donation total, as a value and currency.",
+ "createdAt": "When the donation was made.",
+ "updatedAt": "When the donation was last changed.",
+ },
+ },
+ "members": {
+ "description": "A membership supporter of the shop and the state of their subscription.",
+ "docs_url": f"{_API_REFERENCE}/memberships/list-members",
+ "columns": {
+ "id": "Unique identifier of the member.",
+ "email": "Email address of the member.",
+ "nickname": "Display name of the member.",
+ "createdAt": "When the member joined.",
+ "subscription": "Current subscription state (ACTIVE, CANCELLED, SUSPENDED or NONE) with the tier variant, billing interval and amount.",
+ },
+ },
+ "membership_tiers": {
+ "description": "A membership tier offered by the shop, with its monthly and annual variants.",
+ "docs_url": f"{_API_REFERENCE}/memberships/list-tiers",
+ "columns": {
+ "id": "Unique identifier of the tier.",
+ "name": "Tier name.",
+ "imageUrl": "Image shown for the tier.",
+ "variants": "Purchasable variants of the tier, each with its billing interval (MONTHLY or ANNUAL) and price.",
+ },
+ },
+ "promotions": {
+ "description": "A discount promotion configured for the shop or for memberships.",
+ "docs_url": f"{_API_REFERENCE}/promotions/list-promotions",
+ "columns": {
+ "id": "Unique identifier of the promotion.",
+ "type": "Promotion kind: SHOP_SINGLE, SHOP_MULTI, SHOP_AUTO_APPLYING, MEMBERSHIPS_SINGLE or MEMBERSHIPS_MULTI.",
+ "title": "Internal name of the promotion.",
+ "code": "Discount code supporters enter at checkout. Single-code promotions only.",
+ "codes": "Discount codes generated for the promotion. Multi-code promotions only.",
+ "discount": "The discount the promotion applies.",
+ "appliesTo": "What the discount applies to, for example the entire order or selected products.",
+ "requirements": "Conditions a cart must meet before the promotion applies.",
+ "limits": "Usage limits configured on the promotion.",
+ "usageCount": "How many times the promotion has been redeemed.",
+ "status": "Whether the promotion is live, ended, archived or fully used.",
+ },
+ },
+ "mailing_list_entries": {
+ "description": "An email address subscribed to the shop's mailing list.",
+ "docs_url": f"{_API_REFERENCE}/mailing-lists/list-entries",
+ "columns": {
+ "id": "Unique identifier of the mailing list entry.",
+ "email": "Subscribed email address.",
+ },
+ },
+}
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
new file mode 100644
index 000000000000..4e4460ced7af
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/fourthwall.py
@@ -0,0 +1,393 @@
+import dataclasses
+from datetime import datetime
+from typing import Any, Optional
+
+import orjson
+import pyarrow as pa
+from asgiref.sync import async_to_sync
+from dateutil import parser
+from requests import 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 (
+ ExternalWebhookInfo,
+ WebhookCreationResult,
+ WebhookDeletionResult,
+ WebhookSyncResult,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (
+ coerce_datetime_to_utc,
+)
+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 (
+ PageNumberPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+ EndpointResource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.fourthwall.settings import (
+ ALL_WEBHOOK_EVENTS,
+ BASE_URL,
+ FOURTHWALL_ENDPOINTS,
+ PAGE_SIZE,
+ WEBHOOK_EVENT_DATA_UNWRAP_KEY,
+ WEBHOOK_SCHEMA_NAMES,
+)
+
+REQUEST_TIMEOUT_SECONDS = 30
+
+# Lower bound used on the first incremental sync, before a watermark exists.
+INCREMENTAL_INITIAL_VALUE = "1970-01-01T00:00:00Z"
+
+
+class FourthwallResumeConfig:
+ # Opaque framework paginator checkpoint (the next page number), round-tripped into
+ # `initial_paginator_state` on resume.
+ paginator_state: dict[str, Any]
+
+
+def api_root(api_version: str) -> str:
+ return f"{BASE_URL}/open-api/{api_version}"
+
+
+def _format_datetime(value: Any) -> str:
+ """Format the incremental watermark for Fourthwall's `updatedAt[gt]` filter.
+
+ Truncates to whole seconds, which rounds the lower bound *down* — a sync re-reads at most a
+ few boundary orders (the merge dedupes them) rather than skipping any order whose updatedAt
+ equals the watermark.
+ """
+ normalized = coerce_datetime_to_utc(value)
+ if normalized is None:
+ return str(value)
+ return normalized.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _client_config(username: str, password: str, api_version: str) -> ClientConfig:
+ return {
+ "base_url": api_root(api_version),
+ "auth": {"type": "http_basic", "username": username, "password": password},
+ "headers": {"Accept": "application/json"},
+ # Order, donation and member rows carry supporter names, emails and postal addresses,
+ # so keep the raw bodies out of HTTP sample capture (still metered and logged).
+ "session": make_tracked_session(capture=False, redact_values=(password,)),
+ # The API user's credentials ride every request, so pin them to the Fourthwall origin
+ # and refuse redirects rather than letting a 3xx move them somewhere else.
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ "request_timeout": REQUEST_TIMEOUT_SECONDS,
+ }
+
+
+def get_resource(endpoint: str, should_use_incremental_field: bool) -> EndpointResource:
+ config = FOURTHWALL_ENDPOINTS[endpoint]
+
+ endpoint_config: Endpoint = {"path": config.path}
+
+ if 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
+ # is a changed API shape — fail loud rather than quietly syncing zero rows.
+ endpoint_config["data_selector_required"] = True
+ # `totalPages` stops pagination on the last page instead of paying one extra empty
+ # request; `base_page=0` matches Fourthwall's 0-based `page` parameter.
+ endpoint_config["paginator"] = PageNumberPaginator(base_page=0, page_param="page", total_path="totalPages")
+ else:
+ endpoint_config["paginator"] = "single_page"
+
+ if should_use_incremental_field and config.incremental_param:
+ endpoint_config["incremental"] = {
+ "start_param": config.incremental_param,
+ "cursor_path": config.incremental_fields[0]["field"],
+ "initial_value": INCREMENTAL_INITIAL_VALUE,
+ "convert": _format_datetime,
+ }
+
+ return {
+ "name": config.name,
+ "table_name": config.name,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}
+ if should_use_incremental_field and config.incremental_param
+ else "replace",
+ "endpoint": endpoint_config,
+ "table_format": "delta",
+ }
+
+
+def _coerce_payload(value: Any) -> Optional[dict[str, Any]]:
+ """Read a webhook column back as a dict; the buffering layer JSON-encodes nested values."""
+ if isinstance(value, str | bytes):
+ try:
+ value = orjson.loads(value)
+ except orjson.JSONDecodeError:
+ return None
+ return value if isinstance(value, dict) else None
+
+
+def _parse_datetime(value: Any) -> Optional[datetime]:
+ if not isinstance(value, str):
+ return None
+ try:
+ return parser.parse(value)
+ except (ValueError, OverflowError):
+ return None
+
+
+def webhook_table_transformer(table: pa.Table) -> pa.Table:
+ """Reshape raw webhook deliveries into rows matching the pull-API table shape.
+
+ Deliveries land as the whole event envelope (`{id, type, createdAt, data, ...}`), so the
+ resource object has to be lifted out of `data` — and out of `data.order` for ORDER_UPDATED,
+ which nests it one level deeper. Only the newest event per object id survives: delta merge
+ dedupes across syncs but not within one batch, so an ORDER_PLACED followed by an
+ ORDER_UPDATED for the same order must collapse here.
+ """
+ if "data" not in table.column_names or "type" not in table.column_names:
+ return table_from_py_list([])
+
+ created_at_column = (
+ table.column("createdAt").to_pylist() if "createdAt" in table.column_names else [None] * table.num_rows
+ )
+
+ latest_by_id: dict[Any, tuple[Optional[datetime], dict[str, Any]]] = {}
+ for event_type, data, event_created_at in zip(
+ table.column("type").to_pylist(), table.column("data").to_pylist(), created_at_column
+ ):
+ row = _coerce_payload(data)
+ if row is None:
+ continue
+
+ unwrap_key = WEBHOOK_EVENT_DATA_UNWRAP_KEY.get(str(event_type))
+ if unwrap_key is not None:
+ row = _coerce_payload(row.get(unwrap_key))
+ if row is None:
+ continue
+
+ row_id = row.get("id")
+ if row_id is None:
+ continue
+
+ created_at = _parse_datetime(event_created_at)
+ existing = latest_by_id.get(row_id)
+ # Later rows win ties so batch arrival order breaks equal or unparseable timestamps.
+ if existing is None or existing[0] is None or (created_at is not None and created_at >= existing[0]):
+ latest_by_id[row_id] = (created_at, row)
+
+ return table_from_py_list([row for _, row in latest_by_id.values()])
+
+
+def fourthwall_source(
+ username: str,
+ password: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ api_version: str,
+ resumable_source_manager: ResumableSourceManager[FourthwallResumeConfig],
+ webhook_source_manager: Optional[WebhookSourceManager] = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = FOURTHWALL_ENDPOINTS[endpoint]
+
+ rest_config: RESTAPIConfig = {
+ "client": _client_config(username, password, api_version),
+ "resources": [get_resource(endpoint, should_use_incremental_field)],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None:
+ initial_paginator_state = resume.paginator_state
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # The hook fires after a page has been yielded, so a crash re-yields the last page
+ # (merge dedupes on the primary key) rather than skipping it. Only persist while a
+ # next page remains; the Redis TTL handles cleanup.
+ if state:
+ resumable_source_manager.save_state(FourthwallResumeConfig(paginator_state=dict(state)))
+
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ webhook_enabled = False
+ if webhook_source_manager is not None and endpoint in WEBHOOK_SCHEMA_NAMES:
+ webhook_enabled = async_to_sync(webhook_source_manager.webhook_enabled)()
+
+ def items():
+ if webhook_enabled and webhook_source_manager is not None:
+ return webhook_source_manager.get_items(table_transformer=webhook_table_transformer)
+ return resource
+
+ partitioned = config.partition_key is not None
+ return SourceResponse(
+ name=config.name,
+ items=items,
+ primary_keys=config.primary_key,
+ sort_mode=config.sort_mode,
+ partition_count=1 if partitioned else None,
+ partition_size=1 if partitioned else None,
+ partition_mode="datetime" if partitioned else None,
+ partition_format="month" if partitioned else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+def _make_session(username: str, password: str) -> Session:
+ session = make_tracked_session(
+ headers={"Accept": "application/json"},
+ redact_values=(password,),
+ # Webhook responses can carry the signing secret, so keep them out of sample capture.
+ capture=False,
+ allow_redirects=False,
+ )
+ session.auth = (username, password)
+ return session
+
+
+def validate_credentials(username: str, password: str, api_version: str) -> tuple[bool, str | None]:
+ """Probe the shop endpoint — the cheapest call that proves the API user is real.
+
+ Fourthwall API users have full access to every Open API endpoint, so one probe validates
+ every table this source syncs.
+ """
+ response = _make_session(username, password).get(
+ f"{api_root(api_version)}/shops/current", timeout=REQUEST_TIMEOUT_SECONDS
+ )
+ if response.status_code == 200:
+ return True, None
+ if response.status_code in (401, 403):
+ return False, "Fourthwall rejected the API user. Check the username and password and try again."
+ if response.status_code == 404:
+ return False, "No Fourthwall shop is reachable with this API user."
+ return False, f"Fourthwall returned an unexpected status: {response.status_code}"
+
+
+def _iterate_webhooks(session: Session, api_version: str) -> list[dict[str, Any]]:
+ webhooks: list[dict[str, Any]] = []
+ page = 0
+ while True:
+ response = session.get(
+ f"{api_root(api_version)}/webhooks",
+ params={"page": page, "size": PAGE_SIZE},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ response.raise_for_status()
+ body = response.json()
+ webhooks.extend(item for item in body.get("results") or [] if isinstance(item, dict))
+
+ total_pages = body.get("totalPages")
+ page += 1
+ if not isinstance(total_pages, int) or page >= total_pages:
+ return webhooks
+
+
+def _webhooks_matching(session: Session, api_version: str, webhook_url: str) -> list[dict[str, Any]]:
+ return [item for item in _iterate_webhooks(session, api_version) if item.get("url") == webhook_url]
+
+
+def create_webhook(username: str, password: str, api_version: str, webhook_url: str) -> WebhookCreationResult:
+ try:
+ session = _make_session(username, password)
+ response = session.post(
+ f"{api_root(api_version)}/webhooks",
+ json={"url": webhook_url, "allowedTypes": ALL_WEBHOOK_EVENTS},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ if response.status_code not in (200, 201):
+ return WebhookCreationResult(
+ success=False,
+ error=(
+ f"Fourthwall refused to create the webhook (HTTP {response.status_code}). "
+ "Please create it manually below."
+ ),
+ )
+
+ # The create response is documented to carry the shop's webhook signing secret, but the
+ # published schema for the webhook object does not list it. When it is absent, the user
+ # copies the secret from their shop's developer settings instead.
+ secret = response.json().get("secret")
+ if not secret:
+ return WebhookCreationResult(success=True, pending_inputs=["signing_secret"])
+ return WebhookCreationResult(success=True, extra_inputs={"signing_secret": secret})
+ except Exception as e:
+ return WebhookCreationResult(
+ success=False,
+ error=f"Failed to create the Fourthwall webhook: {e}. Please create it manually below.",
+ )
+
+
+def sync_webhook_events(
+ username: str, password: str, api_version: str, webhook_url: str, desired_events: list[str]
+) -> WebhookSyncResult:
+ """Add any missing `desired_events` to the shop's webhook pointing at `webhook_url`.
+
+ Events are merged rather than replaced, so a webhook a user broadened by hand keeps its
+ extra events. Fourthwall's update endpoint requires the full url plus event list.
+ """
+ try:
+ session = _make_session(username, password)
+ for webhook in _webhooks_matching(session, api_version, webhook_url):
+ current = webhook.get("allowedTypes") or []
+ merged = sorted(set(current) | set(desired_events))
+ if merged == sorted(current):
+ continue
+ response = session.put(
+ f"{api_root(api_version)}/webhooks/{webhook.get('id')}",
+ json={"url": webhook_url, "allowedTypes": merged},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ response.raise_for_status()
+ return WebhookSyncResult(success=True)
+ except Exception as e:
+ return WebhookSyncResult(success=False, error=f"Failed to update Fourthwall webhook events: {e}")
+
+
+def get_external_webhook_info(username: str, password: str, api_version: str, webhook_url: str) -> ExternalWebhookInfo:
+ try:
+ matching = _webhooks_matching(_make_session(username, password), api_version, webhook_url)
+ if not matching:
+ return ExternalWebhookInfo(exists=False)
+ return ExternalWebhookInfo(
+ exists=True,
+ url=matching[0].get("url"),
+ enabled_events=matching[0].get("allowedTypes"),
+ status="enabled",
+ )
+ except Exception as e:
+ return ExternalWebhookInfo(exists=False, error=str(e))
+
+
+def delete_webhook(username: str, password: str, api_version: str, webhook_url: str) -> WebhookDeletionResult:
+ try:
+ session = _make_session(username, password)
+ errors: list[str] = []
+ for webhook in _webhooks_matching(session, api_version, webhook_url):
+ response = session.delete(
+ f"{api_root(api_version)}/webhooks/{webhook.get('id')}", timeout=REQUEST_TIMEOUT_SECONDS
+ )
+ if response.status_code not in (200, 204):
+ errors.append(f"webhook {webhook.get('id')}: HTTP {response.status_code}")
+ if errors:
+ return WebhookDeletionResult(success=False, error="; ".join(errors))
+ return WebhookDeletionResult(success=True)
+ except Exception as e:
+ return WebhookDeletionResult(success=False, error=str(e))
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
new file mode 100644
index 000000000000..46448fecd938
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/settings.py
@@ -0,0 +1,126 @@
+from dataclasses import dataclass, field
+from typing import Literal
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
+
+BASE_URL = "https://api.fourthwall.com"
+
+# Fourthwall's list endpoints take a 0-based `page` and a `size`. The docs give a default of 20
+# and document no maximum, so 100 cuts the request count without relying on an undocumented cap.
+# No endpoint takes a sort parameter, so a row inserted while a full walk is in progress can shift
+# the offsets; a full-refresh sync would miss it and pick it up on the next run.
+PAGE_SIZE = 100
+
+
+@dataclass
+class FourthwallEndpointConfig:
+ name: str
+ # Path below `/open-api/{version}`; the version segment comes from the source's pin.
+ path: str
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Server-side lower-bound filter that matches `incremental_fields`, e.g. `updatedAt[gt]`.
+ incremental_param: str | None = None
+ partition_key: str | None = None
+ primary_key: list[str] = field(default_factory=lambda: ["id"])
+ # 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
+ sort_mode: Literal["asc", "desc"] = "asc"
+ # Webhook event types whose payload carries this table's row.
+ webhook_events: tuple[str, ...] = ()
+
+
+FOURTHWALL_ENDPOINTS: dict[str, FourthwallEndpointConfig] = {
+ "orders": FourthwallEndpointConfig(
+ name="orders",
+ path="/order",
+ # `updatedAt[gt]` is a real server-side filter and it rides every page (only `page`
+ # changes between requests), so an incremental sync fetches fewer pages rather than
+ # just changing the write disposition.
+ incremental_fields=[incremental_field("updatedAt")],
+ incremental_param="updatedAt[gt]",
+ partition_key="createdAt",
+ # Fourthwall documents no ordering for the orders list and offers no sort parameter, so
+ # we cannot claim rows arrive oldest-first. `desc` makes the pipeline finalize the
+ # watermark only after a fully successful sync, so a partial run can't advance it past
+ # orders it never fetched.
+ sort_mode="desc",
+ webhook_events=("ORDER_PLACED", "ORDER_UPDATED"),
+ ),
+ "products": FourthwallEndpointConfig(
+ name="products",
+ path="/products",
+ # The products list only filters by `search`, so there is no server-side timestamp
+ # filter to sync incrementally against.
+ partition_key="createdAt",
+ ),
+ "collections": FourthwallEndpointConfig(
+ name="collections",
+ path="/collections",
+ ),
+ "donations": FourthwallEndpointConfig(
+ name="donations",
+ path="/donations",
+ partition_key="createdAt",
+ webhook_events=("DONATION",),
+ ),
+ "members": FourthwallEndpointConfig(
+ name="members",
+ path="/memberships/members",
+ partition_key="createdAt",
+ webhook_events=("SUBSCRIPTION_PURCHASED", "SUBSCRIPTION_CHANGED", "SUBSCRIPTION_EXPIRED"),
+ ),
+ "membership_tiers": FourthwallEndpointConfig(
+ name="membership_tiers",
+ path="/memberships/tiers",
+ # Returns a bare array of tiers with no pagination parameters.
+ paginated=False,
+ ),
+ "promotions": FourthwallEndpointConfig(
+ name="promotions",
+ path="/promotions",
+ ),
+ "mailing_list_entries": FourthwallEndpointConfig(
+ name="mailing_list_entries",
+ path="/mailing-list-entries",
+ ),
+}
+
+ENDPOINTS = tuple(FOURTHWALL_ENDPOINTS)
+
+INCREMENTAL_ENDPOINTS = tuple(name for name, config in FOURTHWALL_ENDPOINTS.items() if config.incremental_fields)
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in FOURTHWALL_ENDPOINTS.items() if config.incremental_fields
+}
+
+# Only these tables are offered webhook sync: their event set covers the resource's whole
+# mutation surface and each event's `data` is the same object the list endpoint returns.
+# Product, collection and promotion events exist too, but their update payloads nest the
+# object under a differently shaped wrapper we cannot map without a live sample, so those
+# tables stay on polling.
+SCHEMA_TO_WEBHOOK_EVENTS: dict[str, list[str]] = {
+ name: list(config.webhook_events) for name, config in FOURTHWALL_ENDPOINTS.items() if config.webhook_events
+}
+
+WEBHOOK_SCHEMA_NAMES = tuple(SCHEMA_TO_WEBHOOK_EVENTS)
+
+ALL_WEBHOOK_EVENTS = sorted({event for events in SCHEMA_TO_WEBHOOK_EVENTS.values() for event in events})
+
+# Schema name -> the `schema_mapping` key incoming deliveries are routed by. Several event types
+# feed one table, so the hog template collapses the event type to this resource key first.
+SCHEMA_TO_WEBHOOK_RESOURCE: dict[str, str] = {
+ "orders": "order",
+ "donations": "donation",
+ "members": "member",
+}
+
+WEBHOOK_EVENT_TO_RESOURCE: dict[str, str] = {
+ event: SCHEMA_TO_WEBHOOK_RESOURCE[name] for name, events in SCHEMA_TO_WEBHOOK_EVENTS.items() for event in events
+}
+
+# ORDER_UPDATED wraps the order under `data.order` (the rest of the events we subscribe to put
+# the object straight in `data`), so webhook rows need unwrapping before they can merge onto the
+# table the pull path fills.
+WEBHOOK_EVENT_DATA_UNWRAP_KEY: dict[str, str] = {"ORDER_UPDATED": "order"}
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 3256c76d29fd..aad1e1bcac5b 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
@@ -1,32 +1,262 @@
-from typing import cast
+from typing import TYPE_CHECKING, Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ ExternalWebhookInfo,
+ FieldType,
+ ResumableSource,
+ WebhookCreationResult,
+ WebhookDeletionResult,
+ WebhookSource,
+ WebhookSyncResult,
+)
+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.common.webhook_s3 import WebhookSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.fourthwall import fourthwall as api_client
+from products.warehouse_sources.backend.temporal.data_imports.sources.fourthwall.fourthwall import (
+ FourthwallResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.fourthwall.settings import (
+ ENDPOINTS,
+ INCREMENTAL_ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ SCHEMA_TO_WEBHOOK_EVENTS,
+ SCHEMA_TO_WEBHOOK_RESOURCE,
+ WEBHOOK_SCHEMA_NAMES,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.fourthwall import (
FourthwallSourceConfig,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+if TYPE_CHECKING:
+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
+
+DEVELOPER_SETTINGS_HELP = (
+ "In your Fourthwall dashboard go to **Settings > For developers > Open API** and choose "
+ "**Create API User**. Only a shop super admin can do this."
+)
+
@SourceRegistry.register
-class FourthwallSource(SimpleSource[FourthwallSourceConfig]):
+class FourthwallSource(
+ ResumableSource[FourthwallSourceConfig, FourthwallResumeConfig],
+ WebhookSource[FourthwallSourceConfig],
+):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ # Every Open API path is served under `/open-api/v1.0`, which is what this source calls.
+ supported_versions = ("v1.0",)
+ default_version = "v1.0"
+ api_docs_url = "https://docs.fourthwall.com/"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.FOURTHWALL
+ @property
+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.fourthwall.webhook_template import ( # noqa: PLC0415
+ template,
+ )
+
+ return template
+
+ @property
+ def webhook_resource_map(self) -> dict[str, str]:
+ return SCHEMA_TO_WEBHOOK_RESOURCE
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": (
+ "Fourthwall rejected the API user. Recreate it under Settings > For developers and reconnect."
+ ),
+ "403 Client Error": (
+ "This Fourthwall API user is not allowed to read that data. "
+ "Recreate it under Settings > For developers and reconnect."
+ ),
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.fourthwall.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: FourthwallSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ # Orders are merge-only: `updatedAt` moves when an order changes status, so append mode
+ # would add a second row per update instead of upserting the one order.
+ return build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ merge_only=INCREMENTAL_ENDPOINTS,
+ supports_webhooks=WEBHOOK_SCHEMA_NAMES,
+ )
+
+ def validate_credentials(
+ self,
+ config: FourthwallSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return api_client.validate_credentials(config.username, config.password, self.resolve_api_version(api_version))
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FourthwallResumeConfig]:
+ return ResumableSourceManager[FourthwallResumeConfig](inputs, FourthwallResumeConfig)
+
+ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:
+ return WebhookSourceManager(inputs, inputs.logger)
+
+ def create_webhook(
+ self, config: FourthwallSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
+ ) -> WebhookCreationResult:
+ return api_client.create_webhook(
+ config.username, config.password, self.resolve_api_version(api_version), webhook_url
+ )
+
+ def get_desired_webhook_events(
+ self, config: FourthwallSourceConfig, eligible_schema_names: list[str]
+ ) -> list[str] | None:
+ return sorted({event for name in eligible_schema_names for event in SCHEMA_TO_WEBHOOK_EVENTS.get(name, [])})
+
+ def sync_webhook_events(
+ self,
+ config: FourthwallSourceConfig,
+ webhook_url: str,
+ team_id: int,
+ eligible_schema_names: list[str],
+ api_version: str | None = None,
+ ) -> WebhookSyncResult:
+ desired_events = self.get_desired_webhook_events(config, eligible_schema_names) or []
+ return api_client.sync_webhook_events(
+ config.username, config.password, self.resolve_api_version(api_version), webhook_url, desired_events
+ )
+
+ def get_external_webhook_info(
+ self, config: FourthwallSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
+ ) -> ExternalWebhookInfo | None:
+ return api_client.get_external_webhook_info(
+ config.username, config.password, self.resolve_api_version(api_version), webhook_url
+ )
+
+ def delete_webhook(
+ self, config: FourthwallSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
+ ) -> WebhookDeletionResult:
+ return api_client.delete_webhook(
+ config.username, config.password, self.resolve_api_version(api_version), webhook_url
+ )
+
+ def source_for_pipeline(
+ self,
+ config: FourthwallSourceConfig,
+ resumable_source_manager: ResumableSourceManager[FourthwallResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return api_client.fourthwall_source(
+ username=config.username,
+ password=config.password,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ api_version=self.resolve_api_version(inputs.api_version),
+ resumable_source_manager=resumable_source_manager,
+ webhook_source_manager=self.get_webhook_source_manager(inputs),
+ 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,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.FOURTHWALL,
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"
+ f"{DEVELOPER_SETTINGS_HELP}"
+ ),
+ keywords=["merch", "memberships", "creator commerce"],
+ docsUrl="https://posthog.com/docs/cdp/sources/fourthwall",
iconPath="/static/services/fourthwall.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="username",
+ label="API user username",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ caption=DEVELOPER_SETTINGS_HELP,
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="password",
+ label="API user password",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
+ webhookSetupCaption=(
+ "PostHog tries to register a webhook on your shop using the API user above, "
+ "subscribed to the order, donation and membership events.\n\n"
+ "**Manual setup** (only needed if automatic registration failed):\n\n"
+ "1. Go to **Settings > For developers > Webhooks** in your Fourthwall dashboard\n"
+ "2. Add a webhook pointing at the URL shown below\n"
+ "3. Subscribe it to `ORDER_PLACED`, `ORDER_UPDATED`, `DONATION`, "
+ "`SUBSCRIPTION_PURCHASED`, `SUBSCRIPTION_CHANGED` and `SUBSCRIPTION_EXPIRED`\n\n"
+ "Either way, copy the secret key from that same settings page into the field below "
+ "so PostHog can verify deliveries."
+ ),
+ webhookFields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="signing_secret",
+ label="Signing secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ caption=(
+ "Your shop's webhook secret key, from Settings > For developers. PostHog "
+ "uses it to verify the X-Fourthwall-Hmac-SHA256 header on every delivery."
+ ),
+ secret=True,
+ ),
+ ],
+ ),
)
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
new file mode 100644
index 000000000000..4327c79e116b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/tests/test_fourthwall.py
@@ -0,0 +1,527 @@
+import json
+from datetime import UTC, datetime
+from typing import Any, cast
+
+import pytest
+from unittest import mock
+
+from requests import Response
+
+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.fourthwall.fourthwall import (
+ FourthwallResumeConfig,
+ _format_datetime,
+ create_webhook,
+ delete_webhook,
+ fourthwall_source,
+ get_external_webhook_info,
+ get_resource,
+ sync_webhook_events,
+ validate_credentials,
+ webhook_table_transformer,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.fourthwall.settings import (
+ ALL_WEBHOOK_EVENTS,
+ ENDPOINTS,
+ FOURTHWALL_ENDPOINTS,
+ PAGE_SIZE,
+)
+
+SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.fourthwall.fourthwall.make_tracked_session"
+)
+REST_RESOURCE_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.fourthwall.fourthwall.rest_api_resource"
+)
+API_ROOT = "https://api.fourthwall.com/open-api/v1.0"
+
+
+def _page(results: list[dict[str, Any]], total_pages: int) -> Response:
+ response = Response()
+ response.status_code = 200
+ response._content = json.dumps(
+ {"results": results, "total": len(results), "page": 0, "size": PAGE_SIZE, "totalPages": total_pages}
+ ).encode()
+ return response
+
+
+def _bare(items: list[dict[str, Any]]) -> Response:
+ response = Response()
+ response.status_code = 200
+ response._content = json.dumps(items).encode()
+ return response
+
+
+def _make_manager(resume_state: FourthwallResumeConfig | 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, snapshotting each request at prepare time (params mutate per page)."""
+ session.headers = {}
+ snapshots: list[dict[str, Any]] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ snapshots.append({"url": request.url, "params": dict(request.params or {})})
+ prepared = mock.MagicMock()
+ prepared.url = request.url
+ return prepared
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return snapshots
+
+
+def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any):
+ return fourthwall_source(
+ "api-user",
+ "api-secret",
+ endpoint,
+ team_id=1,
+ job_id="job-1",
+ api_version="v1.0",
+ resumable_source_manager=manager,
+ **kwargs,
+ )
+
+
+def _rows(source_response) -> list[dict[str, Any]]:
+ return [row for page in source_response.items() for row in page]
+
+
+def _order(order_id: str, updated_at: str = "2026-05-01T10:00:00.000Z") -> dict[str, Any]:
+ return {"id": order_id, "status": "CONFIRMED", "createdAt": "2026-04-01T10:00:00.000Z", "updatedAt": updated_at}
+
+
+class TestFormatDatetime:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2026, 5, 1, 10, 30, 15, 123456, tzinfo=UTC), "2026-05-01T10:30:15Z"),
+ # Naive values are treated as UTC, matching the rest of the pipeline.
+ (datetime(2026, 5, 1, 10, 30, 15), "2026-05-01T10:30:15Z"),
+ ],
+ )
+ def test_truncates_to_whole_seconds_in_utc(self, value, expected):
+ # Rounding the lower bound down re-reads a few boundary orders (merge dedupes them)
+ # instead of skipping an order whose updatedAt equals the watermark.
+ assert _format_datetime(value) == expected
+
+ def test_non_datetime_passes_through_as_string(self):
+ assert _format_datetime("2026-05-01T10:30:15Z") == "2026-05-01T10:30:15Z"
+
+
+def _endpoint_config(endpoint: str, should_use_incremental_field: bool = False) -> dict[str, Any]:
+ return cast("dict[str, Any]", get_resource(endpoint, should_use_incremental_field)["endpoint"])
+
+
+class TestGetResource:
+ @pytest.mark.parametrize("endpoint", [name for name in ENDPOINTS if FOURTHWALL_ENDPOINTS[name].paginated])
+ def test_paginated_endpoints_select_the_results_envelope(self, endpoint):
+ endpoint_config = _endpoint_config(endpoint)
+
+ assert endpoint_config["data_selector"] == "results"
+ assert endpoint_config["params"]["size"] == PAGE_SIZE
+ assert endpoint_config["path"] == FOURTHWALL_ENDPOINTS[endpoint].path
+
+ @pytest.mark.parametrize("endpoint", [name for name in ENDPOINTS if not FOURTHWALL_ENDPOINTS[name].paginated])
+ def test_bare_array_endpoints_take_no_selector_and_a_single_page(self, endpoint):
+ # A `results` selector here would match nothing and sync zero rows.
+ endpoint_config = _endpoint_config(endpoint)
+
+ assert "data_selector" not in endpoint_config
+ assert endpoint_config["paginator"] == "single_page"
+
+ @pytest.mark.parametrize(
+ "endpoint, should_use_incremental_field, expected_disposition",
+ [
+ ("orders", True, {"disposition": "merge", "strategy": "upsert"}),
+ ("orders", False, "replace"),
+ # products has no server-side timestamp filter, so it stays a full replace even
+ # when the pipeline asks for an incremental run.
+ ("products", True, "replace"),
+ ],
+ )
+ def test_write_disposition_follows_real_incremental_support(
+ self, endpoint, should_use_incremental_field, expected_disposition
+ ):
+ resource = get_resource(endpoint, should_use_incremental_field=should_use_incremental_field)
+ assert resource["write_disposition"] == expected_disposition
+
+ def test_only_orders_declares_a_server_side_incremental_filter(self):
+ # Declaring an incremental param an endpoint doesn't support would send a filter the
+ # API ignores, turning every "incremental" sync back into a full scan.
+ with_param = {name for name, config in FOURTHWALL_ENDPOINTS.items() if config.incremental_param}
+ assert with_param == {"orders"}
+ assert FOURTHWALL_ENDPOINTS["orders"].incremental_param == "updatedAt[gt]"
+
+
+class TestPagination:
+ @mock.patch(SESSION_PATCH)
+ def test_walks_pages_until_total_pages(self, MockSession):
+ session = MockSession.return_value
+ requests_seen = _wire(session, [_page([_order("1")], 2), _page([_order("2")], 2)])
+
+ manager = _make_manager()
+ rows = _rows(_source("orders", manager))
+
+ assert [row["id"] for row in rows] == ["1", "2"]
+ assert [request["params"]["page"] for request in requests_seen] == [0, 1]
+ assert all(request["params"]["size"] == PAGE_SIZE for request in requests_seen)
+ # Checkpointed only while a next page remains, after the page was yielded.
+ assert manager.save_state.call_count == 1
+ assert manager.save_state.call_args.args[0] == FourthwallResumeConfig(paginator_state={"page": 1})
+
+ @mock.patch(SESSION_PATCH)
+ def test_resumes_from_saved_page(self, MockSession):
+ session = MockSession.return_value
+ requests_seen = _wire(session, [_page([_order("9")], 4)])
+
+ rows = _rows(_source("orders", _make_manager(FourthwallResumeConfig(paginator_state={"page": 3}))))
+
+ assert [row["id"] for row in rows] == ["9"]
+ assert requests_seen[0]["params"]["page"] == 3
+
+ @mock.patch(SESSION_PATCH)
+ def test_bare_array_endpoint_yields_body_rows_without_pagination(self, MockSession):
+ session = MockSession.return_value
+ requests_seen = _wire(session, [_bare([{"id": "tier_1", "name": "Gold"}])])
+
+ rows = _rows(_source("membership_tiers", _make_manager()))
+
+ assert rows == [{"id": "tier_1", "name": "Gold"}]
+ assert len(requests_seen) == 1
+
+
+class TestIncrementalRequests:
+ @mock.patch(SESSION_PATCH)
+ def test_incremental_sync_sends_the_watermark_on_every_page(self, MockSession):
+ session = MockSession.return_value
+ requests_seen = _wire(session, [_page([_order("1")], 2), _page([_order("2")], 2)])
+
+ _rows(
+ _source(
+ "orders",
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 5, 1, 10, 0, 0, tzinfo=UTC),
+ )
+ )
+
+ # The filter has to ride every page, otherwise later pages walk the full history.
+ assert [request["params"].get("updatedAt[gt]") for request in requests_seen] == [
+ "2026-05-01T10:00:00Z",
+ "2026-05-01T10:00:00Z",
+ ]
+
+ @mock.patch(SESSION_PATCH)
+ def test_first_incremental_sync_starts_from_the_epoch(self, MockSession):
+ session = MockSession.return_value
+ requests_seen = _wire(session, [_page([_order("1")], 1)])
+
+ _rows(_source("orders", _make_manager(), should_use_incremental_field=True))
+
+ assert requests_seen[0]["params"]["updatedAt[gt]"] == "1970-01-01T00:00:00Z"
+
+ @mock.patch(SESSION_PATCH)
+ def test_full_refresh_sends_no_timestamp_filter(self, MockSession):
+ session = MockSession.return_value
+ requests_seen = _wire(session, [_page([_order("1")], 1)])
+
+ _rows(_source("orders", _make_manager()))
+
+ assert "updatedAt[gt]" not in requests_seen[0]["params"]
+
+
+class TestSourceResponseMetadata:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ @mock.patch(REST_RESOURCE_PATCH)
+ def test_metadata_matches_the_endpoint_catalog(self, mock_rest_api_resource, endpoint):
+ config = FOURTHWALL_ENDPOINTS[endpoint]
+
+ 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"]
+ 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)
+
+ def test_orders_finalize_the_watermark_only_after_a_full_sync(self):
+ # Fourthwall documents no ordering for the orders list and takes no sort parameter, so
+ # `asc` would checkpoint the watermark to whatever the first page happened to contain.
+ assert FOURTHWALL_ENDPOINTS["orders"].sort_mode == "desc"
+
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_partition_keys_never_move(self, endpoint):
+ # A partition key that changes rewrites partitions on every sync.
+ assert FOURTHWALL_ENDPOINTS[endpoint].partition_key in (None, "createdAt")
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected_valid",
+ [(200, True), (401, False), (403, False), (404, False), (429, False), (500, False)],
+ )
+ @mock.patch(SESSION_PATCH)
+ def test_status_mapping(self, MockSession, status_code, expected_valid):
+ MockSession.return_value.get.return_value = mock.MagicMock(status_code=status_code)
+
+ is_valid, error = validate_credentials("api-user", "api-secret", "v1.0")
+
+ assert is_valid is expected_valid
+ assert (error is None) is expected_valid
+
+ @mock.patch(SESSION_PATCH)
+ def test_probes_the_shop_endpoint_on_the_pinned_version(self, MockSession):
+ session = MockSession.return_value
+ session.get.return_value = mock.MagicMock(status_code=200)
+
+ validate_credentials("api-user", "api-secret", "v1.0")
+
+ assert session.get.call_args.args[0] == f"{API_ROOT}/shops/current"
+ assert session.auth == ("api-user", "api-secret")
+
+
+class TestWebhookTableTransformer:
+ def _table(self, events: list[dict[str, Any]]):
+ return table_from_py_list(events)
+
+ def test_lifts_the_resource_out_of_the_event_envelope(self):
+ table = self._table(
+ [
+ {
+ "id": "weve_1",
+ "type": "ORDER_PLACED",
+ "createdAt": "2026-05-01T10:00:00+00:00",
+ "data": _order("order_1"),
+ }
+ ]
+ )
+
+ rows = webhook_table_transformer(table).to_pylist()
+
+ assert [row["id"] for row in rows] == ["order_1"]
+ assert rows[0]["status"] == "CONFIRMED"
+
+ def test_unwraps_the_nested_order_on_order_updated(self):
+ # ORDER_UPDATED nests the order under `data.order`; without unwrapping, the row would
+ # carry the wrapper's shape and never merge onto the orders table.
+ table = self._table(
+ [
+ {
+ "id": "weve_1",
+ "type": "ORDER_UPDATED",
+ "createdAt": "2026-05-01T10:00:00+00:00",
+ "data": {"order": _order("order_1"), "update": {"type": "STATUS"}},
+ }
+ ]
+ )
+
+ rows = webhook_table_transformer(table).to_pylist()
+
+ assert [row["id"] for row in rows] == ["order_1"]
+
+ def test_keeps_only_the_newest_event_per_object(self):
+ # Delta merge dedupes across syncs but not within one batch, so a placed-then-updated
+ # pair for the same order has to collapse here.
+ table = self._table(
+ [
+ {
+ "id": "weve_1",
+ "type": "ORDER_PLACED",
+ "createdAt": "2026-05-01T10:00:00+00:00",
+ "data": _order("order_1", updated_at="2026-05-01T10:00:00.000Z"),
+ },
+ {
+ "id": "weve_2",
+ "type": "ORDER_UPDATED",
+ "createdAt": "2026-05-02T10:00:00+00:00",
+ "data": {"order": _order("order_1", updated_at="2026-05-02T10:00:00.000Z")},
+ },
+ ]
+ )
+
+ rows = webhook_table_transformer(table).to_pylist()
+
+ assert len(rows) == 1
+ assert rows[0]["updatedAt"] == "2026-05-02T10:00:00.000Z"
+
+ def test_out_of_order_delivery_still_keeps_the_newest(self):
+ table = self._table(
+ [
+ {
+ "id": "weve_2",
+ "type": "ORDER_UPDATED",
+ "createdAt": "2026-05-02T10:00:00+00:00",
+ "data": {"order": _order("order_1", updated_at="2026-05-02T10:00:00.000Z")},
+ },
+ {
+ "id": "weve_1",
+ "type": "ORDER_PLACED",
+ "createdAt": "2026-05-01T10:00:00+00:00",
+ "data": _order("order_1", updated_at="2026-05-01T10:00:00.000Z"),
+ },
+ ]
+ )
+
+ rows = webhook_table_transformer(table).to_pylist()
+
+ assert len(rows) == 1
+ assert rows[0]["updatedAt"] == "2026-05-02T10:00:00.000Z"
+
+ @pytest.mark.parametrize(
+ "event",
+ [
+ {"id": "weve_1", "type": "ORDER_PLACED", "createdAt": "2026-05-01T10:00:00+00:00", "data": {}},
+ {"id": "weve_1", "type": "ORDER_UPDATED", "createdAt": "2026-05-01T10:00:00+00:00", "data": {}},
+ ],
+ )
+ def test_drops_payloads_with_no_object_id(self, event):
+ # A row with no primary key would break the merge, so it must never reach the table.
+ assert webhook_table_transformer(self._table([event])).num_rows == 0
+
+ def test_empty_delivery_batch_yields_no_rows(self):
+ assert webhook_table_transformer(table_from_py_list([{"unexpected": 1}])).num_rows == 0
+
+
+class TestWebhookManagement:
+ def _session(self, MockSession) -> mock.MagicMock:
+ return MockSession.return_value
+
+ def _webhook_page(self, results: list[dict[str, Any]], total_pages: int = 1) -> mock.MagicMock:
+ response = mock.MagicMock(status_code=200)
+ response.json.return_value = {"results": results, "totalPages": total_pages}
+ return response
+
+ @mock.patch(SESSION_PATCH)
+ def test_create_webhook_stores_the_returned_secret(self, MockSession):
+ session = self._session(MockSession)
+ session.post.return_value = mock.MagicMock(status_code=200)
+ session.post.return_value.json.return_value = {"id": "wcon_1", "secret": "shhh"}
+
+ result = create_webhook("api-user", "api-secret", "v1.0", "https://us.posthog.com/w/1")
+
+ assert result.success is True
+ assert result.extra_inputs == {"signing_secret": "shhh"}
+ assert session.post.call_args.args[0] == f"{API_ROOT}/webhooks"
+ assert session.post.call_args.kwargs["json"] == {
+ "url": "https://us.posthog.com/w/1",
+ "allowedTypes": ALL_WEBHOOK_EVENTS,
+ }
+
+ @mock.patch(SESSION_PATCH)
+ def test_create_webhook_asks_for_the_secret_when_the_response_omits_it(self, MockSession):
+ # The published webhook schema does not list `secret`, so the user has to paste it;
+ # silently succeeding without it would leave every delivery failing the signature check.
+ session = self._session(MockSession)
+ session.post.return_value = mock.MagicMock(status_code=200)
+ session.post.return_value.json.return_value = {"id": "wcon_1"}
+
+ result = create_webhook("api-user", "api-secret", "v1.0", "https://us.posthog.com/w/1")
+
+ assert result.success is True
+ assert result.pending_inputs == ["signing_secret"]
+ assert result.extra_inputs == {}
+
+ @pytest.mark.parametrize("status_code", [400, 401, 429])
+ @mock.patch(SESSION_PATCH)
+ def test_create_webhook_reports_a_rejected_registration(self, MockSession, status_code):
+ session = self._session(MockSession)
+ session.post.return_value = mock.MagicMock(status_code=status_code)
+
+ result = create_webhook("api-user", "api-secret", "v1.0", "https://us.posthog.com/w/1")
+
+ assert result.success is False
+ assert result.error is not None
+
+ @mock.patch(SESSION_PATCH)
+ def test_sync_webhook_events_merges_instead_of_replacing(self, MockSession):
+ # Replacing would wipe events a user added by hand in the Fourthwall dashboard.
+ session = self._session(MockSession)
+ session.get.return_value = self._webhook_page(
+ [{"id": "wcon_1", "url": "https://us.posthog.com/w/1", "allowedTypes": ["THANK_YOU_SENT"]}]
+ )
+
+ result = sync_webhook_events("api-user", "api-secret", "v1.0", "https://us.posthog.com/w/1", ["ORDER_PLACED"])
+
+ assert result.success is True
+ assert session.put.call_args.kwargs["json"] == {
+ "url": "https://us.posthog.com/w/1",
+ "allowedTypes": ["ORDER_PLACED", "THANK_YOU_SENT"],
+ }
+
+ @mock.patch(SESSION_PATCH)
+ def test_sync_webhook_events_skips_an_already_correct_webhook(self, MockSession):
+ session = self._session(MockSession)
+ session.get.return_value = self._webhook_page(
+ [{"id": "wcon_1", "url": "https://us.posthog.com/w/1", "allowedTypes": ["ORDER_PLACED"]}]
+ )
+
+ sync_webhook_events("api-user", "api-secret", "v1.0", "https://us.posthog.com/w/1", ["ORDER_PLACED"])
+
+ session.put.assert_not_called()
+
+ @mock.patch(SESSION_PATCH)
+ def test_webhook_lookup_walks_every_page(self, MockSession):
+ # Stopping after page one would silently skip a shop's webhook and leave a stale
+ # registration behind on delete.
+ session = self._session(MockSession)
+ session.get.side_effect = [
+ self._webhook_page([{"id": "wcon_1", "url": "https://other", "allowedTypes": []}], total_pages=2),
+ self._webhook_page(
+ [{"id": "wcon_2", "url": "https://us.posthog.com/w/1", "allowedTypes": []}], total_pages=2
+ ),
+ ]
+ session.delete.return_value = mock.MagicMock(status_code=200)
+
+ result = delete_webhook("api-user", "api-secret", "v1.0", "https://us.posthog.com/w/1")
+
+ assert result.success is True
+ assert session.delete.call_args.args[0] == f"{API_ROOT}/webhooks/wcon_2"
+
+ @mock.patch(SESSION_PATCH)
+ def test_delete_webhook_reports_a_failed_deletion(self, MockSession):
+ session = self._session(MockSession)
+ session.get.return_value = self._webhook_page(
+ [{"id": "wcon_1", "url": "https://us.posthog.com/w/1", "allowedTypes": []}]
+ )
+ session.delete.return_value = mock.MagicMock(status_code=500)
+
+ result = delete_webhook("api-user", "api-secret", "v1.0", "https://us.posthog.com/w/1")
+
+ assert result.success is False
+
+ @mock.patch(SESSION_PATCH)
+ def test_external_webhook_info_matches_on_url(self, MockSession):
+ session = self._session(MockSession)
+ session.get.return_value = self._webhook_page(
+ [
+ {"id": "wcon_1", "url": "https://elsewhere", "allowedTypes": ["DONATION"]},
+ {"id": "wcon_2", "url": "https://us.posthog.com/w/1", "allowedTypes": ["ORDER_PLACED"]},
+ ]
+ )
+
+ info = get_external_webhook_info("api-user", "api-secret", "v1.0", "https://us.posthog.com/w/1")
+
+ assert info.exists is True
+ assert info.enabled_events == ["ORDER_PLACED"]
+
+ @mock.patch(SESSION_PATCH)
+ def test_external_webhook_info_when_absent(self, MockSession):
+ self._session(MockSession).get.return_value = self._webhook_page([])
+
+ assert get_external_webhook_info("api-user", "api-secret", "v1.0", "https://us.posthog.com/w/1").exists is False
+
+ @mock.patch(SESSION_PATCH)
+ def test_webhook_helpers_surface_transport_failures(self, MockSession):
+ self._session(MockSession).get.side_effect = Exception("boom")
+
+ assert get_external_webhook_info("api-user", "api-secret", "v1.0", "https://u/1").error == "boom"
+ assert sync_webhook_events("api-user", "api-secret", "v1.0", "https://u/1", []).success is False
+ assert delete_webhook("api-user", "api-secret", "v1.0", "https://u/1").success is False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/tests/test_fourthwall_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/tests/test_fourthwall_source.py
new file mode 100644
index 000000000000..704dc5c9deaa
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/tests/test_fourthwall_source.py
@@ -0,0 +1,237 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.fourthwall.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.fourthwall.fourthwall import (
+ FourthwallResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.fourthwall.settings import (
+ ALL_WEBHOOK_EVENTS,
+ ENDPOINTS,
+ INCREMENTAL_ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ SCHEMA_TO_WEBHOOK_EVENTS,
+ SCHEMA_TO_WEBHOOK_RESOURCE,
+ WEBHOOK_EVENT_TO_RESOURCE,
+ WEBHOOK_SCHEMA_NAMES,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.fourthwall.source import FourthwallSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.fourthwall.webhook_template import template
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.fourthwall import (
+ FourthwallSourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+API_CLIENT_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.fourthwall.source.api_client"
+WEBHOOK_URL = "https://us.posthog.com/public/webhooks/abc"
+
+
+class TestFourthwallSource:
+ def setup_method(self):
+ self.source = FourthwallSource()
+ self.team_id = 123
+ self.config = FourthwallSourceConfig(username="api-user", password="api-secret")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.FOURTHWALL
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Fourthwall"
+ assert config.label == "Fourthwall"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # unreleasedSource hides the connector from every user.
+ assert not config.unreleasedSource
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/fourthwall"
+
+ @pytest.mark.parametrize(
+ "field_name, expected_type, expected_secret",
+ [
+ ("username", SourceFieldInputConfigType.TEXT, False),
+ ("password", SourceFieldInputConfigType.PASSWORD, True),
+ ],
+ )
+ def test_credential_fields(self, field_name, expected_type, expected_secret):
+ # The API user's password is a full-access shop credential; storing it unmasked would
+ # expose it in the source list.
+ field = next(
+ f
+ for f in self.source.get_source_config.fields
+ if isinstance(f, SourceFieldInputConfig) and f.name == field_name
+ )
+ assert field.type == expected_type
+ assert field.secret is expected_secret
+ assert field.required is True
+
+ def test_webhook_fields_include_a_secret_signing_secret(self):
+ config = self.source.get_source_config
+ assert config.webhookFields is not None
+ field = next(
+ f for f in config.webhookFields if isinstance(f, SourceFieldInputConfig) and f.name == "signing_secret"
+ )
+ assert field.secret is True
+
+ def test_api_version_matches_the_path_the_code_calls(self):
+ # The pin has to name the version the requests actually use, or the deprecation and
+ # upgrade paths point at the wrong API.
+ assert self.source.supported_versions == ("v1.0",)
+ assert self.source.resolve_api_version(None) == "v1.0"
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.fourthwall.com/open-api/v1.0/order?page=0",
+ "403 Client Error: Forbidden for url: https://api.fourthwall.com/open-api/v1.0/donations",
+ ],
+ )
+ def test_auth_failures_are_non_retryable(self, observed_error):
+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "429 Client Error: Too Many Requests for url: https://api.fourthwall.com/open-api/v1.0/order",
+ "500 Server Error for url: https://api.fourthwall.com/open-api/v1.0/order",
+ ],
+ )
+ def test_transient_failures_stay_retryable(self, other_error):
+ assert not any(key in other_error for key in self.source.get_non_retryable_errors())
+
+ def test_get_schemas_lists_every_endpoint(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ def test_only_orders_supports_incremental(self):
+ # Advertising incremental on an endpoint with no server-side timestamp filter would
+ # fetch every page anyway while pretending the sync got cheaper.
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+ incremental = {name for name, schema in schemas.items() if schema.supports_incremental}
+ assert incremental == set(INCREMENTAL_ENDPOINTS) == {"orders"}
+ assert schemas["orders"].incremental_fields == INCREMENTAL_FIELDS["orders"]
+
+ def test_incremental_schemas_are_merge_only(self):
+ # `updatedAt` moves whenever an order changes status, so append would add a row per
+ # update instead of upserting the order.
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+ assert schemas["orders"].supports_append is False
+
+ def test_webhook_capable_schemas(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+ assert {name for name, schema in schemas.items() if schema.supports_webhooks} == set(WEBHOOK_SCHEMA_NAMES)
+ assert all(not schema.webhook_only for schema in schemas.values())
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["donations"])
+ assert [schema.name for schema in schemas] == ["donations"]
+
+ def test_canonical_descriptions_cover_declared_tables_only(self):
+ # A key that isn't a schema name is never applied, so the table silently falls back to
+ # the LLM description we paid to avoid.
+ assert set(CANONICAL_DESCRIPTIONS) == set(ENDPOINTS)
+ assert self.source.get_canonical_descriptions() is CANONICAL_DESCRIPTIONS
+
+ @pytest.mark.parametrize(
+ "client_result, expected",
+ [((True, None), True), ((False, "Fourthwall rejected the API user."), False)],
+ )
+ @mock.patch(f"{API_CLIENT_PATCH}.validate_credentials")
+ def test_validate_credentials(self, mock_validate, client_result, expected):
+ mock_validate.return_value = client_result
+
+ is_valid, error = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected
+ assert (error is None) is expected
+ mock_validate.assert_called_once_with("api-user", "api-secret", "v1.0")
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is FourthwallResumeConfig
+
+ @mock.patch(f"{API_CLIENT_PATCH}.fourthwall_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "orders"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-05-01T00:00:00Z"
+ inputs.api_version = None
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["username"] == "api-user"
+ assert kwargs["password"] == "api-secret"
+ assert kwargs["endpoint"] == "orders"
+ assert kwargs["api_version"] == "v1.0"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["webhook_source_manager"] is not None
+ assert kwargs["db_incremental_field_last_value"] == "2026-05-01T00:00:00Z"
+
+ @mock.patch(f"{API_CLIENT_PATCH}.fourthwall_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_source):
+ # Passing a watermark through on a full refresh would inject a filter the user never
+ # asked for and truncate the table.
+ inputs = mock.MagicMock()
+ inputs.schema_name = "products"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-05-01T00:00:00Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_webhook_resource_map_covers_the_webhook_schemas(self):
+ assert self.source.webhook_resource_map == SCHEMA_TO_WEBHOOK_RESOURCE
+ assert set(SCHEMA_TO_WEBHOOK_RESOURCE) == set(WEBHOOK_SCHEMA_NAMES)
+
+ def test_webhook_template_resource_keys_match_the_settings_mapping(self):
+ # The hog template carries its own event -> resource dict; a schema mapped to a key the
+ # template never emits would drop every delivery for that table.
+ for event, resource in WEBHOOK_EVENT_TO_RESOURCE.items():
+ assert f"'{event}': '{resource}'" in template.code
+
+ def test_webhook_template_declares_the_inputs_the_source_sets(self):
+ assert template.type == "warehouse_source_webhook"
+ input_keys = {input_schema["key"] for input_schema in template.inputs_schema}
+ assert {"signing_secret", "schema_mapping", "source_id"} <= input_keys
+
+ def test_get_desired_webhook_events_covers_eligible_schemas_only(self):
+ events = self.source.get_desired_webhook_events(self.config, ["orders", "donations"])
+ assert events == sorted(SCHEMA_TO_WEBHOOK_EVENTS["orders"] + SCHEMA_TO_WEBHOOK_EVENTS["donations"])
+
+ def test_get_desired_webhook_events_ignores_polling_only_schemas(self):
+ assert self.source.get_desired_webhook_events(self.config, ["products"]) == []
+
+ def test_all_webhook_events_is_the_union_of_the_schema_events(self):
+ assert set(ALL_WEBHOOK_EVENTS) == set(WEBHOOK_EVENT_TO_RESOURCE)
+
+ @mock.patch(f"{API_CLIENT_PATCH}.create_webhook")
+ def test_create_webhook_delegates(self, mock_create):
+ self.source.create_webhook(self.config, WEBHOOK_URL, self.team_id)
+ mock_create.assert_called_once_with("api-user", "api-secret", "v1.0", WEBHOOK_URL)
+
+ @mock.patch(f"{API_CLIENT_PATCH}.delete_webhook")
+ def test_delete_webhook_delegates(self, mock_delete):
+ self.source.delete_webhook(self.config, WEBHOOK_URL, self.team_id)
+ mock_delete.assert_called_once_with("api-user", "api-secret", "v1.0", WEBHOOK_URL)
+
+ @mock.patch(f"{API_CLIENT_PATCH}.get_external_webhook_info")
+ def test_get_external_webhook_info_delegates(self, mock_info):
+ self.source.get_external_webhook_info(self.config, WEBHOOK_URL, self.team_id)
+ mock_info.assert_called_once_with("api-user", "api-secret", "v1.0", WEBHOOK_URL)
+
+ @mock.patch(f"{API_CLIENT_PATCH}.sync_webhook_events")
+ def test_sync_webhook_events_passes_desired_events(self, mock_sync):
+ self.source.sync_webhook_events(self.config, WEBHOOK_URL, self.team_id, ["donations"])
+ mock_sync.assert_called_once_with(
+ "api-user", "api-secret", "v1.0", WEBHOOK_URL, sorted(SCHEMA_TO_WEBHOOK_EVENTS["donations"])
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/tests/test_fourthwall_webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/tests/test_fourthwall_webhook_template.py
new file mode 100644
index 000000000000..1afca8425fba
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/tests/test_fourthwall_webhook_template.py
@@ -0,0 +1,162 @@
+import hmac
+import json
+import base64
+import hashlib
+
+from parameterized import parameterized
+
+from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.fourthwall.webhook_template import template
+
+SOURCE_ID = "source_test_123"
+SIGNING_SECRET = "e3f93c7c-c92b-4b8f-a9b1-5b70e0891abc"
+SCHEMA_MAPPING = {"order": "schema_orders", "donation": "schema_donations", "member": "schema_members"}
+
+
+class TestFourthwallWarehouseWebhookTemplate(BaseHogFunctionTemplateTest):
+ template = template
+
+ def createHogGlobals(self, globals=None) -> dict:
+ data: dict = {
+ "request": {
+ "method": "POST",
+ "headers": {},
+ "body": {},
+ "query": {},
+ "stringBody": "",
+ "ip": "127.0.0.1",
+ },
+ }
+ if globals and globals.get("request"):
+ data["request"].update(globals["request"])
+ return data
+
+ def _event(self, event_type: str = "ORDER_PLACED") -> dict:
+ return {
+ "id": "weve_1",
+ "webhookId": "wcon_1",
+ "shopId": "sh_1",
+ "type": event_type,
+ "apiVersion": "V1",
+ "createdAt": "2026-05-01T10:00:00+00:00",
+ "testMode": False,
+ "data": {"id": "order_1", "status": "CONFIRMED"},
+ }
+
+ def _request(self, secret: str, body: dict, method: str = "POST") -> dict:
+ payload = json.dumps(body)
+ signature = base64.b64encode(hmac.new(secret.encode(), payload.encode(), hashlib.sha256).digest()).decode()
+ return {
+ "request": {
+ "method": method,
+ "headers": {"x-fourthwall-hmac-sha256": signature},
+ "body": json.loads(payload),
+ "stringBody": payload,
+ "query": {},
+ }
+ }
+
+ def _inputs(self, **overrides) -> dict:
+ return {
+ "signing_secret": SIGNING_SECRET,
+ "bypass_signature_check": False,
+ "schema_mapping": SCHEMA_MAPPING,
+ "source_id": SOURCE_ID,
+ **overrides,
+ }
+
+ @parameterized.expand(
+ [
+ ("ORDER_PLACED", "schema_orders"),
+ ("ORDER_UPDATED", "schema_orders"),
+ ("DONATION", "schema_donations"),
+ ("SUBSCRIPTION_PURCHASED", "schema_members"),
+ ("SUBSCRIPTION_CHANGED", "schema_members"),
+ ("SUBSCRIPTION_EXPIRED", "schema_members"),
+ ]
+ )
+ def test_routes_each_subscribed_event_to_its_table(self, event_type, expected_schema_id):
+ # Fourthwall signs with base64, not hex; a hex comparison would reject every delivery.
+ globals = self._request(SIGNING_SECRET, self._event(event_type))
+
+ self.run_function(self._inputs(), globals=globals)
+
+ self.mock_produce_to_warehouse_webhooks.assert_called_once_with(globals["request"]["body"], expected_schema_id)
+
+ def test_unsubscribed_event_is_acknowledged_and_dropped(self):
+ # Fourthwall delivers every event the webhook is subscribed to; an unmapped one must
+ # not 500 the endpoint into a retry storm.
+ globals = self._request(SIGNING_SECRET, self._event("THANK_YOU_SENT"))
+
+ res = self.run_function(self._inputs(), globals=globals)
+
+ assert res.result["httpResponse"]["status"] == 200
+ self.mock_produce_to_warehouse_webhooks.assert_not_called()
+
+ def test_event_for_a_table_the_user_did_not_enable_is_dropped(self):
+ globals = self._request(SIGNING_SECRET, self._event("DONATION"))
+
+ res = self.run_function(self._inputs(schema_mapping={"order": "schema_orders"}), globals=globals)
+
+ assert res.result["httpResponse"]["status"] == 200
+ self.mock_produce_to_warehouse_webhooks.assert_not_called()
+
+ def test_bad_signature_is_rejected(self):
+ globals = self._request("some-other-secret", self._event())
+
+ res = self.run_function(self._inputs(), globals=globals)
+
+ assert res.result == {"httpResponse": {"status": 400, "body": "Bad signature"}}
+ self.mock_produce_to_warehouse_webhooks.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("missing_signature", {}, {"signing_secret": SIGNING_SECRET}, "Missing signature"),
+ (
+ "no_secret_configured",
+ {"x-fourthwall-hmac-sha256": "x"},
+ {"signing_secret": ""},
+ "Signing secret not configured",
+ ),
+ ]
+ )
+ def test_unverifiable_delivery_is_rejected(self, _name, headers, input_overrides, expected_body):
+ body = self._event()
+ globals = {
+ "request": {
+ "method": "POST",
+ "headers": headers,
+ "body": body,
+ "stringBody": json.dumps(body),
+ "query": {},
+ }
+ }
+
+ res = self.run_function(self._inputs(**input_overrides), globals=globals)
+
+ assert res.result == {"httpResponse": {"status": 400, "body": expected_body}}
+ self.mock_produce_to_warehouse_webhooks.assert_not_called()
+
+ def test_non_post_request_returns_405(self):
+ globals = self._request(SIGNING_SECRET, self._event(), method="GET")
+
+ res = self.run_function(self._inputs(), globals=globals)
+
+ assert res.result == {"httpResponse": {"status": 405, "body": "Method not allowed"}}
+
+ def test_bypass_signature_check_still_routes(self):
+ body = self._event()
+ globals = {
+ "request": {
+ "method": "POST",
+ "headers": {},
+ "body": body,
+ "stringBody": json.dumps(body),
+ "query": {},
+ }
+ }
+
+ self.run_function(self._inputs(signing_secret="", bypass_signature_check=True), globals=globals)
+
+ self.mock_produce_to_warehouse_webhooks.assert_called_once_with(body, "schema_orders")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/webhook_template.py
new file mode 100644
index 000000000000..27da01dd2da3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fourthwall/webhook_template.py
@@ -0,0 +1,144 @@
+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
+
+template: HogFunctionTemplateDC = HogFunctionTemplateDC(
+ status="alpha",
+ free=False,
+ type="warehouse_source_webhook",
+ id="template-warehouse-source-fourthwall",
+ name="Fourthwall warehouse source webhook",
+ description="Receive Fourthwall webhook events for data warehouse ingestion",
+ icon_url="/static/services/fourthwall.png",
+ category=["Data warehouse"],
+ code_language="hog",
+ code="""\
+if (request.method != 'POST') {
+ return {
+ 'httpResponse': {
+ 'status': 405,
+ 'body': 'Method not allowed'
+ }
+ }
+}
+
+if (not inputs.bypass_signature_check) {
+ if (empty(inputs.signing_secret)) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Signing secret not configured',
+ }
+ }
+ }
+
+ let signature := request.headers['x-fourthwall-hmac-sha256']
+
+ if (empty(signature)) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Missing signature',
+ }
+ }
+ }
+
+ // Fourthwall sends the base64-encoded HMAC-SHA256 of the raw request body, keyed by the
+ // shop's webhook secret. No timestamp is involved.
+ let computedSignature := sha256HmacChain([inputs.signing_secret, request.stringBody], 'base64')
+
+ if (computedSignature != signature) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Bad signature',
+ }
+ }
+ }
+}
+
+let eventType := request.body.type
+
+if (empty(eventType)) {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': 'No event type found, skipping'
+ }
+ }
+}
+
+// Several event types feed one warehouse table, so the event is collapsed to a resource key
+// before the schema lookup. Keep this in sync with WEBHOOK_EVENT_TO_RESOURCE in settings.py.
+let resourceByEvent := {
+ 'ORDER_PLACED': 'order',
+ 'ORDER_UPDATED': 'order',
+ 'DONATION': 'donation',
+ 'SUBSCRIPTION_PURCHASED': 'member',
+ 'SUBSCRIPTION_CHANGED': 'member',
+ 'SUBSCRIPTION_EXPIRED': 'member',
+}
+
+let resource := resourceByEvent?.[eventType]
+
+if (empty(resource)) {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': f'Unhandled event type: {eventType}, skipping'
+ }
+ }
+}
+
+let schemaId := inputs.schema_mapping?.[resource]
+
+if (empty(schemaId)) {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': f'No schema mapping for event type: {eventType}, skipping'
+ }
+ }
+}
+
+produceToWarehouseWebhooks(request.body, schemaId)""",
+ inputs_schema=[
+ {
+ "type": "string",
+ "key": "signing_secret",
+ "label": "Signing secret",
+ "required": False,
+ "secret": True,
+ "hidden": False,
+ "description": (
+ "Your shop's webhook secret key. Used to verify the X-Fourthwall-Hmac-SHA256 header "
+ "(base64 HMAC-SHA256 of the raw request body) so deliveries provably come from Fourthwall."
+ ),
+ },
+ {
+ "type": "boolean",
+ "key": "bypass_signature_check",
+ "label": "Bypass signature check",
+ "description": "If set, the X-Fourthwall-Hmac-SHA256 header will not be checked. This is not recommended.",
+ "default": False,
+ "required": False,
+ "secret": False,
+ },
+ {
+ "type": "json",
+ "key": "schema_mapping",
+ "label": "Schema mapping",
+ "description": "Maps Fourthwall resource keys to ExternalDataSchema IDs",
+ "required": True,
+ "secret": False,
+ "hidden": True,
+ },
+ {
+ "type": "string",
+ "key": "source_id",
+ "label": "Source ID",
+ "description": "The ExternalDataSource ID this webhook is associated with",
+ "required": True,
+ "secret": False,
+ "hidden": True,
+ },
+ ],
+)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/fourthwall.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/fourthwall.py
index f4ba1f9d89c8..fabc19be3e66 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/fourthwall.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/fourthwall.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class FourthwallSourceConfig(config.Config):
- pass
+ username: str
+ password: str