: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 sourcegraph import source (#71165)
Tom Owerscaef05f8fd28
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex f4d9f73ac9d9..0fa437cb0d5f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -490,6 +490,7 @@ the row lists both.| sonar_cloud | HTTP | requests | ✅ || sonarqube | HTTP | requests | ✅ || sonatype_nexus | HTTP | requests | ✅ |+| sourcegraph | HTTP (GraphQL) | requests | ✅ || spacelift | HTTP (GraphQL) | requests | ✅ || sparkpost | HTTP | requests | ✅ || split_io | HTTP | requests | ✅ |@@ -929,7 +930,6 @@ doesn't conflict with concurrent PRs.- solarwinds_service_desk- sonar_cloud- sonatype_nexus-- sourcegraph- spacelift- spotify_ads- spotlercrmdiff --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 17a00a638aa9..52721984e1ab 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@@ -4103,7 +4103,8 @@ class SonatypeNexusSourceConfig(config.Config):@config.configclass SourcegraphSourceConfig(config.Config):- pass+ host: str+ access_token: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/canonical_descriptions.pynew file mode 100644index 000000000000..b8c562b8daef--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/canonical_descriptions.py@@ -0,0 +1,53 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "repositories": {+ "description": "A repository indexed by the Sourcegraph instance, mirrored from a code host such as GitHub, GitLab, or Bitbucket.",+ "docs_url": "https://sourcegraph.com/docs/api/graphql",+ "columns": {+ "id": "Unique identifier for the repository (opaque GraphQL ID).",+ "databaseID": "The repository's numeric ID in the Sourcegraph database.",+ "name": "The repository's name, including the code host prefix (e.g. github.com/org/repo).",+ "description": "The repository's description from the code host.",+ "language": "The primary programming language of the repository, as detected by Sourcegraph.",+ "createdAt": "When the repository was added to the Sourcegraph instance.",+ "updatedAt": "When the repository's metadata was last updated on the Sourcegraph instance.",+ "isPrivate": "Whether the repository is private on its code host.",+ "isFork": "Whether the repository is a fork of another repository.",+ "isArchived": "Whether the repository is archived on its code host.",+ "stars": "The number of stars the repository has on its code host.",+ "url": "The repository's URL path on the Sourcegraph instance.",+ "externalRepository": "The code host the repository is mirrored from (service type and service ID).",+ "defaultBranch": "The repository's default branch ref (e.g. refs/heads/main).",+ },+ },+ "users": {+ "description": "A user account on the Sourcegraph instance. Listing users requires a site-admin access token.",+ "docs_url": "https://sourcegraph.com/docs/api/graphql",+ "columns": {+ "id": "Unique identifier for the user (opaque GraphQL ID).",+ "username": "The user's username on the Sourcegraph instance.",+ "displayName": "The user's display name.",+ "avatarURL": "URL of the user's avatar image.",+ "url": "The user's profile URL path on the Sourcegraph instance.",+ "createdAt": "When the user account was created.",+ "updatedAt": "When the user account was last updated.",+ "siteAdmin": "Whether the user is a site admin of the Sourcegraph instance.",+ "builtinAuth": "Whether the user authenticates with Sourcegraph's built-in username/password auth.",+ "emails": "The email addresses associated with the user, with primary and verification status.",+ },+ },+ "organizations": {+ "description": "An organization on the Sourcegraph instance, used to group users and share settings. Listing organizations requires a site-admin access token.",+ "docs_url": "https://sourcegraph.com/docs/api/graphql",+ "columns": {+ "id": "Unique identifier for the organization (opaque GraphQL ID).",+ "name": "The organization's unique name.",+ "displayName": "The organization's display name.",+ "createdAt": "When the organization was created.",+ "url": "The organization's URL path on the Sourcegraph instance.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/settings.pynew file mode 100644index 000000000000..0d5ecfa8ae6a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/settings.py@@ -0,0 +1,131 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField++# Field selections stick to long-stable parts of the Sourcegraph GraphQL schema so the same+# query validates on older self-hosted instances, not just sourcegraph.com.+REPOSITORIES_QUERY = """+query Repositories($first: Int!, $after: String) {+ repositories(first: $first, after: $after, orderBy: REPOSITORY_CREATED_AT, descending: false) {+ nodes {+ id+ databaseID+ name+ description+ language+ createdAt+ updatedAt+ isPrivate+ isFork+ isArchived+ stars+ url+ externalRepository {+ serviceType+ serviceID+ }+ defaultBranch {+ name+ }+ }+ pageInfo {+ endCursor+ hasNextPage+ }+ }+}+"""++USERS_QUERY = """+query Users($first: Int!, $after: String) {+ users(first: $first, after: $after) {+ nodes {+ id+ username+ displayName+ avatarURL+ url+ createdAt+ updatedAt+ siteAdmin+ builtinAuth+ emails {+ isPrimary+ verified+ }+ }+ pageInfo {+ endCursor+ hasNextPage+ }+ }+}+"""++# The organizations connection has no cursor (nodes + totalCount only), so it is fetched as a+# single capped request — see UNPAGINATED_FETCH_LIMIT in sourcegraph.py.+ORGANIZATIONS_QUERY = """+query Organizations($first: Int!) {+ organizations(first: $first) {+ nodes {+ id+ name+ displayName+ createdAt+ url+ }+ totalCount+ }+}+"""+++@dataclass+class SourcegraphEndpointConfig:+ name: str+ query: str+ # Top-level key under `data` holding the connection (e.g. "repositories").+ data_path: str+ # None of the connections expose a server-side updated-since filter, so every endpoint is+ # full-refresh only; the list stays as the declarative menu should Sourcegraph add one.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable, immutable field to partition by. Never updatedAt (it mutates).+ partition_key: Optional[str] = None+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ page_size: int = 100+ # Relay-style cursor pagination (first/after + pageInfo). False = single capped request+ # for connections without a cursor.+ paginated: bool = True+ # Extra context surfaced in the schema picker.+ description: Optional[str] = None+++SOURCEGRAPH_ENDPOINTS: dict[str, SourcegraphEndpointConfig] = {+ "repositories": SourcegraphEndpointConfig(+ name="repositories",+ query=REPOSITORIES_QUERY,+ data_path="repositories",+ partition_key="createdAt",+ ),+ "users": SourcegraphEndpointConfig(+ name="users",+ query=USERS_QUERY,+ data_path="users",+ description="Requires a site-admin access token",+ ),+ "organizations": SourcegraphEndpointConfig(+ name="organizations",+ query=ORGANIZATIONS_QUERY,+ data_path="organizations",+ paginated=False,+ description="Requires a site-admin access token",+ ),+}++ENDPOINTS = tuple(SOURCEGRAPH_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in SOURCEGRAPH_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/source.pyindex 5fe02edbdedb..4af020ee74cd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/source.py@@ -1,30 +1,161 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.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 SourcegraphSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.sourcegraph.settings import (+ ENDPOINTS,+ SOURCEGRAPH_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.sourcegraph.sourcegraph import (+ HOST_NOT_ALLOWED_ERROR,+ RESPONSE_TIMEOUT_ERROR,+ RESPONSE_TOO_LARGE_ERROR,+ SourcegraphResumeConfig,+ get_endpoint_permissions as get_sourcegraph_endpoint_permissions,+ sourcegraph_source,+ validate_credentials as validate_sourcegraph_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SourcegraphSource(SimpleSource[SourcegraphSourceConfig]):+class SourcegraphSource(ResumableSource[SourcegraphSourceConfig, SourcegraphResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SOURCEGRAPH+ @property+ def connection_host_fields(self) -> list[str]:+ # The access token is sent to whatever host `host` points at, so retargeting+ # it must re-require the token (prevents credential exfiltration to another host).+ return ["host"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.SOURCEGRAPH,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Sourcegraph",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Sourcegraph instance URL and an access token to pull your Sourcegraph data into the PostHog Data warehouse.++You can create an access token in Sourcegraph under **Settings > Access tokens**.++The `users` and `organizations` tables require a token created by a **site admin**; `repositories` works with any user's token.+""",iconPath="/static/services/sourcegraph.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/sourcegraph",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="host",+ label="Sourcegraph URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://sourcegraph.example.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="access_token",+ label="Access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="sgp_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid Sourcegraph access token. Please generate a new token and reconnect.",+ "403 Client Error": "Your Sourcegraph access token lacks the required permissions. Please check the token and try again.",+ "Sourcegraph GraphQL error: not authenticated": "Your Sourcegraph access token is not authenticated for this data. Please generate a new token and reconnect.",+ "Sourcegraph GraphQL error: must be site admin": "This table requires a site-admin access token. Please reconnect with a token created by a Sourcegraph site admin.",+ HOST_NOT_ALLOWED_ERROR: "The Sourcegraph URL is not allowed. Please use your organization's Sourcegraph instance URL.",+ RESPONSE_TOO_LARGE_ERROR: "The Sourcegraph API response was too large to sync.",+ RESPONSE_TIMEOUT_ERROR: "The Sourcegraph API response took too long to download.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.sourcegraph.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: SourcegraphSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # No Sourcegraph connection exposes a server-side updated-since filter, so every+ # endpoint is full-refresh only (the cursor still makes runs resumable mid-sync).+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ description=SOURCEGRAPH_ENDPOINTS[endpoint].description,+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: SourcegraphSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_sourcegraph_credentials(config.host, config.access_token, schema_name, team_id)++ def get_endpoint_permissions(+ self, config: SourcegraphSourceConfig, team_id: int, endpoints: list[str]+ ) -> dict[str, str | None]:+ return get_sourcegraph_endpoint_permissions(config.host, config.access_token, team_id, endpoints)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SourcegraphResumeConfig]:+ return ResumableSourceManager[SourcegraphResumeConfig](inputs, SourcegraphResumeConfig)++ def source_for_pipeline(+ self,+ config: SourcegraphSourceConfig,+ resumable_source_manager: ResumableSourceManager[SourcegraphResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return sourcegraph_source(+ host=config.host,+ access_token=config.access_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ team_id=inputs.team_id,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/sourcegraph.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/sourcegraph.pynew file mode 100644index 000000000000..86c467860327--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/sourcegraph.py@@ -0,0 +1,442 @@+import re+import json+import time+import threading+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional++import requests+import structlog+from structlog.types import FilteringBoundLogger+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.sourcegraph.settings import (+ SOURCEGRAPH_ENDPOINTS,+ SourcegraphEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+MAX_RETRY_AFTER_SECONDS = 60+# Cap for connections without cursor pagination (organizations). Sourcegraph instances rarely+# have more than a handful of orgs; a truncated fetch is logged.+UNPAGINATED_FETCH_LIMIT = 1000++# The Sourcegraph host is customer-controlled, so its cursor pagination is untrusted: a malicious+# or compromised instance can hand back an endless run of full pages with fresh cursors and keep an+# import worker occupied until the activity's week-long timeout. Bound a single run by both page+# count and cumulative wall-clock so an endless (or pathologically slow) stream fails the sync+# instead of holding the worker — a real instance completes well inside both. At page_size 100 the+# page cap is ~10M rows; the deadline sits far below the activity ceiling.+MAX_PAGES_PER_RUN = 100_000+MAX_PAGINATION_SECONDS = 6 * 60 * 60++HOST_NOT_ALLOWED_ERROR = "Sourcegraph host is not allowed"+GRAPHQL_ERROR_PREFIX = "Sourcegraph GraphQL error"++RESPONSE_TOO_LARGE_ERROR = "Sourcegraph API response exceeded the size limit"+RESPONSE_TIMEOUT_ERROR = "Sourcegraph API response exceeded the download time limit"++# The Sourcegraph host is customer-controlled (self-hosted instances), so responses are+# streamed and read under a byte cap — an arbitrarily large (or endless) 200 body must fail+# the sync instead of exhausting worker memory. The cap applies to decoded bytes, so a gzip+# bomb can't slip past it.+MAX_RESPONSE_BYTES = 256 * 1024 * 1024+_READ_CHUNK_BYTES = 1024 * 1024+# The per-read timeout only bounds the gap between chunks, so a server can trickle one byte+# just before each read timeout and keep a worker occupied indefinitely. A monotonic+# total-transfer deadline caps how long a single body read may take end to end, independent+# of how the bytes are paced. A single streamed read blocks until a whole chunk (or EOF)+# arrives, so the in-loop deadline check can't interrupt it; a watchdog force-closes the+# response once the deadline passes, unblocking that read so this slow-drip path fails the sync.+MAX_RESPONSE_SECONDS = 600+# Bytes read from an error body for a diagnostic message. Error bodies are never needed in+# full, so only a short bounded snippet is ever pulled into memory.+_ERROR_SNIPPET_BYTES = 2048++module_logger = structlog.get_logger(__name__)+++class SourcegraphRetryableError(Exception):+ def __init__(self, message: str, retry_after: float | None = None) -> None:+ super().__init__(message)+ self.retry_after = retry_after+++class SourcegraphHostNotAllowedError(Exception):+ pass+++class SourcegraphResponseTooLargeError(Exception):+ pass+++class SourcegraphResponseTimeoutError(Exception):+ pass+++class SourcegraphPaginationLimitError(Exception):+ """A single run walked more pages, or ran longer, than the per-run bounds allow."""++ pass+++def _read_bounded(response: requests.Response, max_bytes: int, max_seconds: float = MAX_RESPONSE_SECONDS) -> bytes:+ """Read a streamed response body under both a byte cap and a total-transfer deadline.++ A single ``iter_content`` read blocks until a whole chunk (or EOF) arrives, so the in-loop+ deadline check alone can't stop a slow-drip body that trickles bytes under the per-read socket+ timeout — the loop never regains control to check the clock. A watchdog thread force-closes the+ response once the deadline passes, which unblocks that read so the sync fails instead of holding+ the worker indefinitely. The in-loop check still covers bodies that arrive as many quick chunks.+ """+ total = 0+ chunks: list[bytes] = []+ deadline = time.monotonic() + max_seconds+ finished = threading.Event()+ timed_out = threading.Event()++ def _abort_on_deadline() -> None:+ if not finished.wait(max_seconds):+ timed_out.set()+ response.close()++ watchdog = threading.Thread(target=_abort_on_deadline, daemon=True)+ watchdog.start()++ read_complete = False+ try:+ for chunk in response.iter_content(chunk_size=_READ_CHUNK_BYTES):+ if timed_out.is_set():+ break+ total += len(chunk)+ if total > max_bytes:+ raise SourcegraphResponseTooLargeError(f"{RESPONSE_TOO_LARGE_ERROR} ({max_bytes} bytes)")+ if time.monotonic() > deadline:+ raise SourcegraphResponseTimeoutError(f"{RESPONSE_TIMEOUT_ERROR} ({max_seconds:g}s)")+ chunks.append(chunk)+ read_complete = True+ except Exception:+ # Force-closing the response mid-read surfaces here as a transport error; when the watchdog+ # fired, report the deadline rather than the incidental socket failure.+ if not timed_out.is_set():+ raise+ finally:+ finished.set()++ if timed_out.is_set() and not read_complete:+ raise SourcegraphResponseTimeoutError(f"{RESPONSE_TIMEOUT_ERROR} ({max_seconds:g}s)")+ return b"".join(chunks)+++def _error_snippet(response: requests.Response) -> str:+ try:+ chunk = next(response.iter_content(chunk_size=_ERROR_SNIPPET_BYTES), b"")+ return chunk[:_ERROR_SNIPPET_BYTES].decode("utf-8", errors="replace")+ except Exception:+ return ""+++class SourcegraphQueryError(Exception):+ """A GraphQL-level error returned with HTTP 200 (e.g. missing site-admin permissions)."""++ pass+++class SourcegraphResumeConfig:+ # Relay `endCursor` of the last fully-yielded page. None means "start from the first page".+ cursor: str | None = None+++def normalize_host(host: str) -> str:+ """Turn whatever the user typed into a bare Sourcegraph host.++ Accepts values like ``sourcegraph.example.com``, ``https://sourcegraph.example.com/``,+ or ``sourcegraph.example.com/.api/graphql`` and returns ``sourcegraph.example.com``.+ """+ host = host.strip()+ host = re.sub(r"^https?://", "", host, flags=re.IGNORECASE)+ host = host.split("/")[0]+ return host.strip().rstrip("/")+++def _graphql_url(host: str) -> str:+ return f"https://{normalize_host(host)}/.api/graphql"+++def _get_headers(access_token: str) -> dict[str, str]:+ return {+ "Authorization": f"token {access_token}",+ "Accept": "application/json",+ "Content-Type": "application/json",+ }+++def _parse_retry_after(response: requests.Response) -> float | None:+ raw = response.headers.get("Retry-After")+ if raw and raw.strip().isdigit():+ return min(float(raw.strip()), MAX_RETRY_AFTER_SECONDS)+ return None+++def _retry_wait(retry_state: RetryCallState) -> float:+ """Honor a server-provided Retry-After when present, else exponential backoff."""+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, SourcegraphRetryableError) and exc.retry_after is not None:+ return exc.retry_after+ return wait_exponential_jitter(initial=1, max=30)(retry_state)+++@retry(+ retry=retry_if_exception_type((SourcegraphRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=_retry_wait,+ reraise=True,+)+def _execute(+ session: requests.Session,+ url: str,+ headers: dict[str, str],+ query: str,+ variables: dict[str, Any],+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ """POST a GraphQL query and return the ``data`` payload, raising on transport or GraphQL errors."""+ # Don't follow redirects: the validated host could 3xx to an internal address, defeating+ # the host check done before the request (SSRF). `stream=True` so the body is only read+ # through `_read_bounded` / `_error_snippet` under a byte cap.+ with session.post(+ url,+ json={"query": query, "variables": variables},+ headers=headers,+ timeout=REQUEST_TIMEOUT_SECONDS,+ allow_redirects=False,+ stream=True,+ ) as response:+ if response.status_code == 429 or response.status_code >= 500:+ retry_after = _parse_retry_after(response) if response.status_code == 429 else None+ raise SourcegraphRetryableError(+ f"Sourcegraph API error (retryable): status={response.status_code}, url={url}",+ retry_after=retry_after,+ )++ # A 3xx isn't an error status (`response.ok` is True), so reject it explicitly rather than+ # silently parsing the redirect body as data.+ if response.is_redirect or response.is_permanent_redirect:+ raise SourcegraphHostNotAllowedError(+ f"Sourcegraph API returned an unexpected redirect (status={response.status_code}); refusing to follow it"+ )++ if not response.ok:+ logger.error(+ f"Sourcegraph API error: status={response.status_code}, body={_error_snippet(response)}, url={url}"+ )+ response.raise_for_status()++ body = json.loads(_read_bounded(response, MAX_RESPONSE_BYTES))++ # Sourcegraph returns GraphQL-level failures (bad query, missing site-admin permissions)+ # with HTTP 200 and an `errors` array.+ errors = body.get("errors")+ if errors:+ messages = "; ".join(str(error.get("message", error)) for error in errors)+ raise SourcegraphQueryError(f"{GRAPHQL_ERROR_PREFIX}: {messages}")++ data = body.get("data")+ if not isinstance(data, dict):+ raise SourcegraphQueryError(f"{GRAPHQL_ERROR_PREFIX}: response has no data payload")++ return data+++def validate_credentials(+ host: str, access_token: str, schema_name: Optional[str] = None, team_id: Optional[int] = None+) -> tuple[bool, str | None]:+ """Probe the API to confirm the access token is genuine.++ At source-create (``schema_name is None``) we only check the token itself via ``currentUser``+ — the admin-scoped connections (users, organizations) may legitimately be out of scope for a+ non-admin token. A scoped probe (``schema_name`` set) runs that endpoint's query with+ ``first: 1`` so permission failures surface for the specific table.+ """+ try:+ normalized = normalize_host(host)+ except Exception:+ return False, "Invalid Sourcegraph URL"++ if not normalized or not re.match(r"^[A-Za-z0-9.\-:]+$", normalized):+ return False, "Invalid Sourcegraph URL"++ # The host is fully customer-controlled (self-hosted instances), so block hosts that resolve+ # to private/internal addresses (SSRF). Only enforced on cloud — see _is_host_safe.+ if team_id is not None:+ host_ok, host_err = _is_host_safe(normalized, team_id)+ if not host_ok:+ return False, host_err or HOST_NOT_ALLOWED_ERROR++ if schema_name is not None and schema_name in SOURCEGRAPH_ENDPOINTS:+ endpoint_config = SOURCEGRAPH_ENDPOINTS[schema_name]+ query = endpoint_config.query+ variables: dict[str, Any] = {"first": 1, "after": None} if endpoint_config.paginated else {"first": 1}+ else:+ query = "query { currentUser { username } }"+ variables = {}++ session = make_tracked_session()+ try:+ _execute(session, _graphql_url(normalized), _get_headers(access_token), query, variables, module_logger)+ except requests.HTTPError as e:+ if e.response is not None and e.response.status_code == 401:+ return False, "Invalid Sourcegraph access token"+ return False, str(e)+ except SourcegraphQueryError as e:+ return False, str(e)+ except SourcegraphHostNotAllowedError:+ return False, HOST_NOT_ALLOWED_ERROR+ except Exception as e:+ return False, str(e)++ return True, None+++def get_endpoint_permissions(host: str, access_token: str, team_id: int, endpoints: list[str]) -> dict[str, str | None]:+ """Probe each endpoint with ``first: 1`` and report which are blocked by missing permissions.++ Only a genuine GraphQL-level denial (e.g. "must be site admin", "not authenticated") counts as+ a permission error — transient transport failures leave the endpoint marked reachable so this+ never blocks source creation.+ """+ results: dict[str, str | None] = dict.fromkeys(endpoints)+ session = make_tracked_session()+ headers = _get_headers(access_token)+ url = _graphql_url(host)++ for endpoint in endpoints:+ endpoint_config = SOURCEGRAPH_ENDPOINTS.get(endpoint)+ if endpoint_config is None:+ continue+ variables: dict[str, Any] = {"first": 1, "after": None} if endpoint_config.paginated else {"first": 1}+ try:+ _execute(session, url, headers, endpoint_config.query, variables, module_logger)+ except SourcegraphQueryError as e:+ results[endpoint] = str(e)+ except Exception:+ # A throttle, 5xx, or network blip is not a missing scope.+ continue++ return results+++def get_rows(+ host: str,+ access_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SourcegraphResumeConfig],+ team_id: int,+) -> Iterator[Any]:+ config = SOURCEGRAPH_ENDPOINTS[endpoint]+ headers = _get_headers(access_token)++ # Re-check at run time (not just at source-create) in case the host was edited or now+ # resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.+ host_ok, host_err = _is_host_safe(normalize_host(host), team_id)+ if not host_ok:+ raise SourcegraphHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)++ url = _graphql_url(host)+ # One session reused across every page so urllib3 keeps the connection alive instead of+ # re-handshaking per request.+ session = make_tracked_session()++ if not config.paginated:+ data = _execute(session, url, headers, config.query, {"first": UNPAGINATED_FETCH_LIMIT}, logger)+ connection = data.get(config.data_path) or {}+ nodes = connection.get("nodes") or []+ total_count = connection.get("totalCount")+ if isinstance(total_count, int) and total_count > len(nodes):+ logger.warning(+ f"Sourcegraph: {endpoint} has {total_count} rows but the API exposes no cursor; "+ f"only the first {len(nodes)} were fetched"+ )+ if nodes:+ yield nodes+ return++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ after: str | None = resume.cursor if resume is not None else None+ if after:+ logger.debug(f"Sourcegraph: resuming {endpoint} from cursor {after}")++ pagination_deadline = time.monotonic() + MAX_PAGINATION_SECONDS+ pages_fetched = 0++ while True:+ data = _execute(session, url, headers, config.query, {"first": config.page_size, "after": after}, logger)+ connection = data.get(config.data_path) or {}+ nodes = connection.get("nodes") or []+ page_info = connection.get("pageInfo") or {}+ pages_fetched += 1++ if nodes:+ yield nodes++ end_cursor = page_info.get("endCursor")+ if not page_info.get("hasNextPage") or not end_cursor or not nodes:+ break++ # Save AFTER yielding so a crash re-fetches (and re-yields) the last page rather than+ # skipping it — merge dedupes on the primary key.+ resumable_source_manager.save_state(SourcegraphResumeConfig(cursor=end_cursor))+ after = end_cursor++ # A customer-controlled host can hand back an endless run of full pages with fresh cursors;+ # fail the run once it crosses either per-run bound so it can't occupy a worker until the+ # activity's week-long timeout. The cursor is already checkpointed, so an activity retry+ # within this job resumes from here rather than re-walking from the start.+ if pages_fetched >= MAX_PAGES_PER_RUN:+ raise SourcegraphPaginationLimitError(+ f"Sourcegraph {endpoint} exceeded the per-run page limit ({MAX_PAGES_PER_RUN})"+ )+ if time.monotonic() > pagination_deadline:+ raise SourcegraphPaginationLimitError(+ f"Sourcegraph {endpoint} exceeded the per-run pagination deadline ({MAX_PAGINATION_SECONDS:g}s)"+ )+++def sourcegraph_source(+ host: str,+ access_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SourcegraphResumeConfig],+ team_id: int,+) -> SourceResponse:+ endpoint_config: SourcegraphEndpointConfig = SOURCEGRAPH_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ host=host,+ access_token=access_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ team_id=team_id,+ ),+ primary_keys=endpoint_config.primary_keys,+ # repositories is requested with orderBy: REPOSITORY_CREATED_AT ascending; the other+ # endpoints are full-refresh only, so the watermark direction is unused for them.+ sort_mode="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/sourcegraph/tests/test_sourcegraph.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/tests/test_sourcegraph.pynew file mode 100644index 000000000000..aec0a86bc532--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/tests/test_sourcegraph.py@@ -0,0 +1,399 @@+import json+import threading+from typing import Any++import pytest+from unittest import mock++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.sourcegraph.settings import SOURCEGRAPH_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.sourcegraph.sourcegraph import (+ MAX_RESPONSE_BYTES,+ SourcegraphHostNotAllowedError,+ SourcegraphPaginationLimitError,+ SourcegraphQueryError,+ SourcegraphResponseTimeoutError,+ SourcegraphResponseTooLargeError,+ SourcegraphResumeConfig,+ SourcegraphRetryableError,+ _parse_retry_after,+ _read_bounded,+ _retry_wait,+ get_endpoint_permissions,+ get_rows,+ normalize_host,+ sourcegraph_source,+ validate_credentials,+)++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.sourcegraph.sourcegraph"+++def _response(+ *,+ status_code: int = 200,+ json_data: Any = None,+ headers: dict[str, str] | None = None,+ body_bytes: bytes | None = None,+) -> mock.MagicMock:+ response = mock.MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 400+ response.is_redirect = status_code in (302, 303, 307)+ response.is_permanent_redirect = status_code in (301, 308)+ response.headers = headers or {}+ response.json.return_value = json_data+ # `_execute` reads the streamed body via `_read_bounded(response, ...)`, so feed the serialized+ # payload back through `iter_content`; a fresh iterator per call keeps `_error_snippet` working too.+ if body_bytes is None:+ body_bytes = json.dumps(json_data).encode() if json_data is not None else b""+ response.iter_content.side_effect = lambda *args, **kwargs: iter([body_bytes] if body_bytes else [])+ # `_execute` uses `with session.post(...) as response`, so the mock must return itself on enter.+ response.__enter__.return_value = response+ response.__exit__.return_value = False+ if status_code >= 400:+ response.raise_for_status.side_effect = requests.HTTPError(+ f"{status_code} Client Error: for url: https://sourcegraph.example.com/.api/graphql",+ response=response,+ )+ return response+++def _connection_page(+ data_path: str, nodes: list[dict], *, end_cursor: str | None = None, has_next_page: bool = False+) -> dict:+ return {+ "data": {+ data_path: {+ "nodes": nodes,+ "pageInfo": {"endCursor": end_cursor, "hasNextPage": has_next_page},+ }+ }+ }+++def host_is_safe():+ with mock.patch(f"{MODULE}._is_host_safe", return_value=(True, None)):+ yield+++def session():+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_make_session:+ yield mock_make_session.return_value+++class TestNormalizeHost:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ ("sourcegraph.example.com", "sourcegraph.example.com"),+ ("https://sourcegraph.example.com", "sourcegraph.example.com"),+ ("http://sourcegraph.example.com/", "sourcegraph.example.com"),+ (" sourcegraph.example.com ", "sourcegraph.example.com"),+ ("sourcegraph.example.com/.api/graphql", "sourcegraph.example.com"),+ ("https://sourcegraph.com/search", "sourcegraph.com"),+ ],+ )+ def test_normalize_host(self, raw, expected):+ assert normalize_host(raw) == expected+++class TestGetRows:+ def test_paginates_with_cursor_and_saves_state_after_yield(self, host_is_safe, session):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ page1 = _connection_page(+ "repositories", [{"id": "r1"}, {"id": "r2"}], end_cursor="cursor-1", has_next_page=True+ )+ page2 = _connection_page("repositories", [{"id": "r3"}], end_cursor="cursor-2", has_next_page=False)+ session.post.side_effect = [_response(json_data=page1), _response(json_data=page2)]++ rows = get_rows("sourcegraph.example.com", "sgp_token", "repositories", mock.MagicMock(), manager, team_id=1)++ first_batch = next(rows)+ assert first_batch == [{"id": "r1"}, {"id": "r2"}]+ # State is saved only after the batch is yielded, so a crash re-yields (not skips) it.+ assert not manager.save_state.called++ second_batch = next(rows)+ assert second_batch == [{"id": "r3"}]+ manager.save_state.assert_called_once_with(SourcegraphResumeConfig(cursor="cursor-1"))++ with pytest.raises(StopIteration):+ next(rows)++ first_vars = session.post.call_args_list[0].kwargs["json"]["variables"]+ second_vars = session.post.call_args_list[1].kwargs["json"]["variables"]+ assert first_vars["after"] is None+ assert second_vars["after"] == "cursor-1"++ def test_resumes_from_saved_cursor(self, host_is_safe, session):+ manager = mock.MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = SourcegraphResumeConfig(cursor="saved-cursor")+ session.post.return_value = _response(json_data=_connection_page("repositories", [{"id": "r9"}]))++ rows = list(+ get_rows("sourcegraph.example.com", "sgp_token", "repositories", mock.MagicMock(), manager, team_id=1)+ )++ assert rows == [[{"id": "r9"}]]+ assert session.post.call_args.kwargs["json"]["variables"]["after"] == "saved-cursor"++ def test_stops_on_empty_page_even_if_has_next_page(self, host_is_safe, session):+ # Termination guard: a malformed connection claiming more pages with no rows must not loop.+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ session.post.return_value = _response(+ json_data=_connection_page("repositories", [], end_cursor="cursor-1", has_next_page=True)+ )++ rows = list(+ get_rows("sourcegraph.example.com", "sgp_token", "repositories", mock.MagicMock(), manager, team_id=1)+ )++ assert rows == []+ assert session.post.call_count == 1++ def test_endless_pagination_stops_at_the_page_limit(self, host_is_safe, session):+ # A customer-controlled host that always returns a full page + fresh cursor + hasNextPage+ # must fail the run at the page cap rather than loop until the activity's week-long timeout.+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ session.post.side_effect = lambda *args, **kwargs: _response(+ json_data=_connection_page("repositories", [{"id": "r"}], end_cursor="c", has_next_page=True)+ )++ with mock.patch(f"{MODULE}.MAX_PAGES_PER_RUN", 3):+ with pytest.raises(SourcegraphPaginationLimitError):+ list(+ get_rows(+ "sourcegraph.example.com", "sgp_token", "repositories", mock.MagicMock(), manager, team_id=1+ )+ )++ assert session.post.call_count == 3++ def test_endless_pagination_stops_at_the_deadline(self, host_is_safe, session):+ # The cumulative wall-clock bound catches a host that drips full pages slowly enough to stay+ # under the page cap; a deadline already in the past trips right after the first page.+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ session.post.side_effect = lambda *args, **kwargs: _response(+ json_data=_connection_page("repositories", [{"id": "r"}], end_cursor="c", has_next_page=True)+ )++ with mock.patch(f"{MODULE}.MAX_PAGINATION_SECONDS", -1):+ with pytest.raises(SourcegraphPaginationLimitError):+ list(+ get_rows(+ "sourcegraph.example.com", "sgp_token", "repositories", mock.MagicMock(), manager, team_id=1+ )+ )++ assert session.post.call_count == 1++ def test_unpaginated_endpoint_fetches_once_and_warns_on_truncation(self, host_is_safe, session):+ manager = mock.MagicMock()+ logger = mock.MagicMock()+ session.post.return_value = _response(+ json_data={"data": {"organizations": {"nodes": [{"id": "o1"}], "totalCount": 1500}}}+ )++ rows = list(get_rows("sourcegraph.example.com", "sgp_token", "organizations", logger, manager, team_id=1))++ assert rows == [[{"id": "o1"}]]+ assert session.post.call_count == 1+ assert session.post.call_args.kwargs["json"]["variables"] == {"first": 1000}+ assert not manager.save_state.called+ assert logger.warning.called++ def test_graphql_error_raises_query_error(self, host_is_safe, session):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ session.post.return_value = _response(json_data={"errors": [{"message": "must be site admin"}], "data": None})++ with pytest.raises(SourcegraphQueryError, match="must be site admin"):+ list(get_rows("sourcegraph.example.com", "sgp_token", "users", mock.MagicMock(), manager, team_id=1))++ def test_redirect_response_is_refused(self, host_is_safe, session):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ session.post.return_value = _response(status_code=302)++ with pytest.raises(SourcegraphHostNotAllowedError):+ list(get_rows("sourcegraph.example.com", "sgp_token", "repositories", mock.MagicMock(), manager, team_id=1))++ def test_unsafe_host_is_blocked_before_any_request(self, session):+ manager = mock.MagicMock()+ with mock.patch(f"{MODULE}._is_host_safe", return_value=(False, "blocked")):+ with pytest.raises(SourcegraphHostNotAllowedError, match="blocked"):+ list(+ get_rows("sourcegraph.internal", "sgp_token", "repositories", mock.MagicMock(), manager, team_id=1)+ )+ assert not session.post.called+++class TestValidateCredentials:+ def test_valid_token_probes_current_user(self, session):+ session.post.return_value = _response(json_data={"data": {"currentUser": {"username": "alice"}}})++ assert validate_credentials("sourcegraph.example.com", "sgp_token") == (True, None)+ assert "currentUser" in session.post.call_args.kwargs["json"]["query"]++ def test_scoped_probe_runs_the_endpoint_query(self, session):+ session.post.return_value = _response(json_data=_connection_page("users", [{"id": "u1"}]))++ assert validate_credentials("sourcegraph.example.com", "sgp_token", schema_name="users") == (True, None)+ body = session.post.call_args.kwargs["json"]+ assert body["query"] == SOURCEGRAPH_ENDPOINTS["users"].query+ assert body["variables"] == {"first": 1, "after": None}++ def test_401_maps_to_invalid_token(self, session):+ session.post.return_value = _response(status_code=401)++ valid, error = validate_credentials("sourcegraph.example.com", "sgp_bad")++ assert valid is False+ assert error == "Invalid Sourcegraph access token"++ def test_graphql_error_surfaces_message(self, session):+ session.post.return_value = _response(json_data={"errors": [{"message": "not authenticated"}], "data": None})++ valid, error = validate_credentials("sourcegraph.example.com", "sgp_token", schema_name="users")++ assert valid is False+ assert error is not None and "not authenticated" in error++ @pytest.mark.parametrize("bad_host", ["", " ", "not a host!"])+ def test_invalid_host_is_rejected_without_a_request(self, session, bad_host):+ valid, error = validate_credentials(bad_host, "sgp_token")++ assert valid is False+ assert error == "Invalid Sourcegraph URL"+ assert not session.post.called++ def test_unsafe_host_is_blocked(self, session):+ with mock.patch(f"{MODULE}._is_host_safe", return_value=(False, "host not allowed")):+ valid, error = validate_credentials("sourcegraph.internal", "sgp_token", team_id=1)++ assert valid is False+ assert error == "host not allowed"+ assert not session.post.called+++class TestGetEndpointPermissions:+ def test_denied_endpoints_report_reason_and_transient_failures_stay_reachable(self, session):+ def _post(url, **kwargs):+ query = kwargs["json"]["query"]+ if "query Users" in query:+ return _response(json_data={"errors": [{"message": "must be site admin"}], "data": None})+ if "query Organizations" in query:+ # Plain Timeout is not in the tenacity retry list, so this fails fast in the test+ # while still exercising the "transient network failure" branch.+ raise requests.Timeout("boom")+ return _response(json_data=_connection_page("repositories", [{"id": "r1"}]))++ session.post.side_effect = _post++ results = get_endpoint_permissions(+ "sourcegraph.example.com", "sgp_token", team_id=1, endpoints=["repositories", "users", "organizations"]+ )++ assert results["repositories"] is None+ assert results["users"] is not None and "must be site admin" in results["users"]+ # A network blip is not a missing scope.+ assert results["organizations"] is None+++class TestSourcegraphSource:+ def test_repositories_response_is_partitioned_on_created_at(self):+ response = sourcegraph_source(+ "sourcegraph.example.com", "sgp_token", "repositories", mock.MagicMock(), mock.MagicMock(), team_id=1+ )++ assert response.name == "repositories"+ assert response.primary_keys == ["id"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["createdAt"]+ assert response.partition_format == "month"++ @pytest.mark.parametrize("endpoint", ["users", "organizations"])+ def test_small_tables_are_not_partitioned(self, endpoint):+ response = sourcegraph_source(+ "sourcegraph.example.com", "sgp_token", endpoint, mock.MagicMock(), mock.MagicMock(), team_id=1+ )++ assert response.primary_keys == ["id"]+ assert response.partition_mode is None+ assert response.partition_keys is None+++class TestReadBounded:+ # The Sourcegraph host is customer-controlled, so a malicious 200 body must fail the sync+ # rather than exhaust or indefinitely occupy a worker.+ def test_oversized_body_is_rejected(self):+ response = mock.MagicMock()+ response.iter_content.return_value = iter([b"x" * 10, b"y" * 10])++ with pytest.raises(SourcegraphResponseTooLargeError):+ _read_bounded(response, max_bytes=15)++ def test_slow_drip_body_hits_the_deadline(self):+ response = mock.MagicMock()+ response.iter_content.return_value = iter([b"a", b"b", b"c"])++ # First call sets the deadline; the next read is past it, so a body that arrives as many+ # quick chunks but overruns the deadline is aborted by the in-loop check.+ with mock.patch(f"{MODULE}.time.monotonic", side_effect=[0.0, 100.0]):+ with pytest.raises(SourcegraphResponseTimeoutError):+ _read_bounded(response, max_bytes=1000, max_seconds=1.0)++ def test_watchdog_aborts_a_read_blocked_past_the_deadline(self):+ # A real slow-drip body blocks inside a single iter_content read, so the in-loop deadline+ # check never regains control — only the watchdog closing the response can interrupt it.+ closed = threading.Event()++ def blocking_read(*args: Any, **kwargs: Any):+ # Block like a socket read would until the watchdog force-closes the response.+ if not closed.wait(5.0):+ raise AssertionError("watchdog did not close the response")+ raise requests.exceptions.ChunkedEncodingError("connection closed")+ yield # type: ignore[unreachable] # makes this a generator so iter_content returns an iterator++ response = mock.MagicMock()+ response.iter_content.side_effect = blocking_read+ response.close.side_effect = lambda: closed.set()++ with pytest.raises(SourcegraphResponseTimeoutError):+ _read_bounded(response, max_bytes=1000, max_seconds=0.1)++ def test_bounded_body_is_returned(self):+ response = mock.MagicMock()+ response.iter_content.return_value = iter([b'{"data', b'": {}}'])++ assert _read_bounded(response, max_bytes=MAX_RESPONSE_BYTES) == b'{"data": {}}'+++class TestRetryHelpers:+ @pytest.mark.parametrize(+ "header, expected",+ [+ ({"Retry-After": "7"}, 7.0),+ ({"Retry-After": "999"}, 60.0),+ ({"Retry-After": "Wed, 21 Oct 2026 07:28:00 GMT"}, None),+ ({}, None),+ ],+ )+ def test_parse_retry_after(self, header, expected):+ response = mock.MagicMock()+ response.headers = header+ assert _parse_retry_after(response) == expected++ def test_retry_wait_prefers_retry_after(self):+ state = mock.MagicMock()+ state.outcome.exception.return_value = SourcegraphRetryableError("rate limited", retry_after=7.0)+ assert _retry_wait(state) == 7.0diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/tests/test_sourcegraph_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/tests/test_sourcegraph_source.pynew file mode 100644index 000000000000..265c00dd4204--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sourcegraph/tests/test_sourcegraph_source.py@@ -0,0 +1,130 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++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 SourcegraphSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.sourcegraph.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.sourcegraph.source import SourcegraphSource+from products.warehouse_sources.backend.temporal.data_imports.sources.sourcegraph.sourcegraph import (+ SourcegraphResumeConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestSourcegraphSource:+ def setup_method(self):+ self.source = SourcegraphSource()+ self.team_id = 123+ self.config = SourcegraphSourceConfig(host="https://sourcegraph.example.com", access_token="sgp_token")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.SOURCEGRAPH++ def test_connection_host_fields_force_token_reentry_on_host_change(self):+ # `host` is where the access token is sent; changing it must re-require the+ # token so the stored secret can't be redirected to an attacker-controlled host.+ assert self.source.connection_host_fields == ["host"]++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Sourcegraph"+ assert config.label == "Sourcegraph"+ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/sourcegraph.png"++ field_names = [f.name for f in config.fields]+ assert field_names == ["host", "access_token"]++ host_field, token_field = config.fields+ assert isinstance(host_field, SourceFieldInputConfig)+ assert host_field.type == SourceFieldInputConfigType.TEXT+ assert host_field.secret is False++ assert isinstance(token_field, SourceFieldInputConfig)+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ @pytest.mark.parametrize(+ "expected_key",+ [+ "401 Client Error",+ "403 Client Error",+ "Sourcegraph GraphQL error: not authenticated",+ "Sourcegraph GraphQL error: must be site admin",+ ],+ )+ def test_non_retryable_errors(self, expected_key):+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_schemas_returns_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_all_schemas_are_full_refresh_only(self):+ # No Sourcegraph connection has a server-side updated-since filter; advertising+ # incremental sync would silently re-fetch everything each run.+ for schema in self.source.get_schemas(self.config, self.team_id):+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ @pytest.mark.parametrize("endpoint", ["users", "organizations"])+ def test_admin_scoped_schemas_mention_site_admin(self, endpoint):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert "site-admin" in (schemas[endpoint].description or "")++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["repositories"])+ assert len(schemas) == 1+ assert schemas[0].name == "repositories"++ def test_get_schemas_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "mock_return",+ [+ (True, None),+ (False, "Invalid Sourcegraph access token"),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.sourcegraph.source.validate_sourcegraph_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return):+ mock_validate.return_value = mock_return++ result = self.source.validate_credentials(self.config, self.team_id, schema_name="users")++ assert result == mock_return+ mock_validate.assert_called_once_with(self.config.host, self.config.access_token, "users", self.team_id)++ def test_get_resumable_source_manager(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is SourcegraphResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.sourcegraph.source.sourcegraph_source"+ )+ def test_source_for_pipeline_plumbs_arguments(self, mock_sourcegraph_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "repositories"+ inputs.team_id = 42+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_sourcegraph_source.assert_called_once()+ kwargs = mock_sourcegraph_source.call_args.kwargs+ assert kwargs["host"] == "https://sourcegraph.example.com"+ assert kwargs["access_token"] == "sgp_token"+ assert kwargs["endpoint"] == "repositories"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["team_id"] == 42