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 travis_ci import source (#71220)

Tom Owersb7eabe5e31a5
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 83a1714451b9..ff98b5b95e04 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -465,6 +465,7 @@ the row lists both.
| tmdb | HTTP | requests | ✅ |
| todoist | HTTP | requests | ✅ |
| together_ai | HTTP | requests | ✅ |
+| travis_ci | HTTP | requests | ✅ |
| trello | HTTP | requests | ✅ |
| tremendous | HTTP | requests | ✅ |
| trigger_dev | HTTP | requests | ✅ |
@@ -942,7 +943,6 @@ doesn't conflict with concurrent PRs.
- tinyemail
- toggl
- track_pms
-- travis_ci
- tremendous
- trustpilot
- turso
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 485cf7ce8b5d..cd1fa6153b3f 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
@@ -4322,7 +4322,7 @@ class TrackPMSSourceConfig(config.Config):
@config.config
class TravisCISourceConfig(config.Config):
- pass
+ api_token: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/travis_ci/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/travis_ci/canonical_descriptions.py
new file mode 100644
index 000000000000..4b38cea7d0b1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/travis_ci/canonical_descriptions.py
@@ -0,0 +1,86 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "repositories": {
+ "description": "A repository on Travis CI, corresponding to a repository on GitHub or another source control provider.",
+ "docs_url": "https://developer.travis-ci.com/resource/repositories",
+ "columns": {
+ "id": "Value uniquely identifying the repository.",
+ "name": "The repository's name on GitHub.",
+ "slug": "Same as {repository.owner.name}/{repository.name}.",
+ "description": "The repository's description from GitHub.",
+ "github_id": "The repository's id on GitHub.",
+ "github_language": "The main programming language used according to GitHub.",
+ "active": "Whether or not this repository is currently enabled on Travis CI.",
+ "private": "Whether or not this repository is private.",
+ "owner": "GitHub user or organization the repository belongs to.",
+ "default_branch": "The default branch on GitHub.",
+ "starred": "Whether or not this repository is starred.",
+ "managed_by_installation": "Whether or not this repository is managed by a GitHub App installation.",
+ "active_on_org": "Whether or not this repository runs builds on travis-ci.org (may also be null).",
+ },
+ },
+ "builds": {
+ "description": "A single build run for a repository, triggered by a push, pull request, cron, or API request.",
+ "docs_url": "https://developer.travis-ci.com/resource/builds",
+ "columns": {
+ "id": "Value uniquely identifying the build.",
+ "number": "Incremental number for a repository's builds.",
+ "state": "Current state of the build (e.g. created, started, passed, failed, errored, canceled).",
+ "duration": "Wall clock time in seconds.",
+ "event_type": "Event that triggered the build (push, pull_request, cron, api).",
+ "previous_state": "State of the previous build (useful to see if state changed).",
+ "pull_request_title": "Title of the build's pull request.",
+ "pull_request_number": "Number of the build's pull request.",
+ "started_at": "When the build started.",
+ "finished_at": "When the build finished.",
+ "private": "Whether or not the build is private.",
+ "repository": "GitHub user or organization the build belongs to.",
+ "branch": "The branch the build is associated with.",
+ "tag": "The build's tag.",
+ "commit": "The commit the build is associated with.",
+ "jobs": "List of jobs that are part of the build's matrix.",
+ "stages": "The stages of the build.",
+ "created_by": "The user or organization that created the build.",
+ "updated_at": "When the build was last updated.",
+ "repository_id": "Id of the repository the build belongs to (added by PostHog for joins).",
+ },
+ },
+ "jobs": {
+ "description": "A single job of a build's matrix — the unit of work that runs on one VM or container.",
+ "docs_url": "https://developer.travis-ci.com/resource/jobs",
+ "columns": {
+ "id": "Value uniquely identifying the job.",
+ "allow_failure": "The job's allow_failure setting.",
+ "number": "Incremental number for a repository's builds.",
+ "state": "Current state of the job (e.g. created, queued, started, passed, failed, errored, canceled).",
+ "started_at": "When the job started.",
+ "finished_at": "When the job finished.",
+ "build": "The build the job is associated with.",
+ "queue": "Worker queue this job is/was scheduled on.",
+ "repository": "GitHub user or organization the job belongs to.",
+ "commit": "The commit the job is associated with.",
+ "owner": "GitHub user or organization the job belongs to.",
+ "stage": "The stage the job is in.",
+ "created_at": "When the job was created.",
+ "updated_at": "When the job was last updated.",
+ "private": "Whether or not the job is private.",
+ "build_id": "Id of the build the job belongs to (added by PostHog; the incremental cursor).",
+ "repository_id": "Id of the repository the job belongs to (added by PostHog for joins).",
+ },
+ },
+ "branches": {
+ "description": "A branch of a repository known to Travis CI, with its last build.",
+ "docs_url": "https://developer.travis-ci.com/resource/branches",
+ "columns": {
+ "name": "Name of the git branch.",
+ "default_branch": "Whether or not this is the repository's default branch.",
+ "exists_on_github": "Whether or not the branch still exists on GitHub.",
+ "last_build": "Last build on the branch.",
+ "repository": "GitHub user or organization the branch belongs to.",
+ "repository_id": "Id of the repository the branch belongs to (added by PostHog; part of the primary key).",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/travis_ci/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/travis_ci/settings.py
new file mode 100644
index 000000000000..0c64139468b1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/travis_ci/settings.py
@@ -0,0 +1,100 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class TravisCIEndpointConfig:
+ name: str
+ # Path template relative to the API base. Fan-out endpoints carry a ``{repository_id}``
+ # placeholder filled per repository.
+ path: str
+ # Key holding the row list in the JSON response (Travis v3 wraps collections, e.g.
+ # ``{"builds": [...], "@pagination": {...}}``).
+ collection_key: str
+ # Iterate every accessible repository and query ``path`` once per repo.
+ fan_out_over_repositories: bool = False
+ # Extra query params sent on the first page request (``@pagination.next`` hrefs carry
+ # them forward on subsequent pages).
+ extra_params: dict[str, str] = field(default_factory=dict)
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Field used to partition the Delta table. Must be STABLE (set once at creation) — never
+ # ``updated_at``/``started_at`` style fields, which mutate on restarts and would rewrite
+ # partitions on every sync.
+ partition_key: Optional[str] = None
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ should_sync_default: bool = True
+
+
+# Travis CI API v3 endpoints. The API exposes no server-side timestamp filter, but list
+# endpoints accept ``sort_by`` and return monotonically increasing ids, so builds and jobs
+# sync incrementally by paginating newest-first (``sort_by=id:desc``, verified against the
+# live API) and stopping once a page reaches the last-synced id watermark.
+TRAVIS_CI_ENDPOINTS: dict[str, TravisCIEndpointConfig] = {
+ "repositories": TravisCIEndpointConfig(
+ name="repositories",
+ path="/repos",
+ collection_key="repositories",
+ # Repositories expose no creation timestamp, so no partitioning or incremental sync.
+ ),
+ "builds": TravisCIEndpointConfig(
+ name="builds",
+ path="/repo/{repository_id}/builds",
+ collection_key="builds",
+ fan_out_over_repositories=True,
+ extra_params={"sort_by": "id:desc"},
+ # Build ids are global (not per-repo), so the id watermark holds across the fan-out.
+ # A build's state/finished_at mutate after it first appears; once it drops below the
+ # watermark it isn't re-fetched — a full refresh re-pulls final states.
+ incremental_fields=[
+ {
+ "label": "id",
+ "type": IncrementalFieldType.Integer,
+ "field": "id",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ # Builds expose no immutable creation timestamp (started_at resets on restart), so no
+ # partitioning.
+ ),
+ "jobs": TravisCIEndpointConfig(
+ name="jobs",
+ path="/repo/{repository_id}/builds",
+ collection_key="builds",
+ fan_out_over_repositories=True,
+ # ``include=build.jobs`` promotes each build's embedded jobs to their standard
+ # representation, so jobs ride the builds pagination (1 request per 100 builds)
+ # instead of one request per build.
+ extra_params={"sort_by": "id:desc", "include": "build.jobs"},
+ # The watermark is the parent build id (injected as ``build_id``): a page of builds
+ # with no jobs still advances the cursor deterministically, which a job-id watermark
+ # can't guarantee.
+ incremental_fields=[
+ {
+ "label": "build_id",
+ "type": IncrementalFieldType.Integer,
+ "field": "build_id",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ partition_key="created_at",
+ ),
+ "branches": TravisCIEndpointConfig(
+ name="branches",
+ path="/repo/{repository_id}/branches",
+ collection_key="branches",
+ fan_out_over_repositories=True,
+ # Branches carry no id; the name is only unique within a repository.
+ primary_keys=["repository_id", "name"],
+ # Full refresh only, and it re-walks every repo's branch list each sync — off by
+ # default to avoid the API cost for users who don't need it.
+ should_sync_default=False,
+ ),
+}
+
+ENDPOINTS = tuple(TRAVIS_CI_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in TRAVIS_CI_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/travis_ci/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/travis_ci/source.py
index 75ad1c31a24a..978dacdc341d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/travis_ci/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/travis_ci/source.py
@@ -1,19 +1,46 @@
-from typing import cast
+from typing import Optional, cast
from 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.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import TravisCISourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.travis_ci.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.travis_ci.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ TRAVIS_CI_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.travis_ci.travis_ci import (
+ TravisCIResumeConfig,
+ travis_ci_source,
+ validate_credentials as validate_travis_ci_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class TravisCISource(SimpleSource[TravisCISourceConfig]):
+class TravisCISource(ResumableSource[TravisCISourceConfig, TravisCIResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.TRAVISCI
@@ -24,7 +51,100 @@ class TravisCISource(SimpleSource[TravisCISourceConfig]):
name=SchemaExternalDataSourceType.TRAVIS_CI,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Travis CI (Idera)",
+ releaseStatus=ReleaseStatus.ALPHA,
+ docsUrl="https://posthog.com/docs/cdp/sources/travis-ci",
+ caption="""Enter your Travis CI API token to sync your CI/CD build history into the PostHog Data warehouse.
+
+You can find or generate the token in your [Travis CI settings](https://app.travis-ci.com/account/preferences) under **API authentication**, or with the Travis CI CLI: `travis token --com`.
+
+The token can read every repository its owning user has access to; only those repositories are synced.
+""",
iconPath="/static/services/travis_ci.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # Travis CI answers 403 "access denied" for missing/invalid/revoked tokens (it does
+ # not use 401, but match it too in case that changes). Retrying can't satisfy a
+ # credential problem, so stop the sync.
+ "401 Client Error: Unauthorized for url: https://api.travis-ci.com": "Your Travis CI API token is invalid or has been revoked. Generate a new token in your Travis CI settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.travis-ci.com": "Your Travis CI API token is invalid or has been revoked. Generate a new token in your Travis CI settings, then reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: TravisCISourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _description(endpoint: str) -> str | None:
+ if endpoint in ("builds", "jobs"):
+ return (
+ "Synced newest-first; incremental syncs stop at the last-synced id, so rows that "
+ "were still running when previously synced keep their state from that sync — run a "
+ "full refresh to re-pull final states"
+ )
+ if endpoint == "branches":
+ return "Full refresh only, walking every accessible repository's branch list"
+ return None
+
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=TRAVIS_CI_ENDPOINTS[endpoint].should_sync_default,
+ description=_description(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: TravisCISourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # Travis CI tokens carry no scopes, so one /user probe covers every endpoint — a valid
+ # token can read everything the owning user can.
+ return validate_travis_ci_credentials(config.api_token)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TravisCIResumeConfig]:
+ return ResumableSourceManager[TravisCIResumeConfig](inputs, TravisCIResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: TravisCISourceConfig,
+ resumable_source_manager: ResumableSourceManager[TravisCIResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return travis_ci_source(
+ api_token=config.api_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/travis_ci/tests/test_travis_ci.py b/products/warehouse_sources/backend/temporal/data_imports/sources/travis_ci/tests/test_travis_ci.py
new file mode 100644
index 000000000000..629557f7a2f4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/travis_ci/tests/test_travis_ci.py
@@ -0,0 +1,383 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+from unittest.mock import MagicMock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.travis_ci import travis_ci
+from products.warehouse_sources.backend.temporal.data_imports.sources.travis_ci.travis_ci import (
+ TRAVIS_CI_BASE_URL,
+ TravisCIResumeConfig,
+ _resolve_page_url,
+ get_rows,
+ travis_ci_source,
+ validate_credentials,
+)
+
+REPOS_URL = f"{TRAVIS_CI_BASE_URL}/repos?limit=100"
+BUILDS_PARAMS = "limit=100&sort_by=id%3Adesc"
+JOBS_PARAMS = "limit=100&sort_by=id%3Adesc&include=build.jobs"
+
+
+def _page(collection_key: str, items: list[dict[str, Any]], next_path: str | None = None) -> dict[str, Any]:
+ return {collection_key: items, "@pagination": {"next": {"@href": next_path} if next_path else None}}
+
+
+class _FakeResumableManager:
+ def __init__(self, state: TravisCIResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[TravisCIResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> TravisCIResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: TravisCIResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _collect(
+ manager: _FakeResumableManager,
+ pages: dict[str, dict[str, Any]],
+ endpoint: str,
+ logger: Any = None,
+ **kwargs: Any,
+) -> tuple[list[dict[str, Any]], list[str]]:
+ fetched: list[str] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict[str, Any]:
+ fetched.append(url)
+ return pages[url]
+
+ rows: list[dict[str, Any]] = []
+ with (
+ mock.patch.object(travis_ci, "make_tracked_session", lambda *a, **k: MagicMock()),
+ mock.patch.object(travis_ci, "_fetch_page", fake_fetch),
+ ):
+ for batch in get_rows(
+ api_token="tok",
+ endpoint=endpoint,
+ logger=logger if logger is not None else MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
+ ):
+ rows.extend(batch)
+ return rows, fetched
+
+
+class TestRepositories:
+ def test_follows_pagination_and_strips_meta_keys(self) -> None:
+ page2_path = "/repos?limit=100&offset=100"
+ pages = {
+ REPOS_URL: _page(
+ "repositories",
+ [{"@type": "repository", "@href": "/repo/1", "id": 1, "slug": "o/a"}],
+ next_path=page2_path,
+ ),
+ f"{TRAVIS_CI_BASE_URL}{page2_path}": _page("repositories", [{"id": 2, "slug": "o/b"}]),
+ }
+ manager = _FakeResumableManager()
+ rows, fetched = _collect(manager, pages, endpoint="repositories")
+
+ assert [r["id"] for r in rows] == [1, 2]
+ assert "@type" not in rows[0] and "@href" not in rows[0]
+ assert fetched == [REPOS_URL, f"{TRAVIS_CI_BASE_URL}{page2_path}"]
+ # State is saved AFTER the page is yielded, pointing at the next page, so a crash
+ # re-yields the in-progress page instead of skipping it.
+ assert manager.saved == [TravisCIResumeConfig(next_path=page2_path)]
+
+ def test_resumes_from_saved_page_path(self) -> None:
+ resume_path = "/repos?limit=100&offset=200"
+ pages = {f"{TRAVIS_CI_BASE_URL}{resume_path}": _page("repositories", [{"id": 9}])}
+ manager = _FakeResumableManager(TravisCIResumeConfig(next_path=resume_path))
+ rows, fetched = _collect(manager, pages, endpoint="repositories")
+
+ assert fetched == [f"{TRAVIS_CI_BASE_URL}{resume_path}"]
+ assert [r["id"] for r in rows] == [9]
+
+
+class TestBuildsFanOut:
+ def test_fans_out_over_repositories_and_bookmarks_progress(self) -> None:
+ repo1_page2 = f"/repo/1/builds?{BUILDS_PARAMS}&offset=100"
+ pages = {
+ REPOS_URL: _page("repositories", [{"id": 1}, {"id": 2}]),
+ f"{TRAVIS_CI_BASE_URL}/repo/1/builds?{BUILDS_PARAMS}": _page(
+ "builds", [{"@type": "build", "id": 30}, {"id": 20}], next_path=repo1_page2
+ ),
+ f"{TRAVIS_CI_BASE_URL}{repo1_page2}": _page("builds", [{"id": 10}]),
+ f"{TRAVIS_CI_BASE_URL}/repo/2/builds?{BUILDS_PARAMS}": _page("builds", [{"id": 25}]),
+ }
+ manager = _FakeResumableManager()
+ rows, _fetched = _collect(manager, pages, endpoint="builds")
+
+ assert [(r["id"], r["repository_id"]) for r in rows] == [(30, 1), (20, 1), (10, 1), (25, 2)]
+ assert manager.saved == [
+ TravisCIResumeConfig(next_path=repo1_page2, repository_id=1),
+ TravisCIResumeConfig(next_path=None, repository_id=2),
+ ]
+
+ @parameterized.expand([("int_watermark", 20), ("str_watermark", "20")])
+ def test_incremental_stops_at_watermark(self, _name: str, watermark: Any) -> None:
+ repo1_page2 = f"/repo/1/builds?{BUILDS_PARAMS}&offset=100"
+ pages = {
+ REPOS_URL: _page("repositories", [{"id": 1}, {"id": 2}]),
+ f"{TRAVIS_CI_BASE_URL}/repo/1/builds?{BUILDS_PARAMS}": _page(
+ "builds", [{"id": 30}, {"id": 20}], next_path=repo1_page2
+ ),
+ f"{TRAVIS_CI_BASE_URL}/repo/2/builds?{BUILDS_PARAMS}": _page("builds", [{"id": 15}]),
+ }
+ rows, fetched = _collect(
+ _FakeResumableManager(),
+ pages,
+ endpoint="builds",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
+ )
+
+ # Only builds newer than the watermark are yielded, and repo 1's older second page is
+ # never fetched. Repo 2 is still scanned — the watermark is global, so each repo's scan
+ # stops independently once it reaches already-synced builds.
+ assert [r["id"] for r in rows] == [30]
+ assert f"{TRAVIS_CI_BASE_URL}{repo1_page2}" not in fetched
+ assert f"{TRAVIS_CI_BASE_URL}/repo/2/builds?{BUILDS_PARAMS}" in fetched
+
+ def test_full_refresh_walks_all_pages(self) -> None:
+ repo1_page2 = f"/repo/1/builds?{BUILDS_PARAMS}&offset=100"
+ pages = {
+ REPOS_URL: _page("repositories", [{"id": 1}]),
+ f"{TRAVIS_CI_BASE_URL}/repo/1/builds?{BUILDS_PARAMS}": _page("builds", [{"id": 30}], next_path=repo1_page2),
+ f"{TRAVIS_CI_BASE_URL}{repo1_page2}": _page("builds", [{"id": 10}]),
+ }
+ rows, _fetched = _collect(_FakeResumableManager(), pages, endpoint="builds")
+ assert [r["id"] for r in rows] == [30, 10]
+
+ def test_resumes_from_bookmarked_repository(self) -> None:
+ resume_path = f"/repo/2/builds?{BUILDS_PARAMS}&offset=100"
+ pages = {
+ REPOS_URL: _page("repositories", [{"id": 1}, {"id": 2}, {"id": 3}]),
+ f"{TRAVIS_CI_BASE_URL}{resume_path}": _page("builds", [{"id": 5}]),
+ f"{TRAVIS_CI_BASE_URL}/repo/3/builds?{BUILDS_PARAMS}": _page("builds", [{"id": 7}]),
+ }
+ manager = _FakeResumableManager(TravisCIResumeConfig(next_path=resume_path, repository_id=2))
+ rows, fetched = _collect(manager, pages, endpoint="builds")
+
+ # Repo 1 is skipped entirely, repo 2 resumes at the saved page, repo 3 starts fresh.
+ assert f"{TRAVIS_CI_BASE_URL}/repo/1/builds?{BUILDS_PARAMS}" not in fetched
+ assert [(r["id"], r["repository_id"]) for r in rows] == [(5, 2), (7, 3)]
+
+ def test_missing_bookmarked_repository_starts_over(self) -> None:
+ pages = {
+ REPOS_URL: _page("repositories", [{"id": 1}]),
+ f"{TRAVIS_CI_BASE_URL}/repo/1/builds?{BUILDS_PARAMS}": _page("builds", [{"id": 3}]),
+ }
+ manager = _FakeResumableManager(TravisCIResumeConfig(next_path="/repo/99/builds", repository_id=99))
+ rows, _fetched = _collect(manager, pages, endpoint="builds")
+ assert [r["id"] for r in rows] == [3]
+
+ def test_page_cap_stops_pagination_and_warns(self) -> None:
+ repo1_page2 = f"/repo/1/builds?{BUILDS_PARAMS}&offset=100"
+ pages = {
+ REPOS_URL: _page("repositories", [{"id": 1}]),
+ f"{TRAVIS_CI_BASE_URL}/repo/1/builds?{BUILDS_PARAMS}": _page("builds", [{"id": 30}], next_path=repo1_page2),
+ }
+ logger = MagicMock()
+ with mock.patch.object(travis_ci, "MAX_PAGES_PER_REPO", 1):
+ rows, fetched = _collect(_FakeResumableManager(), pages, endpoint="builds", logger=logger)
+
+ assert [r["id"] for r in rows] == [30]
+ assert f"{TRAVIS_CI_BASE_URL}{repo1_page2}" not in fetched
+ logger.warning.assert_called_once()
+
+
+class TestJobs:
+ def test_flattens_embedded_jobs_with_parent_identifiers(self) -> None:
+ pages = {
+ REPOS_URL: _page("repositories", [{"id": 1}]),
+ f"{TRAVIS_CI_BASE_URL}/repo/1/builds?{JOBS_PARAMS}": _page(
+ "builds",
+ [
+ {
+ "id": 30,
+ "jobs": [
+ {"@type": "job", "id": 301, "state": "passed", "build": {"@type": "build", "id": 30}},
+ {"id": 302, "state": "failed"},
+ ],
+ },
+ {"id": 20, "jobs": []},
+ ],
+ ),
+ }
+ rows, _fetched = _collect(_FakeResumableManager(), pages, endpoint="jobs")
+
+ assert [(r["id"], r["build_id"], r["repository_id"]) for r in rows] == [(301, 30, 1), (302, 30, 1)]
+ # Meta keys are stripped recursively, including from nested minimal representations.
+ assert "@type" not in rows[0]
+ assert "@type" not in rows[0]["build"]
+
+ def test_incremental_stops_at_build_watermark(self) -> None:
+ pages = {
+ REPOS_URL: _page("repositories", [{"id": 1}]),
+ f"{TRAVIS_CI_BASE_URL}/repo/1/builds?{JOBS_PARAMS}": _page(
+ "builds",
+ [
+ {"id": 30, "jobs": [{"id": 301}]},
+ {"id": 20, "jobs": [{"id": 201}]},
+ ],
+ next_path=f"/repo/1/builds?{JOBS_PARAMS}&offset=100",
+ ),
+ }
+ rows, fetched = _collect(
+ _FakeResumableManager(),
+ pages,
+ endpoint="jobs",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=20,
+ )
+
+ assert [r["id"] for r in rows] == [301]
+ assert len(fetched) == 2 # /repos + first builds page; the older page is never fetched
+
+
+class TestBranches:
+ def test_rows_carry_composite_primary_key_fields(self) -> None:
+ pages = {
+ REPOS_URL: _page("repositories", [{"id": 1}]),
+ f"{TRAVIS_CI_BASE_URL}/repo/1/branches?limit=100": _page(
+ "branches", [{"@type": "branch", "name": "main", "default_branch": True}]
+ ),
+ }
+ rows, _fetched = _collect(_FakeResumableManager(), pages, endpoint="branches")
+ assert rows == [{"name": "main", "default_branch": True, "repository_id": 1}]
+
+
+class TestPaginationCursorValidation:
+ @parameterized.expand(
+ [
+ ("relative_path", "/repos?limit=100&offset=100", f"{TRAVIS_CI_BASE_URL}/repos?limit=100&offset=100"),
+ ("bare_path", "/user", f"{TRAVIS_CI_BASE_URL}/user"),
+ ]
+ )
+ def test_accepts_relative_cursor(self, _name: str, cursor: str, expected: str) -> None:
+ assert _resolve_page_url(cursor) == expected
+
+ @parameterized.expand(
+ [
+ # A userinfo-smuggling cursor: concatenation makes the API host the userinfo and the
+ # attacker host the real host, exfiltrating the Authorization header.
+ ("userinfo_smuggle", "@attacker.example/next"),
+ ("scheme_relative", "//attacker.example/next"),
+ ("absolute_url", "https://attacker.example/next"),
+ ("leading_space", " /repos"),
+ ("no_leading_slash", "repos?limit=100"),
+ ]
+ )
+ def test_rejects_host_changing_cursor(self, _name: str, cursor: str) -> None:
+
+ with pytest.raises(ValueError):
+ _resolve_page_url(cursor)
+
+
+class TestHostileCursorFailsSync:
+ def test_hostile_next_cursor_from_upstream_raises(self) -> None:
+
+ pages = {
+ REPOS_URL: _page("repositories", [{"id": 1}], next_path="@attacker.example/next"),
+ }
+ with pytest.raises(ValueError):
+ _collect(_FakeResumableManager(), pages, endpoint="repositories")
+
+ def test_hostile_resume_cursor_raises(self) -> None:
+
+ manager = _FakeResumableManager(TravisCIResumeConfig(next_path="@attacker.example/next"))
+ with pytest.raises(ValueError):
+ _collect(manager, {}, endpoint="repositories")
+
+
+class TestRedirectsDisabled:
+ def test_sessions_disable_redirects(self) -> None:
+ # allow_redirects=False keeps a poisoned cursor or hostile response from bouncing the
+ # credentialed request (and its token) to another host — defense in depth alongside
+ # cursor validation.
+ made: list[dict[str, Any]] = []
+
+ def fake_make(*_args: Any, **kwargs: Any) -> MagicMock:
+ made.append(kwargs)
+ return MagicMock()
+
+ with mock.patch.object(travis_ci, "make_tracked_session", fake_make):
+ validate_credentials("tok")
+ assert made and all(call.get("allow_redirects") is False for call in made)
+
+
+class _FakeResponse:
+ def __init__(self, status_code: int, body: Any = None) -> None:
+ self.status_code = status_code
+ self._body = body or {}
+ self.text = ""
+
+ def json(self) -> Any:
+ return self._body
+
+
+class TestValidateCredentials:
+ @staticmethod
+ def _validate_with(response_or_error: Any) -> tuple[bool, str | None]:
+ session = MagicMock()
+ if isinstance(response_or_error, Exception):
+ session.get.side_effect = response_or_error
+ else:
+ session.get.return_value = response_or_error
+ with mock.patch.object(travis_ci, "make_tracked_session", lambda *a, **k: session):
+ return validate_credentials("tok")
+
+ @parameterized.expand(
+ [
+ ("valid", 200, True),
+ # Travis answers 403 "access denied" for missing/invalid tokens (it has no scopes),
+ # so a 403 means the token is bad — unlike sources where 403 = missing scope.
+ ("access_denied", 403, False),
+ ("unauthorized", 401, False),
+ ("server_error", 500, False),
+ ]
+ )
+ def test_status_mapping(self, _name: str, status_code: int, expected_ok: bool) -> None:
+ ok, error = self._validate_with(_FakeResponse(status_code, {"error_message": "boom"}))
+ assert ok is expected_ok
+ assert (error is None) is expected_ok
+
+ def test_network_error_is_reported_not_raised(self) -> None:
+ ok, error = self._validate_with(requests.ConnectionError("boom"))
+ assert ok is False
+ assert error is not None and "Travis CI" in error
+
+
+class TestTravisCISourceResponse:
+ @parameterized.expand(
+ [
+ ("repositories", ["id"], None),
+ ("builds", ["id"], None),
+ ("jobs", ["id"], "created_at"),
+ ("branches", ["repository_id", "name"], None),
+ ]
+ )
+ def test_source_response_shape(self, endpoint: str, primary_keys: list[str], partition_key: str | None) -> None:
+ response = travis_ci_source(
+ api_token="tok",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ assert response.sort_mode == "desc"
+ if partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/travis_ci/tests/test_travis_ci_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/travis_ci/tests/test_travis_ci_source.py
new file mode 100644
index 000000000000..7fae8ba3c694
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/travis_ci/tests/test_travis_ci_source.py
@@ -0,0 +1,158 @@
+from typing import Any
+
+from unittest import mock
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import TravisCISourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.travis_ci.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.travis_ci.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.travis_ci.source import TravisCISource
+from products.warehouse_sources.backend.temporal.data_imports.sources.travis_ci.travis_ci import TravisCIResumeConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config() -> TravisCISourceConfig:
+ return TravisCISourceConfig(api_token="travis-token")
+
+
+class TestTravisCISource:
+ def setup_method(self) -> None:
+ self.source = TravisCISource()
+ self.team_id = 123
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.TRAVISCI
+
+ def test_source_config_fields(self) -> None:
+ config = self.source.get_source_config
+ assert not config.unreleasedSource
+ assert [f.name for f in config.fields] == ["api_token"]
+ token_field = config.fields[0]
+ assert isinstance(token_field, SourceFieldInputConfig)
+ assert token_field.secret is True
+
+ def test_get_schemas_lists_every_endpoint(self) -> None:
+ schemas = {s.name for s in self.source.get_schemas(_config(), team_id=self.team_id)}
+ assert schemas == set(ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ # Builds and jobs page newest-first and stop at the id watermark; repositories and
+ # branches expose no usable cursor, so they are full refresh only.
+ ("repositories", False),
+ ("builds", True),
+ ("jobs", True),
+ ("branches", False),
+ ]
+ )
+ def test_incremental_support_per_endpoint(self, endpoint: str, expected: bool) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(_config(), team_id=self.team_id)}
+ assert schemas[endpoint].supports_incremental is expected
+ assert schemas[endpoint].supports_append is expected
+
+ def test_branches_not_synced_by_default(self) -> None:
+ # Branches re-walk every repository's full branch list each sync, so they must stay
+ # opt-in rather than being force-enabled by one-shot source creation.
+ schemas = {s.name: s for s in self.source.get_schemas(_config(), team_id=self.team_id)}
+ assert schemas["branches"].should_sync_default is False
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(_config(), team_id=self.team_id, names=["builds"])
+ assert [s.name for s in schemas] == ["builds"]
+
+ @parameterized.expand(
+ [
+ # Travis answers 403 (not 401) for bad tokens, so the 403 mapping is the one that
+ # actually stops endless retries on revoked credentials.
+ (
+ "access_denied",
+ "403 Client Error: Forbidden for url: https://api.travis-ci.com/repo/1/builds?limit=100",
+ ),
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.travis-ci.com/user"),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("read_timeout", "HTTPSConnectionPool(host='api.travis-ci.com', port=443): Read timed out."),
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.travis-ci.com/repos"),
+ ("rate_limited", "Travis CI API error (retryable): status=429"),
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable)
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ assert set(self.source.get_canonical_descriptions()) == set(ENDPOINTS)
+ assert self.source.get_canonical_descriptions() is CANONICAL_DESCRIPTIONS
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ inputs = MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is TravisCIResumeConfig
+
+ def test_validate_credentials_delegates_with_token(self) -> None:
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.travis_ci.source.validate_travis_ci_credentials",
+ return_value=(True, None),
+ ) as mock_validate:
+ result = self.source.validate_credentials(_config(), team_id=self.team_id, schema_name="builds")
+ assert result == (True, None)
+ mock_validate.assert_called_once_with("travis-token")
+
+ def test_source_for_pipeline_plumbs_arguments(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "builds"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 278462667
+ manager = MagicMock()
+
+ captured: dict[str, Any] = {}
+
+ def fake_source(**kwargs: Any) -> MagicMock:
+ captured.update(kwargs)
+ return MagicMock()
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.travis_ci.source.travis_ci_source",
+ side_effect=fake_source,
+ ):
+ self.source.source_for_pipeline(_config(), manager, inputs)
+
+ assert captured["api_token"] == "travis-token"
+ assert captured["endpoint"] == "builds"
+ assert captured["should_use_incremental_field"] is True
+ assert captured["db_incremental_field_last_value"] == 278462667
+ assert captured["resumable_source_manager"] is manager
+
+ def test_source_for_pipeline_drops_last_value_when_not_incremental(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "repositories"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = 278462667
+
+ captured: dict[str, Any] = {}
+
+ def fake_source(**kwargs: Any) -> MagicMock:
+ captured.update(kwargs)
+ return MagicMock()
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.travis_ci.source.travis_ci_source",
+ side_effect=fake_source,
+ ):
+ self.source.source_for_pipeline(_config(), MagicMock(), inputs)
+
+ assert captured["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/travis_ci/travis_ci.py b/products/warehouse_sources/backend/temporal/data_imports/sources/travis_ci/travis_ci.py
new file mode 100644
index 000000000000..a47eb7916369
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/travis_ci/travis_ci.py
@@ -0,0 +1,349 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+from urllib.parse import urlencode, urlsplit
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.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.travis_ci.settings import TRAVIS_CI_ENDPOINTS
+
+TRAVIS_CI_BASE_URL = "https://api.travis-ci.com"
+TRAVIS_CI_HOST = urlsplit(TRAVIS_CI_BASE_URL).netloc
+# Verified against the live API for builds/branches; the documented default is 25.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+# Hard page caps so a fan-out can't scan unboundedly; both are logged when reached.
+MAX_REPO_PAGES = 100 # 10k repositories
+MAX_PAGES_PER_REPO = 1000 # 100k builds/branches per repository
+
+
+class TravisCIRetryableError(Exception):
+ pass
+
+
+def _resolve_page_url(page_path: str) -> str:
+ """Join a Travis pagination cursor onto the API base, pinned to the Travis host.
+
+ ``@pagination.next.@href`` is a server-supplied (and persisted-as-resume-state) value, so
+ it is untrusted. A hostile cursor such as ``@attacker.example/next`` concatenates into
+ ``https://[email protected]/next`` — ``attacker.example`` becomes the host
+ and receives the ``Authorization: token <api_token>`` header. We require a single leading
+ ``/`` (rejecting scheme-relative ``//host`` and userinfo/scheme smuggling) and re-parse the
+ joined URL to confirm the scheme and host are unchanged before it is ever requested.
+ """
+ if not page_path.startswith("/") or page_path.startswith("//"):
+ raise ValueError(f"Travis CI: refusing non-relative pagination cursor: {page_path!r}")
+ url = f"{TRAVIS_CI_BASE_URL}{page_path}"
+ parts = urlsplit(url)
+ if parts.scheme != "https" or parts.netloc != TRAVIS_CI_HOST:
+ raise ValueError(f"Travis CI: pagination cursor resolves to unexpected host: {page_path!r}")
+ return url
+
+
+class TravisCIResumeConfig:
+ # Relative ``@pagination.next.@href`` of the next page to fetch. None means "start the
+ # bookmarked unit at its first page" — used when the bookmark advances to a fan-out repo
+ # whose first page URL isn't built until the loop reaches it.
+ next_path: str | None = None
+ # The fan-out repository currently being processed. A stable repo-id bookmark (not a
+ # positional index) so repos added/removed between a crash and the retry can't resume us
+ # into the wrong repository. None for the non-fan-out repositories endpoint.
+ repository_id: int | None = None
+
+
+def _get_headers(api_token: str) -> dict[str, str]:
+ return {
+ # Every v3 request must carry this header; without it the API falls back to v2 routing.
+ "Travis-API-Version": "3",
+ "Authorization": f"token {api_token}",
+ "Accept": "application/json",
+ }
+
+
+def _strip_meta(value: Any) -> Any:
+ """Recursively drop Travis v3 envelope keys (``@type``, ``@href``, ``@representation``, ...)."""
+ if isinstance(value, dict):
+ return {key: _strip_meta(item) for key, item in value.items() if not key.startswith("@")}
+ if isinstance(value, list):
+ return [_strip_meta(item) for item in value]
+ return value
+
+
+def _coerce_watermark(value: Any) -> int | None:
+ """Coerce the stored incremental watermark (build/job id) to an int; None if unusable."""
+ if value is None:
+ return None
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def validate_credentials(api_token: str) -> tuple[bool, str | None]:
+ """Probe /user to confirm the token is genuine.
+
+ Travis CI tokens carry no scopes — a valid token can read everything the owning user can —
+ and the API answers 403 "access denied" for both missing and invalid tokens (verified
+ against the live API; it does not use 401), so any 403 here means the token is bad.
+ """
+ session = make_tracked_session(redact_values=(api_token,), allow_redirects=False)
+ try:
+ response = session.get(
+ f"{TRAVIS_CI_BASE_URL}/user", headers=_get_headers(api_token), timeout=REQUEST_TIMEOUT_SECONDS
+ )
+ except requests.exceptions.RequestException:
+ return False, "Could not reach the Travis CI API. Please try again."
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code in (401, 403):
+ return False, "Invalid Travis CI API token. Check the token in your Travis CI settings and try again."
+
+ try:
+ message = response.json().get("error_message", response.text)
+ except Exception:
+ message = response.text
+ return False, message
+
+
+@retry(
+ retry=retry_if_exception_type((TravisCIRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> dict[str, Any]:
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise TravisCIRetryableError(f"Travis CI API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Travis CI API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _next_path(data: dict[str, Any]) -> str | None:
+ """Relative href of the next page from the ``@pagination`` envelope, or None on the last page."""
+ pagination = data.get("@pagination") or {}
+ next_page = pagination.get("next")
+ if not next_page:
+ return None
+ return next_page.get("@href")
+
+
+def _iter_collection(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ path: str,
+ params: dict[str, Any],
+ collection_key: str,
+ max_pages: int,
+ resource: str,
+ start_path: str | None = None,
+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:
+ """Yield ``(items, next_path)`` per page of a v3 collection, following ``@pagination.next``.
+
+ ``@pagination.next.@href`` carries the original query params forward, so ``params`` only
+ shape the first request. ``start_path`` (a saved next href) replaces the first page when
+ resuming.
+ """
+ page_path = start_path if start_path is not None else f"{path}?{urlencode(params)}"
+ pages_fetched = 0
+
+ while True:
+ data = _fetch_page(session, _resolve_page_url(page_path), headers, logger)
+ items = data.get(collection_key) or []
+ next_path = _next_path(data)
+ pages_fetched += 1
+
+ yield items, next_path
+
+ if not next_path:
+ return
+
+ if pages_fetched >= max_pages:
+ logger.warning(
+ f"Travis CI: page cap reached for {resource}, stopping pagination. max_pages={max_pages}, path={path}"
+ )
+ return
+
+ page_path = next_path
+
+
+def _list_repository_ids(session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger) -> list[int]:
+ repository_ids: list[int] = []
+ for repositories, _ in _iter_collection(
+ session,
+ headers,
+ logger,
+ "/repos",
+ {"limit": PAGE_SIZE},
+ "repositories",
+ max_pages=MAX_REPO_PAGES,
+ resource="repositories",
+ ):
+ repository_ids.extend(repository["id"] for repository in repositories)
+ return repository_ids
+
+
+def _rows_for_page(
+ endpoint: str, repository_id: int, items: list[dict[str, Any]], watermark: int | None
+) -> tuple[list[dict[str, Any]], bool]:
+ """Shape one fan-out page into rows, returning ``(rows, reached_watermark)``.
+
+ Pages arrive sorted ``id:desc``, so the first item at or below the watermark means every
+ remaining item (and page) for this repository was already synced.
+ """
+ rows: list[dict[str, Any]] = []
+ reached_watermark = False
+
+ if endpoint == "jobs":
+ for build in items:
+ if watermark is not None and build["id"] <= watermark:
+ reached_watermark = True
+ break
+ for job in build.get("jobs") or []:
+ rows.append({**_strip_meta(job), "build_id": build["id"], "repository_id": repository_id})
+ return rows, reached_watermark
+
+ for item in items:
+ if watermark is not None and item.get("id") is not None and item["id"] <= watermark:
+ reached_watermark = True
+ break
+ rows.append({**_strip_meta(item), "repository_id": repository_id})
+ return rows, reached_watermark
+
+
+def get_rows(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TravisCIResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ if endpoint not in TRAVIS_CI_ENDPOINTS:
+ raise ValueError(f"Unknown Travis CI endpoint: {endpoint}")
+
+ config = TRAVIS_CI_ENDPOINTS[endpoint]
+ headers = _get_headers(api_token)
+ session = make_tracked_session(redact_values=(api_token,), allow_redirects=False)
+ watermark = _coerce_watermark(db_incremental_field_last_value) if should_use_incremental_field else None
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if not config.fan_out_over_repositories:
+ start_path = resume.next_path if resume is not None else None
+ if start_path is not None:
+ logger.debug(f"Travis CI: resuming {endpoint} from saved page path")
+ for items, next_path in _iter_collection(
+ session,
+ headers,
+ logger,
+ config.path,
+ {"limit": PAGE_SIZE, **config.extra_params},
+ config.collection_key,
+ max_pages=MAX_REPO_PAGES,
+ resource=endpoint,
+ start_path=start_path,
+ ):
+ rows = [_strip_meta(item) for item in items]
+ if rows:
+ yield rows
+ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the
+ # in-progress page rather than skipping it — merge dedupes on the primary key.
+ if next_path:
+ resumable_source_manager.save_state(TravisCIResumeConfig(next_path=next_path))
+ return
+
+ repository_ids = _list_repository_ids(session, headers, logger)
+
+ # Resolve the saved repo-id bookmark to the slice of repos still to process. If the
+ # bookmarked repo no longer exists (removed between a crash and the retry), start over from
+ # the first repo — merge dedupes the re-pulled rows on the primary key. ``resume_path`` is
+ # consumed by the bookmarked repo only.
+ remaining = repository_ids
+ resume_path: str | None = None
+ if resume is not None and resume.repository_id is not None and resume.repository_id in repository_ids:
+ remaining = repository_ids[repository_ids.index(resume.repository_id) :]
+ resume_path = resume.next_path
+ logger.debug(f"Travis CI: resuming {endpoint} from repository_id={resume.repository_id}")
+
+ for index, repository_id in enumerate(remaining):
+ start_path = resume_path
+ resume_path = None # only the resumed-into repo uses the saved path; the rest start fresh
+
+ for items, next_path in _iter_collection(
+ session,
+ headers,
+ logger,
+ config.path.format(repository_id=repository_id),
+ {"limit": PAGE_SIZE, **config.extra_params},
+ config.collection_key,
+ max_pages=MAX_PAGES_PER_REPO,
+ resource=f"{endpoint} of repository {repository_id}",
+ start_path=start_path,
+ ):
+ rows, reached_watermark = _rows_for_page(endpoint, repository_id, items, watermark)
+ if rows:
+ yield rows
+ if reached_watermark:
+ # Everything further back in this repo predates the watermark — already synced.
+ break
+ if next_path:
+ resumable_source_manager.save_state(
+ TravisCIResumeConfig(next_path=next_path, repository_id=repository_id)
+ )
+
+ # Advance the bookmark to the next repo so a crash between repos resumes correctly. Its
+ # first page path is built fresh when the loop reaches it.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(
+ TravisCIResumeConfig(next_path=None, repository_id=remaining[index + 1])
+ )
+
+
+def travis_ci_source(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TravisCIResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = TRAVIS_CI_ENDPOINTS[endpoint]
+ partition_key = config.partition_key
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_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,
+ # Lists return newest-first (the API default, and we pass sort_by=id:desc explicitly on
+ # incremental endpoints), so the watermark only persists at successful job end.
+ sort_mode="desc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if partition_key else None,
+ partition_format="month" if partition_key else None,
+ partition_keys=[partition_key] if partition_key else None,
+ )