:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement bitbucket import source (#71200)
Tom Owersd3fcee87bc66
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 94ab80be4244..2145922fa806 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -82,6 +82,7 @@ the row lists both.| bigmailer | HTTP | requests | ✅ || bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) || bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ |+| bitbucket | HTTP | requests | ✅ || bland_ai | HTTP | requests | ✅ || blogger | HTTP | requests | ✅ || bluetally | HTTP | requests | ✅ |@@ -595,7 +596,6 @@ doesn't conflict with concurrent PRs.- basecamp- bettermode- bigcommerce-- bitbucket- bitly- bitrise- boxdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/bitbucket.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/bitbucket.pynew file mode 100644index 000000000000..336b863d989e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/bitbucket.py@@ -0,0 +1,418 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit++import requests+from dateutil import parser as dateutil_parser+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.bitbucket.settings import (+ BITBUCKET_ENDPOINTS,+ BitbucketEndpointConfig,+)+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++BITBUCKET_BASE_URL = "https://api.bitbucket.org/2.0"++REQUEST_TIMEOUT_SECONDS = 60+VALIDATION_TIMEOUT_SECONDS = 10+++class BitbucketRetryableError(Exception):+ pass+++class BitbucketResumeConfig:+ # Full URL of the next page to fetch. None means "start the current bookmark's list+ # from its first page" (the URL is built fresh when the loop reaches it).+ next_url: str | None = None+ # Fan-out bookmark: the repository slug currently being processed. A stable slug+ # (not a positional index) so repos added/removed between a crash and the retry+ # can't resume us into the wrong repo. None for top-level endpoints.+ repo_slug: str | None = None++[email protected](frozen=True)+class BitbucketAuth:+ """Either an Atlassian API token (Basic auth with the account email as username)+ or a workspace/repository access token (Bearer)."""++ email: str | None = None+ api_token: str | None = None+ access_token: str | None = None+++def _make_session(auth: BitbucketAuth) -> requests.Session:+ session = make_tracked_session()+ session.headers.update({"Accept": "application/json"})+ if auth.access_token:+ session.headers.update({"Authorization": f"Bearer {auth.access_token}"})+ else:+ session.auth = (auth.email or "", auth.api_token or "")+ return session+++def _as_utc_datetime(value: Any) -> datetime | None:+ """Coerce a cutoff/row value (datetime, date, or ISO string) to an aware UTC datetime."""+ if isinstance(value, datetime):+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ if isinstance(value, str):+ try:+ # dateutil handles Bitbucket's nanosecond fractions (e.g. pipelines'+ # "2024-05-21T01:50:36.611482242Z"), which fromisoformat may not.+ return _as_utc_datetime(dateutil_parser.parse(value))+ except (ValueError, TypeError, OverflowError):+ return None+ return None+++def _format_bbql_datetime(value: Any) -> str:+ parsed = _as_utc_datetime(value)+ if parsed is None:+ return str(value)+ return parsed.isoformat()+++def _page_predates_cutoff(items: list[dict[str, Any]], field: str, cutoff: datetime) -> bool:+ """True when every row on the page predates the cutoff — the newest-first scroll has+ walked past the watermark and can stop. Rows with a missing/unparseable timestamp+ count as not-predating, so a malformed page keeps paginating rather than truncating."""+ if not items:+ return False+ for item in items:+ value = _as_utc_datetime(item.get(field)) if isinstance(item, dict) else None+ if value is None or value > cutoff:+ return False+ return True+++def _increment_page_url(url: str, current_page: int) -> str:+ """Rebuild `url` pointing at the next page. Used instead of following the response's+ `next` URL for endpoints (pipelines) that drop the `sort` param from `next`, which+ would silently revert page 2+ to oldest-first ordering."""+ parts = urlsplit(url)+ query = [(k, v) for k, v in parse_qsl(parts.query) if k != "page"]+ query.append(("page", str(current_page + 1)))+ return urlunsplit((parts.scheme, parts.netloc, parts.path, urlencode(query), parts.fragment))+++def _ensure_bitbucket_url(url: str) -> str:+ """Refuse to fetch anything off the Bitbucket API origin. Pagination `next` URLs come+ from response bodies and are persisted in resume state, so without this pin a tampered+ response or poisoned resume state could point the credentialed session (Basic auth or+ Bearer token) at an arbitrary host and exfiltrate the customer's credentials."""+ parts = urlsplit(url)+ if parts.scheme != "https" or parts.netloc != "api.bitbucket.org":+ raise ValueError(f"Refusing to fetch non-Bitbucket URL: {url}")+ return url+++@retry(+ retry=retry_if_exception_type(+ (+ BitbucketRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ # Bitbucket enforces roughly per-hour request budgets; a generous jittered backoff+ # rides out short 429 windows without hand-rolled Retry-After parsing.+ wait=wait_exponential_jitter(initial=2, max=60),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict[str, Any]:+ response = session.get(_ensure_bitbucket_url(url), timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise BitbucketRetryableError(f"Bitbucket API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # 404s during fan-out (repo deleted mid-sync, pipelines not enabled) are handled+ # by the caller; anything else is a real failure.+ log = logger.warning if response.status_code == 404 else logger.error+ log(f"Bitbucket API error: status={response.status_code}, body={response.text[:500]}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(auth: BitbucketAuth, workspace: str) -> tuple[bool, str | None]:+ """Probe the repositories list — the scope every stream needs — to confirm the+ credentials are genuine and the workspace is reachable."""+ session = _make_session(auth)+ url = f"{BITBUCKET_BASE_URL}/repositories/{workspace}?pagelen=1"+ try:+ response = session.get(url, timeout=VALIDATION_TIMEOUT_SECONDS)+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid Bitbucket credentials. Check your email and API token (or access token) and try again."+ if response.status_code == 403:+ return (+ False,+ "Your Bitbucket token does not have repository read access. Grant the repository read scope and try again.",+ )+ if response.status_code == 404:+ return False, f"Workspace '{workspace}' not found or not accessible with these credentials."+ return False, f"Bitbucket API returned status {response.status_code}"+++def _build_initial_params(+ config: BitbucketEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> list[tuple[str, str]]:+ params: list[tuple[str, str]] = [("pagelen", str(config.page_size))]+ params.extend(config.extra_params)++ cursor_field = incremental_field or config.default_incremental_field+ if (+ config.server_filter_field+ and should_use_incremental_field+ and db_incremental_field_last_value is not None+ and cursor_field+ ):+ formatted = _format_bbql_datetime(db_incremental_field_last_value)+ params.append(("q", f'{cursor_field} > "{formatted}"'))+ # Ascending on the cursor field so new rows append past the walk instead of+ # shifting already-fetched pages.+ params.append(("sort", cursor_field))+ elif config.server_filter_field:+ # Full walk of a BBQL-capable endpoint: sort on the immutable created_on so+ # rows updated mid-walk can't reshuffle pages under the paginator.+ params.append(("sort", "created_on"))+ elif config.sort_param:+ params.append(("sort", config.sort_param))++ return params+++def _build_url(path: str, params: list[tuple[str, str]]) -> str:+ if not params:+ return f"{BITBUCKET_BASE_URL}{path}"+ return f"{BITBUCKET_BASE_URL}{path}?{urlencode(params)}"+++def _normalize_row(row: dict[str, Any], repo: dict[str, Any] | None) -> dict[str, Any]:+ if repo is None:+ return row+ # Inject the parent repo context: child rows only carry it nested (or not at all),+ # and the composite primary keys need a stable top-level column.+ return {+ **row,+ "repository_uuid": repo.get("uuid"),+ "repository_slug": repo.get("slug"),+ "repository_full_name": repo.get("full_name"),+ }+++def _normalize_member_row(row: dict[str, Any]) -> dict[str, Any]:+ user = row.get("user") or {}+ return {**row, "user_uuid": user.get("uuid"), "user_display_name": user.get("display_name")}+++def _iter_repositories(+ session: requests.Session, workspace: str, logger: FilteringBoundLogger+) -> Iterator[dict[str, Any]]:+ """Page through the workspace's repositories, oldest-first (created_on is immutable,+ so the enumeration order is stable across resume attempts)."""+ url = _build_url(f"/repositories/{workspace}", [("pagelen", "100"), ("sort", "created_on")])+ while True:+ data = _fetch_page(session, url, logger)+ yield from data.get("values", [])+ next_url = data.get("next")+ if not next_url:+ break+ url = next_url+++def _client_side_cutoff(+ config: BitbucketEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> datetime | None:+ """The watermark for endpoints without a server-side filter (commits, pipelines):+ they scroll newest-first and stop once a whole page predates this value."""+ if config.server_filter_field or not should_use_incremental_field:+ return None+ return _as_utc_datetime(db_incremental_field_last_value)+++def _get_top_level_rows(+ session: requests.Session,+ config: BitbucketEndpointConfig,+ workspace: str,+ resumable_source_manager: ResumableSourceManager[BitbucketResumeConfig],+ logger: FilteringBoundLogger,+ params: list[tuple[str, str]],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.next_url:+ url = resume.next_url+ logger.debug(f"Bitbucket: resuming {config.name} from URL: {url}")+ else:+ url = _build_url(config.path.format(workspace=workspace), params)++ is_members = config.name == "workspace_members"+ while True:+ data = _fetch_page(session, url, logger)+ items = data.get("values", [])+ next_url = data.get("next")++ if items:+ yield [_normalize_member_row(item) if is_members else item for item in 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_url:+ resumable_source_manager.save_state(BitbucketResumeConfig(next_url=next_url))++ if not next_url:+ break+ url = next_url+++def _get_fan_out_rows(+ session: requests.Session,+ config: BitbucketEndpointConfig,+ workspace: str,+ resumable_source_manager: ResumableSourceManager[BitbucketResumeConfig],+ logger: FilteringBoundLogger,+ params: list[tuple[str, str]],+ cutoff: datetime | None,+ cursor_field: str | None,+) -> Iterator[list[dict[str, Any]]]:+ repos = [repo for repo in _iter_repositories(session, workspace, logger) if repo.get("slug")]++ # Resolve the saved repo bookmark to the slice still to process. If the bookmarked+ # repo no longer exists, start over from the first repo — merge dedupes re-pulled rows.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = repos+ resume_url: str | None = None+ if resume is not None and resume.repo_slug is not None:+ slugs = [repo["slug"] for repo in repos]+ if resume.repo_slug in slugs:+ remaining = repos[slugs.index(resume.repo_slug) :]+ resume_url = resume.next_url+ logger.debug(f"Bitbucket: resuming {config.name} from repo={resume.repo_slug}, url={resume_url}")++ for index, repo in enumerate(remaining):+ url = resume_url or _build_url(config.path.format(workspace=workspace, repo_slug=repo["slug"]), params)+ resume_url = None # only the resumed-into repo uses the saved URL; the rest start fresh++ try:+ while True:+ data = _fetch_page(session, url, logger)+ items = data.get("values", [])+ next_url = data.get("next")+ if next_url and config.rebuild_page_urls:+ next_url = _increment_page_url(url, int(data.get("page") or 1))++ if cutoff is not None and cursor_field and _page_predates_cutoff(items, cursor_field, cutoff):+ # Newest-first scroll walked past the watermark: everything from here+ # back is already synced, so stop without yielding this page.+ break++ if items:+ yield [_normalize_row(item, repo) for item in items]+ if next_url:+ resumable_source_manager.save_state(+ BitbucketResumeConfig(next_url=next_url, repo_slug=repo["slug"])+ )++ if not next_url:+ break+ url = next_url+ except requests.HTTPError as exc:+ # A repo deleted between enumeration and this fetch 404s, as do the pipelines/+ # deployments endpoints on repos with Pipelines disabled. Skip the repo rather+ # than failing the whole sync; any other HTTP error is re-raised.+ if exc.response is not None and exc.response.status_code == 404:+ logger.warning(f"Bitbucket: {config.name} not available for repo {repo['slug']}, skipping")+ else:+ raise++ # Advance the bookmark to the next repo so a crash between repos resumes correctly.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(+ BitbucketResumeConfig(next_url=None, repo_slug=remaining[index + 1]["slug"])+ )+++def get_rows(+ auth: BitbucketAuth,+ workspace: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[BitbucketResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = BITBUCKET_ENDPOINTS[endpoint]+ # One session reused across every page (and, for fan-out, every repo) so urllib3+ # keeps the connection alive instead of re-handshaking per request.+ session = _make_session(auth)+ params = _build_initial_params(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )++ if config.fan_out_over_repos:+ cutoff = _client_side_cutoff(config, should_use_incremental_field, db_incremental_field_last_value)+ cursor_field = incremental_field or config.default_incremental_field+ yield from _get_fan_out_rows(+ session, config, workspace, resumable_source_manager, logger, params, cutoff, cursor_field+ )+ else:+ yield from _get_top_level_rows(session, config, workspace, resumable_source_manager, logger, params)+++def bitbucket_source(+ auth: BitbucketAuth,+ workspace: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[BitbucketResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = BITBUCKET_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ auth=auth,+ workspace=workspace,+ 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,+ incremental_field=incremental_field,+ ),+ primary_keys=endpoint_config.primary_keys,+ # Fan-out runs interleave repos (each newest-first), so rows aren't globally+ # ascending — desc defers the incremental watermark to successful job end (max+ # seen), instead of checkpointing per batch as asc would. Top-level endpoints+ # request an ascending server sort, so asc checkpointing is safe there.+ sort_mode="desc" if endpoint_config.fan_out_over_repos else "asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" 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/bitbucket/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/canonical_descriptions.pynew file mode 100644index 000000000000..79a8490d1bb1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/canonical_descriptions.py@@ -0,0 +1,114 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "repositories": {+ "description": "A git repository in the Bitbucket Cloud workspace.",+ "docs_url": "https://developer.atlassian.com/cloud/bitbucket/rest/api-group-repositories/#api-repositories-workspace-get",+ "columns": {+ "uuid": "The repository's immutable, globally unique identifier (a braced UUID).",+ "name": "The display name of the repository.",+ "full_name": "The workspace and repository slugs joined with a slash (e.g. workspace/repo).",+ "slug": "The URL-safe repository slug within the workspace.",+ "description": "The repository description.",+ "is_private": "Whether the repository is private.",+ "fork_policy": "Controls the ability to fork the repository: allow_forks, no_public_forks, or no_forks.",+ "language": "The main programming language, as set on the repository.",+ "created_on": "When the repository was created.",+ "updated_on": "When the repository was last updated (pushes, settings changes, etc.).",+ "size": "The size of the repository in bytes.",+ "mainbranch": "The repository's main branch object (name and type).",+ "owner": "The account (workspace or user) that owns the repository.",+ "project": "The Bitbucket project the repository belongs to.",+ "website": "The website URL associated with the repository.",+ "has_issues": "Whether the (deprecated) Bitbucket issue tracker is enabled.",+ "has_wiki": "Whether the repository wiki is enabled.",+ },+ },+ "pull_requests": {+ "description": "A pull request in any repository of the workspace, in any state (open, merged, declined, or superseded).",+ "docs_url": "https://developer.atlassian.com/cloud/bitbucket/rest/api-group-pullrequests/#api-repositories-workspace-repo-slug-pullrequests-get",+ "columns": {+ "id": "The pull request's numeric id, unique only within its repository.",+ "repository_uuid": "UUID of the repository the pull request belongs to (injected by PostHog; part of the primary key).",+ "repository_slug": "Slug of the repository the pull request belongs to (injected by PostHog).",+ "repository_full_name": "workspace/repo of the repository the pull request belongs to (injected by PostHog).",+ "title": "The title of the pull request.",+ "description": "The description of the pull request.",+ "state": "The pull request state: OPEN, MERGED, DECLINED, or SUPERSEDED.",+ "draft": "Whether the pull request is a draft.",+ "author": "The account that created the pull request.",+ "source": "The source branch, commit, and repository of the pull request.",+ "destination": "The destination branch, commit, and repository of the pull request.",+ "merge_commit": "The commit that merged the pull request, when merged.",+ "closed_by": "The account that merged or declined the pull request.",+ "reason": "The reason the pull request was declined, when declined.",+ "comment_count": "Number of comments on the pull request.",+ "task_count": "Number of tasks on the pull request.",+ "close_source_branch": "Whether the source branch is deleted on merge.",+ "created_on": "When the pull request was created.",+ "updated_on": "When the pull request was last updated (commits, comments, state changes).",+ },+ },+ "commits": {+ "description": "A commit reachable from any branch of any repository in the workspace, newest-first in topological order.",+ "docs_url": "https://developer.atlassian.com/cloud/bitbucket/rest/api-group-commits/#api-repositories-workspace-repo-slug-commits-get",+ "columns": {+ "hash": "The commit's SHA-1 hash, unique within its repository.",+ "repository_uuid": "UUID of the repository the commit was fetched from (injected by PostHog; part of the primary key).",+ "repository_slug": "Slug of the repository the commit was fetched from (injected by PostHog).",+ "repository_full_name": "workspace/repo of the repository the commit was fetched from (injected by PostHog).",+ "date": "The author timestamp of the commit.",+ "message": "The full commit message.",+ "author": "The commit's author, both the raw git signature and the linked Bitbucket user when resolvable.",+ "parents": "The parent commit(s) of this commit.",+ "summary": "The rendered commit message summary.",+ },+ },+ "pipelines": {+ "description": "A Bitbucket Pipelines run (CI/CD build) in any repository of the workspace.",+ "docs_url": "https://developer.atlassian.com/cloud/bitbucket/rest/api-group-pipelines/#api-repositories-workspace-repo-slug-pipelines-get",+ "columns": {+ "uuid": "The pipeline run's globally unique identifier (a braced UUID).",+ "repository_uuid": "UUID of the repository the pipeline ran in (injected by PostHog).",+ "repository_slug": "Slug of the repository the pipeline ran in (injected by PostHog).",+ "repository_full_name": "workspace/repo of the repository the pipeline ran in (injected by PostHog).",+ "build_number": "The run's sequential build number within its repository.",+ "state": "The pipeline state object, including status (e.g. PENDING, IN_PROGRESS, COMPLETED) and result (e.g. SUCCESSFUL, FAILED, STOPPED).",+ "target": "What the pipeline ran against: ref type/name, commit, and selector.",+ "trigger": "What started the pipeline (push, manual, schedule).",+ "creator": "The account that triggered the pipeline, when applicable.",+ "created_on": "When the pipeline run was created.",+ "completed_on": "When the pipeline run finished.",+ "build_seconds_used": "Build minutes consumed by the run, in seconds.",+ "duration_in_seconds": "Wall-clock duration of the run in seconds.",+ "first_successful": "Whether this was the first successful run for its target.",+ "expired": "Whether the run's logs and artifacts have expired.",+ },+ },+ "deployments": {+ "description": "A deployment of a pipeline release to an environment, in any repository of the workspace.",+ "docs_url": "https://developer.atlassian.com/cloud/bitbucket/rest/api-group-deployments/#api-repositories-workspace-repo-slug-deployments-get",+ "columns": {+ "uuid": "The deployment's globally unique identifier (a braced UUID).",+ "repository_uuid": "UUID of the repository the deployment belongs to (injected by PostHog).",+ "repository_slug": "Slug of the repository the deployment belongs to (injected by PostHog).",+ "repository_full_name": "workspace/repo of the repository the deployment belongs to (injected by PostHog).",+ "state": "The deployment state, including its name (e.g. COMPLETED) and start/completion timestamps.",+ "environment": "The environment the release was deployed to.",+ "release": "The release that was deployed, including the pipeline and commit it was built from.",+ "step": "The pipeline step that performed the deployment.",+ },+ },+ "workspace_members": {+ "description": "A user's membership in the Bitbucket Cloud workspace.",+ "docs_url": "https://developer.atlassian.com/cloud/bitbucket/rest/api-group-workspaces/#api-workspaces-workspace-members-get",+ "columns": {+ "user_uuid": "The member's user UUID (injected by PostHog from the nested user object; primary key).",+ "user_display_name": "The member's display name (injected by PostHog from the nested user object).",+ "user": "The member's user account object.",+ "workspace": "The workspace the membership belongs to.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/settings.pynew file mode 100644index 000000000000..4f61c161de5a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/settings.py@@ -0,0 +1,155 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++_UPDATED_ON_CREATED_ON: list[IncrementalField] = [+ {+ "label": "updated_on",+ "type": IncrementalFieldType.DateTime,+ "field": "updated_on",+ "field_type": IncrementalFieldType.DateTime,+ },+ {+ "label": "created_on",+ "type": IncrementalFieldType.DateTime,+ "field": "created_on",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++@dataclass+class BitbucketEndpointConfig:+ name: str+ path: str # Path template with {workspace} and, for fan-out endpoints, {repo_slug}+ incremental_fields: list[IncrementalField]+ default_incremental_field: Optional[str] = None+ partition_key: Optional[str] = None+ # Bitbucket's default pagelen is 10; most collections cap at 100 but the pull+ # requests list rejects anything above 50 with "Invalid pagelen".+ page_size: int = 100+ primary_keys: list[str] = field(default_factory=lambda: ["uuid"])+ # Fan-out: fetched once per repository in the workspace, with {repo_slug}+ # substituted into the path and repository context injected into each row.+ fan_out_over_repos: bool = False+ # BBQL field for a server-side incremental filter (`q=<field> > "<ts>"`), verified+ # to actually filter (a future-date probe returns 0 rows). None = the endpoint+ # silently ignores `q` (commits, pipelines); incremental sync instead scrolls+ # newest-first and stops client-side once a whole page predates the watermark.+ server_filter_field: Optional[str] = None+ # Value for the `sort` param, or None when the endpoint has a fixed order+ # (commits are always newest-first and ignore sort).+ sort_param: Optional[str] = None+ # Repeated params are legal in Bitbucket's API (e.g. one `state` per PR state),+ # so extra params are (key, value) pairs rather than a dict.+ extra_params: list[tuple[str, str]] = field(default_factory=list)+ should_sync_default: bool = True+ # The pipelines endpoint drops `sort` from the `next` URL it returns, silently+ # reverting page 2+ to oldest-first. Endpoints with this flag paginate by+ # incrementing the `page` param on the original URL instead of following `next`.+ rebuild_page_urls: bool = False+++BITBUCKET_ENDPOINTS: dict[str, BitbucketEndpointConfig] = {+ "repositories": BitbucketEndpointConfig(+ name="repositories",+ path="/repositories/{workspace}",+ partition_key="created_on",+ incremental_fields=_UPDATED_ON_CREATED_ON,+ default_incremental_field="updated_on",+ server_filter_field="updated_on",+ sort_param="updated_on",+ primary_keys=["uuid"],+ ),+ "pull_requests": BitbucketEndpointConfig(+ name="pull_requests",+ path="/repositories/{workspace}/{repo_slug}/pullrequests",+ partition_key="created_on",+ incremental_fields=_UPDATED_ON_CREATED_ON,+ default_incremental_field="updated_on",+ server_filter_field="updated_on",+ sort_param="updated_on",+ page_size=50, # PR list rejects pagelen > 50+ fan_out_over_repos=True,+ # PR ids restart at 1 in every repo, so the parent uuid is required for a+ # table-wide unique key.+ primary_keys=["repository_uuid", "id"],+ # The endpoint defaults to OPEN only; ask for every state explicitly.+ extra_params=[+ ("state", "OPEN"),+ ("state", "MERGED"),+ ("state", "DECLINED"),+ ("state", "SUPERSEDED"),+ ],+ ),+ "commits": BitbucketEndpointConfig(+ name="commits",+ path="/repositories/{workspace}/{repo_slug}/commits",+ partition_key="date",+ # No server-side time filter (the API accepts `q` but ignores it) and the list+ # is always newest-first in topological order, so incremental sync scrolls from+ # the newest commit and stops once an entire page predates the watermark.+ # Topological order means dates aren't strictly monotonic, so an old-dated merge+ # commit surfacing late can be missed — same trade-off as the GitHub source.+ incremental_fields=[+ {+ "label": "date",+ "type": IncrementalFieldType.DateTime,+ "field": "date",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ default_incremental_field="date",+ fan_out_over_repos=True,+ # The same commit hash exists in every fork within the workspace, so the+ # repo uuid keeps the key unique table-wide.+ primary_keys=["repository_uuid", "hash"],+ ),+ "pipelines": BitbucketEndpointConfig(+ name="pipelines",+ path="/repositories/{workspace}/{repo_slug}/pipelines/",+ partition_key="created_on",+ # Pipelines ignore `q` too, but honor `sort`; scroll newest-first and stop+ # client-side at the watermark, like commits.+ incremental_fields=[+ {+ "label": "created_on",+ "type": IncrementalFieldType.DateTime,+ "field": "created_on",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ default_incremental_field="created_on",+ sort_param="-created_on",+ fan_out_over_repos=True,+ # Pipeline uuids are real UUIDs (globally unique), so no composite key is+ # needed even though this is a fan-out child.+ primary_keys=["uuid"],+ rebuild_page_urls=True,+ ),+ "deployments": BitbucketEndpointConfig(+ name="deployments",+ path="/repositories/{workspace}/{repo_slug}/deployments/",+ # No verified server-side filter or stable sort for deployments, so full+ # refresh only (volume is bounded by actual deploy count per repo).+ incremental_fields=[],+ fan_out_over_repos=True,+ primary_keys=["uuid"],+ ),+ "workspace_members": BitbucketEndpointConfig(+ name="workspace_members",+ path="/workspaces/{workspace}/members",+ # Membership objects carry no timestamps; full refresh only (tiny volume).+ incremental_fields=[],+ # Membership rows have no top-level id; the transport injects `user_uuid`+ # from the nested user object.+ primary_keys=["user_uuid"],+ ),+}++ENDPOINTS = tuple(BITBUCKET_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in BITBUCKET_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/source.pyindex fa81e7b25cfe..9316261de12d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/source.py@@ -1,30 +1,220 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.bitbucket.bitbucket import (+ BitbucketAuth,+ BitbucketResumeConfig,+ bitbucket_source,+ validate_credentials as validate_bitbucket_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.bitbucket.settings import (+ BITBUCKET_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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import BitbucketSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class BitbucketSource(SimpleSource[BitbucketSourceConfig]):+class BitbucketSource(ResumableSource[BitbucketSourceConfig, BitbucketResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.BITBUCKET+ @property+ def connection_host_fields(self) -> list[str]:+ # The stored token is sent to api.bitbucket.org/2.0/.../<workspace>, so retargeting+ # the workspace must force re-entry of the secret.+ return ["workspace"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.BITBUCKET,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Atlassian Bitbucket Cloud",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["atlassian", "git", "ci"],+ caption="""Connect your Bitbucket Cloud workspace to sync repositories, pull requests, commits, pipelines, and more.++Your credentials need the **repository**, **pullrequest**, **pipeline**, and **account** read scopes. Avoid app passwords — Atlassian is retiring them; use an API token or an access token instead.""",iconPath="/static/services/bitbucket.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/bitbucket",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="workspace",+ label="Workspace",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="my-workspace",+ caption="Your workspace ID — the part after `bitbucket.org/` in your workspace URL.",+ secret=False,+ ),+ SourceFieldSelectConfig(+ name="auth_method",+ label="Authentication type",+ required=True,+ defaultValue="api_token",+ options=[+ SourceFieldSelectConfigOption(+ label="Atlassian API token",+ value="api_token",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="email",+ label="Atlassian account email",+ type=SourceFieldInputConfigType.EMAIL,+ required=False,+ placeholder="[email protected]",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ caption="Create an API token with scopes in your [Atlassian account settings](https://id.atlassian.com/manage-profile/security/api-tokens).",+ secret=True,+ ),+ ],+ ),+ ),+ SourceFieldSelectConfigOption(+ label="Access token",+ value="access_token",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="access_token",+ label="Access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ caption="A workspace, project, or repository access token created in your Bitbucket settings.",+ secret=True,+ ),+ ],+ ),+ ),+ ],+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.bitbucket.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.bitbucket.org": "Your Bitbucket credentials are invalid or have been revoked. Check your email and API token (or access token), then reconnect.",+ "403 Client Error: Forbidden for url: https://api.bitbucket.org": "Your Bitbucket token is missing a read scope needed to sync this data. Grant the repository, pullrequest, pipeline, and account read scopes, then reconnect.",+ # Off-origin pagination/resume URL rejected by the transport's origin pin —+ # deterministic until the bad resume state expires, so don't retry into it.+ "Refusing to fetch non-Bitbucket URL": "Bitbucket returned an unexpected pagination URL. Please retry the sync; if the problem persists, contact support.",+ # Deterministic config errors from _get_auth — retrying can't fix them.+ "Missing Bitbucket access token": "No Bitbucket access token is configured. Please update the source configuration.",+ "Missing Atlassian account email or API token": "The Atlassian account email or API token is missing. Please update the source configuration.",+ }++ def _get_auth(self, config: BitbucketSourceConfig) -> BitbucketAuth:+ if config.auth_method.selection == "access_token":+ if not config.auth_method.access_token:+ raise ValueError("Missing Bitbucket access token")+ return BitbucketAuth(access_token=config.auth_method.access_token)++ if not config.auth_method.email or not config.auth_method.api_token:+ raise ValueError("Missing Atlassian account email or API token")+ return BitbucketAuth(email=config.auth_method.email, api_token=config.auth_method.api_token)++ def get_schemas(+ self,+ config: BitbucketSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = BITBUCKET_ENDPOINTS[endpoint]+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: BitbucketSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ auth = self._get_auth(config)+ except ValueError as e:+ raw = str(e)+ friendly = self.get_non_retryable_errors().get(raw)+ return False, friendly or raw+ return validate_bitbucket_credentials(auth, config.workspace)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BitbucketResumeConfig]:+ return ResumableSourceManager[BitbucketResumeConfig](inputs, BitbucketResumeConfig)++ def source_for_pipeline(+ self,+ config: BitbucketSourceConfig,+ resumable_source_manager: ResumableSourceManager[BitbucketResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return bitbucket_source(+ auth=self._get_auth(config),+ workspace=config.workspace,+ 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,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/tests/test_bitbucket.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/tests/test_bitbucket.pynew file mode 100644index 000000000000..e6f23a9392fc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/tests/test_bitbucket.py@@ -0,0 +1,389 @@+from datetime import UTC, datetime+from typing import Any+from urllib.parse import parse_qsl, urlsplit++import pytest+from unittest import mock++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.bitbucket import bitbucket+from products.warehouse_sources.backend.temporal.data_imports.sources.bitbucket.bitbucket import (+ BitbucketAuth,+ BitbucketResumeConfig,+ _as_utc_datetime,+ _build_initial_params,+ _increment_page_url,+ _page_predates_cutoff,+ bitbucket_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.bitbucket.settings import BITBUCKET_ENDPOINTS++CUTOFF = datetime(2024, 6, 1, tzinfo=UTC)++REPO_PAGE = {+ "values": [+ {"slug": "repo-a", "uuid": "{uuid-a}", "full_name": "ws/repo-a"},+ {"slug": "repo-b", "uuid": "{uuid-b}", "full_name": "ws/repo-b"},+ ],+}+++def _response(json_body: dict[str, Any], status: int = 200) -> mock.Mock:+ response = mock.Mock(spec=requests.Response)+ response.status_code = status+ response.ok = status < 400+ response.text = ""+ response.json.return_value = json_body+ if status >= 400:+ response.raise_for_status.side_effect = requests.exceptions.HTTPError(+ f"{status} Client Error for url", response=response+ )+ return response+++def _session_returning(*responses: mock.Mock) -> mock.Mock:+ session = mock.Mock()+ session.get.side_effect = list(responses)+ return session+++def _manager(resume_state: BitbucketResumeConfig | None = None) -> mock.Mock:+ manager = mock.Mock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _requested_urls(session: mock.Mock) -> list[str]:+ return [call.args[0] for call in session.get.call_args_list]+++ "endpoint,should_use_incremental,cutoff,incremental_field,expected_q,expected_sort",+ [+ # Server-side BBQL filter + ascending sort on the chosen cursor field+ ("repositories", True, CUTOFF, "updated_on", 'updated_on > "2024-06-01T00:00:00+00:00"', "updated_on"),+ ("repositories", True, CUTOFF, "created_on", 'created_on > "2024-06-01T00:00:00+00:00"', "created_on"),+ ("pull_requests", True, CUTOFF, "updated_on", 'updated_on > "2024-06-01T00:00:00+00:00"', "updated_on"),+ # Full walk of a BBQL-capable endpoint sorts on immutable created_on for stable pages+ ("repositories", False, None, None, None, "created_on"),+ ("pull_requests", True, None, "updated_on", None, "created_on"),+ # Pipelines ignore `q`: newest-first sort only, watermark handled client-side+ ("pipelines", True, CUTOFF, "created_on", None, "-created_on"),+ # Commits have neither filter nor sort+ ("commits", True, CUTOFF, "date", None, None),+ ],+)+def test_build_initial_params_incremental_behavior(+ endpoint, should_use_incremental, cutoff, incremental_field, expected_q, expected_sort+):+ params = dict(+ _build_initial_params(BITBUCKET_ENDPOINTS[endpoint], should_use_incremental, cutoff, incremental_field)+ )+ assert params.get("q") == expected_q+ assert params.get("sort") == expected_sort+++def test_build_initial_params_pull_requests_keeps_all_state_params():+ # The API defaults to OPEN-only; dropping the state params silently loses merged/declined PRs+ params = _build_initial_params(BITBUCKET_ENDPOINTS["pull_requests"], False, None, None)+ states = [value for key, value in params if key == "state"]+ assert states == ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"]+ assert ("pagelen", "50") in params # PR list rejects pagelen > 50+++ "items,expected",+ [+ ([{"date": "2024-01-01T00:00:00+00:00"}, {"date": "2023-12-01T00:00:00+00:00"}], True),+ # One row past the cutoff keeps paginating+ ([{"date": "2024-01-01T00:00:00+00:00"}, {"date": "2024-07-01T00:00:00+00:00"}], False),+ # Rows equal to the cutoff are already synced+ ([{"date": "2024-06-01T00:00:00+00:00"}], True),+ # Missing or unparseable timestamps must not truncate the walk+ ([{"date": None}], False),+ ([{}], False),+ ([], False),+ # Bitbucket pipelines emit nanosecond fractions+ ([{"date": "2024-05-21T01:50:36.611482242Z"}], True),+ ],+)+def test_page_predates_cutoff(items, expected):+ assert _page_predates_cutoff(items, "date", CUTOFF) is expected+++def test_increment_page_url_preserves_sort_and_replaces_page():+ # Pipelines' `next` URL drops `sort`, silently reverting page 2+ to oldest-first;+ # rebuilding the URL ourselves must keep every param and bump only `page`.+ url = "https://api.bitbucket.org/2.0/repositories/ws/repo/pipelines/?pagelen=100&sort=-created_on&page=3"+ result = _increment_page_url(url, 3)+ query = dict(parse_qsl(urlsplit(result).query))+ assert query == {"pagelen": "100", "sort": "-created_on", "page": "4"}+++ "value,expected",+ [+ ("2024-05-21T01:50:36.611482242Z", datetime(2024, 5, 21, 1, 50, 36, 611482, tzinfo=UTC)),+ (datetime(2024, 5, 21), datetime(2024, 5, 21, tzinfo=UTC)),+ ("not a date", None),+ (None, None),+ ],+)+def test_as_utc_datetime(value, expected):+ assert _as_utc_datetime(value) == expected+++def test_top_level_rows_follow_next_and_save_state_after_yield():+ manager = _manager()+ page_1 = {"values": [{"uuid": "{r1}"}], "next": "https://api.bitbucket.org/page2"}+ page_2 = {"values": [{"uuid": "{r2}"}]}+ session = _session_returning(_response(page_1), _response(page_2))++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ batches = list(get_rows(BitbucketAuth(), "ws", "repositories", mock.Mock(), manager))++ assert [[row["uuid"] for row in batch] for batch in batches] == [["{r1}"], ["{r2}"]]+ assert _requested_urls(session)[1] == "https://api.bitbucket.org/page2"+ # State saved only while more pages remain, so a crash re-yields (not skips) the last page+ manager.save_state.assert_called_once_with(BitbucketResumeConfig(next_url="https://api.bitbucket.org/page2"))+++ "poisoned_url",+ [+ "https://evil.example.com/2.0/repositories/ws",+ "http://api.bitbucket.org/2.0/repositories/ws", # https only+ ],+)+def test_fetch_page_rejects_off_origin_urls_without_sending_credentials(poisoned_url):+ # `next` URLs come from response bodies and resume state; following one off-origin+ # would hand the credentialed session to an arbitrary host+ session = mock.Mock()++ with pytest.raises(ValueError, match="Refusing to fetch non-Bitbucket URL"):+ bitbucket._fetch_page(session, poisoned_url, mock.Mock())++ session.get.assert_not_called()+++def test_poisoned_resume_state_is_not_fetched():+ manager = _manager(BitbucketResumeConfig(next_url="https://evil.example.com/steal-token"))+ session = mock.Mock()++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ with pytest.raises(ValueError, match="Refusing to fetch non-Bitbucket URL"):+ list(get_rows(BitbucketAuth(), "ws", "repositories", mock.Mock(), manager))++ session.get.assert_not_called()+++def test_top_level_rows_resume_from_saved_url():+ manager = _manager(BitbucketResumeConfig(next_url="https://api.bitbucket.org/resume-page"))+ session = _session_returning(_response({"values": [{"uuid": "{r3}"}]}))++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ batches = list(get_rows(BitbucketAuth(), "ws", "repositories", mock.Mock(), manager))++ assert _requested_urls(session) == ["https://api.bitbucket.org/resume-page"]+ assert batches == [[{"uuid": "{r3}"}]]+++def test_workspace_members_rows_get_user_uuid_injected():+ member = {"type": "workspace_membership", "user": {"uuid": "{u1}", "display_name": "Jane"}}+ session = _session_returning(_response({"values": [member]}))++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ batches = list(get_rows(BitbucketAuth(), "ws", "workspace_members", mock.Mock(), _manager()))++ row = batches[0][0]+ assert row["user_uuid"] == "{u1}"+ assert row["user_display_name"] == "Jane"+++def test_fan_out_injects_repository_context_and_advances_bookmark():+ manager = _manager()+ session = _session_returning(+ _response(REPO_PAGE), # repo enumeration+ _response({"values": [{"id": 1}]}), # repo-a pull requests+ _response({"values": [{"id": 1}]}), # repo-b pull requests+ )++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ batches = list(get_rows(BitbucketAuth(), "ws", "pull_requests", mock.Mock(), manager))++ assert [batch[0]["repository_uuid"] for batch in batches] == ["{uuid-a}", "{uuid-b}"]+ assert batches[0][0]["repository_slug"] == "repo-a"+ assert batches[0][0]["repository_full_name"] == "ws/repo-a"+ urls = _requested_urls(session)+ assert "/repositories/ws/repo-a/pullrequests" in urls[1]+ assert "/repositories/ws/repo-b/pullrequests" in urls[2]+ # Bookmark advanced to repo-b after finishing repo-a, so a crash resumes there+ manager.save_state.assert_called_once_with(BitbucketResumeConfig(next_url=None, repo_slug="repo-b"))+++def test_fan_out_resumes_from_bookmarked_repo():+ manager = _manager(BitbucketResumeConfig(next_url="https://api.bitbucket.org/repo-b-page3", repo_slug="repo-b"))+ session = _session_returning(+ _response(REPO_PAGE),+ _response({"values": [{"id": 7}]}), # resumed page of repo-b+ )++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ batches = list(get_rows(BitbucketAuth(), "ws", "pull_requests", mock.Mock(), manager))++ # repo-a is skipped entirely; the walk restarts at repo-b's saved URL+ assert _requested_urls(session)[1] == "https://api.bitbucket.org/repo-b-page3"+ assert [batch[0]["repository_uuid"] for batch in batches] == ["{uuid-b}"]+++def test_fan_out_skips_repo_on_404_and_continues():+ # Pipelines 404 on repos with Pipelines disabled; that must not fail the whole sync+ session = _session_returning(+ _response(REPO_PAGE),+ _response({}, status=404), # repo-a pipelines disabled+ _response({"values": [{"uuid": "{p1}", "created_on": "2024-07-01T00:00:00Z"}]}), # repo-b+ )++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ batches = list(get_rows(BitbucketAuth(), "ws", "pipelines", mock.Mock(), _manager()))++ assert [batch[0]["uuid"] for batch in batches] == ["{p1}"]+++def test_fan_out_non_404_http_error_propagates():+ session = _session_returning(_response(REPO_PAGE), _response({}, status=403))++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ with pytest.raises(requests.exceptions.HTTPError):+ list(get_rows(BitbucketAuth(), "ws", "pipelines", mock.Mock(), _manager()))+++def test_commits_incremental_stops_at_watermark_without_yielding_old_page():+ # Newest-first scroll: page 1 straddles the watermark (yielded), page 2 is entirely+ # older (not yielded, pagination stops without fetching page 3)+ page_1 = {+ "values": [{"hash": "new", "date": "2024-07-01T00:00:00+00:00"}],+ "next": "https://api.bitbucket.org/commits-page2",+ }+ page_2 = {+ "values": [{"hash": "old", "date": "2024-01-01T00:00:00+00:00"}],+ "next": "https://api.bitbucket.org/commits-page3",+ }+ session = _session_returning(+ _response({"values": [REPO_PAGE["values"][0]]}),+ _response(page_1),+ _response(page_2),+ )++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ batches = list(+ get_rows(+ BitbucketAuth(),+ "ws",+ "commits",+ mock.Mock(),+ _manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=CUTOFF,+ incremental_field="date",+ )+ )++ assert [[row["hash"] for row in batch] for batch in batches] == [["new"]]+ assert len(_requested_urls(session)) == 3 # enumeration + 2 pages, page 3 never fetched+++def test_commits_first_sync_walks_past_old_pages():+ # No watermark on the first sync: an all-old page must still be yielded+ page = {"values": [{"hash": "old", "date": "2020-01-01T00:00:00+00:00"}]}+ session = _session_returning(_response({"values": [REPO_PAGE["values"][0]]}), _response(page))++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ batches = list(+ get_rows(BitbucketAuth(), "ws", "commits", mock.Mock(), _manager(), should_use_incremental_field=True)+ )++ assert [[row["hash"] for row in batch] for batch in batches] == [["old"]]+++def test_pipelines_pagination_rebuilds_page_url_instead_of_following_next():+ # Following pipelines' `next` verbatim would drop `sort` and revert to oldest-first+ page_1 = {+ "values": [{"uuid": "{p1}", "created_on": "2024-07-02T00:00:00Z"}],+ "next": "https://api.bitbucket.org/2.0/repositories/ws/repo-a/pipelines/?page=2&pagelen=100",+ "page": 1,+ }+ page_2 = {"values": [{"uuid": "{p2}", "created_on": "2024-07-01T00:00:00Z"}], "page": 2}+ session = _session_returning(_response({"values": [REPO_PAGE["values"][0]]}), _response(page_1), _response(page_2))++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ batches = list(get_rows(BitbucketAuth(), "ws", "pipelines", mock.Mock(), _manager()))++ page_2_query = dict(parse_qsl(urlsplit(_requested_urls(session)[2]).query))+ assert page_2_query["sort"] == "-created_on"+ assert page_2_query["page"] == "2"+ assert [batch[0]["uuid"] for batch in batches] == ["{p1}", "{p2}"]+++ "status,expected_valid,expected_message_fragment",+ [+ (200, True, None),+ (401, False, "Invalid Bitbucket credentials"),+ (403, False, "repository read access"),+ (404, False, "not found or not accessible"),+ (500, False, "500"),+ ],+)+def test_validate_credentials_status_mapping(status, expected_valid, expected_message_fragment):+ session = _session_returning(_response({}, status=status))++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ valid, message = validate_credentials(BitbucketAuth(email="[email protected]", api_token="t"), "ws")++ assert valid is expected_valid+ if expected_message_fragment is None:+ assert message is None+ else:+ assert expected_message_fragment in (message or "")+++ "endpoint,expected_primary_keys,expected_sort_mode,expected_partition_key",+ [+ ("repositories", ["uuid"], "asc", "created_on"),+ # PR ids and commit hashes are only unique within a repo; a non-composite key+ # would seed duplicate rows and degrade every later merge+ ("pull_requests", ["repository_uuid", "id"], "desc", "created_on"),+ ("commits", ["repository_uuid", "hash"], "desc", "date"),+ ("pipelines", ["uuid"], "desc", "created_on"),+ ("deployments", ["uuid"], "desc", None),+ ("workspace_members", ["user_uuid"], "asc", None),+ ],+)+def test_source_response_shape(endpoint, expected_primary_keys, expected_sort_mode, expected_partition_key):+ response = bitbucket_source(BitbucketAuth(), "ws", endpoint, mock.Mock(), mock.Mock())+ assert response.name == endpoint+ assert response.primary_keys == expected_primary_keys+ assert response.sort_mode == expected_sort_mode+ if expected_partition_key is None:+ assert response.partition_keys is None+ else:+ assert response.partition_keys == [expected_partition_key]+ assert response.partition_mode == "datetime"+++def test_session_uses_basic_auth_for_api_token_and_bearer_for_access_token():+ with mock.patch.object(bitbucket, "make_tracked_session", return_value=requests.Session()):+ basic = bitbucket._make_session(BitbucketAuth(email="[email protected]", api_token="tok"))+ assert basic.auth == ("[email protected]", "tok")+ assert "Authorization" not in basic.headers++ with mock.patch.object(bitbucket, "make_tracked_session", return_value=requests.Session()):+ bearer = bitbucket._make_session(BitbucketAuth(access_token="at"))+ assert bearer.headers["Authorization"] == "Bearer at"+ assert bearer.auth is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/tests/test_bitbucket_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/tests/test_bitbucket_source.pynew file mode 100644index 000000000000..f3897bc69c76--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/tests/test_bitbucket_source.py@@ -0,0 +1,164 @@+import pytest+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.bitbucket.bitbucket import (+ BitbucketAuth,+ BitbucketResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.bitbucket.source import BitbucketSource+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 (+ BitbucketAuthMethodConfig,+ BitbucketSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(+ selection: str = "api_token",+ email: str | None = "[email protected]",+ api_token: str | None = "tok",+ access_token: str | None = None,+) -> BitbucketSourceConfig:+ return BitbucketSourceConfig(+ workspace="my-workspace",+ auth_method=BitbucketAuthMethodConfig(+ selection=selection, # type: ignore[arg-type]+ email=email,+ api_token=api_token,+ access_token=access_token,+ ),+ )+++def _source_inputs(+ schema_name: str = "pull_requests",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: object = None,+ incremental_field: str | None = None,+) -> mock.Mock:+ inputs = mock.Mock()+ inputs.schema_name = schema_name+ inputs.team_id = 1+ inputs.should_use_incremental_field = should_use_incremental_field+ inputs.db_incremental_field_last_value = db_incremental_field_last_value+ inputs.incremental_field = incremental_field+ return inputs+++def test_source_type():+ assert BitbucketSource().source_type == ExternalDataSourceType.BITBUCKET+++def test_connection_host_fields_force_secret_reentry_on_workspace_change():+ assert BitbucketSource().connection_host_fields == ["workspace"]+++ "endpoint,supports_incremental",+ [+ ("repositories", True),+ ("pull_requests", True),+ ("commits", True),+ ("pipelines", True),+ # No verified server filter or stable cursor for these — offering an+ # incremental toggle would silently behave like a full refresh+ ("deployments", False),+ ("workspace_members", False),+ ],+)+def test_get_schemas_incremental_support(endpoint, supports_incremental):+ schemas = {s.name: s for s in BitbucketSource().get_schemas(_config(), team_id=1)}+ assert schemas[endpoint].supports_incremental is supports_incremental+ assert schemas[endpoint].supports_append is supports_incremental+ assert bool(schemas[endpoint].incremental_fields) is supports_incremental+++def test_get_schemas_filters_by_names():+ schemas = BitbucketSource().get_schemas(_config(), team_id=1, names=["commits", "pipelines"])+ assert sorted(s.name for s in schemas) == ["commits", "pipelines"]+++ "config,expected_auth",+ [+ (_config(), BitbucketAuth(email="[email protected]", api_token="tok")),+ (+ _config(selection="access_token", email=None, api_token=None, access_token="at"),+ BitbucketAuth(access_token="at"),+ ),+ ],+)+def test_get_auth_builds_the_right_credential(config, expected_auth):+ assert BitbucketSource()._get_auth(config) == expected_auth+++ "config,expected_fragment",+ [+ # Missing credentials surface the curated message, not the raw internal error+ (_config(email=None), "email or API token is missing"),+ (_config(api_token=None), "email or API token is missing"),+ (_config(selection="access_token", access_token=None), "No Bitbucket access token"),+ ],+)+def test_validate_credentials_maps_missing_config_to_friendly_error(config, expected_fragment):+ valid, message = BitbucketSource().validate_credentials(config, team_id=1)+ assert valid is False+ assert expected_fragment in (message or "")+++def test_validate_credentials_delegates_to_transport():+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.bitbucket.source.validate_bitbucket_credentials",+ return_value=(True, None),+ ) as validate:+ assert BitbucketSource().validate_credentials(_config(), team_id=1) == (True, None)++ validate.assert_called_once_with(BitbucketAuth(email="[email protected]", api_token="tok"), "my-workspace")+++def test_get_resumable_source_manager_binds_resume_config():+ manager = BitbucketSource().get_resumable_source_manager(_source_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is BitbucketResumeConfig+++ "should_use_incremental,last_value,expected_last_value",+ [+ (True, "2024-06-01", "2024-06-01"),+ # A stale watermark must not leak into a full-refresh run+ (False, "2024-06-01", None),+ ],+)+def test_source_for_pipeline_plumbs_arguments(should_use_incremental, last_value, expected_last_value):+ inputs = _source_inputs(+ schema_name="commits",+ should_use_incremental_field=should_use_incremental,+ db_incremental_field_last_value=last_value,+ incremental_field="date",+ )+ manager = mock.Mock()++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.bitbucket.source.bitbucket_source"+ ) as transport:+ BitbucketSource().source_for_pipeline(_config(), manager, inputs)++ transport.assert_called_once_with(+ auth=BitbucketAuth(email="[email protected]", api_token="tok"),+ workspace="my-workspace",+ endpoint="commits",+ logger=inputs.logger,+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental,+ db_incremental_field_last_value=expected_last_value,+ incremental_field="date",+ )+++def test_non_retryable_errors_cover_auth_failures():+ errors = BitbucketSource().get_non_retryable_errors()+ assert any("401 Client Error" in key for key in errors)+ assert any("403 Client Error" in key for key in errors)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.pyindex 0df24be28c2a..317a7b06f078 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@@ -44,6 +44,14 @@ class BigQueryUseCustomRegionConfig(config.Config):enabled: bool = config.value(converter=config.str_to_bool, default=False)+class BitbucketAuthMethodConfig(config.Config):+ selection: Literal["api_token", "access_token"] = "api_token"+ email: str | None = None+ api_token: str | None = None+ access_token: str | None = None++@config.configclass ElasticsearchAuthMethodConfig(config.Config):selection: Literal["basic", "api_key"] = "basic"@@ -541,7 +549,8 @@ class BingAdsSourceConfig(config.Config):@config.configclass BitbucketSourceConfig(config.Config):- pass+ workspace: str+ auth_method: BitbucketAuthMethodConfig@config.config