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): implement etsy source (#73780)

Tom Owers6fcaf2983cdf
diff --git a/frontend/public/services/etsy.png b/frontend/public/services/etsy.png
index 64d3ef7bf878..0d0d81dfdc13 100644
Binary files a/frontend/public/services/etsy.png and b/frontend/public/services/etsy.png differ
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 909964ad047a..0334ad10a05d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -218,6 +218,7 @@ the row lists both.
| easypromos | HTTP | requests | ✅ |
| elevenlabs | HTTP | requests | ✅ |
| eppo | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| etsy | HTTP | requests | ✅ |
| freshcaller | HTTP | requests | ✅ |
| freshchat | HTTP | requests | ✅ |
| freshdesk | HTTP | requests | ✅ |
@@ -904,7 +905,6 @@ doesn't conflict with concurrent PRs.
- employment_hero
- encharge
- entsoe
-- etsy
- eurostat
- expensify
- facebook_pages
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/canonical_descriptions.py
new file mode 100644
index 000000000000..d6981198e738
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/canonical_descriptions.py
@@ -0,0 +1,161 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS = "https://developers.etsy.com/documentation/reference"
+
+# Descriptions sourced from the Etsy Open API v3 reference. Partial coverage is fine — any table or
+# column not listed here falls back to LLM enrichment. Every timestamp column is Unix epoch seconds.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "shop": {
+ "description": "The Etsy shop this connection syncs, including its policies, currency and listing counts.",
+ "docs_url": f"{_DOCS}#operation/getShop",
+ "columns": {
+ "shop_id": "Unique identifier for the shop.",
+ "shop_name": "The shop's name as it appears on Etsy.",
+ "user_id": "Numeric id of the Etsy user who owns the shop.",
+ "create_date": "Deprecated alias of created_timestamp.",
+ "created_timestamp": "Unix epoch seconds when the shop was created.",
+ "title": "Short tagline shown under the shop name.",
+ "announcement": "Announcement banner text currently shown on the shop page.",
+ "currency_code": "ISO currency code the shop lists prices in.",
+ "is_vacation": "Whether the shop is currently in vacation mode.",
+ "listing_active_count": "Number of listings currently active in the shop.",
+ "digital_listing_count": "Number of digital (download) listings in the shop.",
+ "url": "Public URL of the shop.",
+ "num_favorers": "Number of Etsy users who have favorited the shop.",
+ "review_count": "Total number of reviews the shop has received.",
+ "review_average": "Average review rating across the shop's reviews.",
+ },
+ },
+ "shop_sections": {
+ "description": "Seller-defined sections used to group listings within the shop.",
+ "docs_url": f"{_DOCS}#operation/getShopSections",
+ "columns": {
+ "shop_section_id": "Unique identifier for the section.",
+ "title": "Display name of the section.",
+ "rank": "Position of the section in the shop's navigation.",
+ "user_id": "Numeric id of the Etsy user who owns the shop.",
+ "active_listing_count": "Number of active listings assigned to the section.",
+ },
+ },
+ "listings": {
+ "description": "Every listing in the shop across all states (active, inactive, sold out, draft and expired).",
+ "docs_url": f"{_DOCS}#operation/getListingsByShop",
+ "columns": {
+ "listing_id": "Unique identifier for the listing.",
+ "user_id": "Numeric id of the Etsy user who created the listing.",
+ "shop_id": "Numeric id of the shop the listing belongs to.",
+ "title": "Listing title.",
+ "description": "Full listing description.",
+ "state": "Listing state: active, inactive, sold_out, draft or expired.",
+ "creation_timestamp": "Unix epoch seconds when the listing was created.",
+ "created_timestamp": "Unix epoch seconds when the listing was created.",
+ "ending_timestamp": "Unix epoch seconds when the listing expires.",
+ "original_creation_timestamp": "Unix epoch seconds when the listing was first created, before any renewal.",
+ "last_modified_timestamp": "Unix epoch seconds when the listing was last updated.",
+ "updated_timestamp": "Unix epoch seconds when the listing was last updated.",
+ "state_timestamp": "Unix epoch seconds when the listing last changed state.",
+ "quantity": "Number of units currently available.",
+ "price": "Listing price, as an amount/divisor/currency_code object.",
+ "currency_code": "ISO currency code of the listing price.",
+ "quantity_sold": "Number of units sold for this listing.",
+ "tags": "Seller-supplied tags used for search.",
+ "taxonomy_id": "Etsy taxonomy node the listing is categorized under.",
+ "shop_section_id": "Section of the shop the listing is assigned to.",
+ "views": "Number of times the listing has been viewed.",
+ "num_favorers": "Number of Etsy users who have favorited the listing.",
+ "url": "Public URL of the listing.",
+ "is_digital": "Whether the listing delivers a digital download.",
+ "who_made": "Who made the item: i_did, someone_else or collective.",
+ "when_made": "Production period the seller declared for the item.",
+ },
+ },
+ "receipts": {
+ "description": "Orders placed with the shop, one row per receipt, with buyer, shipping, totals and status.",
+ "docs_url": f"{_DOCS}#operation/getShopReceipts",
+ "columns": {
+ "receipt_id": "Unique identifier for the receipt (order).",
+ "receipt_type": "Type of receipt; 0 for a standard Etsy order.",
+ "seller_user_id": "Numeric id of the selling Etsy user.",
+ "buyer_user_id": "Numeric id of the buying Etsy user.",
+ "status": "Order status, e.g. paid, completed, open, payment processing or canceled.",
+ "created_timestamp": "Unix epoch seconds when the order was placed.",
+ "updated_timestamp": "Unix epoch seconds when the receipt was last modified.",
+ "is_paid": "Whether the order has been paid.",
+ "is_shipped": "Whether the order has been marked shipped.",
+ "grandtotal": "Total the buyer paid, as an amount/divisor/currency_code object.",
+ "subtotal": "Item subtotal before shipping, discounts and tax.",
+ "total_price": "Total price of the items on the receipt.",
+ "total_shipping_cost": "Shipping charged on the receipt.",
+ "total_tax_cost": "Sales tax charged on the receipt.",
+ "total_vat_cost": "VAT charged on the receipt.",
+ "discount_amt": "Discount applied to the receipt.",
+ "gift_wrap_price": "Gift wrap charge on the receipt.",
+ "shipments": "Shipping notifications recorded against the receipt.",
+ "transactions": "Line items on the receipt; also synced as the transactions table.",
+ "refunds": "Refunds issued against the receipt.",
+ "country_iso": "ISO country code of the shipping address.",
+ "payment_method": "Payment method the buyer used.",
+ },
+ },
+ "transactions": {
+ "description": "Line items on shop orders, one row per purchased listing, expanded from the receipts payload.",
+ "docs_url": f"{_DOCS}#operation/getShopReceiptTransactionsByShop",
+ "columns": {
+ "transaction_id": "Unique identifier for the line item.",
+ "receipt_id": "Receipt (order) this line item belongs to.",
+ "listing_id": "Listing that was purchased.",
+ "product_id": "Specific product variation that was purchased.",
+ "title": "Title of the purchased listing at time of sale.",
+ "description": "Description of the purchased listing at time of sale.",
+ "seller_user_id": "Numeric id of the selling Etsy user.",
+ "buyer_user_id": "Numeric id of the buying Etsy user.",
+ "created_timestamp": "Unix epoch seconds when the line item was created.",
+ "paid_timestamp": "Unix epoch seconds when the line item was paid for.",
+ "shipped_timestamp": "Unix epoch seconds when the line item was shipped.",
+ "quantity": "Number of units purchased.",
+ "price": "Unit price, as an amount/divisor/currency_code object.",
+ "shipping_cost": "Shipping attributed to this line item.",
+ "is_digital": "Whether the purchased listing is a digital download.",
+ "variations": "Buyer-selected variations (size, color, and so on).",
+ "shipping_profile_id": "Shipping profile applied to the line item.",
+ "sku": "Seller SKU of the purchased product.",
+ },
+ },
+ "reviews": {
+ "description": "Buyer reviews left on the shop's transactions, one row per reviewed transaction.",
+ "docs_url": f"{_DOCS}#operation/getReviewsByShop",
+ "columns": {
+ "shop_id": "Numeric id of the reviewed shop.",
+ "listing_id": "Listing the review was left on.",
+ "transaction_id": "Transaction the review was left on; unique per review.",
+ "buyer_user_id": "Numeric id of the reviewing Etsy user, when shared.",
+ "rating": "Star rating from 1 to 5.",
+ "review": "Free-text review body.",
+ "language": "Language the review was written in.",
+ "image_url_fullxfull": "URL of the photo the buyer attached, if any.",
+ "created_timestamp": "Unix epoch seconds when the review was created.",
+ "updated_timestamp": "Unix epoch seconds when the review was last edited.",
+ },
+ },
+ "ledger_entries": {
+ "description": "Payment account ledger: every credit and debit against the shop's Etsy Payments balance, including sales, fees, refunds and payouts.",
+ "docs_url": f"{_DOCS}#operation/getShopPaymentAccountLedgerEntries",
+ "columns": {
+ "entry_id": "Unique identifier for the ledger entry.",
+ "ledger_id": "Identifier of the shop's payment ledger.",
+ "sequence_number": "Position of the entry within the ledger.",
+ "amount": "Signed value of the entry in the ledger's smallest currency unit.",
+ "currency": "ISO currency code of the entry.",
+ "description": "Human-readable description of what the entry is for.",
+ "balance": "Ledger balance in the smallest currency unit after the entry was applied.",
+ "create_date": "Deprecated alias of created_timestamp.",
+ "created_timestamp": "Unix epoch seconds when the entry was recorded.",
+ "ledger_type": "Category of the entry, e.g. sale, fee, refund or payout.",
+ "reference_type": "Type of the object the entry references.",
+ "reference_id": "Identifier of the referenced object, e.g. a receipt id.",
+ "payment_adjustment_id": "Payment adjustment this entry belongs to, when it is a refund.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/etsy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/etsy.py
new file mode 100644
index 000000000000..23c683997407
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/etsy.py
@@ -0,0 +1,394 @@
+import time
+import dataclasses
+from collections import deque
+from collections.abc import Iterator
+from typing import Any, Optional
+
+import structlog
+from requests import Response
+from structlog.types import FilteringBoundLogger
+
+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.etsy.settings import (
+ ETSY_ENDPOINTS,
+ LISTING_STATES,
+ EtsyEndpointConfig,
+)
+
+ETSY_API_BASE = "https://api.etsy.com/v3/application"
+ETSY_TOKEN_URL = "https://api.etsy.com/v3/public/oauth/token"
+
+# Etsy caps list pages at 100 rows and rejects an offset above 12,000.
+PAGE_SIZE = 100
+MAX_OFFSET = 12_000
+# Walk history in 90-day slices, halving a slice that holds more rows than the offset ceiling can
+# reach. One hour is the floor — below that the request count stops being worth it.
+DEFAULT_WINDOW_SECONDS = 90 * 24 * 60 * 60
+MIN_WINDOW_SECONDS = 60 * 60
+# Etsy opened in 2005, so nothing predates this.
+ETSY_HISTORY_START = 1104537600 # 2005-01-01T00:00:00Z
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+NO_SHOP_ERROR = (
+ "This Etsy account has no shop. Enter the shop ID you want to sync, or connect an account that owns a shop."
+)
+INVALID_SHOP_ID_ERROR = "The Etsy shop ID must be a positive number. Leave it blank to use the token's own shop."
+
+
+class EtsyAPIError(Exception):
+ """An Etsy request failed in a way the caller cannot recover from."""
+
+
+def _validate_shop_id(shop_id: str) -> str:
+ """Etsy shop IDs are positive integers. Reject anything else before it reaches the URL."""
+ if not shop_id.isdigit() or int(shop_id) <= 0:
+ raise EtsyAPIError(INVALID_SHOP_ID_ERROR)
+ return shop_id
+
+
+class EtsyResumeConfig:
+ """Where a resumed run picks the walk back up.
+
+ ``window_start``/``window_end`` pin the exact (possibly subdivided) time slice in flight, so a
+ resume finishes that slice and then continues generating slices from ``window_end + 1``.
+ ``listing_state`` does the same for the state fan-out on listings.
+ """
+
+ offset: int = 0
+ window_start: Optional[int] = None
+ window_end: Optional[int] = None
+ listing_state: Optional[str] = None
+
+
+class EtsyClient:
+ """Etsy Open API v3 transport: x-api-key on every call plus a bearer minted from a refresh token.
+
+ Etsy's OAuth2 uses PKCE, so the refresh exchange takes the app's keystring as ``client_id`` and
+ carries no client secret. Access tokens last an hour, which a backfill routinely outlives, so a
+ 401 re-mints once and replays the request.
+ """
+
+ def __init__(self, api_key: str, refresh_token: str, logger: FilteringBoundLogger) -> None:
+ self._api_key = api_key
+ self._refresh_token = refresh_token
+ self._logger = logger
+ self._access_token: Optional[str] = None
+ self._session = make_tracked_session(
+ headers={"x-api-key": api_key, "Accept": "application/json"},
+ redact_values=(api_key, refresh_token),
+ # The keystring rides a custom header, which requests does not strip across a redirect.
+ allow_redirects=False,
+ )
+
+ def _mint_token(self) -> str:
+ response = self._session.post(
+ ETSY_TOKEN_URL,
+ json={
+ "grant_type": "refresh_token",
+ "client_id": self._api_key,
+ "refresh_token": self._refresh_token,
+ },
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ response.raise_for_status()
+ token = response.json().get("access_token")
+ if not token:
+ raise EtsyAPIError("Etsy returned no access token for the refresh token")
+ return str(token)
+
+ def _send(self, path: str, params: Optional[dict[str, Any]]) -> Response:
+ return self._session.get(
+ f"{ETSY_API_BASE}{path}",
+ params=params,
+ headers={"Authorization": f"Bearer {self._access_token}"},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ def request(self, path: str, params: Optional[dict[str, Any]] = None) -> dict[str, Any]:
+ if self._access_token is None:
+ self._access_token = self._mint_token()
+
+ response = self._send(path, params)
+ if response.status_code == 401:
+ self._access_token = self._mint_token()
+ response = self._send(path, params)
+
+ if response.status_code >= 300:
+ self._logger.error(f"Etsy API error: status={response.status_code}, path={path}")
+ response.raise_for_status()
+ raise EtsyAPIError(f"Unexpected Etsy redirect response: status={response.status_code}, path={path}")
+
+ body = response.json()
+ if not isinstance(body, dict):
+ raise EtsyAPIError(f"Unexpected Etsy response body for {path}: expected an object")
+ return body
+
+ def resolve_shop_id(self, configured_shop_id: Optional[str]) -> str:
+ if configured_shop_id and configured_shop_id.strip():
+ # Etsy shop IDs are positive integers. Reject anything else so a configured value can't
+ # smuggle path segments into `/shops/{shop_id}` and retarget the authenticated request.
+ return _validate_shop_id(configured_shop_id.strip())
+
+ shop_id = self.request("/users/me").get("shop_id")
+ if shop_id is None:
+ raise EtsyAPIError(NO_SHOP_ERROR)
+ return str(shop_id)
+
+
+def validate_credentials(api_key: str, refresh_token: str, shop_id: Optional[str]) -> tuple[bool, Optional[str]]:
+ """Cheap probe: mint a token and read the token's own identity.
+
+ Always hits `/users/me`, even with a shop ID configured — otherwise a bogus keystring or refresh
+ token would sail through source creation. Never raises: a probe must not block create.
+ """
+ if shop_id and shop_id.strip():
+ try:
+ _validate_shop_id(shop_id.strip())
+ except EtsyAPIError as error:
+ return False, str(error)
+
+ try:
+ # No job logger exists on the create-time probe path, so use the module logger.
+ client = EtsyClient(api_key, refresh_token, structlog.get_logger(__name__))
+ identity = client.request("/users/me")
+ except Exception:
+ return False, "Could not authenticate with Etsy. Check your API keystring and refresh token."
+
+ if not (shop_id and shop_id.strip()) and identity.get("shop_id") is None:
+ return False, NO_SHOP_ERROR
+ return True, None
+
+
+def _rows_from_results(results: list[Any], config: EtsyEndpointConfig) -> list[dict[str, Any]]:
+ """Flatten a page of results, expanding the nested child list when the endpoint is derived."""
+ if config.expand_key is None:
+ return [row for row in results if isinstance(row, dict)]
+
+ rows: list[dict[str, Any]] = []
+ for row in results:
+ if not isinstance(row, dict):
+ continue
+ rows.extend(child for child in (row.get(config.expand_key) or []) if isinstance(child, dict))
+ return rows
+
+
+def _fetch_page(
+ client: EtsyClient, path: str, params: dict[str, Any], offset: int, config: EtsyEndpointConfig
+) -> tuple[list[dict[str, Any]], int, int]:
+ """One offset page. Returns (rows, raw result count on the page, total rows matching the query)."""
+ body = client.request(path, {**params, "limit": PAGE_SIZE, "offset": offset})
+ results = body.get("results") or []
+ total = int(body.get("count") or 0)
+ return _rows_from_results(results, config), len(results), total
+
+
+def _windowed_pages(
+ client: EtsyClient,
+ path: str,
+ config: EtsyEndpointConfig,
+ window_param: str,
+ start: int,
+ end: int,
+ manager: ResumableSourceManager[EtsyResumeConfig],
+ resume: Optional[EtsyResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk `start`..`end` in time slices, offset-paging each one.
+
+ Etsy's 12,000 offset ceiling means a slice holding more rows than that can never be read to the
+ end, so an oversized slice is halved (down to `MIN_WINDOW_SECONDS`) and retried instead.
+ """
+ pending: deque[tuple[int, int]] = deque()
+ cursor = start
+ offset = 0
+
+ if resume is not None and resume.window_start is not None and resume.window_end is not None:
+ pending.append((resume.window_start, resume.window_end))
+ cursor = resume.window_end + 1
+ offset = resume.offset
+
+ while pending or cursor <= end:
+ if pending:
+ window_start, window_end = pending.popleft()
+ else:
+ window_start = cursor
+ window_end = min(cursor + DEFAULT_WINDOW_SECONDS - 1, end)
+ cursor = window_end + 1
+
+ params = {
+ **config.extra_params,
+ f"min_{window_param}": window_start,
+ f"max_{window_param}": window_end,
+ }
+
+ while True:
+ rows, page_size, total = _fetch_page(client, path, params, offset, config)
+
+ if offset == 0 and total > MAX_OFFSET and (window_end - window_start) >= MIN_WINDOW_SECONDS:
+ midpoint = window_start + (window_end - window_start) // 2
+ pending.appendleft((midpoint + 1, window_end))
+ pending.appendleft((window_start, midpoint))
+ break
+
+ if rows:
+ yield rows
+ offset += page_size
+ # Saved after the yield so a crash replays the last page (merge dedupes) instead of
+ # skipping it.
+ manager.save_state(EtsyResumeConfig(offset=offset, window_start=window_start, window_end=window_end))
+
+ if page_size == 0 or page_size < PAGE_SIZE or offset >= total:
+ offset = 0
+ break
+ if offset > MAX_OFFSET:
+ logger.warning(
+ f"Etsy offset ceiling reached for {config.name} between {window_start} and {window_end}; "
+ f"{total - offset} rows in this window were not read"
+ )
+ offset = 0
+ break
+
+
+def _offset_pages(
+ client: EtsyClient,
+ path: str,
+ config: EtsyEndpointConfig,
+ manager: ResumableSourceManager[EtsyResumeConfig],
+ resume: Optional[EtsyResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """Offset-page an endpoint with no time filter, optionally once per listing state."""
+ states: tuple[Optional[str], ...] = LISTING_STATES if config.fan_out_listing_states else (None,)
+ # State written by the windowed walk is meaningless here, so only a windowless checkpoint resumes.
+ resumable = resume if resume is not None and resume.window_start is None else None
+ offset = resumable.offset if resumable is not None else 0
+
+ if resumable is not None and resumable.listing_state is not None and resumable.listing_state in states:
+ states = states[states.index(resumable.listing_state) :]
+
+ for index, state in enumerate(states):
+ if index > 0:
+ offset = 0
+ params: dict[str, Any] = dict(config.extra_params)
+ if state is not None:
+ params["state"] = state
+
+ while True:
+ rows, page_size, total = _fetch_page(client, path, params, offset, config)
+ if rows:
+ yield rows
+ offset += page_size
+ manager.save_state(EtsyResumeConfig(offset=offset, listing_state=state))
+
+ if page_size == 0 or page_size < PAGE_SIZE or offset >= total:
+ break
+ if offset > MAX_OFFSET:
+ logger.warning(
+ f"Etsy offset ceiling reached for {config.name} (state={state}); "
+ f"{total - offset} rows were not read"
+ )
+ break
+
+
+def get_rows(
+ api_key: str,
+ refresh_token: str,
+ shop_id: Optional[str],
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[EtsyResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: Optional[str] = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = ETSY_ENDPOINTS[endpoint]
+ client = EtsyClient(api_key, refresh_token, logger)
+ path = f"/shops/{client.resolve_shop_id(shop_id)}{config.path}"
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if config.single_object:
+ yield [client.request(path)]
+ elif not config.paginated:
+ rows = _rows_from_results(client.request(path).get("results") or [], config)
+ if rows:
+ yield rows
+ else:
+ window_param = _resolve_window_param(config, should_use_incremental_field, incremental_field)
+ if window_param is None:
+ yield from _offset_pages(client, path, config, resumable_source_manager, resume, logger)
+ else:
+ start = _window_start(should_use_incremental_field, db_incremental_field_last_value)
+ yield from _windowed_pages(
+ client,
+ path,
+ config,
+ window_param,
+ start,
+ int(time.time()),
+ resumable_source_manager,
+ resume,
+ logger,
+ )
+
+ # The walk finished, so a later attempt must start clean rather than resume mid-stream.
+ resumable_source_manager.clear_state()
+
+
+def _resolve_window_param(
+ config: EtsyEndpointConfig, should_use_incremental_field: bool, incremental_field: Optional[str]
+) -> Optional[str]:
+ if should_use_incremental_field and incremental_field:
+ # An unknown cursor field would silently window on the wrong column, so fall back to the
+ # endpoint's own default rather than guessing.
+ return config.window_params.get(incremental_field) or config.default_window_param
+ return config.default_window_param
+
+
+def _window_start(should_use_incremental_field: bool, db_incremental_field_last_value: Optional[Any]) -> int:
+ if not should_use_incremental_field or db_incremental_field_last_value is None:
+ return ETSY_HISTORY_START
+ try:
+ return max(int(db_incremental_field_last_value), ETSY_HISTORY_START)
+ except (TypeError, ValueError):
+ return ETSY_HISTORY_START
+
+
+def etsy_source(
+ api_key: str,
+ refresh_token: str,
+ shop_id: Optional[str],
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[EtsyResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: Optional[str] = None,
+) -> SourceResponse:
+ config = ETSY_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ refresh_token=refresh_token,
+ shop_id=shop_id,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ # Slices are walked oldest-first, but Etsy documents no ordering *within* a page, so a
+ # per-batch watermark could jump past rows still to come in the same slice. "desc" defers
+ # the watermark write to the end of a successful run, which is the safe reading here.
+ sort_mode="desc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/settings.py
new file mode 100644
index 000000000000..4554225d1be2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/settings.py
@@ -0,0 +1,117 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+# Every Etsy v3 timestamp is Unix epoch seconds, and the matching filters
+# (min_created / min_last_modified) take epoch seconds too, so the cursor is an integer.
+def _epoch_field(name: str, label: str) -> IncrementalField:
+ return {
+ "label": label,
+ "type": IncrementalFieldType.Integer,
+ "field": name,
+ "field_type": IncrementalFieldType.Integer,
+ }
+
+
+_CREATED = _epoch_field("created_timestamp", "created_timestamp")
+_UPDATED = _epoch_field("updated_timestamp", "updated_timestamp")
+
+# Listing states Etsy's getListingsByShop accepts. The filter takes one state at a time, so a full
+# catalog needs one pass per state.
+LISTING_STATES: tuple[str, ...] = ("active", "inactive", "sold_out", "draft", "expired")
+
+
+@dataclass(frozen=True)
+class EtsyEndpointConfig:
+ name: str
+ # Appended to /shops/{shop_id}. Empty string is the shop record itself.
+ path: str
+ primary_keys: list[str]
+ # Incremental field name -> the Etsy filter prefix that windows it, e.g. "created" drives
+ # min_created/max_created. Only fields listed here can be synced incrementally.
+ window_params: dict[str, str] = field(default_factory=dict)
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Filter prefix used to walk history when the schema is NOT synced incrementally. `None` means
+ # the endpoint has no time filter at all, so it is paginated by offset alone.
+ default_window_param: str | None = None
+ # Extra query params sent on every request for this endpoint.
+ extra_params: dict[str, str] = field(default_factory=dict)
+ # Endpoint returns a bare object rather than the {count, results} envelope.
+ single_object: bool = False
+ # Endpoint returns {count, results} but accepts no limit/offset.
+ paginated: bool = True
+ # Fan out one request per listing state (Etsy filters a single state per request).
+ fan_out_listing_states: bool = False
+ # Rows live under this key of each result item rather than being the item itself. Used to
+ # derive transactions from the receipts endpoint, which is the only place Etsy exposes them
+ # behind a time filter.
+ expand_key: str | None = None
+
+
+ETSY_ENDPOINTS: dict[str, EtsyEndpointConfig] = {
+ "shop": EtsyEndpointConfig(
+ name="shop",
+ path="",
+ primary_keys=["shop_id"],
+ single_object=True,
+ ),
+ "shop_sections": EtsyEndpointConfig(
+ name="shop_sections",
+ path="/sections",
+ primary_keys=["shop_section_id"],
+ paginated=False,
+ ),
+ "listings": EtsyEndpointConfig(
+ name="listings",
+ path="/listings",
+ primary_keys=["listing_id"],
+ # getListingsByShop exposes no created/updated filter, only a sort, so it is full refresh.
+ # Sorting ascending by creation keeps offset paging stable while new listings are added.
+ extra_params={"sort_on": "created", "sort_order": "asc"},
+ fan_out_listing_states=True,
+ ),
+ "receipts": EtsyEndpointConfig(
+ name="receipts",
+ path="/receipts",
+ primary_keys=["receipt_id"],
+ window_params={"updated_timestamp": "last_modified", "created_timestamp": "created"},
+ incremental_fields=[_UPDATED, _CREATED],
+ default_window_param="created",
+ ),
+ "transactions": EtsyEndpointConfig(
+ name="transactions",
+ # Derived from the receipts payload: the shop-level transactions endpoint has no time
+ # filter, so it cannot page past Etsy's 12,000 offset ceiling on a busy shop.
+ path="/receipts",
+ primary_keys=["transaction_id"],
+ # The window filters the parent receipt, not the transaction, so a transaction-level
+ # watermark would be wrong. Full refresh only.
+ default_window_param="created",
+ expand_key="transactions",
+ ),
+ "reviews": EtsyEndpointConfig(
+ name="reviews",
+ path="/reviews",
+ # One review per transaction, so the transaction id is the review's identity.
+ primary_keys=["transaction_id"],
+ window_params={"created_timestamp": "created"},
+ incremental_fields=[_CREATED],
+ default_window_param="created",
+ ),
+ "ledger_entries": EtsyEndpointConfig(
+ name="ledger_entries",
+ path="/payment-account/ledger-entries",
+ primary_keys=["entry_id"],
+ window_params={"created_timestamp": "created"},
+ incremental_fields=[_CREATED],
+ # Etsy rejects this endpoint without min_created/max_created, so it is always windowed.
+ default_window_param="created",
+ ),
+}
+
+ENDPOINTS: tuple[str, ...] = tuple(ETSY_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in ETSY_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/source.py
index a7ffc24d9f2f..c9fed3e51e94 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/source.py
@@ -1,30 +1,155 @@
-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.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 (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.etsy.etsy import (
+ EtsyResumeConfig,
+ etsy_source,
+ validate_credentials as validate_etsy_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.etsy.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.etsy import EtsySourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class EtsySource(SimpleSource[EtsySourceConfig]):
+class EtsySource(ResumableSource[EtsySourceConfig, EtsyResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ supported_versions = ("v3",)
+ default_version = "v3"
+ api_docs_url = "https://developers.etsy.com/documentation/reference"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ETSY
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # shop_id steers where the stored token is sent (/shops/{shop_id}), so retargeting it must
+ # force the editor to re-enter the credentials rather than reuse the preserved ones.
+ return ["shop_id"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.ETSY,
category=DataWarehouseSourceCategory.E_COMMERCE,
- label="Etsy, Inc. (Etsy Open API v3)",
+ label="Etsy",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["etsy", "receipts", "orders", "marketplace"],
+ caption="""Sync your Etsy shop's orders, listings, reviews and payment ledger into the PostHog Data warehouse.
+
+Register a personal app in the [Etsy developer portal](https://www.etsy.com/developers/your-apps) to get a keystring, then run Etsy's OAuth flow to grant your shop and keep the refresh token it returns. The token needs the `transactions_r`, `listings_r` and `shops_r` scopes — add `billing_r` if you want the payment ledger. Leave the shop ID blank and we'll use the shop the token belongs to.""",
iconPath="/static/services/etsy.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/etsy",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API keystring",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="Your app's keystring",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="refresh_token",
+ label="Refresh token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="shop_id",
+ label="Shop ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="Leave blank to use the token's own shop",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.etsy.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # Etsy answers a revoked or expired refresh token with a 400 from the token endpoint.
+ # Refresh tokens last 90 days, so this is the expected end-of-life failure.
+ "400 Client Error: Bad Request for url: https://api.etsy.com/v3/public/oauth/token": "Your Etsy refresh token is expired or revoked. Etsy refresh tokens last 90 days — reauthorize the app and paste the new token.",
+ "401 Client Error: Unauthorized for url: https://api.etsy.com": "Etsy rejected your credentials. Check the API keystring and refresh token, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.etsy.com": "Your Etsy token is missing a scope this table needs (transactions_r, listings_r, shops_r or billing_r). Reauthorize with the scopes you want to sync.",
+ "This Etsy account has no shop": "The connected Etsy account does not own a shop. Enter the shop ID you want to sync, or reconnect with the seller account.",
+ }
+
+ def get_schemas(
+ self,
+ config: EtsySourceConfig,
+ 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: EtsySourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_etsy_credentials(config.api_key, config.refresh_token, config.shop_id)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[EtsyResumeConfig]:
+ return ResumableSourceManager[EtsyResumeConfig](inputs, EtsyResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: EtsySourceConfig,
+ resumable_source_manager: ResumableSourceManager[EtsyResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return etsy_source(
+ api_key=config.api_key,
+ refresh_token=config.refresh_token,
+ shop_id=config.shop_id,
+ 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
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy.py
new file mode 100644
index 000000000000..6c7f6cd0ae43
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy.py
@@ -0,0 +1,508 @@
+import json
+import time
+from collections.abc import Iterable, Iterator
+from typing import Any, Optional, cast
+
+import pytest
+from freezegun import freeze_time
+from unittest.mock import patch
+
+import structlog
+from parameterized import parameterized
+from requests import HTTPError, Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.etsy.etsy import (
+ ETSY_HISTORY_START,
+ MAX_OFFSET,
+ MIN_WINDOW_SECONDS,
+ PAGE_SIZE,
+ EtsyAPIError,
+ EtsyResumeConfig,
+ _window_start,
+ etsy_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.etsy.settings import (
+ ETSY_ENDPOINTS,
+ LISTING_STATES,
+)
+
+_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.etsy.etsy.make_tracked_session"
+_API_KEY = "etsy-keystring-abcdef123456"
+_REFRESH_TOKEN = "etsy-refresh-token-abcdef123456"
+_LOGGER = structlog.get_logger(__name__)
+
+
+def _response(payload: Any, *, status: int = 200, url: str = "https://api.etsy.com/v3/application/shops/1") -> Response:
+ response = Response()
+ response.status_code = status
+ response.url = url
+ response.reason = "OK" if status < 400 else "Error"
+ response._content = json.dumps(payload).encode()
+ return response
+
+
+def _page(rows: list[dict[str, Any]], total: int) -> Response:
+ return _response({"count": total, "results": rows})
+
+
+def _rows(count: int, start: int = 0, key: str = "receipt_id") -> list[dict[str, Any]]:
+ return [{key: start + i} for i in range(count)]
+
+
+def _token(access_token: str = "token-1") -> Response:
+ return _response({"access_token": access_token, "expires_in": 3600, "token_type": "Bearer"})
+
+
+class _FakeSession:
+ """Stands in for the tracked session: replays canned responses and records every request."""
+
+ def __init__(self, get_responses: list[Response], post_responses: Optional[list[Response]] = None) -> None:
+ self.get_calls: list[tuple[str, dict[str, Any], dict[str, str]]] = []
+ self.post_bodies: list[dict[str, Any]] = []
+ self._get_responses = list(get_responses)
+ self._post_responses = list(post_responses) if post_responses is not None else [_token()]
+
+ def get(
+ self,
+ url: str,
+ params: Optional[dict[str, Any]] = None,
+ headers: Optional[dict[str, str]] = None,
+ timeout: Optional[float] = None,
+ ) -> Response:
+ self.get_calls.append((url, dict(params or {}), dict(headers or {})))
+ if not self._get_responses:
+ raise AssertionError(f"unexpected extra GET: {url} {params}")
+ return self._get_responses.pop(0)
+
+ def post(self, url: str, json: Optional[dict[str, Any]] = None, timeout: Optional[float] = None) -> Response: # noqa: A002 — matches requests' keyword name
+ self.post_bodies.append(dict(json or {}))
+ if not self._post_responses:
+ raise AssertionError("unexpected extra token request")
+ return self._post_responses.pop(0)
+
+
+class _FakeManager(ResumableSourceManager[EtsyResumeConfig]):
+ def __init__(self, resume: Optional[EtsyResumeConfig] = None) -> None:
+ self._resume = resume
+ self.saved: list[EtsyResumeConfig] = []
+ self.cleared = 0
+
+ def can_resume(self) -> bool:
+ return self._resume is not None
+
+ def load_state(self) -> Optional[EtsyResumeConfig]:
+ return self._resume
+
+ def save_state(self, data: EtsyResumeConfig) -> None:
+ self.saved.append(data)
+
+ def clear_state(self) -> None:
+ self.cleared += 1
+
+
+def _collect(
+ session: _FakeSession,
+ endpoint: str,
+ *,
+ shop_id: Optional[str] = "1",
+ manager: Optional[_FakeManager] = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: Optional[str] = None,
+) -> tuple[list[dict[str, Any]], _FakeManager]:
+ active_manager = manager or _FakeManager()
+ with patch(_SESSION_PATCH, return_value=session):
+ batches: Iterator[list[dict[str, Any]]] = get_rows(
+ api_key=_API_KEY,
+ refresh_token=_REFRESH_TOKEN,
+ shop_id=shop_id,
+ endpoint=endpoint,
+ logger=_LOGGER,
+ resumable_source_manager=active_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ )
+ rows = [row for batch in batches for row in batch]
+ return rows, active_manager
+
+
+class TestEtsyTransport:
+ def test_token_is_minted_from_the_refresh_token_and_reused(self) -> None:
+ session = _FakeSession([_page(_rows(1), 1)])
+ _collect(session, "shop_sections")
+
+ assert session.post_bodies == [
+ {"grant_type": "refresh_token", "client_id": _API_KEY, "refresh_token": _REFRESH_TOKEN}
+ ]
+ assert session.get_calls[0][2]["Authorization"] == "Bearer token-1"
+
+ def test_secrets_are_redacted_and_api_key_header_is_set(self) -> None:
+ session = _FakeSession([_page([], 0)])
+ with patch(_SESSION_PATCH, return_value=session) as mock_session:
+ list(
+ get_rows(
+ api_key=_API_KEY,
+ refresh_token=_REFRESH_TOKEN,
+ shop_id="1",
+ endpoint="shop_sections",
+ logger=_LOGGER,
+ resumable_source_manager=_FakeManager(),
+ )
+ )
+
+ kwargs = mock_session.call_args.kwargs
+ assert kwargs["headers"]["x-api-key"] == _API_KEY
+ assert set(kwargs["redact_values"]) == {_API_KEY, _REFRESH_TOKEN}
+ # A custom credential header survives a redirect, so the session must not follow one.
+ assert kwargs["allow_redirects"] is False
+
+ def test_expired_access_token_is_reminted_once_and_the_request_replayed(self) -> None:
+ session = _FakeSession(
+ [_response({}, status=401), _page(_rows(2), 2)],
+ post_responses=[_token("token-1"), _token("token-2")],
+ )
+ rows, _ = _collect(session, "shop_sections")
+
+ assert len(rows) == 2
+ assert len(session.post_bodies) == 2
+ assert session.get_calls[1][2]["Authorization"] == "Bearer token-2"
+
+ def test_persistent_401_is_raised_rather_than_looping(self) -> None:
+ session = _FakeSession(
+ [_response({}, status=401), _response({}, status=401)],
+ post_responses=[_token("token-1"), _token("token-2")],
+ )
+ with pytest.raises(HTTPError):
+ _collect(session, "shop_sections")
+
+ def test_shop_id_is_discovered_when_not_configured(self) -> None:
+ session = _FakeSession([_response({"user_id": 7, "shop_id": 4242}), _page(_rows(1), 1)])
+ _collect(session, "shop_sections", shop_id=None)
+
+ assert session.get_calls[0][0].endswith("/users/me")
+ assert session.get_calls[1][0].endswith("/shops/4242/sections")
+
+ def test_configured_shop_id_skips_discovery(self) -> None:
+ session = _FakeSession([_page(_rows(1), 1)])
+ _collect(session, "shop_sections", shop_id=" 99 ")
+
+ assert session.get_calls[0][0].endswith("/shops/99/sections")
+
+ def test_account_without_a_shop_fails_with_an_actionable_error(self) -> None:
+ session = _FakeSession([_response({"user_id": 7, "shop_id": None})])
+ with pytest.raises(EtsyAPIError, match="no shop"):
+ _collect(session, "shop_sections", shop_id=None)
+
+ @parameterized.expand([("../users/me",), ("42/receipts",), ("abc",), ("0",), ("-1",)])
+ def test_non_numeric_shop_id_is_rejected_before_any_request(self, shop_id: str) -> None:
+ # A configured shop ID is concatenated into /shops/{shop_id}, so a traversal or non-numeric
+ # value must be rejected rather than sent as an authenticated request to another resource.
+ session = _FakeSession([_page(_rows(1), 1)])
+ with pytest.raises(EtsyAPIError, match="positive number"):
+ _collect(session, "shop_sections", shop_id=shop_id)
+
+ assert session.get_calls == []
+
+ def test_single_object_endpoint_yields_the_body_as_one_row(self) -> None:
+ session = _FakeSession([_response({"shop_id": 1, "shop_name": "Testy"})])
+ rows, manager = _collect(session, "shop")
+
+ assert rows == [{"shop_id": 1, "shop_name": "Testy"}]
+ assert session.get_calls[0][1] == {}
+ assert manager.cleared == 1
+
+ def test_unpaginated_endpoint_sends_no_limit_or_offset(self) -> None:
+ session = _FakeSession([_page([{"shop_section_id": 3}], 1)])
+ rows, _ = _collect(session, "shop_sections")
+
+ assert rows == [{"shop_section_id": 3}]
+ assert session.get_calls[0][1] == {}
+
+ def test_listings_fan_out_covers_every_state(self) -> None:
+ session = _FakeSession([_page([{"listing_id": i}], 1) for i in range(len(LISTING_STATES))])
+ rows, manager = _collect(session, "listings")
+
+ assert [call[1]["state"] for call in session.get_calls] == list(LISTING_STATES)
+ assert [call[1]["sort_on"] for call in session.get_calls] == ["created"] * len(LISTING_STATES)
+ assert len(rows) == len(LISTING_STATES)
+ assert manager.saved[0].listing_state == LISTING_STATES[0]
+
+ def test_offset_pagination_walks_full_pages_then_stops_on_a_short_one(self) -> None:
+ session = _FakeSession(
+ [_page(_rows(PAGE_SIZE, key="listing_id"), 150), _page(_rows(50, start=100, key="listing_id"), 150)]
+ + [_page([], 0) for _ in range(len(LISTING_STATES) - 1)]
+ )
+ rows, manager = _collect(session, "listings")
+
+ assert len(rows) == 150
+ assert [call[1]["offset"] for call in session.get_calls[:2]] == [0, PAGE_SIZE]
+ assert [state.offset for state in manager.saved[:2]] == [PAGE_SIZE, 150]
+
+ def test_offset_pagination_stops_at_the_offset_ceiling(self) -> None:
+ # Etsy rejects an offset above 12,000, so a state with more rows than that must terminate
+ # rather than request an offset the API refuses.
+ pages = [_page(_rows(PAGE_SIZE, key="listing_id"), 20_000) for _ in range(MAX_OFFSET // PAGE_SIZE + 1)]
+ session = _FakeSession(pages + [_page([], 0) for _ in range(len(LISTING_STATES) - 1)])
+ rows, _ = _collect(session, "listings")
+
+ assert len(rows) == MAX_OFFSET + PAGE_SIZE
+ assert max(call[1]["offset"] for call in session.get_calls) == MAX_OFFSET
+
+ @freeze_time("2005-01-15")
+ def test_windowed_endpoint_sends_a_created_window_over_all_history(self) -> None:
+ session = _FakeSession([_page(_rows(2), 2)])
+ rows, _ = _collect(session, "receipts")
+
+ params = session.get_calls[0][1]
+ assert params["min_created"] == ETSY_HISTORY_START
+ assert params["max_created"] == int(time.time())
+ assert params["limit"] == PAGE_SIZE
+ assert len(rows) == 2
+
+ @freeze_time("2005-07-01")
+ def test_windows_advance_until_the_range_is_covered(self) -> None:
+ session = _FakeSession([_page([], 0) for _ in range(3)])
+ _collect(session, "receipts")
+
+ windows = [(call[1]["min_created"], call[1]["max_created"]) for call in session.get_calls]
+ assert len(windows) == 3
+ # Contiguous, non-overlapping, and finishing at "now".
+ assert windows[0][0] == ETSY_HISTORY_START
+ assert windows[1][0] == windows[0][1] + 1
+ assert windows[2][0] == windows[1][1] + 1
+ assert windows[-1][1] == int(time.time())
+
+ @freeze_time("2005-01-15")
+ def test_oversized_window_is_halved_instead_of_hitting_the_offset_ceiling(self) -> None:
+ # First probe reports more rows than the offset ceiling can reach, so the slice splits.
+ session = _FakeSession(
+ [_page(_rows(PAGE_SIZE), MAX_OFFSET + 1), _page(_rows(1), 1), _page(_rows(1, start=1), 1)]
+ )
+ rows, _ = _collect(session, "receipts")
+
+ windows = [(call[1]["min_created"], call[1]["max_created"]) for call in session.get_calls]
+ outer_start, outer_end = windows[0]
+ assert windows[1][0] == outer_start
+ assert windows[2] == (windows[1][1] + 1, outer_end)
+ # The oversized probe page is discarded, so only the halves' rows land.
+ assert len(rows) == 2
+
+ @freeze_time("2005-01-01 00:30:00")
+ def test_window_that_cannot_be_split_further_stops_at_the_offset_ceiling(self) -> None:
+ # A one-hour slice is the floor, so an over-full one reads what it can and moves on.
+ pages = [_page(_rows(PAGE_SIZE), 50_000) for _ in range(MAX_OFFSET // PAGE_SIZE + 1)]
+ session = _FakeSession(pages)
+ rows, _ = _collect(session, "receipts")
+
+ window = session.get_calls[0][1]
+ assert window["max_created"] - window["min_created"] < MIN_WINDOW_SECONDS
+ assert len(rows) == MAX_OFFSET + PAGE_SIZE
+
+ @freeze_time("2005-01-15")
+ def test_resume_finishes_the_saved_window_then_continues_after_it(self) -> None:
+ saved_end = ETSY_HISTORY_START + 1000
+ manager = _FakeManager(
+ EtsyResumeConfig(offset=PAGE_SIZE, window_start=ETSY_HISTORY_START, window_end=saved_end)
+ )
+ session = _FakeSession([_page(_rows(1), PAGE_SIZE + 1), _page([], 0)])
+ _collect(session, "receipts", manager=manager)
+
+ first, second = session.get_calls[0][1], session.get_calls[1][1]
+ assert (first["min_created"], first["max_created"], first["offset"]) == (
+ ETSY_HISTORY_START,
+ saved_end,
+ PAGE_SIZE,
+ )
+ assert second["min_created"] == saved_end + 1
+
+ @freeze_time("2005-01-15")
+ def test_state_is_saved_after_each_batch_and_cleared_when_the_walk_finishes(self) -> None:
+ session = _FakeSession([_page(_rows(PAGE_SIZE), 150), _page(_rows(50, start=100), 150)])
+ _, manager = _collect(session, "receipts")
+
+ assert [state.offset for state in manager.saved] == [PAGE_SIZE, 150]
+ assert manager.saved[0].window_start == ETSY_HISTORY_START
+ assert manager.cleared == 1
+
+ @freeze_time("2005-01-15")
+ def test_transactions_are_expanded_out_of_the_receipts_payload(self) -> None:
+ session = _FakeSession(
+ [
+ _page(
+ [
+ {"receipt_id": 1, "transactions": [{"transaction_id": 10}, {"transaction_id": 11}]},
+ {"receipt_id": 2, "transactions": []},
+ ],
+ 2,
+ )
+ ]
+ )
+ rows, _ = _collect(session, "transactions")
+
+ assert rows == [{"transaction_id": 10}, {"transaction_id": 11}]
+ assert session.get_calls[0][0].endswith("/shops/1/receipts")
+
+ @freeze_time("2005-01-15")
+ def test_offset_advances_by_parent_rows_not_expanded_children(self) -> None:
+ # Offset addresses receipts, so a page of 100 receipts advances by 100 even when it
+ # expands into far more transactions.
+ parents = [
+ {"receipt_id": i, "transactions": [{"transaction_id": i * 2}, {"transaction_id": i * 2 + 1}]}
+ for i in range(PAGE_SIZE)
+ ]
+ session = _FakeSession([_page(parents, 150), _page([], 150)])
+ rows, _ = _collect(session, "transactions")
+
+ assert len(rows) == PAGE_SIZE * 2
+ assert session.get_calls[1][1]["offset"] == PAGE_SIZE
+
+ @parameterized.expand(
+ [
+ ("updated_timestamp", "min_last_modified"),
+ ("created_timestamp", "min_created"),
+ # An unrecognised cursor must not silently window on the wrong column.
+ ("not_a_field", "min_created"),
+ (None, "min_created"),
+ ]
+ )
+ @freeze_time("2006-01-15")
+ def test_incremental_field_selects_the_matching_etsy_filter(
+ self, incremental_field: Optional[str], expected_param: str
+ ) -> None:
+ cursor = 1_136_073_600 # 2006-01-01
+ session = _FakeSession([_page([], 0) for _ in range(2)])
+ _collect(
+ session,
+ "receipts",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=cursor,
+ incremental_field=incremental_field,
+ )
+
+ params = session.get_calls[0][1]
+ assert expected_param in params
+ assert params[expected_param] == cursor
+
+ @freeze_time("2005-01-15")
+ def test_full_refresh_ignores_a_stale_cursor(self) -> None:
+ session = _FakeSession([_page([], 0)])
+ _collect(session, "receipts", should_use_incremental_field=False, db_incremental_field_last_value=999_999_999)
+
+ assert session.get_calls[0][1]["min_created"] == ETSY_HISTORY_START
+
+ @parameterized.expand(
+ [
+ (False, None, ETSY_HISTORY_START),
+ (True, None, ETSY_HISTORY_START),
+ (True, 1_600_000_000, 1_600_000_000),
+ # A cursor before Etsy existed (or a junk one) can only mean "start from the beginning".
+ (True, 5, ETSY_HISTORY_START),
+ (True, "not-a-number", ETSY_HISTORY_START),
+ ]
+ )
+ def test_window_start_resolution(self, incremental: bool, cursor: Any, expected: int) -> None:
+ assert _window_start(incremental, cursor) == expected
+
+
+class TestEtsyValidateCredentials:
+ def test_valid_credentials_resolve_the_shop(self) -> None:
+ session = _FakeSession([_response({"user_id": 1, "shop_id": 5})])
+ with patch(_SESSION_PATCH, return_value=session):
+ assert validate_credentials(_API_KEY, _REFRESH_TOKEN, None) == (True, None)
+
+ def test_configured_shop_id_still_probes_the_token(self) -> None:
+ # Skipping the probe here would let a bogus keystring or refresh token pass source creation.
+ session = _FakeSession([_response({"user_id": 1, "shop_id": None})])
+ with patch(_SESSION_PATCH, return_value=session):
+ assert validate_credentials(_API_KEY, _REFRESH_TOKEN, "77") == (True, None)
+
+ assert session.get_calls[0][0].endswith("/users/me")
+
+ @parameterized.expand([(400,), (401,), (403,), (500,)])
+ def test_failed_probe_reports_a_message_without_raising(self, status: int) -> None:
+ # Two of each so the 401 re-mint path has something to replay against.
+ session = _FakeSession(
+ [_response({}, status=status), _response({}, status=status)], post_responses=[_token(), _token()]
+ )
+ with patch(_SESSION_PATCH, return_value=session):
+ ok, error = validate_credentials(_API_KEY, _REFRESH_TOKEN, None)
+
+ assert ok is False
+ assert error is not None
+
+ def test_account_without_a_shop_surfaces_its_own_message(self) -> None:
+ session = _FakeSession([_response({"user_id": 1, "shop_id": None})])
+ with patch(_SESSION_PATCH, return_value=session):
+ ok, error = validate_credentials(_API_KEY, _REFRESH_TOKEN, None)
+
+ assert ok is False
+ assert error is not None and "no shop" in error
+
+ def test_transport_failure_does_not_raise(self) -> None:
+ with patch(_SESSION_PATCH, side_effect=OSError("boom")):
+ assert validate_credentials(_API_KEY, _REFRESH_TOKEN, None)[0] is False
+
+ def test_invalid_shop_id_fails_validation_without_probing(self) -> None:
+ # A malformed shop ID is caught up front, so no request is issued to authenticate.
+ with patch(_SESSION_PATCH, side_effect=AssertionError("must not connect")):
+ ok, error = validate_credentials(_API_KEY, _REFRESH_TOKEN, "../users/me")
+
+ assert ok is False
+ assert error is not None and "positive number" in error
+
+
+class TestEtsySourceResponse:
+ @parameterized.expand([(name,) for name in ETSY_ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = etsy_source(
+ api_key=_API_KEY,
+ refresh_token=_REFRESH_TOKEN,
+ shop_id="1",
+ endpoint=endpoint,
+ logger=_LOGGER,
+ resumable_source_manager=_FakeManager(),
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == ETSY_ENDPOINTS[endpoint].primary_keys
+ # Etsy documents no ordering within a page, so the watermark must only be written once the
+ # run completes — which is what "desc" buys us.
+ assert response.sort_mode == "desc"
+
+ @freeze_time("2005-01-15")
+ def test_items_is_lazy_and_streams_rows(self) -> None:
+ session = _FakeSession([_page(_rows(3), 3)])
+ response = etsy_source(
+ api_key=_API_KEY,
+ refresh_token=_REFRESH_TOKEN,
+ shop_id="1",
+ endpoint="receipts",
+ logger=_LOGGER,
+ resumable_source_manager=_FakeManager(),
+ )
+
+ assert session.get_calls == []
+ with patch(_SESSION_PATCH, return_value=session):
+ batches = cast(Iterable[Any], response.items())
+ rows = [row for batch in batches for row in batch]
+
+ assert len(rows) == 3
+
+
+class TestEtsyEndpointCatalog:
+ @parameterized.expand([(name,) for name in ETSY_ENDPOINTS])
+ def test_advertised_incremental_fields_map_to_a_real_filter(self, endpoint: str) -> None:
+ config = ETSY_ENDPOINTS[endpoint]
+
+ assert config.name == endpoint
+ assert config.primary_keys
+ for field in config.incremental_fields:
+ # An advertised cursor with no Etsy filter behind it would sync a full refresh while
+ # telling the user it was incremental.
+ assert field["field"] in config.window_params
+ if config.incremental_fields:
+ assert config.default_window_param is not None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy_source.py
new file mode 100644
index 000000000000..4e9dc280a239
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy_source.py
@@ -0,0 +1,149 @@
+from typing import Optional
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.etsy import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.etsy.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.etsy.etsy import EtsyResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.etsy.settings import ENDPOINTS, ETSY_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.etsy.source import EtsySource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.etsy import EtsySourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_INCREMENTAL_ENDPOINTS = [name for name, cfg in ETSY_ENDPOINTS.items() if cfg.incremental_fields]
+_FULL_REFRESH_ENDPOINTS = [name for name, cfg in ETSY_ENDPOINTS.items() if not cfg.incremental_fields]
+
+
+def _config(shop_id: Optional[str] = None) -> EtsySourceConfig:
+ return EtsySourceConfig(api_key="key", refresh_token="refresh", shop_id=shop_id)
+
+
+class TestEtsySourceClass:
+ def test_source_type(self) -> None:
+ assert EtsySource().source_type == ExternalDataSourceType.ETSY
+
+ def test_source_config(self) -> None:
+ config = EtsySource().get_source_config
+
+ assert config.label == "Etsy"
+ assert config.category == DataWarehouseSourceCategory.E_COMMERCE
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/etsy"
+ assert config.iconPath == "/static/services/etsy.png"
+ # A hidden source cannot be connected — a finished source must stay visible.
+ assert config.unreleasedSource is None
+
+ def test_source_fields(self) -> None:
+ fields = EtsySource().get_source_config.fields
+ assert [f.name for f in fields] == ["api_key", "refresh_token", "shop_id"]
+
+ @parameterized.expand([("api_key", True, True), ("refresh_token", True, True), ("shop_id", False, False)])
+ def test_credential_fields_are_secret_and_shop_id_is_optional(
+ self, name: str, expected_secret: bool, expected_required: bool
+ ) -> None:
+ field = next(f for f in EtsySource().get_source_config.fields if f.name == name)
+
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.secret is expected_secret
+ assert field.required is expected_required
+
+ def test_shop_id_is_a_connection_host_field(self) -> None:
+ # shop_id steers where the stored token is sent, so changing it must force credential re-entry.
+ assert EtsySource().connection_host_fields == ["shop_id"]
+
+ def test_api_version_metadata(self) -> None:
+ assert EtsySource.supported_versions == ("v3",)
+ assert EtsySource.default_version == "v3"
+ assert EtsySource.api_docs_url is not None
+ assert EtsySource.api_docs_url.startswith("https://")
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas is a static catalog with no I/O, so the public docs table list must render.
+ assert EtsySource.lists_tables_without_credentials is True
+ assert {table["name"] for table in EtsySource().get_documented_tables()} == set(ENDPOINTS)
+
+ @parameterized.expand([("401",), ("403",), ("no shop",)])
+ def test_non_retryable_errors_cover_permanent_failures(self, fragment: str) -> None:
+ assert any(fragment in key for key in EtsySource().get_non_retryable_errors())
+
+ def test_get_schemas_covers_all_endpoints(self) -> None:
+ schemas = EtsySource().get_schemas(_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @parameterized.expand([(name,) for name in _INCREMENTAL_ENDPOINTS])
+ def test_incremental_endpoints_support_incremental(self, endpoint: str) -> None:
+ schema = EtsySource().get_schemas(_config(), team_id=1, names=[endpoint])[0]
+
+ assert schema.supports_incremental is True
+ assert [f["field"] for f in schema.incremental_fields] == [
+ f["field"] for f in ETSY_ENDPOINTS[endpoint].incremental_fields
+ ]
+
+ @parameterized.expand([(name,) for name in _FULL_REFRESH_ENDPOINTS])
+ def test_full_refresh_endpoints_do_not_advertise_incremental(self, endpoint: str) -> None:
+ schema = EtsySource().get_schemas(_config(), team_id=1, names=[endpoint])[0]
+
+ assert schema.supports_incremental is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_name_filter(self) -> None:
+ schemas = EtsySource().get_schemas(_config(), team_id=1, names=["receipts"])
+ assert [s.name for s in schemas] == ["receipts"]
+
+ @parameterized.expand([(True, None), (False, "Bad credentials")])
+ def test_validate_credentials_passes_through(self, ok: bool, error: Optional[str]) -> None:
+ with patch.object(source_module, "validate_etsy_credentials", return_value=(ok, error)) as mock_validate:
+ assert EtsySource().validate_credentials(_config("42"), team_id=1) == (ok, error)
+
+ assert mock_validate.call_args.args == ("key", "refresh", "42")
+
+ def test_resumable_manager_bound_to_resume_config(self) -> None:
+ manager = EtsySource().get_resumable_source_manager(MagicMock())
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is EtsyResumeConfig
+
+ @patch.object(source_module, "etsy_source")
+ def test_source_for_pipeline_plumbs_inputs(self, mock_etsy_source: MagicMock) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "receipts"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1_700_000_000
+ inputs.incremental_field = "updated_timestamp"
+ manager = MagicMock()
+
+ EtsySource().source_for_pipeline(_config("42"), manager, inputs)
+
+ kwargs = mock_etsy_source.call_args.kwargs
+ assert kwargs["api_key"] == "key"
+ assert kwargs["refresh_token"] == "refresh"
+ assert kwargs["shop_id"] == "42"
+ assert kwargs["endpoint"] == "receipts"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1_700_000_000
+ assert kwargs["incremental_field"] == "updated_timestamp"
+
+ @patch.object(source_module, "etsy_source")
+ def test_source_for_pipeline_drops_cursor_on_full_refresh(self, mock_etsy_source: MagicMock) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "listings"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = 1_700_000_000
+
+ EtsySource().source_for_pipeline(_config(), MagicMock(), inputs)
+
+ assert mock_etsy_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_canonical_descriptions_match_endpoints(self) -> None:
+ descriptions = EtsySource().get_canonical_descriptions()
+
+ assert descriptions is CANONICAL_DESCRIPTIONS
+ assert set(descriptions) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/etsy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/etsy.py
index 7b62efa43c41..d381b0dcff2c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/etsy.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/etsy.py
@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class EtsySourceConfig(config.Config):
- pass
+ api_key: str
+ refresh_token: str
+ shop_id: str | None = None