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 bitrise import source (#71166)

Tom Owers402871c8de92
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 4a9f8df8441c..7cada1d9ee7f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -87,6 +87,7 @@ the row lists both.
| bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) |
| bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ |
| bitbucket | HTTP | requests | ✅ |
+| bitrise | HTTP | requests | ✅ |
| bland_ai | HTTP | requests | ✅ |
| blogger | HTTP | requests | ✅ |
| bluetally | HTTP | requests | ✅ |
@@ -622,7 +623,6 @@ doesn't conflict with concurrent PRs.
- basecamp
- bigcommerce
- bitly
-- bitrise
- box
- braintrust
- branch
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bitrise/bitrise.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bitrise/bitrise.py
new file mode 100644
index 000000000000..a60f893b98d6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bitrise/bitrise.py
@@ -0,0 +1,353 @@
+import dataclasses
+from collections.abc import Callable, Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import quote, urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.bitrise.settings import BITRISE_ENDPOINTS
+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
+
+BITRISE_BASE_URL = "https://api.bitrise.io/v0.1"
+# Bitrise list endpoints cap `limit` at 50.
+PAGE_LIMIT = 50
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRY_ATTEMPTS = 5
+# Safety overlap subtracted from the incremental watermark: builds that were still running (or on
+# hold) at the last sync keep mutating (status, finished_at) after their trigger time, so each run
+# re-pulls a trailing window and merge dedupes the re-fetched rows on the primary key.
+INCREMENTAL_LOOKBACK = timedelta(hours=24)
+
+
+class BitriseRetryableError(Exception):
+ pass
+
+
+Fetcher = Callable[[str, dict[str, Any]], dict[str, Any]]
+
+
+class BitriseResumeConfig:
+ # Fan-out bookmark: the app currently being processed. A stable slug (not a positional index)
+ # so apps added/removed between a crash and the retry can't resume us into the wrong app.
+ # None for the top-level apps endpoint.
+ app_slug: str | None = None
+ # `next` paging anchor within the current listing. None means "start at the first page".
+ next: str | None = None
+
+
+def _get_session(api_token: str) -> requests.Session:
+ # Bitrise expects the raw token in the Authorization header (no Bearer prefix).
+ return make_tracked_session(headers={"Authorization": api_token}, redact_values=(api_token,))
+
+
+def _to_unix_timestamp(value: Any) -> int | None:
+ """Convert an incremental cursor to the Unix timestamp Bitrise's `after` filter expects."""
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return int(dt.timestamp())
+ if isinstance(value, date):
+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp())
+ if isinstance(value, int | float):
+ return int(value)
+ if isinstance(value, str):
+ try:
+ return int(datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp())
+ except ValueError:
+ return None
+ return None
+
+
+def _build_after_param(should_use_incremental_field: bool, db_incremental_field_last_value: Any) -> int | None:
+ if not should_use_incremental_field or db_incremental_field_last_value is None:
+ return None
+ timestamp = _to_unix_timestamp(db_incremental_field_last_value)
+ if timestamp is None:
+ return None
+ return max(0, timestamp - int(INCREMENTAL_LOOKBACK.total_seconds()))
+
+
+def validate_credentials(api_token: str) -> bool:
+ """Confirm the token is genuine with a cheap probe.
+
+ Personal access tokens can call /me; workspace API tokens are workspace-scoped and may not,
+ so fall back to a one-app listing before declaring the token invalid.
+ """
+ session = _get_session(api_token)
+ try:
+ response = session.get(f"{BITRISE_BASE_URL}/me", timeout=10)
+ if response.status_code == 200:
+ return True
+ response = session.get(f"{BITRISE_BASE_URL}/apps?{urlencode({'limit': 1})}", timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _make_fetcher(session: requests.Session, logger: FilteringBoundLogger) -> Fetcher:
+ @retry(
+ retry=retry_if_exception_type(
+ (
+ BitriseRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=2, max=60),
+ reraise=True,
+ )
+ def fetch(path: str, params: dict[str, Any]) -> dict[str, Any]:
+ url = f"{BITRISE_BASE_URL}{path}"
+ if params:
+ url = f"{url}?{urlencode(params)}"
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # Bitrise rate-limits per account and returns 429; back off exponentially.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise BitriseRetryableError(f"Bitrise API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # 404 is expected during fan-out (an app or build deleted mid-sync) and handled by callers.
+ log = logger.warning if response.status_code == 404 else logger.error
+ log(f"Bitrise API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ return fetch
+
+
+def _iter_pages(
+ fetch: Fetcher,
+ path: str,
+ params: dict[str, Any],
+ start_next: str | None = None,
+) -> Iterator[tuple[list[Any], str | None]]:
+ """Walk a Bitrise cursor-paginated listing, yielding (items, next_anchor) per page.
+
+ Bitrise signals more pages with a `paging.next` anchor value passed back as `?next=`;
+ the anchor is absent on the final page.
+ """
+ next_anchor = start_next
+ while True:
+ page_params = dict(params)
+ if next_anchor:
+ page_params["next"] = next_anchor
+ data = fetch(path, page_params)
+ items = data.get("data") or []
+ next_anchor = (data.get("paging") or {}).get("next")
+ yield items, next_anchor
+ if not next_anchor:
+ return
+
+
+def _list_app_slugs(fetch: Fetcher) -> list[str]:
+ return [app["slug"] for items, _ in _iter_pages(fetch, "/apps", {"limit": PAGE_LIMIT}) for app in items]
+
+
+def _resolve_fan_out_resume(
+ app_slugs: list[str],
+ resumable_source_manager: ResumableSourceManager[BitriseResumeConfig],
+ logger: FilteringBoundLogger,
+) -> tuple[list[str], str | None]:
+ """Slice the app list down to what a crashed attempt still owes.
+
+ If the bookmarked app no longer exists (deleted between runs), start over from the first app;
+ merge dedupes any re-pulled rows on the primary key.
+ """
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.app_slug is not None and resume.app_slug in app_slugs:
+ logger.debug(f"Bitrise: resuming from app_slug={resume.app_slug}, next={resume.next}")
+ return app_slugs[app_slugs.index(resume.app_slug) :], resume.next
+ return app_slugs, None
+
+
+def _get_apps_rows(
+ fetch: Fetcher,
+ resumable_source_manager: ResumableSourceManager[BitriseResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start_next = resume.next if resume else None
+
+ for items, next_anchor in _iter_pages(fetch, "/apps", {"limit": PAGE_LIMIT}, start_next):
+ if items:
+ yield items
+ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the last
+ # page rather than skipping it — merge dedupes on the primary key.
+ if next_anchor:
+ resumable_source_manager.save_state(BitriseResumeConfig(next=next_anchor))
+
+
+def _get_builds_rows(
+ fetch: Fetcher,
+ resumable_source_manager: ResumableSourceManager[BitriseResumeConfig],
+ logger: FilteringBoundLogger,
+ after: int | None,
+) -> Iterator[list[dict[str, Any]]]:
+ app_slugs = _list_app_slugs(fetch)
+ remaining, resume_next = _resolve_fan_out_resume(app_slugs, resumable_source_manager, logger)
+
+ params: dict[str, Any] = {"limit": PAGE_LIMIT, "sort_by": "created_at"}
+ if after is not None:
+ params["after"] = after
+
+ for index, app_slug in enumerate(remaining):
+ start_next = resume_next
+ resume_next = None # only the resumed-into app uses the saved anchor; the rest start fresh
+
+ try:
+ for items, next_anchor in _iter_pages(fetch, f"/apps/{quote(app_slug)}/builds", params, start_next):
+ rows = [{**build, "app_slug": app_slug} for build in items]
+ if rows:
+ yield rows
+ if next_anchor:
+ resumable_source_manager.save_state(BitriseResumeConfig(app_slug=app_slug, next=next_anchor))
+ except requests.HTTPError as exc:
+ if exc.response is not None and exc.response.status_code == 404:
+ logger.warning(f"Bitrise: app {app_slug} not found while fetching builds, skipping")
+ else:
+ raise
+
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(BitriseResumeConfig(app_slug=remaining[index + 1], next=None))
+
+
+def _get_workflows_rows(
+ fetch: Fetcher,
+ resumable_source_manager: ResumableSourceManager[BitriseResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ app_slugs = _list_app_slugs(fetch)
+ remaining, _ = _resolve_fan_out_resume(app_slugs, resumable_source_manager, logger)
+
+ for index, app_slug in enumerate(remaining):
+ try:
+ # build-workflows returns bare workflow name strings, not objects; no pagination.
+ data = fetch(f"/apps/{quote(app_slug)}/build-workflows", {})
+ rows = [{"app_slug": app_slug, "workflow": name} for name in data.get("data") or []]
+ if rows:
+ yield rows
+ except requests.HTTPError as exc:
+ if exc.response is not None and exc.response.status_code == 404:
+ logger.warning(f"Bitrise: app {app_slug} not found while fetching workflows, skipping")
+ else:
+ raise
+
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(BitriseResumeConfig(app_slug=remaining[index + 1], next=None))
+
+
+def _get_artifacts_rows(
+ fetch: Fetcher,
+ resumable_source_manager: ResumableSourceManager[BitriseResumeConfig],
+ logger: FilteringBoundLogger,
+ after: int | None,
+) -> Iterator[list[dict[str, Any]]]:
+ """Two-level fan-out: apps -> builds -> per-build artifact listings.
+
+ The incremental filter applies at the parent builds level (`after` on trigger time), and each
+ artifact row carries `build_triggered_at` so the pipeline can watermark on it. Resume state is
+ kept at app granularity only: a resumed attempt restarts the bookmarked app's builds and merge
+ dedupes the re-pulled artifacts.
+ """
+ app_slugs = _list_app_slugs(fetch)
+ remaining, _ = _resolve_fan_out_resume(app_slugs, resumable_source_manager, logger)
+
+ build_params: dict[str, Any] = {"limit": PAGE_LIMIT, "sort_by": "created_at"}
+ if after is not None:
+ build_params["after"] = after
+
+ for index, app_slug in enumerate(remaining):
+ try:
+ for build_items, _ in _iter_pages(fetch, f"/apps/{quote(app_slug)}/builds", build_params):
+ for build in build_items:
+ build_slug = build["slug"]
+ for items, _ in _iter_pages(
+ fetch, f"/apps/{quote(app_slug)}/builds/{quote(build_slug)}/artifacts", {"limit": PAGE_LIMIT}
+ ):
+ rows = [
+ {
+ **artifact,
+ "app_slug": app_slug,
+ "build_slug": build_slug,
+ "build_triggered_at": build.get("triggered_at"),
+ }
+ for artifact in items
+ ]
+ if rows:
+ yield rows
+ except requests.HTTPError as exc:
+ if exc.response is not None and exc.response.status_code == 404:
+ logger.warning(f"Bitrise: app {app_slug} not found while fetching artifacts, skipping")
+ else:
+ raise
+
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(BitriseResumeConfig(app_slug=remaining[index + 1], next=None))
+
+
+def get_rows(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BitriseResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ # One session reused across every page (and every app in a fan-out) so urllib3 keeps the
+ # connection alive instead of re-handshaking per request.
+ session = _get_session(api_token)
+ fetch = _make_fetcher(session, logger)
+
+ after = _build_after_param(should_use_incremental_field, db_incremental_field_last_value)
+
+ if endpoint == "apps":
+ yield from _get_apps_rows(fetch, resumable_source_manager)
+ elif endpoint == "builds":
+ yield from _get_builds_rows(fetch, resumable_source_manager, logger, after)
+ elif endpoint == "workflows":
+ yield from _get_workflows_rows(fetch, resumable_source_manager, logger)
+ elif endpoint == "artifacts":
+ yield from _get_artifacts_rows(fetch, resumable_source_manager, logger, after)
+ else:
+ raise ValueError(f"Unknown Bitrise endpoint: {endpoint}")
+
+
+def bitrise_source(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BitriseResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ endpoint_config = BITRISE_ENDPOINTS[endpoint]
+
+ 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=endpoint_config.primary_keys,
+ # Bitrise returns builds newest-first and the fan-out walks app by app, so rows never
+ # arrive in ascending timestamp order. desc mode persists the incremental watermark only
+ # at successful job end, which is the only safe point for a fan-out stream.
+ sort_mode="desc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="week" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bitrise/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bitrise/canonical_descriptions.py
new file mode 100644
index 000000000000..1bc8576c54e1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bitrise/canonical_descriptions.py
@@ -0,0 +1,77 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "apps": {
+ "description": "An app registered on Bitrise, tying a source code repository to its CI configuration.",
+ "docs_url": "https://api-docs.bitrise.io/#/application",
+ "columns": {
+ "slug": "Unique identifier of the app.",
+ "title": "Display name of the app.",
+ "project_type": "Detected project type (e.g. ios, android, react-native, flutter).",
+ "provider": "Git hosting provider of the connected repository (e.g. github, gitlab, bitbucket).",
+ "repo_owner": "Owner (user or organization) of the connected repository.",
+ "repo_slug": "Name of the connected repository.",
+ "repo_url": "URL of the connected repository.",
+ "is_disabled": "Whether the app is disabled on Bitrise.",
+ "status": "Status of the app's most recent build (1 success, 0 not finished, -1 failed).",
+ "is_public": "Whether the app's build results are publicly visible.",
+ "owner": "The account (user or organization) that owns the app, with account_type, name, and slug.",
+ "avatar_url": "URL of the app's avatar image.",
+ },
+ },
+ "builds": {
+ "description": "A single CI build run of an app, with its status, timing, and trigger metadata. "
+ "Bitrise only returns builds from roughly the last 200 days.",
+ "docs_url": "https://api-docs.bitrise.io/#/builds",
+ "columns": {
+ "app_slug": "Identifier of the app the build belongs to (added by PostHog during sync).",
+ "slug": "Unique identifier of the build.",
+ "build_number": "Sequential build number within the app.",
+ "status": "Numeric build status (0 running, 1 successful, 2 failed, 3 aborted with failure, 4 aborted with success).",
+ "status_text": "Human-readable build status (e.g. success, error, aborted).",
+ "abort_reason": "Reason the build was aborted, if it was.",
+ "branch": "Git branch the build ran on.",
+ "tag": "Git tag that triggered the build, if any.",
+ "commit_hash": "Hash of the commit the build ran against.",
+ "commit_message": "Message of the commit the build ran against.",
+ "commit_view_url": "URL to view the commit on the git provider.",
+ "triggered_workflow": "Name of the Bitrise workflow the build ran.",
+ "triggered_by": "What triggered the build (e.g. webhook, manual).",
+ "triggered_at": "When the build was triggered.",
+ "started_on_worker_at": "When the build started on a worker machine.",
+ "environment_prepare_finished_at": "When the build environment finished preparing.",
+ "finished_at": "When the build finished.",
+ "is_on_hold": "Whether the build is queued waiting for a free concurrency slot.",
+ "machine_type_id": "Identifier of the machine type the build ran on.",
+ "stack_identifier": "Identifier of the stack (build environment image) the build ran on.",
+ "pull_request_id": "Identifier of the pull request that triggered the build, if any.",
+ "pull_request_target_branch": "Target branch of the triggering pull request.",
+ "pull_request_view_url": "URL to view the triggering pull request.",
+ },
+ },
+ "workflows": {
+ "description": "A workflow defined in an app's Bitrise configuration, one row per app and workflow name.",
+ "docs_url": "https://api-docs.bitrise.io/#/builds",
+ "columns": {
+ "app_slug": "Identifier of the app the workflow belongs to (added by PostHog during sync).",
+ "workflow": "Name of the workflow.",
+ },
+ },
+ "artifacts": {
+ "description": "A file produced by a build (e.g. an IPA, APK, or log archive).",
+ "docs_url": "https://api-docs.bitrise.io/#/build-artifact",
+ "columns": {
+ "app_slug": "Identifier of the app the artifact belongs to (added by PostHog during sync).",
+ "build_slug": "Identifier of the build that produced the artifact (added by PostHog during sync).",
+ "build_triggered_at": "When the build that produced the artifact was triggered (added by PostHog during sync).",
+ "slug": "Unique identifier of the artifact within its build.",
+ "title": "File name of the artifact.",
+ "artifact_type": "Type of the artifact (e.g. android-apk, ios-ipa, file).",
+ "artifact_meta": "Type-specific metadata of the artifact.",
+ "file_size_bytes": "Size of the artifact file in bytes.",
+ "is_public_page_enabled": "Whether a public install page is enabled for the artifact.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bitrise/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bitrise/settings.py
new file mode 100644
index 000000000000..60f5fdcba8d7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bitrise/settings.py
@@ -0,0 +1,65 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class BitriseEndpointConfig:
+ name: str
+ primary_keys: list[str] = field(default_factory=lambda: ["slug"])
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable datetime field to partition on (trigger time never changes once a build exists).
+ partition_key: str | None = None
+ should_sync_default: bool = True
+
+
+# Bitrise's builds endpoint accepts a server-side `after` Unix-timestamp filter (builds run after
+# the given time), which gives an honest incremental sync on `triggered_at`. Artifacts inherit
+# that filter through their parent build fan-out, keyed on the injected `build_triggered_at`.
+# Apps and workflows are small listings with no server-side time filter, so they stay full refresh.
+BITRISE_ENDPOINTS: dict[str, BitriseEndpointConfig] = {
+ "apps": BitriseEndpointConfig(
+ name="apps",
+ ),
+ "builds": BitriseEndpointConfig(
+ name="builds",
+ # Build slugs look globally unique but Bitrise doesn't document that scope, so keep the
+ # app linkage in the key.
+ primary_keys=["app_slug", "slug"],
+ partition_key="triggered_at",
+ incremental_fields=[
+ {
+ "label": "triggered_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "triggered_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "workflows": BitriseEndpointConfig(
+ name="workflows",
+ # The build-workflows endpoint returns bare workflow names, unique per app only.
+ primary_keys=["app_slug", "workflow"],
+ ),
+ "artifacts": BitriseEndpointConfig(
+ name="artifacts",
+ # Artifact slugs are only unique within their build.
+ primary_keys=["app_slug", "build_slug", "slug"],
+ partition_key="build_triggered_at",
+ should_sync_default=False,
+ incremental_fields=[
+ {
+ "label": "build_triggered_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "build_triggered_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+}
+
+ENDPOINTS = tuple(BITRISE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in BITRISE_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bitrise/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bitrise/source.py
index 07b611f4628d..bd9468f2e4dd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bitrise/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bitrise/source.py
@@ -1,19 +1,43 @@
-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.bitrise.bitrise import (
+ BitriseResumeConfig,
+ bitrise_source,
+ validate_credentials as validate_bitrise_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bitrise.settings import (
+ BITRISE_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import BitriseSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class BitriseSource(SimpleSource[BitriseSourceConfig]):
+class BitriseSource(ResumableSource[BitriseSourceConfig, BitriseResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BITRISE
@@ -24,7 +48,107 @@ class BitriseSource(SimpleSource[BitriseSourceConfig]):
name=SchemaExternalDataSourceType.BITRISE,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Bitrise",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Bitrise API token to pull your CI build data into the PostHog Data warehouse.
+
+You can create a personal access token in your [Bitrise security settings](https://app.bitrise.io/me/account/security), or use a workspace API token from your workspace settings.
+""",
iconPath="/static/services/bitrise.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/bitrise",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.bitrise.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked Bitrise token surfaces as a requests HTTPError when the fetcher
+ # calls `raise_for_status()`. Retrying can never satisfy a credential problem, so stop
+ # the sync. Match the stable status text and base host, not the per-request path.
+ "401 Client Error: Unauthorized for url: https://api.bitrise.io": "Your Bitrise API token is invalid or has been revoked. Create a new token in your Bitrise security settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.bitrise.io": "Your Bitrise API token does not have access to this data. Check the token's scope in Bitrise, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: BitriseSourceConfig,
+ 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 == "builds":
+ return "The Bitrise API only returns builds from roughly the last 200 days"
+ if endpoint == "artifacts":
+ return (
+ "Fetches artifacts for every build, one request per build. "
+ "Disabled by default because of the API cost"
+ )
+ return None
+
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = BITRISE_ENDPOINTS[endpoint]
+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=has_incremental,
+ # Builds mutate after creation (status, finished_at) and incremental runs re-pull
+ # a lookback window, so merge is the only safe write mode — append would
+ # materialize the re-pulled rows as duplicates.
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.should_sync_default,
+ description=_description(endpoint),
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: BitriseSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_bitrise_credentials(config.api_token):
+ return True, None
+
+ return False, "Invalid Bitrise API token"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BitriseResumeConfig]:
+ return ResumableSourceManager[BitriseResumeConfig](inputs, BitriseResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: BitriseSourceConfig,
+ resumable_source_manager: ResumableSourceManager[BitriseResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return bitrise_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/bitrise/tests/test_bitrise.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bitrise/tests/test_bitrise.py
new file mode 100644
index 000000000000..1fa762f52501
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bitrise/tests/test_bitrise.py
@@ -0,0 +1,350 @@
+from datetime import UTC, date, datetime
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bitrise.bitrise import (
+ INCREMENTAL_LOOKBACK,
+ BitriseResumeConfig,
+ _build_after_param,
+ _to_unix_timestamp,
+ bitrise_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bitrise.settings import (
+ BITRISE_ENDPOINTS,
+ ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+TRACKED_SESSION = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bitrise.bitrise.make_tracked_session"
+)
+
+
+def _response(body: dict[str, Any], status_code: int = 200) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = body
+ resp.status_code = status_code
+ resp.ok = status_code < 400
+ return resp
+
+
+class FakeResumableManager(ResumableSourceManager[BitriseResumeConfig]):
+ def __init__(self, state: BitriseResumeConfig | None = None):
+ self._state = state
+ self.saved: list[BitriseResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> BitriseResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: BitriseResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestToUnixTimestamp:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), 1767323045),
+ (datetime(2026, 1, 2, 3, 4, 5), 1767323045),
+ (date(2026, 1, 2), 1767312000),
+ ("2026-01-02T03:04:05Z", 1767323045),
+ ("2026-01-02T03:04:05+00:00", 1767323045),
+ (1767323045, 1767323045),
+ ("not-a-date", None),
+ ],
+ )
+ def test_conversion(self, value, expected):
+ assert _to_unix_timestamp(value) == expected
+
+
+class TestBuildAfterParam:
+ def test_subtracts_lookback_from_watermark(self):
+ watermark = datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC)
+ after = _build_after_param(True, watermark)
+ assert after == 1767323045 - int(INCREMENTAL_LOOKBACK.total_seconds())
+
+ @pytest.mark.parametrize(
+ "should_use_incremental_field, last_value",
+ [
+ (False, datetime(2026, 1, 2, tzinfo=UTC)),
+ (True, None),
+ (True, "garbage"),
+ ],
+ )
+ def test_no_filter_when_not_incremental(self, should_use_incremental_field, last_value):
+ assert _build_after_param(should_use_incremental_field, last_value) is None
+
+
+class TestValidateCredentials:
+ @mock.patch(TRACKED_SESSION)
+ def test_valid_personal_access_token(self, mock_session):
+ mock_session.return_value.get.return_value = _response({"data": {}})
+ assert validate_credentials("token") is True
+ # /me succeeded, no fallback probe needed.
+ assert mock_session.return_value.get.call_count == 1
+
+ @mock.patch(TRACKED_SESSION)
+ def test_workspace_token_falls_back_to_apps_probe(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response({"message": "Unauthorized"}, status_code=401),
+ _response({"data": []}),
+ ]
+ assert validate_credentials("workspace-token") is True
+
+ @mock.patch(TRACKED_SESSION)
+ def test_invalid_token(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response({"message": "Unauthorized"}, status_code=401),
+ _response({"message": "Unauthorized"}, status_code=401),
+ ]
+ assert validate_credentials("bad") is False
+
+ @mock.patch(TRACKED_SESSION)
+ def test_swallows_exceptions(self, mock_session):
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("token") is False
+
+
+class TestGetRowsApps:
+ @mock.patch(TRACKED_SESSION)
+ def test_paginates_via_next_anchor_and_saves_state(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response({"data": [{"slug": "app1"}], "paging": {"next": "anchor1"}}),
+ _response({"data": [{"slug": "app2"}], "paging": {}}),
+ ]
+ manager = FakeResumableManager()
+
+ batches = list(get_rows("token", "apps", mock.MagicMock(), manager))
+
+ assert [item["slug"] for batch in batches for item in batch] == ["app1", "app2"]
+ second_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert parse_qs(urlparse(second_url).query)["next"] == ["anchor1"]
+ # State saved once, after the first page yielded and only while more pages remain.
+ assert [saved.next for saved in manager.saved] == ["anchor1"]
+
+ @mock.patch(TRACKED_SESSION)
+ def test_resumes_from_saved_anchor(self, mock_session):
+ mock_session.return_value.get.return_value = _response({"data": [{"slug": "app3"}], "paging": {}})
+ manager = FakeResumableManager(state=BitriseResumeConfig(next="anchor2"))
+
+ batches = list(get_rows("token", "apps", mock.MagicMock(), manager))
+
+ assert [item["slug"] for batch in batches for item in batch] == ["app3"]
+ first_url = mock_session.return_value.get.call_args_list[0].args[0]
+ assert parse_qs(urlparse(first_url).query)["next"] == ["anchor2"]
+
+
+class TestGetRowsBuilds:
+ @mock.patch(TRACKED_SESSION)
+ def test_fans_out_over_apps_and_injects_app_slug(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response({"data": [{"slug": "app1"}, {"slug": "app2"}], "paging": {}}),
+ _response({"data": [{"slug": "b1", "triggered_at": "2026-01-01T00:00:00Z"}], "paging": {}}),
+ _response({"data": [{"slug": "b2", "triggered_at": "2026-01-02T00:00:00Z"}], "paging": {}}),
+ ]
+
+ batches = list(get_rows("token", "builds", mock.MagicMock(), FakeResumableManager()))
+
+ flat = [item for batch in batches for item in batch]
+ assert [(b["slug"], b["app_slug"]) for b in flat] == [("b1", "app1"), ("b2", "app2")]
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert urlparse(urls[1]).path == "/v0.1/apps/app1/builds"
+ assert urlparse(urls[2]).path == "/v0.1/apps/app2/builds"
+ assert parse_qs(urlparse(urls[1]).query)["sort_by"] == ["created_at"]
+
+ @mock.patch(TRACKED_SESSION)
+ def test_incremental_passes_after_param(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response({"data": [{"slug": "app1"}], "paging": {}}),
+ _response({"data": [], "paging": {}}),
+ ]
+
+ list(
+ get_rows(
+ "token",
+ "builds",
+ mock.MagicMock(),
+ FakeResumableManager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 2, tzinfo=UTC),
+ )
+ )
+
+ builds_url = mock_session.return_value.get.call_args_list[1].args[0]
+ after = int(parse_qs(urlparse(builds_url).query)["after"][0])
+ assert after == int(datetime(2026, 1, 2, tzinfo=UTC).timestamp()) - int(INCREMENTAL_LOOKBACK.total_seconds())
+
+ @mock.patch(TRACKED_SESSION)
+ def test_full_refresh_has_no_after_param(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response({"data": [{"slug": "app1"}], "paging": {}}),
+ _response({"data": [], "paging": {}}),
+ ]
+
+ list(get_rows("token", "builds", mock.MagicMock(), FakeResumableManager()))
+
+ builds_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert "after" not in parse_qs(urlparse(builds_url).query)
+
+ @mock.patch(TRACKED_SESSION)
+ def test_saves_bookmark_between_apps_and_page_anchor_within_app(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response({"data": [{"slug": "app1"}, {"slug": "app2"}], "paging": {}}),
+ _response({"data": [{"slug": "b1"}], "paging": {"next": "page2"}}),
+ _response({"data": [{"slug": "b2"}], "paging": {}}),
+ _response({"data": [{"slug": "b3"}], "paging": {}}),
+ ]
+ manager = FakeResumableManager()
+
+ list(get_rows("token", "builds", mock.MagicMock(), manager))
+
+ assert [(s.app_slug, s.next) for s in manager.saved] == [("app1", "page2"), ("app2", None)]
+
+ @mock.patch(TRACKED_SESSION)
+ def test_resumes_from_bookmarked_app(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response({"data": [{"slug": "app1"}, {"slug": "app2"}], "paging": {}}),
+ _response({"data": [{"slug": "b9"}], "paging": {}}),
+ ]
+ manager = FakeResumableManager(state=BitriseResumeConfig(app_slug="app2", next="page3"))
+
+ batches = list(get_rows("token", "builds", mock.MagicMock(), manager))
+
+ # app1 is skipped entirely; app2 resumes from its saved page anchor.
+ flat = [item for batch in batches for item in batch]
+ assert [(b["slug"], b["app_slug"]) for b in flat] == [("b9", "app2")]
+ builds_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert urlparse(builds_url).path == "/v0.1/apps/app2/builds"
+ assert parse_qs(urlparse(builds_url).query)["next"] == ["page3"]
+
+ @mock.patch(TRACKED_SESSION)
+ def test_stale_bookmark_restarts_from_first_app(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response({"data": [{"slug": "app1"}], "paging": {}}),
+ _response({"data": [{"slug": "b1"}], "paging": {}}),
+ ]
+ manager = FakeResumableManager(state=BitriseResumeConfig(app_slug="deleted-app", next="page9"))
+
+ batches = list(get_rows("token", "builds", mock.MagicMock(), manager))
+
+ flat = [item for batch in batches for item in batch]
+ assert [b["app_slug"] for b in flat] == ["app1"]
+ builds_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert "next" not in parse_qs(urlparse(builds_url).query)
+
+ @mock.patch(TRACKED_SESSION)
+ def test_deleted_app_404_is_skipped(self, mock_session):
+ not_found = _response({"message": "Not Found"}, status_code=404)
+ not_found.raise_for_status.side_effect = requests.HTTPError(response=not_found)
+ mock_session.return_value.get.side_effect = [
+ _response({"data": [{"slug": "app1"}, {"slug": "app2"}], "paging": {}}),
+ not_found,
+ _response({"data": [{"slug": "b2"}], "paging": {}}),
+ ]
+
+ batches = list(get_rows("token", "builds", mock.MagicMock(), FakeResumableManager()))
+
+ flat = [item for batch in batches for item in batch]
+ assert [(b["slug"], b["app_slug"]) for b in flat] == [("b2", "app2")]
+
+
+class TestGetRowsWorkflows:
+ @mock.patch(TRACKED_SESSION)
+ def test_maps_workflow_names_to_rows(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response({"data": [{"slug": "app1"}], "paging": {}}),
+ _response({"data": ["primary", "deploy"]}),
+ ]
+
+ batches = list(get_rows("token", "workflows", mock.MagicMock(), FakeResumableManager()))
+
+ flat = [item for batch in batches for item in batch]
+ assert flat == [
+ {"app_slug": "app1", "workflow": "primary"},
+ {"app_slug": "app1", "workflow": "deploy"},
+ ]
+
+
+class TestGetRowsArtifacts:
+ @mock.patch(TRACKED_SESSION)
+ def test_fans_out_over_builds_and_injects_parent_identifiers(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response({"data": [{"slug": "app1"}], "paging": {}}),
+ _response({"data": [{"slug": "b1", "triggered_at": "2026-01-01T00:00:00Z"}], "paging": {}}),
+ _response({"data": [{"slug": "art1", "title": "app.ipa"}], "paging": {}}),
+ ]
+
+ batches = list(get_rows("token", "artifacts", mock.MagicMock(), FakeResumableManager()))
+
+ flat = [item for batch in batches for item in batch]
+ assert flat == [
+ {
+ "slug": "art1",
+ "title": "app.ipa",
+ "app_slug": "app1",
+ "build_slug": "b1",
+ "build_triggered_at": "2026-01-01T00:00:00Z",
+ }
+ ]
+ artifacts_url = mock_session.return_value.get.call_args_list[2].args[0]
+ assert urlparse(artifacts_url).path == "/v0.1/apps/app1/builds/b1/artifacts"
+
+ @mock.patch(TRACKED_SESSION)
+ def test_incremental_filters_parent_builds(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response({"data": [{"slug": "app1"}], "paging": {}}),
+ _response({"data": [], "paging": {}}),
+ ]
+
+ list(
+ get_rows(
+ "token",
+ "artifacts",
+ mock.MagicMock(),
+ FakeResumableManager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 2, tzinfo=UTC),
+ )
+ )
+
+ builds_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert "after" in parse_qs(urlparse(builds_url).query)
+
+
+class TestGetRowsUnknownEndpoint:
+ @mock.patch(TRACKED_SESSION)
+ def test_raises_value_error(self, mock_session):
+ with pytest.raises(ValueError):
+ list(get_rows("token", "nope", mock.MagicMock(), FakeResumableManager()))
+
+
+class TestBitriseSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = BITRISE_ENDPOINTS[endpoint]
+ response = bitrise_source("token", endpoint, mock.MagicMock(), FakeResumableManager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ # Fan-out + newest-first ordering: the watermark must only persist at job end.
+ assert response.sort_mode == "desc"
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+
+ def test_fan_out_endpoints_have_parent_in_primary_key(self):
+ assert BITRISE_ENDPOINTS["builds"].primary_keys == ["app_slug", "slug"]
+ assert BITRISE_ENDPOINTS["workflows"].primary_keys == ["app_slug", "workflow"]
+ assert BITRISE_ENDPOINTS["artifacts"].primary_keys == ["app_slug", "build_slug", "slug"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bitrise/tests/test_bitrise_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bitrise/tests/test_bitrise_source.py
new file mode 100644
index 000000000000..45394e9a4375
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bitrise/tests/test_bitrise_source.py
@@ -0,0 +1,150 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bitrise.bitrise import BitriseResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.bitrise.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bitrise.source import BitriseSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import BitriseSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestBitriseSource:
+ def setup_method(self):
+ self.source = BitriseSource()
+ self.team_id = 123
+ self.config = BitriseSourceConfig(api_token="bitrise-token")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.BITRISE
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Bitrise"
+ assert config.label == "Bitrise"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/bitrise.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/bitrise"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_token"]
+
+ def test_api_token_field_is_secret_password(self):
+ config = self.source.get_source_config
+ token_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.secret is True
+ assert token_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.bitrise.io/v0.1/apps",
+ "403 Client Error: Forbidden for url: https://api.bitrise.io/v0.1/apps/abc123/builds",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.bitrise.io/v0.1/apps",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ incremental = {schema.name for schema in schemas if schema.supports_incremental}
+ # Only builds (and artifacts, through their parent build fan-out) can be filtered
+ # server-side via the `after` Unix-timestamp param.
+ assert incremental == {"builds", "artifacts"}
+
+ def test_incremental_schemas_advertise_their_fields(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["builds"].incremental_fields == INCREMENTAL_FIELDS["builds"]
+ assert [f["field"] for f in schemas["builds"].incremental_fields] == ["triggered_at"]
+ assert [f["field"] for f in schemas["artifacts"].incremental_fields] == ["build_triggered_at"]
+ assert schemas["apps"].incremental_fields == []
+ # Builds mutate after creation, so append mode is never offered.
+ assert all(schema.supports_append is False for schema in schemas.values())
+
+ def test_artifacts_disabled_by_default(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+ assert schemas["artifacts"].should_sync_default is False
+ assert schemas["builds"].should_sync_default is True
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["builds"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "builds"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid Bitrise API token"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bitrise.source.validate_bitrise_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(self.config.api_token)
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert manager._data_class is BitriseResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bitrise.source.bitrise_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_bitrise_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "builds"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-02T03:04:05Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_bitrise_source.assert_called_once()
+ kwargs = mock_bitrise_source.call_args.kwargs
+ assert kwargs["api_token"] == "bitrise-token"
+ assert kwargs["endpoint"] == "builds"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-02T03:04:05Z"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bitrise.source.bitrise_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_bitrise_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "builds"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-02T03:04:05Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_bitrise_source.call_args.kwargs["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 54bb5981c8d7..e89b3234bec5 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
@@ -593,7 +593,7 @@ class BitlySourceConfig(config.Config):
@config.config
class BitriseSourceConfig(config.Config):
- pass
+ api_token: str
@config.config