: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
import time
import dataclasses
from collections import deque
from collections.abc import Iterator
from typing import Any, Optional
import structlog
from requests import HTTPError, Response
from structlog.types import FilteringBoundLogger
from products.warehouse_sources.sources.etsy.settings import (
ETSY_ENDPOINTS,
LISTING_STATES,
EtsyBatchLookup,
EtsyEndpointConfig,
EtsyFanOut,
)
from products.warehouse_sources.sources.sdk import ResumableSourceManager, SourceResponse, make_tracked_session
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."
# Etsy meters each app's own API key, as a per-second allowance and then a sliding 24-hour quota.
# When a refusal carries this header, a zero says the day's quota is gone rather than a burst.
REMAINING_TODAY_HEADER = "x-remaining-today"
# Stable sentinels the source classifies on. Keep them in step with `EtsySource`.
DAILY_QUOTA_EXHAUSTED_ERROR = "Etsy daily request quota exhausted"
RATE_LIMITED_ERROR = "Etsy rate limit reached"
DAILY_QUOTA_EXHAUSTED_MESSAGE = (
"Your Etsy app has used its whole 24 hour request quota, so this sync stopped early. The quota frees up again "
"over the next 24 hours and the next sync carries on from here. If it keeps happening, ask Etsy to raise your "
"app's daily limit or sync this source less often."
)
RATE_LIMITED_MESSAGE = (
"Etsy is rate limiting your app's requests, so this sync stopped early. The next sync carries on from here. "
"If it keeps happening, ask Etsy to raise your app's rate limit."
)
RATE_LIMITED_VALIDATION_MESSAGE = (
"Etsy is rate limiting your app, so we could not check these credentials. Try again in a few minutes."
)
class EtsyAPIError(Exception):
"""An Etsy request failed in a way the caller cannot recover from."""
class EtsyRateLimitError(EtsyAPIError):
"""Etsy refused the request because the app is out of requests."""
def _remaining_today(response: Response) -> Optional[int]:
raw = response.headers.get(REMAINING_TODAY_HEADER)
if raw is None:
return None
try:
return int(raw)
except ValueError:
return None
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
@dataclasses.dataclass(frozen=False)
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.
Since 9 February 2026 Etsy rejects any v3 request whose ``x-api-key`` is the keystring alone, so
the header pairs it with the app's shared secret as ``keystring:secret``. The OAuth2 refresh
exchange still uses PKCE and takes the keystring on its own as ``client_id``. 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, shared_secret: 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._shop_opened_at: Optional[int] = None
self._shop_opened_at_resolved = False
self._session = make_tracked_session(
headers={"x-api-key": f"{api_key}:{shared_secret}", "Accept": "application/json"},
redact_values=(api_key, shared_secret, 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,
# An OAuth2 token endpoint takes form encoding; Etsy rejects a JSON body outright.
data={
"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 == 429:
# The tracked session already retried this while honoring Etsy's retry-after, so what
# reaches here is a limit no backoff inside the run can clear. Raising now also stops
# the walk from spending the rest of the quota on requests that can only be refused.
raise EtsyRateLimitError(
DAILY_QUOTA_EXHAUSTED_ERROR if _remaining_today(response) == 0 else RATE_LIMITED_ERROR
)
if response.status_code >= 300:
self._logger.error(
f"Etsy API error: status={response.status_code}, path={path}, body={response.text[:500]}"
)
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 shop_opened_at(self, shop_id: str) -> Optional[int]:
"""Epoch second the shop opened, or None when Etsy reports no usable value.
Nothing a shop owns predates the shop, so a walk with no cursor starts here rather than at
Etsy's launch year. Every window in between can only come back empty, and each one spends a
request against the app's daily quota, which is what a sync runs out of before it finishes.
"""
if not self._shop_opened_at_resolved:
# getShop needs no OAuth scope, so this stays readable for any token the source accepts.
opened_at = self.request(f"/shops/{shop_id}").get("created_timestamp")
try:
self._shop_opened_at = int(opened_at) if opened_at is not None else None
except (TypeError, ValueError):
self._shop_opened_at = None
self._shop_opened_at_resolved = True
return self._shop_opened_at
def validate_credentials(
api_key: str, shared_secret: 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, shared_secret, refresh_token, structlog.get_logger(__name__))
identity = client.request("/users/me")
except EtsyRateLimitError:
return False, RATE_LIMITED_VALIDATION_MESSAGE
except Exception:
return False, "Could not authenticate with Etsy. Check your API keystring, shared secret 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 _flatten_tree(nodes: list[Any], children_key: str) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
stack = [node for node in reversed(nodes) if isinstance(node, dict)]
while stack:
node = stack.pop()
children = node.get(children_key) or []
rows.append({key: value for key, value in node.items() if key != children_key})
stack.extend(child for child in reversed(children) if isinstance(child, dict))
return rows
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.flatten_key is not None:
return _flatten_tree(results, config.flatten_key)
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 _max_offset(config: EtsyEndpointConfig) -> int:
return MAX_OFFSET if config.max_offset is None else config.max_offset
def _fetch_page(
client: EtsyClient, path: str, params: dict[str, Any], offset: int, config: EtsyEndpointConfig
) -> tuple[list[dict[str, Any]], int, int]: # nosemgrep: tuple-return-prefer-dataclass -- pre-existing, file moved
"""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: Optional[ResumableSourceManager[EtsyResumeConfig]],
resume: Optional[EtsyResumeConfig],
logger: FilteringBoundLogger,
) -> Iterator[list[dict[str, Any]]]:
"""Walk `start`..`end` in time slices, offset-paging each one.
A slice holding more rows than its offset ceiling can reach can never be read to the end, so an
oversized slice is halved (down to `MIN_WINDOW_SECONDS`) and retried instead. Both the slice
width and the ceiling vary by endpoint: Etsy rejects a window wider than `max_window_seconds`,
and serves no offset above `max_offset`.
"""
window_seconds = config.max_window_seconds or DEFAULT_WINDOW_SECONDS
max_offset = _max_offset(config)
# Offsets step by PAGE_SIZE from zero, so the ceiling itself is still a readable page.
readable_rows = max_offset + PAGE_SIZE
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 + 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 > readable_rows 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.
if manager is not None:
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: Optional[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
max_offset = _max_offset(config)
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
if manager is not None:
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 _inventory_product_rows(listings: list[Any]) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
for listing in listings:
if not isinstance(listing, dict):
continue
inventory = listing.get("inventory") or {}
# The *_on_property lists say which variation properties drive price, quantity and SKU, so
# each product row keeps them to stay readable on its own.
inventory_fields = {key: value for key, value in inventory.items() if key != "products"}
for product in inventory.get("products") or []:
if isinstance(product, dict):
rows.append({**product, **inventory_fields, "listing_id": listing.get("listing_id")})
return rows
def _lookup_batch(client: EtsyClient, path: str, lookup: EtsyBatchLookup, ids: list[str]) -> list[Any]:
try:
return client.request(path, {lookup.ids_param: ",".join(ids)}).get("results") or []
except HTTPError as error:
# Etsy fails the whole batch with a 404 when any one id is gone, e.g. a listing deleted
# after the parent page was read. Split the batch to keep every id that still resolves.
if error.response is None or error.response.status_code != 404:
raise
if len(ids) == 1:
return []
midpoint = len(ids) // 2
return _lookup_batch(client, path, lookup, ids[:midpoint]) + _lookup_batch(client, path, lookup, ids[midpoint:])
def _batch_lookup_pages(
client: EtsyClient,
lookup: EtsyBatchLookup,
shop_id: str,
parent_pages: Iterator[list[dict[str, Any]]],
manager: ResumableSourceManager[EtsyResumeConfig],
) -> Iterator[list[dict[str, Any]]]:
path = lookup.path.format(shop_id=shop_id)
seen: set[Any] = set()
for parent_rows in parent_pages:
ids = [str(row[lookup.id_field]) for row in parent_rows if row.get(lookup.id_field) is not None]
results = _lookup_batch(client, path, lookup, ids) if ids else []
if lookup.inventory_products:
rows = _inventory_product_rows(results)
else:
rows = [row for row in results if isinstance(row, dict)]
if lookup.dedupe_key is not None:
fresh: list[dict[str, Any]] = []
for row in rows:
key = row.get(lookup.dedupe_key)
if key not in seen:
seen.add(key)
fresh.append(row)
rows = fresh
if rows:
yield rows
else:
# Many parent pages can resolve to nothing, e.g. ledger entries for fees or payouts.
manager.safe_point()
def _fan_out_pages(
client: EtsyClient,
fan_out: EtsyFanOut,
shop_id: str,
parent_pages: Iterator[list[dict[str, Any]]],
manager: ResumableSourceManager[EtsyResumeConfig],
) -> Iterator[list[dict[str, Any]]]:
for parent_rows in parent_pages:
for parent_row in parent_rows:
parent_id = parent_row.get(fan_out.id_field)
if parent_id is None:
continue
try:
body = client.request(f"/shops/{shop_id}{fan_out.path.format(id=parent_id)}")
except HTTPError as error:
# A listing deleted after the parent page was read is gone, not a failed sync.
if error.response is None or error.response.status_code != 404:
raise
body = {}
rows = [{**row, fan_out.id_field: parent_id} for row in body.get("results") or [] if isinstance(row, dict)]
if rows:
yield rows
else:
# Many listings carry no properties, and each one still costs a request.
manager.safe_point()
def _paged_rows(
client: EtsyClient,
shop_id: str,
path: str,
config: EtsyEndpointConfig,
manager: Optional[ResumableSourceManager[EtsyResumeConfig]],
resume: Optional[EtsyResumeConfig],
logger: FilteringBoundLogger,
should_use_incremental_field: bool,
db_incremental_field_last_value: Optional[Any],
incremental_field: Optional[str],
) -> Iterator[list[dict[str, Any]]]:
window_param = _resolve_window_param(config, should_use_incremental_field, incremental_field)
if window_param is None:
yield from _offset_pages(client, path, config, manager, resume, logger)
return
end = int(time.time())
start = _window_start(should_use_incremental_field, db_incremental_field_last_value)
# A resumed walk carries on from its saved window, so `start` is unused and looking the
# shop up would only spend a request.
resuming_window = resume is not None and resume.window_start is not None
if start == ETSY_HISTORY_START and not resuming_window:
opened_at = client.shop_opened_at(shop_id)
# A missing or clock-skewed opening date falls back to the full range, so a bad
# value can never shorten the walk.
if opened_at is not None and ETSY_HISTORY_START < opened_at <= end:
start = opened_at
yield from _windowed_pages(client, path, config, window_param, start, end, manager, resume, logger)
def get_rows(
api_key: str,
shared_secret: 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, shared_secret, refresh_token, logger)
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
if config.shop_scoped:
resolved_shop_id = client.resolve_shop_id(shop_id)
path = f"/shops/{resolved_shop_id}{config.path}"
else:
# Etsy-wide reference data, so there is no shop to look up.
resolved_shop_id = ""
path = config.path
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
elif config.fan_out is not None:
parent = ETSY_ENDPOINTS[config.fan_out.parent]
parent_pages = _paged_rows(
client,
resolved_shop_id,
f"/shops/{resolved_shop_id}{parent.path}",
parent,
resumable_source_manager,
resume,
logger,
should_use_incremental_field=False,
db_incremental_field_last_value=None,
incremental_field=None,
)
yield from _fan_out_pages(client, config.fan_out, resolved_shop_id, parent_pages, resumable_source_manager)
elif config.batch_lookup is not None:
parent = ETSY_ENDPOINTS[config.batch_lookup.parent]
# The set of rows already yielded does not survive to a resumed attempt, and a resumed full
# refresh appends, so a deduplicated lookup saves no cursor. A restarted attempt is then a
# fresh run, which replaces what earlier attempts wrote.
resumes = config.batch_lookup.dedupe_key is None
parent_pages = _paged_rows(
client,
resolved_shop_id,
f"/shops/{resolved_shop_id}{parent.path}",
parent,
resumable_source_manager if resumes else None,
resume if resumes else None,
logger,
should_use_incremental_field=False,
db_incremental_field_last_value=None,
incremental_field=None,
)
yield from _batch_lookup_pages(
client, config.batch_lookup, resolved_shop_id, parent_pages, resumable_source_manager
)
else:
yield from _paged_rows(
client,
resolved_shop_id,
path,
config,
resumable_source_manager,
resume,
logger,
should_use_incremental_field,
db_incremental_field_last_value,
incremental_field,
)
# 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,
shared_secret: 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,
shared_secret=shared_secret,
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",
)