: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 cloudbeds import source (#69329)
Tom Owers973d173fbb62
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 3bfe1f74f6c9..9d5d78319e51 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -119,6 +119,7 @@ the row lists both.| clockify | HTTP | requests | ✅ || clockodo | HTTP | requests | ✅ || close | HTTP | requests + `rest_source.RESTClient` | ✅ |+| cloudbeds | HTTP | requests | ✅ || convertkit | HTTP | requests | ✅ || convex | HTTP | requests | ✅ || copper | HTTP | requests | ✅ |@@ -476,6 +477,7 @@ doesn't conflict with concurrent PRs.- clarifai- clazar- cloudbeds+- coassemble- cockroachdb- cody- constant_contactdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/canonical_descriptions.pynew file mode 100644index 000000000000..5ae80bf17716--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/canonical_descriptions.py@@ -0,0 +1,90 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Cloudbeds PMS API v1.2 docs (https://developers.cloudbeds.com).+# Partial coverage is fine - uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "hotels": {+ "description": "A property (hotel, hostel, or vacation rental) managed by the Cloudbeds account.",+ "docs_url": "https://developers.cloudbeds.com",+ "columns": {+ "propertyID": "The unique ID of the property.",+ "propertyName": "The name of the property.",+ "propertyType": "The type of property (e.g. hotel, hostel, vacation rental).",+ "propertyCurrency": "The currency the property operates in.",+ "propertyPhone": "The property's contact phone number.",+ "propertyEmail": "The property's contact email address.",+ },+ },+ "reservations": {+ "description": "A booking at a property, covering one or more rooms and guests.",+ "docs_url": "https://developers.cloudbeds.com",+ "columns": {+ "reservationID": "The unique ID of the reservation.",+ "propertyID": "The ID of the property the reservation belongs to.",+ "guestID": "The ID of the primary guest on the reservation.",+ "guestName": "The name of the primary guest on the reservation.",+ "status": "The reservation status (e.g. confirmed, checked_in, checked_out, canceled, no_show).",+ "startDate": "The check-in date of the reservation.",+ "endDate": "The check-out date of the reservation.",+ "dateCreated": "When the reservation was created.",+ "dateModified": "When the reservation was last modified.",+ "sourceName": "The booking source or channel the reservation came from.",+ "balance": "The outstanding balance on the reservation.",+ },+ },+ "guests": {+ "description": "A guest profile stored at the property, linked to one or more reservations.",+ "docs_url": "https://developers.cloudbeds.com",+ "columns": {+ "guestID": "The unique ID of the guest.",+ "propertyID": "The ID of the property the guest profile belongs to.",+ "guestFirstName": "The guest's first name.",+ "guestLastName": "The guest's last name.",+ "guestEmail": "The guest's email address.",+ "guestPhone": "The guest's phone number.",+ "guestCountry": "The guest's country.",+ "reservationID": "The ID of the reservation the guest is associated with.",+ },+ },+ "rooms": {+ "description": "A physical room (or unit) at a property, listed per property by the rooms endpoint.",+ "docs_url": "https://developers.cloudbeds.com",+ "columns": {+ "roomID": "The unique ID of the room.",+ "propertyID": "The ID of the property the room belongs to.",+ "roomName": "The name or number of the room.",+ "roomTypeID": "The ID of the room type the room belongs to.",+ "roomTypeName": "The name of the room type the room belongs to.",+ "roomBlocked": "Whether the room is currently blocked from sale.",+ },+ },+ "room_types": {+ "description": "A room category at a property (e.g. double, dorm bed) with its occupancy and inventory settings.",+ "docs_url": "https://developers.cloudbeds.com",+ "columns": {+ "roomTypeID": "The unique ID of the room type.",+ "propertyID": "The ID of the property the room type belongs to.",+ "roomTypeName": "The name of the room type.",+ "roomTypeNameShort": "The short code of the room type.",+ "maxGuests": "The maximum number of guests the room type accommodates.",+ "isPrivate": "Whether the room type is a private room (as opposed to a shared/dorm room).",+ "roomsAvailable": "The number of rooms of this type available for sale.",+ },+ },+ "transactions": {+ "description": "A financial transaction (charge, payment, tax, or adjustment) posted at the property.",+ "docs_url": "https://developers.cloudbeds.com",+ "columns": {+ "transactionID": "The unique ID of the transaction.",+ "propertyID": "The ID of the property the transaction belongs to.",+ "reservationID": "The ID of the reservation the transaction is attached to, if any.",+ "guestID": "The ID of the guest the transaction is attached to, if any.",+ "amount": "The amount of the transaction.",+ "currency": "The currency of the transaction.",+ "description": "The description of the transaction.",+ "transactionDateTime": "When the transaction was posted.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/cloudbeds.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/cloudbeds.pynew file mode 100644index 000000000000..3b6a3405e3a6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/cloudbeds.py@@ -0,0 +1,215 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import urlsplit++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.cloudbeds.settings import (+ CLOUDBEDS_ENDPOINTS,+ CloudbedsEndpointConfig,+)+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++CLOUDBEDS_BASE_URL = "https://api.cloudbeds.com/api/v1.2"+# List endpoints accept pageSize up to 100 (the default); the largest page minimises round trips+# against Cloudbeds' 5 req/sec property-credential rate limit.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+# Cheap endpoint used to confirm a token is genuine. Every credential (API key or OAuth token) can+# read the properties it is scoped to, so one probe validates the token itself; per-endpoint scopes+# are handled at sync time via get_non_retryable_errors.+DEFAULT_PROBE_PATH = "/getHotels"+++class CloudbedsRetryableError(Exception):+ pass+++class CloudbedsApiError(Exception):+ """Cloudbeds returned HTTP 200 with `success: false` (bad params, missing scope, ...)."""++ pass+++class CloudbedsResumeConfig:+ # Next pageNumber to fetch (1-based). Cloudbeds paginates by page number, so a crashed+ # full-refresh sync resumes from the page after the last one yielded; merge dedupes the+ # re-pulled page on the primary key. `None` means start from the first page.+ page: int | None = None+++def _headers(api_key: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}+++def _flatten_rows(rows: list[dict[str, Any]], config: CloudbedsEndpointConfig) -> list[dict[str, Any]]:+ if not config.flatten_field:+ return rows++ flattened: list[dict[str, Any]] = []+ for parent in rows:+ nested = parent.get(config.flatten_field)+ if not isinstance(nested, list):+ continue+ # Direct access so a missing required parent field (e.g. propertyID) fails fast instead of+ # silently writing None across every flattened child row.+ parent_fields = {key: parent[key] for key in config.flatten_parent_fields}+ for row in nested:+ flattened.append({**row, **parent_fields})+ return flattened+++@retry(+ retry=retry_if_exception_type((CloudbedsRetryableError, 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,+ params: dict[str, Any],+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ response = session.get(f"{CLOUDBEDS_BASE_URL}{path}", params=params, timeout=REQUEST_TIMEOUT_SECONDS)++ # Exceeding Cloudbeds' rate limit (5 req/sec for property credentials) returns 429; backing off+ # matters because repeated violations can temporarily suspend the credential.+ if response.status_code == 429 or response.status_code >= 500:+ raise CloudbedsRetryableError(f"Cloudbeds API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ # Cloudbeds error bodies can echo guest/reservation data, so log only a short capped+ # excerpt rather than the full body.+ logger.error(f"Cloudbeds API error: status={response.status_code}, path={path}, body={response.text[:200]}")+ # raise_for_status() would embed the full request URL in the exception, which is surfaced as+ # the schema's latest_error. Cloudbeds authenticates via the Authorization header today, but+ # rebuild the error from scheme/host/path only so a redirect or future query-param auth can+ # never leak the api_key into stored error state. The "<status> Client Error: <reason> for+ # url: https://api.cloudbeds.com" prefix stays stable for get_non_retryable_errors() matching.+ safe = urlsplit(response.url)+ raise requests.HTTPError(+ f"{response.status_code} Client Error: {response.reason} for url: {safe.scheme}://{safe.netloc}{safe.path}",+ response=response,+ )++ data = response.json()+ if not isinstance(data, dict):+ raise CloudbedsRetryableError(f"Cloudbeds returned an unexpected payload for {path}: {type(data).__name__}")++ # Cloudbeds signals request-level errors (bad params, missing OAuth scope, ...) as HTTP 200 with+ # success=false and a message - these are not transient, so fail instead of retrying.+ if data.get("success") is False:+ raise CloudbedsApiError(f"Cloudbeds API request to {path} failed: {data.get('message', 'unknown error')}")++ rows = data.get("data")+ if not isinstance(rows, list):+ raise CloudbedsRetryableError(f"Cloudbeds returned an unexpected data payload for {path}")++ return rows+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CloudbedsResumeConfig],+ property_id: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = CLOUDBEDS_ENDPOINTS[endpoint]+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))++ # Group (multi-property) credentials require propertyID to scope reads; single-property+ # credentials can omit it.+ base_params: dict[str, Any] = {"propertyID": property_id} if property_id else {}++ if not config.paginated:+ rows = _fetch_page(session, config.path, base_params, logger)+ flattened = _flatten_rows(rows, config)+ if flattened:+ yield flattened+ return++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.page if (resume and resume.page) else 1+ if resume and resume.page:+ logger.debug(f"Cloudbeds: resuming {endpoint} from page {page}")++ while True:+ params = {**base_params, "pageNumber": page, "pageSize": PAGE_SIZE}+ rows = _fetch_page(session, config.path, params, logger)+ flattened = _flatten_rows(rows, config)+ if flattened:+ yield flattened++ # A short (or empty) page means we've reached the end of the collection.+ if len(rows) < PAGE_SIZE:+ break++ page += 1+ # 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(CloudbedsResumeConfig(page=page))+++def cloudbeds_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CloudbedsResumeConfig],+ property_id: str | None = None,+) -> SourceResponse:+ config = CLOUDBEDS_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ property_id=property_id,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )+++def check_access(+ api_key: str, property_id: str | None = None, path: str = DEFAULT_PROBE_PATH+) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the API key or OAuth access token.++ 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,))+ params: dict[str, Any] = {"propertyID": property_id} if property_id else {}+ try:+ response = session.get(f"{CLOUDBEDS_BASE_URL}{path}", params=params, timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Cloudbeds: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Cloudbeds returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(api_key: str, property_id: str | None = None) -> tuple[bool, str | None]:+ status, message = check_access(api_key, property_id)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Cloudbeds API key"+ return False, message or "Could not validate Cloudbeds API key"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/settings.pynew file mode 100644index 000000000000..1fee9c8a77ce--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/settings.py@@ -0,0 +1,65 @@+from dataclasses import dataclass, field+++@dataclass+class CloudbedsEndpointConfig:+ name: str+ path: str+ # Cloudbeds identifiers (reservationID, guestID, roomID, ...) are documented as unique across the+ # account the credential is scoped to, so a single ID field is a safe primary key per endpoint.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Endpoints that accept pageNumber/pageSize. Non-paginated endpoints return the full collection+ # in one response.+ paginated: bool = True+ # Some endpoints group rows under a nested list per property (e.g. getRooms returns one object+ # per property with a `rooms` array). When set, each nested row is emitted as its own row with+ # the parent's fields from `flatten_parent_fields` copied in.+ flatten_field: str | None = None+ flatten_parent_fields: list[str] = field(default_factory=list)+++# Cloudbeds PMS API v1.2 list endpoints. All are full refresh only for now: getReservations+# documents a server-side `modifiedSince` filter, but Cloudbeds notes some reservation+# modifications are not reflected in the modified timestamp, and we have not been able to verify+# the filter's behavior against a live account - so we conservatively ship full refresh and dedupe+# on primary keys (see the implementing-warehouse-sources skill).+CLOUDBEDS_ENDPOINTS: dict[str, CloudbedsEndpointConfig] = {+ "hotels": CloudbedsEndpointConfig(+ name="hotels",+ path="/getHotels",+ primary_keys=["propertyID"],+ paginated=False,+ ),+ "reservations": CloudbedsEndpointConfig(+ name="reservations",+ path="/getReservations",+ primary_keys=["reservationID"],+ ),+ "guests": CloudbedsEndpointConfig(+ name="guests",+ path="/getGuestList",+ primary_keys=["guestID"],+ ),+ "rooms": CloudbedsEndpointConfig(+ name="rooms",+ path="/getRooms",+ primary_keys=["roomID"],+ paginated=False,+ flatten_field="rooms",+ flatten_parent_fields=["propertyID"],+ ),+ "room_types": CloudbedsEndpointConfig(+ name="room_types",+ path="/getRoomTypes",+ primary_keys=["roomTypeID"],+ ),+ "transactions": CloudbedsEndpointConfig(+ name="transactions",+ path="/getTransactions",+ primary_keys=["transactionID"],+ ),+}++ENDPOINTS = tuple(CLOUDBEDS_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/source.pyindex a3d6149d6cbc..16e82feccd2f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/source.py@@ -1,30 +1,152 @@-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.cloudbeds.cloudbeds import (+ CloudbedsResumeConfig,+ cloudbeds_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudbeds.settings import (+ CLOUDBEDS_ENDPOINTS,+ ENDPOINTS,+)+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 CloudbedsSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CloudbedsSource(SimpleSource[CloudbedsSourceConfig]):+class CloudbedsSource(ResumableSource[CloudbedsSourceConfig, CloudbedsResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog - safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CLOUDBEDS+ @property+ def connection_host_fields(self) -> list[str]:+ # `property_id` scopes which property the stored API key reads from; retargeting it must+ # re-require the key so a group-level credential can't be pointed at another property.+ return ["property_id"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.CLOUDBEDS,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Cloudbeds",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Cloudbeds API key to pull your properties, reservations, guests, rooms, room types, and transactions into the PostHog Data warehouse.++You can create an API key under **Settings → API credentials** in [Cloudbeds](https://hotels.cloudbeds.com). Note that Cloudbeds API keys expire after 30 days of inactivity, so a key that has not been used recently may need to be regenerated.++If your account manages multiple properties, enter the ID of the property you want to sync - group-level credentials require it to scope reads to a single property.+""",iconPath="/static/services/cloudbeds.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/cloudbeds",+ keywords=["pms", "hotel", "hospitality"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="property_id",+ label="Property ID (required for multi-property accounts)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="",+ secret=False,+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.cloudbeds.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.cloudbeds.com": "Your Cloudbeds API key is invalid or has expired (keys expire after 30 days of inactivity). Generate a new key under Settings → API credentials, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.cloudbeds.com": "Your Cloudbeds credentials do not have access to this data. Check the credential's permission scopes, then reconnect.",+ }++ def get_schemas(+ self,+ config: CloudbedsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only for now - see the note in settings.py about the+ # unverified `modifiedSince` filter on getReservations.+ 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: CloudbedsSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # One probe validates the token itself; per-endpoint OAuth scopes surface at sync time via+ # get_non_retryable_errors.+ return validate_credentials(config.api_key, config.property_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CloudbedsResumeConfig]:+ return ResumableSourceManager[CloudbedsResumeConfig](inputs, CloudbedsResumeConfig)++ def source_for_pipeline(+ self,+ config: CloudbedsSourceConfig,+ resumable_source_manager: ResumableSourceManager[CloudbedsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in CLOUDBEDS_ENDPOINTS:+ raise ValueError(f"Unknown Cloudbeds schema '{inputs.schema_name}'")++ return cloudbeds_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ property_id=config.property_id,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/tests/test_cloudbeds.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/tests/test_cloudbeds.pynew file mode 100644index 000000000000..123fcbf6bb93--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/tests/test_cloudbeds.py@@ -0,0 +1,297 @@+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.cloudbeds import cloudbeds+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudbeds.cloudbeds import (+ PAGE_SIZE,+ CloudbedsApiError,+ CloudbedsResumeConfig,+ CloudbedsRetryableError,+ check_access,+ cloudbeds_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudbeds.settings import (+ CLOUDBEDS_ENDPOINTS,+ ENDPOINTS,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = cloudbeds._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: CloudbedsResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[CloudbedsResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> CloudbedsResumeConfig | None:+ return self._state++ def save_state(self, data: CloudbedsResumeConfig) -> None:+ self.saved.append(data)+++def _full_page(start_id: int) -> list[dict]:+ return [{"reservationID": str(start_id + i)} for i in range(PAGE_SIZE)]+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: dict[tuple[str, Any], list[Any]],+ endpoint: str = "reservations",+ property_id: str | None = None,+ ) -> tuple[list[dict], list[dict[str, Any]]]:+ calls: list[dict[str, Any]] = []++ def fake_fetch(session: Any, path: str, params: dict[str, Any], logger: Any) -> list[dict]:+ calls.append(params)+ return pages[(path, params.get("pageNumber"))]++ monkeypatch.setattr(cloudbeds, "_fetch_page", fake_fetch)+ monkeypatch.setattr(cloudbeds, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="cbat_key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ property_id=property_id,+ ):+ rows.extend(batch)+ return rows, calls++ def test_short_page_yields_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows, _ = self._collect(+ manager, monkeypatch, {("/getReservations", 1): [{"reservationID": "1"}, {"reservationID": "2"}]}+ )+ assert rows == [{"reservationID": "1"}, {"reservationID": "2"}]+ # The page was short, so we stop without persisting resume state.+ assert manager.saved == []++ def test_follows_page_number_pagination_until_short_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ ("/getReservations", 1): _full_page(0),+ ("/getReservations", 2): [{"reservationID": "999"}],+ }+ rows, _ = self._collect(manager, monkeypatch, pages)+ assert len(rows) == PAGE_SIZE + 1+ # State is saved after the first page (advancing to page 2), then we stop on the short page.+ assert [s.page for s in manager.saved] == [2]++ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(CloudbedsResumeConfig(page=3))+ # Page 1 must never be fetched on resume.+ rows, calls = self._collect(manager, monkeypatch, {("/getReservations", 3): [{"reservationID": "5"}]})+ assert rows == [{"reservationID": "5"}]+ assert [c["pageNumber"] for c in calls] == [3]++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows, _ = self._collect(manager, monkeypatch, {("/getReservations", 1): []})+ assert rows == []+ assert manager.saved == []++ def test_property_id_is_sent_on_every_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ ("/getReservations", 1): _full_page(0),+ ("/getReservations", 2): [],+ }+ _, calls = self._collect(manager, monkeypatch, pages, property_id="12345")+ assert all(c["propertyID"] == "12345" for c in calls)++ def test_non_paginated_endpoint_fetches_once_and_never_saves_state(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {("/getHotels", None): [{"propertyID": "1"}, {"propertyID": "2"}]}+ rows, calls = self._collect(manager, monkeypatch, pages, endpoint="hotels")+ assert rows == [{"propertyID": "1"}, {"propertyID": "2"}]+ assert len(calls) == 1+ assert "pageNumber" not in calls[0]+ assert manager.saved == []++ def test_rooms_are_flattened_with_property_id(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ ("/getRooms", None): [+ {+ "propertyID": "1",+ "propertyName": "Hotel One",+ "rooms": [{"roomID": "r1", "roomName": "101"}, {"roomID": "r2", "roomName": "102"}],+ },+ {"propertyID": "2", "propertyName": "Hotel Two", "rooms": []},+ ]+ }+ rows, _ = self._collect(manager, monkeypatch, pages, endpoint="rooms")+ assert rows == [+ {"roomID": "r1", "roomName": "101", "propertyID": "1"},+ {"roomID": "r2", "roomName": "102", "propertyID": "1"},+ ]+++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 {"success": True, "data": []}+ response.text = ""+ response.reason = "Unauthorized"+ response.url = "https://api.cloudbeds.com/api/v1.2/getReservations?propertyID=1"+ 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(CloudbedsRetryableError):+ _fetch_page_unwrapped(session, "/getReservations", {}, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_sanitized_http_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError) as exc_info:+ _fetch_page_unwrapped(session, "/getReservations", {}, MagicMock())+ message = str(exc_info.value)+ # Keeps the prefix get_non_retryable_errors() matches on, but drops the query string so a+ # future credential-bearing URL can never leak into persisted error state.+ assert message.startswith(f"{status} Client Error:")+ assert "for url: https://api.cloudbeds.com/api/v1.2/getReservations" in message+ assert "?" not in message++ def test_success_returns_data_rows(self) -> None:+ body = {"success": True, "data": [{"reservationID": "1"}], "count": 1, "total": 1}+ session = self._session_returning(200, body)+ rows = _fetch_page_unwrapped(session, "/getReservations", {}, MagicMock())+ assert rows == [{"reservationID": "1"}]++ def test_success_false_raises_api_error_not_retryable(self) -> None:+ # Cloudbeds signals bad params / missing scopes as HTTP 200 + success=false; retrying would+ # loop forever, so it must surface as a distinct non-retryable error.+ body = {"success": False, "message": "Access denied for this endpoint"}+ session = self._session_returning(200, body)+ with pytest.raises(CloudbedsApiError, match="Access denied"):+ _fetch_page_unwrapped(session, "/getReservations", {}, MagicMock())++ @parameterized.expand(+ [+ ("non_dict_body", [{"reservationID": "1"}]),+ ("missing_data_key", {"success": True}),+ ("non_list_data", {"success": True, "data": {"reservationID": "1"}}),+ ]+ )+ def test_unexpected_payloads_are_retryable(self, _name: str, body: Any) -> None:+ session = self._session_returning(200, body)+ with pytest.raises(CloudbedsRetryableError):+ _fetch_page_unwrapped(session, "/getReservations", {}, MagicMock())+++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, "Cloudbeds returned HTTP 500"),+ ]+ )+ @patch(f"{cloudbeds.__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("cbat_key") == (expected_status, expected_message)++ @patch(f"{cloudbeds.__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("cbat_key")+ assert status == 0+ assert message is not None and "boom" in message++ @patch(f"{cloudbeds.__name__}.make_tracked_session")+ def test_probe_scopes_to_property_when_configured(self, mock_session: MagicMock) -> None:+ response = MagicMock()+ response.status_code = 200+ response.ok = True+ session = self._session(response)+ mock_session.return_value = session+ check_access("cbat_key", property_id="12345")+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"propertyID": "12345"}++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid Cloudbeds API key"),+ ("forbidden", 403, False, "Invalid Cloudbeds API key"),+ ("server_error", 500, False, "Cloudbeds returned HTTP 500"),+ ]+ )+ @patch(f"{cloudbeds.__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("cbat_key") == (expected_valid, expected_message)+++class TestCloudbedsSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = cloudbeds_source(+ api_key="cbat_key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == CLOUDBEDS_ENDPOINTS[endpoint].primary_keys+ # No creation timestamp is verified stable across every object, so we don't partition.+ assert response.partition_mode is None++ def test_endpoint_catalog_is_consistent(self) -> None:+ assert set(CLOUDBEDS_ENDPOINTS) == set(ENDPOINTS)+ assert all(config.primary_keys for config in CLOUDBEDS_ENDPOINTS.values())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/tests/test_cloudbeds_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/tests/test_cloudbeds_source.pynew file mode 100644index 000000000000..92707e6fe1a6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudbeds/tests/test_cloudbeds_source.py@@ -0,0 +1,147 @@+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.cloudbeds.cloudbeds import CloudbedsResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudbeds.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudbeds.source import CloudbedsSource+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 CloudbedsSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestCloudbedsSource:+ def setup_method(self) -> None:+ self.source = CloudbedsSource()+ self.team_id = 123+ self.config = CloudbedsSourceConfig(api_key="cbat_key", property_id="12345")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.CLOUDBEDS++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Cloudbeds"+ assert config.label == "Cloudbeds"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # Deliberately still hidden while endpoint behavior is verified against a live account.+ assert config.unreleasedSource is True+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/cloudbeds"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key", "property_id"]++ 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_property_id_field_is_optional(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "property_id")+ assert field.required is False+ assert field.secret is False++ def test_property_id_is_a_connection_host_field(self) -> None:+ # property_id scopes which property the preserved API key reads from, so retargeting it must+ # re-require the key - otherwise a group-level credential could be pointed at another property.+ assert self.source.connection_host_fields == ["property_id"]++ 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=["reservations"])+ assert len(schemas) == 1+ assert schemas[0].name == "reservations"++ 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.cloudbeds.com/api/v1.2/getReservations?pageNumber=1",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://api.cloudbeds.com/api/v1.2/getGuestList?pageNumber=1",+ ),+ ]+ )+ 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.cloudbeds.com/api/v1.2/getHotels",+ ),+ (+ "rate_limited",+ "429 Client Error: Too Many Requests for url: https://api.cloudbeds.com/api/v1.2/getReservations",+ ),+ ]+ )+ 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.cloudbeds.source.validate_credentials"+ )+ def test_validate_credentials_delegates_with_api_key_and_property(self, mock_validate: mock.MagicMock) -> None:+ # The status-to-message mapping lives in cloudbeds.validate_credentials; here we only assert+ # the source probes with the configured credentials and returns the delegate's verdict.+ mock_validate.return_value = (False, "Invalid Cloudbeds API key")+ result = self.source.validate_credentials(self.config, self.team_id)+ mock_validate.assert_called_once_with("cbat_key", "12345")+ assert result == (False, "Invalid Cloudbeds 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 CloudbedsResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cloudbeds.source.cloudbeds_source"+ ) as mock_source:+ inputs = mock.MagicMock()+ inputs.schema_name = "reservations"+ 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"] == "cbat_key"+ assert kwargs["endpoint"] == "reservations"+ assert kwargs["property_id"] == "12345"+ 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 Cloudbeds schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex e6b194039565..1751839bab0a 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@@ -779,7 +779,8 @@ class CloseSourceConfig(config.Config):@config.configclass CloudbedsSourceConfig(config.Config):- pass+ api_key: str+ property_id: str | None = None@config.config