:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement fleetio import source (#66752)
Tom Owersb196c720f2d2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex f9f3ea9819fc..718b91c2ccdc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -121,6 +121,7 @@ the row lists both.| financial_modelling | HTTP | requests | ✅ || finnhub | HTTP | requests | ✅ || finnworlds | HTTP | requests | ✅ |+| fleetio | HTTP | requests | ✅ || front | HTTP | requests | ✅ || fullstory | HTTP | requests | ✅ || github | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |@@ -398,7 +399,6 @@ doesn't conflict with concurrent PRs.- firebase- firebolt- firehydrant-- fleetio- flexmail- flexport- float_appdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/canonical_descriptions.pynew file mode 100644index 000000000000..9e8543ad5815--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/canonical_descriptions.py@@ -0,0 +1,155 @@+"""Canonical, documentation-sourced descriptions for Fleetio endpoints and columns.++Sourced from the official Fleetio API reference (https://developer.fleetio.com/docs/api).+Keyed by the endpoint names in `settings.py` `FLEETIO_ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced Fleetio table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_COMMON_COLUMNS = {+ "id": "Unique identifier for the record in Fleetio.",+ "created_at": "Timestamp when the record was created.",+ "updated_at": "Timestamp when the record was last updated.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "vehicles": {+ "description": "An asset tracked in Fleetio — typically a vehicle or piece of equipment, with its identifying and status details.",+ "docs_url": "https://developer.fleetio.com/docs/api/vehicles",+ "columns": {+ **_COMMON_COLUMNS,+ "name": "Display name of the vehicle.",+ "vin": "Vehicle Identification Number.",+ "make": "Manufacturer of the vehicle.",+ "model": "Model of the vehicle.",+ "year": "Model year of the vehicle.",+ "license_plate": "License plate number.",+ "vehicle_status_name": "Current operational status of the vehicle (e.g. Active, In Shop).",+ "vehicle_type_name": "The vehicle's type/classification.",+ "current_meter_value": "Most recent primary meter reading (e.g. odometer).",+ "secondary_meter_value": "Most recent secondary meter reading (e.g. engine hours).",+ "group_name": "Name of the group the vehicle belongs to.",+ "archived_at": "Timestamp when the vehicle was archived, if applicable.",+ },+ },+ "contacts": {+ "description": "A person in Fleetio — an operator, technician, or other contact who can be assigned to vehicles, work orders, and issues.",+ "docs_url": "https://developer.fleetio.com/docs/api/contacts",+ "columns": {+ **_COMMON_COLUMNS,+ "name": "Full name of the contact.",+ "first_name": "Contact's first name.",+ "last_name": "Contact's last name.",+ "email": "Contact's email address.",+ "group_name": "Name of the group the contact belongs to.",+ "employee": "Whether the contact is an employee.",+ "technician": "Whether the contact is a technician.",+ "archived_at": "Timestamp when the contact was archived, if applicable.",+ },+ },+ "fuel_entries": {+ "description": "A record of fuel purchased or used for a vehicle, including volume, cost, and the meter reading at fill-up.",+ "docs_url": "https://developer.fleetio.com/docs/api/fuel-entries",+ "columns": {+ **_COMMON_COLUMNS,+ "vehicle_id": "Identifier of the vehicle this fuel entry belongs to.",+ "date": "Date and time of the fuel entry.",+ "raw_usage": "Volume of fuel added (in the account's fuel units).",+ "us_gallons": "Volume of fuel added, normalized to US gallons.",+ "total_amount": "Total cost of the fuel entry.",+ "cost_per_unit": "Cost per unit of fuel.",+ "usage_in_gallons": "Fuel usage expressed in gallons.",+ "meter_entry_value": "Meter reading captured at the time of fueling.",+ "fuel_type_name": "The type of fuel used.",+ },+ },+ "meter_entries": {+ "description": "A meter reading for a vehicle (e.g. odometer mileage or engine hours) recorded at a point in time.",+ "docs_url": "https://developer.fleetio.com/docs/api/meter-entries",+ "columns": {+ **_COMMON_COLUMNS,+ "vehicle_id": "Identifier of the vehicle this meter entry belongs to.",+ "value": "The recorded meter value.",+ "date": "Date the meter reading was taken.",+ "meter_type": "Whether the reading is the primary or secondary meter.",+ "void": "Whether the meter entry has been voided.",+ "auto_voided_at": "Timestamp when the entry was automatically voided, if applicable.",+ },+ },+ "service_entries": {+ "description": "A record of maintenance or service performed on a vehicle, including the service tasks completed and their cost.",+ "docs_url": "https://developer.fleetio.com/docs/api/service-entries",+ "columns": {+ **_COMMON_COLUMNS,+ "vehicle_id": "Identifier of the vehicle that was serviced.",+ "completed_at": "Timestamp when the service was completed.",+ "started_at": "Timestamp when the service started.",+ "total_amount_cents": "Total cost of the service entry, in cents.",+ "labor_cost_cents": "Labor cost portion, in cents.",+ "parts_cost_cents": "Parts cost portion, in cents.",+ "meter_entry_value": "Meter reading captured at the time of service.",+ "vendor_name": "Name of the vendor that performed the service.",+ },+ },+ "work_orders": {+ "description": "A work order in Fleetio that groups the issues, service tasks, parts, and labor needed to maintain a vehicle.",+ "docs_url": "https://developer.fleetio.com/docs/api/work-orders",+ "columns": {+ **_COMMON_COLUMNS,+ "vehicle_id": "Identifier of the vehicle the work order is for.",+ "number": "Human-readable work order number.",+ "status_name": "Current status of the work order (e.g. Open, Completed).",+ "issued_at": "Timestamp when the work order was issued.",+ "started_at": "Timestamp when work started.",+ "completed_at": "Timestamp when the work order was completed.",+ "total_amount_cents": "Total cost of the work order, in cents.",+ "vehicle_meter_value": "Meter reading captured for the work order.",+ },+ },+ "issues": {+ "description": "A reported problem or fault for a vehicle that may require service, optionally linked to a work order.",+ "docs_url": "https://developer.fleetio.com/docs/api/issues",+ "columns": {+ **_COMMON_COLUMNS,+ "vehicle_id": "Identifier of the vehicle the issue was reported for.",+ "number": "Human-readable issue number.",+ "summary": "Short summary of the issue.",+ "description": "Detailed description of the issue.",+ "state": "Current state of the issue (e.g. open, resolved, closed).",+ "reported_at": "Timestamp when the issue was reported.",+ "resolved_at": "Timestamp when the issue was resolved, if applicable.",+ "due_date": "Date the issue is due to be addressed.",+ "reported_by_name": "Name of the contact who reported the issue.",+ },+ },+ "parts": {+ "description": "An inventory part in Fleetio used in service entries and work orders, with cost and stocking details.",+ "docs_url": "https://developer.fleetio.com/docs/api/parts",+ "columns": {+ **_COMMON_COLUMNS,+ "number": "Part number.",+ "description": "Description of the part.",+ "manufacturer_part_number": "The manufacturer's part number.",+ "unit_cost_cents": "Cost per unit of the part, in cents.",+ "part_category_name": "Category the part belongs to.",+ "measurement_unit_name": "Unit of measure for the part.",+ "archived_at": "Timestamp when the part was archived, if applicable.",+ },+ },+ "vehicle_assignments": {+ "description": "A record linking a contact (operator) to a vehicle for a period of time.",+ "docs_url": "https://developer.fleetio.com/docs/api/vehicle-assignments",+ "columns": {+ **_COMMON_COLUMNS,+ "vehicle_id": "Identifier of the assigned vehicle.",+ "contact_id": "Identifier of the contact assigned to the vehicle.",+ "started_at": "Timestamp when the assignment started.",+ "ended_at": "Timestamp when the assignment ended, if applicable.",+ "current": "Whether this is the vehicle's current assignment.",+ "comments_count": "Number of comments on the assignment.",+ },+ },+}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.pynew file mode 100644index 000000000000..af5c2a102f81--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/fleetio.py@@ -0,0 +1,274 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.fleetio.settings import (+ FLEETIO_ENDPOINTS,+ FleetioEndpointConfig,+)++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_VERSION = "2024-06-30"+PER_PAGE = 100+DEFAULT_INCREMENTAL_FIELD = "updated_at"++MAX_RETRIES = 5+++class FleetioRetryableError(Exception):+ """Transient 5xx — safe to retry with backoff."""+++class FleetioRateLimitError(Exception):+ """429 Too Many Requests. Carries the server's Retry-After (seconds) so we can honor it."""++ def __init__(self, message: str, retry_after: float | None = None) -> None:+ super().__init__(message)+ self.retry_after = retry_after+++def _get_headers(api_key: str, account_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Token {api_key}",+ "Account-Token": account_token,+ "X-Api-Version": FLEETIO_API_VERSION,+ "Accept": "application/json",+ }+++def _format_incremental_value(value: Any) -> str:+ """Format an incremental cursor value for Fleetio's `filter[...][gt]` parameter.++ Fleetio parses standard ISO 8601 timestamps (Rails `Time.zone.parse`), so isoformat with an+ explicit UTC offset is accepted. Naive datetimes are treated as UTC.+ """+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return aware.isoformat()+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat()+ return str(value)+++def _build_url(base_url: str, params: dict[str, Any]) -> str:+ """Build a URL with an encoded query string.++ The `filter[updated_at][gt]` / `sort[updated_at]` keys contain literal brackets; `urlencode`+ percent-encodes them (and the timestamp's `+`/`:`), which Rack decodes back to brackets on the+ server, so the encoded form is equivalent to the documented literal form.+ """+ if not params:+ return base_url+ return f"{base_url}?{urlencode(params)}"+++def _build_base_params(+ config: FleetioEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> dict[str, Any]:+ """Build the query params reused on every page (the cursor is added per request).++ Sort ascending on the field we checkpoint against so `SourceResponse.sort_mode="asc"` holds and+ the watermark advances correctly: the chosen incremental field when syncing incrementally, else a+ stable field (`created_at`) to keep full-refresh pagination from skipping/duplicating rows as data+ is inserted mid-sync.+ """+ params: dict[str, Any] = {"per_page": PER_PAGE}++ sort_field = (incremental_field if should_use_incremental_field else None) or config.partition_key or "created_at"+ params[f"sort[{sort_field}]"] = "asc"++ if should_use_incremental_field and db_incremental_field_last_value is not None:+ # `filter[<field>][gt]` is the documented server-side timestamp filter for API versions+ # 2024-01-01+ (the `gt` operator mirrors the legacy `q[<field>_gt]` ransack predicate). The+ # cursor envelope carries the active filter forward, so it stays applied on every page rather+ # than only the first — no unbounded history re-walk on incremental syncs. Not yet verified+ # against a live account (no test credentials); see PR notes.+ filter_field = incremental_field or DEFAULT_INCREMENTAL_FIELD+ params[f"filter[{filter_field}][gt]"] = _format_incremental_value(db_incremental_field_last_value)++ return params+++class FleetioResumeConfig:+ # The cursor to start the next page from. None means "start at the first page".+ start_cursor: str | None = None+++def _parse_retry_after(value: str | None) -> float | None:+ if not value:+ return None+ try:+ return float(value)+ except ValueError:+ return None+++def _retry_wait(retry_state: Any) -> float:+ """Honor a 429's Retry-After header when present, else fall back to exponential backoff."""+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, FleetioRateLimitError) and exc.retry_after is not None:+ return exc.retry_after+ return wait_exponential_jitter(initial=1, max=30)(retry_state)+++@retry(+ retry=retry_if_exception_type(+ (FleetioRetryableError, FleetioRateLimitError, requests.ReadTimeout, requests.ConnectionError)+ ),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=_retry_wait,+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict[str, Any]:+ response = session.get(url, headers=headers, timeout=60)++ if response.status_code == 429:+ raise FleetioRateLimitError(+ f"Fleetio API rate limited: url={url}",+ retry_after=_parse_retry_after(response.headers.get("Retry-After")),+ )++ if response.status_code >= 500:+ raise FleetioRetryableError(f"Fleetio API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Fleetio API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ data = response.json()+ if not isinstance(data, dict):+ # With X-Api-Version pinned, every index endpoint returns the cursor envelope+ # ({"records": [...], "next_cursor": ...}). A bare list would mean the version pin was+ # ignored (legacy page-based response); fail loudly rather than silently syncing one page.+ raise FleetioRetryableError(f"Unexpected Fleetio response shape (expected cursor envelope): url={url}")+ return data+++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.+ url = _build_url(f"{FLEETIO_BASE_URL}/vehicles", {"per_page": 1})+ try:+ # Redact both credentials in 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.+ session = make_tracked_session(redact_values=(api_key, account_token))+ response = session.get(url, headers=_get_headers(api_key, account_token), timeout=10)+ return response.status_code == 200+ except Exception:+ return False+++def get_rows(+ api_key: str,+ account_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FleetioResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[Any]:+ config = FLEETIO_ENDPOINTS[endpoint]+ headers = _get_headers(api_key, account_token)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)+ # One session reused across every page so urllib3 keeps the connection alive. Redact both+ # credentials in logged URLs and captured samples — `Account-Token` is a connector-specific+ # header name the generic auth scrubbers don't recognise.+ session = make_tracked_session(redact_values=(api_key, account_token))++ base_params = _build_base_params(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_cursor = resume.start_cursor if resume else None+ if start_cursor:+ logger.debug(f"Fleetio: resuming {endpoint} from cursor={start_cursor}")++ while True:+ params = dict(base_params)+ if start_cursor:+ params["start_cursor"] = start_cursor+ url = _build_url(f"{FLEETIO_BASE_URL}{config.path}", params)++ data = _fetch_page(session, url, headers, logger)+ records = data.get("records", [])+ next_cursor = data.get("next_cursor")++ yielded_this_page = False+ for item in records:+ batcher.batch(item)++ if batcher.should_yield():+ yield batcher.get_table()+ yielded_this_page = True++ # Save state once, AFTER every record on this page has been batched, so a mid-page yield (the+ # 100 MB byte-size limit) can't advance the cursor past records we haven't seen yet. A crash+ # then re-fetches the whole page rather than skipping its tail — merge dedupes on the primary+ # key. Only save when we yielded data and more pages remain.+ if yielded_this_page and next_cursor:+ resumable_source_manager.save_state(FleetioResumeConfig(start_cursor=next_cursor))++ if not next_cursor:+ break+ start_cursor = next_cursor++ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def fleetio_source(+ api_key: str,+ account_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FleetioResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = FLEETIO_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ account_token=account_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=endpoint_config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/settings.pynew file mode 100644index 000000000000..d96d4cb22f4c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/settings.py@@ -0,0 +1,51 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++def _datetime_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++# Every core Fleetio index endpoint exposes `updated_at` (server-managed, monotonic on change) and+# `created_at` (stable). We offer both as incremental cursors and default the partition to `created_at`+# so partitions never rewrite.+_DEFAULT_INCREMENTAL_FIELDS: list[IncrementalField] = [_datetime_field("updated_at"), _datetime_field("created_at")]+++@dataclass+class FleetioEndpointConfig:+ name: str+ path: str+ incremental_fields: list[IncrementalField] = field(default_factory=lambda: list(_DEFAULT_INCREMENTAL_FIELDS))+ # Partition by a stable field (created_at), never updated_at, so partitions don't rewrite each sync.+ partition_key: str | None = "created_at"+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+++# Core data streams a Fleetio user will actually want, cross-referenced against the dltHub Fleetio+# source and the common Airbyte/Fivetran fleet-management stream list. All are top-level index+# endpoints under https://secure.fleetio.com/api/v1 with `id`, `created_at`, and `updated_at`.+FLEETIO_ENDPOINTS: dict[str, FleetioEndpointConfig] = {+ "vehicles": FleetioEndpointConfig(name="vehicles", path="/vehicles"),+ "contacts": FleetioEndpointConfig(name="contacts", path="/contacts"),+ "fuel_entries": FleetioEndpointConfig(name="fuel_entries", path="/fuel_entries"),+ "meter_entries": FleetioEndpointConfig(name="meter_entries", path="/meter_entries"),+ "service_entries": FleetioEndpointConfig(name="service_entries", path="/service_entries"),+ "work_orders": FleetioEndpointConfig(name="work_orders", path="/work_orders"),+ "issues": FleetioEndpointConfig(name="issues", path="/issues"),+ "parts": FleetioEndpointConfig(name="parts", path="/parts"),+ "vehicle_assignments": FleetioEndpointConfig(name="vehicle_assignments", path="/vehicle_assignments"),+}++ENDPOINTS = tuple(FLEETIO_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in FLEETIO_ENDPOINTS.items()+}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 0b093c5841c8..2b05908db8b9 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@@ -1,30 +1,157 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.fleetio.fleetio import (+ FleetioResumeConfig,+ fleetio_source,+ validate_credentials as validate_fleetio_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.fleetio.settings import (+ ENDPOINTS,+ FLEETIO_ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FleetioSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class FleetioSource(SimpleSource[FleetioSourceConfig]):+class FleetioSource(ResumableSource[FleetioSourceConfig, FleetioResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.FLEETIO+ @property+ def connection_host_fields(self) -> list[str]:+ # `account_token` selects which Fleetio account the stored API key is sent to. Editing it on+ # an existing source must force the key to be re-entered — otherwise an editor could retarget+ # the preserved key at another Fleetio account, exposing it across a tenant boundary the user+ # never approved.+ return ["account_token"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.FLEETIO,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Fleetio",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Fleetio API key and account token to pull your Fleetio fleet data into the PostHog Data warehouse.++Create an API key under **Account Menu → Account Settings → API Keys** in Fleetio. Your account token is shown on the same page (it identifies your Fleetio account).""",iconPath="/static/services/fleetio.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/fleetio",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="account_token",+ label="Account token",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.fleetio.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.+ # Retrying can never satisfy a credential problem. Match the stable status text and base+ # host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://secure.fleetio.com": "Your Fleetio API key or account token is invalid or has been revoked. Generate a new API key in your Fleetio account settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://secure.fleetio.com": "Your Fleetio API key does not have permission to read this data. Check the key's permissions in your Fleetio account settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: FleetioSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = FLEETIO_ENDPOINTS[endpoint]+ has_incremental = len(endpoint_config.incremental_fields) > 0+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: FleetioSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_fleetio_credentials(config.api_key, config.account_token):+ return True, None++ return False, "Invalid Fleetio API key or account token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FleetioResumeConfig]:+ return ResumableSourceManager[FleetioResumeConfig](inputs, FleetioResumeConfig)++ def source_for_pipeline(+ self,+ config: FleetioSourceConfig,+ resumable_source_manager: ResumableSourceManager[FleetioResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return fleetio_source(+ api_key=config.api_key,+ account_token=config.account_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/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.pynew file mode 100644index 000000000000..75e614007337--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/tests/test_fleetio.py@@ -0,0 +1,261 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.fleetio import fleetio+from products.warehouse_sources.backend.temporal.data_imports.sources.fleetio.fleetio import (+ FLEETIO_API_VERSION,+ FleetioRateLimitError,+ FleetioResumeConfig,+ _build_base_params,+ _build_url,+ _format_incremental_value,+ _get_headers,+ _parse_retry_after,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.fleetio.settings import FLEETIO_ENDPOINTS+++class TestFormatIncrementalValue:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14+00:00"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14+00:00"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00+00:00"),+ ("string_passthrough", "some-cursor", "some-cursor"),+ ]+ )+ def test_format(self, _name: str, value: object, expected: str) -> None:+ assert _format_incremental_value(value) == expected+++class TestHeaders:+ def test_includes_both_auth_headers_and_pinned_version(self) -> None:+ headers = _get_headers("key123", "acct456")+ assert headers["Authorization"] == "Token key123"+ assert headers["Account-Token"] == "acct456"+ # The version pin is what guarantees the cursor-pagination + filter/sort contract.+ assert headers["X-Api-Version"] == FLEETIO_API_VERSION+++class TestBuildUrl:+ def test_no_params_returns_base(self) -> None:+ assert _build_url("https://x/api", {}) == "https://x/api"++ def test_brackets_and_timestamp_are_encoded(self) -> None:+ url = _build_url(+ "https://x/api/vehicles",+ {"filter[updated_at][gt]": "2026-03-04T02:58:14+00:00", "per_page": 100},+ )+ # urlencode percent-encodes the brackets and the `+`/`:` in the timestamp; Rack decodes+ # them back server-side, so the encoded form is equivalent to the literal documented form.+ assert "filter%5Bupdated_at%5D%5Bgt%5D=2026-03-04T02%3A58%3A14%2B00%3A00" in url+ assert "per_page=100" in url+++class TestBuildBaseParams:+ def test_full_refresh_sorts_by_partition_key_and_has_no_filter(self) -> None:+ params = _build_base_params(+ FLEETIO_ENDPOINTS["vehicles"],+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ incremental_field=None,+ )+ assert params == {"per_page": 100, "sort[created_at]": "asc"}++ def test_incremental_sorts_and_filters_on_chosen_field(self) -> None:+ params = _build_base_params(+ FLEETIO_ENDPOINTS["vehicles"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ incremental_field="updated_at",+ )+ assert params["sort[updated_at]"] == "asc"+ assert params["filter[updated_at][gt]"] == "2026-03-04T02:58:14+00:00"++ def test_incremental_first_sync_has_no_filter_value(self) -> None:+ # First incremental sync has no last value yet — sort, but don't filter (pull everything).+ params = _build_base_params(+ FLEETIO_ENDPOINTS["vehicles"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ incremental_field="updated_at",+ )+ assert params == {"per_page": 100, "sort[updated_at]": "asc"}++ def test_incremental_on_created_at_filters_created_at(self) -> None:+ params = _build_base_params(+ FLEETIO_ENDPOINTS["fuel_entries"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ incremental_field="created_at",+ )+ assert params["sort[created_at]"] == "asc"+ assert params["filter[created_at][gt]"] == "2026-01-01T00:00:00+00:00"+++class TestParseRetryAfter:+ @parameterized.expand(+ [("seconds", "30", 30.0), ("float", "1.5", 1.5), ("blank", None, None), ("garbage", "soon", None)]+ )+ def test_parse(self, _name: str, value: str | None, expected: float | None) -> None:+ assert _parse_retry_after(value) == expected+++class _FakeResumableManager:+ def __init__(self, state: FleetioResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[FleetioResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> FleetioResumeConfig | None:+ return self._state++ def save_state(self, data: FleetioResumeConfig) -> None:+ self.saved.append(data)+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: dict[str, Any],+ **kwargs: Any,+ ) -> tuple[list[dict], list[str]]:+ fetched: list[str] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ fetched.append(url)+ result = pages[url]+ if isinstance(result, Exception):+ raise result+ return result++ monkeypatch.setattr(fleetio, "_fetch_page", fake_fetch)++ rows: list[dict] = []+ for table in get_rows(+ api_key="k",+ account_token="a",+ endpoint="vehicles",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(table.to_pylist())+ return rows, fetched++ def test_paginates_until_next_cursor_is_null(self, monkeypatch: Any) -> None:+ base = "https://secure.fleetio.com/api/v1/vehicles?per_page=100&sort%5Bcreated_at%5D=asc"+ page2 = base + "&start_cursor=CUR2"+ pages = {+ base: {"records": [{"id": 1}, {"id": 2}], "next_cursor": "CUR2"},+ page2: {"records": [{"id": 3}], "next_cursor": None},+ }+ rows, fetched = self._collect(_FakeResumableManager(), monkeypatch, pages)+ assert rows == [{"id": 1}, {"id": 2}, {"id": 3}]+ assert fetched == [base, page2]++ def test_resume_starts_from_saved_cursor(self, monkeypatch: Any) -> None:+ resumed = "https://secure.fleetio.com/api/v1/vehicles?per_page=100&sort%5Bcreated_at%5D=asc&start_cursor=SAVED"+ pages = {resumed: {"records": [{"id": 9}], "next_cursor": None}}+ manager = _FakeResumableManager(FleetioResumeConfig(start_cursor="SAVED"))+ rows, fetched = self._collect(manager, monkeypatch, pages)+ assert rows == [{"id": 9}]+ assert fetched == [resumed]++ def test_saves_state_after_yielding_a_batch_with_more_pages(self, monkeypatch: Any) -> None:+ # Force a yield after every row by capping the batch at one row.+ real_batcher = fleetio.Batcher+ monkeypatch.setattr(+ fleetio,+ "Batcher",+ lambda **kwargs: real_batcher(+ logger=kwargs["logger"], chunk_size=1, chunk_size_bytes=kwargs["chunk_size_bytes"]+ ),+ )+ base = "https://secure.fleetio.com/api/v1/vehicles?per_page=100&sort%5Bcreated_at%5D=asc"+ page2 = base + "&start_cursor=CUR2"+ pages = {+ base: {"records": [{"id": 1}], "next_cursor": "CUR2"},+ page2: {"records": [{"id": 2}], "next_cursor": None},+ }+ manager = _FakeResumableManager()+ self._collect(manager, monkeypatch, pages)+ # State saved with the NEXT page's cursor (so a crash re-yields, never skips), and only while+ # more pages remain — the final page (next_cursor=None) saves nothing.+ assert manager.saved == [FleetioResumeConfig(start_cursor="CUR2")]++ def test_saves_state_once_per_page_even_when_yielding_mid_page(self, monkeypatch: Any) -> None:+ # Multiple yields within a single page (chunk_size=1, two records) must save the cursor only+ # once, AFTER the whole page is batched — saving on the first mid-page yield would advance the+ # cursor past the page's remaining records and skip them on resume.+ real_batcher = fleetio.Batcher+ monkeypatch.setattr(+ fleetio,+ "Batcher",+ lambda **kwargs: real_batcher(+ logger=kwargs["logger"], chunk_size=1, chunk_size_bytes=kwargs["chunk_size_bytes"]+ ),+ )+ base = "https://secure.fleetio.com/api/v1/vehicles?per_page=100&sort%5Bcreated_at%5D=asc"+ page2 = base + "&start_cursor=CUR2"+ pages = {+ base: {"records": [{"id": 1}, {"id": 2}], "next_cursor": "CUR2"},+ page2: {"records": [{"id": 3}], "next_cursor": None},+ }+ manager = _FakeResumableManager()+ rows, _ = self._collect(manager, monkeypatch, pages)+ assert rows == [{"id": 1}, {"id": 2}, {"id": 3}]+ assert manager.saved == [FleetioResumeConfig(start_cursor="CUR2")]+++class TestValidateCredentials:+ @pytest.mark.parametrize("status_code,expected", [(200, True), (401, False), (403, False)])+ def test_status_maps_to_bool(self, status_code: int, expected: bool, monkeypatch: Any) -> None:+ response = MagicMock()+ response.status_code = status_code+ session = MagicMock()+ session.get.return_value = response+ monkeypatch.setattr(fleetio, "make_tracked_session", lambda *a, **k: session)+ assert validate_credentials("k", "a") is expected++ def test_network_error_is_not_valid(self, monkeypatch: Any) -> None:+ session = MagicMock()+ session.get.side_effect = Exception("boom")+ monkeypatch.setattr(fleetio, "make_tracked_session", lambda *a, **k: session)+ assert validate_credentials("k", "a") is False+++class TestFetchPage:+ def _session_returning(self, status_code: int, headers: dict[str, str] | None = None, json_body: Any = None):+ response = MagicMock()+ response.status_code = status_code+ response.headers = headers or {}+ response.ok = status_code < 400+ response.json.return_value = json_body if json_body is not None else {"records": [], "next_cursor": None}+ session = MagicMock()+ session.get.return_value = response+ return session++ def test_429_raises_rate_limit_with_retry_after(self) -> None:+ # Call the undecorated body (bypassing tenacity) to assert the error carries Retry-After.+ session = self._session_returning(429, headers={"Retry-After": "12"})+ with pytest.raises(FleetioRateLimitError) as exc:+ fleetio._fetch_page.__wrapped__(session, "https://x", {}, MagicMock()) # type: ignore[attr-defined]+ assert exc.value.retry_after == 12.0++ def test_non_dict_response_is_treated_as_retryable(self) -> None:+ # A bare list means the version pin was ignored (legacy response) — fail loudly, don't truncate.+ session = self._session_returning(200, json_body=[{"id": 1}])+ with pytest.raises(fleetio.FleetioRetryableError):+ fleetio._fetch_page.__wrapped__(session, "https://x", {}, MagicMock()) # type: ignore[attr-defined]diff --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.pynew file mode 100644index 000000000000..d5bf0289696d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/tests/test_fleetio_source.py@@ -0,0 +1,142 @@+from typing import Any++import pytest+from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.fleetio import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.fleetio.fleetio import FleetioResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.fleetio.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.fleetio.source import FleetioSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FleetioSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestFleetioSource:+ def setup_method(self) -> None:+ self.source = FleetioSource()+ self.team_id = 123++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.FLEETIO++ def test_config_fields(self) -> None:+ config = self.source.get_source_config+ fields = {f.name: f for f in config.fields if isinstance(f, SourceFieldInputConfig)}+ assert set(fields) == {"api_key", "account_token"}+ # The API key is the secret; the account token is an account identifier, not a password.+ assert fields["api_key"].required is True+ assert fields["api_key"].secret is True+ assert fields["account_token"].required is True+ assert fields["account_token"].secret is False++ def test_connection_host_fields_includes_account_token(self) -> None:+ # Changing the targeted Fleetio account must force the API key to be re-entered.+ assert self.source.connection_host_fields == ["account_token"]++ def test_docs_url_matches_doc_filename(self) -> None:+ assert self.source.get_source_config.docsUrl == "https://posthog.com/docs/cdp/sources/fleetio"++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O, so the public docs can render the table list.+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_every_endpoint_with_incremental(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(MagicMock(), team_id=self.team_id)}+ assert set(schemas) == set(ENDPOINTS)+ for schema in schemas.values():+ assert schema.supports_incremental is True+ assert schema.supports_append is True+ labels = {f["field"] for f in schema.incremental_fields}+ assert {"updated_at", "created_at"} <= labels++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(MagicMock(), team_id=self.team_id, names=["vehicles"])+ assert [s.name for s in schemas] == ["vehicles"]++ def test_documented_tables_render_from_static_catalog(self) -> None:+ tables = {t["name"]: t for t in self.source.get_documented_tables()}+ assert set(tables) == set(ENDPOINTS)+ # Canonical descriptions flow through to the public docs.+ assert tables["vehicles"]["description"]+ assert "Full refresh" in tables["vehicles"]["sync_methods"]+ assert "Incremental" in tables["vehicles"]["sync_methods"]++ @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)+ config = FleetioSourceConfig(api_key="k", account_token="a")+ valid, error = self.source.validate_credentials(config, self.team_id)+ assert valid is expected_valid+ assert (error is None) is expected_valid++ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://secure.fleetio.com/api/v1/vehicles"),+ ("forbidden", "403 Client Error: Forbidden for url: https://secure.fleetio.com/api/v1/parts"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("timeout", "HTTPSConnectionPool(host='secure.fleetio.com', port=443): Read timed out."),+ ("server_error", "500 Server Error for url: https://secure.fleetio.com/api/v1/vehicles"),+ ("rate_limit", "429 Too Many Requests"),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)++ def test_resumable_manager_is_bound_to_resume_config(self) -> None:+ inputs = MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is FleetioResumeConfig++ def test_source_for_pipeline_plumbs_args(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}++ def fake_fleetio_source(**kwargs: Any) -> str:+ captured.update(kwargs)+ return "response"++ monkeypatch.setattr(source_module, "fleetio_source", fake_fleetio_source)++ config = FleetioSourceConfig(api_key="my-key", account_token="my-acct")+ manager = MagicMock()+ inputs = MagicMock()+ inputs.schema_name = "vehicles"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01"+ inputs.incremental_field = "updated_at"++ result: Any = self.source.source_for_pipeline(config, manager, inputs)++ assert result == "response"+ assert captured["api_key"] == "my-key"+ assert captured["account_token"] == "my-acct"+ assert captured["endpoint"] == "vehicles"+ assert captured["resumable_source_manager"] is manager+ assert captured["should_use_incremental_field"] is True+ assert captured["db_incremental_field_last_value"] == "2026-01-01"+ assert captured["incremental_field"] == "updated_at"++ 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))++ config = FleetioSourceConfig(api_key="k", account_token="a")+ inputs = MagicMock()+ inputs.schema_name = "vehicles"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01"+ inputs.incremental_field = None++ self.source.source_for_pipeline(config, MagicMock(), inputs)+ assert captured["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex c6b2ee7676ca..c86d274fdfc4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -1170,7 +1170,8 @@ class FireboltSourceConfig(config.Config):@config.configclass FleetioSourceConfig(config.Config):- pass+ api_key: str+ account_token: str@config.config