: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 printify import source (#69369)
Tom Owersa2d49e818134
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 32ac31bbda68..8500a4f01da8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -292,6 +292,7 @@ the row lists both.| postgres | DB protocol | psycopg | ➖ || postmark | HTTP | requests | ✅ || pretix | HTTP | requests | ✅ |+| printify | HTTP | requests | ✅ || productboard | HTTP | requests | ✅ || pylon | HTTP | requests | ✅ || qualaroo | HTTP | requests | ✅ |@@ -657,7 +658,6 @@ doesn't conflict with concurrent PRs.- poplar- prestashop- primetric-- printify- productive- pypi- qontodiff --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 deda57cae7ef..16109767bf78 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@@ -2739,7 +2739,7 @@ class PrimetricSourceConfig(config.Config):@config.configclass PrintifySourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/printify/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/printify/canonical_descriptions.pynew file mode 100644index 000000000000..bc1c1b668848--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/printify/canonical_descriptions.py@@ -0,0 +1,103 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Printify API docs (https://developers.printify.com).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "shops": {+ "description": "A sales channel (shop) connected to your Printify account, e.g. a Shopify or Etsy store.",+ "docs_url": "https://developers.printify.com/#shops",+ "columns": {+ "id": "The unique ID of the shop.",+ "title": "The shop's display name.",+ "sales_channel": "The sales channel platform the shop is connected to (e.g. shopify, etsy).",+ },+ },+ "products": {+ "description": "A product created in a Printify shop, including its variants, print areas, and publishing state.",+ "docs_url": "https://developers.printify.com/#products",+ "columns": {+ "id": "The unique ID of the product.",+ "shop_id": "The ID of the shop the product belongs to.",+ "title": "The product's name.",+ "description": "The product's description.",+ "tags": "Tags attached to the product.",+ "options": "Purchase options (e.g. color, size) and their values.",+ "variants": "All variant combinations of the product with pricing and availability.",+ "images": "Mock-up images of the product.",+ "created_at": "When the product was created.",+ "updated_at": "When the product was last updated.",+ "visible": "Whether the product is visible in the connected sales channel.",+ "blueprint_id": "The ID of the catalog blueprint the product is based on.",+ "print_provider_id": "The ID of the print provider fulfilling the product.",+ "print_areas": "The design placeholders and artwork placed on the product.",+ "is_locked": "Whether the product is locked because it has pending orders.",+ },+ },+ "orders": {+ "description": "An order submitted to Printify for fulfillment, including line items, shipping, and status.",+ "docs_url": "https://developers.printify.com/#orders",+ "columns": {+ "id": "The unique ID of the order.",+ "shop_id": "The ID of the shop the order belongs to.",+ "address_to": "The delivery address of the order.",+ "line_items": "The products and variants included in the order.",+ "metadata": "Order metadata, including the sales-channel order id and shop order number.",+ "total_price": "The total price of the order, in cents.",+ "total_shipping": "The total shipping cost of the order, in cents.",+ "total_tax": "The total tax on the order, in cents.",+ "status": "The production status of the order (e.g. pending, in-production, fulfilled).",+ "shipping_method": "The ID of the shipping method selected for the order.",+ "shipments": "Carrier and tracking information for the order's shipments.",+ "created_at": "When the order was created.",+ "sent_to_production_at": "When the order was sent to production.",+ "fulfilled_at": "When the order was fulfilled.",+ },+ },+ "uploads": {+ "description": "An artwork image uploaded to your Printify media library.",+ "docs_url": "https://developers.printify.com/#uploads",+ "columns": {+ "id": "The unique ID of the uploaded image.",+ "file_name": "The file name of the uploaded image.",+ "height": "The image height in pixels.",+ "width": "The image width in pixels.",+ "size": "The file size in bytes.",+ "mime_type": "The MIME type of the image file.",+ "preview_url": "A URL to preview the image.",+ "upload_time": "When the image was uploaded.",+ },+ },+ "webhooks": {+ "description": "A webhook subscription registered on a Printify shop.",+ "docs_url": "https://developers.printify.com/#webhooks",+ "columns": {+ "id": "The unique ID of the webhook.",+ "shop_id": "The ID of the shop the webhook is registered on.",+ "topic": "The event topic the webhook is subscribed to (e.g. order:created).",+ "url": "The URL webhook events are delivered to.",+ },+ },+ "blueprints": {+ "description": "A catalog blueprint — a base product (e.g. a t-shirt model) that shop products are built from.",+ "docs_url": "https://developers.printify.com/#catalog",+ "columns": {+ "id": "The unique ID of the blueprint.",+ "title": "The blueprint's name.",+ "description": "The blueprint's description.",+ "brand": "The brand of the underlying garment or product.",+ "model": "The manufacturer model of the underlying garment or product.",+ "images": "Preview images of the blueprint.",+ },+ },+ "print_providers": {+ "description": "A print provider available in the Printify catalog to fulfill products.",+ "docs_url": "https://developers.printify.com/#catalog",+ "columns": {+ "id": "The unique ID of the print provider.",+ "title": "The print provider's name.",+ "location": "The print provider's location address.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/printify/printify.py b/products/warehouse_sources/backend/temporal/data_imports/sources/printify/printify.pynew file mode 100644index 000000000000..c693df1f5eb5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/printify/printify.py@@ -0,0 +1,262 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import urlsplit++import requests+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.printify.settings import (+ PRINTIFY_ENDPOINTS,+ PrintifyEndpointConfig,+)++PRINTIFY_BASE_URL = "https://api.printify.com/v1"+REQUEST_TIMEOUT_SECONDS = 60+# Cheap endpoint used to confirm a token is genuine. Every shop-scoped stream needs the shop list+# anyway, so `shops.read` access is effectively required for the source to work at all.+DEFAULT_PROBE_PATH = "/shops.json"+++class PrintifyRetryableError(Exception):+ pass+++class PrintifyResumeConfig:+ # Shop currently being iterated for shop-scoped endpoints; None for account-level endpoints.+ # A resumed sync re-fetches this shop from `page`; merge dedupes re-pulled rows on the+ # primary key.+ shop_id: int | None = None+ # Next page to fetch (1-based, Laravel-style page numbers). Ignored by non-paginated endpoints.+ page: int = 1+++def _headers(api_key: str) -> dict[str, str]:+ # Printify requires a User-Agent header on every request.+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ "User-Agent": "PostHog",+ }+++@retry(+ retry=retry_if_exception_type((PrintifyRetryableError, 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,+ page: int | None,+ limit: int | None,+ logger: FilteringBoundLogger,+) -> tuple[list[dict[str, Any]], bool]:+ params: dict[str, Any] = {}+ if page is not None:+ params["page"] = page+ if limit is not None:+ params["limit"] = limit++ response = session.get(+ f"{PRINTIFY_BASE_URL}{path}",+ params=params or None,+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ # Printify throttles at 600 req/min globally (100 req/min on catalog endpoints) with HTTP 429.+ if response.status_code == 429 or response.status_code >= 500:+ raise PrintifyRetryableError(f"Printify API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"Printify API error: status={response.status_code}, body={response.text}, path={path}")+ # raise_for_status() would embed the full request URL in the exception, which is surfaced+ # as the schema's latest_error outside the warehouse table ACLs. Printify authenticates via+ # the Authorization header today, but rebuild the error from scheme/host/path only so a+ # redirect or future query-param auth can never leak credentials into stored error state.+ # The "<status> Client Error: <reason> for url: https://api.printify.com" prefix stays+ # stable for get_non_retryable_errors() matching.+ safe = urlsplit(response.url)+ raise requests.HTTPError(+ f"{response.status_code} Client Error: {response.reason} for url: {safe.scheme}://{safe.netloc}{safe.path}",+ response=response,+ )++ data = response.json()++ # Non-paginated endpoints (shops, webhooks, catalog) return a bare JSON array.+ if isinstance(data, list):+ return data, False++ # Paginated endpoints return a Laravel paginator: {"current_page", "data": [...], "last_page",+ # "next_page_url", ...}.+ if isinstance(data, dict) and isinstance(data.get("data"), list):+ items: list[dict[str, Any]] = data["data"]+ current_page = data.get("current_page")+ last_page = data.get("last_page")+ if isinstance(current_page, int) and isinstance(last_page, int):+ has_more = current_page < last_page+ else:+ has_more = bool(data.get("next_page_url"))+ return items, has_more and bool(items)++ raise PrintifyRetryableError(f"Printify returned an unexpected payload for {path}: {type(data).__name__}")+++def _prepare_rows(+ config: PrintifyEndpointConfig, items: list[dict[str, Any]], shop_id: int | None+) -> list[dict[str, Any]]:+ rows = items+ if config.redact_fields:+ redacted = set(config.redact_fields)+ rows = [{key: value for key, value in row.items() if key not in redacted} for row in rows]+ if shop_id is not None:+ # Shop-scoped objects don't reliably carry their shop id, and the composite primary key+ # needs it. Webhook objects that already include one keep the API's own value.+ rows = [{**row, "shop_id": row.get("shop_id", shop_id)} for row in rows]+ return rows+++def _iter_endpoint_pages(+ session: requests.Session,+ config: PrintifyEndpointConfig,+ path: str,+ start_page: int,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PrintifyResumeConfig],+ shop_id: int | None,+) -> Iterator[list[dict[str, Any]]]:+ if not config.paginated:+ items, _ = _fetch_page(session, path, None, None, logger)+ if items:+ yield _prepare_rows(config, items, shop_id)+ # Save AFTER yielding so a crash resumes at this shop — re-fetching it once is+ # idempotent because merge dedupes on the primary key.+ if shop_id is not None:+ resumable_source_manager.save_state(PrintifyResumeConfig(shop_id=shop_id, page=1))+ return++ page = start_page+ while True:+ items, has_more = _fetch_page(session, path, page, config.page_size, logger)+ if items:+ yield _prepare_rows(config, items, shop_id)++ if not has_more or not items:+ break++ page += 1+ # 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(PrintifyResumeConfig(shop_id=shop_id, page=page))+++def _list_shops(session: requests.Session, logger: FilteringBoundLogger) -> list[dict[str, Any]]:+ shops, _ = _fetch_page(session, PRINTIFY_ENDPOINTS["shops"].path, None, None, logger)+ return shops+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PrintifyResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = PRINTIFY_ENDPOINTS[endpoint]+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if not config.shop_scoped:+ start_page = resume.page if resume else 1+ if resume:+ logger.debug(f"Printify: resuming {endpoint} from page {start_page}")+ yield from _iter_endpoint_pages(+ session, config, config.path, start_page, logger, resumable_source_manager, shop_id=None+ )+ return++ shops = _list_shops(session, logger)+ resume_shop_id = resume.shop_id if resume else None+ resume_page = resume.page if resume else 1+ if resume_shop_id is not None and all(shop["id"] != resume_shop_id for shop in shops):+ # The saved shop no longer exists (disconnected sales channel); start from the beginning.+ logger.debug(f"Printify: saved shop {resume_shop_id} not found, restarting {endpoint} from the first shop")+ resume_shop_id = None++ if resume_shop_id is not None:+ logger.debug(f"Printify: resuming {endpoint} from shop {resume_shop_id}, page {resume_page}")++ skipping = resume_shop_id is not None+ for shop in shops:+ shop_id = shop["id"]+ if skipping:+ if shop_id != resume_shop_id:+ continue+ skipping = False+ start_page = resume_page+ else:+ start_page = 1++ path = config.path.format(shop_id=shop_id)+ yield from _iter_endpoint_pages(+ session, config, path, start_page, logger, resumable_source_manager, shop_id=shop_id+ )+++def printify_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PrintifyResumeConfig],+) -> SourceResponse:+ config = PRINTIFY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )+++def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the API token.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))+ try:+ response = session.get(f"{PRINTIFY_BASE_URL}{path}", timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Printify: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Printify returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ status, message = check_access(api_key)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Printify API token"+ return False, message or "Could not validate Printify API token"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/printify/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/printify/settings.pynew file mode 100644index 000000000000..ee289d15e3e4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/printify/settings.py@@ -0,0 +1,66 @@+from dataclasses import dataclass, field+++@dataclass+class PrintifyEndpointConfig:+ name: str+ # Path relative to the API base URL; `{shop_id}` is filled per shop for shop-scoped endpoints.+ path: str+ # Most Printify resources (products, orders, webhooks) live under a shop, so the source lists+ # shops first and fans out per shop.+ shop_scoped: bool = False+ # Laravel-style page-number pagination (`?page=`, `current_page`/`last_page`/`next_page_url`).+ # Non-paginated endpoints return a bare JSON array in one response.+ paginated: bool = False+ # Value for the `limit` query param; None means the endpoint doesn't accept one.+ page_size: int | None = None+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Fields stripped from rows before they're yielded (credentials that must not land in a+ # warehouse table).+ redact_fields: list[str] = field(default_factory=list)+++# Printify REST API v1 list endpoints (https://developers.printify.com). All are full-refresh only:+# no list endpoint documents a server-side `updated_at`/`since` filter, so there is no incremental+# cursor to advance. Shop-scoped endpoints use a composite primary key — object ids look globally+# unique (Mongo-style), but the docs don't guarantee it, so the shop id is included to be safe.+PRINTIFY_ENDPOINTS: dict[str, PrintifyEndpointConfig] = {+ "shops": PrintifyEndpointConfig(name="shops", path="/shops.json"),+ "products": PrintifyEndpointConfig(+ name="products",+ path="/shops/{shop_id}/products.json",+ shop_scoped=True,+ paginated=True,+ page_size=100,+ primary_keys=["shop_id", "id"],+ ),+ "orders": PrintifyEndpointConfig(+ name="orders",+ path="/shops/{shop_id}/orders.json",+ shop_scoped=True,+ paginated=True,+ # The orders endpoint caps results at 10 per page, so we rely on the API default.+ page_size=None,+ primary_keys=["shop_id", "id"],+ ),+ "uploads": PrintifyEndpointConfig(+ name="uploads",+ path="/uploads.json",+ paginated=True,+ page_size=100,+ ),+ "webhooks": PrintifyEndpointConfig(+ name="webhooks",+ path="/shops/{shop_id}/webhooks.json",+ shop_scoped=True,+ primary_keys=["shop_id", "id"],+ # A webhook's signing secret would let any table reader forge Printify webhook requests.+ redact_fields=["secret"],+ ),+ "blueprints": PrintifyEndpointConfig(name="blueprints", path="/catalog/blueprints.json"),+ "print_providers": PrintifyEndpointConfig(name="print_providers", path="/catalog/print_providers.json"),+}++ENDPOINTS = tuple(PRINTIFY_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/printify/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/printify/source.pyindex e974ece46518..b796fa4db020 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/printify/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/printify/source.py@@ -1,19 +1,42 @@-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 PrintifySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.printify.printify import (+ PrintifyResumeConfig,+ printify_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.printify.settings import (+ ENDPOINTS,+ PRINTIFY_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class PrintifySource(SimpleSource[PrintifySourceConfig]):+class PrintifySource(ResumableSource[PrintifySourceConfig, PrintifyResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PRINTIFY@@ -24,7 +47,88 @@ class PrintifySource(SimpleSource[PrintifySourceConfig]):name=SchemaExternalDataSourceType.PRINTIFY,category=DataWarehouseSourceCategory.E_COMMERCE,label="Printify",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Printify personal access token to pull your print-on-demand data into the PostHog Data warehouse.++You can generate a token under **My Profile → Connections** in [Printify](https://printify.com). The token needs the `shops.read`, `products.read`, `orders.read`, `uploads.read`, `webhooks.read`, and `catalog.read` scopes. Personal access tokens expire after one year.+""",iconPath="/static/services/printify.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/printify",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API token",+ 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.printify.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.printify.com": "Your Printify API token is invalid or has expired. Generate a new token under My Profile → Connections, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.printify.com": "Your Printify API token does not have access to this data. Check the token's scopes, then reconnect.",+ }++ def get_schemas(+ self,+ config: PrintifySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — Printify's list endpoints expose no server-side+ # `updated_at`/`since` filter, so there is no incremental cursor to advance.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ 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: PrintifySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # One probe against the shop list validates the token; the shop list is also a hard+ # prerequisite for every shop-scoped stream, so this is the scope that matters most.+ return validate_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PrintifyResumeConfig]:+ return ResumableSourceManager[PrintifyResumeConfig](inputs, PrintifyResumeConfig)++ def source_for_pipeline(+ self,+ config: PrintifySourceConfig,+ resumable_source_manager: ResumableSourceManager[PrintifyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in PRINTIFY_ENDPOINTS:+ raise ValueError(f"Unknown Printify schema '{inputs.schema_name}'")++ return printify_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/printify/tests/test_printify.py b/products/warehouse_sources/backend/temporal/data_imports/sources/printify/tests/test_printify.pynew file mode 100644index 000000000000..0e14fc0ea3cd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/printify/tests/test_printify.py@@ -0,0 +1,320 @@+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.printify import printify+from products.warehouse_sources.backend.temporal.data_imports.sources.printify.printify import (+ PrintifyResumeConfig,+ PrintifyRetryableError,+ check_access,+ get_rows,+ printify_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.printify.settings import (+ ENDPOINTS,+ PRINTIFY_ENDPOINTS,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = printify._fetch_page.__wrapped__ # type: ignore[attr-defined]++# (path, page) -> (items, has_more), the shape _fetch_page returns per request.+_Pages = dict[tuple[str, int | None], tuple[list[dict], bool]]+++class _FakeResumableManager:+ def __init__(self, state: PrintifyResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[PrintifyResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> PrintifyResumeConfig | None:+ return self._state++ def save_state(self, data: PrintifyResumeConfig) -> None:+ self.saved.append(data)+++class TestFetchPage:+ def _session_returning(+ self,+ status_code: int,+ body: Any = None,+ url: str = "https://api.printify.com/v1/shops.json",+ reason: str = "Error",+ ) -> 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.url = url+ response.reason = reason+ 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(PrintifyRetryableError):+ _fetch_page_unwrapped(session, "/shops.json", None, None, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_http_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "/shops.json", None, None, MagicMock())++ def test_client_error_scrubs_query_string_and_keeps_non_retryable_prefix(self) -> None:+ # Printify authenticates via header today, but a redirect or future query-param auth must+ # never land in the rebuilt HTTPError (surfaced as the schema's latest_error). The status+ # and host prefix stays stable so get_non_retryable_errors() still matches.+ session = self._session_returning(+ 401, url="https://api.printify.com/v1/shops.json?token=SECRET&page=1", reason="Unauthorized"+ )+ with pytest.raises(requests.HTTPError) as exc:+ _fetch_page_unwrapped(session, "/shops.json", 1, None, MagicMock())+ assert str(exc.value) == "401 Client Error: Unauthorized for url: https://api.printify.com/v1/shops.json"++ def test_bare_array_response_has_no_more_pages(self) -> None:+ session = self._session_returning(200, [{"id": 1}, {"id": 2}])+ items, has_more = _fetch_page_unwrapped(session, "/shops.json", None, None, MagicMock())+ assert items == [{"id": 1}, {"id": 2}]+ assert has_more is False++ @parameterized.expand(+ [+ ("mid_pagination", {"current_page": 1, "last_page": 3, "data": [{"id": "a"}]}, True),+ ("last_page", {"current_page": 3, "last_page": 3, "data": [{"id": "a"}]}, False),+ ("empty_page", {"current_page": 1, "last_page": 3, "data": []}, False),+ ("next_url_fallback", {"data": [{"id": "a"}], "next_page_url": "https://api.printify.com/?page=2"}, True),+ ("null_next_url_fallback", {"data": [{"id": "a"}], "next_page_url": None}, False),+ ]+ )+ def test_paginator_termination(self, _name: str, body: dict, expected_has_more: bool) -> None:+ session = self._session_returning(200, body)+ items, has_more = _fetch_page_unwrapped(session, "/shops/1/products.json", 1, 100, MagicMock())+ assert items == body["data"]+ assert has_more is expected_has_more++ @parameterized.expand(+ [+ ("string_body", "nope"),+ ("dict_without_data", {"error": "oops"}),+ ("data_not_a_list", {"data": {"id": 1}}),+ ]+ )+ def test_malformed_payload_is_retryable(self, _name: str, body: Any) -> None:+ session = self._session_returning(200, body)+ with pytest.raises(PrintifyRetryableError):+ _fetch_page_unwrapped(session, "/shops/1/products.json", 1, 100, MagicMock())++ @parameterized.expand(+ [+ ("page_and_limit", 2, 100, {"page": 2, "limit": 100}),+ ("page_without_limit", 2, None, {"page": 2}),+ ("no_pagination_params", None, None, None),+ ]+ )+ def test_request_params(self, _name: str, page: int | None, limit: int | None, expected: dict | None) -> None:+ session = self._session_returning(200, [])+ _fetch_page_unwrapped(session, "/shops/1/orders.json", page, limit, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == expected+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: _Pages,+ endpoint: str,+ ) -> list[dict]:+ def fake_fetch(+ session: Any, path: str, page: int | None, limit: int | None, logger: Any+ ) -> tuple[list[dict], bool]:+ return pages[(path, page)]++ monkeypatch.setattr(printify, "_fetch_page", fake_fetch)+ monkeypatch.setattr(printify, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="printify-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_shop_fanout_injects_shop_id_into_rows(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages: _Pages = {+ ("/shops.json", None): ([{"id": 111}, {"id": 222}], False),+ ("/shops/111/products.json", 1): ([{"id": "p1"}], False),+ ("/shops/222/products.json", 1): ([{"id": "p2"}], False),+ }+ rows = self._collect(manager, monkeypatch, pages, "products")+ assert rows == [{"id": "p1", "shop_id": 111}, {"id": "p2", "shop_id": 222}]++ def test_webhook_rows_keep_api_shop_id_and_drop_signing_secret(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages: _Pages = {+ ("/shops.json", None): ([{"id": 111}], False),+ ("/shops/111/webhooks.json", None): ([{"id": "w1", "shop_id": "111", "secret": "whsec_123"}], False),+ }+ rows = self._collect(manager, monkeypatch, pages, "webhooks")+ # The signing secret must never reach the warehouse — a reader could forge webhook requests.+ assert rows == [{"id": "w1", "shop_id": "111"}]++ def test_paginated_fanout_saves_state_after_each_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages: _Pages = {+ ("/shops.json", None): ([{"id": 111}], False),+ ("/shops/111/products.json", 1): ([{"id": "p1"}], True),+ ("/shops/111/products.json", 2): ([{"id": "p2"}], False),+ }+ rows = self._collect(manager, monkeypatch, pages, "products")+ assert [r["id"] for r in rows] == ["p1", "p2"]+ assert [(s.shop_id, s.page) for s in manager.saved] == [(111, 2)]++ def test_resume_skips_earlier_shops_and_starts_at_saved_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(PrintifyResumeConfig(shop_id=222, page=3))+ # Pages for shop 111 (and pages 1-2 of shop 222) are deliberately absent — fetching them+ # would KeyError, proving the resume path never re-fetches them.+ pages: _Pages = {+ ("/shops.json", None): ([{"id": 111}, {"id": 222}, {"id": 333}], False),+ ("/shops/222/products.json", 3): ([{"id": "p3"}], False),+ ("/shops/333/products.json", 1): ([{"id": "p4"}], False),+ }+ rows = self._collect(manager, monkeypatch, pages, "products")+ assert [r["id"] for r in rows] == ["p3", "p4"]++ def test_resume_with_vanished_shop_restarts_from_first_shop(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(PrintifyResumeConfig(shop_id=999, page=5))+ pages: _Pages = {+ ("/shops.json", None): ([{"id": 111}], False),+ ("/shops/111/products.json", 1): ([{"id": "p1"}], False),+ }+ rows = self._collect(manager, monkeypatch, pages, "products")+ assert [r["id"] for r in rows] == ["p1"]++ def test_account_level_paginated_endpoint_resumes_from_saved_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(PrintifyResumeConfig(shop_id=None, page=2))+ pages: _Pages = {+ ("/uploads.json", 2): ([{"id": "u2"}], False),+ }+ rows = self._collect(manager, monkeypatch, pages, "uploads")+ assert [r["id"] for r in rows] == ["u2"]++ def test_non_paginated_account_endpoint_yields_once_without_state(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages: _Pages = {+ ("/catalog/blueprints.json", None): ([{"id": 5}, {"id": 6}], False),+ }+ rows = self._collect(manager, monkeypatch, pages, "blueprints")+ assert [r["id"] for r in rows] == [5, 6]+ assert manager.saved == []++ def test_non_paginated_fanout_saves_state_per_shop(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages: _Pages = {+ ("/shops.json", None): ([{"id": 111}, {"id": 222}], False),+ ("/shops/111/webhooks.json", None): ([{"id": "w1"}], False),+ ("/shops/222/webhooks.json", None): ([], False),+ }+ self._collect(manager, monkeypatch, pages, "webhooks")+ assert [(s.shop_id, s.page) for s in manager.saved] == [(111, 1), (222, 1)]+++class TestPrintifySourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = printify_source(+ api_key="printify-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == PRINTIFY_ENDPOINTS[endpoint].primary_keys++ def test_shop_scoped_endpoints_use_composite_primary_key(self) -> None:+ for config in PRINTIFY_ENDPOINTS.values():+ expected = ["shop_id", "id"] if config.shop_scoped else ["id"]+ assert config.primary_keys == expected, config.name+++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, "Printify returned HTTP 500"),+ ]+ )+ @patch(f"{printify.__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("printify-key") == (expected_status, expected_message)++ @patch(f"{printify.__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("printify-key")+ assert status == 0+ assert message is not None and "boom" in message++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid Printify API token"),+ ("forbidden", 403, False, "Invalid Printify API token"),+ ("server_error", 500, False, "Printify returned HTTP 500"),+ ]+ )+ @patch(f"{printify.__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("printify-key") == (expected_valid, expected_message)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/printify/tests/test_printify_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/printify/tests/test_printify_source.pynew file mode 100644index 000000000000..4b58ae6f2def--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/printify/tests/test_printify_source.py@@ -0,0 +1,134 @@+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 PrintifySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.printify.printify import PrintifyResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.printify.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.printify.source import PrintifySource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestPrintifySource:+ def setup_method(self) -> None:+ self.source = PrintifySource()+ self.team_id = 123+ self.config = PrintifySourceConfig(api_key="printify-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.PRINTIFY++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Printify"+ assert config.label == "Printify"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/printify"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_no_connection_host_fields(self) -> None:+ # The only field is the secret API token; the base URL is hardcoded, so there is no+ # non-secret field an editor could retarget to reuse a preserved token 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_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["products"])+ assert len(schemas) == 1+ assert schemas[0].name == "products"++ 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)++ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.printify.com/v1/shops.json",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://api.printify.com/v1/shops/1/orders.json?page=1",+ ),+ ]+ )+ 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.printify.com/v1/shops.json",+ ),+ (+ "rate_limited",+ "429 Client Error: Too Many Requests for url: https://api.printify.com/v1/catalog/blueprints.json",+ ),+ ]+ )+ 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.printify.source.validate_credentials")+ def test_validate_credentials_delegates_with_api_key(self, mock_validate: mock.MagicMock) -> None:+ # The status-to-message mapping lives in printify.validate_credentials; here we only assert+ # the source probes with the configured token and returns the delegate's verdict unchanged.+ mock_validate.return_value = (False, "Invalid Printify API token")+ result = self.source.validate_credentials(self.config, self.team_id)+ mock_validate.assert_called_once_with("printify-key")+ assert result == (False, "Invalid Printify API token")++ 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 PrintifyResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.printify.source.printify_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "orders"+ 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"] == "printify-key"+ assert kwargs["endpoint"] == "orders"+ assert kwargs["resumable_source_manager"] is manager++ 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 Printify schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)