: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 sonarqube import source (#71195)
Tom Owers0ca118622bca
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex da4803a91125..09930ce27abd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -452,6 +452,7 @@ the row lists both.| snowflake | DB protocol | snowflake-connector-python | ➖ || snowplow | HTTP | requests | ✅ || solarwinds_service_desk | HTTP | requests | ✅ |+| sonarqube | HTTP | requests | ✅ || sparkpost | HTTP | requests | ✅ || split_io | HTTP | requests | ✅ || square | HTTP | requests | ✅ |@@ -912,7 +913,6 @@ doesn't conflict with concurrent PRs.- snyk- solarwinds_service_desk- sonar_cloud-- sonarqube- sonatype_nexus- sourcegraph- spaceliftdiff --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 227c06be48b7..1c28c1da6901 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@@ -4005,7 +4005,8 @@ class SonarCloudSourceConfig(config.Config):@config.configclass SonarqubeSourceConfig(config.Config):- pass+ host: str+ token: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/canonical_descriptions.pynew file mode 100644index 000000000000..e37bc924d58a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/canonical_descriptions.py@@ -0,0 +1,82 @@+"""Canonical, documentation-sourced descriptions for SonarQube Server endpoints and columns.++Sourced from the official SonarQube Web API reference (`<your-instance>/web_api`). Keyed by the+endpoint names in `settings.py` `SONARQUBE_ENDPOINTS`, which match the `ExternalDataSchema.name` of a+synced SonarQube 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 analyzed on your SonarQube instance (components with the TRK qualifier).",+ "docs_url": "https://docs.sonarsource.com/sonarqube-server/latest/",+ "columns": {+ "key": "Unique project key.",+ "name": "Display name of the project.",+ "qualifier": "Component qualifier; TRK for projects.",+ "visibility": "Whether the project is public or private.",+ "lastAnalysisDate": "Timestamp of the most recent analysis.",+ },+ },+ "metrics": {+ "description": "Definitions of the metrics SonarQube can measure (e.g. coverage, bugs, code smells).",+ "docs_url": "https://docs.sonarsource.com/sonarqube-server/latest/user-guide/metric-definitions/",+ "columns": {+ "key": "Unique metric key (e.g. `coverage`, `bugs`).",+ "name": "Human-readable metric name.",+ "type": "Value type of the metric (INT, FLOAT, PERCENT, RATING, …).",+ "domain": "Domain the metric belongs to (Reliability, Coverage, …).",+ "description": "Explanation of what the metric measures.",+ "direction": "Whether higher (1) or lower (-1) values are better.",+ "qualitative": "Whether the metric feeds a quality rating.",+ "hidden": "Whether the metric is hidden from the UI.",+ },+ },+ "rules": {+ "description": "The catalog of coding rules used to raise issues during analysis.",+ "docs_url": "https://docs.sonarsource.com/sonarqube-server/latest/user-guide/rules/overview/",+ "columns": {+ "key": "Unique rule key (e.g. `java:S1234`).",+ "name": "Human-readable rule name.",+ "lang": "Language the rule applies to.",+ "langName": "Display name of the language.",+ "type": "Rule type: BUG, VULNERABILITY, CODE_SMELL, or SECURITY_HOTSPOT.",+ "severity": "Default severity assigned to issues raised by the rule.",+ "status": "Rule lifecycle status (READY, DEPRECATED, …).",+ },+ },+ "issues": {+ "description": "Issues raised by analysis — bugs, vulnerabilities, code smells, and security hotspots.",+ "docs_url": "https://docs.sonarsource.com/sonarqube-server/latest/user-guide/issues/",+ "columns": {+ "key": "Unique issue key.",+ "rule": "Key of the rule that raised the issue.",+ "severity": "Issue severity (BLOCKER, CRITICAL, MAJOR, MINOR, INFO).",+ "component": "Key of the file or component the issue is on.",+ "project": "Key of the project the issue belongs to.",+ "line": "Line number the issue points at.",+ "status": "Issue status (OPEN, CONFIRMED, RESOLVED, CLOSED, …).",+ "resolution": "Resolution when the issue is closed (FIXED, WONTFIX, FALSE-POSITIVE).",+ "type": "Issue type: BUG, VULNERABILITY, CODE_SMELL.",+ "message": "Description of the issue.",+ "effort": "Estimated effort to fix the issue.",+ "author": "Email of the author of the code that raised the issue.",+ "creationDate": "Time at which the issue was first detected.",+ "updateDate": "Time at which the issue was last changed.",+ },+ },+ "users": {+ "description": "Users of the SonarQube instance. Requires the Administer System permission.",+ "docs_url": "https://docs.sonarsource.com/sonarqube-server/latest/instance-administration/authentication/overview/",+ "columns": {+ "login": "Unique user login.",+ "name": "Display name of the user.",+ "email": "User's email address.",+ "active": "Whether the user account is active.",+ "local": "Whether the user is managed locally rather than via an external identity provider.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/docs/sonarqube.md b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/docs/sonarqube.mdnew file mode 100644index 000000000000..862376f9aae0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/docs/sonarqube.md@@ -0,0 +1,59 @@+---+title: Linking SonarQube as a source+sidebar: Docs+showTitle: true+availability: { free: full, selfServe: full, enterprise: full }+sourceId: Sonarqube+beta: true+---++<!--+This is the user-facing source doc. It must be moved to the posthog.com repo at+contents/docs/cdp/sources/sonarqube.md (it lives here only because this PR has no posthog.com+checkout). Once there, run `python manage.py audit_source_docs --docs-dir <posthog.com>/contents/docs/cdp/sources`.+-->++import SourceSetupIntro from "../\_snippets/source-setup-intro.mdx"+import SyncModes from "../\_snippets/sync-modes.mdx"+import TroubleshootingLink from "../\_snippets/dw-troubleshooting-link.mdx"+import AlphaRelease from "../\_snippets/alpha-release.mdx"++<AlphaRelease />++Sync code-quality data from your self-hosted [SonarQube Server](https://www.sonarsource.com/products/sonarqube/) into the PostHog data warehouse — projects, metric definitions, coding rules, issues, and users — so you can trend technical debt, reliability, and issue counts across your projects over time.++## Prerequisites++- A running SonarQube Server instance reachable from the public internet.+- A user token generated in SonarQube. The token inherits the permissions of the user who created it, so it can read the projects, issues, and rules that user can see.+- To sync the **users** table, the token's user needs the _Administer System_ permission. All other tables only need normal browse access.++## Adding a data source++<SourceSetupIntro />++You'll need:++- **Server URL** — the base URL of your SonarQube instance, e.g. `https://sonarqube.yourcompany.com`.+- **User token** — create one under **My Account → Security → Generate Tokens** in your SonarQube instance. Copy it immediately; SonarQube only shows it once.++## Sync modes++<SyncModes />++**Issues** support incremental sync: after the first run, only issues created since the last sync are fetched (using the `createdAfter` filter on the issue creation date). Because SonarQube exposes no "updated since" filter for issues, status changes on existing issues (for example, an issue being resolved) are only picked up on a full refresh. Projects, metrics, rules, and users are small reference sets that sync with a full refresh each run.++## Configuration++<SourceParameters />++## Supported tables++<SourceTables />++## Troubleshooting++- **The users table fails to sync.** `/api/users/search` requires the _Administer System_ permission. Either grant it to the token's user or leave the users table unselected — it's off by default.+- **Fewer issues than expected on a large project.** SonarQube caps issue search at 10,000 results per query window. PostHog automatically pages past this by re-windowing on the issue creation date, so all issues are synced; if you still see gaps, check that the token can browse the affected projects.++<TroubleshootingLink />diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/settings.pynew file mode 100644index 000000000000..9f659752ac0e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/settings.py@@ -0,0 +1,94 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# SonarQube caps `ps` (page size) at 500 on virtually every list endpoint.+PAGE_SIZE = 500++# /api/issues/search rejects any request where `p * ps` exceeds 10,000. To read past it we+# re-window using `createdAfter` set to the last issue's creation date and start paging again.+ISSUES_MAX_RESULTS = 10_000+++def _created_at_incremental_fields() -> list[IncrementalField]:+ # /api/issues/search only exposes a creation-time server filter (`createdAfter`), keyed on+ # each issue's `creationDate`. There is no server-side "updated since" filter, so incremental+ # syncs pick up newly created issues; status changes on old issues are only reflected on a+ # full refresh.+ return [+ {+ "label": "creationDate",+ "type": IncrementalFieldType.DateTime,+ "field": "creationDate",+ "field_type": IncrementalFieldType.DateTime,+ },+ ]+++@dataclass+class SonarqubeEndpointConfig:+ name: str+ path: str # Path under the instance base URL, e.g. "/api/issues/search"+ response_key: str # Root key of the list in the JSON response+ supports_incremental: bool = False+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable creation-time field to partition by. None when the resource has no reliable created_at.+ partition_key: Optional[str] = None+ primary_keys: list[str] = field(default_factory=lambda: ["key"])+ # Query params merged into every request for this endpoint (e.g. a required qualifier).+ extra_params: dict[str, str] = field(default_factory=dict)+ # issues/search hard-caps results at p*ps<=10000; walk past it by re-windowing on createdAfter.+ windowed_incremental: bool = False+ should_sync_default: bool = True+++SONARQUBE_ENDPOINTS: dict[str, SonarqubeEndpointConfig] = {+ # Projects the token can see. /api/components/search with qualifiers=TRK lists projects and+ # only needs the browse permission, unlike /api/projects/search which requires Administer System.+ "projects": SonarqubeEndpointConfig(+ name="projects",+ path="/api/components/search",+ response_key="components",+ extra_params={"qualifiers": "TRK"},+ ),+ # Metric definitions — a small reference set that changes rarely, so full refresh each run.+ "metrics": SonarqubeEndpointConfig(+ name="metrics",+ path="/api/metrics/search",+ response_key="metrics",+ ),+ # Coding rules catalog — reference data used to interpret issues. Full refresh.+ "rules": SonarqubeEndpointConfig(+ name="rules",+ path="/api/rules/search",+ response_key="rules",+ ),+ # Issues (code smells, bugs, vulnerabilities). The core time series. `createdAfter` filters+ # server-side on creationDate; sorting ascending by CREATION_DATE lets us both sync+ # incrementally and re-window past the 10,000-result ceiling.+ "issues": SonarqubeEndpointConfig(+ name="issues",+ path="/api/issues/search",+ response_key="issues",+ supports_incremental=True,+ incremental_fields=_created_at_incremental_fields(),+ partition_key="creationDate",+ windowed_incremental=True,+ ),+ # Users. /api/users/search requires Administer System permission, so it's off by default —+ # a token without it can still sync everything else.+ "users": SonarqubeEndpointConfig(+ name="users",+ path="/api/users/search",+ response_key="users",+ primary_keys=["login"],+ should_sync_default=False,+ ),+}++ENDPOINTS = tuple(SONARQUBE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in SONARQUBE_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/sonarqube.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/sonarqube.pynew file mode 100644index 000000000000..fdc6b32e9370--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/sonarqube.py@@ -0,0 +1,406 @@+import json+import time+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode, urlparse++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.batcher import Batcher+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.sonarqube.settings import (+ ISSUES_MAX_RESULTS,+ PAGE_SIZE,+ SONARQUBE_ENDPOINTS,+ SonarqubeEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRY_ATTEMPTS = 5++# Hard cap on a single decoded response body. A user-configured server could serve an+# arbitrarily large or highly compressed page; the read timeout only bounds idle socket+# reads, not total size. Cap the decoded bytes so a misbehaving instance can't exhaust the+# worker's memory. A legitimate `ps=500` page is well under this.+MAX_RESPONSE_BYTES = 64 * 1024 * 1024++# Wall-clock ceiling on reading a single response. The per-read timeout resets on every byte,+# so a server can drip data indefinitely and hold a shared worker; bound the whole transfer so+# a slow-drip host is cut off. Generous enough that a legitimate page never trips it.+MAX_TRANSFER_SECONDS = 300++# Pages we can request per issues window before p*ps breaches SonarQube's 10,000-result ceiling.+ISSUES_MAX_PAGES = ISSUES_MAX_RESULTS // PAGE_SIZE++# Absolute backstop on how many pages a single sync will fetch. SonarQube's list endpoints cap at+# p*ps<=10,000, and the issues sync re-windows past that, so a well-behaved server never comes near+# this. A user-controlled server can instead keep claiming more results (or advancing the issues+# window) indefinitely, looping forever and holding a shared import worker; cap the page count and+# fail non-retryably if it's ever breached. 50M rows is far beyond any real instance.+MAX_PAGES = 100_000+++class SonarqubeRetryableError(Exception):+ pass+++class SonarqubeResumeConfig:+ # Next 1-indexed page to fetch. None means "start from page 1".+ next_page: int | None = None+ # For the issues re-windowing: the `createdAfter` value of the window in progress. None for the+ # simple (non-windowed) endpoints and for an issues sync that hasn't re-windowed yet.+ created_after: str | None = None+++def normalize_base_url(host: str) -> str:+ """Reduce user input to a validated SonarQube server base URL with no trailing slash or path.++ Accepts a bare host or a full URL. Bare hosts default to https; plaintext http:// is rejected+ because the token travels as a bearer header and must stay off the wire in the clear. Rejects+ anything without a hostname so the stored token can only ever be sent to the configured instance.+ """+ cleaned = host.strip()+ if not cleaned:+ raise ValueError("SonarQube server URL is required")+ if "://" not in cleaned:+ cleaned = f"https://{cleaned}"+ parsed = urlparse(cleaned)+ if parsed.scheme != "https" or not parsed.hostname:+ raise ValueError(f"Invalid SonarQube server URL (must be https): {host}")+ # Keep scheme + netloc only; drop any path/query the user pasted so we control the API paths.+ port = f":{parsed.port}" if parsed.port else ""+ return f"https://{parsed.hostname}{port}"+++def hostname_of(host: str) -> str:+ return urlparse(normalize_base_url(host)).hostname or ""+++def _headers(token: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {token}", "Accept": "application/json"}+++def _format_created_after(value: Any) -> str:+ """Format an incremental cursor as the datetime string SonarQube's `createdAfter` accepts.++ SonarQube expects `yyyy-MM-ddTHH:mm:ss+hhmm`; a naive datetime is assumed UTC.+ """+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return aware.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S%z")+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%S%z")+ return str(value)+++def _build_url(base_url: str, path: str, params: dict[str, Any]) -> str:+ if not params:+ return f"{base_url}{path}"+ return f"{base_url}{path}?{urlencode(params)}"+++def _extract_paging(data: dict[str, Any]) -> tuple[int, int, int]:+ """Return (pageIndex, pageSize, total) from either SonarQube paging shape.++ Most endpoints wrap it in a `paging` object; /api/metrics/search returns `p`, `ps`, `total`+ at the top level instead.+ """+ paging = data.get("paging")+ if isinstance(paging, dict):+ return (+ int(paging.get("pageIndex", 1)),+ int(paging.get("pageSize", PAGE_SIZE)),+ int(paging.get("total", 0)),+ )+ return (+ int(data.get("p", 1)),+ int(data.get("ps", PAGE_SIZE)),+ int(data.get("total", 0)),+ )+++def _read_bounded(response: requests.Response) -> bytes:+ """Read a streamed response body into memory under a byte cap and a wall-clock deadline.++ `iter_content` yields content-decoded chunks, so the running total also caps decompressed+ size — a small gzip bomb can't blow past the limit. A monotonic deadline checked between+ chunks bounds the whole transfer so a server that drips data can't hold the worker+ indefinitely. Raises a non-retryable ``ValueError`` when either bound is exceeded. This mirrors+ the `_read_capped_body` convention shared by the langfuse/instana/formbricks/qualys_vmdr+ sources; the per-read idle timeout and the platform's 2-minute activity heartbeat are the+ backstops for a read blocked mid-chunk.+ """+ started = time.monotonic()+ total = 0+ chunks: list[bytes] = []+ for chunk in response.iter_content(chunk_size=1024 * 1024):+ if not chunk:+ continue+ total += len(chunk)+ if total > MAX_RESPONSE_BYTES:+ raise ValueError(+ f"SonarQube response exceeded the {MAX_RESPONSE_BYTES // (1024 * 1024)} MiB limit; "+ "check the configured server URL."+ )+ if time.monotonic() - started > MAX_TRANSFER_SECONDS:+ raise ValueError(+ f"SonarQube response exceeded the {MAX_TRANSFER_SECONDS}s transfer limit; "+ "check the configured server URL."+ )+ chunks.append(chunk)+ return b"".join(chunks)+++@retry(+ retry=retry_if_exception_type((SonarqubeRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> dict:+ # Streamed so the body is read under a byte cap rather than buffered whole by `requests`.+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS, stream=True)+ try:+ # Rate limits are governed by the customer's own instance capacity rather than a vendor quota;+ # back off and retry on 429 and transient 5xx rather than failing the sync.+ if response.status_code == 429 or response.status_code >= 500:+ raise SonarqubeRetryableError(f"SonarQube API error (retryable): status={response.status_code}, url={url}")++ # Redirects are disabled at the session level as an SSRF boundary; a 3xx means the configured+ # server is redirecting elsewhere, which we treat as a configuration error rather than follow.+ if 300 <= response.status_code < 400:+ raise ValueError(+ f"SonarQube server returned an unexpected redirect (status={response.status_code}); "+ "check the configured server URL."+ )++ body = _read_bounded(response)++ if not response.ok:+ logger.error(f"SonarQube API error: status={response.status_code}, body={body[:500]!r}, url={url}")+ response.raise_for_status()++ return json.loads(body or b"null")+ finally:+ response.close()+++def _iter_simple(+ session: requests.Session,+ base_url: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ batcher: Batcher,+ resumable_source_manager: ResumableSourceManager[SonarqubeResumeConfig],+ config: SonarqubeEndpointConfig,+) -> Iterator[Any]:+ """Page through a list endpoint with SonarQube's 1-based `p`/`ps` pagination (full refresh)."""+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.next_page if resume is not None and resume.next_page else 1+ if page > 1:+ logger.debug(f"SonarQube: resuming {config.name} from page {page}")++ pages_fetched = 0+ while True:+ if pages_fetched >= MAX_PAGES:+ # A well-behaved server drops has_more long before this; a server that keeps claiming+ # more results would loop forever and hold the worker. Fail non-retryably instead.+ raise ValueError(+ f"SonarQube {config.name} exceeded the {MAX_PAGES}-page safety cap; the server keeps "+ "reporting more results. Check the configured server URL."+ )+ params = {**config.extra_params, "p": page, "ps": PAGE_SIZE}+ data = _fetch_page(session, _build_url(base_url, config.path, params), headers, logger)+ pages_fetched += 1+ items = data.get(config.response_key, [])+ page_index, page_size, total = _extract_paging(data)+ has_more = bool(items) and page_index * page_size < total++ for item in items:+ batcher.batch(item)+ if batcher.should_yield():+ yield batcher.get_table()+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it —+ # merge dedupes on the primary key.+ if has_more:+ resumable_source_manager.save_state(SonarqubeResumeConfig(next_page=page + 1))++ if not has_more:+ break+ page += 1+++def _iter_windowed_issues(+ session: requests.Session,+ base_url: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ batcher: Batcher,+ resumable_source_manager: ResumableSourceManager[SonarqubeResumeConfig],+ config: SonarqubeEndpointConfig,+ initial_created_after: str | None,+) -> Iterator[Any]:+ """Page /api/issues/search ascending by creation date, re-windowing past the 10,000-result cap.++ Within one `createdAfter` window SonarQube only serves the first 10,000 results (p*ps<=10000).+ Once we exhaust that window we set `createdAfter` to the last issue's creationDate and start+ again. `createdAfter` is inclusive, so boundary issues re-appear across windows — merge dedupes+ them on the primary key. Sorting ascending keeps the incremental watermark advancing monotonically.+ """+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ created_after = resume.created_after if resume is not None and resume.created_after else initial_created_after+ page = resume.next_page if resume is not None and resume.next_page else 1+ if resume is not None and (resume.created_after or (resume.next_page and resume.next_page > 1)):+ logger.debug(f"SonarQube: resuming issues from createdAfter={created_after}, page={page}")++ pages_fetched = 0+ while True:+ last_creation_date: str | None = None+ window_exhausted = False++ while True:+ if pages_fetched >= MAX_PAGES:+ # Each window is bounded, but a server that keeps advancing the window with full+ # pages would spawn windows forever and hold the worker. Fail non-retryably instead.+ raise ValueError(+ f"SonarQube issues exceeded the {MAX_PAGES}-page safety cap; the server keeps "+ "advancing the window with more results. Check the configured server URL."+ )+ params: dict[str, Any] = {"s": "CREATION_DATE", "asc": "true", "p": page, "ps": PAGE_SIZE}+ if created_after:+ params["createdAfter"] = created_after+ data = _fetch_page(session, _build_url(base_url, config.path, params), headers, logger)+ pages_fetched += 1+ items = data.get(config.response_key, [])+ page_index, page_size, total = _extract_paging(data)++ for item in items:+ creation_date = item.get("creationDate")+ if creation_date:+ last_creation_date = creation_date+ batcher.batch(item)+ if batcher.should_yield():+ yield batcher.get_table()+ resumable_source_manager.save_state(+ SonarqubeResumeConfig(next_page=page, created_after=created_after)+ )++ if not items or page_index * page_size >= total:+ # Fetched every result the server will return for this window and there is no+ # further window — the whole endpoint is drained.+ return+ if page + 1 > ISSUES_MAX_PAGES:+ # The next page would breach the 10,000-result ceiling; re-window instead.+ window_exhausted = True+ break+ page += 1++ if not window_exhausted:+ return+ # A window with >10,000 results whose newest row shares createdAfter can't advance; stop+ # rather than loop forever (merge already has those rows).+ if not last_creation_date or last_creation_date == created_after:+ logger.warning(+ f"SonarQube: cannot advance issues window past createdAfter={created_after}; "+ "more than 10,000 issues share this timestamp. Stopping to avoid an infinite loop."+ )+ return+ created_after = last_creation_date+ page = 1+++def get_rows(+ host: str,+ token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SonarqubeResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[Any]:+ config = SONARQUBE_ENDPOINTS[endpoint]+ base_url = normalize_base_url(host)+ headers = _headers(token)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)+ session = make_tracked_session(redact_values=(token,), allow_redirects=False)++ if config.windowed_incremental:+ initial_created_after = (+ _format_created_after(db_incremental_field_last_value)+ if should_use_incremental_field and db_incremental_field_last_value+ else None+ )+ yield from _iter_windowed_issues(+ session, base_url, headers, logger, batcher, resumable_source_manager, config, initial_created_after+ )+ else:+ yield from _iter_simple(session, base_url, headers, logger, batcher, resumable_source_manager, config)++ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def sonarqube_source(+ host: str,+ token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SonarqubeResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = SONARQUBE_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ host=host,+ token=token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ # Issues are fetched ascending by creation date, so the watermark advances safely per batch.+ sort_mode="asc",+ 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,+ )+++def validate_credentials(host: str, token: str) -> tuple[bool, int | None]:+ """Probe /api/authentication/validate to confirm the token is genuine.++ Returns ``(ok, status_code)``. This endpoint needs no project permission, so a token that can+ only read some projects still validates at source creation. ``status_code`` is ``None`` on a+ transport error; raises ``ValueError`` if the server URL is malformed.+ """+ url = _build_url(normalize_base_url(host), "/api/authentication/validate", {})+ try:+ response = make_tracked_session(redact_values=(token,), allow_redirects=False).get(+ url, headers=_headers(token), timeout=10, stream=True+ )+ except Exception:+ return False, None+ try:+ if response.status_code != 200:+ return False, response.status_code+ try:+ payload = json.loads(_read_bounded(response) or b"null")+ return bool(payload.get("valid")), response.status_code+ except Exception:+ return False, response.status_code+ finally:+ response.close()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/source.pyindex 7676f21887ca..88c91d63275c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/source.py@@ -1,19 +1,45 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import ValidateDatabaseHostMixinfrom 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 SonarqubeSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ SONARQUBE_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube.sonarqube import (+ SonarqubeResumeConfig,+ hostname_of,+ sonarqube_source,+ validate_credentials as validate_sonarqube_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SonarqubeSource(SimpleSource[SonarqubeSourceConfig]):+class SonarqubeSource(ResumableSource[SonarqubeSourceConfig, SonarqubeResumeConfig], ValidateDatabaseHostMixin):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SONARQUBE@@ -24,7 +50,113 @@ class SonarqubeSource(SimpleSource[SonarqubeSourceConfig]):name=SchemaExternalDataSourceType.SONARQUBE,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Sonar (SonarSource) - SonarQube Server",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Connect your self-hosted SonarQube Server to pull code-quality data into the PostHog Data warehouse.++Enter your server URL (e.g. `https://sonarqube.yourcompany.com`) and a user token. Create a token under **My Account → Security → Generate Tokens** in your SonarQube instance. The token inherits your permissions, so it can read the projects, issues, and rules you can see. Syncing the **users** table additionally requires the *Administer System* permission.""",iconPath="/static/services/sonarqube.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/sonarqube",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="host",+ label="Server URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://sonarqube.yourcompany.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="token",+ label="User token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.+ # Retrying can never fix a credential/permission problem, so fail the sync. Match the+ # stable status text, not the per-request URL.+ "401 Client Error: Unauthorized": "Your SonarQube token is invalid or has expired. Generate a new token in your SonarQube account settings, then reconnect.",+ "403 Client Error: Forbidden": "Your SonarQube token is missing the permissions needed to sync this data (the users table needs the Administer System permission). Check the token's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: SonarqubeSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = SONARQUBE_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=endpoint_config.supports_incremental,+ supports_append=endpoint_config.supports_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: SonarqubeSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ host_valid, host_error = self.is_database_host_valid(hostname_of(config.host), team_id)+ except ValueError as e:+ return False, str(e)+ if not host_valid:+ return False, host_error++ ok, status_code = validate_sonarqube_credentials(config.host, config.token)+ if ok:+ return True, None+ if status_code == 401:+ return False, "Invalid SonarQube token"+ return False, "Could not connect to SonarQube with the provided server URL and token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SonarqubeResumeConfig]:+ return ResumableSourceManager[SonarqubeResumeConfig](inputs, SonarqubeResumeConfig)++ def source_for_pipeline(+ self,+ config: SonarqubeSourceConfig,+ resumable_source_manager: ResumableSourceManager[SonarqubeResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ host_valid, host_error = self.is_database_host_valid(hostname_of(config.host), inputs.team_id)+ if not host_valid:+ raise ValueError(host_error or "Invalid SonarQube host")++ return sonarqube_source(+ host=config.host,+ token=config.token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/tests/test_sonarqube.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/tests/test_sonarqube.pynew file mode 100644index 000000000000..cdedb474fff3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/tests/test_sonarqube.py@@ -0,0 +1,381 @@+import json+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube import sonarqube+from products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube.sonarqube import (+ SonarqubeResumeConfig,+ _extract_paging,+ _format_created_after,+ get_rows,+ normalize_base_url,+ validate_credentials,+)++_BASE = "https://sonar.example.com"+++class TestNormalizeBaseUrl:+ @parameterized.expand(+ [+ ("full_https", "https://sonar.example.com", "https://sonar.example.com"),+ ("bare_host_defaults_https", "sonar.example.com", "https://sonar.example.com"),+ ("trailing_slash", "https://sonar.example.com/", "https://sonar.example.com"),+ ("strips_path", "https://sonar.example.com/sonarqube/foo", "https://sonar.example.com"),+ ("keeps_port", "https://sonar.example.com:9000", "https://sonar.example.com:9000"),+ ("whitespace", " https://sonar.example.com ", "https://sonar.example.com"),+ ]+ )+ def test_valid(self, _name: str, value: str, expected: str) -> None:+ assert normalize_base_url(value) == expected++ @parameterized.expand(+ [+ ("empty", ""),+ ("whitespace_only", " "),+ ("scheme_only", "https://"),+ ("ftp", "ftp://x"),+ # Plaintext http would put the bearer token on the wire in the clear.+ ("http_rejected", "http://sonar.internal"),+ ]+ )+ def test_invalid_raises(self, _name: str, value: str) -> None:+ with pytest.raises(ValueError):+ normalize_base_url(value)+++class TestFormatCreatedAfter:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14+0000"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14+0000"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00+0000"),+ ("string_passthrough", "2026-03-04T02:58:14+0000", "2026-03-04T02:58:14+0000"),+ ]+ )+ def test_format(self, _name: str, value: Any, expected: str) -> None:+ assert _format_created_after(value) == expected+++class TestExtractPaging:+ def test_paging_object_shape(self) -> None:+ # issues/components/rules/users wrap paging in a `paging` object.+ assert _extract_paging({"paging": {"pageIndex": 2, "pageSize": 500, "total": 1200}}) == (2, 500, 1200)++ def test_top_level_shape(self) -> None:+ # /api/metrics/search returns p/ps/total at the top level instead.+ assert _extract_paging({"p": 1, "ps": 500, "total": 42}) == (1, 500, 42)+++class _FakeResumableManager:+ def __init__(self, state: SonarqubeResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[SonarqubeResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> SonarqubeResumeConfig | None:+ return self._state++ def save_state(self, data: SonarqubeResumeConfig) -> None:+ self.saved.append(data)+++class _FakeBatcher:+ """Yields one batch per item so save-after-yield behavior is observable without 2000+ rows."""++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ self._rows: list[dict] = []++ def batch(self, row: dict) -> None:+ self._rows.append(row)++ def should_yield(self, include_incomplete_chunk: bool = False) -> bool:+ return len(self._rows) > 0++ def get_table(self) -> list[dict]:+ rows = self._rows+ self._rows = []+ return rows+++def _patch_fetch(monkeypatch: Any, pages: dict[str, Any]) -> list[str]:+ fetched: list[str] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ fetched.append(url)+ return pages[url]++ monkeypatch.setattr(sonarqube, "_fetch_page", fake_fetch)+ return fetched+++def _collect(monkeypatch: Any, manager: _FakeResumableManager, **kwargs: Any) -> list[dict]:+ monkeypatch.setattr(sonarqube, "Batcher", _FakeBatcher)+ rows: list[dict] = []+ for batch in get_rows(+ host=_BASE,+ token="tok",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(batch)+ return rows+++class TestSimplePagination:+ def test_paginates_until_total_reached(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(sonarqube, "PAGE_SIZE", 2)+ pages = {+ f"{_BASE}/api/metrics/search?p=1&ps=2": {+ "metrics": [{"key": "a"}, {"key": "b"}],+ "p": 1,+ "ps": 2,+ "total": 3,+ },+ f"{_BASE}/api/metrics/search?p=2&ps=2": {"metrics": [{"key": "c"}], "p": 2, "ps": 2, "total": 3},+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="metrics")++ assert [r["key"] for r in rows] == ["a", "b", "c"]+ assert fetched == list(pages)++ def test_passes_required_qualifier_for_projects(self, monkeypatch: Any) -> None:+ url = f"{_BASE}/api/components/search?qualifiers=TRK&p=1&ps=500"+ pages = {url: {"components": [{"key": "proj"}], "paging": {"pageIndex": 1, "pageSize": 500, "total": 1}}}+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="projects")++ assert [r["key"] for r in rows] == ["proj"]+ assert fetched == [url]++ def test_saves_resume_state_only_while_more_pages_remain(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(sonarqube, "PAGE_SIZE", 1)+ pages = {+ f"{_BASE}/api/metrics/search?p=1&ps=1": {"metrics": [{"key": "a"}], "p": 1, "ps": 1, "total": 2},+ f"{_BASE}/api/metrics/search?p=2&ps=1": {"metrics": [{"key": "b"}], "p": 2, "ps": 1, "total": 2},+ }+ _patch_fetch(monkeypatch, pages)+ manager = _FakeResumableManager()+ _collect(monkeypatch, manager, endpoint="metrics")++ assert manager.saved == [SonarqubeResumeConfig(next_page=2)]++ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:+ url = f"{_BASE}/api/metrics/search?p=2&ps=500"+ pages = {url: {"metrics": [{"key": "b"}], "p": 2, "ps": 500, "total": 1000}}+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(SonarqubeResumeConfig(next_page=2)), endpoint="metrics")++ assert [r["key"] for r in rows] == ["b"]+ assert fetched == [url]++ def test_raises_at_page_cap_when_server_never_stops_paging(self, monkeypatch: Any) -> None:+ # A server that always returns a full page and claims more results would loop forever;+ # the cap turns that into a non-retryable failure after MAX_PAGES fetches.+ monkeypatch.setattr(sonarqube, "MAX_PAGES", 3)+ calls = 0++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ nonlocal calls+ calls += 1+ return {"metrics": [{"key": "x"}], "p": 1, "ps": 500, "total": 10**9}++ monkeypatch.setattr(sonarqube, "_fetch_page", fake_fetch)+ with pytest.raises(ValueError):+ _collect(monkeypatch, _FakeResumableManager(), endpoint="metrics")+ assert calls == 3+++class TestWindowedIssues:+ def test_single_window_paginates_and_stops(self, monkeypatch: Any) -> None:+ pages = {+ f"{_BASE}/api/issues/search?s=CREATION_DATE&asc=true&p=1&ps=500": {+ "issues": [{"key": "i1", "creationDate": "2024-01-01T00:00:00+0000"}],+ "paging": {"pageIndex": 1, "pageSize": 500, "total": 1},+ },+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="issues")++ assert [r["key"] for r in rows] == ["i1"]+ assert fetched == list(pages)++ def test_incremental_adds_created_after(self, monkeypatch: Any) -> None:+ url = (+ f"{_BASE}/api/issues/search?s=CREATION_DATE&asc=true&p=1&ps=500&createdAfter=2026-03-04T02%3A58%3A14%2B0000"+ )+ pages = {+ url: {+ "issues": [{"key": "i9", "creationDate": "2026-03-05T00:00:00+0000"}],+ "paging": {"pageIndex": 1, "pageSize": 500, "total": 1},+ }+ }+ fetched = _patch_fetch(monkeypatch, pages)+ _collect(+ monkeypatch,+ _FakeResumableManager(),+ endpoint="issues",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ )+ assert fetched == [url]++ def test_rewindows_past_the_result_cap(self, monkeypatch: Any) -> None:+ # Shrink the cap so re-windowing triggers after 2 pages instead of 20.+ monkeypatch.setattr(sonarqube, "ISSUES_MAX_PAGES", 2)+ boundary = "2024-01-02T00:00:00+0000"+ pages = {+ # Window 1: total stays above pageIndex*pageSize so the loop never "completes" — it hits+ # the page cap and must re-window on the last issue's creation date.+ f"{_BASE}/api/issues/search?s=CREATION_DATE&asc=true&p=1&ps=500": {+ "issues": [{"key": "i1", "creationDate": "2024-01-01T00:00:00+0000"}],+ "paging": {"pageIndex": 1, "pageSize": 500, "total": 9999},+ },+ f"{_BASE}/api/issues/search?s=CREATION_DATE&asc=true&p=2&ps=500": {+ "issues": [{"key": "i2", "creationDate": boundary}],+ "paging": {"pageIndex": 2, "pageSize": 500, "total": 9999},+ },+ # Window 2: createdAfter = last issue's creationDate; small total so it finishes.+ f"{_BASE}/api/issues/search?s=CREATION_DATE&asc=true&p=1&ps=500&createdAfter=2024-01-02T00%3A00%3A00%2B0000": {+ "issues": [+ {"key": "i2", "creationDate": boundary},+ {"key": "i3", "creationDate": "2024-01-03T00:00:00+0000"},+ ],+ "paging": {"pageIndex": 1, "pageSize": 500, "total": 2},+ },+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="issues")++ # i2 re-appears across the window boundary (createdAfter is inclusive); merge dedupes on `key`.+ assert [r["key"] for r in rows] == ["i1", "i2", "i2", "i3"]+ assert fetched == list(pages)++ def test_stops_when_window_cannot_advance(self, monkeypatch: Any) -> None:+ # >cap issues sharing one creationDate can't advance the window; stop instead of looping forever.+ monkeypatch.setattr(sonarqube, "ISSUES_MAX_PAGES", 1)+ same_date = "2024-01-01T00:00:00+0000"+ pages = {+ f"{_BASE}/api/issues/search?s=CREATION_DATE&asc=true&p=1&ps=500&createdAfter=2024-01-01T00%3A00%3A00%2B0000": {+ "issues": [{"key": "i1", "creationDate": same_date}],+ "paging": {"pageIndex": 1, "pageSize": 500, "total": 9999},+ },+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(+ monkeypatch,+ _FakeResumableManager(),+ endpoint="issues",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),+ )++ assert [r["key"] for r in rows] == ["i1"]+ # Only the first page is fetched — no infinite re-windowing on the same timestamp.+ assert fetched == list(pages)++ def test_raises_at_page_cap_when_server_never_stops_advancing_windows(self, monkeypatch: Any) -> None:+ # Each window is bounded, but a server that keeps advancing createdAfter with full windows+ # would spawn windows forever; the cap turns that into a non-retryable failure.+ monkeypatch.setattr(sonarqube, "MAX_PAGES", 3)+ monkeypatch.setattr(sonarqube, "ISSUES_MAX_PAGES", 1) # re-window after every page+ calls = 0++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ nonlocal calls+ calls += 1+ return {+ "issues": [{"key": f"i{calls}", "creationDate": f"2024-01-{calls:02d}T00:00:00+0000"}],+ "paging": {"pageIndex": 1, "pageSize": 500, "total": 9999},+ }++ monkeypatch.setattr(sonarqube, "_fetch_page", fake_fetch)+ with pytest.raises(ValueError):+ _collect(monkeypatch, _FakeResumableManager(), endpoint="issues")+ assert calls == 3+++class _FakeResponse:+ def __init__(self, status_code: int, payload: Any = None) -> None:+ self.status_code = status_code+ self._payload = payload+ self.closed = False++ def iter_content(self, chunk_size: int = 1) -> Any:+ if self._payload is None:+ return+ yield json.dumps(self._payload).encode()++ def close(self) -> None:+ self.closed = True+++class _FakeStream:+ """Yields caller-supplied byte chunks so `_read_bounded`'s cap can be exercised directly."""++ def __init__(self, chunks: list[bytes]) -> None:+ self._chunks = chunks++ def iter_content(self, chunk_size: int = 1) -> Any:+ yield from self._chunks+++class TestReadBounded:+ @pytest.mark.parametrize(+ "cap, chunks, expected",+ [+ (16, [b"aaaa", b"bbbb"], b"aaaabbbb"),+ (8, [b"aaaa", b"bbbb"], b"aaaabbbb"), # exactly at the cap is allowed+ (0, [], b""),+ ],+ )+ def test_reads_body_within_cap(self, cap, chunks, expected, monkeypatch) -> None:+ monkeypatch.setattr(sonarqube, "MAX_RESPONSE_BYTES", cap)+ assert sonarqube._read_bounded(_FakeStream(chunks)) == expected # type: ignore[arg-type]++ def test_raises_when_body_exceeds_cap(self, monkeypatch) -> None:+ monkeypatch.setattr(sonarqube, "MAX_RESPONSE_BYTES", 4)+ with pytest.raises(ValueError):+ sonarqube._read_bounded(_FakeStream([b"aaaa", b"b"])) # type: ignore[arg-type]++ def test_raises_when_transfer_exceeds_deadline(self, monkeypatch) -> None:+ # Fake monotonic clock: deadline is set on the first read, jumps past it before the second chunk.+ ticks = iter([0.0, 1.0, 999.0])+ monkeypatch.setattr(sonarqube.time, "monotonic", lambda: next(ticks))+ monkeypatch.setattr(sonarqube, "MAX_TRANSFER_SECONDS", 10)+ with pytest.raises(ValueError):+ sonarqube._read_bounded(_FakeStream([b"aaaa", b"bbbb"])) # type: ignore[arg-type]+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status, payload, expected_ok, expected_code",+ [+ (200, {"valid": True}, True, 200),+ (200, {"valid": False}, False, 200),+ (401, None, False, 401),+ (503, None, False, 503),+ ],+ )+ def test_status_mapping(self, status, payload, expected_ok, expected_code, monkeypatch) -> None:+ session = MagicMock()+ session.get.return_value = _FakeResponse(status, payload)+ monkeypatch.setattr(sonarqube, "make_tracked_session", lambda **kwargs: session)++ assert validate_credentials(_BASE, "tok") == (expected_ok, expected_code)++ def test_transport_error_returns_none_status(self, monkeypatch) -> None:+ session = MagicMock()+ session.get.side_effect = ConnectionError("boom")+ monkeypatch.setattr(sonarqube, "make_tracked_session", lambda **kwargs: session)++ assert validate_credentials(_BASE, "tok") == (False, None)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/tests/test_sonarqube_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/tests/test_sonarqube_source.pynew file mode 100644index 000000000000..43f8c6d8ac1d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sonarqube/tests/test_sonarqube_source.py@@ -0,0 +1,170 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SonarqubeSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube.settings import (+ ENDPOINTS,+ SONARQUBE_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube.sonarqube import SonarqubeResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube.source import SonarqubeSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++_INCREMENTAL_ENDPOINTS = {"issues"}+_FULL_REFRESH_ENDPOINTS = {"projects", "metrics", "rules", "users"}+++class TestSonarqubeSource:+ def setup_method(self):+ self.source = SonarqubeSource()+ self.team_id = 123+ self.config = SonarqubeSourceConfig(host="https://sonar.example.com", token="tok")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.SONARQUBE++ def test_get_source_config_is_released_alpha(self):+ # A finished source must be visible (no unreleasedSource) and soft-labeled ALPHA.+ config = self.source.get_source_config++ assert config.name.value == "Sonarqube"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/sonarqube.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/sonarqube"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["host", "token"]++ def test_token_field_is_secret_password(self):+ config = self.source.get_source_config+ token_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "token")+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://sonar.example.com/api/issues/search?p=1&ps=500",+ "403 Client Error: Forbidden for url: https://sonar.example.com/api/users/search?p=1&ps=500",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "429 Client Error: Too Many Requests for url: https://sonar.example.com/api/issues/search",+ "500 Server Error: Internal Server Error for url: https://sonar.example.com/api/issues/search",+ "HTTPSConnectionPool(host='sonar.example.com', port=443): Read timed out.",+ ],+ )+ def test_non_retryable_errors_do_not_match_transient(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_match_endpoints_with_correct_sync_modes(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ for name in _INCREMENTAL_ENDPOINTS:+ assert schemas[name].supports_incremental is True+ assert schemas[name].supports_append is True+ assert [f["field"] for f in schemas[name].incremental_fields] == ["creationDate"]+ for name in _FULL_REFRESH_ENDPOINTS:+ assert schemas[name].supports_incremental is False+ assert schemas[name].supports_append is False+ assert schemas[name].incremental_fields == []++ def test_users_table_is_off_by_default(self):+ # /api/users/search needs Administer System; a token without it must still sync everything else.+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}+ assert schemas["users"].should_sync_default is False+ assert schemas["issues"].should_sync_default is True++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["issues"])+ assert len(schemas) == 1+ assert schemas[0].name == "issues"++ def test_lists_tables_without_credentials_publishes_catalog(self):+ assert self.source.lists_tables_without_credentials is True+ documented = self.source.get_documented_tables()+ assert {table["name"] for table in documented} == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self):+ canonical = self.source.get_canonical_descriptions()+ assert set(canonical) == set(SONARQUBE_ENDPOINTS)++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ ((True, 200), True, None),+ ((False, 401), False, "Invalid SonarQube token"),+ ((False, 403), False, "Could not connect to SonarQube with the provided server URL and token"),+ ((False, None), False, "Could not connect to SonarQube with the provided server URL and token"),+ ],+ )+ @mock.patch.object(SonarqubeSource, "is_database_host_valid", return_value=(True, None))+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube.source.validate_sonarqube_credentials"+ )+ def test_validate_credentials(self, mock_validate, _mock_host, 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("https://sonar.example.com", "tok")++ @mock.patch.object(SonarqubeSource, "is_database_host_valid", return_value=(False, "Blocked internal host"))+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube.source.validate_sonarqube_credentials"+ )+ def test_validate_credentials_rejects_unsafe_host_without_probing(self, mock_validate, _mock_host):+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is False+ assert error_message == "Blocked internal host"+ mock_validate.assert_not_called()++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert manager._data_class is SonarqubeResumeConfig++ @mock.patch.object(SonarqubeSource, "is_database_host_valid", return_value=(True, None))+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube.source.sonarqube_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_sonarqube_source, _mock_host):+ inputs = mock.MagicMock()+ inputs.schema_name = "issues"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00+0000"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_sonarqube_source.assert_called_once()+ kwargs = mock_sonarqube_source.call_args.kwargs+ assert kwargs["host"] == "https://sonar.example.com"+ assert kwargs["token"] == "tok"+ assert kwargs["endpoint"] == "issues"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00+0000"++ @mock.patch.object(SonarqubeSource, "is_database_host_valid", return_value=(True, None))+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.sonarqube.source.sonarqube_source")+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_sonarqube_source, _mock_host):+ inputs = mock.MagicMock()+ inputs.schema_name = "projects"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00+0000"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_sonarqube_source.call_args.kwargs["db_incremental_field_last_value"] is None