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 BigCommerce source (#78865)

Tom Owers609f3665c2e8
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 020f0e0617ce..818419868c0a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -102,6 +102,7 @@ the row lists both.
| beehiiv | HTTP | requests + `rest_source.RESTClient` | ✅ |
| better_stack | HTTP | requests | ✅ |
| bettermode | HTTP (GraphQL) | requests | ✅ |
+| bigcommerce | HTTP | requests + `rest_source.RESTClient` | ✅ |
| bigmailer | HTTP | requests | ✅ |
| bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) |
| bill_com | HTTP | requests | ✅ |
@@ -833,7 +834,6 @@ doesn't conflict with concurrent PRs.
- basecamp
- bcms
- bexio
-- bigcommerce
- bigeye
- billit
- billomat
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigcommerce/bigcommerce.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigcommerce/bigcommerce.py
new file mode 100644
index 000000000000..6d41417c53f0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigcommerce/bigcommerce.py
@@ -0,0 +1,160 @@
+import dataclasses
+from datetime import UTC, datetime
+from typing import Any, Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bigcommerce.settings import (
+ ENDPOINT_PATHS,
+ INCREMENTAL_FIELDS,
+ V2_ENDPOINTS,
+)
+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 (
+ Endpoint,
+ EndpointResource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+BASE_URL = "https://api.bigcommerce.com"
+# BigCommerce caps `limit` at 250 on both the V3 catalog/customers collections and the
+# legacy V2 orders collection.
+PAGE_SIZE = 250
+
+
+class BigCommerceResumeConfig:
+ page: int
+
+
+def _to_v3_timestamp(value: Any) -> str:
+ """Format an incremental cursor value for the V3 `date_modified:min` filter, which
+ expects ISO 8601 (e.g. `2019-08-24T14:15:22Z`)."""
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ return str(value)
+
+
+def _to_v2_timestamp(value: Any) -> str:
+ """Format an incremental cursor value for the legacy V2 `min_date_modified` filter,
+ which — unlike V3 — expects an RFC 2822 / HTTP-date string (e.g. `Sun, 22 Aug
+ 2021 00:00:00 +0000`)."""
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return dt.astimezone(UTC).strftime("%a, %d %b %Y %H:%M:%S +0000")
+ return str(value)
+
+
+def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResource:
+ path = ENDPOINT_PATHS[name]
+ is_v2 = name in V2_ENDPOINTS
+ use_incremental = should_use_incremental_field and name in INCREMENTAL_FIELDS
+
+ params: dict[str, Any] = {"limit": PAGE_SIZE}
+ if use_incremental:
+ if is_v2:
+ params["min_date_modified"] = {
+ "type": "incremental",
+ "cursor_path": "date_modified",
+ "initial_value": None,
+ "convert": _to_v2_timestamp,
+ }
+ else:
+ params["date_modified:min"] = {
+ "type": "incremental",
+ "cursor_path": "date_modified",
+ "initial_value": None,
+ "convert": _to_v3_timestamp,
+ }
+
+ # V3 reports the page count directly, so pagination stops without an extra empty-page
+ # request. V2 has no such envelope, so it falls back to stopping on a short/empty page.
+ paginator = PageNumberPaginator(
+ base_page=1,
+ page_param="page",
+ total_path=None if is_v2 else "meta.pagination.total_pages",
+ )
+
+ endpoint: Endpoint = {
+ "path": path,
+ "params": params,
+ "paginator": paginator,
+ # V3 wraps rows in {"data": [...], "meta": {...}}; the legacy V2 orders endpoint
+ # returns a bare JSON array.
+ "data_selector": None if is_v2 else "data",
+ }
+
+ return {
+ "name": name,
+ "table_name": name,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if use_incremental else "replace",
+ "endpoint": endpoint,
+ "table_format": "delta",
+ }
+
+
+def bigcommerce_source(
+ store_hash: str,
+ access_token: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[BigCommerceResumeConfig],
+ db_incremental_field_last_value: Optional[Any],
+ should_use_incremental_field: bool = False,
+):
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": f"{BASE_URL}/stores/{store_hash}",
+ "auth": {
+ "type": "api_key",
+ "name": "X-Auth-Token",
+ "api_key": access_token,
+ "location": "header",
+ },
+ "headers": {"Accept": "application/json"},
+ },
+ "resource_defaults": {},
+ "resources": [get_resource(endpoint, should_use_incremental_field)],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {"page": resume_config.page}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Only persist when there's a next page to resume to; the Redis TTL handles cleanup
+ # on completion.
+ if state and state.get("page"):
+ resumable_source_manager.save_state(BigCommerceResumeConfig(page=int(state["page"])))
+
+ return rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+
+def validate_credentials(store_hash: str, access_token: str) -> Optional[int]:
+ """Probe a cheap V3 endpoint. Returns the HTTP status code, or None on a connection error."""
+ try:
+ response = make_tracked_session(redact_values=(access_token,)).get(
+ f"{BASE_URL}/stores/{store_hash}/v3/catalog/products",
+ params={"limit": 1},
+ headers={"X-Auth-Token": access_token, "Accept": "application/json"},
+ timeout=30,
+ )
+ except Exception:
+ return None
+ return response.status_code
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigcommerce/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigcommerce/canonical_descriptions.py
new file mode 100644
index 000000000000..6b909d789c40
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigcommerce/canonical_descriptions.py
@@ -0,0 +1,108 @@
+"""Canonical, documentation-sourced descriptions for BigCommerce endpoints and columns.
+
+Sourced from the official BigCommerce REST API reference
+(https://developer.bigcommerce.com/api-reference). Keyed by the resource names in
+`settings.py` `ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced
+BigCommerce table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "products": {
+ "description": "A product listed for sale in the BigCommerce catalog.",
+ "docs_url": "https://developer.bigcommerce.com/docs/rest-catalog/products",
+ "columns": {
+ "id": "Unique identifier for the product.",
+ "name": "Product name.",
+ "sku": "Stock keeping unit (SKU) of the product.",
+ "type": "Product type: `physical` or `digital`.",
+ "price": "Base price of the product, excluding tax.",
+ "cost_price": "Cost price of the product, for internal reporting.",
+ "retail_price": "Suggested retail price (MSRP) of the product.",
+ "sale_price": "Sale price of the product, if on sale.",
+ "weight": "Weight of the product, in the store's configured weight unit.",
+ "inventory_level": "Current stock level, when inventory tracking is enabled.",
+ "inventory_tracking": "How inventory is tracked: `none`, `product`, or `variant`.",
+ "brand_id": "Identifier of the brand this product belongs to, if any.",
+ "categories": "Identifiers of the categories this product is assigned to.",
+ "is_visible": "Whether the product is visible on the storefront.",
+ "is_featured": "Whether the product is marked as featured.",
+ "date_created": "Date and time the product was created.",
+ "date_modified": "Date and time the product was last modified.",
+ "availability": "Availability status: `available`, `disabled`, or `preorder`.",
+ "condition": "Condition of the product: `New`, `Used`, or `Refurbished`.",
+ },
+ },
+ "categories": {
+ "description": "A category used to organize products in the storefront navigation.",
+ "docs_url": "https://developer.bigcommerce.com/docs/rest-catalog/catalog-categories",
+ "columns": {
+ "id": "Unique identifier for the category.",
+ "parent_id": "Identifier of the parent category, or 0 for a top-level category.",
+ "name": "Category name.",
+ "description": "Category description, which may contain HTML.",
+ "views": "Number of times the category page has been viewed.",
+ "sort_order": "Position of the category relative to its siblings.",
+ "is_visible": "Whether the category is visible on the storefront.",
+ "custom_url": "Custom URL path for the category page.",
+ },
+ },
+ "brands": {
+ "description": "A brand that products in the catalog can be assigned to.",
+ "docs_url": "https://developer.bigcommerce.com/docs/rest-catalog/catalog-brands",
+ "columns": {
+ "id": "Unique identifier for the brand.",
+ "name": "Brand name.",
+ "page_title": "Title shown in the browser tab for the brand's storefront page.",
+ "meta_description": "Meta description used for the brand's storefront page.",
+ "search_keywords": "Comma-separated keywords used for on-site search.",
+ "custom_url": "Custom URL path for the brand page.",
+ },
+ },
+ "customers": {
+ "description": "A registered customer account on the storefront.",
+ "docs_url": "https://developer.bigcommerce.com/docs/rest-management/customers",
+ "columns": {
+ "id": "Unique identifier for the customer.",
+ "email": "Customer's email address.",
+ "first_name": "Customer's first name.",
+ "last_name": "Customer's last name.",
+ "company": "Company name associated with the customer.",
+ "phone": "Customer's phone number.",
+ "customer_group_id": "Identifier of the customer group this customer belongs to.",
+ "notes": "Internal notes about the customer.",
+ "tax_exempt_category": "Tax exemption category applied to the customer, if any.",
+ "date_created": "Date and time the customer account was created.",
+ "date_modified": "Date and time the customer account was last modified.",
+ "registration_ip_address": "IP address the customer used when registering.",
+ "store_credit_amounts": "Store credit balances held by the customer.",
+ },
+ },
+ "orders": {
+ "description": "A customer order placed on the store.",
+ "docs_url": "https://developer.bigcommerce.com/docs/rest-management/orders",
+ "columns": {
+ "id": "Unique identifier for the order.",
+ "customer_id": "Identifier of the customer who placed the order, or 0 for a guest order.",
+ "status": "Human-readable order status (e.g. `Awaiting Fulfillment`, `Shipped`).",
+ "status_id": "Numeric identifier of the order status.",
+ "date_created": "Date and time the order was created.",
+ "date_modified": "Date and time the order was last modified.",
+ "date_shipped": "Date and time the order was shipped, if applicable.",
+ "subtotal_ex_tax": "Order subtotal, excluding tax.",
+ "subtotal_inc_tax": "Order subtotal, including tax.",
+ "total_ex_tax": "Order total, excluding tax.",
+ "total_inc_tax": "Order total, including tax.",
+ "total_tax": "Total tax charged on the order.",
+ "total_shipping": "Total shipping cost charged on the order.",
+ "currency_code": "Three-letter ISO currency code of the order.",
+ "payment_method": "Payment method used for the order.",
+ "payment_status": "Status of payment collection for the order.",
+ "items_total": "Total number of items in the order.",
+ "is_deleted": "Whether the order has been deleted.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigcommerce/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigcommerce/settings.py
new file mode 100644
index 000000000000..6d0110c021fd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigcommerce/settings.py
@@ -0,0 +1,50 @@
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Resources a user is likely to want from a BigCommerce store. BigCommerce is mid-migration
+# from its legacy V2 REST API to V3: catalog resources and customers already have V3
+# equivalents, but core order objects are still V2-only (BigCommerce has never shipped a V3
+# replacement for `/v2/orders`), so orders stays on the legacy API.
+ENDPOINTS = (
+ "products",
+ "categories",
+ "brands",
+ "customers",
+ "orders",
+)
+
+# Schema/endpoint name -> BigCommerce REST API path (relative to
+# `https://api.bigcommerce.com/stores/{store_hash}`).
+ENDPOINT_PATHS: dict[str, str] = {
+ "products": "/v3/catalog/products",
+ "categories": "/v3/catalog/categories",
+ "brands": "/v3/catalog/brands",
+ "customers": "/v3/customers",
+ "orders": "/v2/orders",
+}
+
+# Endpoints still served by the legacy V2 API: no `data` envelope, no `meta.pagination`,
+# and a different incremental filter param + date format than V3.
+V2_ENDPOINTS = frozenset({"orders"})
+
+# Categories and brands carry no modification timestamp in either API version, so they're
+# full refresh only. Products, customers and orders all expose a genuine server-side
+# "modified since" filter.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ endpoint: [
+ {
+ "label": "date_modified",
+ "type": IncrementalFieldType.DateTime,
+ "field": "date_modified",
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ]
+ for endpoint in ("products", "customers", "orders")
+}
+
+# Stable creation-time field to partition on, per endpoint. Categories and brands have no
+# creation timestamp field and are left unpartitioned.
+PARTITION_FIELDS: dict[str, str] = {
+ "products": "date_created",
+ "customers": "date_created",
+ "orders": "date_created",
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigcommerce/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigcommerce/source.py
index 2b16c9a38590..9eaaeca498c0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bigcommerce/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigcommerce/source.py
@@ -1,13 +1,35 @@
-from typing import cast
+from typing import 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.bigcommerce.bigcommerce import (
+ BigCommerceResumeConfig,
+ bigcommerce_source,
+ validate_credentials as validate_bigcommerce_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bigcommerce.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ PARTITION_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bigcommerce import (
BigCommerceSourceConfig,
)
@@ -15,18 +37,151 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class BigCommerceSource(SimpleSource[BigCommerceSourceConfig]):
+class BigCommerceSource(ResumableSource[BigCommerceSourceConfig, BigCommerceResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ supported_versions = ("v3",)
+ default_version = "v3"
+ api_docs_url = "https://developer.bigcommerce.com/api-reference"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BIGCOMMERCE
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "BigCommerce authentication failed. Check your store hash and access token.",
+ "403 Client Error": (
+ "Your BigCommerce access token does not have the required OAuth scopes for this resource."
+ ),
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.bigcommerce.canonical_descriptions import ( # noqa: PLC0415 -- lazy import keeps this out of the hot registration path
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: BigCommerceSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: BigCommerceSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ if not config.store_hash or not config.access_token:
+ return False, "Missing BigCommerce credentials"
+
+ status = validate_bigcommerce_credentials(config.store_hash, config.access_token)
+
+ if status == 200:
+ return True, None
+
+ # A token scoped to only some resources still passes the create-time probe; per-table
+ # access is reported separately at sync time via get_non_retryable_errors.
+ if status == 403 and schema_name is None:
+ return True, None
+
+ if status == 403:
+ return False, "Your BigCommerce access token does not have the required OAuth scopes for this resource."
+
+ if status == 401:
+ return False, "BigCommerce authentication failed. Check your store hash and access token."
+
+ return False, "Could not connect to your BigCommerce store. Please check the store hash."
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BigCommerceResumeConfig]:
+ return ResumableSourceManager[BigCommerceResumeConfig](inputs, BigCommerceResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: BigCommerceSourceConfig,
+ resumable_source_manager: ResumableSourceManager[BigCommerceResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ # Only the endpoints that expose a server-side "modified since" filter sync
+ # incrementally — guard against a stale schema requesting it elsewhere.
+ use_incremental = inputs.should_use_incremental_field and inputs.schema_name in INCREMENTAL_FIELDS
+
+ resource = bigcommerce_source(
+ store_hash=config.store_hash,
+ access_token=config.access_token,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=use_incremental,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value if use_incremental else None,
+ )
+
+ response = SourceResponse(
+ name=resource.name,
+ items=lambda: resource,
+ primary_keys=["id"],
+ column_hints=resource.column_hints,
+ # Whether BigCommerce's `sort`/`direction` params hold a stable ascending order
+ # page-to-page isn't verified against a live store. Deferring the watermark commit
+ # until the whole resource has been read (desc semantics) avoids skipping rows if
+ # the true order turns out not to be strictly ascending.
+ sort_mode="desc" if use_incremental else "asc",
+ )
+
+ partition_key = PARTITION_FIELDS.get(inputs.schema_name)
+ if partition_key:
+ response.partition_count = 1
+ response.partition_size = 1
+ response.partition_mode = "datetime"
+ response.partition_format = "month"
+ response.partition_keys = [partition_key]
+
+ return response
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.BIG_COMMERCE,
category=DataWarehouseSourceCategory.E_COMMERCE,
label="BigCommerce",
+ caption=(
+ "Enter your BigCommerce store hash and API access token to pull your store data into "
+ "the PostHog Data warehouse. Create an API account under **Settings → API → "
+ "Store-level API accounts** with `read-only` scope for **Products**, **Orders** and "
+ "**Customers**."
+ ),
iconPath="/static/services/bigcommerce.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/bigcommerce",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="store_hash",
+ label="Store hash",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="abc123",
+ secret=False,
+ caption="Found in your store's control panel URL: `https://store-{store_hash}.mybigcommerce.com`.",
+ ),
+ SourceFieldInputConfig(
+ name="access_token",
+ label="Access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigcommerce/tests/test_bigcommerce.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigcommerce/tests/test_bigcommerce.py
new file mode 100644
index 000000000000..7ab836dd3eeb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigcommerce/tests/test_bigcommerce.py
@@ -0,0 +1,320 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, datetime
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bigcommerce.bigcommerce import (
+ BigCommerceResumeConfig,
+ _to_v2_timestamp,
+ _to_v3_timestamp,
+ bigcommerce_source,
+ get_resource,
+ validate_credentials,
+)
+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 Endpoint
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+
+class TestGetResource:
+ @parameterized.expand(
+ [
+ ("products", "/v3/catalog/products", "data", True),
+ ("categories", "/v3/catalog/categories", "data", True),
+ ("brands", "/v3/catalog/brands", "data", True),
+ ("customers", "/v3/customers", "data", True),
+ ("orders", "/v2/orders", None, False),
+ ]
+ )
+ def test_path_and_envelope_per_endpoint(
+ self, name: str, expected_path: str, expected_data_selector: str | None, expects_total_path: bool
+ ) -> None:
+ resource = get_resource(name, should_use_incremental_field=False)
+ endpoint = cast(Endpoint, resource["endpoint"])
+
+ assert endpoint["path"] == expected_path
+ assert endpoint["data_selector"] == expected_data_selector
+ assert resource["table_name"] == name
+ assert resource["table_format"] == "delta"
+
+ paginator = cast(PageNumberPaginator, endpoint["paginator"])
+ assert paginator.page_param == "page"
+ assert paginator.base_page == 1
+ assert (paginator.total_path is not None) is expects_total_path
+
+ @parameterized.expand(
+ [
+ ("products", False),
+ ("categories", False),
+ ("brands", False),
+ ("customers", False),
+ ("orders", False),
+ ("products", True),
+ ("categories", True), # categories has no date_modified field: stays full refresh
+ ("brands", True), # same for brands
+ ("customers", True),
+ ("orders", True),
+ ]
+ )
+ def test_write_disposition_and_incremental_param(self, name: str, should_use_incremental_field: bool) -> None:
+ resource = get_resource(name, should_use_incremental_field)
+ endpoint = cast(Endpoint, resource["endpoint"])
+ params = cast(dict[str, Any], endpoint["params"])
+
+ incremental_capable = name in ("products", "customers", "orders")
+ use_incremental = should_use_incremental_field and incremental_capable
+
+ if use_incremental:
+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
+ else:
+ assert resource["write_disposition"] == "replace"
+
+ incremental_key = "min_date_modified" if name == "orders" else "date_modified:min"
+ if use_incremental:
+ assert incremental_key in params
+ assert params[incremental_key]["type"] == "incremental"
+ else:
+ assert incremental_key not in params
+
+ def test_limit_is_set_for_every_endpoint(self) -> None:
+ for name in ("products", "categories", "brands", "customers", "orders"):
+ resource = get_resource(name, should_use_incremental_field=False)
+ endpoint = cast(Endpoint, resource["endpoint"])
+ assert cast(dict[str, Any], endpoint["params"])["limit"] == 250
+
+
+class TestTimestampConverters:
+ @parameterized.expand(
+ [
+ ("naive", datetime(2024, 1, 2, 3, 4, 5), "2024-01-02T03:04:05Z"),
+ ("aware_utc", datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "2024-01-02T03:04:05Z"),
+ ]
+ )
+ def test_to_v3_timestamp_formats_datetime(self, _label: str, value: datetime, expected: str) -> None:
+ assert _to_v3_timestamp(value) == expected
+
+ def test_to_v3_timestamp_passes_through_non_datetime(self) -> None:
+ assert _to_v3_timestamp("already-a-string") == "already-a-string"
+
+ @parameterized.expand(
+ [
+ ("naive", datetime(2024, 1, 2, 3, 4, 5), "Tue, 02 Jan 2024 03:04:05 +0000"),
+ ("aware_utc", datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "Tue, 02 Jan 2024 03:04:05 +0000"),
+ ]
+ )
+ def test_to_v2_timestamp_formats_datetime(self, _label: str, value: datetime, expected: str) -> None:
+ assert _to_v2_timestamp(value) == expected
+
+ def test_to_v2_timestamp_passes_through_non_datetime(self) -> None:
+ assert _to_v2_timestamp("already-a-string") == "already-a-string"
+
+
+def _make_http_response(body: Any, status_code: int = 200, headers: dict[str, str] | None = None) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ for key, value in (headers or {}).items():
+ resp.headers[key] = value
+ return resp
+
+
+def _v3_page(items: list[dict[str, Any]], current_page: int, total_pages: int) -> dict[str, Any]:
+ return {
+ "data": items,
+ "meta": {"pagination": {"current_page": current_page, "total_pages": total_pages}},
+ }
+
+
+class TestBigCommerceSourceResumeBehavior:
+ """End-to-end resume behaviour of ``bigcommerce_source`` via ``rest_api_resource``."""
+
+ def _drive(
+ self, endpoint: str, manager: MagicMock, responses: list[Response], should_use_incremental_field: bool = False
+ ) -> tuple[MagicMock, list[dict[str, Any]]]:
+ """Drive ``bigcommerce_source`` with a mocked HTTP session.
+
+ Returns ``(mock_session, sent_params)`` — shallow copies of ``request.params``
+ captured at send-time, since the paginator mutates the Request object in place
+ between pages.
+ """
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ return next(response_iter)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ resource = bigcommerce_source(
+ store_hash="store123",
+ access_token="test-token",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=None,
+ should_use_incremental_field=should_use_incremental_field,
+ )
+ list(cast(Iterable[Any], resource))
+ return mock_session, sent_params
+
+ def test_v3_fresh_run_pages_until_total_pages_reached(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_http_response(_v3_page([{"id": 1}], current_page=1, total_pages=3)),
+ _make_http_response(_v3_page([{"id": 2}], current_page=2, total_pages=3)),
+ _make_http_response(_v3_page([{"id": 3}], current_page=3, total_pages=3)),
+ ]
+ _, sent_params = self._drive("products", manager, responses)
+
+ pages_sent = [p.get("page") for p in sent_params]
+ assert pages_sent == [1, 2, 3]
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [
+ BigCommerceResumeConfig(page=2),
+ BigCommerceResumeConfig(page=3),
+ ]
+
+ def test_v2_orders_stops_on_empty_page_with_no_pagination_envelope(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_http_response([{"id": 1}]),
+ _make_http_response([{"id": 2}]),
+ _make_http_response([]),
+ ]
+ _, sent_params = self._drive("orders", manager, responses)
+
+ assert [p.get("page") for p in sent_params] == [1, 2, 3]
+
+ def test_resume_seeds_paginator_with_saved_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = BigCommerceResumeConfig(page=5)
+
+ responses = [_make_http_response(_v3_page([{"id": 9}], current_page=5, total_pages=5))]
+ _, sent_params = self._drive("customers", manager, responses)
+
+ assert [p.get("page") for p in sent_params] == [5]
+ manager.load_state.assert_called_once()
+
+ def test_terminal_single_page_does_not_save_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response(_v3_page([{"id": 1}], current_page=1, total_pages=1))]
+ self._drive("brands", manager, responses)
+
+ manager.save_state.assert_not_called()
+
+ def test_does_not_load_state_when_cannot_resume(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response(_v3_page([{"id": 1}], current_page=1, total_pages=1))]
+ self._drive("categories", manager, responses)
+
+ manager.load_state.assert_not_called()
+
+ def test_v3_incremental_param_carries_converted_timestamp(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ last_value = datetime(2024, 5, 6, 7, 8, 9, tzinfo=UTC)
+
+ sent_params: list[dict[str, Any]] = []
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ return _make_http_response(_v3_page([], current_page=1, total_pages=1))
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ resource = bigcommerce_source(
+ store_hash="store123",
+ access_token="test-token",
+ endpoint="products",
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=last_value,
+ should_use_incremental_field=True,
+ )
+ list(cast(Iterable[Any], resource))
+
+ assert sent_params[0]["date_modified:min"] == "2024-05-06T07:08:09Z"
+
+ def test_v2_incremental_param_carries_rfc2822_timestamp(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ last_value = datetime(2024, 5, 6, 7, 8, 9, tzinfo=UTC)
+
+ sent_params: list[dict[str, Any]] = []
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ return _make_http_response([])
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ resource = bigcommerce_source(
+ store_hash="store123",
+ access_token="test-token",
+ endpoint="orders",
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=last_value,
+ should_use_incremental_field=True,
+ )
+ list(cast(Iterable[Any], resource))
+
+ assert sent_params[0]["min_date_modified"] == "Mon, 06 May 2024 07:08:09 +0000"
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize("status_code", [200, 401, 403, 404])
+ def test_returns_status_code(self, status_code: int) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bigcommerce.bigcommerce.make_tracked_session"
+ ) as mock_make_session:
+ mock_make_session.return_value.get.return_value = MagicMock(status_code=status_code)
+ assert validate_credentials("store123", "token") == status_code
+
+ def test_returns_none_on_connection_error(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bigcommerce.bigcommerce.make_tracked_session"
+ ) as mock_make_session:
+ mock_make_session.return_value.get.side_effect = ConnectionError("boom")
+ assert validate_credentials("store123", "token") is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigcommerce/tests/test_bigcommerce_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigcommerce/tests/test_bigcommerce_source.py
new file mode 100644
index 000000000000..e7bbc4c40248
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigcommerce/tests/test_bigcommerce_source.py
@@ -0,0 +1,194 @@
+from typing import Optional
+
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bigcommerce.bigcommerce import (
+ BigCommerceResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bigcommerce.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ PARTITION_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bigcommerce.source import BigCommerceSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bigcommerce import (
+ BigCommerceSourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+INCREMENTAL_ENDPOINTS = set(INCREMENTAL_FIELDS.keys())
+
+
+def _make_inputs(schema_name: str, should_use_incremental_field: bool = False, last_value: object = None):
+ return mock.MagicMock(
+ schema_name=schema_name,
+ team_id=123,
+ job_id="job-1",
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=last_value,
+ )
+
+
+class TestBigCommerceSource:
+ def setup_method(self):
+ self.source = BigCommerceSource()
+ self.team_id = 123
+ self.config = BigCommerceSourceConfig(store_hash="store123", access_token="test-token")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.BIGCOMMERCE
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "BigCommerce"
+ assert config.label == "BigCommerce"
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/bigcommerce.png"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["store_hash", "access_token"]
+
+ access_token = config.fields[1]
+ assert isinstance(access_token, SourceFieldInputConfig)
+ assert access_token.type == SourceFieldInputConfigType.PASSWORD
+ assert access_token.secret is True
+ assert access_token.required is True
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors(self, expected_key):
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_lists_all_endpoints(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @parameterized.expand(sorted(ENDPOINTS))
+ def test_get_schemas_incremental_only_for_supported_endpoints(self, endpoint):
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)
+ expected = endpoint in INCREMENTAL_ENDPOINTS
+
+ assert schema.supports_incremental is expected
+ assert schema.supports_append is expected
+ if expected:
+ assert schema.incremental_fields[0]["field"] == "date_modified"
+ else:
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["orders"])
+ assert [s.name for s in schemas] == ["orders"]
+
+ def test_get_schemas_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []
+
+ @pytest.mark.parametrize(
+ "status, schema_name, expected_valid",
+ [
+ (200, None, True),
+ (200, "orders", True),
+ (401, None, False),
+ (403, None, True), # token valid but scoped narrower than the probe endpoint -> allowed at create
+ (403, "orders", False), # rejected for a specific schema check
+ (404, None, False),
+ (None, None, False), # connection error
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bigcommerce.source.validate_bigcommerce_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, status, schema_name, expected_valid):
+ mock_validate.return_value = status
+
+ is_valid, _ = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
+
+ assert is_valid is expected_valid
+ mock_validate.assert_called_once_with("store123", "test-token")
+
+ def test_validate_credentials_missing_fields(self):
+ config = BigCommerceSourceConfig(store_hash="", access_token="")
+ is_valid, message = self.source.validate_credentials(config, self.team_id)
+
+ assert is_valid is False
+ assert message == "Missing BigCommerce credentials"
+
+ def test_get_resumable_source_manager(self):
+ manager = self.source.get_resumable_source_manager(_make_inputs("orders"))
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is BigCommerceResumeConfig
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bigcommerce.source.bigcommerce_source"
+ )
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source):
+ mock_resource = mock.MagicMock(name="orders", column_hints=None)
+ mock_source.return_value = mock_resource
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+ inputs = _make_inputs("orders", should_use_incremental_field=True, last_value="2024-01-01T00:00:00")
+
+ response = self.source.source_for_pipeline(self.config, manager, inputs)
+
+ _, kwargs = mock_source.call_args
+ assert kwargs["store_hash"] == "store123"
+ assert kwargs["access_token"] == "test-token"
+ assert kwargs["endpoint"] == "orders"
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01T00:00:00"
+ assert response.primary_keys == ["id"]
+ assert response.sort_mode == "desc"
+
+ def test_source_for_pipeline_full_refresh_drops_last_value(self):
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+ inputs = _make_inputs("customers", should_use_incremental_field=False, last_value="2024-01-01T00:00:00")
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bigcommerce.source.bigcommerce_source"
+ ) as mock_source:
+ mock_source.return_value = mock.MagicMock(name="customers", column_hints=None)
+ response = self.source.source_for_pipeline(self.config, manager, inputs)
+
+ _, kwargs = mock_source.call_args
+ assert kwargs["db_incremental_field_last_value"] is None
+ assert response.sort_mode == "asc"
+
+ def test_source_for_pipeline_ignores_incremental_for_non_incremental_endpoint(self):
+ # Categories has no date_modified field; a stale schema requesting incremental sync
+ # must fall back to full refresh instead of sending a cursor the endpoint can't use.
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+ inputs = _make_inputs("categories", should_use_incremental_field=True, last_value="2024-01-01T00:00:00")
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bigcommerce.source.bigcommerce_source"
+ ) as mock_source:
+ mock_source.return_value = mock.MagicMock(name="categories", column_hints=None)
+ response = self.source.source_for_pipeline(self.config, manager, inputs)
+
+ _, kwargs = mock_source.call_args
+ assert kwargs["should_use_incremental_field"] is False
+ assert kwargs["db_incremental_field_last_value"] is None
+ assert response.sort_mode == "asc"
+
+ @parameterized.expand(sorted(ENDPOINTS))
+ def test_source_for_pipeline_partitioning(self, endpoint):
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+ inputs = _make_inputs(endpoint)
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bigcommerce.source.bigcommerce_source"
+ ) as mock_source:
+ mock_source.return_value = mock.MagicMock(name=endpoint, column_hints=None)
+ response = self.source.source_for_pipeline(self.config, manager, inputs)
+
+ expected_key: Optional[str] = PARTITION_FIELDS.get(endpoint)
+ if expected_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [expected_key]
+ else:
+ assert response.partition_keys is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bigcommerce.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bigcommerce.py
index 8a95d58a728e..98f63971c122 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bigcommerce.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bigcommerce.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class BigCommerceSourceConfig(config.Config):
- pass
+ store_hash: str
+ access_token: str