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.

9.4 KB
Raw Blame
from dataclasses import dataclass, field

from products.warehouse_sources.sources.sdk 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 EtsyBatchLookup:
    """Rows fetched by id from a batch endpoint, one request per page of a parent endpoint."""

    # Endpoint whose pages supply the ids. Its walk, windows and resume state drive the lookup.
    parent: str
    # Absolute path under /v3/application. `{shop_id}` is filled in with the resolved shop.
    path: str
    ids_param: str
    # Field on each parent row that holds the id to look up.
    id_field: str
    # Each result is a listing carrying its inventory record, and every product in it becomes a row.
    inventory_products: bool = False
    # Different parent pages can return the same row, e.g. a payment and its later refund are
    # separate ledger entries, so rows already yielded this run are dropped.
    dedupe_key: str | None = None


@dataclass(frozen=True)
class EtsyFanOut:
    """Rows fetched with one request per row of a parent endpoint."""

    # Endpoint whose pages supply the ids. Its walk and resume state drive the fan-out.
    parent: str
    # Appended to /shops/{shop_id}. `{id}` is filled in with each parent row's id.
    path: str
    # Field on each parent row that holds the id. Each child row carries it under the same name.
    id_field: str


@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
    # Etsy caps the window narrower and the offset lower on some endpoints, rejecting the request
    # outright above either. `None` takes the source-wide default.
    max_window_seconds: int | None = None
    max_offset: int | 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
    # Path is absolute under /v3/application rather than appended to /shops/{shop_id}.
    shop_scoped: bool = True
    # Results are a tree whose nodes nest under this key. Every node becomes a row.
    flatten_key: str | None = None
    # Rows come from a batch endpoint keyed on ids the parent endpoint pages through.
    batch_lookup: EtsyBatchLookup | None = None
    # Rows come from one request per row the parent endpoint pages through.
    fan_out: EtsyFanOut | 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",
        # Etsy answers getReviewsByShop anonymously however the request is authenticated, and
        # caps an anonymous request at the first page.
        max_offset=0,
    ),
    "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,
        # and rejects a window wider than 31 days.
        default_window_param="created",
        max_window_seconds=31 * 24 * 60 * 60,
    ),
    "payments": EtsyEndpointConfig(
        name="payments",
        path="",
        primary_keys=["payment_id"],
        # Etsy reads payments only by id. The ledger is the one place payment ids appear behind a
        # time filter, so the walk pages the ledger and resolves each page's entries to payments.
        # The window filters ledger entries, not payments, so a payment-level watermark would be
        # wrong. Full refresh only.
        batch_lookup=EtsyBatchLookup(
            parent="ledger_entries",
            path="/shops/{shop_id}/payment-account/ledger-entries/payments",
            ids_param="ledger_entry_ids",
            id_field="entry_id",
            dedupe_key="payment_id",
        ),
    ),
    "listing_inventory": EtsyEndpointConfig(
        name="listing_inventory",
        path="",
        # Product ids are only documented as unique within a listing.
        primary_keys=["listing_id", "product_id"],
        batch_lookup=EtsyBatchLookup(
            parent="listings",
            path="/listings/batch/inventory",
            ids_param="listing_ids",
            id_field="listing_id",
            inventory_products=True,
        ),
    ),
    "return_policies": EtsyEndpointConfig(
        name="return_policies",
        path="/policies/return",
        primary_keys=["return_policy_id"],
        paginated=False,
    ),
    "shipping_profiles": EtsyEndpointConfig(
        name="shipping_profiles",
        path="/shipping-profiles",
        primary_keys=["shipping_profile_id"],
        paginated=False,
    ),
    "readiness_state_definitions": EtsyEndpointConfig(
        name="readiness_state_definitions",
        path="/readiness-state-definitions",
        primary_keys=["readiness_state_id"],
    ),
    "listing_properties": EtsyEndpointConfig(
        name="listing_properties",
        path="",
        # Property ids name an attribute such as color, so they repeat across listings.
        primary_keys=["listing_id", "property_id"],
        # Etsy has no batch read and no listings include for properties, so this costs one request
        # per listing.
        fan_out=EtsyFanOut(parent="listings", path="/listings/{id}/properties", id_field="listing_id"),
    ),
    "seller_taxonomy_nodes": EtsyEndpointConfig(
        name="seller_taxonomy_nodes",
        path="/seller-taxonomy/nodes",
        primary_keys=["id"],
        paginated=False,
        shop_scoped=False,
        flatten_key="children",
    ),
}

ENDPOINTS: tuple[str, ...] = tuple(ETSY_ENDPOINTS.keys())

INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
    name: config.incremental_fields for name, config in ETSY_ENDPOINTS.items()
}