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.

6.8 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    VersionDeprecation,
    build_endpoint_schemas,
    detect,
)
from products.warehouse_sources.sources.shipstation._config import ShipStationSourceConfig
from products.warehouse_sources.sources.shipstation.settings import (
    SHIPSTATION_DEFAULT_VERSION,
    SHIPSTATION_SUPPORTED_VERSIONS,
    SHIPSTATION_V1,
    schema_catalog_for_version,
)
from products.warehouse_sources.sources.shipstation.shipstation import (
    ShipStationResumeConfig,
    shipstation_source,
    validate_credentials as validate_shipstation_credentials,
)


@SourceRegistry.register
class ShipStationSource(ResumableSource[ShipStationSourceConfig, ShipStationResumeConfig]):
    codebase_detection = detect(env=("^SHIPSTATION_",))

    api_docs_url = "https://docs.shipstation.com/"

    supported_versions = SHIPSTATION_SUPPORTED_VERSIONS
    default_version = SHIPSTATION_DEFAULT_VERSION
    # ShipStation has deprecated the original v1 API in favor of the ShipEngine-based v2. No
    # removal date is announced yet; the vendor promises advance notice (sunset_at=None).
    deprecated_versions = (VersionDeprecation(version=SHIPSTATION_V1, sunset_at=None),)

    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs

    @property
    def source_type(self) -> ExternalDataSourceType:
        return ExternalDataSourceType.SHIPSTATION

    def get_canonical_descriptions(self) -> CanonicalDescriptions:
        from products.warehouse_sources.sources.shipstation.canonical_descriptions import CANONICAL_DESCRIPTIONS

        return CANONICAL_DESCRIPTIONS

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            "401 Client Error: Unauthorized for url: https://ssapi.shipstation.com": "ShipStation authentication failed. Please check your API key and API secret.",
            "403 Client Error: Forbidden for url: https://ssapi.shipstation.com": "ShipStation denied access. Please check that your plan includes API access.",
            "401 Client Error: Unauthorized for url: https://api.shipstation.com/v2": "ShipStation authentication failed. Please check your API key.",
            "403 Client Error: Forbidden for url: https://api.shipstation.com/v2": "ShipStation denied access. Please check that your plan includes API access.",
        }

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.SHIPSTATION,
            category=DataWarehouseSourceCategory.E_COMMERCE,
            label="ShipStation",
            caption="""Enter your ShipStation API credentials to pull your ShipStation shipping data into the PostHog data warehouse.

New connections use ShipStation API v2, which needs only the API key from your [ShipStation API settings](https://docs.shipstation.com/getting-started). The API secret is only for older v1 connections, which ShipStation is deprecating.

API access requires a ShipStation plan tier that includes it.""",
            iconPath="/static/services/shipstation.png",
            docsUrl="https://posthog.com/docs/cdp/sources/shipstation",
            releaseStatus=ReleaseStatus.GA,
            fields=cast(
                list[FieldType],
                # The two versions take different credentials: v2 needs only the API key, v1 an
                # API key + secret. api_key is required either way; api_secret is optional at the
                # form level and enforced for v1 by `validate_credentials`.
                [
                    SourceFieldInputConfig(
                        name="api_key",
                        label="API key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="",
                        secret=True,
                    ),
                    SourceFieldInputConfig(
                        name="api_secret",
                        label="API secret (v1 only)",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=False,
                        placeholder="",
                        secret=True,
                    ),
                ],
            ),
        )

    def get_schemas(
        self,
        config: ShipStationSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        # v1 and v2 expose different resource catalogs, so discovery must build from the pin.
        endpoints, incremental_fields = schema_catalog_for_version(self.resolve_api_version(api_version))
        return build_endpoint_schemas(endpoints, incremental_fields, names)

    def validate_credentials(
        self,
        config: ShipStationSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        # The probe host and required credentials differ by version, so probe the resolved pin
        # (pre-creation calls pass None → default v2, the version a new source is stamped with).
        ok, error = validate_shipstation_credentials(
            config.api_key, config.api_secret, self.resolve_api_version(api_version)
        )
        if ok:
            return True, None
        return False, error or "Invalid ShipStation API credentials"

    def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ShipStationResumeConfig]:
        return ResumableSourceManager[ShipStationResumeConfig](inputs, ShipStationResumeConfig)

    def source_for_pipeline(
        self,
        config: ShipStationSourceConfig,
        resumable_source_manager: ResumableSourceManager[ShipStationResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return shipstation_source(
            api_key=config.api_key,
            api_secret=config.api_secret,
            endpoint=inputs.schema_name,
            team_id=inputs.team_id,
            job_id=inputs.job_id,
            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,
            api_version=self.resolve_api_version(inputs.api_version),
        )