Skip to content

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

feat(data-warehouse): implement ubidots import source (#69379)

Tom Owers9c6fb644bc0d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 8701fad6e10b..e3a0e6157e9a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -347,6 +347,7 @@ the row lists both.
| trello | HTTP | requests | ✅ |
| twilio | HTTP | requests | ✅ |
| typeform | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| ubidots | HTTP | requests | ✅ |
| vercel | HTTP | requests | ✅ |
| vitally | HTTP | requests + `rest_source.RESTClient` | ✅ |
| webflow | HTTP | requests | ✅ |
@@ -733,7 +734,6 @@ doesn't conflict with concurrent PRs.
- twitter
- twitter_ads
- tyntec_sms
-- ubidots
- unleash
- uppromote
- uptick
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index b4b774847e6f..d911a99d8cb0 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
@@ -3535,7 +3535,10 @@ class USCensusSourceConfig(config.Config):
@config.config
class UbidotsSourceConfig(config.Config):
- pass
+ api_token: str
+ api_base_url: Literal["https://industrial.api.ubidots.com", "https://things.ubidots.com"] | None = config.value(
+ default="https://industrial.api.ubidots.com"
+ )
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/canonical_descriptions.py
new file mode 100644
index 000000000000..58ab050edbe4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/canonical_descriptions.py
@@ -0,0 +1,87 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "devices": {
+ "description": "A device is a container that collects data from a physical asset (sensor, machine, gateway) into variables.",
+ "docs_url": "https://docs.ubidots.com/reference/device-object",
+ "columns": {
+ "id": "Unique identifier of the device.",
+ "label": "Unique, URL-safe identifier used to reference the device in API calls.",
+ "name": "Human-readable name of the device.",
+ "description": "Free-text description of the device.",
+ "organization": "Organization the device belongs to, if any.",
+ "tags": "List of tags assigned to the device.",
+ "properties": "Custom key-value properties attached to the device.",
+ "isActive": "Whether the device is active.",
+ "lastActivity": "When the device last received data.",
+ "createdAt": "When the device was created.",
+ },
+ },
+ "variables": {
+ "description": "A variable holds one time series of dots (values) inside a device, e.g. temperature or humidity.",
+ "docs_url": "https://docs.ubidots.com/reference/variable-object",
+ "columns": {
+ "id": "Unique identifier of the variable.",
+ "label": "Unique, URL-safe identifier of the variable within its device.",
+ "name": "Human-readable name of the variable.",
+ "description": "Free-text description of the variable.",
+ "device": "The device this variable belongs to.",
+ "type": "Variable type: raw (ingested data) or synthetic (computed expression).",
+ "unit": "Display unit of the variable's values.",
+ "syntheticExpression": "Expression that computes the values of a synthetic variable.",
+ "tags": "List of tags assigned to the variable.",
+ "properties": "Custom key-value properties attached to the variable.",
+ "lastValue": "The most recent dot received by the variable.",
+ "lastActivity": "When the variable last received data.",
+ "createdAt": "When the variable was created.",
+ },
+ },
+ "device_groups": {
+ "description": "A device group is a user-defined collection of devices, used to organize fleets and target events.",
+ "docs_url": "https://docs.ubidots.com/reference/device-groups",
+ "columns": {
+ "id": "Unique identifier of the device group.",
+ "label": "Unique, URL-safe identifier of the device group.",
+ "name": "Human-readable name of the device group.",
+ "devices": "Devices that belong to the group.",
+ "createdAt": "When the device group was created.",
+ },
+ },
+ "device_types": {
+ "description": "A device type is a template of properties, variables, and appearance applied to devices of the same kind.",
+ "docs_url": "https://docs.ubidots.com/reference/device-types",
+ "columns": {
+ "id": "Unique identifier of the device type.",
+ "label": "Unique, URL-safe identifier of the device type.",
+ "name": "Human-readable name of the device type.",
+ "description": "Free-text description of the device type.",
+ "properties": "Property definitions applied to devices of this type.",
+ "variables": "Variable definitions applied to devices of this type.",
+ "createdAt": "When the device type was created.",
+ },
+ },
+ "events": {
+ "description": "An event is a condition-based rule that triggers actions (email, SMS, webhook) when device data meets its criteria.",
+ "docs_url": "https://docs.ubidots.com/reference/events",
+ "columns": {
+ "id": "Unique identifier of the event.",
+ "name": "Human-readable name of the event.",
+ "description": "Free-text description of the event.",
+ "isActive": "Whether the event is enabled.",
+ "createdAt": "When the event was created.",
+ },
+ },
+ "values": {
+ "description": "A dot: one timestamped data point of a variable's time series. Joins to the variables table via the variable column.",
+ "docs_url": "https://docs.ubidots.com/v1.6/reference/get-variable-data-1",
+ "columns": {
+ "variable": "Identifier of the variable this dot belongs to (joins to variables.id).",
+ "timestamp": "Unix epoch milliseconds at which the dot was recorded.",
+ "value": "Numeric value of the dot.",
+ "context": "Optional key-value metadata sent with the dot (e.g. GPS coordinates).",
+ "created_at": "Unix epoch milliseconds at which the dot was ingested by Ubidots.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/settings.py
new file mode 100644
index 000000000000..622dd66eea6a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/settings.py
@@ -0,0 +1,62 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Ubidots hosts vary by account tier: Industrial/enterprise accounts live on
+# industrial.api.ubidots.com, legacy STEM/educational accounts on things.ubidots.com. Both expose
+# the same v2.0 (metadata) and v1.6 (values) REST APIs — verified with live probes against both.
+DEFAULT_UBIDOTS_API_BASE_URL = "https://industrial.api.ubidots.com"
+ALLOWED_UBIDOTS_API_BASE_URLS = (
+ DEFAULT_UBIDOTS_API_BASE_URL,
+ "https://things.ubidots.com",
+)
+
+# Dots (values) carry a millisecond epoch `timestamp`, which is what the v1.6 values endpoints
+# filter on server-side via the `start` query param.
+TIMESTAMP_INCREMENTAL: IncrementalField = {
+ "label": "timestamp",
+ "type": IncrementalFieldType.Integer,
+ "field": "timestamp",
+ "field_type": IncrementalFieldType.Integer,
+}
+
+
+@dataclass
+class UbidotsEndpointConfig:
+ name: str
+ path: str # Full path including the API version prefix, e.g. "/api/v2.0/devices/"
+ # Only the values endpoint filters server-side (`start`/`end` ms timestamps); v2.0 metadata
+ # endpoints expose no documented monotonic update cursor, so they are full refresh only.
+ supports_incremental: bool = False
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+# The `values` stream fans out per variable: v2.0 lists the variables, then v1.6
+# /variables/{id}/values pages through each variable's time-series dots (newest first).
+VALUES_ENDPOINT = "values"
+VALUES_PATH_TEMPLATE = "/api/v1.6/variables/{variable_id}/values"
+
+UBIDOTS_ENDPOINTS: dict[str, UbidotsEndpointConfig] = {
+ "devices": UbidotsEndpointConfig(name="devices", path="/api/v2.0/devices/"),
+ "variables": UbidotsEndpointConfig(name="variables", path="/api/v2.0/variables/"),
+ "device_groups": UbidotsEndpointConfig(name="device_groups", path="/api/v2.0/device_groups/"),
+ "device_types": UbidotsEndpointConfig(name="device_types", path="/api/v2.0/device_types/"),
+ "events": UbidotsEndpointConfig(name="events", path="/api/v2.0/events/"),
+ VALUES_ENDPOINT: UbidotsEndpointConfig(
+ name=VALUES_ENDPOINT,
+ path=VALUES_PATH_TEMPLATE,
+ supports_incremental=True,
+ incremental_fields=[TIMESTAMP_INCREMENTAL],
+ # A variable stores at most one dot per millisecond timestamp (writing the same timestamp
+ # overwrites), but timestamps repeat across variables — the parent id keeps the key unique
+ # table-wide.
+ primary_keys=["variable", "timestamp"],
+ ),
+}
+
+ENDPOINTS = tuple(UBIDOTS_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in UBIDOTS_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/source.py
index 4e8f8518e792..d422af63d3ce 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/source.py
@@ -1,19 +1,46 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-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.generated_configs import UbidotsSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.ubidots.settings import (
+ DEFAULT_UBIDOTS_API_BASE_URL,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ UBIDOTS_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.ubidots.ubidots import (
+ UbidotsResumeConfig,
+ ubidots_source,
+ validate_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class UbidotsSource(SimpleSource[UbidotsSourceConfig]):
+class UbidotsSource(ResumableSource[UbidotsSourceConfig, UbidotsResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.UBIDOTS
@@ -24,7 +51,115 @@ class UbidotsSource(SimpleSource[UbidotsSourceConfig]):
name=SchemaExternalDataSourceType.UBIDOTS,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Ubidots",
- iconPath="/static/services/ubidots.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ keywords=["iot", "sensors", "telemetry"],
+ caption="""Enter your Ubidots API token to pull your IoT devices, variables, and sensor values into the PostHog Data warehouse.
+
+Use the permanent token from **your profile → API Credentials** in Ubidots — tokens minted via the temporary-token endpoint expire after a few hours and will break syncs. Industrial and enterprise accounts use the default API base URL; pick `https://things.ubidots.com` only for legacy STEM accounts.
+""",
+ iconPath="/static/services/ubidots.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/ubidots",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldSelectConfig(
+ name="api_base_url",
+ label="API base URL",
+ required=False,
+ defaultValue=DEFAULT_UBIDOTS_API_BASE_URL,
+ options=[
+ SourceFieldSelectConfigOption(
+ label=DEFAULT_UBIDOTS_API_BASE_URL, value=DEFAULT_UBIDOTS_API_BASE_URL
+ ),
+ SourceFieldSelectConfigOption(
+ label="https://things.ubidots.com", value="https://things.ubidots.com"
+ ),
+ ],
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.ubidots.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ message_401 = (
+ "Your Ubidots API token is invalid or has expired. Use the permanent token from your profile's "
+ "API Credentials page, then reconnect."
+ )
+ message_403 = (
+ "Your Ubidots API token does not have access to this data. Check the token owner's permissions, "
+ "then reconnect."
+ )
+ return {
+ "401 Client Error: Unauthorized for url: https://industrial.api.ubidots.com": message_401,
+ "403 Client Error: Forbidden for url: https://industrial.api.ubidots.com": message_403,
+ "401 Client Error: Unauthorized for url: https://things.ubidots.com": message_401,
+ "403 Client Error: Forbidden for url: https://things.ubidots.com": message_403,
+ }
+
+ def get_schemas(
+ self,
+ config: UbidotsSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Only `values` filters server-side (`start`/`end` millisecond timestamps); the v2.0
+ # metadata endpoints expose no monotonic update cursor, so they are full refresh only.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=UBIDOTS_ENDPOINTS[endpoint].supports_incremental,
+ supports_append=UBIDOTS_ENDPOINTS[endpoint].supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(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: UbidotsSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # Ubidots tokens are account-wide, so a single probe validates access to every schema.
+ return validate_credentials(config.api_token, config.api_base_url)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[UbidotsResumeConfig]:
+ return ResumableSourceManager[UbidotsResumeConfig](inputs, UbidotsResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: UbidotsSourceConfig,
+ resumable_source_manager: ResumableSourceManager[UbidotsResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in UBIDOTS_ENDPOINTS:
+ raise ValueError(f"Unknown Ubidots schema '{inputs.schema_name}'")
+
+ return ubidots_source(
+ api_token=config.api_token,
+ api_base_url=config.api_base_url,
+ 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,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/tests/test_ubidots.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/tests/test_ubidots.py
new file mode 100644
index 000000000000..2920776aefe4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/tests/test_ubidots.py
@@ -0,0 +1,471 @@
+from collections.abc import Mapping
+from datetime import UTC, datetime
+from typing import Any, Optional
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.ubidots import ubidots
+from products.warehouse_sources.backend.temporal.data_imports.sources.ubidots.settings import (
+ DEFAULT_UBIDOTS_API_BASE_URL,
+ ENDPOINTS,
+ VALUES_ENDPOINT,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.ubidots.ubidots import (
+ UbidotsResumeConfig,
+ UbidotsRetryableError,
+ _start_timestamp_ms,
+ _validated_api_base_url,
+ _validated_page_url,
+ check_access,
+ get_rows,
+ get_values_rows,
+ ubidots_source,
+ validate_credentials,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = ubidots._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+DEVICES_FIRST_URL = f"{DEFAULT_UBIDOTS_API_BASE_URL}/api/v2.0/devices/?page_size=200"
+VARIABLES_FIRST_URL = f"{DEFAULT_UBIDOTS_API_BASE_URL}/api/v2.0/variables/?page_size=200"
+
+
+def _values_url(variable_id: str, start: Optional[int] = None) -> str:
+ url = f"{DEFAULT_UBIDOTS_API_BASE_URL}/api/v1.6/variables/{variable_id}/values?page_size=200"
+ return f"{url}&start={start}" if start is not None else url
+
+
+class _FakeResumableManager:
+ def __init__(self, state: UbidotsResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[UbidotsResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> UbidotsResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: UbidotsResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _fake_transport(monkeypatch: Any, pages: Mapping[str, tuple[list[dict], Optional[str]]]) -> None:
+ def fake_fetch(session: Any, url: str, logger: Any) -> tuple[list[dict], Optional[str]]:
+ return pages[url]
+
+ monkeypatch.setattr(ubidots, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(ubidots, "make_tracked_session", lambda **kwargs: MagicMock())
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: Mapping[str, tuple[list[dict], Optional[str]]],
+ endpoint: str = "devices",
+ ) -> list[dict]:
+ _fake_transport(monkeypatch, pages)
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_token="BBUS-token",
+ api_base_url=None,
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows
+
+ def test_single_page_yields_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {DEVICES_FIRST_URL: ([{"id": "a"}, {"id": "b"}], None)})
+ assert rows == [{"id": "a"}, {"id": "b"}]
+ # A null next link ends the sync without persisting resume state.
+ assert manager.saved == []
+
+ def test_follows_next_url_cursor_until_null(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ second = f"{DEFAULT_UBIDOTS_API_BASE_URL}/api/v2.0/devices/?page=2&page_size=200"
+ pages: dict[str, tuple[list[dict], Optional[str]]] = {
+ DEVICES_FIRST_URL: ([{"id": "a"}], second),
+ second: ([{"id": "b"}], None),
+ }
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": "a"}, {"id": "b"}]
+ # State is saved once — after the first page, pointing at the next cursor — then we stop.
+ assert [s.next_url for s in manager.saved] == [second]
+
+ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:
+ second = f"{DEFAULT_UBIDOTS_API_BASE_URL}/api/v2.0/devices/?page=2&page_size=200"
+ manager = _FakeResumableManager(UbidotsResumeConfig(next_url=second))
+ # The first page URL must never be fetched on resume.
+ rows = self._collect(manager, monkeypatch, {second: ([{"id": "b"}], None)})
+ assert rows == [{"id": "b"}]
+
+ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {DEVICES_FIRST_URL: ([], None)})
+ assert rows == []
+ assert manager.saved == []
+
+ def test_tampered_resume_cursor_is_rejected(self, monkeypatch: Any) -> None:
+ # A poisoned Redis cursor must never be fetched with the token-bearing session.
+ manager = _FakeResumableManager(UbidotsResumeConfig(next_url="https://evil.example.com/steal"))
+ with pytest.raises(ValueError, match="off the configured Ubidots host"):
+ self._collect(manager, monkeypatch, {})
+
+
+class TestGetValuesRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: Mapping[str, tuple[list[dict], Optional[str]]],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ logger: Any = None,
+ ) -> list[dict]:
+ _fake_transport(monkeypatch, pages)
+ rows: list[dict] = []
+ for batch in get_values_rows(
+ api_token="BBUS-token",
+ api_base_url=None,
+ logger=logger or MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ):
+ rows.extend(batch)
+ return rows
+
+ def test_fans_out_per_variable_and_injects_variable_id(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages: dict[str, tuple[list[dict], Optional[str]]] = {
+ VARIABLES_FIRST_URL: ([{"id": "var1"}, {"id": "var2"}], None),
+ _values_url("var1"): ([{"timestamp": 2, "value": 1.0}], None),
+ _values_url("var2"): ([{"timestamp": 3, "value": 2.0}], None),
+ }
+ rows = self._collect(manager, monkeypatch, pages)
+ # The dot payload has no variable field — injection is what makes the composite key unique.
+ assert rows == [
+ {"timestamp": 2, "value": 1.0, "variable": "var1"},
+ {"timestamp": 3, "value": 2.0, "variable": "var2"},
+ ]
+ # Each fully synced variable is checkpointed so a resumed job skips past it.
+ assert [s.completed_variable_ids for s in manager.saved] == [["var1"], ["var1", "var2"]]
+
+ def test_incremental_watermark_is_passed_as_start(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages: dict[str, tuple[list[dict], Optional[str]]] = {
+ VARIABLES_FIRST_URL: ([{"id": "var1"}], None),
+ # A URL without &start= is absent from this map, so dropping the server-side filter
+ # would KeyError here rather than silently re-fetching full history.
+ _values_url("var1", start=1700000000000): ([{"timestamp": 1700000000001}], None),
+ }
+ rows = self._collect(
+ manager,
+ monkeypatch,
+ pages,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1700000000000,
+ )
+ assert rows == [{"timestamp": 1700000000001, "variable": "var1"}]
+
+ @pytest.mark.parametrize(
+ "should_use_incremental_field,last_value",
+ [
+ pytest.param(False, 1700000000000, id="full_refresh_ignores_watermark"),
+ pytest.param(True, None, id="incremental_without_watermark"),
+ ],
+ )
+ def test_no_start_param_when_not_filtering(
+ self, should_use_incremental_field: bool, last_value: Any, monkeypatch: Any
+ ) -> None:
+ manager = _FakeResumableManager()
+ pages: dict[str, tuple[list[dict], Optional[str]]] = {
+ VARIABLES_FIRST_URL: ([{"id": "var1"}], None),
+ _values_url("var1"): ([{"timestamp": 5}], None),
+ }
+ rows = self._collect(
+ manager,
+ monkeypatch,
+ pages,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=last_value,
+ )
+ assert rows == [{"timestamp": 5, "variable": "var1"}]
+
+ def test_resume_skips_completed_and_continues_current_variable(self, monkeypatch: Any) -> None:
+ var2_page2 = f"{DEFAULT_UBIDOTS_API_BASE_URL}/api/v1.6/variables/var2/values?page=2&page_size=200"
+ manager = _FakeResumableManager(
+ UbidotsResumeConfig(next_url=var2_page2, current_variable_id="var2", completed_variable_ids=["var1"])
+ )
+ pages: dict[str, tuple[list[dict], Optional[str]]] = {
+ VARIABLES_FIRST_URL: ([{"id": "var1"}, {"id": "var2"}, {"id": "var3"}], None),
+ # var1 is complete and var2 resumes mid-pagination — their first-page URLs must never
+ # be fetched again.
+ var2_page2: ([{"timestamp": 2}], None),
+ _values_url("var3"): ([{"timestamp": 3}], None),
+ }
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [
+ {"timestamp": 2, "variable": "var2"},
+ {"timestamp": 3, "variable": "var3"},
+ ]
+
+ def test_mid_variable_state_saved_after_yield(self, monkeypatch: Any) -> None:
+ page2 = f"{DEFAULT_UBIDOTS_API_BASE_URL}/api/v1.6/variables/var1/values?page=2&page_size=200"
+ manager = _FakeResumableManager()
+ pages: dict[str, tuple[list[dict], Optional[str]]] = {
+ VARIABLES_FIRST_URL: ([{"id": "var1"}], None),
+ _values_url("var1"): ([{"timestamp": 2}], page2),
+ page2: ([{"timestamp": 1}], None),
+ }
+ self._collect(manager, monkeypatch, pages)
+ mid = manager.saved[0]
+ assert (mid.next_url, mid.current_variable_id, mid.completed_variable_ids) == (page2, "var1", [])
+ done = manager.saved[-1]
+ assert (done.next_url, done.current_variable_id, done.completed_variable_ids) == (None, None, ["var1"])
+
+ def test_page_cap_stops_pagination_and_warns(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(ubidots, "MAX_VALUES_PAGES_PER_VARIABLE", 1)
+ page2 = f"{DEFAULT_UBIDOTS_API_BASE_URL}/api/v1.6/variables/var1/values?page=2&page_size=200"
+ manager = _FakeResumableManager()
+ logger = MagicMock()
+ pages: dict[str, tuple[list[dict], Optional[str]]] = {
+ VARIABLES_FIRST_URL: ([{"id": "var1"}], None),
+ # page2 is absent from the map — fetching past the cap would KeyError.
+ _values_url("var1"): ([{"timestamp": 2}], page2),
+ }
+ rows = self._collect(manager, monkeypatch, pages, logger=logger)
+ assert rows == [{"timestamp": 2, "variable": "var1"}]
+ logger.warning.assert_called_once()
+ # The capped variable still counts as complete so the sync can finish.
+ assert manager.saved[-1].completed_variable_ids == ["var1"]
+
+ def test_poisoned_next_link_is_rejected(self, monkeypatch: Any) -> None:
+ # A next link off the configured host must stop the sync, not be followed with the token.
+ manager = _FakeResumableManager()
+ pages: dict[str, tuple[list[dict], Optional[str]]] = {
+ VARIABLES_FIRST_URL: ([{"id": "var1"}], None),
+ _values_url("var1"): ([{"timestamp": 2}], "https://evil.example.com/next"),
+ }
+ with pytest.raises(ValueError, match="off the configured Ubidots host"):
+ self._collect(manager, monkeypatch, pages)
+
+ def test_variables_list_pagination_is_followed(self, monkeypatch: Any) -> None:
+ variables_page2 = f"{DEFAULT_UBIDOTS_API_BASE_URL}/api/v2.0/variables/?page=2&page_size=200"
+ manager = _FakeResumableManager()
+ pages: dict[str, tuple[list[dict], Optional[str]]] = {
+ VARIABLES_FIRST_URL: ([{"id": "var1"}], variables_page2),
+ variables_page2: ([{"id": "var2"}], None),
+ _values_url("var1"): ([{"timestamp": 1}], None),
+ _values_url("var2"): ([{"timestamp": 2}], None),
+ }
+ rows = self._collect(manager, monkeypatch, pages)
+ assert [r["variable"] for r in rows] == ["var1", "var2"]
+
+
+class TestFetchPage:
+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else {"results": [], "next": None}
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(UbidotsRetryableError):
+ _fetch_page_unwrapped(session, DEVICES_FIRST_URL, MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(session, DEVICES_FIRST_URL, MagicMock())
+
+ def test_success_returns_results_and_next(self) -> None:
+ next_url = f"{DEFAULT_UBIDOTS_API_BASE_URL}/api/v2.0/devices/?page=2&page_size=200"
+ body = {"count": 5, "next": next_url, "previous": None, "results": [{"id": "a"}]}
+ session = self._session_returning(200, body)
+ rows, returned_next = _fetch_page_unwrapped(session, DEVICES_FIRST_URL, MagicMock())
+ assert rows == [{"id": "a"}]
+ assert returned_next == next_url
+
+ def test_null_next_returns_none(self) -> None:
+ body = {"count": 1, "next": None, "previous": None, "results": [{"id": "a"}]}
+ session = self._session_returning(200, body)
+ _, returned_next = _fetch_page_unwrapped(session, DEVICES_FIRST_URL, MagicMock())
+ assert returned_next is None
+
+ @parameterized.expand([("bare_list", [{"id": "a"}]), ("missing_results", {"count": 1})])
+ def test_unexpected_payload_is_retryable(self, _name: str, body: Any) -> None:
+ session = self._session_returning(200, body)
+ with pytest.raises(UbidotsRetryableError):
+ _fetch_page_unwrapped(session, DEVICES_FIRST_URL, MagicMock())
+
+ def test_request_uses_absolute_url_without_params(self) -> None:
+ session = self._session_returning(200, {"results": [], "next": None})
+ url = f"{DEFAULT_UBIDOTS_API_BASE_URL}/api/v2.0/devices/?page=3&page_size=200"
+ _fetch_page_unwrapped(session, url, MagicMock())
+ args, kwargs = session.get.call_args
+ assert args[0] == url
+ # The cursor URL already carries paging; we must not re-send page params.
+ assert "params" not in kwargs
+
+
+class TestHelpers:
+ @parameterized.expand(
+ [
+ ("none", None, None),
+ ("int_ms", 1700000000000, 1700000000000),
+ ("float_ms", 1700000000000.7, 1700000000000),
+ ("numeric_string", "1700000000000", 1700000000000),
+ ("datetime", datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC), 1700000000000000 // 1000),
+ ("garbage_string", "not-a-timestamp", None),
+ ("bool", True, None),
+ ]
+ )
+ def test_start_timestamp_ms(self, _name: str, value: Any, expected: Optional[int]) -> None:
+ assert _start_timestamp_ms(value) == expected
+
+ @parameterized.expand(
+ [
+ ("default_when_none", None, "https://industrial.api.ubidots.com"),
+ ("industrial", "https://industrial.api.ubidots.com", "https://industrial.api.ubidots.com"),
+ ("legacy", "https://things.ubidots.com", "https://things.ubidots.com"),
+ ("trailing_slash", "https://things.ubidots.com/", "https://things.ubidots.com"),
+ ]
+ )
+ def test_validated_api_base_url_accepts_allowed_hosts(self, _name: str, given: str | None, expected: str) -> None:
+ assert _validated_api_base_url(given) == expected
+
+ @parameterized.expand(
+ [
+ ("attacker_host", "https://evil.example.com"),
+ ("lookalike", "https://industrial.api.ubidots.com.evil.example.com"),
+ ]
+ )
+ def test_validated_api_base_url_rejects_unknown_hosts(self, _name: str, given: str) -> None:
+ # The stored token must never be sent to a host outside the fixed Ubidots set.
+ with pytest.raises(ValueError):
+ _validated_api_base_url(given)
+
+ @parameterized.expand(
+ [
+ ("same_host_https", "https://industrial.api.ubidots.com/api/v2.0/devices/?page=2"),
+ ("same_host_with_query", "https://industrial.api.ubidots.com/api/v1.6/variables/v1/values?page=3"),
+ ]
+ )
+ def test_validated_page_url_accepts_same_host(self, _name: str, url: str) -> None:
+ assert _validated_page_url(url, DEFAULT_UBIDOTS_API_BASE_URL) == url
+
+ def test_validated_page_url_upgrades_http_to_https(self) -> None:
+ # Proxied APIs sometimes emit http next links; same-host http is upgraded, not rejected.
+ upgraded = _validated_page_url(
+ "http://industrial.api.ubidots.com/api/v2.0/devices/?page=2", DEFAULT_UBIDOTS_API_BASE_URL
+ )
+ assert upgraded == "https://industrial.api.ubidots.com/api/v2.0/devices/?page=2"
+
+ @parameterized.expand(
+ [
+ ("attacker_host", "https://evil.example.com/api/v2.0/devices/?page=2"),
+ ("lookalike", "https://industrial.api.ubidots.com.evil.example.com/api/v2.0/devices/"),
+ ("other_ubidots_host", "https://things.ubidots.com/api/v2.0/devices/?page=2"),
+ ("non_http_scheme", "file:///etc/passwd"),
+ ]
+ )
+ def test_validated_page_url_rejects_off_host_urls(self, _name: str, url: str) -> None:
+ with pytest.raises(ValueError, match="off the configured Ubidots host"):
+ _validated_page_url(url, DEFAULT_UBIDOTS_API_BASE_URL)
+
+
+class TestCheckAccess:
+ def _session(self, response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, 200, None),
+ ("unauthorized", 401, False, 401, None),
+ ("forbidden", 403, False, 403, None),
+ ("server_error", 500, False, 500, "Ubidots returned HTTP 500"),
+ ]
+ )
+ def test_status_mapping(
+ self, _name: str, status: int, ok: bool, expected_status: int, expected_message: str | None
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ with patch.object(ubidots, "make_tracked_session", return_value=self._session(response)):
+ assert check_access("BBUS-token", None) == (expected_status, expected_message)
+
+ def test_connection_error_maps_to_zero(self) -> None:
+ session = self._session(requests.ConnectionError("boom"))
+ with patch.object(ubidots, "make_tracked_session", return_value=session):
+ status, message = check_access("BBUS-token", None)
+ assert status == 0
+ assert message is not None and "boom" in message
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, None),
+ ("unauthorized", 401, False, "Invalid Ubidots API token"),
+ ("forbidden", 403, False, "Invalid Ubidots API token"),
+ ("server_error", 500, False, "Ubidots returned HTTP 500"),
+ ]
+ )
+ def test_validate_credentials(
+ self, _name: str, status: int, expected_valid: bool, expected_message: str | None
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ with patch.object(ubidots, "make_tracked_session", return_value=self._session(response)):
+ assert validate_credentials("BBUS-token", None) == (expected_valid, expected_message)
+
+ def test_validate_credentials_rejects_bad_base_url(self) -> None:
+ valid, message = validate_credentials("BBUS-token", "https://evil.example.com")
+ assert valid is False
+ assert message is not None and "API base URL" in message
+
+
+class TestUbidotsSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = ubidots_source(
+ api_token="BBUS-token",
+ api_base_url=None,
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ if endpoint == VALUES_ENDPOINT:
+ # The parent id is half the composite key — timestamps repeat across variables.
+ assert response.primary_keys == ["variable", "timestamp"]
+ # Values return newest first, so the watermark must only commit at sync end.
+ assert response.sort_mode == "desc"
+ else:
+ assert response.primary_keys == ["id"]
+ assert response.sort_mode == "asc"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/tests/test_ubidots_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/tests/test_ubidots_source.py
new file mode 100644
index 000000000000..923c9b2bb0f8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/tests/test_ubidots_source.py
@@ -0,0 +1,130 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+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 UbidotsSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.ubidots.settings import ENDPOINTS, VALUES_ENDPOINT
+from products.warehouse_sources.backend.temporal.data_imports.sources.ubidots.source import UbidotsSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.ubidots.ubidots import UbidotsResumeConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestUbidotsSource:
+ def setup_method(self) -> None:
+ self.source = UbidotsSource()
+ self.team_id = 123
+ self.config = UbidotsSourceConfig(api_token="BBUS-token")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.UBIDOTS
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Ubidots"
+ assert config.label == "Ubidots"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # Deliberately still gated while the source lands across PRs.
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/ubidots"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["api_token", "api_base_url"]
+
+ def test_api_token_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_only_values_is_incremental(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert set(schemas) == set(ENDPOINTS)
+
+ values = schemas[VALUES_ENDPOINT]
+ assert values.supports_incremental is True
+ assert [f["field"] for f in values.incremental_fields] == ["timestamp"]
+
+ for name, schema in schemas.items():
+ if name == VALUES_ENDPOINT:
+ continue
+ assert schema.supports_incremental is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["devices"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "devices"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ ("401 Client Error: Unauthorized for url: https://industrial.api.ubidots.com/api/v2.0/devices/",),
+ ("403 Client Error: Forbidden for url: https://industrial.api.ubidots.com/api/v2.0/variables/",),
+ ("401 Client Error: Unauthorized for url: https://things.ubidots.com/api/v1.6/variables/abc/values",),
+ ("403 Client Error: Forbidden for url: https://things.ubidots.com/api/v2.0/events/",),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, 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(
+ [
+ ("500 Server Error: Internal Server Error for url: https://industrial.api.ubidots.com/api/v2.0/devices/",),
+ ("429 Client Error: Too Many Requests for url: https://things.ubidots.com/api/v2.0/variables/",),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.ubidots.source.validate_credentials")
+ def test_validate_credentials_delegates_to_shared_helper(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.return_value = (False, "Invalid Ubidots API token")
+ result = self.source.validate_credentials(self.config, self.team_id)
+ assert result == (False, "Invalid Ubidots API token")
+ mock_validate.assert_called_once_with("BBUS-token", "https://industrial.api.ubidots.com")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is UbidotsResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.ubidots.source.ubidots_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = VALUES_ENDPOINT
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1700000000000
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_token"] == "BBUS-token"
+ assert kwargs["api_base_url"] == "https://industrial.api.ubidots.com"
+ assert kwargs["endpoint"] == VALUES_ENDPOINT
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1700000000000
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown Ubidots schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/ubidots.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/ubidots.py
new file mode 100644
index 000000000000..b4da7e127877
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/ubidots.py
@@ -0,0 +1,325 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import datetime
+from typing import Any, Optional
+from urllib.parse import urlencode, urlparse, urlunparse
+
+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.ubidots.settings import (
+ ALLOWED_UBIDOTS_API_BASE_URLS,
+ DEFAULT_UBIDOTS_API_BASE_URL,
+ UBIDOTS_ENDPOINTS,
+ VALUES_ENDPOINT,
+ VALUES_PATH_TEMPLATE,
+)
+
+# The values endpoint defaults to 100 dots per page and the documented examples show page_size is
+# honored; 200 keeps pages modest while halving round trips on large time series.
+PAGE_SIZE = 200
+REQUEST_TIMEOUT_SECONDS = 60
+# Hard cap on values pages fetched per variable in a single sync, to bound worst-case scans of
+# multi-year telemetry. Newest dots come first, so a capped first sync keeps the most recent
+# history and later incremental syncs stay complete from the watermark forward.
+MAX_VALUES_PAGES_PER_VARIABLE = 10_000
+VARIABLES_LIST_PATH = "/api/v2.0/variables/"
+# Cheap list probe used to confirm a token is genuine. Ubidots tokens are account-wide, so one
+# probe validates access to every endpoint.
+DEFAULT_PROBE_PATH = "/api/v2.0/devices/"
+
+
+class UbidotsRetryableError(Exception):
+ pass
+
+
+class UbidotsResumeConfig:
+ # Full URL of the next page to fetch, verbatim from the API's ``next`` link (Ubidots uses
+ # DRF-style page-number pagination with count/next/previous/results). For the values stream
+ # this is the next page within ``current_variable_id``.
+ next_url: str | None = None
+ # Values stream only: the variable whose pages ``next_url`` continues, plus the variables
+ # already fully synced this run, so a resumed job skips straight past them.
+ current_variable_id: str | None = None
+ completed_variable_ids: list[str] = dataclasses.field(default_factory=list)
+
+
+def _headers(api_token: str) -> dict[str, str]:
+ # X-Auth-Token is Ubidots' recommended production auth; the ?token= query param would leak the
+ # token into request logs.
+ return {"X-Auth-Token": api_token, "Accept": "application/json"}
+
+
+def _validated_api_base_url(api_base_url: str | None) -> str:
+ normalized = (api_base_url or DEFAULT_UBIDOTS_API_BASE_URL).rstrip("/")
+ if normalized not in ALLOWED_UBIDOTS_API_BASE_URLS:
+ raise ValueError(
+ "API base URL must be one of https://industrial.api.ubidots.com or https://things.ubidots.com."
+ )
+ return normalized
+
+
+def _validated_page_url(url: str, base_url: str) -> str:
+ """Pin pagination and resume URLs to the configured Ubidots host.
+
+ ``next`` links come from API responses and resume cursors come from Redis; neither may
+ redirect the token-bearing session off the configured host. A matching-host http link is
+ upgraded to https rather than rejected, since proxied APIs sometimes emit http next links.
+ """
+ parsed = urlparse(url)
+ if parsed.netloc != urlparse(base_url).netloc or parsed.scheme not in ("http", "https"):
+ raise ValueError(f"Refusing to follow pagination URL off the configured Ubidots host: {url}")
+ if parsed.scheme == "http":
+ return urlunparse(parsed._replace(scheme="https"))
+ return url
+
+
+def _start_timestamp_ms(value: Any) -> Optional[int]:
+ """Coerce an incremental watermark into the millisecond epoch integer `start` expects."""
+ if value is None:
+ return None
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, int | float):
+ return int(value)
+ if isinstance(value, datetime):
+ return int(value.timestamp() * 1000)
+ try:
+ return int(str(value))
+ except ValueError:
+ return None
+
+
+@retry(
+ retry=retry_if_exception_type((UbidotsRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ logger: FilteringBoundLogger,
+) -> tuple[list[dict[str, Any]], Optional[str]]:
+ # ``url`` is always absolute — either the initial endpoint URL or a verbatim ``next`` link, so
+ # page params are baked in and never re-sent.
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise UbidotsRetryableError(f"Ubidots API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Ubidots API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ data = response.json()
+ if not isinstance(data, dict) or not isinstance(data.get("results"), list):
+ raise UbidotsRetryableError(f"Ubidots returned an unexpected payload for {url}: {type(data).__name__}")
+
+ next_url = data.get("next")
+ return data["results"], next_url if isinstance(next_url, str) and next_url else None
+
+
+def get_rows(
+ api_token: str,
+ api_base_url: str | None,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[UbidotsResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = UBIDOTS_ENDPOINTS[endpoint]
+ base_url = _validated_api_base_url(api_base_url)
+ session = make_tracked_session(headers=_headers(api_token), redact_values=(api_token,))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ url: Optional[str] = (
+ _validated_page_url(resume.next_url, base_url)
+ if (resume and resume.next_url)
+ else f"{base_url}{config.path}?{urlencode({'page_size': PAGE_SIZE})}"
+ )
+ if resume and resume.next_url:
+ logger.debug(f"Ubidots: resuming {endpoint} from cursor {url}")
+
+ while url:
+ items, next_url = _fetch_page(session, url, logger)
+ if items:
+ yield items
+
+ # A null ``next`` link means we've reached the end of the collection.
+ if not next_url:
+ break
+
+ url = _validated_page_url(next_url, base_url)
+ # Save AFTER yielding so a crash re-fetches from the next cursor (already-yielded pages are
+ # persisted); merge dedupes the re-pulled page on the primary key.
+ resumable_source_manager.save_state(UbidotsResumeConfig(next_url=url))
+
+
+def _iter_variable_ids(
+ session: requests.Session,
+ base_url: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[str]:
+ """List every variable id via the v2.0 API — the parent set the values stream fans out over."""
+ url: Optional[str] = f"{base_url}{VARIABLES_LIST_PATH}?{urlencode({'page_size': PAGE_SIZE})}"
+ while url:
+ items, next_url = _fetch_page(session, url, logger)
+ url = _validated_page_url(next_url, base_url) if next_url else None
+ for item in items:
+ # Direct access on purpose: a variable without an id would otherwise silently drop its
+ # whole time series from the sync — better to fail loudly on a malformed page.
+ yield str(item["id"])
+
+
+def _initial_values_url(base_url: str, variable_id: str, start: Optional[int]) -> str:
+ params: dict[str, Any] = {"page_size": PAGE_SIZE}
+ if start is not None:
+ # `start` is inclusive, so the boundary dot is re-pulled and deduped by the merge on
+ # ["variable", "timestamp"] — safer than +1ms arithmetic on the watermark.
+ params["start"] = start
+ return f"{base_url}{VALUES_PATH_TEMPLATE.format(variable_id=variable_id)}?{urlencode(params)}"
+
+
+def get_values_rows(
+ api_token: str,
+ api_base_url: str | None,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[UbidotsResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ base_url = _validated_api_base_url(api_base_url)
+ session = make_tracked_session(headers=_headers(api_token), redact_values=(api_token,))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ completed: set[str] = set(resume.completed_variable_ids) if resume else set()
+ resume_variable_id = resume.current_variable_id if resume else None
+ resume_next_url = resume.next_url if resume else None
+
+ start = _start_timestamp_ms(db_incremental_field_last_value) if should_use_incremental_field else None
+
+ for variable_id in _iter_variable_ids(session, base_url, logger):
+ if variable_id in completed:
+ continue
+
+ if variable_id == resume_variable_id and resume_next_url:
+ url: Optional[str] = _validated_page_url(resume_next_url, base_url)
+ logger.debug(f"Ubidots: resuming values for variable {variable_id} from cursor {url}")
+ else:
+ url = _initial_values_url(base_url, variable_id, start)
+
+ pages_fetched = 0
+ while url:
+ items, next_url = _fetch_page(session, url, logger)
+ if items:
+ # Dots don't carry their variable, so inject the parent id — it's half the
+ # composite primary key and the join key to the variables table.
+ yield [{**item, "variable": variable_id} for item in items]
+
+ pages_fetched += 1
+ if not next_url:
+ break
+ if pages_fetched >= MAX_VALUES_PAGES_PER_VARIABLE:
+ logger.warning(
+ f"Ubidots: hit the {MAX_VALUES_PAGES_PER_VARIABLE}-page cap for variable {variable_id}; "
+ "older values were not fetched this sync"
+ )
+ break
+
+ url = _validated_page_url(next_url, base_url)
+ # Save AFTER yielding so a crash re-fetches from the next cursor; merge dedupes the
+ # re-pulled page on ["variable", "timestamp"].
+ resumable_source_manager.save_state(
+ UbidotsResumeConfig(
+ next_url=url,
+ current_variable_id=variable_id,
+ completed_variable_ids=sorted(completed),
+ )
+ )
+
+ completed.add(variable_id)
+ resumable_source_manager.save_state(UbidotsResumeConfig(completed_variable_ids=sorted(completed)))
+
+
+def ubidots_source(
+ api_token: str,
+ api_base_url: str | None,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[UbidotsResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> SourceResponse:
+ config = UBIDOTS_ENDPOINTS[endpoint]
+
+ if endpoint == VALUES_ENDPOINT:
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_values_rows(
+ api_token=api_token,
+ api_base_url=api_base_url,
+ 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,
+ partition_count=1,
+ partition_size=1,
+ # Values return newest first and the API exposes no ascending sort, so the incremental
+ # watermark is only committed once the whole sync completes.
+ sort_mode="desc",
+ )
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_token,
+ api_base_url=api_base_url,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ )
+
+
+def check_access(api_token: str, api_base_url: str | None, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single cheap endpoint to validate the API token.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise.
+ """
+ base_url = _validated_api_base_url(api_base_url)
+ session = make_tracked_session(headers=_headers(api_token), redact_values=(api_token,))
+ try:
+ response = session.get(f"{base_url}{path}?{urlencode({'page_size': 1})}", timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to Ubidots: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"Ubidots returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(api_token: str, api_base_url: str | None) -> tuple[bool, str | None]:
+ try:
+ status, message = check_access(api_token, api_base_url)
+ except ValueError as e:
+ return False, str(e)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid Ubidots API token"
+ return False, message or "Could not validate Ubidots API token"