:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement shopwired import source (#69389)
Tom Owers23346a7c3edc
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 5194eb5ee0a8..d69f602a9dce 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -312,6 +312,7 @@ the row lists both.| servicenow | HTTP | requests | ✅ || shipstation | HTTP | requests | ✅ || shopify | HTTP | requests | ✅ |+| shopwired | HTTP | requests | ✅ || shortcut | HTTP | requests | ✅ || shortio | HTTP | requests | ✅ || simplecast | HTTP | requests | ✅ |@@ -685,7 +686,6 @@ doesn't conflict with concurrent PRs.- sharepoint- sharetribe- shippo-- shopwired- shortio- shutterstock- sigma_computingdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 9fa38e4f0ba2..795e4c9e0f56 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -3108,7 +3108,8 @@ class ShippoSourceConfig(config.Config):@config.configclass ShopWiredSourceConfig(config.Config):- pass+ api_key: str+ api_secret: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopwired/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopwired/canonical_descriptions.pynew file mode 100644index 000000000000..da3bba18f032--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopwired/canonical_descriptions.py@@ -0,0 +1,133 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the ShopWired API docs (https://help.shopwired.co.uk/api).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "products": {+ "description": "A product in your ShopWired store, including pricing, stock, and SEO fields.",+ "docs_url": "https://help.shopwired.co.uk/api/products/api-products",+ "columns": {+ "id": "The unique ID of the product.",+ "title": "The product's title.",+ "description": "The product's description.",+ "active": "Whether the product is active (visible on the store).",+ "sku": "The product's SKU code.",+ "stock": "The stock quantity of the product.",+ "price": "The product's price.",+ "salePrice": "The product's sale price, if any.",+ "comparePrice": "The product's compare-at price.",+ "weight": "The product's weight.",+ "gtin": "The product's GTIN.",+ "mpn": "The product's MPN.",+ "url": "The full URL of the product page.",+ "slug": "The URL slug of the product.",+ "vatExclusive": "Whether the product price excludes VAT.",+ "rewardPoints": "Reward points earned when purchasing the product.",+ },+ },+ "categories": {+ "description": "A category used to group products in your ShopWired store.",+ "docs_url": "https://help.shopwired.co.uk/api/categorisation/api-categories",+ "columns": {+ "id": "The unique ID of the category.",+ "title": "The category's title.",+ "description": "The category's description.",+ "url": "The full URL of the category page.",+ "active": "Whether the category is active.",+ "metaTitle": "The page title tag for the category page.",+ "metaDescription": "The meta description for the category page.",+ "metaKeywords": "The meta keywords for the category page.",+ },+ },+ "brands": {+ "description": "A brand assigned to products in your ShopWired store.",+ "docs_url": "https://help.shopwired.co.uk/api/categorisation/api-brands",+ "columns": {+ "id": "The unique ID of the brand.",+ "title": "The brand's name.",+ "description": "The brand's description.",+ "url": "The full URL of the brand page.",+ "active": "Whether the brand is active.",+ },+ },+ "tags": {+ "description": "A tag used to label and filter products in your ShopWired store.",+ "docs_url": "https://help.shopwired.co.uk/api/categorisation/api-tags",+ "columns": {+ "id": "The unique ID of the tag.",+ "title": "The tag's name.",+ "description": "The tag's description.",+ "url": "The full URL of the tag page.",+ "active": "Whether the tag is active.",+ },+ },+ "customers": {+ "description": "A customer account (regular or trade) registered on your ShopWired store.",+ "docs_url": "https://help.shopwired.co.uk/api/orders-customers/api-customers",+ "columns": {+ "id": "The unique ID of the customer.",+ "trade": "Whether the customer is a trade customer.",+ "active": "Whether the customer account is active.",+ "firstName": "The customer's first name.",+ "lastName": "The customer's last name.",+ "email": "The customer's email address.",+ "phone": "The customer's telephone number.",+ "acceptsMarketing": "Whether the customer opted in to marketing (regular customers only).",+ "companyName": "The customer's company name (trade customers only).",+ "city": "The customer's city.",+ "postcode": "The customer's postcode.",+ "notes": "Internal notes about the customer.",+ "rewardPoints": "The customer's reward points balance.",+ },+ },+ "orders": {+ "description": "An order placed on your ShopWired store, including line items, addresses, and totals.",+ "docs_url": "https://help.shopwired.co.uk/api/orders-customers/api-orders",+ "columns": {+ "id": "The unique ID of the order.",+ "reference": "The merchant-facing order number, distinct from the ID.",+ "created": "When the order was created.",+ "archived": "Whether the order is archived.",+ "status": "The order's status (ID, name, and type).",+ "paymentMethod": "The payment method used for the order.",+ "total": "The total amount of the order.",+ "subTotal": "The order subtotal before shipping and fees.",+ "shippingTotal": "The shipping amount charged on the order.",+ "tax": "The tax type and value applied to the order.",+ "products": "The line items on the order.",+ "billingAddress": "The order's billing address.",+ "shippingAddress": "The order's shipping address.",+ "customer": "The customer who placed the order.",+ "trackingUrl": "The shipment tracking URL, if set.",+ "transactionId": "The payment provider's transaction ID.",+ "comments": "Comments the customer left on the order.",+ },+ },+ "order_statuses": {+ "description": "An order status configured on your ShopWired store (e.g. Paid, Dispatched).",+ "docs_url": "https://help.shopwired.co.uk/api/orders-customers/api-order-status",+ "columns": {+ "id": "The unique ID of the status.",+ "name": "The name of the order status.",+ },+ },+ "vouchers": {+ "description": "A discount voucher customers can redeem on your ShopWired store.",+ "docs_url": "https://help.shopwired.co.uk/api/orders-customers/api-vouchers",+ "columns": {+ "id": "The unique ID of the voucher.",+ "code": "The code customers enter to redeem the voucher.",+ "discount": "The discount type (percent, amount, or free_shipping) and value.",+ "validFrom": "When the voucher becomes valid.",+ "expiresOn": "When the voucher expires.",+ "target": "What the voucher applies to (orders over a value, a category, or products).",+ "active": "Whether the voucher is active.",+ "uses": "The maximum total number of uses.",+ "used": "How many times the voucher has been used.",+ "customerUses": "The maximum uses per customer account.",+ "comments": "Internal notes about the voucher.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopwired/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopwired/settings.pynew file mode 100644index 000000000000..ce5ada4e9387--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopwired/settings.py@@ -0,0 +1,63 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# List endpoints accept a `count` of up to 100 (default 50); the largest page minimises round trips+# against ShopWired's leaky-bucket rate limit (burst 40, 2 requests/second sustained).+PAGE_SIZE = 100++# Orders are the only resource with a documented server-side created-date filter (`from`/`to` UNIX+# timestamps) and a date sort (`sort=date`/`date_desc`), so they are the only incremental endpoint.+# `created` is stable (an order's creation date never changes), making it safe for both the+# incremental cursor and datetime partitioning.+_CREATED_INCREMENTAL: list[IncrementalField] = [+ {+ "label": "created",+ "type": IncrementalFieldType.DateTime,+ "field": "created",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++@dataclass+class ShopWiredEndpointConfig:+ name: str+ path: str+ # ShopWired object IDs are integers, unique per resource across the whole account.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable creation timestamp used for datetime partitioning, when the resource exposes one.+ partition_key: Optional[str] = None+ # Query param value for `sort` guaranteeing a stable ascending order while paginating.+ # `None` keeps the API default (creation-date order).+ sort_param: Optional[str] = None+ # The order-statuses endpoint documents no pagination params, so it's fetched in one request.+ paginated: bool = True+++SHOPWIRED_ENDPOINTS: dict[str, ShopWiredEndpointConfig] = {+ "products": ShopWiredEndpointConfig(name="products", path="/products"),+ "categories": ShopWiredEndpointConfig(name="categories", path="/categories"),+ "brands": ShopWiredEndpointConfig(name="brands", path="/brands"),+ "tags": ShopWiredEndpointConfig(name="tags", path="/tags"),+ "customers": ShopWiredEndpointConfig(name="customers", path="/customers"),+ "orders": ShopWiredEndpointConfig(+ name="orders",+ path="/orders",+ incremental_fields=_CREATED_INCREMENTAL,+ partition_key="created",+ # Ascending creation-date sort keeps the pipeline's incremental watermark+ # (`sort_mode="asc"`) advancing correctly while paginating.+ sort_param="date",+ ),+ "order_statuses": ShopWiredEndpointConfig(name="order_statuses", path="/order-statuses", paginated=False),+ "vouchers": ShopWiredEndpointConfig(name="vouchers", path="/vouchers"),+}++ENDPOINTS = tuple(SHOPWIRED_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in SHOPWIRED_ENDPOINTS.items() if config.incremental_fields+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopwired/shopwired.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopwired/shopwired.pynew file mode 100644index 000000000000..dbc3d5d74768--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopwired/shopwired.py@@ -0,0 +1,219 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional++import requests+from dateutil import parser+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.shopwired.settings import (+ PAGE_SIZE,+ SHOPWIRED_ENDPOINTS,+)++# ShopWired's dedicated API domain; the version segment is mandatory in every path.+SHOPWIRED_BASE_URL = "https://api.ecommerceapi.uk/v1"+REQUEST_TIMEOUT_SECONDS = 60+# Cheap probe used to confirm an API key/secret pair is genuine. Keys are account-wide, so one+# probe validates access to every list endpoint.+DEFAULT_PROBE_PATH = "/products/count"+++class ShopWiredRetryableError(Exception):+ pass+++class ShopWiredResumeConfig:+ # Number of rows already yielded — ShopWired paginates with `count`/`offset` query params, so a+ # crashed sync resumes from the page after the last one yielded; merge dedupes on `id`.+ offset: int = 0+ # The `from` created-date filter (UNIX timestamp) the interrupted run was using. Pinned in the+ # resume state so a resumed run keeps the same window — recomputing it from a watermark that+ # advanced mid-run would shift rows under the saved offset.+ from_timestamp: int | None = None+++def _make_session(api_key: str, api_secret: str) -> requests.Session:+ # Private-app auth is HTTP Basic with the API key as username and the secret as password.+ session = make_tracked_session(headers={"Accept": "application/json"}, redact_values=(api_key, api_secret))+ session.auth = (api_key, api_secret)+ return session+++def to_unix_timestamp(value: Any) -> int | None:+ """Convert an incremental watermark (datetime, date, epoch number, or date string) to a UNIX+ timestamp for ShopWired's `from` query param. Naive datetimes are treated as UTC so the result+ doesn't depend on the worker's local timezone."""+ if value is None:+ return None+ if isinstance(value, bool):+ return None+ if isinstance(value, int | float):+ return int(value)+ if isinstance(value, datetime):+ if value.tzinfo is None:+ value = value.replace(tzinfo=UTC)+ return int(value.timestamp())+ if isinstance(value, date):+ return int(datetime(value.year, value.month, value.day, tzinfo=UTC).timestamp())+ if isinstance(value, str) and value.strip():+ try:+ parsed = parser.parse(value)+ except (ValueError, OverflowError):+ return None+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=UTC)+ return int(parsed.timestamp())+ return None+++@retry(+ retry=retry_if_exception_type((ShopWiredRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ path: str,+ params: dict[str, Any],+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ response = session.get(+ f"{SHOPWIRED_BASE_URL}{path}",+ params=params,+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ # ShopWired rate limits with a leaky bucket (burst 40, 2 req/s sustained) and returns 429 when+ # exceeded; the exponential backoff drains the bucket before the next attempt.+ if response.status_code == 429 or response.status_code >= 500:+ raise ShopWiredRetryableError(f"ShopWired API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"ShopWired API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ data = response.json()+ # ShopWired list endpoints return a bare JSON array with no wrapper or pagination metadata.+ if not isinstance(data, list):+ raise ShopWiredRetryableError(f"ShopWired returned an unexpected payload for {path}: {type(data).__name__}")++ return data+++def get_rows(+ api_key: str,+ api_secret: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ShopWiredResumeConfig],+ db_incremental_field_last_value: Optional[Any] = None,+) -> Iterator[list[dict[str, Any]]]:+ config = SHOPWIRED_ENDPOINTS[endpoint]+ session = _make_session(api_key, api_secret)++ if not config.paginated:+ # No documented pagination params (order statuses) — one request returns the full list.+ items = _fetch_page(session, config.path, {}, logger)+ if items:+ yield items+ return++ from_timestamp = to_unix_timestamp(db_incremental_field_last_value)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume.offset if resume else 0+ if resume:+ # Keep the interrupted run's `from` window so the saved offset still points at the same rows.+ from_timestamp = resume.from_timestamp+ logger.debug(f"ShopWired: resuming {endpoint} from offset {offset}")++ while True:+ params: dict[str, Any] = {"count": PAGE_SIZE, "offset": offset}+ if config.sort_param is not None:+ params["sort"] = config.sort_param+ if from_timestamp is not None:+ # Server-side created-date filter (UNIX timestamp). Assumed inclusive, so the watermark+ # row is re-fetched and deduped by the merge on `id`.+ params["from"] = from_timestamp++ items = _fetch_page(session, config.path, params, logger)+ if items:+ yield items++ # A short (or empty) page means we've reached the end of the collection.+ if len(items) < PAGE_SIZE:+ break++ offset += len(items)+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(ShopWiredResumeConfig(offset=offset, from_timestamp=from_timestamp))+++def shopwired_source(+ api_key: str,+ api_secret: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ShopWiredResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = SHOPWIRED_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ api_secret=api_secret,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ db_incremental_field_last_value=db_incremental_field_last_value if should_use_incremental_field else None,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ sort_mode="asc",+ )+++def check_access(api_key: str, api_secret: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the API key/secret pair.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = _make_session(api_key, api_secret)+ try:+ response = session.get(f"{SHOPWIRED_BASE_URL}{path}", timeout=15)+ except Exception as e:+ return 0, f"Could not connect to ShopWired: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"ShopWired returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(api_key: str, api_secret: str) -> tuple[bool, str | None]:+ status, message = check_access(api_key, api_secret)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid ShopWired API key or secret"+ return False, message or "Could not validate ShopWired credentials"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopwired/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopwired/source.pyindex ae2243bd17c1..74e4102df2bf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shopwired/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopwired/source.py@@ -1,19 +1,43 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ShopWiredSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.shopwired.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ SHOPWIRED_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.shopwired.shopwired import (+ ShopWiredResumeConfig,+ shopwired_source,+ validate_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class ShopWiredSource(SimpleSource[ShopWiredSourceConfig]):+class ShopWiredSource(ResumableSource[ShopWiredSourceConfig, ShopWiredResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SHOPWIRED@@ -24,7 +48,98 @@ class ShopWiredSource(SimpleSource[ShopWiredSourceConfig]):name=SchemaExternalDataSourceType.SHOP_WIRED,category=DataWarehouseSourceCategory.E_COMMERCE,label="ShopWired",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your ShopWired API credentials to pull your store data into the PostHog Data warehouse.++You can create an API key and secret under **Account > API keys** in your [ShopWired](https://www.shopwired.co.uk) account. The credentials grant read access to your products, categories, brands, tags, customers, orders, and vouchers.+""",iconPath="/static/services/shopwired.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/shopwired",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="api_secret",+ label="API secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.shopwired.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.ecommerceapi.uk": "Your ShopWired API key or secret is invalid or has been revoked. Generate new credentials under Account > API keys, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.ecommerceapi.uk": "Your ShopWired API credentials do not have access to this data. Check the key's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: ShopWiredSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Only orders expose a server-side created-date filter (`from`), so every other endpoint is+ # full refresh only.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=endpoint in INCREMENTAL_FIELDS,+ supports_append=endpoint in INCREMENTAL_FIELDS,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: ShopWiredSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The API key/secret pair is account-wide, so a single probe validates access to every schema.+ return validate_credentials(config.api_key, config.api_secret)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ShopWiredResumeConfig]:+ return ResumableSourceManager[ShopWiredResumeConfig](inputs, ShopWiredResumeConfig)++ def source_for_pipeline(+ self,+ config: ShopWiredSourceConfig,+ resumable_source_manager: ResumableSourceManager[ShopWiredResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in SHOPWIRED_ENDPOINTS:+ raise ValueError(f"Unknown ShopWired schema '{inputs.schema_name}'")++ return shopwired_source(+ api_key=config.api_key,+ api_secret=config.api_secret,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopwired/tests/test_shopwired.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopwired/tests/test_shopwired.pynew file mode 100644index 000000000000..5630a68f4e46--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopwired/tests/test_shopwired.py@@ -0,0 +1,327 @@+import time+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.shopwired import shopwired+from products.warehouse_sources.backend.temporal.data_imports.sources.shopwired.settings import (+ PAGE_SIZE,+ SHOPWIRED_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.shopwired.shopwired import (+ ShopWiredResumeConfig,+ ShopWiredRetryableError,+ check_access,+ get_rows,+ shopwired_source,+ to_unix_timestamp,+ validate_credentials,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = shopwired._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: ShopWiredResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[ShopWiredResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> ShopWiredResumeConfig | None:+ return self._state++ def save_state(self, data: ShopWiredResumeConfig) -> None:+ self.saved.append(data)+++def _full_page(start_id: int) -> list[dict]:+ return [{"id": start_id + i} for i in range(PAGE_SIZE)]+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: dict[int, list[dict]],+ endpoint: str = "products",+ db_incremental_field_last_value: Any = None,+ requested_params: list[dict] | None = None,+ ) -> list[dict]:+ def fake_fetch(session: Any, path: str, params: dict[str, Any], logger: Any) -> list[dict]:+ if requested_params is not None:+ requested_params.append(params)+ return pages[params.get("offset", 0)]++ monkeypatch.setattr(shopwired, "_fetch_page", fake_fetch)+ monkeypatch.setattr(shopwired, "_make_session", lambda *args: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="sw-key",+ api_secret="sw-secret",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ db_incremental_field_last_value=db_incremental_field_last_value,+ ):+ rows.extend(batch)+ return rows++ def test_short_page_yields_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {0: [{"id": 1}, {"id": 2}]})+ assert rows == [{"id": 1}, {"id": 2}]+ # The page is short, so we stop without persisting resume state.+ assert manager.saved == []++ def test_follows_offset_pagination_until_short_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {0: _full_page(0), PAGE_SIZE: [{"id": 999}]}+ rows = self._collect(manager, monkeypatch, pages)+ assert len(rows) == PAGE_SIZE + 1+ # State is saved after the full first page (offset advances by its row count), then we stop.+ assert [s.offset for s in manager.saved] == [PAGE_SIZE]++ def test_resumes_from_saved_offset_and_pinned_window(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(ShopWiredResumeConfig(offset=200, from_timestamp=1700000000))+ requested: list[dict] = []+ rows = self._collect(+ manager,+ monkeypatch,+ {200: [{"id": 5}]},+ endpoint="orders",+ # A watermark that advanced mid-run must not replace the pinned window from the resume state.+ db_incremental_field_last_value=datetime(2024, 6, 1, tzinfo=UTC),+ requested_params=requested,+ )+ assert rows == [{"id": 5}]+ assert requested[0]["offset"] == 200+ assert requested[0]["from"] == 1700000000++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {0: []})+ assert rows == []+ assert manager.saved == []++ def test_incremental_run_sends_from_and_sort_params(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ requested: list[dict] = []+ watermark = datetime(2024, 1, 1, tzinfo=UTC)+ self._collect(+ manager,+ monkeypatch,+ {0: [{"id": 1}]},+ endpoint="orders",+ db_incremental_field_last_value=watermark,+ requested_params=requested,+ )+ assert requested[0]["from"] == int(watermark.timestamp())+ assert requested[0]["sort"] == "date"++ def test_full_refresh_run_omits_from_param(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ requested: list[dict] = []+ self._collect(manager, monkeypatch, {0: [{"id": 1}]}, endpoint="products", requested_params=requested)+ assert "from" not in requested[0]+ assert "sort" not in requested[0]++ def test_unpaginated_endpoint_fetches_once(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ requested: list[dict] = []+ # A full-size page must not trigger a second request — order statuses document no pagination.+ rows = self._collect(+ manager, monkeypatch, {0: _full_page(0)}, endpoint="order_statuses", requested_params=requested+ )+ assert len(rows) == PAGE_SIZE+ assert len(requested) == 1+ assert requested[0] == {}+ assert manager.saved == []+++class TestToUnixTimestamp:+ @parameterized.expand(+ [+ ("none", None, None),+ ("datetime", datetime(2024, 1, 1, tzinfo=UTC), 1704067200),+ # Naive values must be treated as UTC regardless of the worker's local timezone.+ ("naive_datetime", datetime(2024, 1, 1), 1704067200),+ ("date", date(2024, 1, 1), 1704067200),+ ("epoch_int", 1704067200, 1704067200),+ ("epoch_float", 1704067200.5, 1704067200),+ ("rfc2822_string", "Mon, 01 Jan 2024 00:00:00 +0000", 1704067200),+ ("iso_string", "2024-01-01T00:00:00+00:00", 1704067200),+ ("naive_iso_string", "2024-01-01T00:00:00", 1704067200),+ ("unparseable_string", "not-a-date-at-all-99", None),+ ("empty_string", "", None),+ ]+ )+ def test_conversion(self, _name: str, value: Any, expected: int | None) -> None:+ assert to_unix_timestamp(value) == expected++ def test_naive_values_are_utc_regardless_of_local_timezone(self, monkeypatch: Any) -> None:+ # CI runs in UTC, where a local-time interpretation of naive values happens to give the+ # right answer — force a non-UTC timezone so a regression to naive .timestamp() fails here.+ monkeypatch.setenv("TZ", "America/New_York")+ time.tzset()+ try:+ assert to_unix_timestamp(date(2024, 1, 1)) == 1704067200+ assert to_unix_timestamp(datetime(2024, 1, 1)) == 1704067200+ assert to_unix_timestamp("2024-01-01T00:00:00") == 1704067200+ finally:+ monkeypatch.undo()+ time.tzset()+++class TestFetchPage:+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body if body is not None else []+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(ShopWiredRetryableError):+ _fetch_page_unwrapped(session, "/products", {"count": PAGE_SIZE, "offset": 0}, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "/products", {"count": PAGE_SIZE, "offset": 0}, MagicMock())++ def test_success_returns_bare_array(self) -> None:+ session = self._session_returning(200, [{"id": 1}])+ assert _fetch_page_unwrapped(session, "/products", {}, MagicMock()) == [{"id": 1}]++ def test_non_list_body_is_retryable(self) -> None:+ session = self._session_returning(200, {"error": "unexpected"})+ with pytest.raises(ShopWiredRetryableError):+ _fetch_page_unwrapped(session, "/products", {}, MagicMock())++ def test_params_are_passed_through(self) -> None:+ session = self._session_returning(200, [])+ params = {"count": PAGE_SIZE, "offset": 300, "sort": "date", "from": 1700000000}+ _fetch_page_unwrapped(session, "/orders", params, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == params+++class TestCheckAccess:+ @staticmethod+ def _session(response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ return session++ @parameterized.expand(+ [+ ("ok", 200, True, 200, None),+ ("unauthorized", 401, False, 401, None),+ ("forbidden", 403, False, 403, None),+ ("server_error", 500, False, 500, "ShopWired returned HTTP 500"),+ ]+ )+ @patch(f"{shopwired.__name__}.make_tracked_session")+ def test_status_mapping(+ self,+ _name: str,+ status: int,+ ok: bool,+ expected_status: int,+ expected_message: str | None,+ mock_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ mock_session.return_value = self._session(response)+ assert check_access("sw-key", "sw-secret") == (expected_status, expected_message)++ @patch(f"{shopwired.__name__}.make_tracked_session")+ def test_connection_error_maps_to_zero(self, mock_session: MagicMock) -> None:+ mock_session.return_value = self._session(requests.ConnectionError("boom"))+ status, message = check_access("sw-key", "sw-secret")+ assert status == 0+ assert message is not None and "boom" in message++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid ShopWired API key or secret"),+ ("forbidden", 403, False, "Invalid ShopWired API key or secret"),+ ("server_error", 500, False, "ShopWired returned HTTP 500"),+ ]+ )+ @patch(f"{shopwired.__name__}.make_tracked_session")+ def test_validate_credentials(+ self,+ _name: str,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ mock_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ mock_session.return_value = self._session(response)+ assert validate_credentials("sw-key", "sw-secret") == (expected_valid, expected_message)+++class TestShopWiredSourceResponse:+ @parameterized.expand([(name,) for name in SHOPWIRED_ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = shopwired_source(+ api_key="sw-key",+ api_secret="sw-secret",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "asc"++ def test_orders_partition_on_stable_created_field(self) -> None:+ response = shopwired_source(+ api_key="sw-key",+ api_secret="sw-secret",+ endpoint="orders",+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created"]++ def test_non_order_endpoints_have_no_datetime_partition(self) -> None:+ response = shopwired_source(+ api_key="sw-key",+ api_secret="sw-secret",+ endpoint="products",+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopwired/tests/test_shopwired_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopwired/tests/test_shopwired_source.pynew file mode 100644index 000000000000..5e6640b82099--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopwired/tests/test_shopwired_source.py@@ -0,0 +1,140 @@+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.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ShopWiredSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.shopwired.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.shopwired.shopwired import ShopWiredResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.shopwired.source import ShopWiredSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestShopWiredSource:+ def setup_method(self) -> None:+ self.source = ShopWiredSource()+ self.team_id = 123+ self.config = ShopWiredSourceConfig(api_key="sw-key", api_secret="sw-secret")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.SHOPWIRED++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "ShopWired"+ assert config.label == "ShopWired"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/shopwired"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key", "api_secret"]++ @parameterized.expand([("api_key",), ("api_secret",)])+ def test_credential_fields_are_secret_passwords(self, field_name: str) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == field_name)+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_no_connection_host_fields(self) -> None:+ # Both fields are secrets and the base URL is hardcoded, so there is no non-secret field an+ # editor could retarget to reuse preserved credentials against another host.+ assert self.source.connection_host_fields == []++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_only_orders_supports_incremental(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ by_name = {s.name: s for s in schemas}+ assert by_name["orders"].supports_incremental is True+ assert [f["field"] for f in by_name["orders"].incremental_fields] == ["created"]+ for name, schema in by_name.items():+ if name == "orders":+ continue+ assert schema.supports_incremental is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["orders"])+ assert len(schemas) == 1+ assert schemas[0].name == "orders"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)+ orders = next(t for t in tables if t["name"] == "orders")+ assert "Incremental" in orders["sync_methods"]++ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.ecommerceapi.uk/v1/orders?count=100",+ ),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.ecommerceapi.uk/v1/products?count=100"),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.ecommerceapi.uk/v1/orders"),+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.ecommerceapi.uk/v1/products"),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.shopwired.source.validate_credentials"+ )+ def test_validate_credentials_delegates_with_credentials(self, mock_validate: mock.MagicMock) -> None:+ # The status-to-message mapping lives in shopwired.validate_credentials; here we only assert the+ # source probes with the configured credentials and returns the delegate's verdict unchanged.+ mock_validate.return_value = (False, "Invalid ShopWired API key or secret")+ result = self.source.validate_credentials(self.config, self.team_id)+ mock_validate.assert_called_once_with("sw-key", "sw-secret")+ assert result == (False, "Invalid ShopWired API key or secret")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is ShopWiredResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.shopwired.source.shopwired_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "orders"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = 1700000000+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "sw-key"+ assert kwargs["api_secret"] == "sw-secret"+ assert kwargs["endpoint"] == "orders"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == 1700000000++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown ShopWired schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)