:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse_sources): support Ubidots API version v2.0 (#74177)
Tom Owers5ddef345691d
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.pyindex 622dd66eea6a..e1a77a2c939d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/settings.py@@ -32,10 +32,13 @@ class UbidotsEndpointConfig: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).+# The `values` stream fans out per variable: v2.0 lists the variables, then the Data API pages+# through each variable's time-series dots. The Data API is versioned separately from the entity+# API — the legacy "v1" source version reads dots from the v1.6 paginated per-variable endpoint,+# while the "v2.0" source version reads them from the v2.0 `data/series` batch endpoint.VALUES_ENDPOINT = "values"VALUES_PATH_TEMPLATE = "/api/v1.6/variables/{variable_id}/values"+DATA_SERIES_PATH = "/api/v2.0/data/series/"UBIDOTS_ENDPOINTS: dict[str, UbidotsEndpointConfig] = {"devices": UbidotsEndpointConfig(name="devices", path="/api/v2.0/devices/"),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.pyindex ec387db1fc30..24a5eb0a1131 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@@ -32,6 +32,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.ubidots.seUBIDOTS_ENDPOINTS,)from products.warehouse_sources.backend.temporal.data_imports.sources.ubidots.ubidots import (+ SUPPORTED_UBIDOTS_API_VERSIONS,+ UBIDOTS_API_VERSION_V2_0,UbidotsResumeConfig,ubidots_source,validate_credentials,@@ -43,6 +45,8 @@ from products.warehouse_sources.backend.types import ExternalDataSourceTypeclass UbidotsSource(ResumableSource[UbidotsSourceConfig, UbidotsResumeConfig]):lists_tables_without_credentials = True # static endpoint catalog — safe for public docsapi_docs_url = "https://docs.ubidots.com/reference/welcome"+ supported_versions = SUPPORTED_UBIDOTS_API_VERSIONS+ default_version = UBIDOTS_API_VERSION_V2_0@propertydef source_type(self) -> ExternalDataSourceType:@@ -123,8 +127,9 @@ Use the permanent token from **your profile → API Credentials** in Ubidots —force_refresh: bool = False,api_version: str | None = None,) -> 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.+ # The table set is version-independent: every version discovers entities through the v2.0+ # entity API, so the pin doesn't change which schemas exist. Only `values` filters+ # server-side (`start`/`end` ms); metadata endpoints expose no update cursor (full refresh).schemas = [SourceSchema(name=endpoint,@@ -146,7 +151,8 @@ Use the permanent token from **your profile → API Credentials** in Ubidots —schema_name: Optional[str] = None,api_version: str | None = None,) -> tuple[bool, str | None]:- # Ubidots tokens are account-wide, so a single probe validates access to every schema.+ # Ubidots tokens are account-wide, so a single probe validates access to every schema. The+ # probe hits the v2.0 entity API, which every version uses, so the pin makes no difference.return validate_credentials(config.api_token, config.api_base_url)def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[UbidotsResumeConfig]:@@ -167,6 +173,7 @@ Use the permanent token from **your profile → API Credentials** in Ubidots —endpoint=inputs.schema_name,logger=inputs.logger,resumable_source_manager=resumable_source_manager,+ api_version=self.resolve_api_version(inputs.api_version),should_use_incremental_field=inputs.should_use_incremental_field,db_incremental_field_last_value=inputs.db_incremental_field_last_value,)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.pyindex 2920776aefe4..e4f3f1e7d43e 100644--- 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@@ -1,8 +1,10 @@-from collections.abc import Mapping+import json+from collections.abc import Iterator, Mappingfrom datetime import UTC, datetimefrom typing import Any, Optionalimport pytest+from freezegun import freeze_timefrom unittest.mock import MagicMock, patchimport requests@@ -15,6 +17,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.ubidots.seVALUES_ENDPOINT,)from products.warehouse_sources.backend.temporal.data_imports.sources.ubidots.ubidots import (+ MAX_EMPTY_VALUES_WINDOWS,+ UBIDOTS_API_VERSION_LEGACY,+ UBIDOTS_API_VERSION_V2_0,+ VALUES_WINDOW_MS,+ UbidotsResponseTooLargeError,+ UbidotsResponseTooSlowError,UbidotsResumeConfig,UbidotsRetryableError,_start_timestamp_ms,@@ -23,6 +31,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.ubidots.ubcheck_access,get_rows,get_values_rows,+ get_values_rows_v2,ubidots_source,validate_credentials,)@@ -459,6 +468,7 @@ class TestUbidotsSourceResponse:endpoint=endpoint,logger=MagicMock(),resumable_source_manager=MagicMock(),+ api_version=UBIDOTS_API_VERSION_LEGACY,)assert response.name == endpointif endpoint == VALUES_ENDPOINT:@@ -469,3 +479,248 @@ class TestUbidotsSourceResponse:else:assert response.primary_keys == ["id"]assert response.sort_mode == "asc"++ @pytest.mark.parametrize(+ "api_version,expected_fn",+ [+ pytest.param(UBIDOTS_API_VERSION_LEGACY, "get_values_rows", id="legacy"),+ pytest.param(UBIDOTS_API_VERSION_V2_0, "get_values_rows_v2", id="v2_0"),+ pytest.param("v9.9", "get_values_rows", id="unknown_pin_falls_back_to_legacy"),+ ],+ )+ def test_values_stream_dispatches_on_api_version(+ self, api_version: str, expected_fn: str, monkeypatch: Any+ ) -> None:+ # The values stream is the only version-dependent surface: "v2.0" reads via the v2.0 Data+ # API, every other pin via the legacy v1.6 endpoint. A misroute would sync the wrong wire.+ called: list[str] = []++ def _recorder(fn_name: str) -> Any:+ def _fn(**kwargs: Any) -> Iterator[list[dict]]:+ called.append(fn_name)+ return iter(())++ return _fn++ for name in ("get_values_rows", "get_values_rows_v2"):+ monkeypatch.setattr(ubidots, name, _recorder(name))++ response = ubidots_source(+ api_token="BBUS-token",+ api_base_url=None,+ endpoint=VALUES_ENDPOINT,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ api_version=api_version,+ )+ # Invoking the lazy items() thunk is what selects and calls the version-specific fetcher.+ response.items()+ assert called == [expected_fn]+++@freeze_time("2026-07-28T00:00:00Z")+class TestGetValuesRowsV2:+ NOW_MS = int(datetime(2026, 7, 28, tzinfo=UTC).timestamp() * 1000)++ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ variable_pages: Mapping[str, tuple[list[dict], Optional[str]]],+ series_by_variable: Mapping[str, list[dict]],+ bodies: list[dict] | None = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ logger: Any = None,+ ) -> list[dict]:+ def fake_fetch_page(session: Any, url: str, log: Any) -> tuple[list[dict], Optional[str]]:+ return variable_pages[url]++ # Dots live in the newest window only; every older window comes back empty, which is what a+ # real variable with a finite history looks like to the descending walk.+ served: set[str] = set()++ def fake_fetch_series(session: Any, url: str, body: dict, log: Any) -> list[dict]:+ if bodies is not None:+ bodies.append(body)+ variable_id = body["variables"][0]["variable"]+ entries = series_by_variable[variable_id]+ if variable_id in served:+ return [{**entry, "results": []} for entry in entries]+ served.add(variable_id)+ return entries++ monkeypatch.setattr(ubidots, "_fetch_page", fake_fetch_page)+ monkeypatch.setattr(ubidots, "_fetch_data_series", fake_fetch_series)+ monkeypatch.setattr(ubidots, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_values_rows_v2(+ 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()+ rows = self._collect(+ manager,+ monkeypatch,+ variable_pages={VARIABLES_FIRST_URL: ([{"id": "var1"}, {"id": "var2"}], None)},+ series_by_variable={+ "var1": [{"variable": {"id": "var1"}, "code": 200, "results": [{"timestamp": 2, "value": 1.0}]}],+ "var2": [{"variable": {"id": "var2"}, "code": 200, "results": [{"timestamp": 3, "value": 2.0}]}],+ },+ )+ assert rows == [+ {"timestamp": 2, "value": 1.0, "variable": "var1"},+ {"timestamp": 3, "value": 2.0, "variable": "var2"},+ ]+ completions = [s.completed_variable_ids for s in manager.saved if s.current_window_end is None]+ assert completions == [["var1"], ["var1", "var2"]]++ def test_full_refresh_walks_bounded_windows_newest_first(self, monkeypatch: Any) -> None:+ # The v2.0 endpoint is unpaginated, so an unwindowed request would pull a variable's whole+ # history into memory in one response.+ bodies: list[dict] = []+ self._collect(+ _FakeResumableManager(),+ monkeypatch,+ variable_pages={VARIABLES_FIRST_URL: ([{"id": "var1"}], None)},+ series_by_variable={"var1": [{"variable": {"id": "var1"}, "code": 200, "results": [{"timestamp": 1}]}]},+ bodies=bodies,+ )+ assert all(body["end"] - body["start"] == VALUES_WINDOW_MS for body in bodies)+ assert [body["end"] for body in bodies] == [self.NOW_MS - i * VALUES_WINDOW_MS for i in range(len(bodies))]+ # One window with dots, then the run of empties that ends the walk — not a scan to the epoch.+ assert len(bodies) == 1 + MAX_EMPTY_VALUES_WINDOWS++ def test_incremental_walk_floors_at_the_watermark(self, monkeypatch: Any) -> None:+ # Empty windows must not cut an incremental run short: the range down to the watermark is+ # known and has to be covered even where the variable went quiet.+ watermark = self.NOW_MS - int(2.5 * VALUES_WINDOW_MS)+ bodies: list[dict] = []+ rows = self._collect(+ _FakeResumableManager(),+ monkeypatch,+ variable_pages={VARIABLES_FIRST_URL: ([{"id": "var1"}], None)},+ series_by_variable={+ "var1": [{"variable": {"id": "var1"}, "code": 200, "results": [{"timestamp": watermark + 1}]}]+ },+ bodies=bodies,+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )+ assert rows == [{"timestamp": watermark + 1, "variable": "var1"}]+ assert len(bodies) == 3+ assert bodies[0]["end"] == self.NOW_MS+ assert bodies[-1]["start"] == watermark+ assert all(body["start"] >= watermark for body in bodies)++ def test_resume_continues_variable_from_saved_window_end(self, monkeypatch: Any) -> None:+ resume_end = self.NOW_MS - 5 * VALUES_WINDOW_MS+ manager = _FakeResumableManager(UbidotsResumeConfig(current_variable_id="var1", current_window_end=resume_end))+ bodies: list[dict] = []+ self._collect(+ manager,+ monkeypatch,+ variable_pages={VARIABLES_FIRST_URL: ([{"id": "var1"}], None)},+ series_by_variable={"var1": [{"variable": {"id": "var1"}, "code": 200, "results": [{"timestamp": 1}]}]},+ bodies=bodies,+ )+ # Resuming from `now` instead would re-fetch every window the interrupted run already did.+ assert bodies[0]["end"] == resume_end+ assert manager.saved[0].current_window_end == resume_end - VALUES_WINDOW_MS++ def test_variable_with_error_code_is_skipped_but_completed(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ logger = MagicMock()+ rows = self._collect(+ manager,+ monkeypatch,+ variable_pages={VARIABLES_FIRST_URL: ([{"id": "var1"}], None)},+ # A per-variable 403/404 arrives as a non-200 code inside the 200 envelope.+ series_by_variable={"var1": [{"variable": {"id": "var1"}, "code": 403, "results": []}]},+ logger=logger,+ )+ assert rows == []+ logger.warning.assert_called_once()+ assert manager.saved[-1].completed_variable_ids == ["var1"]++ def test_resume_skips_completed_variables(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(UbidotsResumeConfig(completed_variable_ids=["var1"]))+ rows = self._collect(+ manager,+ monkeypatch,+ variable_pages={VARIABLES_FIRST_URL: ([{"id": "var1"}, {"id": "var2"}], None)},+ # var1 is already complete — its series must never be requested on resume.+ series_by_variable={"var2": [{"variable": {"id": "var2"}, "code": 200, "results": [{"timestamp": 9}]}]},+ )+ assert rows == [{"timestamp": 9, "variable": "var2"}]+++class TestFetchDataSeries:+ @staticmethod+ def _session_returning(status_code: int, body: Any = None, raw: bytes | None = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ payload = raw if raw is not None else json.dumps(body if body is not None else {"results": []}).encode()+ # The fetcher reads bodies with stream=True via response.iter_content.+ response.iter_content.return_value = iter([payload])+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.post.return_value = response+ return session++ @staticmethod+ def _fetch(session: MagicMock) -> list[dict]:+ return ubidots._fetch_data_series.__wrapped__( # type: ignore[attr-defined]+ session, f"{DEFAULT_UBIDOTS_API_BASE_URL}/api/v2.0/data/series/", {"variables": []}, MagicMock()+ )++ def test_success_returns_results_list(self) -> None:+ entry = {"variable": {"id": "var1"}, "code": 200, "results": [{"timestamp": 1, "value": 2.0}]}+ assert self._fetch(self._session_returning(200, {"start": 0, "end": 1, "results": [entry]})) == [entry]++ @parameterized.expand([("rate_limited", 429), ("server_error", 500)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ with pytest.raises(UbidotsRetryableError):+ self._fetch(self._session_returning(status))++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ with pytest.raises(requests.HTTPError):+ self._fetch(self._session_returning(status))++ @parameterized.expand(+ [+ ("list_envelope", b'[{"code": 200}]'),+ ("results_not_a_list", b'{"results": {}}'),+ ("not_json", b"<html>gateway</html>"),+ ]+ )+ def test_malformed_payloads_raise_retryable_error(self, _name: str, raw: bytes) -> None:+ # A proxy or an API change can answer 200 with something that isn't the documented envelope;+ # indexing it blindly would blow up with a TypeError halfway through a sync.+ with pytest.raises(UbidotsRetryableError):+ self._fetch(self._session_returning(200, raw=raw))++ def test_oversized_body_is_refused_before_parsing(self) -> None:+ session = self._session_returning(200, raw=b'{"results": []}')+ with patch.object(ubidots, "MAX_RESPONSE_BYTES", 4), pytest.raises(UbidotsResponseTooLargeError):+ self._fetch(session)++ def test_slow_body_is_refused(self) -> None:+ # A host dribbling the body stays under the per-read timeout indefinitely; only the+ # wall-clock budget stops it holding an import worker open.+ session = self._session_returning(200, raw=b'{"results": []}')+ with patch.object(ubidots, "MAX_DOWNLOAD_SECONDS", -1), pytest.raises(UbidotsResponseTooSlowError):+ self._fetch(session)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.pyindex b6a0774e6b8e..19df12c7ac3d 100644--- 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@@ -104,12 +104,19 @@ class TestUbidotsSource:assert isinstance(manager, ResumableSourceManager)assert manager._data_class is UbidotsResumeConfig+ def test_version_declarations(self) -> None:+ # v2.0 is the default new sources are stamped with; v1 stays supported so existing pins keep+ # syncing through the legacy v1.6 Data API.+ assert self.source.supported_versions == ("v1", "v2.0")+ assert self.source.default_version == "v2.0"+@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_ENDPOINTinputs.should_use_incremental_field = Trueinputs.db_incremental_field_last_value = 1700000000000+ inputs.api_version = Nonemanager = mock.MagicMock()self.source.source_for_pipeline(self.config, manager, inputs)@@ -123,6 +130,25 @@ class TestUbidotsSource:assert kwargs["should_use_incremental_field"] is Trueassert kwargs["db_incremental_field_last_value"] == 1700000000000+ @parameterized.expand(+ [+ ("no_pin_resolves_to_default", None, "v2.0"),+ ("legacy_pin_honored", "v1", "v1"),+ ("v2_pin_honored", "v2.0", "v2.0"),+ ]+ )+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.ubidots.source.ubidots_source")+ def test_source_for_pipeline_threads_resolved_api_version(+ self, _name: str, pin: str | None, expected: str, mock_source: mock.MagicMock+ ) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = VALUES_ENDPOINT+ inputs.api_version = pin++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_source.call_args.kwargs["api_version"] == expected+def test_source_for_pipeline_rejects_unknown_schema(self) -> None:inputs = mock.MagicMock()inputs.schema_name = "not_a_table"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.pyindex b4da7e127877..ad1e41dcd7b3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/ubidots.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/ubidots.py@@ -1,3 +1,5 @@+import json+import timeimport dataclassesfrom collections.abc import Iteratorfrom datetime import datetime@@ -9,16 +11,26 @@ from structlog.types import FilteringBoundLoggerfrom tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitterfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import UNVERSIONED_API_VERSIONfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.ubidots.settings import (ALLOWED_UBIDOTS_API_BASE_URLS,+ DATA_SERIES_PATH,DEFAULT_UBIDOTS_API_BASE_URL,UBIDOTS_ENDPOINTS,VALUES_ENDPOINT,VALUES_PATH_TEMPLATE,)+# Supported Ubidots API versions, as opaque vendor labels (never parsed or ordered). Every version+# reads entity endpoints (devices, variables, ...) from the v2.0 entity API and differs only in the+# Data API used for the `values` stream: the legacy "v1" line reads dots from the v1.6 paginated+# per-variable endpoint, "v2.0" reads them from the v2.0 `data/series` batch endpoint.+UBIDOTS_API_VERSION_LEGACY = UNVERSIONED_API_VERSION # "v1"+UBIDOTS_API_VERSION_V2_0 = "v2.0"+SUPPORTED_UBIDOTS_API_VERSIONS = (UBIDOTS_API_VERSION_LEGACY, UBIDOTS_API_VERSION_V2_0)+# 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@@ -32,11 +44,44 @@ VARIABLES_LIST_PATH = "/api/v2.0/variables/"# probe validates access to every endpoint.DEFAULT_PROBE_PATH = "/api/v2.0/devices/"+# The v2.0 `data/series` endpoint has no server-side pagination, so the requested window is the+# only thing bounding a response. Walk each variable newest-first in fixed windows so a single+# request can never cover an unbounded history, and cap the windows per sync the way the legacy+# path caps pages.+VALUES_WINDOW_MS = 30 * 24 * 60 * 60 * 1000+MAX_VALUES_WINDOWS_PER_VARIABLE = 120+# A full refresh has no watermark to walk back to. Rather than request empty windows all the way+# to the epoch, stop once a variable has clearly run out of history. Six windows tolerates half a+# year of silence mid-history; anything longer is truncated, same as the legacy page cap.+MAX_EMPTY_VALUES_WINDOWS = 6++# `requests` buffers a whole body into memory before it can be parsed, and the window is a time+# bound rather than a size one — a high-frequency variable can still answer with a very large+# response. Cap what is read, and put a wall-clock budget on the read so a host that dribbles the+# body under the per-read timeout can't hold a shared import worker open indefinitely.+MAX_RESPONSE_BYTES = 256 * 1024 * 1024+RESPONSE_CHUNK_BYTES = 256 * 1024+MAX_DOWNLOAD_SECONDS = 300+# Error bodies can be as large as the response cap, so log a small preview plus the byte length+# rather than interpolating the whole thing into a log event.+ERROR_BODY_LOG_PREVIEW_BYTES = 8 * 1024++RESPONSE_TOO_LARGE_ERROR = "Ubidots response body was too large"+RESPONSE_TOO_SLOW_ERROR = "Ubidots response download was too slow"+class UbidotsRetryableError(Exception):pass+class UbidotsResponseTooLargeError(Exception):+ pass+++class UbidotsResponseTooSlowError(Exception):+ pass++@dataclasses.dataclassclass UbidotsResumeConfig:# Full URL of the next page to fetch, verbatim from the API's ``next`` link (Ubidots uses@@ -47,6 +92,10 @@ class UbidotsResumeConfig:# already fully synced this run, so a resumed job skips straight past them.current_variable_id: str | None = Nonecompleted_variable_ids: list[str] = dataclasses.field(default_factory=list)+ # Values stream on the v2.0 Data API only: upper bound of the next window to request for+ # ``current_variable_id``. That path walks time windows backwards instead of following pages,+ # so this is its equivalent of ``next_url``.+ current_window_end: int | None = Nonedef _headers(api_token: str) -> dict[str, str]:@@ -246,21 +295,211 @@ def get_values_rows(resumable_source_manager.save_state(UbidotsResumeConfig(completed_variable_ids=sorted(completed)))+def _read_capped_body(response: requests.Response) -> bytes:+ """Stream the body into memory, aborting past MAX_RESPONSE_BYTES or MAX_DOWNLOAD_SECONDS.++ Both caps are non-retryable: re-issuing the same request yields the same oversized or slow+ body, so failing the sync with a clear error beats burning retries on it.+ """+ chunks: list[bytes] = []+ total = 0+ deadline = time.monotonic() + MAX_DOWNLOAD_SECONDS+ try:+ for chunk in response.iter_content(chunk_size=RESPONSE_CHUNK_BYTES):+ if time.monotonic() > deadline:+ raise UbidotsResponseTooSlowError(+ f"{RESPONSE_TOO_SLOW_ERROR}: exceeded {MAX_DOWNLOAD_SECONDS}s download budget"+ )+ if not chunk:+ continue+ total += len(chunk)+ if total > MAX_RESPONSE_BYTES:+ raise UbidotsResponseTooLargeError(f"{RESPONSE_TOO_LARGE_ERROR}: exceeded {MAX_RESPONSE_BYTES} bytes")+ chunks.append(chunk)+ finally:+ response.close()+ return b"".join(chunks)+++@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_data_series(+ session: requests.Session,+ url: str,+ body: dict[str, Any],+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ """POST the v2.0 `data/series` endpoint and return its per-variable ``results`` list."""+ # stream=True so the body isn't buffered before we can cap it — see _read_capped_body.+ response = session.post(url, json=body, timeout=REQUEST_TIMEOUT_SECONDS, stream=True)++ if response.status_code == 429 or response.status_code >= 500:+ response.close()+ raise UbidotsRetryableError(f"Ubidots API error (retryable): status={response.status_code}, url={url}")++ raw = _read_capped_body(response)++ if not response.ok:+ preview = raw[:ERROR_BODY_LOG_PREVIEW_BYTES].decode(errors="replace")+ logger.error(+ f"Ubidots API error: status={response.status_code}, body_bytes={len(raw)}, "+ f"body_preview={preview}, url={url}"+ )+ response.raise_for_status()++ try:+ data = json.loads(raw or b"null")+ except ValueError as e:+ raise UbidotsRetryableError(f"Ubidots returned a non-JSON payload for {url}") from e+ 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__}")++ return data["results"]+++def _fetch_values_window(+ session: requests.Session,+ url: str,+ variable_id: str,+ window_start: int,+ window_end: int,+ logger: FilteringBoundLogger,+) -> Optional[list[dict[str, Any]]]:+ """Fetch one ``[window_start, window_end]`` window of a variable's dots.++ Returns the window's rows, or ``None`` when the API reported a per-variable failure, so the+ caller knows to give up on this variable rather than keep walking its history.+ """+ body = {"start": window_start, "end": window_end, "variables": [{"variable": variable_id}]}+ results = _fetch_data_series(session, url, body, logger)++ # A single-variable request returns at most one entry; match by id in case the API echoes+ # extra entries. Per-variable 403/404 arrive as a non-200 ``code`` inside the 200 envelope.+ entry = next((r for r in results if str((r.get("variable") or {}).get("id")) == variable_id), None)+ if entry is None or entry.get("code") != 200:+ logger.warning(f"Ubidots: skipping variable {variable_id} (data/series code={entry and entry.get('code')})")+ return None++ points = entry.get("results") or []+ # 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.+ return [{**point, "variable": variable_id} for point in points if isinstance(point, dict)]+++def get_values_rows_v2(+ 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]]]:+ """Values stream for the v2.0 source version, via the v2.0 Data API `data/series` endpoint.++ Variables are still listed through the v2.0 entity API; dots are then fetched one variable at a+ time. This batch API has no server-side pagination, so the requested time range is the only+ thing bounding a response: each variable's history is walked in `VALUES_WINDOW_MS` windows,+ newest first, and resume is per window (``current_window_end``) within a variable.++ An incremental run walks down to the watermark exactly. A full refresh has no lower bound, so it+ stops after `MAX_EMPTY_VALUES_WINDOWS` consecutive empty windows (or the per-variable window+ cap) and keeps the most recent history — the same trade-off the legacy path makes with its page+ cap, and later incremental runs stay complete from the watermark forward.+ """+ 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_window_end = resume.current_window_end if resume else None++ now_ms = int(time.time() * 1000)+ watermark = _start_timestamp_ms(db_incremental_field_last_value) if should_use_incremental_field else None+ # A future-dated watermark (bad clock upstream) would build an inverted window every run;+ # clamping to now keeps the sync self-healing.+ floor = min(watermark, now_ms) if watermark is not None else None+ url = f"{base_url}{DATA_SERIES_PATH}?{urlencode({'results_format': 'object'})}"++ 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_window_end is not None:+ window_end = resume_window_end+ logger.debug(f"Ubidots: resuming values for variable {variable_id} from window end {window_end}")+ else:+ window_end = now_ms+ if floor is not None:+ window_end = max(window_end, floor)++ windows_fetched = 0+ empty_windows = 0+ while True:+ window_start = window_end - VALUES_WINDOW_MS+ if floor is not None:+ window_start = max(window_start, floor)++ rows = _fetch_values_window(session, url, variable_id, window_start, window_end, logger)+ windows_fetched += 1+ if rows is None:+ break++ if rows:+ empty_windows = 0+ yield rows+ else:+ empty_windows += 1++ if floor is not None and window_start <= floor:+ break+ if floor is None and empty_windows >= MAX_EMPTY_VALUES_WINDOWS:+ break+ if windows_fetched >= MAX_VALUES_WINDOWS_PER_VARIABLE:+ logger.warning(+ f"Ubidots: hit the {MAX_VALUES_WINDOWS_PER_VARIABLE}-window cap for variable {variable_id}; "+ "older values were not fetched this sync"+ )+ break++ # Windows share their boundary timestamp, so the boundary dot is re-pulled and deduped+ # by the merge on ["variable", "timestamp"] — safer than 1ms arithmetic.+ window_end = window_start+ # Save AFTER yielding so a crash re-fetches this window rather than skipping it.+ resumable_source_manager.save_state(+ UbidotsResumeConfig(+ current_variable_id=variable_id,+ current_window_end=window_end,+ 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],+ api_version: str,should_use_incremental_field: bool = False,db_incremental_field_last_value: Any = None,) -> SourceResponse:config = UBIDOTS_ENDPOINTS[endpoint]if endpoint == VALUES_ENDPOINT:+ # The Data API diverges by version; every other stream is version-independent (v2.0 entities).+ values_fn = get_values_rows_v2 if api_version == UBIDOTS_API_VERSION_V2_0 else get_values_rowsreturn SourceResponse(name=endpoint,- items=lambda: get_values_rows(+ items=lambda: values_fn(api_token=api_token,api_base_url=api_base_url,logger=logger,