Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add AfterShip source (#77131)

Tom Owers740706f34152
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index cb7555057cf1..7b435dd2f0a1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -54,6 +54,7 @@ the row lists both.
| adobe_commerce | HTTP | requests | ✅ |
| adroll | HTTP | requests | ✅ |
| adyen | HTTP | requests | ✅ |
+| aftership | HTTP | requests + `rest_source.RESTClient` | ✅ |
| agilecrm | HTTP | requests | ✅ |
| aha | HTTP | requests | ✅ |
| aha_ideas | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -714,7 +715,6 @@ doesn't conflict with concurrent PRs.
- adapty
- adobe_commerce
- adp_workforce_now
-- aftership
- ahrefs
- aikido_security
- airbridge
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/aftership.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/aftership.py
new file mode 100644
index 000000000000..aed438557488
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/aftership.py
@@ -0,0 +1,183 @@
+import dataclasses
+from datetime import UTC, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aftership.settings import (
+ AFTERSHIP_BASE_URL,
+ AFTERSHIP_ENDPOINTS,
+ DEFAULT_VERSION,
+)
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ JSONResponseCursorPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+
+# AfterShip authenticates every request with the API key in this header. The legacy
+# `aftership-api-key` header stopped working with the 2023-10 version.
+API_KEY_HEADER = "as-api-key"
+
+VALIDATION_TIMEOUT_SECONDS = 15
+
+
+class AftershipResumeConfig:
+ # Cursor of the next unread page, replayed as `cursor` on the resumed request.
+ cursor: str
+ # The time-filter value the interrupted run was using, reused verbatim on resume. The
+ # watermark may have advanced from committed batches, and narrowing the window mid-walk
+ # would hand AfterShip a cursor that points outside the filtered result set.
+ incremental_start: Optional[str] = None
+
+
+def base_url(api_version: str) -> str:
+ return f"{AFTERSHIP_BASE_URL}/{api_version}"
+
+
+def _to_aftership_datetime(value: Any) -> Optional[str]:
+ """Coerce an incremental cursor value into the exact shape AfterShip's time filters accept.
+
+ `created_at_min` / `updated_at_min` are validated against
+ `YYYY-MM-DDTHH:mm:ss+HH:MM`, so a trailing `Z` or fractional seconds is rejected with a 400.
+ """
+ if isinstance(value, str):
+ try:
+ value = datetime.fromisoformat(value)
+ except ValueError:
+ return None
+ if not isinstance(value, datetime):
+ return None
+ normalized = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return normalized.replace(microsecond=0).isoformat()
+
+
+def _drop_courier_connection_credentials(row: dict[str, Any]) -> dict[str, Any]:
+ # `credentials` carries the carrier API keys, usernames and passwords the user handed to
+ # AfterShip. They are login secrets rather than shipment analytics, so they never reach the
+ # warehouse, where any project member could query them.
+ return {key: value for key, value in row.items() if key != "credentials"}
+
+
+def check_access(
+ api_key: str,
+ schema_name: Optional[str] = None,
+ api_version: str = DEFAULT_VERSION,
+) -> tuple[bool, Optional[int]]:
+ """Probe AfterShip and report ``(is_valid, status_code)``.
+
+ With no ``schema_name`` this only proves the key is genuine; with one it proves the key can
+ read that endpoint. ``limit=1`` keeps the probe off the per-endpoint rate-limit budget.
+ """
+ endpoint = AFTERSHIP_ENDPOINTS[schema_name] if schema_name is not None else AFTERSHIP_ENDPOINTS["trackings"]
+ query = urlencode({"limit": 1}) if endpoint.cursor_paginated else ""
+ url = f"{base_url(api_version)}{endpoint.path}"
+ if query:
+ url = f"{url}?{query}"
+
+ return validate_via_probe(
+ lambda: make_tracked_session(redact_values=(api_key,)),
+ url,
+ headers={API_KEY_HEADER: api_key},
+ timeout=VALIDATION_TIMEOUT_SECONDS,
+ # The key rides a custom header, which `requests` would replay to a cross-origin redirect.
+ allow_redirects=False,
+ )
+
+
+def aftership_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[AftershipResumeConfig],
+ should_use_incremental_field: bool = False,
+ incremental_field_name: Optional[str] = None,
+ db_incremental_field_last_value: Optional[Any] = None,
+ api_version: str = DEFAULT_VERSION,
+) -> SourceResponse:
+ config = AFTERSHIP_ENDPOINTS[endpoint]
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None:
+ initial_paginator_state = {"cursor": resume.cursor}
+ incremental_start = resume.incremental_start
+ else:
+ incremental_start = (
+ _to_aftership_datetime(db_incremental_field_last_value)
+ if should_use_incremental_field and db_incremental_field_last_value is not None
+ else None
+ )
+
+ # The user's chosen incremental field decides which server-side filter we send. A field with
+ # no matching filter (or an endpoint with none at all) syncs the full window instead of
+ # pretending to filter.
+ incremental_param = config.incremental_params.get(incremental_field_name or "")
+
+ params: dict[str, Any] = dict(config.extra_params)
+ if incremental_param is not None and incremental_start is not None:
+ params[incremental_param] = incremental_start
+
+ rest_config: RESTAPIConfig = {
+ "client": {
+ "base_url": base_url(api_version),
+ "auth": {"type": "api_key", "name": API_KEY_HEADER, "location": "header", "api_key": api_key},
+ "paginator": JSONResponseCursorPaginator(cursor_path="data.pagination.next_cursor", cursor_param="cursor")
+ if config.cursor_paginated
+ else SinglePagePaginator(),
+ },
+ "resources": [
+ {
+ "name": endpoint,
+ "endpoint": {
+ "path": config.path,
+ "params": params,
+ "data_selector": config.data_selector,
+ },
+ **({"data_map": _drop_courier_connection_credentials} if endpoint == "courier_connections" else {}),
+ }
+ ],
+ }
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Persist only while a next page remains. The framework calls this AFTER a page is
+ # yielded, so a crash re-yields the last page (merge dedupes on the primary key) rather
+ # than skipping it.
+ if state and state.get("cursor"):
+ resumable_source_manager.save_state(
+ AftershipResumeConfig(cursor=str(state["cursor"]), incremental_start=incremental_start)
+ )
+
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ # The time window is written into `params` above (a resumed run must reuse the saved
+ # window verbatim), so the framework's own incremental plumbing stays out of the way.
+ db_incremental_field_last_value=None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=config.primary_key,
+ # AfterShip documents no ordering for its list endpoints and offers no sort parameter, so
+ # we can't claim rows arrive oldest-first. `desc` is the safe reading of an unknown order:
+ # the pipeline commits the watermark once at the end of the sync from the highest value it
+ # saw, instead of checkpointing each batch as if the stream were ascending.
+ sort_mode="desc",
+ 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,
+ column_hints=resource.column_hints,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/canonical_descriptions.py
new file mode 100644
index 000000000000..d186d35bb3b1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/canonical_descriptions.py
@@ -0,0 +1,126 @@
+"""Canonical, documentation-sourced descriptions for AfterShip Tracking API tables and columns.
+
+Sourced from the AfterShip Tracking API 2026-07 OpenAPI schema and reference
+(https://www.aftership.com/docs/tracking). Keyed by the table names in `settings.py`
+`ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced AfterShip table. Columns
+absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "trackings": {
+ "description": "A shipment AfterShip is tracking, including its current delivery status, origin and destination, estimated delivery dates, and the full checkpoint history reported by the carrier.",
+ "docs_url": "https://www.aftership.com/docs/tracking/model/tracking",
+ "columns": {
+ "id": "System-generated tracking ID, which can be customized by the user when creating the tracking.",
+ "legacy_id": "The original 24-character tracking ID, kept for compatibility since IDs grew to 32 characters.",
+ "created_at": "Date and time the shipment was imported or added to AfterShip, in UTC.",
+ "updated_at": "Date and time the shipment was last updated, in UTC.",
+ "tracking_number": "Carrier tracking number of the shipment.",
+ "slug": "Unique courier code. Set to 'unrecognized' when the tracking number matches no known carrier.",
+ "active": "Whether AfterShip is still tracking the shipment. False once there have been no updates for a few days.",
+ "custom_fields": "Custom key/value fields set on the tracking when it was created.",
+ "transit_time": "Total transit time in days: delivered date minus pickup date, or current date minus pickup date while undelivered. Null when there is no pickup date.",
+ "origin_country_region": "ISO Alpha-3 code of the origin country or region.",
+ "origin_state": "State of the sender's address.",
+ "origin_city": "City of the sender's address.",
+ "origin_postal_code": "Postal code of the sender's address.",
+ "origin_raw_location": "Sender address the shipment ships from.",
+ "destination_country_region": "ISO Alpha-3 code of the destination country or region.",
+ "destination_state": "State of the recipient's address.",
+ "destination_city": "City of the recipient's address.",
+ "destination_postal_code": "Postal code of the recipient's address.",
+ "destination_raw_location": "Shipping address the shipment ships to.",
+ "courier_destination_country_region": "Destination country or region as reported by the carrier, ISO Alpha-3. Null when the carrier does not provide it.",
+ "courier_estimated_delivery_date": "Estimated delivery date provided by the carrier, with its min and max bounds.",
+ "note": "Free text note on the tracking.",
+ "order_id": "Globally unique identifier for the order.",
+ "order_id_path": "URL of the order in your own system or store.",
+ "order_date": "Date and time the order was created in your system or store.",
+ "shipment_package_count": "Number of packages under the tracking.",
+ "shipment_pickup_date": "Date and time the carrier picked the shipment up, in the pickup location's timezone.",
+ "shipment_delivery_date": "Date and time the shipment was delivered, in the recipient's timezone.",
+ "shipment_type": "Carrier service type used for the shipment.",
+ "shipment_weight": "Total weight of the shipment, as a value and unit.",
+ "shipment_dimensions": "Physical dimensions of the package: length, width and height.",
+ "signed_by": "Name recorded as signing for a delivered shipment.",
+ "source": "How the tracking was added to AfterShip.",
+ "tag": "Current delivery status, one of Pending, InfoReceived, InTransit, OutForDelivery, AttemptFail, Delivered, AvailableForPickup, Exception or Expired.",
+ "subtag": "Current delivery sub-status, a more specific breakdown of the tag.",
+ "subtag_message": "Human-readable message for the current sub-status.",
+ "title": "Display title for the tracking. Defaults to the tracking number and can be customized.",
+ "tracked_count": "Number of times AfterShip has polled the carrier for this shipment.",
+ "language": "Recipient's language, used to pick the language of tracking notifications.",
+ "checkpoints": "Array of carrier checkpoint events, each with its time, location, status and message.",
+ "subscribed_smses": "Phone numbers subscribed to SMS notifications for this shipment.",
+ "subscribed_emails": "Email addresses subscribed to email notifications for this shipment.",
+ "return_to_sender": "Whether the shipment is being returned to the sender, based on its checkpoint sub-tags.",
+ "order_promised_delivery_date": "Delivery date promised to the customer for the order, in the recipient's timezone.",
+ "delivery_type": "How the shipment is delivered: pickup_at_store, pickup_at_courier or door_to_door.",
+ "pickup_location": "Pickup location for the recipient.",
+ "pickup_note": "Pickup note for the recipient.",
+ "courier_tracking_link": "Official carrier tracking URL for the shipment, when the carrier has one.",
+ "first_attempted_at": "Date and time of the carrier's first delivery attempt, in the recipient's timezone.",
+ "courier_redirect_link": "Carrier URL where the recipient can change the delivery date or address, when supported.",
+ "tracking_account_number": "Shipper's carrier account number, required by some carriers to retrieve tracking info.",
+ "tracking_key": "Extra tracking credential required by some carriers to retrieve tracking info.",
+ "tracking_ship_date": "Date the merchant shipped the package and it became ready for carrier pickup.",
+ "on_time_status": "Whether the shipment was delivered on time.",
+ "on_time_difference": "Number of days the delivery ran early or late.",
+ "order_tags": "Tags applied to the order.",
+ "aftership_estimated_delivery_date": "Estimated delivery date predicted by AfterShip's model and shown to recipients, with its confidence code and bounds.",
+ "custom_estimated_delivery_date": "Estimated delivery time derived from your own custom estimated-delivery-date settings.",
+ "order_number": "Human-readable identifier for the order.",
+ "first_estimated_delivery": "The shipment's original estimated delivery date, and which source produced it.",
+ "latest_estimated_delivery": "The most recently calculated estimated delivery date, its source, and why it was revised.",
+ "shipment_tags": "Tags applied to the shipment for categorizing and filtering.",
+ "courier_connection_id": "Identifier of the carrier account connection used to fetch updates for this shipment.",
+ "carbon_emissions": "Total carbon emissions generated by the shipment, as a value and unit, when AfterShip can calculate it.",
+ "location_id": "Identifier of the location the items were fulfilled from, used as the origin address when set.",
+ "shipping_method": "Shipping method the customer chose at checkout.",
+ "failed_delivery_attempts": "Number of failed delivery attempts recorded during the shipment.",
+ "signature_requirement": "Proof-of-delivery signature option required for the shipment.",
+ "delivery_location_type": "Secure place the carrier left the package, such as a locker, mailbox or front porch.",
+ "aftership_tracking_url": "URL of the AfterShip shipment tracking page for this shipment.",
+ "aftership_tracking_order_url": "URL of the AfterShip order tracking page covering every shipment in the order.",
+ "first_mile": "Details of the first leg of the shipment, up to the handover to the last-mile carrier.",
+ "last_mile": "Details of the last leg of the shipment, from the last-mile carrier through to delivery.",
+ "customers": "Customer records associated with the tracking, up to three.",
+ "proof_of_delivery": "Proof-of-delivery records captured on delivery, such as a signature or photo.",
+ "multi_piece_info": "Details of the other packages when one shipment order is fulfilled by several physical packages.",
+ "shipment_direction": "Business direction of the shipment: 'forward' for an outbound order shipment, 'return' for a customer return.",
+ "return_shipment": "The return shipment linked to this outbound shipment, when AfterShip has detected one.",
+ "forward_shipment": "The original outbound shipment this return traces back to, when AfterShip has detected one.",
+ },
+ },
+ "couriers": {
+ "description": "A carrier activated on your AfterShip account, with the extra fields it needs to track a shipment and the countries it serves.",
+ "docs_url": "https://www.aftership.com/docs/tracking/model/courier",
+ "columns": {
+ "slug": "Unique courier code used to identify the carrier across the AfterShip API.",
+ "name": "Name of the courier.",
+ "phone": "Contact phone number of the courier.",
+ "other_name": "Alternative name of the courier.",
+ "web_url": "Website of the courier.",
+ "required_fields": "Extra fields required to track a shipment with this courier, such as tracking_account_number or tracking_postal_code.",
+ "optional_fields": "Extra fields that some of this courier's tracking numbers need.",
+ "default_language": "Default language of tracking results from this courier.",
+ "support_languages": "Other languages this courier supports for tracking results.",
+ "service_from_country_regions": "ISO Alpha-3 codes of the countries or regions where the courier provides service.",
+ "credentials": "Shape of the authentication details this courier needs to create a carrier connection.",
+ },
+ },
+ "courier_connections": {
+ "description": "A carrier account you connected to AfterShip so it can pull tracking updates directly from that carrier. The stored carrier credentials are dropped during sync and never land in the warehouse.",
+ "docs_url": "https://www.aftership.com/docs/tracking/model/courier-connection",
+ "columns": {
+ "id": "Identifier AfterShip generated for the carrier connection.",
+ "courier_slug": "Unique courier code of the connected carrier.",
+ "created_at": "Date and time the connection was created, in UTC.",
+ "updated_at": "Date and time the connection was last updated, in UTC.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/settings.py
new file mode 100644
index 000000000000..8e4b1bfbe601
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/settings.py
@@ -0,0 +1,83 @@
+from dataclasses import dataclass, field
+from typing import Any, Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
+
+# AfterShip pins the Tracking API version in the URL path (https://api.aftership.com/tracking/<version>)
+# and ships a new dated version every six months. 2026-07 is the current generally available version
+# and the one the official SDK targets, so every path below is built against it.
+AFTERSHIP_2026_07 = "2026-07"
+SUPPORTED_VERSIONS = (AFTERSHIP_2026_07,)
+DEFAULT_VERSION = AFTERSHIP_2026_07
+
+AFTERSHIP_BASE_URL = "https://api.aftership.com/tracking"
+
+# Max page size accepted by both cursor-paginated list endpoints (default 100, max 200).
+PAGE_SIZE = 200
+
+
+@dataclass
+class AftershipEndpointConfig:
+ name: str
+ """Table name we expose to the user."""
+ path: str
+ """API path relative to the versioned base URL."""
+ data_selector: str
+ """JSON path to the row array inside AfterShip's `{"meta": ..., "data": ...}` envelope."""
+ primary_key: list[str]
+ cursor_paginated: bool = True
+ """Cursor pagination via `cursor` + `data.pagination.next_cursor`. False means a single page."""
+ incremental_params: dict[str, str] = field(default_factory=dict)
+ """Incremental field name -> the server-side "updated/created since" query param it maps to."""
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ partition_key: Optional[str] = None
+ """A STABLE field to partition on. Never an updated_at-style field, which would rewrite
+ partitions on every sync."""
+ extra_params: dict[str, Any] = field(default_factory=dict)
+ """Static query params sent on every request for the endpoint."""
+
+
+AFTERSHIP_ENDPOINTS: dict[str, AftershipEndpointConfig] = {
+ # GET /trackings is the only endpoint with server-side time filters. Both `created_at_min` and
+ # `updated_at_min` genuinely filter server-side, so either can back an incremental sync.
+ #
+ # Caveat worth knowing when reading synced data: AfterShip defaults `created_at_min` to 120 days
+ # ago and documents that it only stores 120 days of trackings, so a sync never reaches further
+ # back than that regardless of the sync type. We deliberately don't send a wider `created_at_min`
+ # of our own — there is no documented behaviour for a window beyond the retention period.
+ "trackings": AftershipEndpointConfig(
+ name="trackings",
+ path="/trackings",
+ data_selector="data.trackings",
+ primary_key=["id"],
+ incremental_params={"updated_at": "updated_at_min", "created_at": "created_at_min"},
+ incremental_fields=[incremental_field("updated_at"), incremental_field("created_at")],
+ partition_key="created_at",
+ extra_params={"limit": PAGE_SIZE},
+ ),
+ # GET /couriers returns the couriers activated on the account. It has no cursor and no time
+ # filter, so it is a single-page full refresh keyed on the courier slug.
+ "couriers": AftershipEndpointConfig(
+ name="couriers",
+ path="/couriers",
+ data_selector="data.couriers",
+ primary_key=["slug"],
+ cursor_paginated=False,
+ ),
+ # GET /courier-connections is cursor paginated but exposes no time filter, so it stays full
+ # refresh even though rows carry created_at/updated_at.
+ "courier_connections": AftershipEndpointConfig(
+ name="courier_connections",
+ path="/courier-connections",
+ data_selector="data.courier_connections",
+ primary_key=["id"],
+ extra_params={"limit": PAGE_SIZE},
+ ),
+}
+
+ENDPOINTS = tuple(AFTERSHIP_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in AFTERSHIP_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/source.py
index c1b9439385d2..485f0a837ab1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/source.py
@@ -1,13 +1,37 @@
-from typing import cast
+from typing import Optional, cast
from 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.sources.aftership.aftership import (
+ AftershipResumeConfig,
+ aftership_source,
+ check_access,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aftership.settings import (
+ AFTERSHIP_ENDPOINTS,
+ DEFAULT_VERSION,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ SUPPORTED_VERSIONS,
+)
+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 (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.aftership import (
AftershipSourceConfig,
)
@@ -15,7 +39,12 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AftershipSource(SimpleSource[AftershipSourceConfig]):
+class AftershipSource(ResumableSource[AftershipSourceConfig, AftershipResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://www.aftership.com/docs/tracking/quickstart/versioning"
+ supported_versions = SUPPORTED_VERSIONS
+ default_version = DEFAULT_VERSION
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.AFTERSHIP
@@ -26,7 +55,99 @@ class AftershipSource(SimpleSource[AftershipSourceConfig]):
name=SchemaExternalDataSourceType.AFTERSHIP,
category=DataWarehouseSourceCategory.E_COMMERCE,
label="AfterShip",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your AfterShip API key to pull your shipment tracking data into the PostHog Data warehouse.
+
+You can create a key in the AfterShip admin under **Settings → API keys**.
+
+AfterShip's tracking search only reaches back 120 days, so a sync covers your last 120 days of shipments.
+""",
+ docsUrl="https://posthog.com/docs/cdp/sources/aftership",
iconPath="/static/services/aftership.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ keywords=["shipping", "shipment tracking", "logistics", "couriers"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.aftership.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AftershipSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: AftershipSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ if schema_name is not None and schema_name not in AFTERSHIP_ENDPOINTS:
+ return False, f"Unknown AfterShip table '{schema_name}'"
+
+ is_valid, status = check_access(config.api_key, schema_name, self.resolve_api_version(api_version))
+ if is_valid:
+ return True, None
+
+ if status == 401:
+ return False, "Invalid AfterShip API key"
+ if status == 403:
+ # A key can legitimately be scoped to a subset of the API, so a forbidden probe only
+ # fails once the user asks for the specific table the key cannot read.
+ if schema_name is None:
+ return True, None
+ return False, f"Your AfterShip API key does not have permission to read '{schema_name}'"
+
+ return False, "Could not validate your AfterShip API key"
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Your AfterShip API key is invalid or expired. Please create a new key and reconnect.",
+ "403 Client Error": "Your AfterShip API key does not have the required permissions. Please check the key's scopes and try again.",
+ }
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AftershipResumeConfig]:
+ return ResumableSourceManager[AftershipResumeConfig](inputs, AftershipResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AftershipSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AftershipResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return aftership_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ incremental_field_name=inputs.incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ api_version=self.resolve_api_version(inputs.api_version),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/tests/test_aftership.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/tests/test_aftership.py
new file mode 100644
index 000000000000..8fe741ca0876
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/tests/test_aftership.py
@@ -0,0 +1,386 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, datetime, timedelta, timezone
+from typing import Any, Optional, cast
+
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+from requests import HTTPError, Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aftership.aftership import (
+ API_KEY_HEADER,
+ AftershipResumeConfig,
+ _to_aftership_datetime,
+ aftership_source,
+ check_access,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aftership.settings import (
+ DEFAULT_VERSION,
+ PAGE_SIZE,
+)
+
+BASE_URL = f"https://api.aftership.com/tracking/{DEFAULT_VERSION}"
+# RESTClient builds its session via make_tracked_session in the rest_client module.
+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+PROBE_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.aftership.aftership.validate_via_probe"
+
+
+def _response(
+ key: str,
+ items: Optional[list[dict[str, Any]]] = None,
+ *,
+ next_cursor: Optional[str] = None,
+ status_code: int = 200,
+) -> Response:
+ data: dict[str, Any] = {key: items or []}
+ if next_cursor is not None:
+ data["pagination"] = {"next_cursor": next_cursor, "has_next_page": True}
+ resp = Response()
+ resp.status_code = status_code
+ resp.url = f"{BASE_URL}/trackings"
+ resp._content = json.dumps({"meta": {"code": 200}, "data": data}).encode()
+ return resp
+
+
+def _make_manager(resume_state: Optional[AftershipResumeConfig] = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _wire(session: mock.MagicMock, responses: list[Response]) -> tuple[list[dict[str, Any]], list[str]]:
+ # ``request.params`` is one dict mutated in place across pages, so snapshot a copy while each
+ # request is prepared rather than reading it after the run.
+ session.headers = {}
+ param_snapshots: list[dict[str, Any]] = []
+ url_snapshots: list[str] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ param_snapshots.append(dict(request.params or {}))
+ url_snapshots.append(request.url)
+ return mock.MagicMock()
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return param_snapshots, url_snapshots
+
+
+def _rows(source_response: Any) -> list[dict[str, Any]]:
+ return [row for page in cast("Iterable[Any]", source_response.items()) for row in page]
+
+
+def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any) -> Any:
+ return aftership_source("key", endpoint, team_id=1, job_id="j", resumable_source_manager=manager, **kwargs)
+
+
+class TestToAftershipDatetime:
+ @parameterized.expand(
+ [
+ ("aware_utc", datetime(2026, 1, 15, 12, 30, 45, tzinfo=UTC), "2026-01-15T12:30:45+00:00"),
+ ("naive_treated_as_utc", datetime(2026, 1, 15, 12, 30, 45), "2026-01-15T12:30:45+00:00"),
+ (
+ "other_offset_converted",
+ datetime(2026, 1, 15, 20, 30, 45, tzinfo=timezone(timedelta(hours=8))),
+ "2026-01-15T12:30:45+00:00",
+ ),
+ (
+ "microseconds_dropped",
+ datetime(2026, 1, 15, 12, 30, 45, 123456, tzinfo=UTC),
+ "2026-01-15T12:30:45+00:00",
+ ),
+ ("zulu_string_rewritten", "2026-01-15T12:30:45Z", "2026-01-15T12:30:45+00:00"),
+ ("offset_string", "2026-01-15T20:30:45+08:00", "2026-01-15T12:30:45+00:00"),
+ ("garbage_string", "not-a-date", None),
+ ("non_datetime_type", 12345, None),
+ ]
+ )
+ def test_coercion(self, _name: str, value: Any, expected: Optional[str]) -> None:
+ # AfterShip validates these params against ^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}$,
+ # so a trailing Z or fractional seconds is a 400.
+ assert _to_aftership_datetime(value) == expected
+
+
+class TestPagination:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_follows_next_cursor_from_nested_envelope(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ params, urls = _wire(
+ session,
+ [
+ _response("trackings", [{"id": "1"}], next_cursor="cur-1"),
+ _response("trackings", [{"id": "2"}]),
+ ],
+ )
+
+ rows = _rows(_source("trackings", _make_manager()))
+
+ assert [r["id"] for r in rows] == ["1", "2"]
+ assert urls[0] == f"{BASE_URL}/trackings"
+ assert params[0] == {"limit": PAGE_SIZE}
+ assert params[1] == {"limit": PAGE_SIZE, "cursor": "cur-1"}
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_missing_cursor_ends_pagination_without_checkpoint(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response("trackings", [{"id": "a"}])])
+
+ manager = _make_manager()
+ rows = _rows(_source("trackings", manager))
+
+ assert [r["id"] for r in rows] == ["a"]
+ assert session.send.call_count == 1
+ manager.save_state.assert_not_called()
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_couriers_is_single_page_and_never_sends_a_cursor(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ # A next_cursor in the body must not restart pagination for an endpoint that has none.
+ params, urls = _wire(session, [_response("couriers", [{"slug": "usps"}], next_cursor="cur-1")])
+
+ rows = _rows(_source("couriers", _make_manager()))
+
+ assert [r["slug"] for r in rows] == ["usps"]
+ assert session.send.call_count == 1
+ assert urls[0] == f"{BASE_URL}/couriers"
+ assert params[0] == {}
+
+
+class TestIncrementalFiltering:
+ @parameterized.expand(
+ [
+ ("updated_at", "updated_at", "updated_at_min"),
+ ("created_at", "created_at", "created_at_min"),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_users_incremental_field_picks_the_server_side_filter(
+ self, _name: str, incremental_field_name: str, expected_param: str, MockSession: mock.MagicMock
+ ) -> None:
+ session = MockSession.return_value
+ params, _urls = _wire(session, [_response("trackings", [{"id": "1"}])])
+
+ _rows(
+ _source(
+ "trackings",
+ _make_manager(),
+ should_use_incremental_field=True,
+ incremental_field_name=incremental_field_name,
+ db_incremental_field_last_value=datetime(2026, 1, 15, 12, 0, 0, tzinfo=UTC),
+ )
+ )
+
+ assert params[0][expected_param] == "2026-01-15T12:00:00+00:00"
+ assert len([key for key in params[0] if key.endswith("_min")]) == 1
+
+ @parameterized.expand(
+ [
+ ("unmapped_field_on_incremental_endpoint", "trackings", "shipment_delivery_date"),
+ ("full_refresh_endpoint", "courier_connections", "updated_at"),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_no_filter_sent_when_the_field_has_no_server_side_param(
+ self, _name: str, endpoint: str, incremental_field_name: str, MockSession: mock.MagicMock
+ ) -> None:
+ session = MockSession.return_value
+ params, _urls = _wire(session, [_response(endpoint, [])])
+
+ _rows(
+ _source(
+ endpoint,
+ _make_manager(),
+ should_use_incremental_field=True,
+ incremental_field_name=incremental_field_name,
+ db_incremental_field_last_value=datetime(2026, 1, 15, tzinfo=UTC),
+ )
+ )
+
+ assert not [key for key in params[0] if key.endswith("_min")]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_filter_is_resent_on_every_page(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ params, _urls = _wire(
+ session,
+ [_response("trackings", [{"id": "1"}], next_cursor="cur-1"), _response("trackings", [{"id": "2"}])],
+ )
+
+ _rows(
+ _source(
+ "trackings",
+ _make_manager(),
+ should_use_incremental_field=True,
+ incremental_field_name="updated_at",
+ db_incremental_field_last_value=datetime(2026, 1, 15, tzinfo=UTC),
+ )
+ )
+
+ assert all(page["updated_at_min"] == "2026-01-15T00:00:00+00:00" for page in params)
+
+
+class TestResume:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_saves_cursor_and_window_after_yielding_each_page(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [_response("trackings", [{"id": "1"}], next_cursor="cur-1"), _response("trackings", [{"id": "2"}])],
+ )
+
+ manager = _make_manager()
+ _rows(
+ _source(
+ "trackings",
+ manager,
+ should_use_incremental_field=True,
+ incremental_field_name="updated_at",
+ db_incremental_field_last_value=datetime(2026, 1, 15, tzinfo=UTC),
+ )
+ )
+
+ manager.save_state.assert_called_once_with(
+ AftershipResumeConfig(cursor="cur-1", incremental_start="2026-01-15T00:00:00+00:00")
+ )
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_from_saved_cursor_and_reuses_the_saved_window(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ params, _urls = _wire(session, [_response("trackings", [{"id": "9"}])])
+
+ manager = _make_manager(AftershipResumeConfig(cursor="cur-8", incremental_start="2026-01-01T00:00:00+00:00"))
+ rows = _rows(
+ _source(
+ "trackings",
+ manager,
+ should_use_incremental_field=True,
+ incremental_field_name="updated_at",
+ # The watermark advanced from committed batches; narrowing the window mid-walk
+ # would leave the saved cursor pointing outside the filtered result set.
+ db_incremental_field_last_value=datetime(2026, 2, 1, tzinfo=UTC),
+ )
+ )
+
+ assert [r["id"] for r in rows] == ["9"]
+ assert params[0]["cursor"] == "cur-8"
+ assert params[0]["updated_at_min"] == "2026-01-01T00:00:00+00:00"
+
+
+class TestSourceResponse:
+ @parameterized.expand(
+ [
+ ("trackings", "trackings", ["id"], ["created_at"]),
+ ("couriers", "couriers", ["slug"], None),
+ ("courier_connections", "courier_connections", ["id"], None),
+ ]
+ )
+ def test_primary_keys_and_partitioning(
+ self, _name: str, endpoint: str, expected_keys: list[str], expected_partition_keys: Optional[list[str]]
+ ) -> None:
+ response = _source(endpoint, _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == expected_keys
+ assert response.partition_keys == expected_partition_keys
+ # AfterShip documents no ordering and offers no sort param, so the watermark is only
+ # committed once at the end of the sync.
+ assert response.sort_mode == "desc"
+
+
+class TestRequestShape:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_api_key_is_sent_in_the_as_api_key_header(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ session.headers = {}
+ prepared: list[Any] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ fake = mock.MagicMock()
+ fake.headers = {}
+ fake.url = request.url
+ # `auth` is a callable applied to the prepared request by the framework.
+ prepared.append(request.auth(fake) if request.auth else fake)
+ return fake
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = [_response("trackings", [])]
+
+ _rows(_source("trackings", _make_manager()))
+
+ # The legacy `aftership-api-key` header stopped working at API version 2023-10.
+ assert prepared[0].headers[API_KEY_HEADER] == "key"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_api_version_is_a_path_segment(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ _params, urls = _wire(session, [_response("trackings", [])])
+
+ _rows(_source("trackings", _make_manager(), api_version="2026-01"))
+
+ assert urls[0] == "https://api.aftership.com/tracking/2026-01/trackings"
+
+ @parameterized.expand([(401,), (403,)])
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_auth_errors_raise_a_matchable_http_error(self, status_code: int, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response("trackings", [], status_code=status_code)])
+
+ with pytest.raises(HTTPError) as exc:
+ _rows(_source("trackings", _make_manager()))
+ assert f"{status_code} Client Error" in str(exc.value)
+
+
+class TestCourierConnectionRedaction:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_carrier_credentials_never_reach_the_warehouse(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response(
+ "courier_connections",
+ [
+ {
+ "id": "conn-1",
+ "courier_slug": "dhl-api",
+ "credentials": {"api_key": "carrier-secret", "password": "hunter2"},
+ "created_at": "2026-01-01T00:00:00+00:00",
+ }
+ ],
+ )
+ ],
+ )
+
+ rows = _rows(_source("courier_connections", _make_manager()))
+
+ assert rows == [{"id": "conn-1", "courier_slug": "dhl-api", "created_at": "2026-01-01T00:00:00+00:00"}]
+
+
+class TestCheckAccess:
+ @parameterized.expand(
+ [
+ ("token_only", None, f"{BASE_URL}/trackings?limit=1"),
+ ("cursor_endpoint", "courier_connections", f"{BASE_URL}/courier-connections?limit=1"),
+ ("single_page_endpoint", "couriers", f"{BASE_URL}/couriers"),
+ ]
+ )
+ @mock.patch(PROBE_PATCH)
+ def test_probe_url_per_schema(
+ self, _name: str, schema_name: Optional[str], expected_url: str, mock_probe: mock.MagicMock
+ ) -> None:
+ mock_probe.return_value = (True, 200)
+
+ assert check_access("key", schema_name) == (True, 200)
+ assert mock_probe.call_args.args[1] == expected_url
+
+ @mock.patch(PROBE_PATCH)
+ def test_probe_does_not_follow_redirects(self, mock_probe: mock.MagicMock) -> None:
+ mock_probe.return_value = (True, 200)
+
+ check_access("key")
+
+ # The key rides a custom header, which requests would replay to a redirect target.
+ assert mock_probe.call_args.kwargs["allow_redirects"] is False
+ assert mock_probe.call_args.kwargs["headers"] == {API_KEY_HEADER: "key"}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/tests/test_aftership_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/tests/test_aftership_source.py
new file mode 100644
index 000000000000..0ac069c7a1ad
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/tests/test_aftership_source.py
@@ -0,0 +1,192 @@
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aftership.aftership import AftershipResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.aftership.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aftership.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.aftership.source import AftershipSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.aftership import (
+ AftershipSourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+CHECK_ACCESS_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.aftership.source.check_access"
+AFTERSHIP_SOURCE_PATH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.aftership.source.aftership_source"
+)
+
+
+class TestAftershipSource:
+ def setup_method(self) -> None:
+ self.source = AftershipSource()
+ self.team_id = 123
+ self.config = AftershipSourceConfig(api_key="as-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.AFTERSHIP
+
+ def test_version_pin_matches_the_path_the_code_calls(self) -> None:
+ assert self.source.supported_versions == ("2026-07",)
+ assert self.source.default_version == "2026-07"
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Aftership"
+ assert config.label == "AfterShip"
+ assert config.category == DataWarehouseSourceCategory.E_COMMERCE
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # A finished source must stay visible in the wizard.
+ assert not config.unreleasedSource
+
+ def test_api_key_field_is_a_required_secret(self) -> None:
+ config = self.source.get_source_config
+ fields = [f for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert [f.name for f in fields] == ["api_key"]
+ assert fields[0].type == SourceFieldInputConfigType.PASSWORD
+ assert fields[0].secret is True
+ assert fields[0].required is True
+
+ def test_get_schemas_marks_only_trackings_incremental(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ by_name = {s.name: s for s in schemas}
+ # Only GET /trackings has server-side created/updated time filters.
+ assert by_name["trackings"].supports_incremental is True
+ assert [f["field"] for f in by_name["trackings"].incremental_fields] == ["updated_at", "created_at"]
+ for name in ("couriers", "courier_connections"):
+ assert by_name[name].supports_incremental is False
+ assert by_name[name].incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["couriers", "nope"])
+ assert [s.name for s in schemas] == ["couriers"]
+
+ def test_canonical_descriptions_cover_every_table(self) -> None:
+ # Keys must match the schema names, or the enrichment silently falls back to the LLM.
+ assert set(self.source.get_canonical_descriptions()) == set(ENDPOINTS)
+ assert set(CANONICAL_DESCRIPTIONS) == set(ENDPOINTS)
+
+ def test_courier_connection_credentials_are_not_documented_as_a_column(self) -> None:
+ # The sync drops the column; documenting it would advertise a table that never exists.
+ assert "credentials" not in CANONICAL_DESCRIPTIONS["courier_connections"]["columns"]
+
+ @parameterized.expand(
+ [
+ ("ok", True, 200, None, True, None),
+ ("bad_key", False, 401, None, False, "Invalid AfterShip API key"),
+ ("scoped_key_at_create", False, 403, None, True, None),
+ (
+ "scoped_key_for_table",
+ False,
+ 403,
+ "trackings",
+ False,
+ "Your AfterShip API key does not have permission to read 'trackings'",
+ ),
+ ("unreachable", False, None, None, False, "Could not validate your AfterShip API key"),
+ ]
+ )
+ @mock.patch(CHECK_ACCESS_PATH)
+ def test_validate_credentials(
+ self,
+ _name: str,
+ probe_valid: bool,
+ status: int | None,
+ schema_name: str | None,
+ expected_valid: bool,
+ expected_message: str | None,
+ mock_check: mock.MagicMock,
+ ) -> None:
+ mock_check.return_value = (probe_valid, status)
+ is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
+ assert is_valid is expected_valid
+ assert message == expected_message
+
+ @mock.patch(CHECK_ACCESS_PATH)
+ def test_validate_credentials_rejects_unknown_table_without_probing(self, mock_check: mock.MagicMock) -> None:
+ is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name="not_a_table")
+ assert is_valid is False
+ assert message == "Unknown AfterShip table 'not_a_table'"
+ mock_check.assert_not_called()
+
+ @mock.patch(CHECK_ACCESS_PATH)
+ def test_validate_credentials_probes_under_the_resolved_version(self, mock_check: mock.MagicMock) -> None:
+ mock_check.return_value = (True, 200)
+ self.source.validate_credentials(self.config, self.team_id, schema_name="trackings", api_version=None)
+ assert mock_check.call_args.args == ("as-key", "trackings", "2026-07")
+
+ @parameterized.expand(
+ [
+ ("bad_key", "401 Client Error: Unauthorized for url: https://api.aftership.com/tracking/2026-07/trackings"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.aftership.com/tracking/2026-07/couriers"),
+ ]
+ )
+ def test_non_retryable_errors_match_credential_failures(self, _name: str, observed_error: str) -> None:
+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())
+
+ @parameterized.expand(
+ [
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.aftership.com/tracking"),
+ ("server_error", "503 Server Error: Service Unavailable for url: https://api.aftership.com/tracking"),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient_failures(self, _name: str, unrelated_error: str) -> None:
+ assert not any(key in unrelated_error for key in self.source.get_non_retryable_errors())
+
+ 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 AftershipResumeConfig
+
+ @parameterized.expand([("unpinned", None, "2026-07"), ("pinned", "2026-07", "2026-07")])
+ @mock.patch(AFTERSHIP_SOURCE_PATH)
+ def test_source_for_pipeline_plumbs_arguments(
+ self, _name: str, pin: str | None, expected_version: str, mock_source: mock.MagicMock
+ ) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "trackings"
+ inputs.team_id = 123
+ inputs.job_id = "job-1"
+ inputs.should_use_incremental_field = True
+ inputs.incremental_field = "updated_at"
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00+00:00"
+ inputs.api_version = pin
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "as-key"
+ assert kwargs["endpoint"] == "trackings"
+ assert kwargs["team_id"] == 123
+ assert kwargs["job_id"] == "job-1"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ # The user's chosen cursor column decides which server-side filter is sent.
+ assert kwargs["incremental_field_name"] == "updated_at"
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00+00:00"
+ assert kwargs["api_version"] == expected_version
+
+ @mock.patch(AFTERSHIP_SOURCE_PATH)
+ def test_source_for_pipeline_drops_the_watermark_on_full_refresh(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "couriers"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00+00:00"
+ inputs.api_version = None
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/aftership.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/aftership.py
index 3b90ce81a650..791ae2654a31 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/aftership.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/aftership.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class AftershipSourceConfig(config.Config):
- pass
+ api_key: str