:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse_sources): support Fleetio API version 2025-05-05 (#74161)
Tom Owerscd0bf8a3042c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/fleetio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/fleetio.pyindex 0ac543913ce4..18180993b919 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/fleetio.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/fleetio.py@@ -21,17 +21,57 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.fleetio.seFleetioEndpointConfig,)-FLEETIO_BASE_URL = "https://secure.fleetio.com/api/v1"-# Pin a modern date version explicitly. A Fleetio API key is locked to whatever version was current-# when it was created, but the `X-Api-Version` header overrides that lock per request. 2024-06-30 is-# the version where every index endpoint gained cursor pagination + `filter`/`sort`, while still-# living under the `/api/v1` path (integer paths are only dropped from 2025-05-05 onward). Pinning it-# means we get one consistent pagination/filtering contract regardless of the key's locked version.+FLEETIO_API_HOST = "https://secure.fleetio.com"++# A Fleetio API key is locked to whatever date version was current when it was created, but the+# `X-Api-Version` header overrides that lock per request. We pin a modern date version explicitly so+# every index endpoint serves the same cursor-pagination + `filter`/`sort` contract regardless of the+# key's locked version. Two labels are supported:+# "v1" -> the 2024-06-30 date version, served under the integer `/api/v1` path.+# "2025-05-05" -> the same pagination/filter contract, but Fleetio drops the integer path segment+# from this version onward (resources move to `/api/{resource}`).+# See https://developer.fleetio.com/docs/overview/versioning.+FLEETIO_LEGACY_VERSION = "v1"+FLEETIO_VERSION_2025_05_05 = "2025-05-05"++# Oldest -> newest. `FleetioSource` declares these as its supported versions and defaults to the last.+SUPPORTED_VERSIONS = (FLEETIO_LEGACY_VERSION, FLEETIO_VERSION_2025_05_05)+DEFAULT_VERSION = SUPPORTED_VERSIONS[-1]++# Kept for the legacy "v1" wire contract's `X-Api-Version` value (the label and header diverge only+# for that label). Referenced by tests as the header the "v1" pin sends.FLEETIO_API_VERSION = "2024-06-30"++[email protected](frozen=True)+class _VersionContract:+ base_url: str+ version_header: str+++# Maps every supported label to the wire contract it selects. Coverage is exhaustive by construction+# (`_resolve_contract` raises on an unmapped pin) — never fall through to a default, which would send+# no version header and silently track "latest", the drift versioning exists to prevent.+_VERSION_CONTRACTS: dict[str, _VersionContract] = {+ FLEETIO_LEGACY_VERSION: _VersionContract(base_url=f"{FLEETIO_API_HOST}/api/v1", version_header=FLEETIO_API_VERSION),+ FLEETIO_VERSION_2025_05_05: _VersionContract(+ base_url=f"{FLEETIO_API_HOST}/api", version_header=FLEETIO_VERSION_2025_05_05+ ),+}++# Base URL of the legacy contract; retained as a module constant for readability at call sites.+FLEETIO_BASE_URL = _VERSION_CONTRACTS[FLEETIO_LEGACY_VERSION].base_urlPER_PAGE = 100DEFAULT_INCREMENTAL_FIELD = "updated_at"+def _resolve_contract(api_version: str) -> _VersionContract:+ try:+ return _VERSION_CONTRACTS[api_version]+ except KeyError:+ raise ValueError(f"Unsupported Fleetio API version pin: {api_version!r}")++class FleetioAuth(AuthConfigBase):"""Fleetio authenticates with two separate headers, not one.@@ -55,11 +95,11 @@ class FleetioAuth(AuthConfigBase):return tuple(value for value in (self.api_key, self.account_token) if value)-def _non_secret_headers() -> dict[str, str]:+def _non_secret_headers(version_header: str) -> dict[str, str]:# Only the non-secret version/accept headers live here; the credentials go through FleetioAuth so# their values are registered for redaction. Pinning the version is what guarantees the# cursor-pagination + filter/sort contract.- return {"X-Api-Version": FLEETIO_API_VERSION, "Accept": "application/json"}+ return {"X-Api-Version": version_header, "Accept": "application/json"}def _format_incremental_value(value: Any) -> str:@@ -111,15 +151,17 @@ class FleetioResumeConfig:start_cursor: str | None = None-def validate_credentials(api_key: str, account_token: str) -> bool:- # Probe a cheap index endpoint; Fleetio API keys are account-scoped (no per-endpoint scopes), so- # one 200 confirms both headers are genuine. Both credentials are redacted from logged URLs and- # captured samples — `Account-Token` is a connector-specific header name the generic auth scrubbers- # don't recognise, so value-based redaction is required to keep it out of HTTP telemetry.+def validate_credentials(api_key: str, account_token: str, api_version: str) -> bool:+ # Probe a cheap index endpoint under the resolved version so the probe exercises the same base+ # path/version the source will sync with. Fleetio API keys are account-scoped (no per-endpoint+ # scopes), so one 200 confirms both headers are genuine. Both credentials are redacted from logged+ # URLs and captured samples — `Account-Token` is a connector-specific header name the generic auth+ # scrubbers don't recognise, so value-based redaction is required to keep it out of HTTP telemetry.+ contract = _resolve_contract(api_version)ok, _status = validate_via_probe(lambda: make_tracked_session(redact_values=(api_key, account_token)),- f"{FLEETIO_BASE_URL}/vehicles?per_page=1",- headers=_non_secret_headers(),+ f"{contract.base_url}/vehicles?per_page=1",+ headers=_non_secret_headers(contract.version_header),auth=FleetioAuth(api_key, account_token),)return ok@@ -132,11 +174,13 @@ def fleetio_source(team_id: int,job_id: str,resumable_source_manager: ResumableSourceManager[FleetioResumeConfig],+ api_version: str = DEFAULT_VERSION,should_use_incremental_field: bool = False,db_incremental_field_last_value: Optional[Any] = None,incremental_field: str | None = None,) -> SourceResponse:config = FLEETIO_ENDPOINTS[endpoint]+ contract = _resolve_contract(api_version)params = _build_base_params(config, should_use_incremental_field, db_incremental_field_last_value, incremental_field@@ -144,8 +188,8 @@ def fleetio_source(rest_config: RESTAPIConfig = {"client": {- "base_url": FLEETIO_BASE_URL,- "headers": _non_secret_headers(),+ "base_url": contract.base_url,+ "headers": _non_secret_headers(contract.version_header),"auth": FleetioAuth(api_key, account_token),# Every index endpoint returns the cursor envelope ({"records": [...], "next_cursor": ...});# the cursor is carried forward as the `start_cursor` query param.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/source.pyindex 7acf96677b78..84b9a2ab5e42 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/source.py@@ -24,6 +24,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.schbuild_endpoint_schemas,)from products.warehouse_sources.backend.temporal.data_imports.sources.fleetio.fleetio import (+ DEFAULT_VERSION,+ SUPPORTED_VERSIONS,FleetioResumeConfig,fleetio_source,validate_credentials as validate_fleetio_credentials,@@ -40,9 +42,9 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass FleetioSource(ResumableSource[FleetioSourceConfig, FleetioResumeConfig]):- supported_versions = ("v1",)- default_version = "v1"- api_docs_url = "https://developer.fleetio.com"+ supported_versions = SUPPORTED_VERSIONS+ default_version = DEFAULT_VERSION+ api_docs_url = "https://developer.fleetio.com/docs/overview/versioning"lists_tables_without_credentials = True # static endpoint catalog — safe for public docs@@ -127,7 +129,7 @@ Create an API key under **Account Menu → Account Settings → API Keys** in Flschema_name: Optional[str] = None,api_version: str | None = None,) -> tuple[bool, str | None]:- if validate_fleetio_credentials(config.api_key, config.account_token):+ if validate_fleetio_credentials(config.api_key, config.account_token, self.resolve_api_version(api_version)):return True, Nonereturn False, "Invalid Fleetio API key or account token"@@ -147,6 +149,7 @@ Create an API key under **Account Menu → Account Settings → API Keys** in Flendpoint=inputs.schema_name,team_id=inputs.team_id,job_id=inputs.job_id,+ api_version=self.resolve_api_version(inputs.api_version),resumable_source_manager=resumable_source_manager,should_use_incremental_field=inputs.should_use_incremental_field,db_incremental_field_last_value=inputs.db_incremental_field_last_valuediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/tests/test_fleetio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/tests/test_fleetio.pyindex 045e219ea63f..fe05ed218c97 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/tests/test_fleetio.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/tests/test_fleetio.py@@ -11,6 +11,8 @@ from requests.structures import CaseInsensitiveDictfrom products.warehouse_sources.backend.temporal.data_imports.sources.fleetio.fleetio import (FLEETIO_API_VERSION,+ FLEETIO_LEGACY_VERSION,+ FLEETIO_VERSION_2025_05_05,FleetioAuth,FleetioResumeConfig,_build_base_params,@@ -208,13 +210,42 @@ class TestPagination:assert params[0]["sort[updated_at]"] == "asc"assert params[0]["filter[updated_at][gt]"] == "2026-03-04T02:58:14+00:00"+ @parameterized.expand(+ [+ # The "v1" pin sends the 2024-06-30 date version under the integer `/api/v1` path;+ # 2025-05-05 drops the integer segment and moves resources to `/api/{resource}`.+ (FLEETIO_LEGACY_VERSION, FLEETIO_API_VERSION, "https://secure.fleetio.com/api/v1/vehicles"),+ (FLEETIO_VERSION_2025_05_05, "2025-05-05", "https://secure.fleetio.com/api/vehicles"),+ ]+ )@mock.patch(CLIENT_SESSION_PATCH)- def test_version_header_is_set_on_session(self, MockSession) -> None:+ def test_version_selects_header_and_base_path(+ self, api_version: str, expected_header: str, expected_url: str, MockSession+ ) -> None:session = MockSession.return_value- _wire(session, [_response([{"id": 1}], None)])+ session.headers = {}+ request_urls: list[str] = []++ def _prepare(request: Any) -> mock.MagicMock:+ request_urls.append(request.url)+ prepared = mock.MagicMock()+ prepared.url = expected_url+ return prepared++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = [_response([{"id": 1}], None)]++ _rows(_source(_make_manager(), api_version=api_version))- _rows(_source(_make_manager()))- assert session.headers.get("X-Api-Version") == FLEETIO_API_VERSION+ assert session.headers.get("X-Api-Version") == expected_header+ assert request_urls[0] == expected_url++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_unsupported_version_pin_raises(self, MockSession) -> None:+ # A pin outside the supported map must fail loudly rather than fall through to no version+ # header (which would silently track "latest").+ with pytest.raises(ValueError, match="Unsupported Fleetio API version"):+ _source(_make_manager(), api_version="1999-01-01")@mock.patch(CLIENT_SESSION_PATCH)def test_bare_list_body_fails_loudly(self, MockSession) -> None:@@ -232,9 +263,28 @@ class TestValidateCredentials:@mock.patch(FLEETIO_SESSION_PATCH)def test_status_maps_to_bool(self, mock_session, status_code: int, expected: bool) -> None:mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)- assert validate_credentials("k", "a") is expected+ assert validate_credentials("k", "a", FLEETIO_VERSION_2025_05_05) is expected++ @pytest.mark.parametrize(+ "api_version,expected_header,expected_url",+ [+ (FLEETIO_LEGACY_VERSION, FLEETIO_API_VERSION, "https://secure.fleetio.com/api/v1/vehicles?per_page=1"),+ (FLEETIO_VERSION_2025_05_05, "2025-05-05", "https://secure.fleetio.com/api/vehicles?per_page=1"),+ ],+ )+ @mock.patch(FLEETIO_SESSION_PATCH)+ def test_probe_targets_version_base_path(+ self, mock_session, api_version: str, expected_header: str, expected_url: str+ ) -> None:+ # The probe must hit the same base path/version the source will sync with, so a new source+ # created on the default version validates against the endpoints it will actually read.+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ validate_credentials("k", "a", api_version)+ call = mock_session.return_value.get.call_args+ assert call.args[0] == expected_url+ assert call.kwargs["headers"]["X-Api-Version"] == expected_header@mock.patch(FLEETIO_SESSION_PATCH)def test_network_error_is_not_valid(self, mock_session) -> None:mock_session.return_value.get.side_effect = Exception("boom")- assert validate_credentials("k", "a") is False+ assert validate_credentials("k", "a", FLEETIO_VERSION_2025_05_05) is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/tests/test_fleetio_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/tests/test_fleetio_source.pyindex 14d667b7b49b..820ae934dbb4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/tests/test_fleetio_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/tests/test_fleetio_source.py@@ -67,14 +67,36 @@ class TestFleetioSource:assert "Full refresh" in tables["vehicles"]["sync_methods"]assert "Incremental" in tables["vehicles"]["sync_methods"]+ def test_version_declarations(self) -> None:+ # New sources start on the newest stable version; the legacy pin stays supported so existing+ # rows keep syncing unchanged.+ assert self.source.default_version == "2025-05-05"+ assert set(self.source.supported_versions) == {"v1", "2025-05-05"}+@pytest.mark.parametrize("probe_result,expected_valid", [(True, True), (False, False)])def test_validate_credentials(self, probe_result: bool, expected_valid: bool, monkeypatch: Any) -> None:- monkeypatch.setattr(source_module, "validate_fleetio_credentials", lambda api_key, account_token: probe_result)+ monkeypatch.setattr(+ source_module, "validate_fleetio_credentials", lambda api_key, account_token, api_version: probe_result+ )config = FleetioSourceConfig(api_key="k", account_token="a")valid, error = self.source.validate_credentials(config, self.team_id)assert valid is expected_validassert (error is None) is expected_valid+ @pytest.mark.parametrize("pin,expected", [(None, "2025-05-05"), ("v1", "v1"), ("2025-05-05", "2025-05-05")])+ def test_validate_credentials_probes_resolved_version(+ self, pin: str | None, expected: str, monkeypatch: Any+ ) -> None:+ captured: dict[str, Any] = {}+ monkeypatch.setattr(+ source_module,+ "validate_fleetio_credentials",+ lambda api_key, account_token, api_version: captured.update(api_version=api_version) or True,+ )+ config = FleetioSourceConfig(api_key="k", account_token="a")+ self.source.validate_credentials(config, self.team_id, api_version=pin)+ assert captured["api_version"] == expected+@parameterized.expand([("unauthorized", "401 Client Error: Unauthorized for url: https://secure.fleetio.com/api/v1/vehicles"),@@ -114,6 +136,7 @@ class TestFleetioSource:manager = MagicMock()inputs = MagicMock()inputs.schema_name = "vehicles"+ inputs.api_version = "v1"inputs.should_use_incremental_field = Trueinputs.db_incremental_field_last_value = "2026-01-01"inputs.incremental_field = "updated_at"@@ -124,11 +147,27 @@ class TestFleetioSource:assert captured["api_key"] == "my-key"assert captured["account_token"] == "my-acct"assert captured["endpoint"] == "vehicles"+ assert captured["api_version"] == "v1"assert captured["resumable_source_manager"] is managerassert captured["should_use_incremental_field"] is Trueassert captured["db_incremental_field_last_value"] == "2026-01-01"assert captured["incremental_field"] == "updated_at"+ @pytest.mark.parametrize("pin,expected", [(None, "2025-05-05"), ("v1", "v1"), ("2025-05-05", "2025-05-05")])+ def test_source_for_pipeline_resolves_api_version(self, pin: str | None, expected: str, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}+ monkeypatch.setattr(source_module, "fleetio_source", lambda **kwargs: captured.update(kwargs))++ config = FleetioSourceConfig(api_key="k", account_token="a")+ inputs = MagicMock()+ inputs.schema_name = "vehicles"+ inputs.api_version = pin+ inputs.should_use_incremental_field = False+ inputs.incremental_field = None++ self.source.source_for_pipeline(config, MagicMock(), inputs)+ assert captured["api_version"] == expected+def test_source_for_pipeline_drops_last_value_when_not_incremental(self, monkeypatch: Any) -> None:captured: dict[str, Any] = {}monkeypatch.setattr(source_module, "fleetio_source", lambda **kwargs: captured.update(kwargs))