:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement oncehub import source (#69351)
Tom Owersb331af44fc2e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex df6d6e8c1748..b276f3c65614 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -250,6 +250,7 @@ the row lists both.| northpass_lms | HTTP | requests | ✅ || notion | HTTP | requests | ✅ || omnisend | HTTP | requests | ✅ |+| oncehub | HTTP | requests | ✅ || onfleet | HTTP (cursor pagination) | requests | ✅ || open_exchange_rates | HTTP | requests | ✅ || opinion_stage | HTTP | requests | ✅ |@@ -610,7 +611,6 @@ doesn't conflict with concurrent PRs.- northpass_lms- nutshell- nylas-- oncehub- onedrive- onehundredms- onepagecrmdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 97b27225c1a3..80fe4fee216d 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@@ -2331,7 +2331,7 @@ class OmnisendSourceConfig(config.Config):@config.configclass OncehubSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/oncehub/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/oncehub/canonical_descriptions.pynew file mode 100644index 000000000000..60be4ed668cc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/oncehub/canonical_descriptions.py@@ -0,0 +1,104 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the OnceHub Booking Calendars API docs (https://developers.oncehub.com).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "bookings": {+ "description": "A meeting scheduled through OnceHub, including its lifecycle status, timing, and the customer it was booked with.",+ "docs_url": "https://developers.oncehub.com/reference/booking-calendars/",+ "columns": {+ "id": "Unique identifier for the booking.",+ "tracking_id": "A unique tracking ID automatically assigned to every booking.",+ "subject": "The name of the service or subject as defined in the booking form.",+ "status": "The status of the booking: requested, scheduled, rescheduled, completed, canceled, or no_show.",+ "in_trash": "Whether the booking was moved to trash in the activity stream.",+ "creation_time": "The date and time when the booking was created.",+ "starting_time": "The date and time when the meeting is scheduled to start.",+ "last_updated_time": "The date and time the booking was last updated.",+ "customer_timezone": "The IANA timezone selected by the customer when making the booking.",+ "duration_minutes": "The length of the meeting, in minutes.",+ "virtual_conferencing": "Information about the video conference for virtual meetings.",+ "location_description": "Information about the physical location for in-person meetings.",+ "rescheduled_booking_id": "The ID of the booking that was rescheduled, if any.",+ "cancel_reschedule_information": "Information about the cancel or reschedule event, null if never canceled or rescheduled.",+ "attendees": "List of all meeting attendee emails.",+ "form_submission": "Information entered by the customer into the booking form.",+ "booking_page": "The ID of the booking page used to make the booking.",+ "master_page": "The ID of the master booking page used to make the booking.",+ "event_type": "The ID of the service (event type) selected by the customer.",+ "booking_calendar": "The ID of the booking calendar used to make the booking.",+ "external_calendar": "Information about the connected external calendar used in the booking.",+ "owner": "The ID of the user who originally accepted the booking.",+ "contact": "The ID of the contact the booking was scheduled with.",+ "conversation": "The ID of the conversation the booking was scheduled from, if any.",+ "utm_params": "UTM parameters attached to the booking, null if none exist.",+ "payment_information": "Payment information for the booking if payment was collected via Stripe.",+ "custom_fields": "Custom fields added to the meeting object type on the account.",+ },+ },+ "booking_calendars": {+ "description": "A booking calendar (scheduling link) that accepts bookings for a host user or team.",+ "docs_url": "https://developers.oncehub.com/reference/booking-calendars/",+ "columns": {+ "id": "Unique identifier for the booking calendar.",+ "host": "The user ID or team ID of the booking calendar meeting host.",+ "name": "The internal label of the booking calendar.",+ "subject": "The customer-facing subject of the booking calendar.",+ "url": "The public URL of the booking calendar.",+ "published": "Whether the booking calendar is enabled and accepts bookings.",+ "duration_minutes": "Meeting duration in minutes.",+ },+ },+ "contacts": {+ "description": "A contact (customer) who has interacted with your OnceHub scheduling pages.",+ "docs_url": "https://developers.oncehub.com/reference/booking-calendars/",+ "columns": {+ "id": "Unique identifier for the contact.",+ "creation_time": "The date and time when the contact was created.",+ "last_updated_time": "The date and time the contact was last updated.",+ "last_interacted_time": "The date and time of the last interaction with the contact.",+ "owner": "The ID of the user who owns the contact.",+ "status": "The qualification status of the contact (Qualified, Sales qualified, Marketing qualified, or Disqualified).",+ "email": "Email address of the contact.",+ "first_name": "First name of the contact.",+ "last_name": "Last name of the contact.",+ "company": "Company name of the contact.",+ "company_size": "Size of the contact's company.",+ "job_title": "Job title of the contact.",+ "phone": "Phone number in E.164 format.",+ "mobile_phone": "Mobile phone number in E.164 format.",+ "street_address": "Street address of the contact.",+ "city": "City of the contact.",+ "state": "State or province of the contact.",+ "country": "Country of the contact.",+ "post_code": "Postal code of the contact.",+ "timezone": "IANA timezone of the contact.",+ "has_consent": "Whether the contact has given consent.",+ "custom_fields": "Custom fields associated with the contact.",+ },+ },+ "users": {+ "description": "A user (team member) in your OnceHub account.",+ "docs_url": "https://developers.oncehub.com/reference/booking-calendars/",+ "columns": {+ "id": "Unique identifier for the user.",+ "first_name": "User's first name.",+ "last_name": "User's last name.",+ "email": "User's email address.",+ "status": "The status of the user: active or invited.",+ "role_name": "The role of the user, for example Administrator, Member, Team Manager, or Account Owner.",+ "timezone": "User's IANA timezone.",+ "teams": "The IDs of the teams the user belongs to.",+ },+ },+ "teams": {+ "description": "A team of users in your OnceHub account.",+ "docs_url": "https://developers.oncehub.com/reference/booking-calendars/",+ "columns": {+ "id": "Unique identifier for the team.",+ "name": "The name of the team.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/oncehub/oncehub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/oncehub/oncehub.pynew file mode 100644index 000000000000..eb289a083c8f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/oncehub/oncehub.py@@ -0,0 +1,159 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional++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.oncehub.settings import ONCEHUB_ENDPOINTS++ONCEHUB_BASE_URL = "https://api.oncehub.com/v2"+# List endpoints accept a `limit` of 1-100 (default 10); the largest page minimises round trips+# against OnceHub's tight 5 requests/second account rate limit.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+# Cheap endpoint used to confirm an API key is genuine. The key is account-wide, so one probe+# validates access to every list endpoint.+DEFAULT_PROBE_PATH = "/users"+++class OncehubRetryableError(Exception):+ pass+++class OncehubResumeConfig:+ # Cursor for the next page: OnceHub paginates by passing the last item's object ID as `after`.+ # A crashed full-refresh sync resumes from the page after the last one yielded; merge dedupes+ # on `id`. `None` means start from the first page.+ cursor: str | None = None+++def _headers(api_key: str) -> dict[str, str]:+ return {"API-Key": api_key, "Accept": "application/json"}+++@retry(+ retry=retry_if_exception_type((OncehubRetryableError, 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,+ path: str,+ cursor: str | None,+ limit: int,+ logger: FilteringBoundLogger,+) -> tuple[list[dict[str, Any]], bool]:+ params: dict[str, Any] = {"limit": limit}+ if cursor is not None:+ params["after"] = cursor++ response = session.get(+ f"{ONCEHUB_BASE_URL}{path}",+ params=params,+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ # OnceHub rate limits at 5 req/s per account (429 with type "rate_limit_error"); back off and retry.+ if response.status_code == 429 or response.status_code >= 500:+ raise OncehubRetryableError(f"OnceHub API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"OnceHub API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ data = response.json()+ # OnceHub list endpoints wrap records in {"object": "list", "data": [...], "has_more": bool}.+ if not isinstance(data, dict) or not isinstance(data.get("data"), list):+ raise OncehubRetryableError(f"OnceHub returned an unexpected payload for {path}: {type(data).__name__}")++ results: list[dict[str, Any]] = data["data"]+ has_more = bool(data.get("has_more"))+ return results, has_more+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OncehubResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = ONCEHUB_ENDPOINTS[endpoint]+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ cursor = resume.cursor if resume else None+ if resume and resume.cursor is not None:+ logger.debug(f"OnceHub: resuming {endpoint} from cursor {cursor}")++ while True:+ items, has_more = _fetch_page(session, config.path, cursor, PAGE_SIZE, logger)+ if items:+ yield items++ if not has_more or not items:+ break++ # Cursor pagination advances by the last item's object ID — OnceHub has no numeric offset.+ cursor = items[-1]["id"]+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(OncehubResumeConfig(cursor=cursor))+++def oncehub_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OncehubResumeConfig],+) -> SourceResponse:+ config = ONCEHUB_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ 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_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the API key.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))+ try:+ response = session.get(f"{ONCEHUB_BASE_URL}{path}", params={"limit": 1}, timeout=15)+ except Exception as e:+ return 0, f"Could not connect to OnceHub: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"OnceHub returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ status, message = check_access(api_key)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid OnceHub API key"+ return False, message or "Could not validate OnceHub API key"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/oncehub/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/oncehub/settings.pynew file mode 100644index 000000000000..162bc6f69976--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/oncehub/settings.py@@ -0,0 +1,25 @@+from dataclasses import dataclass, field+++@dataclass+class OncehubEndpointConfig:+ name: str+ path: str+ # OnceHub object IDs are prefixed strings (BKNG-, CTC-, USR-, TM-, BKC-) that are unique+ # across the account, so `id` is a safe primary key for every endpoint.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+++# OnceHub Booking Calendars API (v2) list endpoints. All are full refresh only: the API's+# `last_updated_time.gt` filters are date-granular and list results paginate by object-ID cursor+# in reverse-chronological order, so there is no reliable server-side incremental cursor to+# advance safely without verified ordering guarantees.+ONCEHUB_ENDPOINTS: dict[str, OncehubEndpointConfig] = {+ "bookings": OncehubEndpointConfig(name="bookings", path="/bookings"),+ "booking_calendars": OncehubEndpointConfig(name="booking_calendars", path="/booking-calendars"),+ "contacts": OncehubEndpointConfig(name="contacts", path="/contacts"),+ "users": OncehubEndpointConfig(name="users", path="/users"),+ "teams": OncehubEndpointConfig(name="teams", path="/teams"),+}++ENDPOINTS = tuple(ONCEHUB_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/oncehub/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/oncehub/source.pyindex cd150861df6c..b9d2fc28054a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/oncehub/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/oncehub/source.py@@ -1,19 +1,42 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import OncehubSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.oncehub.oncehub import (+ OncehubResumeConfig,+ oncehub_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.oncehub.settings import (+ ENDPOINTS,+ ONCEHUB_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class OncehubSource(SimpleSource[OncehubSourceConfig]):+class OncehubSource(ResumableSource[OncehubSourceConfig, OncehubResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ONCEHUB@@ -23,8 +46,90 @@ class OncehubSource(SimpleSource[OncehubSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.ONCEHUB,category=DataWarehouseSourceCategory.PRODUCTIVITY,- label="Oncehub",+ label="OnceHub",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["scheduleonce", "scheduling", "booking"],+ caption="""Enter your OnceHub API key to pull your scheduling and booking data into the PostHog Data warehouse.++You can generate an API key in [OnceHub](https://app.oncehub.com) under **Settings → API & Webhooks**. The key is shown only once at creation, so copy it right away. It grants read access to your bookings, booking calendars, contacts, users, and teams.+""",iconPath="/static/services/oncehub.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/oncehub",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.oncehub.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.oncehub.com": "Your OnceHub API key is invalid or has been revoked. Generate a new key under Settings → API & Webhooks, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.oncehub.com": "Your OnceHub API key does not have access to this data. Check the key's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: OncehubSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — OnceHub's `last_updated_time.gt` filters are+ # date-granular and cursor pagination returns newest-first, so there is no reliable+ # server-side incremental cursor to advance.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ 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: OncehubSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The API key is account-wide, so a single probe validates access to every schema.+ return validate_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OncehubResumeConfig]:+ return ResumableSourceManager[OncehubResumeConfig](inputs, OncehubResumeConfig)++ def source_for_pipeline(+ self,+ config: OncehubSourceConfig,+ resumable_source_manager: ResumableSourceManager[OncehubResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in ONCEHUB_ENDPOINTS:+ raise ValueError(f"Unknown OnceHub schema '{inputs.schema_name}'")++ return oncehub_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/oncehub/tests/test_oncehub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/oncehub/tests/test_oncehub.pynew file mode 100644index 000000000000..cadac200de98--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/oncehub/tests/test_oncehub.py@@ -0,0 +1,242 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.oncehub import oncehub+from products.warehouse_sources.backend.temporal.data_imports.sources.oncehub.oncehub import (+ PAGE_SIZE,+ OncehubResumeConfig,+ OncehubRetryableError,+ check_access,+ get_rows,+ oncehub_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.oncehub.settings import (+ ENDPOINTS,+ ONCEHUB_ENDPOINTS,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = oncehub._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: OncehubResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[OncehubResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> OncehubResumeConfig | None:+ return self._state++ def save_state(self, data: OncehubResumeConfig) -> None:+ self.saved.append(data)+++def _full_page(prefix: str) -> list[dict]:+ return [{"id": f"{prefix}-{i}"} for i in range(PAGE_SIZE)]+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: dict[str | None, tuple[list[dict], bool]],+ endpoint: str = "bookings",+ ) -> list[dict]:+ def fake_fetch(session: Any, path: str, cursor: str | None, limit: int, logger: Any) -> tuple[list[dict], bool]:+ return pages[cursor]++ monkeypatch.setattr(oncehub, "_fetch_page", fake_fetch)+ monkeypatch.setattr(oncehub, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="oncehub-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_single_page_has_more_false_yields_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {None: ([{"id": "BKNG-1"}, {"id": "BKNG-2"}], False)})+ assert rows == [{"id": "BKNG-1"}, {"id": "BKNG-2"}]+ # has_more is false, so we stop without persisting resume state.+ assert manager.saved == []++ def test_follows_after_cursor_until_has_more_false(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ # First page is full with has_more true; the cursor becomes the last item's id.+ first_page = _full_page("BKNG")+ last_id = first_page[-1]["id"]+ pages: dict[str | None, tuple[list[dict], bool]] = {+ None: (first_page, True),+ last_id: ([{"id": "BKNG-final"}], False),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert len(rows) == PAGE_SIZE + 1+ # State is saved after the first page (cursor advances to the last id), then we stop.+ assert [s.cursor for s in manager.saved] == [last_id]++ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(OncehubResumeConfig(cursor="BKNG-99"))+ # The initial (cursor=None) page must never be fetched on resume.+ rows = self._collect(manager, monkeypatch, {"BKNG-99": ([{"id": "BKNG-100"}], False)})+ assert rows == [{"id": "BKNG-100"}]++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {None: ([], False)})+ assert rows == []+ assert manager.saved == []+++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 {"object": "list", "data": [], "has_more": False}+ 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(OncehubRetryableError):+ _fetch_page_unwrapped(session, "/bookings", None, PAGE_SIZE, 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, "/bookings", None, PAGE_SIZE, MagicMock())++ def test_success_returns_data_and_has_more(self) -> None:+ body = {"object": "list", "data": [{"id": "BKNG-1"}], "has_more": True}+ session = self._session_returning(200, body)+ results, has_more = _fetch_page_unwrapped(session, "/bookings", None, PAGE_SIZE, MagicMock())+ assert results == [{"id": "BKNG-1"}]+ assert has_more is True++ def test_non_dict_body_is_retryable(self) -> None:+ session = self._session_returning(200, [{"id": "BKNG-1"}])+ with pytest.raises(OncehubRetryableError):+ _fetch_page_unwrapped(session, "/bookings", None, PAGE_SIZE, MagicMock())++ def test_missing_data_key_is_retryable(self) -> None:+ session = self._session_returning(200, {"object": "list", "has_more": False})+ with pytest.raises(OncehubRetryableError):+ _fetch_page_unwrapped(session, "/bookings", None, PAGE_SIZE, MagicMock())++ def test_first_page_uses_limit_without_cursor(self) -> None:+ session = self._session_returning(200)+ _fetch_page_unwrapped(session, "/contacts", None, PAGE_SIZE, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"limit": PAGE_SIZE}++ def test_subsequent_page_sends_after_cursor(self) -> None:+ session = self._session_returning(200)+ _fetch_page_unwrapped(session, "/contacts", "CTC-42", PAGE_SIZE, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"limit": PAGE_SIZE, "after": "CTC-42"}+++class TestCheckAccess:+ @staticmethod+ def _session(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, "OnceHub returned HTTP 500"),+ ]+ )+ @patch(f"{oncehub.__name__}.make_tracked_session")+ def test_status_mapping(+ self,+ _name: str,+ status: int,+ ok: bool,+ expected_status: int,+ expected_message: str | None,+ mock_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ mock_session.return_value = self._session(response)+ assert check_access("oncehub-key") == (expected_status, expected_message)++ @patch(f"{oncehub.__name__}.make_tracked_session")+ def test_connection_error_maps_to_zero(self, mock_session: MagicMock) -> None:+ mock_session.return_value = self._session(requests.ConnectionError("boom"))+ status, message = check_access("oncehub-key")+ assert status == 0+ assert message is not None and "boom" in message++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid OnceHub API key"),+ ("forbidden", 403, False, "Invalid OnceHub API key"),+ ("server_error", 500, False, "OnceHub returned HTTP 500"),+ ]+ )+ @patch(f"{oncehub.__name__}.make_tracked_session")+ def test_validate_credentials(+ self,+ _name: str,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ mock_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ mock_session.return_value = self._session(response)+ assert validate_credentials("oncehub-key") == (expected_valid, expected_message)+++class TestOncehubSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = oncehub_source(+ api_key="oncehub-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # Lists paginate newest-first with no stable ascending order, so we don't partition.+ assert response.partition_mode is None++ def test_every_endpoint_uses_id_primary_key(self) -> None:+ assert all(config.primary_keys == ["id"] for config in ONCEHUB_ENDPOINTS.values())+ assert set(ONCEHUB_ENDPOINTS) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/oncehub/tests/test_oncehub_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/oncehub/tests/test_oncehub_source.pynew file mode 100644index 000000000000..b1b45b1ff983--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/oncehub/tests/test_oncehub_source.py@@ -0,0 +1,131 @@+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 OncehubSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.oncehub.oncehub import OncehubResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.oncehub.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.oncehub.source import OncehubSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestOncehubSource:+ def setup_method(self) -> None:+ self.source = OncehubSource()+ self.team_id = 123+ self.config = OncehubSourceConfig(api_key="oncehub-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.ONCEHUB++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Oncehub"+ assert config.label == "OnceHub"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/oncehub"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_api_key_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_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_no_connection_host_fields(self) -> None:+ # The only field is the secret API key; the base URL is hardcoded, so there is no non-secret+ # field an editor could retarget to reuse a preserved key against another host.+ assert self.source.connection_host_fields == []++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["bookings"])+ assert len(schemas) == 1+ assert schemas[0].name == "bookings"++ 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)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.oncehub.com/v2/bookings?limit=100",+ ),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.oncehub.com/v2/contacts?limit=100"),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://api.oncehub.com/v2/bookings",+ ),+ (+ "rate_limited",+ "429 Client Error: Too Many Requests for url: https://api.oncehub.com/v2/contacts",+ ),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, _name: str, 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.oncehub.source.validate_credentials")+ def test_validate_credentials_delegates_with_api_key(self, mock_validate: mock.MagicMock) -> None:+ # The status-to-message mapping lives in oncehub.validate_credentials; here we only assert the+ # source probes with the configured key and returns the delegate's verdict unchanged.+ mock_validate.return_value = (False, "Invalid OnceHub API key")+ result = self.source.validate_credentials(self.config, self.team_id)+ mock_validate.assert_called_once_with("oncehub-key")+ assert result == (False, "Invalid OnceHub API key")++ 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 OncehubResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.oncehub.source.oncehub_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "bookings"+ 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_key"] == "oncehub-key"+ assert kwargs["endpoint"] == "bookings"+ assert kwargs["resumable_source_manager"] is manager++ 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 OnceHub schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)