: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 onfleet import source (#67807)
Tom Owersb0ff0d9e9d23
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 7a5899d1e45c..2bdb890832fe 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -215,6 +215,7 @@ the row lists both.| northpass_lms | HTTP | requests | ✅ || notion | HTTP | requests | ✅ || omnisend | HTTP | requests | ✅ |+| onfleet | HTTP (cursor pagination) | requests | ✅ || orb | HTTP | requests + `rest_source.RESTClient` | ✅ || openweather | HTTP | requests | ✅ || ortto | HTTP | requests | ✅ |@@ -543,7 +544,6 @@ doesn't conflict with concurrent PRs.- onehundredms- onepagecrm- onesignal-- onfleet- open_data_dc- open_exchange_rates- openaqdiff --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 7a73027b9ea3..f66742ca5de5 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@@ -2226,7 +2226,7 @@ class OnepagecrmSourceConfig(config.Config):@config.configclass OnfleetSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/onfleet/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/onfleet/canonical_descriptions.pynew file mode 100644index 000000000000..dc52af2a56e8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/onfleet/canonical_descriptions.py@@ -0,0 +1,140 @@+"""Canonical, documentation-sourced descriptions for Onfleet endpoints and columns.++Sourced from the official Onfleet API reference (https://docs.onfleet.com/reference).+Keyed by the endpoint names in `settings.py` `ONFLEET_ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced Onfleet table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "tasks": {+ "description": "Units of delivery work, each defined by a destination and a recipient, that move through the created, assigned, active, and completed states.",+ "docs_url": "https://docs.onfleet.com/reference/tasks",+ "columns": {+ "id": "Unique identifier for the task.",+ "timeCreated": "Time the task was created, in UNIX epoch milliseconds.",+ "timeLastModified": "Time the task was last modified, in UNIX epoch milliseconds.",+ "organization": "Identifier of the organization that owns the task.",+ "shortId": "A short, human-readable identifier for the task.",+ "trackingURL": "Public URL where the recipient can track the task.",+ "worker": "Identifier of the worker assigned to the task, if any.",+ "merchant": "Identifier of the organization that created the task.",+ "executor": "Identifier of the organization responsible for executing the task.",+ "creator": "Identifier of the administrator who created the task.",+ "dependencies": "Identifiers of tasks that must be completed before this one.",+ "state": "Current state of the task (0 unassigned, 1 assigned, 2 active, 3 completed).",+ "completeAfter": "Earliest time the task should be completed, in UNIX epoch milliseconds.",+ "completeBefore": "Latest time the task should be completed, in UNIX epoch milliseconds.",+ "pickupTask": "Whether the task is a pickup task.",+ "notes": "Free-form notes attached to the task.",+ "completionDetails": "Details captured when the task was completed (time, notes, proof of delivery).",+ "feedback": "Recipient feedback left for the task.",+ "metadata": "Custom key/value metadata attached to the task.",+ "overrides": "Recipient/destination field overrides applied to this task only.",+ "quantity": "Quantity of items associated with the task.",+ "serviceTime": "Expected on-site service time for the task, in minutes.",+ "identity": "Recipient identity verification requirements for the task.",+ "container": "The container (worker, team, or organization) the task is assigned to.",+ "trackingViewedTime": "Time the recipient first viewed the tracking page, in UNIX epoch milliseconds.",+ "estimatedCompletionTime": "Estimated completion time, in UNIX epoch milliseconds.",+ "estimatedArrivalTime": "Estimated arrival time at the destination, in UNIX epoch milliseconds.",+ "destination": "The task's destination address and location.",+ "recipients": "The recipients associated with the task.",+ },+ },+ "workers": {+ "description": "Delivery drivers who complete tasks, including their duty status, vehicle, team membership, and location.",+ "docs_url": "https://docs.onfleet.com/reference/workers",+ "columns": {+ "id": "Unique identifier for the worker.",+ "timeCreated": "Time the worker was created, in UNIX epoch milliseconds.",+ "timeLastModified": "Time the worker was last modified, in UNIX epoch milliseconds.",+ "organization": "Identifier of the organization the worker belongs to.",+ "name": "The worker's full name.",+ "displayName": "The worker's display name shown to recipients.",+ "phone": "The worker's phone number.",+ "activeTask": "Identifier of the task the worker is currently working on, if any.",+ "tasks": "Ordered identifiers of tasks assigned to the worker.",+ "onDuty": "Whether the worker is currently on duty.",+ "timeLastSeen": "Time the worker's device was last seen, in UNIX epoch milliseconds.",+ "capacity": "The worker's carrying capacity.",+ "userData": "Metadata about the worker's device and app.",+ "accountStatus": "The worker's account status.",+ "metadata": "Custom key/value metadata attached to the worker.",+ "teams": "Identifiers of the teams the worker belongs to.",+ "vehicle": "The worker's vehicle details.",+ "location": "The worker's last known [longitude, latitude] location.",+ },+ },+ "teams": {+ "description": "Groups of workers, optionally attached to hubs, used to organize and dispatch delivery work.",+ "docs_url": "https://docs.onfleet.com/reference/teams",+ "columns": {+ "id": "Unique identifier for the team.",+ "timeCreated": "Time the team was created, in UNIX epoch milliseconds.",+ "timeLastModified": "Time the team was last modified, in UNIX epoch milliseconds.",+ "name": "The team's name.",+ "workers": "Identifiers of the workers in the team.",+ "managers": "Identifiers of the administrators managing the team.",+ "hub": "Identifier of the hub the team is based at, if any.",+ "enableSelfAssignment": "Whether workers can self-assign tasks from the team.",+ },+ },+ "hubs": {+ "description": "Physical locations (warehouses, depots) that tasks and teams can be anchored to.",+ "docs_url": "https://docs.onfleet.com/reference/hubs",+ "columns": {+ "id": "Unique identifier for the hub.",+ "name": "The hub's name.",+ "address": "The hub's postal address.",+ "location": "The hub's [longitude, latitude] location.",+ "teams": "Identifiers of the teams based at the hub.",+ },+ },+ "administrators": {+ "description": "Dashboard users (admins and dispatchers) in the organization, with their roles and contact details.",+ "docs_url": "https://docs.onfleet.com/reference/administrators",+ "columns": {+ "id": "Unique identifier for the administrator.",+ "timeCreated": "Time the administrator was created, in UNIX epoch milliseconds.",+ "timeLastModified": "Time the administrator was last modified, in UNIX epoch milliseconds.",+ "organization": "Identifier of the organization the administrator belongs to.",+ "name": "The administrator's name.",+ "email": "The administrator's email address.",+ "phone": "The administrator's phone number.",+ "type": "The administrator's type (super, standard, or dispatcher).",+ "isActive": "Whether the administrator has accepted their invitation and is active.",+ "metadata": "Custom key/value metadata attached to the administrator.",+ },+ },+ "webhooks": {+ "description": "Registered webhook subscriptions that push Onfleet events to external URLs.",+ "docs_url": "https://docs.onfleet.com/reference/webhooks",+ "columns": {+ "id": "Unique identifier for the webhook.",+ "name": "The webhook's name.",+ "count": "Total number of successful requests made for the webhook.",+ "url": "The destination URL the webhook posts to.",+ "trigger": "The numeric event trigger the webhook fires on.",+ "threshold": "Threshold (in meters or seconds) for proximity/eta triggers.",+ "isEnabled": "Whether the webhook is currently enabled.",+ },+ },+ "organization": {+ "description": "The caller's own Onfleet organization: its name, timezone, country, and delegatee relationships.",+ "docs_url": "https://docs.onfleet.com/reference/organizations",+ "columns": {+ "id": "Unique identifier for the organization.",+ "name": "The organization's name.",+ "email": "The organization's contact email.",+ "timeCreated": "Time the organization was created, in UNIX epoch milliseconds.",+ "timeLastModified": "Time the organization was last modified, in UNIX epoch milliseconds.",+ "country": "The organization's country.",+ "timezone": "The organization's timezone.",+ "delegateeIds": "Identifiers of organizations this organization delegates to.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/onfleet/onfleet.py b/products/warehouse_sources/backend/temporal/data_imports/sources/onfleet/onfleet.pynew file mode 100644index 000000000000..f94f39876dd5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/onfleet/onfleet.py@@ -0,0 +1,221 @@+import base64+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.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.onfleet.settings import (+ ONFLEET_ENDPOINTS,+ OnfleetEndpointConfig,+)++ONFLEET_BASE_URL = "https://onfleet.com/api/v2"+# Onfleet enforces an internal 70s timeout on large list endpoints (e.g. /workers) before+# returning a 502, so give each request room up to that boundary.+REQUEST_TIMEOUT_SECONDS = 70+MAX_RETRIES = 5+# `/tasks/all` requires a `from` param; epoch 0 pulls the full history on the initial/full sync.+DEFAULT_FROM_MS = 0+++class OnfleetRetryableError(Exception):+ pass+++class OnfleetResumeConfig:+ # The `lastId` cursor returned by the previous page; the next request continues after it.+ last_id: str+ # The `from` epoch-ms lower bound in effect for this sync, re-sent on every page so the+ # server-side window stays applied across the whole paginated walk.+ from_ms: int+++def _basic_auth_token(api_key: str) -> str:+ # Onfleet uses HTTP Basic auth with the API key as the username and an empty password.+ return base64.b64encode(f"{api_key}:".encode("ascii")).decode("ascii")+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Basic {_basic_auth_token(api_key)}",+ "Accept": "application/json",+ }+++def _to_epoch_ms(value: Any) -> Optional[int]:+ """Coerce an incremental cursor value to UNIX epoch milliseconds for Onfleet's `from` filter.++ Onfleet stores and filters timestamps as epoch milliseconds, so the persisted watermark is+ already an int in the common case; datetimes/dates are accepted defensively.+ """+ if value is None or isinstance(value, bool):+ return None+ if isinstance(value, int):+ return value+ if isinstance(value, float):+ return int(value)+ if isinstance(value, datetime):+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return int(dt.timestamp() * 1000)+ if isinstance(value, date):+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp() * 1000)+ try:+ return int(value)+ except (TypeError, ValueError):+ return None+++def _build_url(path: str, params: dict[str, Any]) -> str:+ clean = {key: value for key, value in params.items() if value is not None}+ if not clean:+ return f"{ONFLEET_BASE_URL}{path}"+ return f"{ONFLEET_BASE_URL}{path}?{urlencode(clean)}"+++@retry(+ retry=retry_if_exception_type((OnfleetRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+)+def _fetch(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ # Onfleet rate-limits at 20 req/s org-wide (429) and returns 502 on the internal timeout.+ if response.status_code == 429 or response.status_code >= 500:+ raise OnfleetRetryableError(f"Onfleet API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Onfleet API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def get_credentials_status(api_key: str) -> Optional[int]:+ """Return the HTTP status of a cheap authenticated probe, or None on transport failure.++ `/organization` returns the caller's own organization — a light authenticated endpoint that+ only confirms the API key is genuine, not per-endpoint scope.+ """+ try:+ response = make_tracked_session().get(+ f"{ONFLEET_BASE_URL}/organization", headers=_get_headers(api_key), timeout=10+ )+ return response.status_code+ except Exception:+ return None+++def _get_paginated_rows(+ session: requests.Session,+ headers: dict[str, str],+ config: OnfleetEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OnfleetResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ """Walk `/tasks/all` via the `lastId` cursor, bounded by the server-side `from` window."""+ from_ms = _to_epoch_ms(db_incremental_field_last_value) if should_use_incremental_field else None+ if from_ms is None:+ from_ms = DEFAULT_FROM_MS++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ last_id: str | None = None+ if resume is not None:+ last_id = resume.last_id+ from_ms = resume.from_ms+ logger.debug(f"Onfleet: resuming {config.name} from lastId={last_id}, from={from_ms}")++ while True:+ params: dict[str, Any] = {"from": from_ms}+ if last_id:+ params["lastId"] = last_id++ data = _fetch(session, _build_url(config.path, params), headers, logger)+ items = data.get(config.data_key, []) or []+ next_id = data.get("lastId")++ if items:+ yield items+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it —+ # merge dedupes the re-pulled rows on the primary key.+ if next_id and next_id != last_id:+ resumable_source_manager.save_state(OnfleetResumeConfig(last_id=next_id, from_ms=from_ms))++ # A missing (or non-advancing) lastId marks the final page.+ if not next_id or next_id == last_id:+ break+ last_id = next_id+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OnfleetResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = ONFLEET_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ # One session reused across every page so urllib3 keeps the connection alive.+ session = make_tracked_session()++ if config.paginated:+ yield from _get_paginated_rows(+ session,+ headers,+ config,+ logger,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ return++ # Every other endpoint returns the full collection in a single response with no pagination.+ data = _fetch(session, _build_url(config.path, {}), headers, logger)+ if config.single_object:+ if data:+ yield [data]+ elif data:+ yield data+++def onfleet_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OnfleetResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = ONFLEET_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ # `/tasks/all` returns rows ascending by creation time; the single-batch endpoints are+ # order-insensitive. Onfleet timestamps are epoch-ms integers, which the datetime+ # partitioner would misbucket (it treats ints as epoch seconds), so partitioning is off.+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/onfleet/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/onfleet/settings.pynew file mode 100644index 000000000000..5283bf58c585--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/onfleet/settings.py@@ -0,0 +1,60 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class OnfleetEndpointConfig:+ name: str+ path: str+ # Only `/tasks/all` is paginated (cursor via `lastId`, 64 rows/page). Every other list+ # endpoint returns the full collection as a bare JSON array in a single response.+ paginated: bool = False+ # Key wrapping the row array on the paginated endpoint (e.g. {"lastId": ..., "tasks": [...]}).+ data_key: Optional[str] = None+ # `/organization` returns a single object rather than an array.+ single_object: bool = False+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ should_sync_default: bool = True+++# Onfleet timestamps are UNIX epoch **milliseconds** stored as integers, so candidate incremental+# fields are integers even though the UI presents them as datetimes.+#+# Only `/tasks/all` exposes a server-side time filter (`from`/`to`, epoch ms). `from` filters on a+# task's creation time (completion time for tasks in the `completed` state) and results are always+# sorted ascending by creation time, so incremental sync anchors on `timeCreated`. Every other+# endpoint returns a bare array with no time filter and no pagination, so those are full refresh.+#+# Partitioning is intentionally left off: the datetime partitioner interprets an integer partition+# key as epoch *seconds*, which would misbucket Onfleet's epoch-*millisecond* timestamps.+ONFLEET_ENDPOINTS: dict[str, OnfleetEndpointConfig] = {+ "tasks": OnfleetEndpointConfig(+ name="tasks",+ path="/tasks/all",+ paginated=True,+ data_key="tasks",+ incremental_fields=[+ {+ "label": "timeCreated",+ "type": IncrementalFieldType.DateTime,+ "field": "timeCreated",+ "field_type": IncrementalFieldType.Integer,+ },+ ],+ ),+ "workers": OnfleetEndpointConfig(name="workers", path="/workers"),+ "teams": OnfleetEndpointConfig(name="teams", path="/teams"),+ "hubs": OnfleetEndpointConfig(name="hubs", path="/hubs"),+ "administrators": OnfleetEndpointConfig(name="administrators", path="/admins"),+ "webhooks": OnfleetEndpointConfig(name="webhooks", path="/webhooks"),+ "organization": OnfleetEndpointConfig(name="organization", path="/organization", single_object=True),+}++ENDPOINTS = tuple(ONFLEET_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in ONFLEET_ENDPOINTS.items() if config.incremental_fields+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/onfleet/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/onfleet/source.pyindex 39dbac2896ed..96c1395a25dc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/onfleet/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/onfleet/source.py@@ -1,19 +1,43 @@-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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import OnfleetSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.onfleet.onfleet import (+ OnfleetResumeConfig,+ get_credentials_status,+ onfleet_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.onfleet.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ ONFLEET_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class OnfleetSource(SimpleSource[OnfleetSourceConfig]):+class OnfleetSource(ResumableSource[OnfleetSourceConfig, OnfleetResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ONFLEET@@ -24,7 +48,96 @@ class OnfleetSource(SimpleSource[OnfleetSourceConfig]):name=SchemaExternalDataSourceType.ONFLEET,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Onfleet",+ caption="""Enter your Onfleet API key to pull your Onfleet last-mile delivery data into the PostHog Data warehouse.++You can create an API key in your [Onfleet dashboard](https://onfleet.com/dashboard#/manage) under **Settings → API & Webhooks**. Onfleet API keys are org-scoped and grant read access to your organization's data.""",iconPath="/static/services/onfleet.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/onfleet",+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.onfleet.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://onfleet.com": "Your Onfleet API key is invalid or has been revoked. Create a new API key in your Onfleet dashboard, then reconnect.",+ "403 Client Error: Forbidden for url: https://onfleet.com": "Your Onfleet API key does not have permission to read this data. Check the key's permissions in your Onfleet dashboard, then reconnect.",+ }++ def get_schemas(+ self,+ config: OnfleetSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint, None) is not None,+ supports_append=INCREMENTAL_FIELDS.get(endpoint, None) is not None,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=ONFLEET_ENDPOINTS[endpoint].should_sync_default,+ )+ 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: OnfleetSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ status = get_credentials_status(config.api_key)+ if status == 200:+ return True, None+ # A 403 at source-create means the token is genuine but scoped; accept it so users can+ # still connect a restricted key. Only reject 403 when validating a specific schema.+ if status == 403 and schema_name is None:+ return True, None+ if status in (401, 403):+ return False, "Invalid or unauthorized Onfleet API key"+ return False, "Could not validate Onfleet API key. Please try again."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OnfleetResumeConfig]:+ return ResumableSourceManager[OnfleetResumeConfig](inputs, OnfleetResumeConfig)++ def source_for_pipeline(+ self,+ config: OnfleetSourceConfig,+ resumable_source_manager: ResumableSourceManager[OnfleetResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return onfleet_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/onfleet/tests/test_onfleet.py b/products/warehouse_sources/backend/temporal/data_imports/sources/onfleet/tests/test_onfleet.pynew file mode 100644index 000000000000..00b188a7ee0d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/onfleet/tests/test_onfleet.py@@ -0,0 +1,206 @@+import base64+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.onfleet.onfleet import (+ OnfleetResumeConfig,+ _basic_auth_token,+ _build_url,+ _to_epoch_ms,+ get_credentials_status,+ get_rows,+ onfleet_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.onfleet.settings import (+ ENDPOINTS,+ ONFLEET_ENDPOINTS,+)++_TRANSPORT = "products.warehouse_sources.backend.temporal.data_imports.sources.onfleet.onfleet.make_tracked_session"+++def _make_manager(resume_state: OnfleetResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _resp(body: Any) -> mock.MagicMock:+ resp = mock.MagicMock(status_code=200, ok=True)+ resp.json.return_value = body+ return resp+++class TestToEpochMs:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (None, None),+ (True, None),+ (1700000000000, 1700000000000),+ (1700000000000.5, 1700000000000),+ ("1700000000000", 1700000000000),+ ("not-a-number", None),+ # datetime/date must convert to MILLISECONDS, not seconds — the crux of Onfleet's `from`.+ (datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC), 1700000000000),+ (date(2023, 11, 15), int(datetime(2023, 11, 15, tzinfo=UTC).timestamp()) * 1000),+ ],+ )+ def test_to_epoch_ms_values(self, value, expected):+ assert _to_epoch_ms(value) == expected+++class TestBasicAuth:+ def test_api_key_is_username_with_empty_password(self):+ # Onfleet Basic auth: API key as username, empty password.+ assert base64.b64decode(_basic_auth_token("my-key")).decode() == "my-key:"+++class TestBuildUrl:+ def test_no_params(self):+ assert _build_url("/tasks/all", {}) == "https://onfleet.com/api/v2/tasks/all"++ def test_drops_none_values_and_encodes(self):+ url = _build_url("/tasks/all", {"from": 0, "lastId": None})+ assert url == "https://onfleet.com/api/v2/tasks/all?from=0"+++class TestGetRowsPaginated:+ @mock.patch(_TRANSPORT)+ def test_paginates_via_last_id_and_stops_when_absent(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _resp({"lastId": "abc", "tasks": [{"id": "1"}, {"id": "2"}]}),+ _resp({"tasks": [{"id": "3"}]}), # no lastId -> final page+ ]+ manager = _make_manager()++ batches = list(get_rows("key", "tasks", mock.MagicMock(), manager))++ assert [row["id"] for batch in batches for row in batch] == ["1", "2", "3"]+ # Second request continues after the first page's lastId.+ assert "lastId=abc" in mock_session.return_value.get.call_args_list[1].args[0]+ # State saved once (only while a next cursor exists), after yielding the page.+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0].last_id == "abc"++ @mock.patch(_TRANSPORT)+ def test_resumes_from_saved_cursor(self, mock_session):+ mock_session.return_value.get.return_value = _resp({"tasks": [{"id": "9"}]})+ manager = _make_manager(OnfleetResumeConfig(last_id="saved", from_ms=1234))++ list(get_rows("key", "tasks", mock.MagicMock(), manager))++ first_url = mock_session.return_value.get.call_args_list[0].args[0]+ assert "lastId=saved" in first_url+ assert "from=1234" in first_url++ @mock.patch(_TRANSPORT)+ def test_incremental_from_value_used_as_epoch_ms(self, mock_session):+ mock_session.return_value.get.return_value = _resp({"tasks": [{"id": "1"}]})+ manager = _make_manager()++ list(+ get_rows(+ "key",+ "tasks",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000000,+ )+ )++ assert "from=1700000000000" in mock_session.return_value.get.call_args_list[0].args[0]++ @mock.patch(_TRANSPORT)+ def test_full_refresh_defaults_from_to_zero(self, mock_session):+ mock_session.return_value.get.return_value = _resp({"tasks": [{"id": "1"}]})+ manager = _make_manager()++ list(get_rows("key", "tasks", mock.MagicMock(), manager))++ assert "from=0" in mock_session.return_value.get.call_args_list[0].args[0]++ @mock.patch(_TRANSPORT)+ def test_empty_page_with_advancing_cursor_keeps_paginating(self, mock_session):+ # A page can be empty yet still carry an advancing lastId; pagination must continue+ # (not terminate) so later, non-empty pages are not skipped.+ mock_session.return_value.get.side_effect = [+ _resp({"lastId": "p2", "tasks": []}),+ _resp({"tasks": [{"id": "1"}]}), # no lastId -> final page+ ]+ manager = _make_manager()++ batches = list(get_rows("key", "tasks", mock.MagicMock(), manager))++ assert [row["id"] for batch in batches for row in batch] == ["1"]+ assert "lastId=p2" in mock_session.return_value.get.call_args_list[1].args[0]+ # No batch was yielded for the empty page, so no state was saved for it.+ manager.save_state.assert_not_called()++ @mock.patch(_TRANSPORT)+ def test_non_advancing_cursor_terminates(self, mock_session):+ # A repeated lastId must not loop forever.+ mock_session.return_value.get.side_effect = [+ _resp({"lastId": "x", "tasks": [{"id": "1"}]}),+ _resp({"lastId": "x", "tasks": [{"id": "1"}]}),+ ]+ manager = _make_manager()++ batches = list(get_rows("key", "tasks", mock.MagicMock(), manager))++ assert mock_session.return_value.get.call_count == 2+ assert [row["id"] for batch in batches for row in batch] == ["1", "1"]+++class TestGetRowsNonPaginated:+ @mock.patch(_TRANSPORT)+ def test_bare_array_endpoint_yields_once(self, mock_session):+ mock_session.return_value.get.return_value = _resp([{"id": "w1"}, {"id": "w2"}])+ manager = _make_manager()++ batches = list(get_rows("key", "workers", mock.MagicMock(), manager))++ assert batches == [[{"id": "w1"}, {"id": "w2"}]]+ assert mock_session.return_value.get.call_count == 1+ manager.save_state.assert_not_called()++ @mock.patch(_TRANSPORT)+ def test_single_object_endpoint_wraps_in_list(self, mock_session):+ mock_session.return_value.get.return_value = _resp({"id": "org1", "name": "Acme"})+ manager = _make_manager()++ batches = list(get_rows("key", "organization", mock.MagicMock(), manager))++ assert batches == [[{"id": "org1", "name": "Acme"}]]+++class TestGetCredentialsStatus:+ @pytest.mark.parametrize("status_code", [200, 401, 403, 500])+ @mock.patch(_TRANSPORT)+ def test_returns_status_code(self, mock_session, status_code):+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)+ assert get_credentials_status("key") == status_code++ @mock.patch(_TRANSPORT)+ def test_returns_none_on_transport_error(self, mock_session):+ mock_session.return_value.get.side_effect = Exception("boom")+ assert get_credentials_status("key") is None+++class TestOnfleetSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = ONFLEET_ENDPOINTS[endpoint]+ response = onfleet_source("key", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ assert response.sort_mode == "asc"+ # Onfleet epoch-ms timestamps would misbucket under the datetime partitioner, so partitioning is off.+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/onfleet/tests/test_onfleet_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/onfleet/tests/test_onfleet_source.pynew file mode 100644index 000000000000..fd1364dc62c9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/onfleet/tests/test_onfleet_source.py@@ -0,0 +1,113 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import OnfleetSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.onfleet.onfleet import OnfleetResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.onfleet.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.onfleet.source import OnfleetSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++_TRANSPORT_STATUS = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.onfleet.source.get_credentials_status"+)+++class TestOnfleetSource:+ def setup_method(self):+ self.source = OnfleetSource()+ self.team_id = 123+ self.config = OnfleetSourceConfig(api_key="key")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.ONFLEET++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Onfleet"+ assert config.label == "Onfleet"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/onfleet"++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://onfleet.com/api/v2/tasks/all?from=0",+ "403 Client Error: Forbidden for url: https://onfleet.com/api/v2/workers",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ @pytest.mark.parametrize(+ "other_error",+ [+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",+ "500 Server Error for url: https://onfleet.com/api/v2/tasks/all",+ ],+ )+ def test_non_retryable_errors_ignore_unrelated(self, other_error):+ assert not any(key in other_error for key in self.source.get_non_retryable_errors())++ def test_get_schemas_lists_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_only_tasks_supports_incremental(self):+ by_name = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert by_name["tasks"].supports_incremental is True+ assert [f["field"] for f in by_name["tasks"].incremental_fields] == ["timeCreated"]+ for name in ("workers", "teams", "hubs", "administrators", "webhooks", "organization"):+ assert by_name[name].supports_incremental is False++ def test_get_schemas_filters_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["tasks", "workers"])+ assert {s.name for s in schemas} == {"tasks", "workers"}++ @pytest.mark.parametrize(+ "status, schema_name, expected_ok",+ [+ (200, None, True),+ (200, "tasks", True),+ (401, None, False),+ # 403 at source-create is a genuine but scoped key -> accept; reject for a specific schema.+ (403, None, True),+ (403, "tasks", False),+ (500, None, False),+ (None, None, False),+ ],+ )+ def test_validate_credentials(self, status, schema_name, expected_ok):+ with mock.patch(_TRANSPORT_STATUS, return_value=status):+ ok, _ = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)+ assert ok is expected_ok++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is OnfleetResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self):+ inputs = mock.MagicMock()+ inputs.schema_name = "tasks"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = 1700000000000+ inputs.incremental_field = "timeCreated"+ manager = mock.MagicMock()++ response = self.source.source_for_pipeline(self.config, manager, inputs)++ assert response.name == "tasks"+ assert response.primary_keys == ["id"]