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.

8.3 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.etsy._config import EtsySourceConfig
from products.warehouse_sources.sources.etsy.etsy import (
    DAILY_QUOTA_EXHAUSTED_ERROR,
    DAILY_QUOTA_EXHAUSTED_MESSAGE,
    RATE_LIMITED_ERROR,
    RATE_LIMITED_MESSAGE,
    EtsyResumeConfig,
    etsy_source,
    validate_credentials as validate_etsy_credentials,
)
from products.warehouse_sources.sources.etsy.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    build_endpoint_schemas,
    detect,
)


@SourceRegistry.register
class EtsySource(ResumableSource[EtsySourceConfig, EtsyResumeConfig]):
    codebase_detection = detect(env=("^ETSY_",))

    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=ExternalDataSourceType.ETSY,
            category=DataWarehouseSourceCategory.E_COMMERCE,
            label="Etsy",
            releaseStatus=ReleaseStatus.GA,
            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 and its shared secret, 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",
            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="shared_secret",
                        label="Shared secret",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="Your app's shared secret",
                        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.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, shared secret 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_retryable_errors(self) -> set[str]:
        # EtsyClient reads over the tracked session, whose `DEFAULT_RETRY` adapter already retries
        # a 429 or 5xx three times. A response that still reaches us here is an exhausted upstream
        # blip — transient, not a PostHog bug — and Temporal retries the whole activity, so the
        # sync self-recovers. `raise_for_status` derives these prefixes from the status code alone,
        # not the vendor's reason text, so they're stable to match on (see mailchimp/impact sources
        # for the same pattern). The token exchange is a POST, which the adapter does not retry, so
        # the bare status prefix stays here alongside the sentinels the reads raise.
        return {"429 Client Error", "Server Error", DAILY_QUOTA_EXHAUSTED_ERROR, RATE_LIMITED_ERROR}

    def get_retry_exhausted_errors(self) -> dict[str, str]:
        # Without these, a rate limit that outlives the retry budget leaves the job holding raw 429
        # text, which names neither whose limit was hit nor when it clears.
        return {
            DAILY_QUOTA_EXHAUSTED_ERROR: DAILY_QUOTA_EXHAUSTED_MESSAGE,
            RATE_LIMITED_ERROR: RATE_LIMITED_MESSAGE,
            "429 Client Error": RATE_LIMITED_MESSAGE,
        }

    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.shared_secret, 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,
            shared_secret=config.shared_secret,
            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,
        )