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): resumable rest_source paginators + first source migration (alguna) (#71520)

Tom Owers8ec3def41193
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/alguna.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/alguna.py
index c0e0f838883d..12894bc66ef9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/alguna.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/alguna.py
@@ -1,144 +1,114 @@
import dataclasses
-from collections.abc import Iterator
-from typing import Any
-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 typing import Any, Optional
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.alguna.settings import ALGUNA_ENDPOINTS
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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ OffsetPaginator,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
ALGUNA_BASE_URL = "https://api.alguna.io"
# Alguna's API is date-versioned; every request must send this header or calls fail.
ALGUNA_API_VERSION = "2026-04-01"
PAGE_LIMIT = 100
-REQUEST_TIMEOUT_SECONDS = 60
-
-
-class AlgunaRetryableError(Exception):
- pass
@dataclasses.dataclass
class AlgunaResumeConfig:
- # Byte-for-byte deterministic restart point: list endpoints paginate with required
- # limit/offset params, so the row offset of the next unfetched page is the full resume state.
+ # Row offset of the next unfetched page — Alguna list endpoints paginate with limit/offset.
offset: int = 0
-def _get_headers(api_key: str) -> dict[str, str]:
- return {
- "Authorization": f"Bearer {api_key}",
- "Alguna-Version": ALGUNA_API_VERSION,
- "Accept": "application/json",
- }
-
-
-def _build_url(path: str, params: dict[str, Any]) -> str:
- return f"{ALGUNA_BASE_URL}{path}?{urlencode(params)}"
-
-
-def validate_credentials(api_key: str) -> bool:
- url = _build_url("/customers", {"limit": 1, "offset": 0, "sort": "created_at:asc"})
- try:
- session = make_tracked_session(redact_values=(api_key,))
- response = session.get(url, headers=_get_headers(api_key), timeout=10)
- return response.status_code == 200
- except Exception:
- return False
-
-
-@retry(
- retry=retry_if_exception_type(
- (
- AlgunaRetryableError,
- requests.ReadTimeout,
- requests.ConnectionError,
- requests.exceptions.ChunkedEncodingError,
- )
- ),
- stop=stop_after_attempt(5),
- wait=wait_exponential_jitter(initial=1, max=30),
- reraise=True,
-)
-def _fetch_page(
- session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger
-) -> dict[str, Any]:
- response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
-
- if response.status_code == 429 or response.status_code >= 500:
- raise AlgunaRetryableError(f"Alguna API error (retryable): status={response.status_code}, url={url}")
-
- if not response.ok:
- logger.error(f"Alguna API error: status={response.status_code}, body={response.text}, url={url}")
- response.raise_for_status()
-
- return response.json()
-
-
-def get_rows(
- api_key: str,
- endpoint: str,
- logger: FilteringBoundLogger,
- resumable_source_manager: ResumableSourceManager[AlgunaResumeConfig],
-) -> Iterator[list[dict[str, Any]]]:
- config = ALGUNA_ENDPOINTS[endpoint]
- headers = _get_headers(api_key)
- session = make_tracked_session(redact_values=(api_key,))
-
- resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
- offset = resume.offset if resume is not None else 0
- if offset:
- logger.debug(f"Alguna: resuming {endpoint} from offset={offset}")
-
- while True:
- params: dict[str, Any] = {"limit": PAGE_LIMIT, "offset": offset}
- if config.sort is not None:
- params["sort"] = config.sort
-
- data = _fetch_page(session, _build_url(config.path, params), headers, logger)
- # Direct access: a 200 body without "data" means the response shape changed — fail the
- # sync loudly instead of silently reporting 0 rows.
- items = data["data"]
- if not items:
- break
-
- yield items
-
- offset += len(items)
- # A short page means we've reached the end; don't save state for a finished sync.
- if len(items) < PAGE_LIMIT:
- break
-
- # Save AFTER yielding so a crash re-yields the last page rather than skipping it —
- # merge dedupes on the primary key.
- resumable_source_manager.save_state(AlgunaResumeConfig(offset=offset))
+def _version_headers() -> dict[str, str]:
+ # Auth (Bearer) is supplied via the framework auth config so its value is redacted from logs;
+ # only the non-secret version/accept headers are set here.
+ return {"Alguna-Version": ALGUNA_API_VERSION, "Accept": "application/json"}
def alguna_source(
api_key: str,
endpoint: str,
- logger: FilteringBoundLogger,
+ team_id: int,
+ job_id: str,
resumable_source_manager: ResumableSourceManager[AlgunaResumeConfig],
+ db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
config = ALGUNA_ENDPOINTS[endpoint]
+ params: dict[str, Any] = {"limit": PAGE_LIMIT}
+ if config.sort is not None:
+ params["sort"] = config.sort
+
+ rest_config: RESTAPIConfig = {
+ "client": {
+ "base_url": ALGUNA_BASE_URL,
+ "headers": _version_headers(),
+ "auth": {"type": "bearer", "token": api_key},
+ # Alguna has no top-level `total`; termination is short/empty page (OffsetPaginator default).
+ "paginator": OffsetPaginator(limit=PAGE_LIMIT, total_path=None),
+ },
+ # Per-resource settings are fully specified below, so no shared defaults are needed.
+ "resource_defaults": {},
+ "resources": [
+ {
+ "name": endpoint,
+ "endpoint": {
+ "path": config.path,
+ "params": params,
+ "data_selector": "data",
+ # A 200 body without `data` means the response shape changed — fail loud
+ # instead of silently syncing 0 rows.
+ "data_selector_required": True,
+ },
+ }
+ ],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None:
+ initial_paginator_state = {"offset": resume.offset}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Persist only when a next page remains; save AFTER a page is yielded so a crash re-yields
+ # the last page (merge dedupes) rather than skipping it.
+ if state and state.get("offset") is not None:
+ resumable_source_manager.save_state(AlgunaResumeConfig(offset=int(state["offset"])))
+
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
return SourceResponse(
name=endpoint,
- items=lambda: get_rows(
- api_key=api_key,
- endpoint=endpoint,
- logger=logger,
- resumable_source_manager=resumable_source_manager,
- ),
+ items=lambda: resource,
primary_keys=config.primary_keys,
partition_count=1,
partition_size=1,
partition_mode="datetime",
partition_format="month",
partition_keys=[config.partition_key],
+ column_hints=resource.column_hints,
+ )
+
+
+def validate_credentials(api_key: str) -> bool:
+ ok, _status = validate_via_probe(
+ lambda: make_tracked_session(redact_values=(api_key,)),
+ f"{ALGUNA_BASE_URL}/customers?limit=1&offset=0&sort=created_at:asc",
+ headers={"Authorization": f"Bearer {api_key}", **_version_headers()},
)
+ return ok
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/settings.py
index 8c2641622212..828a367bc93f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/settings.py
@@ -33,4 +33,6 @@ ALGUNA_ENDPOINTS: dict[str, AlgunaEndpointConfig] = {
ENDPOINTS = tuple(ALGUNA_ENDPOINTS.keys())
-INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in ALGUNA_ENDPOINTS}
+# Empty: no endpoint exposes an incremental watermark (see the note above), so every stream is full
+# refresh. `build_endpoint_schemas` treats a missing entry — not an empty list — as non-incremental.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/source.py
index 92a87282fea6..6eb08b451319 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/source.py
@@ -29,7 +29,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
)
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.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AlgunaSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -95,19 +98,7 @@ You can create an API key in your Alguna dashboard under Settings > Credentials.
names: list[str] | None = None,
force_refresh: bool = False,
) -> list[SourceSchema]:
- schemas = [
- SourceSchema(
- name=endpoint,
- supports_incremental=False,
- supports_append=False,
- 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
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
def validate_credentials(
self, config: AlgunaSourceConfig, team_id: int, schema_name: Optional[str] = None
@@ -129,6 +120,8 @@ You can create an API key in your Alguna dashboard under Settings > Credentials.
return alguna_source(
api_key=config.api_key,
endpoint=inputs.schema_name,
- logger=inputs.logger,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
resumable_source_manager=resumable_source_manager,
+ db_incremental_field_last_value=None, # every Alguna endpoint is full refresh
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/tests/test_alguna.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/tests/test_alguna.py
index a4eb32b502e0..18ae6139ab23 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/tests/test_alguna.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/tests/test_alguna.py
@@ -1,26 +1,36 @@
+import json
from typing import Any
-from urllib.parse import parse_qs, urlparse
import pytest
from unittest import mock
-import requests
-from parameterized import parameterized
+from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.alguna.alguna import (
ALGUNA_API_VERSION,
AlgunaResumeConfig,
alguna_source,
- get_rows,
validate_credentials,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.alguna.settings import ALGUNA_ENDPOINTS, ENDPOINTS
-SESSION_PATCH_TARGET = (
+# RESTClient builds its session via make_tracked_session in the rest_client module.
+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+# validate_credentials builds its own tracked session in the alguna module.
+ALGUNA_SESSION_PATCH = (
"products.warehouse_sources.backend.temporal.data_imports.sources.alguna.alguna.make_tracked_session"
)
+def _response(items: list[dict[str, Any]] | None, *, drop_data: bool = False) -> Response:
+ body: dict[str, Any] = {"pagination": {"per_page": 100}}
+ if not drop_data:
+ body["data"] = items or []
+ resp = Response()
+ resp.status_code = 200
+ resp._content = json.dumps(body).encode()
+ return resp
+
+
def _make_manager(resume_state: AlgunaResumeConfig | None = None) -> mock.MagicMock:
manager = mock.MagicMock()
manager.can_resume.return_value = resume_state is not None
@@ -28,153 +38,114 @@ def _make_manager(resume_state: AlgunaResumeConfig | None = None) -> mock.MagicM
return manager
-def _response(items: list[dict[str, Any]], status_code: int = 200) -> mock.MagicMock:
- resp = mock.MagicMock()
- resp.status_code = status_code
- resp.ok = status_code < 400
- resp.json.return_value = {"data": items, "pagination": {"per_page": 100, "total_pages": 1}}
- return resp
+def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+ """Wire a mock session and return a list that captures each request's params AT SEND TIME.
+ ``request.params`` is a single dict mutated in place across pages, so inspecting it after the run
+ shows only the final state — snapshot a copy when each request is prepared instead.
+ """
+ session.headers = {}
+ param_snapshots: list[dict[str, Any]] = []
-def _query(call: mock._Call) -> dict[str, list[str]]:
- return parse_qs(urlparse(call.args[0]).query)
+ def _prepare(request: Any) -> mock.MagicMock:
+ param_snapshots.append(dict(request.params or {}))
+ return mock.MagicMock()
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return param_snapshots
-class TestValidateCredentials:
- @parameterized.expand(
- [
- ("ok", 200, True),
- ("unauthorized", 401, False),
- ("forbidden", 403, False),
- ("server_error", 500, False),
- ]
- )
- def test_validate_credentials_status_mapping(self, _name: str, status_code: int, expected: bool) -> None:
- response = mock.MagicMock()
- response.status_code = status_code
-
- with mock.patch(SESSION_PATCH_TARGET) as mock_session:
- mock_session.return_value.get.return_value = response
- assert validate_credentials("key") is expected
-
- def test_validate_credentials_swallows_exceptions(self):
- with mock.patch(SESSION_PATCH_TARGET) as mock_session:
- mock_session.return_value.get.side_effect = Exception("boom")
- assert validate_credentials("key") is False
-
-
-class TestGetRows:
- @mock.patch(SESSION_PATCH_TARGET)
- def test_paginates_with_limit_offset(self, mock_session):
- full_page = [{"id": f"cust_{i}"} for i in range(100)]
- last_page = [{"id": "cust_last"}]
- mock_session.return_value.get.side_effect = [_response(full_page), _response(last_page)]
- manager = _make_manager()
- batches = list(get_rows("key", "customers", mock.MagicMock(), manager))
+def _rows(source_response) -> list[dict[str, Any]]:
+ return [row for page in source_response.items() for row in page]
+
- assert [item["id"] for batch in batches for item in batch] == [*(f"cust_{i}" for i in range(100)), "cust_last"]
+class TestPagination:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_paginates_and_progresses_offset(self, MockSession) -> None:
+ session = MockSession.return_value
+ full_page = [{"id": f"c_{i}"} for i in range(100)]
+ params = _wire(session, [_response(full_page), _response([{"id": "c_last"}])])
- calls = mock_session.return_value.get.call_args_list
- assert _query(calls[0])["offset"] == ["0"]
- assert _query(calls[0])["limit"] == ["100"]
- assert _query(calls[0])["sort"] == ["created_at:asc"]
- assert _query(calls[1])["offset"] == ["100"]
+ manager = _make_manager()
+ rows = _rows(alguna_source("key", "customers", team_id=1, job_id="j", resumable_source_manager=manager))
- # State is saved only after a full page has been yielded, so a crash re-yields
- # the last page instead of skipping it.
+ assert [r["id"] for r in rows] == [*(f"c_{i}" for i in range(100)), "c_last"]
+ assert params[0]["offset"] == 0
+ assert params[0]["limit"] == 100
+ assert params[1]["offset"] == 100
+ # Checkpoint saved after the first full page (points at the next page); short page ends it.
manager.save_state.assert_called_once()
- assert manager.save_state.call_args.args[0].offset == 100
+ assert manager.save_state.call_args.args[0] == AlgunaResumeConfig(offset=100)
- @mock.patch(SESSION_PATCH_TARGET)
- def test_requests_send_auth_and_version_headers(self, mock_session):
- mock_session.return_value.get.return_value = _response([{"id": "cust_1"}])
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_short_first_page_makes_one_request_and_no_checkpoint(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response([{"id": "a"}, {"id": "b"}])])
- list(get_rows("key", "customers", mock.MagicMock(), _make_manager()))
+ manager = _make_manager()
+ rows = _rows(alguna_source("key", "customers", team_id=1, job_id="j", resumable_source_manager=manager))
- headers = mock_session.return_value.get.call_args.kwargs["headers"]
- assert headers["Authorization"] == "Bearer key"
- # Alguna rejects any request without the date-based version header.
- assert headers["Alguna-Version"] == ALGUNA_API_VERSION
+ assert [r["id"] for r in rows] == ["a", "b"]
+ assert session.send.call_count == 1
+ manager.save_state.assert_not_called()
- @parameterized.expand([("payments",), ("products",)])
- def test_no_sort_param_for_endpoints_without_sort(self, endpoint: str) -> None:
- with mock.patch(SESSION_PATCH_TARGET) as mock_session:
- mock_session.return_value.get.return_value = _response([{"id": "x"}])
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_from_saved_offset(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_response([{"id": "c_201"}])])
- list(get_rows("key", endpoint, mock.MagicMock(), _make_manager()))
+ manager = _make_manager(AlgunaResumeConfig(offset=200))
+ _rows(alguna_source("key", "customers", team_id=1, job_id="j", resumable_source_manager=manager))
- assert "sort" not in _query(mock_session.return_value.get.call_args)
+ assert params[0]["offset"] == 200
- @mock.patch(SESSION_PATCH_TARGET)
- def test_resumes_from_saved_offset(self, mock_session):
- mock_session.return_value.get.return_value = _response([{"id": "cust_201"}])
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_version_header_is_set_on_session(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response([{"id": "a"}])])
- manager = _make_manager(AlgunaResumeConfig(offset=200))
- list(get_rows("key", "customers", mock.MagicMock(), manager))
+ _rows(alguna_source("key", "customers", team_id=1, job_id="j", resumable_source_manager=_make_manager()))
+ assert session.headers.get("Alguna-Version") == ALGUNA_API_VERSION
- assert _query(mock_session.return_value.get.call_args_list[0])["offset"] == ["200"]
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_sort_param_present_for_sortable_endpoint(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_response([{"id": "a"}])])
- @mock.patch(SESSION_PATCH_TARGET)
- def test_empty_first_page_stops_without_yield(self, mock_session):
- mock_session.return_value.get.return_value = _response([])
+ _rows(alguna_source("key", "customers", team_id=1, job_id="j", resumable_source_manager=_make_manager()))
+ assert params[0]["sort"] == "created_at:asc"
- manager = _make_manager()
- batches = list(get_rows("key", "customers", mock.MagicMock(), manager))
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_no_sort_param_for_unsortable_endpoint(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_response([{"id": "a"}])])
- assert batches == []
- manager.save_state.assert_not_called()
+ _rows(alguna_source("key", "payments", team_id=1, job_id="j", resumable_source_manager=_make_manager()))
+ assert "sort" not in params[0]
- @mock.patch(SESSION_PATCH_TARGET)
- def test_short_page_terminates_without_saving_state(self, mock_session):
- mock_session.return_value.get.return_value = _response([{"id": "cust_1"}, {"id": "cust_2"}])
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_missing_data_key_raises_loudly(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response(None, drop_data=True)])
- manager = _make_manager()
- batches = list(get_rows("key", "customers", mock.MagicMock(), manager))
+ # A 200 body without "data" means the response shape changed — fail loud, not silently 0 rows.
+ with pytest.raises(ValueError, match="matched nothing"):
+ _rows(alguna_source("key", "customers", team_id=1, job_id="j", resumable_source_manager=_make_manager()))
- assert len(batches) == 1
- assert mock_session.return_value.get.call_count == 1
- manager.save_state.assert_not_called()
- @mock.patch(SESSION_PATCH_TARGET)
- def test_missing_data_key_raises(self, mock_session):
- resp = mock.MagicMock()
- resp.status_code = 200
- resp.ok = True
- resp.json.return_value = {"unexpected": "envelope"}
- mock_session.return_value.get.return_value = resp
-
- # A 200 body without "data" means the response shape changed — the sync must fail
- # loudly instead of silently reporting 0 rows.
- with pytest.raises(KeyError):
- list(get_rows("key", "customers", mock.MagicMock(), _make_manager()))
-
- @mock.patch(SESSION_PATCH_TARGET)
- def test_auth_error_raises_without_retry(self, mock_session):
- resp = mock.MagicMock()
- resp.status_code = 401
- resp.ok = False
- resp.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=resp)
- mock_session.return_value.get.return_value = resp
-
- with pytest.raises(requests.HTTPError):
- list(get_rows("key", "customers", mock.MagicMock(), _make_manager()))
-
- # Credential failures must not burn retry attempts before surfacing.
- assert mock_session.return_value.get.call_count == 1
-
-
-class TestAlgunaSourceResponse:
- @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])
- def test_response_metadata_per_endpoint(self, endpoint: str) -> None:
- config = ALGUNA_ENDPOINTS[endpoint]
- response = alguna_source("key", endpoint, mock.MagicMock(), _make_manager())
-
- assert response.name == endpoint
- assert response.primary_keys == config.primary_keys
- assert response.partition_mode == "datetime"
- assert response.partition_keys == [config.partition_key]
-
- @parameterized.expand([(name, config) for name, config in ALGUNA_ENDPOINTS.items()])
- def test_partition_keys_are_stable_creation_fields(self, _name: str, config) -> None:
- assert config.partition_key == "created_at"
+class TestValidateCredentials:
+ @mock.patch(ALGUNA_SESSION_PATCH)
+ def test_ok(self, mock_session) -> None:
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
+ assert validate_credentials("key") is True
+
+ @mock.patch(ALGUNA_SESSION_PATCH)
+ def test_unauthorized(self, mock_session) -> None:
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=401)
+ assert validate_credentials("key") is False
+
+ @mock.patch(ALGUNA_SESSION_PATCH)
+ def test_swallows_exceptions(self, mock_session) -> None:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("key") is False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/paginators.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/paginators.py
index 70298f4df38f..4b2d39b43d63 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/paginators.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/paginators.py
@@ -50,6 +50,13 @@ class BaseNextUrlPaginator(BasePaginator):
super().__init__()
self._next_url: Optional[str] = None
+ def init_request(self, request: Request) -> None:
+ # Apply a seeded resume URL to the first request so a resumed run starts at the
+ # saved next-page link rather than the base path.
+ if self._next_url is not None:
+ request.url = self._next_url
+ request.params = {}
+
def update_request(self, request: Request) -> None:
if self._next_url is not None:
request.url = self._next_url
@@ -60,6 +67,15 @@ class BaseNextUrlPaginator(BasePaginator):
# until the URL grows large enough for the server to reject it.
request.params = {}
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ return {"next_url": self._next_url} if self._has_next_page and self._next_url is not None else None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ next_url = state.get("next_url")
+ if next_url is not None:
+ self._next_url = next_url
+ self._has_next_page = True
+
class HeaderLinkPaginator(BaseNextUrlPaginator):
def __init__(self, links_next_key: str = "next") -> None:
@@ -116,6 +132,13 @@ class JSONResponseCursorPaginator(BasePaginator):
self.cursor_param = cursor_param
self._cursor_value: Optional[str] = None
+ def init_request(self, request: Request) -> None:
+ # Apply a seeded resume cursor to the first request.
+ if self._cursor_value is not None:
+ if request.params is None:
+ request.params = {}
+ request.params[self.cursor_param] = self._cursor_value
+
def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
try:
values = find_values(self.cursor_path, response.json())
@@ -133,6 +156,15 @@ class JSONResponseCursorPaginator(BasePaginator):
request.params = {}
request.params[self.cursor_param] = self._cursor_value
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ return {"cursor": self._cursor_value} if self._has_next_page and self._cursor_value is not None else None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ cursor = state.get("cursor")
+ if cursor is not None:
+ self._cursor_value = cursor
+ self._has_next_page = True
+
def __str__(self) -> str:
return f"JSONResponseCursorPaginator(cursor_path={self.cursor_path})"
@@ -196,6 +228,16 @@ class OffsetPaginator(BasePaginator):
request.params = {}
request.params[self.offset_param] = self.offset
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ # self.offset already points at the next page to fetch (update_state incremented it).
+ return {"offset": self.offset} if self._has_next_page else None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ offset = state.get("offset")
+ if offset is not None:
+ self.offset = int(offset)
+ self._has_next_page = True
+
def __str__(self) -> str:
return f"OffsetPaginator(offset={self.offset}, limit={self.limit})"
@@ -241,6 +283,16 @@ class PageNumberPaginator(BasePaginator):
request.params = {}
request.params[self.page_param] = self.page
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ # self.page already points at the next page to fetch (update_state incremented it).
+ return {"page": self.page} if self._has_next_page else None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ page = state.get("page")
+ if page is not None:
+ self.page = int(page)
+ self._has_next_page = True
+
def __str__(self) -> str:
return f"PageNumberPaginator(page={self.page})"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_paginators.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_paginators.py
index 738bb086f358..4f93b51231fb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_paginators.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_paginators.py
@@ -190,3 +190,59 @@ class TestSingleEntityPath:
)
def test_detection(self, path: str, expected: bool) -> None:
assert single_entity_path(path) == expected
+
+
+class TestPaginatorResume:
+ def test_offset_paginator_round_trips_resume_state(self) -> None:
+ p = OffsetPaginator(limit=100, total_path=None)
+ p.update_state(_make_response(), data=[{} for _ in range(100)]) # full page -> more
+ assert p.has_next_page is True
+ state = p.get_resume_state()
+ assert state == {"offset": 100}
+
+ resumed = OffsetPaginator(limit=100, total_path=None)
+ resumed.set_resume_state(state)
+ req = Request(method="GET", url="https://api.example.com/x")
+ resumed.init_request(req)
+ assert req.params["offset"] == 100
+
+ def test_offset_paginator_no_resume_state_when_done(self) -> None:
+ p = OffsetPaginator(limit=100, total_path=None)
+ p.update_state(_make_response(), data=[{}]) # short page -> done
+ assert p.get_resume_state() is None
+
+ def test_page_number_paginator_round_trips_resume_state(self) -> None:
+ p = PageNumberPaginator(page=1)
+ p.update_state(_make_response(), data=[{} for _ in range(50)])
+ state = p.get_resume_state()
+ assert state == {"page": 2}
+
+ resumed = PageNumberPaginator(page=1)
+ resumed.set_resume_state(state)
+ req = Request(method="GET", url="https://api.example.com/x")
+ resumed.init_request(req)
+ assert req.params["page"] == 2
+
+ def test_cursor_paginator_round_trips_resume_state(self) -> None:
+ p = JSONResponseCursorPaginator(cursor_path="cursors.next", cursor_param="cursor")
+ p.update_state(_make_response({"cursors": {"next": "abc"}}))
+ state = p.get_resume_state()
+ assert state == {"cursor": "abc"}
+
+ resumed = JSONResponseCursorPaginator(cursor_param="cursor")
+ resumed.set_resume_state(state)
+ req = Request(method="GET", url="https://api.example.com/x")
+ resumed.init_request(req)
+ assert req.params["cursor"] == "abc"
+
+ def test_next_url_paginator_round_trips_resume_state(self) -> None:
+ p = JSONResponsePaginator(next_url_path="next")
+ p.update_state(_make_response({"next": "https://api.example.com/page2"}))
+ state = p.get_resume_state()
+ assert state == {"next_url": "https://api.example.com/page2"}
+
+ resumed = JSONResponsePaginator()
+ resumed.set_resume_state(state)
+ req = Request(method="GET", url="https://api.example.com/page1")
+ resumed.init_request(req)
+ assert req.url == "https://api.example.com/page2"