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 coveralls import source (#71169)

Tom Owers991b1ff6a1a9
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 7b1dffc3f4bc..cba0e57b4ee1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -137,6 +137,7 @@ the row lists both.
| convex | HTTP | requests | ✅ |
| copper | HTTP | requests | ✅ |
| coupa | HTTP | requests | ✅ |
+| coveralls | HTTP | requests | ✅ |
| crates_io | HTTP | requests | ✅ |
| crunchbase | HTTP | requests | ✅ |
| culture_amp | HTTP | requests | ✅ |
@@ -602,7 +603,6 @@ doesn't conflict with concurrent PRs.
- coralogix
- cosmosdb
- couchbase
-- coveralls
- criteo
- cronitor
- curve
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coveralls/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coveralls/canonical_descriptions.py
new file mode 100644
index 000000000000..06051930d641
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coveralls/canonical_descriptions.py
@@ -0,0 +1,48 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "builds": {
+ "description": "One row per CI build reported to Coveralls across every configured repository, "
+ "with its coverage totals and commit metadata.",
+ "docs_url": "https://docs.coveralls.io/api-introduction",
+ "columns": {
+ "id": "Unique identifier of the build on Coveralls.",
+ "repo_name": "Repository the build belongs to, in owner/repo form.",
+ "branch": "Git branch the build ran against.",
+ "url": "URL associated with the build, when set.",
+ "badge_url": "URL of the coverage badge image generated for this build.",
+ "commit_sha": "SHA of the commit the coverage report was generated for.",
+ "commit_message": "Message of the commit the coverage report was generated for.",
+ "committer_name": "Name of the commit author.",
+ "committer_email": "Email of the commit author.",
+ "created_at": "When the build was created on Coveralls.",
+ "updated_at": "When the build was last updated on Coveralls (e.g. after a recalculation).",
+ "calculated_at": "When Coveralls last calculated the build's coverage.",
+ "covered_percent": "Percentage of relevant lines covered by tests in this build.",
+ "coverage_change": "Change in covered_percent compared to the previous build.",
+ "covered_lines": "Number of relevant lines executed by tests.",
+ "missed_lines": "Number of relevant lines not executed by tests.",
+ "relevant_lines": "Total number of lines considered relevant for coverage.",
+ "covered_branches": "Number of relevant branches executed by tests.",
+ "missed_branches": "Number of relevant branches not executed by tests.",
+ "relevant_branches": "Total number of branches considered relevant for coverage.",
+ },
+ },
+ "repositories": {
+ "description": "Repository-level Coveralls configuration for each configured repository, from "
+ "the /api/v1/repos endpoint (requires a personal API token).",
+ "docs_url": "https://docs.coveralls.io/api-repos-endpoint",
+ "columns": {
+ "service": "Git hosting service the repository lives on (github, gitlab, or bitbucket).",
+ "name": "Repository name in owner/repo form.",
+ "comment_on_pull_requests": "Whether Coveralls comments coverage results on pull requests.",
+ "send_build_status": "Whether Coveralls sends commit status checks to the git service.",
+ "commit_status_fail_threshold": "Minimum coverage percentage below which the commit status fails.",
+ "commit_status_fail_change_threshold": "Maximum allowed coverage drop before the commit status fails.",
+ "created_at": "When the repository was added to Coveralls.",
+ "updated_at": "When the repository's Coveralls configuration was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coveralls/coveralls.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coveralls/coveralls.py
new file mode 100644
index 000000000000..1f14a7ce8458
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coveralls/coveralls.py
@@ -0,0 +1,403 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import quote
+
+import requests
+from dateutil import parser as dateutil_parser
+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.coveralls.settings import (
+ COVERALLS_ENDPOINTS,
+ CoverallsEndpointConfig,
+)
+
+COVERALLS_BASE_URL = "https://coveralls.io"
+
+REQUEST_TIMEOUT_SECONDS = 30
+MAX_RETRY_ATTEMPTS = 5
+
+# Each configured repository costs one request per ~10 builds on every full sync, so cap the config
+# to bound worker time and outbound fan-out.
+MAX_REPOSITORIES = 100
+
+# Backstop against a pathological `pages` value or a feed that never converges; 10k pages is 100k
+# builds for a single repository, far beyond any real coverage history we expect to sync.
+MAX_PAGES_PER_REPOSITORY = 10_000
+
+
+class CoverallsRetryableError(Exception):
+ pass
+
+
+class CoverallsResumeConfig:
+ # The repository ("owner/repo") currently being walked. A stable name bookmark (not a positional
+ # index) so repositories added/removed between a crash and the retry can't resume us into the
+ # wrong repository. None means "start from the first configured repository".
+ repository: str | None = None
+ # Next page of the builds feed to fetch for that repository. None means page 1.
+ page: int | None = None
+
+
+def parse_repositories(raw: str | None) -> list[str]:
+ """Parse the user's free-text ``repositories`` field into a list of ``owner/repo`` names.
+
+ Accepts one repository per line and/or comma-separated names. Raises ``ValueError`` with an
+ actionable message on bad input so the user fixes the config rather than getting a silently
+ empty sync. Names are de-duplicated case-insensitively while preserving order.
+ """
+ if not raw:
+ raise ValueError("At least one repository is required, in owner/repo form.")
+
+ repositories: list[str] = []
+ seen: set[str] = set()
+ for token in re.split(r"[\n,]", raw):
+ name = token.strip().strip("/")
+ if not name:
+ continue
+ if "/" not in name:
+ raise ValueError(
+ f"Repository '{name}' is invalid: use the owner/repo form, e.g. lemurheavy/coveralls-ruby."
+ )
+ normalized = name.lower()
+ if normalized not in seen:
+ seen.add(normalized)
+ repositories.append(name)
+
+ if len(repositories) > MAX_REPOSITORIES:
+ raise ValueError(f"Too many repositories: at most {MAX_REPOSITORIES} are allowed per source.")
+
+ if not repositories:
+ raise ValueError("At least one repository is required, in owner/repo form.")
+
+ return repositories
+
+
+def _builds_url(service: str, repository: str, page: int) -> str:
+ # Percent-encode each path segment (keeping the owner/repo separator) so an odd character
+ # can't break out of the path.
+ return f"{COVERALLS_BASE_URL}/{quote(service, safe='')}/{quote(repository, safe='/')}.json?page={page}"
+
+
+def _repo_config_url(service: str, repository: str) -> str:
+ return f"{COVERALLS_BASE_URL}/api/v1/repos/{quote(service, safe='')}/{quote(repository, safe='/')}"
+
+
+def _token_headers(api_token: str | None) -> dict[str, str]:
+ headers = {"Accept": "application/json"}
+ if api_token:
+ headers["Authorization"] = f"token {api_token}"
+ return headers
+
+
+@retry(
+ retry=retry_if_exception_type((CoverallsRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_json(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any] | None:
+ """Fetch a JSON document, returning ``None`` for a 404.
+
+ Coveralls 404s both for repositories it doesn't track and (on the web ``.json`` feed) for
+ private repositories the caller can't see, so a 404 is skipped per-repository rather than
+ failing the whole sync. Transient 429/5xx raise a retryable error; other client errors raise
+ ``requests.HTTPError``.
+ """
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 404:
+ logger.warning(f"Coveralls: {url} returned 404, skipping")
+ return None
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise CoverallsRetryableError(f"Coveralls API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Coveralls API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _as_utc(value: datetime) -> datetime:
+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+
+
+def _incremental_cutoff(db_incremental_field_last_value: Any, lookback: timedelta | None) -> datetime | None:
+ """Resolve the watermark into a UTC cutoff for the desc walk, minus the safety lookback."""
+ value = db_incremental_field_last_value
+ if isinstance(value, str):
+ try:
+ value = dateutil_parser.parse(value)
+ except (ValueError, TypeError):
+ return None
+ if not isinstance(value, datetime):
+ return None
+ cutoff = _as_utc(value)
+ return cutoff - lookback if lookback else cutoff
+
+
+def _is_older_than_cutoff(value: Any, cutoff: datetime) -> bool:
+ if isinstance(value, str):
+ try:
+ value = dateutil_parser.parse(value)
+ except (ValueError, TypeError):
+ return False
+ if not isinstance(value, datetime):
+ return False
+ return _as_utc(value) <= cutoff
+
+
+def get_builds_rows(
+ service: str,
+ repositories: list[str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CoverallsResumeConfig],
+ cutoff: datetime | None,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk each repository's paginated builds feed, newest-first.
+
+ The feed has no server-side time filter, so incremental syncs stop paging a repository the
+ moment a build at or before the ``cutoff`` watermark appears — the feed is strictly
+ newest-first, so everything after it is older. Each page is yielded before the resume state
+ advances, so a crash re-yields the last page rather than skipping it (merge dedupes on the
+ primary key).
+ """
+ session = make_tracked_session()
+ headers = {"Accept": "application/json"}
+
+ # Resolve the saved repository bookmark to the slice still to process. If the bookmarked
+ # repository is no longer configured, start over from the first one — merge dedupes the
+ # re-pulled rows on the primary key.
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ remaining = repositories
+ resume_page: int | None = None
+ if resume is not None and resume.repository is not None and resume.repository in repositories:
+ remaining = repositories[repositories.index(resume.repository) :]
+ resume_page = resume.page
+ logger.debug(f"Coveralls: resuming builds from repository={resume.repository}, page={resume_page}")
+
+ for index, repository in enumerate(remaining):
+ page = resume_page or 1
+ resume_page = None # only the resumed-into repository uses the saved page; the rest start at 1
+
+ while page <= MAX_PAGES_PER_REPOSITORY:
+ data = _fetch_json(session, _builds_url(service, repository, page), headers, logger)
+ if data is None:
+ break
+
+ builds = data.get("builds") or []
+ if not builds:
+ break
+
+ rows: list[dict[str, Any]] = []
+ for build in builds:
+ if not isinstance(build, dict):
+ continue
+ # `repo_name` completes the primary key; the feed already includes it, but fall
+ # back to the configured name in case it's ever omitted.
+ build.setdefault("repo_name", repository)
+ rows.append(build)
+ yield rows
+
+ total_pages = data.get("pages") or 0
+ has_next = page < total_pages
+ # Strictly newest-first (verified against the live feed): the first build at or before
+ # the watermark means every remaining page is older, so stop walking this repository.
+ if cutoff is not None and any(_is_older_than_cutoff(build.get("created_at"), cutoff) for build in rows):
+ break
+ if not has_next:
+ break
+
+ page += 1
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it.
+ resumable_source_manager.save_state(CoverallsResumeConfig(repository=repository, page=page))
+ else:
+ logger.warning(
+ f"Coveralls: hit the {MAX_PAGES_PER_REPOSITORY}-page cap for repository={repository}, "
+ "older builds were not synced"
+ )
+
+ # Advance the bookmark to the next repository so a crash between repositories resumes there.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(CoverallsResumeConfig(repository=remaining[index + 1], page=1))
+
+
+# Documented configuration fields of the /api/v1/repos response. Rows are built from this
+# allowlist rather than passed through: the response also carries the secret repo token used to
+# submit coverage jobs, and a pass-through would persist that credential as queryable warehouse
+# data. Fail-closed — any undocumented field is dropped.
+_REPOSITORY_FIELDS = (
+ "id",
+ "service",
+ "name",
+ "comment_on_pull_requests",
+ "send_build_status",
+ "commit_status_fail_threshold",
+ "commit_status_fail_change_threshold",
+ "created_at",
+ "updated_at",
+)
+
+
+def get_repository_rows(
+ service: str,
+ repositories: list[str],
+ api_token: str | None,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """One row per configured repository from the ``/api/v1/repos`` endpoint.
+
+ The endpoint needs a personal API token. Rows carry only the allowlisted configuration
+ fields (never the repo's secret coverage-upload token), stamped with the ``service`` and
+ ``name`` the primary key needs in case the API omits them.
+ """
+ if not api_token:
+ raise ValueError(
+ "A personal API token is required to sync the repositories table. "
+ "Add one from your Coveralls account settings, or disable this table."
+ )
+
+ # The /api/v1/repos response carries the repo's secret coverage-upload token, which the
+ # name-based sample scrubbers don't recognise — disable capture so it can't land in stored
+ # HTTP samples (requests stay metered and logged).
+ session = make_tracked_session(capture=False)
+ headers = _token_headers(api_token)
+
+ for repository in repositories:
+ data = _fetch_json(session, _repo_config_url(service, repository), headers, logger)
+ if data is None:
+ # Coveralls also answers 404 (not 401) for insufficient access, so name both causes.
+ logger.warning(
+ f"Coveralls: repository {repository!r} not found via /api/v1/repos — it may not be "
+ "tracked on Coveralls or the API token may lack access; skipping"
+ )
+ continue
+ row = {key: data[key] for key in _REPOSITORY_FIELDS if key in data}
+ row.setdefault("service", service)
+ row.setdefault("name", repository)
+ yield [row]
+
+
+def validate_credentials(
+ service: str,
+ repositories_raw: str | None,
+ api_token: str | None,
+ schema_name: str | None = None,
+) -> tuple[bool, str | None]:
+ """Confirm the config is usable by probing the first configured repository's builds feed.
+
+ The builds feed is public, so there is no key to check for it; a 404 means the repository
+ isn't tracked on Coveralls (or is private, which the feed doesn't expose without a browser
+ session). Only when validating the ``repositories`` schema specifically is the API token
+ probed, so a missing token never blocks source creation.
+ """
+ try:
+ repositories = parse_repositories(repositories_raw)
+ except ValueError as exc:
+ return False, str(exc)
+
+ repository = repositories[0]
+ session = make_tracked_session()
+
+ try:
+ response = session.get(
+ _builds_url(service, repository, 1), headers={"Accept": "application/json"}, timeout=REQUEST_TIMEOUT_SECONDS
+ )
+ except Exception:
+ return False, "Could not reach the Coveralls API. Please try again."
+
+ if response.status_code == 404:
+ return False, (
+ f"Repository '{repository}' was not found on Coveralls for service '{service}'. "
+ "Check the owner/repo spelling, and note that private repositories are not supported."
+ )
+ if response.status_code != 200:
+ return False, f"Coveralls API returned an unexpected status code: {response.status_code}"
+
+ if schema_name == "repositories":
+ if not api_token:
+ return False, "The repositories table requires a personal API token."
+ # The /api/v1/repos response carries the repo's secret coverage-upload token — probe it on a
+ # capture-disabled session so it can't land in stored HTTP samples.
+ token_session = make_tracked_session(capture=False)
+ try:
+ token_response = token_session.get(
+ _repo_config_url(service, repository),
+ headers=_token_headers(api_token),
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ except Exception:
+ return False, "Could not reach the Coveralls API. Please try again."
+ if token_response.status_code in (401, 403):
+ return False, "Your Coveralls personal API token is invalid or expired."
+ # Coveralls answers 404 (not 401) for unauthorized /api/v1/repos requests too, so a 404
+ # here can mean either an untracked repository or a bad token.
+ if token_response.status_code == 404:
+ return False, (
+ f"Coveralls could not find '{repository}' via the repos API — the repository may not "
+ "be tracked on Coveralls, or the personal API token may be invalid."
+ )
+ if token_response.status_code != 200:
+ return False, f"Coveralls API returned an unexpected status code: {token_response.status_code}"
+
+ return True, None
+
+
+def coveralls_source(
+ endpoint: str,
+ service: str,
+ repositories_raw: str | None,
+ api_token: str | None,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CoverallsResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config: CoverallsEndpointConfig = COVERALLS_ENDPOINTS[endpoint]
+ repositories = parse_repositories(repositories_raw)
+
+ cutoff = (
+ _incremental_cutoff(db_incremental_field_last_value, config.incremental_lookback)
+ if should_use_incremental_field
+ else None
+ )
+
+ def items() -> Iterator[list[dict[str, Any]]]:
+ if endpoint == "repositories":
+ return get_repository_rows(service, repositories, api_token, logger)
+ return get_builds_rows(service, repositories, logger, resumable_source_manager, cutoff)
+
+ partition_kwargs: dict[str, Any] = {}
+ if config.partition_key is not None:
+ partition_kwargs = {
+ "partition_count": 1,
+ "partition_size": 1,
+ "partition_mode": "datetime",
+ "partition_format": "month",
+ "partition_keys": [config.partition_key],
+ }
+
+ return SourceResponse(
+ name=endpoint,
+ items=items,
+ primary_keys=config.primary_keys,
+ # The builds feed is strictly newest-first with no way to ask for ascending order, so the
+ # incremental watermark persists only at successful job end. The repositories stream has no
+ # meaningful order, and desc is the safe declaration for it too (no per-batch checkpointing).
+ sort_mode="desc",
+ **partition_kwargs,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coveralls/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coveralls/settings.py
new file mode 100644
index 000000000000..370e39789946
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coveralls/settings.py
@@ -0,0 +1,64 @@
+from dataclasses import dataclass, field
+from datetime import timedelta
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# A build's creation time never changes, so it's a stable incremental cursor and partition key.
+_CREATED_AT_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+
+@dataclass
+class CoverallsEndpointConfig:
+ name: str
+ primary_keys: list[str]
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable datetime column used for partitioning, or `None` for streams without one.
+ partition_key: Optional[str] = None
+ # Requires the optional personal API token (the public builds feed does not).
+ requires_api_token: bool = False
+ should_sync_default: bool = True
+ description: Optional[str] = None
+ # Safety overlap subtracted from the incremental watermark before the desc walk stops, re-pulling
+ # a window of builds that merge dedupes on the primary key. Covers builds that land in an
+ # already-fetched repository while a multi-repository sync is still running (the persisted
+ # watermark is the max across every repository in the run).
+ incremental_lookback: Optional[timedelta] = None
+
+
+COVERALLS_ENDPOINTS: dict[str, CoverallsEndpointConfig] = {
+ "builds": CoverallsEndpointConfig(
+ name="builds",
+ # Build ids look globally unique (one sequence across coveralls.io), but that isn't
+ # documented — the repository name makes the key robust either way.
+ primary_keys=["repo_name", "id"],
+ incremental_fields=list(_CREATED_AT_INCREMENTAL_FIELDS),
+ partition_key="created_at",
+ incremental_lookback=timedelta(hours=24),
+ description="Coverage builds: one row per CI build across every configured repository, "
+ "with covered/missed/relevant line and branch counts, coverage change, and commit metadata.",
+ ),
+ "repositories": CoverallsEndpointConfig(
+ name="repositories",
+ primary_keys=["service", "name"],
+ requires_api_token=True,
+ # Requires the optional personal API token, which source creation doesn't validate — the
+ # schema picker leaves it off so an untokened source doesn't fail on its first sync.
+ should_sync_default=False,
+ description="Repository configuration: one row per configured repository from the "
+ "`/api/v1/repos` endpoint. Requires a personal API token.",
+ ),
+}
+
+ENDPOINTS = tuple(COVERALLS_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in COVERALLS_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coveralls/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coveralls/source.py
index 9b29b69106a3..75e6e81a9979 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coveralls/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coveralls/source.py
@@ -1,30 +1,190 @@
-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.coveralls.coveralls import (
+ CoverallsResumeConfig,
+ coveralls_source,
+ validate_credentials as validate_coveralls_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.coveralls.settings import (
+ COVERALLS_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CoverallsSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class CoverallsSource(SimpleSource[CoverallsSourceConfig]):
+class CoverallsSource(ResumableSource[CoverallsSourceConfig, CoverallsResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.COVERALLS
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `service` and `repositories` decide which repos the stored `api_token` is sent to query,
+ # so retargeting either must re-require the token — otherwise an editor without the token
+ # could reuse the preserved one to pull data from repositories it grants access to.
+ return ["service", "repositories"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.COVERALLS,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
- label="Coveralls (Coveralls.io)",
+ label="Coveralls",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["code coverage", "coverage", "coveralls.io"],
+ caption="""Pull per-build code coverage history from [Coveralls](https://coveralls.io) into the PostHog Data warehouse to track coverage trends and catch regressions across repositories.
+
+Enter the repositories you want to track, one per line (or comma-separated), in `owner/repo` form. For example:
+
+```
+lemurheavy/coveralls-ruby
+posthog/posthog
+```
+
+The builds feed is public, so no credentials are needed for public repositories (private repositories are not supported). The optional `repositories` table uses Coveralls' repos API and needs a [personal API token](https://coveralls.io/account) from your Coveralls account settings.""",
iconPath="/static/services/coveralls.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/coveralls",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="service",
+ label="Git service",
+ required=True,
+ defaultValue="github",
+ options=[
+ SourceFieldSelectConfigOption(label="GitHub", value="github"),
+ SourceFieldSelectConfigOption(label="GitLab", value="gitlab"),
+ SourceFieldSelectConfigOption(label="Bitbucket", value="bitbucket"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="repositories",
+ label="Repositories",
+ type=SourceFieldInputConfigType.TEXTAREA,
+ required=True,
+ placeholder="lemurheavy/coveralls-ruby\nposthog/posthog",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_token",
+ label="Personal API token (optional)",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.coveralls.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://coveralls.io": "Your Coveralls personal API token is invalid or expired. Create a new token in your Coveralls account settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://coveralls.io": "Your Coveralls personal API token does not have access to this repository. Check the token and repository access, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: CoverallsSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ # The builds feed has no server-side time filter, but it's strictly newest-first, so
+ # an incremental sync walks pages only until it reaches the last-seen `created_at`
+ # watermark — API cost stays proportional to new builds, not full history.
+ supports_incremental=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,
+ # Incremental runs re-pull a safety window past the watermark; only merge dedupes
+ # those on the primary key, append would materialize them as duplicates.
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=COVERALLS_ENDPOINTS[endpoint].should_sync_default,
+ description=COVERALLS_ENDPOINTS[endpoint].description,
+ )
+ 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: CoverallsSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_coveralls_credentials(
+ service=config.service,
+ repositories_raw=config.repositories,
+ api_token=config.api_token,
+ schema_name=schema_name,
+ )
+
+ def get_endpoint_permissions(
+ self, config: CoverallsSourceConfig, team_id: int, endpoints: list[str]
+ ) -> dict[str, str | None]:
+ permissions: dict[str, str | None] = dict.fromkeys(endpoints)
+ for endpoint in endpoints:
+ if COVERALLS_ENDPOINTS.get(endpoint) and COVERALLS_ENDPOINTS[endpoint].requires_api_token:
+ if not config.api_token:
+ permissions[endpoint] = "Requires a personal API token from your Coveralls account settings."
+ return permissions
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CoverallsResumeConfig]:
+ return ResumableSourceManager[CoverallsResumeConfig](inputs, CoverallsResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: CoverallsSourceConfig,
+ resumable_source_manager: ResumableSourceManager[CoverallsResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return coveralls_source(
+ endpoint=inputs.schema_name,
+ service=config.service,
+ repositories_raw=config.repositories,
+ api_token=config.api_token,
+ 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/coveralls/tests/test_coveralls.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coveralls/tests/test_coveralls.py
new file mode 100644
index 000000000000..8aa9aceb182a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coveralls/tests/test_coveralls.py
@@ -0,0 +1,456 @@
+import json
+from datetime import UTC, datetime
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+import requests
+import structlog
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.coveralls.coveralls import (
+ COVERALLS_BASE_URL,
+ MAX_REPOSITORIES,
+ CoverallsResumeConfig,
+ CoverallsRetryableError,
+ _builds_url,
+ _fetch_json,
+ _incremental_cutoff,
+ _repo_config_url,
+ coveralls_source,
+ get_builds_rows,
+ get_repository_rows,
+ parse_repositories,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.coveralls.settings import COVERALLS_ENDPOINTS
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.coveralls.coveralls"
+
+
+def _response(status: int = 200, body: Optional[dict[str, Any]] = None) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.status_code = status
+ resp.ok = 200 <= status < 300
+ resp.json.return_value = body or {}
+ resp.text = json.dumps(body or {})
+ if not resp.ok:
+ resp.raise_for_status.side_effect = requests.HTTPError(
+ f"{status} Client Error for url: {COVERALLS_BASE_URL}", response=requests.Response()
+ )
+ return resp
+
+
+def _build(build_id: int, created_at: str, repo_name: str | None = "acme/widgets") -> dict[str, Any]:
+ build: dict[str, Any] = {
+ "id": build_id,
+ "branch": "master",
+ "commit_sha": f"sha-{build_id}",
+ "created_at": created_at,
+ "covered_percent": 90.0,
+ }
+ if repo_name is not None:
+ build["repo_name"] = repo_name
+ return build
+
+
+def _builds_page(page: int, pages: int, builds: list[dict[str, Any]]) -> dict[str, Any]:
+ return {"page": page, "pages": pages, "total": pages * 10, "builds": builds}
+
+
+def _manager(state: CoverallsResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = state is not None
+ manager.load_state.return_value = state
+ return manager
+
+
+class TestParseRepositories:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("acme/widgets", ["acme/widgets"]),
+ ("acme/widgets\nacme/gadgets", ["acme/widgets", "acme/gadgets"]),
+ ("acme/widgets, acme/gadgets", ["acme/widgets", "acme/gadgets"]),
+ (" acme/widgets , acme/gadgets \n acme/things ", ["acme/widgets", "acme/gadgets", "acme/things"]),
+ # De-duplicated case-insensitively while preserving order, so the primary key never sees
+ # the same repository twice.
+ ("acme/widgets\nAcme/Widgets\nacme/gadgets", ["acme/widgets", "acme/gadgets"]),
+ ("acme/widgets\n\n \nacme/gadgets", ["acme/widgets", "acme/gadgets"]),
+ # GitLab subgroups keep their full path.
+ ("group/subgroup/project", ["group/subgroup/project"]),
+ ],
+ )
+ def test_valid(self, raw, expected):
+ assert parse_repositories(raw) == expected
+
+ @pytest.mark.parametrize("raw", [None, "", " \n ", " , , ", "not-owner-repo"])
+ def test_invalid_raises(self, raw):
+ with pytest.raises(ValueError):
+ parse_repositories(raw)
+
+ def test_rejects_too_many_repositories(self):
+ raw = "\n".join(f"acme/repo{i}" for i in range(MAX_REPOSITORIES + 1))
+ with pytest.raises(ValueError, match="Too many repositories"):
+ parse_repositories(raw)
+
+
+class TestUrls:
+ def test_builds_url_shape(self):
+ assert _builds_url("github", "acme/widgets", 3) == f"{COVERALLS_BASE_URL}/github/acme/widgets.json?page=3"
+
+ def test_repo_config_url_shape(self):
+ assert _repo_config_url("github", "acme/widgets") == f"{COVERALLS_BASE_URL}/api/v1/repos/github/acme/widgets"
+
+ def test_encodes_odd_characters(self):
+ # An odd character must not break out of the path.
+ assert "%3F" in _builds_url("github", "acme/widg?ets", 1)
+
+
+# tenacity exposes the undecorated function via `__wrapped__` so status classification can be
+# asserted without waiting through retry backoff.
+_fetch_once = _fetch_json.__wrapped__ # type: ignore[attr-defined]
+
+
+class TestFetchJson:
+ def test_ok_returns_body(self):
+ session = mock.MagicMock()
+ session.get.return_value = _response(200, {"builds": []})
+
+ assert _fetch_once(session, "https://coveralls.io/x", {}, structlog.get_logger()) == {"builds": []}
+
+ def test_404_returns_none(self):
+ # A typo'd, untracked, or private repository must be skipped, not fail the whole sync.
+ session = mock.MagicMock()
+ session.get.return_value = _response(404)
+
+ assert _fetch_once(session, "https://coveralls.io/x", {}, structlog.get_logger()) is None
+
+ @pytest.mark.parametrize("status", [429, 500, 503])
+ def test_retryable_statuses_raise_retryable(self, status):
+ session = mock.MagicMock()
+ session.get.return_value = _response(status)
+
+ with pytest.raises(CoverallsRetryableError):
+ _fetch_once(session, "https://coveralls.io/x", {}, structlog.get_logger())
+
+ def test_other_client_error_raises(self):
+ session = mock.MagicMock()
+ session.get.return_value = _response(401)
+
+ with pytest.raises(requests.HTTPError):
+ _fetch_once(session, "https://coveralls.io/x", {}, structlog.get_logger())
+
+
+class TestIncrementalCutoff:
+ @pytest.mark.parametrize(
+ "value, lookback, expected",
+ [
+ # The DB hands the watermark back as a datetime or an ISO string; both must resolve.
+ (datetime(2021, 4, 16, 12, 0, tzinfo=UTC), None, datetime(2021, 4, 16, 12, 0, tzinfo=UTC)),
+ ("2021-04-16T12:00:00Z", None, datetime(2021, 4, 16, 12, 0, tzinfo=UTC)),
+ # The safety lookback re-pulls a window before the watermark; merge dedupes it.
+ (
+ datetime(2021, 4, 16, 12, 0, tzinfo=UTC),
+ COVERALLS_ENDPOINTS["builds"].incremental_lookback,
+ datetime(2021, 4, 15, 12, 0, tzinfo=UTC),
+ ),
+ (None, None, None),
+ ("not-a-date", None, None),
+ ],
+ )
+ def test_cutoff(self, value, lookback, expected):
+ assert _incremental_cutoff(value, lookback) == expected
+
+
+class TestGetBuildsRows:
+ def test_walks_every_page_until_pages_reached(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = [
+ _response(200, _builds_page(1, 2, [_build(20, "2021-04-16T17:46:20Z")])),
+ _response(200, _builds_page(2, 2, [_build(10, "2021-04-13T18:45:20Z")])),
+ ]
+
+ batches = list(get_builds_rows("github", ["acme/widgets"], structlog.get_logger(), _manager(), None))
+
+ assert [[row["id"] for row in batch] for batch in batches] == [[20], [10]]
+ assert mock_session.return_value.get.call_count == 2
+
+ def test_stops_on_empty_page(self):
+ # Past-the-end pages return an empty builds list; the walk must terminate rather than loop.
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(200, _builds_page(1, 0, []))
+
+ batches = list(get_builds_rows("github", ["acme/widgets"], structlog.get_logger(), _manager(), None))
+
+ assert batches == []
+ assert mock_session.return_value.get.call_count == 1
+
+ def test_incremental_stops_at_watermark(self):
+ # The feed is newest-first: once a build at or before the cutoff shows up, later pages are
+ # all older, so an incremental sync must not fetch them.
+ cutoff = datetime(2021, 4, 15, 0, 0, tzinfo=UTC)
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(
+ 200,
+ _builds_page(1, 5, [_build(20, "2021-04-16T17:46:20Z"), _build(10, "2021-04-13T18:45:20Z")]),
+ )
+
+ batches = list(get_builds_rows("github", ["acme/widgets"], structlog.get_logger(), _manager(), cutoff))
+
+ # The page containing the old build is still yielded (merge dedupes), but no further page is fetched.
+ assert len(batches) == 1
+ assert mock_session.return_value.get.call_count == 1
+
+ def test_no_watermark_walks_full_history(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = [
+ _response(200, _builds_page(1, 2, [_build(20, "2021-04-16T17:46:20Z")])),
+ _response(200, _builds_page(2, 2, [_build(10, "2021-04-13T18:45:20Z")])),
+ ]
+
+ batches = list(get_builds_rows("github", ["acme/widgets"], structlog.get_logger(), _manager(), None))
+
+ assert len(batches) == 2
+
+ def test_skips_404_repository_and_continues(self):
+ # One typo'd or private repository must not kill the sync for the others.
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = [
+ _response(404),
+ _response(200, _builds_page(1, 1, [_build(30, "2021-04-16T17:46:20Z", repo_name="acme/gadgets")])),
+ ]
+
+ batches = list(
+ get_builds_rows("github", ["acme/nope", "acme/gadgets"], structlog.get_logger(), _manager(), None)
+ )
+
+ assert [[row["id"] for row in batch] for batch in batches] == [[30]]
+
+ def test_stamps_repo_name_when_missing(self):
+ # `repo_name` is part of the primary key; a row without it couldn't upsert cleanly.
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(
+ 200, _builds_page(1, 1, [_build(20, "2021-04-16T17:46:20Z", repo_name=None)])
+ )
+
+ batches = list(get_builds_rows("github", ["acme/widgets"], structlog.get_logger(), _manager(), None))
+
+ assert batches[0][0]["repo_name"] == "acme/widgets"
+
+ def test_saves_state_after_each_page_and_between_repositories(self):
+ manager = _manager()
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = [
+ _response(200, _builds_page(1, 2, [_build(20, "2021-04-16T17:46:20Z")])),
+ _response(200, _builds_page(2, 2, [_build(10, "2021-04-13T18:45:20Z")])),
+ _response(200, _builds_page(1, 1, [_build(30, "2021-04-17T00:00:00Z", repo_name="acme/gadgets")])),
+ ]
+
+ generator = get_builds_rows(
+ "github", ["acme/widgets", "acme/gadgets"], structlog.get_logger(), manager, None
+ )
+
+ next(generator)
+ # State is only saved AFTER a page is yielded and consumed, so a crash re-yields it.
+ manager.save_state.assert_not_called()
+
+ next(generator)
+ manager.save_state.assert_called_once_with(CoverallsResumeConfig(repository="acme/widgets", page=2))
+
+ list(generator)
+
+ assert manager.save_state.call_args_list[-1] == mock.call(
+ CoverallsResumeConfig(repository="acme/gadgets", page=1)
+ )
+
+ def test_resumes_from_saved_repository_and_page(self):
+ # A resumed sync must skip completed repositories and start the bookmarked one at the saved
+ # page, not restart the whole walk.
+ manager = _manager(CoverallsResumeConfig(repository="acme/gadgets", page=3))
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(
+ 200, _builds_page(3, 3, [_build(5, "2021-01-01T00:00:00Z", repo_name="acme/gadgets")])
+ )
+
+ batches = list(
+ get_builds_rows("github", ["acme/widgets", "acme/gadgets"], structlog.get_logger(), manager, None)
+ )
+
+ assert len(batches) == 1
+ called_url = mock_session.return_value.get.call_args[0][0]
+ assert called_url == _builds_url("github", "acme/gadgets", 3)
+
+ def test_resume_bookmark_no_longer_configured_starts_over(self):
+ manager = _manager(CoverallsResumeConfig(repository="acme/removed", page=7))
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(
+ 200, _builds_page(1, 1, [_build(20, "2021-04-16T17:46:20Z")])
+ )
+
+ list(get_builds_rows("github", ["acme/widgets"], structlog.get_logger(), manager, None))
+
+ called_url = mock_session.return_value.get.call_args[0][0]
+ assert called_url == _builds_url("github", "acme/widgets", 1)
+
+
+class TestGetRepositoryRows:
+ def test_requires_api_token(self):
+ with pytest.raises(ValueError, match="personal API token"):
+ list(get_repository_rows("github", ["acme/widgets"], None, structlog.get_logger()))
+
+ def test_yields_row_per_repository_with_key_columns(self):
+ # `service` and `name` form the primary key, so they must be present even if the API
+ # response omits them.
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = [
+ _response(200, {"comment_on_pull_requests": True, "repo_token": "secret-upload-token"}),
+ _response(404),
+ _response(200, {"name": "acme/gadgets", "send_build_status": False, "token": "secret"}),
+ ]
+
+ batches = list(
+ get_repository_rows(
+ "github", ["acme/widgets", "acme/nope", "acme/gadgets"], "tok", structlog.get_logger()
+ )
+ )
+
+ assert len(batches) == 2
+ assert batches[0][0]["service"] == "github"
+ assert batches[0][0]["name"] == "acme/widgets"
+ assert batches[1][0]["name"] == "acme/gadgets"
+ # The response's secret coverage-upload token must never be persisted as warehouse data.
+ for batch in batches:
+ assert not any("token" in key for key in batch[0])
+
+ def test_sends_token_header(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(200, {})
+
+ list(get_repository_rows("github", ["acme/widgets"], "tok", structlog.get_logger()))
+
+ headers = mock_session.return_value.get.call_args[1]["headers"]
+
+ assert headers["Authorization"] == "token tok"
+
+ def test_repos_session_disables_sample_capture(self):
+ # The /api/v1/repos response carries the repo's secret coverage-upload token, so the
+ # session must opt out of HTTP sample capture — otherwise the token lands in stored samples.
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(200, {})
+
+ list(get_repository_rows("github", ["acme/widgets"], "tok", structlog.get_logger()))
+
+ assert mock_session.call_args.kwargs.get("capture") is False
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status, expected_valid",
+ [
+ (200, True),
+ (404, False),
+ (500, False),
+ ],
+ )
+ def test_builds_feed_status_mapping(self, status, expected_valid):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(status)
+
+ is_valid, _ = validate_credentials("github", "acme/widgets", None)
+
+ assert is_valid is expected_valid
+
+ def test_invalid_repositories_fail_without_request(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ is_valid, message = validate_credentials("github", "", None)
+
+ assert is_valid is False
+ assert message is not None
+ mock_session.return_value.get.assert_not_called()
+
+ def test_network_error_is_invalid(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = Exception("boom")
+
+ is_valid, message = validate_credentials("github", "acme/widgets", None)
+
+ assert is_valid is False
+ assert message is not None
+
+ def test_repositories_schema_requires_token(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(200)
+
+ is_valid, message = validate_credentials("github", "acme/widgets", None, schema_name="repositories")
+
+ assert is_valid is False
+ assert message is not None and "token" in message
+
+ @pytest.mark.parametrize(
+ "token_status, expected_valid",
+ [
+ (200, True),
+ (401, False),
+ # Coveralls answers 404 (not 401) for unauthorized repos-API requests too.
+ (404, False),
+ ],
+ )
+ def test_repositories_schema_probes_token(self, token_status, expected_valid):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = [_response(200), _response(token_status)]
+
+ is_valid, _ = validate_credentials("github", "acme/widgets", "tok", schema_name="repositories")
+
+ assert is_valid is expected_valid
+
+
+class TestCoverallsSource:
+ @pytest.mark.parametrize("endpoint", list(COVERALLS_ENDPOINTS))
+ def test_source_response_shape(self, endpoint):
+ response = coveralls_source(
+ endpoint=endpoint,
+ service="github",
+ repositories_raw="acme/widgets",
+ api_token=None,
+ logger=structlog.get_logger(),
+ resumable_source_manager=_manager(),
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == COVERALLS_ENDPOINTS[endpoint].primary_keys
+ assert response.sort_mode == "desc"
+
+ def test_only_builds_is_partitioned(self):
+ builds = coveralls_source(
+ endpoint="builds",
+ service="github",
+ repositories_raw="acme/widgets",
+ api_token=None,
+ logger=structlog.get_logger(),
+ resumable_source_manager=_manager(),
+ )
+ repositories = coveralls_source(
+ endpoint="repositories",
+ service="github",
+ repositories_raw="acme/widgets",
+ api_token="tok",
+ logger=structlog.get_logger(),
+ resumable_source_manager=_manager(),
+ )
+
+ assert builds.partition_mode == "datetime"
+ assert builds.partition_keys == ["created_at"]
+ assert repositories.partition_mode is None
+ assert repositories.partition_keys is None
+
+ def test_invalid_repositories_raise(self):
+ with pytest.raises(ValueError):
+ coveralls_source(
+ endpoint="builds",
+ service="github",
+ repositories_raw="",
+ api_token=None,
+ logger=structlog.get_logger(),
+ resumable_source_manager=_manager(),
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coveralls/tests/test_coveralls_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coveralls/tests/test_coveralls_source.py
new file mode 100644
index 000000000000..c1cf7afdbe51
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coveralls/tests/test_coveralls_source.py
@@ -0,0 +1,188 @@
+import pytest
+from unittest import mock
+
+import structlog
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.coveralls.coveralls import CoverallsResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.coveralls.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.coveralls.source import CoverallsSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CoverallsSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _make_inputs(
+ schema_name: str = "builds",
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value=None,
+) -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-id",
+ source_id="source-id",
+ team_id=123,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ db_incremental_field_earliest_value=None,
+ incremental_field="created_at" if should_use_incremental_field else None,
+ incremental_field_type=None,
+ job_id="job-id",
+ logger=structlog.get_logger(),
+ reset_pipeline=False,
+ )
+
+
+class TestCoverallsSource:
+ def setup_method(self):
+ self.source = CoverallsSource()
+ self.team_id = 123
+ self.config = CoverallsSourceConfig(repositories="acme/widgets\nacme/gadgets", service="github")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.COVERALLS
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Coveralls"
+ assert config.label == "Coveralls"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/coveralls"
+ # The source is finished and must be visible/connectable.
+ assert not config.unreleasedSource
+
+ def test_get_source_config_fields(self):
+ fields = self.source.get_source_config.fields
+
+ by_name = {field.name: field for field in fields}
+ assert set(by_name) == {"service", "repositories", "api_token"}
+
+ service_field = by_name["service"]
+ assert isinstance(service_field, SourceFieldSelectConfig)
+ assert {option.value for option in service_field.options} == {"github", "gitlab", "bitbucket"}
+
+ repositories_field = by_name["repositories"]
+ assert isinstance(repositories_field, SourceFieldInputConfig)
+ assert repositories_field.type == SourceFieldInputConfigType.TEXTAREA
+ assert repositories_field.required is True
+ assert repositories_field.secret is False
+
+ token_field = by_name["api_token"]
+ assert isinstance(token_field, SourceFieldInputConfig)
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.required is False
+ assert token_field.secret is True
+
+ def test_connection_host_fields_gate_token_retargeting(self):
+ # `service` and `repositories` decide which repos the stored token queries, so the update
+ # serializer must re-require the token when either changes — dropping them here would let
+ # an editor reuse a preserved token against repos it never had token access to.
+ assert self.source.connection_host_fields == ["service", "repositories"]
+
+ def test_get_schemas_lists_all_endpoints(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ def test_builds_schema_sync_modes(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ # Incremental works via the newest-first watermark stop; the safety-window re-pull means
+ # only merge (not append) is safe.
+ assert schemas["builds"].supports_incremental is True
+ assert schemas["builds"].supports_append is False
+ assert [f["field"] for f in schemas["builds"].incremental_fields] == ["created_at"]
+
+ def test_repositories_schema_is_full_refresh_and_off_by_default(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ # Needs the optional API token, which source creation doesn't validate.
+ assert schemas["repositories"].supports_incremental is False
+ assert schemas["repositories"].supports_append is False
+ assert schemas["repositories"].should_sync_default is False
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["builds"])
+
+ assert [schema.name for schema in schemas] == ["builds"]
+
+ def test_non_retryable_errors_cover_auth_failures(self):
+ errors = self.source.get_non_retryable_errors()
+
+ assert any(key.startswith("401 Client Error") for key in errors)
+ assert any(key.startswith("403 Client Error") for key in errors)
+
+ def test_canonical_descriptions_cover_every_endpoint(self):
+ assert set(self.source.get_canonical_descriptions()) == set(ENDPOINTS)
+
+ def test_lists_tables_without_credentials(self):
+ # Static endpoint catalog with no I/O, so the public docs can render the table list.
+ assert self.source.lists_tables_without_credentials is True
+ assert len(self.source.get_documented_tables()) == len(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "api_token, expected_reason",
+ [
+ (None, "Requires a personal API token from your Coveralls account settings."),
+ ("tok", None),
+ ],
+ )
+ def test_endpoint_permissions_gate_repositories_on_token(self, api_token, expected_reason):
+ config = CoverallsSourceConfig(repositories="acme/widgets", service="github", api_token=api_token)
+
+ permissions = self.source.get_endpoint_permissions(config, self.team_id, list(ENDPOINTS))
+
+ assert permissions["builds"] is None
+ assert permissions["repositories"] == expected_reason
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.coveralls.source.validate_coveralls_credentials"
+ )
+ def test_validate_credentials_plumbs_config(self, mock_validate):
+ mock_validate.return_value = (True, None)
+
+ is_valid, message = self.source.validate_credentials(self.config, self.team_id, "repositories")
+
+ assert (is_valid, message) == (True, None)
+ mock_validate.assert_called_once_with(
+ service="github",
+ repositories_raw="acme/widgets\nacme/gadgets",
+ api_token=None,
+ schema_name="repositories",
+ )
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is CoverallsResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.coveralls.source.coveralls_source")
+ def test_source_for_pipeline_plumbs_args(self, mock_coveralls_source):
+ inputs = _make_inputs(schema_name="builds")
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_coveralls_source.assert_called_once_with(
+ endpoint="builds",
+ service="github",
+ repositories_raw="acme/widgets\nacme/gadgets",
+ api_token=None,
+ logger=inputs.logger,
+ resumable_source_manager=manager,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.coveralls.source.coveralls_source")
+ def test_source_for_pipeline_passes_watermark_only_when_incremental(self, mock_coveralls_source):
+ # A stale watermark left on the schema must not leak into a full-refresh run.
+ inputs = _make_inputs(should_use_incremental_field=False, db_incremental_field_last_value="2021-04-16")
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_coveralls_source.call_args[1]["db_incremental_field_last_value"] is None
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 c1fc76de9266..1a61d9edcec6 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
@@ -1037,7 +1037,9 @@ class CoupaSourceConfig(config.Config):
@config.config
class CoverallsSourceConfig(config.Config):
- pass
+ repositories: str
+ service: Literal["github", "gitlab", "bitbucket"] = config.value(default="github")
+ api_token: str | None = None
@config.config