: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 easypost import source (#65643)
Tom Owers116e7c09e26e
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 1137bb152ae4..f0a96fdb11bb 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -97,6 +97,7 @@ the row lists both.| dixa | HTTP | requests | ✅ || doit | HTTP | requests | ✅ || drip | HTTP | requests | ✅ |+| easypost | HTTP | requests | ✅ || freshdesk | HTTP | requests | ✅ || freshsales | HTTP | requests | ✅ || elasticemail | HTTP | requests | ✅ |@@ -367,7 +368,6 @@ doesn't conflict with concurrent PRs.- dynamics365- dynamodb- e_conomic-- easypost- easypromos- ebay- eloquadiff --git a/posthog/temporal/data_imports/sources/easypost/canonical_descriptions.py b/posthog/temporal/data_imports/sources/easypost/canonical_descriptions.pynew file mode 100644index 000000000000..c591349ee0e8--- /dev/null+++ b/posthog/temporal/data_imports/sources/easypost/canonical_descriptions.py@@ -0,0 +1,126 @@+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions++# Sourced from the official EasyPost API docs (https://docs.easypost.com). Partial coverage is fine —+# any uncovered endpoint/column falls back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "shipments": {+ "description": "A request to ship a parcel between two addresses, including rates, the purchased label (postage_label), and tracking.",+ "docs_url": "https://docs.easypost.com/docs/shipments",+ "columns": {+ "id": 'Unique identifier for the shipment, begins with "shp_".',+ "mode": 'Whether the shipment was created in "test" or "production" mode.',+ "status": "Current status of the shipment (e.g. unknown, pre_transit, in_transit, delivered).",+ "tracking_code": "Tracking code assigned by the carrier once postage is purchased.",+ "to_address": "The destination address object.",+ "from_address": "The origin address object.",+ "parcel": "The parcel (dimensions and weight) being shipped.",+ "rates": "Available carrier rates for this shipment.",+ "selected_rate": "The rate that was purchased for this shipment.",+ "postage_label": "The purchased shipping label, including its image URL.",+ "created_at": "When the shipment was created.",+ "updated_at": "When the shipment was last updated.",+ },+ },+ "trackers": {+ "description": "Tracks the progress of a parcel through a carrier's network, with status and per-scan tracking details.",+ "docs_url": "https://docs.easypost.com/docs/trackers",+ "columns": {+ "id": 'Unique identifier for the tracker, begins with "trk_".',+ "mode": 'Whether the tracker was created in "test" or "production" mode.',+ "tracking_code": "The tracking code being tracked.",+ "status": "Current delivery status (e.g. pre_transit, in_transit, out_for_delivery, delivered, failure).",+ "carrier": "The carrier handling the parcel.",+ "tracking_details": "Ordered list of scan events recorded for the parcel.",+ "est_delivery_date": "Estimated delivery date reported by the carrier.",+ "created_at": "When the tracker was created.",+ "updated_at": "When the tracker was last updated.",+ },+ },+ "events": {+ "description": "An immutable record of a change to an EasyPost object (e.g. tracker.updated), the same payload delivered to webhooks.",+ "docs_url": "https://docs.easypost.com/docs/events",+ "columns": {+ "id": 'Unique identifier for the event, begins with "evt_".',+ "object": 'The string "Event".',+ "description": "Result type and event name (e.g. tracker.created).",+ "mode": 'Whether the event was created in "test" or "production" mode.',+ "status": "Delivery status of the associated webhook, if any.",+ "created_at": "When the event was created.",+ "updated_at": "When the event was last updated.",+ },+ },+ "batches": {+ "description": "A group of shipments processed together, used for bulk label purchase and scan form generation.",+ "docs_url": "https://docs.easypost.com/docs/batches",+ "columns": {+ "id": 'Unique identifier for the batch, begins with "batch_".',+ "state": "Current processing state of the batch (e.g. creating, created, purchased).",+ "num_shipments": "Number of shipments in the batch.",+ "created_at": "When the batch was created.",+ "updated_at": "When the batch was last updated.",+ },+ },+ "addresses": {+ "description": "A physical address, optionally verified, used as the origin or destination of shipments.",+ "docs_url": "https://docs.easypost.com/docs/addresses",+ "columns": {+ "id": 'Unique identifier for the address, begins with "adr_".',+ "street1": "First line of the street address.",+ "street2": "Second line of the street address.",+ "city": "City.",+ "state": "State or province.",+ "zip": "Postal code.",+ "country": "ISO 3166 country code.",+ "created_at": "When the address was created.",+ "updated_at": "When the address was last updated.",+ },+ },+ "insurances": {+ "description": "Insurance purchased against loss or damage for a shipment.",+ "docs_url": "https://docs.easypost.com/docs/insurance",+ "columns": {+ "id": 'Unique identifier for the insurance, begins with "ins_".',+ "amount": "Insured value of the parcel.",+ "status": "Current status of the insurance claim/coverage.",+ "tracking_code": "Tracking code of the insured shipment.",+ "created_at": "When the insurance was created.",+ "updated_at": "When the insurance was last updated.",+ },+ },+ "refunds": {+ "description": "A request to refund the postage cost of a purchased label.",+ "docs_url": "https://docs.easypost.com/docs/refunds",+ "columns": {+ "id": 'Unique identifier for the refund, begins with "rfnd_".',+ "status": "Current status of the refund (e.g. submitted, refunded, rejected).",+ "tracking_code": "Tracking code of the shipment being refunded.",+ "carrier": "Carrier the refund was requested from.",+ "created_at": "When the refund was created.",+ "updated_at": "When the refund was last updated.",+ },+ },+ "scan_forms": {+ "description": "A manifest (SCAN form) covering a set of shipments for a single carrier pickup.",+ "docs_url": "https://docs.easypost.com/docs/scan-form",+ "columns": {+ "id": 'Unique identifier for the scan form, begins with "sf_".',+ "status": "Current status of the scan form.",+ "tracking_codes": "Tracking codes of the shipments included on the scan form.",+ "created_at": "When the scan form was created.",+ "updated_at": "When the scan form was last updated.",+ },+ },+ "pickups": {+ "description": "A scheduled carrier pickup for one or more shipments.",+ "docs_url": "https://docs.easypost.com/docs/pickups",+ "columns": {+ "id": 'Unique identifier for the pickup, begins with "pickup_".',+ "status": "Current status of the pickup (e.g. unknown, scheduled, canceled).",+ "reference": "Optional user-supplied reference for the pickup.",+ "min_datetime": "Earliest time the parcel is available for pickup.",+ "max_datetime": "Latest time the parcel is available for pickup.",+ "created_at": "When the pickup was created.",+ "updated_at": "When the pickup was last updated.",+ },+ },+}diff --git a/posthog/temporal/data_imports/sources/easypost/easypost.py b/posthog/temporal/data_imports/sources/easypost/easypost.pynew file mode 100644index 000000000000..1b36c3fe7d17--- /dev/null+++ b/posthog/temporal/data_imports/sources/easypost/easypost.py@@ -0,0 +1,188 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, datetime+from typing import Any++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.easypost.settings import EASYPOST_ENDPOINTS++EASYPOST_BASE_URL = "https://api.easypost.com/v2"+# EasyPost caps page_size at 100 across cursor-paginated list endpoints.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+++class EasypostRetryableError(Exception):+ pass+++class EasypostResumeConfig:+ # `before_id` of the page we last yielded. EasyPost paginates newest-first, so advancing the+ # cursor means asking for records created *before* this id. `None` resumes from the first page.+ before_id: str | None = None+++def _ensure_utc(value: datetime) -> datetime:+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+++def _parse_datetime(value: Any) -> datetime | None:+ """Parse an EasyPost ISO-8601 timestamp (e.g. ``2024-01-15T10:30:00Z``) to an aware UTC datetime."""+ if value is None:+ return None+ if isinstance(value, datetime):+ return _ensure_utc(value)+ if isinstance(value, str):+ try:+ return _ensure_utc(datetime.fromisoformat(value.replace("Z", "+00:00")))+ except ValueError:+ return None+ return None+++def _format_datetime(value: datetime) -> str:+ """Format a datetime for EasyPost's ``start_datetime`` filter (ISO-8601, UTC, ``Z`` suffix)."""+ return _ensure_utc(value).strftime("%Y-%m-%dT%H:%M:%SZ")+++@retry(+ retry=retry_if_exception_type((EasypostRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, params: dict[str, Any], logger: FilteringBoundLogger+) -> dict[str, Any]:+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise EasypostRetryableError(f"EasyPost API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"EasyPost API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_key: str) -> bool:+ """Probe a cheap list endpoint. EasyPost API keys carry full account access (no per-endpoint+ scopes), so a 200 means the key is genuine and active; anything else (401 invalid, 403 inactive)+ is a credential failure."""+ session = make_tracked_session(redact_values=(api_key,))+ session.auth = (api_key, "")+ try:+ response = session.get(+ f"{EASYPOST_BASE_URL}/shipments", params={"page_size": 1}, timeout=REQUEST_TIMEOUT_SECONDS+ )+ return response.status_code == 200+ except Exception:+ return False+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[EasypostResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = EASYPOST_ENDPOINTS[endpoint]+ incremental_field_name = incremental_field or "created_at"++ session = make_tracked_session(redact_values=(api_key,))+ session.auth = (api_key, "")++ # Incremental cursor: EasyPost returns newest-first, so we walk backwards (via `before_id`) and+ # stop once a page reaches the watermark. `start_datetime` filters server-side on `created_at`+ # as an optimization; the client-side stop guarantees correct, bounded behaviour even if the+ # endpoint ignores the filter when combined with cursor pagination.+ last_value_dt: datetime | None = None+ start_datetime: str | None = None+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ last_value_dt = _parse_datetime(db_incremental_field_last_value)+ if last_value_dt is not None:+ start_datetime = _format_datetime(last_value_dt)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ before_id = resume.before_id if resume else None+ if before_id:+ logger.debug(f"EasyPost: resuming {endpoint} from before_id={before_id}")++ while True:+ params: dict[str, Any] = {"page_size": PAGE_SIZE}+ if before_id:+ params["before_id"] = before_id+ if start_datetime:+ params["start_datetime"] = start_datetime++ data = _fetch_page(session, f"{EASYPOST_BASE_URL}{config.path}", params, logger)+ items = data.get(config.name, [])+ if not items:+ break++ has_more = bool(data.get("has_more", False))++ reached_watermark = False+ rows: list[dict[str, Any]] = []+ for item in items:+ if last_value_dt is not None:+ created = _parse_datetime(item.get(incremental_field_name))+ if created is not None and created <= last_value_dt:+ reached_watermark = True+ break+ rows.append(item)++ if rows:+ yield rows+ # Save the cursor for the page we just yielded (not the next one) so a crash re-fetches+ # and re-yields this page — merge dedupes on the `id` primary key — rather than skipping it.+ resumable_source_manager.save_state(EasypostResumeConfig(before_id=before_id))++ if reached_watermark or not has_more:+ break++ before_id = items[-1]["id"]+++def easypost_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[EasypostResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = EASYPOST_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,+ incremental_field=incremental_field,+ ),+ primary_keys=config.primary_keys,+ # EasyPost list endpoints return records newest-first (descending creation time).+ sort_mode="desc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/posthog/temporal/data_imports/sources/easypost/settings.py b/posthog/temporal/data_imports/sources/easypost/settings.pynew file mode 100644index 000000000000..410cb4f9982b--- /dev/null+++ b/posthog/temporal/data_imports/sources/easypost/settings.py@@ -0,0 +1,95 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class EasypostEndpointConfig:+ name: str+ # Path segment under https://api.easypost.com/v2/. EasyPost list responses wrap the array+ # under a key matching the resource (e.g. `/shipments` -> {"shipments": [...]}), so the+ # endpoint name doubles as the response collection key.+ path: str+ incremental_fields: list[IncrementalField]+ # Stable creation timestamp used both as the incremental cursor and partition key. EasyPost+ # orders list results newest-first by creation time, so `created_at` is the only field whose+ # ordering the descending pagination + watermark logic can rely on.+ partition_key: Optional[str] = "created_at"+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Events are immutable once emitted, so they're append-only. Mutable resources (shipments,+ # trackers, …) still expose `created_at` incremental sync, which appends newly created rows;+ # later mutations to an existing row are only picked up by a full refresh.+ append_only: bool = False+ should_sync_default: bool = True+++def _created_at_fields() -> list[IncrementalField]:+ return [+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ]+++# Cursor-paginated list endpoints (before_id/after_id + has_more) that all share the EasyPost+# object shape: a globally-unique prefixed `id`, plus `created_at` / `updated_at` ISO-8601+# timestamps. `start_datetime` filters server-side on `created_at`. `/parcels` has no list+# endpoint and `/webhooks` is unpaginated, so neither is exposed as a sync table here.+EASYPOST_ENDPOINTS: dict[str, EasypostEndpointConfig] = {+ "addresses": EasypostEndpointConfig(+ name="addresses",+ path="/addresses",+ incremental_fields=_created_at_fields(),+ ),+ "batches": EasypostEndpointConfig(+ name="batches",+ path="/batches",+ incremental_fields=_created_at_fields(),+ ),+ "events": EasypostEndpointConfig(+ name="events",+ path="/events",+ incremental_fields=_created_at_fields(),+ append_only=True,+ ),+ "insurances": EasypostEndpointConfig(+ name="insurances",+ path="/insurances",+ incremental_fields=_created_at_fields(),+ ),+ "pickups": EasypostEndpointConfig(+ name="pickups",+ path="/pickups",+ incremental_fields=_created_at_fields(),+ ),+ "refunds": EasypostEndpointConfig(+ name="refunds",+ path="/refunds",+ incremental_fields=_created_at_fields(),+ ),+ "scan_forms": EasypostEndpointConfig(+ name="scan_forms",+ path="/scan_forms",+ incremental_fields=_created_at_fields(),+ ),+ "shipments": EasypostEndpointConfig(+ name="shipments",+ path="/shipments",+ incremental_fields=_created_at_fields(),+ ),+ "trackers": EasypostEndpointConfig(+ name="trackers",+ path="/trackers",+ incremental_fields=_created_at_fields(),+ ),+}++ENDPOINTS = tuple(EASYPOST_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in EASYPOST_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/easypost/source.py b/posthog/temporal/data_imports/sources/easypost/source.pyindex 7cd1c5f7ece9..7d0eb4fda076 100644--- a/posthog/temporal/data_imports/sources/easypost/source.py+++ b/posthog/temporal/data_imports/sources/easypost/source.py@@ -1,20 +1,33 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptionsfrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchema+from posthog.temporal.data_imports.sources.easypost.easypost import (+ EasypostResumeConfig,+ easypost_source,+ validate_credentials as validate_easypost_credentials,+)+from posthog.temporal.data_imports.sources.easypost.settings import EASYPOST_ENDPOINTS, ENDPOINTS, INCREMENTAL_FIELDSfrom posthog.temporal.data_imports.sources.generated_configs import EasypostSourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class EasypostSource(SimpleSource[EasypostSourceConfig]):+class EasypostSource(ResumableSource[EasypostSourceConfig, EasypostResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.EASYPOST@@ -24,8 +37,94 @@ class EasypostSource(SimpleSource[EasypostSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.EASYPOST,category=DataWarehouseSourceCategory.E_COMMERCE,- label="Easypost",+ label="EasyPost",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your EasyPost API key to automatically pull your EasyPost shipping data into the PostHog Data warehouse.++You can find your API keys in your [EasyPost account settings](https://www.easypost.com/account/api-keys). Use a production key to sync production data, or a test key to sync test-mode data.""",iconPath="/static/services/easypost.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/easypost",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="EZAK... or EZTK...",+ secret=True,+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from posthog.temporal.data_imports.sources.easypost.canonical_descriptions import CANONICAL_DESCRIPTIONS++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # EasyPost API keys carry full account access (no per-endpoint scopes), so a 401 or 403+ # from a list endpoint means the key is invalid, revoked, or inactive — retrying can't+ # fix that. Match the stable status text and base host, not the per-request path.+ "401 Client Error: Unauthorized for url: https://api.easypost.com": "Your EasyPost API key is invalid or has been revoked. Create a new key in your EasyPost account settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.easypost.com": "Your EasyPost API key is inactive or not authorized. Activate the key (or create a new one) in your EasyPost account settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: EasypostSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = EASYPOST_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ # `created_at` incremental sync appends newly created rows; immutable resources+ # (events) are append-only, mutable ones additionally allow incremental.+ supports_incremental=not endpoint_config.append_only,+ supports_append=True,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ 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: EasypostSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_easypost_credentials(config.api_key):+ return True, None++ return False, "Invalid EasyPost API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[EasypostResumeConfig]:+ return ResumableSourceManager[EasypostResumeConfig](inputs, EasypostResumeConfig)++ def source_for_pipeline(+ self,+ config: EasypostSourceConfig,+ resumable_source_manager: ResumableSourceManager[EasypostResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return easypost_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,+ incremental_field=inputs.incremental_field,+ )diff --git a/posthog/temporal/data_imports/sources/easypost/tests/test_easypost.py b/posthog/temporal/data_imports/sources/easypost/tests/test_easypost.pynew file mode 100644index 000000000000..54f1bf608415--- /dev/null+++ b/posthog/temporal/data_imports/sources/easypost/tests/test_easypost.py@@ -0,0 +1,205 @@+from datetime import UTC, datetime+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.temporal.data_imports.sources.easypost import easypost+from posthog.temporal.data_imports.sources.easypost.easypost import (+ EasypostResumeConfig,+ _format_datetime,+ _parse_datetime,+ easypost_source,+ get_rows,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.easypost.settings import ENDPOINTS+++class _FakeResumableManager:+ def __init__(self, state: EasypostResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[EasypostResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> EasypostResumeConfig | None:+ return self._state++ def save_state(self, data: EasypostResumeConfig) -> None:+ self.saved.append(data)+++def _patch_pages(monkeypatch: Any, pages_by_before_id: dict[Any, dict[str, Any]]) -> None:+ def fake_fetch(session: Any, url: str, params: dict[str, Any], logger: Any) -> dict[str, Any]:+ return pages_by_before_id[params.get("before_id")]++ monkeypatch.setattr(easypost, "_fetch_page", fake_fetch)+++def _collect(manager: _FakeResumableManager, endpoint: str = "shipments", **kwargs: Any) -> list[dict[str, Any]]:+ rows: list[dict[str, Any]] = []+ for batch in get_rows("k", endpoint, MagicMock(), manager, **kwargs): # type: ignore[arg-type]+ rows.extend(batch)+ return rows+++class TestParseDatetime:+ @parameterized.expand(+ [+ ("z_suffix", "2024-01-15T10:30:00Z", datetime(2024, 1, 15, 10, 30, 0, tzinfo=UTC)),+ ("offset", "2024-01-15T10:30:00+00:00", datetime(2024, 1, 15, 10, 30, 0, tzinfo=UTC)),+ ("naive_datetime", datetime(2024, 1, 15, 10, 30, 0), datetime(2024, 1, 15, 10, 30, 0, tzinfo=UTC)),+ ("none", None, None),+ ("garbage", "not-a-date", None),+ ]+ )+ def test_parse(self, _name: str, value: Any, expected: datetime | None) -> None:+ assert _parse_datetime(value) == expected+++class TestFormatDatetime:+ def test_uses_z_suffix(self) -> None:+ result = _format_datetime(datetime(2024, 1, 2, 12, 0, 0, tzinfo=UTC))+ assert result == "2024-01-02T12:00:00Z"+ assert "+00:00" not in result+++class TestGetRows:+ def test_paginates_via_before_id(self, monkeypatch: Any) -> None:+ _patch_pages(+ monkeypatch,+ {+ None: {"shipments": [{"id": "shp_1"}, {"id": "shp_2"}], "has_more": True},+ "shp_2": {"shipments": [{"id": "shp_3"}], "has_more": False},+ },+ )+ rows = _collect(_FakeResumableManager())+ assert [r["id"] for r in rows] == ["shp_1", "shp_2", "shp_3"]++ def test_stops_when_page_is_empty(self, monkeypatch: Any) -> None:+ _patch_pages(monkeypatch, {None: {"shipments": [], "has_more": True}})+ assert _collect(_FakeResumableManager()) == []++ def test_saves_resume_cursor_for_each_yielded_page(self, monkeypatch: Any) -> None:+ # The saved cursor points at the page just yielded (not the next one), so a crash re-fetches+ # and re-yields it rather than skipping ahead — merge dedupes on the id primary key.+ manager = _FakeResumableManager()+ _patch_pages(+ monkeypatch,+ {+ None: {"shipments": [{"id": "shp_1"}], "has_more": True},+ "shp_1": {"shipments": [{"id": "shp_2"}], "has_more": False},+ },+ )+ _collect(manager)+ assert [s.before_id for s in manager.saved] == [None, "shp_1"]++ def test_resumes_from_saved_before_id(self, monkeypatch: Any) -> None:+ _patch_pages(monkeypatch, {"shp_2": {"shipments": [{"id": "shp_3"}], "has_more": False}})+ rows = _collect(_FakeResumableManager(EasypostResumeConfig(before_id="shp_2")))+ assert [r["id"] for r in rows] == ["shp_3"]++ def test_incremental_stops_at_watermark(self, monkeypatch: Any) -> None:+ # Descending order: once a record at/below the watermark appears, everything after it is older,+ # so pagination must stop client-side even though has_more is True.+ _patch_pages(+ monkeypatch,+ {+ None: {+ "shipments": [+ {"id": "shp_3", "created_at": "2024-01-03T00:00:00Z"},+ {"id": "shp_2", "created_at": "2024-01-02T00:00:00Z"},+ {"id": "shp_1", "created_at": "2024-01-01T00:00:00Z"},+ ],+ "has_more": True,+ },+ },+ )+ rows = _collect(+ _FakeResumableManager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),+ incremental_field="created_at",+ )+ assert [r["id"] for r in rows] == ["shp_3"]++ def test_incremental_passes_start_datetime_filter(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}++ def fake_fetch(session: Any, url: str, params: dict[str, Any], logger: Any) -> dict[str, Any]:+ captured.update(params)+ return {"shipments": [], "has_more": False}++ monkeypatch.setattr(easypost, "_fetch_page", fake_fetch)+ _collect(+ _FakeResumableManager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 2, 12, 0, 0, tzinfo=UTC),+ incremental_field="created_at",+ )+ assert captured["start_datetime"] == "2024-01-02T12:00:00Z"+ assert captured["page_size"] == 100++ def test_full_refresh_sends_no_time_filter(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}++ def fake_fetch(session: Any, url: str, params: dict[str, Any], logger: Any) -> dict[str, Any]:+ captured.update(params)+ return {"shipments": [], "has_more": False}++ monkeypatch.setattr(easypost, "_fetch_page", fake_fetch)+ _collect(_FakeResumableManager())+ assert "start_datetime" not in captured+ assert "before_id" not in captured+++class TestValidateCredentials:+ @parameterized.expand(+ [("ok", 200, True), ("unauthorized", 401, False), ("inactive", 403, False), ("server", 500, False)]+ )+ def test_status_mapping(self, _name: str, status: int, expected: bool) -> None:+ session = MagicMock()+ response = MagicMock()+ response.status_code = status+ session.get.return_value = response+ with patch.object(easypost, "make_tracked_session", lambda *a, **k: session):+ assert validate_credentials("k") is expected++ def test_network_error_is_invalid(self) -> None:+ session = MagicMock()+ session.get.side_effect = Exception("boom")+ with patch.object(easypost, "make_tracked_session", lambda *a, **k: session):+ assert validate_credentials("k") is False++ def test_redacts_api_key_in_http_logging(self) -> None:+ # The API key is sent as the Basic auth username; it must be registered for redaction so it+ # cannot leak into HTTP telemetry/sample capture.+ factory = MagicMock(return_value=MagicMock())+ with patch.object(easypost, "make_tracked_session", factory):+ validate_credentials("secret-key")+ factory.assert_called_once_with(redact_values=("secret-key",))+++class TestGetRowsRedaction:+ def test_redacts_api_key_in_http_logging(self, monkeypatch: Any) -> None:+ # Same secret-leak guard as validate_credentials, on the sync request path.+ factory = MagicMock(return_value=MagicMock())+ monkeypatch.setattr(easypost, "make_tracked_session", factory)+ _patch_pages(monkeypatch, {None: {"shipments": [], "has_more": False}})+ list(get_rows("secret-key", "shipments", MagicMock(), _FakeResumableManager())) # type: ignore[arg-type]+ factory.assert_called_once_with(redact_values=("secret-key",))+++class TestEasypostSource:+ @parameterized.expand([(name,) for name in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = easypost_source("k", endpoint, MagicMock(), _FakeResumableManager()) # type: ignore[arg-type]+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # EasyPost returns newest-first; the watermark logic depends on this being declared.+ assert response.sort_mode == "desc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]diff --git a/posthog/temporal/data_imports/sources/easypost/tests/test_easypost_source.py b/posthog/temporal/data_imports/sources/easypost/tests/test_easypost_source.pynew file mode 100644index 000000000000..a57fe1081617--- /dev/null+++ b/posthog/temporal/data_imports/sources/easypost/tests/test_easypost_source.py@@ -0,0 +1,143 @@+from typing import Any++from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.schema import (+ ExternalDataSourceType as SchemaExternalDataSourceType,+ SourceFieldInputConfig,+)++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.easypost.easypost import EasypostResumeConfig+from posthog.temporal.data_imports.sources.easypost.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.easypost.source import EasypostSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++def _config() -> Any:+ config = MagicMock()+ config.api_key = "EZAK_test"+ return config+++class TestSourceConfig:+ def test_source_type(self) -> None:+ assert EasypostSource().source_type == ExternalDataSourceType.EASYPOST++ def test_source_config_basics(self) -> None:+ config = EasypostSource().get_source_config+ assert config.name == SchemaExternalDataSourceType.EASYPOST+ assert config.label == "EasyPost"+ # Stays hidden behind the unreleased flag while in alpha.+ assert config.unreleasedSource is True++ def test_source_config_has_password_api_key_field(self) -> None:+ fields = EasypostSource().get_source_config.fields+ assert [f.name for f in fields] == ["api_key"]+ api_key_field = fields[0]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.required is True+ assert api_key_field.secret is True+++class TestGetSchemas:+ def test_returns_every_endpoint(self) -> None:+ schemas = EasypostSource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_names_filter(self) -> None:+ schemas = EasypostSource().get_schemas(_config(), team_id=1, names=["shipments", "events"])+ assert {s.name for s in schemas} == {"shipments", "events"}++ @parameterized.expand([(name,) for name in ENDPOINTS])+ def test_every_schema_advertises_created_at(self, endpoint: str) -> None:+ schemas = {s.name: s for s in EasypostSource().get_schemas(_config(), team_id=1)}+ schema = schemas[endpoint]+ assert [f["field"] for f in schema.incremental_fields] == ["created_at"]+ assert schema.supports_append is True++ def test_events_are_append_only(self) -> None:+ # Events are immutable, so they're append-only (no incremental updates to existing rows).+ schemas = {s.name: s for s in EasypostSource().get_schemas(_config(), team_id=1)}+ assert schemas["events"].supports_incremental is False+ assert schemas["shipments"].supports_incremental is True+++class TestValidateCredentials:+ def test_valid(self, monkeypatch: Any) -> None:+ from posthog.temporal.data_imports.sources.easypost import source as source_module++ monkeypatch.setattr(source_module, "validate_easypost_credentials", lambda api_key: True)+ assert EasypostSource().validate_credentials(_config(), team_id=1) == (True, None)++ def test_invalid(self, monkeypatch: Any) -> None:+ from posthog.temporal.data_imports.sources.easypost import source as source_module++ monkeypatch.setattr(source_module, "validate_easypost_credentials", lambda api_key: False)+ ok, error = EasypostSource().validate_credentials(_config(), team_id=1)+ assert ok is False+ assert error is not None+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.easypost.com/v2/shipments?page_size=1",+ ),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.easypost.com/v2/events"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = EasypostSource().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.easypost.com/v2/shipments"),+ ("rate_limit", "429 Client Error: Too Many Requests for url: https://api.easypost.com/v2/shipments"),+ ("timeout", "HTTPSConnectionPool(host='api.easypost.com', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = EasypostSource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestResumableSourceManager:+ def test_manager_is_bound_to_resume_config(self) -> None:+ inputs = MagicMock()+ inputs.logger = MagicMock()+ manager = EasypostSource().get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is EasypostResumeConfig+++class TestSourceForPipeline:+ def test_plumbs_incremental_inputs(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "shipments"+ inputs.logger = MagicMock()+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-01T00:00:00Z"+ inputs.incremental_field = "created_at"++ response = EasypostSource().source_for_pipeline(_config(), MagicMock(), inputs)+ assert response.name == "shipments"+ assert response.sort_mode == "desc"++ def test_drops_last_value_when_not_incremental(self) -> None:+ # When the schema isn't synced incrementally, the watermark must not leak into the request.+ inputs = MagicMock()+ inputs.schema_name = "addresses"+ inputs.logger = MagicMock()+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-01-01T00:00:00Z"+ inputs.incremental_field = None++ response = EasypostSource().source_for_pipeline(_config(), MagicMock(), inputs)+ assert response.name == "addresses"diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 8400fb4a73c8..b4f6065e9187 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -997,7 +997,7 @@ class EZOfficeInventorySourceConfig(config.Config):@config.configclass EasypostSourceConfig(config.Config):- pass+ api_key: str@config.config