: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): add Cloudability import source (#84357)
Tom Owers144ea413b61a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudability/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudability/canonical_descriptions.pynew file mode 100644index 000000000000..4cb6c232e891--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudability/canonical_descriptions.py@@ -0,0 +1,90 @@+"""Canonical, documentation-sourced descriptions for Cloudability endpoints and columns.++Sourced from IBM's Cloudability v3 API reference (see each entry's `docs_url`). Keyed by the+resource names in `settings.py` `ENDPOINTS`, which match the `ExternalDataSchema.name` of a+synced Cloudability table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Costs": {+ "description": "Cloud cost and usage totals grouped by vendor, account, region, and service, "+ "over a trailing window. Fully replaced each sync to absorb late vendor billing restatements.",+ "docs_url": "https://www.ibm.com/docs/en/cloudability-commercial/cloudability-standard/saas?topic=api-cost-reporting-end-point",+ "columns": {+ "vendor": "Cloud vendor the cost was billed by (for example AWS, Azure, or GCP).",+ "linked_account_name": "Display name of the linked cloud account the cost was billed to.",+ "region": "Cloud provider region the usage occurred in.",+ "enhanced_service_name": "Cloudability-normalized name of the cloud service the cost was billed for.",+ "unblended_cost": "Cost as billed by the vendor, before amortization or discounts are applied.",+ "total_amortized_cost": "Cost with upfront and recurring charges (for example reserved instance fees) spread evenly across their term.",+ "usage_hours": "Number of hours the resource was in use during the reporting window.",+ },+ },+ "Views": {+ "description": "A saved set of filters that scopes cost and usage data to a subset of accounts, "+ "tags, or business dimensions.",+ "docs_url": "https://www.ibm.com/docs/en/SSXUJG/cloudability/api/v3/views_end_point.htm",+ "columns": {+ "id": "Unique identifier for the view.",+ "title": "Display name of the view.",+ "description": "Description of what the view scopes to.",+ "ownerId": "Identifier of the user who owns the view.",+ "ownerEmail": "Email address of the user who owns the view.",+ "sharedWithOrganization": "Whether the view is shared with the whole organization.",+ "sharedWithUsers": "User IDs the view has been explicitly shared with.",+ "filters": "The filter rules that scope this view's data.",+ },+ },+ "BusinessMappingDimensions": {+ "description": "A rule-based custom dimension that allocates cloud spend to cost centers, "+ "products, environments, or applications.",+ "docs_url": "https://www.ibm.com/docs/en/cloudability-commercial/cloudability-premium/saas?topic=api-business-mappings-end-point",+ "columns": {+ "name": "Unique identifier for the business dimension.",+ "index": "Numeric slot (1-10) the dimension occupies.",+ "kind": "Always 'BUSINESS_DIMENSION' for this endpoint.",+ "defaultValue": "Value assigned when no statement matches a cost row.",+ "statements": "Ordered matching rules, each mapping a match expression to a value.",+ },+ },+ "BusinessMappingMetrics": {+ "description": "A rule-based custom metric computed from cloud cost and usage data, such as a "+ "cost allocated by a business formula.",+ "docs_url": "https://www.ibm.com/docs/en/cloudability-commercial/cloudability-premium/saas?topic=api-business-mappings-end-point",+ "columns": {+ "name": "Unique identifier for the business metric.",+ "index": "Numeric slot the metric occupies.",+ "kind": "Always 'BUSINESS_METRIC' for this endpoint.",+ "numberFormat": "Display format for the metric's value, 'currency' or 'number'.",+ "defaultValueExpression": "Fallback expression evaluated when no statement matches.",+ "preMatchExpression": "Expression evaluated globally before per-row statements.",+ "statements": "Ordered conditional rules used to compute the metric's value.",+ "updatedAt": "Time the metric definition was last updated.",+ },+ },+ "Anomalies": {+ "description": "A cost anomaly Cloudability detected, such as a first-time or unusually large "+ "spend on a service.",+ "docs_url": "https://www.ibm.com/docs/en/cloudability-commercial/cloudability-premium/saas?topic=v3-anomaly-detection-end-point",+ "columns": {+ "id": "Unique identifier for the anomaly.",+ "date": "Date the anomalous spend occurred.",+ "type": "Category of anomaly detected.",+ "vendor": "Cloud vendor the anomalous spend was billed by.",+ "vendorAccountName": "Display name of the cloud account the anomalous spend occurred on.",+ "enhancedServiceName": "Cloudability-normalized name of the service the anomaly was detected on.",+ "usageFamily": "Broader usage category the anomalous service belongs to.",+ "unblendedCost": "Actual cost billed for the anomalous spend.",+ "unusualSpend": "Dollar amount by which the spend exceeded the expected baseline.",+ "unusualSpendPercentage": "Percentage by which the spend exceeded the expected baseline.",+ "currencyCode": "Currency the cost amounts are denominated in.",+ "tags": "Cost allocation tags associated with the anomalous resource.",+ "businessDimensions": "Business mapping dimension values associated with the anomalous resource.",+ "issueFields": "Additional fields describing the specific issue detected.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudability/cloudability.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudability/cloudability.pynew file mode 100644index 000000000000..23c1060ee08f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudability/cloudability.py@@ -0,0 +1,179 @@+from datetime import date, timedelta+from typing import Any, Optional++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.cloudability.settings import (+ ANOMALIES_LOOKBACK_DAYS,+ COST_REPORT_DIMENSIONS,+ COST_REPORT_LOOKBACK_DAYS,+ COST_REPORT_METRICS,+ PRIMARY_KEYS,+)+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 (+ JSONResponseCursorPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+++@frozen+class CloudabilityResumeConfig:+ cursor: str+++def base_url(region: str) -> str:+ host = "api-eu.cloudability.com" if region == "eu" else "api.cloudability.com"+ return f"https://{host}/v3"+++def get_resource(name: str, view_id: Optional[str]) -> EndpointResource:+ today = date.today()++ if name == "Costs":+ return {+ "name": "Costs",+ "table_name": "costs",+ "write_disposition": "replace",+ "endpoint": {+ "path": "/reporting/cost/run",+ "data_selector": "results",+ "data_selector_required": True,+ "params": {+ "start_date": (today - timedelta(days=COST_REPORT_LOOKBACK_DAYS)).isoformat(),+ "end_date": today.isoformat(),+ "dimensions": ",".join(COST_REPORT_DIMENSIONS),+ "metrics": ",".join(COST_REPORT_METRICS),+ "limit": 10000,+ },+ # Cloudability paginates cost reports >10,000 rows with a `pagination.next`+ # token rather than offset/limit once the first page is exhausted.+ "paginator": JSONResponseCursorPaginator(cursor_path="pagination.next", cursor_param="token"),+ },+ "table_format": "delta",+ }++ if name == "Views":+ return {+ "name": "Views",+ "table_name": "views",+ "write_disposition": "replace",+ "endpoint": {+ "path": "/views",+ "data_selector_required": True,+ "paginator": "single_page",+ },+ "table_format": "delta",+ }++ if name == "BusinessMappingDimensions":+ return {+ "name": "BusinessMappingDimensions",+ "table_name": "business_mapping_dimensions",+ "write_disposition": "replace",+ "endpoint": {+ "path": "/business-mappings/dimensions",+ "data_selector_required": True,+ "paginator": "single_page",+ },+ "table_format": "delta",+ }++ if name == "BusinessMappingMetrics":+ return {+ "name": "BusinessMappingMetrics",+ "table_name": "business_mapping_metrics",+ "write_disposition": "replace",+ "endpoint": {+ "path": "/business-mappings/metrics/",+ "data_selector_required": True,+ "paginator": "single_page",+ },+ "table_format": "delta",+ }++ if name == "Anomalies":+ return {+ "name": "Anomalies",+ "table_name": "anomalies",+ "write_disposition": "replace",+ "endpoint": {+ "path": "/anomalies",+ "data_selector_required": True,+ "params": {+ "startDate": (today - timedelta(days=ANOMALIES_LOOKBACK_DAYS)).isoformat(),+ "endDate": today.isoformat(),+ "viewId": view_id,+ },+ "paginator": "single_page",+ },+ "table_format": "delta",+ }++ raise ValueError(f"Unknown Cloudability endpoint: {name}")+++def validate_credentials(api_key: str, region: str) -> bool:+ res = make_tracked_session(redact_values=(api_key,)).get(+ f"{base_url(region)}/views",+ auth=(api_key, ""),+ )+ return res.status_code == 200+++def cloudability_source(+ api_key: str,+ region: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[CloudabilityResumeConfig],+ view_id: Optional[str],+) -> SourceResponse:+ config: RESTAPIConfig = {+ "client": {+ "base_url": base_url(region),+ "auth": {+ "type": "http_basic",+ "username": api_key,+ "password": "",+ },+ },+ "resource_defaults": {+ "write_disposition": "replace",+ },+ "resources": [get_resource(endpoint, view_id)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = {"cursor": resume_config.cursor}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only the Costs endpoint's cursor paginator ever returns resume state; the other+ # (single-page) endpoints call this with None and it's a no-op.+ if state and state.get("cursor"):+ resumable_source_manager.save_state(CloudabilityResumeConfig(cursor=str(state["cursor"])))++ resource = rest_api_resource(+ config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=resource.name,+ items=lambda: resource,+ primary_keys=PRIMARY_KEYS[endpoint],+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudability/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudability/settings.pynew file mode 100644index 000000000000..b9b0c33ae669--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudability/settings.py@@ -0,0 +1,42 @@+from products.warehouse_sources.backend.types import IncrementalField++# Cloudability's v3 API is REST/JSON, authenticated with an API key sent as the HTTP Basic+# username (empty password). None of these endpoints expose a server-side "modified since"+# filter, so every table is full refresh — see cloudability.py for how each one is queried.+ENDPOINTS = (+ "Costs",+ "Views",+ "BusinessMappingDimensions",+ "BusinessMappingMetrics",+ "Anomalies",+)++# No endpoint documents a reliable incremental cursor: cost rows are a dimension-grouped+# aggregate over a queried date window (no per-row id/timestamp survives the group-by), and the+# entity endpoints (views, business mappings, anomalies) don't expose an updated-since filter.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}++PRIMARY_KEYS: dict[str, list[str]] = {+ # No id survives the dimension group-by on a cost report row; the dimension values+ # queried together are what uniquely identifies a row for the window synced.+ "Costs": ["vendor", "linked_account_name", "region", "enhanced_service_name"],+ "Views": ["id"],+ "BusinessMappingDimensions": ["name"],+ "BusinessMappingMetrics": ["name"],+ "Anomalies": ["id"],+}++# Dimensions and metrics for the Costs report, taken from the worked examples on Cloudability's+# own "Cost Reporting End Point" doc (not guessed) — the endpoint accepts up to 15 dimensions and+# 8 metrics, but a source can't ask the user to pick per-sync, so this is a sensible fixed set.+COST_REPORT_DIMENSIONS = ("vendor", "linked_account_name", "region", "enhanced_service_name")+COST_REPORT_METRICS = ("unblended_cost", "total_amortized_cost", "usage_hours")++# Cost data is restated for weeks after the fact as vendor invoices settle, and the report has no+# per-row date dimension to merge on incrementally, so each sync re-queries and replaces this+# trailing window rather than trying to accumulate history additively.+COST_REPORT_LOOKBACK_DAYS = 395++# Anomalies are queried over a trailing window and fully replaced each sync, since the API only+# supports "detected between startDate and endDate" rather than an updated-since filter.+ANOMALIES_LOOKBACK_DAYS = 90diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudability/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudability/source.pyindex af907ebfda4d..75a2b183bf24 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudability/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudability/source.py@@ -1,13 +1,36 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudability.cloudability import (+ CloudabilityResumeConfig,+ cloudability_source,+ validate_credentials as validate_cloudability_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudability.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.cloudability import (CloudabilitySourceConfig,)@@ -15,18 +38,112 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CloudabilitySource(SimpleSource[CloudabilitySourceConfig]):+class CloudabilitySource(ResumableSource[CloudabilitySourceConfig, CloudabilityResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ supported_versions = ("v3",)+ default_version = "v3"+ api_docs_url = "https://www.ibm.com/docs/en/cloudability-commercial/cloudability-premium/saas?topic=api-getting-started-cloudability-v3"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CLOUDABILITY+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Cloudability authentication failed. Please check your API key and region.",+ "Unauthorized for url": "Cloudability authentication failed. Please check your API key and region.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.cloudability.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: CloudabilitySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: CloudabilitySourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ if validate_cloudability_credentials(config.api_key, config.region):+ return True, None++ return False, "Invalid credentials. Check your API key and region."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CloudabilityResumeConfig]:+ return ResumableSourceManager[CloudabilityResumeConfig](inputs, CloudabilityResumeConfig)++ def source_for_pipeline(+ self,+ config: CloudabilitySourceConfig,+ resumable_source_manager: ResumableSourceManager[CloudabilityResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return cloudability_source(+ api_key=config.api_key,+ region=config.region,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ view_id=config.view_id or None,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.CLOUDABILITY,category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,label="Apptio Cloudability (IBM)",+ keywords=["cloudability", "finops", "cloud cost", "apptio"],+ docsUrl="https://posthog.com/docs/cdp/sources/cloudability",iconPath="/static/services/cloudability.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ caption="Generate this in Cloudability under the gear icon > Preferences > Enable Access.",+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US (api.cloudability.com)", value="us"),+ SourceFieldSelectConfigOption(label="EU (api-eu.cloudability.com)", value="eu"),+ ],+ ),+ SourceFieldInputConfig(+ name="view_id",+ label="Default view ID (optional)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="",+ secret=False,+ caption="Scopes the Anomalies table to one Cloudability view. Leave blank to use your organization's default view.",+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudability/tests/test_cloudability.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudability/tests/test_cloudability.pynew file mode 100644index 000000000000..ac04ebe99b87--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudability/tests/test_cloudability.py@@ -0,0 +1,221 @@+import json+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.cloudability.cloudability import (+ CloudabilityResumeConfig,+ base_url,+ cloudability_source,+ get_resource,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudability.settings import (+ COST_REPORT_DIMENSIONS,+ COST_REPORT_METRICS,+ ENDPOINTS,+ PRIMARY_KEYS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponseCursorPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import Endpoint+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+++class TestBaseUrl:+ @pytest.mark.parametrize(+ "region, expected",+ [+ ("us", "https://api.cloudability.com/v3"),+ ("eu", "https://api-eu.cloudability.com/v3"),+ # Anything unrecognized falls back to US rather than sending an unpredictable host.+ ("unknown", "https://api.cloudability.com/v3"),+ ],+ )+ def test_base_url(self, region, expected):+ assert base_url(region) == expected+++class TestGetResource:+ def test_costs_uses_cursor_paginator_and_documented_dimensions(self):+ resource = get_resource("Costs", view_id=None)++ endpoint = cast(Endpoint, resource["endpoint"])+ assert endpoint["path"] == "/reporting/cost/run"+ assert endpoint["data_selector"] == "results"+ assert isinstance(endpoint["paginator"], JSONResponseCursorPaginator)+ params = cast(dict[str, Any], endpoint["params"])+ assert params["dimensions"] == ",".join(COST_REPORT_DIMENSIONS)+ assert params["metrics"] == ",".join(COST_REPORT_METRICS)+ assert resource["write_disposition"] == "replace"++ def test_costs_date_window_is_start_before_end(self):+ endpoint = cast(Endpoint, get_resource("Costs", view_id=None)["endpoint"])+ params = cast(dict[str, Any], endpoint["params"])+ assert params["start_date"] < params["end_date"]++ @pytest.mark.parametrize(+ "endpoint_name, path",+ [+ ("Views", "/views"),+ ("BusinessMappingDimensions", "/business-mappings/dimensions"),+ ("BusinessMappingMetrics", "/business-mappings/metrics/"),+ ],+ )+ def test_single_page_endpoints(self, endpoint_name, path):+ resource = get_resource(endpoint_name, view_id=None)+ endpoint = cast(Endpoint, resource["endpoint"])++ assert endpoint["path"] == path+ assert endpoint["paginator"] == "single_page"+ assert endpoint["data_selector_required"] is True++ def test_anomalies_omits_view_id_when_not_configured(self):+ endpoint = cast(Endpoint, get_resource("Anomalies", view_id=None)["endpoint"])+ params = cast(dict[str, Any], endpoint["params"])+ assert params["viewId"] is None++ def test_anomalies_passes_configured_view_id(self):+ endpoint = cast(Endpoint, get_resource("Anomalies", view_id="42")["endpoint"])+ params = cast(dict[str, Any], endpoint["params"])+ assert params["viewId"] == "42"++ def test_unknown_endpoint_raises(self):+ with pytest.raises(ValueError, match="Unknown Cloudability endpoint"):+ get_resource("NotARealEndpoint", view_id=None)++ def test_every_declared_endpoint_has_a_primary_key(self):+ for endpoint_name in ENDPOINTS:+ resource = get_resource(endpoint_name, view_id="42")+ assert PRIMARY_KEYS[endpoint_name]+ assert resource["table_format"] == "delta"+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected",+ [(200, True), (401, False), (403, False), (500, False)],+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cloudability.cloudability.make_tracked_session"+ )+ def test_validate_credentials_checks_status_code(self, mock_make_session, status_code, expected):+ mock_session = mock_make_session.return_value+ mock_session.get.return_value = MagicMock(status_code=status_code)++ assert validate_credentials("api-key", "us") is expected++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cloudability.cloudability.make_tracked_session"+ )+ def test_validate_credentials_uses_basic_auth_with_empty_password(self, mock_make_session):+ mock_session = mock_make_session.return_value+ mock_session.get.return_value = MagicMock(status_code=200)++ validate_credentials("api-key", "eu")++ mock_session.get.assert_called_once_with(+ "https://api-eu.cloudability.com/v3/views",+ auth=("api-key", ""),+ )+++def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ return resp+++class TestCloudabilitySourceResumeBehavior:+ """End-to-end resume behaviour of ``cloudability_source`` via ``rest_api_resource``."""++ def _drive(+ self, endpoint: str, manager: MagicMock, responses: list[Response], view_id: str | None = None+ ) -> tuple[MagicMock, list[dict[str, Any]]]:+ sent_params: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_params.append(dict(request.params or {}))+ return next(response_iter)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ resource = cloudability_source(+ api_key="test-key",+ region="us",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ view_id=view_id,+ )+ list(cast(Iterable[Any], resource.items()))+ return mock_session, sent_params++ def test_fresh_run_saves_token_after_non_terminal_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response({"results": [{"vendor": "AWS"}], "pagination": {"next": "tok-1"}}),+ _make_http_response({"results": [{"vendor": "GCP"}]}),+ ]+ _, sent_params = self._drive("Costs", manager, responses)++ tokens_sent = [p.get("token") for p in sent_params]+ assert tokens_sent == [None, "tok-1"]++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [CloudabilityResumeConfig(cursor="tok-1")]++ def test_resume_seeds_paginator_with_saved_token(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = CloudabilityResumeConfig(cursor="tok-resumed")++ responses = [_make_http_response({"results": [{"vendor": "Azure"}]})]+ _, sent_params = self._drive("Costs", manager, responses)++ assert [p.get("token") for p in sent_params] == ["tok-resumed"]+ manager.load_state.assert_called_once()++ def test_terminal_single_page_does_not_save_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response({"results": [{"vendor": "AWS"}]})]+ self._drive("Costs", manager, responses)++ manager.save_state.assert_not_called()++ @pytest.mark.parametrize(+ "endpoint, response_body",+ [+ ("Views", [{"id": "v1", "title": "Default"}]),+ ("BusinessMappingDimensions", [{"name": "team", "index": 1}]),+ ("BusinessMappingMetrics", [{"name": "allocated_cost", "index": 1}]),+ ("Anomalies", [{"id": "a1", "vendor": "AWS"}]),+ ],+ )+ def test_single_page_endpoints_do_not_save_resume_state(self, endpoint, response_body) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response(response_body)]+ _, rows = self._drive(endpoint, manager, responses)++ manager.save_state.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudability/tests/test_cloudability_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudability/tests/test_cloudability_source.pynew file mode 100644index 000000000000..00bb536d32fe--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudability/tests/test_cloudability_source.py@@ -0,0 +1,155 @@+from types import SimpleNamespace+from typing import cast++import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.cloudability.cloudability import (+ CloudabilityResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudability.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudability.source import CloudabilitySource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.cloudability import (+ CloudabilitySourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestCloudabilitySource:+ def setup_method(self):+ self.source = CloudabilitySource()+ self.team_id = 123+ self.config = CloudabilitySourceConfig(api_key="key", region="us", view_id=None)++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.CLOUDABILITY++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Cloudability"+ assert config.category is not None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert not config.unreleasedSource+ assert config.iconPath == "/static/services/cloudability.png"+ assert len(config.fields) == 3++ api_key_field = config.fields[0]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.name == "api_key"+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.required is True+ assert api_key_field.secret is True++ region_field = config.fields[1]+ assert isinstance(region_field, SourceFieldSelectConfig)+ assert region_field.name == "region"+ assert region_field.defaultValue == "us"+ assert {option.value for option in region_field.options} == {"us", "eu"}++ view_id_field = config.fields[2]+ assert isinstance(view_id_field, SourceFieldInputConfig)+ assert view_id_field.name == "view_id"+ assert view_id_field.required is False+ assert view_id_field.secret is False++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "Unauthorized for url"])+ def test_non_retryable_errors_includes_auth_keys(self, expected_key):+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_schemas_returns_every_endpoint(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_no_endpoint_advertises_incremental(self, endpoint):+ # None of Cloudability's endpoints expose a server-side "modified since" filter.+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)+ assert schema.supports_incremental is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Views"])+ assert len(schemas) == 1+ assert schemas[0].name == "Views"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ (True, True, None),+ (False, False, "Invalid credentials. Check your API key and region."),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cloudability.source.validate_cloudability_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with(self.config.api_key, self.config.region)++ def test_get_resumable_source_manager_is_bound_to_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is CloudabilityResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cloudability.source.cloudability_source"+ )+ def test_source_for_pipeline_plumbs_inputs(self, mock_cloudability_source):+ mock_cloudability_source.return_value = SimpleNamespace(name="Views")+ manager = mock.MagicMock(spec=ResumableSourceManager)+ inputs = SimpleNamespace(schema_name="Views", team_id=self.team_id, job_id="job-1")++ response = self.source.source_for_pipeline(self.config, manager, cast(SourceInputs, inputs))++ mock_cloudability_source.assert_called_once_with(+ api_key="key",+ region="us",+ endpoint="Views",+ team_id=self.team_id,+ job_id="job-1",+ resumable_source_manager=manager,+ view_id=None,+ )+ assert response is mock_cloudability_source.return_value++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cloudability.source.cloudability_source"+ )+ def test_source_for_pipeline_passes_blank_view_id_as_none(self, mock_cloudability_source):+ # An empty string from the form must not be sent to Cloudability as a literal viewId="".+ config = CloudabilitySourceConfig(api_key="key", region="eu", view_id="")+ mock_cloudability_source.return_value = SimpleNamespace(name="Anomalies")+ manager = mock.MagicMock(spec=ResumableSourceManager)+ inputs = SimpleNamespace(schema_name="Anomalies", team_id=self.team_id, job_id="job-2")++ self.source.source_for_pipeline(config, manager, cast(SourceInputs, inputs))++ assert mock_cloudability_source.call_args.kwargs["view_id"] is None++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cloudability.source.cloudability_source"+ )+ def test_source_for_pipeline_passes_configured_view_id(self, mock_cloudability_source):+ config = CloudabilitySourceConfig(api_key="key", region="us", view_id="42")+ mock_cloudability_source.return_value = SimpleNamespace(name="Anomalies")+ manager = mock.MagicMock(spec=ResumableSourceManager)+ inputs = SimpleNamespace(schema_name="Anomalies", team_id=self.team_id, job_id="job-3")++ self.source.source_for_pipeline(config, manager, cast(SourceInputs, inputs))++ assert mock_cloudability_source.call_args.kwargs["view_id"] == "42"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cloudability.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cloudability.pyindex 0f9cf83ff7b8..30421d8b76dd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cloudability.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cloudability.py@@ -1,9 +1,13 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config@config.configclass CloudabilitySourceConfig(config.Config):- pass+ api_key: str+ region: Literal["us", "eu"] = config.value(default="us")+ view_id: str | None = None