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(warehouse_sources): support Ably API version 2 (#74167)

Tom Owers6fedbb0d2a20
diff --git a/products/warehouse_sources/backend/migrations/0108_pin_zendesk_sunshine_v1.py b/products/warehouse_sources/backend/migrations/0108_pin_zendesk_sunshine_v1.py
new file mode 100644
index 000000000000..61ffc7b4d7cb
--- /dev/null
+++ b/products/warehouse_sources/backend/migrations/0108_pin_zendesk_sunshine_v1.py
@@ -0,0 +1,36 @@
+from django.db import migrations
+
+# Zendesk Sunshine now defaults to v2 (the current custom objects API). v2 exposes a different
+# table set from the legacy v1 Sunshine API (no relationship/policy tables, records reshaped under
+# `custom_object_fields`), so a source moving from v1 to v2 is a lossy transition, not an in-place
+# `api_version` flip: the next discovery cycle would orphan the v1 tables and start the v2 ones
+# fresh. That migration is therefore intentionally NOT scripted — the manual path is documented in
+# the PR and run per-source by a human.
+#
+# This migration only backs out the NULL cohort from the default flip. A NULL `api_version` resolves
+# to `default_version`, which just moved v1 -> v2, so any Sunshine source created without an explicit
+# pin (direct-ORM/seeder paths that bypass the API's create-time stamping) would silently jump onto
+# v2's divergent table set. Pinning those rows to v1 keeps them on the version they were syncing.
+ZENDESK_SUNSHINE_SOURCE_TYPE = "ZendeskSunshine"
+V1_VERSION = "v1"
+
+
+def pin_zendesk_sunshine_v1(apps, schema_editor):
+ ExternalDataSource = apps.get_model("warehouse_sources", "ExternalDataSource")
+
+ # Source-level pins only. Filtering on NULL keeps this idempotent — a re-run matches nothing,
+ # and rows already carrying an explicit pin (v1 or v2) are left as their owner set them.
+ # Schema-level overrides (`ExternalDataSchema.api_version`) are customer-managed and untouched.
+ ExternalDataSource.objects.filter(source_type=ZENDESK_SUNSHINE_SOURCE_TYPE, api_version__isnull=True).update(
+ api_version=V1_VERSION
+ )
+
+
+class Migration(migrations.Migration):
+ dependencies = [("warehouse_sources", "0107_repin_marketstack_api_version_v2")]
+
+ operations = [
+ # Reverse is a no-op: once pinned, a v1 row is indistinguishable from one natively stamped v1,
+ # so re-nulling would wrongly clear legitimate explicit pins too.
+ migrations.RunPython(pin_zendesk_sunshine_v1, migrations.RunPython.noop, elidable=False),
+ ]
diff --git a/products/warehouse_sources/backend/migrations/0109_repin_ably_api_version_v2.py b/products/warehouse_sources/backend/migrations/0109_repin_ably_api_version_v2.py
new file mode 100644
index 000000000000..f773faa21560
--- /dev/null
+++ b/products/warehouse_sources/backend/migrations/0109_repin_ably_api_version_v2.py
@@ -0,0 +1,36 @@
+from django.db import migrations
+
+# Ably sunset REST protocol v1 on 2025-11-01; the source now defaults new instances to "2" and
+# sends `X-Ably-Version: 2` explicitly. This repins existing source-level pins from the legacy
+# unversioned label ("v1") to "2" so they stop tracking Ably's mutable default and stay on
+# protocol 2. The `/stats` endpoint and its response shape are identical across the two protocol
+# versions and the source auto-infers its schema, so no data/schema transform is needed — only
+# the pin moves.
+ABLY_SOURCE_TYPE = "Ably"
+OLD_VERSION = "v1"
+NEW_VERSION = "2"
+
+
+def repin_ably_v1_to_v2(apps, schema_editor):
+ ExternalDataSource = apps.get_model("warehouse_sources", "ExternalDataSource")
+
+ # Only the source-level pin is touched. Schema-level `ExternalDataSchema.api_version`
+ # overrides are user-managed (a customer intentionally pinned that schema) and are left
+ # alone — the schema-level deprecation warning prompts the user to migrate those.
+ #
+ # NULL pins already resolve to the source's `default_version` (now "2"), so they need no
+ # update. Matching only `api_version="v1"` keeps this idempotent: a second run matches nothing.
+ ExternalDataSource.objects.filter(source_type=ABLY_SOURCE_TYPE, api_version=OLD_VERSION).update(
+ api_version=NEW_VERSION
+ )
+
+
+class Migration(migrations.Migration):
+ dependencies = [("warehouse_sources", "0108_pin_zendesk_sunshine_v1")]
+
+ operations = [
+ # Reverse is a no-op: once repinned, these rows are indistinguishable from natively-created
+ # ones, so a blanket downgrade would clobber legitimate "2" pins and move customers back
+ # onto the sunset v1 protocol.
+ migrations.RunPython(repin_ably_v1_to_v2, migrations.RunPython.noop, elidable=False),
+ ]
diff --git a/products/warehouse_sources/backend/migrations/0110_pin_shipstation_null_api_version_to_v1.py b/products/warehouse_sources/backend/migrations/0110_pin_shipstation_null_api_version_to_v1.py
new file mode 100644
index 000000000000..19f455e57bc8
--- /dev/null
+++ b/products/warehouse_sources/backend/migrations/0110_pin_shipstation_null_api_version_to_v1.py
@@ -0,0 +1,35 @@
+from django.db import migrations
+
+# ShipStation's default vendor API version flips to "v2" (the ShipEngine-based API) in the same
+# change that adds this migration. Existing ShipStation rows were pinned "v1" by migration 0075, but
+# a row created via a direct-ORM path that bypasses creation-time stamping could still have a NULL
+# `api_version`, and a NULL pin resolves to `default_version` — so it would silently follow the flip
+# to v2. v2 needs a different credential (a single API-Key the customer must generate) and exposes a
+# different table set, so an unpinned v1 source moved to v2 would break. Pin any such rows back to
+# "v1" so the flip only affects newly created sources.
+#
+# This does NOT repin v1 customers to v2: that migration is not safe to script (v2 credentials can't
+# be derived from v1's, and the resource set differs), so it is documented as a manual path in the PR.
+SHIPSTATION_SOURCE_TYPE = "ShipStation"
+SHIPSTATION_V1 = "v1"
+
+
+def pin_null_shipstation_rows_to_v1(apps, schema_editor):
+ ExternalDataSource = apps.get_model("warehouse_sources", "ExternalDataSource")
+
+ # The isnull guard keeps it idempotent (safe under retries) and never overwrites a concrete pin.
+ ExternalDataSource.objects.filter(source_type=SHIPSTATION_SOURCE_TYPE, api_version__isnull=True).update(
+ api_version=SHIPSTATION_V1
+ )
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("warehouse_sources", "0109_repin_ably_api_version_v2"),
+ ]
+
+ operations = [
+ # Reverse is a no-op: after this runs, the pinned rows are indistinguishable from natively
+ # created v1 sources, so nulling "v1" pins would also destroy legitimate creation-time stamps.
+ migrations.RunPython(pin_null_shipstation_rows_to_v1, migrations.RunPython.noop, elidable=True),
+ ]
diff --git a/products/warehouse_sources/backend/migrations/0111_repin_zonka_feedback_api_version.py b/products/warehouse_sources/backend/migrations/0111_repin_zonka_feedback_api_version.py
new file mode 100644
index 000000000000..837961fdd822
--- /dev/null
+++ b/products/warehouse_sources/backend/migrations/0111_repin_zonka_feedback_api_version.py
@@ -0,0 +1,31 @@
+from django.db import migrations
+
+# Zonka deprecated its older API generation (vendor "API 2.0") in favor of the current v2.1 API. The
+# source now defaults new instances to v2.1, and our legacy `v1` label already targets the current
+# host (apis.zonkafeedback.com) — there is no per-version request dispatch, so v1 and v2.1 resolve to
+# identical requests here. The repin is a pure pin move with no data/schema transform.
+ZONKA_FEEDBACK_SOURCE_TYPE = "ZonkaFeedback"
+DEPRECATED_VERSION = "v1"
+TARGET_VERSION = "v2.1"
+
+
+def repin_zonka_feedback_api_version(apps, schema_editor):
+ ExternalDataSource = apps.get_model("warehouse_sources", "ExternalDataSource")
+
+ # Only touch source-level pins still on the deprecated version. NULL pins already resolve to the
+ # source's `default_version` (now v2.1), so they need no update. Filtering on the exact old value
+ # keeps this idempotent — a re-run matches nothing. Schema-level overrides
+ # (`ExternalDataSchema.api_version`) are intentionally customer-pinned and are left untouched.
+ ExternalDataSource.objects.filter(source_type=ZONKA_FEEDBACK_SOURCE_TYPE, api_version=DEPRECATED_VERSION).update(
+ api_version=TARGET_VERSION
+ )
+
+
+class Migration(migrations.Migration):
+ dependencies = [("warehouse_sources", "0110_pin_shipstation_null_api_version_to_v1")]
+
+ operations = [
+ # Reverse is a no-op: once repinned, these rows are indistinguishable from natively-created
+ # ones, so a blanket downgrade would clobber legitimate v2.1 pins.
+ migrations.RunPython(repin_zonka_feedback_api_version, migrations.RunPython.noop, elidable=False),
+ ]
diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txt
index 7f026c73533f..8149a0ed7a69 100644
--- a/products/warehouse_sources/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0107_repin_marketstack_api_version_v2
+0111_repin_zonka_feedback_api_version
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/ably.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/ably.py
index 1aa8c74d5007..1ae01a6f62c7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/ably.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/ably.py
@@ -18,6 +18,26 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+# Ably REST protocol version, sent via the `X-Ably-Version` header. The legacy label
+# (`UNVERSIONED_API_VERSION`, "v1") predates this source declaring a version and maps to *no*
+# header — the exact request the source has always made, which Ably serves under its current
+# default. Ably protocol 1 was sunset on 2025-11-01, so sending an explicit `X-Ably-Version: 1`
+# would only start failing otherwise-working syncs; the deprecation banner and repin migration
+# move those rows to "2" instead. The "2" pin sends the header so the source stays on protocol 2
+# rather than silently tracking whatever Ably later makes its default.
+ABLY_VERSION_2 = "2"
+
+_VERSION_HEADER: dict[str, str] = {
+ ABLY_VERSION_2: ABLY_VERSION_2,
+}
+
+
+def version_header(api_version: str) -> dict[str, str]:
+ """`X-Ably-Version` header for a resolved version pin. Versions absent from the map (the
+ legacy unversioned label) send no header — see the note on `_VERSION_HEADER`."""
+ value = _VERSION_HEADER.get(api_version)
+ return {"X-Ably-Version": value} if value else {}
+
@dataclasses.dataclass
class AblyResumeConfig:
@@ -107,6 +127,7 @@ def ably_source(
job_id: str,
resumable_source_manager: ResumableSourceManager[AblyResumeConfig],
db_incremental_field_last_value: Optional[Any],
+ api_version: str,
should_use_incremental_field: bool = False,
):
username, password = split_api_key(api_key)
@@ -114,6 +135,7 @@ def ably_source(
config: RESTAPIConfig = {
"client": {
"base_url": BASE_URL,
+ "headers": version_header(api_version),
"auth": {
"type": "http_basic",
"username": username,
@@ -158,12 +180,12 @@ def ably_source(
)
-def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+def validate_credentials(api_key: str, api_version: str) -> tuple[bool, str | None]:
username, password = split_api_key(api_key)
if not password:
return False, "Ably API key is malformed — expected the format `{app-id}.{key-id}:{key-secret}`."
- session = make_tracked_session(redact_values=(password, api_key))
+ session = make_tracked_session(headers=version_header(api_version), redact_values=(password, api_key))
try:
response = session.get(
f"{BASE_URL}/stats",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/source.py
index 8fd66bbbc43e..7c7b3a1d3a64 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/source.py
@@ -1,3 +1,4 @@
+from datetime import date
from typing import Optional, cast
from posthog.schema import (
@@ -16,6 +17,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
SourceResponse,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.ably.ably import (
+ ABLY_VERSION_2,
AblyResumeConfig,
ably_source,
validate_credentials as validate_ably_credentials,
@@ -28,7 +30,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.ably.setti
PRIMARY_KEYS,
STATS_UNITS,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ UNVERSIONED_API_VERSION,
+ FieldType,
+ ResumableSource,
+ VersionDeprecation,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
)
@@ -47,6 +54,10 @@ class AblySource(ResumableSource[AblySourceConfig, AblyResumeConfig]):
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
api_docs_url = "https://ably.com/docs/api/rest-api"
+ supported_versions = (UNVERSIONED_API_VERSION, ABLY_VERSION_2)
+ default_version = ABLY_VERSION_2
+ deprecated_versions = (VersionDeprecation(version=UNVERSIONED_API_VERSION, sunset_at=date(2025, 11, 1)),)
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ABLY
@@ -73,12 +84,16 @@ class AblySource(ResumableSource[AblySourceConfig, AblyResumeConfig]):
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
+ # The endpoint catalog (`/stats`) and its shape are identical across Ably protocol
+ # versions, so discovery is version-independent — the pin is consumed at the request layer.
return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
def validate_credentials(
self, config: AblySourceConfig, team_id: int, schema_name: Optional[str] = None, api_version: str | None = None
) -> tuple[bool, str | None]:
- return validate_ably_credentials(config.api_key)
+ # Pre-creation calls pass no pin and resolve to `default_version` (what new rows are
+ # stamped with); a pinned source revalidates under its own `X-Ably-Version` header.
+ return validate_ably_credentials(config.api_key, self.resolve_api_version(api_version))
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AblyResumeConfig]:
return ResumableSourceManager[AblyResumeConfig](inputs, AblyResumeConfig)
@@ -95,6 +110,7 @@ class AblySource(ResumableSource[AblySourceConfig, AblyResumeConfig]):
team_id=inputs.team_id,
job_id=inputs.job_id,
resumable_source_manager=resumable_source_manager,
+ api_version=self.resolve_api_version(inputs.api_version),
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
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably.py
index 2c3ebc54d0ed..21d537e88e0d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably.py
@@ -8,6 +8,7 @@ from requests import Response
from requests.exceptions import ConnectionError as RequestsConnectionError
from products.warehouse_sources.backend.temporal.data_imports.sources.ably.ably import (
+ ABLY_VERSION_2,
AblyResumeConfig,
_add_interval_start,
_parse_interval_start,
@@ -15,10 +16,27 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.ably.ably
get_resource,
split_api_key,
validate_credentials,
+ version_header,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import UNVERSIONED_API_VERSION
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+class TestVersionHeader:
+ @pytest.mark.parametrize(
+ ("api_version", "expected"),
+ [
+ # "2" pins the source to protocol 2 explicitly. The legacy unversioned label sends no
+ # header — Ably protocol 1 is sunset, so `X-Ably-Version: 1` would only fail; the empty
+ # header keeps those rows on Ably's current default until the repin migration moves them.
+ (ABLY_VERSION_2, {"X-Ably-Version": "2"}),
+ (UNVERSIONED_API_VERSION, {}),
+ ],
+ )
+ def test_maps_version_to_header(self, api_version: str, expected: dict[str, str]) -> None:
+ assert version_header(api_version) == expected
+
+
class TestSplitApiKey:
@pytest.mark.parametrize(
("api_key", "expected_username", "expected_password"),
@@ -138,6 +156,7 @@ class TestAblySourceResumeBehavior:
job_id="test_job",
resumable_source_manager=manager,
db_incremental_field_last_value=None,
+ api_version=ABLY_VERSION_2,
should_use_incremental_field=should_use_incremental_field,
)
pages = list(resource)
@@ -230,6 +249,7 @@ class TestAblyHostPinningAndRedirects:
job_id="test_job",
resumable_source_manager=manager,
db_incremental_field_last_value=None,
+ api_version=ABLY_VERSION_2,
)
list(resource)
@@ -262,7 +282,7 @@ class TestValidateCredentials:
with patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.ably.ably.make_tracked_session"
) as mock_make_session:
- ok, error = validate_credentials("no-colon-here")
+ ok, error = validate_credentials("no-colon-here", ABLY_VERSION_2)
assert ok is False
assert error is not None and "malformed" in error.lower()
@@ -282,8 +302,10 @@ class TestValidateCredentials:
"products.warehouse_sources.backend.temporal.data_imports.sources.ably.ably.make_tracked_session"
) as mock_make_session:
mock_make_session.return_value.get.return_value = MagicMock(status_code=status_code)
- ok, error = validate_credentials("app.key:secret")
+ ok, error = validate_credentials("app.key:secret", ABLY_VERSION_2)
+ # The probe validates under the pinned version's header, not Ably's default.
+ assert mock_make_session.call_args.kwargs["headers"] == {"X-Ably-Version": "2"}
assert ok is expect_ok
if not expect_ok:
assert error is not None
@@ -293,7 +315,7 @@ class TestValidateCredentials:
"products.warehouse_sources.backend.temporal.data_imports.sources.ably.ably.make_tracked_session"
) as mock_make_session:
mock_make_session.return_value.get.side_effect = RequestsConnectionError("boom")
- ok, error = validate_credentials("app.key:secret")
+ ok, error = validate_credentials("app.key:secret", ABLY_VERSION_2)
assert ok is False
assert error == "boom"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably_source.py
index 1774c9aa0ec9..bb80c733c33c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably_source.py
@@ -86,6 +86,7 @@ class TestAblySource:
team_id=self.team_id,
job_id="job-1",
schema_name="Stats",
+ api_version="2",
should_use_incremental_field=True,
db_incremental_field_last_value=1700000000000,
)
@@ -106,6 +107,7 @@ class TestAblySource:
team_id=self.team_id,
job_id="job-1",
resumable_source_manager=manager,
+ api_version="2",
should_use_incremental_field=True,
db_incremental_field_last_value=1700000000000,
)
@@ -116,6 +118,39 @@ class TestAblySource:
assert response.partition_keys == ["interval_start"]
assert response.sort_mode == "asc"
+ @pytest.mark.parametrize(
+ ("pinned", "resolved"),
+ [
+ # No pin falls back to default_version ("2"); an explicit pin is honored verbatim,
+ # including the legacy label so a deprecated source keeps its own request path.
+ (None, "2"),
+ ("v1", "v1"),
+ ("2", "2"),
+ ],
+ )
+ def test_source_for_pipeline_resolves_and_threads_api_version(self, pinned, resolved):
+ config = AblySourceConfig(api_key="app.key:secret", unit="hour")
+ inputs = MagicMock(
+ team_id=self.team_id,
+ job_id="job-1",
+ schema_name="Stats",
+ api_version=pinned,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ manager = MagicMock(spec=ResumableSourceManager)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.ably.source.ably_source"
+ ) as mock_ably_source:
+ mock_resource = MagicMock(column_hints=None)
+ mock_resource.name = "Stats"
+ mock_ably_source.return_value = mock_resource
+
+ self.source.source_for_pipeline(config, manager, inputs)
+
+ assert mock_ably_source.call_args.kwargs["api_version"] == resolved
+
def test_source_for_pipeline_ignores_last_value_on_full_refresh(self):
config = AblySourceConfig(api_key="app.key:secret", unit="hour")
inputs = MagicMock(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/shipstation.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/shipstation.py
index 4f1ee59410f7..8835d70d51da 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/shipstation.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/shipstation.py
@@ -7,4 +7,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class ShipStationSourceConfig(config.Config):
api_key: str
- api_secret: str
+ api_secret: str | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shipstation/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shipstation/settings.py
index e010d0ed67dd..f37a5b2f843c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shipstation/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shipstation/settings.py
@@ -3,6 +3,16 @@ from typing import Optional
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+# ShipStation runs two live vendor APIs. v1 is the original ssapi.shipstation.com API (HTTP Basic
+# with an API key + secret, US Pacific DateTimes). v2 is the ShipStation API v2 (ShipEngine-based)
+# at api.shipstation.com/v2 — a single API-Key header, ISO 8601 UTC timestamps, and an entirely
+# different resource model (shipments/labels/carriers/…), not a reskin of v1. The vendor has
+# deprecated v1; new sources start on v2.
+SHIPSTATION_V1 = "v1"
+SHIPSTATION_V2 = "v2"
+SHIPSTATION_SUPPORTED_VERSIONS = (SHIPSTATION_V1, SHIPSTATION_V2)
+SHIPSTATION_DEFAULT_VERSION = SHIPSTATION_V2
+
@dataclass
class ShipStationEndpointConfig:
@@ -122,3 +132,128 @@ ENDPOINTS = tuple(SHIPSTATION_ENDPOINTS.keys())
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
name: config.incremental_fields for name, config in SHIPSTATION_ENDPOINTS.items() if config.incremental_fields
}
+
+
+def _v2_datetime_incremental_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+# ShipStation API v2 (ShipEngine) — https://docs.shipstation.com / OpenAPI at
+# https://shipengine.github.io/shipengine-openapi/. Base https://api.shipstation.com/v2. List
+# responses wrap rows under the plural resource key and (for the paginated ones) carry
+# `page`/`pages`/`total`/`links`; timestamps are ISO 8601 UTC and the date filters are
+# `created_at_start` / `modified_at_start`. Carriers, warehouses and tags are small reference
+# lists with no pagination envelope or date filter, so they full-refresh.
+SHIPSTATION_V2_ENDPOINTS: dict[str, ShipStationEndpointConfig] = {
+ "shipments": ShipStationEndpointConfig(
+ name="shipments",
+ path="/shipments",
+ primary_key="shipment_id",
+ data_key="shipments",
+ partition_key="created_at",
+ incremental_params={
+ "modified_at": "modified_at_start",
+ "created_at": "created_at_start",
+ },
+ sort_by={
+ "modified_at": "modified_at",
+ "created_at": "created_at",
+ },
+ incremental_fields=[
+ _v2_datetime_incremental_field("modified_at"),
+ _v2_datetime_incremental_field("created_at"),
+ ],
+ ),
+ "labels": ShipStationEndpointConfig(
+ name="labels",
+ path="/labels",
+ primary_key="label_id",
+ data_key="labels",
+ partition_key="created_at",
+ incremental_params={"created_at": "created_at_start"},
+ sort_by={"created_at": "created_at"},
+ incremental_fields=[
+ _v2_datetime_incremental_field("created_at"),
+ ],
+ ),
+ "batches": ShipStationEndpointConfig(
+ name="batches",
+ path="/batches",
+ primary_key="batch_id",
+ data_key="batches",
+ partition_key="created_at",
+ incremental_params={"created_at": "created_at_start"},
+ sort_by={"created_at": "created_at"},
+ incremental_fields=[
+ _v2_datetime_incremental_field("created_at"),
+ ],
+ ),
+ "manifests": ShipStationEndpointConfig(
+ name="manifests",
+ path="/manifests",
+ primary_key="manifest_id",
+ data_key="manifests",
+ partition_key="created_at",
+ # `/manifests` filters on `created_at_start` but documents no sortBy enum — the window
+ # plus merge-on-pk keeps incremental correct (same shape as v1 fulfillments).
+ incremental_params={"created_at": "created_at_start"},
+ incremental_fields=[
+ _v2_datetime_incremental_field("created_at"),
+ ],
+ ),
+ "pickups": ShipStationEndpointConfig(
+ name="pickups",
+ path="/pickups",
+ primary_key="pickup_id",
+ data_key="pickups",
+ partition_key="created_at",
+ incremental_params={"created_at": "created_at_start"},
+ incremental_fields=[
+ _v2_datetime_incremental_field("created_at"),
+ ],
+ ),
+ "carriers": ShipStationEndpointConfig(
+ name="carriers",
+ path="/carriers",
+ primary_key="carrier_id",
+ data_key="carriers",
+ paginated=False,
+ ),
+ "warehouses": ShipStationEndpointConfig(
+ name="warehouses",
+ path="/warehouses",
+ primary_key="warehouse_id",
+ data_key="warehouses",
+ paginated=False,
+ ),
+ "tags": ShipStationEndpointConfig(
+ name="tags",
+ path="/tags",
+ primary_key="tag_id",
+ data_key="tags",
+ paginated=False,
+ ),
+}
+
+V2_ENDPOINTS = tuple(SHIPSTATION_V2_ENDPOINTS.keys())
+
+V2_INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in SHIPSTATION_V2_ENDPOINTS.items() if config.incremental_fields
+}
+
+
+def endpoints_for_version(api_version: str) -> dict[str, ShipStationEndpointConfig]:
+ """The endpoint catalog for a resolved version pin. v1 and v2 expose different resources."""
+ return SHIPSTATION_V2_ENDPOINTS if api_version == SHIPSTATION_V2 else SHIPSTATION_ENDPOINTS
+
+
+def schema_catalog_for_version(api_version: str) -> tuple[tuple[str, ...], dict[str, list[IncrementalField]]]:
+ """The `(endpoint names, incremental fields)` pair `get_schemas` builds from, per version."""
+ if api_version == SHIPSTATION_V2:
+ return V2_ENDPOINTS, V2_INCREMENTAL_FIELDS
+ return ENDPOINTS, INCREMENTAL_FIELDS
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shipstation/shipstation.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shipstation/shipstation.py
index 72591196298b..ecafba26c6c0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shipstation/shipstation.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shipstation/shipstation.py
@@ -1,10 +1,9 @@
import dataclasses
-from datetime import date, datetime
+from datetime import UTC, date, datetime
from typing import Any, Optional
from zoneinfo import ZoneInfo
from requests import Response
-from requests.auth import HTTPBasicAuth
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
@@ -12,6 +11,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (
+ APIKeyAuth,
+ HttpBasicAuth,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
PageNumberPaginator,
SinglePagePaginator,
@@ -19,18 +22,79 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
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.shipstation.settings import (
- SHIPSTATION_ENDPOINTS,
+ SHIPSTATION_V1,
+ SHIPSTATION_V2,
ShipStationEndpointConfig,
+ endpoints_for_version,
)
-SHIPSTATION_BASE_URL = "https://ssapi.shipstation.com"
-# ShipStation list pages cap at 500 items.
+# ShipStation list pages cap at 500 items on both versions.
PAGE_SIZE = 500
# All ShipStation v1 DateTime values are US Pacific time, not UTC.
SHIPSTATION_TZ = ZoneInfo("America/Los_Angeles")
[email protected](frozen=True)
+class ShipStationDialect:
+ """Per-version transport differences between the two live ShipStation APIs.
+
+ The endpoint catalog is version-specific (see `settings`), but the request layer only differs
+ in these axes: the host, auth scheme, query-param spellings (page size + sort), the date-filter
+ format, and the credential probe path."""
+
+ base_url: str
+ # Page-size param name (v1 camelCase `pageSize`, v2 snake_case `page_size`).
+ page_size_param: str
+ # Sort param names + ascending value (v1 `sortBy`/`sortDir`/`ASC`, v2 `sort_by`/`sort_dir`/`asc`).
+ sort_by_param: str
+ sort_dir_param: str
+ sort_dir_asc: str
+ # v1 stores/filters DateTime in US Pacific; v2 (ShipEngine) uses ISO 8601 UTC.
+ uses_pacific_time: bool
+ # v1 authenticates with HTTP Basic (key + secret); v2 with a single API-Key header.
+ uses_api_key_header: bool
+ # Cheap, always-present list endpoint used as a credential/permission probe.
+ credentials_probe_path: str
+
+
+SHIPSTATION_DIALECTS: dict[str, ShipStationDialect] = {
+ SHIPSTATION_V1: ShipStationDialect(
+ base_url="https://ssapi.shipstation.com",
+ page_size_param="pageSize",
+ sort_by_param="sortBy",
+ sort_dir_param="sortDir",
+ sort_dir_asc="ASC",
+ uses_pacific_time=True,
+ uses_api_key_header=False,
+ credentials_probe_path="/stores",
+ ),
+ SHIPSTATION_V2: ShipStationDialect(
+ base_url="https://api.shipstation.com/v2",
+ page_size_param="page_size",
+ sort_by_param="sort_by",
+ sort_dir_param="sort_dir",
+ sort_dir_asc="asc",
+ uses_pacific_time=False,
+ uses_api_key_header=True,
+ credentials_probe_path="/carriers",
+ ),
+}
+
+
+def _dialect(api_version: str) -> ShipStationDialect:
+ # Both supported labels are keyed explicitly. An undeclared pin is honored verbatim upstream
+ # (`resolve_api_version`); fall back to the original v1 transport rather than guessing a newer
+ # host/auth scheme for it.
+ return SHIPSTATION_DIALECTS.get(api_version, SHIPSTATION_DIALECTS[SHIPSTATION_V1])
+
+
+def _build_auth(api_key: str, api_secret: str | None, dialect: ShipStationDialect) -> APIKeyAuth | HttpBasicAuth:
+ if dialect.uses_api_key_header:
+ return APIKeyAuth(api_key=api_key, name="API-Key", location="header")
+ return HttpBasicAuth(api_key, api_secret)
+
+
@dataclasses.dataclass
class ShipStationResumeConfig:
# ShipStation paginates with a 1-based page number; the framework's PageNumberPaginator resume
@@ -65,12 +129,14 @@ class ShipStationPageNumberPaginator(PageNumberPaginator):
self._has_next_page = False
-def _format_date_filter(value: Any) -> str:
+def _format_date_filter(value: Any, dialect: ShipStationDialect = SHIPSTATION_DIALECTS[SHIPSTATION_V1]) -> str:
"""Format an incremental cursor for ShipStation's date filters.
- The API both stores and filters in US Pacific time ('yyyy-mm-dd hh:mm:ss').
- Naive values are assumed to already be Pacific (they come from API rows);
- aware values are converted."""
+ v1 both stores and filters in US Pacific time ('yyyy-mm-dd hh:mm:ss'); naive values are
+ assumed to already be Pacific (they come from API rows) and aware values are converted. v2
+ (ShipEngine) filters in ISO 8601 UTC ('2024-01-02T03:04:05Z')."""
+ if not dialect.uses_pacific_time:
+ return _format_utc_date_filter(value)
if isinstance(value, datetime):
dt = value if value.tzinfo is None else value.astimezone(SHIPSTATION_TZ)
return dt.strftime("%Y-%m-%d %H:%M:%S")
@@ -82,16 +148,27 @@ def _format_date_filter(value: Any) -> str:
return text.split(".")[0]
+def _format_utc_date_filter(value: Any) -> str:
+ if isinstance(value, datetime):
+ dt = value.astimezone(UTC) if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return value.strftime("%Y-%m-%dT00:00:00Z")
+ # v2 row values are already ISO 8601 UTC; pass them through unchanged.
+ return str(value)
+
+
def _build_params(
config: ShipStationEndpointConfig,
should_use_incremental_field: bool,
db_incremental_field_last_value: Any,
incremental_field: str | None,
+ dialect: ShipStationDialect = SHIPSTATION_DIALECTS[SHIPSTATION_V1],
) -> dict[str, Any]:
params: dict[str, Any] = {}
if config.paginated:
- params["pageSize"] = PAGE_SIZE
+ params[dialect.page_size_param] = PAGE_SIZE
if not config.incremental_params:
return params
@@ -101,31 +178,47 @@ def _build_params(
if should_use_incremental_field and db_incremental_field_last_value is not None:
filter_param = config.incremental_params.get(cursor_field)
if filter_param is not None:
- params[filter_param] = _format_date_filter(db_incremental_field_last_value)
+ params[filter_param] = _format_date_filter(db_incremental_field_last_value, dialect)
# Ascending sort on the cursor field (when the endpoint documents one) keeps
# page boundaries stable and advances the incremental watermark monotonically.
sort_by = config.sort_by.get(cursor_field)
if sort_by is not None:
- params["sortBy"] = sort_by
- params["sortDir"] = "ASC"
+ params[dialect.sort_by_param] = sort_by
+ params[dialect.sort_dir_param] = dialect.sort_dir_asc
return params
-def validate_credentials(api_key: str, api_secret: str) -> bool:
- """Confirm the key pair is valid with a cheap one-store listing probe."""
+def validate_credentials(
+ api_key: str, api_secret: str | None, api_version: str = SHIPSTATION_V1
+) -> tuple[bool, str | None]:
+ """Confirm the credentials are valid with a cheap list probe on the version's host.
+
+ v1 needs an API key + secret (HTTP Basic); v2 needs only the single API-Key value, so the
+ required pair depends on the resolved version rather than the form."""
+ dialect = _dialect(api_version)
+ if not api_key:
+ return False, "A ShipStation API key is required."
+ if not dialect.uses_api_key_header and not api_secret:
+ return False, "ShipStation API v1 requires both an API key and an API secret."
+
ok, _status = validate_via_probe(
- lambda: make_tracked_session(redact_values=(api_key, api_secret)),
- f"{SHIPSTATION_BASE_URL}/stores",
- auth=HTTPBasicAuth(api_key, api_secret),
+ lambda: make_tracked_session(redact_values=tuple(v for v in (api_key, api_secret) if v)),
+ f"{dialect.base_url}{dialect.credentials_probe_path}",
+ auth=_build_auth(api_key, api_secret, dialect),
+ # v2 sends its key in a custom API-Key header, which requests would replay across a
+ # cross-host redirect; refuse redirects so the probe can't leak it.
+ allow_redirects=not dialect.uses_api_key_header,
)
- return ok
+ if ok:
+ return True, None
+ return False, "Invalid ShipStation API credentials"
def shipstation_source(
api_key: str,
- api_secret: str,
+ api_secret: str | None,
endpoint: str,
team_id: int,
job_id: str,
@@ -133,18 +226,27 @@ def shipstation_source(
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Optional[Any] = None,
incremental_field: str | None = None,
+ api_version: str = SHIPSTATION_V1,
) -> SourceResponse:
- config = SHIPSTATION_ENDPOINTS[endpoint]
+ dialect = _dialect(api_version)
+ config = endpoints_for_version(api_version)[endpoint]
paginator = ShipStationPageNumberPaginator(PAGE_SIZE) if config.paginated else SinglePagePaginator()
- params = _build_params(config, should_use_incremental_field, db_incremental_field_last_value, incremental_field)
+ params = _build_params(
+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field, dialect
+ )
rest_config: RESTAPIConfig = {
"client": {
- "base_url": SHIPSTATION_BASE_URL,
+ "base_url": dialect.base_url,
"headers": {"Accept": "application/json"},
- # Basic auth via the framework so the secret is redacted from logs.
- "auth": {"type": "http_basic", "username": api_key, "password": api_secret},
+ # Auth via the framework so the secret is redacted from logs.
+ "auth": _build_auth(api_key, api_secret, dialect),
+ # The v2 API-Key header would survive a cross-host redirect (requests only strips
+ # Authorization), so pin v2 requests to the base host and refuse redirects. v1's Basic
+ # auth is stripped by requests across hosts, so its behavior is left unchanged.
+ "allowed_hosts": [] if dialect.uses_api_key_header else None,
+ "allow_redirects": not dialect.uses_api_key_header,
"paginator": paginator,
},
"resource_defaults": {},
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shipstation/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shipstation/source.py
index 6befab8217bb..214b0e439545 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shipstation/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shipstation/source.py
@@ -13,7 +13,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
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.base import (
+ FieldType,
+ ResumableSource,
+ VersionDeprecation,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
)
@@ -27,8 +31,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
ShipStationSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.shipstation.settings import (
- ENDPOINTS,
- INCREMENTAL_FIELDS,
+ SHIPSTATION_DEFAULT_VERSION,
+ SHIPSTATION_SUPPORTED_VERSIONS,
+ SHIPSTATION_V1,
+ schema_catalog_for_version,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.shipstation.shipstation import (
ShipStationResumeConfig,
@@ -40,7 +46,13 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class ShipStationSource(ResumableSource[ShipStationSourceConfig, ShipStationResumeConfig]):
- api_docs_url = "https://www.shipstation.com/docs/api/"
+ api_docs_url = "https://docs.shipstation.com/"
+
+ supported_versions = SHIPSTATION_SUPPORTED_VERSIONS
+ default_version = SHIPSTATION_DEFAULT_VERSION
+ # ShipStation has deprecated the original v1 API in favor of the ShipEngine-based v2. No
+ # removal date is announced yet; the vendor promises advance notice (sunset_at=None).
+ deprecated_versions = (VersionDeprecation(version=SHIPSTATION_V1, sunset_at=None),)
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
@@ -59,6 +71,8 @@ class ShipStationSource(ResumableSource[ShipStationSourceConfig, ShipStationResu
return {
"401 Client Error: Unauthorized for url: https://ssapi.shipstation.com": "ShipStation authentication failed. Please check your API key and API secret.",
"403 Client Error: Forbidden for url: https://ssapi.shipstation.com": "ShipStation denied access. Please check that your plan includes API access.",
+ "401 Client Error: Unauthorized for url: https://api.shipstation.com/v2": "ShipStation authentication failed. Please check your API key.",
+ "403 Client Error: Forbidden for url: https://api.shipstation.com/v2": "ShipStation denied access. Please check that your plan includes API access.",
}
@property
@@ -67,14 +81,19 @@ class ShipStationSource(ResumableSource[ShipStationSourceConfig, ShipStationResu
name=SchemaExternalDataSourceType.SHIP_STATION,
category=DataWarehouseSourceCategory.E_COMMERCE,
label="ShipStation",
- caption="""Enter your ShipStation API credentials to pull your ShipStation order and shipping data into the PostHog Data warehouse.
+ caption="""Enter your ShipStation API credentials to pull your ShipStation shipping data into the PostHog data warehouse.
+
+New connections use ShipStation API v2, which needs only the API key from your [ShipStation API settings](https://docs.shipstation.com/getting-started). The API secret is only for older v1 connections, which ShipStation is deprecating.
-You can find your API key and API secret in [ShipStation](https://ship.shipstation.com/settings/api-settings) under Settings > Account > API Settings. API access requires a ShipStation plan tier that includes it.""",
+API access requires a ShipStation plan tier that includes it.""",
iconPath="/static/services/shipstation.png",
docsUrl="https://posthog.com/docs/cdp/sources/shipstation",
releaseStatus=ReleaseStatus.ALPHA,
fields=cast(
list[FieldType],
+ # The two versions take different credentials: v2 needs only the API key, v1 an
+ # API key + secret. api_key is required either way; api_secret is optional at the
+ # form level and enforced for v1 by `validate_credentials`.
[
SourceFieldInputConfig(
name="api_key",
@@ -86,9 +105,9 @@ You can find your API key and API secret in [ShipStation](https://ship.shipstati
),
SourceFieldInputConfig(
name="api_secret",
- label="API secret",
+ label="API secret (v1 only)",
type=SourceFieldInputConfigType.PASSWORD,
- required=True,
+ required=False,
placeholder="",
secret=True,
),
@@ -105,7 +124,9 @@ You can find your API key and API secret in [ShipStation](https://ship.shipstati
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+ # v1 and v2 expose different resource catalogs, so discovery must build from the pin.
+ endpoints, incremental_fields = schema_catalog_for_version(self.resolve_api_version(api_version))
+ return build_endpoint_schemas(endpoints, incremental_fields, names)
def validate_credentials(
self,
@@ -114,10 +135,14 @@ You can find your API key and API secret in [ShipStation](https://ship.shipstati
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
- if validate_shipstation_credentials(config.api_key, config.api_secret):
+ # The probe host and required credentials differ by version, so probe the resolved pin
+ # (pre-creation calls pass None → default v2, the version a new source is stamped with).
+ ok, error = validate_shipstation_credentials(
+ config.api_key, config.api_secret, self.resolve_api_version(api_version)
+ )
+ if ok:
return True, None
-
- return False, "Invalid ShipStation API credentials"
+ return False, error or "Invalid ShipStation API credentials"
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ShipStationResumeConfig]:
return ResumableSourceManager[ShipStationResumeConfig](inputs, ShipStationResumeConfig)
@@ -140,4 +165,5 @@ You can find your API key and API secret in [ShipStation](https://ship.shipstati
if inputs.should_use_incremental_field
else None,
incremental_field=inputs.incremental_field,
+ api_version=self.resolve_api_version(inputs.api_version),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shipstation/tests/test_shipstation.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shipstation/tests/test_shipstation.py
index 6662836755c8..b0c373be97c5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shipstation/tests/test_shipstation.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shipstation/tests/test_shipstation.py
@@ -7,19 +7,31 @@ from unittest import mock
from requests import Response
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (
+ APIKeyAuth,
+ HttpBasicAuth,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.shipstation.settings import (
ENDPOINTS,
SHIPSTATION_ENDPOINTS,
+ SHIPSTATION_V1,
+ SHIPSTATION_V2,
+ SHIPSTATION_V2_ENDPOINTS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.shipstation.shipstation import (
PAGE_SIZE,
+ SHIPSTATION_DIALECTS,
ShipStationResumeConfig,
+ _build_auth,
_build_params,
_format_date_filter,
shipstation_source,
validate_credentials,
)
+V1_DIALECT = SHIPSTATION_DIALECTS[SHIPSTATION_V1]
+V2_DIALECT = SHIPSTATION_DIALECTS[SHIPSTATION_V2]
+
# 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"
# validate_credentials builds its own tracked session in the shipstation module.
@@ -92,6 +104,20 @@ class TestFormatDateFilter:
def test_format_values(self, value, expected):
assert _format_date_filter(value) == expected
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ # v2 (ShipEngine) filters in ISO 8601 UTC, not Pacific.
+ (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "2024-01-02T03:04:05Z"),
+ # Naive values from v2 rows are already UTC.
+ (datetime(2024, 1, 2, 3, 4, 5), "2024-01-02T03:04:05Z"),
+ (date(2024, 1, 2), "2024-01-02T00:00:00Z"),
+ ("2024-01-02T03:04:05.657Z", "2024-01-02T03:04:05.657Z"),
+ ],
+ )
+ def test_format_values_v2_uses_iso_utc(self, value, expected):
+ assert _format_date_filter(value, V2_DIALECT) == expected
+
class TestBuildParams:
@pytest.mark.parametrize(
@@ -128,6 +154,22 @@ class TestBuildParams:
assert "createDateStart" not in params
assert params["sortBy"] == "ModifyDate"
+ def test_v2_uses_snake_case_filter_and_sort_spellings(self):
+ # v1 spellings (createDateStart / sortBy=CreateDate / ASC) leaking into a v2 request would
+ # be rejected or silently ignored by the v2 API.
+ params = _build_params(
+ SHIPSTATION_V2_ENDPOINTS["shipments"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC),
+ incremental_field="created_at",
+ dialect=V2_DIALECT,
+ )
+
+ assert params["created_at_start"] == "2024-01-02T03:04:05Z"
+ assert params["sort_by"] == "created_at"
+ assert params["sort_dir"] == "asc"
+ assert params["page_size"] == PAGE_SIZE
+
def test_fulfillments_have_filter_but_no_sort(self):
params = _build_params(
SHIPSTATION_ENDPOINTS["fulfillments"],
@@ -167,12 +209,29 @@ class TestValidateCredentials:
response.status_code = status_code
mock_session.return_value.get.return_value = response
- assert validate_credentials("key", "secret") is expected
+ ok, _error = validate_credentials("key", "secret")
+ assert ok is expected
@mock.patch(SHIPSTATION_SESSION_PATCH)
def test_validate_credentials_swallows_exceptions(self, mock_session):
mock_session.return_value.get.side_effect = Exception("boom")
- assert validate_credentials("key", "secret") is False
+ ok, _error = validate_credentials("key", "secret")
+ assert ok is False
+
+ def test_v1_requires_secret_without_probing(self):
+ # v1 authenticates with a key + secret pair; a missing secret must fail before any request.
+ ok, error = validate_credentials("key", None, SHIPSTATION_V1)
+ assert ok is False
+ assert error is not None and "secret" in error.lower()
+
+ @mock.patch(SHIPSTATION_SESSION_PATCH)
+ def test_v2_probes_v2_host_with_api_key_only(self, mock_session):
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
+
+ ok, _error = validate_credentials("key", None, SHIPSTATION_V2)
+
+ assert ok is True
+ assert mock_session.return_value.get.call_args.args[0] == "https://api.shipstation.com/v2/carriers"
class TestExtractionShapes:
@@ -297,6 +356,69 @@ class TestPagination:
manager.save_state.assert_not_called()
+class TestVersionDispatch:
+ @pytest.mark.parametrize(
+ "dialect, expected_type, header_present",
+ [
+ (V1_DIALECT, HttpBasicAuth, False),
+ (V2_DIALECT, APIKeyAuth, True),
+ ],
+ )
+ def test_build_auth_scheme_per_version(self, dialect, expected_type, header_present):
+ auth = _build_auth("key", "secret", dialect)
+
+ assert isinstance(auth, expected_type)
+ if header_present:
+ # v2 sends the key in an API-Key header; a wrong scheme would 401 every request.
+ assert auth.name == "API-Key"
+ assert auth.api_key == "key"
+ else:
+ assert (auth.username, auth.password) == ("key", "secret")
+
+ @pytest.mark.parametrize(
+ "api_version, endpoint, body, expected_url, expected_page_size_param",
+ [
+ (
+ SHIPSTATION_V1,
+ "orders",
+ {"orders": [{"orderId": 1}], "page": 1, "pages": 1},
+ "https://ssapi.shipstation.com/orders",
+ "pageSize",
+ ),
+ (
+ SHIPSTATION_V2,
+ "shipments",
+ {"shipments": [{"shipment_id": "se-1"}], "page": 1, "pages": 1},
+ "https://api.shipstation.com/v2/shipments",
+ "page_size",
+ ),
+ ],
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_request_targets_version_host_and_pagination(
+ self, MockSession, api_version, endpoint, body, expected_url, expected_page_size_param
+ ):
+ # The bug this guards: a v2 pin syncing against v1's host/paths/params (every table 404s).
+ session = MockSession.return_value
+ session.headers = {}
+ urls: list[str] = []
+ params: list[dict[str, Any]] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ urls.append(request.url)
+ params.append(dict(request.params or {}))
+ # v2 enforces allowed_hosts, which parses prepared.url — give it the real URL string.
+ return mock.MagicMock(url=request.url)
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = [_response(body)]
+
+ _rows(_source(endpoint, _make_manager(), api_version=api_version))
+
+ assert urls[0] == expected_url
+ assert expected_page_size_param in params[0]
+
+
class TestShipStationSourceResponse:
@pytest.mark.parametrize("endpoint", list(ENDPOINTS))
@mock.patch(CLIENT_SESSION_PATCH)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shipstation/tests/test_shipstation_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shipstation/tests/test_shipstation_source.py
index 1fd516c270c9..7dba4dfc2961 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shipstation/tests/test_shipstation_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shipstation/tests/test_shipstation_source.py
@@ -3,6 +3,7 @@ from unittest import mock
from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import VersionDeprecation
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.shipstation import (
ShipStationSourceConfig,
@@ -10,6 +11,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
from products.warehouse_sources.backend.temporal.data_imports.sources.shipstation.settings import (
ENDPOINTS,
INCREMENTAL_FIELDS,
+ SHIPSTATION_V1,
+ SHIPSTATION_V2,
+ V2_ENDPOINTS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.shipstation.shipstation import (
ShipStationResumeConfig,
@@ -39,19 +43,29 @@ class TestShipStationSource:
field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
assert field_names == ["api_key", "api_secret"]
- @pytest.mark.parametrize("field_name", ["api_key", "api_secret"])
- def test_credential_field_is_secret_password(self, field_name):
+ @pytest.mark.parametrize(
+ "field_name, required",
+ [
+ # api_key is needed by both versions; api_secret is v1-only, so optional at the form
+ # level (v2 users have no secret) and enforced for v1 in validate_credentials.
+ ("api_key", True),
+ ("api_secret", False),
+ ],
+ )
+ def test_credential_field_is_secret_password(self, field_name, required):
config = self.source.get_source_config
secret_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == field_name)
assert secret_field.type == SourceFieldInputConfigType.PASSWORD
assert secret_field.secret is True
- assert secret_field.required is True
+ assert secret_field.required is required
@pytest.mark.parametrize(
"observed_error",
[
"401 Client Error: Unauthorized for url: https://ssapi.shipstation.com/orders?pageSize=500",
"403 Client Error: Forbidden for url: https://ssapi.shipstation.com/stores",
+ "401 Client Error: Unauthorized for url: https://api.shipstation.com/v2/shipments?page_size=500",
+ "403 Client Error: Forbidden for url: https://api.shipstation.com/v2/carriers",
],
)
def test_non_retryable_errors_match_auth_failures(self, observed_error):
@@ -69,16 +83,40 @@ class TestShipStationSource:
non_retryable_errors = self.source.get_non_retryable_errors()
assert not any(key in other_vendor_error for key in non_retryable_errors)
- def test_get_schemas(self):
- schemas = self.source.get_schemas(self.config, self.team_id)
+ def test_declares_both_versions_defaulting_to_v2_with_v1_deprecated(self):
+ # The core of this change: v2 is the newest supported version and default, v1 is
+ # deprecated (no announced sunset date). A dropped deprecation or a held-back default
+ # would silently keep new sources on the retired v1 API.
+ assert self.source.supported_versions == (SHIPSTATION_V1, SHIPSTATION_V2)
+ assert self.source.default_version == SHIPSTATION_V2
+ assert self.source.deprecated_versions == (VersionDeprecation(version=SHIPSTATION_V1, sunset_at=None),)
- assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ @pytest.mark.parametrize(
+ "api_version, expected_names, expected_incremental",
+ [
+ (SHIPSTATION_V1, set(ENDPOINTS), {"orders", "shipments", "fulfillments"}),
+ (SHIPSTATION_V2, set(V2_ENDPOINTS), {"shipments", "labels", "batches", "manifests", "pickups"}),
+ ],
+ )
+ def test_get_schemas_returns_the_pinned_versions_catalog(self, api_version, expected_names, expected_incremental):
+ # v1 and v2 expose different resource sets; discovery must follow the pin or a pinned
+ # source's tables disappear/duplicate on reconciliation.
+ schemas = self.source.get_schemas(self.config, self.team_id, api_version=api_version)
+
+ assert {schema.name for schema in schemas} == expected_names
incremental = {schema.name for schema in schemas if schema.supports_incremental}
- # Only the date-filterable list endpoints support incremental sync.
- assert incremental == {"orders", "shipments", "fulfillments"}
+ assert incremental == expected_incremental
+
+ def test_get_schemas_defaults_to_v2(self):
+ # An unpinned discovery call resolves to the default version (v2).
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {schema.name for schema in schemas} == set(V2_ENDPOINTS)
def test_incremental_schemas_advertise_their_fields(self):
- schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+ schemas = {
+ schema.name: schema
+ for schema in self.source.get_schemas(self.config, self.team_id, api_version=SHIPSTATION_V1)
+ }
assert schemas["orders"].incremental_fields == INCREMENTAL_FIELDS["orders"]
assert {f["field"] for f in schemas["orders"].incremental_fields} == {"modifyDate", "createDate"}
@@ -86,7 +124,7 @@ class TestShipStationSource:
assert schemas["products"].supports_append is False
def test_get_schemas_filtered_by_names(self):
- schemas = self.source.get_schemas(self.config, self.team_id, names=["orders"])
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["orders"], api_version=SHIPSTATION_V1)
assert len(schemas) == 1
assert schemas[0].name == "orders"
@@ -96,8 +134,13 @@ class TestShipStationSource:
@pytest.mark.parametrize(
"mock_return, expected_valid, expected_message",
[
- (True, True, None),
- (False, False, "Invalid ShipStation API credentials"),
+ ((True, None), True, None),
+ (
+ (False, "ShipStation API v1 requires both an API key and an API secret."),
+ False,
+ "ShipStation API v1 requires both an API key and an API secret.",
+ ),
+ ((False, None), False, "Invalid ShipStation API credentials"),
],
)
@mock.patch(
@@ -110,7 +153,8 @@ class TestShipStationSource:
assert is_valid is expected_valid
assert error_message == expected_message
- mock_validate.assert_called_once_with(self.config.api_key, self.config.api_secret)
+ # Pre-creation validation probes the default version (new sources are stamped v2).
+ mock_validate.assert_called_once_with(self.config.api_key, self.config.api_secret, SHIPSTATION_V2)
def test_get_resumable_source_manager_binds_resume_config(self):
inputs = mock.MagicMock()
@@ -142,6 +186,22 @@ class TestShipStationSource:
assert kwargs["db_incremental_field_last_value"] == "2024-01-02T03:04:05.0000000"
assert kwargs["incremental_field"] == "modifyDate"
+ @pytest.mark.parametrize("pin, expected", [(None, SHIPSTATION_V2), ("v1", "v1"), ("v2", "v2")])
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.shipstation.source.shipstation_source"
+ )
+ def test_source_for_pipeline_resolves_api_version(self, mock_shipstation_source, pin, expected):
+ # The resolved pin must reach the transport, else a v2 source would sync against v1.
+ inputs = mock.MagicMock()
+ inputs.schema_name = "shipments"
+ inputs.should_use_incremental_field = False
+ inputs.incremental_field = None
+ inputs.api_version = pin
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_shipstation_source.call_args.kwargs["api_version"] == expected
+
@mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.shipstation.source.shipstation_source"
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/canonical_descriptions.py
index c3e5ea98609f..bb8170f517a0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/canonical_descriptions.py
@@ -65,4 +65,42 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"limit": "Maximum allowed by the account's plan.",
},
},
+ # v2 custom objects API tables.
+ "custom_objects": {
+ "description": "A custom object: a user-defined data model (identified by its key) that custom object records are validated against.",
+ "docs_url": "https://developer.zendesk.com/api-reference/custom-data/custom-objects/custom_objects/",
+ "columns": {
+ "key": "Unique, user-defined identifier for the custom object.",
+ "title": "Display name of the custom object.",
+ "title_pluralized": "Pluralized display name of the custom object.",
+ "description": "Description of the custom object.",
+ "created_at": "When the custom object was created.",
+ "updated_at": "When the custom object was last updated.",
+ },
+ },
+ "custom_object_records": {
+ "description": "A custom object record: an instance of a custom object, with its data held under custom_object_fields.",
+ "docs_url": "https://developer.zendesk.com/api-reference/custom-data/custom-objects/custom_object_records/",
+ "columns": {
+ "id": "Unique identifier of the record, assigned automatically on creation.",
+ "name": "Display name of the record.",
+ "custom_object_key": "Key of the custom object this record belongs to.",
+ "external_id": "Unique identifier from another system, if one was supplied.",
+ "custom_object_fields": "The record's field values, keyed by field key.",
+ "created_at": "When the record was created.",
+ "updated_at": "When the record was last updated.",
+ },
+ },
+ "custom_object_fields": {
+ "description": "A field defined on a custom object: describes one attribute (its key, type, and options) that records of the object can set.",
+ "docs_url": "https://developer.zendesk.com/api-reference/custom-data/custom-objects/custom_object_fields/",
+ "columns": {
+ "id": "Unique identifier of the field, assigned automatically on creation.",
+ "key": "Unique, user-defined identifier for the field within its custom object.",
+ "type": "Data type of the field (for example text, dropdown, or lookup).",
+ "title": "Display name of the field.",
+ "created_at": "When the field was created.",
+ "updated_at": "When the field was last updated.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/docs/zendesk-sunshine.md b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/docs/zendesk-sunshine.md
index 4cefd01ed1ee..32d4c252a30b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/docs/zendesk-sunshine.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/docs/zendesk-sunshine.md
@@ -14,13 +14,15 @@ import AlphaRelease from "../\_snippets/alpha-release.mdx"
<AlphaRelease />
-The Zendesk Sunshine source syncs your legacy Zendesk custom objects (the Sunshine custom data API) into PostHog: object types, object records, relationship types, relationship records, permission policies, and account limits.
+The Zendesk Sunshine source syncs your Zendesk custom objects into PostHog.
-> **Note:** Zendesk is retiring legacy custom objects in 2026 and no new legacy objects can be created since January 15, 2026. This source reads the legacy `/api/sunshine/` API, so it is mainly useful for keeping a queryable copy of that data before Zendesk removes it. It does not cover the newer custom objects experience under the Zendesk Support API.
+New sources use Zendesk's current custom objects API (`/api/v2/custom_objects`, version `v2`) and sync custom object definitions, their records, and field schemas.
+
+> **Note:** Zendesk is removing the legacy Sunshine custom objects API (`/api/sunshine/`, version `v1`) on June 30, 2026, and no new legacy objects can be created since January 15, 2026. Sources created before `v2` became the default are still pinned to `v1` and keep working until then. PostHog shows a deprecation warning on those sources; move each one to `v2` from the source's settings before the sunset date. Because the `v1` and `v2` table sets differ, switching a source to `v2` resyncs it under the new tables rather than converting the existing ones in place.
## Prerequisites
-- A Zendesk plan that includes legacy custom objects, with legacy custom objects activated by an admin in Admin Center (Objects and rules → Custom objects).
+- A Zendesk plan that includes custom objects, with custom objects activated by an admin in Admin Center (Objects and rules → Custom objects).
- API token access enabled for your Zendesk account (Admin Center → Apps and integrations → APIs → Zendesk API).
- A Zendesk API token. Generate one in Admin Center under Apps and integrations → APIs → Zendesk API → Add API token.
@@ -38,7 +40,7 @@ You'll need:
<SyncModes />
-Object records support incremental syncs on `updated_at`, served by Zendesk's custom object search API which filters server side. All other tables are small catalogs and sync as full refreshes.
+On `v2`, all tables sync as full refreshes; the current records API has no server-side `updated_at` filter, so records are fetched sorted by `updated_at`. On legacy `v1`, object records support incremental syncs on `updated_at` via the Sunshine search API, and the other tables are small catalogs that full refresh.
## Configuration
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/settings.py
index 4ea7fcaa6d46..a883acc469c8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/settings.py
@@ -1,14 +1,28 @@
from dataclasses import dataclass, field
+from typing import Any
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import UNVERSIONED_API_VERSION
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
from products.warehouse_sources.backend.types import IncrementalField
+# v1 is the legacy Sunshine custom objects API (`/api/sunshine/`, no version token). v2 is the
+# current custom objects API under the standard Support API (`/api/v2/custom_objects`). Zendesk is
+# retiring the legacy API (no new legacy objects after 2026-01-15, removed 2026-06-30), so new
+# sources default to v2; existing sources stay on their pin until a human migrates them.
+ZENDESK_SUNSHINE_V1 = UNVERSIONED_API_VERSION
+ZENDESK_SUNSHINE_V2 = "v2"
+
+# Per-version base path segment appended to `https://{subdomain}.zendesk.com/`.
+BASE_PATH_BY_VERSION = {ZENDESK_SUNSHINE_V1: "api/sunshine/", ZENDESK_SUNSHINE_V2: "api/v2/"}
+
# Catalog endpoints (object types, relationship types, limits) are small; a conservative
# page size keeps responses light.
DEFAULT_PAGE_SIZE = 100
# Record endpoints (`objects/records`, `relationships/records`, `objects/query`) document
# `per_page` from 1 to 1000.
RECORDS_PAGE_SIZE = 1000
+# The v2 custom object records list caps `per_page` at 100.
+RECORDS_PAGE_SIZE_V2 = 100
# The legacy custom objects search endpoint — the only Sunshine endpoint with a server-side
# `_updated_at` range filter, so incremental object record syncs go through it.
@@ -37,6 +51,11 @@ class ZendeskSunshineEndpointConfig:
include_from_parent: list[str] = field(default_factory=list)
parent_field_renames: dict[str, str] = field(default_factory=dict)
single_page: bool = False
+ # JSON key holding the row array in the response envelope. v1 Sunshine wraps everything in
+ # `data`; v2 uses a per-resource key (`custom_objects`, `custom_object_records`, ...).
+ data_selector: str = "data"
+ # Extra static query params merged into the list request (e.g. v2 records `sort=updated_at`).
+ extra_params: dict[str, Any] = field(default_factory=dict)
ZENDESK_SUNSHINE_ENDPOINTS: dict[str, ZendeskSunshineEndpointConfig] = {
@@ -100,3 +119,68 @@ ENDPOINTS = tuple(ZENDESK_SUNSHINE_ENDPOINTS)
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
name: config.incremental_fields for name, config in ZENDESK_SUNSHINE_ENDPOINTS.items()
}
+
+# v2 custom objects API. The legacy relationship and permission-policy resources have no v2
+# equivalent, and the record shape differs (fields nest under `custom_object_fields` rather than a
+# flat `attributes`), so the v2 table set is deliberately different from v1 — this is why repinning
+# an existing source is a lossy transform rather than an in-place `api_version` flip. The v2 records
+# list endpoint has no server-side `updated_at` filter (only `filter[ids]`/`filter[external_ids]`),
+# so records sync as full refresh sorted by `updated_at`.
+ZENDESK_SUNSHINE_V2_ENDPOINTS: dict[str, ZendeskSunshineEndpointConfig] = {
+ "custom_objects": ZendeskSunshineEndpointConfig(
+ name="custom_objects",
+ path="custom_objects",
+ primary_keys=["key"],
+ partition_key="created_at",
+ data_selector="custom_objects",
+ ),
+ "custom_object_records": ZendeskSunshineEndpointConfig(
+ name="custom_object_records",
+ path="custom_objects/{custom_object_key}/records",
+ primary_keys=["id"],
+ page_size=RECORDS_PAGE_SIZE_V2,
+ partition_key="created_at",
+ data_selector="custom_object_records",
+ extra_params={"sort": "updated_at"},
+ fanout_parent="custom_objects",
+ resolve_placeholder="custom_object_key",
+ resolve_field="key",
+ ),
+ "custom_object_fields": ZendeskSunshineEndpointConfig(
+ name="custom_object_fields",
+ path="custom_objects/{custom_object_key}/fields",
+ primary_keys=["id"],
+ page_size=RECORDS_PAGE_SIZE_V2,
+ data_selector="custom_object_fields",
+ fanout_parent="custom_objects",
+ resolve_placeholder="custom_object_key",
+ resolve_field="key",
+ ),
+}
+
+V2_ENDPOINTS = tuple(ZENDESK_SUNSHINE_V2_ENDPOINTS)
+
+ENDPOINTS_BY_VERSION: dict[str, dict[str, ZendeskSunshineEndpointConfig]] = {
+ ZENDESK_SUNSHINE_V1: ZENDESK_SUNSHINE_ENDPOINTS,
+ ZENDESK_SUNSHINE_V2: ZENDESK_SUNSHINE_V2_ENDPOINTS,
+}
+
+INCREMENTAL_FIELDS_BY_VERSION: dict[str, dict[str, list[IncrementalField]]] = {
+ version: {name: config.incremental_fields for name, config in endpoints.items()}
+ for version, endpoints in ENDPOINTS_BY_VERSION.items()
+}
+
+# Endpoints offered as merge-incremental (never append) per version. The v1 object records query
+# filter is inclusive on its lower bound, so boundary rows re-fetch every sync and only merge
+# dedupes them; v2 has no incremental records, so nothing to declare.
+MERGE_ONLY_BY_VERSION: dict[str, tuple[str, ...]] = {
+ ZENDESK_SUNSHINE_V1: ("object_records",),
+ ZENDESK_SUNSHINE_V2: (),
+}
+
+
+def endpoints_for_version(api_version: str) -> dict[str, ZendeskSunshineEndpointConfig]:
+ try:
+ return ENDPOINTS_BY_VERSION[api_version]
+ except KeyError as e:
+ raise ValueError(f"Unsupported Zendesk Sunshine API version: {api_version!r}") from e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/source.py
index 70e770e71b78..afe20de99c06 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/source.py
@@ -1,4 +1,5 @@
import re
+import datetime
from typing import Optional, cast
from posthog.schema import (
@@ -14,7 +15,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
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.base import (
+ FieldType,
+ ResumableSource,
+ VersionDeprecation,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
)
@@ -28,8 +33,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
ZendeskSunshineSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.settings import (
- ENDPOINTS,
- INCREMENTAL_FIELDS,
+ ENDPOINTS_BY_VERSION,
+ INCREMENTAL_FIELDS_BY_VERSION,
+ MERGE_ONLY_BY_VERSION,
+ ZENDESK_SUNSHINE_V1,
+ ZENDESK_SUNSHINE_V2,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.zendesk_sunshine import (
ZendeskSunshineResumeConfig,
@@ -43,9 +51,14 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class ZendeskSunshineSource(ResumableSource[ZendeskSunshineSourceConfig, ZendeskSunshineResumeConfig]):
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
- # The Sunshine API path (`/api/sunshine/`) carries no version token, so the unversioned
- # `supported_versions`/`default_version` defaults apply.
- api_docs_url = "https://developer.zendesk.com/api-reference/custom-data/custom-objects-api/custom-objects-api/"
+
+ # v1 is the legacy Sunshine API (`/api/sunshine/`); v2 is the current custom objects API
+ # (`/api/v2/custom_objects`). Zendesk is retiring the legacy API, so new sources default to v2
+ # while existing v1-pinned sources keep working until a human migrates them.
+ supported_versions = (ZENDESK_SUNSHINE_V1, ZENDESK_SUNSHINE_V2)
+ default_version = ZENDESK_SUNSHINE_V2
+ deprecated_versions = (VersionDeprecation(version=ZENDESK_SUNSHINE_V1, sunset_at=datetime.date(2026, 6, 30)),)
+ api_docs_url = "https://developer.zendesk.com/api-reference/custom-data/custom-objects/custom_objects/"
@property
def source_type(self) -> ExternalDataSourceType:
@@ -65,12 +78,18 @@ class ZendeskSunshineSource(ResumableSource[ZendeskSunshineSourceConfig, Zendesk
"and that token access is enabled for your account."
),
"403 Client Error: Forbidden for url": (
- "Zendesk denied access to the Sunshine API. Check that legacy custom objects are activated for "
+ "Zendesk denied access to the custom objects API. Check that custom objects are activated for "
"your account and that the API token has access."
),
"404 Client Error: Not Found for url": (
- "The Zendesk Sunshine (legacy custom objects) API was not found. Check the subdomain is correct "
- "and that legacy custom objects are activated in Admin Center."
+ "The Zendesk custom objects API was not found. Check the subdomain is correct and that custom "
+ "objects are activated in Admin Center. Sources still pinned to the legacy Sunshine API (v1) will "
+ "start returning this once Zendesk removes it; switch the source to v2 to keep syncing."
+ ),
+ # A pin outside the supported set stops the source from resolving a request path. Retrying
+ # the ~6h discovery cadence can never fix a bad pin, so surface it instead of looping.
+ "Unsupported Zendesk Sunshine API version": (
+ "This source is pinned to a Zendesk Sunshine API version PostHog no longer supports. Switch it to v2."
),
}
@@ -83,9 +102,18 @@ class ZendeskSunshineSource(ResumableSource[ZendeskSunshineSourceConfig, Zendesk
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- # The query endpoint's `_updated_at.start` filter is inclusive, so boundary rows are
- # re-fetched on every sync; only merge mode dedupes them, hence no append support.
- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=("object_records",))
+ # The v1 and v2 table sets differ, so a pinned source must discover under its own version —
+ # discovery diffs run under the source pin and would orphan tables that don't exist in the
+ # other version's catalog.
+ version = self.resolve_api_version(api_version)
+ if version not in ENDPOINTS_BY_VERSION:
+ raise ValueError(f"Unsupported Zendesk Sunshine API version: {version!r}")
+ return build_endpoint_schemas(
+ ENDPOINTS_BY_VERSION[version],
+ INCREMENTAL_FIELDS_BY_VERSION[version],
+ names,
+ merge_only=MERGE_ONLY_BY_VERSION[version],
+ )
def validate_credentials(
self,
@@ -98,7 +126,11 @@ class ZendeskSunshineSource(ResumableSource[ZendeskSunshineSourceConfig, Zendesk
if not re.match(r"^[a-zA-Z0-9-]+$", subdomain):
return False, "Zendesk subdomain is incorrect"
- return validate_zendesk_sunshine_credentials(config.subdomain, config.api_key, config.email_address)
+ # Pre-creation calls pass no pin and resolve to default_version (what new rows are stamped
+ # with); a pinned source revalidates against its own version's probe endpoint.
+ return validate_zendesk_sunshine_credentials(
+ config.subdomain, config.api_key, config.email_address, self.resolve_api_version(api_version)
+ )
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ZendeskSunshineResumeConfig]:
return ResumableSourceManager[ZendeskSunshineResumeConfig](inputs, ZendeskSunshineResumeConfig)
@@ -121,6 +153,7 @@ class ZendeskSunshineSource(ResumableSource[ZendeskSunshineSourceConfig, Zendesk
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),
)
@property
@@ -129,9 +162,9 @@ class ZendeskSunshineSource(ResumableSource[ZendeskSunshineSourceConfig, Zendesk
name=SchemaExternalDataSourceType.ZENDESK_SUNSHINE,
category=DataWarehouseSourceCategory.CRM,
label="Zendesk Sunshine",
- caption="""Import your legacy Zendesk custom objects (the Sunshine custom data API) into the PostHog Data warehouse: object types, object records, relationships, and limits.
+ caption="""Import your Zendesk custom objects into the PostHog Data warehouse: object definitions, their records, and field schemas.
-Requires a Zendesk plan with legacy custom objects activated in Admin Center. Note that Zendesk is retiring legacy custom objects in 2026, so this source is mainly useful for keeping a copy of that data. Authenticate with your Zendesk email address and an API token (token access must be enabled for your account).""",
+New sources use Zendesk's current custom objects API. The legacy Sunshine API (v1) is still supported for existing sources, but Zendesk is removing it on June 30, 2026. Authenticate with your Zendesk email address and an API token (token access must be enabled for your account).""",
keywords=["zendesk", "sunshine", "custom objects", "custom data"],
iconPath="/static/services/zendesk_sunshine.png",
iconClassName="rounded dark:bg-white p-[2px]",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/tests/test_zendesk_sunshine.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/tests/test_zendesk_sunshine.py
index 7cb55dc588b7..1aa04400fa2a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/tests/test_zendesk_sunshine.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/tests/test_zendesk_sunshine.py
@@ -12,6 +12,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.settings import (
DEFAULT_QUERY_WINDOW_START,
ZENDESK_SUNSHINE_ENDPOINTS,
+ ZENDESK_SUNSHINE_V1,
+ ZENDESK_SUNSHINE_V2,
+ ZENDESK_SUNSHINE_V2_ENDPOINTS,
+ endpoints_for_version,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.zendesk_sunshine import (
SunshineLinksPaginator,
@@ -28,6 +32,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_su
)
BASE_URL = "https://nibbles.zendesk.com/api/sunshine/"
+V2_BASE_URL = "https://nibbles.zendesk.com/api/v2/"
MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.zendesk_sunshine"
@@ -86,9 +91,27 @@ class TestZendeskSunshineTransport:
def test_normalize_subdomain(self, _name: str, raw: str, expected: str) -> None:
assert normalize_subdomain(raw) == expected
- def test_get_base_url(self) -> None:
- assert get_base_url("nibbles") == BASE_URL
- assert get_base_url("https://nibbles.zendesk.com") == BASE_URL
+ @parameterized.expand(
+ [
+ ("v1", ZENDESK_SUNSHINE_V1, BASE_URL),
+ ("v2", ZENDESK_SUNSHINE_V2, V2_BASE_URL),
+ ]
+ )
+ def test_get_base_url(self, _name: str, api_version: str, expected: str) -> None:
+ assert get_base_url("nibbles", api_version) == expected
+ assert get_base_url("https://nibbles.zendesk.com", api_version) == expected
+
+ def test_get_base_url_rejects_unknown_version(self) -> None:
+ with pytest.raises(ValueError, match="Unsupported Zendesk Sunshine API version"):
+ get_base_url("nibbles", "v9")
+
+ def test_endpoints_for_version_selects_catalog_and_rejects_unknown(self) -> None:
+ assert endpoints_for_version(ZENDESK_SUNSHINE_V1) is ZENDESK_SUNSHINE_ENDPOINTS
+ assert endpoints_for_version(ZENDESK_SUNSHINE_V2) is ZENDESK_SUNSHINE_V2_ENDPOINTS
+ # The message is matched verbatim by `get_non_retryable_errors`; a bad sync-time pin must
+ # fail non-retryably rather than loop the discovery retry.
+ with pytest.raises(ValueError, match="Unsupported Zendesk Sunshine API version"):
+ endpoints_for_version("v9")
@parameterized.expand(
[
@@ -294,7 +317,7 @@ class TestZendeskSunshineTransport:
session.get.return_value = mock.Mock(status_code=status_code)
with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
- is_valid, message = validate_credentials("nibbles", "token", "[email protected]")
+ is_valid, message = validate_credentials("nibbles", "token", "[email protected]", ZENDESK_SUNSHINE_V1)
assert is_valid is expected_valid
if message_fragment is None:
@@ -303,6 +326,23 @@ class TestZendeskSunshineTransport:
assert message is not None and message_fragment in message
assert session.get.call_args.kwargs["auth"] == ("[email protected]/token", "token")
+ @parameterized.expand(
+ [
+ ("v1", ZENDESK_SUNSHINE_V1, f"{BASE_URL}objects/types"),
+ ("v2", ZENDESK_SUNSHINE_V2, f"{V2_BASE_URL}custom_objects"),
+ ]
+ )
+ def test_validate_credentials_probes_version_specific_endpoint(
+ self, _name: str, api_version: str, expected_url: str
+ ) -> None:
+ session = mock.MagicMock()
+ session.get.return_value = mock.Mock(status_code=200)
+
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ validate_credentials("nibbles", "token", "[email protected]", api_version)
+
+ assert session.get.call_args.args[0] == expected_url
+
def test_list_object_type_keys_follows_pagination(self) -> None:
session = mock.MagicMock()
page1 = mock.Mock(status_code=200)
@@ -315,7 +355,7 @@ class TestZendeskSunshineTransport:
session.get.side_effect = [page1, page2]
with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
- keys = list_object_type_keys("nibbles", "token", "[email protected]")
+ keys = list_object_type_keys("nibbles", "token", "[email protected]", ZENDESK_SUNSHINE_V1)
assert keys == ["product", "order", "shipment"]
second_call = session.get.call_args_list[1]
@@ -355,6 +395,7 @@ class TestZendeskSunshineSourceResponses:
team_id=1,
job_id="job-1",
resumable_source_manager=_FakeResumeManager(), # type: ignore[arg-type]
+ api_version=ZENDESK_SUNSHINE_V1,
)
assert response.name == endpoint
@@ -374,6 +415,7 @@ class TestZendeskSunshineSourceResponses:
team_id=1,
job_id="job-1",
resumable_source_manager=_FakeResumeManager(), # type: ignore[arg-type]
+ api_version=ZENDESK_SUNSHINE_V1,
)
resource = response.items()
@@ -409,6 +451,7 @@ class TestZendeskSunshineIncrementalObjectRecords:
team_id=1,
job_id="job-1",
resumable_source_manager=manager, # type: ignore[arg-type]
+ api_version=ZENDESK_SUNSHINE_V1,
should_use_incremental_field=True,
db_incremental_field_last_value=db_incremental_field_last_value,
)
@@ -474,6 +517,7 @@ class TestZendeskSunshineFrameworkIntegration:
"""
def _source_response(self, endpoint: str, manager: _FakeResumeManager, **kwargs: Any) -> Any:
+ kwargs.setdefault("api_version", ZENDESK_SUNSHINE_V1)
return zendesk_sunshine_source(
subdomain="nibbles",
api_key="token",
@@ -547,3 +591,27 @@ class TestZendeskSunshineFrameworkIntegration:
assert query_request.qs["per_page"] == ["1000"]
# The completed type is checkpointed so a retry skips it.
assert manager.saved[-1]["completed"] == ["product"]
+
+ def test_v2_custom_object_records_fanout_uses_v2_paths_and_envelope(self, requests_mock: Any) -> None:
+ # v2 fans out over the custom objects list (envelope `custom_objects`) into each object's
+ # records under `/api/v2/custom_objects/{key}/records` (envelope `custom_object_records`),
+ # sorted by updated_at since v2 has no server-side updated_at filter.
+ requests_mock.get(
+ f"{V2_BASE_URL}custom_objects",
+ json={"custom_objects": [{"key": "product"}], "links": {"next": None}},
+ )
+ requests_mock.get(
+ f"{V2_BASE_URL}custom_objects/product/records",
+ json={
+ "custom_object_records": [{"id": "1", "updated_at": "2026-01-05T00:00:00.000Z"}],
+ "links": {"next": None},
+ },
+ )
+
+ response = self._source_response("custom_object_records", _FakeResumeManager(), api_version=ZENDESK_SUNSHINE_V2)
+ rows = [row for page in _collect_pages(response) for row in page]
+
+ assert rows == [{"id": "1", "updated_at": "2026-01-05T00:00:00.000Z"}]
+ records_request = next(r for r in requests_mock.request_history if "custom_objects/product/records" in r.path)
+ assert records_request.qs["sort"] == ["updated_at"]
+ assert records_request.qs["per_page"] == ["100"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/tests/test_zendesk_sunshine_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/tests/test_zendesk_sunshine_source.py
index 3e38ff1e1810..6687d7cc5ecd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/tests/test_zendesk_sunshine_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/tests/test_zendesk_sunshine_source.py
@@ -1,6 +1,10 @@
+import datetime
+
import pytest
from unittest import mock
+from parameterized import parameterized
+
from posthog.schema import (
DataWarehouseSourceCategory,
ReleaseStatus,
@@ -11,7 +15,11 @@ from posthog.schema import (
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.zendesksunshine import (
ZendeskSunshineSourceConfig,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.settings import (
+ ENDPOINTS_BY_VERSION,
+ ZENDESK_SUNSHINE_V1,
+ ZENDESK_SUNSHINE_V2,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.source import (
ZendeskSunshineSource,
)
@@ -53,18 +61,25 @@ class TestZendeskSunshineSource:
assert fields["email_address"].type == SourceFieldInputConfigType.EMAIL
assert all(f.required for f in fields.values())
- def test_get_schemas_endpoints(self) -> None:
+ @parameterized.expand([("v1", ZENDESK_SUNSHINE_V1), ("v2", ZENDESK_SUNSHINE_V2)])
+ def test_get_schemas_returns_version_table_set(self, _name: str, api_version: str) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, api_version=api_version)
+ assert {s.name for s in schemas} == set(ENDPOINTS_BY_VERSION[api_version])
+
+ def test_get_schemas_defaults_to_v2_table_set(self) -> None:
+ # No pin resolves to default_version (v2); discovery of a NULL-pinned source must not fall
+ # back to the legacy v1 catalog.
schemas = self.source.get_schemas(self.config, self.team_id)
- assert {s.name for s in schemas} == set(ENDPOINTS)
+ assert {s.name for s in schemas} == set(ENDPOINTS_BY_VERSION[ZENDESK_SUNSHINE_V2])
- def test_get_schemas_incremental_semantics(self) -> None:
- schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ def test_get_schemas_v1_object_records_are_merge_incremental(self) -> None:
+ schemas = {
+ s.name: s for s in self.source.get_schemas(self.config, self.team_id, api_version=ZENDESK_SUNSHINE_V1)
+ }
- # Only object records have a server-side timestamp filter (the `objects/query`
- # endpoint's `_updated_at` range); everything else is full refresh.
+ # v1 object records sync incrementally via the `objects/query` `_updated_at` range; its
+ # inclusive lower bound re-fetches boundary rows, so only merge (dedupes on `id`) is offered.
assert schemas["object_records"].supports_incremental is True
- # The inclusive `_updated_at.start` window re-fetches boundary rows each sync, so only
- # merge (which dedupes on `id`) is offered — append would duplicate those rows.
assert schemas["object_records"].supports_append is False
assert [f["field"] for f in schemas["object_records"].incremental_fields] == ["updated_at"]
@@ -72,13 +87,36 @@ class TestZendeskSunshineSource:
assert schemas[name].supports_incremental is False, name
assert schemas[name].incremental_fields == [], name
+ def test_get_schemas_v2_records_are_full_refresh(self) -> None:
+ # The v2 records list endpoint has no server-side updated_at filter, so no v2 table is
+ # incremental.
+ schemas = self.source.get_schemas(self.config, self.team_id, api_version=ZENDESK_SUNSHINE_V2)
+ for schema in schemas:
+ assert schema.supports_incremental is False, schema.name
+ assert schema.incremental_fields == [], schema.name
+
def test_get_schemas_filtered_by_names(self) -> None:
- schemas = self.source.get_schemas(self.config, self.team_id, names=["object_records"])
+ schemas = self.source.get_schemas(
+ self.config, self.team_id, names=["object_records"], api_version=ZENDESK_SUNSHINE_V1
+ )
assert [s.name for s in schemas] == ["object_records"]
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_get_schemas_rejects_unsupported_version(self) -> None:
+ with pytest.raises(ValueError, match="Unsupported Zendesk Sunshine API version"):
+ self.source.get_schemas(self.config, self.team_id, api_version="v9")
+
+ def test_versions_declare_deprecated_v1_with_sunset(self) -> None:
+ assert self.source.supported_versions == (ZENDESK_SUNSHINE_V1, ZENDESK_SUNSHINE_V2)
+ assert self.source.default_version == ZENDESK_SUNSHINE_V2
+ deprecation = self.source.get_version_deprecation(ZENDESK_SUNSHINE_V1)
+ assert deprecation is not None
+ assert deprecation.sunset_at == datetime.date(2026, 6, 30)
+ # The default must never be deprecated — new sources are stamped with it.
+ assert self.source.get_version_deprecation(ZENDESK_SUNSHINE_V2) is None
+
@pytest.mark.parametrize(
"observed_error",
[
@@ -119,7 +157,18 @@ class TestZendeskSunshineSource:
result = self.source.validate_credentials(self.config, self.team_id)
assert result == (True, None)
- mock_validate.assert_called_once_with("nibbles", "zendesk-token", "[email protected]")
+ # No pin → resolves to default_version (v2), so a new source validates against v2.
+ mock_validate.assert_called_once_with("nibbles", "zendesk-token", "[email protected]", ZENDESK_SUNSHINE_V2)
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.source.validate_zendesk_sunshine_credentials"
+ )
+ def test_validate_credentials_plumbs_pinned_version(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.return_value = (True, None)
+
+ self.source.validate_credentials(self.config, self.team_id, api_version=ZENDESK_SUNSHINE_V1)
+
+ mock_validate.assert_called_once_with("nibbles", "zendesk-token", "[email protected]", ZENDESK_SUNSHINE_V1)
def test_get_resumable_source_manager_binds_resume_config(self) -> None:
inputs = mock.MagicMock()
@@ -136,6 +185,7 @@ class TestZendeskSunshineSource:
inputs.job_id = "job-1"
inputs.should_use_incremental_field = True
inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ inputs.api_version = ZENDESK_SUNSHINE_V1
manager = mock.MagicMock()
self.source.source_for_pipeline(self.config, manager, inputs)
@@ -148,6 +198,8 @@ class TestZendeskSunshineSource:
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"
+ # The resolved source pin reaches the request layer.
+ assert kwargs["api_version"] == ZENDESK_SUNSHINE_V1
@mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.source.zendesk_sunshine_source"
@@ -164,4 +216,6 @@ class TestZendeskSunshineSource:
def test_canonical_descriptions_cover_endpoints(self) -> None:
descriptions = self.source.get_canonical_descriptions()
- assert set(descriptions.keys()) == set(ENDPOINTS)
+ # Descriptions are keyed by schema name and version-blind, so they must cover both catalogs.
+ expected = set(ENDPOINTS_BY_VERSION[ZENDESK_SUNSHINE_V1]) | set(ENDPOINTS_BY_VERSION[ZENDESK_SUNSHINE_V2])
+ assert set(descriptions.keys()) == expected
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/zendesk_sunshine.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/zendesk_sunshine.py
index e697a284f348..58155c2906b8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/zendesk_sunshine.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk_sunshine/zendesk_sunshine.py
@@ -31,15 +31,22 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk_sunshine.settings import (
+ BASE_PATH_BY_VERSION,
DEFAULT_PAGE_SIZE,
DEFAULT_QUERY_WINDOW_START,
MAX_PAGES_PER_QUERY_WINDOW,
QUERY_PATH,
RECORDS_PAGE_SIZE,
- ZENDESK_SUNSHINE_ENDPOINTS,
+ ZENDESK_SUNSHINE_V1,
+ ZENDESK_SUNSHINE_V2,
ZendeskSunshineEndpointConfig,
+ endpoints_for_version,
)
+# The credential probe hits one reachable list endpoint per version — the object-type catalog,
+# which every account with the API activated can read.
+_VALIDATE_PROBE_PATH = {ZENDESK_SUNSHINE_V1: "objects/types", ZENDESK_SUNSHINE_V2: "custom_objects"}
+
@dataclasses.dataclass
class ZendeskSunshineResumeConfig:
@@ -68,8 +75,12 @@ def normalize_subdomain(subdomain: str) -> str:
return re.sub(r"\.zendesk\.com$", "", subdomain, flags=re.IGNORECASE)
-def get_base_url(subdomain: str) -> str:
- return f"https://{normalize_subdomain(subdomain)}.zendesk.com/api/sunshine/"
+def get_base_url(subdomain: str, api_version: str) -> str:
+ try:
+ base_path = BASE_PATH_BY_VERSION[api_version]
+ except KeyError as e:
+ raise ValueError(f"Unsupported Zendesk Sunshine API version: {api_version!r}") from e
+ return f"https://{normalize_subdomain(subdomain)}.zendesk.com/{base_path}"
def to_query_datetime(value: Any) -> str | None:
@@ -176,9 +187,9 @@ class SunshineObjectQueryPaginator(SunshineLinksPaginator):
self._pages_in_window = int(state.get("pages_in_window") or 0)
-def _client_config(subdomain: str, api_key: str, email_address: str) -> ClientConfig:
+def _client_config(subdomain: str, api_key: str, email_address: str, api_version: str) -> ClientConfig:
return {
- "base_url": get_base_url(subdomain),
+ "base_url": get_base_url(subdomain, api_version),
"auth": {
"type": "http_basic",
# Zendesk API token auth requires the `{email}/token` username form.
@@ -198,9 +209,9 @@ def _top_level_resource(endpoint_config: ZendeskSunshineEndpointConfig, base_url
"write_disposition": "replace",
"endpoint": {
"path": endpoint_config.path,
- "params": {"per_page": endpoint_config.page_size},
+ "params": {"per_page": endpoint_config.page_size, **endpoint_config.extra_params},
"paginator": SunshineLinksPaginator(base_url),
- "data_selector": "data",
+ "data_selector": endpoint_config.data_selector,
},
"table_format": "delta",
}
@@ -221,10 +232,11 @@ def _fanout_resources(
"field": endpoint_config.resolve_field,
},
}
+ child_params.update(endpoint_config.extra_params)
child_endpoint: Endpoint = {
"path": endpoint_config.path,
"params": child_params,
- "data_selector": "data",
+ "data_selector": endpoint_config.data_selector,
}
if endpoint_config.single_page:
child_endpoint["paginator"] = SinglePagePaginator()
@@ -284,9 +296,9 @@ def _make_resume_hook(
return save_checkpoint
-def list_object_type_keys(subdomain: str, api_key: str, email_address: str) -> list[str]:
+def list_object_type_keys(subdomain: str, api_key: str, email_address: str, api_version: str) -> list[str]:
"""Fetch every legacy object type key, following `links.next` pagination."""
- base_url = get_base_url(subdomain)
+ base_url = get_base_url(subdomain, api_version)
session = make_tracked_session(redact_values=(api_key,), headers={"Accept": "application/json"})
session.auth = (f"{email_address}/token", api_key)
@@ -312,6 +324,7 @@ def _object_records_incremental(
job_id: str,
db_incremental_field_last_value: Optional[Any],
resumable_source_manager: ResumableSourceManager[ZendeskSunshineResumeConfig],
+ api_version: str,
) -> Iterator[list[dict[str, Any]]]:
"""Incremental object records: one `objects/query` walk per object type.
@@ -319,8 +332,8 @@ def _object_records_incremental(
shape by hand: completed types are skipped, and the in-progress type resumes from its
saved paginator snapshot.
"""
- base_url = get_base_url(subdomain)
- client_config = _client_config(subdomain, api_key, email_address)
+ base_url = get_base_url(subdomain, api_version)
+ client_config = _client_config(subdomain, api_key, email_address, api_version)
resume_state = _load_resume_state(resumable_source_manager) or {}
# Pin the query window across retries: the pipeline advances the incremental watermark
@@ -347,7 +360,7 @@ def _object_records_incremental(
)
)
- for type_key in list_object_type_keys(subdomain, api_key, email_address):
+ for type_key in list_object_type_keys(subdomain, api_key, email_address, api_version):
if type_key in completed:
continue
initial_paginator_state = current_child_state if type_key == current_key else None
@@ -382,11 +395,13 @@ def zendesk_sunshine_source(
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[ZendeskSunshineResumeConfig],
+ api_version: str,
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
- endpoint_config = ZENDESK_SUNSHINE_ENDPOINTS[endpoint]
- base_url = get_base_url(subdomain)
+ endpoints = endpoints_for_version(api_version)
+ endpoint_config = endpoints[endpoint]
+ base_url = get_base_url(subdomain, api_version)
items: Callable[[], Iterable[Any]]
if endpoint_config.name == "object_records" and should_use_incremental_field:
@@ -400,13 +415,14 @@ def zendesk_sunshine_source(
job_id,
db_incremental_field_last_value,
resumable_source_manager,
+ api_version,
)
items = incremental_items
elif endpoint_config.fanout_parent is not None:
- parent_config = ZENDESK_SUNSHINE_ENDPOINTS[endpoint_config.fanout_parent]
+ parent_config = endpoints[endpoint_config.fanout_parent]
config: RESTAPIConfig = {
- "client": _client_config(subdomain, api_key, email_address),
+ "client": _client_config(subdomain, api_key, email_address, api_version),
"resource_defaults": {},
"resources": _fanout_resources(endpoint_config, parent_config, base_url),
}
@@ -425,7 +441,7 @@ def zendesk_sunshine_source(
items = lambda: dependent_resource # noqa: E731
else:
top_level_config: RESTAPIConfig = {
- "client": _client_config(subdomain, api_key, email_address),
+ "client": _client_config(subdomain, api_key, email_address, api_version),
"resource_defaults": {},
"resources": [_top_level_resource(endpoint_config, base_url)],
}
@@ -454,10 +470,10 @@ def zendesk_sunshine_source(
return response
-def validate_credentials(subdomain: str, api_key: str, email_address: str) -> tuple[bool, str | None]:
+def validate_credentials(subdomain: str, api_key: str, email_address: str, api_version: str) -> tuple[bool, str | None]:
session = make_tracked_session(redact_values=(api_key,), headers={"Accept": "application/json"})
response = session.get(
- urljoin(get_base_url(subdomain), "objects/types"),
+ urljoin(get_base_url(subdomain, api_version), _VALIDATE_PROBE_PATH[api_version]),
params={"per_page": 1},
auth=(f"{email_address}/token", api_key),
timeout=30,
@@ -471,7 +487,7 @@ def validate_credentials(subdomain: str, api_key: str, email_address: str) -> tu
)
if response.status_code in (403, 404):
return False, (
- "The Zendesk Sunshine (legacy custom objects) API is not available for this account. "
- "Check that legacy custom objects are activated in Admin Center and that your plan supports them."
+ "The Zendesk custom objects API is not available for this account. "
+ "Check that custom objects are activated in Admin Center and that your plan supports them."
)
- return False, f"Zendesk Sunshine returned an unexpected response (HTTP {response.status_code})"
+ return False, f"Zendesk returned an unexpected response (HTTP {response.status_code})"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/source.py
index fb1f59d18767..7fc1301dde0d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/source.py
@@ -15,7 +15,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
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.base import (
+ FieldType,
+ ResumableSource,
+ VersionDeprecation,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
)
@@ -51,6 +55,12 @@ class ZonkaFeedbackSource(ResumableSource[ZonkaFeedbackSourceConfig, ZonkaFeedba
supported_versions = (ZONKA_API_VERSION_V1, ZONKA_API_VERSION_V2_1)
default_version = ZONKA_API_VERSION_V2_1
+ # Zonka deprecated its older API generation (vendor "API 2.0", docs.api2.zonkafeedback.com) in
+ # favor of the current v2.1 API; no sunset date is published. Our legacy `v1` label is the
+ # pre-versioning placeholder that already resolves to the current v2.1 host (apis.zonkafeedback.com),
+ # so it stays supported for existing pins but carries the flag that fires the generic in-product
+ # deprecation warning.
+ deprecated_versions = (VersionDeprecation(version=ZONKA_API_VERSION_V1, sunset_at=None),)
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/tests/test_zonka_feedback_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/tests/test_zonka_feedback_source.py
index 9759d564520d..c26c2fb3aae3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/tests/test_zonka_feedback_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zonka_feedback/tests/test_zonka_feedback_source.py
@@ -159,6 +159,14 @@ class TestZonkaFeedbackSource:
assert self.source.resolve_api_version(None) == ZONKA_API_VERSION_V2_1
assert self.source.resolve_api_version(ZONKA_API_VERSION_V1) == ZONKA_API_VERSION_V1
+ def test_v1_is_deprecated_without_sunset_and_v2_1_is_not(self) -> None:
+ # Zonka published no sunset date for its older API generation, so the legacy v1 label is
+ # flagged deprecated with sunset_at=None; the default v2.1 must never be deprecated.
+ deprecation = self.source.get_version_deprecation(ZONKA_API_VERSION_V1)
+ assert deprecation is not None
+ assert deprecation.sunset_at is None
+ assert self.source.get_version_deprecation(ZONKA_API_VERSION_V2_1) is None
+
@mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.zonka_feedback.source.zonka_feedback_source"
)