: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
feat(data-warehouse): implement shippo import source (#69392)
Tom Owersb4f102458e04
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex a0762c5088a8..4a909a236787 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -333,6 +333,7 @@ the row lists both.| sendowl | HTTP | requests | ✅ || sentry | HTTP | requests + `rest_source.RESTClient` | ✅ || servicenow | HTTP | requests | ✅ |+| shippo | HTTP | requests | ✅ || shipstation | HTTP | requests | ✅ || shopify | HTTP | requests | ✅ || shopwired | HTTP | requests | ✅ |@@ -762,6 +763,7 @@ doesn't conflict with concurrent PRs.- sharepoint- sharetribe- shippo+- shopwired- shortio- shutterstock- sigma_computingdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex d6e1e8228d14..57571201d9a6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -3365,7 +3365,7 @@ class ShipStationSourceConfig(config.Config):@config.configclass ShippoSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/canonical_descriptions.pynew file mode 100644index 000000000000..ff51143cd076--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/canonical_descriptions.py@@ -0,0 +1,192 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the official Shippo API reference: https://docs.goshippo.com/api-reference+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "shipments": {+ "description": "A shipment groups a sender address, a recipient address, and one or more parcels, and is the basis for requesting rates and purchasing labels. Shipments older than 390 days are not returned by the API.",+ "docs_url": "https://docs.goshippo.com/api-reference/shipments/list-all-shipments",+ "columns": {+ "object_id": "Unique identifier of the given Shipment object.",+ "object_created": "Date and time of Shipment creation.",+ "object_updated": "Date and time of last Shipment update.",+ "object_owner": "Username of the user who created the Shipment object.",+ "status": "Status of the shipment: WAITING, QUEUED, SUCCESS, or ERROR.",+ "address_from": "Address object of the sender / seller.",+ "address_to": "Address object of the recipient / buyer.",+ "address_return": "Address object where the shipment will be sent back to if returned; defaults to address_from.",+ "parcels": "Parcel objects to be shipped.",+ "rates": "Rate objects available for the shipment; populated asynchronously unless created with async=false.",+ "carrier_accounts": "Carrier account object_ids used for rating; when empty, all active carrier accounts are used.",+ "customs_declaration": "Customs Declaration object required for international shipments.",+ "shipment_date": "Date the shipment will be tendered to the carrier.",+ "messages": "Informational and error messages generated during shipment processing.",+ "metadata": "A string of up to 100 characters that can be filled with any user-defined data.",+ "test": "Whether the object was created in test mode.",+ },+ },+ "transactions": {+ "description": "A transaction is the purchase of a shipping label from a rate — it carries the label URL, tracking number, and tracking status.",+ "docs_url": "https://docs.goshippo.com/api-reference/transactions/list-all-shipping-labels",+ "columns": {+ "object_id": "Unique identifier of the given Transaction object.",+ "object_created": "Date and time of Transaction creation.",+ "object_updated": "Date and time of last Transaction update.",+ "object_owner": "Username of the user who created the Transaction object.",+ "object_state": "Validity of the Transaction object: VALID or INVALID.",+ "status": "Status of the transaction: WAITING, QUEUED, SUCCESS, ERROR, REFUNDED, REFUNDPENDING, or REFUNDREJECTED.",+ "rate": "ID (or simplified object) of the Rate that was purchased.",+ "label_url": "URL of the shipping label to print.",+ "label_file_type": "File format of the generated label.",+ "tracking_number": "Carrier tracking number; only present for trackable shipments processed successfully.",+ "tracking_status": "Latest tracking status: UNKNOWN, PRE_TRANSIT, TRANSIT, DELIVERED, RETURNED, or FAILURE.",+ "tracking_url_provider": "URL of the tracking page on the carrier's website.",+ "commercial_invoice_url": "URL of the commercial invoice, for international shipments.",+ "eta": "Estimated time of arrival according to the carrier.",+ "messages": "Informational and error messages generated during transaction processing.",+ "metadata": "A string of up to 100 characters that can be filled with any user-defined data.",+ "test": "Whether the object was created in test mode.",+ },+ },+ "orders": {+ "description": "An order placed in a connected shop app (Shopify, Amazon, eBay, etc.) or created via the API, with line items, totals, and any purchased-label transactions.",+ "docs_url": "https://docs.goshippo.com/api-reference/orders/list-all-orders",+ "columns": {+ "object_id": "Unique identifier of the given Order object.",+ "object_owner": "Username of the user who created the Order object.",+ "order_number": "An alphanumeric identifier for the order used by the seller or customer.",+ "order_status": "Status of the order: UNKNOWN, AWAITPAY, PAID, REFUNDED, CANCELLED, PARTIALLY_FULFILLED, or SHIPPED.",+ "placed_at": "Date and time the order was placed, which can differ from when the order object was created in Shippo.",+ "shop_app": "Platform the order was created on (for example Shopify, Amazon, eBay, or Shippo).",+ "to_address": "Address object of the order recipient.",+ "from_address": "Address object of the order sender.",+ "line_items": "Items included in the order.",+ "transactions": "Transaction objects for labels purchased for this order.",+ "total_price": "Total amount paid by the customer.",+ "total_tax": "Total tax charged on the order.",+ "subtotal_price": "Sum of the item prices before shipping and tax.",+ "currency": "ISO 4217 currency of the order amounts.",+ "shipping_cost": "Shipping amount paid by the customer.",+ "shipping_method": "Shipping method chosen by the customer.",+ "weight": "Total weight of the order.",+ "weight_unit": "Unit used for the order weight: g, kg, lb, or oz.",+ },+ },+ "addresses": {+ "description": "A sender or recipient address, including validation results. Addresses are immutable once created.",+ "docs_url": "https://docs.goshippo.com/api-reference/addresses/list-all-addresses",+ "columns": {+ "object_id": "Unique identifier of the given Address object.",+ "object_created": "Date and time of Address creation.",+ "object_updated": "Date and time of the last change made to the Address by Shippo's systems.",+ "object_owner": "Username of the user who created the Address object.",+ "name": "Full name of the addressee.",+ "company": "Company name.",+ "street1": "First address line.",+ "city": "City name.",+ "state": "State or province code.",+ "zip": "Postal code.",+ "country": "ISO 3166-1 alpha-2 country code.",+ "phone": "Phone number of the addressee.",+ "email": "Email address of the addressee.",+ "is_residential": "Whether the address is residential.",+ "is_complete": "Whether the address contains all values required for any shipping operation.",+ "validation_results": "Result of address validation, including whether the address is valid and any messages.",+ "test": "Whether the object was created in test mode.",+ },+ },+ "parcels": {+ "description": "The physical dimensions and weight of a package to be shipped. Parcels are immutable once created.",+ "docs_url": "https://docs.goshippo.com/api-reference/parcels/list-all-parcels",+ "columns": {+ "object_id": "Unique identifier of the given Parcel object; required to create a Shipment.",+ "object_created": "Date and time of Parcel creation.",+ "object_updated": "Date and time of the last change made to the Parcel by Shippo's systems.",+ "object_owner": "Username of the user who created the Parcel object.",+ "object_state": "Validity of the Parcel object.",+ "length": "Length of the parcel.",+ "width": "Width of the parcel.",+ "height": "Height of the parcel.",+ "distance_unit": "Unit used for the parcel dimensions: cm, in, ft, m, mm, or yd.",+ "weight": "Weight of the parcel.",+ "mass_unit": "Unit used for the parcel weight: g, kg, lb, or oz.",+ "template": "Carrier-specific parcel template; when set, length, width, height, and distance_unit are ignored.",+ "metadata": "A string of up to 100 characters that can be filled with any user-defined data.",+ "test": "Whether the object was created in test mode.",+ },+ },+ "carrier_accounts": {+ "description": "A carrier account connected to Shippo (USPS, FedEx, UPS, etc.) used to retrieve rates and purchase labels.",+ "docs_url": "https://docs.goshippo.com/api-reference/carrier-accounts/list-all-carrier-accounts",+ "columns": {+ "object_id": "Unique identifier of the carrier account object.",+ "object_owner": "Username of the user who created the carrier account object.",+ "carrier": "Carrier token, e.g. usps, fedex, or ups.",+ "carrier_name": "Human-readable name of the carrier.",+ "account_id": "Identifier of the account with the carrier; masked in API responses.",+ "active": "Whether the account is active; active accounts are used for rating when a shipment does not specify accounts.",+ "is_shippo_account": "Whether this is a Shippo-provided master account rather than the user's own carrier account.",+ "parameters": "Carrier-specific additional parameters for the account.",+ "test": "Whether the object was created in test mode.",+ },+ },+ "refunds": {+ "description": "A request to cancel a purchased shipping label and refund the transaction.",+ "docs_url": "https://docs.goshippo.com/api-reference/refunds/list-all-refunds",+ "columns": {+ "object_id": "Unique identifier of the given Refund object.",+ "object_created": "Date and time of Refund creation.",+ "object_updated": "Date and time of last Refund update.",+ "object_owner": "Username of the user who created the Refund object.",+ "transaction": "Object ID of the Transaction to be refunded.",+ "status": "Status of the refund: QUEUED, PENDING, SUCCESS, or ERROR.",+ "test": "Whether the object was created in test mode.",+ },+ },+ "customs_items": {+ "description": "A distinct item in an international parcel, declared for customs. Customs items are immutable once created.",+ "docs_url": "https://docs.goshippo.com/api-reference/customs-items/list-all-customs-items",+ "columns": {+ "object_id": "Unique identifier of the given Customs Item object.",+ "object_created": "Date and time of Customs Item creation.",+ "object_updated": "Date and time of last Customs Item update.",+ "object_owner": "Username of the user who created the Customs Item object.",+ "object_state": "Validity of the Customs Item object: VALID or INVALID.",+ "description": "Text description of the item, e.g. 'T-Shirt'.",+ "quantity": "Quantity of this item in the shipment; must be greater than 0.",+ "net_weight": "Total weight of this item, i.e. quantity multiplied by the weight of each item.",+ "mass_unit": "Unit used for the net weight: g, kg, lb, or oz.",+ "value_amount": "Total value of this item, i.e. quantity multiplied by the value of each item.",+ "value_currency": "ISO 4217 currency of the item value.",+ "origin_country": "ISO country code of the country of origin, e.g. US or DE.",+ "tariff_number": "Tariff number of the item; takes precedence over hs_code.",+ "hs_code": "Harmonized System code of the item; used when tariff_number is absent.",+ "sku_code": "SKU code of the item.",+ "metadata": "A string of up to 100 characters that can be filled with any user-defined data.",+ "test": "Whether the object was created in test mode.",+ },+ },+ "customs_declarations": {+ "description": "The customs declaration for an international shipment, referencing the customs items it contains. Customs declarations are immutable once created.",+ "docs_url": "https://docs.goshippo.com/api-reference/customs-declarations/list-all-customs-declarations",+ "columns": {+ "object_id": "Unique identifier of the given Customs Declaration object.",+ "object_created": "Date and time of Customs Declaration creation.",+ "object_updated": "Date and time of last Customs Declaration update.",+ "object_owner": "Username of the user who created the Customs Declaration object.",+ "object_state": "Validity of the Customs Declaration object: VALID or INVALID.",+ "items": "Object IDs of the Customs Items declared in this declaration.",+ "contents_type": "Type of goods in the shipment: DOCUMENTS, GIFT, SAMPLE, MERCHANDISE, HUMANITARIAN_DONATION, RETURN_MERCHANDISE, or OTHER.",+ "contents_explanation": "Explanation of the shipment contents; required when contents_type is OTHER.",+ "non_delivery_option": "What the carrier should do if the shipment cannot be delivered: ABANDON or RETURN.",+ "certify": "Whether the certify_signer certifies that the declaration information is provided truthfully.",+ "certify_signer": "Name of the person certifying the declaration information.",+ "exporter_reference": "Exporter reference of the shipment.",+ "importer_reference": "Importer reference of the shipment.",+ "invoice": "Invoice reference of the shipment.",+ "metadata": "A string of up to 100 characters that can be filled with any user-defined data.",+ "test": "Whether the object was created in test mode.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/settings.pynew file mode 100644index 000000000000..e0fa9cf1b49f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/settings.py@@ -0,0 +1,90 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class ShippoEndpointConfig:+ name: str+ path: str+ # Shippo object_ids are unique per account across each resource type.+ primary_keys: list[str] = field(default_factory=lambda: ["object_id"])+ # Stable creation-time field used for datetime partitioning. Never an updated_at-style+ # field, which would rewrite partitions on every sync.+ partition_key: Optional[str] = None+ # Only /shipments accepts the server-side object_created_gt/gte/lt/lte filters (per Shippo's+ # filtering docs); every other list endpoint is page/results pagination only.+ supports_created_filter: bool = False+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++# Shippo list endpoints all return {"next": url|null, "previous": url|null, "results": [...]}+# and paginate with `page` + `results` (max 100). Only shipments supports server-side+# creation-date filtering, so it is the only endpoint advertised as incremental; orders expose+# `start_date`/`end_date` but those filter on `placed_at` (when the order was placed in the shop,+# not when the object was created in Shippo) and order status is mutable, so orders stay full+# refresh to avoid missing late-imported or updated rows.+SHIPPO_ENDPOINTS: dict[str, ShippoEndpointConfig] = {+ "shipments": ShippoEndpointConfig(+ name="shipments",+ path="/shipments",+ partition_key="object_created",+ supports_created_filter=True,+ incremental_fields=[+ {+ "label": "object_created",+ "type": IncrementalFieldType.DateTime,+ "field": "object_created",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ "transactions": ShippoEndpointConfig(+ name="transactions",+ path="/transactions",+ partition_key="object_created",+ ),+ "orders": ShippoEndpointConfig(+ name="orders",+ path="/orders",+ # Orders have no object_created field; placed_at is required and stable once set.+ partition_key="placed_at",+ ),+ "addresses": ShippoEndpointConfig(+ name="addresses",+ path="/addresses",+ partition_key="object_created",+ ),+ "parcels": ShippoEndpointConfig(+ name="parcels",+ path="/parcels",+ partition_key="object_created",+ ),+ "carrier_accounts": ShippoEndpointConfig(+ name="carrier_accounts",+ path="/carrier_accounts",+ # Carrier account objects carry no object_created, and the table is tiny — no partitioning.+ ),+ "refunds": ShippoEndpointConfig(+ name="refunds",+ path="/refunds",+ partition_key="object_created",+ ),+ "customs_items": ShippoEndpointConfig(+ name="customs_items",+ path="/customs/items",+ partition_key="object_created",+ ),+ "customs_declarations": ShippoEndpointConfig(+ name="customs_declarations",+ path="/customs/declarations",+ partition_key="object_created",+ ),+}++ENDPOINTS = tuple(SHIPPO_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in SHIPPO_ENDPOINTS.items() if config.incremental_fields+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/shippo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/shippo.pynew file mode 100644index 000000000000..5e65273e216c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/shippo.py@@ -0,0 +1,261 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import urlencode, urlsplit++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++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.shippo.settings import SHIPPO_ENDPOINTS++SHIPPO_BASE_URL = "https://api.goshippo.com"+SHIPPO_HOST = "api.goshippo.com"+# List endpoints cap `results` at 100 (values over 200 truncate); the largest page minimises+# round trips against Shippo's tight GET-list rate limit (50/min live, 10/min test).+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 7+# Shippo rejects creation-date ranges wider than 90 days, so incremental syncs walk the+# watermark forward in windows kept safely under that cap.+CREATED_FILTER_WINDOW = timedelta(days=89)+# Cheap probe used to confirm an API token is genuine. The token is account-wide, so one probe+# validates access to every list endpoint.+DEFAULT_PROBE_PATH = "/shipments"+++class ShippoRetryableError(Exception):+ pass+++class ShippoUntrustedURLError(Exception):+ pass+++def _validate_pagination_url(url: str) -> str:+ """Pin every authenticated request to the Shippo API origin.++ The `next` cursor comes from the response body (and is persisted in resume state), so a+ tampered response or a poisoned cursor must not be able to retarget the credential-bearing+ request at another host and leak the customer's Shippo token (SSRF). Returns the URL+ unchanged when it is trusted.+ """+ parts = urlsplit(url)+ if parts.scheme != "https" or parts.netloc != SHIPPO_HOST:+ raise ShippoUntrustedURLError(f"Refusing to follow pagination URL outside {SHIPPO_BASE_URL}/")+ return url+++class ShippoResumeConfig:+ # Opaque `next` URL of the page to fetch next; Shippo documents these links as subject to+ # change in format, so we follow them verbatim rather than reconstructing page numbers.+ next_url: str | None = None+ # ISO timestamp of the creation-date window currently being walked (incremental shipments+ # syncs only). `None` for unfiltered full-catalog pagination.+ window_start: str | None = None+++def _headers(api_key: str) -> dict[str, str]:+ return {"Authorization": f"ShippoToken {api_key}", "Accept": "application/json"}+++def _format_datetime(value: datetime) -> str:+ # Shippo's date filters take ISO 8601 UTC without offsets; truncating to whole seconds only+ # ever widens the exclusive lower bound, and merge dedupes any re-pulled rows.+ return value.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+++def _parse_datetime(value: Any) -> Optional[datetime]:+ if value is None or isinstance(value, bool):+ return None+ if isinstance(value, datetime):+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ if isinstance(value, str):+ try:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)+ return None+++def _build_url(path: str, params: dict[str, Any]) -> str:+ clean_params = {key: value for key, value in params.items() if value is not None}+ return f"{SHIPPO_BASE_URL}{path}/?{urlencode(clean_params)}"+++@retry(+ retry=retry_if_exception_type((ShippoRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=5, max=90),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict[str, Any]:+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)++ # Shippo rate limits per method per minute (GET-list is only 50/min live, 10/min test), so+ # the backoff must be generous enough to cross into the next minute window.+ if response.status_code == 429 or response.status_code >= 500:+ raise ShippoRetryableError(f"Shippo API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Shippo API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ data = response.json()+ # Shippo list endpoints wrap records in {"next": url|null, "previous": url|null, "results": [...]}.+ if not isinstance(data, dict) or not isinstance(data.get("results"), list):+ raise ShippoRetryableError(f"Shippo returned an unexpected payload for {url}: {type(data).__name__}")++ return data+++def _paginate(+ session: requests.Session,+ first_url: str,+ window_start: str | None,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ShippoResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ url: str | None = first_url+ while url:+ data = _fetch_page(session, _validate_pagination_url(url), logger)+ items: list[dict[str, Any]] = data["results"]+ if items:+ yield items++ url = data.get("next") or None+ if url:+ # Reject an off-origin cursor before it is persisted, so a poisoned resume state can+ # never later replay the token to another host.+ _validate_pagination_url(url)+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages+ # are persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(ShippoResumeConfig(next_url=url, window_start=window_start))+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ShippoResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = SHIPPO_ENDPOINTS[endpoint]+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,), allow_redirects=False)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ watermark = _parse_datetime(db_incremental_field_last_value) if should_use_incremental_field else None++ if watermark is not None and config.supports_created_filter:+ # Walk forward from the watermark in sub-90-day creation-date windows (Shippo rejects+ # wider ranges). Note Shippo does not return shipments older than 390 days, which bounds+ # how far back the very first sync can reach regardless of windowing.+ now = datetime.now(UTC)+ resume_url: str | None = None+ if resume is not None and resume.window_start is not None:+ resumed_start = _parse_datetime(resume.window_start)+ if resumed_start is not None:+ watermark = resumed_start+ resume_url = resume.next_url+ logger.debug(f"Shippo: resuming {endpoint} window {resume.window_start} from {resume_url}")++ window_start = watermark+ while window_start < now:+ window_end = min(window_start + CREATED_FILTER_WINDOW, now)+ start_iso = _format_datetime(window_start)+ if resume_url is not None:+ first_url, resume_url = resume_url, None+ else:+ first_url = _build_url(+ config.path,+ {+ "results": PAGE_SIZE,+ "object_created_gt": start_iso,+ "object_created_lte": _format_datetime(window_end),+ },+ )+ yield from _paginate(session, first_url, start_iso, logger, resumable_source_manager)++ window_start = window_end+ resumable_source_manager.save_state(+ ShippoResumeConfig(next_url=None, window_start=_format_datetime(window_start))+ )+ else:+ if resume is not None and resume.next_url is not None and resume.window_start is None:+ first_url = resume.next_url+ logger.debug(f"Shippo: resuming {endpoint} from {first_url}")+ else:+ first_url = _build_url(config.path, {"results": PAGE_SIZE})+ yield from _paginate(session, first_url, None, logger, resumable_source_manager)+++def shippo_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ShippoResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = SHIPPO_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ 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,+ ),+ primary_keys=config.primary_keys,+ # Shippo does not document (or accept a param controlling) list ordering, so we+ # conservatively treat responses as unordered: "desc" defers the incremental watermark+ # commit to the end of a successful run instead of checkpointing per batch.+ sort_mode="desc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the API token.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,), allow_redirects=False)+ try:+ response = session.get(f"{SHIPPO_BASE_URL}{path}/?{urlencode({'results': 1})}", timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Shippo: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Shippo returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ status, message = check_access(api_key)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Shippo API token"+ return False, message or "Could not validate Shippo API token"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/source.pyindex 4fdf8adc4e21..05404ae25e56 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/source.py@@ -1,19 +1,43 @@-from typing import cast+from typing import Optional, castfrom 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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ShippoSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.shippo.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ SHIPPO_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.shippo.shippo import (+ ShippoResumeConfig,+ shippo_source,+ validate_credentials as validate_shippo_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class ShippoSource(SimpleSource[ShippoSourceConfig]):+class ShippoSource(ResumableSource[ShippoSourceConfig, ShippoResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SHIPPO@@ -24,7 +48,96 @@ class ShippoSource(SimpleSource[ShippoSourceConfig]):name=SchemaExternalDataSourceType.SHIPPO,category=DataWarehouseSourceCategory.E_COMMERCE,label="Shippo",+ keywords=["shipping", "shipping labels", "logistics", "goshippo"],+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Shippo API token to pull your shipping data into the PostHog Data warehouse.++You can find your live (`shippo_live_...`) and test (`shippo_test_...`) API tokens under **Settings → API** in the [Shippo dashboard](https://apps.goshippo.com/settings/api). The token grants read access to your shipments, labels, orders, addresses, parcels, refunds, customs data, and carrier accounts.+""",iconPath="/static/services/shippo.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/shippo",unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="shippo_live_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.shippo.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.goshippo.com": "Your Shippo API token is invalid or has been revoked. Generate a new token under Settings → API in the Shippo dashboard, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.goshippo.com": "Your Shippo API token does not have access to this data. Check the token's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: ShippoSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Only shipments supports incremental sync — it is the one endpoint with a server-side+ # creation-date filter (object_created_gt/lte). Everything else is full refresh.+ schemas: list[SourceSchema] = []+ for endpoint in ENDPOINTS:+ incremental_fields = INCREMENTAL_FIELDS.get(endpoint)+ schemas.append(+ SourceSchema(+ name=endpoint,+ supports_incremental=incremental_fields is not None,+ supports_append=incremental_fields is not None,+ incremental_fields=incremental_fields or [],+ )+ )++ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]++ return schemas++ def validate_credentials(+ self, config: ShippoSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The API token is account-wide, so a single probe validates access to every schema.+ return validate_shippo_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ShippoResumeConfig]:+ return ResumableSourceManager[ShippoResumeConfig](inputs, ShippoResumeConfig)++ def source_for_pipeline(+ self,+ config: ShippoSourceConfig,+ resumable_source_manager: ResumableSourceManager[ShippoResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in SHIPPO_ENDPOINTS:+ raise ValueError(f"Unknown Shippo schema '{inputs.schema_name}'")++ return shippo_source(+ api_key=config.api_key,+ 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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/tests/test_shippo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/tests/test_shippo.pynew file mode 100644index 000000000000..1a63ed7c4e0c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/tests/test_shippo.py@@ -0,0 +1,332 @@+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from freezegun import freeze_time+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.shippo import shippo+from products.warehouse_sources.backend.temporal.data_imports.sources.shippo.settings import ENDPOINTS, SHIPPO_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.shippo.shippo import (+ PAGE_SIZE,+ SHIPPO_BASE_URL,+ ShippoResumeConfig,+ ShippoRetryableError,+ ShippoUntrustedURLError,+ _validate_pagination_url,+ check_access,+ get_rows,+ shippo_source,+ validate_credentials,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = shippo._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: ShippoResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[ShippoResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> ShippoResumeConfig | None:+ return self._state++ def save_state(self, data: ShippoResumeConfig) -> None:+ self.saved.append(data)+++def _query_params(url: str) -> dict[str, str]:+ return {key: values[0] for key, values in parse_qs(urlparse(url).query).items()}+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: dict[str, dict],+ endpoint: str = "shipments",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ ) -> tuple[list[dict], list[str]]:+ requested: list[str] = []++ def fake_fetch(session: Any, url: str, logger: Any) -> dict:+ requested.append(url)+ for prefix, response in pages.items():+ if url.startswith(prefix):+ return response+ raise AssertionError(f"Unexpected URL fetched: {url}")++ monkeypatch.setattr(shippo, "_fetch_page", fake_fetch)+ monkeypatch.setattr(shippo, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="shippo_test_key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ):+ rows.extend(batch)+ return rows, requested++ def test_full_refresh_follows_next_urls_and_saves_state_after_yield(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ page_2 = f"{SHIPPO_BASE_URL}/addresses/?page=2&results={PAGE_SIZE}"+ pages: dict[str, dict] = {+ page_2: {"next": None, "results": [{"object_id": "b"}]},+ f"{SHIPPO_BASE_URL}/addresses/?results={PAGE_SIZE}": {"next": page_2, "results": [{"object_id": "a"}]},+ }+ rows, requested = self._collect(manager, monkeypatch, pages, endpoint="addresses")++ assert rows == [{"object_id": "a"}, {"object_id": "b"}]+ assert requested[0] == f"{SHIPPO_BASE_URL}/addresses/?results={PAGE_SIZE}"+ # State points at the *next* page so a crash re-fetches only unpersisted data.+ assert [(s.next_url, s.window_start) for s in manager.saved] == [(page_2, None)]++ def test_full_refresh_resumes_from_saved_next_url(self, monkeypatch: Any) -> None:+ page_3 = f"{SHIPPO_BASE_URL}/parcels/?page=3&results={PAGE_SIZE}"+ manager = _FakeResumableManager(ShippoResumeConfig(next_url=page_3, window_start=None))+ rows, requested = self._collect(+ manager, monkeypatch, {page_3: {"next": None, "results": [{"object_id": "z"}]}}, endpoint="parcels"+ )+ assert rows == [{"object_id": "z"}]+ # The first (unfiltered) page must never be re-fetched on resume.+ assert requested == [page_3]++ def test_empty_results_page_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows, _ = self._collect(+ manager,+ monkeypatch,+ {f"{SHIPPO_BASE_URL}/refunds/?results={PAGE_SIZE}": {"next": None, "results": []}},+ endpoint="refunds",+ )+ assert rows == []+ assert manager.saved == []++ @freeze_time("2026-07-08T12:00:00Z")+ def test_incremental_walks_creation_windows_under_90_days(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {f"{SHIPPO_BASE_URL}/shipments/": {"next": None, "results": [{"object_id": "s"}]}}+ # Watermark ~188 days before the frozen clock: needs 3 windows to reach "now".+ rows, requested = self._collect(+ manager,+ monkeypatch,+ pages,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ )++ assert len(rows) == 3+ windows = [+ (_query_params(url)["object_created_gt"], _query_params(url)["object_created_lte"]) for url in requested+ ]+ assert windows == [+ ("2026-01-01T00:00:00Z", "2026-03-31T00:00:00Z"),+ ("2026-03-31T00:00:00Z", "2026-06-28T00:00:00Z"),+ ("2026-06-28T00:00:00Z", "2026-07-08T12:00:00Z"),+ ]+ # Windows are contiguous (gt of window N+1 == lte of window N): no gaps, no overlap.+ assert all(windows[i][1] == windows[i + 1][0] for i in range(len(windows) - 1))+ # Window completion is persisted so a crash between windows resumes from the boundary.+ completed = [s for s in manager.saved if s.next_url is None]+ assert [s.window_start for s in completed] == [+ "2026-03-31T00:00:00Z",+ "2026-06-28T00:00:00Z",+ "2026-07-08T12:00:00Z",+ ]++ @freeze_time("2026-07-08T12:00:00Z")+ def test_incremental_resumes_mid_window_then_advances(self, monkeypatch: Any) -> None:+ page_2 = f"{SHIPPO_BASE_URL}/shipments/?page=2&object_created_gt=2026-06-01T00:00:00Z"+ manager = _FakeResumableManager(ShippoResumeConfig(next_url=page_2, window_start="2026-06-01T00:00:00Z"))+ pages: dict[str, dict] = {+ page_2: {"next": None, "results": [{"object_id": "resumed"}]},+ f"{SHIPPO_BASE_URL}/shipments/?results=": {"next": None, "results": []},+ }+ rows, requested = self._collect(+ manager,+ monkeypatch,+ pages,+ should_use_incremental_field=True,+ # Stale watermark must be superseded by the resumed window position.+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ )++ assert rows == [{"object_id": "resumed"}]+ # First request is the saved page URL, not a rebuilt window from the watermark.+ assert requested[0] == page_2+ # The rest of the run continues from the resumed window's end, not from January.+ assert all("2026-01-01" not in url for url in requested[1:])++ def test_incremental_without_watermark_falls_back_to_full_pagination(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows, requested = self._collect(+ manager,+ monkeypatch,+ {f"{SHIPPO_BASE_URL}/shipments/?results={PAGE_SIZE}": {"next": None, "results": [{"object_id": "s"}]}},+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ )+ assert rows == [{"object_id": "s"}]+ assert "object_created_gt" not in requested[0]++ def test_first_page_url_uses_endpoint_path(self, monkeypatch: Any) -> None:+ # The customs endpoints live under a nested path; a bare name-derived URL would 404.+ manager = _FakeResumableManager()+ _, requested = self._collect(+ manager,+ monkeypatch,+ {f"{SHIPPO_BASE_URL}/customs/items/?results={PAGE_SIZE}": {"next": None, "results": []}},+ endpoint="customs_items",+ )+ assert requested == [f"{SHIPPO_BASE_URL}/customs/items/?results={PAGE_SIZE}"]+++class TestValidatePaginationURL:+ def test_on_origin_url_passes_through(self) -> None:+ url = f"{SHIPPO_BASE_URL}/shipments/?page=2&results={PAGE_SIZE}"+ assert _validate_pagination_url(url) == url++ @parameterized.expand(+ [+ ("off_origin_host", "https://evil.example.com/shipments/?results=100"),+ ("look_alike_host", "https://api.goshippo.com.evil.com/shipments/"),+ ("plain_http", "http://api.goshippo.com/shipments/"),+ ("credential_in_host", "https://[email protected]/shipments/"),+ ]+ )+ def test_off_origin_cursor_rejected(self, _name: str, url: str) -> None:+ # A tampered `next` cursor must never redirect the token-bearing request off-origin.+ with pytest.raises(ShippoUntrustedURLError):+ _validate_pagination_url(url)+++class TestFetchPage:+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body if body is not None else {"next": None, "results": []}+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(ShippoRetryableError):+ _fetch_page_unwrapped(session, f"{SHIPPO_BASE_URL}/shipments/", MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("bad_request", 400)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, f"{SHIPPO_BASE_URL}/shipments/", MagicMock())++ @parameterized.expand(+ [+ ("non_dict_body", [{"object_id": "a"}]),+ ("missing_results_key", {"next": None}),+ ]+ )+ def test_unexpected_payload_is_retryable(self, _name: str, body: Any) -> None:+ session = self._session_returning(200, body)+ with pytest.raises(ShippoRetryableError):+ _fetch_page_unwrapped(session, f"{SHIPPO_BASE_URL}/shipments/", MagicMock())++ def test_success_returns_payload(self) -> None:+ body = {"next": "url", "results": [{"object_id": "a"}]}+ session = self._session_returning(200, body)+ assert _fetch_page_unwrapped(session, f"{SHIPPO_BASE_URL}/shipments/", MagicMock()) == body+++class TestCheckAccess:+ @staticmethod+ def _session(response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ return session++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid Shippo API token"),+ ("forbidden", 403, False, "Invalid Shippo API token"),+ ("server_error", 500, False, "Shippo returned HTTP 500"),+ ]+ )+ @patch(f"{shippo.__name__}.make_tracked_session")+ def test_validate_credentials_status_mapping(+ self,+ _name: str,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ mock_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ mock_session.return_value = self._session(response)+ assert validate_credentials("shippo_test_key") == (expected_valid, expected_message)++ @patch(f"{shippo.__name__}.make_tracked_session")+ def test_connection_error_maps_to_zero(self, mock_session: MagicMock) -> None:+ mock_session.return_value = self._session(requests.ConnectionError("boom"))+ status, message = check_access("shippo_test_key")+ assert status == 0+ assert message is not None and "boom" in message+++class TestShippoSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = shippo_source(+ api_key="shippo_test_key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["object_id"]+ # Shippo doesn't document list ordering, so the watermark must only commit at run end.+ assert response.sort_mode == "desc"++ partition_key = SHIPPO_ENDPOINTS[endpoint].partition_key+ if partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [partition_key]+ else:+ assert response.partition_mode is None++ def test_partition_keys_are_stable_creation_fields(self) -> None:+ # updated_at-style partition keys rewrite partitions on every sync.+ assert all(+ config.partition_key in (None, "object_created", "placed_at") for config in SHIPPO_ENDPOINTS.values()+ )+ # Carrier accounts carry no object_created field, so partitioning them would break the sync.+ assert SHIPPO_ENDPOINTS["carrier_accounts"].partition_key is None++ def test_only_shipments_supports_created_filter(self) -> None:+ # Shippo only honors object_created_* filters on /shipments; declaring them elsewhere+ # would make "incremental" syncs silently unfiltered.+ assert [name for name, config in SHIPPO_ENDPOINTS.items() if config.supports_created_filter] == ["shipments"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/tests/test_shippo_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/tests/test_shippo_source.pynew file mode 100644index 000000000000..6801d95143d0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/tests/test_shippo_source.py@@ -0,0 +1,158 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ShippoSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.shippo.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.shippo.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.shippo.shippo import ShippoResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.shippo.source import ShippoSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestShippoSource:+ def setup_method(self) -> None:+ self.source = ShippoSource()+ self.team_id = 123+ self.config = ShippoSourceConfig(api_key="shippo_test_key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.SHIPPO++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Shippo"+ assert config.label == "Shippo"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/shippo"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_no_connection_host_fields(self) -> None:+ # The only field is the secret API token; the base URL is hardcoded, so there is no+ # non-secret field an editor could retarget to reuse a preserved token elsewhere.+ assert self.source.connection_host_fields == []++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_get_schemas_only_shipments_is_incremental(self) -> None:+ # Only /shipments honors the server-side object_created filters; advertising incremental+ # on any other endpoint would silently sync unfiltered data.+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas["shipments"].supports_incremental is True+ assert [f["field"] for f in schemas["shipments"].incremental_fields] == ["object_created"]+ for name, schema in schemas.items():+ if name != "shipments":+ assert schema.supports_incremental is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["transactions"])+ assert len(schemas) == 1+ assert schemas[0].name == "transactions"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ # Keys must match schema names exactly or the enrichment silently falls back to the LLM.+ assert set(CANONICAL_DESCRIPTIONS) == set(ENDPOINTS)++ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.goshippo.com/shipments/?results=100",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://api.goshippo.com/transactions/?results=100",+ ),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.goshippo.com/shipments/"),+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.goshippo.com/shipments/"),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.shippo.source.validate_shippo_credentials"+ )+ def test_validate_credentials_delegates_with_api_key(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (False, "Invalid Shippo API token")+ result = self.source.validate_credentials(self.config, self.team_id)+ mock_validate.assert_called_once_with("shippo_test_key")+ assert result == (False, "Invalid Shippo API token")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is ShippoResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.shippo.source.shippo_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "shipments"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "shippo_test_key"+ assert kwargs["endpoint"] == "shipments"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.shippo.source.shippo_source")+ def test_source_for_pipeline_drops_watermark_for_full_refresh(self, mock_source: mock.MagicMock) -> None:+ # A stale watermark left on the schema must not leak into a full-refresh run.+ inputs = mock.MagicMock()+ inputs.schema_name = "shipments"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown Shippo schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)