Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement sonar_cloud import source (#71150)

Tom Owers4232b7b98cd1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index ca1bc1a9bcd8..8c5d2c70fe90 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -476,6 +476,7 @@ the row lists both.
| snowplow | HTTP | requests | ✅ |
| snyk | HTTP | requests | ✅ |
| solarwinds_service_desk | HTTP | requests | ✅ |
+| sonar_cloud | HTTP | requests | ✅ |
| sonarqube | HTTP | requests | ✅ |
| spacelift | HTTP (GraphQL) | requests | ✅ |
| sparkpost | HTTP | requests | ✅ |
@@ -921,7 +922,6 @@ doesn't conflict with concurrent PRs.
- smartengage
- smartwaiver
- solarwinds_service_desk
-- sonar_cloud
- sonatype_nexus
- sourcegraph
- spacelift
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.py
index 2f40e653aba5..8832088a7d86 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
@@ -4073,7 +4073,9 @@ class SolarwindsServiceDeskSourceConfig(config.Config):
@config.config
class SonarCloudSourceConfig(config.Config):
- pass
+ token: str
+ organization: str
+ region: Literal["eu", "us"] = config.value(default="eu")
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonar_cloud/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonar_cloud/canonical_descriptions.py
new file mode 100644
index 000000000000..34838a098c81
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonar_cloud/canonical_descriptions.py
@@ -0,0 +1,71 @@
+"""Canonical, documentation-sourced descriptions for SonarQube Cloud endpoints and columns.
+
+Sourced from the official SonarQube Cloud Web API reference (the in-app `/web_api` docs).
+Keyed by the endpoint names in `settings.py` `SONAR_CLOUD_ENDPOINTS`, which match the
+`ExternalDataSchema.name` of a synced 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 = {
+ "projects": {
+ "description": "Projects (top-level components) in the organization, as returned by components/search_projects.",
+ "docs_url": "https://sonarcloud.io/web_api/api/components",
+ "columns": {
+ "key": "Unique project key within the organization.",
+ "name": "Display name of the project.",
+ "qualifier": "Component qualifier; TRK for projects.",
+ "organization": "Organization key the project belongs to.",
+ "analysisDate": "Timestamp of the project's most recent analysis.",
+ "revision": "SCM revision of the most recent analysis.",
+ "visibility": "Project visibility (public or private).",
+ },
+ },
+ "issues": {
+ "description": "Code issues (bugs, vulnerabilities, code smells) across the organization's projects.",
+ "docs_url": "https://sonarcloud.io/web_api/api/issues",
+ "columns": {
+ "key": "Unique identifier for the issue.",
+ "rule": "Key of the rule that raised the issue.",
+ "severity": "Issue severity (INFO, MINOR, MAJOR, CRITICAL, BLOCKER).",
+ "component": "Key of the component (file) the issue was found in.",
+ "project": "Key of the project the issue belongs to.",
+ "line": "Line number the issue points to, if any.",
+ "status": "Current status of the issue (e.g. OPEN, CONFIRMED, RESOLVED, CLOSED).",
+ "resolution": "Resolution once the issue is closed (e.g. FIXED, WONTFIX, FALSE-POSITIVE).",
+ "type": "Issue type (BUG, VULNERABILITY, CODE_SMELL).",
+ "effort": "Estimated effort to fix the issue.",
+ "tags": "Tags attached to the issue.",
+ "creationDate": "Timestamp when the issue was first detected.",
+ "updateDate": "Timestamp when the issue was last updated.",
+ "author": "Author of the code that introduced the issue.",
+ },
+ },
+ "metrics": {
+ "description": "Definitions of the metrics SonarQube Cloud can compute (coverage, bugs, duplications, ...).",
+ "docs_url": "https://sonarcloud.io/web_api/api/metrics",
+ "columns": {
+ "id": "Internal identifier of the metric.",
+ "key": "Unique metric key (e.g. coverage, bugs, ncloc).",
+ "name": "Human-readable metric name.",
+ "description": "Description of what the metric measures.",
+ "domain": "Domain the metric belongs to (e.g. Coverage, Reliability).",
+ "type": "Value type of the metric (INT, FLOAT, PERCENT, RATING, ...).",
+ "direction": "Whether higher or lower values are better.",
+ "qualitative": "Whether the metric is qualitative.",
+ "hidden": "Whether the metric is hidden from the UI.",
+ },
+ },
+ "quality_gates": {
+ "description": "Quality gates defined in the organization (the pass/fail conditions applied to analyses).",
+ "docs_url": "https://sonarcloud.io/web_api/api/qualitygates",
+ "columns": {
+ "id": "Unique identifier of the quality gate.",
+ "name": "Name of the quality gate.",
+ "isDefault": "Whether this is the organization's default quality gate.",
+ "isBuiltIn": "Whether this is a built-in, non-editable quality gate.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonar_cloud/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonar_cloud/settings.py
new file mode 100644
index 000000000000..356ee5164775
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonar_cloud/settings.py
@@ -0,0 +1,73 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+# SonarQube Cloud v1 web API host per region. The token and organization are region-bound, so the
+# host the user picks decides which of these we hit. v2 (api.sonarcloud.io / api.sonarqube.us) is
+# gradually replacing v1, but v1 is still the mature, documented surface for these resources.
+REGION_HOSTS: dict[str, str] = {
+ "eu": "https://sonarcloud.io/api",
+ "us": "https://sonarqube.us/api",
+}
+
+# v1 search endpoints page via `p`/`ps` (max 500) and hard-cap the total result set at 10000 rows.
+# We ask for the largest page and stop once the cap is reached; slicing past it would need date/facet
+# windowing, which the v1 surface doesn't offer uniformly.
+MAX_PAGE_SIZE = 500
+RESULT_CAP = 10000
+
+
+@dataclass
+class SonarCloudEndpointConfig:
+ name: str
+ # v1 path relative to `<host>/api`, e.g. "issues/search".
+ path: str
+ # Key in the JSON response holding the row list (SonarQube Cloud wraps rows differently per resource).
+ data_key: str
+ primary_keys: list[str] = field(default_factory=lambda: ["key"])
+ # Most resources are scoped to a single organization; metric definitions are global.
+ requires_organization: bool = True
+ # Stable creation-time field to partition by. Never an updated_at-style field, which would rewrite
+ # partitions every sync. `None` disables partitioning for the endpoint.
+ partition_key: Optional[str] = None
+ # Some resources (quality gates) return a flat, unpaginated list.
+ paginated: bool = True
+ should_sync_default: bool = True
+
+
+# Endpoint catalog. Mirrors the streams the existing Airbyte SonarCloud connector ships (projects,
+# issues, metrics) plus quality gates, all reachable with just an organization key. Every stream is
+# full refresh: SonarQube Cloud exposes no uniform server-side update cursor, so there is no reliable
+# incremental field to advertise (see the source docstring).
+SONAR_CLOUD_ENDPOINTS: dict[str, SonarCloudEndpointConfig] = {
+ "projects": SonarCloudEndpointConfig(
+ name="projects",
+ path="components/search_projects",
+ data_key="components",
+ ),
+ "issues": SonarCloudEndpointConfig(
+ name="issues",
+ path="issues/search",
+ data_key="issues",
+ partition_key="creationDate",
+ ),
+ "metrics": SonarCloudEndpointConfig(
+ name="metrics",
+ path="metrics/search",
+ data_key="metrics",
+ requires_organization=False,
+ ),
+ "quality_gates": SonarCloudEndpointConfig(
+ name="quality_gates",
+ path="qualitygates/list",
+ data_key="qualitygates",
+ primary_keys=["id"],
+ paginated=False,
+ ),
+}
+
+ENDPOINTS = tuple(SONAR_CLOUD_ENDPOINTS.keys())
+
+# No endpoint advertises a server-side timestamp filter we've verified, so none are incremental.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in SONAR_CLOUD_ENDPOINTS}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonar_cloud/sonar_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonar_cloud/sonar_cloud.py
new file mode 100644
index 000000000000..94b404dffbf4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonar_cloud/sonar_cloud.py
@@ -0,0 +1,178 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from 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.sonar_cloud.settings import (
+ MAX_PAGE_SIZE,
+ REGION_HOSTS,
+ RESULT_CAP,
+ SONAR_CLOUD_ENDPOINTS,
+)
+
+
+class SonarCloudRetryableError(Exception):
+ pass
+
+
+class SonarCloudResumeConfig:
+ # 1-based index of the next page to fetch. Paginated endpoints resume from here after a crash;
+ # non-paginated endpoints ignore it.
+ page: int = 1
+
+
+def _base_url(region: str) -> str:
+ return REGION_HOSTS.get((region or "eu").lower(), REGION_HOSTS["eu"])
+
+
+def _headers(token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {token}",
+ "Accept": "application/json",
+ }
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ SonarCloudRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict[str, Any]:
+ response = session.get(url, timeout=60)
+
+ # SonarQube Cloud returns 429 with no documented quota on rate limiting; back off and retry.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise SonarCloudRetryableError(f"SonarQube Cloud API error (retryable): status={response.status_code}")
+
+ if not response.ok:
+ logger.error(f"SonarQube Cloud API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _build_url(base_url: str, path: str, params: dict[str, Any]) -> str:
+ query = urlencode({k: v for k, v in params.items() if v is not None})
+ return f"{base_url}/{path}?{query}" if query else f"{base_url}/{path}"
+
+
+def _total(data: dict[str, Any]) -> int | None:
+ """Total row count, from either the nested `paging` object or the flat top-level fields."""
+ paging = data.get("paging")
+ if isinstance(paging, dict) and paging.get("total") is not None:
+ return int(paging["total"])
+ if data.get("total") is not None:
+ return int(data["total"])
+ return None
+
+
+def validate_credentials(token: str, organization: str, region: str, timeout: int = 10) -> int:
+ """Probe the projects endpoint and return the HTTP status code (or 0 on transport failure).
+
+ A single cheap request confirms the token is genuine. The caller decides how to treat 403
+ (valid token, missing scope) depending on whether it's validating a specific schema.
+ """
+ url = _build_url(_base_url(region), "components/search_projects", {"organization": organization, "ps": 1})
+ try:
+ response = make_tracked_session(headers=_headers(token)).get(url, timeout=timeout)
+ return response.status_code
+ except Exception:
+ return 0
+
+
+def get_rows(
+ token: str,
+ organization: str,
+ region: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SonarCloudResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = SONAR_CLOUD_ENDPOINTS[endpoint]
+ base_url = _base_url(region)
+ session = make_tracked_session(headers=_headers(token))
+
+ base_params: dict[str, Any] = {}
+ if config.requires_organization:
+ base_params["organization"] = organization
+
+ if not config.paginated:
+ data = _fetch(session, _build_url(base_url, config.path, base_params), logger)
+ rows = data.get(config.data_key, [])
+ if rows:
+ yield rows
+ return
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.page if resume is not None else 1
+ fetched = (page - 1) * MAX_PAGE_SIZE
+
+ while True:
+ params = {**base_params, "p": page, "ps": MAX_PAGE_SIZE}
+ data = _fetch(session, _build_url(base_url, config.path, params), logger)
+ rows = data.get(config.data_key, [])
+ if not rows:
+ break
+
+ yield rows
+ fetched += len(rows)
+
+ total = _total(data)
+ # v1 hard-caps results at 10000 regardless of the reported total; stop there to avoid
+ # requesting pages the API will reject.
+ if len(rows) < MAX_PAGE_SIZE or fetched >= RESULT_CAP or (total is not None and fetched >= total):
+ if fetched >= RESULT_CAP and (total is None or total > RESULT_CAP):
+ logger.warning(
+ f"SonarQube Cloud endpoint {endpoint} hit the 10000-result cap; rows beyond the cap were not synced"
+ )
+ break
+
+ page += 1
+ # Save after yielding so a crash re-yields the last page (merge dedupes on the primary key)
+ # rather than skipping it.
+ resumable_source_manager.save_state(SonarCloudResumeConfig(page=page))
+
+
+def sonar_cloud_source(
+ token: str,
+ organization: str,
+ region: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SonarCloudResumeConfig],
+) -> SourceResponse:
+ config = SONAR_CLOUD_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ token=token,
+ organization=organization,
+ region=region,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonar_cloud/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonar_cloud/source.py
index e2351d85588e..d7ef46a4b54d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sonar_cloud/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonar_cloud/source.py
@@ -1,30 +1,179 @@
-from typing import cast
+from typing import Optional, cast
from 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.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 SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SonarCloudSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.sonar_cloud.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ REGION_HOSTS,
+ SONAR_CLOUD_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.sonar_cloud.sonar_cloud import (
+ SonarCloudResumeConfig,
+ sonar_cloud_source,
+ validate_credentials as validate_sonar_cloud_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SonarCloudSource(SimpleSource[SonarCloudSourceConfig]):
+class SonarCloudSource(ResumableSource[SonarCloudSourceConfig, SonarCloudResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SONARCLOUD
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # Both dimensions retarget the preserved token: `region` decides which regional host it is
+ # sent to, and `organization` decides which tenant it acts on. Changing either must re-require
+ # the token so an editor can't silently redirect the stored credential to another host or org.
+ return ["region", "organization"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.SONAR_CLOUD,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Sonar Cloud",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your SonarQube Cloud user token and organization key to sync code-quality data into the PostHog Data warehouse.
+
+Generate a **user token** under **My Account → Security** in SonarQube Cloud, and find your **organization key** on your organization's homepage.
+""",
iconPath="/static/services/sonar_cloud.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/sonar-cloud",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="token",
+ label="User token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="organization",
+ label="Organization key",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="my-organization",
+ secret=False,
+ ),
+ SourceFieldSelectConfig(
+ name="region",
+ label="Region",
+ required=True,
+ defaultValue="eu",
+ options=[
+ SourceFieldSelectConfigOption(label="EU (sonarcloud.io)", value="eu"),
+ SourceFieldSelectConfigOption(label="US (sonarqube.us)", value="us"),
+ ],
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.sonar_cloud.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # Match the stable status text + region host, not the per-request path/query. A bad token or a
+ # missing scope can never be satisfied by retrying, so fail the sync fast.
+ errors: dict[str, str | None] = {}
+ for host in REGION_HOSTS.values():
+ errors[f"401 Client Error: Unauthorized for url: {host}"] = (
+ "Your SonarQube Cloud token is invalid or has been revoked. Generate a new user token and reconnect."
+ )
+ errors[f"403 Client Error: Forbidden for url: {host}"] = (
+ "Your SonarQube Cloud token is missing the permissions needed to sync this data. "
+ "Check the token's access and reconnect."
+ )
+ return errors
+
+ def get_schemas(
+ self,
+ config: SonarCloudSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ # SonarQube Cloud exposes no uniform server-side update cursor, so every stream is full refresh.
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=SONAR_CLOUD_ENDPOINTS[endpoint].should_sync_default,
+ )
+ 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: SonarCloudSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ status = validate_sonar_cloud_credentials(config.token, config.organization, config.region)
+ if status == 200:
+ return True, None
+ if status == 401:
+ return False, "Invalid SonarQube Cloud token"
+ # A 403 means the token is genuine but lacks scope for the probe endpoint. Accept it at
+ # source-create — users may only grant scopes for the tables they want — but reject it when
+ # validating a specific schema.
+ if status == 403 and schema_name is None:
+ return True, None
+ if status == 403:
+ return False, "Your SonarQube Cloud token does not have access to this resource"
+ return False, "Could not connect to SonarQube Cloud. Check your token, organization key, and region."
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SonarCloudResumeConfig]:
+ return ResumableSourceManager[SonarCloudResumeConfig](inputs, SonarCloudResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SonarCloudSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SonarCloudResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return sonar_cloud_source(
+ token=config.token,
+ organization=config.organization,
+ region=config.region,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonar_cloud/tests/test_sonar_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonar_cloud/tests/test_sonar_cloud.py
new file mode 100644
index 000000000000..f96e6a914a21
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonar_cloud/tests/test_sonar_cloud.py
@@ -0,0 +1,164 @@
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.sonar_cloud import sonar_cloud
+from products.warehouse_sources.backend.temporal.data_imports.sources.sonar_cloud.settings import MAX_PAGE_SIZE
+from products.warehouse_sources.backend.temporal.data_imports.sources.sonar_cloud.sonar_cloud import (
+ SonarCloudResumeConfig,
+ _base_url,
+ _total,
+ get_rows,
+ sonar_cloud_source,
+ validate_credentials,
+)
+
+
+class FakeResumeManager(ResumableSourceManager[SonarCloudResumeConfig]):
+ """Minimal ResumableSourceManager stand-in that records saved state without touching Redis."""
+
+ def __init__(self, state: SonarCloudResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[SonarCloudResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> SonarCloudResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: SonarCloudResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _page(rows: list[dict[str, Any]], total: int) -> dict[str, Any]:
+ return {"components": rows, "paging": {"pageIndex": 1, "pageSize": MAX_PAGE_SIZE, "total": total}}
+
+
+class TestBaseUrl:
+ @parameterized.expand(
+ [
+ ("eu", "https://sonarcloud.io/api"),
+ ("us", "https://sonarqube.us/api"),
+ ("US", "https://sonarqube.us/api"),
+ ("", "https://sonarcloud.io/api"),
+ ("unknown", "https://sonarcloud.io/api"),
+ ]
+ )
+ def test_region_host(self, region: str, expected: str) -> None:
+ assert _base_url(region) == expected
+
+
+class TestTotal:
+ @parameterized.expand(
+ [
+ ("nested_paging", {"paging": {"total": 42}}, 42),
+ ("flat_metrics_shape", {"p": 1, "ps": 100, "total": 7}, 7),
+ ("missing", {"metrics": []}, None),
+ ]
+ )
+ def test_total_extraction(self, _name: str, data: dict[str, Any], expected: int | None) -> None:
+ # metrics/search returns p/ps/total at the top level while issues/projects nest them under
+ # `paging`; a regression that only reads one shape would silently over- or under-fetch the other.
+ assert _total(data) == expected
+
+
+class TestGetRowsPagination:
+ def test_stops_on_short_page(self) -> None:
+ # A page smaller than the requested size means we've reached the end; the loop must stop rather
+ # than requesting an empty next page forever.
+ pages = [_page([{"key": "a"}, {"key": "b"}], total=2)]
+ with patch.object(sonar_cloud, "make_tracked_session", return_value=MagicMock()):
+ with patch.object(sonar_cloud, "_fetch", side_effect=pages) as fetch:
+ batches = list(get_rows("t", "org", "eu", "projects", MagicMock(), FakeResumeManager()))
+ assert [r["key"] for batch in batches for r in batch] == ["a", "b"]
+ assert fetch.call_count == 1
+
+ def test_walks_multiple_pages_until_total(self) -> None:
+ full = [{"key": str(i)} for i in range(MAX_PAGE_SIZE)]
+ pages = [
+ {"components": full, "paging": {"total": MAX_PAGE_SIZE + 1}},
+ {"components": [{"key": "last"}], "paging": {"total": MAX_PAGE_SIZE + 1}},
+ ]
+ manager = FakeResumeManager()
+ with patch.object(sonar_cloud, "make_tracked_session", return_value=MagicMock()):
+ with patch.object(sonar_cloud, "_fetch", side_effect=pages) as fetch:
+ batches = list(get_rows("t", "org", "eu", "projects", MagicMock(), manager))
+ assert fetch.call_count == 2
+ assert sum(len(b) for b in batches) == MAX_PAGE_SIZE + 1
+ # State is saved after yielding the first (full) page so a crash re-yields rather than skips.
+ assert manager.saved == [SonarCloudResumeConfig(page=2)]
+
+ def test_resumes_from_saved_page(self) -> None:
+ # Resume state points at page 2; the first request must be for page 2, not page 1.
+ pages = [{"components": [{"key": "p2"}], "paging": {"total": MAX_PAGE_SIZE + 1}}]
+ with patch.object(sonar_cloud, "make_tracked_session", return_value=MagicMock()):
+ with patch.object(sonar_cloud, "_build_url", wraps=sonar_cloud._build_url) as build:
+ with patch.object(sonar_cloud, "_fetch", side_effect=pages):
+ list(
+ get_rows(
+ "t", "org", "eu", "projects", MagicMock(), FakeResumeManager(SonarCloudResumeConfig(page=2))
+ )
+ )
+ assert build.call_args_list[0].kwargs.get("params", build.call_args_list[0].args[2])["p"] == 2
+
+ def test_result_cap_stops_and_warns(self) -> None:
+ # The v1 API hard-caps results at 10000 rows; the loop must stop at the cap even when the
+ # reported total is higher, and it should log that rows were dropped.
+ cap_pages = 10000 // MAX_PAGE_SIZE
+ full = [{"key": str(i)} for i in range(MAX_PAGE_SIZE)]
+ pages = [{"components": full, "paging": {"total": 999999}} for _ in range(cap_pages)]
+ logger = MagicMock()
+ with patch.object(sonar_cloud, "make_tracked_session", return_value=MagicMock()):
+ with patch.object(sonar_cloud, "_fetch", side_effect=pages) as fetch:
+ list(get_rows("t", "org", "eu", "projects", logger, FakeResumeManager()))
+ assert fetch.call_count == cap_pages
+ assert logger.warning.called
+
+
+class TestGetRowsNonPaginated:
+ def test_quality_gates_single_request(self) -> None:
+ data = {"qualitygates": [{"id": "1", "name": "Sonar way"}]}
+ manager = FakeResumeManager()
+ with patch.object(sonar_cloud, "make_tracked_session", return_value=MagicMock()):
+ with patch.object(sonar_cloud, "_fetch", return_value=data) as fetch:
+ batches = list(get_rows("t", "org", "eu", "quality_gates", MagicMock(), manager))
+ assert fetch.call_count == 1
+ assert batches == [[{"id": "1", "name": "Sonar way"}]]
+ assert manager.saved == []
+
+
+class TestValidateCredentials:
+ @parameterized.expand([(200, 200), (401, 401), (403, 403), (500, 500)])
+ def test_returns_status_code(self, status: int, expected: int) -> None:
+ session = MagicMock()
+ session.get.return_value = MagicMock(status_code=status)
+ with patch.object(sonar_cloud, "make_tracked_session", return_value=session):
+ assert validate_credentials("token", "org", "eu") == expected
+
+ def test_transport_failure_returns_zero(self) -> None:
+ with patch.object(sonar_cloud, "make_tracked_session", side_effect=Exception("boom")):
+ assert validate_credentials("token", "org", "eu") == 0
+
+
+class TestSourceResponse:
+ def test_partitioned_endpoint(self) -> None:
+ response = sonar_cloud_source("t", "org", "eu", "issues", MagicMock(), FakeResumeManager())
+ assert response.name == "issues"
+ assert response.primary_keys == ["key"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["creationDate"]
+
+ def test_non_partitioned_endpoint(self) -> None:
+ response = sonar_cloud_source("t", "org", "eu", "metrics", MagicMock(), FakeResumeManager())
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ def test_quality_gates_merge_on_id(self) -> None:
+ # Quality gate rows carry `id`/`name` but no `key`; merging on the default `key` primary key
+ # would never dedupe and duplicate rows on every sync.
+ response = sonar_cloud_source("t", "org", "eu", "quality_gates", MagicMock(), FakeResumeManager())
+ assert response.primary_keys == ["id"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonar_cloud/tests/test_sonar_cloud_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonar_cloud/tests/test_sonar_cloud_source.py
new file mode 100644
index 000000000000..4f89f5e66ba4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonar_cloud/tests/test_sonar_cloud_source.py
@@ -0,0 +1,119 @@
+from unittest.mock import patch
+
+import structlog
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig, SourceFieldSelectConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SonarCloudSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.sonar_cloud import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.sonar_cloud.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.sonar_cloud.sonar_cloud import (
+ SonarCloudResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.sonar_cloud.source import SonarCloudSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config() -> SonarCloudSourceConfig:
+ return SonarCloudSourceConfig(token="tok", organization="org", region="eu")
+
+
+class TestSonarCloudSourceConfig:
+ def test_source_type(self) -> None:
+ assert SonarCloudSource().source_type == ExternalDataSourceType.SONARCLOUD
+
+ def test_is_visible_not_unreleased(self) -> None:
+ # A finished source must be visible: unreleasedSource hides it from every user.
+ assert SonarCloudSource().get_source_config.unreleasedSource in (None, False)
+
+ def test_config_fields(self) -> None:
+ fields = {f.name: f for f in SonarCloudSource().get_source_config.fields}
+ assert set(fields) == {"token", "organization", "region"}
+ token_field = fields["token"]
+ assert isinstance(token_field, SourceFieldInputConfig)
+ assert token_field.secret is True
+ region_field = fields["region"]
+ assert isinstance(region_field, SourceFieldSelectConfig)
+ assert region_field.defaultValue == "eu"
+
+ def test_region_and_organization_are_connection_host_fields(self) -> None:
+ # `region` retargets where the stored token is sent and `organization` retargets which tenant
+ # it acts on; the update serializer must force re-entering the token when either changes.
+ assert SonarCloudSource().connection_host_fields == ["region", "organization"]
+
+
+class TestGetSchemas:
+ def test_lists_every_endpoint_full_refresh(self) -> None:
+ schemas = SonarCloudSource().get_schemas(_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # No endpoint has a verified server-side update cursor, so all are full refresh.
+ assert all(not s.supports_incremental and not s.supports_append for s in schemas)
+
+ def test_filters_by_name(self) -> None:
+ schemas = SonarCloudSource().get_schemas(_config(), team_id=1, names=["issues"])
+ assert [s.name for s in schemas] == ["issues"]
+
+ def test_documented_tables_render_without_credentials(self) -> None:
+ # lists_tables_without_credentials must produce the public-docs table catalog.
+ tables = SonarCloudSource().get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, None, True),
+ ("bad_token", 401, None, False),
+ ("forbidden_at_create", 403, None, True),
+ ("forbidden_for_schema", 403, "issues", False),
+ ("transport_error", 0, None, False),
+ ]
+ )
+ def test_status_mapping(self, _name: str, status: int, schema_name: str | None, expected_ok: bool) -> None:
+ with patch.object(source_module, "validate_sonar_cloud_credentials", return_value=status):
+ ok, _ = SonarCloudSource().validate_credentials(_config(), team_id=1, schema_name=schema_name)
+ assert ok is expected_ok
+
+
+class TestResumableWiring:
+ def test_resumable_manager_bound_to_config(self) -> None:
+ manager = SonarCloudSource().get_resumable_source_manager(_fake_inputs())
+ assert manager._data_class is SonarCloudResumeConfig
+
+ def test_source_for_pipeline_plumbs_arguments(self) -> None:
+ inputs = _fake_inputs(schema_name="issues")
+ source = SonarCloudSource()
+ with patch.object(source_module, "sonar_cloud_source") as sonar_source:
+ source.source_for_pipeline(_config(), source.get_resumable_source_manager(inputs), inputs)
+ _, kwargs = sonar_source.call_args
+ assert kwargs["token"] == "tok"
+ assert kwargs["organization"] == "org"
+ assert kwargs["region"] == "eu"
+ assert kwargs["endpoint"] == "issues"
+
+
+class TestNonRetryableErrors:
+ def test_covers_both_region_hosts(self) -> None:
+ errors = SonarCloudSource().get_non_retryable_errors()
+ assert "401 Client Error: Unauthorized for url: https://sonarcloud.io/api" in errors
+ assert "401 Client Error: Unauthorized for url: https://sonarqube.us/api" in errors
+ assert "403 Client Error: Forbidden for url: https://sonarcloud.io/api" in errors
+
+
+def _fake_inputs(schema_name: str = "projects") -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="s",
+ source_id="src",
+ team_id=1,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ job_id="job",
+ logger=structlog.get_logger(),
+ reset_pipeline=False,
+ )